53 lines
1.7 KiB
JavaScript
53 lines
1.7 KiB
JavaScript
import mongoose from 'mongoose';
|
|
import { generateId } from '../../utils.js';
|
|
const { Schema } = mongoose;
|
|
|
|
// Define the main product schema
|
|
const productSchema = new Schema(
|
|
{
|
|
_reference: { type: String, default: () => generateId()() },
|
|
name: { type: String, required: true },
|
|
tags: [{ type: String }],
|
|
version: { type: String },
|
|
vendor: { type: Schema.Types.ObjectId, ref: 'vendor', required: true },
|
|
cost: { type: Number, required: false },
|
|
price: { type: Number, required: false },
|
|
priceMode: { type: String, default: 'margin' },
|
|
margin: { type: Number, required: false },
|
|
amount: { type: Number, required: false },
|
|
costTaxRate: { type: Schema.Types.ObjectId, ref: 'taxRate', required: false },
|
|
priceTaxRate: { type: Schema.Types.ObjectId, ref: 'taxRate', required: false },
|
|
costWithTax: { type: Number, required: false },
|
|
priceWithTax: { type: Number, required: false },
|
|
},
|
|
{ timestamps: true }
|
|
);
|
|
// Add virtual id getter
|
|
productSchema.virtual('id').get(function () {
|
|
return this._id;
|
|
});
|
|
|
|
// Configure JSON serialization to include virtuals
|
|
productSchema.set('toJSON', { virtuals: true });
|
|
|
|
productSchema.statics.recalculate = async function (product, user) {
|
|
const orderItemModel = mongoose.model('orderItem');
|
|
const itemId = product._id;
|
|
const draftOrderItems = await orderItemModel
|
|
.find({
|
|
'state.type': 'draft',
|
|
itemType: 'product',
|
|
item: itemId,
|
|
})
|
|
.populate('order')
|
|
.lean();
|
|
|
|
for (const orderItem of draftOrderItems) {
|
|
await orderItemModel.recalculate(orderItem, user);
|
|
}
|
|
|
|
};
|
|
|
|
// Create and export the model
|
|
export const productModel = mongoose.model('product', productSchema);
|