feat: Implement automatic sermon archiving based on dates

Add intelligent auto-archiving system that automatically moves sermons to the "Previous Sermons" list when they are 1 day past their most recent date.

Features:
- Auto-archive logic that checks both primary and additional sermon dates
- Finds the most recent date across all dates for a sermon
- Archives sermon 1 day after the most recent date has passed
- Manual trigger via "Run Auto-Archive Now" button on admin page
- Automatic daily execution via scheduled cleanup task
- Clear admin UI with explanatory text and status messages
- Manual archive/unarchive functionality preserved

Implementation:
- Added getMostRecentSermonDate() helper to find latest date from primary and additional dates
- Added autoArchiveOldSermons() function to database utils
- Created /api/sermons/auto-archive endpoint for manual triggering
- Integrated into daily cleanup plugin schedule
- Updated admin UI with auto-archive button and status indicators
- Added unarchiveSermon() function for completeness

The system runs automatically every 24 hours and can be manually triggered by admins. Sermons are moved to the previous sermons dropdown on the home page exactly 1 day after their final presentation date, ensuring the main page always shows current and upcoming content while preserving access to past sermons.

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

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
2025-11-07 09:53:17 -05:00
parent 3a50cbebdd
commit 0ff37e8999
4 changed files with 173 additions and 13 deletions

View File

@@ -0,0 +1,41 @@
import { getSessionUsername } from '~/server/utils/auth'
import { autoArchiveOldSermons, getUserByUsername } from '~/server/utils/database'
export default defineEventHandler(async (event) => {
// Check authentication
const username = await getSessionUsername(event)
if (!username) {
throw createError({
statusCode: 401,
message: 'Unauthorized'
})
}
// Check admin role
const user = getUserByUsername(username)
if (!user || user.is_admin !== 1) {
throw createError({
statusCode: 403,
message: 'Forbidden - Admin access required'
})
}
try {
const result = autoArchiveOldSermons()
return {
success: true,
message: result.archivedCount > 0
? `Successfully auto-archived ${result.archivedCount} sermon(s)`
: 'No sermons needed to be archived',
archivedCount: result.archivedCount
}
} catch (error: any) {
throw createError({
statusCode: 500,
message: error.message || 'Failed to auto-archive sermons'
})
}
})

View File

@@ -1,4 +1,4 @@
import { getSetting, deleteOldSermons, deleteExpiredSessions, getDatabase } from '../utils/database'
import { getSetting, deleteOldSermons, deleteExpiredSessions, autoArchiveOldSermons, getDatabase } from '../utils/database'
// Map retention policy to days
const retentionDaysMap: Record<string, number> = {
@@ -12,6 +12,20 @@ const retentionDaysMap: Record<string, number> = {
'10_years': 3650
}
async function runSermonAutoArchive() {
try {
const result = autoArchiveOldSermons()
if (result.archivedCount > 0) {
console.log(`[Sermon Auto-Archive] Archived ${result.archivedCount} sermon(s) that passed their most recent date`)
} else {
console.log(`[Sermon Auto-Archive] No sermons needed archiving`)
}
} catch (error) {
console.error('[Sermon Auto-Archive] Error running auto-archive:', error)
}
}
async function runSermonCleanup() {
try {
// Get the retention policy setting
@@ -75,6 +89,7 @@ async function runPasswordResetCleanup() {
async function runAllCleanupTasks() {
console.log('[Cleanup] Starting scheduled cleanup tasks')
await runSermonAutoArchive()
await runSermonCleanup()
await runSessionCleanup()
await runRateLimitCleanup()

View File

@@ -372,6 +372,62 @@ export function archiveSermon(id: number) {
return db.prepare('UPDATE sermons SET archived = 1 WHERE id = ?').run(id)
}
export function unarchiveSermon(id: number) {
const db = getDatabase()
return db.prepare('UPDATE sermons SET archived = 0 WHERE id = ?').run(id)
}
// Get the most recent date from a sermon (checking both primary date and additional dates)
function getMostRecentSermonDate(sermon: any): Date {
const dates: string[] = [sermon.date]
// Add additional dates if they exist
if (sermon.dates) {
try {
const additionalDates = JSON.parse(sermon.dates)
dates.push(...additionalDates)
} catch {
// If parsing fails, just use primary date
}
}
// Convert all dates to Date objects and find the most recent
const dateTimes = dates.map(dateStr => {
const date = new Date(dateStr + 'T00:00:00')
return date.getTime()
})
return new Date(Math.max(...dateTimes))
}
export function autoArchiveOldSermons(): { archivedCount: number } {
const db = getDatabase()
// Get all non-archived sermons
const sermons = db.prepare('SELECT * FROM sermons WHERE archived = 0').all() as any[]
const now = new Date()
now.setHours(0, 0, 0, 0) // Start of today
let archivedCount = 0
for (const sermon of sermons) {
const mostRecentDate = getMostRecentSermonDate(sermon)
// Calculate days difference
const oneDayAfterSermon = new Date(mostRecentDate)
oneDayAfterSermon.setDate(oneDayAfterSermon.getDate() + 1)
// If it's been at least 1 day since the most recent sermon date, archive it
if (now >= oneDayAfterSermon) {
archiveSermon(sermon.id!)
archivedCount++
}
}
return { archivedCount }
}
export function getSermonBySlug(slug: string) {
const db = getDatabase()
return db.prepare('SELECT * FROM sermons WHERE slug = ?').get(slug) as Sermon | undefined