import { Collection, ObjectId as MongoObjectId } from "mongodb"; import { getDb, ObjectId } from "../index"; import { KNOWLEDGE_DOCUMENTS_COLLECTION, KNOWLEDGE_DOCUMENT_READY_PROJECTION, KNOWLEDGE_DOCUMENT_STATUSES, } from "./knowledgeDocuments.constants"; import type { CreateKnowledgeDocumentInput, KnowledgeDocument, KnowledgeDocumentDoc, KnowledgeDocumentReadyProjection, UpdateKnowledgeDocumentInput, } from "./knowledgeDocuments.types"; export const getKnowledgeDocumentsCollection = (): Collection => { return getDb().collection( KNOWLEDGE_DOCUMENTS_COLLECTION, ); }; export const createKnowledgeDocument = async ( input: CreateKnowledgeDocumentInput, ): Promise => { const now = new Date(); const { status, progressPercent, _id, ...rest } = input; const { insertedId } = await getKnowledgeDocumentsCollection().insertOne({ ...(_id ? { _id } : {}), ...rest, status: status ?? KNOWLEDGE_DOCUMENT_STATUSES.UPLOADING, progressPercent: progressPercent ?? 0, createdAt: now, updatedAt: now, }); return insertedId; }; export const getKnowledgeDocumentById = async ( id: string, ): Promise => { return getKnowledgeDocumentsCollection().findOne({ _id: new ObjectId(id) }); }; export const listKnowledgeDocumentsByClientId = async ( clientId: string, ): Promise => { return getKnowledgeDocumentsCollection() .find({ clientId }) .sort({ createdAt: -1 }) .toArray(); }; export const listReadyKnowledgeDocumentIdsByClientId = async ( clientId: string, ): Promise => { const docs = await getKnowledgeDocumentsCollection() .find( { clientId, status: KNOWLEDGE_DOCUMENT_STATUSES.READY }, { projection: { _id: 1 } }, ) .sort({ createdAt: -1 }) .toArray(); return docs.map((doc) => doc._id.toString()); }; export const listReadyKnowledgeDocumentsByClientId = async ( clientId: string, ): Promise => { return getKnowledgeDocumentsCollection() .find( { clientId, status: KNOWLEDGE_DOCUMENT_STATUSES.READY }, { projection: KNOWLEDGE_DOCUMENT_READY_PROJECTION }, ) .sort({ createdAt: -1 }) .toArray() as Promise; }; export const updateKnowledgeDocument = async ( id: string, updates: UpdateKnowledgeDocumentInput, ): Promise => { return getKnowledgeDocumentsCollection().findOneAndUpdate( { _id: new ObjectId(id) }, { $set: { ...updates, updatedAt: new Date() } }, { returnDocument: "after" }, ); }; export const deleteKnowledgeDocument = async (id: string): Promise => { const result = await getKnowledgeDocumentsCollection().deleteOne({ _id: new ObjectId(id), }); return result.deletedCount === 1; };