@managesome/eposmatic-toolkit 0.4.26 → 0.4.27
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/esm/helpers/materialized-reports/index.js +1 -0
- package/esm/helpers/materialized-reports/materialized-credit-bills-helpers.js +9 -4
- package/esm/helpers/materialized-reports/materialized-delivery-classification-helpers.js +25 -9
- package/esm/helpers/materialized-reports/materialized-delivery-compile-helpers.js +8 -5
- package/esm/helpers/materialized-reports/materialized-discount-accumulator-helpers.js +13 -1
- package/esm/helpers/materialized-reports/materialized-discount-source-helpers.js +0 -3
- package/esm/helpers/materialized-reports/materialized-integer-contract.js +142 -0
- package/esm/helpers/materialized-reports/materialized-payments-comparison-accumulator-helpers.js +7 -1
- package/esm/helpers/materialized-reports/materialized-prep-time-classification-helpers.js +9 -2
- package/esm/helpers/materialized-reports/materialized-sales-comparison-accumulator-helpers.js +17 -7
- package/esm/helpers/materialized-reports/tenant-discount-source-formatter.js +29 -29
- package/esm/helpers/materialized-reports/tenant-sales-overview-helpers.js +4 -2
- package/esm/helpers/utils/duration-conversion.js +31 -0
- package/esm/helpers/utils/index.js +2 -0
- package/esm/helpers/utils/percentage-conversion.js +69 -0
- package/esm/schemas/models/materialized_tenant_discount_sources.js +5 -1
- package/lib/helpers/materialized-reports/index.d.ts +1 -0
- package/lib/helpers/materialized-reports/index.js +1 -0
- package/lib/helpers/materialized-reports/materialized-credit-bills-helpers.js +9 -4
- package/lib/helpers/materialized-reports/materialized-delivery-classification-helpers.js +25 -9
- package/lib/helpers/materialized-reports/materialized-delivery-compile-helpers.js +8 -5
- package/lib/helpers/materialized-reports/materialized-discount-accumulator-helpers.d.ts +18 -0
- package/lib/helpers/materialized-reports/materialized-discount-accumulator-helpers.js +14 -2
- package/lib/helpers/materialized-reports/materialized-discount-source-helpers.js +0 -3
- package/lib/helpers/materialized-reports/materialized-integer-contract.d.ts +68 -0
- package/lib/helpers/materialized-reports/materialized-integer-contract.js +147 -0
- package/lib/helpers/materialized-reports/materialized-payments-comparison-accumulator-helpers.js +7 -1
- package/lib/helpers/materialized-reports/materialized-prep-time-classification-helpers.js +9 -2
- package/lib/helpers/materialized-reports/materialized-sales-comparison-accumulator-helpers.js +17 -7
- package/lib/helpers/materialized-reports/tenant-discount-source-formatter.d.ts +12 -30
- package/lib/helpers/materialized-reports/tenant-discount-source-formatter.js +29 -30
- package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.js +4 -2
- package/lib/helpers/types/materialized-reports-apis.d.ts +11 -3
- package/lib/helpers/utils/duration-conversion.d.ts +19 -0
- package/lib/helpers/utils/duration-conversion.js +37 -0
- package/lib/helpers/utils/index.d.ts +2 -0
- package/lib/helpers/utils/index.js +2 -0
- package/lib/helpers/utils/percentage-conversion.d.ts +49 -0
- package/lib/helpers/utils/percentage-conversion.js +76 -0
- package/lib/schemas/models/materialized_tenant_discount_sources.d.ts +0 -3
- package/lib/schemas/models/materialized_tenant_discount_sources.js +5 -1
- package/lib/schemas/types/materialized_tenant_discount_entries.d.ts +11 -4
- package/lib/schemas/types/materialized_tenant_discount_sources.d.ts +23 -4
- package/lib/tests/materialized-reports/fixtures.d.ts +15 -1
- package/lib/tests/materialized-reports/fixtures.js +118 -8
- package/lib/tests/materialized-reports/materialized-discount-classification.test.js +34 -24
- package/lib/tests/materialized-reports/materialized-discount-sources.test.js +14 -10
- package/lib/tests/materialized-reports/materialized-integer-contract.test.d.ts +1 -0
- package/lib/tests/materialized-reports/materialized-integer-contract.test.js +223 -0
- package/lib/tests/materialized-reports/materialized-write-paths-inventory.test.d.ts +1 -0
- package/lib/tests/materialized-reports/materialized-write-paths-inventory.test.js +58 -0
- package/lib/tests/materialized-reports/materialized-writers-integer-only.test.d.ts +1 -0
- package/lib/tests/materialized-reports/materialized-writers-integer-only.test.js +150 -0
- package/lib/tests/materialized-reports/sales-overview-baseline.test.js +51 -51
- package/lib/tests/materialized-reports/tenant-discount-source-formatter.test.js +80 -41
- package/package.json +1 -1
|
@@ -67,7 +67,11 @@ export const MaterializedTenantDiscountSourceSchema = new Schema({
|
|
|
67
67
|
enum: [...ALL_MATERIALIZED_DISCOUNT_SLOTS, null],
|
|
68
68
|
},
|
|
69
69
|
sub_kind: { type: String, required: true, enum: ALL_MATERIALIZED_DISCOUNT_SUB_KINDS },
|
|
70
|
-
rate:
|
|
70
|
+
// NO stored average rate: a source stores the integer SUM of its
|
|
71
|
+
// percentage rates (`percentage_rate_sum`, in basis points) and the COUNT
|
|
72
|
+
// of its percentage rows (`percentage_row_count`). The average is DERIVED
|
|
73
|
+
// (sum / count) at the read boundary, so no fractional average is ever
|
|
74
|
+
// stored and the sum stays exact.
|
|
71
75
|
rate_kind: {
|
|
72
76
|
type: String,
|
|
73
77
|
default: null,
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
export * from './key-helpers';
|
|
2
2
|
export * from './materialized-credit-bills-helpers';
|
|
3
|
+
export * from './materialized-integer-contract';
|
|
3
4
|
export * from './materialized-discount-accumulator-helpers';
|
|
4
5
|
export * from './materialized-discount-classification-helpers';
|
|
5
6
|
export * from './materialized-discount-close-day-helpers';
|
|
@@ -16,6 +16,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
|
16
16
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
17
|
__exportStar(require("./key-helpers"), exports);
|
|
18
18
|
__exportStar(require("./materialized-credit-bills-helpers"), exports);
|
|
19
|
+
__exportStar(require("./materialized-integer-contract"), exports);
|
|
19
20
|
__exportStar(require("./materialized-discount-accumulator-helpers"), exports);
|
|
20
21
|
__exportStar(require("./materialized-discount-classification-helpers"), exports);
|
|
21
22
|
__exportStar(require("./materialized-discount-close-day-helpers"), exports);
|
|
@@ -131,8 +131,11 @@ function buildCreditBillIssuedCandidatesFromOrder(order, orderLocalDate, options
|
|
|
131
131
|
const paymentId = payment.payment_id ?? payment._id ?? null;
|
|
132
132
|
if (paymentId == null || paymentId.length === 0)
|
|
133
133
|
return null; // un-keyable bill — data issue
|
|
134
|
-
|
|
135
|
-
|
|
134
|
+
// Money is integer CENTS: the payment amounts are rounded to the cent at
|
|
135
|
+
// this writer boundary, because a materialized ledger document may not
|
|
136
|
+
// hold a decimal.
|
|
137
|
+
const amount = Math.round(payment.amount_due ?? 0);
|
|
138
|
+
const receivedAmount = Math.round(payment.amount_paid ?? 0);
|
|
136
139
|
const settled = !settledLater && receivedAmount >= amount;
|
|
137
140
|
candidates.push({
|
|
138
141
|
order_id: order._id,
|
|
@@ -167,7 +170,8 @@ function buildCreditBillEventCandidatesFromOrder(order, eventLocalDate, options)
|
|
|
167
170
|
const paymentId = payment.payment_id ?? payment._id ?? null;
|
|
168
171
|
if (paymentId == null || paymentId.length === 0)
|
|
169
172
|
return null; // un-keyable bill — data issue
|
|
170
|
-
|
|
173
|
+
// Money is integer CENTS (see the issued-bill candidate above).
|
|
174
|
+
const receivedAmount = Math.round(payment.amount_paid ?? 0);
|
|
171
175
|
if (receivedAmount <= 0)
|
|
172
176
|
continue; // nothing collected yet
|
|
173
177
|
candidates.push({
|
|
@@ -175,7 +179,8 @@ function buildCreditBillEventCandidatesFromOrder(order, eventLocalDate, options)
|
|
|
175
179
|
payment_id: paymentId,
|
|
176
180
|
order_status: order.order_status,
|
|
177
181
|
platform: order.platform,
|
|
178
|
-
|
|
182
|
+
// Money is integer CENTS.
|
|
183
|
+
amount: Math.round(payment.amount_due ?? 0),
|
|
179
184
|
issued_at: issuedAt,
|
|
180
185
|
issued_local_date: orderLocalDate,
|
|
181
186
|
issued_local_hour: issuedHourLabel,
|
|
@@ -151,6 +151,16 @@ function freshDeliveryCounters() {
|
|
|
151
151
|
},
|
|
152
152
|
};
|
|
153
153
|
}
|
|
154
|
+
/**
|
|
155
|
+
* A source money amount → integer CENTS (0 when absent/broken).
|
|
156
|
+
*
|
|
157
|
+
* Rounding happens HERE, at the writer boundary: the materialized document is
|
|
158
|
+
* the thing that must be integral.
|
|
159
|
+
*/
|
|
160
|
+
const cents = (value) => {
|
|
161
|
+
const number = typeof value === 'number' ? value : Number(value);
|
|
162
|
+
return Number.isFinite(number) ? Math.round(number) : 0;
|
|
163
|
+
};
|
|
154
164
|
/** Which fixed distance bucket a metre value falls in. */
|
|
155
165
|
function deliveryDistanceBucketKey(meters) {
|
|
156
166
|
const value = Math.abs(Number(meters) || 0);
|
|
@@ -215,17 +225,20 @@ function addDeliveryOrder(acc, order) {
|
|
|
215
225
|
const counters = acc.counters;
|
|
216
226
|
counters.adoption.delivery_order_count += 1;
|
|
217
227
|
const details = order.delivery_details ?? {};
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
counters.money.
|
|
221
|
-
counters.money.
|
|
222
|
-
counters.money.
|
|
223
|
-
counters.money.
|
|
228
|
+
// Money is integer CENTS: each source amount is rounded to the cent at this
|
|
229
|
+
// writer boundary, because a materialized document may not hold a decimal.
|
|
230
|
+
counters.money.net_sale_amount += cents(order.net_sale_amount ?? order.amount_earned);
|
|
231
|
+
counters.money.collected_amount += cents(order.amount_collected);
|
|
232
|
+
counters.money.tip_amount += cents(order.tip_amount);
|
|
233
|
+
counters.money.discount_amount += cents(order.total_discount_applied);
|
|
234
|
+
counters.money.refund_amount += cents(order.amount_refunded);
|
|
235
|
+
counters.money.tax_amount += cents(order.gst_amount) + cents(order.tax_amount);
|
|
224
236
|
// `delivery_cost` is the field IOrderDeliveryDetails ACTUALLY declares; the other two
|
|
225
237
|
// names are tolerated fallbacks. Reading the wrong one silently reported every charge
|
|
226
238
|
// as ZERO while the statement row (which used the right field) showed the real value -
|
|
227
239
|
// an inconsistency the formatter test caught.
|
|
228
|
-
|
|
240
|
+
// Money is integer CENTS.
|
|
241
|
+
const charge = cents(details.delivery_cost ?? details.delivery_charge ?? details.delivery_charge_amount);
|
|
229
242
|
if (charge !== 0) {
|
|
230
243
|
counters.money.delivery_charge_amount += charge;
|
|
231
244
|
counters.money.delivery_charge_count += 1;
|
|
@@ -272,12 +285,15 @@ function addDelivery(acc, delivery, order, key) {
|
|
|
272
285
|
// the rider before completion and must not inflate the materialized report.
|
|
273
286
|
const earnings = delivery.rider_earnings;
|
|
274
287
|
const isFinalPayout = earnings?.status === delivery_1.RIDER_EARNINGS_STATUS_ENUM.FINAL;
|
|
275
|
-
|
|
288
|
+
// Money is integer CENTS.
|
|
289
|
+
const revenue = isFinalPayout ? cents(earnings.amount) : 0;
|
|
276
290
|
if (isFinalPayout) {
|
|
277
291
|
counters.money.rider_revenue_amount += revenue;
|
|
278
292
|
counters.money.rider_revenue_count += 1;
|
|
279
293
|
}
|
|
280
|
-
|
|
294
|
+
// The distance is stored in whole METRES (the unit the delivery collection
|
|
295
|
+
// documents it in) — a materialized document may not hold a decimal.
|
|
296
|
+
const meters = Math.round(Number(delivery.distance_in_meters_from_store) || 0);
|
|
281
297
|
counters.distance.sum_meters += meters;
|
|
282
298
|
counters.distance.count += 1;
|
|
283
299
|
const bucketKey = deliveryDistanceBucketKey(meters);
|
|
@@ -176,9 +176,11 @@ function buildEntryRow(delivery, order, details) {
|
|
|
176
176
|
rider_name: delivery?.rider_name == null ? null : String(delivery.rider_name),
|
|
177
177
|
status: status,
|
|
178
178
|
cancel_reason: delivery?.cancel_reason == null ? null : String(delivery.cancel_reason),
|
|
179
|
-
|
|
179
|
+
// The distance is stored in whole METRES and the revenue in integer CENTS —
|
|
180
|
+
// a materialized document may not hold a decimal.
|
|
181
|
+
distance_meters: Math.round(Number(delivery?.distance_in_meters_from_store) || 0),
|
|
180
182
|
rider_revenue: delivery?.rider_earnings?.status === delivery_1.RIDER_EARNINGS_STATUS_ENUM.FINAL
|
|
181
|
-
? Number(delivery.rider_earnings.amount) || 0
|
|
183
|
+
? Math.round(Number(delivery.rider_earnings.amount) || 0)
|
|
182
184
|
: null,
|
|
183
185
|
tracking_enabled: delivery?.tracking_enabled === true,
|
|
184
186
|
has_pickup_proof: delivery?.pickup_food_image_url != null,
|
|
@@ -188,9 +190,10 @@ function buildEntryRow(delivery, order, details) {
|
|
|
188
190
|
city: details?.city == null ? null : String(details.city),
|
|
189
191
|
state: details?.state == null ? null : String(details.state),
|
|
190
192
|
street: details?.street == null ? null : String(details.street),
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
193
|
+
// Money is integer CENTS.
|
|
194
|
+
net_sale_amount: Math.round(Number(order?.net_sale_amount ?? order?.amount_earned) || 0),
|
|
195
|
+
collected_amount: Math.round(Number(order?.amount_collected) || 0),
|
|
196
|
+
delivery_charge: Math.round(Number(details?.delivery_cost) || 0),
|
|
194
197
|
order_created_at: orderCreatedAt ?? createdAt,
|
|
195
198
|
assigned_at: delivery?.assigned_at == null ? null : new Date(delivery.assigned_at),
|
|
196
199
|
picked_up_at: delivery?.picked_up_at == null ? null : new Date(delivery.picked_up_at),
|
|
@@ -23,6 +23,16 @@ import { createEmptyDiscountSlotCounter } from './materialized-discount-classifi
|
|
|
23
23
|
* - Negative discounts are surcharges (the POS drops them from
|
|
24
24
|
* `total_discount_applied`); they contribute nothing here.
|
|
25
25
|
*
|
|
26
|
+
* UNITS (the integer-only storage contract — see
|
|
27
|
+
* `materialized-integer-contract.ts`):
|
|
28
|
+
* - `amount` / `resolved_amount` / `item_value` / `covered_amount` /
|
|
29
|
+
* `order_amount` — integer CENTS (the order's money fields are already
|
|
30
|
+
* integer cents; this accumulator copies them unchanged);
|
|
31
|
+
* - `rate` — integer BASIS POINTS for a percentage row (1% = 100 bps) and
|
|
32
|
+
* integer CENTS for a fixed row. The order's discount details are written in
|
|
33
|
+
* that same unit (`getOrderDiscountDetailsWithPrice`), so the raw value is
|
|
34
|
+
* passed through WITHOUT a conversion.
|
|
35
|
+
*
|
|
26
36
|
* Pure and total: no throws, no clock, no I/O.
|
|
27
37
|
*/
|
|
28
38
|
/** Punch-hour label of an order's local day (`'YYYY-MM-DD HH'`), hour = 0..23. */
|
|
@@ -40,6 +50,14 @@ export interface IAccumulateOrderDiscountsResult {
|
|
|
40
50
|
/** Orders the accumulator would count (has ANY discount or a comp payment). */
|
|
41
51
|
has_discount: boolean;
|
|
42
52
|
}
|
|
53
|
+
/**
|
|
54
|
+
* 100% off, in BASIS POINTS (the stored unit of a percentage rate).
|
|
55
|
+
*
|
|
56
|
+
* A percentage rate is stored in integer basis points (1% = 100 bps), so the
|
|
57
|
+
* "this item is free" test is `rate >= 10000` — a UNIT comparison against a
|
|
58
|
+
* named constant, never a magnitude guess.
|
|
59
|
+
*/
|
|
60
|
+
export declare const FULL_DISCOUNT_BASIS_POINTS: number;
|
|
43
61
|
/** One comp tender's share of an order's coverage. */
|
|
44
62
|
export interface IComplimentaryPaymentShare {
|
|
45
63
|
payment_id: string | null;
|
|
@@ -1,15 +1,24 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.createEmptyDiscountSlotCounter = exports.toDiscountHourLabel = void 0;
|
|
3
|
+
exports.createEmptyDiscountSlotCounter = exports.toDiscountHourLabel = exports.FULL_DISCOUNT_BASIS_POINTS = void 0;
|
|
4
4
|
exports.classifyComplimentaryOrder = classifyComplimentaryOrder;
|
|
5
5
|
exports.accumulateOrderDiscounts = accumulateOrderDiscounts;
|
|
6
6
|
exports.mergeDiscountSlotCounters = mergeDiscountSlotCounters;
|
|
7
7
|
const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
|
|
8
8
|
const order_1 = require("../../constants/enums/order");
|
|
9
9
|
const payments_1 = require("../../constants/enums/payments");
|
|
10
|
+
const percentage_conversion_1 = require("../utils/percentage-conversion");
|
|
10
11
|
const materialized_discount_classification_helpers_1 = require("./materialized-discount-classification-helpers");
|
|
11
12
|
Object.defineProperty(exports, "createEmptyDiscountSlotCounter", { enumerable: true, get: function () { return materialized_discount_classification_helpers_1.createEmptyDiscountSlotCounter; } });
|
|
12
13
|
const isComplimentaryPayment = (payment) => payment?.payment_type === payments_1.PAYMENT_TYPE_ENUM.COMPLIMENTARY;
|
|
14
|
+
/**
|
|
15
|
+
* 100% off, in BASIS POINTS (the stored unit of a percentage rate).
|
|
16
|
+
*
|
|
17
|
+
* A percentage rate is stored in integer basis points (1% = 100 bps), so the
|
|
18
|
+
* "this item is free" test is `rate >= 10000` — a UNIT comparison against a
|
|
19
|
+
* named constant, never a magnitude guess.
|
|
20
|
+
*/
|
|
21
|
+
exports.FULL_DISCOUNT_BASIS_POINTS = (0, percentage_conversion_1.convertPercentToBasisPoints)(100);
|
|
13
22
|
/**
|
|
14
23
|
* Classifies an order's COMPLIMENTARY tenders. Returns null when there is none.
|
|
15
24
|
*
|
|
@@ -142,7 +151,10 @@ function orderSubKindCounter(counters, slot, subKind) {
|
|
|
142
151
|
function accumulateItemSlot(counters, entries, order, context, itemId, catalogItemId, itemName, itemValue, reading, resolved, itemTotal, catalogAuto) {
|
|
143
152
|
const raw = nonNegative(reading.rate);
|
|
144
153
|
const money = nonNegative(resolved);
|
|
145
|
-
|
|
154
|
+
// A percentage rate is stored in BASIS POINTS (1% = 100 bps), so "100% off" is
|
|
155
|
+
// 10000 bps. This is a UNIT comparison, not a magnitude heuristic: the unit is
|
|
156
|
+
// fixed by the storage contract, so the threshold is a named constant.
|
|
157
|
+
const isFree = reading.is_percentage && raw >= exports.FULL_DISCOUNT_BASIS_POINTS;
|
|
146
158
|
if (reading.slot === MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_SLOT_ENUM.SPECIAL) {
|
|
147
159
|
const counter = counters.item_special;
|
|
148
160
|
counter.count += 1;
|
|
@@ -281,7 +281,6 @@ function classifyDiscountEntrySource(entry) {
|
|
|
281
281
|
return unattributedIdentity(level);
|
|
282
282
|
}
|
|
283
283
|
const nonNegative = (value) => (Number.isFinite(value) && value > 0 ? value : 0);
|
|
284
|
-
const round2 = (value) => Math.round((value ?? 0) * 100) / 100;
|
|
285
284
|
const emptyMetrics = () => ({
|
|
286
285
|
orderIds: new Set(),
|
|
287
286
|
row_count: 0,
|
|
@@ -384,7 +383,6 @@ function buildDiscountSourcesForScope(input) {
|
|
|
384
383
|
const docs = [];
|
|
385
384
|
for (const bucket of buckets.values()) {
|
|
386
385
|
const { identity, totals } = bucket;
|
|
387
|
-
const rate = totals.percentage_row_count > 0 ? round2(totals.percentage_rate_sum / totals.percentage_row_count) : null;
|
|
388
386
|
const kind = identity.kind === MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_ENTRY_KIND_ENUM.COMPLIMENTARY
|
|
389
387
|
? MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_ENTRY_KIND_ENUM.COMPLIMENTARY
|
|
390
388
|
: totals.free_item_count > 0 && totals.free_item_count === totals.row_count
|
|
@@ -405,7 +403,6 @@ function buildDiscountSourcesForScope(input) {
|
|
|
405
403
|
level: identity.level,
|
|
406
404
|
slot: identity.slot,
|
|
407
405
|
sub_kind: identity.sub_kind,
|
|
408
|
-
rate,
|
|
409
406
|
rate_kind: rateKindOf(totals),
|
|
410
407
|
percentage_row_count: totals.percentage_row_count,
|
|
411
408
|
percentage_rate_sum: totals.percentage_rate_sum,
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* THE integer-only storage contract for materialized report documents.
|
|
3
|
+
*
|
|
4
|
+
* Every numeric leaf of every materialized document is an INTEGER:
|
|
5
|
+
*
|
|
6
|
+
* | category | unit |
|
|
7
|
+
* |--------------------------------------------|-----------------------------------------|
|
|
8
|
+
* | money (`*_amount`, `*_value`, `covered_amount`) | integer CENTS |
|
|
9
|
+
* | percentage rates (`rate`, `percentage_rate_sum`) | integer BASIS POINTS (1% = 100 bps) |
|
|
10
|
+
* | durations | integer MINUTES |
|
|
11
|
+
* | counts / iterations / schema versions | integers |
|
|
12
|
+
* | shares, averages, ratios | NOT stored — derived in the formatter |
|
|
13
|
+
*
|
|
14
|
+
* The contract exists because a float in a stored document is a silent
|
|
15
|
+
* precision decision: `0.1 + 0.2` is not `0.3`, and a report that sums floats
|
|
16
|
+
* drifts from the ledger it claims to mirror. Units are converted ONCE, at a
|
|
17
|
+
* documented boundary, and then the value is only ever copied.
|
|
18
|
+
*
|
|
19
|
+
* This module is the enforcement point:
|
|
20
|
+
* - `findNonIntegerNumericLeaves` reports every offending path (audit / tests).
|
|
21
|
+
* - `assertIntegerOnlyDocument` throws with the offending path (persistence).
|
|
22
|
+
*
|
|
23
|
+
* It is a VALIDATOR, not a rounding pass. A decimal that reaches this point is
|
|
24
|
+
* a bug in a writer, and the writer must fix its unit — silently rounding it
|
|
25
|
+
* would hide the defect and bake a wrong number into the report.
|
|
26
|
+
*/
|
|
27
|
+
/** Why a numeric leaf is not allowed in a materialized document. */
|
|
28
|
+
export type TMaterializedNumericViolationReason =
|
|
29
|
+
/** A decimal number (e.g. `131.25`). */
|
|
30
|
+
'decimal'
|
|
31
|
+
/** `NaN` / `Infinity` / `-Infinity`. */
|
|
32
|
+
| 'non-finite'
|
|
33
|
+
/** A numeric string (`'131.25'`) — a decimal smuggled in as text. */
|
|
34
|
+
| 'numeric-string';
|
|
35
|
+
export interface IMaterializedNumericViolation {
|
|
36
|
+
/** Dotted path of the offending leaf (`discount_counters.X.payments[].amount`). */
|
|
37
|
+
path: string;
|
|
38
|
+
/** The rejected value. */
|
|
39
|
+
value: unknown;
|
|
40
|
+
reason: TMaterializedNumericViolationReason;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Collects every numeric leaf that violates the integer-only contract.
|
|
44
|
+
*
|
|
45
|
+
* Walks plain objects and arrays. Ignores `Date`, `ObjectId`, `null`,
|
|
46
|
+
* booleans, buffers and strings that are not numeric. Rejects:
|
|
47
|
+
* - decimal numbers,
|
|
48
|
+
* - `NaN` / `Infinity`,
|
|
49
|
+
* - strings that look numeric.
|
|
50
|
+
*/
|
|
51
|
+
export declare function findNonIntegerNumericLeaves(document: unknown): IMaterializedNumericViolation[];
|
|
52
|
+
/**
|
|
53
|
+
* Throws when a materialized document violates the integer-only contract.
|
|
54
|
+
*
|
|
55
|
+
* Called at persistence, right before the write. The message names the
|
|
56
|
+
* offending path so the writer that produced it can be fixed directly.
|
|
57
|
+
*/
|
|
58
|
+
export declare function assertIntegerOnlyDocument(document: unknown, context?: {
|
|
59
|
+
collection?: string;
|
|
60
|
+
label?: string;
|
|
61
|
+
}): void;
|
|
62
|
+
/**
|
|
63
|
+
* Asserts a whole SET of documents (a scope, a plan, a batch) in one call.
|
|
64
|
+
*/
|
|
65
|
+
export declare function assertIntegerOnlyDocuments(documents: unknown[], context?: {
|
|
66
|
+
collection?: string;
|
|
67
|
+
label?: string;
|
|
68
|
+
}): void;
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* THE integer-only storage contract for materialized report documents.
|
|
4
|
+
*
|
|
5
|
+
* Every numeric leaf of every materialized document is an INTEGER:
|
|
6
|
+
*
|
|
7
|
+
* | category | unit |
|
|
8
|
+
* |--------------------------------------------|-----------------------------------------|
|
|
9
|
+
* | money (`*_amount`, `*_value`, `covered_amount`) | integer CENTS |
|
|
10
|
+
* | percentage rates (`rate`, `percentage_rate_sum`) | integer BASIS POINTS (1% = 100 bps) |
|
|
11
|
+
* | durations | integer MINUTES |
|
|
12
|
+
* | counts / iterations / schema versions | integers |
|
|
13
|
+
* | shares, averages, ratios | NOT stored — derived in the formatter |
|
|
14
|
+
*
|
|
15
|
+
* The contract exists because a float in a stored document is a silent
|
|
16
|
+
* precision decision: `0.1 + 0.2` is not `0.3`, and a report that sums floats
|
|
17
|
+
* drifts from the ledger it claims to mirror. Units are converted ONCE, at a
|
|
18
|
+
* documented boundary, and then the value is only ever copied.
|
|
19
|
+
*
|
|
20
|
+
* This module is the enforcement point:
|
|
21
|
+
* - `findNonIntegerNumericLeaves` reports every offending path (audit / tests).
|
|
22
|
+
* - `assertIntegerOnlyDocument` throws with the offending path (persistence).
|
|
23
|
+
*
|
|
24
|
+
* It is a VALIDATOR, not a rounding pass. A decimal that reaches this point is
|
|
25
|
+
* a bug in a writer, and the writer must fix its unit — silently rounding it
|
|
26
|
+
* would hide the defect and bake a wrong number into the report.
|
|
27
|
+
*/
|
|
28
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
29
|
+
exports.findNonIntegerNumericLeaves = findNonIntegerNumericLeaves;
|
|
30
|
+
exports.assertIntegerOnlyDocument = assertIntegerOnlyDocument;
|
|
31
|
+
exports.assertIntegerOnlyDocuments = assertIntegerOnlyDocuments;
|
|
32
|
+
/** A string that is entirely a number (decimal or not) — never allowed in a document. */
|
|
33
|
+
const NUMERIC_STRING = /^[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?$/;
|
|
34
|
+
/**
|
|
35
|
+
* IDENTIFIER fields may legitimately hold a numeric-looking string.
|
|
36
|
+
*
|
|
37
|
+
* A materialized document names its scopes with strings: `scope_field: "2026"`
|
|
38
|
+
* (a year scope), `day_index: "2026-09-15"`, `_id` / `order_id` / `entry_key` /
|
|
39
|
+
* `source_key` (opaque ids). Those are identifiers, not money, so they are not
|
|
40
|
+
* violations — while a numeric string in a field that holds a NUMBER (money,
|
|
41
|
+
* a rate, a count) is a decimal smuggled in as text and IS a violation. The
|
|
42
|
+
* schema catches the typed case; this rule catches the `Mixed` payload case.
|
|
43
|
+
*/
|
|
44
|
+
const IDENTIFIER_FIELD = /^(scope_field|day_index|key|_id|.*_id)$/;
|
|
45
|
+
/**
|
|
46
|
+
* Human/readable fields may legitimately contain a numeric-looking string
|
|
47
|
+
* (`source_name: "50"`, `reason: "123"`). They are not numeric storage: the
|
|
48
|
+
* integer contract applies to money/rate/count/duration leaves. Only reject a
|
|
49
|
+
* numeric-looking string when it sits in a field that is not one of these.
|
|
50
|
+
*/
|
|
51
|
+
const TEXT_FIELD = /(name|label|title|reason|note|description|reference|code|currency|platform|status|type|source_key|order_number)$/i;
|
|
52
|
+
/**
|
|
53
|
+
* Mongo ObjectId / BSON values are identity, not numbers.
|
|
54
|
+
*
|
|
55
|
+
* Duck-typed on `_bsontype` so the toolkit keeps no mongoose dependency
|
|
56
|
+
* (it is published to the frontends too).
|
|
57
|
+
*/
|
|
58
|
+
const isBsonLike = (value) => typeof value === 'object' && value !== null && typeof value._bsontype === 'string';
|
|
59
|
+
/** Dates, buffers and other non-numeric leaves are ignored. */
|
|
60
|
+
const isIgnoredLeaf = (value) => value === null ||
|
|
61
|
+
typeof value === 'boolean' ||
|
|
62
|
+
value instanceof Date ||
|
|
63
|
+
value instanceof RegExp ||
|
|
64
|
+
(typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) ||
|
|
65
|
+
isBsonLike(value);
|
|
66
|
+
const childPath = (parent, key) => (parent.length === 0 ? key : `${parent}.${key}`);
|
|
67
|
+
/**
|
|
68
|
+
* Collects every numeric leaf that violates the integer-only contract.
|
|
69
|
+
*
|
|
70
|
+
* Walks plain objects and arrays. Ignores `Date`, `ObjectId`, `null`,
|
|
71
|
+
* booleans, buffers and strings that are not numeric. Rejects:
|
|
72
|
+
* - decimal numbers,
|
|
73
|
+
* - `NaN` / `Infinity`,
|
|
74
|
+
* - strings that look numeric.
|
|
75
|
+
*/
|
|
76
|
+
function findNonIntegerNumericLeaves(document) {
|
|
77
|
+
const violations = [];
|
|
78
|
+
const walk = (node, path) => {
|
|
79
|
+
if (node === undefined)
|
|
80
|
+
return;
|
|
81
|
+
if (isIgnoredLeaf(node))
|
|
82
|
+
return;
|
|
83
|
+
if (typeof node === 'number') {
|
|
84
|
+
if (!Number.isFinite(node)) {
|
|
85
|
+
violations.push({ path, value: node, reason: 'non-finite' });
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
if (!Number.isInteger(node)) {
|
|
89
|
+
violations.push({ path, value: node, reason: 'decimal' });
|
|
90
|
+
}
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
if (typeof node === 'string') {
|
|
94
|
+
const key = path.slice(path.lastIndexOf('.') + 1);
|
|
95
|
+
if (NUMERIC_STRING.test(node.trim()) &&
|
|
96
|
+
node.trim().length > 0 &&
|
|
97
|
+
!IDENTIFIER_FIELD.test(key) &&
|
|
98
|
+
!TEXT_FIELD.test(key)) {
|
|
99
|
+
violations.push({ path, value: node, reason: 'numeric-string' });
|
|
100
|
+
}
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
if (Array.isArray(node)) {
|
|
104
|
+
node.forEach((item, index) => walk(item, `${path}[${index}]`));
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
if (typeof node === 'object') {
|
|
108
|
+
for (const [key, value] of Object.entries(node)) {
|
|
109
|
+
walk(value, childPath(path, key));
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
};
|
|
113
|
+
walk(document, '');
|
|
114
|
+
return violations;
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Throws when a materialized document violates the integer-only contract.
|
|
118
|
+
*
|
|
119
|
+
* Called at persistence, right before the write. The message names the
|
|
120
|
+
* offending path so the writer that produced it can be fixed directly.
|
|
121
|
+
*/
|
|
122
|
+
function assertIntegerOnlyDocument(document, context) {
|
|
123
|
+
const violations = findNonIntegerNumericLeaves(document);
|
|
124
|
+
if (violations.length === 0)
|
|
125
|
+
return;
|
|
126
|
+
const scope = context?.label ?? context?.collection ?? 'materialized document';
|
|
127
|
+
const preview = violations
|
|
128
|
+
.slice(0, 5)
|
|
129
|
+
.map((violation) => `${violation.path || '<root>'}=${String(violation.value)} (${violation.reason})`)
|
|
130
|
+
.join(', ');
|
|
131
|
+
const more = violations.length > 5 ? `, +${violations.length - 5} more` : '';
|
|
132
|
+
throw new Error(`Integer-only storage contract violated in ${scope}: ${preview}${more}. ` +
|
|
133
|
+
'Materialized documents store integer cents / basis points / minutes — ' +
|
|
134
|
+
'convert the unit at the writer boundary instead of persisting a decimal.');
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Asserts a whole SET of documents (a scope, a plan, a batch) in one call.
|
|
138
|
+
*/
|
|
139
|
+
function assertIntegerOnlyDocuments(documents, context) {
|
|
140
|
+
documents.forEach((document, index) => {
|
|
141
|
+
const scope = context?.label ?? context?.collection;
|
|
142
|
+
assertIntegerOnlyDocument(document, {
|
|
143
|
+
collection: scope,
|
|
144
|
+
label: scope != null ? `${scope}[${index}]` : undefined,
|
|
145
|
+
});
|
|
146
|
+
});
|
|
147
|
+
}
|
package/lib/helpers/materialized-reports/materialized-payments-comparison-accumulator-helpers.js
CHANGED
|
@@ -25,9 +25,15 @@ Object.defineProperty(exports, "normalizeMaterializedPaymentType", { enumerable:
|
|
|
25
25
|
* OPEN string; only reserved key characters make it un-keyable.
|
|
26
26
|
*/
|
|
27
27
|
/** Coerces a source amount to a finite number (0 when absent/broken). */
|
|
28
|
+
/**
|
|
29
|
+
* A source money amount → integer CENTS (0 when absent/broken).
|
|
30
|
+
*
|
|
31
|
+
* The order's money is integer cents; rounding here is the writer boundary
|
|
32
|
+
* that guarantees a materialized document never holds a decimal.
|
|
33
|
+
*/
|
|
28
34
|
const cents = (value) => {
|
|
29
35
|
const number = typeof value === 'number' ? value : Number(value);
|
|
30
|
-
return Number.isFinite(number) ? number : 0;
|
|
36
|
+
return Number.isFinite(number) ? Math.round(number) : 0;
|
|
31
37
|
};
|
|
32
38
|
function createEmptyPaymentsComparisonCounters() {
|
|
33
39
|
return {
|
|
@@ -10,12 +10,19 @@ const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
|
|
|
10
10
|
/**
|
|
11
11
|
* Numeric or null - never NaN. The stored field is a duration in whole minutes.
|
|
12
12
|
*/
|
|
13
|
+
/**
|
|
14
|
+
* A source duration → whole MINUTES (the stored unit).
|
|
15
|
+
*
|
|
16
|
+
* A duration in a materialized document is an integer number of minutes, so a
|
|
17
|
+
* fractional source value is rounded here — at the writer boundary — instead
|
|
18
|
+
* of travelling into the document.
|
|
19
|
+
*/
|
|
13
20
|
const toMinutes = (value) => {
|
|
14
21
|
if (typeof value === 'number' && Number.isFinite(value))
|
|
15
|
-
return value;
|
|
22
|
+
return Math.round(value);
|
|
16
23
|
if (typeof value === 'string' && value.trim() !== '') {
|
|
17
24
|
const parsed = Number(value);
|
|
18
|
-
return Number.isFinite(parsed) ? parsed : null;
|
|
25
|
+
return Number.isFinite(parsed) ? Math.round(parsed) : null;
|
|
19
26
|
}
|
|
20
27
|
return null;
|
|
21
28
|
};
|
package/lib/helpers/materialized-reports/materialized-sales-comparison-accumulator-helpers.js
CHANGED
|
@@ -40,13 +40,20 @@ const ENUMS_1 = require("../../constants/ENUMS");
|
|
|
40
40
|
* orders are keyed `CANCELLED:*` and are split out by the formatter, exactly
|
|
41
41
|
* like the overview.
|
|
42
42
|
*
|
|
43
|
-
* Every value is added
|
|
44
|
-
*
|
|
43
|
+
* Every MONEY value is added in integer CENTS: the order's money is integer
|
|
44
|
+
* cents (see the order-write boundary), and a materialized document may not
|
|
45
|
+
* hold a decimal, so each amount is rounded to the cent HERE — the writer
|
|
46
|
+
* boundary — rather than being copied into the document as-is.
|
|
47
|
+
*/
|
|
48
|
+
/**
|
|
49
|
+
* A source money amount → integer CENTS (0 when absent/broken).
|
|
50
|
+
*
|
|
51
|
+
* The order's money is integer cents; rounding here is the LAST step that can
|
|
52
|
+
* guarantee it, because a materialized document must never hold a decimal.
|
|
45
53
|
*/
|
|
46
|
-
/** Coerces a source amount to a finite number (0 when absent/broken). */
|
|
47
54
|
const cents = (value) => {
|
|
48
55
|
const number = typeof value === 'number' ? value : Number(value);
|
|
49
|
-
return Number.isFinite(number) ? number : 0;
|
|
56
|
+
return Number.isFinite(number) ? Math.round(number) : 0;
|
|
50
57
|
};
|
|
51
58
|
const isFiniteNumber = (value) => typeof value === 'number' && Number.isFinite(value);
|
|
52
59
|
/** A zeroed counter block. */
|
|
@@ -79,16 +86,19 @@ const itemsGrossAmount = (order) => {
|
|
|
79
86
|
function getOrderGrossAmountCents(order) {
|
|
80
87
|
if (order == null)
|
|
81
88
|
return 0;
|
|
89
|
+
// Money is integer CENTS: the order's own fields are rounded to the cent at
|
|
90
|
+
// this boundary, so a materialized document never holds a decimal.
|
|
82
91
|
if (isFiniteNumber(order.price))
|
|
83
|
-
return order.price;
|
|
84
|
-
return itemsGrossAmount(order);
|
|
92
|
+
return Math.round(order.price);
|
|
93
|
+
return Math.round(itemsGrossAmount(order));
|
|
85
94
|
}
|
|
86
95
|
/** Discounts applied to the order, in CENTS. */
|
|
87
96
|
function getOrderDiscountAmountCents(order) {
|
|
88
97
|
if (order == null)
|
|
89
98
|
return 0;
|
|
99
|
+
// Money is integer CENTS.
|
|
90
100
|
if (isFiniteNumber(order.total_discount_applied))
|
|
91
|
-
return order.total_discount_applied;
|
|
101
|
+
return Math.round(order.total_discount_applied);
|
|
92
102
|
return cents(order.order_discount_details?.total_discount);
|
|
93
103
|
}
|
|
94
104
|
/** Total tax collected, in CENTS (GST + the unused `tax_amount` bucket). */
|
|
@@ -4,11 +4,16 @@ import { IMaterializedTenantDiscountSourcesReport } from '../types/materialized-
|
|
|
4
4
|
* Frontend formatter for `POST /reports/discounts/sources` — the "By discount"
|
|
5
5
|
* tab.
|
|
6
6
|
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
7
|
+
* UNITS (the integer-only storage contract):
|
|
8
|
+
* - money is stored in integer CENTS and converts to decimals exactly once,
|
|
9
|
+
* here;
|
|
10
|
+
* - a percentage rate is stored in integer BASIS POINTS (1% = 100 bps) and
|
|
11
|
+
* converts to percent exactly once, here;
|
|
12
|
+
* - `share_percent` is computed from the formatted rows themselves so the
|
|
13
|
+
* table always sums to 100% (excluding complimentary, which is deliberately
|
|
14
|
+
* not a discount). The endpoint already folded the selection's scope groups
|
|
15
|
+
* and applied the platform / order-status filters, so this formatter never
|
|
16
|
+
* re-aggregates money.
|
|
12
17
|
*/
|
|
13
18
|
export interface IFormattedDiscountSourceRow {
|
|
14
19
|
source_key: string;
|
|
@@ -21,9 +26,9 @@ export interface IFormattedDiscountSourceRow {
|
|
|
21
26
|
type_label: string;
|
|
22
27
|
/** The rate kind as its own label ("Percentage" / "Fixed" / "Mixed" / "—"). */
|
|
23
28
|
rate_kind_label: string;
|
|
24
|
-
/**
|
|
29
|
+
/** The DERIVED average rate in integer BASIS POINTS (1% = 100 bps); null when absent. */
|
|
25
30
|
rate: number | null;
|
|
26
|
-
/**
|
|
31
|
+
/** The display percentage — basis points converted to percent exactly once. */
|
|
27
32
|
rate_percent: number | null;
|
|
28
33
|
rate_label: string;
|
|
29
34
|
order_count: number;
|
|
@@ -69,29 +74,6 @@ export interface IDiscountSourceShareReconciliation {
|
|
|
69
74
|
show_overage: boolean;
|
|
70
75
|
}
|
|
71
76
|
export declare function getDiscountSourceShareReconciliation(summaryTotal: number | null | undefined, sourceTotal: number): IDiscountSourceShareReconciliation;
|
|
72
|
-
/**
|
|
73
|
-
* THE rate normalisation rule for discount source rows.
|
|
74
|
-
*
|
|
75
|
-
* A source row's `rate` is the average of the percentage rates of its
|
|
76
|
-
* percentage rows, copied verbatim from the order's discount details. The
|
|
77
|
-
* WRITE side has no single unit for that field: the `discounts` collection
|
|
78
|
-
* stores a percentage value in CENTS (`value` is an `IPrice`, so 50% is
|
|
79
|
-
* stored as 5000) and some writers copy that raw number into the order's
|
|
80
|
-
* discount details, while others (manual quick discounts, payment-type
|
|
81
|
-
* discounts) store the plain percent (25 for 25%). The stored source row
|
|
82
|
-
* therefore carries whichever form the writer used.
|
|
83
|
-
*
|
|
84
|
-
* THE RULE (one rule, applied at the display boundary):
|
|
85
|
-
* - a rate ABOVE 100 is CENTS-SCALED -> divide by 100 (5000 -> 50%);
|
|
86
|
-
* - a rate of 100 or below is ALREADY a percentage -> use as-is (15 -> 15%).
|
|
87
|
-
*
|
|
88
|
-
* A real percentage discount can never exceed 100 (the POS clamps it), so the
|
|
89
|
-
* >100 boundary separates the two forms for every value the platform can
|
|
90
|
-
* produce, except exactly 100, which is read as 100%.
|
|
91
|
-
*
|
|
92
|
-
* This is a DISPLAY rule only: it never rewrites a stored document.
|
|
93
|
-
*/
|
|
94
|
-
export declare function normalizeDiscountSourceRatePercent(rate: number | null | undefined): number | null;
|
|
95
77
|
/**
|
|
96
78
|
* Formats one or more tenants' source records into the page model.
|
|
97
79
|
*
|