Includes all Phase 1 features: - Search-first navigation with auto-complete - Responsive reading interface (desktop/tablet/mobile) - 4 customization presets + full fine-tuning controls - Layered details panel with notes, bookmarks, highlights - Smart offline caching with IndexedDB and auto-sync - Full accessibility (WCAG 2.1 AA) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
891 lines
29 KiB
Markdown
891 lines
29 KiB
Markdown
# Biblical Guide - Backend Architecture Analysis
|
|
|
|
## Executive Summary
|
|
|
|
The Biblical Guide application is a comprehensive Next.js-based web application with a sophisticated backend architecture designed to support Bible reading, prayer requests, AI chat, user management, and a full admin panel. The backend utilizes PostgreSQL for persistent storage, JWT for authentication, Stripe for payments/subscriptions, and various third-party integrations.
|
|
|
|
---
|
|
|
|
## 1. DATABASE SCHEMA & MODELS
|
|
|
|
### Database Provider
|
|
- **Type**: PostgreSQL
|
|
- **ORM**: Prisma 6.16.2
|
|
- **Connection**: Via `DATABASE_URL` environment variable
|
|
- **Total Models**: 32 core data models
|
|
|
|
### Core Data Models
|
|
|
|
#### User Management
|
|
|
|
**User**
|
|
- Unique fields: `id`, `email`
|
|
- Authentication: `passwordHash`
|
|
- Profile: `name`, `role` ("user", "admin", "moderator"), `theme`, `fontSize`, `favoriteBibleVersion`
|
|
- Subscription: `subscriptionTier` ("free", "premium"), `subscriptionStatus`, `conversationLimit`, `conversationCount`, `limitResetDate`
|
|
- Stripe Integration: `stripeCustomerId`, `stripeSubscriptionId`
|
|
- Tracking: `createdAt`, `updatedAt`, `lastLoginAt`
|
|
- Relationships: 14 one-to-many relationships (sessions, bookmarks, notes, highlights, etc.)
|
|
- Indexes: on `role`, `subscriptionTier`, `stripeCustomerId`
|
|
|
|
**Session**
|
|
- Fields: `id`, `userId`, `token` (unique), `expiresAt`, `createdAt`
|
|
- 7-day token expiration
|
|
- Cascade delete when user deleted
|
|
- Indexes: on `userId`, `token`
|
|
|
|
#### Bible Data Models
|
|
|
|
**BibleVersion**
|
|
- Fields: `id`, `name`, `abbreviation`, `language`, `description`, `country`, `englishTitle`, `flagImageUrl`, `zipFileUrl`, `isDefault`
|
|
- Composite unique constraint: `abbreviation` + `language`
|
|
- Supports multi-language Bible versions
|
|
- Indexes: on `language`, `isDefault`, and composite index `(language, isDefault)`
|
|
|
|
**BibleBook**
|
|
- Fields: `id`, `versionId`, `name`, `testament`, `orderNum`, `bookKey` (cross-version matching)
|
|
- Links to `BibleVersion`
|
|
- Unique constraints: `(versionId, orderNum)` and `(versionId, bookKey)`
|
|
- Indexes: on `versionId`, `testament`
|
|
|
|
**BibleChapter**
|
|
- Fields: `id`, `bookId`, `chapterNum`
|
|
- Unique constraint: `(bookId, chapterNum)`
|
|
- Index: on `bookId`
|
|
|
|
**BibleVerse**
|
|
- Fields: `id`, `chapterId`, `verseNum`, `text` (Text type)
|
|
- Unique constraint: `(chapterId, verseNum)`
|
|
- Index: on `chapterId`
|
|
|
|
**BiblePassage** (Legacy/Embedding Search)
|
|
- Fields: `id`, `testament`, `book`, `chapter`, `verse`, `ref`, `lang`, `translation`, `textRaw`, `textNorm`, `embedding` (vector)
|
|
- Used for AI embedding search functionality
|
|
- Unique constraint: `(translation, lang, book, chapter, verse)`
|
|
- Indexes: on `(book, chapter)`, `testament`
|
|
|
|
#### User Content Models
|
|
|
|
**Bookmark** (Verse-level)
|
|
- Fields: `id`, `userId`, `verseId`, `note`, `color` (#FFD700 default), `createdAt`
|
|
- Unique constraint: `(userId, verseId)` - one bookmark per verse per user
|
|
- Indexes: on `userId`
|
|
|
|
**ChapterBookmark**
|
|
- Fields: `id`, `userId`, `bookId`, `chapterNum`, `note`, `createdAt`
|
|
- Unique constraint: `(userId, bookId, chapterNum)`
|
|
- Index: on `userId`
|
|
|
|
**Highlight**
|
|
- Fields: `id`, `userId`, `verseId`, `color`, `note` (Text), `tags[]`, `createdAt`, `updatedAt`
|
|
- Supports colored highlighting with notes and tags
|
|
- Unique constraint: `(userId, verseId)`
|
|
- Indexes: on `userId`, `verseId`
|
|
|
|
**Note**
|
|
- Fields: `id`, `userId`, `verseId`, `content` (Text), `createdAt`, `updatedAt`
|
|
- User notes on verses
|
|
- Indexes: on `userId`, `verseId`
|
|
|
|
**ReadingHistory**
|
|
- Fields: `id`, `userId`, `versionId`, `bookId`, `chapterNum`, `verseNum`, `viewedAt`
|
|
- Tracks user reading position
|
|
- Unique constraint: `(userId, versionId)` - one reading position per version per user
|
|
- Indexes: on `(userId, viewedAt)`, `(userId, versionId)`
|
|
|
|
#### Communication Models
|
|
|
|
**ChatConversation**
|
|
- Fields: `id`, `userId` (optional for anonymous), `title` (auto-generated), `language` ("ro"/"en"), `isActive`, `createdAt`, `updatedAt`, `lastMessageAt`
|
|
- Supports authenticated and anonymous conversations
|
|
- Cascade delete on user delete
|
|
- Index: composite `(userId, language, lastMessageAt)`
|
|
|
|
**ChatMessage**
|
|
- Fields: `id`, `conversationId`, `userId` (optional), `role` (USER/ASSISTANT/SYSTEM), `content` (Text), `metadata` (JSON), `timestamp`
|
|
- Cascade delete on conversation/user delete
|
|
- Indexes: on `(conversationId, timestamp)`, `(userId, timestamp)`
|
|
|
|
**ChatMessageRole Enum**
|
|
- Values: `USER`, `ASSISTANT`, `SYSTEM`
|
|
|
|
#### Prayer System Models
|
|
|
|
**PrayerRequest**
|
|
- Fields: `id`, `userId` (optional), `title`, `description` (Text), `category` (personal/family/health/work/ministry/world), `author`, `isAnonymous`, `isPublic`, `language`, `prayerCount`, `isActive`, `createdAt`, `updatedAt`
|
|
- Supports public/private and anonymous prayers
|
|
- Cascade delete on user delete
|
|
- Indexes: on `createdAt`, `category`, `isActive`
|
|
|
|
**Prayer**
|
|
- Fields: `id`, `requestId`, `ipAddress`, `createdAt`
|
|
- Anonymous prayer tracking via IP address
|
|
- Unique constraint: `(requestId, ipAddress)` - one prayer per IP per request
|
|
|
|
**UserPrayer**
|
|
- Fields: `id`, `userId`, `requestId`, `createdAt`
|
|
- Authenticated user prayer tracking
|
|
- Unique constraint: `(userId, requestId)`
|
|
- Indexes: on `userId`, `requestId`
|
|
|
|
#### Reading Plans Models
|
|
|
|
**ReadingPlan**
|
|
- Fields: `id`, `name`, `description`, `type` (PREDEFINED/CUSTOM), `duration` (days), `schedule` (JSON), `difficulty`, `language`, `isActive`, `createdAt`, `updatedAt`
|
|
- Flexible schedule format supporting multiple languages
|
|
- Indexes: on `type`, `language`, `isActive`
|
|
|
|
**UserReadingPlan**
|
|
- Fields: `id`, `userId`, `planId` (optional for custom), `name`, `startDate`, `targetEndDate`, `actualEndDate`, `status` (ACTIVE/COMPLETED/PAUSED/CANCELLED), `currentDay`, `completedDays`, `streak`, `longestStreak`, `customSchedule` (JSON), `reminderEnabled`, `reminderTime`, `createdAt`, `updatedAt`
|
|
- Tracks user progress in reading plans with streaks
|
|
- Indexes: on `userId`, `status`, `(userId, status)`
|
|
|
|
**UserReadingProgress**
|
|
- Fields: `id`, `userId`, `userPlanId`, `planDay`, `date`, `bookId`, `chapterNum`, `versesRead`, `completed`, `notes` (Text), `createdAt`, `updatedAt`
|
|
- Unique constraint: `(userPlanId, planDay, bookId, chapterNum)` - one entry per chapter per day per plan
|
|
- Indexes: on `userId`, `userPlanId`, `(userId, date)`
|
|
|
|
#### Payment & Subscription Models
|
|
|
|
**Donation**
|
|
- Fields: `id`, `userId` (optional), `stripeSessionId` (unique), `stripePaymentId`, `email`, `name`, `amount` (cents), `currency` ("usd" default), `status` (PENDING/COMPLETED/FAILED/REFUNDED/CANCELLED), `message` (Text), `isAnonymous`, `isRecurring`, `recurringInterval`, `metadata` (JSON), `createdAt`, `updatedAt`
|
|
- Supports one-time and recurring donations
|
|
- Set null on user delete (anonymous donations preserved)
|
|
- Indexes: on `userId`, `status`, `createdAt`, `email`
|
|
|
|
**Subscription**
|
|
- Fields: `id`, `userId`, `stripeSubscriptionId` (unique), `stripePriceId`, `stripeCustomerId`, `status` (SubscriptionStatus enum), `currentPeriodStart`, `currentPeriodEnd`, `cancelAtPeriodEnd`, `tier` ("premium"), `interval` ("month"/"year"), `metadata` (JSON), `createdAt`, `updatedAt`
|
|
- Tracks active Stripe subscriptions
|
|
- Cascade delete on user delete
|
|
- Indexes: on `userId`, `status`, `stripeSubscriptionId`
|
|
|
|
**SubscriptionStatus Enum**
|
|
- Values: `ACTIVE`, `CANCELLED`, `PAST_DUE`, `TRIALING`, `INCOMPLETE`, `INCOMPLETE_EXPIRED`, `UNPAID`
|
|
|
|
#### Content Management Models
|
|
|
|
**Page**
|
|
- Fields: `id`, `title`, `slug` (unique), `content` (Text), `contentType` (RICH_TEXT/HTML/MARKDOWN), `excerpt`, `featuredImage`, `seoTitle`, `seoDescription`, `status` (DRAFT/PUBLISHED/ARCHIVED), `showInNavigation`, `showInFooter`, `navigationOrder`, `footerOrder`, `createdBy`, `updatedBy`, `createdAt`, `updatedAt`, `publishedAt`
|
|
- Full CMS functionality with SEO support
|
|
- Indexes: on `slug`, `status`, `(showInNavigation, navigationOrder)`, `(showInFooter, footerOrder)`
|
|
|
|
**MediaFile**
|
|
- Fields: `id`, `filename`, `originalName`, `mimeType`, `size`, `path`, `url`, `alt`, `uploadedBy`, `createdAt`
|
|
- File storage tracking
|
|
- Indexes: on `uploadedBy`, `mimeType`
|
|
|
|
**SocialMediaLink**
|
|
- Fields: `id`, `platform` (unique), `name`, `url`, `icon`, `isEnabled`, `order`, `createdBy`, `updatedBy`, `createdAt`, `updatedAt`
|
|
- Manages social media links in footer
|
|
- Index: on `(isEnabled, order)`
|
|
|
|
**MailgunSettings**
|
|
- Fields: `id`, `apiKey` (encrypted), `domain`, `region` ("US"/"EU"), `fromEmail`, `fromName`, `replyToEmail`, `isEnabled`, `testMode`, `webhookUrl`, `updatedBy`, `createdAt`, `updatedAt`
|
|
- Email service configuration
|
|
- Index: on `isEnabled`
|
|
|
|
#### User Preferences
|
|
|
|
**UserPreference**
|
|
- Fields: `id`, `userId`, `key`, `value`
|
|
- Key-value store for user settings
|
|
- Unique constraint: `(userId, key)`
|
|
|
|
---
|
|
|
|
## 2. AUTHENTICATION SYSTEM
|
|
|
|
### JWT-Based Authentication
|
|
|
|
**Token Architecture**
|
|
- **Algorithm**: JWT with HS256
|
|
- **Secret**: Stored in `JWT_SECRET` environment variable
|
|
- **Expiration**: 7 days for user tokens, 24 hours for admin tokens
|
|
- **Payload**: `{ userId: string }` for users, `{ userId, email, role, type: 'admin' }` for admins
|
|
|
|
**Authentication Flow**
|
|
|
|
1. **User Registration** (`POST /api/auth/register`)
|
|
- Validates email/password with Zod schemas
|
|
- Creates `User` with hashed password (bcryptjs, 10 rounds)
|
|
- Generates JWT token
|
|
- Creates `Session` record with 7-day expiration
|
|
- Returns user data and token
|
|
|
|
2. **User Login** (`POST /api/auth/login`)
|
|
- Validates credentials against stored hash
|
|
- Generates JWT token
|
|
- Creates `Session` record
|
|
- Updates `lastLoginAt`
|
|
- Returns user data and token
|
|
|
|
3. **Token Verification**
|
|
- `verifyToken(token)`: Verifies JWT signature and returns decoded payload
|
|
- `getUserFromToken(token)`: Retrieves full user record from token
|
|
- `isTokenExpired(token)`: Checks expiration without verification (client-side safe)
|
|
|
|
4. **Admin Authentication** (`POST /api/admin/auth/login`)
|
|
- Requires `role` to be "admin" or "moderator"
|
|
- Returns admin token via secure httpOnly cookie
|
|
- Cookie: `adminToken`, httpOnly, secure (production), sameSite: strict, max age 8 hours
|
|
- Also accepts Bearer token in Authorization header
|
|
|
|
### Admin Permission System
|
|
|
|
**Admin Roles**
|
|
- **Admin**: Full system access (super admin)
|
|
- **Moderator**: Limited access (content, user management, analytics)
|
|
|
|
**Permission Enums** (from `lib/admin-auth.ts`)
|
|
```
|
|
READ_USERS
|
|
WRITE_USERS
|
|
DELETE_USERS
|
|
READ_CONTENT
|
|
WRITE_CONTENT
|
|
DELETE_CONTENT
|
|
READ_ANALYTICS
|
|
READ_CHAT
|
|
WRITE_CHAT
|
|
DELETE_CHAT
|
|
SYSTEM_BACKUP
|
|
SYSTEM_HEALTH
|
|
SUPER_ADMIN
|
|
```
|
|
|
|
**Moderator Permissions**: READ_USERS, WRITE_USERS, READ_CONTENT, WRITE_CONTENT, DELETE_CONTENT, READ_ANALYTICS, READ_CHAT, WRITE_CHAT
|
|
|
|
**Auth Middleware**
|
|
- `verifyAdminAuth()`: Checks Bearer token or adminToken cookie
|
|
- `hasAdminAccess()`: Validates admin/moderator role
|
|
- `isSuperAdmin()`: Checks admin role specifically
|
|
- `hasPermission()`: Validates specific permission
|
|
|
|
### Client-Side Auth Management
|
|
|
|
**Token Handling**
|
|
- Tokens stored in `localStorage` as `authToken`
|
|
- Client function: `isTokenExpired()` - decodes JWT without verification
|
|
- Client function: `clearExpiredToken()` - removes expired tokens from storage
|
|
|
|
**Authentication Headers**
|
|
- Format: `Authorization: Bearer <token>`
|
|
- Used in all protected API endpoints
|
|
|
|
---
|
|
|
|
## 3. PAYMENT & SUBSCRIPTION SYSTEM
|
|
|
|
### Stripe Integration
|
|
|
|
**Configuration**
|
|
- **Client Library**: `@stripe/stripe-js` 8.0.0
|
|
- **Server Library**: `stripe` 19.1.0
|
|
- **API Version**: `2025-09-30.clover`
|
|
- **Keys**:
|
|
- Public Key: `NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY`
|
|
- Secret Key: `STRIPE_SECRET_KEY`
|
|
- Webhook Secret: `STRIPE_WEBHOOK_SECRET`
|
|
|
|
**Subscription Pricing**
|
|
- **Free Tier**: 10 conversations/month limit
|
|
- **Premium Tier**: Unlimited conversations
|
|
- **Price IDs**:
|
|
- `STRIPE_PREMIUM_MONTHLY_PRICE_ID`
|
|
- `STRIPE_PREMIUM_YEARLY_PRICE_ID`
|
|
|
|
### Donation System
|
|
|
|
**Donation Flow** (`POST /api/stripe/checkout`)
|
|
- Creates Stripe checkout session
|
|
- Supports one-time and recurring donations
|
|
- Presets: $5, $10, $25, $50, $100, $250
|
|
- Tracks via `Donation` model with statuses:
|
|
- PENDING (initial)
|
|
- COMPLETED (payment succeeded)
|
|
- FAILED (payment failed)
|
|
- REFUNDED (refunded)
|
|
- CANCELLED (session expired)
|
|
|
|
**Donation Webhooks** (`POST /api/stripe/webhook`)
|
|
- `checkout.session.completed`: Updates donation to COMPLETED
|
|
- `checkout.session.expired`: Updates donation to CANCELLED
|
|
- `payment_intent.payment_failed`: Updates donation to FAILED
|
|
- `charge.refunded`: Updates donation to REFUNDED
|
|
- Stores payment metadata (status, email, error info)
|
|
|
|
### Subscription System
|
|
|
|
**Subscription Flow** (`POST /api/subscriptions/checkout`)
|
|
- Creates Stripe customer if not exists
|
|
- Creates subscription checkout session
|
|
- Validates price ID configuration
|
|
- Prevents duplicate active subscriptions
|
|
- Returns session ID and checkout URL
|
|
- Allows promotion codes
|
|
- Requires Bearer token authentication
|
|
|
|
**Subscription Portal** (`POST /api/subscriptions/portal`)
|
|
- Generates Stripe customer portal link
|
|
- Users can manage/cancel subscriptions
|
|
- Requires authentication
|
|
|
|
**Subscription Webhooks** (`POST /api/stripe/webhook`)
|
|
- `customer.subscription.created`: Creates `Subscription` record, updates user tier to premium
|
|
- `customer.subscription.updated`: Updates `Subscription` and user tier/limit
|
|
- `customer.subscription.deleted`: Downgrades user to free tier
|
|
- `invoice.payment_succeeded`: Ensures subscription marked active
|
|
- `invoice.payment_failed`: Sets subscription status to past_due
|
|
|
|
**Webhook Payload Handling**
|
|
- Verifies Stripe signature
|
|
- Extracts userId from subscription metadata
|
|
- Extracts pricing tier and interval from price ID
|
|
- Updates both `Subscription` and `User` models atomically
|
|
|
|
### Conversation Limit Management
|
|
|
|
**Limit Checking** (`checkConversationLimit()`)
|
|
- Validates user subscription tier and count
|
|
- Resets monthly counter if period expired
|
|
- Premium users with active subscriptions get unlimited access
|
|
- Free users get 10/month limit
|
|
- Automatic monthly reset calculation
|
|
|
|
**Limit Enforcement**
|
|
- Checked before creating new conversation
|
|
- Returns: `{ allowed, remaining, limit, tier, resetDate }`
|
|
- Returns infinite remaining for premium users
|
|
|
|
**Limit Increment** (`incrementConversationCount()`)
|
|
- Called when new conversation created
|
|
- Sets initial reset date if not set (1 month from now)
|
|
- Increments counter by 1
|
|
|
|
---
|
|
|
|
## 4. API STRUCTURE & ENDPOINTS
|
|
|
|
### Framework & Runtime
|
|
- **Framework**: Next.js 15.5.3 with App Router
|
|
- **Runtime**: All routes set to `nodejs` (not Edge)
|
|
- **Response Format**: JSON via `NextResponse`
|
|
|
|
### API Categories
|
|
|
|
#### Authentication Endpoints
|
|
|
|
**User Auth**
|
|
- `POST /api/auth/register` - User registration with email/password
|
|
- `POST /api/auth/login` - User login
|
|
- `GET /api/auth/me` - Get authenticated user profile
|
|
- `POST /api/auth/logout` - Logout (clear token)
|
|
|
|
**Admin Auth**
|
|
- `POST /api/admin/auth/login` - Admin login with role validation
|
|
- `GET /api/admin/auth/me` - Get admin profile
|
|
- `POST /api/admin/auth/logout` - Admin logout
|
|
|
|
#### Bible Data Endpoints
|
|
|
|
**Bible Versions**
|
|
- `GET /api/bible/versions` - List Bible versions by language
|
|
- Query params: `locale`, `all`, `limit`, `search`
|
|
- Caching: 1 hour cache with 2-hour stale-while-revalidate
|
|
|
|
**Bible Books**
|
|
- `GET /api/bible/books` - Get books for a version
|
|
|
|
**Bible Chapters**
|
|
- `GET /api/bible/chapter` - Get full chapter with verses
|
|
|
|
**Bible Verses**
|
|
- `GET /api/bible/verses` - Get specific verses
|
|
- `GET /api/bible/search` - Search verses
|
|
|
|
**SEO URLs**
|
|
- `GET /api/bible/seo-url` - Convert friendly URLs to references
|
|
|
|
#### User Content Endpoints
|
|
|
|
**Bookmarks**
|
|
- `GET /api/bookmarks/all` - Get all user bookmarks (verses & chapters)
|
|
- `POST /api/bookmarks/verse` - Create verse bookmark
|
|
- `GET /api/bookmarks/verse/check` - Check if verse bookmarked
|
|
- `POST /api/bookmarks/verse/bulk-check` - Check multiple verses
|
|
- `POST /api/bookmarks/chapter` - Create chapter bookmark
|
|
- `GET /api/bookmarks/chapter/check` - Check if chapter bookmarked
|
|
|
|
**Highlights**
|
|
- `GET /api/highlights` - Get user highlights
|
|
- `POST /api/highlights` - Create highlight with color/tags/notes
|
|
- `PUT /api/highlights/[id]` - Update highlight
|
|
- `DELETE /api/highlights/[id]` - Delete highlight
|
|
- `POST /api/highlights/bulk` - Bulk operations
|
|
|
|
**Notes**
|
|
- Not shown in list but available through verse endpoints
|
|
|
|
#### User Management Endpoints
|
|
|
|
**Profile**
|
|
- `GET /api/user/profile` - Get user profile
|
|
- `PUT /api/user/profile` - Update profile
|
|
|
|
**Settings**
|
|
- `GET /api/user/settings` - Get user settings
|
|
- `PUT /api/user/settings` - Update settings
|
|
|
|
**Favorite Version**
|
|
- `PUT /api/user/favorite-version` - Set default Bible version
|
|
|
|
**Reading Progress**
|
|
- `GET /api/user/reading-progress` - Get reading position
|
|
- `PUT /api/user/reading-progress` - Update reading position
|
|
|
|
#### Reading Plans Endpoints
|
|
|
|
**Reading Plans**
|
|
- `GET /api/reading-plans` - List all available plans
|
|
|
|
**User Reading Plans**
|
|
- `GET /api/user/reading-plans` - Get user's reading plans with status filter
|
|
- `POST /api/user/reading-plans` - Enroll in plan or create custom plan
|
|
- `GET /api/user/reading-plans/[id]` - Get specific plan details
|
|
- `PUT /api/user/reading-plans/[id]` - Update plan
|
|
- `DELETE /api/user/reading-plans/[id]` - Cancel plan
|
|
|
|
**Reading Progress**
|
|
- `GET /api/user/reading-plans/[id]/progress` - Get progress for plan
|
|
- `POST /api/user/reading-plans/[id]/progress` - Log reading for day
|
|
- `PUT /api/user/reading-plans/[id]/progress` - Update progress
|
|
|
|
#### Prayer Endpoints
|
|
|
|
**Prayer Requests**
|
|
- `GET /api/prayers` - List public prayer requests (with filters)
|
|
- Query params: `category`, `limit`, `visibility`, `languages`
|
|
- Supports public/private filtering based on auth
|
|
- `POST /api/prayers` - Create prayer request
|
|
- Supports anonymous or authenticated
|
|
- `GET /api/prayers/[id]` - Get prayer details
|
|
- `POST /api/prayers/[id]/pray` - Log prayer for request
|
|
- `PUT /api/prayers/[id]` - Update prayer (owner only)
|
|
- `DELETE /api/prayers/[id]` - Delete prayer (owner only)
|
|
|
|
**Prayer Generation**
|
|
- `POST /api/prayers/generate` - Generate prayer prompt (AI)
|
|
|
|
#### Chat Endpoints
|
|
|
|
**Chat Conversations**
|
|
- `GET /api/chat/conversations` - List user conversations (auth required)
|
|
- `POST /api/chat/conversations` - Create new conversation
|
|
- `GET /api/chat/conversations/[id]` - Get conversation with messages
|
|
- `PUT /api/chat/conversations/[id]` - Update conversation
|
|
- `DELETE /api/chat/conversations/[id]` - Delete conversation
|
|
|
|
**Chat Messages**
|
|
- `POST /api/chat` - Send message and get AI response
|
|
- Status: Currently disabled (returns 503)
|
|
- Requires Bearer token auth for new conversations
|
|
- Checks conversation limits for free users
|
|
- Integrates with Azure OpenAI
|
|
- Stores messages in database for authenticated users
|
|
- Uses vector search for relevant Bible verses
|
|
|
|
#### Subscription & Payment Endpoints
|
|
|
|
**Donations**
|
|
- `POST /api/stripe/checkout` - Create donation checkout session
|
|
|
|
**Subscriptions**
|
|
- `POST /api/subscriptions/checkout` - Create subscription checkout session
|
|
- `POST /api/subscriptions/portal` - Get customer portal URL
|
|
|
|
**Webhooks**
|
|
- `POST /api/stripe/webhook` - Stripe webhook handler
|
|
|
|
#### Admin Endpoints
|
|
|
|
**Users**
|
|
- `GET /api/admin/users` - List users with pagination/filtering
|
|
- Query params: `page`, `pageSize`, `search`, `role`
|
|
- Returns user counts (conversations, prayers, bookmarks)
|
|
- `GET /api/admin/users/[id]` - Get user details
|
|
- `PUT /api/admin/users/[id]` - Update user
|
|
- `DELETE /api/admin/users/[id]` - Delete user
|
|
|
|
**Chat Management**
|
|
- `GET /api/admin/chat/conversations` - List all conversations
|
|
- `GET /api/admin/chat/conversations/[id]` - Get conversation details
|
|
- `DELETE /api/admin/chat/conversations/[id]` - Delete conversation
|
|
|
|
**Content Management**
|
|
- `GET /api/admin/pages` - List CMS pages
|
|
- `POST /api/admin/pages` - Create page
|
|
- `GET /api/admin/pages/[id]` - Get page
|
|
- `PUT /api/admin/pages/[id]` - Update page
|
|
- `DELETE /api/admin/pages/[id]` - Delete page
|
|
|
|
**Prayer Requests**
|
|
- `GET /api/admin/content/prayer-requests` - List all prayers
|
|
- `GET /api/admin/content/prayer-requests/[id]` - Get prayer details
|
|
- `PUT /api/admin/content/prayer-requests/[id]` - Update prayer
|
|
- `DELETE /api/admin/content/prayer-requests/[id]` - Delete prayer
|
|
|
|
**Media Management**
|
|
- `POST /api/admin/media` - Upload media files
|
|
- `DELETE /api/admin/media/[id]` - Delete media
|
|
|
|
**Social Media**
|
|
- `GET /api/admin/social-media` - List social links
|
|
- `POST /api/admin/social-media` - Create social link
|
|
- `PUT /api/admin/social-media/[id]` - Update social link
|
|
- `DELETE /api/admin/social-media/[id]` - Delete social link
|
|
|
|
**Email Configuration**
|
|
- `GET /api/admin/mailgun` - Get Mailgun settings
|
|
- `PUT /api/admin/mailgun` - Update Mailgun settings
|
|
- `POST /api/admin/mailgun/test` - Test email connection
|
|
|
|
#### Analytics Endpoints
|
|
|
|
**Overview**
|
|
- `GET /api/admin/analytics/overview` - Comprehensive dashboard stats
|
|
- Period-based stats (default 30 days)
|
|
- User metrics: total, new, active
|
|
- Content metrics: prayers, requests, conversations
|
|
- Category distributions
|
|
- Daily activity breakdown
|
|
|
|
**Content Analytics**
|
|
- `GET /api/admin/analytics/content` - Content-specific metrics
|
|
|
|
**User Analytics**
|
|
- `GET /api/admin/analytics/users` - User behavior metrics
|
|
|
|
**Real-time Analytics**
|
|
- `GET /api/admin/analytics/realtime` - Current active users/activity
|
|
|
|
**Stats**
|
|
- `GET /api/stats` - Public statistics
|
|
|
|
#### System Endpoints
|
|
|
|
**Health Check**
|
|
- `GET /api/health` - API health status
|
|
|
|
**System Health**
|
|
- `GET /api/admin/system/health` - Detailed system health
|
|
|
|
**System Backup**
|
|
- `POST /api/admin/system/backup` - Database backup
|
|
|
|
#### Utility Endpoints
|
|
|
|
**Contact Form**
|
|
- `POST /api/contact` - Contact form submission
|
|
|
|
**CAPTCHA**
|
|
- `POST /api/captcha` - CAPTCHA verification
|
|
|
|
**Debug Endpoints** (Development)
|
|
- `GET /api/debug/user` - Debug user info
|
|
- `GET /api/debug/schema` - Debug schema info
|
|
- `GET /api/debug/token` - Debug token info
|
|
|
|
---
|
|
|
|
## 5. KEY BUSINESS LOGIC & FEATURES
|
|
|
|
### Conversation Limit System
|
|
- Free tier: 10 conversations/month
|
|
- Premium tier: Unlimited
|
|
- Automatic monthly reset
|
|
- Prevents over-usage
|
|
|
|
### Prayer System Features
|
|
- Public/private prayers
|
|
- Anonymous submission support
|
|
- Prayer count tracking (IP-based for anonymous, user-based for authenticated)
|
|
- Category classification (personal, family, health, work, ministry, world)
|
|
- Language-aware filtering
|
|
- Multi-language support
|
|
|
|
### Reading Plans
|
|
- Predefined and custom plans
|
|
- Daily tracking with streak system
|
|
- Progress tracking with completion status
|
|
- Reminder system (enabled/disabled with time)
|
|
- Flexible JSON-based schedules
|
|
- Target date management
|
|
|
|
### Chat System (Currently Disabled)
|
|
- Conversation persistence
|
|
- Message history tracking
|
|
- Integration with Azure OpenAI
|
|
- Vector search for Bible verses
|
|
- Context-aware responses
|
|
- Multi-language system prompts
|
|
- Subscription-based limit enforcement
|
|
|
|
### Vector Search (BiblePassage model)
|
|
- Embedding-based verse search
|
|
- Language-specific filtering
|
|
- Used for AI chat context
|
|
- Supports: EN (ASV), ES (RVA 1909), etc.
|
|
|
|
### Admin System Features
|
|
- User management with pagination
|
|
- Chat conversation moderation
|
|
- Content (pages) management with SEO
|
|
- Prayer request moderation
|
|
- Media file management
|
|
- Social media link management
|
|
- Email service configuration (Mailgun)
|
|
- Comprehensive analytics dashboard
|
|
- Daily activity tracking
|
|
- System health monitoring
|
|
|
|
---
|
|
|
|
## 6. EXTERNAL INTEGRATIONS
|
|
|
|
### Stripe
|
|
- Payment processing (one-time)
|
|
- Subscription management (recurring)
|
|
- Webhook event handling
|
|
- Customer portal access
|
|
|
|
### Azure OpenAI
|
|
- Chat completions API
|
|
- Multi-language support
|
|
- Temperature/top_p configuration
|
|
- Content filtering detection
|
|
- Fallback responses
|
|
|
|
### Mailgun
|
|
- Email service
|
|
- Contact form handling
|
|
- Password reset emails
|
|
- Test mode support
|
|
- Multi-region support (US/EU)
|
|
|
|
### Vector Database
|
|
- PostgreSQL with pgvector extension
|
|
- Bible verse embeddings
|
|
- Hybrid search capability
|
|
|
|
---
|
|
|
|
## 7. FILE STORAGE
|
|
|
|
### System
|
|
- **Model**: `MediaFile`
|
|
- **Fields**: filename, originalName, mimeType, size, path, url, alt, uploadedBy
|
|
- **Tracking**: User upload attribution, creation timestamp
|
|
- **Indexes**: By uploader, by MIME type
|
|
|
|
### Upload Endpoint
|
|
- `POST /api/admin/media` - Admin only file uploads
|
|
|
|
### Usage in CMS
|
|
- Pages can have featured images
|
|
- Supported in content rich text editor
|
|
|
|
---
|
|
|
|
## 8. TECHNOLOGY STACK
|
|
|
|
### Backend Framework
|
|
- Next.js 15.5.3 (with App Router)
|
|
- Node.js runtime
|
|
|
|
### Database
|
|
- PostgreSQL
|
|
- Prisma ORM 6.16.2
|
|
- pgvector for embeddings
|
|
|
|
### Authentication & Security
|
|
- JWT (jsonwebtoken 9.0.2)
|
|
- bcryptjs for password hashing (3.0.2)
|
|
- CORS headers management
|
|
|
|
### API Integration
|
|
- Stripe 19.1.0 (payments)
|
|
- Mailgun.js 12.0.3 (email)
|
|
- OpenAI 5.22.0 (Azure OpenAI)
|
|
- Socket.io 4.8.1 (WebSocket support)
|
|
|
|
### Validation
|
|
- Zod 3.25.76 (schema validation)
|
|
|
|
### State Management
|
|
- Zustand 5.0.8
|
|
|
|
### Utilities
|
|
- uuid 13.0.0 (ID generation)
|
|
- axios (via stripe, mailgun, openai)
|
|
|
|
### Development
|
|
- TypeScript 5.9.2
|
|
- tsx 4.20.5 (TypeScript runner)
|
|
|
|
---
|
|
|
|
## 9. ENVIRONMENT VARIABLES
|
|
|
|
### Database
|
|
- `DATABASE_URL` - PostgreSQL connection string
|
|
- `VECTOR_SCHEMA` - Schema name for vector tables (default: ai_bible)
|
|
- `EMBED_DIMS` - Embedding dimensions (default: 1536)
|
|
|
|
### JWT & Auth
|
|
- `JWT_SECRET` - Secret key for JWT signing
|
|
|
|
### Stripe
|
|
- `NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY` - Public key (client-side)
|
|
- `STRIPE_SECRET_KEY` - Secret key (server-side)
|
|
- `STRIPE_WEBHOOK_SECRET` - Webhook signature verification
|
|
- `STRIPE_PREMIUM_MONTHLY_PRICE_ID` - Monthly subscription price ID
|
|
- `STRIPE_PREMIUM_YEARLY_PRICE_ID` - Yearly subscription price ID
|
|
|
|
### Azure OpenAI
|
|
- `AZURE_OPENAI_ENDPOINT` - API endpoint
|
|
- `AZURE_OPENAI_KEY` - API key
|
|
- `AZURE_OPENAI_DEPLOYMENT` - Model deployment name
|
|
- `AZURE_OPENAI_API_VERSION` - API version
|
|
|
|
### Email (Mailgun)
|
|
- Configured in database `MailgunSettings` table (encrypted in DB)
|
|
- Can be updated via admin panel
|
|
|
|
### Application
|
|
- `NEXTAUTH_URL` - Base URL for callbacks
|
|
- `NODE_ENV` - Environment (development/production)
|
|
|
|
---
|
|
|
|
## 10. CURRENT STATUS & NOTES
|
|
|
|
### Disabled Features
|
|
- Chat feature currently disabled (returns 503 Service Unavailable)
|
|
- Reason: Likely maintenance or missing Azure OpenAI configuration
|
|
|
|
### Pending Implementation
|
|
- Password reset functionality (structure in place, not fully implemented)
|
|
- WebSocket support (server available but not actively used)
|
|
|
|
### Security Considerations
|
|
- Mailgun API keys stored encrypted in database
|
|
- JWT secrets required for all environments
|
|
- Admin tokens use httpOnly cookies for CSRF protection
|
|
- Stripe webhook signature verification implemented
|
|
- User data cascades deleted appropriately
|
|
|
|
### Performance Optimizations
|
|
- Database indexes on frequently queried fields
|
|
- Composite indexes for common filter combinations
|
|
- Unique constraints to prevent duplicates
|
|
- Pagination in admin list endpoints
|
|
- Select-only fields to reduce data transfer
|
|
|
|
### Monitoring & Logging
|
|
- Extensive console logging throughout API routes
|
|
- Error tracking in webhook handlers
|
|
- Analytics dashboard for monitoring usage patterns
|
|
|
|
---
|
|
|
|
## 11. DATA RELATIONSHIPS DIAGRAM
|
|
|
|
```
|
|
User (1)
|
|
├── (1:M) Session
|
|
├── (1:M) ChatConversation -> (1:M) ChatMessage
|
|
├── (1:M) Bookmark -> BibleVerse -> BibleChapter -> BibleBook -> BibleVersion
|
|
├── (1:M) ChapterBookmark -> BibleBook
|
|
├── (1:M) Highlight -> BibleVerse
|
|
├── (1:M) Note -> BibleVerse
|
|
├── (1:M) ReadingHistory -> BibleVersion
|
|
├── (1:M) PrayerRequest -> (1:M) Prayer & UserPrayer
|
|
├── (1:M) UserReadingPlan -> ReadingPlan & UserReadingProgress
|
|
├── (1:M) Donation
|
|
├── (1:M) Subscription
|
|
├── (1:M) Page (created & updated)
|
|
├── (1:M) MediaFile
|
|
├── (1:M) SocialMediaLink (created & updated)
|
|
└── (1:M) MailgunSettings (updated)
|
|
```
|
|
|
|
---
|
|
|
|
## 12. API RESPONSE PATTERNS
|
|
|
|
### Success Response
|
|
```json
|
|
{
|
|
"success": true,
|
|
"data": {},
|
|
"message": "Optional message"
|
|
}
|
|
```
|
|
|
|
### Error Response
|
|
```json
|
|
{
|
|
"success": false,
|
|
"error": "Error message",
|
|
"details": [] // Optional validation details
|
|
}
|
|
```
|
|
|
|
### Pagination Response
|
|
```json
|
|
{
|
|
"data": [],
|
|
"pagination": {
|
|
"page": 0,
|
|
"pageSize": 10,
|
|
"total": 100,
|
|
"totalPages": 10
|
|
}
|
|
}
|
|
```
|
|
|
|
---
|
|
|
|
## 13. DEPLOYMENT CONSIDERATIONS
|
|
|
|
### Build Configuration
|
|
- `NODE_OPTIONS='--max-old-space-size=4096'` for standard builds
|
|
- `NODE_OPTIONS='--max-old-space-size=8192'` for production builds
|
|
- `NEXT_PRIVATE_SKIP_SIZE_LIMIT=1` available for fast builds (skips size check)
|
|
|
|
### Production Checklist
|
|
- All environment variables configured
|
|
- Database migrations applied (`prisma migrate deploy`)
|
|
- Stripe webhooks configured with correct URL
|
|
- Azure OpenAI credentials validated
|
|
- Mailgun settings configured and tested
|
|
- CORS headers for cross-origin requests
|
|
- HTTPS enforced for secure cookies
|
|
- Database backups enabled
|
|
- Monitoring/alerting configured
|
|
|
|
---
|
|
|
|
## Conclusion
|
|
|
|
The Biblical Guide backend is a sophisticated, well-structured application with:
|
|
- Comprehensive user management and authentication
|
|
- Flexible subscription/payment system via Stripe
|
|
- Rich content management for Bible data
|
|
- Multi-feature user engagement (bookmarks, notes, highlights, prayers, reading plans)
|
|
- Full admin panel for system management
|
|
- AI-powered chat with context awareness
|
|
- Scalable architecture with proper indexing and data relationships
|
|
|
|
The codebase demonstrates good practices in API design, security, and data modeling with room for future enhancements in performance optimization and additional features.
|