payservedb 5.6.1 → 5.6.3

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.
package/index.js CHANGED
@@ -171,7 +171,9 @@ const models = {
171
171
  GLAccountDoubleEntries: require('./src/models/gl_account_double_entries'),
172
172
  PendingCredential: require('./src/models/pendingCredentials'),
173
173
  UnitManagementTemplate: require('./src/models/unitManagementTemplate'),
174
- PropertyManagerRevenue: require('./src/models/propertyManagerRevenue')
174
+ PropertyManagerRevenue: require('./src/models/propertyManagerRevenue'),
175
+ PropertyManagerContract: require('./src/models/propertyManagerContract'),
176
+ BillerAddress: require('./src/models/billerAddress')
175
177
  };
176
178
 
177
179
  // Function to get models dynamically from a specific database connection
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "payservedb",
3
- "version": "5.6.1",
3
+ "version": "5.6.3",
4
4
  "main": "index.js",
5
5
  "scripts": {
6
6
  "test": "echo \"Error: no test specified\" && exit 1"
@@ -0,0 +1,117 @@
1
+ const mongoose = require("mongoose");
2
+
3
+ // Define the schema for Biller Address
4
+ const billerAddressSchema = new mongoose.Schema(
5
+ {
6
+ name: {
7
+ type: String,
8
+ required: [true, "Address name is required"],
9
+ trim: true,
10
+ minlength: [1, "Address name must be at least 1 character long"],
11
+ },
12
+ companyName: {
13
+ type: String,
14
+ required: [true, "Company name is required"],
15
+ trim: true,
16
+ },
17
+ website: {
18
+ type: String,
19
+ trim: true,
20
+ validate: {
21
+ validator: function (v) {
22
+ if (!v) return true; // Optional field
23
+ return /^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-])\/?$/.test(v);
24
+ },
25
+ message: "Please enter a valid website URL"
26
+ }
27
+ },
28
+ email: {
29
+ type: String,
30
+ required: [true, "Email is required"],
31
+ trim: true,
32
+ lowercase: true,
33
+ validate: {
34
+ validator: function (v) {
35
+ return /^\w+([\.-]?\w+)@\w+([\.-]?\w+)(\.\w{2,3})+$/.test(v);
36
+ },
37
+ message: "Please enter a valid email address"
38
+ }
39
+ },
40
+ phone: {
41
+ type: String,
42
+ trim: true,
43
+ },
44
+ address: {
45
+ type: String,
46
+ required: [true, "Address is required"],
47
+ trim: true,
48
+ },
49
+ city: {
50
+ type: String,
51
+ required: [true, "City is required"],
52
+ trim: true,
53
+ },
54
+ state: {
55
+ type: String,
56
+ trim: true,
57
+ },
58
+ country: {
59
+ type: String,
60
+ required: [true, "Country is required"],
61
+ trim: true,
62
+ default: "Kenya"
63
+ },
64
+ postalCode: {
65
+ type: String,
66
+ trim: true,
67
+ },
68
+ logo: {
69
+ type: String, // Will store the file path/URL of the uploaded logo
70
+ required: false,
71
+ },
72
+ isDefault: {
73
+ type: Boolean,
74
+ default: false,
75
+ },
76
+ facilityId: {
77
+ type: mongoose.Schema.Types.ObjectId,
78
+ ref: "Facility",
79
+ required: true,
80
+ },
81
+ createdBy: {
82
+ type: mongoose.Schema.Types.ObjectId,
83
+ ref: "User",
84
+ },
85
+ updatedBy: {
86
+ type: mongoose.Schema.Types.ObjectId,
87
+ ref: "User",
88
+ }
89
+ },
90
+ {
91
+ timestamps: true,
92
+ }
93
+ );
94
+
95
+ // Index for efficient queries
96
+ billerAddressSchema.index({ facilityId: 1 });
97
+ billerAddressSchema.index({ facilityId: 1, isDefault: 1 });
98
+
99
+ // Pre-save middleware to ensure only one default address per facility
100
+ billerAddressSchema.pre('save', async function (next) {
101
+ if (this.isDefault && this.isModified('isDefault')) {
102
+ // If this address is being set as default, unset all other defaults for this facility
103
+ await this.constructor.updateMany(
104
+ {
105
+ facilityId: this.facilityId,
106
+ _id: { $ne: this._id }
107
+ },
108
+ { $set: { isDefault: false } }
109
+ );
110
+ }
111
+ next();
112
+ });
113
+
114
+ // Compile the model from the schema
115
+ const BillerAddress = mongoose.model("BillerAddress", billerAddressSchema);
116
+
117
+ module.exports = BillerAddress;
@@ -0,0 +1,359 @@
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',
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',
23
+ required: [true, 'Customer ID is required']
24
+ },
25
+ // Optional fields - only required when status is "Active"
26
+ startDate: {
27
+ type: Date,
28
+ required: function() {
29
+ return this.status === 'Active';
30
+ }
31
+ },
32
+ endDate: {
33
+ type: Date,
34
+ required: function() {
35
+ return this.status === 'Active';
36
+ }
37
+ },
38
+ invoiceDay: {
39
+ type: Number,
40
+ required: function() {
41
+ return this.status === 'Active';
42
+ },
43
+ min: [1, 'Invoice day must be between 1 and 31'],
44
+ max: [31, 'Invoice day must be between 1 and 31']
45
+ },
46
+ dueDate: {
47
+ type: String, // Store as string like "5th", "10th", etc.
48
+ required: function() {
49
+ return this.status === 'Active';
50
+ }
51
+ },
52
+ balanceBroughtForward: {
53
+ type: Number,
54
+ default: 0
55
+ },
56
+ collectionFrequency: {
57
+ type: String,
58
+ enum: ['Daily', 'Weekly', 'Bi-Weekly', 'Monthly', 'Quarterly', 'Semi-Annually', 'Annually'],
59
+ default: 'Monthly',
60
+ required: function() {
61
+ return this.status === 'Active';
62
+ }
63
+ },
64
+ // Always required fields regardless of status
65
+ managementFee: {
66
+ type: {
67
+ type: String,
68
+ enum: ['percentage', 'amount'],
69
+ required: [true, 'Management fee type is required']
70
+ },
71
+ value: {
72
+ type: Number,
73
+ required: [true, 'Management fee value is required'],
74
+ min: [0, 'Management fee value cannot be negative']
75
+ }
76
+ },
77
+ // GL Account configurations - matching LeaseAgreement pattern
78
+ invoiceDoubleEntryAccount: {
79
+ type: mongoose.Schema.Types.ObjectId,
80
+ ref: 'GLAccountDoubleEntries'
81
+ },
82
+ paymentDoubleEntryAccount: {
83
+ type: mongoose.Schema.Types.ObjectId,
84
+ ref: 'GLAccountDoubleEntries'
85
+ },
86
+ // GL Account direct configurations (used when creating double entry records)
87
+ glAccounts: {
88
+ invoice: {
89
+ debit: {
90
+ type: mongoose.Schema.Types.ObjectId,
91
+ ref: 'GLAccount'
92
+ },
93
+ credit: {
94
+ type: mongoose.Schema.Types.ObjectId,
95
+ ref: 'GLAccount'
96
+ }
97
+ },
98
+ payment: {
99
+ debit: {
100
+ type: mongoose.Schema.Types.ObjectId,
101
+ ref: 'GLAccount'
102
+ },
103
+ credit: {
104
+ type: mongoose.Schema.Types.ObjectId,
105
+ ref: 'GLAccount'
106
+ }
107
+ }
108
+ },
109
+ status: {
110
+ type: String,
111
+ enum: ['Active', 'Inactive', 'Completed', 'Suspended', 'Terminated'],
112
+ default: 'Inactive',
113
+ required: [true, 'Status is required']
114
+ },
115
+ facilityId: {
116
+ type: mongoose.Schema.Types.ObjectId,
117
+ ref: 'Facility',
118
+ required: [true, 'Facility ID is required']
119
+ },
120
+ lastInvoiceDate: {
121
+ type: Date
122
+ },
123
+ nextInvoiceDate: {
124
+ type: Date
125
+ },
126
+ autoSend: {
127
+ type: Boolean,
128
+ default: false
129
+ },
130
+ // Track data source and sync information
131
+ leaseDataSource: {
132
+ type: String,
133
+ enum: ['lease', 'manual'],
134
+ default: 'manual'
135
+ },
136
+ lastSyncedAt: {
137
+ type: Date
138
+ },
139
+ // Track which units have lease agreements
140
+ unitsWithLeases: [{
141
+ unitId: {
142
+ type: mongoose.Schema.Types.ObjectId,
143
+ ref: 'Unit'
144
+ },
145
+ leaseId: {
146
+ type: mongoose.Schema.Types.ObjectId,
147
+ ref: 'LeaseAgreement'
148
+ },
149
+ syncedAt: {
150
+ type: Date,
151
+ default: Date.now
152
+ }
153
+ }],
154
+ createdBy: {
155
+ type: mongoose.Schema.Types.ObjectId,
156
+ ref: 'User'
157
+ },
158
+ updatedBy: {
159
+ type: mongoose.Schema.Types.ObjectId,
160
+ ref: 'User'
161
+ },
162
+ // Track contract edit history
163
+ editHistory: [{
164
+ editedBy: {
165
+ type: mongoose.Schema.Types.Mixed,
166
+ ref: 'User'
167
+ },
168
+ editedAt: {
169
+ type: Date,
170
+ default: Date.now
171
+ },
172
+ reason: {
173
+ type: String,
174
+ required: true
175
+ },
176
+ changes: {
177
+ type: Object
178
+ }
179
+ }]
180
+ },
181
+ {
182
+ timestamps: true,
183
+ toJSON: { virtuals: true },
184
+ toObject: { virtuals: true }
185
+ }
186
+ );
187
+
188
+ // Virtual populate for Property Manager details
189
+ PropertyManagerContractSchema.virtual('propertyManagerDetails', {
190
+ ref: 'User',
191
+ localField: 'propertyManager',
192
+ foreignField: '_id',
193
+ justOne: true
194
+ });
195
+
196
+ // Virtual populate for Customer details
197
+ PropertyManagerContractSchema.virtual('customer', {
198
+ ref: 'Customer',
199
+ localField: 'customerId',
200
+ foreignField: '_id',
201
+ justOne: true
202
+ });
203
+
204
+ // Virtual populate for Units details
205
+ PropertyManagerContractSchema.virtual('unitDetails', {
206
+ ref: 'Unit',
207
+ localField: 'units',
208
+ foreignField: '_id'
209
+ });
210
+
211
+ // Virtual populate for invoice double entry account
212
+ PropertyManagerContractSchema.virtual('invoiceDoubleEntry', {
213
+ ref: 'GLAccountDoubleEntries',
214
+ localField: 'invoiceDoubleEntryAccount',
215
+ foreignField: '_id',
216
+ justOne: true
217
+ });
218
+
219
+ // Virtual populate for payment double entry account
220
+ PropertyManagerContractSchema.virtual('paymentDoubleEntry', {
221
+ ref: 'GLAccountDoubleEntries',
222
+ localField: 'paymentDoubleEntryAccount',
223
+ foreignField: '_id',
224
+ justOne: true
225
+ });
226
+
227
+ // Virtual populate for Facility details
228
+ PropertyManagerContractSchema.virtual('facility', {
229
+ ref: 'Facility',
230
+ localField: 'facilityId',
231
+ foreignField: '_id',
232
+ justOne: true
233
+ });
234
+
235
+ // Virtual to check if contract is complete (has all lease-dependent fields)
236
+ PropertyManagerContractSchema.virtual('isComplete').get(function() {
237
+ return this.startDate && this.endDate && this.invoiceDay && this.dueDate && this.collectionFrequency;
238
+ });
239
+
240
+ // Virtual to get completion percentage
241
+ PropertyManagerContractSchema.virtual('completionPercentage').get(function() {
242
+ const requiredFields = ['startDate', 'endDate', 'invoiceDay', 'dueDate', 'collectionFrequency'];
243
+ const completedFields = requiredFields.filter(field => this[field] != null).length;
244
+ return Math.round((completedFields / requiredFields.length) * 100);
245
+ });
246
+
247
+ // Pre-save middleware to ensure endDate is after startDate (only when both exist)
248
+ PropertyManagerContractSchema.pre('save', function (next) {
249
+ if (this.startDate && this.endDate && this.startDate >= this.endDate) {
250
+ next(new Error('End date must be after start date'));
251
+ } else {
252
+ next();
253
+ }
254
+ });
255
+
256
+ // Pre-save middleware to validate units array is not empty
257
+ PropertyManagerContractSchema.pre('save', function (next) {
258
+ if (!this.units || this.units.length === 0) {
259
+ next(new Error('At least one unit must be specified'));
260
+ } else {
261
+ next();
262
+ }
263
+ });
264
+
265
+ // Pre-save middleware to validate management fee
266
+ PropertyManagerContractSchema.pre('save', function (next) {
267
+ if (this.managementFee.type === 'percentage' && this.managementFee.value > 100) {
268
+ next(new Error('Management fee percentage cannot exceed 100%'));
269
+ } else {
270
+ next();
271
+ }
272
+ });
273
+
274
+ // Pre-save middleware to auto-update status based on completion
275
+ PropertyManagerContractSchema.pre('save', function (next) {
276
+ // If contract has all required lease fields and is currently Inactive, make it Active
277
+ if (this.status === 'Inactive' && this.isComplete) {
278
+ this.status = 'Active';
279
+ this.leaseDataSource = 'lease';
280
+ this.lastSyncedAt = new Date();
281
+ }
282
+
283
+ // If contract is missing required fields and is currently Active, make it Inactive
284
+ if (this.status === 'Active' && !this.isComplete) {
285
+ this.status = 'Inactive';
286
+ }
287
+
288
+ next();
289
+ });
290
+
291
+ // Pre-save middleware to set next invoice date based on collection frequency (only for active contracts)
292
+ PropertyManagerContractSchema.pre('save', function (next) {
293
+ if (this.isNew && this.status === 'Active' && this.startDate && this.invoiceDay && !this.nextInvoiceDate) {
294
+ const baseDate = new Date(this.startDate);
295
+ baseDate.setDate(this.invoiceDay);
296
+
297
+ // If the invoice day has passed this month, set for next month
298
+ if (baseDate < this.startDate) {
299
+ baseDate.setMonth(baseDate.getMonth() + 1);
300
+ }
301
+
302
+ this.nextInvoiceDate = baseDate;
303
+ }
304
+ next();
305
+ });
306
+
307
+ // Method to sync with lease data
308
+ PropertyManagerContractSchema.methods.syncWithLeaseData = async function(leaseData) {
309
+ if (!leaseData) return;
310
+
311
+ this.startDate = leaseData.leaseTerms?.startDate || this.startDate;
312
+ this.endDate = leaseData.leaseTerms?.endDate || this.endDate;
313
+ this.invoiceDay = leaseData.financialTerms?.paymentDueDate || this.invoiceDay;
314
+ this.balanceBroughtForward = leaseData.financialTerms?.balanceBroughtForward || this.balanceBroughtForward;
315
+ this.collectionFrequency = leaseData.billingCycle?.frequency || this.collectionFrequency;
316
+ this.autoSend = leaseData.billingCycle?.autoSend !== undefined ? leaseData.billingCycle.autoSend : this.autoSend;
317
+
318
+ // Copy GL accounts if available
319
+ if (leaseData.glAccounts) {
320
+ this.glAccounts = leaseData.glAccounts;
321
+ }
322
+ if (leaseData.invoiceDoubleEntryAccount) {
323
+ this.invoiceDoubleEntryAccount = leaseData.invoiceDoubleEntryAccount;
324
+ }
325
+ if (leaseData.paymentDoubleEntryAccount) {
326
+ this.paymentDoubleEntryAccount = leaseData.paymentDoubleEntryAccount;
327
+ }
328
+
329
+ this.leaseDataSource = 'lease';
330
+ this.lastSyncedAt = new Date();
331
+
332
+ // Auto-calculate due date from payment due date if not set
333
+ if (this.invoiceDay && !this.dueDate) {
334
+ const dueDateMap = {
335
+ 1: "1st", 5: "5th", 10: "10th", 15: "15th"
336
+ };
337
+ this.dueDate = dueDateMap[this.invoiceDay] || `${this.invoiceDay}th`;
338
+ }
339
+
340
+ return this.save();
341
+ };
342
+
343
+ // Indexes for efficient queries
344
+ PropertyManagerContractSchema.index({ customerId: 1, status: 1 });
345
+ PropertyManagerContractSchema.index({ facilityId: 1 });
346
+ PropertyManagerContractSchema.index({ units: 1 });
347
+ PropertyManagerContractSchema.index({ propertyManager: 1 }); // New index for property manager
348
+ PropertyManagerContractSchema.index({ invoiceDoubleEntryAccount: 1 });
349
+ PropertyManagerContractSchema.index({ paymentDoubleEntryAccount: 1 });
350
+ PropertyManagerContractSchema.index({ startDate: 1, endDate: 1 });
351
+ PropertyManagerContractSchema.index({ nextInvoiceDate: 1, status: 1 });
352
+ PropertyManagerContractSchema.index({ leaseDataSource: 1 });
353
+ PropertyManagerContractSchema.index({ 'unitsWithLeases.unitId': 1 });
354
+
355
+
356
+ // Compile the model from the schema
357
+ const PropertyManagerContract = mongoose.model("PropertyManagerContract", PropertyManagerContractSchema);
358
+
359
+ module.exports = PropertyManagerContract;
@@ -50,14 +50,13 @@ const unitSchema = new mongoose.Schema({
50
50
  type: Boolean,
51
51
  default: false
52
52
  },
53
- propertyManagementFee: {
54
- type: Number,
55
- required: function () {
53
+ propertyManagerName: {
54
+ type: String,
55
+ required: function() {
56
56
  return this.isManagedByPropertyManager === true;
57
- },
58
- min: [0, "Property management fee must be at least 0"],
59
- max: [100, "Property management fee cannot exceed 100%"]
57
+ }
60
58
  },
59
+
61
60
  occupants: [
62
61
  {
63
62
  customerId: { type: mongoose.Schema.Types.ObjectId, ref: 'Customer' },
@@ -95,17 +94,18 @@ const unitSchema = new mongoose.Schema({
95
94
  timestamps: true // Automatically add createdAt and updatedAt fields
96
95
  });
97
96
 
98
- // Add pre-save middleware to handle propertyManagementFee
97
+ // Add pre-save middleware to handle property management fields
99
98
  unitSchema.pre('save', function (next) {
100
- // Clear propertyManagementFee if not managed by property manager
99
+ // Clear property management fields if not managed by property manager
101
100
  if (!this.isManagedByPropertyManager) {
102
- this.propertyManagementFee = null;
101
+ this.propertyManagerName = null;
103
102
  }
104
103
  next();
105
104
  });
106
105
 
107
106
  // Indexes for improved performance
108
107
  unitSchema.index({ name: 1 });
108
+ unitSchema.index({ isManagedByPropertyManager: 1 });
109
109
 
110
110
  // Compile the model from the schema
111
111
  const Unit = mongoose.model('Unit', unitSchema);