import mongoose from "mongoose"; // Define Product record schema const ProductRecordSchema = new mongoose.Schema({ productid: { type: mongoose.Schema.Types.ObjectId, ref: "Product", required: true, }, SKU: { type: String, required: true, }, productName: { type: String, required: true, }, openingInventory: { type: Number, default: 0, set: (value) => { if (typeof value === "string") { // Convert to number and remove leading zeros return Number(value.replace(/^0+/, "")) || undefined; } return value; }, }, Stock: { type: Number, default: 0, }, monthstartstock: { type: Number, default: 0, }, liquidation: { type: Number, default: 0, }, monthlyorderquantity: { type: Number, default: 0, }, }); // Define main Stock schema const StockSchema = new mongoose.Schema( { userId: { type: mongoose.Schema.Types.ObjectId, refPath: "User", required: true, unique: true, }, products: [ProductRecordSchema], }, { timestamps: true, versionKey: false } ); // Static method to reset monthly fields StockSchema.statics.resetMonthlyFields = async function () { try { const stocks = await this.find(); for (const stock of stocks) { for (const product of stock.products) { product.liquidation = 0; product.monthstartstock = product.Stock; product.monthlyorderquantity = 0; } await stock.save(); } console.log("Monthly reset completed successfully!"); } catch (error) { console.error("Error during monthly reset:", error); } }; export const PDStock = mongoose.model("PDStock", StockSchema);