Refactor stock event schema for improved readability and consistency
All checks were successful
farmcontrol/farmcontrol-ws/pipeline/head This commit looks good

- Cleaned up the stock event schema by removing unnecessary line breaks and ensuring consistent formatting across the code.
- Enhanced readability of function parameters and return statements for better maintainability.
- Made minor adjustments to comments and structure to align with coding standards.
This commit is contained in:
Tom Butcher 2026-07-26 19:00:30 +01:00
parent 2b660ec61d
commit 766f4722ea

View File

@ -6,13 +6,13 @@ const { Schema } = mongoose;
const parentStockModelNames = { const parentStockModelNames = {
filamentStock: 'filamentStock', filamentStock: 'filamentStock',
partStock: 'partStock', partStock: 'partStock',
productStock: 'productStock', productStock: 'productStock'
}; };
const initialStockStates = { const initialStockStates = {
filamentStock: 'unconsumed', filamentStock: 'unconsumed',
partStock: 'new', partStock: 'new',
productStock: 'posted', productStock: 'posted'
}; };
const getStartingAmount = (parentType, parentStock) => { const getStartingAmount = (parentType, parentStock) => {
@ -23,7 +23,12 @@ const getStartingAmount = (parentType, parentStock) => {
return parentStock.startingQuantity ?? 0; return parentStock.startingQuantity ?? 0;
}; };
const buildParentState = (parentType, parentStock, currentAmount, startingAmount) => { const buildParentState = (
parentType,
parentStock,
currentAmount,
startingAmount
) => {
if (parentStock.state?.type === 'draft') { if (parentStock.state?.type === 'draft') {
return undefined; return undefined;
} }
@ -43,8 +48,6 @@ const buildParentState = (parentType, parentStock, currentAmount, startingAmount
const progress = currentAmount / startingAmount; const progress = currentAmount / startingAmount;
console.log('progress', progress);
if (currentAmount === startingAmount) { if (currentAmount === startingAmount) {
return { ...parentStock.state, type: fullState, progress: 1 }; return { ...parentStock.state, type: fullState, progress: 1 };
} }
@ -60,18 +63,20 @@ const getStockEventTotal = async (parentId, parentType) => {
if (!parentId) return null; if (!parentId) return null;
const objectId = const objectId =
parentId instanceof mongoose.Types.ObjectId ? parentId : new mongoose.Types.ObjectId(parentId); parentId instanceof mongoose.Types.ObjectId
? parentId
: new mongoose.Types.ObjectId(parentId);
const [result] = await mongoose const [result] = await mongoose
.model('stockEvent') .model('stockEvent')
.aggregate([ .aggregate([
{ $match: { parent: objectId, parentType } }, { $match: { parent: objectId, parentType } },
{ $group: { _id: null, total: { $sum: '$value' }, count: { $sum: 1 } } }, { $group: { _id: null, total: { $sum: '$value' }, count: { $sum: 1 } } }
]); ]);
return { return {
total: result?.total ?? 0, total: result?.total ?? 0,
count: result?.count ?? 0, count: result?.count ?? 0
}; };
}; };
@ -108,7 +113,8 @@ const HISTORY_RATE_LIMIT_MS = 3000;
const isWithinHistoryRateLimit = (lastEntry, timestamp = new Date()) => { const isWithinHistoryRateLimit = (lastEntry, timestamp = new Date()) => {
if (!lastEntry?.timestamp) return false; if (!lastEntry?.timestamp) return false;
const elapsed = new Date(timestamp).getTime() - new Date(lastEntry.timestamp).getTime(); const elapsed =
new Date(timestamp).getTime() - new Date(lastEntry.timestamp).getTime();
return elapsed < HISTORY_RATE_LIMIT_MS; return elapsed < HISTORY_RATE_LIMIT_MS;
}; };
@ -116,7 +122,9 @@ const getLastParentHistoryValue = (parentType, history = []) => {
const lastEntry = history.at(-1); const lastEntry = history.at(-1);
if (!lastEntry) return undefined; if (!lastEntry) return undefined;
return parentType === 'filamentStock' ? lastEntry.currentWeight : lastEntry.currentQuantity; return parentType === 'filamentStock'
? lastEntry.currentWeight
: lastEntry.currentQuantity;
}; };
const parentValuesEqual = (parentType, a, b) => { const parentValuesEqual = (parentType, a, b) => {
@ -147,7 +155,9 @@ const appendParentHistoryIfChanged = (
const history = parentStock.history || []; const history = parentStock.history || [];
const lastEntry = history.at(-1); const lastEntry = history.at(-1);
const currentValue = const currentValue =
parentType === 'filamentStock' ? updateData.currentWeight : updateData.currentQuantity; parentType === 'filamentStock'
? updateData.currentWeight
: updateData.currentQuantity;
const lastHistoryValue = getLastParentHistoryValue(parentType, history); const lastHistoryValue = getLastParentHistoryValue(parentType, history);
if (parentValuesEqual(parentType, currentValue, lastHistoryValue)) { if (parentValuesEqual(parentType, currentValue, lastHistoryValue)) {
@ -160,7 +170,10 @@ const appendParentHistoryIfChanged = (
return { return {
...updateData, ...updateData,
history: [...history, buildParentHistoryEntry(parentType, currentValue, timestamp)], history: [
...history,
buildParentHistoryEntry(parentType, currentValue, timestamp)
]
}; };
}; };
@ -174,7 +187,7 @@ const recalculateParentStock = async (parentType, parentId, user) => {
const parentStock = await getObject({ const parentStock = await getObject({
model: parentModel, model: parentModel,
id: parentId, id: parentId,
cached: true, cached: true
}); });
if (!parentStock || parentStock.error) return; if (!parentStock || parentStock.error) return;
@ -190,7 +203,7 @@ const recalculateParentStock = async (parentType, parentId, user) => {
buildParentUpdateData(parentType, parentStock, events) buildParentUpdateData(parentType, parentStock, events)
), ),
user, user,
recalculate: false, recalculate: false
}); });
}; };
@ -202,30 +215,30 @@ const stockEventSchema = new Schema(
parent: { parent: {
type: Schema.Types.ObjectId, type: Schema.Types.ObjectId,
refPath: 'parentType', refPath: 'parentType',
required: true, required: true
}, },
parentType: { parentType: {
type: String, type: String,
required: true, required: true,
enum: ['filamentStock', 'partStock', 'productStock'], // Add other models as needed enum: ['filamentStock', 'partStock', 'productStock'] // Add other models as needed
}, },
owner: { owner: {
type: Schema.Types.ObjectId, type: Schema.Types.ObjectId,
refPath: 'ownerType', refPath: 'ownerType',
required: true, required: true
}, },
ownerType: { ownerType: {
type: String, type: String,
required: true, required: true,
enum: ['user', 'subJob', 'stockAudit', 'stockTransfer'], enum: ['user', 'subJob', 'stockAudit', 'stockTransfer']
}, },
history: [ history: [
{ {
value: { type: Number, required: true }, value: { type: Number, required: true },
timestamp: { type: Date, default: Date.now }, timestamp: { type: Date, default: Date.now }
}, }
], ],
timestamp: { type: Date, default: Date.now }, timestamp: { type: Date, default: Date.now }
}, },
{ timestamps: true } { timestamps: true }
); );
@ -239,15 +252,18 @@ stockEventSchema.statics.recalculate = async function (stockEvent, user) {
const currentValue = stockEvent.value; const currentValue = stockEvent.value;
const timestamp = stockEvent.timestamp || new Date(); const timestamp = stockEvent.timestamp || new Date();
if (currentValue !== lastHistoryValue && !isWithinHistoryRateLimit(lastEntry, timestamp)) { if (
currentValue !== lastHistoryValue &&
!isWithinHistoryRateLimit(lastEntry, timestamp)
) {
await editObject({ await editObject({
model: this, model: this,
id: stockEvent._id, id: stockEvent._id,
updateData: { updateData: {
history: [...history, { value: currentValue, timestamp }], history: [...history, { value: currentValue, timestamp }]
}, },
user, user,
recalculate: false, recalculate: false
}); });
} }