payservedb 9.4.6 → 9.4.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (231) hide show
  1. package/.env +2 -2
  2. package/ZOHO_INTEGRATION_SCHEMA.md +644 -644
  3. package/index.js +417 -417
  4. package/package.json +17 -17
  5. package/src/models/InvoiceWithholdingTax.js +67 -67
  6. package/src/models/account.js +52 -52
  7. package/src/models/agent_departments.js +59 -59
  8. package/src/models/agent_notifications.js +53 -53
  9. package/src/models/agent_performance.js +127 -127
  10. package/src/models/agent_roles.js +77 -77
  11. package/src/models/agents.js +154 -154
  12. package/src/models/apilog.js +18 -18
  13. package/src/models/approvalsWorkflows.js +49 -49
  14. package/src/models/archivedapilog.js +18 -18
  15. package/src/models/asset.js +92 -92
  16. package/src/models/assetsAssignment.js +64 -64
  17. package/src/models/auditTrail.js +346 -346
  18. package/src/models/auto_reply_rule.js +68 -68
  19. package/src/models/bankdetails.js +47 -47
  20. package/src/models/billerAddress.js +124 -124
  21. package/src/models/booking_invoice.js +165 -165
  22. package/src/models/bookinganalytics.js +63 -63
  23. package/src/models/bookingconfig.js +45 -45
  24. package/src/models/bookingproperty.js +179 -179
  25. package/src/models/bookingreservation.js +239 -239
  26. package/src/models/bookingrevenuerecord.js +84 -84
  27. package/src/models/budget.js +95 -95
  28. package/src/models/budgetCategory.js +19 -19
  29. package/src/models/campaigns.js +108 -108
  30. package/src/models/cashpayment.js +289 -289
  31. package/src/models/combinedUnits.js +62 -62
  32. package/src/models/combined_invoice.js +424 -424
  33. package/src/models/common_area_electricity.js +38 -38
  34. package/src/models/common_area_generator.js +41 -41
  35. package/src/models/common_area_utility_alert.js +37 -37
  36. package/src/models/common_area_water.js +39 -39
  37. package/src/models/communication_status.js +33 -33
  38. package/src/models/communication_user_opt.js +32 -32
  39. package/src/models/community_guidelines.js +35 -35
  40. package/src/models/company.js +53 -53
  41. package/src/models/coreBaseSettings.js +16 -16
  42. package/src/models/coreInvoiceSettings.js +100 -100
  43. package/src/models/counter_schema.js +21 -21
  44. package/src/models/country_tax.js +42 -42
  45. package/src/models/currency_settings.js +39 -39
  46. package/src/models/customer.js +251 -251
  47. package/src/models/customer_preference.js +52 -52
  48. package/src/models/customer_satisfaction_survey.js +297 -297
  49. package/src/models/customer_surveys.js +139 -139
  50. package/src/models/customer_tickets.js +237 -237
  51. package/src/models/dailyChecklist.js +312 -312
  52. package/src/models/default_payment_details.js +17 -17
  53. package/src/models/deliveryTimeMarks.js +18 -18
  54. package/src/models/document_type.js +19 -19
  55. package/src/models/dutyRosterChecklist.js +250 -250
  56. package/src/models/dutyroster.js +136 -136
  57. package/src/models/email.js +37 -37
  58. package/src/models/email_cc_config.js +48 -48
  59. package/src/models/email_sms_queue.js +61 -61
  60. package/src/models/email_thread.js +35 -35
  61. package/src/models/entry_exit.js +53 -53
  62. package/src/models/expense.js +99 -99
  63. package/src/models/expense_category.js +45 -45
  64. package/src/models/facility.js +76 -76
  65. package/src/models/facilityBillingPrices.js +29 -29
  66. package/src/models/facilityInvoice.js +240 -240
  67. package/src/models/facilityInvoicePayment.js +52 -52
  68. package/src/models/facilityInvoiceRecipient.js +32 -32
  69. package/src/models/facilityWalletTransactionsMetadata.js +236 -236
  70. package/src/models/facility_departements.js +20 -20
  71. package/src/models/facility_etims_config.js +116 -116
  72. package/src/models/facility_payment_details.js +20 -20
  73. package/src/models/facility_rating.js +78 -78
  74. package/src/models/facilityasset.js +25 -25
  75. package/src/models/faq.js +15 -15
  76. package/src/models/gl_account_double_entries.js +25 -25
  77. package/src/models/gl_accounts.js +56 -56
  78. package/src/models/gl_entries.js +49 -49
  79. package/src/models/goodsReceivedNotes.js +115 -115
  80. package/src/models/guard.js +47 -47
  81. package/src/models/handover.js +258 -258
  82. package/src/models/inspection_category.js +38 -38
  83. package/src/models/invoice.js +561 -561
  84. package/src/models/invoiceCreditAdjustment.js +45 -45
  85. package/src/models/invoice_edit_log.js +81 -81
  86. package/src/models/invoice_generation_approval.js +86 -86
  87. package/src/models/invoicing_schedule.js +40 -40
  88. package/src/models/item_inspection.js +96 -96
  89. package/src/models/knowledge_base.js +109 -109
  90. package/src/models/knowledge_base_rating.js +44 -44
  91. package/src/models/leaseagreement.js +266 -266
  92. package/src/models/leasetemplate.js +17 -17
  93. package/src/models/levy.js +229 -212
  94. package/src/models/levy_deposits.js +139 -139
  95. package/src/models/levy_invoice_settings.js +26 -26
  96. package/src/models/levy_payment_receipt.js +156 -156
  97. package/src/models/levycontract.js +213 -236
  98. package/src/models/levytype.js +23 -23
  99. package/src/models/maintenance_service_vendor.js +38 -38
  100. package/src/models/maintenance_services.js +17 -17
  101. package/src/models/maintenancerequisition.js +31 -31
  102. package/src/models/master_workplan.js +32 -32
  103. package/src/models/master_workplan_child.js +34 -34
  104. package/src/models/message.js +38 -38
  105. package/src/models/module.js +21 -21
  106. package/src/models/movein_amenity.js +13 -13
  107. package/src/models/movein_application.js +28 -28
  108. package/src/models/movein_audit_log.js +21 -21
  109. package/src/models/movein_booking.js +33 -33
  110. package/src/models/movein_commission.js +46 -46
  111. package/src/models/movein_conversation.js +25 -25
  112. package/src/models/movein_deal.js +79 -79
  113. package/src/models/movein_disbursement.js +36 -36
  114. package/src/models/movein_email_thread.js +19 -19
  115. package/src/models/movein_enquiry.js +16 -16
  116. package/src/models/movein_featured_package.js +16 -16
  117. package/src/models/movein_handoff_token.js +16 -16
  118. package/src/models/movein_invoice.js +24 -24
  119. package/src/models/movein_landlord.js +18 -18
  120. package/src/models/movein_landlord_user.js +20 -20
  121. package/src/models/movein_lease.js +37 -37
  122. package/src/models/movein_message.js +27 -27
  123. package/src/models/movein_notification.js +27 -27
  124. package/src/models/movein_otp.js +14 -14
  125. package/src/models/movein_payment.js +46 -46
  126. package/src/models/movein_reminder.js +77 -77
  127. package/src/models/movein_reservation.js +31 -31
  128. package/src/models/movein_settings.js +25 -25
  129. package/src/models/movein_tenancy.js +55 -55
  130. package/src/models/movein_unit.js +59 -59
  131. package/src/models/movein_user.js +15 -15
  132. package/src/models/movein_viewing_slot.js +21 -21
  133. package/src/models/movein_want_unit.js +20 -20
  134. package/src/models/notification.js +44 -44
  135. package/src/models/paymentTermsMarks.js +19 -19
  136. package/src/models/penalty.js +76 -76
  137. package/src/models/pendingCredentials.js +32 -32
  138. package/src/models/powerMeterCommunicationProtocol.js +17 -17
  139. package/src/models/powerMeterCustomerAccount.js +78 -78
  140. package/src/models/powerMeterCustomerBand.js +14 -14
  141. package/src/models/powerMeterDailyReading.js +30 -30
  142. package/src/models/powerMeterGateways.js +40 -40
  143. package/src/models/powerMeterMonthlyReading.js +34 -34
  144. package/src/models/powerMeterPowerCharges.js +85 -85
  145. package/src/models/powerMeterSettings.js +211 -211
  146. package/src/models/powerMeterSingleDayReading.js +32 -32
  147. package/src/models/powerMeters.js +149 -149
  148. package/src/models/powerMetersManufacturer.js +14 -14
  149. package/src/models/power_invoice.js +371 -371
  150. package/src/models/power_meter_account.js +81 -81
  151. package/src/models/power_meter_command_logs.js +30 -30
  152. package/src/models/power_meter_command_queue.js +33 -33
  153. package/src/models/power_meter_negative_balance.js +44 -44
  154. package/src/models/power_prepaid_credits.js +47 -47
  155. package/src/models/power_prepaid_debits.js +53 -53
  156. package/src/models/power_prepaid_orders.js +78 -78
  157. package/src/models/power_sms_notification.js +26 -26
  158. package/src/models/privacy_policy.js +19 -19
  159. package/src/models/propertyManagementSettings.js +55 -55
  160. package/src/models/propertyManagerContract.js +579 -579
  161. package/src/models/propertyManagerRevenue.js +195 -195
  162. package/src/models/propertyManagerRevenueEntry.js +108 -108
  163. package/src/models/purchaseOrderInvoice.js +74 -74
  164. package/src/models/purchase_order.js +213 -213
  165. package/src/models/purchase_request.js +110 -110
  166. package/src/models/quickbooks_config.js +52 -52
  167. package/src/models/recipient_group.js +61 -61
  168. package/src/models/recipient_group_member.js +62 -62
  169. package/src/models/refresh_token.js +23 -23
  170. package/src/models/reminder.js +197 -197
  171. package/src/models/report.js +13 -13
  172. package/src/models/resident.js +121 -121
  173. package/src/models/rfq_details.js +131 -131
  174. package/src/models/rfq_response.js +153 -153
  175. package/src/models/service_charge_invoice_upload.js +42 -42
  176. package/src/models/service_charge_payments.js +27 -27
  177. package/src/models/servicerequest.js +55 -55
  178. package/src/models/settings.js +62 -62
  179. package/src/models/short_urls.js +21 -21
  180. package/src/models/smart_meter_daily_consumption.js +44 -44
  181. package/src/models/sms_africastalking.js +20 -20
  182. package/src/models/sms_balance_notification.js +26 -26
  183. package/src/models/sms_meliora.js +20 -20
  184. package/src/models/staff.js +36 -36
  185. package/src/models/stocksandspare.js +161 -161
  186. package/src/models/suppliers.js +79 -79
  187. package/src/models/terms_and_conditions.js +19 -19
  188. package/src/models/tickets.js +186 -186
  189. package/src/models/tickets_category.js +72 -72
  190. package/src/models/unitManagementTemplate.js +44 -44
  191. package/src/models/unitasset.js +25 -25
  192. package/src/models/units.js +148 -148
  193. package/src/models/user.js +186 -186
  194. package/src/models/valueaddedservices.js +50 -50
  195. package/src/models/vas_invoices_upload.js +50 -50
  196. package/src/models/vas_payments.js +24 -24
  197. package/src/models/vasinvoice.js +196 -196
  198. package/src/models/vasvendor.js +52 -52
  199. package/src/models/visitLog.js +95 -95
  200. package/src/models/visitor.js +67 -67
  201. package/src/models/waitlist.js +45 -45
  202. package/src/models/wallet.js +44 -44
  203. package/src/models/wallet_transaction.js +67 -67
  204. package/src/models/wallet_transactions.js +72 -72
  205. package/src/models/water_invoice.js +362 -362
  206. package/src/models/water_meter_Command_Queue.js +33 -33
  207. package/src/models/water_meter_account.js +86 -86
  208. package/src/models/water_meter_billing.js +58 -58
  209. package/src/models/water_meter_combined_accounts.js +92 -92
  210. package/src/models/water_meter_communication.js +17 -17
  211. package/src/models/water_meter_communication_logs.js +39 -39
  212. package/src/models/water_meter_concentrator.js +70 -70
  213. package/src/models/water_meter_daily_history.js +32 -32
  214. package/src/models/water_meter_high_risk.js +36 -36
  215. package/src/models/water_meter_iot_cards.js +34 -34
  216. package/src/models/water_meter_loan_deduction.js +134 -134
  217. package/src/models/water_meter_manufacturer.js +35 -35
  218. package/src/models/water_meter_monthly_history.js +36 -36
  219. package/src/models/water_meter_negative_amounts.js +44 -44
  220. package/src/models/water_meter_settings.js +296 -296
  221. package/src/models/water_meter_single_day_history.js +34 -34
  222. package/src/models/water_meter_size.js +15 -15
  223. package/src/models/water_meters.js +176 -176
  224. package/src/models/water_meters_delivery.js +76 -76
  225. package/src/models/water_prepaid_credit.js +47 -47
  226. package/src/models/water_prepaid_debit.js +50 -50
  227. package/src/models/whatsapp_conversation.js +23 -23
  228. package/src/models/workorder.js +49 -49
  229. package/src/models/zohoAccount.js +453 -453
  230. package/src/models/zohoIntegration.js +262 -262
  231. package/src/models/zohoItem.js +504 -504
@@ -1,561 +1,561 @@
1
- const mongoose = require("mongoose");
2
-
3
- const invoiceSchema = new mongoose.Schema(
4
- {
5
- invoiceNumber: {
6
- type: String,
7
- required: true,
8
- unique: true,
9
- },
10
- accountNumber: {
11
- type: String,
12
- required: true,
13
- },
14
- client: {
15
- clientId: {
16
- type: mongoose.Schema.Types.ObjectId,
17
- ref: "Customer",
18
- required: true,
19
- },
20
- firstName: {
21
- type: String,
22
- required: true,
23
- },
24
- lastName: {
25
- type: String,
26
- required: true,
27
- },
28
- kraPin: {
29
- type: String,
30
- default: null,
31
- },
32
- },
33
- facility: {
34
- id: {
35
- type: mongoose.Schema.Types.ObjectId,
36
- ref: "Facility",
37
- required: true,
38
- },
39
- name: {
40
- type: String,
41
- required: true,
42
- },
43
- },
44
- unit: {
45
- id: { type: mongoose.Schema.Types.ObjectId, ref: "Unit", required: true },
46
- name: { type: String, required: true },
47
- },
48
- currency: {
49
- id: {
50
- type: mongoose.Schema.Types.ObjectId,
51
- ref: "Currency",
52
- required: true,
53
- },
54
- name: {
55
- type: String,
56
- required: true,
57
- },
58
- code: {
59
- type: String,
60
- required: true,
61
- uppercase: true,
62
- minlength: 3,
63
- maxlength: 3,
64
- },
65
- },
66
- items: [
67
- {
68
- description: { type: String, required: true },
69
- quantity: { type: Number, required: true, min: 1 },
70
- unitPrice: { type: Number, required: true, min: 0 },
71
- },
72
- ],
73
- subTotal: {
74
- type: Number,
75
- required: true,
76
- },
77
- tax: {
78
- type: Number,
79
- required: true,
80
- },
81
- taxes: [
82
- {
83
- name: { type: String, required: true }, // e.g. "VAT", "Withholding Tax"
84
- percentage: { type: Number, required: true }, // e.g. 16
85
- amount: { type: Number, required: true }, // e.g. 160.00 (subTotal * percentage / 100)
86
- },
87
- ],
88
- withholdingTaxes: [
89
- {
90
- name: { type: String, required: true }, // e.g. "withholding"
91
- percentage: { type: Number, required: true }, // e.g. 5
92
- amount: { type: Number, required: true }, // e.g. 50 (subTotal * percentage / 100)
93
- },
94
- ],
95
- totalWithholdingTax: {
96
- type: Number,
97
- default: 0,
98
- },
99
- totalAmount: {
100
- type: Number,
101
- required: true,
102
- },
103
- amountPaid: {
104
- type: Number,
105
- default: 0,
106
- min: 0,
107
- },
108
- // Mark as deprecated, keep for backward compatibility
109
- overpay: {
110
- type: Number,
111
- default: 0,
112
- min: 0,
113
- deprecated: true,
114
- },
115
- issueDate: {
116
- type: Date,
117
- required: true,
118
- },
119
- dueDate: {
120
- type: Date,
121
- required: true,
122
- },
123
- status: {
124
- type: String,
125
- required: true,
126
- enum: [
127
- "Unpaid",
128
- "Pending",
129
- "Paid",
130
- "Overdue",
131
- "Cancelled",
132
- "Partially Paid",
133
- "Void",
134
- ],
135
- },
136
- penalty: {
137
- type: Number,
138
- default: 0,
139
- },
140
- whatFor: {
141
- invoiceType: { type: String, required: true },
142
- description: { type: String },
143
- },
144
- invoiceNote: {
145
- type: String,
146
- default: null,
147
- },
148
- balanceBroughtForward: {
149
- type: Number,
150
- default: 0,
151
- },
152
- // NEW FIELD 1: Year-Month for easy filtering
153
- yearMonth: {
154
- type: String,
155
- match: /^\d{4}-\d{2}$/, // Validates format like "2025-08"
156
- index: true,
157
- },
158
- // NEW FIELD 2: Simple notification tracking
159
- notificationsSent: {
160
- sms: {
161
- type: Boolean,
162
- default: false,
163
- },
164
- email: {
165
- type: Boolean,
166
- default: false,
167
- },
168
- attempts: {
169
- type: Number,
170
- default: 0,
171
- },
172
- },
173
- voidMetadata: {
174
- voidedBy: {
175
- userId: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
176
- name: { type: String },
177
- role: { type: String },
178
- },
179
- voidedAt: { type: Date },
180
- reason: { type: String },
181
- },
182
- cancelMetadata: {
183
- cancelledBy: {
184
- userId: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
185
- name: { type: String },
186
- role: { type: String },
187
- },
188
- cancelledAt: { type: Date },
189
- reason: { type: String },
190
- },
191
- lastReminderSent: Date,
192
- reminderHistory: [
193
- {
194
- sentAt: Date,
195
- reminderId: mongoose.Schema.Types.ObjectId,
196
- notificationTypes: [String],
197
- },
198
- ],
199
- reconciliationHistory: [
200
- {
201
- date: { type: Date, required: true },
202
- paymentDate: {
203
- type: Date
204
- },
205
- amount: { type: Number, required: true },
206
- type: {
207
- type: String,
208
- enum: [
209
- "payment",
210
- "cash",
211
- "cheque",
212
- "bank-transfer",
213
- "mpesa-transfer",
214
- "overpay-transfer",
215
- "balance-deduction",
216
- "overpay-received",
217
- "credit-forward",
218
- "debit-forward",
219
- ],
220
- required: true,
221
- },
222
- sourceInvoice: String,
223
- destinationInvoice: String,
224
- paymentReference: String,
225
- paymentCompletion: String,
226
- remainingBalance: Number,
227
- notes: String,
228
- exchangeRate: {
229
- type: Number,
230
- default: 1, // For cross-currency reconciliations
231
- },
232
- originalCurrency: {
233
- code: String, // Original currency code if different from invoice currency
234
- amount: Number, // Amount in original currency
235
- },
236
- },
237
- ],
238
- paymentDetails: {
239
- paymentStatus: { type: String, required: true },
240
- paymentMethod: { type: String },
241
- paymentDate: { type: Date },
242
- transactionId: { type: String },
243
- },
244
- // New field to track when an invoice has been viewed
245
- viewStatus: {
246
- isOpened: { type: Boolean, default: false },
247
- openedAt: { type: Date, default: null },
248
- openedBy: {
249
- facilityId: { type: mongoose.Schema.Types.ObjectId, ref: "Facility" },
250
- userId: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
251
- userRole: { type: String },
252
- },
253
- viewHistory: [
254
- {
255
- viewedAt: { type: Date, required: true },
256
- facilityId: { type: mongoose.Schema.Types.ObjectId, ref: "Facility" },
257
- userId: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
258
- },
259
- ],
260
- },
261
- invoiceUrl: {
262
- type: String,
263
- default: null,
264
- },
265
- // eTims tax integration fields
266
- ticketUrl: {
267
- type: String,
268
- default: null,
269
- description: "QR code URL from eTims/KRA for tax invoice verification",
270
- },
271
- txsync: {
272
- status: {
273
- type: String,
274
- enum: ["pending", "synced", "failed", "not-applicable"],
275
- default: "not-applicable",
276
- },
277
- syncedAt: {
278
- type: Date,
279
- default: null,
280
- },
281
- etimsInvoiceNo: {
282
- type: String,
283
- default: null,
284
- },
285
- sdcId: {
286
- type: String,
287
- default: null,
288
- },
289
- receiptNo: {
290
- type: String,
291
- default: null,
292
- },
293
- errorMessage: {
294
- type: String,
295
- default: null,
296
- },
297
- attempts: {
298
- type: Number,
299
- default: 0,
300
- },
301
- lastAttemptAt: {
302
- type: Date,
303
- default: null,
304
- },
305
- },
306
- creditNote: {
307
- status: {
308
- type: String,
309
- enum: ["pending", "synced", "failed"],
310
- default: undefined, // absent until a void triggers one
311
- },
312
- creditNoteTraderNo: { type: String, default: null },
313
- etimsCreditNoteNo: { type: String, default: null },
314
- sdcId: { type: String, default: null },
315
- receiptNo: { type: String, default: null },
316
- verificationUrl: { type: String, default: null },
317
- syncedAt: { type: Date, default: null },
318
- lastAttemptAt: { type: Date, default: null },
319
- errorMessage: { type: String, default: null },
320
- attempts: { type: Number, default: 0 },
321
- },
322
- digitax: {
323
- synced: {
324
- type: Boolean,
325
- default: false
326
- },
327
- syncedAt: Date,
328
- status: {
329
- type: String,
330
- enum: [
331
- "PENDING",
332
- "PROCESSING",
333
- "SUCCESS",
334
- "FAILED"
335
- ],
336
- default: "PENDING"
337
- },
338
- saleId: String,
339
- traderInvoiceNumber: String,
340
- digitaxInvoiceNumber: Number,
341
- receiptNumber: Number,
342
- serialNumber: String,
343
- receiptTypeCode: String,
344
- offlineUrl: String,
345
- saleDetailUrl: String,
346
- etimsUrl: String,
347
- attempts: {
348
- type: Number,
349
- default: 0
350
- },
351
- lastAttemptAt: Date,
352
- lastError: String,
353
- response: mongoose.Schema.Types.Mixed
354
- },
355
- // New fields for double entry accounts
356
- invoiceDoubleEntryAccount: {
357
- type: mongoose.Schema.Types.ObjectId,
358
- ref: "GLAccountDoubleEntries",
359
- required: false,
360
- },
361
- paymentDoubleEntryAccount: {
362
- type: mongoose.Schema.Types.ObjectId,
363
- ref: "GLAccountDoubleEntries",
364
- required: false,
365
- },
366
- // GL account details for invoice entries
367
- accountdebitedData: {
368
- amount: { type: Number },
369
- description: { type: String },
370
- isActive: { type: Boolean, default: true },
371
- },
372
- accountcreditedData: {
373
- amount: { type: Number },
374
- description: { type: String },
375
- isActive: { type: Boolean, default: true },
376
- },
377
- },
378
- {
379
- timestamps: true,
380
- },
381
- );
382
-
383
- // Add indexes for frequently queried fields
384
- invoiceSchema.index({ accountNumber: 1 });
385
- invoiceSchema.index({ status: 1 });
386
- invoiceSchema.index({ "client.clientId": 1, status: 1 });
387
- invoiceSchema.index({ "reconciliationHistory.paymentReference": 1 });
388
- invoiceSchema.index({ issueDate: -1 });
389
- invoiceSchema.index({ "currency.code": 1 }); // Add index for currency code
390
- invoiceSchema.index({ "currency.id": 1 }); // Add index for currency ID
391
- invoiceSchema.index({ "currency.code": 1, "client.clientId": 1, status: 1 }); // Compound index for currency-based queries
392
- invoiceSchema.index({ "client.clientId": 1, balanceBroughtForward: 1 }); // Add index for finding invoices with credit balances
393
- invoiceSchema.index({ "viewStatus.isOpened": 1 }); // Add index for view status
394
- invoiceSchema.index({ "viewStatus.openedBy.facilityId": 1 }); // Add index for facility view tracking
395
- // Add index for double entry accounts
396
- invoiceSchema.index({ invoiceDoubleEntryAccount: 1 });
397
- invoiceSchema.index({ paymentDoubleEntryAccount: 1 });
398
- // NEW INDEXES for new fields
399
- invoiceSchema.index({ yearMonth: 1 }); // For filtering by year-month
400
- invoiceSchema.index({ yearMonth: 1, status: 1 }); // Combined index for monthly reports
401
- invoiceSchema.index({ "notificationsSent.sms": 1 }); // For finding SMS sent/not sent
402
- invoiceSchema.index({ "notificationsSent.email": 1 }); // For finding email sent/not sent
403
- // eTims tax sync indexes
404
- invoiceSchema.index({ "txsync.status": 1 }); // For finding invoices by sync status
405
- invoiceSchema.index({ "txsync.etimsInvoiceNo": 1 }); // For looking up by eTims invoice number
406
-
407
- // Add virtual field for calculating balance
408
- invoiceSchema.virtual("calculatedBalance").get(function () {
409
- const baseBalance = this.totalAmount - (this.amountPaid || 0);
410
-
411
- // Add positive balanceBroughtForward (customer owes money)
412
- if (this.balanceBroughtForward > 0) {
413
- return baseBalance + this.balanceBroughtForward;
414
- }
415
-
416
- // Subtract negative balanceBroughtForward (credit)
417
- return baseBalance;
418
- });
419
-
420
- // Add virtual field for credit balance
421
- invoiceSchema.virtual("creditBalance").get(function () {
422
- return this.balanceBroughtForward < 0
423
- ? Math.abs(this.balanceBroughtForward)
424
- : 0;
425
- });
426
-
427
- // Getter for compatible overpay field
428
- invoiceSchema.virtual("effectiveOverpay").get(function () {
429
- return this.balanceBroughtForward < 0
430
- ? Math.abs(this.balanceBroughtForward)
431
- : 0;
432
- });
433
-
434
- // Add virtual populate for invoice double entry account
435
- invoiceSchema.virtual("invoiceDoubleEntry", {
436
- ref: "GLAccountDoubleEntries",
437
- localField: "invoiceDoubleEntryAccount",
438
- foreignField: "_id",
439
- justOne: true,
440
- });
441
-
442
- // Add virtual populate for payment double entry account
443
- invoiceSchema.virtual("paymentDoubleEntry", {
444
- ref: "GLAccountDoubleEntries",
445
- localField: "paymentDoubleEntryAccount",
446
- foreignField: "_id",
447
- justOne: true,
448
- });
449
-
450
- // Add method for currency conversion if needed
451
- invoiceSchema.methods.convertAmount = function (
452
- amount,
453
- fromCurrency,
454
- toCurrency,
455
- exchangeRate,
456
- ) {
457
- if (fromCurrency === toCurrency) {
458
- return amount;
459
- }
460
- return amount * exchangeRate;
461
- };
462
-
463
- // Add static method to find invoices by currency
464
- invoiceSchema.statics.findByCurrency = function (currencyCode) {
465
- return this.find({ "currency.code": currencyCode.toUpperCase() });
466
- };
467
-
468
- // Add static method to find invoices with credit balance
469
- invoiceSchema.statics.findWithCreditBalance = function (clientId) {
470
- return this.find({
471
- "client.clientId": clientId,
472
- balanceBroughtForward: { $lt: 0 },
473
- }).sort({ updatedAt: -1 });
474
- };
475
-
476
- // Add static method to calculate totals by currency
477
- invoiceSchema.statics.calculateTotalsByCurrency = function (query = {}) {
478
- return this.aggregate([
479
- { $match: query },
480
- {
481
- $group: {
482
- _id: "$currency.code",
483
- totalAmount: { $sum: "$totalAmount" },
484
- totalPaid: { $sum: "$amountPaid" },
485
- count: { $sum: 1 },
486
- },
487
- },
488
- ]);
489
- };
490
-
491
- // New static method to find all unviewed invoices
492
- invoiceSchema.statics.findUnviewedInvoices = function (facilityId) {
493
- return this.find({
494
- "facility.id": facilityId,
495
- "viewStatus.isOpened": false,
496
- });
497
- };
498
-
499
- // NEW STATIC METHODS for new fields
500
- // Find invoices by year-month
501
- invoiceSchema.statics.findByYearMonth = function (yearMonth) {
502
- return this.find({ yearMonth: yearMonth });
503
- };
504
-
505
- // Find invoices where notifications haven't been sent
506
- invoiceSchema.statics.findPendingNotifications = function (facilityId) {
507
- return this.find({
508
- "facility.id": facilityId,
509
- status: { $in: ["Unpaid", "Overdue"] },
510
- $or: [
511
- { "notificationsSent.sms": false },
512
- { "notificationsSent.email": false },
513
- ],
514
- });
515
- };
516
-
517
- // Find invoices pending eTims sync
518
- invoiceSchema.statics.findPendingTaxSync = function (facilityId) {
519
- return this.find({
520
- "facility.id": facilityId,
521
- "txsync.status": "pending",
522
- });
523
- };
524
-
525
- // Find invoices with failed eTims sync
526
- invoiceSchema.statics.findFailedTaxSync = function (facilityId) {
527
- return this.find({
528
- "facility.id": facilityId,
529
- "txsync.status": "failed",
530
- });
531
- };
532
-
533
- // Pre-save middleware to ensure overpay and balanceBroughtForward stay in sync during transition
534
- invoiceSchema.pre("save", function (next) {
535
-
536
- if (this.taxes && this.taxes.length > 0) {
537
- this.tax = Math.round(
538
- this.taxes.reduce((sum, t) => sum + (t.amount || 0), 0) * 100
539
- ) / 100;
540
- }
541
-
542
- // If balanceBroughtForward is negative (credit), sync with overpay for backwards compatibility
543
- if (this.balanceBroughtForward < 0) {
544
- this.overpay = Math.abs(this.balanceBroughtForward);
545
- } else {
546
- this.overpay = 0; // No overpay if there's no negative balance
547
- }
548
-
549
- // NEW: Auto-generate yearMonth from issueDate if not provided
550
- if (!this.yearMonth && this.issueDate) {
551
- const year = this.issueDate.getFullYear();
552
- const month = String(this.issueDate.getMonth() + 1).padStart(2, "0");
553
- this.yearMonth = `${year}-${month}`;
554
- }
555
-
556
- next();
557
- });
558
-
559
- const Invoice = mongoose.model("Invoice", invoiceSchema);
560
-
561
- module.exports = Invoice;
1
+ const mongoose = require("mongoose");
2
+
3
+ const invoiceSchema = new mongoose.Schema(
4
+ {
5
+ invoiceNumber: {
6
+ type: String,
7
+ required: true,
8
+ unique: true,
9
+ },
10
+ accountNumber: {
11
+ type: String,
12
+ required: true,
13
+ },
14
+ client: {
15
+ clientId: {
16
+ type: mongoose.Schema.Types.ObjectId,
17
+ ref: "Customer",
18
+ required: true,
19
+ },
20
+ firstName: {
21
+ type: String,
22
+ required: true,
23
+ },
24
+ lastName: {
25
+ type: String,
26
+ required: true,
27
+ },
28
+ kraPin: {
29
+ type: String,
30
+ default: null,
31
+ },
32
+ },
33
+ facility: {
34
+ id: {
35
+ type: mongoose.Schema.Types.ObjectId,
36
+ ref: "Facility",
37
+ required: true,
38
+ },
39
+ name: {
40
+ type: String,
41
+ required: true,
42
+ },
43
+ },
44
+ unit: {
45
+ id: { type: mongoose.Schema.Types.ObjectId, ref: "Unit", required: true },
46
+ name: { type: String, required: true },
47
+ },
48
+ currency: {
49
+ id: {
50
+ type: mongoose.Schema.Types.ObjectId,
51
+ ref: "Currency",
52
+ required: true,
53
+ },
54
+ name: {
55
+ type: String,
56
+ required: true,
57
+ },
58
+ code: {
59
+ type: String,
60
+ required: true,
61
+ uppercase: true,
62
+ minlength: 3,
63
+ maxlength: 3,
64
+ },
65
+ },
66
+ items: [
67
+ {
68
+ description: { type: String, required: true },
69
+ quantity: { type: Number, required: true, min: 1 },
70
+ unitPrice: { type: Number, required: true, min: 0 },
71
+ },
72
+ ],
73
+ subTotal: {
74
+ type: Number,
75
+ required: true,
76
+ },
77
+ tax: {
78
+ type: Number,
79
+ required: true,
80
+ },
81
+ taxes: [
82
+ {
83
+ name: { type: String, required: true }, // e.g. "VAT", "Withholding Tax"
84
+ percentage: { type: Number, required: true }, // e.g. 16
85
+ amount: { type: Number, required: true }, // e.g. 160.00 (subTotal * percentage / 100)
86
+ },
87
+ ],
88
+ withholdingTaxes: [
89
+ {
90
+ name: { type: String, required: true }, // e.g. "withholding"
91
+ percentage: { type: Number, required: true }, // e.g. 5
92
+ amount: { type: Number, required: true }, // e.g. 50 (subTotal * percentage / 100)
93
+ },
94
+ ],
95
+ totalWithholdingTax: {
96
+ type: Number,
97
+ default: 0,
98
+ },
99
+ totalAmount: {
100
+ type: Number,
101
+ required: true,
102
+ },
103
+ amountPaid: {
104
+ type: Number,
105
+ default: 0,
106
+ min: 0,
107
+ },
108
+ // Mark as deprecated, keep for backward compatibility
109
+ overpay: {
110
+ type: Number,
111
+ default: 0,
112
+ min: 0,
113
+ deprecated: true,
114
+ },
115
+ issueDate: {
116
+ type: Date,
117
+ required: true,
118
+ },
119
+ dueDate: {
120
+ type: Date,
121
+ required: true,
122
+ },
123
+ status: {
124
+ type: String,
125
+ required: true,
126
+ enum: [
127
+ "Unpaid",
128
+ "Pending",
129
+ "Paid",
130
+ "Overdue",
131
+ "Cancelled",
132
+ "Partially Paid",
133
+ "Void",
134
+ ],
135
+ },
136
+ penalty: {
137
+ type: Number,
138
+ default: 0,
139
+ },
140
+ whatFor: {
141
+ invoiceType: { type: String, required: true },
142
+ description: { type: String },
143
+ },
144
+ invoiceNote: {
145
+ type: String,
146
+ default: null,
147
+ },
148
+ balanceBroughtForward: {
149
+ type: Number,
150
+ default: 0,
151
+ },
152
+ // NEW FIELD 1: Year-Month for easy filtering
153
+ yearMonth: {
154
+ type: String,
155
+ match: /^\d{4}-\d{2}$/, // Validates format like "2025-08"
156
+ index: true,
157
+ },
158
+ // NEW FIELD 2: Simple notification tracking
159
+ notificationsSent: {
160
+ sms: {
161
+ type: Boolean,
162
+ default: false,
163
+ },
164
+ email: {
165
+ type: Boolean,
166
+ default: false,
167
+ },
168
+ attempts: {
169
+ type: Number,
170
+ default: 0,
171
+ },
172
+ },
173
+ voidMetadata: {
174
+ voidedBy: {
175
+ userId: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
176
+ name: { type: String },
177
+ role: { type: String },
178
+ },
179
+ voidedAt: { type: Date },
180
+ reason: { type: String },
181
+ },
182
+ cancelMetadata: {
183
+ cancelledBy: {
184
+ userId: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
185
+ name: { type: String },
186
+ role: { type: String },
187
+ },
188
+ cancelledAt: { type: Date },
189
+ reason: { type: String },
190
+ },
191
+ lastReminderSent: Date,
192
+ reminderHistory: [
193
+ {
194
+ sentAt: Date,
195
+ reminderId: mongoose.Schema.Types.ObjectId,
196
+ notificationTypes: [String],
197
+ },
198
+ ],
199
+ reconciliationHistory: [
200
+ {
201
+ date: { type: Date, required: true },
202
+ paymentDate: {
203
+ type: Date
204
+ },
205
+ amount: { type: Number, required: true },
206
+ type: {
207
+ type: String,
208
+ enum: [
209
+ "payment",
210
+ "cash",
211
+ "cheque",
212
+ "bank-transfer",
213
+ "mpesa-transfer",
214
+ "overpay-transfer",
215
+ "balance-deduction",
216
+ "overpay-received",
217
+ "credit-forward",
218
+ "debit-forward",
219
+ ],
220
+ required: true,
221
+ },
222
+ sourceInvoice: String,
223
+ destinationInvoice: String,
224
+ paymentReference: String,
225
+ paymentCompletion: String,
226
+ remainingBalance: Number,
227
+ notes: String,
228
+ exchangeRate: {
229
+ type: Number,
230
+ default: 1, // For cross-currency reconciliations
231
+ },
232
+ originalCurrency: {
233
+ code: String, // Original currency code if different from invoice currency
234
+ amount: Number, // Amount in original currency
235
+ },
236
+ },
237
+ ],
238
+ paymentDetails: {
239
+ paymentStatus: { type: String, required: true },
240
+ paymentMethod: { type: String },
241
+ paymentDate: { type: Date },
242
+ transactionId: { type: String },
243
+ },
244
+ // New field to track when an invoice has been viewed
245
+ viewStatus: {
246
+ isOpened: { type: Boolean, default: false },
247
+ openedAt: { type: Date, default: null },
248
+ openedBy: {
249
+ facilityId: { type: mongoose.Schema.Types.ObjectId, ref: "Facility" },
250
+ userId: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
251
+ userRole: { type: String },
252
+ },
253
+ viewHistory: [
254
+ {
255
+ viewedAt: { type: Date, required: true },
256
+ facilityId: { type: mongoose.Schema.Types.ObjectId, ref: "Facility" },
257
+ userId: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
258
+ },
259
+ ],
260
+ },
261
+ invoiceUrl: {
262
+ type: String,
263
+ default: null,
264
+ },
265
+ // eTims tax integration fields
266
+ ticketUrl: {
267
+ type: String,
268
+ default: null,
269
+ description: "QR code URL from eTims/KRA for tax invoice verification",
270
+ },
271
+ txsync: {
272
+ status: {
273
+ type: String,
274
+ enum: ["pending", "synced", "failed", "not-applicable"],
275
+ default: "not-applicable",
276
+ },
277
+ syncedAt: {
278
+ type: Date,
279
+ default: null,
280
+ },
281
+ etimsInvoiceNo: {
282
+ type: String,
283
+ default: null,
284
+ },
285
+ sdcId: {
286
+ type: String,
287
+ default: null,
288
+ },
289
+ receiptNo: {
290
+ type: String,
291
+ default: null,
292
+ },
293
+ errorMessage: {
294
+ type: String,
295
+ default: null,
296
+ },
297
+ attempts: {
298
+ type: Number,
299
+ default: 0,
300
+ },
301
+ lastAttemptAt: {
302
+ type: Date,
303
+ default: null,
304
+ },
305
+ },
306
+ creditNote: {
307
+ status: {
308
+ type: String,
309
+ enum: ["pending", "synced", "failed"],
310
+ default: undefined, // absent until a void triggers one
311
+ },
312
+ creditNoteTraderNo: { type: String, default: null },
313
+ etimsCreditNoteNo: { type: String, default: null },
314
+ sdcId: { type: String, default: null },
315
+ receiptNo: { type: String, default: null },
316
+ verificationUrl: { type: String, default: null },
317
+ syncedAt: { type: Date, default: null },
318
+ lastAttemptAt: { type: Date, default: null },
319
+ errorMessage: { type: String, default: null },
320
+ attempts: { type: Number, default: 0 },
321
+ },
322
+ digitax: {
323
+ synced: {
324
+ type: Boolean,
325
+ default: false
326
+ },
327
+ syncedAt: Date,
328
+ status: {
329
+ type: String,
330
+ enum: [
331
+ "PENDING",
332
+ "PROCESSING",
333
+ "SUCCESS",
334
+ "FAILED"
335
+ ],
336
+ default: "PENDING"
337
+ },
338
+ saleId: String,
339
+ traderInvoiceNumber: String,
340
+ digitaxInvoiceNumber: Number,
341
+ receiptNumber: Number,
342
+ serialNumber: String,
343
+ receiptTypeCode: String,
344
+ offlineUrl: String,
345
+ saleDetailUrl: String,
346
+ etimsUrl: String,
347
+ attempts: {
348
+ type: Number,
349
+ default: 0
350
+ },
351
+ lastAttemptAt: Date,
352
+ lastError: String,
353
+ response: mongoose.Schema.Types.Mixed
354
+ },
355
+ // New fields for double entry accounts
356
+ invoiceDoubleEntryAccount: {
357
+ type: mongoose.Schema.Types.ObjectId,
358
+ ref: "GLAccountDoubleEntries",
359
+ required: false,
360
+ },
361
+ paymentDoubleEntryAccount: {
362
+ type: mongoose.Schema.Types.ObjectId,
363
+ ref: "GLAccountDoubleEntries",
364
+ required: false,
365
+ },
366
+ // GL account details for invoice entries
367
+ accountdebitedData: {
368
+ amount: { type: Number },
369
+ description: { type: String },
370
+ isActive: { type: Boolean, default: true },
371
+ },
372
+ accountcreditedData: {
373
+ amount: { type: Number },
374
+ description: { type: String },
375
+ isActive: { type: Boolean, default: true },
376
+ },
377
+ },
378
+ {
379
+ timestamps: true,
380
+ },
381
+ );
382
+
383
+ // Add indexes for frequently queried fields
384
+ invoiceSchema.index({ accountNumber: 1 });
385
+ invoiceSchema.index({ status: 1 });
386
+ invoiceSchema.index({ "client.clientId": 1, status: 1 });
387
+ invoiceSchema.index({ "reconciliationHistory.paymentReference": 1 });
388
+ invoiceSchema.index({ issueDate: -1 });
389
+ invoiceSchema.index({ "currency.code": 1 }); // Add index for currency code
390
+ invoiceSchema.index({ "currency.id": 1 }); // Add index for currency ID
391
+ invoiceSchema.index({ "currency.code": 1, "client.clientId": 1, status: 1 }); // Compound index for currency-based queries
392
+ invoiceSchema.index({ "client.clientId": 1, balanceBroughtForward: 1 }); // Add index for finding invoices with credit balances
393
+ invoiceSchema.index({ "viewStatus.isOpened": 1 }); // Add index for view status
394
+ invoiceSchema.index({ "viewStatus.openedBy.facilityId": 1 }); // Add index for facility view tracking
395
+ // Add index for double entry accounts
396
+ invoiceSchema.index({ invoiceDoubleEntryAccount: 1 });
397
+ invoiceSchema.index({ paymentDoubleEntryAccount: 1 });
398
+ // NEW INDEXES for new fields
399
+ invoiceSchema.index({ yearMonth: 1 }); // For filtering by year-month
400
+ invoiceSchema.index({ yearMonth: 1, status: 1 }); // Combined index for monthly reports
401
+ invoiceSchema.index({ "notificationsSent.sms": 1 }); // For finding SMS sent/not sent
402
+ invoiceSchema.index({ "notificationsSent.email": 1 }); // For finding email sent/not sent
403
+ // eTims tax sync indexes
404
+ invoiceSchema.index({ "txsync.status": 1 }); // For finding invoices by sync status
405
+ invoiceSchema.index({ "txsync.etimsInvoiceNo": 1 }); // For looking up by eTims invoice number
406
+
407
+ // Add virtual field for calculating balance
408
+ invoiceSchema.virtual("calculatedBalance").get(function () {
409
+ const baseBalance = this.totalAmount - (this.amountPaid || 0);
410
+
411
+ // Add positive balanceBroughtForward (customer owes money)
412
+ if (this.balanceBroughtForward > 0) {
413
+ return baseBalance + this.balanceBroughtForward;
414
+ }
415
+
416
+ // Subtract negative balanceBroughtForward (credit)
417
+ return baseBalance;
418
+ });
419
+
420
+ // Add virtual field for credit balance
421
+ invoiceSchema.virtual("creditBalance").get(function () {
422
+ return this.balanceBroughtForward < 0
423
+ ? Math.abs(this.balanceBroughtForward)
424
+ : 0;
425
+ });
426
+
427
+ // Getter for compatible overpay field
428
+ invoiceSchema.virtual("effectiveOverpay").get(function () {
429
+ return this.balanceBroughtForward < 0
430
+ ? Math.abs(this.balanceBroughtForward)
431
+ : 0;
432
+ });
433
+
434
+ // Add virtual populate for invoice double entry account
435
+ invoiceSchema.virtual("invoiceDoubleEntry", {
436
+ ref: "GLAccountDoubleEntries",
437
+ localField: "invoiceDoubleEntryAccount",
438
+ foreignField: "_id",
439
+ justOne: true,
440
+ });
441
+
442
+ // Add virtual populate for payment double entry account
443
+ invoiceSchema.virtual("paymentDoubleEntry", {
444
+ ref: "GLAccountDoubleEntries",
445
+ localField: "paymentDoubleEntryAccount",
446
+ foreignField: "_id",
447
+ justOne: true,
448
+ });
449
+
450
+ // Add method for currency conversion if needed
451
+ invoiceSchema.methods.convertAmount = function (
452
+ amount,
453
+ fromCurrency,
454
+ toCurrency,
455
+ exchangeRate,
456
+ ) {
457
+ if (fromCurrency === toCurrency) {
458
+ return amount;
459
+ }
460
+ return amount * exchangeRate;
461
+ };
462
+
463
+ // Add static method to find invoices by currency
464
+ invoiceSchema.statics.findByCurrency = function (currencyCode) {
465
+ return this.find({ "currency.code": currencyCode.toUpperCase() });
466
+ };
467
+
468
+ // Add static method to find invoices with credit balance
469
+ invoiceSchema.statics.findWithCreditBalance = function (clientId) {
470
+ return this.find({
471
+ "client.clientId": clientId,
472
+ balanceBroughtForward: { $lt: 0 },
473
+ }).sort({ updatedAt: -1 });
474
+ };
475
+
476
+ // Add static method to calculate totals by currency
477
+ invoiceSchema.statics.calculateTotalsByCurrency = function (query = {}) {
478
+ return this.aggregate([
479
+ { $match: query },
480
+ {
481
+ $group: {
482
+ _id: "$currency.code",
483
+ totalAmount: { $sum: "$totalAmount" },
484
+ totalPaid: { $sum: "$amountPaid" },
485
+ count: { $sum: 1 },
486
+ },
487
+ },
488
+ ]);
489
+ };
490
+
491
+ // New static method to find all unviewed invoices
492
+ invoiceSchema.statics.findUnviewedInvoices = function (facilityId) {
493
+ return this.find({
494
+ "facility.id": facilityId,
495
+ "viewStatus.isOpened": false,
496
+ });
497
+ };
498
+
499
+ // NEW STATIC METHODS for new fields
500
+ // Find invoices by year-month
501
+ invoiceSchema.statics.findByYearMonth = function (yearMonth) {
502
+ return this.find({ yearMonth: yearMonth });
503
+ };
504
+
505
+ // Find invoices where notifications haven't been sent
506
+ invoiceSchema.statics.findPendingNotifications = function (facilityId) {
507
+ return this.find({
508
+ "facility.id": facilityId,
509
+ status: { $in: ["Unpaid", "Overdue"] },
510
+ $or: [
511
+ { "notificationsSent.sms": false },
512
+ { "notificationsSent.email": false },
513
+ ],
514
+ });
515
+ };
516
+
517
+ // Find invoices pending eTims sync
518
+ invoiceSchema.statics.findPendingTaxSync = function (facilityId) {
519
+ return this.find({
520
+ "facility.id": facilityId,
521
+ "txsync.status": "pending",
522
+ });
523
+ };
524
+
525
+ // Find invoices with failed eTims sync
526
+ invoiceSchema.statics.findFailedTaxSync = function (facilityId) {
527
+ return this.find({
528
+ "facility.id": facilityId,
529
+ "txsync.status": "failed",
530
+ });
531
+ };
532
+
533
+ // Pre-save middleware to ensure overpay and balanceBroughtForward stay in sync during transition
534
+ invoiceSchema.pre("save", function (next) {
535
+
536
+ if (this.taxes && this.taxes.length > 0) {
537
+ this.tax = Math.round(
538
+ this.taxes.reduce((sum, t) => sum + (t.amount || 0), 0) * 100
539
+ ) / 100;
540
+ }
541
+
542
+ // If balanceBroughtForward is negative (credit), sync with overpay for backwards compatibility
543
+ if (this.balanceBroughtForward < 0) {
544
+ this.overpay = Math.abs(this.balanceBroughtForward);
545
+ } else {
546
+ this.overpay = 0; // No overpay if there's no negative balance
547
+ }
548
+
549
+ // NEW: Auto-generate yearMonth from issueDate if not provided
550
+ if (!this.yearMonth && this.issueDate) {
551
+ const year = this.issueDate.getFullYear();
552
+ const month = String(this.issueDate.getMonth() + 1).padStart(2, "0");
553
+ this.yearMonth = `${year}-${month}`;
554
+ }
555
+
556
+ next();
557
+ });
558
+
559
+ const Invoice = mongoose.model("Invoice", invoiceSchema);
560
+
561
+ module.exports = Invoice;