File size: 2,015 Bytes
4dbde5b
 
 
 
 
 
 
 
 
 
0159174
 
 
 
 
 
4dbde5b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0330133
4dbde5b
 
 
 
 
 
 
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
import mongoose from "mongoose";

const supplierInvoiceSchema = new mongoose.Schema(
   {
      tenant: {
         type: mongoose.Schema.Types.ObjectId,
         ref: "Tenant",
         required: true,
         index: true,
      },
      branch: {
         type: mongoose.Schema.Types.ObjectId,
         ref: "Branch",
         default: null,
         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, branch: 1, supplier: 1 }, { unique: true });
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);