Some checks failed
farmcontrol/farmcontrol-api/pipeline/head There was a failure building this commit
44 lines
1.5 KiB
JavaScript
44 lines
1.5 KiB
JavaScript
import mongoose from 'mongoose';
|
|
import { generateId } from '../../utils.js';
|
|
const { Schema } = mongoose;
|
|
|
|
// Define the main part schema - cost/price and tax; override at PartSku
|
|
const partSchema = new Schema(
|
|
{
|
|
_reference: { type: String, default: () => generateId()() },
|
|
name: { type: String, required: true },
|
|
file: { type: mongoose.SchemaTypes.ObjectId, ref: 'file', required: false },
|
|
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 }
|
|
);
|
|
|
|
partSchema.index({ name: 'text' });
|
|
|
|
// Add virtual id getter
|
|
partSchema.virtual('id').get(function () {
|
|
return this._id;
|
|
});
|
|
|
|
// Configure JSON serialization to include virtuals
|
|
partSchema.set('toJSON', { virtuals: true });
|
|
|
|
partSchema.statics.recalculate = async function (part, user) {
|
|
const partSkuModel = mongoose.model('partSku');
|
|
const skus = await partSkuModel.find({ part: part._id }).select('_id').lean();
|
|
for (const sku of skus) {
|
|
await partSkuModel.recalculate(sku, user);
|
|
}
|
|
};
|
|
|
|
// Create and export the model
|
|
export const partModel = mongoose.model('part', partSchema);
|