@managesome/eposmatic-toolkit 0.4.25 → 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.
Files changed (60) hide show
  1. package/esm/helpers/materialized-reports/index.js +1 -0
  2. package/esm/helpers/materialized-reports/materialized-credit-bills-helpers.js +9 -4
  3. package/esm/helpers/materialized-reports/materialized-delivery-classification-helpers.js +25 -9
  4. package/esm/helpers/materialized-reports/materialized-delivery-compile-helpers.js +8 -5
  5. package/esm/helpers/materialized-reports/materialized-discount-accumulator-helpers.js +13 -1
  6. package/esm/helpers/materialized-reports/materialized-discount-source-helpers.js +0 -3
  7. package/esm/helpers/materialized-reports/materialized-integer-contract.js +142 -0
  8. package/esm/helpers/materialized-reports/materialized-payments-comparison-accumulator-helpers.js +7 -1
  9. package/esm/helpers/materialized-reports/materialized-prep-time-classification-helpers.js +9 -2
  10. package/esm/helpers/materialized-reports/materialized-sales-comparison-accumulator-helpers.js +17 -7
  11. package/esm/helpers/materialized-reports/tenant-discount-source-formatter.js +36 -6
  12. package/esm/helpers/materialized-reports/tenant-sales-overview-helpers.js +4 -2
  13. package/esm/helpers/utils/duration-conversion.js +31 -0
  14. package/esm/helpers/utils/index.js +2 -0
  15. package/esm/helpers/utils/percentage-conversion.js +69 -0
  16. package/esm/schemas/models/materialized_tenant_discount_sources.js +5 -1
  17. package/esm/schemas/models/tenant_hr_shift_schedules.js +4 -0
  18. package/esm/schemas/models/tenant_hr_shifts.js +4 -0
  19. package/lib/helpers/materialized-reports/index.d.ts +1 -0
  20. package/lib/helpers/materialized-reports/index.js +1 -0
  21. package/lib/helpers/materialized-reports/materialized-credit-bills-helpers.js +9 -4
  22. package/lib/helpers/materialized-reports/materialized-delivery-classification-helpers.js +25 -9
  23. package/lib/helpers/materialized-reports/materialized-delivery-compile-helpers.js +8 -5
  24. package/lib/helpers/materialized-reports/materialized-discount-accumulator-helpers.d.ts +18 -0
  25. package/lib/helpers/materialized-reports/materialized-discount-accumulator-helpers.js +14 -2
  26. package/lib/helpers/materialized-reports/materialized-discount-source-helpers.js +0 -3
  27. package/lib/helpers/materialized-reports/materialized-integer-contract.d.ts +68 -0
  28. package/lib/helpers/materialized-reports/materialized-integer-contract.js +147 -0
  29. package/lib/helpers/materialized-reports/materialized-payments-comparison-accumulator-helpers.js +7 -1
  30. package/lib/helpers/materialized-reports/materialized-prep-time-classification-helpers.js +9 -2
  31. package/lib/helpers/materialized-reports/materialized-sales-comparison-accumulator-helpers.js +17 -7
  32. package/lib/helpers/materialized-reports/tenant-discount-source-formatter.d.ts +15 -5
  33. package/lib/helpers/materialized-reports/tenant-discount-source-formatter.js +36 -6
  34. package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.js +4 -2
  35. package/lib/helpers/types/materialized-reports-apis.d.ts +11 -3
  36. package/lib/helpers/utils/duration-conversion.d.ts +19 -0
  37. package/lib/helpers/utils/duration-conversion.js +37 -0
  38. package/lib/helpers/utils/index.d.ts +2 -0
  39. package/lib/helpers/utils/index.js +2 -0
  40. package/lib/helpers/utils/percentage-conversion.d.ts +49 -0
  41. package/lib/helpers/utils/percentage-conversion.js +76 -0
  42. package/lib/schemas/models/materialized_tenant_discount_sources.d.ts +0 -3
  43. package/lib/schemas/models/materialized_tenant_discount_sources.js +5 -1
  44. package/lib/schemas/models/tenant_hr_shift_schedules.js +4 -0
  45. package/lib/schemas/models/tenant_hr_shifts.js +4 -0
  46. package/lib/schemas/types/materialized_tenant_discount_entries.d.ts +11 -4
  47. package/lib/schemas/types/materialized_tenant_discount_sources.d.ts +23 -4
  48. package/lib/tests/materialized-reports/fixtures.d.ts +15 -1
  49. package/lib/tests/materialized-reports/fixtures.js +118 -8
  50. package/lib/tests/materialized-reports/materialized-discount-classification.test.js +34 -24
  51. package/lib/tests/materialized-reports/materialized-discount-sources.test.js +14 -10
  52. package/lib/tests/materialized-reports/materialized-integer-contract.test.d.ts +1 -0
  53. package/lib/tests/materialized-reports/materialized-integer-contract.test.js +223 -0
  54. package/lib/tests/materialized-reports/materialized-write-paths-inventory.test.d.ts +1 -0
  55. package/lib/tests/materialized-reports/materialized-write-paths-inventory.test.js +58 -0
  56. package/lib/tests/materialized-reports/materialized-writers-integer-only.test.d.ts +1 -0
  57. package/lib/tests/materialized-reports/materialized-writers-integer-only.test.js +150 -0
  58. package/lib/tests/materialized-reports/sales-overview-baseline.test.js +51 -51
  59. package/lib/tests/materialized-reports/tenant-discount-source-formatter.test.js +108 -5
  60. package/package.json +1 -1
@@ -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';
@@ -111,8 +111,11 @@ export function buildCreditBillIssuedCandidatesFromOrder(order, orderLocalDate,
111
111
  const paymentId = payment.payment_id ?? payment._id ?? null;
112
112
  if (paymentId == null || paymentId.length === 0)
113
113
  return null; // un-keyable bill — data issue
114
- const amount = payment.amount_due ?? 0;
115
- const receivedAmount = payment.amount_paid ?? 0;
114
+ // Money is integer CENTS: the payment amounts are rounded to the cent at
115
+ // this writer boundary, because a materialized ledger document may not
116
+ // hold a decimal.
117
+ const amount = Math.round(payment.amount_due ?? 0);
118
+ const receivedAmount = Math.round(payment.amount_paid ?? 0);
116
119
  const settled = !settledLater && receivedAmount >= amount;
117
120
  candidates.push({
118
121
  order_id: order._id,
@@ -147,7 +150,8 @@ export function buildCreditBillEventCandidatesFromOrder(order, eventLocalDate, o
147
150
  const paymentId = payment.payment_id ?? payment._id ?? null;
148
151
  if (paymentId == null || paymentId.length === 0)
149
152
  return null; // un-keyable bill — data issue
150
- const receivedAmount = payment.amount_paid ?? 0;
153
+ // Money is integer CENTS (see the issued-bill candidate above).
154
+ const receivedAmount = Math.round(payment.amount_paid ?? 0);
151
155
  if (receivedAmount <= 0)
152
156
  continue; // nothing collected yet
153
157
  candidates.push({
@@ -155,7 +159,8 @@ export function buildCreditBillEventCandidatesFromOrder(order, eventLocalDate, o
155
159
  payment_id: paymentId,
156
160
  order_status: order.order_status,
157
161
  platform: order.platform,
158
- amount: payment.amount_due ?? 0,
162
+ // Money is integer CENTS.
163
+ amount: Math.round(payment.amount_due ?? 0),
159
164
  issued_at: issuedAt,
160
165
  issued_local_date: orderLocalDate,
161
166
  issued_local_hour: issuedHourLabel,
@@ -139,6 +139,16 @@ export function freshDeliveryCounters() {
139
139
  },
140
140
  };
141
141
  }
142
+ /**
143
+ * A source money amount → integer CENTS (0 when absent/broken).
144
+ *
145
+ * Rounding happens HERE, at the writer boundary: the materialized document is
146
+ * the thing that must be integral.
147
+ */
148
+ const cents = (value) => {
149
+ const number = typeof value === 'number' ? value : Number(value);
150
+ return Number.isFinite(number) ? Math.round(number) : 0;
151
+ };
142
152
  /** Which fixed distance bucket a metre value falls in. */
143
153
  export function deliveryDistanceBucketKey(meters) {
144
154
  const value = Math.abs(Number(meters) || 0);
@@ -203,17 +213,20 @@ export function addDeliveryOrder(acc, order) {
203
213
  const counters = acc.counters;
204
214
  counters.adoption.delivery_order_count += 1;
205
215
  const details = order.delivery_details ?? {};
206
- counters.money.net_sale_amount += Number(order.net_sale_amount ?? order.amount_earned) || 0;
207
- counters.money.collected_amount += Number(order.amount_collected) || 0;
208
- counters.money.tip_amount += Number(order.tip_amount) || 0;
209
- counters.money.discount_amount += Number(order.total_discount_applied) || 0;
210
- counters.money.refund_amount += Number(order.amount_refunded) || 0;
211
- counters.money.tax_amount += (Number(order.gst_amount) || 0) + (Number(order.tax_amount) || 0);
216
+ // Money is integer CENTS: each source amount is rounded to the cent at this
217
+ // writer boundary, because a materialized document may not hold a decimal.
218
+ counters.money.net_sale_amount += cents(order.net_sale_amount ?? order.amount_earned);
219
+ counters.money.collected_amount += cents(order.amount_collected);
220
+ counters.money.tip_amount += cents(order.tip_amount);
221
+ counters.money.discount_amount += cents(order.total_discount_applied);
222
+ counters.money.refund_amount += cents(order.amount_refunded);
223
+ counters.money.tax_amount += cents(order.gst_amount) + cents(order.tax_amount);
212
224
  // `delivery_cost` is the field IOrderDeliveryDetails ACTUALLY declares; the other two
213
225
  // names are tolerated fallbacks. Reading the wrong one silently reported every charge
214
226
  // as ZERO while the statement row (which used the right field) showed the real value -
215
227
  // an inconsistency the formatter test caught.
216
- const charge = Number(details.delivery_cost ?? details.delivery_charge ?? details.delivery_charge_amount) || 0;
228
+ // Money is integer CENTS.
229
+ const charge = cents(details.delivery_cost ?? details.delivery_charge ?? details.delivery_charge_amount);
217
230
  if (charge !== 0) {
218
231
  counters.money.delivery_charge_amount += charge;
219
232
  counters.money.delivery_charge_count += 1;
@@ -260,12 +273,15 @@ export function addDelivery(acc, delivery, order, key) {
260
273
  // the rider before completion and must not inflate the materialized report.
261
274
  const earnings = delivery.rider_earnings;
262
275
  const isFinalPayout = earnings?.status === RIDER_EARNINGS_STATUS_ENUM.FINAL;
263
- const revenue = isFinalPayout ? Number(earnings.amount) || 0 : 0;
276
+ // Money is integer CENTS.
277
+ const revenue = isFinalPayout ? cents(earnings.amount) : 0;
264
278
  if (isFinalPayout) {
265
279
  counters.money.rider_revenue_amount += revenue;
266
280
  counters.money.rider_revenue_count += 1;
267
281
  }
268
- const meters = Number(delivery.distance_in_meters_from_store) || 0;
282
+ // The distance is stored in whole METRES (the unit the delivery collection
283
+ // documents it in) — a materialized document may not hold a decimal.
284
+ const meters = Math.round(Number(delivery.distance_in_meters_from_store) || 0);
269
285
  counters.distance.sum_meters += meters;
270
286
  counters.distance.count += 1;
271
287
  const bucketKey = deliveryDistanceBucketKey(meters);
@@ -172,9 +172,11 @@ function buildEntryRow(delivery, order, details) {
172
172
  rider_name: delivery?.rider_name == null ? null : String(delivery.rider_name),
173
173
  status: status,
174
174
  cancel_reason: delivery?.cancel_reason == null ? null : String(delivery.cancel_reason),
175
- distance_meters: Number(delivery?.distance_in_meters_from_store) || 0,
175
+ // The distance is stored in whole METRES and the revenue in integer CENTS —
176
+ // a materialized document may not hold a decimal.
177
+ distance_meters: Math.round(Number(delivery?.distance_in_meters_from_store) || 0),
176
178
  rider_revenue: delivery?.rider_earnings?.status === RIDER_EARNINGS_STATUS_ENUM.FINAL
177
- ? Number(delivery.rider_earnings.amount) || 0
179
+ ? Math.round(Number(delivery.rider_earnings.amount) || 0)
178
180
  : null,
179
181
  tracking_enabled: delivery?.tracking_enabled === true,
180
182
  has_pickup_proof: delivery?.pickup_food_image_url != null,
@@ -184,9 +186,10 @@ function buildEntryRow(delivery, order, details) {
184
186
  city: details?.city == null ? null : String(details.city),
185
187
  state: details?.state == null ? null : String(details.state),
186
188
  street: details?.street == null ? null : String(details.street),
187
- net_sale_amount: Number(order?.net_sale_amount ?? order?.amount_earned) || 0,
188
- collected_amount: Number(order?.amount_collected) || 0,
189
- delivery_charge: Number(details?.delivery_cost) || 0,
189
+ // Money is integer CENTS.
190
+ net_sale_amount: Math.round(Number(order?.net_sale_amount ?? order?.amount_earned) || 0),
191
+ collected_amount: Math.round(Number(order?.amount_collected) || 0),
192
+ delivery_charge: Math.round(Number(details?.delivery_cost) || 0),
190
193
  order_created_at: orderCreatedAt ?? createdAt,
191
194
  assigned_at: delivery?.assigned_at == null ? null : new Date(delivery.assigned_at),
192
195
  picked_up_at: delivery?.picked_up_at == null ? null : new Date(delivery.picked_up_at),
@@ -1,8 +1,17 @@
1
1
  import { MATERIALIZED_DISCOUNT_ENTRY_KIND_ENUM, MATERIALIZED_DISCOUNT_LEVEL_ENUM, MATERIALIZED_DISCOUNT_SLOT_ENUM, MATERIALIZED_DISCOUNT_SUB_KIND_ENUM, } from '../../constants/MATERIALIZED_REPORTS';
2
2
  import { ORDER_ITEM_TYPE_ENUM } from '../../constants/enums/order';
3
3
  import { PAYMENT_TYPE_ENUM } from '../../constants/enums/payments';
4
+ import { convertPercentToBasisPoints } from '../utils/percentage-conversion';
4
5
  import { createEmptyDiscountOrderCounters, createEmptyDiscountSlotCounter, MATERIALIZED_DISCOUNT_SLOTS, mergeDiscountSlotCounter, readDiscountSlot, resolveRowMoney, } from './materialized-discount-classification-helpers';
5
6
  const isComplimentaryPayment = (payment) => payment?.payment_type === PAYMENT_TYPE_ENUM.COMPLIMENTARY;
7
+ /**
8
+ * 100% off, in BASIS POINTS (the stored unit of a percentage rate).
9
+ *
10
+ * A percentage rate is stored in integer basis points (1% = 100 bps), so the
11
+ * "this item is free" test is `rate >= 10000` — a UNIT comparison against a
12
+ * named constant, never a magnitude guess.
13
+ */
14
+ export const FULL_DISCOUNT_BASIS_POINTS = convertPercentToBasisPoints(100);
6
15
  /**
7
16
  * Classifies an order's COMPLIMENTARY tenders. Returns null when there is none.
8
17
  *
@@ -134,7 +143,10 @@ function orderSubKindCounter(counters, slot, subKind) {
134
143
  function accumulateItemSlot(counters, entries, order, context, itemId, catalogItemId, itemName, itemValue, reading, resolved, itemTotal, catalogAuto) {
135
144
  const raw = nonNegative(reading.rate);
136
145
  const money = nonNegative(resolved);
137
- const isFree = reading.is_percentage && reading.rate >= 100;
146
+ // A percentage rate is stored in BASIS POINTS (1% = 100 bps), so "100% off" is
147
+ // 10000 bps. This is a UNIT comparison, not a magnitude heuristic: the unit is
148
+ // fixed by the storage contract, so the threshold is a named constant.
149
+ const isFree = reading.is_percentage && raw >= FULL_DISCOUNT_BASIS_POINTS;
138
150
  if (reading.slot === MATERIALIZED_DISCOUNT_SLOT_ENUM.SPECIAL) {
139
151
  const counter = counters.item_special;
140
152
  counter.count += 1;
@@ -272,7 +272,6 @@ export function classifyDiscountEntrySource(entry) {
272
272
  return unattributedIdentity(level);
273
273
  }
274
274
  const nonNegative = (value) => (Number.isFinite(value) && value > 0 ? value : 0);
275
- const round2 = (value) => Math.round((value ?? 0) * 100) / 100;
276
275
  const emptyMetrics = () => ({
277
276
  orderIds: new Set(),
278
277
  row_count: 0,
@@ -375,7 +374,6 @@ export function buildDiscountSourcesForScope(input) {
375
374
  const docs = [];
376
375
  for (const bucket of buckets.values()) {
377
376
  const { identity, totals } = bucket;
378
- const rate = totals.percentage_row_count > 0 ? round2(totals.percentage_rate_sum / totals.percentage_row_count) : null;
379
377
  const kind = identity.kind === MATERIALIZED_DISCOUNT_ENTRY_KIND_ENUM.COMPLIMENTARY
380
378
  ? MATERIALIZED_DISCOUNT_ENTRY_KIND_ENUM.COMPLIMENTARY
381
379
  : totals.free_item_count > 0 && totals.free_item_count === totals.row_count
@@ -396,7 +394,6 @@ export function buildDiscountSourcesForScope(input) {
396
394
  level: identity.level,
397
395
  slot: identity.slot,
398
396
  sub_kind: identity.sub_kind,
399
- rate,
400
397
  rate_kind: rateKindOf(totals),
401
398
  percentage_row_count: totals.percentage_row_count,
402
399
  percentage_rate_sum: totals.percentage_rate_sum,
@@ -0,0 +1,142 @@
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
+ /** A string that is entirely a number (decimal or not) — never allowed in a document. */
28
+ const NUMERIC_STRING = /^[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?$/;
29
+ /**
30
+ * IDENTIFIER fields may legitimately hold a numeric-looking string.
31
+ *
32
+ * A materialized document names its scopes with strings: `scope_field: "2026"`
33
+ * (a year scope), `day_index: "2026-09-15"`, `_id` / `order_id` / `entry_key` /
34
+ * `source_key` (opaque ids). Those are identifiers, not money, so they are not
35
+ * violations — while a numeric string in a field that holds a NUMBER (money,
36
+ * a rate, a count) is a decimal smuggled in as text and IS a violation. The
37
+ * schema catches the typed case; this rule catches the `Mixed` payload case.
38
+ */
39
+ const IDENTIFIER_FIELD = /^(scope_field|day_index|key|_id|.*_id)$/;
40
+ /**
41
+ * Human/readable fields may legitimately contain a numeric-looking string
42
+ * (`source_name: "50"`, `reason: "123"`). They are not numeric storage: the
43
+ * integer contract applies to money/rate/count/duration leaves. Only reject a
44
+ * numeric-looking string when it sits in a field that is not one of these.
45
+ */
46
+ const TEXT_FIELD = /(name|label|title|reason|note|description|reference|code|currency|platform|status|type|source_key|order_number)$/i;
47
+ /**
48
+ * Mongo ObjectId / BSON values are identity, not numbers.
49
+ *
50
+ * Duck-typed on `_bsontype` so the toolkit keeps no mongoose dependency
51
+ * (it is published to the frontends too).
52
+ */
53
+ const isBsonLike = (value) => typeof value === 'object' && value !== null && typeof value._bsontype === 'string';
54
+ /** Dates, buffers and other non-numeric leaves are ignored. */
55
+ const isIgnoredLeaf = (value) => value === null ||
56
+ typeof value === 'boolean' ||
57
+ value instanceof Date ||
58
+ value instanceof RegExp ||
59
+ (typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) ||
60
+ isBsonLike(value);
61
+ const childPath = (parent, key) => (parent.length === 0 ? key : `${parent}.${key}`);
62
+ /**
63
+ * Collects every numeric leaf that violates the integer-only contract.
64
+ *
65
+ * Walks plain objects and arrays. Ignores `Date`, `ObjectId`, `null`,
66
+ * booleans, buffers and strings that are not numeric. Rejects:
67
+ * - decimal numbers,
68
+ * - `NaN` / `Infinity`,
69
+ * - strings that look numeric.
70
+ */
71
+ export function findNonIntegerNumericLeaves(document) {
72
+ const violations = [];
73
+ const walk = (node, path) => {
74
+ if (node === undefined)
75
+ return;
76
+ if (isIgnoredLeaf(node))
77
+ return;
78
+ if (typeof node === 'number') {
79
+ if (!Number.isFinite(node)) {
80
+ violations.push({ path, value: node, reason: 'non-finite' });
81
+ return;
82
+ }
83
+ if (!Number.isInteger(node)) {
84
+ violations.push({ path, value: node, reason: 'decimal' });
85
+ }
86
+ return;
87
+ }
88
+ if (typeof node === 'string') {
89
+ const key = path.slice(path.lastIndexOf('.') + 1);
90
+ if (NUMERIC_STRING.test(node.trim()) &&
91
+ node.trim().length > 0 &&
92
+ !IDENTIFIER_FIELD.test(key) &&
93
+ !TEXT_FIELD.test(key)) {
94
+ violations.push({ path, value: node, reason: 'numeric-string' });
95
+ }
96
+ return;
97
+ }
98
+ if (Array.isArray(node)) {
99
+ node.forEach((item, index) => walk(item, `${path}[${index}]`));
100
+ return;
101
+ }
102
+ if (typeof node === 'object') {
103
+ for (const [key, value] of Object.entries(node)) {
104
+ walk(value, childPath(path, key));
105
+ }
106
+ }
107
+ };
108
+ walk(document, '');
109
+ return violations;
110
+ }
111
+ /**
112
+ * Throws when a materialized document violates the integer-only contract.
113
+ *
114
+ * Called at persistence, right before the write. The message names the
115
+ * offending path so the writer that produced it can be fixed directly.
116
+ */
117
+ export function assertIntegerOnlyDocument(document, context) {
118
+ const violations = findNonIntegerNumericLeaves(document);
119
+ if (violations.length === 0)
120
+ return;
121
+ const scope = context?.label ?? context?.collection ?? 'materialized document';
122
+ const preview = violations
123
+ .slice(0, 5)
124
+ .map((violation) => `${violation.path || '<root>'}=${String(violation.value)} (${violation.reason})`)
125
+ .join(', ');
126
+ const more = violations.length > 5 ? `, +${violations.length - 5} more` : '';
127
+ throw new Error(`Integer-only storage contract violated in ${scope}: ${preview}${more}. ` +
128
+ 'Materialized documents store integer cents / basis points / minutes — ' +
129
+ 'convert the unit at the writer boundary instead of persisting a decimal.');
130
+ }
131
+ /**
132
+ * Asserts a whole SET of documents (a scope, a plan, a batch) in one call.
133
+ */
134
+ export function assertIntegerOnlyDocuments(documents, context) {
135
+ documents.forEach((document, index) => {
136
+ const scope = context?.label ?? context?.collection;
137
+ assertIntegerOnlyDocument(document, {
138
+ collection: scope,
139
+ label: scope != null ? `${scope}[${index}]` : undefined,
140
+ });
141
+ });
142
+ }
@@ -13,9 +13,15 @@ import { getMaterializedPaymentGross, isPaymentIncludedInMaterializedSalesOvervi
13
13
  * OPEN string; only reserved key characters make it un-keyable.
14
14
  */
15
15
  /** Coerces a source amount to a finite number (0 when absent/broken). */
16
+ /**
17
+ * A source money amount → integer CENTS (0 when absent/broken).
18
+ *
19
+ * The order's money is integer cents; rounding here is the writer boundary
20
+ * that guarantees a materialized document never holds a decimal.
21
+ */
16
22
  const cents = (value) => {
17
23
  const number = typeof value === 'number' ? value : Number(value);
18
- return Number.isFinite(number) ? number : 0;
24
+ return Number.isFinite(number) ? Math.round(number) : 0;
19
25
  };
20
26
  export function createEmptyPaymentsComparisonCounters() {
21
27
  return {
@@ -2,12 +2,19 @@ import { MATERIALIZED_PREP_TIME_ANCHOR_ENUM, MATERIALIZED_PREP_TIME_BUCKETS, MAT
2
2
  /**
3
3
  * Numeric or null - never NaN. The stored field is a duration in whole minutes.
4
4
  */
5
+ /**
6
+ * A source duration → whole MINUTES (the stored unit).
7
+ *
8
+ * A duration in a materialized document is an integer number of minutes, so a
9
+ * fractional source value is rounded here — at the writer boundary — instead
10
+ * of travelling into the document.
11
+ */
5
12
  const toMinutes = (value) => {
6
13
  if (typeof value === 'number' && Number.isFinite(value))
7
- return value;
14
+ return Math.round(value);
8
15
  if (typeof value === 'string' && value.trim() !== '') {
9
16
  const parsed = Number(value);
10
- return Number.isFinite(parsed) ? parsed : null;
17
+ return Number.isFinite(parsed) ? Math.round(parsed) : null;
11
18
  }
12
19
  return null;
13
20
  };
@@ -25,13 +25,20 @@ import { ORDER_STATUS_ENUM } from '../../constants/ENUMS';
25
25
  * orders are keyed `CANCELLED:*` and are split out by the formatter, exactly
26
26
  * like the overview.
27
27
  *
28
- * Every value is added AS-IS: the source amounts may carry fractional cents and
29
- * the report must be decimal-exact, so no rounding happens here.
28
+ * Every MONEY value is added in integer CENTS: the order's money is integer
29
+ * cents (see the order-write boundary), and a materialized document may not
30
+ * hold a decimal, so each amount is rounded to the cent HERE — the writer
31
+ * boundary — rather than being copied into the document as-is.
32
+ */
33
+ /**
34
+ * A source money amount → integer CENTS (0 when absent/broken).
35
+ *
36
+ * The order's money is integer cents; rounding here is the LAST step that can
37
+ * guarantee it, because a materialized document must never hold a decimal.
30
38
  */
31
- /** Coerces a source amount to a finite number (0 when absent/broken). */
32
39
  const cents = (value) => {
33
40
  const number = typeof value === 'number' ? value : Number(value);
34
- return Number.isFinite(number) ? number : 0;
41
+ return Number.isFinite(number) ? Math.round(number) : 0;
35
42
  };
36
43
  const isFiniteNumber = (value) => typeof value === 'number' && Number.isFinite(value);
37
44
  /** A zeroed counter block. */
@@ -64,16 +71,19 @@ const itemsGrossAmount = (order) => {
64
71
  export function getOrderGrossAmountCents(order) {
65
72
  if (order == null)
66
73
  return 0;
74
+ // Money is integer CENTS: the order's own fields are rounded to the cent at
75
+ // this boundary, so a materialized document never holds a decimal.
67
76
  if (isFiniteNumber(order.price))
68
- return order.price;
69
- return itemsGrossAmount(order);
77
+ return Math.round(order.price);
78
+ return Math.round(itemsGrossAmount(order));
70
79
  }
71
80
  /** Discounts applied to the order, in CENTS. */
72
81
  export function getOrderDiscountAmountCents(order) {
73
82
  if (order == null)
74
83
  return 0;
84
+ // Money is integer CENTS.
75
85
  if (isFiniteNumber(order.total_discount_applied))
76
- return order.total_discount_applied;
86
+ return Math.round(order.total_discount_applied);
77
87
  return cents(order.order_discount_details?.total_discount);
78
88
  }
79
89
  /** Total tax collected, in CENTS (GST + the unused `tax_amount` bucket). */
@@ -1,5 +1,6 @@
1
1
  import { MATERIALIZED_DISCOUNT_RATE_KIND_ENUM, MATERIALIZED_DISCOUNT_SOURCE_CLASS_ENUM, } from '../../constants/MATERIALIZED_REPORTS';
2
2
  import { convertPriceFromCents } from '../utils/price-conversion';
3
+ import { convertBasisPointsToPercent, formatPercentValue } from '../utils/percentage-conversion';
3
4
  const round2 = (value) => Math.round((value ?? 0) * 100) / 100;
4
5
  export function getDiscountSourceShareReconciliation(summaryTotal, sourceTotal) {
5
6
  const summary = Number.isFinite(summaryTotal) ? Math.max(0, summaryTotal ?? 0) : 0;
@@ -31,10 +32,28 @@ const LEVEL_LABELS = {
31
32
  ITEM: 'Item',
32
33
  PAYMENT: 'Payment',
33
34
  };
34
- const formatRate = (rate) => {
35
- if (rate == null || !Number.isFinite(rate))
36
- return '—';
37
- return `${Math.round(rate * 100) / 100}%`;
35
+ /**
36
+ * THE rate of a discount source row.
37
+ *
38
+ * A percentage rate uses integer BASIS POINTS (1% = 100 bps, 50% = 5000) —
39
+ * the same unit the order's discount details use.
40
+ *
41
+ * There is NO magnitude heuristic here: the unit is fixed by the storage
42
+ * contract, so the display is a plain division by 100 — ONCE, at this
43
+ * boundary. A value is never "probably" a percent because it looks small.
44
+ *
45
+ * The average is DERIVED, never read from a stored field: the source stores
46
+ * the integer SUM of its percentage rates (`percentage_rate_sum`, basis points)
47
+ * and the integer COUNT of its percentage rows (`percentage_row_count`), and
48
+ * the average is `sum / count`. There is no stored `rate` and no fallback to
49
+ * one — a source with no percentage rows simply has no rate.
50
+ */
51
+ const sourceBasisPoints = (source) => {
52
+ const sum = source.percentage_rate_sum;
53
+ const count = source.percentage_row_count;
54
+ if (sum == null || count == null || count <= 0)
55
+ return null;
56
+ return sum / count;
38
57
  };
39
58
  const rateKindLabel = (rateKind) => {
40
59
  switch (rateKind) {
@@ -55,6 +74,10 @@ const makeRow = (source, shareBasis) => {
55
74
  // `shareBasis` is CENTS; the row amount above is decimals. Compute the share
56
75
  // in ONE unit so the table sums to 100%.
57
76
  const sharePercent = shareBasis > 0 ? round2((source.discount_amount / shareBasis) * 100) : 0;
77
+ // Basis points -> percent, ONCE. The average is derived from the integer
78
+ // sum/count the source stores; nothing is read from a stored rate.
79
+ const basisPoints = sourceBasisPoints(source);
80
+ const ratePercent = basisPoints == null ? null : convertBasisPointsToPercent(basisPoints);
58
81
  return {
59
82
  source_key: source.source_key,
60
83
  source_name: source.source_name,
@@ -64,8 +87,15 @@ const makeRow = (source, shareBasis) => {
64
87
  level: source.level,
65
88
  level_label: levelLabel,
66
89
  type_label: kindLabel === '—' ? levelLabel : `${levelLabel} · ${kindLabel}`,
67
- rate: source.rate,
68
- rate_label: source.rate_kind === MATERIALIZED_DISCOUNT_RATE_KIND_ENUM.MIXED ? 'mixed' : formatRate(source.rate),
90
+ rate_kind_label: kindLabel,
91
+ /**
92
+ * The DERIVED average rate in BASIS POINTS (1% = 100 bps) — computed from
93
+ * the stored integer sum/count. It is a display value, not a stored one.
94
+ */
95
+ rate: basisPoints,
96
+ /** The display percentage (basis points -> percent). */
97
+ rate_percent: ratePercent,
98
+ rate_label: source.rate_kind === MATERIALIZED_DISCOUNT_RATE_KIND_ENUM.MIXED ? 'mixed' : formatPercentValue(ratePercent),
69
99
  order_count: source.order_count,
70
100
  discount_amount: amount,
71
101
  discount_amount_label: amount.toFixed(2),
@@ -34,14 +34,16 @@ export function isPaymentIncludedInMaterializedSalesOverview(payment) {
34
34
  export function getMaterializedPaymentGross(payment) {
35
35
  const reportedType = normalizeMaterializedPaymentType(payment.payment_type);
36
36
  const isUnpaid = reportedType === PAYMENT_TYPE_ENUM.UNPAID;
37
+ // Money is integer CENTS: the result is rounded to the cent at this
38
+ // boundary, because it feeds a materialized document.
37
39
  if ((payment.amount_refunded ?? 0) === 0) {
38
40
  let gross = isUnpaid ? (payment.amount_due ?? 0) : Math.min(payment.amount_paid ?? 0, payment.amount_due ?? 0);
39
41
  if (payment.card_details != null) {
40
42
  gross -= payment.card_details.card_charges ?? 0;
41
43
  }
42
- return gross;
44
+ return Math.round(gross);
43
45
  }
44
- return -(isUnpaid ? (payment.amount_due ?? 0) : (payment.amount_refunded ?? 0));
46
+ return -Math.round(isUnpaid ? (payment.amount_due ?? 0) : (payment.amount_refunded ?? 0));
45
47
  }
46
48
  // `isMaterializedCreditBillPayment` moved to `./materialized-credit-bills-helpers`
47
49
  // (imported above) — re-exported here for API stability.
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Duration unit conversions.
3
+ *
4
+ * The materialized reports store durations as whole MINUTES
5
+ * (`duration_minutes`, `delta_minutes` — the POS tracks a prep time in whole
6
+ * minutes). There is no fractional duration anywhere in a materialized
7
+ * document.
8
+ *
9
+ * Money uses cents (`price-conversion.ts`), rates use basis points
10
+ * (`percentage-conversion.ts`); durations use minutes.
11
+ */
12
+ export const SECONDS_PER_MINUTE = 60;
13
+ export const MINUTES_PER_HOUR = 60;
14
+ /** Whole minutes → whole seconds (the storage unit stays minutes; this is for display maths). */
15
+ export function convertMinutesToSeconds(minutes) {
16
+ if (!Number.isFinite(minutes))
17
+ return 0;
18
+ return Math.round(minutes * SECONDS_PER_MINUTE);
19
+ }
20
+ /** Whole seconds → whole minutes. */
21
+ export function convertSecondsToMinutes(seconds) {
22
+ if (!Number.isFinite(seconds))
23
+ return 0;
24
+ return Math.round(seconds / SECONDS_PER_MINUTE);
25
+ }
26
+ /** Whole minutes → a decimal hour (display only). */
27
+ export function convertMinutesToHours(minutes) {
28
+ if (!Number.isFinite(minutes))
29
+ return 0;
30
+ return Math.round((minutes / MINUTES_PER_HOUR) * 100) / 100;
31
+ }
@@ -47,6 +47,8 @@ export * from './phone-helpers';
47
47
  export * from './platform-catalog';
48
48
  export * from './platform-num';
49
49
  export * from './platform-specific-tenant-shifts';
50
+ export * from './percentage-conversion';
51
+ export * from './duration-conversion';
50
52
  export * from './price-conversion';
51
53
  export * from './printer-helpers';
52
54
  export * from './public-holidays-helpers';
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Percentage unit conversions.
3
+ *
4
+ * The platform stores a percentage RATE as integer BASIS POINTS (1% = 100
5
+ * bps, 50% = 5000). Basis points are the storage unit because they are
6
+ * integers: a stored percentage can never be fractional, and `50%` is
7
+ * representable exactly while `33.3333333%` is not.
8
+ *
9
+ * Money follows the same idea and uses `price-conversion.ts`
10
+ * (`convertPriceToCents` / `convertPriceFromCents`).
11
+ *
12
+ * The rule is the same on both sides of the API boundary:
13
+ * - BEFORE storing / after fetching: convert with the helpers below;
14
+ * - NEVER infer the unit from the magnitude of a value.
15
+ */
16
+ /** 1% expressed in basis points. */
17
+ export const BASIS_POINTS_PER_PERCENT = 100;
18
+ /**
19
+ * Percent → basis points (the storage unit).
20
+ *
21
+ * The input must be an integer percentage: the platform's rates are whole
22
+ * percent steps. A fractional percent is rejected instead of silently
23
+ * truncated — a half-percent discount must be stored as 50 bps by its writer,
24
+ * not rounded into a whole percent here.
25
+ */
26
+ export function convertPercentToBasisPoints(percent) {
27
+ if (!Number.isFinite(percent))
28
+ return 0;
29
+ if (!Number.isInteger(percent)) {
30
+ throw new Error(`convertPercentToBasisPoints expects an integer percentage (got ${percent}). ` +
31
+ 'Store a fractional rate as integer basis points at its writer.');
32
+ }
33
+ return percent * BASIS_POINTS_PER_PERCENT;
34
+ }
35
+ /**
36
+ * Basis points → percent (the display unit).
37
+ *
38
+ * The result MAY be fractional (5000 bps → 50%, 1667 bps → 16.67%): this is
39
+ * the display boundary, where a rounded number is correct and a stored one
40
+ * would not be.
41
+ */
42
+ export function convertBasisPointsToPercent(basisPoints) {
43
+ if (!Number.isFinite(basisPoints))
44
+ return 0;
45
+ return basisPoints / BASIS_POINTS_PER_PERCENT;
46
+ }
47
+ /**
48
+ * Basis points → a percent label (`'50%'`, `'16.67%'`).
49
+ *
50
+ * `null` / a non-finite value renders as the em dash the reports use for an
51
+ * absent rate.
52
+ */
53
+ export function formatBasisPointsAsPercent(basisPoints) {
54
+ if (basisPoints == null || !Number.isFinite(basisPoints))
55
+ return '—';
56
+ return formatPercentValue(convertBasisPointsToPercent(basisPoints));
57
+ }
58
+ /**
59
+ * A percentage VALUE → a percent label (`'50%'`, `'16.67%'`).
60
+ *
61
+ * The rounding rule lives here so every report formats a percentage the same
62
+ * way. `null` / a non-finite value renders as the em dash the reports use for
63
+ * an absent rate.
64
+ */
65
+ export function formatPercentValue(percent) {
66
+ if (percent == null || !Number.isFinite(percent))
67
+ return '—';
68
+ return `${Math.round(percent * 100) / 100}%`;
69
+ }
@@ -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: { type: Number, default: null },
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,
@@ -35,10 +35,14 @@ export const TenantHrShiftScheduleSchema = new Schema({
35
35
  start_time: {
36
36
  type: Number,
37
37
  required: true,
38
+ min: 0,
39
+ max: 86399,
38
40
  },
39
41
  end_time: {
40
42
  type: Number,
41
43
  required: true,
44
+ min: 0,
45
+ max: 86399,
42
46
  },
43
47
  position: {
44
48
  type: String,