import mongoose from 'mongoose'; import { generateId } from '../../utils.js'; import { aggregateRollups, aggregateRollupsHistory } from '../../database.js'; const addressSchema = new mongoose.Schema({ building: { required: false, type: String }, addressLine1: { required: false, type: String }, addressLine2: { required: false, type: String }, city: { required: false, type: String }, state: { required: false, type: String }, postcode: { required: false, type: String }, country: { required: false, type: String }, }); const clientSchema = new mongoose.Schema( { _reference: { type: String, default: () => generateId()() }, name: { required: true, type: String }, marketplace: { type: mongoose.Schema.Types.ObjectId, ref: 'marketplace', required: false }, externalReference: { type: String, required: false }, email: { required: false, type: String }, phone: { required: false, type: String }, country: { required: false, type: String }, active: { required: true, type: Boolean, default: true }, address: { required: false, type: addressSchema }, tags: [{ required: false, type: String }], }, { timestamps: true } ); clientSchema.index({ name: 'text', email: 'text', phone: 'text', country: 'text', tags: 'text' }); clientSchema.index({ marketplace: 1, externalReference: 1 }, { unique: true, sparse: true }); clientSchema.virtual('id').get(function () { return this._id; }); clientSchema.set('toJSON', { virtuals: true }); const rollupConfigs = [ { name: 'active', filter: { active: true }, rollups: [{ name: 'active', property: 'active', operation: 'count' }], }, { name: 'inactive', filter: { active: false }, rollups: [{ name: 'inactive', property: 'active', operation: 'count' }], }, ]; clientSchema.statics.stats = async function () { const results = await aggregateRollups({ model: this, rollupConfigs: rollupConfigs, }); return results; }; clientSchema.statics.history = async function (from, to) { const results = await aggregateRollupsHistory({ model: this, startDate: from, endDate: to, rollupConfigs: rollupConfigs, }); return results; }; export const clientModel = mongoose.model('client', clientSchema);