Tom Butcher 6393ed5e3e
All checks were successful
farmcontrol/farmcontrol-api/pipeline/head This commit looks good
Add rollup configurations and statistics methods to finance and inventory schemas
This commit enhances the `invoice`, `taxrecord`, `orderitem`, `purchaseorder`, `shipment`, and `salesorder` schemas by introducing new rollup configurations for various states and values. It adds methods for aggregating statistics and historical data using `aggregateRollups` and `aggregateRollupsHistory`, improving data analysis capabilities across financial and inventory records. The new rollups include counts and sums for different transaction types and states, facilitating better reporting and insights into the application's financial and inventory management.
2026-08-30 14:56:48 +01:00

70 lines
1.9 KiB
JavaScript

import mongoose from 'mongoose';
import { generateId } from '../../utils.js';
import { aggregateRollups, aggregateRollupsHistory } from '../../database.js';
const { Schema } = mongoose;
const taxRecordSchema = new Schema(
{
_reference: { type: String, default: () => generateId()() },
taxRate: { type: Schema.Types.ObjectId, ref: 'taxRate', required: true },
transactionType: {
type: String,
required: true,
enum: ['purchaseOrder', 'salesOrder', 'other'],
},
transaction: { type: Schema.Types.ObjectId, refPath: 'transactionType', required: true },
amount: { type: Number, required: true },
taxAmount: { type: Number, required: true },
transactionDate: { required: true, type: Date, default: Date.now },
},
{ timestamps: true }
);
taxRecordSchema.index({ transactionType: 'text' });
const rollupConfigs = [
{
name: 'total',
filter: {},
rollups: [
{ name: 'count', property: 'amount', operation: 'count' },
{ name: 'amount', property: 'amount', operation: 'sum' },
{ name: 'taxAmount', property: 'taxAmount', operation: 'sum' },
],
},
{
name: 'salesOrder',
filter: { transactionType: 'salesOrder' },
rollups: [{ name: 'taxAmount', property: 'taxAmount', operation: 'sum' }],
},
{
name: 'purchaseOrder',
filter: { transactionType: 'purchaseOrder' },
rollups: [{ name: 'taxAmount', property: 'taxAmount', operation: 'sum' }],
},
];
taxRecordSchema.statics.stats = async function () {
return aggregateRollups({
model: this,
rollupConfigs,
});
};
taxRecordSchema.statics.history = async function (from, to) {
return aggregateRollupsHistory({
model: this,
startDate: from,
endDate: to,
rollupConfigs,
});
};
taxRecordSchema.virtual('id').get(function () {
return this._id;
});
taxRecordSchema.set('toJSON', { virtuals: true });
export const taxRecordModel = mongoose.model('taxRecord', taxRecordSchema);