feat: add user favorite Bible version preference system

- Add favoriteBibleVersion field to User schema in Prisma
- Create API endpoint (/api/user/favorite-version) to get/set favorite version
  - GET: retrieve user's favorite Bible version
  - POST: save/update user's favorite Bible version

- Enhance Bible reader functionality
  - Automatically load user's favorite version on mount (logged-in users)
  - Add star button () next to version selector to set current version as default
  - Display success message when favorite version is saved
  - Fall back to default version if no favorite is set

- Add Bible Preferences section to Settings page
  - Display user's current favorite Bible version in dropdown
  - Allow users to view and change favorite version
  - Load all Bible versions (removed 200 limit) to ensure favorite is found
  - Show confirmation message when version is selected
  - Add loading state while fetching versions

- Fix renderValue in Select component to properly display version names
- Add comprehensive debug logging for troubleshooting

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
2025-09-30 09:50:01 +00:00
parent fee36dfdad
commit 2ae2f029ec
4 changed files with 326 additions and 28 deletions

View File

@@ -77,7 +77,9 @@ import {
CloudDownload, CloudDownload,
WifiOff, WifiOff,
Storage, Storage,
MoreVert MoreVert,
Star,
StarBorder
} from '@mui/icons-material' } from '@mui/icons-material'
interface BibleVerse { interface BibleVerse {
@@ -329,32 +331,65 @@ export default function BibleReaderNew({ initialVersion, initialBook, initialCha
// Fetch versions based on showAllVersions state and locale // Fetch versions based on showAllVersions state and locale
useEffect(() => { useEffect(() => {
setVersionsLoading(true) const loadVersions = async () => {
const url = showAllVersions setVersionsLoading(true)
? '/api/bible/versions?all=true&limit=200' // Limit to first 200 for performance const url = showAllVersions
: `/api/bible/versions?language=${locale}` ? '/api/bible/versions?all=true&limit=200' // Limit to first 200 for performance
: `/api/bible/versions?language=${locale}`
try {
const res = await fetch(url)
const data = await res.json()
fetch(url)
.then(res => res.json())
.then(data => {
if (data.success && data.versions) { if (data.success && data.versions) {
setVersions(data.versions) setVersions(data.versions)
// Keep current selection if it exists in new list, otherwise select default/first // Keep current selection if it exists in new list, otherwise select default/first
const currentVersionExists = data.versions.some((v: BibleVersion) => v.id === selectedVersion) const currentVersionExists = data.versions.some((v: BibleVersion) => v.id === selectedVersion)
if (!currentVersionExists || !selectedVersion) { if (!currentVersionExists || !selectedVersion) {
const defaultVersion = data.versions.find((v: BibleVersion) => v.isDefault) || data.versions[0] // Try to load user's favorite version first
if (defaultVersion) { let versionToSelect = null
setSelectedVersion(defaultVersion.id)
if (user) {
const token = localStorage.getItem('authToken')
if (token) {
try {
const favoriteRes = await fetch('/api/user/favorite-version', {
headers: { 'Authorization': `Bearer ${token}` }
})
const favoriteData = await favoriteRes.json()
if (favoriteData.success && favoriteData.favoriteBibleVersion) {
const favoriteVersion = data.versions.find((v: BibleVersion) => v.id === favoriteData.favoriteBibleVersion)
if (favoriteVersion) {
versionToSelect = favoriteVersion
}
}
} catch (error) {
console.error('Error loading favorite version:', error)
}
}
}
// Fall back to default version or first version
if (!versionToSelect) {
versionToSelect = data.versions.find((v: BibleVersion) => v.isDefault) || data.versions[0]
}
if (versionToSelect) {
setSelectedVersion(versionToSelect.id)
} }
} }
} }
setVersionsLoading(false) setVersionsLoading(false)
}) } catch (err) {
.catch(err => {
console.error('Error fetching versions:', err) console.error('Error fetching versions:', err)
setVersionsLoading(false) setVersionsLoading(false)
}) }
}, [locale, showAllVersions, selectedVersion]) }
loadVersions()
}, [locale, showAllVersions, selectedVersion, user])
// Handle URL parameters for bookmark navigation // Handle URL parameters for bookmark navigation
useEffect(() => { useEffect(() => {
@@ -1000,6 +1035,40 @@ export default function BibleReaderNew({ initialVersion, initialBook, initialCha
} }
} }
const handleSetFavoriteVersion = async () => {
if (!user) {
router.push(`/${locale}/login?redirect=${encodeURIComponent(`/${locale}/bible?version=${selectedVersion}&book=${selectedBook}&chapter=${selectedChapter}`)}`)
return
}
const token = localStorage.getItem('authToken')
if (!token) return
try {
const response = await fetch('/api/user/favorite-version', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify({ versionId: selectedVersion })
})
const data = await response.json()
if (data.success) {
setCopyFeedback({
open: true,
message: 'This version has been set as your default'
})
} else {
alert('Failed to set favorite version')
}
} catch (error) {
console.error('Error setting favorite version:', error)
alert('Failed to set favorite version')
}
}
const getThemeStyles = () => { const getThemeStyles = () => {
switch (preferences.theme) { switch (preferences.theme) {
case 'dark': case 'dark':
@@ -1190,6 +1259,15 @@ export default function BibleReaderNew({ initialVersion, initialBook, initialCha
style: { maxHeight: 400 } style: { maxHeight: 400 }
}} }}
/> />
<Tooltip title={user ? 'Set as my default version' : 'Login to set default version'}>
<IconButton
size="small"
onClick={handleSetFavoriteVersion}
sx={{ color: 'warning.main' }}
>
<Star />
</IconButton>
</Tooltip>
<Tooltip title={showAllVersions ? 'Show language versions only' : 'Show all versions'}> <Tooltip title={showAllVersions ? 'Show language versions only' : 'Show all versions'}>
<IconButton <IconButton
size="small" size="small"

View File

@@ -1,6 +1,6 @@
'use client' 'use client'
import { useState } from 'react' import { useState, useEffect } from 'react'
import { useTranslations, useLocale } from 'next-intl' import { useTranslations, useLocale } from 'next-intl'
import { useAuth } from '@/hooks/use-auth' import { useAuth } from '@/hooks/use-auth'
import { ProtectedRoute } from '@/components/auth/protected-route' import { ProtectedRoute } from '@/components/auth/protected-route'
@@ -19,7 +19,8 @@ import {
CardContent, CardContent,
Divider, Divider,
Alert, Alert,
Button Button,
CircularProgress
} from '@mui/material' } from '@mui/material'
import { import {
Settings as SettingsIcon, Settings as SettingsIcon,
@@ -28,7 +29,8 @@ import {
Language, Language,
Notifications, Notifications,
Security, Security,
Save Save,
MenuBook
} from '@mui/icons-material' } from '@mui/icons-material'
export default function SettingsPage() { export default function SettingsPage() {
@@ -43,6 +45,48 @@ export default function SettingsPage() {
language: locale language: locale
}) })
const [message, setMessage] = useState('') const [message, setMessage] = useState('')
const [bibleVersions, setBibleVersions] = useState<any[]>([])
const [favoriteBibleVersion, setFavoriteBibleVersion] = useState<string | null>(null)
const [loadingVersions, setLoadingVersions] = useState(true)
useEffect(() => {
const loadBiblePreferences = async () => {
try {
// Load available versions (no limit to ensure we get all versions including the favorite)
const versionsRes = await fetch('/api/bible/versions?all=true')
const versionsData = await versionsRes.json()
if (versionsData.success) {
console.log('[Settings] Loaded versions:', versionsData.versions.length)
setBibleVersions(versionsData.versions)
}
// Load user's favorite version
const token = localStorage.getItem('authToken')
if (token) {
const favoriteRes = await fetch('/api/user/favorite-version', {
headers: { 'Authorization': `Bearer ${token}` }
})
const favoriteData = await favoriteRes.json()
console.log('[Settings] Favorite version data:', favoriteData)
if (favoriteData.success && favoriteData.favoriteBibleVersion) {
console.log('[Settings] Setting favorite version:', favoriteData.favoriteBibleVersion)
console.log('[Settings] Type of favorite version:', typeof favoriteData.favoriteBibleVersion)
setFavoriteBibleVersion(favoriteData.favoriteBibleVersion)
}
}
} catch (error) {
console.error('Error loading Bible preferences:', error)
} finally {
setLoadingVersions(false)
}
}
if (user) {
loadBiblePreferences()
} else {
setLoadingVersions(false)
}
}, [user])
const handleSettingChange = (setting: string, value: any) => { const handleSettingChange = (setting: string, value: any) => {
setSettings(prev => ({ setSettings(prev => ({
@@ -51,6 +95,33 @@ export default function SettingsPage() {
})) }))
} }
const handleFavoriteVersionChange = async (versionId: string) => {
const token = localStorage.getItem('authToken')
if (!token) return
try {
const response = await fetch('/api/user/favorite-version', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify({ versionId })
})
const data = await response.json()
if (data.success) {
setFavoriteBibleVersion(versionId)
setMessage('Favorite Bible version updated successfully')
} else {
setMessage('Failed to update favorite version')
}
} catch (error) {
console.error('Error updating favorite version:', error)
setMessage('Failed to update favorite version')
}
}
const handleSave = async () => { const handleSave = async () => {
try { try {
// TODO: Implement settings update API // TODO: Implement settings update API
@@ -176,6 +247,69 @@ export default function SettingsPage() {
</Card> </Card>
</Box> </Box>
{/* Bible Preferences */}
<Box sx={{ flex: '1 1 100%' }}>
<Card variant="outlined">
<CardContent>
<Box display="flex" alignItems="center" mb={3}>
<MenuBook sx={{ mr: 1, color: 'primary.main' }} />
<Typography variant="h6">
Bible Preferences
</Typography>
</Box>
<Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
Select your preferred Bible version. This will be loaded automatically when you open the Bible reader.
</Typography>
{loadingVersions ? (
<Box display="flex" justifyContent="center" py={2}>
<CircularProgress size={24} />
</Box>
) : (
<Box>
<FormControl fullWidth>
<InputLabel>Favorite Bible Version</InputLabel>
<Select
value={favoriteBibleVersion || ''}
label="Favorite Bible Version"
onChange={(e) => handleFavoriteVersionChange(e.target.value)}
renderValue={(selected) => {
if (!selected) {
return <em>None selected</em>
}
console.log('[Settings] renderValue - selected:', selected)
console.log('[Settings] renderValue - bibleVersions:', bibleVersions.length)
const version = bibleVersions.find(v => v.id === selected)
console.log('[Settings] renderValue - found version:', version)
if (version) {
return `${version.name} - ${version.abbreviation} (${version.language.toUpperCase()})`
}
return selected
}}
disabled={bibleVersions.length === 0}
>
<MenuItem value="">
<em>None selected</em>
</MenuItem>
{bibleVersions.map((version) => (
<MenuItem key={version.id} value={version.id}>
{version.name} - {version.abbreviation} ({version.language.toUpperCase()})
</MenuItem>
))}
</Select>
</FormControl>
{favoriteBibleVersion && (
<Typography variant="caption" color="success.main" sx={{ mt: 1, display: 'block' }}>
This version will be loaded when you open the Bible reader
</Typography>
)}
</Box>
)}
</CardContent>
</Card>
</Box>
{/* Security Settings */} {/* Security Settings */}
<Box sx={{ flex: '1 1 100%' }}> <Box sx={{ flex: '1 1 100%' }}>
<Card variant="outlined"> <Card variant="outlined">

View File

@@ -0,0 +1,85 @@
import { NextResponse } from 'next/server'
import { prisma } from '@/lib/db'
import jwt from 'jsonwebtoken'
export const runtime = 'nodejs'
// Get user's favorite Bible version
export async function GET(request: Request) {
try {
const authHeader = request.headers.get('authorization')
if (!authHeader?.startsWith('Bearer ')) {
return NextResponse.json({ success: false, error: 'Unauthorized' }, { status: 401 })
}
const token = authHeader.substring(7)
const decoded = jwt.verify(token, process.env.JWT_SECRET!) as { userId: string }
const user = await prisma.user.findUnique({
where: { id: decoded.userId },
select: { favoriteBibleVersion: true }
})
if (!user) {
return NextResponse.json({ success: false, error: 'User not found' }, { status: 404 })
}
return NextResponse.json({
success: true,
favoriteBibleVersion: user.favoriteBibleVersion
})
} catch (error) {
console.error('Error getting favorite version:', error)
return NextResponse.json(
{ success: false, error: 'Failed to get favorite version' },
{ status: 500 }
)
}
}
// Set user's favorite Bible version
export async function POST(request: Request) {
try {
const authHeader = request.headers.get('authorization')
if (!authHeader?.startsWith('Bearer ')) {
return NextResponse.json({ success: false, error: 'Unauthorized' }, { status: 401 })
}
const token = authHeader.substring(7)
const decoded = jwt.verify(token, process.env.JWT_SECRET!) as { userId: string }
const body = await request.json()
const { versionId } = body
if (!versionId) {
return NextResponse.json({ success: false, error: 'Version ID is required' }, { status: 400 })
}
// Verify that the version exists
const version = await prisma.bibleVersion.findUnique({
where: { id: versionId }
})
if (!version) {
return NextResponse.json({ success: false, error: 'Bible version not found' }, { status: 404 })
}
// Update user's favorite version
await prisma.user.update({
where: { id: decoded.userId },
data: { favoriteBibleVersion: versionId }
})
return NextResponse.json({
success: true,
message: 'Favorite Bible version updated',
favoriteBibleVersion: versionId
})
} catch (error) {
console.error('Error setting favorite version:', error)
return NextResponse.json(
{ success: false, error: 'Failed to set favorite version' },
{ status: 500 }
)
}
}

View File

@@ -8,16 +8,17 @@ datasource db {
} }
model User { model User {
id String @id @default(uuid()) id String @id @default(uuid())
email String @unique email String @unique
passwordHash String passwordHash String
name String? name String?
role String @default("user") // "user", "admin", "moderator" role String @default("user") // "user", "admin", "moderator"
theme String @default("light") theme String @default("light")
fontSize String @default("medium") fontSize String @default("medium")
createdAt DateTime @default(now()) favoriteBibleVersion String? // User's preferred Bible version ID
updatedAt DateTime @updatedAt createdAt DateTime @default(now())
lastLoginAt DateTime? updatedAt DateTime @updatedAt
lastLoginAt DateTime?
sessions Session[] sessions Session[]
bookmarks Bookmark[] bookmarks Bookmark[]