import mongooseUniqueValidator from "mongoose-unique-validator"; import {AppMaster} from "@onebro/appmaster"; import { DeepPartial, IModelCreator, IStatus, IQuery, mapSelectedData, getSchemaRefs, ObjectId} from "@onebro/oba-common"; import { FinavigatorLeadConfig, FinavigatorLeadModel, FinavigatorLead, FinavigatorLeadJson, FinavigatorLeadStatuses as statuses, FinavigatorLeadStatus,} from "../types"; import {finavigatorLeadSchema as lead} from "../schemas"; const refs = getSchemaRefs(lead); export const finavigatorLeadModels:IModelCreator = async m => { lead.plugin(mongooseUniqueValidator); lead.virtual("lastStatus").get(function(){return this.status?(this.status[this.status.length - 1] as any).json(statuses):null;}); lead.virtual("lastStatus").set(function(o:IStatus){this.status = [...this.status,o];}); lead.virtual("statusStr").get(function(){return this.lastStatus?this.lastStatus.name + " @ " + this.lastStatus.time:"";}); lead.statics._populate = async function(o?:FinavigatorLead){ await o.populate(refs).execPopulate(); return o;}; lead.statics._find = async function(o:Partial|string){ if(!o) return m.e.badinfo(); const p = typeof o == "string"? await FinavigatorLead.findById(o): await FinavigatorLead.findOne(FinavigatorLead.translateAliases(o)); if(!p) throw m.e.doesNotExist("lead"); return p;}; lead.statics._create = async function(o:FinavigatorLeadConfig){return new FinavigatorLead({ ...o, });}; lead.statics._update = async function(o:FinavigatorLead,p:DeepPartial){ await o.set(p).save(); return await FinavigatorLead._populate(o);}; lead.statics._remove = async function(o:FinavigatorLead){return await o.remove().then(() => ({removed:o._id}));}; lead.statics._query = async function(o:IQuery){ const {query,populate,limit,skip,sort,select} = o; const results:FinavigatorLead[] = await this.find(this.translateAliases(query)) .populate(populate) //.where(where) .limit(limit) .skip(skip) .sort(sort) .exec(); const leads = mapSelectedData(select,results); return {leads};}; lead.statics._lookup = async function({path,query}:{path:string;query:any}){ const pipeline:any[] = []; return FinavigatorLead.aggregate(pipeline) .exec() .then((R:Partial<{[k in keyof (FinavigatorLead & FinavigatorLeadJson)]:any}>[]) => { return {leads:R.map(o => { if(o.status) o.status = { name:statuses[o.status.a0 as FinavigatorLeadStatus], time:o.status.a1, until:o.status.a2, info:o.status.a3}; delete o._id; return o;})}; });}; lead.methods.json = function(){ const {id,created,updated,lastStatus:status,statusStr,method,campaign,contact} = this as FinavigatorLead; const json:FinavigatorLeadJson = {id,created,updated,status,statusStr,method,campaign,contact}; return json;}; const FinavigatorLead = m.db.model("onebrother","FinavigatorLead",lead); await FinavigatorLead.init(); return {FinavigatorLead}; };