@zappie/sdk 0.15.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +52 -0
  3. package/dist/cart/index.js +30 -39
  4. package/dist/cart/index.js.map +1 -1
  5. package/dist/cart/item.d.ts +1 -1
  6. package/dist/cart/quote-client.js +4 -20
  7. package/dist/cart/quote-client.js.map +1 -1
  8. package/dist/cart/quote-response.js +10 -5
  9. package/dist/cart/quote-response.js.map +1 -1
  10. package/dist/cart/storage.js +2 -0
  11. package/dist/cart/storage.js.map +1 -1
  12. package/dist/checkout/embed.d.ts +2 -0
  13. package/dist/checkout/index.d.ts +2 -0
  14. package/dist/checkout/react.d.ts +2 -0
  15. package/dist/checkout-defaults/index.d.ts +3 -0
  16. package/dist/{client-C47e44tl.d.ts → client-uRLLtZJU.d.ts} +1 -1
  17. package/dist/customer/client.js +34 -12
  18. package/dist/customer/client.js.map +1 -1
  19. package/dist/customer/index.d.ts +181 -10
  20. package/dist/customer/reorder.d.ts +40 -0
  21. package/dist/customer/reorder.js +61 -0
  22. package/dist/customer/reorder.js.map +6 -0
  23. package/dist/debug.js +1 -1
  24. package/dist/index.d.ts +4 -4
  25. package/dist/index.js +1 -1
  26. package/dist/integrations/index.d.ts +1 -1
  27. package/dist/internal/perk-hold.js +35 -0
  28. package/dist/internal/perk-hold.js.map +6 -0
  29. package/dist/internal/remembered-address.js +8 -2
  30. package/dist/internal/remembered-address.js.map +1 -1
  31. package/dist/internal.d.ts +1 -1
  32. package/dist/loyalty/cart.js +56 -0
  33. package/dist/loyalty/cart.js.map +6 -0
  34. package/dist/loyalty/client.js +89 -0
  35. package/dist/loyalty/client.js.map +6 -0
  36. package/dist/loyalty/index.d.ts +526 -0
  37. package/dist/loyalty/index.js +13 -0
  38. package/dist/loyalty/index.js.map +6 -0
  39. package/dist/loyalty/react.d.ts +116 -0
  40. package/dist/loyalty/react.js +200 -0
  41. package/dist/loyalty/react.js.map +6 -0
  42. package/dist/loyalty/release.js +43 -0
  43. package/dist/loyalty/release.js.map +6 -0
  44. package/dist/loyalty/types.js +1 -0
  45. package/dist/loyalty/types.js.map +6 -0
  46. package/dist/persist/catalogue.d.ts +2 -2
  47. package/dist/react/index.d.ts +2 -1
  48. package/dist/server/index.d.ts +1 -1
  49. package/dist/testing/index.d.ts +92 -4
  50. package/dist/testing/index.js +2 -0
  51. package/dist/testing/loyalty.js +110 -0
  52. package/dist/testing/loyalty.js.map +6 -0
  53. package/dist/transport/search.d.ts +1 -1
  54. package/dist/transport/selected-menu.d.ts +2 -2
  55. package/dist/{types-ooHA0lwH.d.ts → types-K01NHM_a.d.ts} +28 -3
  56. package/package.json +14 -2
@@ -0,0 +1,116 @@
1
+ import * as react from 'react';
2
+ import { ReactNode } from 'react';
3
+ import { LoyaltyClient, Perk } from '@zappie/sdk/loyalty';
4
+
5
+ /** A normalized ISO 4217 currency code. */
6
+ type Currency = string;
7
+
8
+ /**
9
+ * An API monetary amount in minor units with its currency code.
10
+ */
11
+ type WireMoney = {
12
+ amount_minor: number;
13
+ currency: Currency;
14
+ };
15
+
16
+ /**
17
+ * Provide a loyalty client to the hooks below. Without one, they share a client on `/_zappie/api`.
18
+ */
19
+ declare function LoyaltyProvider({ client, children, }: {
20
+ client: LoyaltyClient;
21
+ children: ReactNode;
22
+ }): react.JSX.Element;
23
+ /** The nearest LoyaltyProvider's client, or the shared one on `/_zappie/api`. */
24
+ declare function useLoyaltyClient(): LoyaltyClient;
25
+ /**
26
+ * Where a loyalty read stands. `off` when the business turned loyalty off, `signed_out` without a
27
+ * customer, and `scope_required` when the shopper signed in before rewards needed their
28
+ * permission: offer `signInAgain`.
29
+ */
30
+ type LoyaltyStatus = "loading" | "ready" | "off" | "signed_out" | "scope_required" | "error";
31
+ /** The status a loyalty failure means, from its HTTP status and the API's code. */
32
+ declare function loyaltyStatus(error: unknown): LoyaltyStatus;
33
+ /** Sign in once more, so the site may use rewards, and come back to this page. */
34
+ declare function signInAgain(returnTo?: string): void;
35
+ /**
36
+ * The signed-in customer's points. `enabled` is true only when the read succeeded and the business
37
+ * has its loyalty programme on: show rewards only then.
38
+ *
39
+ * @param options - `enabled: false` reads nothing, such as for a guest.
40
+ */
41
+ declare function useLoyalty(options?: {
42
+ enabled?: boolean;
43
+ }): {
44
+ status: LoyaltyStatus;
45
+ enabled: boolean;
46
+ points: number | undefined;
47
+ error: unknown;
48
+ refresh: () => void;
49
+ signInAgain: typeof signInAgain;
50
+ };
51
+ /**
52
+ * The active perks at the branch. Read them when the rewards sheet opens, not on every page.
53
+ *
54
+ * @param branchId - The cart's branch. Pass undefined to read nothing yet.
55
+ */
56
+ declare function usePerks(branchId: string | undefined): {
57
+ status: LoyaltyStatus;
58
+ perks: Perk[];
59
+ error: unknown;
60
+ refresh: () => void;
61
+ };
62
+ /**
63
+ * The customer's store credit at the branch. `enabled` is false where the branch doesn't take it.
64
+ * Paying with it happens on the payment page.
65
+ */
66
+ declare function useStoreCredit(branchId: string | undefined): {
67
+ status: LoyaltyStatus;
68
+ enabled: boolean;
69
+ balance: WireMoney | undefined;
70
+ error: unknown;
71
+ };
72
+ /**
73
+ * Claim a paid order's points once per order in this tab, on the order confirmation. Returns
74
+ * `pointsEarned` when the claim earned more than 0: show "You earned N points". The API awards an
75
+ * order's points once, so a reload earns nothing more.
76
+ *
77
+ * @param orderId - The order on the confirmation.
78
+ * @param options - `paid` once the order shows paid. Nothing is claimed before.
79
+ */
80
+ declare function useClaimPoints(orderId: string | undefined, options: {
81
+ paid: boolean;
82
+ }): {
83
+ pointsEarned: number | undefined;
84
+ dismiss: () => void;
85
+ };
86
+ /**
87
+ * The perks in the bag, with redeem and remove. One action runs at a time. `busy` names the perk
88
+ * or redemption it is for, and `error` is the last failure, with the API's message.
89
+ */
90
+ declare function useCartPerks(): {
91
+ perks: readonly Readonly<{
92
+ redemptionId: string;
93
+ perkId: string;
94
+ name: string;
95
+ pointsSpent: number;
96
+ expiresAt: string;
97
+ reward?: "order_discount" | "free_item";
98
+ }>[];
99
+ busy: string | undefined;
100
+ error: unknown;
101
+ clearError: () => void;
102
+ /** Redeem a perk into the bag. Resolves undefined when it failed or another action runs. */
103
+ apply: (perk: Perk) => Promise<Readonly<{
104
+ redemptionId: string;
105
+ perkId: string;
106
+ name: string;
107
+ pointsSpent: number;
108
+ expiresAt: string;
109
+ reward?: "order_discount" | "free_item";
110
+ }> | undefined>;
111
+ /** Take a perk out of the bag and give its points back. */
112
+ remove: (redemptionId: string) => Promise<void | undefined>;
113
+ };
114
+
115
+ export { LoyaltyProvider, loyaltyStatus, signInAgain, useCartPerks, useClaimPoints, useLoyalty, useLoyaltyClient, usePerks, useStoreCredit };
116
+ export type { LoyaltyStatus };
@@ -0,0 +1,200 @@
1
+ "use client";
2
+
3
+ // src/loyalty/react.tsx
4
+ import {
5
+ applyPerk,
6
+ createLoyalty,
7
+ removePerk
8
+ } from "@zappie/sdk/loyalty";
9
+ import { useCart } from "@zappie/sdk/react";
10
+ import {
11
+ createContext,
12
+ useCallback,
13
+ useContext,
14
+ useEffect,
15
+ useRef,
16
+ useState
17
+ } from "react";
18
+ import { currentPath, leaveTo, safeReturnTo } from "../customer/navigation.js";
19
+ import { jsx } from "react/jsx-runtime";
20
+ var Context = createContext(null);
21
+ var shared;
22
+ function LoyaltyProvider({
23
+ client,
24
+ children
25
+ }) {
26
+ return /* @__PURE__ */ jsx(Context.Provider, { value: client, children });
27
+ }
28
+ function useLoyaltyClient() {
29
+ return useContext(Context) ?? (shared ?? (shared = createLoyalty()));
30
+ }
31
+ function loyaltyStatus(error) {
32
+ const { status, apiCode } = error ?? {};
33
+ return status === 401 ? "signed_out" : apiCode === "scope_required" ? "scope_required" : apiCode === "feature_off" || apiCode === "loyalty_off" ? "off" : "error";
34
+ }
35
+ function signInAgain(returnTo) {
36
+ leaveTo(
37
+ `/_zappie/login?return=${encodeURIComponent(safeReturnTo(returnTo ?? currentPath()))}`
38
+ );
39
+ }
40
+ function useRead(key, load) {
41
+ const client = useLoyaltyClient();
42
+ const [state, setState] = useState({ status: "loading" });
43
+ const [round, setRound] = useState(0);
44
+ const loader = useRef(load);
45
+ loader.current = load;
46
+ useEffect(() => {
47
+ if (key === void 0) {
48
+ return;
49
+ }
50
+ let active = true;
51
+ const run = () => {
52
+ loader.current(client).then(
53
+ (data) => {
54
+ if (active) {
55
+ setState({ key, status: "ready", data });
56
+ }
57
+ },
58
+ (error) => {
59
+ if (active) {
60
+ setState({ key, status: loyaltyStatus(error), error });
61
+ }
62
+ }
63
+ );
64
+ };
65
+ run();
66
+ const stop = client.onChange(run);
67
+ return () => {
68
+ active = false;
69
+ stop();
70
+ };
71
+ }, [client, key, round]);
72
+ const refresh = useCallback(() => setRound((value) => value + 1), []);
73
+ return state.key === key ? { status: state.status, data: state.data, error: state.error, refresh } : { status: "loading", refresh };
74
+ }
75
+ function useLoyalty(options = {}) {
76
+ const read = useRead(
77
+ options.enabled === false ? void 0 : "points",
78
+ (client) => client.points()
79
+ );
80
+ return {
81
+ status: read.status,
82
+ enabled: read.status === "ready" && read.data.enabled,
83
+ points: read.data?.points,
84
+ error: read.error,
85
+ refresh: read.refresh,
86
+ signInAgain
87
+ };
88
+ }
89
+ function usePerks(branchId) {
90
+ const read = useRead(
91
+ branchId === void 0 ? void 0 : `perks:${branchId}`,
92
+ (client) => client.perks(branchId)
93
+ );
94
+ return {
95
+ status: read.status,
96
+ perks: read.data ?? [],
97
+ error: read.error,
98
+ refresh: read.refresh
99
+ };
100
+ }
101
+ function useStoreCredit(branchId) {
102
+ const read = useRead(
103
+ branchId === void 0 ? void 0 : `credit:${branchId}`,
104
+ (client) => client.storeCredit(branchId)
105
+ );
106
+ return {
107
+ status: read.status,
108
+ enabled: read.status === "ready" && read.data.enabled,
109
+ balance: read.data?.balance,
110
+ error: read.error
111
+ };
112
+ }
113
+ var claiming = /* @__PURE__ */ new Set();
114
+ function claimedKey(orderId) {
115
+ return `zappie:loyalty-claim:${orderId}`;
116
+ }
117
+ function useClaimPoints(orderId, options) {
118
+ const client = useLoyaltyClient();
119
+ const [earned, setEarned] = useState();
120
+ useEffect(() => {
121
+ if (!orderId || !options.paid || claiming.has(orderId)) {
122
+ return;
123
+ }
124
+ try {
125
+ if (sessionStorage.getItem(claimedKey(orderId))) {
126
+ return;
127
+ }
128
+ } catch {
129
+ }
130
+ claiming.add(orderId);
131
+ client.claim(orderId).then(
132
+ (claim) => {
133
+ try {
134
+ sessionStorage.setItem(claimedKey(orderId), "1");
135
+ } catch {
136
+ }
137
+ if (claim.points_earned > 0) {
138
+ setEarned({ orderId, points: claim.points_earned });
139
+ }
140
+ },
141
+ () => {
142
+ claiming.delete(orderId);
143
+ }
144
+ );
145
+ }, [client, orderId, options.paid]);
146
+ const dismiss = useCallback(() => setEarned(void 0), []);
147
+ return {
148
+ pointsEarned: earned?.orderId === orderId ? earned?.points : void 0,
149
+ dismiss
150
+ };
151
+ }
152
+ function useCartPerks() {
153
+ const client = useLoyaltyClient();
154
+ const cart = useCart();
155
+ const [busy, setBusy] = useState();
156
+ const [error, setError] = useState();
157
+ const running = useRef(false);
158
+ const run = useCallback(
159
+ async (target, action) => {
160
+ if (running.current) {
161
+ return void 0;
162
+ }
163
+ running.current = true;
164
+ setBusy(target);
165
+ setError(void 0);
166
+ try {
167
+ return await action();
168
+ } catch (failure) {
169
+ setError(failure);
170
+ return void 0;
171
+ } finally {
172
+ running.current = false;
173
+ setBusy(void 0);
174
+ }
175
+ },
176
+ []
177
+ );
178
+ return {
179
+ perks: cart.perks,
180
+ busy,
181
+ error,
182
+ clearError: () => setError(void 0),
183
+ /** Redeem a perk into the bag. Resolves undefined when it failed or another action runs. */
184
+ apply: (perk) => run(perk.id, () => applyPerk(cart.actions, client, perk)),
185
+ /** Take a perk out of the bag and give its points back. */
186
+ remove: (redemptionId) => run(redemptionId, () => removePerk(cart.actions, client, redemptionId))
187
+ };
188
+ }
189
+ export {
190
+ LoyaltyProvider,
191
+ loyaltyStatus,
192
+ signInAgain,
193
+ useCartPerks,
194
+ useClaimPoints,
195
+ useLoyalty,
196
+ useLoyaltyClient,
197
+ usePerks,
198
+ useStoreCredit
199
+ };
200
+ //# sourceMappingURL=react.js.map
@@ -0,0 +1,6 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/loyalty/react.tsx"],
4
+ "mappings": ";;;AAGA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAIK;AACP,SAAS,eAAe;AACxB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,aAAa,SAAS,oBAAoB;AAe1C;AAbT,IAAM,UAAU,cAAoC,IAAI;AACxD,IAAI;AAKG,SAAS,gBAAgB;AAAA,EAC9B;AAAA,EACA;AACF,GAGG;AACD,SAAO,oBAAC,QAAQ,UAAR,EAAiB,OAAO,QAAS,UAAS;AACpD;AAGO,SAAS,mBAAkC;AAChD,SAAO,WAAW,OAAO,MAAM,oBAAW,cAAc;AAC1D;AAWO,SAAS,cAAc,OAA+B;AAC3D,QAAM,EAAE,QAAQ,QAAQ,IAAK,SAAS,CAAC;AACvC,SAAO,WAAW,MACd,eACA,YAAY,mBACV,mBACA,YAAY,iBAAiB,YAAY,gBACvC,QACA;AACV;AAGO,SAAS,YAAY,UAAmB;AAC7C;AAAA,IACE,yBAAyB,mBAAmB,aAAa,YAAY,YAAY,CAAC,CAAC,CAAC;AAAA,EACtF;AACF;AAUA,SAAS,QACP,KACA,MACS;AACT,QAAM,SAAS,iBAAiB;AAChC,QAAM,CAAC,OAAO,QAAQ,IAAI,SAKvB,EAAE,QAAQ,UAAU,CAAC;AACxB,QAAM,CAAC,OAAO,QAAQ,IAAI,SAAS,CAAC;AACpC,QAAM,SAAS,OAAO,IAAI;AAC1B,SAAO,UAAU;AACjB,YAAU,MAAM;AACd,QAAI,QAAQ,QAAW;AACrB;AAAA,IACF;AACA,QAAI,SAAS;AACb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AAY,UAAU,QAAQ,SAAS;AAAA,IAC7D;AAAA,EACF;AACF;AAMO,SAAS,eAAe;AAC7B,QAAM,SAAS,iBAAiB;AAChC,QAAM,OAAO,QAAQ;AACrB,QAAM,CAAC,MAAM,OAAO,IAAI,SAAiB;AACzC,QAAM,CAAC,OAAO,QAAQ,IAAI,SAAkB;AAC5C,QAAM,UAAU,OAAO,KAAK;AAC5B,QAAM,MAAM;AAAA,IACV,OAAW,QAAgB,WAA6B;AACtD,UAAI,QAAQ,SAAS;AACnB,eAAO;AAAA,MACT;AACA,cAAQ,UAAU;AAClB,cAAQ,MAAM;AACd,eAAS,MAAS;AAClB,UAAI;AACF,eAAO,MAAM,OAAO;AAAA,MACtB,SAAS,SAAS;AAChB,iBAAS,OAAO;AAChB,eAAO;AAAA,MACT,UAAE;AACA,gBAAQ,UAAU;AAClB,gBAAQ,MAAS;AAAA,MACnB;AAAA,IACF;AAAA,IACA,CAAC;AAAA,EACH;AACA,SAAO;AAAA,IACL,OAAO,KAAK;AAAA,IACZ;AAAA,IACA;AAAA,IACA,YAAY,MAAM,SAAS,MAAS;AAAA;AAAA,IAEpC,OAAO,CAAC,SACN,IAAI,KAAK,IAAI,MAAM,UAAU,KAAK,SAAS,QAAQ,IAAI,CAAC;AAAA;AAAA,IAE1D,QAAQ,CAAC,iBACP,IAAI,cAAc,MAAM,WAAW,KAAK,SAAS,QAAQ,YAAY,CAAC;AAAA,EAC1E;AACF;",
5
+ "names": []
6
+ }
@@ -0,0 +1,43 @@
1
+ // src/loyalty/release.ts
2
+ import { heldBy, unhold } from "../internal/perk-hold.js";
3
+ async function held(id, base, fetcher = globalThis.fetch) {
4
+ const session = heldBy(id);
5
+ if (!session) {
6
+ return false;
7
+ }
8
+ try {
9
+ const response = await fetcher(
10
+ `${base}/checkout/sessions/${encodeURIComponent(session)}`,
11
+ { credentials: "same-origin", headers: { Accept: "application/json" } }
12
+ );
13
+ const ended = response.ok ? (await response.json()).status !== "open" : response.status === 404;
14
+ if (ended) {
15
+ unhold(id);
16
+ }
17
+ return !ended;
18
+ } catch {
19
+ return true;
20
+ }
21
+ }
22
+ async function releasePerks(perks, customerBase = "/_zappie/api", fetcher = globalThis.fetch) {
23
+ const base = customerBase.replace(/\/+$/, "");
24
+ await Promise.all(
25
+ perks.map(async ({ redemptionId }) => {
26
+ if (!await held(redemptionId, base, fetcher)) {
27
+ await fetcher(
28
+ `${base}/me/loyalty/redemptions/${encodeURIComponent(redemptionId)}`,
29
+ {
30
+ method: "DELETE",
31
+ credentials: "same-origin",
32
+ headers: { Accept: "application/json" }
33
+ }
34
+ ).catch(() => void 0);
35
+ }
36
+ })
37
+ );
38
+ }
39
+ export {
40
+ held,
41
+ releasePerks
42
+ };
43
+ //# sourceMappingURL=release.js.map
@@ -0,0 +1,6 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/loyalty/release.ts"],
4
+ "mappings": ";AACA,SAAS,QAAQ,cAAc;AAO/B,eAAsB,KACpB,IACA,MACA,UAAwB,WAAW,OACjB;AAClB,QAAM,UAAU,OAAO,EAAE;AACzB,MAAI,CAAC,SAAS;AACZ,WAAO;AAAA,EACT;AACA,MAAI;AACF,UAAM,WAAW,MAAM;AAAA,MACrB,GAAG,IAAI,sBAAsB,mBAAmB,OAAO,CAAC;AAAA,MACxD,EAAE,aAAa,eAAe,SAAS,EAAE,QAAQ,mBAAmB,EAAE;AAAA,IACxE;AACA,UAAM,QAAQ,SAAS,MACjB,MAAM,SAAS,KAAK,GAA2B,WAAW,SAC5D,SAAS,WAAW;AACxB,QAAI,OAAO;AACT,aAAO,EAAE;AAAA,IACX;AACA,WAAO,CAAC;AAAA,EACV,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAMA,eAAsB,aACpB,OACA,eAAe,gBACf,UAAwB,WAAW,OACpB;AACf,QAAM,OAAO,aAAa,QAAQ,QAAQ,EAAE;AAC5C,QAAM,QAAQ;AAAA,IACZ,MAAM,IAAI,OAAO,EAAE,aAAa,MAAM;AACpC,UAAI,CAAE,MAAM,KAAK,cAAc,MAAM,OAAO,GAAI;AAC9C,cAAM;AAAA,UACJ,GAAG,IAAI,2BAA2B,mBAAmB,YAAY,CAAC;AAAA,UAClE;AAAA,YACE,QAAQ;AAAA,YACR,aAAa;AAAA,YACb,SAAS,EAAE,QAAQ,mBAAmB;AAAA,UACxC;AAAA,QACF,EAAE,MAAM,MAAM,MAAS;AAAA,MACzB;AAAA,IACF,CAAC;AAAA,EACH;AACF;",
5
+ "names": []
6
+ }
@@ -0,0 +1 @@
1
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1,6 @@
1
+ {
2
+ "version": 3,
3
+ "sources": [],
4
+ "mappings": "",
5
+ "names": []
6
+ }
@@ -1,3 +1,3 @@
1
- export { q as CATALOGUE_MAX_AGE_MS, r as CATALOGUE_MAX_BYTES, s as CatalogueScope, t as SavedCatalogue, u as catalogueDigest, w as catalogueKey, x as createCatalogueStorage, y as createSavedCatalogue } from '../client-C47e44tl.js';
1
+ export { q as CATALOGUE_MAX_AGE_MS, r as CATALOGUE_MAX_BYTES, s as CatalogueScope, t as SavedCatalogue, u as catalogueDigest, w as catalogueKey, x as createCatalogueStorage, y as createSavedCatalogue } from '../client-uRLLtZJU.js';
2
2
  import '../models-asoc6fS3.js';
3
- import '../types-ooHA0lwH.js';
3
+ import '../types-K01NHM_a.js';
@@ -3,7 +3,7 @@ import { ZappieError, Zappie } from '../index.js';
3
3
  import { Item, Menu, Store, Money } from '../index.js';
4
4
  import * as react from 'react';
5
5
  import { ReactNode } from 'react';
6
- import { CartModule, CartLineInput, CartLine, CartIssueCode, CartFulfilment, CartState, CartIssue } from '../index.js';
6
+ import { CartModule, CartLineInput, CartLine, CartIssueCode, CartFulfilment, AppliedPerk, CartState, CartIssue } from '../index.js';
7
7
 
8
8
  /** Subscribe to storefront identity and branch-directory data. */
9
9
  declare function useStore(): {
@@ -82,6 +82,7 @@ declare function useCart(): {
82
82
  subtotal: Money | null;
83
83
  fulfilment: CartFulfilment | null;
84
84
  promoCode: string | null;
85
+ perks: readonly AppliedPerk[];
85
86
  state: CartState;
86
87
  issues: readonly CartIssue[];
87
88
  isHydrated: boolean;
@@ -1,5 +1,5 @@
1
1
  import { Branch, Store, Menu, Formatters } from '../index.js';
2
- import { C as Cache } from '../client-C47e44tl.js';
2
+ import { C as Cache } from '../client-uRLLtZJU.js';
3
3
  import { ZappieError, Zappie, ZappieConfig, Transport, StorageLike, StoreResource, MenuResource, ZappieEvents, MenuReadOptions } from '../index.js';
4
4
  export { VERSION } from '../index.js';
5
5
  import { CartModule, CartLineInput } from '../index.js';
@@ -1,8 +1,96 @@
1
- import { C as Cache } from '../client-C47e44tl.js';
1
+ import { C as Cache } from '../client-uRLLtZJU.js';
2
2
  import { Transport, ZappieErrorCode, StorageLike, StoreResource, MenuResource, ZappieEvents, MenuReadOptions } from '../index.js';
3
3
  import { Store, Menu, Formatters } from '../index.js';
4
4
  export { VERSION } from '../index.js';
5
- import { CartModule, CartLineInput } from '../index.js';
5
+ import { WireMoney, CartModule, CartLineInput } from '../index.js';
6
+
7
+ /** The customer's points with the business. `enabled` is false while it has no loyalty programme set up. */
8
+ type Loyalty = {
9
+ object: "loyalty";
10
+ enabled: boolean;
11
+ points: number;
12
+ };
13
+ /** What a perk gives, to show the shopper. The quote prices it exactly. */
14
+ type PerkReward = {
15
+ type: "order_discount" | "free_item";
16
+ /** A percentage off the order. */
17
+ percent_off?: number;
18
+ /** A fixed amount off the order, in the branch's currency. */
19
+ amount_off?: WireMoney;
20
+ /** The free items, when `type` is `free_item`. */
21
+ items?: {
22
+ item_id: string;
23
+ quantity: number;
24
+ }[];
25
+ };
26
+ /** A perk the customer can spend points on at a branch. */
27
+ type Perk = {
28
+ id: string;
29
+ object: "perk";
30
+ name: string;
31
+ description: string | null;
32
+ points_cost: number;
33
+ reward: PerkReward;
34
+ /** The order types the business made the perk for. */
35
+ fulfilments: ("delivery" | "pickup" | "dine_in")[];
36
+ };
37
+ /** A redemption: points spent on a perk, reserved until an order uses it or it is cancelled. */
38
+ type PerkRedemption = {
39
+ id: string;
40
+ object: "perk_redemption";
41
+ status: "reserved" | "cancelled";
42
+ /** Sent when it is reserved. */
43
+ points_spent?: number;
44
+ /** Sent when it is reserved. */
45
+ perk?: {
46
+ id: string;
47
+ name: string;
48
+ };
49
+ /** When an unused reservation gives its points back. Sent when it is reserved. */
50
+ expires_at?: string;
51
+ };
52
+ /** What claiming an order's points earned, and the balance after it. */
53
+ type LoyaltyClaim = {
54
+ object: "loyalty_claim";
55
+ order_id: string;
56
+ points_earned: number;
57
+ points: number;
58
+ };
59
+ /** The customer's store credit at a branch. `enabled` is false when the branch doesn't take it. */
60
+ type StoreCredit = {
61
+ object: "store_credit";
62
+ enabled: boolean;
63
+ balance: WireMoney;
64
+ };
65
+
66
+ /** The in-memory loyalty a mock client serves. */
67
+ type MockLoyaltyOptions = {
68
+ /** False for a business without a loyalty programme. Defaults to true. */
69
+ enabled?: boolean;
70
+ points?: number;
71
+ perks?: Perk[];
72
+ storeCredit?: StoreCredit;
73
+ /** The points each order earns when claimed, by order ID. A second claim earns 0. */
74
+ claims?: Record<string, number>;
75
+ /** Answer every call with this API error code, such as `scope_required` or `feature_off`. */
76
+ failWith?: string;
77
+ };
78
+ /**
79
+ * Create an in-memory loyalty client for tests and previews. Redeeming takes the perk's points and
80
+ * cancelling gives them back, as the API does. Nothing is priced: the quote prices a perk.
81
+ */
82
+ declare function createMockLoyalty(options?: MockLoyaltyOptions): {
83
+ base: string;
84
+ points: () => Promise<Loyalty>;
85
+ perks: (branchId?: string) => Promise<Perk[]>;
86
+ redeem: (perkId: string, redeem?: {
87
+ idempotencyKey?: string;
88
+ }) => Promise<PerkRedemption>;
89
+ cancel: (redemptionId: string) => Promise<undefined>;
90
+ claim: (orderId: string) => Promise<LoyaltyClaim>;
91
+ storeCredit: (branchId?: string) => Promise<StoreCredit>;
92
+ onChange(listener: () => void): () => void;
93
+ };
6
94
 
7
95
  /** Store and branch menus supplied to the deterministic mock transport. */
8
96
  type MockFixtures = {
@@ -67,5 +155,5 @@ declare const fixtures: {
67
155
  };
68
156
  };
69
157
 
70
- export { createMockZappie, fixtures };
71
- export type { MockFixtures, MockOptions };
158
+ export { createMockLoyalty, createMockZappie, fixtures };
159
+ export type { MockFixtures, MockLoyaltyOptions, MockOptions };
@@ -7,6 +7,7 @@ import { delay, throwIfAborted } from "../internal/abort.js";
7
7
  import { multiplyMoney } from "../internal/money-math.js";
8
8
  import { money } from "../money.js";
9
9
  import { VERSION } from "../index.js";
10
+ import { createMockLoyalty } from "./loyalty.js";
10
11
  function createMockZappie(input, opts = {}) {
11
12
  const fixtures2 = structuredClone(input);
12
13
  const before = async (method, ctx) => {
@@ -452,6 +453,7 @@ var fixtures = {
452
453
  };
453
454
  export {
454
455
  VERSION,
456
+ createMockLoyalty,
455
457
  createMockZappie,
456
458
  fixtures
457
459
  };
@@ -0,0 +1,110 @@
1
+ // src/testing/loyalty.ts
2
+ import { ZappieError } from "../errors.js";
3
+ var MockLoyaltyError = class extends ZappieError {
4
+ constructor(status, apiCode, message) {
5
+ super(
6
+ status === 401 ? "unauthorized" : status === 404 ? "not_found" : apiCode === "scope_required" ? apiCode : status === 403 ? "forbidden" : "server_error",
7
+ message,
8
+ { status }
9
+ );
10
+ this.apiCode = apiCode;
11
+ }
12
+ };
13
+ function createMockLoyalty(options = {}) {
14
+ let points = options.points ?? 0;
15
+ let sequence = 0;
16
+ const reserved = /* @__PURE__ */ new Map();
17
+ const claimed = /* @__PURE__ */ new Set();
18
+ const listeners = /* @__PURE__ */ new Set();
19
+ const changed = () => listeners.forEach((listener) => listener());
20
+ const check = async () => {
21
+ await Promise.resolve();
22
+ if (options.failWith) {
23
+ const status = options.failWith === "customer_required" ? 401 : options.failWith.endsWith("_required") || options.failWith === "feature_off" ? 403 : 409;
24
+ throw new MockLoyaltyError(
25
+ status,
26
+ options.failWith,
27
+ `Mock ${options.failWith}`
28
+ );
29
+ }
30
+ };
31
+ const client = {
32
+ base: "/_zappie/api",
33
+ async points() {
34
+ await check();
35
+ return {
36
+ object: "loyalty",
37
+ enabled: options.enabled ?? true,
38
+ points
39
+ };
40
+ },
41
+ async perks() {
42
+ await check();
43
+ return options.enabled === false ? [] : structuredClone(options.perks ?? []);
44
+ },
45
+ async redeem(perkId) {
46
+ await check();
47
+ const perk = options.perks?.find((candidate) => candidate.id === perkId);
48
+ if (!perk) {
49
+ throw new MockLoyaltyError(404, "perk_not_found", "No such perk");
50
+ }
51
+ if (points < perk.points_cost) {
52
+ throw new MockLoyaltyError(
53
+ 409,
54
+ "insufficient_points",
55
+ "You don't have enough points for this perk."
56
+ );
57
+ }
58
+ points -= perk.points_cost;
59
+ const id = `rdm_mock${++sequence}`;
60
+ reserved.set(id, perk.points_cost);
61
+ changed();
62
+ return {
63
+ id,
64
+ object: "perk_redemption",
65
+ status: "reserved",
66
+ points_spent: perk.points_cost,
67
+ perk: { id: perk.id, name: perk.name },
68
+ expires_at: new Date(Date.now() + 864e5).toISOString()
69
+ };
70
+ },
71
+ async cancel(redemptionId) {
72
+ await check();
73
+ points += reserved.get(redemptionId) ?? 0;
74
+ reserved.delete(redemptionId);
75
+ changed();
76
+ },
77
+ async claim(orderId) {
78
+ await check();
79
+ const earned = claimed.has(orderId) ? 0 : options.claims?.[orderId] ?? 0;
80
+ claimed.add(orderId);
81
+ points += earned;
82
+ changed();
83
+ return {
84
+ object: "loyalty_claim",
85
+ order_id: orderId,
86
+ points_earned: earned,
87
+ points
88
+ };
89
+ },
90
+ async storeCredit() {
91
+ await check();
92
+ return options.storeCredit ?? {
93
+ object: "store_credit",
94
+ enabled: false,
95
+ balance: { amount_minor: 0, currency: "NGN" }
96
+ };
97
+ },
98
+ onChange(listener) {
99
+ listeners.add(listener);
100
+ return () => {
101
+ listeners.delete(listener);
102
+ };
103
+ }
104
+ };
105
+ return client;
106
+ }
107
+ export {
108
+ createMockLoyalty
109
+ };
110
+ //# sourceMappingURL=loyalty.js.map
@@ -0,0 +1,6 @@
1
+ {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AAAA,EACF;AACA,SAAO;AACT;",
5
+ "names": []
6
+ }
@@ -1,6 +1,6 @@
1
1
  import { Menu } from '../index.js';
2
2
  import { SearchRequest, SearchPage } from '../index.js';
3
- import '../types-ooHA0lwH.js';
3
+ import '../types-K01NHM_a.js';
4
4
 
5
5
  /** Loaded only when search is used; request authentication/retries stay in REST. */
6
6
  declare function searchPage(ctx: SearchRequest, read: (path: string) => Promise<unknown>, mapMenu: (value: unknown, branchId: string) => Menu, invalid: () => Error): Promise<SearchPage>;