/** * Prisma 辅助函数库 * 提供常用的数据库操作封装 */ import { prisma } from '@/lib/prisma' /** * 读取系统配置 */ export async function getPrismaConfig(key: string): Promise { try { const config = await prisma.system_config.findUnique({ where: { config_key: key } }) return config?.config_value } catch (e) { console.warn(`[Config] 读取配置 ${key} 失败:`, e) return null } } /** * 更新系统配置 */ export async function setPrismaConfig(key: string, value: any, description?: string): Promise { await prisma.system_config.upsert({ where: { config_key: key }, update: { config_value: value, description: description || null, updated_at: new Date() }, create: { config_key: key, config_value: value, description: description || null } }) } /** * 查询用户(通过 ID 或 openId) */ export async function findUserByIdOrOpenId(userId?: string, openId?: string) { if (!userId && !openId) return null return await prisma.users.findFirst({ where: userId ? { id: userId } : { open_id: openId } }) } /** * 批量查询用户 */ export async function findUsersByIds(userIds: string[]) { return await prisma.users.findMany({ where: { id: { in: userIds } } }) } /** * 记录用户追踪 */ export async function trackUserAction( userId: string, action: string, chapterId?: string, target?: string, extraData?: any ) { try { await prisma.user_tracks.create({ data: { id: `track_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`, user_id: userId, action, chapter_id: chapterId || null, target: target || null, extra_data: extraData || null } }) } catch (e) { console.error('[Track] 记录失败:', e) } } /** * 检查用户是否购买章节 */ export async function hasUserPurchasedChapter(userId: string, chapterId: string): Promise { const user = await prisma.users.findUnique({ where: { id: userId }, select: { has_full_book: true, purchased_sections: true } }) if (!user) return false if (user.has_full_book) return true const purchasedSections = user.purchased_sections as any if (Array.isArray(purchasedSections)) { return purchasedSections.includes(chapterId) } return false } /** * 获取用户购买的章节列表 */ export async function getUserPurchasedChapters(userId: string): Promise { const user = await prisma.users.findUnique({ where: { id: userId }, select: { purchased_sections: true } }) const sections = user?.purchased_sections as any return Array.isArray(sections) ? sections : [] } /** * 添加用户购买的章节 */ export async function addUserPurchasedChapter(userId: string, chapterId: string): Promise { const user = await prisma.users.findUnique({ where: { id: userId }, select: { purchased_sections: true } }) const sections = user?.purchased_sections as any const purchased = Array.isArray(sections) ? sections : [] if (!purchased.includes(chapterId)) { purchased.push(chapterId) await prisma.users.update({ where: { id: userId }, data: { purchased_sections: purchased } }) } }