# Backend Quick Reference Guide ## Database Models Quick Index ### User Management (3 models) - **User** - Main user account, auth, subscription tracking - **Session** - JWT token sessions (7 day expiry) - **UserPreference** - Key-value user settings store ### Bible Data (5 models) - **BibleVersion** - Multi-language Bible versions - **BibleBook** - Books within versions - **BibleChapter** - Chapters within books - **BibleVerse** - Individual verses (searchable) - **BiblePassage** - Verses with embeddings (legacy/vector search) ### User Content (5 models) - **Bookmark** - Verse bookmarks - **ChapterBookmark** - Chapter bookmarks - **Highlight** - Colored verse highlights with tags - **Note** - User notes on verses - **ReadingHistory** - Reading position tracking ### Communication (2 models) - **ChatConversation** - Conversation threads - **ChatMessage** - Individual messages (USER/ASSISTANT/SYSTEM roles) ### Prayer System (3 models) - **PrayerRequest** - Prayer request posts - **Prayer** - Anonymous prayers (IP-based tracking) - **UserPrayer** - Authenticated prayers ### Reading Plans (3 models) - **ReadingPlan** - Predefined/custom reading schedules - **UserReadingPlan** - User enrollment with progress/streaks - **UserReadingProgress** - Daily reading logs ### Payment (2 models) - **Subscription** - Active Stripe subscriptions - **Donation** - One-time/recurring donations ### Content Management (4 models) - **Page** - CMS pages (DRAFT/PUBLISHED/ARCHIVED) - **MediaFile** - Uploaded files/images - **SocialMediaLink** - Footer social links - **MailgunSettings** - Email service config --- ## Authentication Quick Reference | Purpose | Endpoint | Method | Auth Required | |---------|----------|--------|---------------| | Register | `/api/auth/register` | POST | No | | Login | `/api/auth/login` | POST | No | | Get Profile | `/api/auth/me` | GET | Bearer token | | Logout | `/api/auth/logout` | POST | Bearer token | | Admin Login | `/api/admin/auth/login` | POST | No (role validated) | | Admin Profile | `/api/admin/auth/me` | GET | Admin cookie/Bearer | **Token Expiry**: 7 days (users), 24 hours (admins) **Storage**: localStorage (client), httpOnly cookie (admin) --- ## API Endpoints by Category ### Bible Data (Read-only, Public) ``` GET /api/bible/versions?locale=ro&limit=10 GET /api/bible/books?versionId=... GET /api/bible/chapter?bookId=...&chapterNum=1 GET /api/bible/verses?chapterId=... GET /api/bible/search?query=... GET /api/bible/seo-url?reference=John%203:16 ``` ### User Content (Protected) ``` GET /api/bookmarks/all POST/GET /api/bookmarks/verse POST/GET /api/bookmarks/chapter GET /api/highlights POST /api/highlights PUT /api/highlights/{id} DELETE /api/highlights/{id} POST /api/highlights/bulk ``` ### Prayer System (Semi-public) ``` GET /api/prayers?category=health&visibility=public&languages=en POST /api/prayers (with or without auth) GET /api/prayers/{id} POST /api/prayers/{id}/pray ``` ### Reading Plans (Protected) ``` GET /api/reading-plans (public list) GET /api/user/reading-plans (user's plans) POST /api/user/reading-plans (enroll) GET /api/user/reading-plans/{id}/progress POST /api/user/reading-plans/{id}/progress ``` ### Chat (Protected but Disabled) ``` POST /api/chat (returns 503) GET /api/chat/conversations POST /api/chat/conversations GET /api/chat/conversations/{id} ``` ### Payment & Subscriptions ``` POST /api/stripe/checkout (donation) POST /api/subscriptions/checkout (subscription) POST /api/subscriptions/portal (manage subscription) POST /api/stripe/webhook (Stripe webhook) ``` ### Admin Panel (Admin/Moderator only) ``` GET /api/admin/users?page=0&pageSize=10&search=...&role=user GET /api/admin/users/{id} GET /api/admin/chat/conversations GET /api/admin/content/prayer-requests GET /api/admin/analytics/overview?period=30 GET /api/admin/analytics/content GET /api/admin/analytics/users POST /api/admin/pages (CMS) POST /api/admin/media (file upload) POST /api/admin/social-media (footer links) POST /api/admin/mailgun (email config) ``` --- ## Subscription Tiers | Feature | Free | Premium | |---------|------|---------| | Chat Conversations/Month | 10 | Unlimited | | Bible Reading | Unlimited | Unlimited | | Bookmarks | Unlimited | Unlimited | | Notes & Highlights | Unlimited | Unlimited | | Prayer Requests | Unlimited | Unlimited | | Reading Plans | Unlimited | Unlimited | | Cost | Free | Monthly/Yearly | --- ## Key Data Constraints ### Unique Constraints - User email - Session token - Bookmark (userId + verseId) - Highlight (userId + verseId) - ChapterBookmark (userId + bookId + chapterNum) - ReadingHistory (userId + versionId) - BibleVersion (abbreviation + language) - BibleBook (versionId + orderNum) - BibleChapter (bookId + chapterNum) - BibleVerse (chapterId + verseNum) - Prayer (requestId + ipAddress) - UserPrayer (userId + requestId) - SocialMediaLink platform - Page slug ### Foreign Key Cascades - User → All user content (sessions, bookmarks, conversations, etc.) - BibleVersion → Books, Chapters, Verses - ChatConversation → ChatMessages - PrayerRequest → Prayers, UserPrayers --- ## Webhook Events (Stripe) | Event | Model Update | User Impact | |-------|--------------|------------| | `checkout.session.completed` | Donation COMPLETED | Payment confirmed | | `checkout.session.expired` | Donation CANCELLED | Session expired | | `payment_intent.payment_failed` | Donation FAILED | Payment failed | | `charge.refunded` | Donation REFUNDED | Refund processed | | `customer.subscription.created` | Subscription created, User tier=premium | Premium access | | `customer.subscription.updated` | Subscription updated | Status change | | `customer.subscription.deleted` | Subscription CANCELLED, User tier=free | Downgraded to free | | `invoice.payment_succeeded` | User subscriptionStatus=active | Payment received | | `invoice.payment_failed` | User subscriptionStatus=past_due | Payment issue | --- ## Admin Permissions ### Admin Role - All permissions (SUPER_ADMIN) - Full system access ### Moderator Role (Limited) - READ_USERS, WRITE_USERS - READ_CONTENT, WRITE_CONTENT, DELETE_CONTENT - READ_ANALYTICS - READ_CHAT, WRITE_CHAT (not DELETE_CHAT) - NO system backup/health access --- ## Important Limits & Defaults | Setting | Value | |---------|-------| | Free Tier Conversation Limit | 10/month | | Token Expiry (User) | 7 days | | Token Expiry (Admin) | 24 hours | | Session Expiry | 7 days | | Admin Cookie MaxAge | 8 hours | | JWT Algorithm | HS256 | | Password Hash Rounds | 10 (bcryptjs) | | Default Bible Language | "ro" | | Default Currency | "usd" | | Donation Presets | $5, $10, $25, $50, $100, $250 | | Prayer Categories | personal, family, health, work, ministry, world | | Page Status Values | DRAFT, PUBLISHED, ARCHIVED | | Subscription Status Values | ACTIVE, CANCELLED, PAST_DUE, TRIALING, INCOMPLETE, INCOMPLETE_EXPIRED, UNPAID | --- ## Common Query Patterns ### Get User with All Content ```prisma user.include({ bookmarks: true, highlights: true, notes: true, chatConversations: { include: { messages: true } }, userReadingPlans: { include: { plan: true } } }) ``` ### Get Conversation with Messages ```prisma chatConversation.include({ messages: { orderBy: { timestamp: 'asc' }, take: 50 // Last 50 messages } }) ``` ### Search Prayer Requests ```prisma prayerRequest.findMany({ where: { isActive: true, isPublic: true, language: { in: ['en', 'ro'] }, category: 'health' }, orderBy: { createdAt: 'desc' } }) ``` --- ## Environment Setup Checklist - [ ] DATABASE_URL (PostgreSQL) - [ ] JWT_SECRET (32+ chars) - [ ] STRIPE_SECRET_KEY - [ ] STRIPE_PUBLISHABLE_KEY (public) - [ ] STRIPE_WEBHOOK_SECRET - [ ] STRIPE_PREMIUM_MONTHLY_PRICE_ID - [ ] STRIPE_PREMIUM_YEARLY_PRICE_ID - [ ] AZURE_OPENAI_ENDPOINT - [ ] AZURE_OPENAI_KEY - [ ] AZURE_OPENAI_DEPLOYMENT - [ ] AZURE_OPENAI_API_VERSION - [ ] NEXTAUTH_URL (base URL) - [ ] NODE_ENV (development/production) --- ## Common Development Tasks ### Run Migrations ```bash npx prisma migrate deploy ``` ### Generate Prisma Client ```bash npx prisma generate ``` ### View Database ```bash npx prisma studio ``` ### Seed Database ```bash npm run db:seed ``` ### Import Bible Data ```bash npm run import-bible ``` --- ## Performance Tips 1. **Use select()** - Only fetch needed fields 2. **Add indexes** - Already done for common queries 3. **Paginate** - Use skip/take for lists 4. **Cache versions** - Bible versions cached 1 hour 5. **Batch operations** - Use bulk endpoints 6. **Lazy load** - Include relations conditionally 7. **Monitor webhooks** - Stripe webhook logs essential --- ## Troubleshooting | Issue | Check | |-------|-------| | Auth fails | JWT_SECRET set? Token not expired? | | Chat disabled | AZURE_OPENAI_* vars configured? | | Webhook fails | STRIPE_WEBHOOK_SECRET correct? | | Email fails | Mailgun settings in DB enabled? | | Bible data empty | Import script run? BibleVersion exists? | | Prayers not showing | isPublic=true & isActive=true? | | Subscriptions broken | Stripe price IDs match env vars? | --- ## Resource Links - **Prisma Docs**: https://www.prisma.io/docs/ - **Next.js Docs**: https://nextjs.org/docs - **Stripe API**: https://stripe.com/docs/api - **JWT.io**: https://jwt.io/ - **Zod Validation**: https://zod.dev/