@managesome/eposmatic-toolkit 0.4.23 → 0.4.24

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 (46) hide show
  1. package/esm/constants/MATERIALIZED_REPORTS.js +83 -2
  2. package/esm/helpers/materialized-reports/index.js +3 -0
  3. package/esm/helpers/materialized-reports/materialized-discount-accumulator-helpers.js +115 -35
  4. package/esm/helpers/materialized-reports/materialized-discount-classification-helpers.js +39 -12
  5. package/esm/helpers/materialized-reports/materialized-discount-details-helpers.js +28 -0
  6. package/esm/helpers/materialized-reports/materialized-discount-source-helpers.js +428 -0
  7. package/esm/helpers/materialized-reports/tenant-discount-source-formatter.js +140 -0
  8. package/esm/schemas/models/index.js +1 -0
  9. package/esm/schemas/models/materialized_tenant_discount_entries.js +12 -0
  10. package/esm/schemas/models/materialized_tenant_discount_sources.js +165 -0
  11. package/esm/schemas/types/index.js +1 -0
  12. package/esm/schemas/types/materialized_tenant_discount_sources.js +1 -0
  13. package/lib/constants/MATERIALIZED_REPORTS.d.ts +79 -2
  14. package/lib/constants/MATERIALIZED_REPORTS.js +85 -4
  15. package/lib/helpers/materialized-reports/index.d.ts +3 -0
  16. package/lib/helpers/materialized-reports/index.js +3 -0
  17. package/lib/helpers/materialized-reports/materialized-discount-accumulator-helpers.d.ts +30 -0
  18. package/lib/helpers/materialized-reports/materialized-discount-accumulator-helpers.js +116 -35
  19. package/lib/helpers/materialized-reports/materialized-discount-classification-helpers.d.ts +27 -4
  20. package/lib/helpers/materialized-reports/materialized-discount-classification-helpers.js +38 -11
  21. package/lib/helpers/materialized-reports/materialized-discount-details-helpers.d.ts +31 -0
  22. package/lib/helpers/materialized-reports/materialized-discount-details-helpers.js +31 -0
  23. package/lib/helpers/materialized-reports/materialized-discount-source-helpers.d.ts +73 -0
  24. package/lib/helpers/materialized-reports/materialized-discount-source-helpers.js +437 -0
  25. package/lib/helpers/materialized-reports/tenant-discount-source-formatter.d.ts +79 -0
  26. package/lib/helpers/materialized-reports/tenant-discount-source-formatter.js +144 -0
  27. package/lib/helpers/types/materialized-reports-apis.d.ts +53 -1
  28. package/lib/schemas/models/index.d.ts +1 -0
  29. package/lib/schemas/models/index.js +1 -0
  30. package/lib/schemas/models/materialized_tenant_discount_entries.d.ts +21 -6
  31. package/lib/schemas/models/materialized_tenant_discount_entries.js +12 -0
  32. package/lib/schemas/models/materialized_tenant_discount_sources.d.ts +331 -0
  33. package/lib/schemas/models/materialized_tenant_discount_sources.js +168 -0
  34. package/lib/schemas/types/index.d.ts +1 -0
  35. package/lib/schemas/types/index.js +1 -0
  36. package/lib/schemas/types/materialized_tenant_discount_entries.d.ts +26 -0
  37. package/lib/schemas/types/materialized_tenant_discount_sources.d.ts +128 -0
  38. package/lib/schemas/types/materialized_tenant_discount_sources.js +2 -0
  39. package/lib/tests/materialized-reports/materialized-discount-classification.test.js +22 -2
  40. package/lib/tests/materialized-reports/materialized-discount-details-helpers.test.d.ts +1 -0
  41. package/lib/tests/materialized-reports/materialized-discount-details-helpers.test.js +59 -0
  42. package/lib/tests/materialized-reports/materialized-discount-sources.test.d.ts +1 -0
  43. package/lib/tests/materialized-reports/materialized-discount-sources.test.js +483 -0
  44. package/lib/tests/materialized-reports/tenant-discount-source-formatter.test.d.ts +1 -0
  45. package/lib/tests/materialized-reports/tenant-discount-source-formatter.test.js +203 -0
  46. package/package.json +1 -1
@@ -0,0 +1,428 @@
1
+ import mongoose from 'mongoose';
2
+ import { DISCOUNTS_KEY_FILTERS, MATERIALIZED_DISCOUNT_ENTRY_KIND_ENUM, MATERIALIZED_DISCOUNT_LEVEL_ENUM, MATERIALIZED_DISCOUNT_RATE_KIND_ENUM, MATERIALIZED_DISCOUNT_SLOT_ENUM, MATERIALIZED_DISCOUNT_SOURCE_CLASS_ENUM, MATERIALIZED_DISCOUNT_SOURCE_KEY, MATERIALIZED_DISCOUNT_SOURCE_KEY_PREFIX, MATERIALIZED_DISCOUNT_SUB_KIND_ENUM, } from '../../constants/MATERIALIZED_REPORTS';
3
+ import { MATERIALIZED_TENANT_DISCOUNT_SOURCES_SCHEMA_VERSION } from '../../schemas/models/materialized_tenant_discount_sources';
4
+ /** `'VISA CARD'` / `'visa-card'` → `'visa_card'`; bounded and lowercase. */
5
+ export function normalizeDiscountSourceKeyPart(value) {
6
+ if (typeof value !== 'string')
7
+ return '';
8
+ return value
9
+ .trim()
10
+ .toLowerCase()
11
+ .replace(/[^a-z0-9]+/g, '_')
12
+ .replace(/^_+|_+$/g, '')
13
+ .slice(0, 80);
14
+ }
15
+ /** `'Discount applied for VISA CARD'` → `'VISA CARD'` (null when absent). */
16
+ export function getPaymentTypeFromDiscountReason(reason) {
17
+ if (typeof reason !== 'string')
18
+ return null;
19
+ const match = /^discount\s+applied\s+for\s+(.+)$/i.exec(reason.trim());
20
+ if (match == null)
21
+ return null;
22
+ const value = match[1].trim();
23
+ return value.length > 0 ? value : null;
24
+ }
25
+ /** `'VISA CARD'` → `'Visa Card'` (display only). */
26
+ function toDisplayWords(value) {
27
+ return value
28
+ .replace(/[_-]+/g, ' ')
29
+ .replace(/\s+/g, ' ')
30
+ .trim()
31
+ .split(' ')
32
+ .filter((part) => part.length > 0)
33
+ .map((part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase())
34
+ .join(' ');
35
+ }
36
+ /** Short id used in a fallback display name. */
37
+ function shortId(value) {
38
+ return value.length > 8 ? value.slice(-6) : value;
39
+ }
40
+ const cleanName = (value) => {
41
+ if (typeof value !== 'string')
42
+ return null;
43
+ const trimmed = value.trim();
44
+ return trimmed.length > 0 ? trimmed : null;
45
+ };
46
+ const unattributedIdentity = (level) => ({
47
+ source_key: MATERIALIZED_DISCOUNT_SOURCE_KEY.UNATTRIBUTED,
48
+ source_id: null,
49
+ source_name: 'Other / unattributed',
50
+ source_class: MATERIALIZED_DISCOUNT_SOURCE_CLASS_ENUM.UNATTRIBUTED,
51
+ kind: MATERIALIZED_DISCOUNT_ENTRY_KIND_ENUM.DISCOUNT,
52
+ level,
53
+ slot: null,
54
+ sub_kind: MATERIALIZED_DISCOUNT_SUB_KIND_ENUM.UNATTRIBUTED,
55
+ complimentary_full: null,
56
+ });
57
+ /**
58
+ * Classifies ONE entry row into its source identity.
59
+ *
60
+ * Ordering matters:
61
+ * 1. COMPLIMENTARY is a tender, not a discount.
62
+ * 2. A catalog-auto id is checked against the row's catalog/order-item ids
63
+ * BEFORE the generic 24-hex → collection rule, because both are ObjectIds.
64
+ * 3. A payment-type discount is a `MANUAL_*` id with a
65
+ * `Discount applied for <type>` reason; it must be separated from a manual
66
+ * discount BEFORE the manual bucket.
67
+ */
68
+ export function classifyDiscountEntrySource(entry) {
69
+ const level = entry.level;
70
+ if (entry.kind === MATERIALIZED_DISCOUNT_ENTRY_KIND_ENUM.COMPLIMENTARY) {
71
+ const full = entry.complimentary_full;
72
+ if (full === true) {
73
+ return {
74
+ source_key: MATERIALIZED_DISCOUNT_SOURCE_KEY.COMPLIMENTARY_FULL,
75
+ source_id: null,
76
+ source_name: 'Fully complimentary',
77
+ source_class: MATERIALIZED_DISCOUNT_SOURCE_CLASS_ENUM.COMPLIMENTARY,
78
+ kind: MATERIALIZED_DISCOUNT_ENTRY_KIND_ENUM.COMPLIMENTARY,
79
+ level: MATERIALIZED_DISCOUNT_LEVEL_ENUM.PAYMENT,
80
+ slot: null,
81
+ sub_kind: MATERIALIZED_DISCOUNT_SUB_KIND_ENUM.UNATTRIBUTED,
82
+ complimentary_full: true,
83
+ };
84
+ }
85
+ if (full === false) {
86
+ return {
87
+ source_key: MATERIALIZED_DISCOUNT_SOURCE_KEY.COMPLIMENTARY_PARTIAL,
88
+ source_id: null,
89
+ source_name: 'Partially complimentary',
90
+ source_class: MATERIALIZED_DISCOUNT_SOURCE_CLASS_ENUM.COMPLIMENTARY,
91
+ kind: MATERIALIZED_DISCOUNT_ENTRY_KIND_ENUM.COMPLIMENTARY,
92
+ level: MATERIALIZED_DISCOUNT_LEVEL_ENUM.PAYMENT,
93
+ slot: null,
94
+ sub_kind: MATERIALIZED_DISCOUNT_SUB_KIND_ENUM.UNATTRIBUTED,
95
+ complimentary_full: false,
96
+ };
97
+ }
98
+ // Defensive invalid-data bucket. The current close ALWAYS writes
99
+ // `complimentary_full`; null means a corrupt/partial document (or a direct
100
+ // DB write). Mark it unknown, never guess full vs partial.
101
+ return {
102
+ source_key: MATERIALIZED_DISCOUNT_SOURCE_KEY.COMPLIMENTARY_UNKNOWN,
103
+ source_id: null,
104
+ source_name: 'Complimentary (unclassified)',
105
+ source_class: MATERIALIZED_DISCOUNT_SOURCE_CLASS_ENUM.COMPLIMENTARY,
106
+ kind: MATERIALIZED_DISCOUNT_ENTRY_KIND_ENUM.COMPLIMENTARY,
107
+ level: MATERIALIZED_DISCOUNT_LEVEL_ENUM.PAYMENT,
108
+ slot: null,
109
+ sub_kind: MATERIALIZED_DISCOUNT_SUB_KIND_ENUM.UNATTRIBUTED,
110
+ complimentary_full: null,
111
+ };
112
+ }
113
+ if (level === MATERIALIZED_DISCOUNT_LEVEL_ENUM.PAYMENT) {
114
+ return unattributedIdentity(level);
115
+ }
116
+ const slot = entry.slot;
117
+ const discountId = cleanName(entry.discount_id);
118
+ const name = cleanName(entry.name);
119
+ const reference = cleanName(entry.reference_number);
120
+ const subKind = entry.sub_kind;
121
+ if (slot === MATERIALIZED_DISCOUNT_SLOT_ENUM.SPECIAL) {
122
+ // Pre-release: catalog auto is identified ONLY by the marker written by the
123
+ // current accumulator or by the current classifier's CATALOG_ITEM value.
124
+ // No id-shape/name fallback for documents materialized before that marker.
125
+ const isCatalogAuto = entry.catalog_auto === true;
126
+ if (isCatalogAuto || subKind === MATERIALIZED_DISCOUNT_SUB_KIND_ENUM.CATALOG_ITEM) {
127
+ return {
128
+ source_key: MATERIALIZED_DISCOUNT_SOURCE_KEY.CATALOG_AUTO,
129
+ source_id: null,
130
+ source_name: 'Catalog auto discount',
131
+ source_class: MATERIALIZED_DISCOUNT_SOURCE_CLASS_ENUM.CATALOG_AUTO,
132
+ kind: MATERIALIZED_DISCOUNT_ENTRY_KIND_ENUM.DISCOUNT,
133
+ level,
134
+ slot,
135
+ sub_kind: MATERIALIZED_DISCOUNT_SUB_KIND_ENUM.CATALOG_ITEM,
136
+ complimentary_full: null,
137
+ };
138
+ }
139
+ if (subKind === MATERIALIZED_DISCOUNT_SUB_KIND_ENUM.PRICE_OVERRIDE) {
140
+ return {
141
+ source_key: MATERIALIZED_DISCOUNT_SOURCE_KEY.PRICE_OVERRIDE_ITEM,
142
+ source_id: null,
143
+ source_name: 'Price override',
144
+ source_class: MATERIALIZED_DISCOUNT_SOURCE_CLASS_ENUM.PRICE_OVERRIDE,
145
+ kind: MATERIALIZED_DISCOUNT_ENTRY_KIND_ENUM.DISCOUNT,
146
+ level,
147
+ slot,
148
+ sub_kind: MATERIALIZED_DISCOUNT_SUB_KIND_ENUM.PRICE_OVERRIDE,
149
+ complimentary_full: null,
150
+ };
151
+ }
152
+ if (subKind === MATERIALIZED_DISCOUNT_SUB_KIND_ENUM.MANUAL) {
153
+ const paymentType = getPaymentTypeFromDiscountReason(entry.reason);
154
+ if (paymentType != null) {
155
+ const normalized = normalizeDiscountSourceKeyPart(paymentType);
156
+ if (normalized.length > 0) {
157
+ return {
158
+ source_key: `${MATERIALIZED_DISCOUNT_SOURCE_KEY_PREFIX.PAYMENT_TYPE}${normalized}`,
159
+ source_id: normalized,
160
+ source_name: `${toDisplayWords(paymentType)} discount`,
161
+ source_class: MATERIALIZED_DISCOUNT_SOURCE_CLASS_ENUM.PAYMENT_TYPE,
162
+ kind: MATERIALIZED_DISCOUNT_ENTRY_KIND_ENUM.DISCOUNT,
163
+ level,
164
+ slot,
165
+ sub_kind: MATERIALIZED_DISCOUNT_SUB_KIND_ENUM.MANUAL,
166
+ complimentary_full: null,
167
+ };
168
+ }
169
+ }
170
+ return {
171
+ source_key: level === MATERIALIZED_DISCOUNT_LEVEL_ENUM.ORDER
172
+ ? MATERIALIZED_DISCOUNT_SOURCE_KEY.MANUAL_ORDER
173
+ : MATERIALIZED_DISCOUNT_SOURCE_KEY.MANUAL_ITEM,
174
+ source_id: null,
175
+ source_name: level === MATERIALIZED_DISCOUNT_LEVEL_ENUM.ORDER ? 'Manual / quick discount' : 'Manual item discount',
176
+ source_class: MATERIALIZED_DISCOUNT_SOURCE_CLASS_ENUM.MANUAL,
177
+ kind: MATERIALIZED_DISCOUNT_ENTRY_KIND_ENUM.DISCOUNT,
178
+ level,
179
+ slot,
180
+ sub_kind: MATERIALIZED_DISCOUNT_SUB_KIND_ENUM.MANUAL,
181
+ complimentary_full: null,
182
+ };
183
+ }
184
+ if (subKind === MATERIALIZED_DISCOUNT_SUB_KIND_ENUM.COLLECTION && discountId != null) {
185
+ return {
186
+ source_key: `${MATERIALIZED_DISCOUNT_SOURCE_KEY_PREFIX.DISCOUNT}${discountId}`,
187
+ source_id: discountId,
188
+ source_name: name ?? `Discount ${shortId(discountId)}`,
189
+ source_class: MATERIALIZED_DISCOUNT_SOURCE_CLASS_ENUM.COLLECTION,
190
+ kind: MATERIALIZED_DISCOUNT_ENTRY_KIND_ENUM.DISCOUNT,
191
+ level,
192
+ slot,
193
+ sub_kind: MATERIALIZED_DISCOUNT_SUB_KIND_ENUM.COLLECTION,
194
+ complimentary_full: null,
195
+ };
196
+ }
197
+ return unattributedIdentity(level);
198
+ }
199
+ if (slot === MATERIALIZED_DISCOUNT_SLOT_ENUM.LOYALTY) {
200
+ if (subKind === MATERIALIZED_DISCOUNT_SUB_KIND_ENUM.WALLET_CASHBACK) {
201
+ return {
202
+ source_key: MATERIALIZED_DISCOUNT_SOURCE_KEY.WALLET_CASHBACK,
203
+ source_id: null,
204
+ source_name: 'Wallet cashback',
205
+ source_class: MATERIALIZED_DISCOUNT_SOURCE_CLASS_ENUM.LOYALTY,
206
+ kind: MATERIALIZED_DISCOUNT_ENTRY_KIND_ENUM.DISCOUNT,
207
+ level,
208
+ slot,
209
+ sub_kind: MATERIALIZED_DISCOUNT_SUB_KIND_ENUM.WALLET_CASHBACK,
210
+ complimentary_full: null,
211
+ };
212
+ }
213
+ // Offers and gift cards both write an ObjectId into the loyalty slot. A
214
+ // reference number is the gift-card code (the loyalty offer writer
215
+ // explicitly leaves it undefined), so it refines an OFFER row when the
216
+ // reference proves a gift card. The same rule is applied live in
217
+ // `readDiscountSlot` from `wallet_redemptions.gift_cards`.
218
+ const loyaltyIsGiftCard = subKind === MATERIALIZED_DISCOUNT_SUB_KIND_ENUM.GIFT_CARD ||
219
+ (subKind === MATERIALIZED_DISCOUNT_SUB_KIND_ENUM.OFFER && reference != null && reference !== 'WALLET_CASHBACK');
220
+ if (loyaltyIsGiftCard) {
221
+ const keyPart = discountId ?? reference;
222
+ if (keyPart == null)
223
+ return unattributedIdentity(level);
224
+ return {
225
+ source_key: `${MATERIALIZED_DISCOUNT_SOURCE_KEY_PREFIX.LOYALTY_GIFT_CARD}${keyPart}`,
226
+ source_id: keyPart,
227
+ source_name: name ?? `Gift card ${reference ?? shortId(keyPart)}`,
228
+ source_class: MATERIALIZED_DISCOUNT_SOURCE_CLASS_ENUM.LOYALTY,
229
+ kind: MATERIALIZED_DISCOUNT_ENTRY_KIND_ENUM.DISCOUNT,
230
+ level,
231
+ slot,
232
+ sub_kind: MATERIALIZED_DISCOUNT_SUB_KIND_ENUM.GIFT_CARD,
233
+ complimentary_full: null,
234
+ };
235
+ }
236
+ if (subKind === MATERIALIZED_DISCOUNT_SUB_KIND_ENUM.OFFER) {
237
+ const keyPart = discountId ?? reference;
238
+ if (keyPart == null)
239
+ return unattributedIdentity(level);
240
+ return {
241
+ source_key: `${MATERIALIZED_DISCOUNT_SOURCE_KEY_PREFIX.LOYALTY_OFFER}${keyPart}`,
242
+ source_id: keyPart,
243
+ source_name: name ?? `Offer ${shortId(keyPart)}`,
244
+ source_class: MATERIALIZED_DISCOUNT_SOURCE_CLASS_ENUM.LOYALTY,
245
+ kind: MATERIALIZED_DISCOUNT_ENTRY_KIND_ENUM.DISCOUNT,
246
+ level,
247
+ slot,
248
+ sub_kind: MATERIALIZED_DISCOUNT_SUB_KIND_ENUM.OFFER,
249
+ complimentary_full: null,
250
+ };
251
+ }
252
+ return unattributedIdentity(level);
253
+ }
254
+ if (slot === MATERIALIZED_DISCOUNT_SLOT_ENUM.VOUCHER) {
255
+ const keyPart = discountId ?? reference;
256
+ if (keyPart == null)
257
+ return unattributedIdentity(level);
258
+ return {
259
+ source_key: `${MATERIALIZED_DISCOUNT_SOURCE_KEY_PREFIX.VOUCHER}${keyPart}`,
260
+ source_id: keyPart,
261
+ source_name: name ?? `Voucher ${reference ?? shortId(keyPart)}`,
262
+ source_class: MATERIALIZED_DISCOUNT_SOURCE_CLASS_ENUM.VOUCHER,
263
+ kind: MATERIALIZED_DISCOUNT_ENTRY_KIND_ENUM.DISCOUNT,
264
+ level,
265
+ slot,
266
+ sub_kind: subKind === MATERIALIZED_DISCOUNT_SUB_KIND_ENUM.OFFER
267
+ ? MATERIALIZED_DISCOUNT_SUB_KIND_ENUM.OFFER
268
+ : MATERIALIZED_DISCOUNT_SUB_KIND_ENUM.UNATTRIBUTED,
269
+ complimentary_full: null,
270
+ };
271
+ }
272
+ return unattributedIdentity(level);
273
+ }
274
+ const nonNegative = (value) => (Number.isFinite(value) && value > 0 ? value : 0);
275
+ const round2 = (value) => Math.round((value ?? 0) * 100) / 100;
276
+ const emptyMetrics = () => ({
277
+ orderIds: new Set(),
278
+ row_count: 0,
279
+ discount_amount: 0,
280
+ free_item_count: 0,
281
+ free_item_value: 0,
282
+ covered_amount: 0,
283
+ percentage_row_count: 0,
284
+ percentage_rate_sum: 0,
285
+ fixed_row_count: 0,
286
+ });
287
+ /** Folds one row into a metrics bucket. */
288
+ function addRow(metrics, entry) {
289
+ const orderId = cleanName(entry.order_id);
290
+ if (orderId != null)
291
+ metrics.orderIds.add(orderId);
292
+ metrics.row_count += 1;
293
+ if (entry.kind !== MATERIALIZED_DISCOUNT_ENTRY_KIND_ENUM.COMPLIMENTARY) {
294
+ metrics.discount_amount += nonNegative(entry.amount);
295
+ }
296
+ if (entry.kind === MATERIALIZED_DISCOUNT_ENTRY_KIND_ENUM.FREE_ITEM) {
297
+ metrics.free_item_count += 1;
298
+ metrics.free_item_value += nonNegative(entry.item_value ?? 0);
299
+ }
300
+ if (entry.kind === MATERIALIZED_DISCOUNT_ENTRY_KIND_ENUM.COMPLIMENTARY) {
301
+ metrics.covered_amount += nonNegative(entry.covered_amount ?? 0);
302
+ }
303
+ if (entry.is_percentage === true) {
304
+ metrics.percentage_row_count += 1;
305
+ metrics.percentage_rate_sum += nonNegative(entry.rate ?? 0);
306
+ }
307
+ else if (entry.is_percentage === false) {
308
+ metrics.fixed_row_count += 1;
309
+ }
310
+ }
311
+ const metricsToKeyMetrics = (key, metrics) => ({
312
+ key,
313
+ order_count: metrics.orderIds.size,
314
+ row_count: metrics.row_count,
315
+ discount_amount: metrics.discount_amount,
316
+ free_item_count: metrics.free_item_count,
317
+ free_item_value: metrics.free_item_value,
318
+ covered_amount: metrics.covered_amount,
319
+ percentage_row_count: metrics.percentage_row_count,
320
+ percentage_rate_sum: metrics.percentage_rate_sum,
321
+ fixed_row_count: metrics.fixed_row_count,
322
+ });
323
+ const rateKindOf = (metrics) => {
324
+ if (metrics.percentage_row_count > 0 && metrics.fixed_row_count > 0) {
325
+ return MATERIALIZED_DISCOUNT_RATE_KIND_ENUM.MIXED;
326
+ }
327
+ if (metrics.percentage_row_count > 0)
328
+ return MATERIALIZED_DISCOUNT_RATE_KIND_ENUM.PERCENTAGE;
329
+ if (metrics.fixed_row_count > 0)
330
+ return MATERIALIZED_DISCOUNT_RATE_KIND_ENUM.FIXED;
331
+ return null;
332
+ };
333
+ /**
334
+ * Builds the source documents for ONE scope from its POST-PLAN entry sections.
335
+ *
336
+ * The caller passes the complete final entry document for the scope (day,
337
+ * hour or accumulated period). Period scopes therefore yield true period
338
+ * sources without a second accumulator: the entry document already holds every
339
+ * sibling day's rows.
340
+ *
341
+ * Returns `[]` for an empty scope (the caller deletes any stored sources for
342
+ * that scope). Returns `null` on malformed input.
343
+ */
344
+ export function buildDiscountSourcesForScope(input) {
345
+ if (input == null)
346
+ return null;
347
+ const { tenantId, brandId, scopeContext, scopeField, sections, computedAt } = input;
348
+ if (typeof tenantId !== 'string' || tenantId.length === 0)
349
+ return null;
350
+ if (typeof brandId !== 'string' || brandId.length === 0)
351
+ return null;
352
+ if (typeof scopeField !== 'string' || scopeField.length === 0)
353
+ return null;
354
+ if (!(computedAt instanceof Date) || Number.isNaN(computedAt.getTime()))
355
+ return null;
356
+ const buckets = new Map();
357
+ for (const [key, section] of Object.entries(sections ?? {})) {
358
+ for (const entry of section?.rows ?? []) {
359
+ if (entry == null)
360
+ continue;
361
+ const identity = classifyDiscountEntrySource(entry);
362
+ const bucketKey = `${identity.source_key}|${identity.level}`;
363
+ let bucket = buckets.get(bucketKey);
364
+ if (bucket == null) {
365
+ bucket = { identity, totals: emptyMetrics(), byKey: new Map() };
366
+ buckets.set(bucketKey, bucket);
367
+ }
368
+ addRow(bucket.totals, entry);
369
+ const keyMetrics = bucket.byKey.get(key) ?? emptyMetrics();
370
+ addRow(keyMetrics, entry);
371
+ bucket.byKey.set(key, keyMetrics);
372
+ }
373
+ }
374
+ const sourceWatermark = input.sourceWatermark ?? computedAt;
375
+ const docs = [];
376
+ for (const bucket of buckets.values()) {
377
+ const { identity, totals } = bucket;
378
+ const rate = totals.percentage_row_count > 0 ? round2(totals.percentage_rate_sum / totals.percentage_row_count) : null;
379
+ const kind = identity.kind === MATERIALIZED_DISCOUNT_ENTRY_KIND_ENUM.COMPLIMENTARY
380
+ ? MATERIALIZED_DISCOUNT_ENTRY_KIND_ENUM.COMPLIMENTARY
381
+ : totals.free_item_count > 0 && totals.free_item_count === totals.row_count
382
+ ? MATERIALIZED_DISCOUNT_ENTRY_KIND_ENUM.FREE_ITEM
383
+ : MATERIALIZED_DISCOUNT_ENTRY_KIND_ENUM.DISCOUNT;
384
+ docs.push({
385
+ _id: new mongoose.Types.ObjectId().toHexString(),
386
+ tenant_id: tenantId,
387
+ brand_id: brandId,
388
+ scope_context: scopeContext,
389
+ scope_field: scopeField,
390
+ day_index: input.dayIndex ?? null,
391
+ source_key: identity.source_key,
392
+ source_id: identity.source_id,
393
+ source_name: identity.source_name,
394
+ source_class: identity.source_class,
395
+ kind,
396
+ level: identity.level,
397
+ slot: identity.slot,
398
+ sub_kind: identity.sub_kind,
399
+ rate,
400
+ rate_kind: rateKindOf(totals),
401
+ percentage_row_count: totals.percentage_row_count,
402
+ percentage_rate_sum: totals.percentage_rate_sum,
403
+ fixed_row_count: totals.fixed_row_count,
404
+ order_count: totals.orderIds.size,
405
+ row_count: totals.row_count,
406
+ discount_amount: totals.discount_amount,
407
+ free_item_count: totals.free_item_count,
408
+ free_item_value: totals.free_item_value,
409
+ complimentary_full: identity.complimentary_full,
410
+ covered_amount: totals.covered_amount,
411
+ key_metrics: [...bucket.byKey.entries()]
412
+ .sort(([a], [b]) => a.localeCompare(b))
413
+ .map(([key, metrics]) => metricsToKeyMetrics(key, metrics)),
414
+ sale_type_key_filters: [...DISCOUNTS_KEY_FILTERS],
415
+ schema_version: MATERIALIZED_TENANT_DISCOUNT_SOURCES_SCHEMA_VERSION,
416
+ source_watermark: sourceWatermark,
417
+ computed_at: computedAt,
418
+ createdAt: computedAt,
419
+ updatedAt: computedAt,
420
+ });
421
+ }
422
+ // Biggest money first, then the free/complimentary rows (which carry no
423
+ // discount money), then name — a deterministic order for the write and the
424
+ // tests. The READ sorts again after folding scopes.
425
+ return docs.sort((a, b) => b.discount_amount - a.discount_amount ||
426
+ a.source_name.localeCompare(b.source_name) ||
427
+ a.level.localeCompare(b.level));
428
+ }
@@ -0,0 +1,140 @@
1
+ import { MATERIALIZED_DISCOUNT_RATE_KIND_ENUM, MATERIALIZED_DISCOUNT_SOURCE_CLASS_ENUM, } from '../../constants/MATERIALIZED_REPORTS';
2
+ import { convertPriceFromCents } from '../utils/price-conversion';
3
+ const round2 = (value) => Math.round((value ?? 0) * 100) / 100;
4
+ export function getDiscountSourceShareReconciliation(summaryTotal, sourceTotal) {
5
+ const summary = Number.isFinite(summaryTotal) ? Math.max(0, summaryTotal ?? 0) : 0;
6
+ const source = Number.isFinite(sourceTotal) ? Math.max(0, sourceTotal) : 0;
7
+ const gap = round2(Math.max(0, summary - source));
8
+ const overage = round2(Math.max(0, source - summary));
9
+ return {
10
+ share_basis: round2(Math.max(summary, source)),
11
+ gap,
12
+ overage,
13
+ show_gap: gap > 0.009,
14
+ show_overage: overage > 0.009,
15
+ };
16
+ }
17
+ const toDecimal = (cents) => convertPriceFromCents(cents ?? 0);
18
+ const CLASS_LABELS = {
19
+ [MATERIALIZED_DISCOUNT_SOURCE_CLASS_ENUM.COLLECTION]: 'Collection',
20
+ [MATERIALIZED_DISCOUNT_SOURCE_CLASS_ENUM.MANUAL]: 'Manual',
21
+ [MATERIALIZED_DISCOUNT_SOURCE_CLASS_ENUM.PAYMENT_TYPE]: 'Payment type',
22
+ [MATERIALIZED_DISCOUNT_SOURCE_CLASS_ENUM.PRICE_OVERRIDE]: 'Price override',
23
+ [MATERIALIZED_DISCOUNT_SOURCE_CLASS_ENUM.CATALOG_AUTO]: 'Catalog auto',
24
+ [MATERIALIZED_DISCOUNT_SOURCE_CLASS_ENUM.LOYALTY]: 'Loyalty',
25
+ [MATERIALIZED_DISCOUNT_SOURCE_CLASS_ENUM.VOUCHER]: 'Voucher',
26
+ [MATERIALIZED_DISCOUNT_SOURCE_CLASS_ENUM.COMPLIMENTARY]: 'Complimentary',
27
+ [MATERIALIZED_DISCOUNT_SOURCE_CLASS_ENUM.UNATTRIBUTED]: 'Other',
28
+ };
29
+ const LEVEL_LABELS = {
30
+ ORDER: 'Order',
31
+ ITEM: 'Item',
32
+ PAYMENT: 'Payment',
33
+ };
34
+ const formatRate = (rate) => {
35
+ if (rate == null || !Number.isFinite(rate))
36
+ return '—';
37
+ return `${Math.round(rate * 100) / 100}%`;
38
+ };
39
+ const rateKindLabel = (rateKind) => {
40
+ switch (rateKind) {
41
+ case MATERIALIZED_DISCOUNT_RATE_KIND_ENUM.PERCENTAGE:
42
+ return 'Percentage';
43
+ case MATERIALIZED_DISCOUNT_RATE_KIND_ENUM.FIXED:
44
+ return 'Fixed';
45
+ case MATERIALIZED_DISCOUNT_RATE_KIND_ENUM.MIXED:
46
+ return 'Mixed';
47
+ default:
48
+ return '—';
49
+ }
50
+ };
51
+ const makeRow = (source, shareBasis) => {
52
+ const amount = round2(toDecimal(source.discount_amount));
53
+ const levelLabel = LEVEL_LABELS[source.level] ?? source.level;
54
+ const kindLabel = rateKindLabel(source.rate_kind);
55
+ // `shareBasis` is CENTS; the row amount above is decimals. Compute the share
56
+ // in ONE unit so the table sums to 100%.
57
+ const sharePercent = shareBasis > 0 ? round2((source.discount_amount / shareBasis) * 100) : 0;
58
+ return {
59
+ source_key: source.source_key,
60
+ source_name: source.source_name,
61
+ source_class: source.source_class,
62
+ class_label: CLASS_LABELS[source.source_class] ?? source.source_class,
63
+ kind: source.kind,
64
+ level: source.level,
65
+ level_label: levelLabel,
66
+ 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),
69
+ order_count: source.order_count,
70
+ discount_amount: amount,
71
+ discount_amount_label: amount.toFixed(2),
72
+ share_percent: sharePercent,
73
+ share_label: `${(Math.round(sharePercent * 10) / 10).toFixed(1)}%`,
74
+ free_item_count: source.free_item_count,
75
+ free_item_value: round2(toDecimal(source.free_item_value)),
76
+ covered_amount: round2(toDecimal(source.covered_amount)),
77
+ complimentary_full: source.complimentary_full,
78
+ };
79
+ };
80
+ /**
81
+ * Formats one or more tenants' source records into the page model.
82
+ *
83
+ * `share_basis` (DECIMALS) lets the page use the SAME denominator as the Hero /
84
+ * summary — normally `summary.total_discount` for the already-filtered page.
85
+ * The effective denominator is `max(summary, source total)`: a source total
86
+ * above the summary is a data-consistency warning, not a >100% share.
87
+ *
88
+ * Returns `null` on unformattable input (never throws).
89
+ */
90
+ export function getFormattedTenantDiscountSources(reports, options) {
91
+ if (!Array.isArray(reports) || reports.some((report) => report == null))
92
+ return null;
93
+ const rawSources = reports.flatMap((report) => report.sources ?? []);
94
+ const discountRows = rawSources.filter((source) => source.source_class !== MATERIALIZED_DISCOUNT_SOURCE_CLASS_ENUM.COMPLIMENTARY);
95
+ const complimentaryRows = rawSources.filter((source) => source.source_class === MATERIALIZED_DISCOUNT_SOURCE_CLASS_ENUM.COMPLIMENTARY);
96
+ const totalCents = discountRows.reduce((sum, source) => sum + (source.discount_amount ?? 0), 0);
97
+ const summaryCents = options?.share_basis != null && Number.isFinite(options.share_basis) && options.share_basis > 0
98
+ ? Math.round(options.share_basis * 100)
99
+ : null;
100
+ // Shares use the LARGER of the report summary and the source total. A source
101
+ // total above the summary is a data-consistency warning, but it must never
102
+ // produce a >100% share; a summary above the source total keeps the
103
+ // unattributed gap visible (shares sum below 100%).
104
+ const shareBasisCents = Math.max(summaryCents ?? totalCents, totalCents);
105
+ const sources = discountRows
106
+ .map((source) => makeRow(source, shareBasisCents))
107
+ .sort((a, b) => b.discount_amount - a.discount_amount || a.source_name.localeCompare(b.source_name));
108
+ const complimentary = complimentaryRows
109
+ .map((source) => makeRow(source, 0))
110
+ .sort((a, b) => b.covered_amount - a.covered_amount || a.source_name.localeCompare(b.source_name));
111
+ // An order is counted once per source. Summing source order counts would
112
+ // double-count an order with two different discounts, so the page does NOT
113
+ // present this as a distinct order total; it is kept for display context.
114
+ const orderCount = discountRows.reduce((sum, source) => sum + (source.order_count ?? 0), 0);
115
+ const complimentaryFullCount = complimentaryRows
116
+ .filter((source) => source.complimentary_full === true)
117
+ .reduce((sum, source) => sum + source.order_count, 0);
118
+ const complimentaryPartialCount = complimentaryRows
119
+ .filter((source) => source.complimentary_full === false)
120
+ .reduce((sum, source) => sum + source.order_count, 0);
121
+ const complimentaryUnknownCount = complimentaryRows
122
+ .filter((source) => source.complimentary_full == null)
123
+ .reduce((sum, source) => sum + source.order_count, 0);
124
+ return {
125
+ tenant_ids: [...new Set(reports.map((report) => report.tenant_id))],
126
+ sources,
127
+ complimentary,
128
+ totals: {
129
+ discount_amount: round2(toDecimal(totalCents)),
130
+ source_count: discountRows.length,
131
+ order_count: orderCount,
132
+ complimentary_covered_amount: round2(toDecimal(complimentaryRows.reduce((sum, source) => sum + (source.covered_amount ?? 0), 0))),
133
+ complimentary_full_count: complimentaryFullCount,
134
+ complimentary_partial_count: complimentaryPartialCount,
135
+ complimentary_unknown_count: complimentaryUnknownCount,
136
+ },
137
+ top_source: sources.length > 0 ? sources[0] : null,
138
+ has_data: discountRows.length > 0 || complimentaryRows.length > 0,
139
+ };
140
+ }
@@ -29,6 +29,7 @@ export * from './marketing_fingerprints';
29
29
  export * from './materialized_credit_bills';
30
30
  export * from './materialized_tenant_discount_entries';
31
31
  export * from './materialized_tenant_discount_reports';
32
+ export * from './materialized_tenant_discount_sources';
32
33
  export * from './materialized_tenant_cash_entries';
33
34
  export * from './materialized_tenant_delivery_entries';
34
35
  export * from './materialized_tenant_delivery_reports';
@@ -28,7 +28,14 @@ const DiscountEntrySchema = new Schema({
28
28
  entry_key: { type: String, required: true },
29
29
  order_id: { type: String, required: true },
30
30
  order_number: { type: Number, default: null },
31
+ // The ORDER ITEM's _id (part of entry_key).
31
32
  item_id: { type: String, default: null },
33
+ // The CATALOG item id — the id a catalog-auto discount writes. Kept
34
+ // separate so a 24-hex catalog id can never be mistaken for a collection
35
+ // discount id after the fact.
36
+ catalog_item_id: { type: String, default: null },
37
+ // True for the item's own catalog/special/half-half auto discount.
38
+ catalog_auto: { type: Boolean, default: null },
32
39
  item_name: { type: String, default: null },
33
40
  payment_id: { type: String, default: null },
34
41
  // Raw slot value (PERCENT for percentage rows) — NEVER money.
@@ -41,6 +48,11 @@ const DiscountEntrySchema = new Schema({
41
48
  name: { type: String, default: null },
42
49
  reference_number: { type: String, default: null },
43
50
  reason: { type: String, default: null },
51
+ // COMPLIMENTARY rows: full vs partial + the amount the tender covered.
52
+ // Null/absent on rows written before this metadata existed.
53
+ complimentary_full: { type: Boolean, default: null },
54
+ covered_amount: { type: Number, default: null },
55
+ order_amount: { type: Number, default: null },
44
56
  staff_id: { type: String, default: null },
45
57
  staff_name: { type: String, default: null },
46
58
  order_taker_id: { type: String, default: null },