payservedb 10.0.4 → 10.0.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.
package/index.js CHANGED
@@ -103,6 +103,7 @@ const models = {
103
103
  LevyContract: require("./src/models/levycontract"),
104
104
  ContractPaymentReceipt: require("./src/models/levy_payment_receipt"),
105
105
  DepositSchema: require("./src/models/levy_deposits"),
106
+ ReceiptCounter: require("./src/models/receipt_counter"),
106
107
  Invoice: require("./src/models/invoice"),
107
108
  CombinedInvoice: require("./src/models/combined_invoice"),
108
109
  InvoiceGeneration: require("./src/models/invoice_generation_approval"),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "payservedb",
3
- "version": "10.0.4",
3
+ "version": "10.0.6",
4
4
  "main": "index.js",
5
5
  "scripts": {
6
6
  "test": "echo \"Error: no test specified\" && exit 1"
@@ -27,7 +27,6 @@ const ContractPaymentReceiptSchema = new Schema(
27
27
  receiptNumber: {
28
28
  type: String,
29
29
  required: [true, 'Receipt number is required'],
30
- unique: true,
31
30
  trim: true
32
31
  },
33
32
  paymentReference: {
@@ -150,9 +149,76 @@ ContractPaymentReceiptSchema.virtual('unit', {
150
149
  justOne: true
151
150
  });
152
151
 
153
- ContractPaymentReceiptSchema.index({ facilityId: 1, receiptNumber: 1 });
152
+ // Receipt numbers must be unique per facility. Existing duplicates must be
153
+ // renumbered before this index can build.
154
+ ContractPaymentReceiptSchema.index({ facilityId: 1, receiptNumber: 1 }, { unique: true });
154
155
  ContractPaymentReceiptSchema.index({ contractId: 1 });
155
156
 
157
+ const RECEIPT_PREFIX = 'RC';
158
+ const RECEIPT_PAD = 5;
159
+
160
+ /**
161
+ * Highest numeric part of any "RC#####" number in a collection (0 if none).
162
+ */
163
+ async function highestReceiptNumber(collection, facilityId) {
164
+ const [row] = await collection.aggregate([
165
+ { $match: { facilityId, receiptNumber: { $regex: `^${RECEIPT_PREFIX}\\d+$` } } },
166
+ {
167
+ $group: {
168
+ _id: null,
169
+ max: {
170
+ $max: {
171
+ $convert: {
172
+ input: { $substrCP: ['$receiptNumber', RECEIPT_PREFIX.length, 20] },
173
+ to: 'int',
174
+ onError: 0
175
+ }
176
+ }
177
+ }
178
+ }
179
+ }
180
+ ]).toArray();
181
+ return row ? row.max : 0;
182
+ }
183
+
184
+ /**
185
+ * Returns the next free receipt number for a facility, e.g. "RC00420".
186
+ *
187
+ * Uses an atomic per-facility counter, seeded from (and never behind) the
188
+ * highest number already present in both the receipts and deposits
189
+ * collections, so imported or manually inserted records cannot be reissued.
190
+ * Pass the same `session` as the surrounding write when inside a transaction.
191
+ * Callers must use the returned number for BOTH the receipt and any deposit
192
+ * linked to it.
193
+ */
194
+ ContractPaymentReceiptSchema.statics.generateReceiptNumber = async function (facilityId, session) {
195
+ const facility = new mongoose.Types.ObjectId(String(facilityId));
196
+ const counters = this.db.collection('receipt_counters');
197
+ const receipts = this.collection;
198
+ const deposits = this.db.collection('deposits');
199
+ const opts = session ? { session } : {};
200
+ const _id = `contract_receipt_${facility}`;
201
+
202
+ const floor = Math.max(
203
+ await highestReceiptNumber(receipts, facility),
204
+ await highestReceiptNumber(deposits, facility)
205
+ );
206
+ // Never let the counter sit behind what already exists.
207
+ await counters.updateOne({ _id }, { $max: { seq: floor } }, { upsert: true, ...opts });
208
+
209
+ for (let attempt = 0; attempt < 50; attempt++) {
210
+ const doc = await counters.findOneAndUpdate(
211
+ { _id },
212
+ { $inc: { seq: 1 } },
213
+ { returnDocument: 'after', ...opts }
214
+ );
215
+ const candidate = `${RECEIPT_PREFIX}${String(doc.seq).padStart(RECEIPT_PAD, '0')}`;
216
+ const taken = await receipts.findOne({ facilityId: facility, receiptNumber: candidate }, { projection: { _id: 1 }, ...opts });
217
+ if (!taken) return candidate;
218
+ }
219
+ throw new Error('Could not generate a unique receipt number');
220
+ };
221
+
156
222
  module.exports = {
157
223
  schema: ContractPaymentReceiptSchema,
158
224
  name: 'ContractPaymentReceipt'
@@ -0,0 +1,17 @@
1
+ const mongoose = require('mongoose');
2
+
3
+ // Per-facility sequence counters keyed by a string _id (e.g. 'receiptNumber').
4
+ // Stored in the shared 'counters' collection; documents here use a string _id,
5
+ // unlike the facility-keyed Counter model in counter_schema.js.
6
+ const ReceiptCounterSchema = new mongoose.Schema(
7
+ {
8
+ _id: { type: String, required: true },
9
+ seq: { type: Number, default: 0 }
10
+ },
11
+ { collection: 'counters' }
12
+ );
13
+
14
+ module.exports = {
15
+ schema: ReceiptCounterSchema,
16
+ name: 'ReceiptCounter'
17
+ };
@@ -47,6 +47,11 @@ const analogBillingSchema = new mongoose.Schema({
47
47
  enum: ['pending', 'reviewed', 'billed', 'failed'],
48
48
  default: 'pending',
49
49
  },
50
+ // Why invoicing this reading failed (set together with status 'failed').
51
+ errorMessage: {
52
+ type: String,
53
+ default: null,
54
+ },
50
55
  }, {
51
56
  timestamps: true,
52
57
  });