payservedb 9.9.2 → 9.9.4

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