import { Collection, ObjectId, WithId } from "mongodb"; import { getDb } from "../index"; import type { ContextNote, ContextNoteEntry } from "./contextNotes.types"; export const getContextNotesCollection = (): Collection => { return getDb().collection("contextNotes"); }; /** Returns all context note documents matching a clientId and product. */ export const getContextNotes = ( clientId: string, product: string, ): Promise[]> => { return getContextNotesCollection().find({ clientId, product }).toArray(); }; /** Returns all currently active note entries across matching documents */ export const getActiveContextNotes = async ( clientId: string, product: string, ): Promise => { const docs = await getContextNotes(clientId, product); const now = new Date(); return docs.flatMap((doc) => doc.notes.filter( (note) => note.activeFrom <= now && (note.expiresAt === null || note.expiresAt > now), ), ); }; /** Creates a new context note document. */ export const createContextNote = ( data: Omit, ): Promise => { return getContextNotesCollection() .insertOne({ ...data, _id: new ObjectId() } as ContextNote) .then((r) => r.insertedId); }; /** Replaces the full notes array on a context note document. */ export const setContextNoteEntries = async ( id: ObjectId, clientId: string, notes: ContextNoteEntry[], ): Promise => { const result = await getContextNotesCollection().updateOne( { _id: id, clientId }, { $set: { notes } }, ); return result.matchedCount > 0; }; /** Updates the configuration fields (systemPrompt, product) on a context note document. */ export const setContextNoteConfig = async ( id: ObjectId, clientId: string, config: { systemPrompt?: string; product?: string }, ): Promise => { const fields: Partial = {}; if (config.systemPrompt !== undefined) fields.systemPrompt = config.systemPrompt; if (config.product !== undefined) fields.product = config.product; if (!Object.keys(fields).length) return false; const result = await getContextNotesCollection().updateOne( { _id: id, clientId }, { $set: fields }, ); return result.matchedCount > 0; }; /** Removes a single note entry from a document by its _id. */ export const deleteContextNoteEntry = async ( id: ObjectId, clientId: string, noteId: ObjectId, ): Promise => { const result = await getContextNotesCollection().updateOne( { _id: id, clientId }, { $pull: { notes: { _id: noteId } as any } }, ); return result.modifiedCount > 0; };