Spaces:
Sleeping
Sleeping
File size: 3,095 Bytes
66821dd b5eea9b 66821dd | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 | 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);
|