import { db, type ActivityLog } from "./db" import { v4 as uuidv4 } from "uuid" /** * 记录活动日志 */ export async function logActivity( action: ActivityLog["action"], entityType: ActivityLog["entityType"], entityId?: string, entityName?: string, changes?: any ): Promise { try { const log: ActivityLog = { id: uuidv4(), action, entityType, entityId, entityName, changes, timestamp: new Date().toISOString(), userId: "local-user", // 本地版本暂时使用固定用户ID userName: "本地用户", } await db.activityLogs.add(log) } catch (error) { console.error("记录活动日志失败:", error) } } /** * 获取活动日志列表 */ export async function getActivityLogs(limit: number = 50): Promise { try { return await db.activityLogs .orderBy("timestamp") .reverse() .limit(limit) .toArray() } catch (error) { console.error("获取活动日志失败:", error) return [] } } /** * 获取特定成员的活动日志 */ export async function getMemberActivityLogs(memberId: string): Promise { try { return await db.activityLogs .where("entityId") .equals(memberId) .reverse() .sortBy("timestamp") } catch (error) { console.error("获取成员活动日志失败:", error) return [] } } /** * 清除旧日志(保留最近N天) */ export async function cleanOldLogs(daysToKeep: number = 90): Promise { try { const cutoffDate = new Date() cutoffDate.setDate(cutoffDate.getDate() - daysToKeep) const cutoffTimestamp = cutoffDate.toISOString() const oldLogs = await db.activityLogs .where("timestamp") .below(cutoffTimestamp) .toArray() await db.activityLogs .where("timestamp") .below(cutoffTimestamp) .delete() return oldLogs.length } catch (error) { console.error("清除旧日志失败:", error) return 0 } } /** * 获取活动统计 */ export async function getActivityStats(): Promise<{ total: number byAction: Record byEntityType: Record recentCount: number }> { try { const allLogs = await db.activityLogs.toArray() const oneDayAgo = new Date() oneDayAgo.setDate(oneDayAgo.getDate() - 1) const byAction: Record = {} const byEntityType: Record = {} let recentCount = 0 allLogs.forEach((log) => { byAction[log.action] = (byAction[log.action] || 0) + 1 byEntityType[log.entityType] = (byEntityType[log.entityType] || 0) + 1 if (new Date(log.timestamp) > oneDayAgo) { recentCount++ } }) return { total: allLogs.length, byAction, byEntityType, recentCount, } } catch (error) { console.error("获取活动统计失败:", error) return { total: 0, byAction: {}, byEntityType: {}, recentCount: 0, } } }