import mongoose from "mongoose"; import crypto from 'crypto'; // 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, }, Sale: { type: Number, required: true, }, Inventory: { type: Number, required: true, }, }); // Define main Inventory schema const InventorySchema = new mongoose.Schema( { uniqueId: { type: String, unique: true, }, userId: { type: mongoose.Schema.Types.ObjectId, refPath: "userType", required: true, }, userType: { type: String, required: true, enum: ["SalesCoOrdinator", "TerritoryManager"], }, addedFor: { type: String, required: true, enum: ["PrincipalDistributor", "RetailDistributor"], }, addedForId: { type: mongoose.Schema.Types.ObjectId, refPath: "addedFor", required: true, }, products: [ProductRecordSchema], }, { timestamps: true, versionKey: false } ); InventorySchema.pre("save", function (next) { if (!this.uniqueId) { const currentYear = new Date().getFullYear().toString().slice(-2); const randomChars = crypto.randomBytes(4).toString("hex").toUpperCase(); this.uniqueId = `${currentYear}-${randomChars}`; } next(); }); export const Inventory = mongoose.model("Inventory", InventorySchema);