@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
@@ -197,8 +197,9 @@ export const ALL_MATERIALIZED_DISCOUNT_SUB_KINDS = Object.values(MATERIALIZED_DI
197
197
  * `materialized_tenant_discount_entries`.
198
198
  *
199
199
  * - `DISCOUNT` — a slot on the order or on one item.
200
- * - `FREE_ITEM` — a 100 % item row (also present as a `DISCOUNT` row; the
201
- * drill-down decides which view lists it).
200
+ * - `FREE_ITEM` — a 100 % item row. It is a SINGLE row of this kind (not
201
+ * duplicated as a DISCOUNT row: `entry_key` is the row's
202
+ * identity, so a duplicate would collide in a period merge).
202
203
  * - `COMPLIMENTARY` — a `COMPLIMENTARY` payment (no discount slot required).
203
204
  */
204
205
  export var MATERIALIZED_DISCOUNT_ENTRY_KIND_ENUM;
@@ -229,6 +230,86 @@ export const MATERIALIZED_DISCOUNT_SOURCE_LIMIT = 12;
229
230
  export const MATERIALIZED_DISCOUNT_SPECIAL_DISCOUNT_ID = 'SPECIAL_DISCOUNT';
230
231
  export const MATERIALIZED_DISCOUNT_MANUAL_PREFIX = 'MANUAL_';
231
232
  export const MATERIALIZED_DISCOUNT_PRICE_OVERRIDE_PREFIX = 'MANUAL_SINGLE_';
233
+ /**
234
+ * SOURCE CLASS of a discount row — the grouping the "By discount" view uses.
235
+ *
236
+ * This is a REPORTING taxonomy, not a new write-path discriminator: every
237
+ * value is derived from the row (slot + id shape + reason + item id), so it
238
+ * can be rebuilt from historical entry documents at any time.
239
+ *
240
+ * - `COLLECTION` — a `discounts` collection document (order- or item-level).
241
+ * - `MANUAL` — a quick/custom amount at the order or item level.
242
+ * - `PAYMENT_TYPE` — a discount configured on a payment type. It looks like a
243
+ * `MANUAL_*` row, but its `special_discount_reason` is
244
+ * `Discount applied for <payment type>`; grouping it as a
245
+ * manual discount would hide which tender drove it.
246
+ * - `PRICE_OVERRIDE` — an item price edit (`MANUAL_SINGLE_*`).
247
+ * - `CATALOG_AUTO` — the item's own catalog `discount_amount`, written with
248
+ * the ITEM id as `special_discount_id` (or the
249
+ * `SPECIAL_DISCOUNT` sentinel). This is why the source
250
+ * classifier compares the id to the row's `item_id`: a
251
+ * catalog id is usually a 24-hex ObjectId and would
252
+ * otherwise be mistaken for a collection discount.
253
+ * - `LOYALTY` — offers, gift cards and wallet cashback (loyalty slot).
254
+ * - `VOUCHER` — voucher / voucher-linked offer (voucher slot).
255
+ * - `COMPLIMENTARY` — a `COMPLIMENTARY` tender, fully or partially covering
256
+ * the order. NOT a discount: never added to the discount
257
+ * total or share.
258
+ * - `UNATTRIBUTED` — money the row's slots cannot explain.
259
+ */
260
+ export var MATERIALIZED_DISCOUNT_SOURCE_CLASS_ENUM;
261
+ (function (MATERIALIZED_DISCOUNT_SOURCE_CLASS_ENUM) {
262
+ MATERIALIZED_DISCOUNT_SOURCE_CLASS_ENUM["COLLECTION"] = "COLLECTION";
263
+ MATERIALIZED_DISCOUNT_SOURCE_CLASS_ENUM["MANUAL"] = "MANUAL";
264
+ MATERIALIZED_DISCOUNT_SOURCE_CLASS_ENUM["PAYMENT_TYPE"] = "PAYMENT_TYPE";
265
+ MATERIALIZED_DISCOUNT_SOURCE_CLASS_ENUM["PRICE_OVERRIDE"] = "PRICE_OVERRIDE";
266
+ MATERIALIZED_DISCOUNT_SOURCE_CLASS_ENUM["CATALOG_AUTO"] = "CATALOG_AUTO";
267
+ MATERIALIZED_DISCOUNT_SOURCE_CLASS_ENUM["LOYALTY"] = "LOYALTY";
268
+ MATERIALIZED_DISCOUNT_SOURCE_CLASS_ENUM["VOUCHER"] = "VOUCHER";
269
+ MATERIALIZED_DISCOUNT_SOURCE_CLASS_ENUM["COMPLIMENTARY"] = "COMPLIMENTARY";
270
+ MATERIALIZED_DISCOUNT_SOURCE_CLASS_ENUM["UNATTRIBUTED"] = "UNATTRIBUTED";
271
+ })(MATERIALIZED_DISCOUNT_SOURCE_CLASS_ENUM || (MATERIALIZED_DISCOUNT_SOURCE_CLASS_ENUM = {}));
272
+ export const ALL_MATERIALIZED_DISCOUNT_SOURCE_CLASSES = Object.values(MATERIALIZED_DISCOUNT_SOURCE_CLASS_ENUM);
273
+ /**
274
+ * Rate shape of a source row, for the "Avg rate" column:
275
+ * `PERCENTAGE` rows show their average %, `FIXED` rows show "—" (a fixed
276
+ * amount has no rate), and `MIXED` rows show "mixed".
277
+ */
278
+ export var MATERIALIZED_DISCOUNT_RATE_KIND_ENUM;
279
+ (function (MATERIALIZED_DISCOUNT_RATE_KIND_ENUM) {
280
+ MATERIALIZED_DISCOUNT_RATE_KIND_ENUM["PERCENTAGE"] = "PERCENTAGE";
281
+ MATERIALIZED_DISCOUNT_RATE_KIND_ENUM["FIXED"] = "FIXED";
282
+ MATERIALIZED_DISCOUNT_RATE_KIND_ENUM["MIXED"] = "MIXED";
283
+ })(MATERIALIZED_DISCOUNT_RATE_KIND_ENUM || (MATERIALIZED_DISCOUNT_RATE_KIND_ENUM = {}));
284
+ export const ALL_MATERIALIZED_DISCOUNT_RATE_KINDS = Object.values(MATERIALIZED_DISCOUNT_RATE_KIND_ENUM);
285
+ /**
286
+ * Source keys that are ONE row regardless of the individual amounts/rates.
287
+ * Manual order discounts are deliberately ONE source (`manual:order`): the id
288
+ * they carry is generated from the amount (`MANUAL_50%`, `MANUAL_Rs 500`), so
289
+ * keying on it would create a new "source" for every amount. The drill-down
290
+ * keeps every individual row/rate.
291
+ */
292
+ export const MATERIALIZED_DISCOUNT_SOURCE_KEY = {
293
+ MANUAL_ORDER: 'manual:order',
294
+ MANUAL_ITEM: 'manual:item',
295
+ PRICE_OVERRIDE_ITEM: 'price_override:item',
296
+ CATALOG_AUTO: 'catalog:auto',
297
+ WALLET_CASHBACK: 'loyalty:wallet_cashback',
298
+ COMPLIMENTARY_FULL: 'complimentary:full',
299
+ COMPLIMENTARY_PARTIAL: 'complimentary:partial',
300
+ // Defensive invalid-data bucket only: the current close always writes
301
+ // `complimentary_full`. This is NOT a legacy compatibility path.
302
+ COMPLIMENTARY_UNKNOWN: 'complimentary:unknown',
303
+ UNATTRIBUTED: 'unattributed',
304
+ };
305
+ /** Prefixes of the parameterised source keys (`discount:<id>` etc.). */
306
+ export const MATERIALIZED_DISCOUNT_SOURCE_KEY_PREFIX = {
307
+ DISCOUNT: 'discount:',
308
+ LOYALTY_OFFER: 'loyalty:offer:',
309
+ LOYALTY_GIFT_CARD: 'loyalty:gift_card:',
310
+ VOUCHER: 'voucher:',
311
+ PAYMENT_TYPE: 'payment_type:',
312
+ };
232
313
  /**
233
314
  * Payment-type label used by the frontend report formatter for the derived
234
315
  * credit-settlement line in a collection day's payments breakdown (a
@@ -4,6 +4,8 @@ export * from './materialized-discount-accumulator-helpers';
4
4
  export * from './materialized-discount-classification-helpers';
5
5
  export * from './materialized-discount-close-day-helpers';
6
6
  export * from './materialized-discount-compile-helpers';
7
+ export * from './materialized-discount-details-helpers';
8
+ export * from './materialized-discount-source-helpers';
7
9
  export * from './materialized-hourly-comparison-close-day-helpers';
8
10
  export * from './materialized-hourly-comparison-compile-helpers';
9
11
  export * from './materialized-hourly-comparison-selection-helpers';
@@ -36,6 +38,7 @@ export * from './tenant-payments-comparison-formatter';
36
38
  export * from './tenant-sales-comparison-formatter';
37
39
  export * from './tenant-sales-overview-close-day-helpers';
38
40
  export * from './tenant-discount-formatter';
41
+ export * from './tenant-discount-source-formatter';
39
42
  export * from './tenant-cash-in-out-formatter';
40
43
  export * from './tenant-delivery-formatter';
41
44
  export * from './tenant-prep-time-formatter';
@@ -1,7 +1,40 @@
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
+ import { ORDER_ITEM_TYPE_ENUM } from '../../constants/enums/order';
2
3
  import { PAYMENT_TYPE_ENUM } from '../../constants/enums/payments';
3
4
  import { createEmptyDiscountOrderCounters, createEmptyDiscountSlotCounter, MATERIALIZED_DISCOUNT_SLOTS, mergeDiscountSlotCounter, readDiscountSlot, resolveRowMoney, } from './materialized-discount-classification-helpers';
4
5
  const isComplimentaryPayment = (payment) => payment?.payment_type === PAYMENT_TYPE_ENUM.COMPLIMENTARY;
6
+ /**
7
+ * Classifies an order's COMPLIMENTARY tenders. Returns null when there is none.
8
+ *
9
+ * A PARTIAL comp has two real shapes in the POS:
10
+ * 1. one COMPLIMENTARY payment with `amount_paid < amount_due` (the "pay
11
+ * partially" flow, no other tender); or
12
+ * 2. a COMPLIMENTARY payment beside another settled tender.
13
+ * Both are partial. "All payments are COMPLIMENTARY" alone would call shape 1
14
+ * full, so the amount is part of the test too.
15
+ *
16
+ * Used by the current close for every comp row. Pre-release has no legacy
17
+ * comp-row inference path.
18
+ */
19
+ export function classifyComplimentaryOrder(order) {
20
+ const payments = order?.payments ?? [];
21
+ const compPayments = payments.filter(isComplimentaryPayment);
22
+ if (compPayments.length === 0)
23
+ return null;
24
+ const orderAmount = nonNegative(Number(order?.grand_total ?? order?.amount_earned ?? 0));
25
+ const coveredAmount = compPayments.reduce((sum, payment) => sum + nonNegative(Number(payment.amount_paid ?? 0)), 0);
26
+ const hasOtherTender = payments.some((payment) => !isComplimentaryPayment(payment) && nonNegative(Number(payment.amount_paid ?? 0)) > 0);
27
+ return {
28
+ full: !hasOtherTender && (orderAmount <= 0 || coveredAmount >= orderAmount - 0.005),
29
+ covered_amount: coveredAmount,
30
+ order_amount: orderAmount,
31
+ payments: compPayments.map((payment) => ({
32
+ payment_id: payment._id != null ? String(payment._id) : null,
33
+ covered_amount: nonNegative(Number(payment.amount_paid ?? 0)),
34
+ note: typeof payment.note === 'string' && payment.note.length > 0 ? payment.note : null,
35
+ })),
36
+ };
37
+ }
5
38
  const nonNegative = (value) => (Number.isFinite(value) && value > 0 ? value : 0);
6
39
  /** The line label of a punch hour (null when the hour is unknown). */
7
40
  export const toDiscountHourLabel = (localDate, hour) => hour == null || hour < 0 || hour > 23 ? null : `${localDate} ${String(hour).padStart(2, '0')}`;
@@ -12,6 +45,8 @@ function entryBase(order, context, kind) {
12
45
  order_id: String(order._id),
13
46
  order_number: order.order_number ?? null,
14
47
  item_id: null,
48
+ catalog_item_id: null,
49
+ catalog_auto: null,
15
50
  item_name: null,
16
51
  payment_id: null,
17
52
  rate: null,
@@ -21,6 +56,9 @@ function entryBase(order, context, kind) {
21
56
  name: null,
22
57
  reference_number: null,
23
58
  reason: null,
59
+ complimentary_full: null,
60
+ covered_amount: null,
61
+ order_amount: null,
24
62
  staff_id: order.staff_details?.staff_id ?? null,
25
63
  staff_name: order.staff_details?.staff_name ?? null,
26
64
  order_taker_id: order.order_taker_details?.staff_id ?? null,
@@ -93,7 +131,7 @@ function orderSubKindCounter(counters, slot, subKind) {
93
131
  return subKind === MATERIALIZED_DISCOUNT_SUB_KIND_ENUM.OFFER ? counters.voucher_offer : counters.voucher_other;
94
132
  }
95
133
  /** Adds one ITEM-LEVEL slot reading into its counters + rows. */
96
- function accumulateItemSlot(counters, entries, order, context, itemId, itemName, itemValue, reading, resolved, itemTotal) {
134
+ function accumulateItemSlot(counters, entries, order, context, itemId, catalogItemId, itemName, itemValue, reading, resolved, itemTotal, catalogAuto) {
97
135
  const raw = nonNegative(reading.rate);
98
136
  const money = nonNegative(resolved);
99
137
  const isFree = reading.is_percentage && reading.rate >= 100;
@@ -187,6 +225,8 @@ function accumulateItemSlot(counters, entries, order, context, itemId, itemName,
187
225
  rate: raw,
188
226
  is_percentage: reading.is_percentage,
189
227
  item_id: itemId,
228
+ catalog_item_id: catalogItemId,
229
+ catalog_auto: catalogAuto ? true : null,
190
230
  item_name: itemName,
191
231
  item_value: isFree ? nonNegative(itemValue) : null,
192
232
  discount_id: reading.discount_id,
@@ -207,6 +247,11 @@ export function accumulateOrderDiscounts(order, context) {
207
247
  const orderDetails = order.order_discount_details ?? null;
208
248
  const applied = nonNegative(Number(order.total_discount_applied ?? 0));
209
249
  const storedOrderTotal = nonNegative(orderDetails?.total_discount != null ? Number(orderDetails.total_discount) : 0);
250
+ // Gift cards and offers both write an ObjectId into the loyalty slot. The
251
+ // order's wallet claims are the authoritative discriminator.
252
+ const giftCardIds = new Set((order.wallet_redemptions?.gift_cards ?? [])
253
+ .map((redemption) => String(redemption?.gift_card_id ?? ''))
254
+ .filter((id) => id.length > 0));
210
255
  // ---- order level -------------------------------------------------------
211
256
  const orderMoney = resolveRowMoney(orderDetails, storedOrderTotal);
212
257
  // Slot PRESENCE = a positive rate OR an id. Zero-rate slots that carry an id
@@ -219,7 +264,7 @@ export function accumulateOrderDiscounts(order, context) {
219
264
  // inflate every occurrence counter while adding nothing to the money; it would
220
265
  // also break the "resolved slots explain the row total" invariant. They are
221
266
  // therefore excluded here (the row itself is not a discount row).
222
- const orderReadings = MATERIALIZED_DISCOUNT_SLOTS.map((slot) => readDiscountSlot(orderDetails, slot))
267
+ const orderReadings = MATERIALIZED_DISCOUNT_SLOTS.map((slot) => readDiscountSlot(orderDetails, slot, { gift_card_ids: giftCardIds }))
223
268
  .filter((reading) => reading != null && reading.rate >= 0)
224
269
  .map((reading) => ({ reading, money: nonNegative(orderMoney.perSlot.get(reading.slot) ?? 0) }))
225
270
  .filter((entry) => entry.money > 0);
@@ -230,8 +275,21 @@ export function accumulateOrderDiscounts(order, context) {
230
275
  counters.order_level_amount += storedOrderTotal;
231
276
  // Money the slots cannot explain (no slots at all, several active slots, or
232
277
  // a slot value the row total contradicts) is a tripwire: counted, never
233
- // silently dropped.
234
- counters.unattributed_amount += nonNegative(orderMoney.unallocated);
278
+ // silently dropped. It also gets a ROW so the source projection can
279
+ // attribute it to "Other / unattributed" instead of losing it between the
280
+ // entry rows and the headline.
281
+ const unallocated = nonNegative(orderMoney.unallocated);
282
+ counters.unattributed_amount += unallocated;
283
+ if (unallocated > 0) {
284
+ entries.push({
285
+ ...entryBase(order, context, MATERIALIZED_DISCOUNT_ENTRY_KIND_ENUM.DISCOUNT),
286
+ slot: null,
287
+ sub_kind: MATERIALIZED_DISCOUNT_SUB_KIND_ENUM.UNATTRIBUTED,
288
+ level: MATERIALIZED_DISCOUNT_LEVEL_ENUM.ORDER,
289
+ entry_key: 'order:unattributed',
290
+ amount: unallocated,
291
+ });
292
+ }
235
293
  }
236
294
  // ---- item level --------------------------------------------------------
237
295
  let itemLevelTotal = 0;
@@ -252,57 +310,79 @@ export function accumulateOrderDiscounts(order, context) {
252
310
  const netValue = nonNegative(Number(item._net_amount ?? 0));
253
311
  const itemValue = netValue > 0 ? netValue : nonNegative(Number(item._gross_amount ?? item.price ?? 0));
254
312
  const itemMoney = resolveRowMoney(itemDetails, itemTotal);
255
- const itemReadings = MATERIALIZED_DISCOUNT_SLOTS.map((slot) => readDiscountSlot(itemDetails, slot))
313
+ // The catalog-auto path writes the ITEM id as `special_discount_id`; a
314
+ // catalog id is usually a 24-hex ObjectId, indistinguishable by shape
315
+ // from a collection discount. Both ids are passed so the classifier can
316
+ // tell them apart (the order-item id also covers the re-order path).
317
+ const itemSlotContext = {
318
+ order_item_id: String(item._id),
319
+ catalog_item_id: item.item_id != null ? String(item.item_id) : null,
320
+ gift_card_ids: giftCardIds,
321
+ };
322
+ const itemReadings = MATERIALIZED_DISCOUNT_SLOTS.map((slot) => readDiscountSlot(itemDetails, slot, itemSlotContext))
256
323
  .filter((reading) => reading != null && reading.rate >= 0)
257
324
  .map((reading) => ({ reading, money: nonNegative(itemMoney.perSlot.get(reading.slot) ?? 0) }))
258
325
  .filter((entry) => entry.money > 0);
259
- if (itemReadings.length === 0) {
260
- // Item money with no usable slot: keep it in the item total (so the
261
- // headline reconciles) and record one unattributed row for the
262
- // drill-down to show.
326
+ for (const { reading: rawReading, money } of itemReadings) {
327
+ // Specials / half-half write their SETUP doc id as the discount id,
328
+ // which is neither the order-item id nor the catalog id. Their auto
329
+ // discount is still a catalog-owned discount: the item type + the
330
+ // constant 'Special Discount' name prove it.
331
+ const catalogAuto = rawReading.sub_kind === MATERIALIZED_DISCOUNT_SUB_KIND_ENUM.CATALOG_ITEM ||
332
+ (rawReading.slot === MATERIALIZED_DISCOUNT_SLOT_ENUM.SPECIAL &&
333
+ rawReading.name === 'Special Discount' &&
334
+ (item.item_type === ORDER_ITEM_TYPE_ENUM.SPECIAL || item.item_type === ORDER_ITEM_TYPE_ENUM.HALF_HALF));
335
+ const reading = catalogAuto && rawReading.sub_kind !== MATERIALIZED_DISCOUNT_SUB_KIND_ENUM.CATALOG_ITEM
336
+ ? { ...rawReading, sub_kind: MATERIALIZED_DISCOUNT_SUB_KIND_ENUM.CATALOG_ITEM }
337
+ : rawReading;
338
+ accumulateItemSlot(counters, entries, order, context, String(item._id), item.item_id != null ? String(item.item_id) : null, item.name ?? null, itemValue, reading, money, itemTotal, catalogAuto);
339
+ }
340
+ // Multi-slot / fixed-slot leftovers, and item money with no usable slot
341
+ // at all, get ONE unattributed row. Keeping this money in a row (not only
342
+ // in the counter) is what lets the source projection reconcile to the
343
+ // headline: Σ source.discount_amount then includes it.
344
+ const itemUnallocated = nonNegative(itemMoney.unallocated);
345
+ if (itemUnallocated > 0) {
263
346
  entries.push({
264
347
  ...entryBase(order, context, MATERIALIZED_DISCOUNT_ENTRY_KIND_ENUM.DISCOUNT),
265
348
  slot: null,
266
349
  sub_kind: MATERIALIZED_DISCOUNT_SUB_KIND_ENUM.UNATTRIBUTED,
267
350
  level: MATERIALIZED_DISCOUNT_LEVEL_ENUM.ITEM,
268
351
  entry_key: `item:${String(item._id)}:unattributed`,
269
- amount: itemTotal,
352
+ amount: itemUnallocated,
270
353
  item_id: String(item._id),
354
+ catalog_item_id: item.item_id != null ? String(item.item_id) : null,
271
355
  item_name: item.name ?? null,
272
356
  });
273
- continue;
274
357
  }
275
- for (const { reading, money } of itemReadings) {
276
- accumulateItemSlot(counters, entries, order, context, String(item._id), item.name ?? null, itemValue, reading, money, itemTotal);
277
- }
278
- // Multi-slot / fixed-slot leftovers stay visible on the order-level
279
- // tripwire so anchors E/H keep holding.
280
- counters.unattributed_amount += nonNegative(itemMoney.unallocated);
358
+ counters.unattributed_amount += itemUnallocated;
281
359
  }
282
360
  }
283
361
  counters.item_level_amount += itemLevelTotal;
284
362
  // ---- headline + comp ---------------------------------------------------
285
363
  counters.amount += applied;
286
- let compAmount = 0;
287
- for (const payment of order.payments ?? []) {
288
- if (!isComplimentaryPayment(payment))
289
- continue;
290
- counters.complimentary.payment_count += 1;
291
- if (payment.note)
292
- counters.complimentary.note_count += 1;
293
- entries.push({
294
- ...entryBase(order, context, MATERIALIZED_DISCOUNT_ENTRY_KIND_ENUM.COMPLIMENTARY),
295
- slot: null,
296
- sub_kind: MATERIALIZED_DISCOUNT_SUB_KIND_ENUM.UNATTRIBUTED,
297
- level: MATERIALIZED_DISCOUNT_LEVEL_ENUM.PAYMENT,
298
- entry_key: `payment:${String(payment._id)}`,
299
- amount: 0,
300
- payment_id: payment._id != null ? String(payment._id) : null,
301
- });
364
+ const comp = classifyComplimentaryOrder(order);
365
+ if (comp != null) {
366
+ counters.complimentary.payment_count += comp.payments.length;
367
+ for (const payment of comp.payments) {
368
+ if (payment.note != null)
369
+ counters.complimentary.note_count += 1;
370
+ entries.push({
371
+ ...entryBase(order, context, MATERIALIZED_DISCOUNT_ENTRY_KIND_ENUM.COMPLIMENTARY),
372
+ slot: null,
373
+ sub_kind: MATERIALIZED_DISCOUNT_SUB_KIND_ENUM.UNATTRIBUTED,
374
+ level: MATERIALIZED_DISCOUNT_LEVEL_ENUM.PAYMENT,
375
+ entry_key: `payment:${String(payment.payment_id)}`,
376
+ amount: 0,
377
+ payment_id: payment.payment_id,
378
+ complimentary_full: comp.full,
379
+ covered_amount: payment.covered_amount,
380
+ order_amount: comp.order_amount,
381
+ });
382
+ }
302
383
  }
303
384
  if (counters.complimentary.payment_count > 0) {
304
- compAmount = nonNegative(Number(order.amount_earned ?? 0));
305
- counters.complimentary.amount += compAmount;
385
+ counters.complimentary.amount += nonNegative(Number(order.amount_earned ?? 0));
306
386
  }
307
387
  // ONE count per order with any discount or comp payment — incremented exactly
308
388
  // once, after every source has been folded (a double increment here would
@@ -1,5 +1,5 @@
1
- import { WALLET_CASHBACK_LOYALTY_DISCOUNT_ID } from '../../constants/COMMON';
2
- import { MATERIALIZED_DISCOUNT_MANUAL_PREFIX, MATERIALIZED_DISCOUNT_PRICE_OVERRIDE_PREFIX, MATERIALIZED_DISCOUNT_SLOT_ENUM, MATERIALIZED_DISCOUNT_SUB_KIND_ENUM, } from '../../constants/MATERIALIZED_REPORTS';
1
+ import { WALLET_CASHBACK_LOYALTY_DISCOUNT_ID, WALLET_CASHBACK_LOYALTY_REFERENCE } from '../../constants/COMMON';
2
+ import { MATERIALIZED_DISCOUNT_MANUAL_PREFIX, MATERIALIZED_DISCOUNT_PRICE_OVERRIDE_PREFIX, MATERIALIZED_DISCOUNT_SLOT_ENUM, MATERIALIZED_DISCOUNT_SPECIAL_DISCOUNT_ID, MATERIALIZED_DISCOUNT_SUB_KIND_ENUM, } from '../../constants/MATERIALIZED_REPORTS';
3
3
  /**
4
4
  * The discounts-report CLASSIFIER (M1) — pure functions that turn one order's
5
5
  * discount slots into the counter contract of
@@ -23,8 +23,6 @@ import { MATERIALIZED_DISCOUNT_MANUAL_PREFIX, MATERIALIZED_DISCOUNT_PRICE_OVERRI
23
23
  * order.
24
24
  */
25
25
  const HEX24 = /^[0-9a-f]{24}$/i;
26
- /** `'SPECIAL_DISCOUNT'` — the catalog item-discount sentinel (pos-web). */
27
- export const MATERIALIZED_DISCOUNT_CATALOG_ITEM_ID = 'SPECIAL_DISCOUNT';
28
26
  export const MATERIALIZED_DISCOUNT_SLOTS = [
29
27
  MATERIALIZED_DISCOUNT_SLOT_ENUM.SPECIAL,
30
28
  MATERIALIZED_DISCOUNT_SLOT_ENUM.LOYALTY,
@@ -33,7 +31,7 @@ export const MATERIALIZED_DISCOUNT_SLOTS = [
33
31
  /** Field-name prefix of a slot in `IDiscountDetails` (`special` → `special_discount`). */
34
32
  const slotFieldKey = (slot) => slot.toLowerCase();
35
33
  /** Reads ONE slot of an `IDiscountDetails` — null when the slot is empty. */
36
- export function readDiscountSlot(details, slot) {
34
+ export function readDiscountSlot(details, slot, context) {
37
35
  if (details == null)
38
36
  return null;
39
37
  const key = slotFieldKey(slot);
@@ -45,22 +43,38 @@ export function readDiscountSlot(details, slot) {
45
43
  // with only `total_discount`) — they are read but contribute 0.
46
44
  if (rate === 0 && discount_id == null)
47
45
  return null;
46
+ const reference_number = details[`${key}_reference_number`] ?? null;
47
+ let sub_kind = classifyDiscountSubKind(slot, discount_id, context);
48
+ // A loyalty OFFER never writes a reference number; the gift-card path writes
49
+ // the card code. Use that as a second discriminator when the wallet claims
50
+ // are not available (older orders, re-imported rows).
51
+ if (slot === MATERIALIZED_DISCOUNT_SLOT_ENUM.LOYALTY &&
52
+ sub_kind === MATERIALIZED_DISCOUNT_SUB_KIND_ENUM.OFFER &&
53
+ reference_number != null &&
54
+ reference_number !== WALLET_CASHBACK_LOYALTY_REFERENCE) {
55
+ sub_kind = MATERIALIZED_DISCOUNT_SUB_KIND_ENUM.GIFT_CARD;
56
+ }
48
57
  return {
49
58
  slot,
50
- sub_kind: classifyDiscountSubKind(slot, discount_id),
59
+ sub_kind,
51
60
  rate: Number.isFinite(rate) ? rate : 0,
52
61
  is_percentage: details[`is_${key}_discount_percentage`] === true,
53
62
  discount_id,
54
63
  name: details[`${key}_discount_name`] ?? null,
55
- reference_number: details[`${key}_reference_number`] ?? null,
64
+ reference_number,
56
65
  reason: details[`${key}_discount_reason`] ?? null,
57
66
  };
58
67
  }
59
68
  /**
60
69
  * Classifies a slot's sub-kind from its id shape (and, for the special slot,
61
70
  * the id's namespace).
71
+ *
72
+ * `context` lets an item-level caller distinguish a catalog-auto discount from
73
+ * a collection discount: the catalog path writes the item's own id, which is
74
+ * usually also a 24-hex ObjectId. Callers that do not know the item ids keep
75
+ * the old shape-only behaviour.
62
76
  */
63
- export function classifyDiscountSubKind(slot, discountId) {
77
+ export function classifyDiscountSubKind(slot, discountId, context) {
64
78
  if (discountId == null)
65
79
  return MATERIALIZED_DISCOUNT_SUB_KIND_ENUM.UNATTRIBUTED;
66
80
  if (slot === MATERIALIZED_DISCOUNT_SLOT_ENUM.VOUCHER) {
@@ -72,14 +86,20 @@ export function classifyDiscountSubKind(slot, discountId) {
72
86
  if (discountId === WALLET_CASHBACK_LOYALTY_DISCOUNT_ID) {
73
87
  return MATERIALIZED_DISCOUNT_SUB_KIND_ENUM.WALLET_CASHBACK;
74
88
  }
75
- // Offers and gift cards both use ObjectIds; the reference number is what
76
- // tells them apart (`buildGiftCardDiscountUpdate` writes the card code).
89
+ // Offers and gift cards both use ObjectIds. The wallet's gift-card claims
90
+ // are the authoritative discriminator when the caller has the order; a
91
+ // reference number (the card code) is the next-best signal.
92
+ const giftCardIds = context?.gift_card_ids;
93
+ if (giftCardIds != null &&
94
+ ('has' in giftCardIds ? giftCardIds.has(discountId) : giftCardIds.includes(discountId))) {
95
+ return MATERIALIZED_DISCOUNT_SUB_KIND_ENUM.GIFT_CARD;
96
+ }
77
97
  return HEX24.test(discountId)
78
98
  ? MATERIALIZED_DISCOUNT_SUB_KIND_ENUM.OFFER
79
99
  : MATERIALIZED_DISCOUNT_SUB_KIND_ENUM.GIFT_CARD;
80
100
  }
81
101
  // SPECIAL slot — the namespace prefix is the discriminator.
82
- if (discountId === MATERIALIZED_DISCOUNT_CATALOG_ITEM_ID) {
102
+ if (discountId === MATERIALIZED_DISCOUNT_SPECIAL_DISCOUNT_ID) {
83
103
  return MATERIALIZED_DISCOUNT_SUB_KIND_ENUM.CATALOG_ITEM;
84
104
  }
85
105
  if (discountId.startsWith(MATERIALIZED_DISCOUNT_PRICE_OVERRIDE_PREFIX)) {
@@ -88,8 +108,15 @@ export function classifyDiscountSubKind(slot, discountId) {
88
108
  if (discountId.startsWith(MATERIALIZED_DISCOUNT_MANUAL_PREFIX)) {
89
109
  return MATERIALIZED_DISCOUNT_SUB_KIND_ENUM.MANUAL;
90
110
  }
91
- if (HEX24.test(discountId))
111
+ if (HEX24.test(discountId)) {
112
+ // A catalog-auto discount writes the item's own id. Both ids are checked:
113
+ // the catalog id is the normal path; the ORDER-item id is the re-order
114
+ // copy path (`order-history.ts`), where the spread preserves the item _id.
115
+ if (context != null && (discountId === context.catalog_item_id || discountId === context.order_item_id)) {
116
+ return MATERIALIZED_DISCOUNT_SUB_KIND_ENUM.CATALOG_ITEM;
117
+ }
92
118
  return MATERIALIZED_DISCOUNT_SUB_KIND_ENUM.COLLECTION;
119
+ }
93
120
  return MATERIALIZED_DISCOUNT_SUB_KIND_ENUM.CATALOG_ITEM;
94
121
  }
95
122
  export function resolveRowMoney(details, rowTotal) {
@@ -0,0 +1,28 @@
1
+ import { MATERIALIZED_DISCOUNT_ENTRY_KIND_ENUM } from '../../constants/MATERIALIZED_REPORTS';
2
+ export function getDiscountDetailsLoadedTotals(rows, view) {
3
+ const list = Array.isArray(rows) ? rows : [];
4
+ let discountCents = 0;
5
+ let compCents = 0;
6
+ let compCount = 0;
7
+ for (const row of list) {
8
+ if (row.kind === MATERIALIZED_DISCOUNT_ENTRY_KIND_ENUM.COMPLIMENTARY) {
9
+ compCount += 1;
10
+ compCents += Number.isFinite(row.covered_amount) ? Math.max(0, row.covered_amount ?? 0) : 0;
11
+ }
12
+ else {
13
+ discountCents += Number.isFinite(row.amount) ? Math.max(0, row.amount ?? 0) : 0;
14
+ }
15
+ }
16
+ const isComplimentaryView = view === MATERIALIZED_DISCOUNT_ENTRY_KIND_ENUM.COMPLIMENTARY;
17
+ return {
18
+ discount_cents: discountCents,
19
+ comp_cents: compCents,
20
+ comp_count: compCount,
21
+ row_count: list.length,
22
+ primary_cents: isComplimentaryView ? compCents : discountCents,
23
+ primary_label: isComplimentaryView ? 'covered' : 'discounts',
24
+ // Only the ALL view can contain both kinds; the kind tabs are filtered
25
+ // server-side, so they never append a cross-kind breakdown.
26
+ include_comp_breakdown: view === 'ALL' && compCount > 0,
27
+ };
28
+ }