const mongoose = require('../db/connect') const { Schema } = mongoose // Define sub-schemas const RequestSchema = new Schema({ requestContentType: { type: String, enum: ['application/json', 'application/x-www-form-urlencoded', 'multipart/form-data', 'empty', 'none'], default: 'application/json' }, requestEncoding: { type: String, enum: ['Json', 'UrlEncoded', 'empty'], default: 'Json' }, requestType: { type: String, enum: ['Post', 'Get', 'empty'], default: 'Post' }, responseType: { type: String, enum: ['Json', 'XML', 'empty'], default: 'Json' }, url: { type: String, required: true } }) const CallsSchema = new Schema({ inboundAnsweredCall: Object, inboundMissedCall: Object, outboundAnsweredCall: Object, outboundUnansweredCall: Object }) const CallJournalingSchema = new Schema({ request: RequestSchema, calls: [CallsSchema], response: Object }) // Define main schema const CRMRestSchema = new Schema({ authorizationEndpoint: { request: RequestSchema }, tokenEndpoint: { request: RequestSchema, body: Object, response: Object }, createContactRecord: { request: RequestSchema, body: Object, response: Object }, lookupContactByPhone: { request: RequestSchema, response: Object }, callJournaling: CallJournalingSchema }) const AuthenticationSchema = new Schema({ type: { type: String, enum: ['basic', 'bearer', 'oauth2'], default: 'bearer' }, userName: String, passWord: String, token: String, crmClientId: String, crmClientSecret: String, crmScopes: String, crmOAuthRefreshToken: String, crmOAuthToken: String, crmPhoneTest: String }) const crmContactSchema = new Schema({ crmBaseURL: { type: String }, companyId: { type: String, required: true }, company: { type: mongoose.Schema.ObjectId, ref: 'company', required: true }, testing: { type: Boolean, default: true }, enabled: { type: Boolean, default: true }, crm: { authentication: AuthenticationSchema, crmRest: [CRMRestSchema] } }, { timestamps: true }, ) crmContactSchema.virtual('crm_contacts', { ref: 'CRM_Contact', localField: '_id', foreignField: 'crm', justOne: false, // match: { rating: 4 } }) crmContactSchema.pre('deleteOne', { document: true, query: false }, async function () { await this.model('CRM_Contact').deleteMany({ crm: this._id }) } ) const CRM = mongoose.model('CRM', crmContactSchema) module.exports = CRM