payservedb 9.4.4 → 9.4.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (231) hide show
  1. package/.env +2 -2
  2. package/ZOHO_INTEGRATION_SCHEMA.md +644 -644
  3. package/index.js +417 -416
  4. package/package.json +17 -17
  5. package/src/models/InvoiceWithholdingTax.js +67 -67
  6. package/src/models/account.js +52 -52
  7. package/src/models/agent_departments.js +59 -59
  8. package/src/models/agent_notifications.js +53 -53
  9. package/src/models/agent_performance.js +127 -127
  10. package/src/models/agent_roles.js +77 -77
  11. package/src/models/agents.js +154 -154
  12. package/src/models/apilog.js +18 -18
  13. package/src/models/approvalsWorkflows.js +49 -49
  14. package/src/models/archivedapilog.js +18 -18
  15. package/src/models/asset.js +92 -92
  16. package/src/models/assetsAssignment.js +64 -64
  17. package/src/models/auditTrail.js +346 -346
  18. package/src/models/auto_reply_rule.js +68 -68
  19. package/src/models/bankdetails.js +47 -47
  20. package/src/models/billerAddress.js +124 -124
  21. package/src/models/booking_invoice.js +165 -165
  22. package/src/models/bookinganalytics.js +63 -63
  23. package/src/models/bookingconfig.js +45 -45
  24. package/src/models/bookingproperty.js +179 -179
  25. package/src/models/bookingreservation.js +239 -239
  26. package/src/models/bookingrevenuerecord.js +84 -84
  27. package/src/models/budget.js +95 -95
  28. package/src/models/budgetCategory.js +19 -19
  29. package/src/models/campaigns.js +108 -108
  30. package/src/models/cashpayment.js +289 -289
  31. package/src/models/combinedUnits.js +62 -62
  32. package/src/models/combined_invoice.js +424 -424
  33. package/src/models/common_area_electricity.js +38 -38
  34. package/src/models/common_area_generator.js +41 -41
  35. package/src/models/common_area_utility_alert.js +37 -37
  36. package/src/models/common_area_water.js +39 -39
  37. package/src/models/communication_status.js +33 -33
  38. package/src/models/communication_user_opt.js +32 -32
  39. package/src/models/community_guidelines.js +35 -35
  40. package/src/models/company.js +53 -53
  41. package/src/models/coreBaseSettings.js +16 -16
  42. package/src/models/coreInvoiceSettings.js +100 -100
  43. package/src/models/counter_schema.js +21 -21
  44. package/src/models/country_tax.js +42 -42
  45. package/src/models/currency_settings.js +39 -39
  46. package/src/models/customer.js +251 -251
  47. package/src/models/customer_preference.js +52 -52
  48. package/src/models/customer_satisfaction_survey.js +297 -297
  49. package/src/models/customer_surveys.js +139 -139
  50. package/src/models/customer_tickets.js +237 -237
  51. package/src/models/dailyChecklist.js +312 -312
  52. package/src/models/default_payment_details.js +17 -17
  53. package/src/models/deliveryTimeMarks.js +18 -18
  54. package/src/models/document_type.js +19 -19
  55. package/src/models/dutyRosterChecklist.js +250 -250
  56. package/src/models/dutyroster.js +136 -136
  57. package/src/models/email.js +37 -37
  58. package/src/models/email_cc_config.js +48 -48
  59. package/src/models/email_sms_queue.js +61 -61
  60. package/src/models/email_thread.js +35 -35
  61. package/src/models/entry_exit.js +53 -53
  62. package/src/models/expense.js +99 -99
  63. package/src/models/expense_category.js +45 -45
  64. package/src/models/facility.js +76 -76
  65. package/src/models/facilityBillingPrices.js +29 -29
  66. package/src/models/facilityInvoice.js +240 -240
  67. package/src/models/facilityInvoicePayment.js +52 -52
  68. package/src/models/facilityInvoiceRecipient.js +32 -32
  69. package/src/models/facilityWalletTransactionsMetadata.js +236 -236
  70. package/src/models/facility_departements.js +20 -20
  71. package/src/models/facility_etims_config.js +116 -116
  72. package/src/models/facility_payment_details.js +20 -20
  73. package/src/models/facility_rating.js +78 -78
  74. package/src/models/facilityasset.js +25 -25
  75. package/src/models/faq.js +15 -15
  76. package/src/models/gl_account_double_entries.js +25 -25
  77. package/src/models/gl_accounts.js +56 -56
  78. package/src/models/gl_entries.js +49 -49
  79. package/src/models/goodsReceivedNotes.js +115 -115
  80. package/src/models/guard.js +47 -47
  81. package/src/models/handover.js +258 -258
  82. package/src/models/inspection_category.js +38 -38
  83. package/src/models/invoice.js +561 -561
  84. package/src/models/invoiceCreditAdjustment.js +45 -45
  85. package/src/models/invoice_edit_log.js +81 -81
  86. package/src/models/invoice_generation_approval.js +86 -86
  87. package/src/models/invoicing_schedule.js +40 -40
  88. package/src/models/item_inspection.js +96 -96
  89. package/src/models/knowledge_base.js +109 -109
  90. package/src/models/knowledge_base_rating.js +44 -44
  91. package/src/models/leaseagreement.js +266 -243
  92. package/src/models/leasetemplate.js +17 -17
  93. package/src/models/levy.js +212 -212
  94. package/src/models/levy_deposits.js +139 -124
  95. package/src/models/levy_invoice_settings.js +26 -26
  96. package/src/models/levy_payment_receipt.js +156 -156
  97. package/src/models/levycontract.js +236 -213
  98. package/src/models/levytype.js +23 -23
  99. package/src/models/maintenance_service_vendor.js +38 -38
  100. package/src/models/maintenance_services.js +17 -17
  101. package/src/models/maintenancerequisition.js +31 -31
  102. package/src/models/master_workplan.js +32 -32
  103. package/src/models/master_workplan_child.js +34 -34
  104. package/src/models/message.js +38 -38
  105. package/src/models/module.js +21 -21
  106. package/src/models/movein_amenity.js +13 -13
  107. package/src/models/movein_application.js +28 -28
  108. package/src/models/movein_audit_log.js +21 -21
  109. package/src/models/movein_booking.js +33 -33
  110. package/src/models/movein_commission.js +46 -46
  111. package/src/models/movein_conversation.js +25 -25
  112. package/src/models/movein_deal.js +79 -79
  113. package/src/models/movein_disbursement.js +36 -36
  114. package/src/models/movein_email_thread.js +19 -19
  115. package/src/models/movein_enquiry.js +16 -16
  116. package/src/models/movein_featured_package.js +16 -16
  117. package/src/models/movein_handoff_token.js +16 -16
  118. package/src/models/movein_invoice.js +24 -24
  119. package/src/models/movein_landlord.js +18 -18
  120. package/src/models/movein_landlord_user.js +20 -20
  121. package/src/models/movein_lease.js +37 -37
  122. package/src/models/movein_message.js +27 -27
  123. package/src/models/movein_notification.js +27 -27
  124. package/src/models/movein_otp.js +14 -14
  125. package/src/models/movein_payment.js +46 -46
  126. package/src/models/movein_reminder.js +77 -77
  127. package/src/models/movein_reservation.js +31 -31
  128. package/src/models/movein_settings.js +25 -25
  129. package/src/models/movein_tenancy.js +55 -55
  130. package/src/models/movein_unit.js +59 -59
  131. package/src/models/movein_user.js +15 -15
  132. package/src/models/movein_viewing_slot.js +21 -21
  133. package/src/models/movein_want_unit.js +20 -20
  134. package/src/models/notification.js +44 -44
  135. package/src/models/paymentTermsMarks.js +19 -19
  136. package/src/models/penalty.js +76 -76
  137. package/src/models/pendingCredentials.js +32 -32
  138. package/src/models/powerMeterCommunicationProtocol.js +17 -17
  139. package/src/models/powerMeterCustomerAccount.js +78 -78
  140. package/src/models/powerMeterCustomerBand.js +14 -14
  141. package/src/models/powerMeterDailyReading.js +30 -30
  142. package/src/models/powerMeterGateways.js +40 -40
  143. package/src/models/powerMeterMonthlyReading.js +34 -34
  144. package/src/models/powerMeterPowerCharges.js +85 -85
  145. package/src/models/powerMeterSettings.js +211 -211
  146. package/src/models/powerMeterSingleDayReading.js +32 -32
  147. package/src/models/powerMeters.js +149 -149
  148. package/src/models/powerMetersManufacturer.js +14 -14
  149. package/src/models/power_invoice.js +371 -371
  150. package/src/models/power_meter_account.js +81 -81
  151. package/src/models/power_meter_command_logs.js +30 -30
  152. package/src/models/power_meter_command_queue.js +33 -33
  153. package/src/models/power_meter_negative_balance.js +44 -44
  154. package/src/models/power_prepaid_credits.js +47 -47
  155. package/src/models/power_prepaid_debits.js +53 -53
  156. package/src/models/power_prepaid_orders.js +78 -78
  157. package/src/models/power_sms_notification.js +26 -26
  158. package/src/models/privacy_policy.js +19 -19
  159. package/src/models/propertyManagementSettings.js +55 -55
  160. package/src/models/propertyManagerContract.js +579 -579
  161. package/src/models/propertyManagerRevenue.js +195 -195
  162. package/src/models/propertyManagerRevenueEntry.js +108 -108
  163. package/src/models/purchaseOrderInvoice.js +74 -74
  164. package/src/models/purchase_order.js +213 -213
  165. package/src/models/purchase_request.js +110 -110
  166. package/src/models/quickbooks_config.js +52 -52
  167. package/src/models/recipient_group.js +61 -61
  168. package/src/models/recipient_group_member.js +62 -62
  169. package/src/models/refresh_token.js +23 -23
  170. package/src/models/reminder.js +197 -197
  171. package/src/models/report.js +13 -13
  172. package/src/models/resident.js +121 -121
  173. package/src/models/rfq_details.js +131 -131
  174. package/src/models/rfq_response.js +153 -153
  175. package/src/models/service_charge_invoice_upload.js +42 -42
  176. package/src/models/service_charge_payments.js +27 -27
  177. package/src/models/servicerequest.js +55 -55
  178. package/src/models/settings.js +62 -62
  179. package/src/models/short_urls.js +21 -21
  180. package/src/models/smart_meter_daily_consumption.js +44 -44
  181. package/src/models/sms_africastalking.js +20 -20
  182. package/src/models/sms_balance_notification.js +26 -26
  183. package/src/models/sms_meliora.js +20 -20
  184. package/src/models/staff.js +36 -36
  185. package/src/models/stocksandspare.js +161 -161
  186. package/src/models/suppliers.js +79 -79
  187. package/src/models/terms_and_conditions.js +19 -19
  188. package/src/models/tickets.js +186 -186
  189. package/src/models/tickets_category.js +72 -72
  190. package/src/models/unitManagementTemplate.js +44 -44
  191. package/src/models/unitasset.js +25 -25
  192. package/src/models/units.js +148 -148
  193. package/src/models/user.js +186 -186
  194. package/src/models/valueaddedservices.js +50 -50
  195. package/src/models/vas_invoices_upload.js +50 -50
  196. package/src/models/vas_payments.js +24 -24
  197. package/src/models/vasinvoice.js +196 -196
  198. package/src/models/vasvendor.js +52 -52
  199. package/src/models/visitLog.js +95 -95
  200. package/src/models/visitor.js +67 -67
  201. package/src/models/waitlist.js +45 -45
  202. package/src/models/wallet.js +44 -44
  203. package/src/models/wallet_transaction.js +67 -67
  204. package/src/models/wallet_transactions.js +72 -72
  205. package/src/models/water_invoice.js +362 -362
  206. package/src/models/water_meter_Command_Queue.js +33 -33
  207. package/src/models/water_meter_account.js +86 -86
  208. package/src/models/water_meter_billing.js +58 -58
  209. package/src/models/water_meter_combined_accounts.js +92 -92
  210. package/src/models/water_meter_communication.js +17 -17
  211. package/src/models/water_meter_communication_logs.js +39 -39
  212. package/src/models/water_meter_concentrator.js +70 -70
  213. package/src/models/water_meter_daily_history.js +32 -32
  214. package/src/models/water_meter_high_risk.js +36 -36
  215. package/src/models/water_meter_iot_cards.js +34 -34
  216. package/src/models/water_meter_loan_deduction.js +134 -134
  217. package/src/models/water_meter_manufacturer.js +35 -35
  218. package/src/models/water_meter_monthly_history.js +36 -36
  219. package/src/models/water_meter_negative_amounts.js +44 -44
  220. package/src/models/water_meter_settings.js +296 -296
  221. package/src/models/water_meter_single_day_history.js +34 -34
  222. package/src/models/water_meter_size.js +15 -15
  223. package/src/models/water_meters.js +176 -176
  224. package/src/models/water_meters_delivery.js +76 -76
  225. package/src/models/water_prepaid_credit.js +47 -47
  226. package/src/models/water_prepaid_debit.js +50 -50
  227. package/src/models/whatsapp_conversation.js +23 -23
  228. package/src/models/workorder.js +49 -49
  229. package/src/models/zohoAccount.js +453 -453
  230. package/src/models/zohoIntegration.js +262 -262
  231. package/src/models/zohoItem.js +504 -504
@@ -1,580 +1,580 @@
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
- // Lease term details
31
- startDate: {
32
- type: Date,
33
- required: function() {
34
- return this.status === 'Active';
35
- }
36
- },
37
- endDate: {
38
- type: Date,
39
- required: function() {
40
- return this.status === 'Active';
41
- }
42
- },
43
- // Payment details - aligned with LeaseAgreement
44
- paymentDueDate: {
45
- type: Number,
46
- required: function() {
47
- return this.status === 'Active';
48
- },
49
- min: [1, 'Payment due date must be between 1 and 31'],
50
- max: [31, 'Payment due date must be between 1 and 31']
51
- },
52
- frequency: {
53
- type: String,
54
- enum: ['Monthly', 'Quarterly', 'Annually'],
55
- default: 'Monthly',
56
- required: function() {
57
- return this.status === 'Active';
58
- }
59
- },
60
- nextInvoiceDate: {
61
- type: Date
62
- },
63
- lastInvoiceDate: {
64
- type: Date
65
- },
66
- autoSend: {
67
- type: Boolean,
68
- default: false
69
- },
70
- balanceBroughtForward: {
71
- type: Number,
72
- default: 0
73
- },
74
- // Management fee
75
- managementFee: {
76
- type: {
77
- type: String,
78
- enum: ['percentage', 'amount'],
79
- required: [true, 'Management fee type is required']
80
- },
81
- value: {
82
- type: Number,
83
- required: [true, 'Management fee value is required'],
84
- min: [0, 'Management fee value cannot be negative'],
85
- validate: {
86
- validator: function(value) {
87
- // If type is percentage, value should not exceed 100
88
- if (this.managementFee.type === 'percentage') {
89
- return value <= 100;
90
- }
91
- return true;
92
- },
93
- message: 'Management fee percentage cannot exceed 100%'
94
- }
95
- }
96
- },
97
- // Per-contract lease commission override — when set (value present)
98
- // it takes precedence over the facility-wide
99
- // PropertyManagementSettings default. Lease commission is the
100
- // one-time fee earned when the property manager places a new
101
- // tenant (first paid rent invoice).
102
- leaseFee: {
103
- type: {
104
- type: String,
105
- enum: ['percentage', 'amount']
106
- },
107
- value: {
108
- type: Number,
109
- min: [0, 'Lease commission value cannot be negative'],
110
- validate: {
111
- validator: function (value) {
112
- if (this.leaseFee && this.leaseFee.type === 'percentage') {
113
- return value <= 100;
114
- }
115
- return true;
116
- },
117
- message: 'Lease commission percentage cannot exceed 100%'
118
- }
119
- }
120
- },
121
- // GL Account configurations - updated to match sample data structure
122
- invoiceDoubleEntryAccount: {
123
- type: mongoose.Schema.Types.ObjectId,
124
- ref: 'GLAccountDoubleEntries'
125
- },
126
- paymentDoubleEntryAccount: {
127
- type: mongoose.Schema.Types.ObjectId,
128
- ref: 'GLAccountDoubleEntries'
129
- },
130
- glAccounts: {
131
- invoice: {
132
- debit: {
133
- type: mongoose.Schema.Types.ObjectId,
134
- ref: 'GLAccount'
135
- },
136
- credit: {
137
- type: mongoose.Schema.Types.ObjectId,
138
- ref: 'GLAccount'
139
- }
140
- },
141
- payment: {
142
- debit: {
143
- type: mongoose.Schema.Types.ObjectId,
144
- ref: 'GLAccount'
145
- },
146
- credit: {
147
- type: mongoose.Schema.Types.ObjectId,
148
- ref: 'GLAccount'
149
- }
150
- }
151
- },
152
- status: {
153
- type: String,
154
- enum: ['Active', 'Inactive', 'Completed', 'Suspended', 'Terminated'],
155
- default: 'Inactive',
156
- required: [true, 'Status is required']
157
- },
158
- createdBy: {
159
- type: mongoose.Schema.Types.ObjectId,
160
- ref: 'User' // References global User collection
161
- },
162
- // Additional fields for contract lifecycle management
163
- suspensionReason: {
164
- type: String
165
- },
166
- terminationReason: {
167
- type: String
168
- },
169
- terminationDate: {
170
- type: Date
171
- },
172
- completionDate: {
173
- type: Date
174
- }
175
- },
176
- {
177
- timestamps: true,
178
- // Ensure virtual fields are included in JSON output
179
- toJSON: { virtuals: true },
180
- toObject: { virtuals: true }
181
- }
182
- );
183
-
184
- // Enhanced pre-save validation
185
- PropertyManagerContractSchema.pre('save', function (next) {
186
- // Validate date range
187
- if (this.startDate && this.endDate && this.startDate >= this.endDate) {
188
- next(new Error('End date must be after start date'));
189
- return;
190
- }
191
-
192
- // Validate units array
193
- if (!this.units || this.units.length === 0) {
194
- next(new Error('At least one unit must be specified'));
195
- return;
196
- }
197
-
198
- // Validate management fee
199
- if (!this.managementFee || !this.managementFee.type || this.managementFee.value === undefined) {
200
- next(new Error('Management fee type and value are required'));
201
- return;
202
- }
203
-
204
- // Validate management fee percentage
205
- if (this.managementFee.type === 'percentage' && this.managementFee.value > 100) {
206
- next(new Error('Management fee percentage cannot exceed 100%'));
207
- return;
208
- }
209
-
210
- // Validate management fee value is non-negative
211
- if (this.managementFee.value < 0) {
212
- next(new Error('Management fee value cannot be negative'));
213
- return;
214
- }
215
-
216
- // Validate payment due date range
217
- if (this.paymentDueDate && (this.paymentDueDate < 1 || this.paymentDueDate > 31)) {
218
- next(new Error('Payment due date must be between 1 and 31'));
219
- return;
220
- }
221
-
222
- // Validate required fields for Active status
223
- if (this.status === 'Active') {
224
- if (!this.startDate) {
225
- next(new Error('Start date is required for Active contracts'));
226
- return;
227
- }
228
- if (!this.endDate) {
229
- next(new Error('End date is required for Active contracts'));
230
- return;
231
- }
232
- if (!this.paymentDueDate) {
233
- next(new Error('Payment due date is required for Active contracts'));
234
- return;
235
- }
236
- if (!this.frequency) {
237
- next(new Error('Payment frequency is required for Active contracts'));
238
- return;
239
- }
240
- }
241
-
242
- next();
243
- });
244
-
245
- // Method to sync with lease data
246
- PropertyManagerContractSchema.methods.syncWithLeaseData = async function(leaseData) {
247
- if (!leaseData) return;
248
-
249
- // Update contract fields from lease data
250
- this.startDate = leaseData.leaseTerms?.startDate || this.startDate;
251
- this.endDate = leaseData.leaseTerms?.endDate || this.endDate;
252
- this.paymentDueDate = leaseData.financialTerms?.paymentDueDate || this.paymentDueDate;
253
- this.balanceBroughtForward = leaseData.financialTerms?.balanceBroughtForward || this.balanceBroughtForward;
254
- this.frequency = leaseData.billingCycle?.frequency || this.frequency;
255
- this.autoSend = leaseData.billingCycle?.autoSend !== undefined ? leaseData.billingCycle.autoSend : this.autoSend;
256
- this.nextInvoiceDate = leaseData.billingCycle?.nextInvoiceDate || this.nextInvoiceDate;
257
- this.lastInvoiceDate = leaseData.billingCycle?.lastInvoiceDate || this.lastInvoiceDate;
258
-
259
- // Automatically activate contract if all required fields are present
260
- if (this.startDate && this.endDate && this.paymentDueDate && this.frequency && this.status === 'Inactive') {
261
- this.status = 'Active';
262
- }
263
-
264
- return this.save();
265
- };
266
-
267
- // Method to check if contract can be activated
268
- PropertyManagerContractSchema.methods.canBeActivated = function() {
269
- return !!(this.startDate && this.endDate && this.paymentDueDate && this.frequency);
270
- };
271
-
272
- // Method to get missing required fields
273
- PropertyManagerContractSchema.methods.getMissingRequiredFields = function() {
274
- const requiredFields = ['startDate', 'endDate', 'paymentDueDate', 'frequency'];
275
- return requiredFields.filter(field => !this[field]);
276
- };
277
-
278
- // Virtual for contract completion status
279
- PropertyManagerContractSchema.virtual('isComplete').get(function() {
280
- return this.canBeActivated();
281
- });
282
-
283
- // Virtual for contract duration in days
284
- PropertyManagerContractSchema.virtual('durationInDays').get(function() {
285
- if (!this.startDate || !this.endDate) return null;
286
- const diffTime = Math.abs(this.endDate - this.startDate);
287
- return Math.ceil(diffTime / (1000 * 60 * 60 * 24));
288
- });
289
-
290
- // Virtual for contract remaining days
291
- PropertyManagerContractSchema.virtual('remainingDays').get(function() {
292
- if (!this.endDate) return null;
293
- const now = new Date();
294
- if (now > this.endDate) return 0;
295
- const diffTime = Math.abs(this.endDate - now);
296
- return Math.ceil(diffTime / (1000 * 60 * 60 * 24));
297
- });
298
-
299
- // Virtual for management fee display
300
- PropertyManagerContractSchema.virtual('managementFeeDisplay').get(function() {
301
- if (!this.managementFee) return null;
302
-
303
- if (this.managementFee.type === 'percentage') {
304
- return `${this.managementFee.value}%`;
305
- } else {
306
- return `$${this.managementFee.value.toLocaleString()}`;
307
- }
308
- });
309
-
310
- // Indexes for better query performance
311
- PropertyManagerContractSchema.index({ customerId: 1, status: 1 });
312
- PropertyManagerContractSchema.index({ facilityId: 1, status: 1 });
313
- PropertyManagerContractSchema.index({ propertyManager: 1, facilityId: 1 });
314
- PropertyManagerContractSchema.index({ units: 1, status: 1 });
315
- PropertyManagerContractSchema.index({ nextInvoiceDate: 1, status: 1 });
316
- PropertyManagerContractSchema.index({ endDate: 1, status: 1 }); // For contract expiration queries
317
- PropertyManagerContractSchema.index({ 'managementFee.type': 1, 'managementFee.value': 1 }); // For fee analysis
318
- PropertyManagerContractSchema.index({ createdAt: -1 }); // For recent contracts
319
- PropertyManagerContractSchema.index({ startDate: 1, endDate: 1 }); // For date range queries
320
-
321
- // Compound indexes for common query patterns
322
- PropertyManagerContractSchema.index({
323
- facilityId: 1,
324
- propertyManager: 1,
325
- status: 1
326
- });
327
-
328
- PropertyManagerContractSchema.index({
329
- facilityId: 1,
330
- customerId: 1,
331
- status: 1
332
- });
333
-
334
- // Text index for searching contract names
335
- PropertyManagerContractSchema.index({
336
- contractName: 'text'
337
- });
338
-
339
- // Static methods for common queries
340
- PropertyManagerContractSchema.statics.findActiveContractsByFacility = function(facilityId) {
341
- return this.find({
342
- facilityId: facilityId,
343
- status: 'Active'
344
- }).populate('propertyManager', 'fullName email')
345
- .populate('units', 'name unitType')
346
- .populate('customerId', 'firstName lastName email');
347
- };
348
-
349
- PropertyManagerContractSchema.statics.findContractsByPropertyManager = function(propertyManagerId, facilityId) {
350
- return this.find({
351
- propertyManager: propertyManagerId,
352
- facilityId: facilityId
353
- }).populate('units', 'name unitType')
354
- .populate('customerId', 'firstName lastName email')
355
- .sort({ createdAt: -1 });
356
- };
357
-
358
- PropertyManagerContractSchema.statics.findExpiringContracts = function(facilityId, daysAhead = 30) {
359
- const futureDate = new Date();
360
- futureDate.setDate(futureDate.getDate() + daysAhead);
361
-
362
- return this.find({
363
- facilityId: facilityId,
364
- status: 'Active',
365
- endDate: {
366
- $gte: new Date(),
367
- $lte: futureDate
368
- }
369
- }).populate('propertyManager', 'fullName email')
370
- .populate('units', 'name unitType')
371
- .populate('customerId', 'firstName lastName email')
372
- .sort({ endDate: 1 });
373
- };
374
-
375
- PropertyManagerContractSchema.statics.findContractsRequiringInvoicing = function(facilityId) {
376
- const today = new Date();
377
- today.setHours(0, 0, 0, 0);
378
-
379
- return this.find({
380
- facilityId: facilityId,
381
- status: 'Active',
382
- nextInvoiceDate: {
383
- $lte: today
384
- }
385
- }).populate('propertyManager', 'fullName email')
386
- .populate('units', 'name unitType')
387
- .populate('customerId', 'firstName lastName email');
388
- };
389
-
390
- PropertyManagerContractSchema.statics.findContractsByFeeType = function(facilityId, feeType) {
391
- return this.find({
392
- facilityId: facilityId,
393
- 'managementFee.type': feeType
394
- }).populate('propertyManager', 'fullName email')
395
- .populate('units', 'name unitType')
396
- .populate('customerId', 'firstName lastName email')
397
- .sort({ 'managementFee.value': -1 });
398
- };
399
-
400
- PropertyManagerContractSchema.statics.getContractStatistics = function(facilityId) {
401
- return this.aggregate([
402
- {
403
- $match: { facilityId: mongoose.Types.ObjectId(facilityId) }
404
- },
405
- {
406
- $group: {
407
- _id: '$status',
408
- count: { $sum: 1 },
409
- totalFeeValue: { $sum: '$managementFee.value' },
410
- avgFeeValue: { $avg: '$managementFee.value' }
411
- }
412
- }
413
- ]);
414
- };
415
-
416
- // Instance methods for contract management
417
- PropertyManagerContractSchema.methods.calculateNextInvoiceDate = function() {
418
- if (!this.lastInvoiceDate && !this.startDate) return null;
419
-
420
- const baseDate = this.lastInvoiceDate || this.startDate;
421
- const nextDate = new Date(baseDate);
422
-
423
- switch (this.frequency) {
424
- case 'Monthly':
425
- nextDate.setMonth(nextDate.getMonth() + 1);
426
- break;
427
- case 'Quarterly':
428
- nextDate.setMonth(nextDate.getMonth() + 3);
429
- break;
430
- case 'Annually':
431
- nextDate.setFullYear(nextDate.getFullYear() + 1);
432
- break;
433
- default:
434
- nextDate.setMonth(nextDate.getMonth() + 1); // Default to monthly
435
- }
436
-
437
- // Set to the payment due date of the month
438
- if (this.paymentDueDate) {
439
- const lastDayOfMonth = new Date(nextDate.getFullYear(), nextDate.getMonth() + 1, 0).getDate();
440
- const dueDate = Math.min(this.paymentDueDate, lastDayOfMonth);
441
- nextDate.setDate(dueDate);
442
- }
443
-
444
- return nextDate;
445
- };
446
-
447
- PropertyManagerContractSchema.methods.updateInvoiceDates = async function(invoiceDate = new Date()) {
448
- this.lastInvoiceDate = invoiceDate;
449
- this.nextInvoiceDate = this.calculateNextInvoiceDate();
450
- return this.save();
451
- };
452
-
453
- PropertyManagerContractSchema.methods.activateContract = async function() {
454
- if (!this.canBeActivated()) {
455
- throw new Error(`Cannot activate contract: missing required fields - ${this.getMissingRequiredFields().join(', ')}`);
456
- }
457
-
458
- this.status = 'Active';
459
-
460
- // Set next invoice date if not already set
461
- if (!this.nextInvoiceDate) {
462
- this.nextInvoiceDate = this.calculateNextInvoiceDate();
463
- }
464
-
465
- return this.save();
466
- };
467
-
468
- PropertyManagerContractSchema.methods.suspendContract = async function(reason) {
469
- this.status = 'Suspended';
470
- this.suspensionReason = reason;
471
- return this.save();
472
- };
473
-
474
- PropertyManagerContractSchema.methods.terminateContract = async function(reason, terminationDate = new Date()) {
475
- this.status = 'Terminated';
476
- this.terminationReason = reason;
477
- this.terminationDate = terminationDate;
478
- return this.save();
479
- };
480
-
481
- PropertyManagerContractSchema.methods.completeContract = async function() {
482
- this.status = 'Completed';
483
- this.completionDate = new Date();
484
- return this.save();
485
- };
486
-
487
- // Method to calculate management fee for a given amount
488
- PropertyManagerContractSchema.methods.calculateManagementFee = function(baseAmount) {
489
- if (!this.managementFee) return 0;
490
-
491
- if (this.managementFee.type === 'percentage') {
492
- return (baseAmount * this.managementFee.value) / 100;
493
- } else {
494
- return this.managementFee.value;
495
- }
496
- };
497
-
498
- // Method to get contract summary
499
- PropertyManagerContractSchema.methods.getContractSummary = function() {
500
- return {
501
- id: this._id,
502
- contractName: this.contractName,
503
- status: this.status,
504
- duration: this.durationInDays,
505
- remainingDays: this.remainingDays,
506
- managementFee: this.managementFeeDisplay,
507
- frequency: this.frequency,
508
- nextInvoiceDate: this.nextInvoiceDate,
509
- isComplete: this.isComplete
510
- };
511
- };
512
-
513
- // Pre-findOneAndUpdate middleware to maintain data integrity
514
- PropertyManagerContractSchema.pre(['findOneAndUpdate', 'updateOne', 'updateMany'], function() {
515
- const update = this.getUpdate();
516
-
517
- // If status is being changed to Active, ensure required fields are present
518
- if (update.$set && update.$set.status === 'Active') {
519
- const requiredFields = ['startDate', 'endDate', 'paymentDueDate', 'frequency'];
520
- // Note: We can't validate here because we don't have access to the full document
521
- // Validation should be done in the application logic before calling update
522
- }
523
-
524
- // Update the updatedAt field
525
- if (update.$set) {
526
- update.$set.updatedAt = new Date();
527
- } else {
528
- this.set({ updatedAt: new Date() });
529
- }
530
- });
531
-
532
- // Post-save middleware for logging and notifications
533
- PropertyManagerContractSchema.post('save', function(doc) {
534
- // Log contract creation/updates
535
- console.log(`Property Manager Contract ${doc.isNew ? 'created' : 'updated'}: ${doc.contractName} (${doc._id})`);
536
-
537
- // Here you could add webhook calls, email notifications, etc.
538
- // Example: notify property manager of contract status changes
539
- if (this.isModified('status')) {
540
- console.log(`Contract status changed to: ${doc.status}`);
541
- // Add notification logic here
542
- }
543
-
544
- // Log invoice date updates
545
- if (this.isModified('nextInvoiceDate') || this.isModified('lastInvoiceDate')) {
546
- console.log(`Invoice dates updated for contract: ${doc.contractName}`);
547
- }
548
- });
549
-
550
- // Error handling for validation errors
551
- PropertyManagerContractSchema.post('save', function(error, doc, next) {
552
- if (error.name === 'ValidationError') {
553
- const messages = Object.values(error.errors).map(err => err.message);
554
- next(new Error(`Contract validation failed: ${messages.join(', ')}`));
555
- } else {
556
- next(error);
557
- }
558
- });
559
-
560
- // JSON transformation to remove sensitive data when returning to client
561
- PropertyManagerContractSchema.methods.toJSON = function() {
562
- const contract = this.toObject();
563
-
564
- // Add computed fields
565
- contract.isComplete = this.isComplete;
566
- contract.canBeActivated = this.canBeActivated();
567
- contract.missingRequiredFields = this.getMissingRequiredFields();
568
- contract.durationInDays = this.durationInDays;
569
- contract.remainingDays = this.remainingDays;
570
- contract.managementFeeDisplay = this.managementFeeDisplay;
571
- contract.contractSummary = this.getContractSummary();
572
-
573
- return contract;
574
- };
575
-
576
- // Export the schema
577
- module.exports = {
578
- schema: PropertyManagerContractSchema,
579
- name: 'PropertyManagerContract'
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
+ // Lease term details
31
+ startDate: {
32
+ type: Date,
33
+ required: function() {
34
+ return this.status === 'Active';
35
+ }
36
+ },
37
+ endDate: {
38
+ type: Date,
39
+ required: function() {
40
+ return this.status === 'Active';
41
+ }
42
+ },
43
+ // Payment details - aligned with LeaseAgreement
44
+ paymentDueDate: {
45
+ type: Number,
46
+ required: function() {
47
+ return this.status === 'Active';
48
+ },
49
+ min: [1, 'Payment due date must be between 1 and 31'],
50
+ max: [31, 'Payment due date must be between 1 and 31']
51
+ },
52
+ frequency: {
53
+ type: String,
54
+ enum: ['Monthly', 'Quarterly', 'Annually'],
55
+ default: 'Monthly',
56
+ required: function() {
57
+ return this.status === 'Active';
58
+ }
59
+ },
60
+ nextInvoiceDate: {
61
+ type: Date
62
+ },
63
+ lastInvoiceDate: {
64
+ type: Date
65
+ },
66
+ autoSend: {
67
+ type: Boolean,
68
+ default: false
69
+ },
70
+ balanceBroughtForward: {
71
+ type: Number,
72
+ default: 0
73
+ },
74
+ // Management fee
75
+ managementFee: {
76
+ type: {
77
+ type: String,
78
+ enum: ['percentage', 'amount'],
79
+ required: [true, 'Management fee type is required']
80
+ },
81
+ value: {
82
+ type: Number,
83
+ required: [true, 'Management fee value is required'],
84
+ min: [0, 'Management fee value cannot be negative'],
85
+ validate: {
86
+ validator: function(value) {
87
+ // If type is percentage, value should not exceed 100
88
+ if (this.managementFee.type === 'percentage') {
89
+ return value <= 100;
90
+ }
91
+ return true;
92
+ },
93
+ message: 'Management fee percentage cannot exceed 100%'
94
+ }
95
+ }
96
+ },
97
+ // Per-contract lease commission override — when set (value present)
98
+ // it takes precedence over the facility-wide
99
+ // PropertyManagementSettings default. Lease commission is the
100
+ // one-time fee earned when the property manager places a new
101
+ // tenant (first paid rent invoice).
102
+ leaseFee: {
103
+ type: {
104
+ type: String,
105
+ enum: ['percentage', 'amount']
106
+ },
107
+ value: {
108
+ type: Number,
109
+ min: [0, 'Lease commission value cannot be negative'],
110
+ validate: {
111
+ validator: function (value) {
112
+ if (this.leaseFee && this.leaseFee.type === 'percentage') {
113
+ return value <= 100;
114
+ }
115
+ return true;
116
+ },
117
+ message: 'Lease commission percentage cannot exceed 100%'
118
+ }
119
+ }
120
+ },
121
+ // GL Account configurations - updated to match sample data structure
122
+ invoiceDoubleEntryAccount: {
123
+ type: mongoose.Schema.Types.ObjectId,
124
+ ref: 'GLAccountDoubleEntries'
125
+ },
126
+ paymentDoubleEntryAccount: {
127
+ type: mongoose.Schema.Types.ObjectId,
128
+ ref: 'GLAccountDoubleEntries'
129
+ },
130
+ glAccounts: {
131
+ invoice: {
132
+ debit: {
133
+ type: mongoose.Schema.Types.ObjectId,
134
+ ref: 'GLAccount'
135
+ },
136
+ credit: {
137
+ type: mongoose.Schema.Types.ObjectId,
138
+ ref: 'GLAccount'
139
+ }
140
+ },
141
+ payment: {
142
+ debit: {
143
+ type: mongoose.Schema.Types.ObjectId,
144
+ ref: 'GLAccount'
145
+ },
146
+ credit: {
147
+ type: mongoose.Schema.Types.ObjectId,
148
+ ref: 'GLAccount'
149
+ }
150
+ }
151
+ },
152
+ status: {
153
+ type: String,
154
+ enum: ['Active', 'Inactive', 'Completed', 'Suspended', 'Terminated'],
155
+ default: 'Inactive',
156
+ required: [true, 'Status is required']
157
+ },
158
+ createdBy: {
159
+ type: mongoose.Schema.Types.ObjectId,
160
+ ref: 'User' // References global User collection
161
+ },
162
+ // Additional fields for contract lifecycle management
163
+ suspensionReason: {
164
+ type: String
165
+ },
166
+ terminationReason: {
167
+ type: String
168
+ },
169
+ terminationDate: {
170
+ type: Date
171
+ },
172
+ completionDate: {
173
+ type: Date
174
+ }
175
+ },
176
+ {
177
+ timestamps: true,
178
+ // Ensure virtual fields are included in JSON output
179
+ toJSON: { virtuals: true },
180
+ toObject: { virtuals: true }
181
+ }
182
+ );
183
+
184
+ // Enhanced pre-save validation
185
+ PropertyManagerContractSchema.pre('save', function (next) {
186
+ // Validate date range
187
+ if (this.startDate && this.endDate && this.startDate >= this.endDate) {
188
+ next(new Error('End date must be after start date'));
189
+ return;
190
+ }
191
+
192
+ // Validate units array
193
+ if (!this.units || this.units.length === 0) {
194
+ next(new Error('At least one unit must be specified'));
195
+ return;
196
+ }
197
+
198
+ // Validate management fee
199
+ if (!this.managementFee || !this.managementFee.type || this.managementFee.value === undefined) {
200
+ next(new Error('Management fee type and value are required'));
201
+ return;
202
+ }
203
+
204
+ // Validate management fee percentage
205
+ if (this.managementFee.type === 'percentage' && this.managementFee.value > 100) {
206
+ next(new Error('Management fee percentage cannot exceed 100%'));
207
+ return;
208
+ }
209
+
210
+ // Validate management fee value is non-negative
211
+ if (this.managementFee.value < 0) {
212
+ next(new Error('Management fee value cannot be negative'));
213
+ return;
214
+ }
215
+
216
+ // Validate payment due date range
217
+ if (this.paymentDueDate && (this.paymentDueDate < 1 || this.paymentDueDate > 31)) {
218
+ next(new Error('Payment due date must be between 1 and 31'));
219
+ return;
220
+ }
221
+
222
+ // Validate required fields for Active status
223
+ if (this.status === 'Active') {
224
+ if (!this.startDate) {
225
+ next(new Error('Start date is required for Active contracts'));
226
+ return;
227
+ }
228
+ if (!this.endDate) {
229
+ next(new Error('End date is required for Active contracts'));
230
+ return;
231
+ }
232
+ if (!this.paymentDueDate) {
233
+ next(new Error('Payment due date is required for Active contracts'));
234
+ return;
235
+ }
236
+ if (!this.frequency) {
237
+ next(new Error('Payment frequency is required for Active contracts'));
238
+ return;
239
+ }
240
+ }
241
+
242
+ next();
243
+ });
244
+
245
+ // Method to sync with lease data
246
+ PropertyManagerContractSchema.methods.syncWithLeaseData = async function(leaseData) {
247
+ if (!leaseData) return;
248
+
249
+ // Update contract fields from lease data
250
+ this.startDate = leaseData.leaseTerms?.startDate || this.startDate;
251
+ this.endDate = leaseData.leaseTerms?.endDate || this.endDate;
252
+ this.paymentDueDate = leaseData.financialTerms?.paymentDueDate || this.paymentDueDate;
253
+ this.balanceBroughtForward = leaseData.financialTerms?.balanceBroughtForward || this.balanceBroughtForward;
254
+ this.frequency = leaseData.billingCycle?.frequency || this.frequency;
255
+ this.autoSend = leaseData.billingCycle?.autoSend !== undefined ? leaseData.billingCycle.autoSend : this.autoSend;
256
+ this.nextInvoiceDate = leaseData.billingCycle?.nextInvoiceDate || this.nextInvoiceDate;
257
+ this.lastInvoiceDate = leaseData.billingCycle?.lastInvoiceDate || this.lastInvoiceDate;
258
+
259
+ // Automatically activate contract if all required fields are present
260
+ if (this.startDate && this.endDate && this.paymentDueDate && this.frequency && this.status === 'Inactive') {
261
+ this.status = 'Active';
262
+ }
263
+
264
+ return this.save();
265
+ };
266
+
267
+ // Method to check if contract can be activated
268
+ PropertyManagerContractSchema.methods.canBeActivated = function() {
269
+ return !!(this.startDate && this.endDate && this.paymentDueDate && this.frequency);
270
+ };
271
+
272
+ // Method to get missing required fields
273
+ PropertyManagerContractSchema.methods.getMissingRequiredFields = function() {
274
+ const requiredFields = ['startDate', 'endDate', 'paymentDueDate', 'frequency'];
275
+ return requiredFields.filter(field => !this[field]);
276
+ };
277
+
278
+ // Virtual for contract completion status
279
+ PropertyManagerContractSchema.virtual('isComplete').get(function() {
280
+ return this.canBeActivated();
281
+ });
282
+
283
+ // Virtual for contract duration in days
284
+ PropertyManagerContractSchema.virtual('durationInDays').get(function() {
285
+ if (!this.startDate || !this.endDate) return null;
286
+ const diffTime = Math.abs(this.endDate - this.startDate);
287
+ return Math.ceil(diffTime / (1000 * 60 * 60 * 24));
288
+ });
289
+
290
+ // Virtual for contract remaining days
291
+ PropertyManagerContractSchema.virtual('remainingDays').get(function() {
292
+ if (!this.endDate) return null;
293
+ const now = new Date();
294
+ if (now > this.endDate) return 0;
295
+ const diffTime = Math.abs(this.endDate - now);
296
+ return Math.ceil(diffTime / (1000 * 60 * 60 * 24));
297
+ });
298
+
299
+ // Virtual for management fee display
300
+ PropertyManagerContractSchema.virtual('managementFeeDisplay').get(function() {
301
+ if (!this.managementFee) return null;
302
+
303
+ if (this.managementFee.type === 'percentage') {
304
+ return `${this.managementFee.value}%`;
305
+ } else {
306
+ return `$${this.managementFee.value.toLocaleString()}`;
307
+ }
308
+ });
309
+
310
+ // Indexes for better query performance
311
+ PropertyManagerContractSchema.index({ customerId: 1, status: 1 });
312
+ PropertyManagerContractSchema.index({ facilityId: 1, status: 1 });
313
+ PropertyManagerContractSchema.index({ propertyManager: 1, facilityId: 1 });
314
+ PropertyManagerContractSchema.index({ units: 1, status: 1 });
315
+ PropertyManagerContractSchema.index({ nextInvoiceDate: 1, status: 1 });
316
+ PropertyManagerContractSchema.index({ endDate: 1, status: 1 }); // For contract expiration queries
317
+ PropertyManagerContractSchema.index({ 'managementFee.type': 1, 'managementFee.value': 1 }); // For fee analysis
318
+ PropertyManagerContractSchema.index({ createdAt: -1 }); // For recent contracts
319
+ PropertyManagerContractSchema.index({ startDate: 1, endDate: 1 }); // For date range queries
320
+
321
+ // Compound indexes for common query patterns
322
+ PropertyManagerContractSchema.index({
323
+ facilityId: 1,
324
+ propertyManager: 1,
325
+ status: 1
326
+ });
327
+
328
+ PropertyManagerContractSchema.index({
329
+ facilityId: 1,
330
+ customerId: 1,
331
+ status: 1
332
+ });
333
+
334
+ // Text index for searching contract names
335
+ PropertyManagerContractSchema.index({
336
+ contractName: 'text'
337
+ });
338
+
339
+ // Static methods for common queries
340
+ PropertyManagerContractSchema.statics.findActiveContractsByFacility = function(facilityId) {
341
+ return this.find({
342
+ facilityId: facilityId,
343
+ status: 'Active'
344
+ }).populate('propertyManager', 'fullName email')
345
+ .populate('units', 'name unitType')
346
+ .populate('customerId', 'firstName lastName email');
347
+ };
348
+
349
+ PropertyManagerContractSchema.statics.findContractsByPropertyManager = function(propertyManagerId, facilityId) {
350
+ return this.find({
351
+ propertyManager: propertyManagerId,
352
+ facilityId: facilityId
353
+ }).populate('units', 'name unitType')
354
+ .populate('customerId', 'firstName lastName email')
355
+ .sort({ createdAt: -1 });
356
+ };
357
+
358
+ PropertyManagerContractSchema.statics.findExpiringContracts = function(facilityId, daysAhead = 30) {
359
+ const futureDate = new Date();
360
+ futureDate.setDate(futureDate.getDate() + daysAhead);
361
+
362
+ return this.find({
363
+ facilityId: facilityId,
364
+ status: 'Active',
365
+ endDate: {
366
+ $gte: new Date(),
367
+ $lte: futureDate
368
+ }
369
+ }).populate('propertyManager', 'fullName email')
370
+ .populate('units', 'name unitType')
371
+ .populate('customerId', 'firstName lastName email')
372
+ .sort({ endDate: 1 });
373
+ };
374
+
375
+ PropertyManagerContractSchema.statics.findContractsRequiringInvoicing = function(facilityId) {
376
+ const today = new Date();
377
+ today.setHours(0, 0, 0, 0);
378
+
379
+ return this.find({
380
+ facilityId: facilityId,
381
+ status: 'Active',
382
+ nextInvoiceDate: {
383
+ $lte: today
384
+ }
385
+ }).populate('propertyManager', 'fullName email')
386
+ .populate('units', 'name unitType')
387
+ .populate('customerId', 'firstName lastName email');
388
+ };
389
+
390
+ PropertyManagerContractSchema.statics.findContractsByFeeType = function(facilityId, feeType) {
391
+ return this.find({
392
+ facilityId: facilityId,
393
+ 'managementFee.type': feeType
394
+ }).populate('propertyManager', 'fullName email')
395
+ .populate('units', 'name unitType')
396
+ .populate('customerId', 'firstName lastName email')
397
+ .sort({ 'managementFee.value': -1 });
398
+ };
399
+
400
+ PropertyManagerContractSchema.statics.getContractStatistics = function(facilityId) {
401
+ return this.aggregate([
402
+ {
403
+ $match: { facilityId: mongoose.Types.ObjectId(facilityId) }
404
+ },
405
+ {
406
+ $group: {
407
+ _id: '$status',
408
+ count: { $sum: 1 },
409
+ totalFeeValue: { $sum: '$managementFee.value' },
410
+ avgFeeValue: { $avg: '$managementFee.value' }
411
+ }
412
+ }
413
+ ]);
414
+ };
415
+
416
+ // Instance methods for contract management
417
+ PropertyManagerContractSchema.methods.calculateNextInvoiceDate = function() {
418
+ if (!this.lastInvoiceDate && !this.startDate) return null;
419
+
420
+ const baseDate = this.lastInvoiceDate || this.startDate;
421
+ const nextDate = new Date(baseDate);
422
+
423
+ switch (this.frequency) {
424
+ case 'Monthly':
425
+ nextDate.setMonth(nextDate.getMonth() + 1);
426
+ break;
427
+ case 'Quarterly':
428
+ nextDate.setMonth(nextDate.getMonth() + 3);
429
+ break;
430
+ case 'Annually':
431
+ nextDate.setFullYear(nextDate.getFullYear() + 1);
432
+ break;
433
+ default:
434
+ nextDate.setMonth(nextDate.getMonth() + 1); // Default to monthly
435
+ }
436
+
437
+ // Set to the payment due date of the month
438
+ if (this.paymentDueDate) {
439
+ const lastDayOfMonth = new Date(nextDate.getFullYear(), nextDate.getMonth() + 1, 0).getDate();
440
+ const dueDate = Math.min(this.paymentDueDate, lastDayOfMonth);
441
+ nextDate.setDate(dueDate);
442
+ }
443
+
444
+ return nextDate;
445
+ };
446
+
447
+ PropertyManagerContractSchema.methods.updateInvoiceDates = async function(invoiceDate = new Date()) {
448
+ this.lastInvoiceDate = invoiceDate;
449
+ this.nextInvoiceDate = this.calculateNextInvoiceDate();
450
+ return this.save();
451
+ };
452
+
453
+ PropertyManagerContractSchema.methods.activateContract = async function() {
454
+ if (!this.canBeActivated()) {
455
+ throw new Error(`Cannot activate contract: missing required fields - ${this.getMissingRequiredFields().join(', ')}`);
456
+ }
457
+
458
+ this.status = 'Active';
459
+
460
+ // Set next invoice date if not already set
461
+ if (!this.nextInvoiceDate) {
462
+ this.nextInvoiceDate = this.calculateNextInvoiceDate();
463
+ }
464
+
465
+ return this.save();
466
+ };
467
+
468
+ PropertyManagerContractSchema.methods.suspendContract = async function(reason) {
469
+ this.status = 'Suspended';
470
+ this.suspensionReason = reason;
471
+ return this.save();
472
+ };
473
+
474
+ PropertyManagerContractSchema.methods.terminateContract = async function(reason, terminationDate = new Date()) {
475
+ this.status = 'Terminated';
476
+ this.terminationReason = reason;
477
+ this.terminationDate = terminationDate;
478
+ return this.save();
479
+ };
480
+
481
+ PropertyManagerContractSchema.methods.completeContract = async function() {
482
+ this.status = 'Completed';
483
+ this.completionDate = new Date();
484
+ return this.save();
485
+ };
486
+
487
+ // Method to calculate management fee for a given amount
488
+ PropertyManagerContractSchema.methods.calculateManagementFee = function(baseAmount) {
489
+ if (!this.managementFee) return 0;
490
+
491
+ if (this.managementFee.type === 'percentage') {
492
+ return (baseAmount * this.managementFee.value) / 100;
493
+ } else {
494
+ return this.managementFee.value;
495
+ }
496
+ };
497
+
498
+ // Method to get contract summary
499
+ PropertyManagerContractSchema.methods.getContractSummary = function() {
500
+ return {
501
+ id: this._id,
502
+ contractName: this.contractName,
503
+ status: this.status,
504
+ duration: this.durationInDays,
505
+ remainingDays: this.remainingDays,
506
+ managementFee: this.managementFeeDisplay,
507
+ frequency: this.frequency,
508
+ nextInvoiceDate: this.nextInvoiceDate,
509
+ isComplete: this.isComplete
510
+ };
511
+ };
512
+
513
+ // Pre-findOneAndUpdate middleware to maintain data integrity
514
+ PropertyManagerContractSchema.pre(['findOneAndUpdate', 'updateOne', 'updateMany'], function() {
515
+ const update = this.getUpdate();
516
+
517
+ // If status is being changed to Active, ensure required fields are present
518
+ if (update.$set && update.$set.status === 'Active') {
519
+ const requiredFields = ['startDate', 'endDate', 'paymentDueDate', 'frequency'];
520
+ // Note: We can't validate here because we don't have access to the full document
521
+ // Validation should be done in the application logic before calling update
522
+ }
523
+
524
+ // Update the updatedAt field
525
+ if (update.$set) {
526
+ update.$set.updatedAt = new Date();
527
+ } else {
528
+ this.set({ updatedAt: new Date() });
529
+ }
530
+ });
531
+
532
+ // Post-save middleware for logging and notifications
533
+ PropertyManagerContractSchema.post('save', function(doc) {
534
+ // Log contract creation/updates
535
+ console.log(`Property Manager Contract ${doc.isNew ? 'created' : 'updated'}: ${doc.contractName} (${doc._id})`);
536
+
537
+ // Here you could add webhook calls, email notifications, etc.
538
+ // Example: notify property manager of contract status changes
539
+ if (this.isModified('status')) {
540
+ console.log(`Contract status changed to: ${doc.status}`);
541
+ // Add notification logic here
542
+ }
543
+
544
+ // Log invoice date updates
545
+ if (this.isModified('nextInvoiceDate') || this.isModified('lastInvoiceDate')) {
546
+ console.log(`Invoice dates updated for contract: ${doc.contractName}`);
547
+ }
548
+ });
549
+
550
+ // Error handling for validation errors
551
+ PropertyManagerContractSchema.post('save', function(error, doc, next) {
552
+ if (error.name === 'ValidationError') {
553
+ const messages = Object.values(error.errors).map(err => err.message);
554
+ next(new Error(`Contract validation failed: ${messages.join(', ')}`));
555
+ } else {
556
+ next(error);
557
+ }
558
+ });
559
+
560
+ // JSON transformation to remove sensitive data when returning to client
561
+ PropertyManagerContractSchema.methods.toJSON = function() {
562
+ const contract = this.toObject();
563
+
564
+ // Add computed fields
565
+ contract.isComplete = this.isComplete;
566
+ contract.canBeActivated = this.canBeActivated();
567
+ contract.missingRequiredFields = this.getMissingRequiredFields();
568
+ contract.durationInDays = this.durationInDays;
569
+ contract.remainingDays = this.remainingDays;
570
+ contract.managementFeeDisplay = this.managementFeeDisplay;
571
+ contract.contractSummary = this.getContractSummary();
572
+
573
+ return contract;
574
+ };
575
+
576
+ // Export the schema
577
+ module.exports = {
578
+ schema: PropertyManagerContractSchema,
579
+ name: 'PropertyManagerContract'
580
580
  };