import mongoose from "mongoose"; const invoiceSchema = new mongoose.Schema( { tenant: { type: mongoose.Schema.Types.ObjectId, ref: "Tenant", required: true, index: true, }, invoiceNumber: { type: String, required: true, trim: true, }, customer: { type: mongoose.Schema.Types.ObjectId, ref: "Customer", required: true, }, issuedBy: { type: mongoose.Schema.Types.ObjectId, ref: "User", default: null, }, items: [ { name: String, price: Number, quantity: Number, total: Number, date: { type: Date, default: Date.now }, productId: { type: mongoose.Schema.Types.ObjectId, ref: "Product" }, }, ], subtotal: { type: Number, default: 0, }, discount: { type: Number, default: 0, }, taxAmount: { type: Number, default: 0, }, totalAmount: { type: Number, default: 0, }, payments: [ { amount: Number, date: { type: Date, default: Date.now }, method: { type: String, default: "cash", }, receivedBy: { type: mongoose.Schema.Types.ObjectId, ref: "User", default: null, }, }, ], paidAmount: { type: Number, default: 0, }, remainingAmount: { type: Number, default: 0, }, status: { type: String, enum: ["draft", "open", "partial", "paid", "cancelled"], default: "open", }, notes: { type: String, default: "", }, isDeleted: { type: Boolean, default: false, }, }, { timestamps: true } ); invoiceSchema.index({ tenant: 1, invoiceNumber: 1 }, { unique: true }); invoiceSchema.methods.calculateTotals = function () { this.items.forEach((item) => { item.total = Number(item.price || 0) * Number(item.quantity || 0); }); this.subtotal = this.items.reduce((sum, item) => sum + Number(item.total || 0), 0); this.totalAmount = Math.max(this.subtotal - Number(this.discount || 0) + Number(this.taxAmount || 0), 0); if (this.payments?.length || this.isModified("payments")) { this.paidAmount = this.payments.reduce( (sum, payment) => sum + Number(payment.amount || 0), 0 ); } this.remainingAmount = Math.max(this.totalAmount - Number(this.paidAmount || 0), 0); if (this.status === "cancelled") { return; } if (this.remainingAmount <= 0) { this.status = "paid"; } else if (this.paidAmount > 0) { this.status = "partial"; } else { this.status = "open"; } }; invoiceSchema.pre("save", function () { this.calculateTotals(); }); export default mongoose.model("Invoice", invoiceSchema);