MultiUsersSalesSystem / backend /models /SupplierInvoiceModel.js
mahmoud
upload frontend & backend folders
66821dd
Raw History Blame
1.78 kB
import mongoose from "mongoose";
const supplierInvoiceSchema = new mongoose.Schema(
{
tenant: {
type: mongoose.Schema.Types.ObjectId,
ref: "Tenant",
required: true,
index: true,
},
supplier: {
type: mongoose.Schema.Types.ObjectId,
ref: "Supplier",
required: true,
},
createdBy: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
default: null,
},
totalAmount: { type: Number, default: 0 },
paidAmount: { type: Number, default: 0 },
remainingAmount: { type: Number, default: 0 },
items: [
{
name: String,
price: Number,
quantity: Number,
total: Number,
date: { type: Date, default: Date.now },
productId: { type: mongoose.Schema.Types.ObjectId, ref: "Product" },
},
],
payments: [
{
amount: Number,
date: { type: Date, default: Date.now },
method: {
type: String,
default: "cash",
},
paidBy: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
default: null,
},
},
],
},
{ timestamps: true }
);
supplierInvoiceSchema.index({ tenant: 1, supplier: 1 });
supplierInvoiceSchema.pre("save", function () {
this.totalAmount = this.items.reduce((sum, item) => sum + Number(item.total || 0), 0);
this.paidAmount = this.payments.reduce((sum, payment) => sum + Number(payment.amount || 0), 0);
this.remainingAmount = Math.max(this.totalAmount - this.paidAmount, 0);
});
export default mongoose.model("SupplierInvoice", supplierInvoiceSchema);