@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.
Files changed (56) 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 +29 -29
  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/lib/helpers/materialized-reports/index.d.ts +1 -0
  18. package/lib/helpers/materialized-reports/index.js +1 -0
  19. package/lib/helpers/materialized-reports/materialized-credit-bills-helpers.js +9 -4
  20. package/lib/helpers/materialized-reports/materialized-delivery-classification-helpers.js +25 -9
  21. package/lib/helpers/materialized-reports/materialized-delivery-compile-helpers.js +8 -5
  22. package/lib/helpers/materialized-reports/materialized-discount-accumulator-helpers.d.ts +18 -0
  23. package/lib/helpers/materialized-reports/materialized-discount-accumulator-helpers.js +14 -2
  24. package/lib/helpers/materialized-reports/materialized-discount-source-helpers.js +0 -3
  25. package/lib/helpers/materialized-reports/materialized-integer-contract.d.ts +68 -0
  26. package/lib/helpers/materialized-reports/materialized-integer-contract.js +147 -0
  27. package/lib/helpers/materialized-reports/materialized-payments-comparison-accumulator-helpers.js +7 -1
  28. package/lib/helpers/materialized-reports/materialized-prep-time-classification-helpers.js +9 -2
  29. package/lib/helpers/materialized-reports/materialized-sales-comparison-accumulator-helpers.js +17 -7
  30. package/lib/helpers/materialized-reports/tenant-discount-source-formatter.d.ts +12 -30
  31. package/lib/helpers/materialized-reports/tenant-discount-source-formatter.js +29 -30
  32. package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.js +4 -2
  33. package/lib/helpers/types/materialized-reports-apis.d.ts +11 -3
  34. package/lib/helpers/utils/duration-conversion.d.ts +19 -0
  35. package/lib/helpers/utils/duration-conversion.js +37 -0
  36. package/lib/helpers/utils/index.d.ts +2 -0
  37. package/lib/helpers/utils/index.js +2 -0
  38. package/lib/helpers/utils/percentage-conversion.d.ts +49 -0
  39. package/lib/helpers/utils/percentage-conversion.js +76 -0
  40. package/lib/schemas/models/materialized_tenant_discount_sources.d.ts +0 -3
  41. package/lib/schemas/models/materialized_tenant_discount_sources.js +5 -1
  42. package/lib/schemas/types/materialized_tenant_discount_entries.d.ts +11 -4
  43. package/lib/schemas/types/materialized_tenant_discount_sources.d.ts +23 -4
  44. package/lib/tests/materialized-reports/fixtures.d.ts +15 -1
  45. package/lib/tests/materialized-reports/fixtures.js +118 -8
  46. package/lib/tests/materialized-reports/materialized-discount-classification.test.js +34 -24
  47. package/lib/tests/materialized-reports/materialized-discount-sources.test.js +14 -10
  48. package/lib/tests/materialized-reports/materialized-integer-contract.test.d.ts +1 -0
  49. package/lib/tests/materialized-reports/materialized-integer-contract.test.js +223 -0
  50. package/lib/tests/materialized-reports/materialized-write-paths-inventory.test.d.ts +1 -0
  51. package/lib/tests/materialized-reports/materialized-write-paths-inventory.test.js +58 -0
  52. package/lib/tests/materialized-reports/materialized-writers-integer-only.test.d.ts +1 -0
  53. package/lib/tests/materialized-reports/materialized-writers-integer-only.test.js +150 -0
  54. package/lib/tests/materialized-reports/sales-overview-baseline.test.js +51 -51
  55. package/lib/tests/materialized-reports/tenant-discount-source-formatter.test.js +80 -41
  56. package/package.json +1 -1
@@ -1,10 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getDiscountSourceShareReconciliation = getDiscountSourceShareReconciliation;
4
- exports.normalizeDiscountSourceRatePercent = normalizeDiscountSourceRatePercent;
5
4
  exports.getFormattedTenantDiscountSources = getFormattedTenantDiscountSources;
6
5
  const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
7
6
  const price_conversion_1 = require("../utils/price-conversion");
7
+ const percentage_conversion_1 = require("../utils/percentage-conversion");
8
8
  const round2 = (value) => Math.round((value ?? 0) * 100) / 100;
9
9
  function getDiscountSourceShareReconciliation(summaryTotal, sourceTotal) {
10
10
  const summary = Number.isFinite(summaryTotal) ? Math.max(0, summaryTotal ?? 0) : 0;
@@ -37,37 +37,27 @@ const LEVEL_LABELS = {
37
37
  PAYMENT: 'Payment',
38
38
  };
39
39
  /**
40
- * THE rate normalisation rule for discount source rows.
40
+ * THE rate of a discount source row.
41
41
  *
42
- * A source row's `rate` is the average of the percentage rates of its
43
- * percentage rows, copied verbatim from the order's discount details. The
44
- * WRITE side has no single unit for that field: the `discounts` collection
45
- * stores a percentage value in CENTS (`value` is an `IPrice`, so 50% is
46
- * stored as 5000) and some writers copy that raw number into the order's
47
- * discount details, while others (manual quick discounts, payment-type
48
- * discounts) store the plain percent (25 for 25%). The stored source row
49
- * therefore carries whichever form the writer used.
42
+ * A percentage rate uses integer BASIS POINTS (1% = 100 bps, 50% = 5000) —
43
+ * the same unit the order's discount details use.
50
44
  *
51
- * THE RULE (one rule, applied at the display boundary):
52
- * - a rate ABOVE 100 is CENTS-SCALED -> divide by 100 (5000 -> 50%);
53
- * - a rate of 100 or below is ALREADY a percentage -> use as-is (15 -> 15%).
45
+ * There is NO magnitude heuristic here: the unit is fixed by the storage
46
+ * contract, so the display is a plain division by 100 — ONCE, at this
47
+ * boundary. A value is never "probably" a percent because it looks small.
54
48
  *
55
- * A real percentage discount can never exceed 100 (the POS clamps it), so the
56
- * >100 boundary separates the two forms for every value the platform can
57
- * produce, except exactly 100, which is read as 100%.
58
- *
59
- * This is a DISPLAY rule only: it never rewrites a stored document.
49
+ * The average is DERIVED, never read from a stored field: the source stores
50
+ * the integer SUM of its percentage rates (`percentage_rate_sum`, basis points)
51
+ * and the integer COUNT of its percentage rows (`percentage_row_count`), and
52
+ * the average is `sum / count`. There is no stored `rate` and no fallback to
53
+ * one — a source with no percentage rows simply has no rate.
60
54
  */
61
- function normalizeDiscountSourceRatePercent(rate) {
62
- if (rate == null || !Number.isFinite(rate))
55
+ const sourceBasisPoints = (source) => {
56
+ const sum = source.percentage_rate_sum;
57
+ const count = source.percentage_row_count;
58
+ if (sum == null || count == null || count <= 0)
63
59
  return null;
64
- return rate > 100 ? rate / 100 : rate;
65
- }
66
- const formatRate = (rate) => {
67
- const percent = normalizeDiscountSourceRatePercent(rate);
68
- if (percent == null)
69
- return '—';
70
- return `${Math.round(percent * 100) / 100}%`;
60
+ return sum / count;
71
61
  };
72
62
  const rateKindLabel = (rateKind) => {
73
63
  switch (rateKind) {
@@ -88,6 +78,10 @@ const makeRow = (source, shareBasis) => {
88
78
  // `shareBasis` is CENTS; the row amount above is decimals. Compute the share
89
79
  // in ONE unit so the table sums to 100%.
90
80
  const sharePercent = shareBasis > 0 ? round2((source.discount_amount / shareBasis) * 100) : 0;
81
+ // Basis points -> percent, ONCE. The average is derived from the integer
82
+ // sum/count the source stores; nothing is read from a stored rate.
83
+ const basisPoints = sourceBasisPoints(source);
84
+ const ratePercent = basisPoints == null ? null : (0, percentage_conversion_1.convertBasisPointsToPercent)(basisPoints);
91
85
  return {
92
86
  source_key: source.source_key,
93
87
  source_name: source.source_name,
@@ -98,9 +92,14 @@ const makeRow = (source, shareBasis) => {
98
92
  level_label: levelLabel,
99
93
  type_label: kindLabel === '—' ? levelLabel : `${levelLabel} · ${kindLabel}`,
100
94
  rate_kind_label: kindLabel,
101
- rate: source.rate,
102
- rate_percent: normalizeDiscountSourceRatePercent(source.rate),
103
- rate_label: source.rate_kind === MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_RATE_KIND_ENUM.MIXED ? 'mixed' : formatRate(source.rate),
95
+ /**
96
+ * The DERIVED average rate in BASIS POINTS (1% = 100 bps) — computed from
97
+ * the stored integer sum/count. It is a display value, not a stored one.
98
+ */
99
+ rate: basisPoints,
100
+ /** The display percentage (basis points -> percent). */
101
+ rate_percent: ratePercent,
102
+ rate_label: source.rate_kind === MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_RATE_KIND_ENUM.MIXED ? 'mixed' : (0, percentage_conversion_1.formatPercentValue)(ratePercent),
104
103
  order_count: source.order_count,
105
104
  discount_amount: amount,
106
105
  discount_amount_label: amount.toFixed(2),
@@ -50,14 +50,16 @@ function isPaymentIncludedInMaterializedSalesOverview(payment) {
50
50
  function getMaterializedPaymentGross(payment) {
51
51
  const reportedType = normalizeMaterializedPaymentType(payment.payment_type);
52
52
  const isUnpaid = reportedType === constants_1.PAYMENT_TYPE_ENUM.UNPAID;
53
+ // Money is integer CENTS: the result is rounded to the cent at this
54
+ // boundary, because it feeds a materialized document.
53
55
  if ((payment.amount_refunded ?? 0) === 0) {
54
56
  let gross = isUnpaid ? (payment.amount_due ?? 0) : Math.min(payment.amount_paid ?? 0, payment.amount_due ?? 0);
55
57
  if (payment.card_details != null) {
56
58
  gross -= payment.card_details.card_charges ?? 0;
57
59
  }
58
- return gross;
60
+ return Math.round(gross);
59
61
  }
60
- return -(isUnpaid ? (payment.amount_due ?? 0) : (payment.amount_refunded ?? 0));
62
+ return -Math.round(isUnpaid ? (payment.amount_due ?? 0) : (payment.amount_refunded ?? 0));
61
63
  }
62
64
  const createEmptyOrderMetric = () => ({
63
65
  count: 0,
@@ -225,7 +225,7 @@ export interface IMaterializedDiscountDetailsRow {
225
225
  catalog_item_id?: string | null;
226
226
  /** True when the row is the item's own catalog/special/half-half discount. */
227
227
  catalog_auto?: boolean | null;
228
- /** The MONEY this row applied, in CENTS (the raw rate rides on `rate`). */
228
+ /** The MONEY this row applied, in CENTS (the raw rate rides on `rate` for entry rows). */
229
229
  amount: number;
230
230
  rate: number | null;
231
231
  is_percentage: boolean | null;
@@ -265,8 +265,16 @@ export interface IMaterializedTenantDiscountSourceRow {
265
265
  level: MATERIALIZED_DISCOUNT_LEVEL_ENUM;
266
266
  slot: MATERIALIZED_DISCOUNT_SLOT_ENUM | null;
267
267
  sub_kind: MATERIALIZED_DISCOUNT_SUB_KIND_ENUM;
268
- /** Average percentage rate; null for a fixed-only or mixed source. */
269
- rate: number | null;
268
+ /**
269
+ * The integer sum of the source's percentage rates, in BASIS POINTS.
270
+ *
271
+ * Together with `percentage_row_count` this is the EXACT average: no average
272
+ * rate is stored, and the frontend derives the display value from these two
273
+ * integers (`sum / count` → basis points → percent).
274
+ */
275
+ percentage_rate_sum: number | null;
276
+ /** The integer count of the source's percentage rows. */
277
+ percentage_row_count: number | null;
270
278
  rate_kind: MATERIALIZED_DISCOUNT_RATE_KIND_ENUM | null;
271
279
  order_count: number;
272
280
  row_count: number;
@@ -0,0 +1,19 @@
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 declare const SECONDS_PER_MINUTE = 60;
13
+ export declare const MINUTES_PER_HOUR = 60;
14
+ /** Whole minutes → whole seconds (the storage unit stays minutes; this is for display maths). */
15
+ export declare function convertMinutesToSeconds(minutes: number): number;
16
+ /** Whole seconds → whole minutes. */
17
+ export declare function convertSecondsToMinutes(seconds: number): number;
18
+ /** Whole minutes → a decimal hour (display only). */
19
+ export declare function convertMinutesToHours(minutes: number): number;
@@ -0,0 +1,37 @@
1
+ "use strict";
2
+ /**
3
+ * Duration unit conversions.
4
+ *
5
+ * The materialized reports store durations as whole MINUTES
6
+ * (`duration_minutes`, `delta_minutes` — the POS tracks a prep time in whole
7
+ * minutes). There is no fractional duration anywhere in a materialized
8
+ * document.
9
+ *
10
+ * Money uses cents (`price-conversion.ts`), rates use basis points
11
+ * (`percentage-conversion.ts`); durations use minutes.
12
+ */
13
+ Object.defineProperty(exports, "__esModule", { value: true });
14
+ exports.MINUTES_PER_HOUR = exports.SECONDS_PER_MINUTE = void 0;
15
+ exports.convertMinutesToSeconds = convertMinutesToSeconds;
16
+ exports.convertSecondsToMinutes = convertSecondsToMinutes;
17
+ exports.convertMinutesToHours = convertMinutesToHours;
18
+ exports.SECONDS_PER_MINUTE = 60;
19
+ exports.MINUTES_PER_HOUR = 60;
20
+ /** Whole minutes → whole seconds (the storage unit stays minutes; this is for display maths). */
21
+ function convertMinutesToSeconds(minutes) {
22
+ if (!Number.isFinite(minutes))
23
+ return 0;
24
+ return Math.round(minutes * exports.SECONDS_PER_MINUTE);
25
+ }
26
+ /** Whole seconds → whole minutes. */
27
+ function convertSecondsToMinutes(seconds) {
28
+ if (!Number.isFinite(seconds))
29
+ return 0;
30
+ return Math.round(seconds / exports.SECONDS_PER_MINUTE);
31
+ }
32
+ /** Whole minutes → a decimal hour (display only). */
33
+ function convertMinutesToHours(minutes) {
34
+ if (!Number.isFinite(minutes))
35
+ return 0;
36
+ return Math.round((minutes / exports.MINUTES_PER_HOUR) * 100) / 100;
37
+ }
@@ -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';
@@ -63,6 +63,8 @@ __exportStar(require("./phone-helpers"), exports);
63
63
  __exportStar(require("./platform-catalog"), exports);
64
64
  __exportStar(require("./platform-num"), exports);
65
65
  __exportStar(require("./platform-specific-tenant-shifts"), exports);
66
+ __exportStar(require("./percentage-conversion"), exports);
67
+ __exportStar(require("./duration-conversion"), exports);
66
68
  __exportStar(require("./price-conversion"), exports);
67
69
  __exportStar(require("./printer-helpers"), exports);
68
70
  __exportStar(require("./public-holidays-helpers"), exports);
@@ -0,0 +1,49 @@
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 declare 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 declare function convertPercentToBasisPoints(percent: number): number;
27
+ /**
28
+ * Basis points → percent (the display unit).
29
+ *
30
+ * The result MAY be fractional (5000 bps → 50%, 1667 bps → 16.67%): this is
31
+ * the display boundary, where a rounded number is correct and a stored one
32
+ * would not be.
33
+ */
34
+ export declare function convertBasisPointsToPercent(basisPoints: number): number;
35
+ /**
36
+ * Basis points → a percent label (`'50%'`, `'16.67%'`).
37
+ *
38
+ * `null` / a non-finite value renders as the em dash the reports use for an
39
+ * absent rate.
40
+ */
41
+ export declare function formatBasisPointsAsPercent(basisPoints: number | null | undefined): string;
42
+ /**
43
+ * A percentage VALUE → a percent label (`'50%'`, `'16.67%'`).
44
+ *
45
+ * The rounding rule lives here so every report formats a percentage the same
46
+ * way. `null` / a non-finite value renders as the em dash the reports use for
47
+ * an absent rate.
48
+ */
49
+ export declare function formatPercentValue(percent: number | null | undefined): string;
@@ -0,0 +1,76 @@
1
+ "use strict";
2
+ /**
3
+ * Percentage unit conversions.
4
+ *
5
+ * The platform stores a percentage RATE as integer BASIS POINTS (1% = 100
6
+ * bps, 50% = 5000). Basis points are the storage unit because they are
7
+ * integers: a stored percentage can never be fractional, and `50%` is
8
+ * representable exactly while `33.3333333%` is not.
9
+ *
10
+ * Money follows the same idea and uses `price-conversion.ts`
11
+ * (`convertPriceToCents` / `convertPriceFromCents`).
12
+ *
13
+ * The rule is the same on both sides of the API boundary:
14
+ * - BEFORE storing / after fetching: convert with the helpers below;
15
+ * - NEVER infer the unit from the magnitude of a value.
16
+ */
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.BASIS_POINTS_PER_PERCENT = void 0;
19
+ exports.convertPercentToBasisPoints = convertPercentToBasisPoints;
20
+ exports.convertBasisPointsToPercent = convertBasisPointsToPercent;
21
+ exports.formatBasisPointsAsPercent = formatBasisPointsAsPercent;
22
+ exports.formatPercentValue = formatPercentValue;
23
+ /** 1% expressed in basis points. */
24
+ exports.BASIS_POINTS_PER_PERCENT = 100;
25
+ /**
26
+ * Percent → basis points (the storage unit).
27
+ *
28
+ * The input must be an integer percentage: the platform's rates are whole
29
+ * percent steps. A fractional percent is rejected instead of silently
30
+ * truncated — a half-percent discount must be stored as 50 bps by its writer,
31
+ * not rounded into a whole percent here.
32
+ */
33
+ function convertPercentToBasisPoints(percent) {
34
+ if (!Number.isFinite(percent))
35
+ return 0;
36
+ if (!Number.isInteger(percent)) {
37
+ throw new Error(`convertPercentToBasisPoints expects an integer percentage (got ${percent}). ` +
38
+ 'Store a fractional rate as integer basis points at its writer.');
39
+ }
40
+ return percent * exports.BASIS_POINTS_PER_PERCENT;
41
+ }
42
+ /**
43
+ * Basis points → percent (the display unit).
44
+ *
45
+ * The result MAY be fractional (5000 bps → 50%, 1667 bps → 16.67%): this is
46
+ * the display boundary, where a rounded number is correct and a stored one
47
+ * would not be.
48
+ */
49
+ function convertBasisPointsToPercent(basisPoints) {
50
+ if (!Number.isFinite(basisPoints))
51
+ return 0;
52
+ return basisPoints / exports.BASIS_POINTS_PER_PERCENT;
53
+ }
54
+ /**
55
+ * Basis points → a percent label (`'50%'`, `'16.67%'`).
56
+ *
57
+ * `null` / a non-finite value renders as the em dash the reports use for an
58
+ * absent rate.
59
+ */
60
+ function formatBasisPointsAsPercent(basisPoints) {
61
+ if (basisPoints == null || !Number.isFinite(basisPoints))
62
+ return '—';
63
+ return formatPercentValue(convertBasisPointsToPercent(basisPoints));
64
+ }
65
+ /**
66
+ * A percentage VALUE → a percent label (`'50%'`, `'16.67%'`).
67
+ *
68
+ * The rounding rule lives here so every report formats a percentage the same
69
+ * way. `null` / a non-finite value renders as the em dash the reports use for
70
+ * an absent rate.
71
+ */
72
+ function formatPercentValue(percent) {
73
+ if (percent == null || !Number.isFinite(percent))
74
+ return '—';
75
+ return `${Math.round(percent * 100) / 100}%`;
76
+ }
@@ -87,7 +87,6 @@ export declare const MaterializedTenantDiscountSourceSchema: Schema<any, import(
87
87
  covered_amount: number;
88
88
  level: import("../../constants/MATERIALIZED_REPORTS").MATERIALIZED_DISCOUNT_LEVEL_ENUM;
89
89
  kind: import("../../constants/MATERIALIZED_REPORTS").MATERIALIZED_DISCOUNT_ENTRY_KIND_ENUM;
90
- rate: number;
91
90
  complimentary_full: boolean;
92
91
  row_count: number;
93
92
  free_item_count: number;
@@ -157,7 +156,6 @@ export declare const MaterializedTenantDiscountSourceSchema: Schema<any, import(
157
156
  covered_amount: number;
158
157
  level: import("../../constants/MATERIALIZED_REPORTS").MATERIALIZED_DISCOUNT_LEVEL_ENUM;
159
158
  kind: import("../../constants/MATERIALIZED_REPORTS").MATERIALIZED_DISCOUNT_ENTRY_KIND_ENUM;
160
- rate: number;
161
159
  complimentary_full: boolean;
162
160
  row_count: number;
163
161
  free_item_count: number;
@@ -227,7 +225,6 @@ export declare const MaterializedTenantDiscountSourceSchema: Schema<any, import(
227
225
  covered_amount: number;
228
226
  level: import("../../constants/MATERIALIZED_REPORTS").MATERIALIZED_DISCOUNT_LEVEL_ENUM;
229
227
  kind: import("../../constants/MATERIALIZED_REPORTS").MATERIALIZED_DISCOUNT_ENTRY_KIND_ENUM;
230
- rate: number;
231
228
  complimentary_full: boolean;
232
229
  row_count: number;
233
230
  free_item_count: number;
@@ -71,7 +71,11 @@ exports.MaterializedTenantDiscountSourceSchema = new mongoose_1.Schema({
71
71
  enum: [...MATERIALIZED_REPORTS_1.ALL_MATERIALIZED_DISCOUNT_SLOTS, null],
72
72
  },
73
73
  sub_kind: { type: String, required: true, enum: MATERIALIZED_REPORTS_1.ALL_MATERIALIZED_DISCOUNT_SUB_KINDS },
74
- rate: { type: Number, default: null },
74
+ // NO stored average rate: a source stores the integer SUM of its
75
+ // percentage rates (`percentage_rate_sum`, in basis points) and the COUNT
76
+ // of its percentage rows (`percentage_row_count`). The average is DERIVED
77
+ // (sum / count) at the read boundary, so no fractional average is ever
78
+ // stored and the sum stays exact.
75
79
  rate_kind: {
76
80
  type: String,
77
81
  default: null,
@@ -49,12 +49,18 @@ export interface IMaterializedDiscountEntry {
49
49
  catalog_auto?: boolean | null;
50
50
  item_name?: string | null;
51
51
  payment_id?: string | null;
52
- /** Raw slot value (PERCENT for percentage rows) — not money. */
52
+ /**
53
+ * The row's slot value — NOT money.
54
+ *
55
+ * For a PERCENTAGE row this is the rate in integer BASIS POINTS (1% = 100
56
+ * bps; 50% = 5000), exactly as the order's discount details store it. For a
57
+ * fixed row it is the fixed amount in integer CENTS.
58
+ */
53
59
  rate: number | null;
54
- /** The MONEY applied by this row (cents) — what the drill-down shows. */
60
+ /** The MONEY applied by this row (integer CENTS) — what the drill-down shows. */
55
61
  amount: number;
56
62
  is_percentage: boolean | null;
57
- /** For FREE_ITEM rows: the discounted item's own value. */
63
+ /** For FREE_ITEM rows: the discounted item's own value (integer CENTS). */
58
64
  item_value?: number | null;
59
65
  discount_id: string | null;
60
66
  name: string | null;
@@ -66,9 +72,10 @@ export interface IMaterializedDiscountEntry {
66
72
  * another tender; null for a row written before this metadata existed.
67
73
  */
68
74
  complimentary_full?: boolean | null;
69
- /** COMPLIMENTARY rows only: the amount this tender covered (cents). */
75
+ /** COMPLIMENTARY rows only: the amount this tender covered (integer CENTS). */
70
76
  covered_amount?: number | null;
71
77
  /** COMPLIMENTARY rows only: the order amount used for the full/partial test. */
78
+ /** The order's total (integer CENTS). */
72
79
  order_amount?: number | null;
73
80
  staff_id: string | null;
74
81
  staff_name: string | null;
@@ -28,6 +28,19 @@ import { MATERIALIZED_DISCOUNT_ENTRY_KIND_ENUM, MATERIALIZED_DISCOUNT_LEVEL_ENUM
28
28
  * bucket per level (the rows keep their individual rates), and a collection is
29
29
  * keyed by its `discounts` `_id`, not by its name.
30
30
  *
31
+ * ## UNITS (the integer-only storage contract)
32
+ *
33
+ * | field | unit |
34
+ * |---|---|
35
+ * | `discount_amount`, `free_item_value`, `covered_amount` | integer CENTS |
36
+ * | `percentage_rate_sum` | integer BASIS POINTS (1% = 100 bps) |
37
+ * | `order_count`, `row_count`, `*_row_count` | integers |
38
+ *
39
+ * NO stored average rate: the source stores the SUM of its percentage rates
40
+ * (`percentage_rate_sum`, integer basis points) and the COUNT of its
41
+ * percentage rows (`percentage_row_count`). The average is derived at the read
42
+ * boundary — `sum / count` — so no fractional average is ever stored.
43
+ *
31
44
  * ## Money
32
45
  *
33
46
  * `discount_amount` is RESOLVED money in CENTS — the same money the entry
@@ -56,9 +69,14 @@ export interface IMaterializedDiscountSourceKeyMetrics {
56
69
  free_item_value: number;
57
70
  /** Amount covered by a COMPLIMENTARY tender (CENTS). */
58
71
  covered_amount: number;
59
- /** Percentage rows (numerator for the displayed average rate). */
72
+ /** Percentage rows (the count behind the derived average rate). */
60
73
  percentage_row_count: number;
61
- /** Σ RAW percentage values (denominator is `percentage_row_count`). */
74
+ /**
75
+ * Σ the percentage rows' RATES, in integer BASIS POINTS (1% = 100 bps).
76
+ *
77
+ * Together with `percentage_row_count` this is the EXACT average: the read
78
+ * derives `sum / count` (basis points) and converts it to a percentage.
79
+ */
62
80
  percentage_rate_sum: number;
63
81
  /** Fixed-amount rows. */
64
82
  fixed_row_count: number;
@@ -86,12 +104,13 @@ export interface IMaterializedTenantDiscountSource {
86
104
  level: MATERIALIZED_DISCOUNT_LEVEL_ENUM;
87
105
  slot: MATERIALIZED_DISCOUNT_SLOT_ENUM | null;
88
106
  sub_kind: MATERIALIZED_DISCOUNT_SUB_KIND_ENUM;
89
- /** Average percentage rate; null for a fixed-only or mixed source. */
90
- rate: number | null;
91
107
  /** Whether the rows behind this source are percentage, fixed or mixed. */
92
108
  rate_kind: MATERIALIZED_DISCOUNT_RATE_KIND_ENUM | null;
109
+ /** The count of the source's percentage rows (integer). */
93
110
  percentage_row_count: number;
111
+ /** Σ the percentage rows' rates, in integer BASIS POINTS. */
94
112
  percentage_rate_sum: number;
113
+ /** The count of the source's fixed-amount rows (integer). */
95
114
  fixed_row_count: number;
96
115
  /** Distinct orders (per scope; never sum overlapping scopes). */
97
116
  order_count: number;
@@ -1,3 +1,4 @@
1
+ import { IDiscountDetails, IOrderCategory } from '../../schemas/types/orders';
1
2
  /**
2
3
  * Loader for the live-store order fixtures used by materialized-report tests.
3
4
  *
@@ -68,6 +69,12 @@ export interface RawFixtureOrder {
68
69
  deferred_settlement?: boolean;
69
70
  is_deleted?: boolean;
70
71
  payments?: FixturePayment[];
72
+ /** Order-level discount details (upgraded to the integer contract on load). */
73
+ order_discount_details?: IDiscountDetails | null;
74
+ /** Order-level item discount details (upgraded to the integer contract on load). */
75
+ item_discount_details?: IDiscountDetails | null;
76
+ /** Order categories (their money is upgraded on load). */
77
+ categories?: IOrderCategory[];
71
78
  /** Enriched ILocalTimeFields (`scripts/enrich-order-fixtures.ts`). */
72
79
  localDate?: string;
73
80
  localHour?: number;
@@ -86,7 +93,14 @@ export interface FixtureOrder extends Omit<RawFixtureOrder, 'createdAt' | 'order
86
93
  */
87
94
  updatedAt: Date;
88
95
  }
89
- /** Load a dataset with dates normalized to `Date` objects (cached per process). */
96
+ /**
97
+ * Load a dataset with dates normalized to `Date` objects AND the legacy
98
+ * storage format upgraded to the integer contract (cents / basis points).
99
+ *
100
+ * The upgrade is applied here — at the SOURCE boundary — so every consumer
101
+ * (the materialized tests, the demo generator, the close-day simulation) reads
102
+ * the same integer source the live store holds today.
103
+ */
90
104
  export declare function loadOrdersDataset(name: OrdersDatasetName): FixtureOrder[];
91
105
  /**
92
106
  * Load the dataset WITHOUT date normalization — useful when asserting the raw
@@ -33,6 +33,106 @@ exports.ORDERS_DATASETS = {
33
33
  exports.ALL_ORDERS_DATASET_NAMES = ['basha', 'bruzo'];
34
34
  const cache = new Map();
35
35
  const rawCache = new Map();
36
+ /**
37
+ * The percentage slots of a discount-details block.
38
+ *
39
+ * A PERCENTAGE slot holds the RATE; a fixed slot holds MONEY. The rate is
40
+ * stored in basis points (1% = 100 bps) — the same unit the order writer uses
41
+ * (`getOrderDiscountDetailsWithPrice`).
42
+ */
43
+ const DISCOUNT_SLOTS = [
44
+ { value: 'special_discount', isPercentage: 'is_special_discount_percentage' },
45
+ { value: 'loyalty_discount', isPercentage: 'is_loyalty_discount_percentage' },
46
+ { value: 'voucher_discount', isPercentage: 'is_voucher_discount_percentage' },
47
+ ];
48
+ /**
49
+ * Upgrade a LEGACY discount-details block to the integer storage contract.
50
+ *
51
+ * The fixtures were exported from live stores BEFORE two platform changes:
52
+ *
53
+ * 1. the order's percentage RATE was stored in whole PERCENT (`special_discount:
54
+ * 25` for 25%); it is now stored in integer BASIS POINTS (`2500`);
55
+ * 2. the order's MONEY was left with a sub-cent fraction (`total_discount:
56
+ * 8717.5`) because the percentage / GST / proportional-split maths never
57
+ * rounded to the cent; money is now integer CENTS.
58
+ *
59
+ * Both upgrades are exact and lossless: ×100 on the rate (a unit change, not
60
+ * a rounding) and a round-to-the-cent on the money (the value is already in
61
+ * cents, so rounding to an integer IS rounding to the cent).
62
+ */
63
+ const upgradeDiscountDetails = (details) => {
64
+ if (details == null)
65
+ return details;
66
+ const upgraded = { ...details };
67
+ for (const slot of DISCOUNT_SLOTS) {
68
+ const value = upgraded[slot.value];
69
+ if (typeof value !== 'number')
70
+ continue;
71
+ if (upgraded[slot.isPercentage] === true) {
72
+ // PERCENT -> BASIS POINTS (the storage unit of a rate).
73
+ upgraded[slot.value] = Math.round(value * 100);
74
+ }
75
+ else {
76
+ // FIXED slot: MONEY in cents -> integer cents.
77
+ upgraded[slot.value] = Math.round(value);
78
+ }
79
+ }
80
+ if (typeof upgraded.total_discount === 'number') {
81
+ upgraded.total_discount = Math.round(upgraded.total_discount);
82
+ }
83
+ return upgraded;
84
+ };
85
+ /** Round a money field to integer cents (the value is already in cents). */
86
+ const toCents = (value) => (typeof value === 'number' ? Math.round(value) : value);
87
+ /**
88
+ * Upgrade a legacy fixture order to the integer storage contract.
89
+ *
90
+ * Only the fields the materialized reports read are touched: the money (to
91
+ * integer cents), the percentage rates (to basis points) and the item/payment
92
+ * breakdown the reports fold. Coordinates (`lat` / `lng`) are degrees — they
93
+ * are legitimately fractional and are NOT part of a report's money contract.
94
+ */
95
+ const upgradeLegacyOrder = (order) => {
96
+ const upgraded = { ...order };
97
+ for (const moneyField of [
98
+ 'grand_total',
99
+ 'amount_collected',
100
+ 'amount_earned',
101
+ 'total_discount_applied',
102
+ 'gst_amount',
103
+ 'tip_amount',
104
+ 'tax_amount',
105
+ ]) {
106
+ upgraded[moneyField] = toCents(upgraded[moneyField]);
107
+ }
108
+ upgraded.order_discount_details = upgradeDiscountDetails(order.order_discount_details ?? null);
109
+ upgraded.item_discount_details = upgradeDiscountDetails(order.item_discount_details ?? null);
110
+ if (Array.isArray(order.payments)) {
111
+ upgraded.payments = order.payments.map((payment) => ({
112
+ ...payment,
113
+ amount_due: toCents(payment.amount_due),
114
+ amount_paid: toCents(payment.amount_paid),
115
+ amount_refunded: toCents(payment.amount_refunded),
116
+ }));
117
+ }
118
+ if (Array.isArray(order.categories)) {
119
+ upgraded.categories = order.categories.map((category) => ({
120
+ ...category,
121
+ items: Array.isArray(category.items)
122
+ ? category.items.map((item) => ({
123
+ ...item,
124
+ _net_amount: toCents(item._net_amount),
125
+ _gross_amount: toCents(item._gross_amount),
126
+ _discount_amount: toCents(item._discount_amount),
127
+ _gst_amount: toCents(item._gst_amount),
128
+ subtotal: toCents(item.subtotal),
129
+ item_discount_details: upgradeDiscountDetails(item.item_discount_details ?? null),
130
+ }))
131
+ : category.items,
132
+ }));
133
+ }
134
+ return upgraded;
135
+ };
36
136
  /**
37
137
  * Resolve a fixture file from either the source tree (`src/tests/...`) or a
38
138
  * compiled tree (`lib/tests/materialized-reports/...` — the repo compiles
@@ -64,18 +164,28 @@ function loadRawOrdersDataset(name) {
64
164
  rawCache.set(name, parsed);
65
165
  return parsed;
66
166
  }
67
- /** Load a dataset with dates normalized to `Date` objects (cached per process). */
167
+ /**
168
+ * Load a dataset with dates normalized to `Date` objects AND the legacy
169
+ * storage format upgraded to the integer contract (cents / basis points).
170
+ *
171
+ * The upgrade is applied here — at the SOURCE boundary — so every consumer
172
+ * (the materialized tests, the demo generator, the close-day simulation) reads
173
+ * the same integer source the live store holds today.
174
+ */
68
175
  function loadOrdersDataset(name) {
69
176
  const cached = cache.get(name);
70
177
  if (cached)
71
178
  return cached;
72
- const orders = loadRawOrdersDataset(name).map((order) => ({
73
- ...order,
74
- createdAt: new Date(order.createdAt),
75
- order_settled_at: order.order_settled_at != null ? new Date(order.order_settled_at) : null,
76
- payments: order.payments ?? [],
77
- updatedAt: order.updatedAt != null ? new Date(order.updatedAt) : new Date(order.createdAt),
78
- }));
179
+ const orders = loadRawOrdersDataset(name).map((rawOrder) => {
180
+ const order = upgradeLegacyOrder(rawOrder);
181
+ return {
182
+ ...order,
183
+ createdAt: new Date(order.createdAt),
184
+ order_settled_at: order.order_settled_at != null ? new Date(order.order_settled_at) : null,
185
+ payments: order.payments ?? [],
186
+ updatedAt: order.updatedAt != null ? new Date(order.updatedAt) : new Date(order.createdAt),
187
+ };
188
+ });
79
189
  cache.set(name, orders);
80
190
  return orders;
81
191
  }