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,663 +1,663 @@
1
- const mongoose = require('mongoose');
2
- const Schema = mongoose.Schema;
3
-
4
- const PropertyManagerContractSchema = new Schema(
5
- {
6
- contractName: {
7
- type: String,
8
- required: [true, 'Contract name is required']
9
- },
10
- propertyManager: {
11
- type: mongoose.Schema.Types.ObjectId,
12
- ref: 'User', // References global User collection
13
- required: [true, 'Property manager is required']
14
- },
15
- units: [{
16
- type: mongoose.Schema.Types.ObjectId,
17
- ref: 'Unit',
18
- required: [true, 'At least one unit is required']
19
- }],
20
- customerId: {
21
- type: mongoose.Schema.Types.ObjectId,
22
- ref: 'Customer', // Can reference global or facility-specific Customer
23
- required: [true, 'Customer ID is required']
24
- },
25
- facilityId: {
26
- type: mongoose.Schema.Types.ObjectId,
27
- ref: 'Facility',
28
- required: [true, 'Facility ID is required']
29
- },
30
- digitax: {
31
-
32
- enabled: Boolean,
33
-
34
- profileId: {
35
- type: mongoose.Schema.Types.ObjectId
36
- },
37
-
38
- itemId: String,
39
-
40
- itemName: String,
41
-
42
- itemClassCode: String,
43
-
44
- taxTypeCode: String,
45
-
46
- synced: Boolean,
47
-
48
- syncedAt: Date,
49
-
50
- lastError: String
51
-
52
- },
53
- // Lease term details
54
- startDate: {
55
- type: Date,
56
- required: function () {
57
- return this.status === 'Active';
58
- }
59
- },
60
- endDate: {
61
- type: Date,
62
- required: function () {
63
- return this.status === 'Active';
64
- }
65
- },
66
- // Payment details - aligned with LeaseAgreement
67
- paymentDueDate: {
68
- type: Number,
69
- required: function () {
70
- return this.status === 'Active';
71
- },
72
- min: [1, 'Payment due date must be between 1 and 31'],
73
- max: [31, 'Payment due date must be between 1 and 31']
74
- },
75
- frequency: {
76
- type: String,
77
- enum: ['Monthly', 'Quarterly', 'Annually'],
78
- default: 'Monthly',
79
- required: function () {
80
- return this.status === 'Active';
81
- }
82
- },
83
- nextInvoiceDate: {
84
- type: Date
85
- },
86
- lastInvoiceDate: {
87
- type: Date
88
- },
89
- autoSend: {
90
- type: Boolean,
91
- default: false
92
- },
93
- balanceBroughtForward: {
94
- type: Number,
95
- default: 0
96
- },
97
- // Management fee
98
- managementFee: {
99
- type: {
100
- type: String,
101
- enum: ['percentage', 'amount'],
102
- required: [true, 'Management fee type is required']
103
- },
104
- value: {
105
- type: Number,
106
- required: [true, 'Management fee value is required'],
107
- min: [0, 'Management fee value cannot be negative'],
108
- validate: {
109
- validator: function (value) {
110
- // If type is percentage, value should not exceed 100
111
- if (this.managementFee.type === 'percentage') {
112
- return value <= 100;
113
- }
114
- return true;
115
- },
116
- message: 'Management fee percentage cannot exceed 100%'
117
- }
118
- }
119
- },
120
- // Per-contract lease commission override — when set (value present)
121
- // it takes precedence over the facility-wide
122
- // PropertyManagementSettings default. Lease commission is the
123
- // one-time fee earned when the property manager places a new
124
- // tenant (first paid rent invoice).
125
- leaseFee: {
126
- type: {
127
- type: String,
128
- enum: ['percentage', 'amount']
129
- },
130
- value: {
131
- type: Number,
132
- min: [0, 'Lease commission value cannot be negative'],
133
- validate: {
134
- validator: function (value) {
135
- if (this.leaseFee && this.leaseFee.type === 'percentage') {
136
- return value <= 100;
137
- }
138
- return true;
139
- },
140
- message: 'Lease commission percentage cannot exceed 100%'
141
- }
142
- }
143
- },
144
- // Currency for fixed-amount managementFee/leaseFee values above.
145
- // Only meaningful when the fee type is 'amount' (percentage fees are
146
- // currency-agnostic).
147
- currencyId: {
148
- type: mongoose.Schema.Types.ObjectId,
149
- ref: 'Currency'
150
- },
151
- // Booking commission by length of stay, covering every unit on this
152
- // contract. This is the ONLY place booking commission is configured
153
- // - it is deliberately NOT settable when listing/editing a unit for
154
- // booking, so a unit's commission always traces back to its property
155
- // manager contract. A unit with no covering Active contract, or a
156
- // stay length matching no tier here, earns 0 commission (no
157
- // facility-wide or per-property fallback rate).
158
- bookingCommissionTiers: [{
159
- minNights: {
160
- type: Number,
161
- required: true,
162
- min: 1
163
- },
164
- maxNights: {
165
- type: Number,
166
- min: 1
167
- },
168
- type: {
169
- type: String,
170
- enum: ['percentage', 'fixed'],
171
- default: 'percentage'
172
- },
173
- value: {
174
- type: Number,
175
- required: true,
176
- min: 0
177
- }
178
- }],
179
- // Per-unit fee overrides. Each unit in `units` may have a different
180
- // management/lease fee here; a unit with no entry here falls back to
181
- // the contract-level managementFee/leaseFee/currencyId above. This is
182
- // what lets one contract cover multiple units at different rates.
183
- unitFees: [{
184
- unitId: {
185
- type: mongoose.Schema.Types.ObjectId,
186
- ref: 'Unit',
187
- required: true
188
- },
189
- managementFee: {
190
- type: {
191
- type: String,
192
- enum: ['percentage', 'amount']
193
- },
194
- value: {
195
- type: Number,
196
- min: [0, 'Management fee value cannot be negative']
197
- }
198
- },
199
- leaseFee: {
200
- type: {
201
- type: String,
202
- enum: ['percentage', 'amount']
203
- },
204
- value: {
205
- type: Number,
206
- min: [0, 'Lease commission value cannot be negative']
207
- }
208
- },
209
- currencyId: {
210
- type: mongoose.Schema.Types.ObjectId,
211
- ref: 'Currency'
212
- }
213
- }],
214
- // GL Account configurations - updated to match sample data structure
215
- invoiceDoubleEntryAccount: {
216
- type: mongoose.Schema.Types.ObjectId,
217
- ref: 'GLAccountDoubleEntries'
218
- },
219
- paymentDoubleEntryAccount: {
220
- type: mongoose.Schema.Types.ObjectId,
221
- ref: 'GLAccountDoubleEntries'
222
- },
223
- glAccounts: {
224
- invoice: {
225
- debit: {
226
- type: mongoose.Schema.Types.ObjectId,
227
- ref: 'GLAccount'
228
- },
229
- credit: {
230
- type: mongoose.Schema.Types.ObjectId,
231
- ref: 'GLAccount'
232
- }
233
- },
234
- payment: {
235
- debit: {
236
- type: mongoose.Schema.Types.ObjectId,
237
- ref: 'GLAccount'
238
- },
239
- credit: {
240
- type: mongoose.Schema.Types.ObjectId,
241
- ref: 'GLAccount'
242
- }
243
- }
244
- },
245
- status: {
246
- type: String,
247
- enum: ['Active', 'Inactive', 'Completed', 'Suspended', 'Terminated'],
248
- // Contracts default Active on creation - billing eligibility is
249
- // driven by lease existence, not contract status. Status is now
250
- // a purely manual lifecycle field the property manager controls.
251
- default: 'Active',
252
- required: [true, 'Status is required']
253
- },
254
- createdBy: {
255
- type: mongoose.Schema.Types.ObjectId,
256
- ref: 'User' // References global User collection
257
- },
258
- // Additional fields for contract lifecycle management
259
- suspensionReason: {
260
- type: String
261
- },
262
- terminationReason: {
263
- type: String
264
- },
265
- terminationDate: {
266
- type: Date
267
- },
268
- completionDate: {
269
- type: Date
270
- }
271
- },
272
- {
273
- timestamps: true,
274
- // Ensure virtual fields are included in JSON output
275
- toJSON: { virtuals: true },
276
- toObject: { virtuals: true }
277
- }
278
- );
279
-
280
- // Enhanced pre-save validation
281
- PropertyManagerContractSchema.pre('save', function (next) {
282
- // Validate date range
283
- if (this.startDate && this.endDate && this.startDate >= this.endDate) {
284
- next(new Error('End date must be after start date'));
285
- return;
286
- }
287
-
288
- // Validate units array
289
- if (!this.units || this.units.length === 0) {
290
- next(new Error('At least one unit must be specified'));
291
- return;
292
- }
293
-
294
- // Validate management fee
295
- if (!this.managementFee || !this.managementFee.type || this.managementFee.value === undefined) {
296
- next(new Error('Management fee type and value are required'));
297
- return;
298
- }
299
-
300
- // Validate management fee percentage
301
- if (this.managementFee.type === 'percentage' && this.managementFee.value > 100) {
302
- next(new Error('Management fee percentage cannot exceed 100%'));
303
- return;
304
- }
305
-
306
- // Validate management fee value is non-negative
307
- if (this.managementFee.value < 0) {
308
- next(new Error('Management fee value cannot be negative'));
309
- return;
310
- }
311
-
312
- // Validate payment due date range
313
- if (this.paymentDueDate && (this.paymentDueDate < 1 || this.paymentDueDate > 31)) {
314
- next(new Error('Payment due date must be between 1 and 31'));
315
- return;
316
- }
317
-
318
- // Note: startDate/endDate/paymentDueDate/frequency are no longer
319
- // required for Active status - contracts are always Active regardless
320
- // of whether a lease has populated those fields yet. They remain
321
- // required only for billing (see invoice_service's eligibility checks,
322
- // which additionally require an active lease before generating an
323
- // invoice).
324
-
325
- next();
326
- });
327
-
328
- // Method to sync with lease data
329
- PropertyManagerContractSchema.methods.syncWithLeaseData = async function (leaseData) {
330
- if (!leaseData) return;
331
-
332
- // Update contract fields from lease data
333
- this.startDate = leaseData.leaseTerms?.startDate || this.startDate;
334
- this.endDate = leaseData.leaseTerms?.endDate || this.endDate;
335
- this.paymentDueDate = leaseData.financialTerms?.paymentDueDate || this.paymentDueDate;
336
- this.balanceBroughtForward = leaseData.financialTerms?.balanceBroughtForward || this.balanceBroughtForward;
337
- this.frequency = leaseData.billingCycle?.frequency || this.frequency;
338
- this.autoSend = leaseData.billingCycle?.autoSend !== undefined ? leaseData.billingCycle.autoSend : this.autoSend;
339
- this.nextInvoiceDate = leaseData.billingCycle?.nextInvoiceDate || this.nextInvoiceDate;
340
- this.lastInvoiceDate = leaseData.billingCycle?.lastInvoiceDate || this.lastInvoiceDate;
341
-
342
- // Automatically activate contract if all required fields are present
343
- if (this.startDate && this.endDate && this.paymentDueDate && this.frequency && this.status === 'Inactive') {
344
- this.status = 'Active';
345
- }
346
-
347
- return this.save();
348
- };
349
-
350
- // Method to check if contract can be activated
351
- PropertyManagerContractSchema.methods.canBeActivated = function () {
352
- return !!(this.startDate && this.endDate && this.paymentDueDate && this.frequency);
353
- };
354
-
355
- // Method to get missing required fields
356
- PropertyManagerContractSchema.methods.getMissingRequiredFields = function () {
357
- const requiredFields = ['startDate', 'endDate', 'paymentDueDate', 'frequency'];
358
- return requiredFields.filter(field => !this[field]);
359
- };
360
-
361
- // Virtual for contract completion status
362
- PropertyManagerContractSchema.virtual('isComplete').get(function () {
363
- return this.canBeActivated();
364
- });
365
-
366
- // Virtual for contract duration in days
367
- PropertyManagerContractSchema.virtual('durationInDays').get(function () {
368
- if (!this.startDate || !this.endDate) return null;
369
- const diffTime = Math.abs(this.endDate - this.startDate);
370
- return Math.ceil(diffTime / (1000 * 60 * 60 * 24));
371
- });
372
-
373
- // Virtual for contract remaining days
374
- PropertyManagerContractSchema.virtual('remainingDays').get(function () {
375
- if (!this.endDate) return null;
376
- const now = new Date();
377
- if (now > this.endDate) return 0;
378
- const diffTime = Math.abs(this.endDate - now);
379
- return Math.ceil(diffTime / (1000 * 60 * 60 * 24));
380
- });
381
-
382
- // Virtual for management fee display
383
- PropertyManagerContractSchema.virtual('managementFeeDisplay').get(function () {
384
- if (!this.managementFee) return null;
385
-
386
- if (this.managementFee.type === 'percentage') {
387
- return `${this.managementFee.value}%`;
388
- } else {
389
- return `$${this.managementFee.value.toLocaleString()}`;
390
- }
391
- });
392
-
393
- // Indexes for better query performance
394
- PropertyManagerContractSchema.index({ customerId: 1, status: 1 });
395
- PropertyManagerContractSchema.index({ facilityId: 1, status: 1 });
396
- PropertyManagerContractSchema.index({ propertyManager: 1, facilityId: 1 });
397
- PropertyManagerContractSchema.index({ units: 1, status: 1 });
398
- PropertyManagerContractSchema.index({ nextInvoiceDate: 1, status: 1 });
399
- PropertyManagerContractSchema.index({ endDate: 1, status: 1 }); // For contract expiration queries
400
- PropertyManagerContractSchema.index({ 'managementFee.type': 1, 'managementFee.value': 1 }); // For fee analysis
401
- PropertyManagerContractSchema.index({ createdAt: -1 }); // For recent contracts
402
- PropertyManagerContractSchema.index({ startDate: 1, endDate: 1 }); // For date range queries
403
-
404
- // Compound indexes for common query patterns
405
- PropertyManagerContractSchema.index({
406
- facilityId: 1,
407
- propertyManager: 1,
408
- status: 1
409
- });
410
-
411
- PropertyManagerContractSchema.index({
412
- facilityId: 1,
413
- customerId: 1,
414
- status: 1
415
- });
416
-
417
- // Text index for searching contract names
418
- PropertyManagerContractSchema.index({
419
- contractName: 'text'
420
- });
421
-
422
- // Static methods for common queries
423
- PropertyManagerContractSchema.statics.findActiveContractsByFacility = function (facilityId) {
424
- return this.find({
425
- facilityId: facilityId,
426
- status: 'Active'
427
- }).populate('propertyManager', 'fullName email')
428
- .populate('units', 'name unitType')
429
- .populate('customerId', 'firstName lastName email');
430
- };
431
-
432
- PropertyManagerContractSchema.statics.findContractsByPropertyManager = function (propertyManagerId, facilityId) {
433
- return this.find({
434
- propertyManager: propertyManagerId,
435
- facilityId: facilityId
436
- }).populate('units', 'name unitType')
437
- .populate('customerId', 'firstName lastName email')
438
- .sort({ createdAt: -1 });
439
- };
440
-
441
- PropertyManagerContractSchema.statics.findExpiringContracts = function (facilityId, daysAhead = 30) {
442
- const futureDate = new Date();
443
- futureDate.setDate(futureDate.getDate() + daysAhead);
444
-
445
- return this.find({
446
- facilityId: facilityId,
447
- status: 'Active',
448
- endDate: {
449
- $gte: new Date(),
450
- $lte: futureDate
451
- }
452
- }).populate('propertyManager', 'fullName email')
453
- .populate('units', 'name unitType')
454
- .populate('customerId', 'firstName lastName email')
455
- .sort({ endDate: 1 });
456
- };
457
-
458
- PropertyManagerContractSchema.statics.findContractsRequiringInvoicing = function (facilityId) {
459
- const today = new Date();
460
- today.setHours(0, 0, 0, 0);
461
-
462
- return this.find({
463
- facilityId: facilityId,
464
- status: 'Active',
465
- nextInvoiceDate: {
466
- $lte: today
467
- }
468
- }).populate('propertyManager', 'fullName email')
469
- .populate('units', 'name unitType')
470
- .populate('customerId', 'firstName lastName email');
471
- };
472
-
473
- PropertyManagerContractSchema.statics.findContractsByFeeType = function (facilityId, feeType) {
474
- return this.find({
475
- facilityId: facilityId,
476
- 'managementFee.type': feeType
477
- }).populate('propertyManager', 'fullName email')
478
- .populate('units', 'name unitType')
479
- .populate('customerId', 'firstName lastName email')
480
- .sort({ 'managementFee.value': -1 });
481
- };
482
-
483
- PropertyManagerContractSchema.statics.getContractStatistics = function (facilityId) {
484
- return this.aggregate([
485
- {
486
- $match: { facilityId: mongoose.Types.ObjectId(facilityId) }
487
- },
488
- {
489
- $group: {
490
- _id: '$status',
491
- count: { $sum: 1 },
492
- totalFeeValue: { $sum: '$managementFee.value' },
493
- avgFeeValue: { $avg: '$managementFee.value' }
494
- }
495
- }
496
- ]);
497
- };
498
-
499
- // Instance methods for contract management
500
- PropertyManagerContractSchema.methods.calculateNextInvoiceDate = function () {
501
- if (!this.lastInvoiceDate && !this.startDate) return null;
502
-
503
- const baseDate = this.lastInvoiceDate || this.startDate;
504
- const nextDate = new Date(baseDate);
505
-
506
- switch (this.frequency) {
507
- case 'Monthly':
508
- nextDate.setMonth(nextDate.getMonth() + 1);
509
- break;
510
- case 'Quarterly':
511
- nextDate.setMonth(nextDate.getMonth() + 3);
512
- break;
513
- case 'Annually':
514
- nextDate.setFullYear(nextDate.getFullYear() + 1);
515
- break;
516
- default:
517
- nextDate.setMonth(nextDate.getMonth() + 1); // Default to monthly
518
- }
519
-
520
- // Set to the payment due date of the month
521
- if (this.paymentDueDate) {
522
- const lastDayOfMonth = new Date(nextDate.getFullYear(), nextDate.getMonth() + 1, 0).getDate();
523
- const dueDate = Math.min(this.paymentDueDate, lastDayOfMonth);
524
- nextDate.setDate(dueDate);
525
- }
526
-
527
- return nextDate;
528
- };
529
-
530
- PropertyManagerContractSchema.methods.updateInvoiceDates = async function (invoiceDate = new Date()) {
531
- this.lastInvoiceDate = invoiceDate;
532
- this.nextInvoiceDate = this.calculateNextInvoiceDate();
533
- return this.save();
534
- };
535
-
536
- PropertyManagerContractSchema.methods.activateContract = async function () {
537
- if (!this.canBeActivated()) {
538
- throw new Error(`Cannot activate contract: missing required fields - ${this.getMissingRequiredFields().join(', ')}`);
539
- }
540
-
541
- this.status = 'Active';
542
-
543
- // Set next invoice date if not already set
544
- if (!this.nextInvoiceDate) {
545
- this.nextInvoiceDate = this.calculateNextInvoiceDate();
546
- }
547
-
548
- return this.save();
549
- };
550
-
551
- PropertyManagerContractSchema.methods.suspendContract = async function (reason) {
552
- this.status = 'Suspended';
553
- this.suspensionReason = reason;
554
- return this.save();
555
- };
556
-
557
- PropertyManagerContractSchema.methods.terminateContract = async function (reason, terminationDate = new Date()) {
558
- this.status = 'Terminated';
559
- this.terminationReason = reason;
560
- this.terminationDate = terminationDate;
561
- return this.save();
562
- };
563
-
564
- PropertyManagerContractSchema.methods.completeContract = async function () {
565
- this.status = 'Completed';
566
- this.completionDate = new Date();
567
- return this.save();
568
- };
569
-
570
- // Method to calculate management fee for a given amount
571
- PropertyManagerContractSchema.methods.calculateManagementFee = function (baseAmount) {
572
- if (!this.managementFee) return 0;
573
-
574
- if (this.managementFee.type === 'percentage') {
575
- return (baseAmount * this.managementFee.value) / 100;
576
- } else {
577
- return this.managementFee.value;
578
- }
579
- };
580
-
581
- // Method to get contract summary
582
- PropertyManagerContractSchema.methods.getContractSummary = function () {
583
- return {
584
- id: this._id,
585
- contractName: this.contractName,
586
- status: this.status,
587
- duration: this.durationInDays,
588
- remainingDays: this.remainingDays,
589
- managementFee: this.managementFeeDisplay,
590
- frequency: this.frequency,
591
- nextInvoiceDate: this.nextInvoiceDate,
592
- isComplete: this.isComplete
593
- };
594
- };
595
-
596
- // Pre-findOneAndUpdate middleware to maintain data integrity
597
- PropertyManagerContractSchema.pre(['findOneAndUpdate', 'updateOne', 'updateMany'], function () {
598
- const update = this.getUpdate();
599
-
600
- // If status is being changed to Active, ensure required fields are present
601
- if (update.$set && update.$set.status === 'Active') {
602
- const requiredFields = ['startDate', 'endDate', 'paymentDueDate', 'frequency'];
603
- // Note: We can't validate here because we don't have access to the full document
604
- // Validation should be done in the application logic before calling update
605
- }
606
-
607
- // Update the updatedAt field
608
- if (update.$set) {
609
- update.$set.updatedAt = new Date();
610
- } else {
611
- this.set({ updatedAt: new Date() });
612
- }
613
- });
614
-
615
- // Post-save middleware for logging and notifications
616
- PropertyManagerContractSchema.post('save', function (doc) {
617
- // Log contract creation/updates
618
- console.log(`Property Manager Contract ${doc.isNew ? 'created' : 'updated'}: ${doc.contractName} (${doc._id})`);
619
-
620
- // Here you could add webhook calls, email notifications, etc.
621
- // Example: notify property manager of contract status changes
622
- if (this.isModified('status')) {
623
- console.log(`Contract status changed to: ${doc.status}`);
624
- // Add notification logic here
625
- }
626
-
627
- // Log invoice date updates
628
- if (this.isModified('nextInvoiceDate') || this.isModified('lastInvoiceDate')) {
629
- console.log(`Invoice dates updated for contract: ${doc.contractName}`);
630
- }
631
- });
632
-
633
- // Error handling for validation errors
634
- PropertyManagerContractSchema.post('save', function (error, doc, next) {
635
- if (error.name === 'ValidationError') {
636
- const messages = Object.values(error.errors).map(err => err.message);
637
- next(new Error(`Contract validation failed: ${messages.join(', ')}`));
638
- } else {
639
- next(error);
640
- }
641
- });
642
-
643
- // JSON transformation to remove sensitive data when returning to client
644
- PropertyManagerContractSchema.methods.toJSON = function () {
645
- const contract = this.toObject();
646
-
647
- // Add computed fields
648
- contract.isComplete = this.isComplete;
649
- contract.canBeActivated = this.canBeActivated();
650
- contract.missingRequiredFields = this.getMissingRequiredFields();
651
- contract.durationInDays = this.durationInDays;
652
- contract.remainingDays = this.remainingDays;
653
- contract.managementFeeDisplay = this.managementFeeDisplay;
654
- contract.contractSummary = this.getContractSummary();
655
-
656
- return contract;
657
- };
658
-
659
- // Export the schema
660
- module.exports = {
661
- schema: PropertyManagerContractSchema,
662
- name: 'PropertyManagerContract'
663
- };
1
+ const mongoose = require('mongoose');
2
+ const Schema = mongoose.Schema;
3
+
4
+ const PropertyManagerContractSchema = new Schema(
5
+ {
6
+ contractName: {
7
+ type: String,
8
+ required: [true, 'Contract name is required']
9
+ },
10
+ propertyManager: {
11
+ type: mongoose.Schema.Types.ObjectId,
12
+ ref: 'User', // References global User collection
13
+ required: [true, 'Property manager is required']
14
+ },
15
+ units: [{
16
+ type: mongoose.Schema.Types.ObjectId,
17
+ ref: 'Unit',
18
+ required: [true, 'At least one unit is required']
19
+ }],
20
+ customerId: {
21
+ type: mongoose.Schema.Types.ObjectId,
22
+ ref: 'Customer', // Can reference global or facility-specific Customer
23
+ required: [true, 'Customer ID is required']
24
+ },
25
+ facilityId: {
26
+ type: mongoose.Schema.Types.ObjectId,
27
+ ref: 'Facility',
28
+ required: [true, 'Facility ID is required']
29
+ },
30
+ digitax: {
31
+
32
+ enabled: Boolean,
33
+
34
+ profileId: {
35
+ type: mongoose.Schema.Types.ObjectId
36
+ },
37
+
38
+ itemId: String,
39
+
40
+ itemName: String,
41
+
42
+ itemClassCode: String,
43
+
44
+ taxTypeCode: String,
45
+
46
+ synced: Boolean,
47
+
48
+ syncedAt: Date,
49
+
50
+ lastError: String
51
+
52
+ },
53
+ // Lease term details
54
+ startDate: {
55
+ type: Date,
56
+ required: function () {
57
+ return this.status === 'Active';
58
+ }
59
+ },
60
+ endDate: {
61
+ type: Date,
62
+ required: function () {
63
+ return this.status === 'Active';
64
+ }
65
+ },
66
+ // Payment details - aligned with LeaseAgreement
67
+ paymentDueDate: {
68
+ type: Number,
69
+ required: function () {
70
+ return this.status === 'Active';
71
+ },
72
+ min: [1, 'Payment due date must be between 1 and 31'],
73
+ max: [31, 'Payment due date must be between 1 and 31']
74
+ },
75
+ frequency: {
76
+ type: String,
77
+ enum: ['Monthly', 'Quarterly', 'Annually'],
78
+ default: 'Monthly',
79
+ required: function () {
80
+ return this.status === 'Active';
81
+ }
82
+ },
83
+ nextInvoiceDate: {
84
+ type: Date
85
+ },
86
+ lastInvoiceDate: {
87
+ type: Date
88
+ },
89
+ autoSend: {
90
+ type: Boolean,
91
+ default: false
92
+ },
93
+ balanceBroughtForward: {
94
+ type: Number,
95
+ default: 0
96
+ },
97
+ // Management fee
98
+ managementFee: {
99
+ type: {
100
+ type: String,
101
+ enum: ['percentage', 'amount'],
102
+ required: [true, 'Management fee type is required']
103
+ },
104
+ value: {
105
+ type: Number,
106
+ required: [true, 'Management fee value is required'],
107
+ min: [0, 'Management fee value cannot be negative'],
108
+ validate: {
109
+ validator: function (value) {
110
+ // If type is percentage, value should not exceed 100
111
+ if (this.managementFee.type === 'percentage') {
112
+ return value <= 100;
113
+ }
114
+ return true;
115
+ },
116
+ message: 'Management fee percentage cannot exceed 100%'
117
+ }
118
+ }
119
+ },
120
+ // Per-contract lease commission override — when set (value present)
121
+ // it takes precedence over the facility-wide
122
+ // PropertyManagementSettings default. Lease commission is the
123
+ // one-time fee earned when the property manager places a new
124
+ // tenant (first paid rent invoice).
125
+ leaseFee: {
126
+ type: {
127
+ type: String,
128
+ enum: ['percentage', 'amount']
129
+ },
130
+ value: {
131
+ type: Number,
132
+ min: [0, 'Lease commission value cannot be negative'],
133
+ validate: {
134
+ validator: function (value) {
135
+ if (this.leaseFee && this.leaseFee.type === 'percentage') {
136
+ return value <= 100;
137
+ }
138
+ return true;
139
+ },
140
+ message: 'Lease commission percentage cannot exceed 100%'
141
+ }
142
+ }
143
+ },
144
+ // Currency for fixed-amount managementFee/leaseFee values above.
145
+ // Only meaningful when the fee type is 'amount' (percentage fees are
146
+ // currency-agnostic).
147
+ currencyId: {
148
+ type: mongoose.Schema.Types.ObjectId,
149
+ ref: 'Currency'
150
+ },
151
+ // Booking commission by length of stay, covering every unit on this
152
+ // contract. This is the ONLY place booking commission is configured
153
+ // - it is deliberately NOT settable when listing/editing a unit for
154
+ // booking, so a unit's commission always traces back to its property
155
+ // manager contract. A unit with no covering Active contract, or a
156
+ // stay length matching no tier here, earns 0 commission (no
157
+ // facility-wide or per-property fallback rate).
158
+ bookingCommissionTiers: [{
159
+ minNights: {
160
+ type: Number,
161
+ required: true,
162
+ min: 1
163
+ },
164
+ maxNights: {
165
+ type: Number,
166
+ min: 1
167
+ },
168
+ type: {
169
+ type: String,
170
+ enum: ['percentage', 'fixed'],
171
+ default: 'percentage'
172
+ },
173
+ value: {
174
+ type: Number,
175
+ required: true,
176
+ min: 0
177
+ }
178
+ }],
179
+ // Per-unit fee overrides. Each unit in `units` may have a different
180
+ // management/lease fee here; a unit with no entry here falls back to
181
+ // the contract-level managementFee/leaseFee/currencyId above. This is
182
+ // what lets one contract cover multiple units at different rates.
183
+ unitFees: [{
184
+ unitId: {
185
+ type: mongoose.Schema.Types.ObjectId,
186
+ ref: 'Unit',
187
+ required: true
188
+ },
189
+ managementFee: {
190
+ type: {
191
+ type: String,
192
+ enum: ['percentage', 'amount']
193
+ },
194
+ value: {
195
+ type: Number,
196
+ min: [0, 'Management fee value cannot be negative']
197
+ }
198
+ },
199
+ leaseFee: {
200
+ type: {
201
+ type: String,
202
+ enum: ['percentage', 'amount']
203
+ },
204
+ value: {
205
+ type: Number,
206
+ min: [0, 'Lease commission value cannot be negative']
207
+ }
208
+ },
209
+ currencyId: {
210
+ type: mongoose.Schema.Types.ObjectId,
211
+ ref: 'Currency'
212
+ }
213
+ }],
214
+ // GL Account configurations - updated to match sample data structure
215
+ invoiceDoubleEntryAccount: {
216
+ type: mongoose.Schema.Types.ObjectId,
217
+ ref: 'GLAccountDoubleEntries'
218
+ },
219
+ paymentDoubleEntryAccount: {
220
+ type: mongoose.Schema.Types.ObjectId,
221
+ ref: 'GLAccountDoubleEntries'
222
+ },
223
+ glAccounts: {
224
+ invoice: {
225
+ debit: {
226
+ type: mongoose.Schema.Types.ObjectId,
227
+ ref: 'GLAccount'
228
+ },
229
+ credit: {
230
+ type: mongoose.Schema.Types.ObjectId,
231
+ ref: 'GLAccount'
232
+ }
233
+ },
234
+ payment: {
235
+ debit: {
236
+ type: mongoose.Schema.Types.ObjectId,
237
+ ref: 'GLAccount'
238
+ },
239
+ credit: {
240
+ type: mongoose.Schema.Types.ObjectId,
241
+ ref: 'GLAccount'
242
+ }
243
+ }
244
+ },
245
+ status: {
246
+ type: String,
247
+ enum: ['Active', 'Inactive', 'Completed', 'Suspended', 'Terminated'],
248
+ // Contracts default Active on creation - billing eligibility is
249
+ // driven by lease existence, not contract status. Status is now
250
+ // a purely manual lifecycle field the property manager controls.
251
+ default: 'Active',
252
+ required: [true, 'Status is required']
253
+ },
254
+ createdBy: {
255
+ type: mongoose.Schema.Types.ObjectId,
256
+ ref: 'User' // References global User collection
257
+ },
258
+ // Additional fields for contract lifecycle management
259
+ suspensionReason: {
260
+ type: String
261
+ },
262
+ terminationReason: {
263
+ type: String
264
+ },
265
+ terminationDate: {
266
+ type: Date
267
+ },
268
+ completionDate: {
269
+ type: Date
270
+ }
271
+ },
272
+ {
273
+ timestamps: true,
274
+ // Ensure virtual fields are included in JSON output
275
+ toJSON: { virtuals: true },
276
+ toObject: { virtuals: true }
277
+ }
278
+ );
279
+
280
+ // Enhanced pre-save validation
281
+ PropertyManagerContractSchema.pre('save', function (next) {
282
+ // Validate date range
283
+ if (this.startDate && this.endDate && this.startDate >= this.endDate) {
284
+ next(new Error('End date must be after start date'));
285
+ return;
286
+ }
287
+
288
+ // Validate units array
289
+ if (!this.units || this.units.length === 0) {
290
+ next(new Error('At least one unit must be specified'));
291
+ return;
292
+ }
293
+
294
+ // Validate management fee
295
+ if (!this.managementFee || !this.managementFee.type || this.managementFee.value === undefined) {
296
+ next(new Error('Management fee type and value are required'));
297
+ return;
298
+ }
299
+
300
+ // Validate management fee percentage
301
+ if (this.managementFee.type === 'percentage' && this.managementFee.value > 100) {
302
+ next(new Error('Management fee percentage cannot exceed 100%'));
303
+ return;
304
+ }
305
+
306
+ // Validate management fee value is non-negative
307
+ if (this.managementFee.value < 0) {
308
+ next(new Error('Management fee value cannot be negative'));
309
+ return;
310
+ }
311
+
312
+ // Validate payment due date range
313
+ if (this.paymentDueDate && (this.paymentDueDate < 1 || this.paymentDueDate > 31)) {
314
+ next(new Error('Payment due date must be between 1 and 31'));
315
+ return;
316
+ }
317
+
318
+ // Note: startDate/endDate/paymentDueDate/frequency are no longer
319
+ // required for Active status - contracts are always Active regardless
320
+ // of whether a lease has populated those fields yet. They remain
321
+ // required only for billing (see invoice_service's eligibility checks,
322
+ // which additionally require an active lease before generating an
323
+ // invoice).
324
+
325
+ next();
326
+ });
327
+
328
+ // Method to sync with lease data
329
+ PropertyManagerContractSchema.methods.syncWithLeaseData = async function (leaseData) {
330
+ if (!leaseData) return;
331
+
332
+ // Update contract fields from lease data
333
+ this.startDate = leaseData.leaseTerms?.startDate || this.startDate;
334
+ this.endDate = leaseData.leaseTerms?.endDate || this.endDate;
335
+ this.paymentDueDate = leaseData.financialTerms?.paymentDueDate || this.paymentDueDate;
336
+ this.balanceBroughtForward = leaseData.financialTerms?.balanceBroughtForward || this.balanceBroughtForward;
337
+ this.frequency = leaseData.billingCycle?.frequency || this.frequency;
338
+ this.autoSend = leaseData.billingCycle?.autoSend !== undefined ? leaseData.billingCycle.autoSend : this.autoSend;
339
+ this.nextInvoiceDate = leaseData.billingCycle?.nextInvoiceDate || this.nextInvoiceDate;
340
+ this.lastInvoiceDate = leaseData.billingCycle?.lastInvoiceDate || this.lastInvoiceDate;
341
+
342
+ // Automatically activate contract if all required fields are present
343
+ if (this.startDate && this.endDate && this.paymentDueDate && this.frequency && this.status === 'Inactive') {
344
+ this.status = 'Active';
345
+ }
346
+
347
+ return this.save();
348
+ };
349
+
350
+ // Method to check if contract can be activated
351
+ PropertyManagerContractSchema.methods.canBeActivated = function () {
352
+ return !!(this.startDate && this.endDate && this.paymentDueDate && this.frequency);
353
+ };
354
+
355
+ // Method to get missing required fields
356
+ PropertyManagerContractSchema.methods.getMissingRequiredFields = function () {
357
+ const requiredFields = ['startDate', 'endDate', 'paymentDueDate', 'frequency'];
358
+ return requiredFields.filter(field => !this[field]);
359
+ };
360
+
361
+ // Virtual for contract completion status
362
+ PropertyManagerContractSchema.virtual('isComplete').get(function () {
363
+ return this.canBeActivated();
364
+ });
365
+
366
+ // Virtual for contract duration in days
367
+ PropertyManagerContractSchema.virtual('durationInDays').get(function () {
368
+ if (!this.startDate || !this.endDate) return null;
369
+ const diffTime = Math.abs(this.endDate - this.startDate);
370
+ return Math.ceil(diffTime / (1000 * 60 * 60 * 24));
371
+ });
372
+
373
+ // Virtual for contract remaining days
374
+ PropertyManagerContractSchema.virtual('remainingDays').get(function () {
375
+ if (!this.endDate) return null;
376
+ const now = new Date();
377
+ if (now > this.endDate) return 0;
378
+ const diffTime = Math.abs(this.endDate - now);
379
+ return Math.ceil(diffTime / (1000 * 60 * 60 * 24));
380
+ });
381
+
382
+ // Virtual for management fee display
383
+ PropertyManagerContractSchema.virtual('managementFeeDisplay').get(function () {
384
+ if (!this.managementFee) return null;
385
+
386
+ if (this.managementFee.type === 'percentage') {
387
+ return `${this.managementFee.value}%`;
388
+ } else {
389
+ return `$${this.managementFee.value.toLocaleString()}`;
390
+ }
391
+ });
392
+
393
+ // Indexes for better query performance
394
+ PropertyManagerContractSchema.index({ customerId: 1, status: 1 });
395
+ PropertyManagerContractSchema.index({ facilityId: 1, status: 1 });
396
+ PropertyManagerContractSchema.index({ propertyManager: 1, facilityId: 1 });
397
+ PropertyManagerContractSchema.index({ units: 1, status: 1 });
398
+ PropertyManagerContractSchema.index({ nextInvoiceDate: 1, status: 1 });
399
+ PropertyManagerContractSchema.index({ endDate: 1, status: 1 }); // For contract expiration queries
400
+ PropertyManagerContractSchema.index({ 'managementFee.type': 1, 'managementFee.value': 1 }); // For fee analysis
401
+ PropertyManagerContractSchema.index({ createdAt: -1 }); // For recent contracts
402
+ PropertyManagerContractSchema.index({ startDate: 1, endDate: 1 }); // For date range queries
403
+
404
+ // Compound indexes for common query patterns
405
+ PropertyManagerContractSchema.index({
406
+ facilityId: 1,
407
+ propertyManager: 1,
408
+ status: 1
409
+ });
410
+
411
+ PropertyManagerContractSchema.index({
412
+ facilityId: 1,
413
+ customerId: 1,
414
+ status: 1
415
+ });
416
+
417
+ // Text index for searching contract names
418
+ PropertyManagerContractSchema.index({
419
+ contractName: 'text'
420
+ });
421
+
422
+ // Static methods for common queries
423
+ PropertyManagerContractSchema.statics.findActiveContractsByFacility = function (facilityId) {
424
+ return this.find({
425
+ facilityId: facilityId,
426
+ status: 'Active'
427
+ }).populate('propertyManager', 'fullName email')
428
+ .populate('units', 'name unitType')
429
+ .populate('customerId', 'firstName lastName email');
430
+ };
431
+
432
+ PropertyManagerContractSchema.statics.findContractsByPropertyManager = function (propertyManagerId, facilityId) {
433
+ return this.find({
434
+ propertyManager: propertyManagerId,
435
+ facilityId: facilityId
436
+ }).populate('units', 'name unitType')
437
+ .populate('customerId', 'firstName lastName email')
438
+ .sort({ createdAt: -1 });
439
+ };
440
+
441
+ PropertyManagerContractSchema.statics.findExpiringContracts = function (facilityId, daysAhead = 30) {
442
+ const futureDate = new Date();
443
+ futureDate.setDate(futureDate.getDate() + daysAhead);
444
+
445
+ return this.find({
446
+ facilityId: facilityId,
447
+ status: 'Active',
448
+ endDate: {
449
+ $gte: new Date(),
450
+ $lte: futureDate
451
+ }
452
+ }).populate('propertyManager', 'fullName email')
453
+ .populate('units', 'name unitType')
454
+ .populate('customerId', 'firstName lastName email')
455
+ .sort({ endDate: 1 });
456
+ };
457
+
458
+ PropertyManagerContractSchema.statics.findContractsRequiringInvoicing = function (facilityId) {
459
+ const today = new Date();
460
+ today.setHours(0, 0, 0, 0);
461
+
462
+ return this.find({
463
+ facilityId: facilityId,
464
+ status: 'Active',
465
+ nextInvoiceDate: {
466
+ $lte: today
467
+ }
468
+ }).populate('propertyManager', 'fullName email')
469
+ .populate('units', 'name unitType')
470
+ .populate('customerId', 'firstName lastName email');
471
+ };
472
+
473
+ PropertyManagerContractSchema.statics.findContractsByFeeType = function (facilityId, feeType) {
474
+ return this.find({
475
+ facilityId: facilityId,
476
+ 'managementFee.type': feeType
477
+ }).populate('propertyManager', 'fullName email')
478
+ .populate('units', 'name unitType')
479
+ .populate('customerId', 'firstName lastName email')
480
+ .sort({ 'managementFee.value': -1 });
481
+ };
482
+
483
+ PropertyManagerContractSchema.statics.getContractStatistics = function (facilityId) {
484
+ return this.aggregate([
485
+ {
486
+ $match: { facilityId: mongoose.Types.ObjectId(facilityId) }
487
+ },
488
+ {
489
+ $group: {
490
+ _id: '$status',
491
+ count: { $sum: 1 },
492
+ totalFeeValue: { $sum: '$managementFee.value' },
493
+ avgFeeValue: { $avg: '$managementFee.value' }
494
+ }
495
+ }
496
+ ]);
497
+ };
498
+
499
+ // Instance methods for contract management
500
+ PropertyManagerContractSchema.methods.calculateNextInvoiceDate = function () {
501
+ if (!this.lastInvoiceDate && !this.startDate) return null;
502
+
503
+ const baseDate = this.lastInvoiceDate || this.startDate;
504
+ const nextDate = new Date(baseDate);
505
+
506
+ switch (this.frequency) {
507
+ case 'Monthly':
508
+ nextDate.setMonth(nextDate.getMonth() + 1);
509
+ break;
510
+ case 'Quarterly':
511
+ nextDate.setMonth(nextDate.getMonth() + 3);
512
+ break;
513
+ case 'Annually':
514
+ nextDate.setFullYear(nextDate.getFullYear() + 1);
515
+ break;
516
+ default:
517
+ nextDate.setMonth(nextDate.getMonth() + 1); // Default to monthly
518
+ }
519
+
520
+ // Set to the payment due date of the month
521
+ if (this.paymentDueDate) {
522
+ const lastDayOfMonth = new Date(nextDate.getFullYear(), nextDate.getMonth() + 1, 0).getDate();
523
+ const dueDate = Math.min(this.paymentDueDate, lastDayOfMonth);
524
+ nextDate.setDate(dueDate);
525
+ }
526
+
527
+ return nextDate;
528
+ };
529
+
530
+ PropertyManagerContractSchema.methods.updateInvoiceDates = async function (invoiceDate = new Date()) {
531
+ this.lastInvoiceDate = invoiceDate;
532
+ this.nextInvoiceDate = this.calculateNextInvoiceDate();
533
+ return this.save();
534
+ };
535
+
536
+ PropertyManagerContractSchema.methods.activateContract = async function () {
537
+ if (!this.canBeActivated()) {
538
+ throw new Error(`Cannot activate contract: missing required fields - ${this.getMissingRequiredFields().join(', ')}`);
539
+ }
540
+
541
+ this.status = 'Active';
542
+
543
+ // Set next invoice date if not already set
544
+ if (!this.nextInvoiceDate) {
545
+ this.nextInvoiceDate = this.calculateNextInvoiceDate();
546
+ }
547
+
548
+ return this.save();
549
+ };
550
+
551
+ PropertyManagerContractSchema.methods.suspendContract = async function (reason) {
552
+ this.status = 'Suspended';
553
+ this.suspensionReason = reason;
554
+ return this.save();
555
+ };
556
+
557
+ PropertyManagerContractSchema.methods.terminateContract = async function (reason, terminationDate = new Date()) {
558
+ this.status = 'Terminated';
559
+ this.terminationReason = reason;
560
+ this.terminationDate = terminationDate;
561
+ return this.save();
562
+ };
563
+
564
+ PropertyManagerContractSchema.methods.completeContract = async function () {
565
+ this.status = 'Completed';
566
+ this.completionDate = new Date();
567
+ return this.save();
568
+ };
569
+
570
+ // Method to calculate management fee for a given amount
571
+ PropertyManagerContractSchema.methods.calculateManagementFee = function (baseAmount) {
572
+ if (!this.managementFee) return 0;
573
+
574
+ if (this.managementFee.type === 'percentage') {
575
+ return (baseAmount * this.managementFee.value) / 100;
576
+ } else {
577
+ return this.managementFee.value;
578
+ }
579
+ };
580
+
581
+ // Method to get contract summary
582
+ PropertyManagerContractSchema.methods.getContractSummary = function () {
583
+ return {
584
+ id: this._id,
585
+ contractName: this.contractName,
586
+ status: this.status,
587
+ duration: this.durationInDays,
588
+ remainingDays: this.remainingDays,
589
+ managementFee: this.managementFeeDisplay,
590
+ frequency: this.frequency,
591
+ nextInvoiceDate: this.nextInvoiceDate,
592
+ isComplete: this.isComplete
593
+ };
594
+ };
595
+
596
+ // Pre-findOneAndUpdate middleware to maintain data integrity
597
+ PropertyManagerContractSchema.pre(['findOneAndUpdate', 'updateOne', 'updateMany'], function () {
598
+ const update = this.getUpdate();
599
+
600
+ // If status is being changed to Active, ensure required fields are present
601
+ if (update.$set && update.$set.status === 'Active') {
602
+ const requiredFields = ['startDate', 'endDate', 'paymentDueDate', 'frequency'];
603
+ // Note: We can't validate here because we don't have access to the full document
604
+ // Validation should be done in the application logic before calling update
605
+ }
606
+
607
+ // Update the updatedAt field
608
+ if (update.$set) {
609
+ update.$set.updatedAt = new Date();
610
+ } else {
611
+ this.set({ updatedAt: new Date() });
612
+ }
613
+ });
614
+
615
+ // Post-save middleware for logging and notifications
616
+ PropertyManagerContractSchema.post('save', function (doc) {
617
+ // Log contract creation/updates
618
+ console.log(`Property Manager Contract ${doc.isNew ? 'created' : 'updated'}: ${doc.contractName} (${doc._id})`);
619
+
620
+ // Here you could add webhook calls, email notifications, etc.
621
+ // Example: notify property manager of contract status changes
622
+ if (this.isModified('status')) {
623
+ console.log(`Contract status changed to: ${doc.status}`);
624
+ // Add notification logic here
625
+ }
626
+
627
+ // Log invoice date updates
628
+ if (this.isModified('nextInvoiceDate') || this.isModified('lastInvoiceDate')) {
629
+ console.log(`Invoice dates updated for contract: ${doc.contractName}`);
630
+ }
631
+ });
632
+
633
+ // Error handling for validation errors
634
+ PropertyManagerContractSchema.post('save', function (error, doc, next) {
635
+ if (error.name === 'ValidationError') {
636
+ const messages = Object.values(error.errors).map(err => err.message);
637
+ next(new Error(`Contract validation failed: ${messages.join(', ')}`));
638
+ } else {
639
+ next(error);
640
+ }
641
+ });
642
+
643
+ // JSON transformation to remove sensitive data when returning to client
644
+ PropertyManagerContractSchema.methods.toJSON = function () {
645
+ const contract = this.toObject();
646
+
647
+ // Add computed fields
648
+ contract.isComplete = this.isComplete;
649
+ contract.canBeActivated = this.canBeActivated();
650
+ contract.missingRequiredFields = this.getMissingRequiredFields();
651
+ contract.durationInDays = this.durationInDays;
652
+ contract.remainingDays = this.remainingDays;
653
+ contract.managementFeeDisplay = this.managementFeeDisplay;
654
+ contract.contractSummary = this.getContractSummary();
655
+
656
+ return contract;
657
+ };
658
+
659
+ // Export the schema
660
+ module.exports = {
661
+ schema: PropertyManagerContractSchema,
662
+ name: 'PropertyManagerContract'
663
+ };