import mongoose from "mongoose"; const invoiceSchema = 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, }, 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 }, type: { type: String, enum: ["product", "service", "catalog"], default: "product", }, productId: { type: mongoose.Schema.Types.ObjectId, ref: "Product" }, serviceId: { type: mongoose.Schema.Types.ObjectId, ref: "Service" }, catalogItemId: { type: mongoose.Schema.Types.ObjectId, ref: "CatalogItem" }, }, ], 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", enum: ["cash", "transfer", "partial", "unpaid"] }, transferType: { type: String, enum: ["instapay", "vodafone_cash", "bank_transfer", "wallet"], default: null }, receivedBy: { type: mongoose.Schema.Types.ObjectId, ref: "User", default: null, }, confirmed: { type: Boolean, default: false }, confirmedBy: { type: mongoose.Schema.Types.ObjectId, ref: "User", default: null, }, confirmedAt: Date, }, ], 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: "", }, serviceRevenue: { type: Number, default: 0, }, productRevenue: { type: Number, default: 0, }, catalogRevenue: { type: Number, default: 0, }, hasServices: { type: Boolean, default: false, }, // Restaurant/Cafe Specific Data restaurantData: { orderType: { type: String, enum: ["dine-in", "takeaway", "delivery"], default: null, }, table: { type: mongoose.Schema.Types.ObjectId, ref: "Table", default: null, }, guestInfo: { name: String, phone: String, }, deliveryAddress: String, driver: { driverId: { type: mongoose.Schema.Types.ObjectId, ref: "Driver", default: null, }, driverUserId: { type: mongoose.Schema.Types.ObjectId, ref: "User", default: null, }, driverName: { type: String, default: "" }, driverPhone: { type: String, default: "" }, assignedAt: { type: Date, default: null }, // ✅ NEW: Track actual payment received from driver paymentReceived: { amount: { type: Number, default: 0 }, receivedAt: { type: Date, default: null }, receivedBy: { type: mongoose.Schema.Types.ObjectId, ref: "User", default: null, }, notes: { type: String, default: "" }, }, // ✅ NEW: Track driver status when assigned driverStatus: { type: String, enum: ["pending_assignment", "available", "busy", "off-duty"], default: "pending_assignment", }, }, }, serviceCharge: { type: Number, default: 0, }, deliveryCharge: { type: Number, default: 0, }, restaurantStatus: { type: String, enum: ["pending", "preparing", "ready_for_delivery", "shipped", "delivered"], default: "pending", }, isDeleted: { type: Boolean, default: false, }, }, { timestamps: true } ); const round2 = (n) => Math.round((n)); invoiceSchema.index({ tenant: 1, branch: 1, invoiceNumber: 1 }, { unique: true }); invoiceSchema.methods.calculateTotals = function () { this.serviceRevenue = 0; this.productRevenue = 0; this.catalogRevenue = 0; this.hasServices = false; this.items.forEach((item) => { item.total = round2(Number(item.price || 0) * Number(item.quantity || 0)); // Track granular revenue if (item.type === "service") { this.serviceRevenue += item.total; this.hasServices = true; } else if (item.type === "catalog") { this.catalogRevenue += item.total; } else { this.productRevenue += item.total; } }); this.subtotal = round2( this.items.reduce((sum, item) => sum + Number(item.total || 0), 0) ); const discount = round2(Number(this.discount || 0)); const tax = round2(Number(this.taxAmount || 0)); const serviceCharge = round2(Number(this.serviceCharge || 0)); const deliveryCharge = round2(Number(this.deliveryCharge || 0)); this.totalAmount = round2( Math.max(this.subtotal - discount + tax + serviceCharge + deliveryCharge, 0) ); if (this.payments?.length || this.isModified("payments")) { this.paidAmount = round2( this.payments.reduce((sum, payment) => { if (payment.method === "cash") return sum + Number(payment.amount || 0); return sum + (payment.confirmed === true ? Number(payment.amount || 0) : 0); }, 0) ); } else { // ✅ IMPORTANT: If no payments exist, paidAmount must be 0 (for unpaid/آجل orders) this.paidAmount = 0; } this.remainingAmount = round2( 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);