payservedb 8.7.0 → 8.7.2

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 (186) hide show
  1. package/.env +2 -2
  2. package/ZOHO_INTEGRATION_SCHEMA.md +644 -644
  3. package/index.js +319 -319
  4. package/package.json +17 -17
  5. package/src/models/account.js +52 -52
  6. package/src/models/agent_departments.js +59 -59
  7. package/src/models/agent_notifications.js +53 -53
  8. package/src/models/agent_performance.js +127 -127
  9. package/src/models/agent_roles.js +77 -77
  10. package/src/models/agents.js +154 -154
  11. package/src/models/apilog.js +18 -18
  12. package/src/models/approvalsWorkflows.js +49 -49
  13. package/src/models/archivedapilog.js +18 -18
  14. package/src/models/asset.js +92 -92
  15. package/src/models/assetsAssignment.js +64 -64
  16. package/src/models/auditTrail.js +346 -346
  17. package/src/models/bankdetails.js +47 -47
  18. package/src/models/billerAddress.js +124 -124
  19. package/src/models/booking_invoice.js +165 -165
  20. package/src/models/bookinganalytics.js +63 -63
  21. package/src/models/bookingconfig.js +45 -45
  22. package/src/models/bookingproperty.js +179 -179
  23. package/src/models/bookingreservation.js +239 -239
  24. package/src/models/bookingrevenuerecord.js +84 -84
  25. package/src/models/budget.js +95 -95
  26. package/src/models/budgetCategory.js +19 -19
  27. package/src/models/campaigns.js +108 -108
  28. package/src/models/cashpayment.js +291 -291
  29. package/src/models/combinedUnits.js +62 -62
  30. package/src/models/combined_invoice.js +424 -424
  31. package/src/models/common_area_electricity.js +38 -38
  32. package/src/models/common_area_generator.js +41 -41
  33. package/src/models/common_area_utility_alert.js +37 -37
  34. package/src/models/common_area_water.js +39 -39
  35. package/src/models/communication_status.js +33 -33
  36. package/src/models/communication_user_opt.js +32 -32
  37. package/src/models/community_guidelines.js +35 -35
  38. package/src/models/company.js +53 -53
  39. package/src/models/coreBaseSettings.js +16 -16
  40. package/src/models/coreInvoiceSettings.js +100 -100
  41. package/src/models/counter_schema.js +21 -21
  42. package/src/models/country_tax.js +42 -42
  43. package/src/models/currency_settings.js +39 -39
  44. package/src/models/customer.js +214 -214
  45. package/src/models/customer_satisfaction_survey.js +278 -278
  46. package/src/models/customer_surveys.js +139 -139
  47. package/src/models/customer_tickets.js +239 -239
  48. package/src/models/dailyChecklist.js +312 -312
  49. package/src/models/default_payment_details.js +17 -17
  50. package/src/models/deliveryTimeMarks.js +18 -18
  51. package/src/models/document_type.js +19 -19
  52. package/src/models/dutyRosterChecklist.js +250 -250
  53. package/src/models/dutyroster.js +136 -136
  54. package/src/models/email.js +37 -37
  55. package/src/models/email_sms_queue.js +61 -61
  56. package/src/models/entry_exit.js +53 -53
  57. package/src/models/expense.js +99 -99
  58. package/src/models/expense_category.js +45 -45
  59. package/src/models/facility.js +71 -71
  60. package/src/models/facilityBillingPrices.js +29 -29
  61. package/src/models/facilityInvoice.js +240 -240
  62. package/src/models/facilityInvoicePayment.js +52 -52
  63. package/src/models/facilityInvoiceRecipient.js +32 -32
  64. package/src/models/facilityWalletTransactionsMetadata.js +236 -236
  65. package/src/models/facility_departements.js +20 -20
  66. package/src/models/facility_payment_details.js +20 -20
  67. package/src/models/facility_rating.js +78 -78
  68. package/src/models/facilityasset.js +25 -25
  69. package/src/models/faq.js +14 -14
  70. package/src/models/gl_account_double_entries.js +25 -25
  71. package/src/models/gl_accounts.js +56 -56
  72. package/src/models/gl_entries.js +49 -49
  73. package/src/models/goodsReceivedNotes.js +115 -115
  74. package/src/models/guard.js +47 -47
  75. package/src/models/handover.js +258 -258
  76. package/src/models/inspection_category.js +38 -38
  77. package/src/models/invoice.js +480 -480
  78. package/src/models/invoice_generation_approval.js +86 -86
  79. package/src/models/invoicing_schedule.js +40 -40
  80. package/src/models/item_inspection.js +96 -96
  81. package/src/models/knowledge_base.js +109 -109
  82. package/src/models/knowledge_base_rating.js +44 -44
  83. package/src/models/leaseagreement.js +237 -237
  84. package/src/models/leasetemplate.js +17 -17
  85. package/src/models/levy.js +223 -223
  86. package/src/models/levy_invoice_settings.js +26 -26
  87. package/src/models/levycontract.js +210 -210
  88. package/src/models/levytype.js +23 -23
  89. package/src/models/maintenance_service_vendor.js +38 -38
  90. package/src/models/maintenance_services.js +17 -17
  91. package/src/models/maintenancerequisition.js +31 -31
  92. package/src/models/master_workplan.js +32 -32
  93. package/src/models/master_workplan_child.js +34 -34
  94. package/src/models/message.js +38 -38
  95. package/src/models/module.js +21 -21
  96. package/src/models/notification.js +44 -44
  97. package/src/models/paymentTermsMarks.js +19 -19
  98. package/src/models/penalty.js +76 -76
  99. package/src/models/pendingCredentials.js +32 -32
  100. package/src/models/powerMeterCommunicationProtocol.js +17 -17
  101. package/src/models/powerMeterCustomerAccount.js +78 -78
  102. package/src/models/powerMeterCustomerBand.js +14 -14
  103. package/src/models/powerMeterDailyReading.js +30 -30
  104. package/src/models/powerMeterGateways.js +40 -40
  105. package/src/models/powerMeterMonthlyReading.js +34 -34
  106. package/src/models/powerMeterPowerCharges.js +85 -85
  107. package/src/models/powerMeterSettings.js +159 -159
  108. package/src/models/powerMeterSingleDayReading.js +32 -32
  109. package/src/models/powerMeters.js +116 -116
  110. package/src/models/powerMetersManufacturer.js +14 -14
  111. package/src/models/power_meter_account.js +81 -81
  112. package/src/models/power_meter_command_logs.js +30 -30
  113. package/src/models/power_meter_command_queue.js +33 -33
  114. package/src/models/power_meter_negative_balance.js +44 -44
  115. package/src/models/power_prepaid_credits.js +47 -47
  116. package/src/models/power_prepaid_debits.js +53 -53
  117. package/src/models/power_prepaid_orders.js +78 -78
  118. package/src/models/power_sms_notification.js +26 -26
  119. package/src/models/privacy_policy.js +19 -19
  120. package/src/models/propertyManagerContract.js +556 -556
  121. package/src/models/propertyManagerRevenue.js +195 -195
  122. package/src/models/purchaseOrderInvoice.js +74 -74
  123. package/src/models/purchase_order.js +213 -213
  124. package/src/models/purchase_request.js +110 -110
  125. package/src/models/quickbooks_config.js +52 -41
  126. package/src/models/refresh_token.js +23 -23
  127. package/src/models/reminder.js +197 -197
  128. package/src/models/report.js +13 -13
  129. package/src/models/resident.js +121 -121
  130. package/src/models/rfq_details.js +131 -131
  131. package/src/models/rfq_response.js +153 -153
  132. package/src/models/service_charge_invoice_upload.js +42 -42
  133. package/src/models/service_charge_payments.js +27 -27
  134. package/src/models/servicerequest.js +55 -55
  135. package/src/models/settings.js +62 -62
  136. package/src/models/short_urls.js +21 -21
  137. package/src/models/smart_meter_daily_consumption.js +44 -44
  138. package/src/models/sms_africastalking.js +20 -20
  139. package/src/models/sms_balance_notification.js +26 -26
  140. package/src/models/sms_meliora.js +20 -20
  141. package/src/models/staff.js +36 -36
  142. package/src/models/stocksandspare.js +161 -161
  143. package/src/models/suppliers.js +74 -74
  144. package/src/models/terms_and_conditions.js +19 -19
  145. package/src/models/tickets.js +186 -186
  146. package/src/models/tickets_category.js +72 -72
  147. package/src/models/unitManagementTemplate.js +44 -44
  148. package/src/models/unitasset.js +25 -25
  149. package/src/models/units.js +118 -118
  150. package/src/models/user.js +185 -185
  151. package/src/models/valueaddedservices.js +50 -79
  152. package/src/models/vas_invoices_upload.js +50 -50
  153. package/src/models/vas_payments.js +24 -24
  154. package/src/models/vasinvoice.js +192 -192
  155. package/src/models/vasvendor.js +57 -57
  156. package/src/models/visitLog.js +95 -95
  157. package/src/models/visitor.js +67 -67
  158. package/src/models/waitlist.js +45 -45
  159. package/src/models/wallet.js +44 -44
  160. package/src/models/wallet_transactions.js +50 -50
  161. package/src/models/water_invoice.js +351 -351
  162. package/src/models/water_meter_Command_Queue.js +33 -33
  163. package/src/models/water_meter_account.js +86 -86
  164. package/src/models/water_meter_billing.js +58 -58
  165. package/src/models/water_meter_combined_accounts.js +92 -92
  166. package/src/models/water_meter_communication.js +17 -17
  167. package/src/models/water_meter_communication_logs.js +39 -39
  168. package/src/models/water_meter_concentrator.js +70 -70
  169. package/src/models/water_meter_daily_history.js +32 -32
  170. package/src/models/water_meter_high_risk.js +36 -36
  171. package/src/models/water_meter_iot_cards.js +34 -34
  172. package/src/models/water_meter_loan_deduction.js +134 -134
  173. package/src/models/water_meter_manufacturer.js +35 -35
  174. package/src/models/water_meter_monthly_history.js +36 -36
  175. package/src/models/water_meter_negative_amounts.js +44 -44
  176. package/src/models/water_meter_settings.js +290 -290
  177. package/src/models/water_meter_single_day_history.js +34 -34
  178. package/src/models/water_meter_size.js +15 -15
  179. package/src/models/water_meters.js +133 -133
  180. package/src/models/water_meters_delivery.js +76 -76
  181. package/src/models/water_prepaid_credit.js +47 -47
  182. package/src/models/water_prepaid_debit.js +50 -50
  183. package/src/models/workorder.js +49 -49
  184. package/src/models/zohoAccount.js +453 -453
  185. package/src/models/zohoIntegration.js +262 -262
  186. package/src/models/zohoItem.js +504 -504
@@ -1,453 +1,453 @@
1
- const mongoose = require("mongoose");
2
-
3
- const ZohoAccountSchema = new mongoose.Schema(
4
- {
5
- facilityId: {
6
- type: mongoose.Schema.Types.ObjectId,
7
- ref: "Facility",
8
- required: [true, "Facility ID is required"],
9
- index: true,
10
- },
11
-
12
- // Account Identification
13
- accountName: {
14
- type: String,
15
- required: [true, "Account name is required"],
16
- trim: true,
17
- maxlength: [255, "Account name cannot exceed 255 characters"],
18
- index: true,
19
- },
20
- accountCode: {
21
- type: String,
22
- trim: true,
23
- sparse: true,
24
- default: null,
25
- index: true,
26
- },
27
- description: {
28
- type: String,
29
- trim: true,
30
- maxlength: [1000, "Description cannot exceed 1000 characters"],
31
- default: null,
32
- },
33
-
34
- // Account Classification
35
- accountType: {
36
- type: String,
37
- required: [true, "Account type is required"],
38
- enum: ["income", "expense", "asset", "liability", "equity"],
39
- index: true,
40
- },
41
- accountSubType: {
42
- type: String,
43
- trim: true,
44
- default: null,
45
- },
46
-
47
- // Account Hierarchy
48
- parentAccountId: {
49
- type: mongoose.Schema.Types.ObjectId,
50
- ref: "ZohoAccount",
51
- default: null,
52
- index: true,
53
- },
54
- zohoParentAccountId: {
55
- type: String,
56
- trim: true,
57
- default: null,
58
- },
59
- isSubAccount: {
60
- type: Boolean,
61
- default: false,
62
- index: true,
63
- },
64
- depth: {
65
- type: Number,
66
- default: 0,
67
- min: [0, "Depth cannot be negative"],
68
- },
69
-
70
- // Zoho Sync Fields
71
- zohoAccountId: {
72
- type: String,
73
- trim: true,
74
- unique: true,
75
- sparse: true,
76
- default: null,
77
- index: true,
78
- },
79
- zohoCurrencyId: {
80
- type: String,
81
- trim: true,
82
- default: null,
83
- },
84
-
85
- // Financial Settings
86
- currencyCode: {
87
- type: String,
88
- trim: true,
89
- uppercase: true,
90
- default: "KES",
91
- maxlength: [3, "Currency code must be 3 characters"],
92
- },
93
- openingBalance: {
94
- type: Number,
95
- default: 0,
96
- },
97
- openingBalanceDate: {
98
- type: Date,
99
- default: null,
100
- },
101
- currentBalance: {
102
- type: Number,
103
- default: 0,
104
- },
105
- lastBalanceUpdate: {
106
- type: Date,
107
- default: null,
108
- },
109
-
110
- // Account Settings
111
- isActive: {
112
- type: Boolean,
113
- default: true,
114
- index: true,
115
- },
116
- isSystemAccount: {
117
- type: Boolean,
118
- default: false,
119
- },
120
- canBeDeleted: {
121
- type: Boolean,
122
- default: true,
123
- },
124
- showInPortal: {
125
- type: Boolean,
126
- default: false,
127
- },
128
-
129
- // Usage Tracking
130
- usageCount: {
131
- type: Number,
132
- default: 0,
133
- min: [0, "Usage count cannot be negative"],
134
- },
135
- lastUsedAt: {
136
- type: Date,
137
- default: null,
138
- },
139
- linkedItemsCount: {
140
- type: Number,
141
- default: 0,
142
- min: [0, "Linked items count cannot be negative"],
143
- },
144
-
145
- // Sync Status
146
- isSynced: {
147
- type: Boolean,
148
- default: false,
149
- index: true,
150
- },
151
- lastSyncedAt: {
152
- type: Date,
153
- default: null,
154
- },
155
- syncStatus: {
156
- type: String,
157
- enum: ["pending", "syncing", "synced", "failed"],
158
- default: "pending",
159
- index: true,
160
- },
161
- syncError: {
162
- type: String,
163
- trim: true,
164
- default: null,
165
- },
166
- lastSyncAttemptAt: {
167
- type: Date,
168
- default: null,
169
- },
170
-
171
- // Audit Fields
172
- createdBy: {
173
- type: mongoose.Schema.Types.ObjectId,
174
- ref: "User",
175
- default: null,
176
- },
177
- updatedBy: {
178
- type: mongoose.Schema.Types.ObjectId,
179
- ref: "User",
180
- default: null,
181
- },
182
- lastModifiedBy: {
183
- type: mongoose.Schema.Types.ObjectId,
184
- ref: "User",
185
- default: null,
186
- },
187
-
188
- // Metadata
189
- notes: {
190
- type: String,
191
- trim: true,
192
- maxlength: [1000, "Notes cannot exceed 1000 characters"],
193
- default: null,
194
- },
195
- metadata: {
196
- type: mongoose.Schema.Types.Mixed,
197
- default: {},
198
- },
199
-
200
- // Zoho Specific Fields
201
- zohoAccountNumber: {
202
- type: String,
203
- trim: true,
204
- default: null,
205
- },
206
- zohoDepth: {
207
- type: Number,
208
- default: null,
209
- },
210
- zohoHasAttachment: {
211
- type: Boolean,
212
- default: false,
213
- },
214
- },
215
- {
216
- timestamps: true,
217
- }
218
- );
219
-
220
- // Compound Indexes
221
- ZohoAccountSchema.index({ facilityId: 1, accountName: 1 });
222
- ZohoAccountSchema.index({ facilityId: 1, accountType: 1 });
223
- ZohoAccountSchema.index({ facilityId: 1, isActive: 1 });
224
- ZohoAccountSchema.index({ facilityId: 1, isSynced: 1 });
225
- ZohoAccountSchema.index({ facilityId: 1, accountType: 1, isActive: 1 });
226
- ZohoAccountSchema.index({ zohoAccountId: 1, facilityId: 1 });
227
-
228
- // Text index for searching
229
- ZohoAccountSchema.index({
230
- accountName: "text",
231
- description: "text",
232
- accountCode: "text",
233
- });
234
-
235
- // Virtual for full account path (for sub-accounts)
236
- ZohoAccountSchema.virtual("fullPath").get(function () {
237
- if (this.parentAccountId) {
238
- return `${this.parentAccountId.accountName} > ${this.accountName}`;
239
- }
240
- return this.accountName;
241
- });
242
-
243
- // Virtual for sync status indicator
244
- ZohoAccountSchema.virtual("needsSync").get(function () {
245
- if (!this.zohoAccountId) return true;
246
- if (!this.isSynced) return true;
247
- return false;
248
- });
249
-
250
- // Method to mark as synced
251
- ZohoAccountSchema.methods.markAsSynced = function (zohoAccountId, zohoData = {}) {
252
- this.zohoAccountId = zohoAccountId;
253
- this.isSynced = true;
254
- this.lastSyncedAt = new Date();
255
- this.syncStatus = "synced";
256
- this.syncError = null;
257
-
258
- // Update Zoho-specific fields if provided
259
- if (zohoData.currencyId) this.zohoCurrencyId = zohoData.currencyId;
260
- if (zohoData.parentAccountId) this.zohoParentAccountId = zohoData.parentAccountId;
261
- if (zohoData.accountNumber) this.zohoAccountNumber = zohoData.accountNumber;
262
- if (zohoData.depth !== undefined) this.zohoDepth = zohoData.depth;
263
-
264
- return this.save();
265
- };
266
-
267
- // Method to mark sync as failed
268
- ZohoAccountSchema.methods.markSyncFailed = function (errorMessage) {
269
- this.syncStatus = "failed";
270
- this.syncError = errorMessage;
271
- this.lastSyncAttemptAt = new Date();
272
- return this.save();
273
- };
274
-
275
- // Method to increment usage count
276
- ZohoAccountSchema.methods.incrementUsage = function () {
277
- this.usageCount += 1;
278
- this.lastUsedAt = new Date();
279
- return this.save();
280
- };
281
-
282
- // Method to update balance
283
- ZohoAccountSchema.methods.updateBalance = function (newBalance) {
284
- this.currentBalance = newBalance;
285
- this.lastBalanceUpdate = new Date();
286
- return this.save();
287
- };
288
-
289
- // Method to activate account
290
- ZohoAccountSchema.methods.activate = function () {
291
- this.isActive = true;
292
- return this.save();
293
- };
294
-
295
- // Method to deactivate account
296
- ZohoAccountSchema.methods.deactivate = function () {
297
- this.isActive = false;
298
- return this.save();
299
- };
300
-
301
- // Static method to find accounts by type
302
- ZohoAccountSchema.statics.findByType = function (facilityId, accountType) {
303
- return this.find({
304
- facilityId,
305
- accountType,
306
- isActive: true,
307
- }).sort({ accountName: 1 });
308
- };
309
-
310
- // Static method to find income accounts (for items)
311
- ZohoAccountSchema.statics.findIncomeAccounts = function (facilityId) {
312
- return this.find({
313
- facilityId,
314
- accountType: "income",
315
- isActive: true,
316
- }).sort({ accountName: 1 });
317
- };
318
-
319
- // Static method to find expense accounts
320
- ZohoAccountSchema.statics.findExpenseAccounts = function (facilityId) {
321
- return this.find({
322
- facilityId,
323
- accountType: "expense",
324
- isActive: true,
325
- }).sort({ accountName: 1 });
326
- };
327
-
328
- // Static method to find unsynced accounts
329
- ZohoAccountSchema.statics.findUnsynced = function (facilityId) {
330
- return this.find({
331
- facilityId,
332
- $or: [{ isSynced: false }, { zohoAccountId: null }],
333
- isActive: true,
334
- }).sort({ createdAt: 1 });
335
- };
336
-
337
- // Static method to search accounts
338
- ZohoAccountSchema.statics.searchAccounts = function (facilityId, searchText) {
339
- return this.find({
340
- facilityId,
341
- isActive: true,
342
- $text: { $search: searchText },
343
- }).sort({ score: { $meta: "textScore" } });
344
- };
345
-
346
- // Pre-save hook to update timestamps
347
- ZohoAccountSchema.pre("save", function (next) {
348
- if (this.isModified() && !this.isNew) {
349
- this.updatedAt = new Date();
350
- }
351
- next();
352
- });
353
-
354
- // Pre-save validation
355
- ZohoAccountSchema.pre("save", function (next) {
356
- // Validate sub-account
357
- if (this.parentAccountId && !this.isSubAccount) {
358
- this.isSubAccount = true;
359
- }
360
- if (!this.parentAccountId && this.isSubAccount) {
361
- this.isSubAccount = false;
362
- }
363
-
364
- // System accounts cannot be deleted
365
- if (this.isSystemAccount) {
366
- this.canBeDeleted = false;
367
- }
368
-
369
- next();
370
- });
371
-
372
- // Instance method to convert to Zoho format
373
- ZohoAccountSchema.methods.toZohoFormat = function () {
374
- const zohoAccount = {
375
- account_name: this.accountName,
376
- account_type: this.accountType,
377
- };
378
-
379
- // Add optional fields
380
- if (this.accountCode) {
381
- zohoAccount.account_code = this.accountCode;
382
- }
383
- if (this.description) {
384
- zohoAccount.description = this.description;
385
- }
386
- if (this.zohoParentAccountId) {
387
- zohoAccount.parent_account_id = this.zohoParentAccountId;
388
- }
389
- if (this.currencyCode) {
390
- zohoAccount.currency_code = this.currencyCode;
391
- }
392
-
393
- return zohoAccount;
394
- };
395
-
396
- // Instance method to update from Zoho data
397
- ZohoAccountSchema.methods.updateFromZoho = function (zohoData) {
398
- if (zohoData.account_id) this.zohoAccountId = zohoData.account_id;
399
- if (zohoData.account_name) this.accountName = zohoData.account_name;
400
- if (zohoData.account_code) this.accountCode = zohoData.account_code;
401
- if (zohoData.account_type) this.accountType = zohoData.account_type;
402
- if (zohoData.account_number) this.zohoAccountNumber = zohoData.account_number;
403
- if (zohoData.description) this.description = zohoData.description;
404
- if (zohoData.is_active !== undefined) this.isActive = zohoData.is_active;
405
- if (zohoData.currency_id) this.zohoCurrencyId = zohoData.currency_id;
406
- if (zohoData.currency_code) this.currencyCode = zohoData.currency_code;
407
- if (zohoData.parent_account_id) this.zohoParentAccountId = zohoData.parent_account_id;
408
- if (zohoData.depth !== undefined) {
409
- this.depth = zohoData.depth;
410
- this.zohoDepth = zohoData.depth;
411
- }
412
-
413
- this.isSynced = true;
414
- this.lastSyncedAt = new Date();
415
- this.syncStatus = "synced";
416
-
417
- return this.save();
418
- };
419
-
420
- // Static method to build account hierarchy
421
- ZohoAccountSchema.statics.getAccountTree = async function (facilityId) {
422
- const accounts = await this.find({ facilityId, isActive: true })
423
- .populate("parentAccountId")
424
- .sort({ accountType: 1, accountName: 1 });
425
-
426
- // Build tree structure
427
- const accountMap = {};
428
- const tree = [];
429
-
430
- accounts.forEach((account) => {
431
- accountMap[account._id] = {
432
- ...account.toObject(),
433
- children: [],
434
- };
435
- });
436
-
437
- accounts.forEach((account) => {
438
- if (account.parentAccountId) {
439
- const parent = accountMap[account.parentAccountId];
440
- if (parent) {
441
- parent.children.push(accountMap[account._id]);
442
- }
443
- } else {
444
- tree.push(accountMap[account._id]);
445
- }
446
- });
447
-
448
- return tree;
449
- };
450
-
451
- const ZohoAccount = mongoose.model("ZohoAccount", ZohoAccountSchema);
452
-
453
- module.exports = ZohoAccount;
1
+ const mongoose = require("mongoose");
2
+
3
+ const ZohoAccountSchema = new mongoose.Schema(
4
+ {
5
+ facilityId: {
6
+ type: mongoose.Schema.Types.ObjectId,
7
+ ref: "Facility",
8
+ required: [true, "Facility ID is required"],
9
+ index: true,
10
+ },
11
+
12
+ // Account Identification
13
+ accountName: {
14
+ type: String,
15
+ required: [true, "Account name is required"],
16
+ trim: true,
17
+ maxlength: [255, "Account name cannot exceed 255 characters"],
18
+ index: true,
19
+ },
20
+ accountCode: {
21
+ type: String,
22
+ trim: true,
23
+ sparse: true,
24
+ default: null,
25
+ index: true,
26
+ },
27
+ description: {
28
+ type: String,
29
+ trim: true,
30
+ maxlength: [1000, "Description cannot exceed 1000 characters"],
31
+ default: null,
32
+ },
33
+
34
+ // Account Classification
35
+ accountType: {
36
+ type: String,
37
+ required: [true, "Account type is required"],
38
+ enum: ["income", "expense", "asset", "liability", "equity"],
39
+ index: true,
40
+ },
41
+ accountSubType: {
42
+ type: String,
43
+ trim: true,
44
+ default: null,
45
+ },
46
+
47
+ // Account Hierarchy
48
+ parentAccountId: {
49
+ type: mongoose.Schema.Types.ObjectId,
50
+ ref: "ZohoAccount",
51
+ default: null,
52
+ index: true,
53
+ },
54
+ zohoParentAccountId: {
55
+ type: String,
56
+ trim: true,
57
+ default: null,
58
+ },
59
+ isSubAccount: {
60
+ type: Boolean,
61
+ default: false,
62
+ index: true,
63
+ },
64
+ depth: {
65
+ type: Number,
66
+ default: 0,
67
+ min: [0, "Depth cannot be negative"],
68
+ },
69
+
70
+ // Zoho Sync Fields
71
+ zohoAccountId: {
72
+ type: String,
73
+ trim: true,
74
+ unique: true,
75
+ sparse: true,
76
+ default: null,
77
+ index: true,
78
+ },
79
+ zohoCurrencyId: {
80
+ type: String,
81
+ trim: true,
82
+ default: null,
83
+ },
84
+
85
+ // Financial Settings
86
+ currencyCode: {
87
+ type: String,
88
+ trim: true,
89
+ uppercase: true,
90
+ default: "KES",
91
+ maxlength: [3, "Currency code must be 3 characters"],
92
+ },
93
+ openingBalance: {
94
+ type: Number,
95
+ default: 0,
96
+ },
97
+ openingBalanceDate: {
98
+ type: Date,
99
+ default: null,
100
+ },
101
+ currentBalance: {
102
+ type: Number,
103
+ default: 0,
104
+ },
105
+ lastBalanceUpdate: {
106
+ type: Date,
107
+ default: null,
108
+ },
109
+
110
+ // Account Settings
111
+ isActive: {
112
+ type: Boolean,
113
+ default: true,
114
+ index: true,
115
+ },
116
+ isSystemAccount: {
117
+ type: Boolean,
118
+ default: false,
119
+ },
120
+ canBeDeleted: {
121
+ type: Boolean,
122
+ default: true,
123
+ },
124
+ showInPortal: {
125
+ type: Boolean,
126
+ default: false,
127
+ },
128
+
129
+ // Usage Tracking
130
+ usageCount: {
131
+ type: Number,
132
+ default: 0,
133
+ min: [0, "Usage count cannot be negative"],
134
+ },
135
+ lastUsedAt: {
136
+ type: Date,
137
+ default: null,
138
+ },
139
+ linkedItemsCount: {
140
+ type: Number,
141
+ default: 0,
142
+ min: [0, "Linked items count cannot be negative"],
143
+ },
144
+
145
+ // Sync Status
146
+ isSynced: {
147
+ type: Boolean,
148
+ default: false,
149
+ index: true,
150
+ },
151
+ lastSyncedAt: {
152
+ type: Date,
153
+ default: null,
154
+ },
155
+ syncStatus: {
156
+ type: String,
157
+ enum: ["pending", "syncing", "synced", "failed"],
158
+ default: "pending",
159
+ index: true,
160
+ },
161
+ syncError: {
162
+ type: String,
163
+ trim: true,
164
+ default: null,
165
+ },
166
+ lastSyncAttemptAt: {
167
+ type: Date,
168
+ default: null,
169
+ },
170
+
171
+ // Audit Fields
172
+ createdBy: {
173
+ type: mongoose.Schema.Types.ObjectId,
174
+ ref: "User",
175
+ default: null,
176
+ },
177
+ updatedBy: {
178
+ type: mongoose.Schema.Types.ObjectId,
179
+ ref: "User",
180
+ default: null,
181
+ },
182
+ lastModifiedBy: {
183
+ type: mongoose.Schema.Types.ObjectId,
184
+ ref: "User",
185
+ default: null,
186
+ },
187
+
188
+ // Metadata
189
+ notes: {
190
+ type: String,
191
+ trim: true,
192
+ maxlength: [1000, "Notes cannot exceed 1000 characters"],
193
+ default: null,
194
+ },
195
+ metadata: {
196
+ type: mongoose.Schema.Types.Mixed,
197
+ default: {},
198
+ },
199
+
200
+ // Zoho Specific Fields
201
+ zohoAccountNumber: {
202
+ type: String,
203
+ trim: true,
204
+ default: null,
205
+ },
206
+ zohoDepth: {
207
+ type: Number,
208
+ default: null,
209
+ },
210
+ zohoHasAttachment: {
211
+ type: Boolean,
212
+ default: false,
213
+ },
214
+ },
215
+ {
216
+ timestamps: true,
217
+ }
218
+ );
219
+
220
+ // Compound Indexes
221
+ ZohoAccountSchema.index({ facilityId: 1, accountName: 1 });
222
+ ZohoAccountSchema.index({ facilityId: 1, accountType: 1 });
223
+ ZohoAccountSchema.index({ facilityId: 1, isActive: 1 });
224
+ ZohoAccountSchema.index({ facilityId: 1, isSynced: 1 });
225
+ ZohoAccountSchema.index({ facilityId: 1, accountType: 1, isActive: 1 });
226
+ ZohoAccountSchema.index({ zohoAccountId: 1, facilityId: 1 });
227
+
228
+ // Text index for searching
229
+ ZohoAccountSchema.index({
230
+ accountName: "text",
231
+ description: "text",
232
+ accountCode: "text",
233
+ });
234
+
235
+ // Virtual for full account path (for sub-accounts)
236
+ ZohoAccountSchema.virtual("fullPath").get(function () {
237
+ if (this.parentAccountId) {
238
+ return `${this.parentAccountId.accountName} > ${this.accountName}`;
239
+ }
240
+ return this.accountName;
241
+ });
242
+
243
+ // Virtual for sync status indicator
244
+ ZohoAccountSchema.virtual("needsSync").get(function () {
245
+ if (!this.zohoAccountId) return true;
246
+ if (!this.isSynced) return true;
247
+ return false;
248
+ });
249
+
250
+ // Method to mark as synced
251
+ ZohoAccountSchema.methods.markAsSynced = function (zohoAccountId, zohoData = {}) {
252
+ this.zohoAccountId = zohoAccountId;
253
+ this.isSynced = true;
254
+ this.lastSyncedAt = new Date();
255
+ this.syncStatus = "synced";
256
+ this.syncError = null;
257
+
258
+ // Update Zoho-specific fields if provided
259
+ if (zohoData.currencyId) this.zohoCurrencyId = zohoData.currencyId;
260
+ if (zohoData.parentAccountId) this.zohoParentAccountId = zohoData.parentAccountId;
261
+ if (zohoData.accountNumber) this.zohoAccountNumber = zohoData.accountNumber;
262
+ if (zohoData.depth !== undefined) this.zohoDepth = zohoData.depth;
263
+
264
+ return this.save();
265
+ };
266
+
267
+ // Method to mark sync as failed
268
+ ZohoAccountSchema.methods.markSyncFailed = function (errorMessage) {
269
+ this.syncStatus = "failed";
270
+ this.syncError = errorMessage;
271
+ this.lastSyncAttemptAt = new Date();
272
+ return this.save();
273
+ };
274
+
275
+ // Method to increment usage count
276
+ ZohoAccountSchema.methods.incrementUsage = function () {
277
+ this.usageCount += 1;
278
+ this.lastUsedAt = new Date();
279
+ return this.save();
280
+ };
281
+
282
+ // Method to update balance
283
+ ZohoAccountSchema.methods.updateBalance = function (newBalance) {
284
+ this.currentBalance = newBalance;
285
+ this.lastBalanceUpdate = new Date();
286
+ return this.save();
287
+ };
288
+
289
+ // Method to activate account
290
+ ZohoAccountSchema.methods.activate = function () {
291
+ this.isActive = true;
292
+ return this.save();
293
+ };
294
+
295
+ // Method to deactivate account
296
+ ZohoAccountSchema.methods.deactivate = function () {
297
+ this.isActive = false;
298
+ return this.save();
299
+ };
300
+
301
+ // Static method to find accounts by type
302
+ ZohoAccountSchema.statics.findByType = function (facilityId, accountType) {
303
+ return this.find({
304
+ facilityId,
305
+ accountType,
306
+ isActive: true,
307
+ }).sort({ accountName: 1 });
308
+ };
309
+
310
+ // Static method to find income accounts (for items)
311
+ ZohoAccountSchema.statics.findIncomeAccounts = function (facilityId) {
312
+ return this.find({
313
+ facilityId,
314
+ accountType: "income",
315
+ isActive: true,
316
+ }).sort({ accountName: 1 });
317
+ };
318
+
319
+ // Static method to find expense accounts
320
+ ZohoAccountSchema.statics.findExpenseAccounts = function (facilityId) {
321
+ return this.find({
322
+ facilityId,
323
+ accountType: "expense",
324
+ isActive: true,
325
+ }).sort({ accountName: 1 });
326
+ };
327
+
328
+ // Static method to find unsynced accounts
329
+ ZohoAccountSchema.statics.findUnsynced = function (facilityId) {
330
+ return this.find({
331
+ facilityId,
332
+ $or: [{ isSynced: false }, { zohoAccountId: null }],
333
+ isActive: true,
334
+ }).sort({ createdAt: 1 });
335
+ };
336
+
337
+ // Static method to search accounts
338
+ ZohoAccountSchema.statics.searchAccounts = function (facilityId, searchText) {
339
+ return this.find({
340
+ facilityId,
341
+ isActive: true,
342
+ $text: { $search: searchText },
343
+ }).sort({ score: { $meta: "textScore" } });
344
+ };
345
+
346
+ // Pre-save hook to update timestamps
347
+ ZohoAccountSchema.pre("save", function (next) {
348
+ if (this.isModified() && !this.isNew) {
349
+ this.updatedAt = new Date();
350
+ }
351
+ next();
352
+ });
353
+
354
+ // Pre-save validation
355
+ ZohoAccountSchema.pre("save", function (next) {
356
+ // Validate sub-account
357
+ if (this.parentAccountId && !this.isSubAccount) {
358
+ this.isSubAccount = true;
359
+ }
360
+ if (!this.parentAccountId && this.isSubAccount) {
361
+ this.isSubAccount = false;
362
+ }
363
+
364
+ // System accounts cannot be deleted
365
+ if (this.isSystemAccount) {
366
+ this.canBeDeleted = false;
367
+ }
368
+
369
+ next();
370
+ });
371
+
372
+ // Instance method to convert to Zoho format
373
+ ZohoAccountSchema.methods.toZohoFormat = function () {
374
+ const zohoAccount = {
375
+ account_name: this.accountName,
376
+ account_type: this.accountType,
377
+ };
378
+
379
+ // Add optional fields
380
+ if (this.accountCode) {
381
+ zohoAccount.account_code = this.accountCode;
382
+ }
383
+ if (this.description) {
384
+ zohoAccount.description = this.description;
385
+ }
386
+ if (this.zohoParentAccountId) {
387
+ zohoAccount.parent_account_id = this.zohoParentAccountId;
388
+ }
389
+ if (this.currencyCode) {
390
+ zohoAccount.currency_code = this.currencyCode;
391
+ }
392
+
393
+ return zohoAccount;
394
+ };
395
+
396
+ // Instance method to update from Zoho data
397
+ ZohoAccountSchema.methods.updateFromZoho = function (zohoData) {
398
+ if (zohoData.account_id) this.zohoAccountId = zohoData.account_id;
399
+ if (zohoData.account_name) this.accountName = zohoData.account_name;
400
+ if (zohoData.account_code) this.accountCode = zohoData.account_code;
401
+ if (zohoData.account_type) this.accountType = zohoData.account_type;
402
+ if (zohoData.account_number) this.zohoAccountNumber = zohoData.account_number;
403
+ if (zohoData.description) this.description = zohoData.description;
404
+ if (zohoData.is_active !== undefined) this.isActive = zohoData.is_active;
405
+ if (zohoData.currency_id) this.zohoCurrencyId = zohoData.currency_id;
406
+ if (zohoData.currency_code) this.currencyCode = zohoData.currency_code;
407
+ if (zohoData.parent_account_id) this.zohoParentAccountId = zohoData.parent_account_id;
408
+ if (zohoData.depth !== undefined) {
409
+ this.depth = zohoData.depth;
410
+ this.zohoDepth = zohoData.depth;
411
+ }
412
+
413
+ this.isSynced = true;
414
+ this.lastSyncedAt = new Date();
415
+ this.syncStatus = "synced";
416
+
417
+ return this.save();
418
+ };
419
+
420
+ // Static method to build account hierarchy
421
+ ZohoAccountSchema.statics.getAccountTree = async function (facilityId) {
422
+ const accounts = await this.find({ facilityId, isActive: true })
423
+ .populate("parentAccountId")
424
+ .sort({ accountType: 1, accountName: 1 });
425
+
426
+ // Build tree structure
427
+ const accountMap = {};
428
+ const tree = [];
429
+
430
+ accounts.forEach((account) => {
431
+ accountMap[account._id] = {
432
+ ...account.toObject(),
433
+ children: [],
434
+ };
435
+ });
436
+
437
+ accounts.forEach((account) => {
438
+ if (account.parentAccountId) {
439
+ const parent = accountMap[account.parentAccountId];
440
+ if (parent) {
441
+ parent.children.push(accountMap[account._id]);
442
+ }
443
+ } else {
444
+ tree.push(accountMap[account._id]);
445
+ }
446
+ });
447
+
448
+ return tree;
449
+ };
450
+
451
+ const ZohoAccount = mongoose.model("ZohoAccount", ZohoAccountSchema);
452
+
453
+ module.exports = ZohoAccount;