Implement complete bookmark functionality for Bible reading
Add both chapter-level and verse-level bookmarking capabilities: Database Changes: - Add ChapterBookmark table for chapter-level bookmarks - Update schema with proper relationships to User and BibleBook models - Maintain existing Bookmark table for verse-level bookmarks API Endpoints: - /api/bookmarks/chapter (GET, POST, DELETE) with check endpoint - /api/bookmarks/verse (GET, POST, DELETE) with check and bulk-check endpoints - JWT authentication required for all bookmark operations - Multilingual error messages (Romanian/English) Frontend Implementation: - Chapter bookmark button in Bible page header with visual state feedback - Individual verse bookmark icons with hover-to-reveal UI - Highlighted background for bookmarked verses - Efficient bulk checking for verse bookmarks per chapter - Real-time UI updates without page refresh 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
@@ -21,16 +21,19 @@ import {
|
||||
useTheme,
|
||||
CircularProgress,
|
||||
Skeleton,
|
||||
IconButton,
|
||||
} from '@mui/material'
|
||||
import {
|
||||
MenuBook,
|
||||
NavigateBefore,
|
||||
NavigateNext,
|
||||
Bookmark,
|
||||
BookmarkBorder,
|
||||
Share,
|
||||
} from '@mui/icons-material'
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useTranslations, useLocale } from 'next-intl'
|
||||
import { useAuth } from '@/hooks/use-auth'
|
||||
|
||||
interface BibleVerse {
|
||||
id: string
|
||||
@@ -62,6 +65,11 @@ export default function BiblePage() {
|
||||
const [selectedChapter, setSelectedChapter] = useState<number>(1)
|
||||
const [verses, setVerses] = useState<BibleVerse[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [isBookmarked, setIsBookmarked] = useState(false)
|
||||
const [bookmarkLoading, setBookmarkLoading] = useState(false)
|
||||
const [verseBookmarks, setVerseBookmarks] = useState<{[key: string]: any}>({})
|
||||
const [verseBookmarkLoading, setVerseBookmarkLoading] = useState<{[key: string]: boolean}>({})
|
||||
const { user } = useAuth()
|
||||
|
||||
// Fetch available books
|
||||
useEffect(() => {
|
||||
@@ -97,6 +105,56 @@ export default function BiblePage() {
|
||||
}
|
||||
}, [selectedBook, selectedChapter])
|
||||
|
||||
// Check if chapter is bookmarked
|
||||
useEffect(() => {
|
||||
if (selectedBook && selectedChapter && user) {
|
||||
const token = localStorage.getItem('authToken')
|
||||
if (token) {
|
||||
fetch(`/api/bookmarks/chapter/check?bookId=${selectedBook}&chapterNum=${selectedChapter}&locale=${locale}`, {
|
||||
headers: {
|
||||
'Authorization': `Bearer ${token}`
|
||||
}
|
||||
})
|
||||
.then(res => res.json())
|
||||
.then(data => {
|
||||
setIsBookmarked(data.isBookmarked || false)
|
||||
})
|
||||
.catch(err => {
|
||||
console.error('Error checking bookmark:', err)
|
||||
})
|
||||
}
|
||||
} else {
|
||||
setIsBookmarked(false)
|
||||
}
|
||||
}, [selectedBook, selectedChapter, user, locale])
|
||||
|
||||
// Check verse bookmarks when verses change
|
||||
useEffect(() => {
|
||||
if (verses.length > 0 && user) {
|
||||
const token = localStorage.getItem('authToken')
|
||||
if (token) {
|
||||
const verseIds = verses.map(verse => verse.id)
|
||||
fetch(`/api/bookmarks/verse/bulk-check?locale=${locale}`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${token}`
|
||||
},
|
||||
body: JSON.stringify({ verseIds })
|
||||
})
|
||||
.then(res => res.json())
|
||||
.then(data => {
|
||||
setVerseBookmarks(data.bookmarks || {})
|
||||
})
|
||||
.catch(err => {
|
||||
console.error('Error checking verse bookmarks:', err)
|
||||
})
|
||||
}
|
||||
} else {
|
||||
setVerseBookmarks({})
|
||||
}
|
||||
}, [verses, user, locale])
|
||||
|
||||
const currentBook = books.find(book => book.id === selectedBook)
|
||||
const maxChapters = currentBook?.chapters?.length || 50 // Default fallback
|
||||
|
||||
@@ -121,6 +179,113 @@ export default function BiblePage() {
|
||||
}
|
||||
}
|
||||
|
||||
const handleBookmarkToggle = async () => {
|
||||
if (!user || !selectedBook || !selectedChapter) return
|
||||
|
||||
setBookmarkLoading(true)
|
||||
const token = localStorage.getItem('authToken')
|
||||
|
||||
if (!token) {
|
||||
setBookmarkLoading(false)
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
if (isBookmarked) {
|
||||
// Remove bookmark
|
||||
const response = await fetch(`/api/bookmarks/chapter?bookId=${selectedBook}&chapterNum=${selectedChapter}&locale=${locale}`, {
|
||||
method: 'DELETE',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${token}`
|
||||
}
|
||||
})
|
||||
|
||||
if (response.ok) {
|
||||
setIsBookmarked(false)
|
||||
}
|
||||
} else {
|
||||
// Add bookmark
|
||||
const response = await fetch(`/api/bookmarks/chapter?locale=${locale}`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${token}`
|
||||
},
|
||||
body: JSON.stringify({
|
||||
bookId: selectedBook,
|
||||
chapterNum: selectedChapter
|
||||
})
|
||||
})
|
||||
|
||||
if (response.ok) {
|
||||
setIsBookmarked(true)
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error toggling bookmark:', error)
|
||||
} finally {
|
||||
setBookmarkLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleVerseBookmarkToggle = async (verse: BibleVerse) => {
|
||||
if (!user) return
|
||||
|
||||
setVerseBookmarkLoading(prev => ({ ...prev, [verse.id]: true }))
|
||||
const token = localStorage.getItem('authToken')
|
||||
|
||||
if (!token) {
|
||||
setVerseBookmarkLoading(prev => ({ ...prev, [verse.id]: false }))
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const isCurrentlyBookmarked = !!verseBookmarks[verse.id]
|
||||
|
||||
if (isCurrentlyBookmarked) {
|
||||
// Remove verse bookmark
|
||||
const response = await fetch(`/api/bookmarks/verse?verseId=${verse.id}&locale=${locale}`, {
|
||||
method: 'DELETE',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${token}`
|
||||
}
|
||||
})
|
||||
|
||||
if (response.ok) {
|
||||
setVerseBookmarks(prev => {
|
||||
const newBookmarks = { ...prev }
|
||||
delete newBookmarks[verse.id]
|
||||
return newBookmarks
|
||||
})
|
||||
}
|
||||
} else {
|
||||
// Add verse bookmark
|
||||
const response = await fetch(`/api/bookmarks/verse?locale=${locale}`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${token}`
|
||||
},
|
||||
body: JSON.stringify({
|
||||
verseId: verse.id
|
||||
})
|
||||
})
|
||||
|
||||
if (response.ok) {
|
||||
const data = await response.json()
|
||||
setVerseBookmarks(prev => ({
|
||||
...prev,
|
||||
[verse.id]: data.bookmark
|
||||
}))
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error toggling verse bookmark:', error)
|
||||
} finally {
|
||||
setVerseBookmarkLoading(prev => ({ ...prev, [verse.id]: false }))
|
||||
}
|
||||
}
|
||||
|
||||
if (loading && books.length === 0) {
|
||||
return (
|
||||
<Box>
|
||||
@@ -223,10 +388,13 @@ export default function BiblePage() {
|
||||
<Box sx={{ display: 'flex', gap: 1 }}>
|
||||
<Button
|
||||
startIcon={<Bookmark />}
|
||||
variant="outlined"
|
||||
variant={isBookmarked ? "contained" : "outlined"}
|
||||
size="small"
|
||||
onClick={handleBookmarkToggle}
|
||||
disabled={!user || bookmarkLoading}
|
||||
color={isBookmarked ? "primary" : "inherit"}
|
||||
>
|
||||
{t('save')}
|
||||
{bookmarkLoading ? t('saving') : (isBookmarked ? t('saved') : t('save'))}
|
||||
</Button>
|
||||
<Button
|
||||
startIcon={<Share />}
|
||||
@@ -253,21 +421,33 @@ export default function BiblePage() {
|
||||
</Box>
|
||||
) : verses.length > 0 ? (
|
||||
<Box>
|
||||
{verses.map((verse) => (
|
||||
<Box key={verse.id} sx={{ mb: 2 }}>
|
||||
{verses.map((verse) => {
|
||||
const isVerseBookmarked = !!verseBookmarks[verse.id]
|
||||
const isVerseLoading = !!verseBookmarkLoading[verse.id]
|
||||
|
||||
return (
|
||||
<Box
|
||||
key={verse.id}
|
||||
sx={{
|
||||
mb: 2,
|
||||
display: 'flex',
|
||||
alignItems: 'flex-start',
|
||||
gap: 1,
|
||||
'&:hover .verse-bookmark': {
|
||||
opacity: 1
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Box sx={{ flex: 1 }}>
|
||||
<Typography
|
||||
variant="body1"
|
||||
component="p"
|
||||
sx={{
|
||||
lineHeight: 1.8,
|
||||
fontSize: '1.1rem',
|
||||
'&:hover': {
|
||||
bgcolor: 'action.hover',
|
||||
cursor: 'pointer',
|
||||
borderRadius: 1,
|
||||
p: 1,
|
||||
m: -1,
|
||||
},
|
||||
bgcolor: isVerseBookmarked ? 'warning.light' : 'transparent',
|
||||
borderRadius: isVerseBookmarked ? 1 : 0,
|
||||
p: isVerseBookmarked ? 1 : 0,
|
||||
}}
|
||||
>
|
||||
<Typography
|
||||
@@ -284,7 +464,25 @@ export default function BiblePage() {
|
||||
{verse.text}
|
||||
</Typography>
|
||||
</Box>
|
||||
))}
|
||||
|
||||
{user && (
|
||||
<IconButton
|
||||
className="verse-bookmark"
|
||||
size="small"
|
||||
onClick={() => handleVerseBookmarkToggle(verse)}
|
||||
disabled={isVerseLoading}
|
||||
sx={{
|
||||
opacity: isVerseBookmarked ? 1 : 0.3,
|
||||
transition: 'opacity 0.2s',
|
||||
color: isVerseBookmarked ? 'warning.main' : 'action.active'
|
||||
}}
|
||||
>
|
||||
{isVerseBookmarked ? <Bookmark fontSize="small" /> : <BookmarkBorder fontSize="small" />}
|
||||
</IconButton>
|
||||
)}
|
||||
</Box>
|
||||
)
|
||||
})}
|
||||
</Box>
|
||||
) : (
|
||||
<Typography textAlign="center" color="text.secondary">
|
||||
|
||||
75
app/api/bookmarks/chapter/check/route.ts
Normal file
75
app/api/bookmarks/chapter/check/route.ts
Normal file
@@ -0,0 +1,75 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { getUserFromToken } from '@/lib/auth'
|
||||
import { prisma } from '@/lib/db'
|
||||
|
||||
export const runtime = 'nodejs'
|
||||
|
||||
function getErrorMessages(locale: string = 'ro') {
|
||||
const messages = {
|
||||
ro: {
|
||||
unauthorized: 'Nu ești autentificat',
|
||||
bookmarkRequired: 'Informațiile bookmark-ului sunt obligatorii',
|
||||
bookmarkError: 'Eroare la verificarea bookmark-ului'
|
||||
},
|
||||
en: {
|
||||
unauthorized: 'Unauthorized',
|
||||
bookmarkRequired: 'Bookmark information is required',
|
||||
bookmarkError: 'Error checking bookmark'
|
||||
}
|
||||
}
|
||||
return messages[locale as keyof typeof messages] || messages.ro
|
||||
}
|
||||
|
||||
// GET - Check if chapter is bookmarked
|
||||
export async function GET(request: Request) {
|
||||
try {
|
||||
const url = new URL(request.url)
|
||||
const locale = url.searchParams.get('locale') || 'ro'
|
||||
const bookId = url.searchParams.get('bookId')
|
||||
const chapterNum = parseInt(url.searchParams.get('chapterNum') || '0')
|
||||
const messages = getErrorMessages(locale)
|
||||
|
||||
// Get token from authorization header
|
||||
const authHeader = request.headers.get('authorization')
|
||||
const token = authHeader?.replace('Bearer ', '')
|
||||
|
||||
if (!token) {
|
||||
return NextResponse.json({ error: messages.unauthorized }, { status: 401 })
|
||||
}
|
||||
|
||||
// Verify token and get user
|
||||
const user = await getUserFromToken(token)
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: messages.unauthorized }, { status: 401 })
|
||||
}
|
||||
|
||||
// Validate input
|
||||
if (!bookId || !chapterNum) {
|
||||
return NextResponse.json({ error: messages.bookmarkRequired }, { status: 400 })
|
||||
}
|
||||
|
||||
// Check if bookmark exists
|
||||
const bookmark = await prisma.chapterBookmark.findUnique({
|
||||
where: {
|
||||
userId_bookId_chapterNum: {
|
||||
userId: user.id,
|
||||
bookId: bookId,
|
||||
chapterNum: chapterNum
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
return NextResponse.json({
|
||||
isBookmarked: !!bookmark,
|
||||
bookmark: bookmark || null
|
||||
})
|
||||
|
||||
} catch (error) {
|
||||
console.error('Bookmark check error:', error)
|
||||
const url = new URL(request.url)
|
||||
const locale = url.searchParams.get('locale') || 'ro'
|
||||
const messages = getErrorMessages(locale)
|
||||
|
||||
return NextResponse.json({ error: messages.bookmarkError }, { status: 500 })
|
||||
}
|
||||
}
|
||||
199
app/api/bookmarks/chapter/route.ts
Normal file
199
app/api/bookmarks/chapter/route.ts
Normal file
@@ -0,0 +1,199 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { getUserFromToken } from '@/lib/auth'
|
||||
import { prisma } from '@/lib/db'
|
||||
|
||||
export const runtime = 'nodejs'
|
||||
|
||||
function getErrorMessages(locale: string = 'ro') {
|
||||
const messages = {
|
||||
ro: {
|
||||
unauthorized: 'Nu ești autentificat',
|
||||
bookmarkRequired: 'Informațiile bookmark-ului sunt obligatorii',
|
||||
bookmarkError: 'Eroare la salvarea bookmark-ului',
|
||||
bookmarkRemoved: 'Bookmark șters cu succes',
|
||||
bookmarkSaved: 'Bookmark salvat cu succes'
|
||||
},
|
||||
en: {
|
||||
unauthorized: 'Unauthorized',
|
||||
bookmarkRequired: 'Bookmark information is required',
|
||||
bookmarkError: 'Error saving bookmark',
|
||||
bookmarkRemoved: 'Bookmark removed successfully',
|
||||
bookmarkSaved: 'Bookmark saved successfully'
|
||||
}
|
||||
}
|
||||
return messages[locale as keyof typeof messages] || messages.ro
|
||||
}
|
||||
|
||||
// GET - Get user's chapter bookmarks
|
||||
export async function GET(request: Request) {
|
||||
try {
|
||||
const url = new URL(request.url)
|
||||
const locale = url.searchParams.get('locale') || 'ro'
|
||||
const messages = getErrorMessages(locale)
|
||||
|
||||
// Get token from authorization header
|
||||
const authHeader = request.headers.get('authorization')
|
||||
const token = authHeader?.replace('Bearer ', '')
|
||||
|
||||
if (!token) {
|
||||
return NextResponse.json({ error: messages.unauthorized }, { status: 401 })
|
||||
}
|
||||
|
||||
// Verify token and get user
|
||||
const user = await getUserFromToken(token)
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: messages.unauthorized }, { status: 401 })
|
||||
}
|
||||
|
||||
// Get user's chapter bookmarks with book information
|
||||
const bookmarks = await prisma.chapterBookmark.findMany({
|
||||
where: {
|
||||
userId: user.id
|
||||
},
|
||||
include: {
|
||||
book: {
|
||||
include: {
|
||||
version: true
|
||||
}
|
||||
}
|
||||
},
|
||||
orderBy: {
|
||||
createdAt: 'desc'
|
||||
}
|
||||
})
|
||||
|
||||
return NextResponse.json({ bookmarks })
|
||||
|
||||
} catch (error) {
|
||||
console.error('Bookmark fetch error:', error)
|
||||
const url = new URL(request.url)
|
||||
const locale = url.searchParams.get('locale') || 'ro'
|
||||
const messages = getErrorMessages(locale)
|
||||
|
||||
return NextResponse.json({ error: messages.bookmarkError }, { status: 500 })
|
||||
}
|
||||
}
|
||||
|
||||
// POST - Create chapter bookmark
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const url = new URL(request.url)
|
||||
const locale = url.searchParams.get('locale') || 'ro'
|
||||
const messages = getErrorMessages(locale)
|
||||
|
||||
// Get token from authorization header
|
||||
const authHeader = request.headers.get('authorization')
|
||||
const token = authHeader?.replace('Bearer ', '')
|
||||
|
||||
if (!token) {
|
||||
return NextResponse.json({ error: messages.unauthorized }, { status: 401 })
|
||||
}
|
||||
|
||||
// Verify token and get user
|
||||
const user = await getUserFromToken(token)
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: messages.unauthorized }, { status: 401 })
|
||||
}
|
||||
|
||||
// Parse request body
|
||||
const { bookId, chapterNum, note } = await request.json()
|
||||
|
||||
// Validate input
|
||||
if (!bookId || !chapterNum) {
|
||||
return NextResponse.json({ error: messages.bookmarkRequired }, { status: 400 })
|
||||
}
|
||||
|
||||
// Create or update bookmark
|
||||
const bookmark = await prisma.chapterBookmark.upsert({
|
||||
where: {
|
||||
userId_bookId_chapterNum: {
|
||||
userId: user.id,
|
||||
bookId: bookId,
|
||||
chapterNum: chapterNum
|
||||
}
|
||||
},
|
||||
update: {
|
||||
note: note || null
|
||||
},
|
||||
create: {
|
||||
userId: user.id,
|
||||
bookId: bookId,
|
||||
chapterNum: chapterNum,
|
||||
note: note || null
|
||||
},
|
||||
include: {
|
||||
book: {
|
||||
include: {
|
||||
version: true
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
return NextResponse.json({
|
||||
message: messages.bookmarkSaved,
|
||||
bookmark
|
||||
})
|
||||
|
||||
} catch (error) {
|
||||
console.error('Bookmark creation error:', error)
|
||||
const url = new URL(request.url)
|
||||
const locale = url.searchParams.get('locale') || 'ro'
|
||||
const messages = getErrorMessages(locale)
|
||||
|
||||
return NextResponse.json({ error: messages.bookmarkError }, { status: 500 })
|
||||
}
|
||||
}
|
||||
|
||||
// DELETE - Remove chapter bookmark
|
||||
export async function DELETE(request: Request) {
|
||||
try {
|
||||
const url = new URL(request.url)
|
||||
const locale = url.searchParams.get('locale') || 'ro'
|
||||
const bookId = url.searchParams.get('bookId')
|
||||
const chapterNum = parseInt(url.searchParams.get('chapterNum') || '0')
|
||||
const messages = getErrorMessages(locale)
|
||||
|
||||
// Get token from authorization header
|
||||
const authHeader = request.headers.get('authorization')
|
||||
const token = authHeader?.replace('Bearer ', '')
|
||||
|
||||
if (!token) {
|
||||
return NextResponse.json({ error: messages.unauthorized }, { status: 401 })
|
||||
}
|
||||
|
||||
// Verify token and get user
|
||||
const user = await getUserFromToken(token)
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: messages.unauthorized }, { status: 401 })
|
||||
}
|
||||
|
||||
// Validate input
|
||||
if (!bookId || !chapterNum) {
|
||||
return NextResponse.json({ error: messages.bookmarkRequired }, { status: 400 })
|
||||
}
|
||||
|
||||
// Delete bookmark
|
||||
await prisma.chapterBookmark.delete({
|
||||
where: {
|
||||
userId_bookId_chapterNum: {
|
||||
userId: user.id,
|
||||
bookId: bookId,
|
||||
chapterNum: chapterNum
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
return NextResponse.json({
|
||||
message: messages.bookmarkRemoved
|
||||
})
|
||||
|
||||
} catch (error) {
|
||||
console.error('Bookmark deletion error:', error)
|
||||
const url = new URL(request.url)
|
||||
const locale = url.searchParams.get('locale') || 'ro'
|
||||
const messages = getErrorMessages(locale)
|
||||
|
||||
return NextResponse.json({ error: messages.bookmarkError }, { status: 500 })
|
||||
}
|
||||
}
|
||||
80
app/api/bookmarks/verse/bulk-check/route.ts
Normal file
80
app/api/bookmarks/verse/bulk-check/route.ts
Normal file
@@ -0,0 +1,80 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { getUserFromToken } from '@/lib/auth'
|
||||
import { prisma } from '@/lib/db'
|
||||
|
||||
export const runtime = 'nodejs'
|
||||
|
||||
function getErrorMessages(locale: string = 'ro') {
|
||||
const messages = {
|
||||
ro: {
|
||||
unauthorized: 'Nu ești autentificat',
|
||||
bookmarkRequired: 'Lista de versete este obligatorie',
|
||||
bookmarkError: 'Eroare la verificarea bookmark-urilor'
|
||||
},
|
||||
en: {
|
||||
unauthorized: 'Unauthorized',
|
||||
bookmarkRequired: 'Verse list is required',
|
||||
bookmarkError: 'Error checking bookmarks'
|
||||
}
|
||||
}
|
||||
return messages[locale as keyof typeof messages] || messages.ro
|
||||
}
|
||||
|
||||
// POST - Check multiple verses for bookmarks
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const url = new URL(request.url)
|
||||
const locale = url.searchParams.get('locale') || 'ro'
|
||||
const messages = getErrorMessages(locale)
|
||||
|
||||
// Get token from authorization header
|
||||
const authHeader = request.headers.get('authorization')
|
||||
const token = authHeader?.replace('Bearer ', '')
|
||||
|
||||
if (!token) {
|
||||
return NextResponse.json({ error: messages.unauthorized }, { status: 401 })
|
||||
}
|
||||
|
||||
// Verify token and get user
|
||||
const user = await getUserFromToken(token)
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: messages.unauthorized }, { status: 401 })
|
||||
}
|
||||
|
||||
// Parse request body
|
||||
const { verseIds } = await request.json()
|
||||
|
||||
// Validate input
|
||||
if (!verseIds || !Array.isArray(verseIds)) {
|
||||
return NextResponse.json({ error: messages.bookmarkRequired }, { status: 400 })
|
||||
}
|
||||
|
||||
// Get all bookmarks for these verses
|
||||
const bookmarks = await prisma.bookmark.findMany({
|
||||
where: {
|
||||
userId: user.id,
|
||||
verseId: {
|
||||
in: verseIds
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
// Create a map of verseId -> bookmark
|
||||
const bookmarkMap = {}
|
||||
bookmarks.forEach(bookmark => {
|
||||
bookmarkMap[bookmark.verseId] = bookmark
|
||||
})
|
||||
|
||||
return NextResponse.json({
|
||||
bookmarks: bookmarkMap
|
||||
})
|
||||
|
||||
} catch (error) {
|
||||
console.error('Verse bookmark bulk check error:', error)
|
||||
const url = new URL(request.url)
|
||||
const locale = url.searchParams.get('locale') || 'ro'
|
||||
const messages = getErrorMessages(locale)
|
||||
|
||||
return NextResponse.json({ error: messages.bookmarkError }, { status: 500 })
|
||||
}
|
||||
}
|
||||
73
app/api/bookmarks/verse/check/route.ts
Normal file
73
app/api/bookmarks/verse/check/route.ts
Normal file
@@ -0,0 +1,73 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { getUserFromToken } from '@/lib/auth'
|
||||
import { prisma } from '@/lib/db'
|
||||
|
||||
export const runtime = 'nodejs'
|
||||
|
||||
function getErrorMessages(locale: string = 'ro') {
|
||||
const messages = {
|
||||
ro: {
|
||||
unauthorized: 'Nu ești autentificat',
|
||||
bookmarkRequired: 'Informațiile bookmark-ului sunt obligatorii',
|
||||
bookmarkError: 'Eroare la verificarea bookmark-ului'
|
||||
},
|
||||
en: {
|
||||
unauthorized: 'Unauthorized',
|
||||
bookmarkRequired: 'Bookmark information is required',
|
||||
bookmarkError: 'Error checking bookmark'
|
||||
}
|
||||
}
|
||||
return messages[locale as keyof typeof messages] || messages.ro
|
||||
}
|
||||
|
||||
// GET - Check if verse is bookmarked
|
||||
export async function GET(request: Request) {
|
||||
try {
|
||||
const url = new URL(request.url)
|
||||
const locale = url.searchParams.get('locale') || 'ro'
|
||||
const verseId = url.searchParams.get('verseId')
|
||||
const messages = getErrorMessages(locale)
|
||||
|
||||
// Get token from authorization header
|
||||
const authHeader = request.headers.get('authorization')
|
||||
const token = authHeader?.replace('Bearer ', '')
|
||||
|
||||
if (!token) {
|
||||
return NextResponse.json({ error: messages.unauthorized }, { status: 401 })
|
||||
}
|
||||
|
||||
// Verify token and get user
|
||||
const user = await getUserFromToken(token)
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: messages.unauthorized }, { status: 401 })
|
||||
}
|
||||
|
||||
// Validate input
|
||||
if (!verseId) {
|
||||
return NextResponse.json({ error: messages.bookmarkRequired }, { status: 400 })
|
||||
}
|
||||
|
||||
// Check if bookmark exists
|
||||
const bookmark = await prisma.bookmark.findUnique({
|
||||
where: {
|
||||
userId_verseId: {
|
||||
userId: user.id,
|
||||
verseId: verseId
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
return NextResponse.json({
|
||||
isBookmarked: !!bookmark,
|
||||
bookmark: bookmark || null
|
||||
})
|
||||
|
||||
} catch (error) {
|
||||
console.error('Verse bookmark check error:', error)
|
||||
const url = new URL(request.url)
|
||||
const locale = url.searchParams.get('locale') || 'ro'
|
||||
const messages = getErrorMessages(locale)
|
||||
|
||||
return NextResponse.json({ error: messages.bookmarkError }, { status: 500 })
|
||||
}
|
||||
}
|
||||
213
app/api/bookmarks/verse/route.ts
Normal file
213
app/api/bookmarks/verse/route.ts
Normal file
@@ -0,0 +1,213 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { getUserFromToken } from '@/lib/auth'
|
||||
import { prisma } from '@/lib/db'
|
||||
|
||||
export const runtime = 'nodejs'
|
||||
|
||||
function getErrorMessages(locale: string = 'ro') {
|
||||
const messages = {
|
||||
ro: {
|
||||
unauthorized: 'Nu ești autentificat',
|
||||
bookmarkRequired: 'Informațiile bookmark-ului sunt obligatorii',
|
||||
bookmarkError: 'Eroare la salvarea bookmark-ului',
|
||||
bookmarkRemoved: 'Bookmark șters cu succes',
|
||||
bookmarkSaved: 'Bookmark salvat cu succes'
|
||||
},
|
||||
en: {
|
||||
unauthorized: 'Unauthorized',
|
||||
bookmarkRequired: 'Bookmark information is required',
|
||||
bookmarkError: 'Error saving bookmark',
|
||||
bookmarkRemoved: 'Bookmark removed successfully',
|
||||
bookmarkSaved: 'Bookmark saved successfully'
|
||||
}
|
||||
}
|
||||
return messages[locale as keyof typeof messages] || messages.ro
|
||||
}
|
||||
|
||||
// GET - Get user's verse bookmarks
|
||||
export async function GET(request: Request) {
|
||||
try {
|
||||
const url = new URL(request.url)
|
||||
const locale = url.searchParams.get('locale') || 'ro'
|
||||
const messages = getErrorMessages(locale)
|
||||
|
||||
// Get token from authorization header
|
||||
const authHeader = request.headers.get('authorization')
|
||||
const token = authHeader?.replace('Bearer ', '')
|
||||
|
||||
if (!token) {
|
||||
return NextResponse.json({ error: messages.unauthorized }, { status: 401 })
|
||||
}
|
||||
|
||||
// Verify token and get user
|
||||
const user = await getUserFromToken(token)
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: messages.unauthorized }, { status: 401 })
|
||||
}
|
||||
|
||||
// Get user's verse bookmarks with verse and chapter information
|
||||
const bookmarks = await prisma.bookmark.findMany({
|
||||
where: {
|
||||
userId: user.id
|
||||
},
|
||||
include: {
|
||||
verse: {
|
||||
include: {
|
||||
chapter: {
|
||||
include: {
|
||||
book: {
|
||||
include: {
|
||||
version: true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
orderBy: {
|
||||
createdAt: 'desc'
|
||||
}
|
||||
})
|
||||
|
||||
return NextResponse.json({ bookmarks })
|
||||
|
||||
} catch (error) {
|
||||
console.error('Verse bookmark fetch error:', error)
|
||||
const url = new URL(request.url)
|
||||
const locale = url.searchParams.get('locale') || 'ro'
|
||||
const messages = getErrorMessages(locale)
|
||||
|
||||
return NextResponse.json({ error: messages.bookmarkError }, { status: 500 })
|
||||
}
|
||||
}
|
||||
|
||||
// POST - Create verse bookmark
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const url = new URL(request.url)
|
||||
const locale = url.searchParams.get('locale') || 'ro'
|
||||
const messages = getErrorMessages(locale)
|
||||
|
||||
// Get token from authorization header
|
||||
const authHeader = request.headers.get('authorization')
|
||||
const token = authHeader?.replace('Bearer ', '')
|
||||
|
||||
if (!token) {
|
||||
return NextResponse.json({ error: messages.unauthorized }, { status: 401 })
|
||||
}
|
||||
|
||||
// Verify token and get user
|
||||
const user = await getUserFromToken(token)
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: messages.unauthorized }, { status: 401 })
|
||||
}
|
||||
|
||||
// Parse request body
|
||||
const { verseId, note, color } = await request.json()
|
||||
|
||||
// Validate input
|
||||
if (!verseId) {
|
||||
return NextResponse.json({ error: messages.bookmarkRequired }, { status: 400 })
|
||||
}
|
||||
|
||||
// Create or update bookmark
|
||||
const bookmark = await prisma.bookmark.upsert({
|
||||
where: {
|
||||
userId_verseId: {
|
||||
userId: user.id,
|
||||
verseId: verseId
|
||||
}
|
||||
},
|
||||
update: {
|
||||
note: note || null,
|
||||
color: color || '#FFD700'
|
||||
},
|
||||
create: {
|
||||
userId: user.id,
|
||||
verseId: verseId,
|
||||
note: note || null,
|
||||
color: color || '#FFD700'
|
||||
},
|
||||
include: {
|
||||
verse: {
|
||||
include: {
|
||||
chapter: {
|
||||
include: {
|
||||
book: {
|
||||
include: {
|
||||
version: true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
return NextResponse.json({
|
||||
message: messages.bookmarkSaved,
|
||||
bookmark
|
||||
})
|
||||
|
||||
} catch (error) {
|
||||
console.error('Verse bookmark creation error:', error)
|
||||
const url = new URL(request.url)
|
||||
const locale = url.searchParams.get('locale') || 'ro'
|
||||
const messages = getErrorMessages(locale)
|
||||
|
||||
return NextResponse.json({ error: messages.bookmarkError }, { status: 500 })
|
||||
}
|
||||
}
|
||||
|
||||
// DELETE - Remove verse bookmark
|
||||
export async function DELETE(request: Request) {
|
||||
try {
|
||||
const url = new URL(request.url)
|
||||
const locale = url.searchParams.get('locale') || 'ro'
|
||||
const verseId = url.searchParams.get('verseId')
|
||||
const messages = getErrorMessages(locale)
|
||||
|
||||
// Get token from authorization header
|
||||
const authHeader = request.headers.get('authorization')
|
||||
const token = authHeader?.replace('Bearer ', '')
|
||||
|
||||
if (!token) {
|
||||
return NextResponse.json({ error: messages.unauthorized }, { status: 401 })
|
||||
}
|
||||
|
||||
// Verify token and get user
|
||||
const user = await getUserFromToken(token)
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: messages.unauthorized }, { status: 401 })
|
||||
}
|
||||
|
||||
// Validate input
|
||||
if (!verseId) {
|
||||
return NextResponse.json({ error: messages.bookmarkRequired }, { status: 400 })
|
||||
}
|
||||
|
||||
// Delete bookmark
|
||||
await prisma.bookmark.delete({
|
||||
where: {
|
||||
userId_verseId: {
|
||||
userId: user.id,
|
||||
verseId: verseId
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
return NextResponse.json({
|
||||
message: messages.bookmarkRemoved
|
||||
})
|
||||
|
||||
} catch (error) {
|
||||
console.error('Verse bookmark deletion error:', error)
|
||||
const url = new URL(request.url)
|
||||
const locale = url.searchParams.get('locale') || 'ro'
|
||||
const messages = getErrorMessages(locale)
|
||||
|
||||
return NextResponse.json({ error: messages.bookmarkError }, { status: 500 })
|
||||
}
|
||||
}
|
||||
@@ -82,6 +82,8 @@
|
||||
"verse": "Verse",
|
||||
"verses": "verses",
|
||||
"save": "Save",
|
||||
"saved": "Saved",
|
||||
"saving": "Saving...",
|
||||
"share": "Share",
|
||||
"previousChapter": "Previous chapter",
|
||||
"nextChapter": "Next chapter",
|
||||
|
||||
@@ -82,6 +82,8 @@
|
||||
"verse": "Versetul",
|
||||
"verses": "versete",
|
||||
"save": "Salvează",
|
||||
"saved": "Salvat",
|
||||
"saving": "Se salvează...",
|
||||
"share": "Partajează",
|
||||
"previousChapter": "Capitolul anterior",
|
||||
"nextChapter": "Capitolul următor",
|
||||
|
||||
@@ -21,6 +21,7 @@ model User {
|
||||
|
||||
sessions Session[]
|
||||
bookmarks Bookmark[]
|
||||
chapterBookmarks ChapterBookmark[]
|
||||
notes Note[]
|
||||
chatMessages ChatMessage[]
|
||||
prayerRequests PrayerRequest[]
|
||||
@@ -68,6 +69,7 @@ model BibleBook {
|
||||
orderNum Int
|
||||
bookKey String // For cross-version matching (e.g., "genesis", "exodus")
|
||||
chapters BibleChapter[]
|
||||
chapterBookmarks ChapterBookmark[]
|
||||
|
||||
version BibleVersion @relation(fields: [versionId], references: [id])
|
||||
|
||||
@@ -151,6 +153,21 @@ model Bookmark {
|
||||
@@index([userId])
|
||||
}
|
||||
|
||||
model ChapterBookmark {
|
||||
id String @id @default(uuid())
|
||||
userId String
|
||||
bookId String
|
||||
chapterNum Int
|
||||
note String?
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
book BibleBook @relation(fields: [bookId], references: [id])
|
||||
|
||||
@@unique([userId, bookId, chapterNum])
|
||||
@@index([userId])
|
||||
}
|
||||
|
||||
model Note {
|
||||
id String @id @default(uuid())
|
||||
userId String
|
||||
|
||||
Reference in New Issue
Block a user