Files

90 lines
2.2 KiB
TypeScript
Raw Permalink Normal View History

2026-06-16 09:43:48 +02:00
import { ObjectId } from "mongodb";
import { getDb } from "@/lib/db";
export type AiAnalysisTargetType = "running" | "strength" | "dashboard";
export type AiAnalysisInput = {
2026-06-18 11:02:31 +02:00
userId: string;
2026-06-16 09:43:48 +02:00
targetType: AiAnalysisTargetType;
targetId: ObjectId;
summary: string;
tips: string[];
model: string;
};
export type AiAnalysis = AiAnalysisInput & {
_id: ObjectId;
createdAt: Date;
};
2026-06-16 11:51:10 +02:00
export type SerializedAiAnalysis = {
_id: string;
targetType: AiAnalysisTargetType;
targetId: string;
summary: string;
tips: string[];
model: string;
createdAt: string;
};
export function serializeAnalysis(analysis: AiAnalysis): SerializedAiAnalysis {
return {
_id: analysis._id.toString(),
targetType: analysis.targetType,
targetId: analysis.targetId.toString(),
summary: analysis.summary,
tips: analysis.tips,
model: analysis.model,
createdAt: analysis.createdAt.toISOString(),
};
}
2026-06-16 09:43:48 +02:00
const COLLECTION = "ai_analyses";
2026-06-18 11:02:31 +02:00
const DASHBOARD_TARGET_ID = new ObjectId("000000000000000000000001");
2026-06-16 09:43:48 +02:00
async function getCollection() {
const db = await getDb();
return db.collection<AiAnalysis>(COLLECTION);
}
export async function saveAiAnalysis(input: AiAnalysisInput): Promise<AiAnalysis> {
const collection = await getCollection();
const doc = { ...input, _id: new ObjectId(), createdAt: new Date() };
await collection.insertOne(doc);
return doc;
}
export async function getLatestAnalysisForTarget(
2026-06-18 11:02:31 +02:00
userId: string,
2026-06-16 09:43:48 +02:00
targetType: AiAnalysisTargetType,
targetId: ObjectId
): Promise<AiAnalysis | null> {
const collection = await getCollection();
2026-06-18 11:02:31 +02:00
return collection.findOne({ userId, targetType, targetId }, { sort: { createdAt: -1 } });
2026-06-16 09:43:48 +02:00
}
2026-06-18 11:02:31 +02:00
export async function getDashboardAnalysis(userId: string): Promise<AiAnalysis | null> {
2026-06-16 09:43:48 +02:00
const collection = await getCollection();
return collection.findOne(
2026-06-18 11:02:31 +02:00
{ userId, targetType: "dashboard", targetId: DASHBOARD_TARGET_ID },
2026-06-16 09:43:48 +02:00
{ sort: { createdAt: -1 } }
);
}
export async function saveDashboardAnalysis(
2026-06-18 11:02:31 +02:00
userId: string,
2026-06-16 09:43:48 +02:00
summary: string,
tips: string[],
model: string
): Promise<AiAnalysis> {
2026-06-18 11:02:31 +02:00
return saveAiAnalysis({
userId,
targetType: "dashboard",
targetId: DASHBOARD_TARGET_ID,
summary,
tips,
model,
});
2026-06-16 09:43:48 +02:00
}