farmcontrol-api/src/database/schemas/inventory/filamentstock.schema.js

66 lines
1.7 KiB
JavaScript

import mongoose from 'mongoose';
import { generateId } from '../../utils.js';
const { Schema } = mongoose;
import { aggregateRollups, aggregateRollupsHistory } from '../../database.js';
// Define the main filamentStock schema
const filamentStockSchema = new Schema(
{
_reference: { type: String, default: () => generateId()() },
state: {
type: { type: String, required: true },
progress: { type: Number, required: false },
},
startingWeight: {
net: { type: Number, required: true },
gross: { type: Number, required: true },
},
currentWeight: {
net: { type: Number, required: true },
gross: { type: Number, required: true },
},
filament: { type: mongoose.Schema.Types.ObjectId, ref: 'filament', required: true },
},
{ timestamps: true }
);
const rollupConfigs = [
{
name: 'totalCurrentWeight',
filter: {},
rollups: [{ name: 'totalCurrentWeight', property: 'currentWeight.net', operation: 'sum' }],
},
];
filamentStockSchema.statics.stats = async function () {
const results = await aggregateRollups({
model: this,
rollupConfigs: rollupConfigs,
});
return results;
};
filamentStockSchema.statics.history = async function (from, to) {
const results = await aggregateRollupsHistory({
model: this,
startDate: from,
endDate: to,
rollupConfigs: rollupConfigs,
});
// Return time-series data array
return results;
};
// Add virtual id getter
filamentStockSchema.virtual('id').get(function () {
return this._id;
});
// Configure JSON serialization to include virtuals
filamentStockSchema.set('toJSON', { virtuals: true });
// Create and export the model
export const filamentStockModel = mongoose.model('filamentStock', filamentStockSchema);