payservedb 8.9.8 → 9.0.0

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