@managesome/eposmatic-toolkit 0.4.42 → 0.4.43

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.
@@ -36,6 +36,9 @@ export * from './location-helpers';
36
36
  export * from './menu-helpers';
37
37
  export * from './minified-catalog';
38
38
  export * from './offer-apply-helpers';
39
+ export * from './offer-item-resolution';
40
+ export * from './offer-claim-sequence';
41
+ export * from './offer-reward-claim';
39
42
  export * from './offers-helpers';
40
43
  export * from './operational-roles-helpers';
41
44
  export * from './order-engine';
@@ -0,0 +1,61 @@
1
+ import { OFFER_REWARD_TYPE_ENUM } from '../../constants';
2
+ /**
3
+ * The voucher-linked claim sequence, in one place.
4
+ *
5
+ * It was copied into six apps (drawer, hook, promo banner, offers screen). One
6
+ * of those copies wrote the voucher code BEFORE resolving the reward item, which
7
+ * is how a sold-out reward left the customer with an applied code and nothing to
8
+ * claim. The order is the contract, and it lives here now.
9
+ */
10
+ /** Trim and upper-case a code; an empty or whitespace-only code becomes null. */
11
+ export function normalizeVoucherCode(voucherCode) {
12
+ const normalized = voucherCode?.trim().toUpperCase() ?? '';
13
+ return normalized.length > 0 ? normalized : null;
14
+ }
15
+ /**
16
+ * Does this reward need items already in the cart before it can be claimed?
17
+ *
18
+ * Order-level rewards (a discount, cashback, points, a gift card, a voucher)
19
+ * apply to a cart; item rewards bring their own item.
20
+ */
21
+ export function offerNeedsExistingCartItems(offer) {
22
+ return (offer.reward_type !== OFFER_REWARD_TYPE_ENUM.ITEMS && offer.reward_type !== OFFER_REWARD_TYPE_ENUM.DISCOUNT_ITEMS);
23
+ }
24
+ /**
25
+ * One ordered claim. Resolve the reward BEFORE writing the code, and roll the
26
+ * code back if the later apply fails.
27
+ *
28
+ * Effects are injected so this stays pure: the caller owns dispatch, navigation
29
+ * and snackbars.
30
+ */
31
+ export function claimVoucherLinkedOffer(steps) {
32
+ const code = normalizeVoucherCode(steps.code);
33
+ if (code == null) {
34
+ return { status: 'blank' };
35
+ }
36
+ if (steps.rewardItemIds.length > 0) {
37
+ const item = steps.resolveRewardItem();
38
+ if (item == null) {
39
+ // Nothing written: this is the whole point.
40
+ return { status: 'unavailable' };
41
+ }
42
+ if (!steps.applyVoucherCode(code)) {
43
+ return { status: 'write-failed' };
44
+ }
45
+ if (steps.rewardItemIds.length > 1) {
46
+ steps.openSelectionScreen();
47
+ }
48
+ else {
49
+ steps.openItemDrawer(item);
50
+ }
51
+ return { status: 'opened' };
52
+ }
53
+ if (!steps.applyVoucherCode(code)) {
54
+ return { status: 'write-failed' };
55
+ }
56
+ if (!steps.applyLinkedOffer()) {
57
+ steps.rollback(steps.offerId);
58
+ return { status: 'failed' };
59
+ }
60
+ return { status: 'applied' };
61
+ }
@@ -0,0 +1,47 @@
1
+ import { OFFER_REWARD_TYPE_ENUM } from '../../constants';
2
+ const defaultIsSoldOut = (item) => item?.sold_out === true;
3
+ /**
4
+ * The first reward item the customer can actually receive, or null.
5
+ *
6
+ * Missing entries and sold-out items are skipped. Without a platform or a tenant
7
+ * there is nothing to resolve against, so the answer is null - which is what
8
+ * makes "don't write the voucher code yet" work (C7).
9
+ */
10
+ export function resolveFirstAvailableRewardItem({ itemIds, mappedItems, platform, tenantId, convert, isSoldOut = defaultIsSoldOut, }) {
11
+ if (platform == null || tenantId == null)
12
+ return null;
13
+ for (let i = 0; i < itemIds.length; i++) {
14
+ const raw = mappedItems[itemIds[i]];
15
+ if (raw == null)
16
+ continue;
17
+ if (isSoldOut(raw))
18
+ continue;
19
+ const converted = convert(raw, platform, tenantId);
20
+ if (converted != null)
21
+ return converted;
22
+ }
23
+ return null;
24
+ }
25
+ /**
26
+ * How many items the reward-selection screen may offer.
27
+ *
28
+ * Rule, in one place:
29
+ * - voucher-linked claim -> the reward's `num_of_items` (one claim was bought);
30
+ * - otherwise -> `stats.applicable_quantity` (every claim the cart can support);
31
+ * - never below 1 when the reward grants at least one item.
32
+ */
33
+ export function getRewardSelectionQuantity({ offer, stats, isVoucherLinked = false, }) {
34
+ const rewardNumOfItems = offer.reward_type === OFFER_REWARD_TYPE_ENUM.DISCOUNT_ITEMS
35
+ ? offer.reward_discount_items?.num_of_items
36
+ : offer.reward_type === OFFER_REWARD_TYPE_ENUM.ITEMS
37
+ ? offer.reward_items?.num_of_items
38
+ : undefined;
39
+ if (isVoucherLinked) {
40
+ return Math.max(1, rewardNumOfItems ?? 1);
41
+ }
42
+ const applicable = stats?.applicable_quantity;
43
+ if (applicable != null && Number.isFinite(applicable) && applicable > 0) {
44
+ return Math.floor(applicable);
45
+ }
46
+ return Math.max(1, rewardNumOfItems ?? 1);
47
+ }
@@ -0,0 +1,33 @@
1
+ import { OFFER_REWARD_TYPE_ENUM, PATHWAY_TO_UNLOCK_TYPE_ENUM } from '../../constants';
2
+ function getRewardExclusiveRefs(offer) {
3
+ if (offer.reward_type === OFFER_REWARD_TYPE_ENUM.DISCOUNT_ITEMS) {
4
+ return offer.reward_discount_items?.exclusive_refs ?? [];
5
+ }
6
+ if (offer.reward_type === OFFER_REWARD_TYPE_ENUM.ITEMS) {
7
+ return offer.reward_items?.exclusive_refs ?? [];
8
+ }
9
+ return [];
10
+ }
11
+ /**
12
+ * Build the claim patch for a reward item: what the item is stamped with, and
13
+ * optionally the loyalty entry it applies.
14
+ */
15
+ export function buildRewardClaim({ offer, catalogItemId, applicableQuantity, isVoucherLinked = offer.pathway_to_unlock_type === PATHWAY_TO_UNLOCK_TYPE_ENUM.VOUCHER, }) {
16
+ const quantity = Math.max(1, Math.floor(applicableQuantity));
17
+ const isGiftCard = offer.reward_type === OFFER_REWARD_TYPE_ENUM.GIFT_CARDS;
18
+ const patch = {
19
+ rewardClaim: isGiftCard ? { type: 'gift-card', giftCardId: offer._id } : { type: 'offer', offerId: offer._id },
20
+ };
21
+ // A gift-card reward always applies its own loyalty entry; an offer claim only
22
+ // does when the discount slot is free (i.e. not bought with a voucher code).
23
+ if (!isVoucherLinked || isGiftCard) {
24
+ patch.applyLoyalty = {
25
+ loyalty_id: offer._id,
26
+ name: offer.name,
27
+ refs: [...getRewardExclusiveRefs(offer), catalogItemId],
28
+ discount_details: null,
29
+ applicable_quantity: quantity,
30
+ };
31
+ }
32
+ return patch;
33
+ }
@@ -36,6 +36,9 @@ export * from './location-helpers';
36
36
  export * from './menu-helpers';
37
37
  export * from './minified-catalog';
38
38
  export * from './offer-apply-helpers';
39
+ export * from './offer-item-resolution';
40
+ export * from './offer-claim-sequence';
41
+ export * from './offer-reward-claim';
39
42
  export * from './offers-helpers';
40
43
  export * from './operational-roles-helpers';
41
44
  export * from './order-engine';
@@ -52,6 +52,9 @@ __exportStar(require("./location-helpers"), exports);
52
52
  __exportStar(require("./menu-helpers"), exports);
53
53
  __exportStar(require("./minified-catalog"), exports);
54
54
  __exportStar(require("./offer-apply-helpers"), exports);
55
+ __exportStar(require("./offer-item-resolution"), exports);
56
+ __exportStar(require("./offer-claim-sequence"), exports);
57
+ __exportStar(require("./offer-reward-claim"), exports);
55
58
  __exportStar(require("./offers-helpers"), exports);
56
59
  __exportStar(require("./operational-roles-helpers"), exports);
57
60
  __exportStar(require("./order-engine"), exports);
@@ -0,0 +1,42 @@
1
+ import { IOffer } from '../../schemas';
2
+ /**
3
+ * The voucher-linked claim sequence, in one place.
4
+ *
5
+ * It was copied into six apps (drawer, hook, promo banner, offers screen). One
6
+ * of those copies wrote the voucher code BEFORE resolving the reward item, which
7
+ * is how a sold-out reward left the customer with an applied code and nothing to
8
+ * claim. The order is the contract, and it lives here now.
9
+ */
10
+ /** Trim and upper-case a code; an empty or whitespace-only code becomes null. */
11
+ export declare function normalizeVoucherCode(voucherCode: string | null | undefined): string | null;
12
+ /**
13
+ * Does this reward need items already in the cart before it can be claimed?
14
+ *
15
+ * Order-level rewards (a discount, cashback, points, a gift card, a voucher)
16
+ * apply to a cart; item rewards bring their own item.
17
+ */
18
+ export declare function offerNeedsExistingCartItems(offer: Pick<IOffer, 'reward_type'>): boolean;
19
+ export type TClaimVoucherLinkedOfferStatus = 'blank' | 'unavailable' | 'write-failed' | 'opened' | 'applied' | 'failed';
20
+ export interface IClaimVoucherLinkedOfferSteps<TItem> {
21
+ offerId: string;
22
+ code: string | null | undefined;
23
+ /** The reward's item ids. Empty means the reward is order-level. */
24
+ rewardItemIds: readonly string[];
25
+ resolveRewardItem: () => TItem | null | undefined;
26
+ applyVoucherCode: (code: string) => boolean;
27
+ openSelectionScreen: () => void;
28
+ openItemDrawer: (item: TItem) => void;
29
+ applyLinkedOffer: () => boolean;
30
+ rollback: (offerId: string) => void;
31
+ }
32
+ export interface IClaimVoucherLinkedOfferResult {
33
+ status: TClaimVoucherLinkedOfferStatus;
34
+ }
35
+ /**
36
+ * One ordered claim. Resolve the reward BEFORE writing the code, and roll the
37
+ * code back if the later apply fails.
38
+ *
39
+ * Effects are injected so this stays pure: the caller owns dispatch, navigation
40
+ * and snackbars.
41
+ */
42
+ export declare function claimVoucherLinkedOffer<TItem>(steps: IClaimVoucherLinkedOfferSteps<TItem>): IClaimVoucherLinkedOfferResult;
@@ -0,0 +1,66 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.normalizeVoucherCode = normalizeVoucherCode;
4
+ exports.offerNeedsExistingCartItems = offerNeedsExistingCartItems;
5
+ exports.claimVoucherLinkedOffer = claimVoucherLinkedOffer;
6
+ const constants_1 = require("../../constants");
7
+ /**
8
+ * The voucher-linked claim sequence, in one place.
9
+ *
10
+ * It was copied into six apps (drawer, hook, promo banner, offers screen). One
11
+ * of those copies wrote the voucher code BEFORE resolving the reward item, which
12
+ * is how a sold-out reward left the customer with an applied code and nothing to
13
+ * claim. The order is the contract, and it lives here now.
14
+ */
15
+ /** Trim and upper-case a code; an empty or whitespace-only code becomes null. */
16
+ function normalizeVoucherCode(voucherCode) {
17
+ const normalized = voucherCode?.trim().toUpperCase() ?? '';
18
+ return normalized.length > 0 ? normalized : null;
19
+ }
20
+ /**
21
+ * Does this reward need items already in the cart before it can be claimed?
22
+ *
23
+ * Order-level rewards (a discount, cashback, points, a gift card, a voucher)
24
+ * apply to a cart; item rewards bring their own item.
25
+ */
26
+ function offerNeedsExistingCartItems(offer) {
27
+ return (offer.reward_type !== constants_1.OFFER_REWARD_TYPE_ENUM.ITEMS && offer.reward_type !== constants_1.OFFER_REWARD_TYPE_ENUM.DISCOUNT_ITEMS);
28
+ }
29
+ /**
30
+ * One ordered claim. Resolve the reward BEFORE writing the code, and roll the
31
+ * code back if the later apply fails.
32
+ *
33
+ * Effects are injected so this stays pure: the caller owns dispatch, navigation
34
+ * and snackbars.
35
+ */
36
+ function claimVoucherLinkedOffer(steps) {
37
+ const code = normalizeVoucherCode(steps.code);
38
+ if (code == null) {
39
+ return { status: 'blank' };
40
+ }
41
+ if (steps.rewardItemIds.length > 0) {
42
+ const item = steps.resolveRewardItem();
43
+ if (item == null) {
44
+ // Nothing written: this is the whole point.
45
+ return { status: 'unavailable' };
46
+ }
47
+ if (!steps.applyVoucherCode(code)) {
48
+ return { status: 'write-failed' };
49
+ }
50
+ if (steps.rewardItemIds.length > 1) {
51
+ steps.openSelectionScreen();
52
+ }
53
+ else {
54
+ steps.openItemDrawer(item);
55
+ }
56
+ return { status: 'opened' };
57
+ }
58
+ if (!steps.applyVoucherCode(code)) {
59
+ return { status: 'write-failed' };
60
+ }
61
+ if (!steps.applyLinkedOffer()) {
62
+ steps.rollback(steps.offerId);
63
+ return { status: 'failed' };
64
+ }
65
+ return { status: 'applied' };
66
+ }
@@ -0,0 +1,51 @@
1
+ import { IOffer } from '../../schemas';
2
+ import type { IOfferWithStats } from './offers-helpers';
3
+ /**
4
+ * Single source for the questions every frontend asks before it can claim a
5
+ * voucher-linked reward. They were answered in six drawers, five hooks and one
6
+ * mobile screen; when the answer changed, five of those places did not.
7
+ *
8
+ * Everything here is pure: callers pass the catalog, the platform and the tenant
9
+ * in. Nothing reads a store, a hook or a global.
10
+ */
11
+ export interface IResolveRewardItemParams<TItem> {
12
+ /** The reward's item ids, in priority order. */
13
+ itemIds: readonly string[];
14
+ /** The app's mapped simplified catalog, keyed by item id. */
15
+ mappedItems: Record<string, TItem | undefined>;
16
+ /** Platform the order is on; resolution is impossible without it. */
17
+ platform: string | null | undefined;
18
+ /** Tenant the order belongs to. */
19
+ tenantId: string | null | undefined;
20
+ /** Convert a mapped catalog entry into the app's workable item. */
21
+ convert: (item: TItem, platform: string, tenantId: string) => unknown | null | undefined;
22
+ /** True when the entry cannot be sold. Defaults to `item.sold_out`. */
23
+ isSoldOut?: (item: TItem) => boolean;
24
+ }
25
+ /**
26
+ * The first reward item the customer can actually receive, or null.
27
+ *
28
+ * Missing entries and sold-out items are skipped. Without a platform or a tenant
29
+ * there is nothing to resolve against, so the answer is null - which is what
30
+ * makes "don't write the voucher code yet" work (C7).
31
+ */
32
+ export declare function resolveFirstAvailableRewardItem<TItem>({ itemIds, mappedItems, platform, tenantId, convert, isSoldOut, }: IResolveRewardItemParams<TItem>): unknown | null;
33
+ export interface IGetRewardSelectionQuantityParams {
34
+ offer: IOffer;
35
+ stats: IOfferWithStats['stats'] | undefined;
36
+ /**
37
+ * True when one voucher code buys ONE claim. A voucher-linked claim is still
38
+ * worth the reward's `num_of_items` items, but never the total of several
39
+ * claims - the customer only paid for one.
40
+ */
41
+ isVoucherLinked?: boolean;
42
+ }
43
+ /**
44
+ * How many items the reward-selection screen may offer.
45
+ *
46
+ * Rule, in one place:
47
+ * - voucher-linked claim -> the reward's `num_of_items` (one claim was bought);
48
+ * - otherwise -> `stats.applicable_quantity` (every claim the cart can support);
49
+ * - never below 1 when the reward grants at least one item.
50
+ */
51
+ export declare function getRewardSelectionQuantity({ offer, stats, isVoucherLinked, }: IGetRewardSelectionQuantityParams): number;
@@ -0,0 +1,51 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.resolveFirstAvailableRewardItem = resolveFirstAvailableRewardItem;
4
+ exports.getRewardSelectionQuantity = getRewardSelectionQuantity;
5
+ const constants_1 = require("../../constants");
6
+ const defaultIsSoldOut = (item) => item?.sold_out === true;
7
+ /**
8
+ * The first reward item the customer can actually receive, or null.
9
+ *
10
+ * Missing entries and sold-out items are skipped. Without a platform or a tenant
11
+ * there is nothing to resolve against, so the answer is null - which is what
12
+ * makes "don't write the voucher code yet" work (C7).
13
+ */
14
+ function resolveFirstAvailableRewardItem({ itemIds, mappedItems, platform, tenantId, convert, isSoldOut = defaultIsSoldOut, }) {
15
+ if (platform == null || tenantId == null)
16
+ return null;
17
+ for (let i = 0; i < itemIds.length; i++) {
18
+ const raw = mappedItems[itemIds[i]];
19
+ if (raw == null)
20
+ continue;
21
+ if (isSoldOut(raw))
22
+ continue;
23
+ const converted = convert(raw, platform, tenantId);
24
+ if (converted != null)
25
+ return converted;
26
+ }
27
+ return null;
28
+ }
29
+ /**
30
+ * How many items the reward-selection screen may offer.
31
+ *
32
+ * Rule, in one place:
33
+ * - voucher-linked claim -> the reward's `num_of_items` (one claim was bought);
34
+ * - otherwise -> `stats.applicable_quantity` (every claim the cart can support);
35
+ * - never below 1 when the reward grants at least one item.
36
+ */
37
+ function getRewardSelectionQuantity({ offer, stats, isVoucherLinked = false, }) {
38
+ const rewardNumOfItems = offer.reward_type === constants_1.OFFER_REWARD_TYPE_ENUM.DISCOUNT_ITEMS
39
+ ? offer.reward_discount_items?.num_of_items
40
+ : offer.reward_type === constants_1.OFFER_REWARD_TYPE_ENUM.ITEMS
41
+ ? offer.reward_items?.num_of_items
42
+ : undefined;
43
+ if (isVoucherLinked) {
44
+ return Math.max(1, rewardNumOfItems ?? 1);
45
+ }
46
+ const applicable = stats?.applicable_quantity;
47
+ if (applicable != null && Number.isFinite(applicable) && applicable > 0) {
48
+ return Math.floor(applicable);
49
+ }
50
+ return Math.max(1, rewardNumOfItems ?? 1);
51
+ }
@@ -0,0 +1,46 @@
1
+ import { IOffer } from '../../schemas';
2
+ /**
3
+ * The claim a free reward item carries when it is added to the cart.
4
+ *
5
+ * Every drawer and the mobile offers screen built this object by hand, and the
6
+ * two of them disagreed: a voucher-linked claim set `applyLoyalty` on one screen
7
+ * and not on another. What the item carries decides which offer the item is
8
+ * stamped with, so it is the same money path as the ledger entry.
9
+ */
10
+ export type TRewardClaim = {
11
+ type: 'offer';
12
+ offerId: string;
13
+ } | {
14
+ type: 'gift-card';
15
+ giftCardId: string;
16
+ };
17
+ export interface IRewardClaimLoyalty {
18
+ loyalty_id: string;
19
+ name: string;
20
+ /** Options/items the reward may not discount, plus the item itself. */
21
+ refs: string[];
22
+ discount_details: null;
23
+ applicable_quantity: number;
24
+ }
25
+ export interface IBuildRewardClaimParams {
26
+ offer: IOffer;
27
+ /** The catalog item being added as the reward. */
28
+ catalogItemId: string;
29
+ /** How many items one claim is worth. */
30
+ applicableQuantity: number;
31
+ /**
32
+ * Set when the claim was bought with a voucher code. Voucher-linked claims do
33
+ * not set `applyLoyalty` - the code already occupies the discount slot.
34
+ * Defaults to the offer's own pathway.
35
+ */
36
+ isVoucherLinked?: boolean;
37
+ }
38
+ export interface IRewardClaimPatch {
39
+ rewardClaim: TRewardClaim;
40
+ applyLoyalty?: IRewardClaimLoyalty;
41
+ }
42
+ /**
43
+ * Build the claim patch for a reward item: what the item is stamped with, and
44
+ * optionally the loyalty entry it applies.
45
+ */
46
+ export declare function buildRewardClaim({ offer, catalogItemId, applicableQuantity, isVoucherLinked, }: IBuildRewardClaimParams): IRewardClaimPatch;
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildRewardClaim = buildRewardClaim;
4
+ const constants_1 = require("../../constants");
5
+ function getRewardExclusiveRefs(offer) {
6
+ if (offer.reward_type === constants_1.OFFER_REWARD_TYPE_ENUM.DISCOUNT_ITEMS) {
7
+ return offer.reward_discount_items?.exclusive_refs ?? [];
8
+ }
9
+ if (offer.reward_type === constants_1.OFFER_REWARD_TYPE_ENUM.ITEMS) {
10
+ return offer.reward_items?.exclusive_refs ?? [];
11
+ }
12
+ return [];
13
+ }
14
+ /**
15
+ * Build the claim patch for a reward item: what the item is stamped with, and
16
+ * optionally the loyalty entry it applies.
17
+ */
18
+ function buildRewardClaim({ offer, catalogItemId, applicableQuantity, isVoucherLinked = offer.pathway_to_unlock_type === constants_1.PATHWAY_TO_UNLOCK_TYPE_ENUM.VOUCHER, }) {
19
+ const quantity = Math.max(1, Math.floor(applicableQuantity));
20
+ const isGiftCard = offer.reward_type === constants_1.OFFER_REWARD_TYPE_ENUM.GIFT_CARDS;
21
+ const patch = {
22
+ rewardClaim: isGiftCard ? { type: 'gift-card', giftCardId: offer._id } : { type: 'offer', offerId: offer._id },
23
+ };
24
+ // A gift-card reward always applies its own loyalty entry; an offer claim only
25
+ // does when the discount slot is free (i.e. not bought with a voucher code).
26
+ if (!isVoucherLinked || isGiftCard) {
27
+ patch.applyLoyalty = {
28
+ loyalty_id: offer._id,
29
+ name: offer.name,
30
+ refs: [...getRewardExclusiveRefs(offer), catalogItemId],
31
+ discount_details: null,
32
+ applicable_quantity: quantity,
33
+ };
34
+ }
35
+ return patch;
36
+ }
@@ -232,8 +232,30 @@ describe('claim accounting: ledger vs cart evidence', () => {
232
232
  category_id: 'c',
233
233
  name: 'C',
234
234
  items: [
235
- { _id: 'ci1', item_id: 'i1', name: 'A', quantity: 1, price: 1000, subtotal: 1000, tax_rate: 0, modifiers: [], special_instructions: '', item_discount_details: null },
236
- { _id: 'ci2', item_id: 'i1', name: 'A', quantity: 1, price: 1000, subtotal: 0, tax_rate: 0, modifiers: [], special_instructions: '', item_discount_details: { loyalty_discount_id: 'o', loyalty_discount: 0, total_discount: 0 } },
235
+ {
236
+ _id: 'ci1',
237
+ item_id: 'i1',
238
+ name: 'A',
239
+ quantity: 1,
240
+ price: 1000,
241
+ subtotal: 1000,
242
+ tax_rate: 0,
243
+ modifiers: [],
244
+ special_instructions: '',
245
+ item_discount_details: null,
246
+ },
247
+ {
248
+ _id: 'ci2',
249
+ item_id: 'i1',
250
+ name: 'A',
251
+ quantity: 1,
252
+ price: 1000,
253
+ subtotal: 0,
254
+ tax_rate: 0,
255
+ modifiers: [],
256
+ special_instructions: '',
257
+ item_discount_details: { loyalty_discount_id: 'o', loyalty_discount: 0, total_discount: 0 },
258
+ },
237
259
  ],
238
260
  },
239
261
  ];
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,110 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const constants_1 = require("../constants");
4
+ const offer_claim_sequence_1 = require("../helpers/utils/offer-claim-sequence");
5
+ /**
6
+ * The claim sequence, tested once for all six frontends.
7
+ *
8
+ * The defect this encodes: the code used to be written before the reward item
9
+ * was resolved, so a sold-out reward left the voucher applied with nothing to
10
+ * claim.
11
+ */
12
+ function makeSteps(overrides = {}) {
13
+ const calls = [];
14
+ const steps = {
15
+ offerId: 'offer-1',
16
+ code: 'save10',
17
+ rewardItemIds: ['item-1'],
18
+ resolveRewardItem: jest.fn(() => {
19
+ calls.push('resolve');
20
+ return { _id: 'item-1' };
21
+ }),
22
+ applyVoucherCode: jest.fn(() => {
23
+ calls.push('write');
24
+ return true;
25
+ }),
26
+ openSelectionScreen: jest.fn(() => calls.push('selection')),
27
+ openItemDrawer: jest.fn(() => calls.push('drawer')),
28
+ applyLinkedOffer: jest.fn(() => {
29
+ calls.push('apply');
30
+ return true;
31
+ }),
32
+ rollback: jest.fn(() => calls.push('rollback')),
33
+ ...overrides,
34
+ };
35
+ return { steps: steps, calls };
36
+ }
37
+ describe('normalizeVoucherCode', () => {
38
+ it('trims and upper-cases', () => {
39
+ expect((0, offer_claim_sequence_1.normalizeVoucherCode)(' save10 ')).toBe('SAVE10');
40
+ });
41
+ it('is null for blank input', () => {
42
+ expect((0, offer_claim_sequence_1.normalizeVoucherCode)('')).toBeNull();
43
+ expect((0, offer_claim_sequence_1.normalizeVoucherCode)(' ')).toBeNull();
44
+ expect((0, offer_claim_sequence_1.normalizeVoucherCode)(null)).toBeNull();
45
+ expect((0, offer_claim_sequence_1.normalizeVoucherCode)(undefined)).toBeNull();
46
+ });
47
+ });
48
+ describe('offerNeedsExistingCartItems', () => {
49
+ it('is false for rewards that bring their own item', () => {
50
+ expect((0, offer_claim_sequence_1.offerNeedsExistingCartItems)({ reward_type: constants_1.OFFER_REWARD_TYPE_ENUM.ITEMS })).toBe(false);
51
+ expect((0, offer_claim_sequence_1.offerNeedsExistingCartItems)({ reward_type: constants_1.OFFER_REWARD_TYPE_ENUM.DISCOUNT_ITEMS })).toBe(false);
52
+ });
53
+ it('is true for order-level rewards', () => {
54
+ expect((0, offer_claim_sequence_1.offerNeedsExistingCartItems)({ reward_type: constants_1.OFFER_REWARD_TYPE_ENUM.DISCOUNT })).toBe(true);
55
+ expect((0, offer_claim_sequence_1.offerNeedsExistingCartItems)({ reward_type: constants_1.OFFER_REWARD_TYPE_ENUM.CASHBACK })).toBe(true);
56
+ expect((0, offer_claim_sequence_1.offerNeedsExistingCartItems)({ reward_type: constants_1.OFFER_REWARD_TYPE_ENUM.POINTS })).toBe(true);
57
+ });
58
+ });
59
+ describe('claimVoucherLinkedOffer - item rewards', () => {
60
+ it('writes nothing when the reward item is unavailable', () => {
61
+ const { steps } = makeSteps({ resolveRewardItem: jest.fn(() => null) });
62
+ expect((0, offer_claim_sequence_1.claimVoucherLinkedOffer)(steps)).toEqual({ status: 'unavailable' });
63
+ expect(steps.applyVoucherCode).not.toHaveBeenCalled();
64
+ expect(steps.openItemDrawer).not.toHaveBeenCalled();
65
+ expect(steps.openSelectionScreen).not.toHaveBeenCalled();
66
+ });
67
+ it('resolves before writing', () => {
68
+ const { steps, calls } = makeSteps();
69
+ (0, offer_claim_sequence_1.claimVoucherLinkedOffer)(steps);
70
+ expect(calls).toEqual(['resolve', 'write', 'drawer']);
71
+ });
72
+ it('opens the selection screen for a multi-item reward', () => {
73
+ const { steps } = makeSteps({ rewardItemIds: ['item-1', 'item-2'] });
74
+ expect((0, offer_claim_sequence_1.claimVoucherLinkedOffer)(steps)).toEqual({ status: 'opened' });
75
+ expect(steps.openSelectionScreen).toHaveBeenCalledTimes(1);
76
+ expect(steps.openItemDrawer).not.toHaveBeenCalled();
77
+ });
78
+ it('opens the drawer with the resolved item', () => {
79
+ const { steps } = makeSteps();
80
+ (0, offer_claim_sequence_1.claimVoucherLinkedOffer)(steps);
81
+ expect(steps.openItemDrawer).toHaveBeenCalledWith({ _id: 'item-1' });
82
+ });
83
+ it('stops when the code write fails', () => {
84
+ const { steps } = makeSteps({ applyVoucherCode: jest.fn(() => false) });
85
+ expect((0, offer_claim_sequence_1.claimVoucherLinkedOffer)(steps)).toEqual({ status: 'write-failed' });
86
+ expect(steps.openItemDrawer).not.toHaveBeenCalled();
87
+ });
88
+ });
89
+ describe('claimVoucherLinkedOffer - order-level rewards', () => {
90
+ it('writes, applies and reports success', () => {
91
+ const { steps, calls } = makeSteps({ rewardItemIds: [] });
92
+ expect((0, offer_claim_sequence_1.claimVoucherLinkedOffer)(steps)).toEqual({ status: 'applied' });
93
+ expect(calls).toEqual(['write', 'apply']);
94
+ expect(steps.rollback).not.toHaveBeenCalled();
95
+ });
96
+ it('rolls the code back when the apply fails', () => {
97
+ const { steps } = makeSteps({
98
+ rewardItemIds: [],
99
+ applyLinkedOffer: jest.fn(() => false),
100
+ });
101
+ expect((0, offer_claim_sequence_1.claimVoucherLinkedOffer)(steps)).toEqual({ status: 'failed' });
102
+ expect(steps.rollback).toHaveBeenCalledWith('offer-1');
103
+ });
104
+ it('never applies an offer for a blank code', () => {
105
+ const { steps } = makeSteps({ rewardItemIds: [], code: ' ' });
106
+ expect((0, offer_claim_sequence_1.claimVoucherLinkedOffer)(steps)).toEqual({ status: 'blank' });
107
+ expect(steps.applyVoucherCode).not.toHaveBeenCalled();
108
+ expect(steps.applyLinkedOffer).not.toHaveBeenCalled();
109
+ });
110
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,99 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const constants_1 = require("../constants");
4
+ const offer_item_resolution_1 = require("../helpers/utils/offer-item-resolution");
5
+ /**
6
+ * Phase 0-1 of the offers unification: the two questions every frontend was
7
+ * answering privately.
8
+ *
9
+ * They are pure on purpose - the catalog, platform and tenant are arguments, so
10
+ * the same answer is available to a hook, a drawer and a mobile screen.
11
+ */
12
+ const mapped = (entries) => entries;
13
+ const convert = (item) => ({ converted: item._id });
14
+ const baseOffer = {
15
+ reward_type: constants_1.OFFER_REWARD_TYPE_ENUM.ITEMS,
16
+ reward_items: { num_of_items: 3 },
17
+ };
18
+ describe('resolveFirstAvailableRewardItem', () => {
19
+ it('returns null without a platform or a tenant', () => {
20
+ expect((0, offer_item_resolution_1.resolveFirstAvailableRewardItem)({
21
+ itemIds: ['a'],
22
+ mappedItems: mapped({ a: { _id: 'a' } }),
23
+ platform: undefined,
24
+ tenantId: 't1',
25
+ convert,
26
+ })).toBeNull();
27
+ expect((0, offer_item_resolution_1.resolveFirstAvailableRewardItem)({
28
+ itemIds: ['a'],
29
+ mappedItems: mapped({ a: { _id: 'a' } }),
30
+ platform: 'WEB_DELIVERY',
31
+ tenantId: undefined,
32
+ convert,
33
+ })).toBeNull();
34
+ });
35
+ it('skips missing and sold-out entries', () => {
36
+ const resolved = (0, offer_item_resolution_1.resolveFirstAvailableRewardItem)({
37
+ itemIds: ['missing', 'sold-out', 'ok'],
38
+ mappedItems: mapped({
39
+ 'sold-out': { _id: 'sold-out', sold_out: true },
40
+ ok: { _id: 'ok', sold_out: false },
41
+ }),
42
+ platform: 'WEB_DELIVERY',
43
+ tenantId: 't1',
44
+ convert,
45
+ });
46
+ expect(resolved).toEqual({ converted: 'ok' });
47
+ });
48
+ it('returns null when the converter refuses every item', () => {
49
+ const resolved = (0, offer_item_resolution_1.resolveFirstAvailableRewardItem)({
50
+ itemIds: ['a', 'b'],
51
+ mappedItems: mapped({ a: { _id: 'a' }, b: { _id: 'b' } }),
52
+ platform: 'WEB_DELIVERY',
53
+ tenantId: 't1',
54
+ convert: () => null,
55
+ });
56
+ expect(resolved).toBeNull();
57
+ });
58
+ it('honours a custom sold-out predicate', () => {
59
+ const resolved = (0, offer_item_resolution_1.resolveFirstAvailableRewardItem)({
60
+ itemIds: ['a'],
61
+ mappedItems: mapped({ a: { _id: 'a', unavailable: true } }),
62
+ platform: 'WEB_DELIVERY',
63
+ tenantId: 't1',
64
+ convert,
65
+ isSoldOut: (item) => item.unavailable === true,
66
+ });
67
+ expect(resolved).toBeNull();
68
+ });
69
+ });
70
+ describe('getRewardSelectionQuantity', () => {
71
+ const stats = (applicable) => ({ applicable_quantity: applicable });
72
+ it('lets a voucher-linked claim buy only the reward itself', () => {
73
+ // one code = one claim, worth num_of_items items - never the total of several
74
+ expect((0, offer_item_resolution_1.getRewardSelectionQuantity)({ offer: baseOffer, stats: stats(9), isVoucherLinked: true })).toBe(3);
75
+ });
76
+ it('uses every applicable claim when the customer bought them', () => {
77
+ expect((0, offer_item_resolution_1.getRewardSelectionQuantity)({ offer: baseOffer, stats: stats(9) })).toBe(9);
78
+ });
79
+ it('falls back to the reward when stats are missing or empty', () => {
80
+ expect((0, offer_item_resolution_1.getRewardSelectionQuantity)({ offer: baseOffer, stats: undefined })).toBe(3);
81
+ expect((0, offer_item_resolution_1.getRewardSelectionQuantity)({ offer: baseOffer, stats: stats(0) })).toBe(3);
82
+ });
83
+ it('reads DISCOUNT_ITEMS rewards too', () => {
84
+ const discountItemsOffer = {
85
+ reward_type: constants_1.OFFER_REWARD_TYPE_ENUM.DISCOUNT_ITEMS,
86
+ reward_discount_items: { num_of_items: 2 },
87
+ };
88
+ expect((0, offer_item_resolution_1.getRewardSelectionQuantity)({ offer: discountItemsOffer, stats: stats(7) })).toBe(7);
89
+ expect((0, offer_item_resolution_1.getRewardSelectionQuantity)({
90
+ offer: discountItemsOffer,
91
+ stats: stats(7),
92
+ isVoucherLinked: true,
93
+ })).toBe(2);
94
+ });
95
+ it('never returns less than one item', () => {
96
+ const noItems = { reward_type: constants_1.OFFER_REWARD_TYPE_ENUM.ITEMS, reward_items: { num_of_items: 0 } };
97
+ expect((0, offer_item_resolution_1.getRewardSelectionQuantity)({ offer: noItems, stats: undefined })).toBe(1);
98
+ });
99
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,78 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const constants_1 = require("../constants");
4
+ const offer_reward_claim_1 = require("../helpers/utils/offer-reward-claim");
5
+ /**
6
+ * What a free reward item carries into the cart.
7
+ *
8
+ * Two screens built this by hand and disagreed about `applyLoyalty` for a
9
+ * voucher-linked claim, so the rule is pinned here once.
10
+ */
11
+ const offer = (overrides = {}) => ({
12
+ _id: 'offer-1',
13
+ name: 'Free item',
14
+ reward_type: constants_1.OFFER_REWARD_TYPE_ENUM.ITEMS,
15
+ pathway_to_unlock_type: constants_1.PATHWAY_TO_UNLOCK_TYPE_ENUM.ORDERS,
16
+ reward_items: { num_of_items: 2, exclusive_refs: ['option-x'] },
17
+ ...overrides,
18
+ });
19
+ describe('buildRewardClaim', () => {
20
+ it('stamps the offer and applies its loyalty entry', () => {
21
+ const patch = (0, offer_reward_claim_1.buildRewardClaim)({ offer: offer(), catalogItemId: 'item-1', applicableQuantity: 2 });
22
+ expect(patch.rewardClaim).toEqual({ type: 'offer', offerId: 'offer-1' });
23
+ expect(patch.applyLoyalty).toEqual({
24
+ loyalty_id: 'offer-1',
25
+ name: 'Free item',
26
+ refs: ['option-x', 'item-1'],
27
+ discount_details: null,
28
+ applicable_quantity: 2,
29
+ });
30
+ });
31
+ it('does not apply loyalty for a voucher-linked claim', () => {
32
+ // the voucher code already occupies the discount slot
33
+ const patch = (0, offer_reward_claim_1.buildRewardClaim)({
34
+ offer: offer({ pathway_to_unlock_type: constants_1.PATHWAY_TO_UNLOCK_TYPE_ENUM.VOUCHER }),
35
+ catalogItemId: 'item-1',
36
+ applicableQuantity: 2,
37
+ });
38
+ expect(patch.rewardClaim).toEqual({ type: 'offer', offerId: 'offer-1' });
39
+ expect(patch.applyLoyalty).toBeUndefined();
40
+ });
41
+ it('reads the exclusive refs of a DISCOUNT_ITEMS reward', () => {
42
+ const patch = (0, offer_reward_claim_1.buildRewardClaim)({
43
+ offer: offer({
44
+ reward_type: constants_1.OFFER_REWARD_TYPE_ENUM.DISCOUNT_ITEMS,
45
+ reward_items: undefined,
46
+ reward_discount_items: { num_of_items: 1, exclusive_refs: ['option-y'] },
47
+ }),
48
+ catalogItemId: 'item-9',
49
+ applicableQuantity: 1,
50
+ });
51
+ expect(patch.applyLoyalty?.refs).toEqual(['option-y', 'item-9']);
52
+ });
53
+ it('stamps a gift-card reward with the gift card id and always applies', () => {
54
+ const patch = (0, offer_reward_claim_1.buildRewardClaim)({
55
+ offer: offer({
56
+ reward_type: constants_1.OFFER_REWARD_TYPE_ENUM.GIFT_CARDS,
57
+ pathway_to_unlock_type: constants_1.PATHWAY_TO_UNLOCK_TYPE_ENUM.VOUCHER,
58
+ }),
59
+ catalogItemId: 'item-1',
60
+ applicableQuantity: 1,
61
+ });
62
+ expect(patch.rewardClaim).toEqual({ type: 'gift-card', giftCardId: 'offer-1' });
63
+ expect(patch.applyLoyalty?.loyalty_id).toBe('offer-1');
64
+ });
65
+ it('honours an explicit voucher flag over the pathway', () => {
66
+ const patch = (0, offer_reward_claim_1.buildRewardClaim)({
67
+ offer: offer(),
68
+ catalogItemId: 'item-1',
69
+ applicableQuantity: 1,
70
+ isVoucherLinked: true,
71
+ });
72
+ expect(patch.applyLoyalty).toBeUndefined();
73
+ });
74
+ it('never carries a quantity below one', () => {
75
+ const patch = (0, offer_reward_claim_1.buildRewardClaim)({ offer: offer(), catalogItemId: 'item-1', applicableQuantity: 0 });
76
+ expect(patch.applyLoyalty?.applicable_quantity).toBe(1);
77
+ });
78
+ });
@@ -631,10 +631,7 @@ describe('pathway x reward matrix', () => {
631
631
  // and the block are both real.
632
632
  const offer = withLifetimeCap(makeOffer(pathway, reward, true));
633
633
  const { stats } = statsFor(offer, { redeemedTimes: 1 });
634
- const itemRewards = new Set([
635
- constants_1.OFFER_REWARD_TYPE_ENUM.ITEMS,
636
- constants_1.OFFER_REWARD_TYPE_ENUM.DISCOUNT_ITEMS,
637
- ]);
634
+ const itemRewards = new Set([constants_1.OFFER_REWARD_TYPE_ENUM.ITEMS, constants_1.OFFER_REWARD_TYPE_ENUM.DISCOUNT_ITEMS]);
638
635
  if (itemRewards.has(reward)) {
639
636
  // Item rewards are claimed by stamping cart items. Eligibility reads that
640
637
  // evidence, not the ledger, so a ledger-only claim is invisible and the
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@managesome/eposmatic-toolkit",
3
- "version": "0.4.42",
3
+ "version": "0.4.43",
4
4
  "description": "A Toolkit Library for Eposmatic",
5
5
  "main": "lib/index.js",
6
6
  "module": "esm/index.js",