import mongoose from "mongoose" ; import { ReportInterface } from "../../types/report" ; import uniqid from "uniqid" ; import { queriesSchema } from "./QueryModel" ; import { getExperimentsByOrganization } from "../services/experiments" ; const reportSchema = new mongoose . Schema ( { id : String , dateCreated : Date , dateUpdated : Date , organization : String , experimentId : String , userId : String , title : String , description : String , runStarted : Date , error : String , queries : queriesSchema , status : String , type : String , args : { } , results : { } , } ) ; type ReportDocument = mongoose . Document & ReportInterface ; const ReportModel = mongoose . model < ReportDocument > ( "Report" , reportSchema ) ; export async function createReport ( organization , initialValue ) { const report = await ReportModel . create ( { status : "private" , ... initialValue , organization , id : uniqid ( "rep_" ) , dateCreated : new Date ( ) , dateUpdated : new Date ( ) , } ) ; return report . toJSON ( ) ; } export async function getReportById ( organization , id ) { const report = await ReportModel . findOne ( { organization , id , } ) ; return report ? report . toJSON ( ) : null ; } export async function getReportsByOrg ( organization , project ) { let reports = await ReportModel . find ( { organization } ) ; if ( reports && project ) { const allExperiments = await getExperimentsByOrganization ( organization , project ) ; const expIds = new Set ( allExperiments . map ( ( e ) => e . id ) ) ; reports = reports . filter ( ( r ) => expIds . has ( r . experimentId ) ) ; } return reports ; } export async function getReportsByExperimentId ( organization , experimentId ) { return ReportModel . find ( { organization , experimentId } ) ; } export async function updateReport ( organization , id , updates ) { await ReportModel . updateOne ( { organization , id , } , { $set : { ... updates , dateUpdated : new Date ( ) , } , } ) ; }