@zappie/sdk 0.18.0 → 0.18.1
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.
- package/CHANGELOG.md +6 -0
- package/dist/account/index.js +1 -5
- package/dist/account/index.js.map +1 -1
- package/dist/account/url.js +1 -23
- package/dist/account/url.js.map +1 -1
- package/dist/branches/index.js +1 -43
- package/dist/branches/index.js.map +1 -1
- package/dist/cart/branch.js +1 -82
- package/dist/cart/branch.js.map +1 -1
- package/dist/cart/errors.js +1 -12
- package/dist/cart/errors.js.map +1 -1
- package/dist/cart/held.js +1 -17
- package/dist/cart/held.js.map +1 -1
- package/dist/cart/index.js +1 -782
- package/dist/cart/index.js.map +1 -1
- package/dist/cart/item.js +1 -11
- package/dist/cart/item.js.map +1 -1
- package/dist/cart/preview.js +1 -31
- package/dist/cart/preview.js.map +1 -1
- package/dist/cart/price.js +1 -24
- package/dist/cart/price.js.map +1 -1
- package/dist/cart/quote-client.js +1 -107
- package/dist/cart/quote-client.js.map +1 -1
- package/dist/cart/quote-response.js +1 -214
- package/dist/cart/quote-response.js.map +1 -1
- package/dist/cart/reconcile.js +1 -107
- package/dist/cart/reconcile.js.map +1 -1
- package/dist/cart/source-menu.js +1 -20
- package/dist/cart/source-menu.js.map +1 -1
- package/dist/cart/storage.js +1 -175
- package/dist/cart/storage.js.map +1 -1
- package/dist/cart/validate.js +1 -270
- package/dist/cart/validate.js.map +1 -1
- package/dist/cart/wire.js +1 -42
- package/dist/cart/wire.js.map +1 -1
- package/dist/cart/working-set.js +1 -79
- package/dist/cart/working-set.js.map +1 -1
- package/dist/checkout/client.js +1 -116
- package/dist/checkout/client.js.map +1 -1
- package/dist/checkout/embed.js +1 -247
- package/dist/checkout/embed.js.map +1 -1
- package/dist/checkout/error.js +1 -19
- package/dist/checkout/error.js.map +1 -1
- package/dist/checkout/index.js +1 -12
- package/dist/checkout/index.js.map +1 -1
- package/dist/checkout/react.js +1 -45
- package/dist/checkout/react.js.map +1 -1
- package/dist/checkout/readiness.js +1 -35
- package/dist/checkout/readiness.js.map +1 -1
- package/dist/checkout/sdk.js +1 -8
- package/dist/checkout/sdk.js.map +1 -1
- package/dist/checkout/session.js +1 -57
- package/dist/checkout/session.js.map +1 -1
- package/dist/checkout-defaults/index.js +1 -205
- package/dist/checkout-defaults/index.js.map +1 -1
- package/dist/client.js +1 -255
- package/dist/client.js.map +1 -1
- package/dist/config/index.js +1 -12
- package/dist/config/index.js.map +1 -1
- package/dist/config.js +1 -27
- package/dist/config.js.map +1 -1
- package/dist/customer/client.js +1 -180
- package/dist/customer/client.js.map +1 -1
- package/dist/customer/error.js +1 -18
- package/dist/customer/error.js.map +1 -1
- package/dist/customer/index.js +1 -7
- package/dist/customer/index.js.map +1 -1
- package/dist/customer/navigation.js +1 -39
- package/dist/customer/navigation.js.map +1 -1
- package/dist/customer/react.js +1 -69
- package/dist/customer/react.js.map +1 -1
- package/dist/customer/reorder.js +1 -60
- package/dist/customer/reorder.js.map +1 -1
- package/dist/customer/request.js +1 -37
- package/dist/customer/request.js.map +1 -1
- package/dist/customer/watch-order.js +1 -79
- package/dist/customer/watch-order.js.map +1 -1
- package/dist/debug.js +1 -77
- package/dist/debug.js.map +1 -1
- package/dist/display/index.js +1 -30
- package/dist/display/index.js.map +1 -1
- package/dist/error-pages/art.js +1 -10
- package/dist/error-pages/art.js.map +1 -1
- package/dist/error-pages/index.js +2 -103
- package/dist/error-pages/index.js.map +1 -1
- package/dist/error-pages/react.js +1 -65
- package/dist/error-pages/react.js.map +1 -1
- package/dist/errors.js +1 -70
- package/dist/errors.js.map +1 -1
- package/dist/in-venue/bill.js +1 -69
- package/dist/in-venue/bill.js.map +1 -1
- package/dist/in-venue/client.js +1 -119
- package/dist/in-venue/client.js.map +1 -1
- package/dist/in-venue/error.js +1 -18
- package/dist/in-venue/error.js.map +1 -1
- package/dist/in-venue/index.js +1 -23
- package/dist/in-venue/index.js.map +1 -1
- package/dist/in-venue/react/bill-page.js +1 -350
- package/dist/in-venue/react/bill-page.js.map +1 -1
- package/dist/in-venue/react/in-venue-page.js +1 -102
- package/dist/in-venue/react/in-venue-page.js.map +1 -1
- package/dist/in-venue/react/order-panel.js +1 -283
- package/dist/in-venue/react/order-panel.js.map +1 -1
- package/dist/in-venue/react/pay-point-page.js +1 -50
- package/dist/in-venue/react/pay-point-page.js.map +1 -1
- package/dist/in-venue/react/shared.js +2 -171
- package/dist/in-venue/react/shared.js.map +1 -1
- package/dist/in-venue/react/table-menus-page.js +1 -151
- package/dist/in-venue/react/table-menus-page.js.map +1 -1
- package/dist/in-venue/react.js +1 -14
- package/dist/in-venue/react.js.map +1 -1
- package/dist/in-venue/table.js +1 -62
- package/dist/in-venue/table.js.map +1 -1
- package/dist/in-venue/watch.js +1 -82
- package/dist/in-venue/watch.js.map +1 -1
- package/dist/index.js +1 -31
- package/dist/index.js.map +1 -1
- package/dist/integrations/index.js +1 -78
- package/dist/integrations/index.js.map +1 -1
- package/dist/internal/abort.js +1 -28
- package/dist/internal/abort.js.map +1 -1
- package/dist/internal/cache.js +1 -141
- package/dist/internal/cache.js.map +1 -1
- package/dist/internal/customer-http.js +1 -75
- package/dist/internal/customer-http.js.map +1 -1
- package/dist/internal/emitter.js +1 -26
- package/dist/internal/emitter.js.map +1 -1
- package/dist/internal/image-widths.js +1 -5
- package/dist/internal/image-widths.js.map +1 -1
- package/dist/internal/money-math.js +1 -29
- package/dist/internal/money-math.js.map +1 -1
- package/dist/internal/perk-hold.js +1 -34
- package/dist/internal/perk-hold.js.map +1 -1
- package/dist/internal/remembered-address.js +1 -68
- package/dist/internal/remembered-address.js.map +1 -1
- package/dist/internal/return-path.js +1 -16
- package/dist/internal/return-path.js.map +1 -1
- package/dist/internal/service-url.js +1 -10
- package/dist/internal/service-url.js.map +1 -1
- package/dist/internal.js +1 -8
- package/dist/internal.js.map +1 -1
- package/dist/loyalty/cart.js +1 -55
- package/dist/loyalty/cart.js.map +1 -1
- package/dist/loyalty/client.js +1 -88
- package/dist/loyalty/client.js.map +1 -1
- package/dist/loyalty/index.js +1 -12
- package/dist/loyalty/index.js.map +1 -1
- package/dist/loyalty/react.js +1 -199
- package/dist/loyalty/react.js.map +1 -1
- package/dist/loyalty/release.js +1 -42
- package/dist/loyalty/release.js.map +1 -1
- package/dist/money.js +1 -46
- package/dist/money.js.map +1 -1
- package/dist/navigation/index.js +1 -55
- package/dist/navigation/index.js.map +1 -1
- package/dist/navigation/react.js +1 -17
- package/dist/navigation/react.js.map +1 -1
- package/dist/navigation-progress/index.js +1 -41
- package/dist/navigation-progress/index.js.map +1 -1
- package/dist/options/index.js +1 -103
- package/dist/options/index.js.map +1 -1
- package/dist/persist/catalogue.js +1 -205
- package/dist/persist/catalogue.js.map +1 -1
- package/dist/places/client.js +1 -96
- package/dist/places/client.js.map +1 -1
- package/dist/places/error.js +1 -18
- package/dist/places/error.js.map +1 -1
- package/dist/places/index.js +1 -7
- package/dist/places/index.js.map +1 -1
- package/dist/places/request.js +1 -39
- package/dist/places/request.js.map +1 -1
- package/dist/places/sdk.js +1 -9
- package/dist/places/sdk.js.map +1 -1
- package/dist/places/search.js +1 -79
- package/dist/places/search.js.map +1 -1
- package/dist/pricing/index.js +1 -80
- package/dist/pricing/index.js.map +1 -1
- package/dist/react/cart.js +1 -40
- package/dist/react/cart.js.map +1 -1
- package/dist/react/changes.js +1 -93
- package/dist/react/changes.js.map +1 -1
- package/dist/react/hooks.js +1 -90
- package/dist/react/hooks.js.map +1 -1
- package/dist/react/index.js +1 -19
- package/dist/react/index.js.map +1 -1
- package/dist/react/provider.js +1 -33
- package/dist/react/provider.js.map +1 -1
- package/dist/react/rollback.js +1 -89
- package/dist/react/rollback.js.map +1 -1
- package/dist/receipts/index.js +1 -48
- package/dist/receipts/index.js.map +1 -1
- package/dist/redirect/index.js +1 -30
- package/dist/redirect/index.js.map +1 -1
- package/dist/server/auth/crypto.js +1 -105
- package/dist/server/auth/crypto.js.map +1 -1
- package/dist/server/auth/jwt.js +1 -203
- package/dist/server/auth/jwt.js.map +1 -1
- package/dist/server/auth/session-store.js +1 -45
- package/dist/server/auth/session-store.js.map +1 -1
- package/dist/server/chosen-branch.js +1 -69
- package/dist/server/chosen-branch.js.map +1 -1
- package/dist/server/edge-cache.js +1 -394
- package/dist/server/edge-cache.js.map +1 -1
- package/dist/server/edge-snapshot.js +1 -199
- package/dist/server/edge-snapshot.js.map +1 -1
- package/dist/server/index.js +1 -113
- package/dist/server/index.js.map +1 -1
- package/dist/server/security.js +1 -135
- package/dist/server/security.js.map +1 -1
- package/dist/server/sign-in.js +1 -17
- package/dist/server/sign-in.js.map +1 -1
- package/dist/server/storefront-url/build-v1.js +1 -65
- package/dist/server/storefront-url/build-v1.js.map +1 -1
- package/dist/server/storefront-url/build-v2.js +1 -50
- package/dist/server/storefront-url/build-v2.js.map +1 -1
- package/dist/server/storefront-url/build.js +1 -18
- package/dist/server/storefront-url/build.js.map +1 -1
- package/dist/server/storefront-url/canonical.js +1 -35
- package/dist/server/storefront-url/canonical.js.map +1 -1
- package/dist/server/storefront-url/contract.js +1 -24
- package/dist/server/storefront-url/contract.js.map +1 -1
- package/dist/server/storefront-url/index.js +1 -15
- package/dist/server/storefront-url/index.js.map +1 -1
- package/dist/server/storefront-url/installation.js +1 -57
- package/dist/server/storefront-url/installation.js.map +1 -1
- package/dist/server/storefront-url/params.js +1 -88
- package/dist/server/storefront-url/params.js.map +1 -1
- package/dist/server/storefront-url/parse-v1.js +1 -137
- package/dist/server/storefront-url/parse-v1.js.map +1 -1
- package/dist/server/storefront-url/parse-v2.js +1 -84
- package/dist/server/storefront-url/parse-v2.js.map +1 -1
- package/dist/server/storefront-url/parse.js +1 -8
- package/dist/server/storefront-url/parse.js.map +1 -1
- package/dist/server/storefront-url/public-id.js +1 -7
- package/dist/server/storefront-url/public-id.js.map +1 -1
- package/dist/server/storefront-url/redirect.js +1 -43
- package/dist/server/storefront-url/redirect.js.map +1 -1
- package/dist/server/storefront-url/sign-in.js +1 -17
- package/dist/server/storefront-url/sign-in.js.map +1 -1
- package/dist/server/storefront-url/types.js +1 -55
- package/dist/server/storefront-url/types.js.map +1 -1
- package/dist/server/storefront-url/url.js +1 -73
- package/dist/server/storefront-url/url.js.map +1 -1
- package/dist/server/webhook.js +1 -95
- package/dist/server/webhook.js.map +1 -1
- package/dist/services/index.js +1 -18
- package/dist/services/index.js.map +1 -1
- package/dist/site-closed/index.js +1 -38
- package/dist/site-closed/index.js.map +1 -1
- package/dist/site-config/helpers.js +1 -58
- package/dist/site-config/helpers.js.map +1 -1
- package/dist/site-config/sections.js +1 -114
- package/dist/site-config/sections.js.map +1 -1
- package/dist/site-config/types.js +1 -31
- package/dist/site-config/types.js.map +1 -1
- package/dist/site-config/validate.js +1 -215
- package/dist/site-config/validate.js.map +1 -1
- package/dist/site-error/index.js +1 -32
- package/dist/site-error/index.js.map +1 -1
- package/dist/site-error/react.js +1 -14
- package/dist/site-error/react.js.map +1 -1
- package/dist/studio/index.js +1 -315
- package/dist/template/index.js +1 -88
- package/dist/template/index.js.map +1 -1
- package/dist/template/react.js +1 -111
- package/dist/template/react.js.map +1 -1
- package/dist/testing/index.js +1 -459
- package/dist/testing/loyalty.js +1 -109
- package/dist/testing/loyalty.js.map +1 -1
- package/dist/transport/category-page.js +1 -24
- package/dist/transport/category-page.js.map +1 -1
- package/dist/transport/mappers.js +1 -356
- package/dist/transport/mappers.js.map +1 -1
- package/dist/transport/presentation.js +1 -67
- package/dist/transport/presentation.js.map +1 -1
- package/dist/transport/quote-body.js +1 -23
- package/dist/transport/quote-body.js.map +1 -1
- package/dist/transport/rest.js +1 -327
- package/dist/transport/rest.js.map +1 -1
- package/dist/transport/search.js +1 -36
- package/dist/transport/search.js.map +1 -1
- package/dist/transport/selected-menu.js +1 -83
- package/dist/transport/selected-menu.js.map +1 -1
- package/dist/transport/store.js +1 -132
- package/dist/transport/store.js.map +1 -1
- package/dist/uploads/index.js +1 -36
- package/dist/uploads/index.js.map +1 -1
- package/dist/url/index.js +1 -15
- package/dist/url/index.js.map +1 -1
- package/dist/visits/index.js +1 -61
- package/dist/visits/index.js.map +1 -1
- package/dist/visits/page-views.js +1 -102
- package/dist/visits/page-views.js.map +1 -1
- package/dist/vite/index.js +3 -373
- package/package.json +1 -1
package/dist/cart/index.js
CHANGED
|
@@ -1,783 +1,2 @@
|
|
|
1
|
-
// src/cart/index.ts
|
|
2
|
-
import { asError, ZappieError } from "../errors.js";
|
|
3
|
-
import { multiplyMoney, sumMoney } from "../internal/money-math.js";
|
|
4
|
-
import { money } from "../money.js";
|
|
5
|
-
import { ZappieCartError } from "./errors.js";
|
|
6
|
-
import { estimateUnitPrice } from "./price.js";
|
|
7
|
-
import { freezeLine, lineInput, reconcile } from "./reconcile.js";
|
|
8
|
-
import { createCartStorage, parseCart, validFulfilment } from "./storage.js";
|
|
9
|
-
import {
|
|
10
|
-
issue,
|
|
11
|
-
normalizeInput,
|
|
12
|
-
resolveVariant,
|
|
13
|
-
validateLine
|
|
14
|
-
} from "./validate.js";
|
|
15
|
-
import { wireFulfilment, wireLine } from "./wire.js";
|
|
16
|
-
var EMPTY_CART = deepFreeze({
|
|
17
|
-
branchId: void 0,
|
|
18
|
-
lines: [],
|
|
19
|
-
count: 0,
|
|
20
|
-
subtotal: null,
|
|
21
|
-
fulfilment: null,
|
|
22
|
-
promoCode: null,
|
|
23
|
-
perks: [],
|
|
24
|
-
state: { status: "ready" },
|
|
25
|
-
issues: [],
|
|
26
|
-
isHydrated: false
|
|
27
|
-
});
|
|
28
|
-
function deepFreeze(value) {
|
|
29
|
-
if (value && typeof value === "object" && !Object.isFrozen(value)) {
|
|
30
|
-
Object.freeze(value);
|
|
31
|
-
for (const child of Object.values(value)) {
|
|
32
|
-
deepFreeze(child);
|
|
33
|
-
}
|
|
34
|
-
}
|
|
35
|
-
return value;
|
|
36
|
-
}
|
|
37
|
-
function identity(input) {
|
|
38
|
-
return JSON.stringify([
|
|
39
|
-
input.itemId,
|
|
40
|
-
input.menuId,
|
|
41
|
-
input.variantId,
|
|
42
|
-
input.note ?? "",
|
|
43
|
-
[...input.choices ?? []].sort(
|
|
44
|
-
(a, b) => a.groupId.localeCompare(b.groupId) || a.choiceId.localeCompare(b.choiceId)
|
|
45
|
-
),
|
|
46
|
-
Object.entries(input.inputs ?? {}).sort(([a], [b]) => a.localeCompare(b))
|
|
47
|
-
]);
|
|
48
|
-
}
|
|
49
|
-
function createCart(deps) {
|
|
50
|
-
const { config, menu: menus, store, events } = deps;
|
|
51
|
-
const ttl = config.cart?.ttl ?? 7 * 24 * 60 * 60 * 1e3;
|
|
52
|
-
if (!Number.isFinite(ttl) || ttl <= 0) {
|
|
53
|
-
throw new ZappieError(
|
|
54
|
-
"invalid_request",
|
|
55
|
-
"Cart ttl must be positive milliseconds"
|
|
56
|
-
);
|
|
57
|
-
}
|
|
58
|
-
let snapshot = EMPTY_CART;
|
|
59
|
-
let menu;
|
|
60
|
-
let branch;
|
|
61
|
-
let selected = config.branch;
|
|
62
|
-
let updatedAt = 0;
|
|
63
|
-
let timer;
|
|
64
|
-
let revision = 0;
|
|
65
|
-
let quoteRevision = 0;
|
|
66
|
-
let moveSequence = 0;
|
|
67
|
-
let refreshSequence = 0;
|
|
68
|
-
let chased;
|
|
69
|
-
let chasedAt = 0;
|
|
70
|
-
let mounted = 0;
|
|
71
|
-
let detach;
|
|
72
|
-
let hydration;
|
|
73
|
-
let lifecycle = 0;
|
|
74
|
-
let legacy;
|
|
75
|
-
const listeners = /* @__PURE__ */ new Set();
|
|
76
|
-
const prefix = `zappie:cart:v1:${config.store}:`;
|
|
77
|
-
const scope = config.cart?.storageScope;
|
|
78
|
-
const keyFor = (id) => `${prefix}${id}${scope ? `:${scope}` : ""}`;
|
|
79
|
-
const key = () => keyFor(branch.id);
|
|
80
|
-
const storage = createCartStorage(
|
|
81
|
-
config.storage,
|
|
82
|
-
(message) => events.emit("warning", { message })
|
|
83
|
-
);
|
|
84
|
-
const readSaved = (id) => {
|
|
85
|
-
let raw = storage.read(keyFor(id));
|
|
86
|
-
if (raw === null && scope) {
|
|
87
|
-
raw = storage.read(prefix + id);
|
|
88
|
-
if (raw !== null) {
|
|
89
|
-
storage.remove(prefix + id);
|
|
90
|
-
storage.write(keyFor(id), raw);
|
|
91
|
-
}
|
|
92
|
-
}
|
|
93
|
-
return raw;
|
|
94
|
-
};
|
|
95
|
-
let quotes;
|
|
96
|
-
let loadingQuotes;
|
|
97
|
-
const quoteClient = () => loadingQuotes ?? (loadingQuotes = import("./quote-client.js").then(
|
|
98
|
-
({ createQuoteClient }) => quotes = createQuoteClient(deps.transport, deps.context, config),
|
|
99
|
-
(error) => {
|
|
100
|
-
loadingQuotes = void 0;
|
|
101
|
-
throw error;
|
|
102
|
-
}
|
|
103
|
-
));
|
|
104
|
-
const publish = (patch) => {
|
|
105
|
-
snapshot = deepFreeze({
|
|
106
|
-
...snapshot,
|
|
107
|
-
...patch,
|
|
108
|
-
branchId: branch?.id
|
|
109
|
-
});
|
|
110
|
-
for (const fn of [...listeners]) {
|
|
111
|
-
try {
|
|
112
|
-
fn();
|
|
113
|
-
} catch (error) {
|
|
114
|
-
events.emit("error", { error: asError(error) });
|
|
115
|
-
}
|
|
116
|
-
}
|
|
117
|
-
};
|
|
118
|
-
const attention = (issues, quote) => issues.some((i) => i.severity !== "info") ? { status: "needs_attention", issues, ...quote ? { quote } : {} } : quote ? { status: "quoted", quote } : { status: "ready" };
|
|
119
|
-
const cancel = () => {
|
|
120
|
-
revision++;
|
|
121
|
-
quoteRevision++;
|
|
122
|
-
clearTimeout(timer);
|
|
123
|
-
quotes?.cancel();
|
|
124
|
-
};
|
|
125
|
-
const wire = () => ({
|
|
126
|
-
lines: snapshot.lines.map(wireLine),
|
|
127
|
-
...snapshot.promoCode ? { promo_code: snapshot.promoCode } : {},
|
|
128
|
-
...snapshot.perks.length && snapshot.fulfilment?.type != "dine_in" ? { perk_redemption_ids: snapshot.perks.map((p) => p.redemptionId) } : {},
|
|
129
|
-
menu_version: menu.version
|
|
130
|
-
});
|
|
131
|
-
const persist = () => {
|
|
132
|
-
const value = {
|
|
133
|
-
v: 1,
|
|
134
|
-
lines: snapshot.lines.map((line) => ({
|
|
135
|
-
...lineInput(line),
|
|
136
|
-
id: line.id,
|
|
137
|
-
name: line.name,
|
|
138
|
-
addedAt: line.addedAt,
|
|
139
|
-
unitPrice: line.unitPrice
|
|
140
|
-
})),
|
|
141
|
-
fulfilment: snapshot.fulfilment,
|
|
142
|
-
promoCode: snapshot.promoCode,
|
|
143
|
-
perks: snapshot.perks,
|
|
144
|
-
menuVersion: menu.version,
|
|
145
|
-
updatedAt
|
|
146
|
-
};
|
|
147
|
-
storage.write(key(), JSON.stringify(value));
|
|
148
|
-
};
|
|
149
|
-
const schedule = () => {
|
|
150
|
-
clearTimeout(timer);
|
|
151
|
-
if (snapshot.lines.length) {
|
|
152
|
-
timer = setTimeout(() => {
|
|
153
|
-
void cart.quote().catch(() => {
|
|
154
|
-
});
|
|
155
|
-
}, 300);
|
|
156
|
-
}
|
|
157
|
-
};
|
|
158
|
-
const resume = () => {
|
|
159
|
-
if (!("quote" in snapshot.state)) {
|
|
160
|
-
schedule();
|
|
161
|
-
}
|
|
162
|
-
};
|
|
163
|
-
const recompute = (lines, pending = snapshot.issues.filter((i) => i.source === "local"), patch = {}) => {
|
|
164
|
-
const currency = store.peek().currency;
|
|
165
|
-
const result = reconcile(lines, menu, branch, currency, pending);
|
|
166
|
-
const subtotal = result.priced ? sumMoney(
|
|
167
|
-
result.lines.map((l) => l.lineSubtotal),
|
|
168
|
-
money(0, currency)
|
|
169
|
-
) : null;
|
|
170
|
-
publish({
|
|
171
|
-
...patch,
|
|
172
|
-
lines: result.lines,
|
|
173
|
-
count: result.lines.reduce((n, l) => n + l.quantity, 0),
|
|
174
|
-
subtotal,
|
|
175
|
-
issues: result.issues,
|
|
176
|
-
state: attention(result.issues)
|
|
177
|
-
});
|
|
178
|
-
for (const i of result.issues) {
|
|
179
|
-
events.emit("cart_issue", { code: i.code });
|
|
180
|
-
}
|
|
181
|
-
};
|
|
182
|
-
const changed = (lines = snapshot.lines, patch = {}) => {
|
|
183
|
-
cancel();
|
|
184
|
-
recompute(lines, void 0, patch);
|
|
185
|
-
updatedAt = Date.now();
|
|
186
|
-
persist();
|
|
187
|
-
schedule();
|
|
188
|
-
};
|
|
189
|
-
const choose = (value) => {
|
|
190
|
-
const found = store.peek()?.branches.find((b) => b.id === value.branchId);
|
|
191
|
-
if (!found) {
|
|
192
|
-
throw new ZappieError(
|
|
193
|
-
"branch_not_found",
|
|
194
|
-
"Load the storefront branch before using its cart"
|
|
195
|
-
);
|
|
196
|
-
}
|
|
197
|
-
menu = value;
|
|
198
|
-
branch = found;
|
|
199
|
-
selected = found.id;
|
|
200
|
-
};
|
|
201
|
-
const load = (raw, writeBack = true) => {
|
|
202
|
-
cancel();
|
|
203
|
-
let saved;
|
|
204
|
-
try {
|
|
205
|
-
saved = raw ? parseCart(raw) : void 0;
|
|
206
|
-
if (saved && Date.now() - saved.updatedAt > ttl) {
|
|
207
|
-
saved = void 0;
|
|
208
|
-
storage.remove(key());
|
|
209
|
-
events.emit("cart_expired", { branchId: branch.id });
|
|
210
|
-
}
|
|
211
|
-
} catch {
|
|
212
|
-
storage.remove(key());
|
|
213
|
-
storage.warning("Invalid saved cart discarded");
|
|
214
|
-
}
|
|
215
|
-
updatedAt = saved?.updatedAt ?? Date.now();
|
|
216
|
-
const idle = Date.now() - updatedAt;
|
|
217
|
-
let fulfilment = saved?.fulfilment ?? null;
|
|
218
|
-
if (fulfilment?.branchId !== branch.id || idle > 864e5 && fulfilment.type === "delivery") {
|
|
219
|
-
fulfilment = null;
|
|
220
|
-
}
|
|
221
|
-
if (fulfilment && "scheduledFor" in fulfilment && fulfilment.scheduledFor && Date.parse(fulfilment.scheduledFor) < Date.now()) {
|
|
222
|
-
fulfilment = { ...fulfilment };
|
|
223
|
-
delete fulfilment.scheduledFor;
|
|
224
|
-
}
|
|
225
|
-
const lines = (saved?.lines ?? []).map((line) => ({
|
|
226
|
-
...line,
|
|
227
|
-
...idle > 864e5 ? { inputs: {} } : {}
|
|
228
|
-
}));
|
|
229
|
-
const result = reconcile(lines, menu, branch, store.peek().currency);
|
|
230
|
-
recompute(result.lines, result.issues, {
|
|
231
|
-
fulfilment,
|
|
232
|
-
promoCode: saved?.promoCode ?? null,
|
|
233
|
-
perks: saved?.perks ?? [],
|
|
234
|
-
isHydrated: true
|
|
235
|
-
});
|
|
236
|
-
if (raw !== null && writeBack) {
|
|
237
|
-
persist();
|
|
238
|
-
}
|
|
239
|
-
storage.sweep(prefix, key(), ttl);
|
|
240
|
-
};
|
|
241
|
-
const ensure = () => {
|
|
242
|
-
const id = branch?.id ?? store.peek()?.branches.find(
|
|
243
|
-
(b) => b.id === selected || b.slug === selected || !selected && b.isDefault
|
|
244
|
-
)?.id ?? (!selected ? store.peek()?.branches[0]?.id : void 0);
|
|
245
|
-
if (snapshot.isHydrated) {
|
|
246
|
-
return;
|
|
247
|
-
}
|
|
248
|
-
const loaded = menu ?? (id ? deps.workingSet.peek(id, []) : void 0);
|
|
249
|
-
if (!loaded || !store.peek()) {
|
|
250
|
-
throw new ZappieError(
|
|
251
|
-
"invalid_request",
|
|
252
|
-
"Load the store and menu before editing the cart"
|
|
253
|
-
);
|
|
254
|
-
}
|
|
255
|
-
choose(loaded);
|
|
256
|
-
const raw = readSaved(branch.id);
|
|
257
|
-
let migrated = [];
|
|
258
|
-
if (raw === null && legacy) {
|
|
259
|
-
try {
|
|
260
|
-
migrated = legacy(storage.read);
|
|
261
|
-
} catch {
|
|
262
|
-
storage.warning("Invalid legacy cart discarded");
|
|
263
|
-
}
|
|
264
|
-
}
|
|
265
|
-
load(raw);
|
|
266
|
-
if (raw === null && legacy) {
|
|
267
|
-
persist();
|
|
268
|
-
}
|
|
269
|
-
for (const input of migrated.slice(0, 100)) {
|
|
270
|
-
try {
|
|
271
|
-
cart.add(input.itemId, input);
|
|
272
|
-
} catch {
|
|
273
|
-
events.emit("cart_issue", { code: "item_unavailable" });
|
|
274
|
-
}
|
|
275
|
-
}
|
|
276
|
-
};
|
|
277
|
-
const refresh = async (target) => {
|
|
278
|
-
const id = branch?.id;
|
|
279
|
-
const seq = moveSequence;
|
|
280
|
-
const request = ++refreshSequence;
|
|
281
|
-
const rev = revision;
|
|
282
|
-
if (!id || !menu) {
|
|
283
|
-
return;
|
|
284
|
-
}
|
|
285
|
-
if (!snapshot.lines.length) {
|
|
286
|
-
return;
|
|
287
|
-
}
|
|
288
|
-
if (menu.completeness !== "partial") {
|
|
289
|
-
const version = await deps.transport.getMenuVersion({
|
|
290
|
-
...deps.context(),
|
|
291
|
-
branchId: id
|
|
292
|
-
});
|
|
293
|
-
if (version.version === menu.version) {
|
|
294
|
-
return;
|
|
295
|
-
}
|
|
296
|
-
target = version.version;
|
|
297
|
-
}
|
|
298
|
-
if (target && target === chased && Date.now() - chasedAt < 3e4) {
|
|
299
|
-
return;
|
|
300
|
-
}
|
|
301
|
-
chased = target;
|
|
302
|
-
chasedAt = Date.now();
|
|
303
|
-
const value = await deps.workingSet.read(
|
|
304
|
-
id,
|
|
305
|
-
snapshot.lines.map((l) => l.itemId),
|
|
306
|
-
true
|
|
307
|
-
);
|
|
308
|
-
if (seq !== moveSequence || request !== refreshSequence || rev !== revision || JSON.stringify(value) === JSON.stringify(menu)) {
|
|
309
|
-
return;
|
|
310
|
-
}
|
|
311
|
-
menu = value;
|
|
312
|
-
cancel();
|
|
313
|
-
recompute(snapshot.lines);
|
|
314
|
-
persist();
|
|
315
|
-
schedule();
|
|
316
|
-
};
|
|
317
|
-
const current = (itemId) => {
|
|
318
|
-
const candidate = deps.workingSet.peek(branch.id, [
|
|
319
|
-
...snapshot.lines.map((l) => l.itemId),
|
|
320
|
-
itemId
|
|
321
|
-
]);
|
|
322
|
-
if (candidate.items[itemId]) {
|
|
323
|
-
menu = candidate;
|
|
324
|
-
}
|
|
325
|
-
};
|
|
326
|
-
const validated = (raw, id, addedAt) => {
|
|
327
|
-
current(raw.itemId);
|
|
328
|
-
const item = Object.hasOwn(menu.items, raw.itemId) ? menu.items[raw.itemId] : void 0;
|
|
329
|
-
const problems = validateLine(item, raw, { menu, branch });
|
|
330
|
-
if (problems.length || !item) {
|
|
331
|
-
throw new ZappieCartError(problems);
|
|
332
|
-
}
|
|
333
|
-
const input = normalizeInput(item, raw);
|
|
334
|
-
const variant = resolveVariant(item, input);
|
|
335
|
-
const choices = (input.choices ?? []).map((c) => ({
|
|
336
|
-
...c,
|
|
337
|
-
quantity: c.quantity ?? 1
|
|
338
|
-
}));
|
|
339
|
-
const unitPrice = estimateUnitPrice(item, {
|
|
340
|
-
choices,
|
|
341
|
-
variantId: variant.id
|
|
342
|
-
});
|
|
343
|
-
return freezeLine({
|
|
344
|
-
id: id ?? `line_${Array.from(globalThis.crypto.getRandomValues(new Uint8Array(10)), (byte) => (byte % 36).toString(36)).join("")}`,
|
|
345
|
-
itemId: item.id,
|
|
346
|
-
...input.menuId !== void 0 ? { menuId: input.menuId } : {},
|
|
347
|
-
name: item.name,
|
|
348
|
-
quantity: input.quantity,
|
|
349
|
-
choices,
|
|
350
|
-
inputs: input.inputs ?? {},
|
|
351
|
-
variantId: variant.id,
|
|
352
|
-
...input.note !== void 0 ? { note: input.note } : {},
|
|
353
|
-
unitPrice,
|
|
354
|
-
lineSubtotal: multiplyMoney(unitPrice, input.quantity),
|
|
355
|
-
addedAt: addedAt ?? (/* @__PURE__ */ new Date()).toISOString()
|
|
356
|
-
});
|
|
357
|
-
};
|
|
358
|
-
const offMenu = events.on("menu:updated", ({ branchId, version }) => {
|
|
359
|
-
if (branch?.id === branchId) {
|
|
360
|
-
const value = menus.peek(branchId);
|
|
361
|
-
if (value && value.completeness !== "partial" && value.version === version && value.version !== menu?.version) {
|
|
362
|
-
refreshSequence++;
|
|
363
|
-
menu = value;
|
|
364
|
-
cancel();
|
|
365
|
-
recompute(snapshot.lines);
|
|
366
|
-
persist();
|
|
367
|
-
schedule();
|
|
368
|
-
}
|
|
369
|
-
}
|
|
370
|
-
});
|
|
371
|
-
const cart = {
|
|
372
|
-
getSnapshot: () => snapshot,
|
|
373
|
-
subscribe(fn) {
|
|
374
|
-
listeners.add(fn);
|
|
375
|
-
return () => {
|
|
376
|
-
listeners.delete(fn);
|
|
377
|
-
};
|
|
378
|
-
},
|
|
379
|
-
async hydrate() {
|
|
380
|
-
if (snapshot.isHydrated) {
|
|
381
|
-
resume();
|
|
382
|
-
return refresh();
|
|
383
|
-
}
|
|
384
|
-
const life = lifecycle;
|
|
385
|
-
hydration ?? (hydration = (async () => {
|
|
386
|
-
const value = await store.get();
|
|
387
|
-
const target = value.branches.find(
|
|
388
|
-
(b) => b.id === selected || b.slug === selected
|
|
389
|
-
) ?? (!selected ? value.branches.find((b) => b.isDefault) ?? value.branches[0] : void 0);
|
|
390
|
-
if (!target) {
|
|
391
|
-
throw new ZappieError(
|
|
392
|
-
"branch_not_found",
|
|
393
|
-
"Cart branch is unavailable"
|
|
394
|
-
);
|
|
395
|
-
}
|
|
396
|
-
let inputs = snapshot.lines;
|
|
397
|
-
if (!snapshot.isHydrated) {
|
|
398
|
-
const raw = readSaved(target.id);
|
|
399
|
-
try {
|
|
400
|
-
const saved = raw ? parseCart(raw) : void 0;
|
|
401
|
-
inputs = saved && Date.now() - saved.updatedAt <= ttl ? saved.lines : raw === null ? legacy?.(storage.read) ?? [] : [];
|
|
402
|
-
} catch {
|
|
403
|
-
inputs = [];
|
|
404
|
-
}
|
|
405
|
-
}
|
|
406
|
-
const loaded = await deps.workingSet.read(
|
|
407
|
-
target.id,
|
|
408
|
-
inputs.map((l) => l.itemId)
|
|
409
|
-
);
|
|
410
|
-
if (life !== lifecycle) {
|
|
411
|
-
return;
|
|
412
|
-
}
|
|
413
|
-
choose(loaded);
|
|
414
|
-
ensure();
|
|
415
|
-
resume();
|
|
416
|
-
if (loaded.completeness !== "partial") {
|
|
417
|
-
await refresh();
|
|
418
|
-
}
|
|
419
|
-
})().finally(() => {
|
|
420
|
-
hydration = void 0;
|
|
421
|
-
}));
|
|
422
|
-
return hydration;
|
|
423
|
-
},
|
|
424
|
-
mount() {
|
|
425
|
-
mounted++;
|
|
426
|
-
if (!detach && typeof window !== "undefined") {
|
|
427
|
-
const onStorage = (event) => {
|
|
428
|
-
if (branch && event.key === key() && storage.accepts(event.storageArea)) {
|
|
429
|
-
const raw = event.newValue;
|
|
430
|
-
let ids;
|
|
431
|
-
try {
|
|
432
|
-
ids = raw ? parseCart(raw).lines.map((l) => l.itemId) : [];
|
|
433
|
-
} catch {
|
|
434
|
-
load(raw, false);
|
|
435
|
-
return;
|
|
436
|
-
}
|
|
437
|
-
const cached = deps.workingSet.peek(branch.id, ids);
|
|
438
|
-
if (cached.completeness !== "partial" || ids.every((id) => cached.items[id])) {
|
|
439
|
-
menu = cached;
|
|
440
|
-
load(raw, false);
|
|
441
|
-
schedule();
|
|
442
|
-
return;
|
|
443
|
-
}
|
|
444
|
-
const rev = revision;
|
|
445
|
-
const request = ++refreshSequence;
|
|
446
|
-
const life = lifecycle;
|
|
447
|
-
void deps.workingSet.read(branch.id, ids).then((value) => {
|
|
448
|
-
if (life === lifecycle && rev === revision && request === refreshSequence) {
|
|
449
|
-
menu = value;
|
|
450
|
-
load(raw, false);
|
|
451
|
-
schedule();
|
|
452
|
-
}
|
|
453
|
-
}).catch(
|
|
454
|
-
(error) => events.emit("error", { error: asError(error) })
|
|
455
|
-
);
|
|
456
|
-
}
|
|
457
|
-
};
|
|
458
|
-
const onFocus = () => {
|
|
459
|
-
void refresh().catch(
|
|
460
|
-
(error) => events.emit("error", { error: asError(error) })
|
|
461
|
-
);
|
|
462
|
-
};
|
|
463
|
-
window.addEventListener("storage", onStorage);
|
|
464
|
-
window.addEventListener("focus", onFocus);
|
|
465
|
-
detach = () => {
|
|
466
|
-
window.removeEventListener("storage", onStorage);
|
|
467
|
-
window.removeEventListener("focus", onFocus);
|
|
468
|
-
};
|
|
469
|
-
}
|
|
470
|
-
if (mounted === 1) {
|
|
471
|
-
void cart.hydrate().catch(
|
|
472
|
-
(error) => events.emit("error", { error: asError(error) })
|
|
473
|
-
);
|
|
474
|
-
}
|
|
475
|
-
let active = true;
|
|
476
|
-
return () => {
|
|
477
|
-
if (active) {
|
|
478
|
-
active = false;
|
|
479
|
-
mounted--;
|
|
480
|
-
if (mounted === 0) {
|
|
481
|
-
detach?.();
|
|
482
|
-
detach = void 0;
|
|
483
|
-
cancel();
|
|
484
|
-
}
|
|
485
|
-
}
|
|
486
|
-
};
|
|
487
|
-
},
|
|
488
|
-
dispose() {
|
|
489
|
-
lifecycle++;
|
|
490
|
-
moveSequence++;
|
|
491
|
-
offMenu();
|
|
492
|
-
cancel();
|
|
493
|
-
detach?.();
|
|
494
|
-
detach = void 0;
|
|
495
|
-
listeners.clear();
|
|
496
|
-
},
|
|
497
|
-
validate(input) {
|
|
498
|
-
ensure();
|
|
499
|
-
current(input.itemId);
|
|
500
|
-
const problems = validateLine(
|
|
501
|
-
Object.hasOwn(menu.items, input.itemId) ? menu.items[input.itemId] : void 0,
|
|
502
|
-
input,
|
|
503
|
-
{ menu, branch }
|
|
504
|
-
);
|
|
505
|
-
return problems.length ? { ok: false, issues: problems } : { ok: true };
|
|
506
|
-
},
|
|
507
|
-
add(item, input = {}) {
|
|
508
|
-
ensure();
|
|
509
|
-
let line = validated({
|
|
510
|
-
...input,
|
|
511
|
-
itemId: typeof item === "string" ? item : item.id
|
|
512
|
-
});
|
|
513
|
-
const existing = snapshot.lines.find(
|
|
514
|
-
(l) => identity(lineInput(l)) === identity(lineInput(line))
|
|
515
|
-
);
|
|
516
|
-
if (existing) {
|
|
517
|
-
line = validated(
|
|
518
|
-
{ ...lineInput(line), quantity: existing.quantity + line.quantity },
|
|
519
|
-
existing.id,
|
|
520
|
-
existing.addedAt
|
|
521
|
-
);
|
|
522
|
-
} else if (snapshot.lines.length >= 100) {
|
|
523
|
-
throw new ZappieCartError([
|
|
524
|
-
issue("quantity_limit", "A cart can contain at most 100 lines")
|
|
525
|
-
]);
|
|
526
|
-
}
|
|
527
|
-
changed(
|
|
528
|
-
existing ? snapshot.lines.map((l) => l.id === existing.id ? line : l) : [...snapshot.lines, line]
|
|
529
|
-
);
|
|
530
|
-
events.emit("add_to_cart", {
|
|
531
|
-
itemId: line.itemId,
|
|
532
|
-
quantity: line.quantity - (existing?.quantity ?? 0),
|
|
533
|
-
value: multiplyMoney(
|
|
534
|
-
line.unitPrice,
|
|
535
|
-
line.quantity - (existing?.quantity ?? 0)
|
|
536
|
-
)
|
|
537
|
-
});
|
|
538
|
-
return line;
|
|
539
|
-
},
|
|
540
|
-
update(lineId, patch) {
|
|
541
|
-
ensure();
|
|
542
|
-
const old = snapshot.lines.find((l) => l.id === lineId);
|
|
543
|
-
if (!old) {
|
|
544
|
-
throw new ZappieCartError([
|
|
545
|
-
issue("item_not_found", "Cart line not found")
|
|
546
|
-
]);
|
|
547
|
-
}
|
|
548
|
-
const input = { ...lineInput(old), ...patch };
|
|
549
|
-
if (patch.choices && !patch.variantId) {
|
|
550
|
-
delete input.variantId;
|
|
551
|
-
}
|
|
552
|
-
let line = validated(input, old.id, old.addedAt);
|
|
553
|
-
const duplicate = snapshot.lines.find(
|
|
554
|
-
(l) => l.id !== lineId && identity(lineInput(l)) === identity(lineInput(line))
|
|
555
|
-
);
|
|
556
|
-
if (duplicate) {
|
|
557
|
-
line = validated(
|
|
558
|
-
{ ...lineInput(line), quantity: line.quantity + duplicate.quantity },
|
|
559
|
-
old.id,
|
|
560
|
-
old.addedAt
|
|
561
|
-
);
|
|
562
|
-
}
|
|
563
|
-
changed(
|
|
564
|
-
snapshot.lines.filter((l) => l.id !== duplicate?.id).map((l) => l.id === lineId ? line : l)
|
|
565
|
-
);
|
|
566
|
-
events.emit("update_cart_line", {
|
|
567
|
-
lineId,
|
|
568
|
-
itemId: line.itemId,
|
|
569
|
-
quantity: line.quantity
|
|
570
|
-
});
|
|
571
|
-
return line;
|
|
572
|
-
},
|
|
573
|
-
remove(lineId) {
|
|
574
|
-
ensure();
|
|
575
|
-
const line = snapshot.lines.find((l) => l.id === lineId);
|
|
576
|
-
changed(snapshot.lines.filter((l) => l.id !== lineId));
|
|
577
|
-
if (line) {
|
|
578
|
-
events.emit("remove_from_cart", {
|
|
579
|
-
itemId: line.itemId,
|
|
580
|
-
quantity: line.quantity,
|
|
581
|
-
value: line.lineSubtotal
|
|
582
|
-
});
|
|
583
|
-
}
|
|
584
|
-
},
|
|
585
|
-
clear() {
|
|
586
|
-
ensure();
|
|
587
|
-
changed([], { fulfilment: null, promoCode: null, perks: [] });
|
|
588
|
-
},
|
|
589
|
-
setFulfilment(value) {
|
|
590
|
-
ensure();
|
|
591
|
-
if (!validFulfilment(value) || value.branchId !== branch.id) {
|
|
592
|
-
throw new ZappieCartError([
|
|
593
|
-
issue(
|
|
594
|
-
"fulfilment_unavailable",
|
|
595
|
-
"Select fulfilment for the cart's branch"
|
|
596
|
-
)
|
|
597
|
-
]);
|
|
598
|
-
}
|
|
599
|
-
changed(snapshot.lines, { fulfilment: structuredClone(value) });
|
|
600
|
-
},
|
|
601
|
-
setPromoCode(code) {
|
|
602
|
-
ensure();
|
|
603
|
-
changed(snapshot.lines, { promoCode: code?.trim() || null });
|
|
604
|
-
},
|
|
605
|
-
setPerks(perks) {
|
|
606
|
-
ensure();
|
|
607
|
-
changed(snapshot.lines, { perks: [...perks] });
|
|
608
|
-
},
|
|
609
|
-
async moveTo(branchId) {
|
|
610
|
-
ensure();
|
|
611
|
-
const seq = ++moveSequence;
|
|
612
|
-
cancel();
|
|
613
|
-
publish({ state: attention(snapshot.issues) });
|
|
614
|
-
const value = await deps.workingSet.read(
|
|
615
|
-
branchId,
|
|
616
|
-
snapshot.lines.map((l) => l.itemId)
|
|
617
|
-
);
|
|
618
|
-
if (seq !== moveSequence) {
|
|
619
|
-
return;
|
|
620
|
-
}
|
|
621
|
-
const oldKey = key();
|
|
622
|
-
const oldLines = snapshot.lines;
|
|
623
|
-
choose(value);
|
|
624
|
-
const kept = oldLines.filter(
|
|
625
|
-
(line) => !validateLine(value.items[line.itemId], lineInput(line), {
|
|
626
|
-
menu: value,
|
|
627
|
-
branch
|
|
628
|
-
}).length
|
|
629
|
-
);
|
|
630
|
-
changed(kept, { fulfilment: null, promoCode: null, perks: [] });
|
|
631
|
-
const dropped = oldLines.filter((line) => !kept.includes(line)).map((line) => ({
|
|
632
|
-
...issue(
|
|
633
|
-
"item_unavailable",
|
|
634
|
-
`${line.name} is unavailable at this branch`
|
|
635
|
-
),
|
|
636
|
-
severity: "warning",
|
|
637
|
-
lineId: line.id
|
|
638
|
-
}));
|
|
639
|
-
const issues = [...snapshot.issues, ...dropped];
|
|
640
|
-
publish({ issues, state: attention(issues) });
|
|
641
|
-
if (oldKey !== key()) {
|
|
642
|
-
storage.remove(oldKey);
|
|
643
|
-
}
|
|
644
|
-
},
|
|
645
|
-
async quote(opts = {}) {
|
|
646
|
-
ensure();
|
|
647
|
-
clearTimeout(timer);
|
|
648
|
-
if (opts.force) {
|
|
649
|
-
events.emit("view_cart", {});
|
|
650
|
-
}
|
|
651
|
-
const body = {
|
|
652
|
-
branch_id: branch.id,
|
|
653
|
-
...snapshot.fulfilment ? { fulfilment: wireFulfilment(snapshot.fulfilment) } : {},
|
|
654
|
-
...wire()
|
|
655
|
-
};
|
|
656
|
-
const failure = opts.force ? void 0 : quotes?.failure(body);
|
|
657
|
-
if (failure !== void 0) {
|
|
658
|
-
throw asError(failure);
|
|
659
|
-
}
|
|
660
|
-
const seq = revision;
|
|
661
|
-
const attempt = ++quoteRevision;
|
|
662
|
-
publish({ state: { status: "quoting" } });
|
|
663
|
-
try {
|
|
664
|
-
const client = await quoteClient();
|
|
665
|
-
return await client.get(body, opts.force ?? false, (quote) => {
|
|
666
|
-
if (seq !== revision) {
|
|
667
|
-
return;
|
|
668
|
-
}
|
|
669
|
-
const local = snapshot.issues.filter((i) => i.source === "local");
|
|
670
|
-
const remote = quote.issues.filter(
|
|
671
|
-
(q) => !local.some(
|
|
672
|
-
(l) => l.code === q.code && l.lineId === q.lineId && l.groupId === q.groupId
|
|
673
|
-
)
|
|
674
|
-
);
|
|
675
|
-
const issues = [...local, ...remote];
|
|
676
|
-
publish({ issues, state: attention(issues, quote) });
|
|
677
|
-
for (const i of remote) {
|
|
678
|
-
events.emit("cart_issue", { code: i.code });
|
|
679
|
-
}
|
|
680
|
-
if (quote.menuVersion !== menu.version || quote.issues.some((i) => i.code === "menu_version_stale")) {
|
|
681
|
-
void refresh(quote.menuVersion).catch(
|
|
682
|
-
(error) => events.emit("error", { error: asError(error) })
|
|
683
|
-
);
|
|
684
|
-
}
|
|
685
|
-
});
|
|
686
|
-
} catch (error) {
|
|
687
|
-
if (seq === revision && attempt === quoteRevision) {
|
|
688
|
-
const local = snapshot.issues.filter((i) => i.source === "local");
|
|
689
|
-
publish({ issues: local, state: attention(local) });
|
|
690
|
-
events.emit("quote_failed", { code: asError(error).code });
|
|
691
|
-
}
|
|
692
|
-
throw error instanceof Error && error.name === "AbortError" ? error : asError(error);
|
|
693
|
-
}
|
|
694
|
-
},
|
|
695
|
-
applyFix(problem, fix = problem.fixes[0]) {
|
|
696
|
-
if (!snapshot.issues.includes(problem) || !fix || !problem.fixes.some((f) => JSON.stringify(f) === JSON.stringify(fix))) {
|
|
697
|
-
throw new ZappieError(
|
|
698
|
-
"invalid_request",
|
|
699
|
-
"Choose a current cart issue and one of its fixes"
|
|
700
|
-
);
|
|
701
|
-
}
|
|
702
|
-
switch (fix.action) {
|
|
703
|
-
case "remove_line": {
|
|
704
|
-
if (problem.lineId) {
|
|
705
|
-
cart.remove(problem.lineId);
|
|
706
|
-
}
|
|
707
|
-
return;
|
|
708
|
-
}
|
|
709
|
-
case "remove_promo":
|
|
710
|
-
cart.setPromoCode(null);
|
|
711
|
-
return;
|
|
712
|
-
case "remove_perks":
|
|
713
|
-
cart.setPerks([]);
|
|
714
|
-
return;
|
|
715
|
-
case "set_quantity": {
|
|
716
|
-
if (problem.lineId) {
|
|
717
|
-
cart.update(problem.lineId, { quantity: fix.quantity });
|
|
718
|
-
}
|
|
719
|
-
return;
|
|
720
|
-
}
|
|
721
|
-
case "accept_price": {
|
|
722
|
-
quotes?.accept(problem);
|
|
723
|
-
const issues = snapshot.issues.filter((i) => i !== problem);
|
|
724
|
-
const quote = "quote" in snapshot.state ? snapshot.state.quote : void 0;
|
|
725
|
-
const accepted = quote ? {
|
|
726
|
-
...quote,
|
|
727
|
-
issues: quote.issues.filter(
|
|
728
|
-
(i) => !(i.code === problem.code && i.lineId === problem.lineId)
|
|
729
|
-
)
|
|
730
|
-
} : void 0;
|
|
731
|
-
publish({ issues, state: attention(issues, accepted) });
|
|
732
|
-
return;
|
|
733
|
-
}
|
|
734
|
-
case "choose_region":
|
|
735
|
-
throw new ZappieError(
|
|
736
|
-
"invalid_request",
|
|
737
|
-
"Choose a delivery region and call setFulfilment with deliveryRegionId"
|
|
738
|
-
);
|
|
739
|
-
default:
|
|
740
|
-
throw new ZappieError(
|
|
741
|
-
"invalid_request",
|
|
742
|
-
`${fix.action} needs the shopper's selection; use update or setFulfilment`
|
|
743
|
-
);
|
|
744
|
-
}
|
|
745
|
-
},
|
|
746
|
-
toCheckoutPayload() {
|
|
747
|
-
ensure();
|
|
748
|
-
const blocking = snapshot.issues.filter((i) => i.severity === "blocking");
|
|
749
|
-
if (!snapshot.lines.length || !snapshot.fulfilment) {
|
|
750
|
-
blocking.push(
|
|
751
|
-
issue(
|
|
752
|
-
"fulfilment_unavailable",
|
|
753
|
-
"Add items and select fulfilment before checkout"
|
|
754
|
-
)
|
|
755
|
-
);
|
|
756
|
-
}
|
|
757
|
-
if (blocking.length) {
|
|
758
|
-
throw new ZappieCartError(blocking);
|
|
759
|
-
}
|
|
760
|
-
return {
|
|
761
|
-
fulfilment: structuredClone(snapshot.fulfilment),
|
|
762
|
-
...wire()
|
|
763
|
-
};
|
|
764
|
-
}
|
|
765
|
-
};
|
|
766
|
-
for (const field of Object.keys(EMPTY_CART)) {
|
|
767
|
-
Object.defineProperty(cart, field, {
|
|
768
|
-
get: () => snapshot[field]
|
|
769
|
-
});
|
|
770
|
-
}
|
|
771
|
-
return {
|
|
772
|
-
cart: Object.freeze(cart),
|
|
773
|
-
cartCatalogue: () => menu,
|
|
774
|
-
setLegacyReader(reader) {
|
|
775
|
-
legacy = reader;
|
|
776
|
-
}
|
|
777
|
-
};
|
|
778
|
-
}
|
|
779
|
-
export {
|
|
780
|
-
EMPTY_CART,
|
|
781
|
-
createCart
|
|
782
|
-
};
|
|
1
|
+
import{asError,ZappieError}from"../errors.js";import{multiplyMoney,sumMoney}from"../internal/money-math.js";import{money}from"../money.js";import{ZappieCartError}from"./errors.js";import{estimateUnitPrice}from"./price.js";import{freezeLine,lineInput,reconcile}from"./reconcile.js";import{createCartStorage,parseCart,validFulfilment}from"./storage.js";import{issue,normalizeInput,resolveVariant,validateLine}from"./validate.js";import{wireFulfilment,wireLine}from"./wire.js";var EMPTY_CART=deepFreeze({branchId:void 0,lines:[],count:0,subtotal:null,fulfilment:null,promoCode:null,perks:[],state:{status:"ready"},issues:[],isHydrated:false});function deepFreeze(value){if(value&&typeof value==="object"&&!Object.isFrozen(value)){Object.freeze(value);for(const child of Object.values(value)){deepFreeze(child)}}return value}function identity(input){return JSON.stringify([input.itemId,input.menuId,input.variantId,input.note??"",[...input.choices??[]].sort((a,b)=>a.groupId.localeCompare(b.groupId)||a.choiceId.localeCompare(b.choiceId)),Object.entries(input.inputs??{}).sort(([a],[b])=>a.localeCompare(b))])}function createCart(deps){const{config,menu:menus,store,events}=deps;const ttl=config.cart?.ttl??7*24*60*60*1e3;if(!Number.isFinite(ttl)||ttl<=0){throw new ZappieError("invalid_request","Cart ttl must be positive milliseconds")}let snapshot=EMPTY_CART;let menu;let branch;let selected=config.branch;let updatedAt=0;let timer;let revision=0;let quoteRevision=0;let moveSequence=0;let refreshSequence=0;let chased;let chasedAt=0;let mounted=0;let detach;let hydration;let lifecycle=0;let legacy;const listeners=new Set;const prefix=`zappie:cart:v1:${config.store}:`;const scope=config.cart?.storageScope;const keyFor=id=>`${prefix}${id}${scope?`:${scope}`:""}`;const key=()=>keyFor(branch.id);const storage=createCartStorage(config.storage,message=>events.emit("warning",{message}));const readSaved=id=>{let raw=storage.read(keyFor(id));if(raw===null&&scope){raw=storage.read(prefix+id);if(raw!==null){storage.remove(prefix+id);storage.write(keyFor(id),raw)}}return raw};let quotes;let loadingQuotes;const quoteClient=()=>loadingQuotes??(loadingQuotes=import("./quote-client.js").then(({createQuoteClient})=>quotes=createQuoteClient(deps.transport,deps.context,config),error=>{loadingQuotes=void 0;throw error}));const publish=patch=>{snapshot=deepFreeze({...snapshot,...patch,branchId:branch?.id});for(const fn of[...listeners]){try{fn()}catch(error){events.emit("error",{error:asError(error)})}}};const attention=(issues,quote)=>issues.some(i=>i.severity!=="info")?{status:"needs_attention",issues,...quote?{quote}:{}}:quote?{status:"quoted",quote}:{status:"ready"};const cancel=()=>{revision++;quoteRevision++;clearTimeout(timer);quotes?.cancel()};const wire=()=>({lines:snapshot.lines.map(wireLine),...snapshot.promoCode?{promo_code:snapshot.promoCode}:{},...snapshot.perks.length&&snapshot.fulfilment?.type!="dine_in"?{perk_redemption_ids:snapshot.perks.map(p=>p.redemptionId)}:{},menu_version:menu.version});const persist=()=>{const value={v:1,lines:snapshot.lines.map(line=>({...lineInput(line),id:line.id,name:line.name,addedAt:line.addedAt,unitPrice:line.unitPrice})),fulfilment:snapshot.fulfilment,promoCode:snapshot.promoCode,perks:snapshot.perks,menuVersion:menu.version,updatedAt};storage.write(key(),JSON.stringify(value))};const schedule=()=>{clearTimeout(timer);if(snapshot.lines.length){timer=setTimeout(()=>{void cart.quote().catch(()=>{})},300)}};const resume=()=>{if(!("quote"in snapshot.state)){schedule()}};const recompute=(lines,pending=snapshot.issues.filter(i=>i.source==="local"),patch={})=>{const currency=store.peek().currency;const result=reconcile(lines,menu,branch,currency,pending);const subtotal=result.priced?sumMoney(result.lines.map(l=>l.lineSubtotal),money(0,currency)):null;publish({...patch,lines:result.lines,count:result.lines.reduce((n,l)=>n+l.quantity,0),subtotal,issues:result.issues,state:attention(result.issues)});for(const i of result.issues){events.emit("cart_issue",{code:i.code})}};const changed=(lines=snapshot.lines,patch={})=>{cancel();recompute(lines,void 0,patch);updatedAt=Date.now();persist();schedule()};const choose=value=>{const found=store.peek()?.branches.find(b=>b.id===value.branchId);if(!found){throw new ZappieError("branch_not_found","Load the storefront branch before using its cart")}menu=value;branch=found;selected=found.id};const load=(raw,writeBack=true)=>{cancel();let saved;try{saved=raw?parseCart(raw):void 0;if(saved&&Date.now()-saved.updatedAt>ttl){saved=void 0;storage.remove(key());events.emit("cart_expired",{branchId:branch.id})}}catch{storage.remove(key());storage.warning("Invalid saved cart discarded")}updatedAt=saved?.updatedAt??Date.now();const idle=Date.now()-updatedAt;let fulfilment=saved?.fulfilment??null;if(fulfilment?.branchId!==branch.id||idle>864e5&&fulfilment.type==="delivery"){fulfilment=null}if(fulfilment&&"scheduledFor"in fulfilment&&fulfilment.scheduledFor&&Date.parse(fulfilment.scheduledFor)<Date.now()){fulfilment={...fulfilment};delete fulfilment.scheduledFor}const lines=(saved?.lines??[]).map(line=>({...line,...idle>864e5?{inputs:{}}:{}}));const result=reconcile(lines,menu,branch,store.peek().currency);recompute(result.lines,result.issues,{fulfilment,promoCode:saved?.promoCode??null,perks:saved?.perks??[],isHydrated:true});if(raw!==null&&writeBack){persist()}storage.sweep(prefix,key(),ttl)};const ensure=()=>{const id=branch?.id??store.peek()?.branches.find(b=>b.id===selected||b.slug===selected||!selected&&b.isDefault)?.id??(!selected?store.peek()?.branches[0]?.id:void 0);if(snapshot.isHydrated){return}const loaded=menu??(id?deps.workingSet.peek(id,[]):void 0);if(!loaded||!store.peek()){throw new ZappieError("invalid_request","Load the store and menu before editing the cart")}choose(loaded);const raw=readSaved(branch.id);let migrated=[];if(raw===null&&legacy){try{migrated=legacy(storage.read)}catch{storage.warning("Invalid legacy cart discarded")}}load(raw);if(raw===null&&legacy){persist()}for(const input of migrated.slice(0,100)){try{cart.add(input.itemId,input)}catch{events.emit("cart_issue",{code:"item_unavailable"})}}};const refresh=async target=>{const id=branch?.id;const seq=moveSequence;const request=++refreshSequence;const rev=revision;if(!id||!menu){return}if(!snapshot.lines.length){return}if(menu.completeness!=="partial"){const version=await deps.transport.getMenuVersion({...deps.context(),branchId:id});if(version.version===menu.version){return}target=version.version}if(target&&target===chased&&Date.now()-chasedAt<3e4){return}chased=target;chasedAt=Date.now();const value=await deps.workingSet.read(id,snapshot.lines.map(l=>l.itemId),true);if(seq!==moveSequence||request!==refreshSequence||rev!==revision||JSON.stringify(value)===JSON.stringify(menu)){return}menu=value;cancel();recompute(snapshot.lines);persist();schedule()};const current=itemId=>{const candidate=deps.workingSet.peek(branch.id,[...snapshot.lines.map(l=>l.itemId),itemId]);if(candidate.items[itemId]){menu=candidate}};const validated=(raw,id,addedAt)=>{current(raw.itemId);const item=Object.hasOwn(menu.items,raw.itemId)?menu.items[raw.itemId]:void 0;const problems=validateLine(item,raw,{menu,branch});if(problems.length||!item){throw new ZappieCartError(problems)}const input=normalizeInput(item,raw);const variant=resolveVariant(item,input);const choices=(input.choices??[]).map(c=>({...c,quantity:c.quantity??1}));const unitPrice=estimateUnitPrice(item,{choices,variantId:variant.id});return freezeLine({id:id??`line_${Array.from(globalThis.crypto.getRandomValues(new Uint8Array(10)),byte=>(byte%36).toString(36)).join("")}`,itemId:item.id,...input.menuId!==void 0?{menuId:input.menuId}:{},name:item.name,quantity:input.quantity,choices,inputs:input.inputs??{},variantId:variant.id,...input.note!==void 0?{note:input.note}:{},unitPrice,lineSubtotal:multiplyMoney(unitPrice,input.quantity),addedAt:addedAt??new Date().toISOString()})};const offMenu=events.on("menu:updated",({branchId,version})=>{if(branch?.id===branchId){const value=menus.peek(branchId);if(value&&value.completeness!=="partial"&&value.version===version&&value.version!==menu?.version){refreshSequence++;menu=value;cancel();recompute(snapshot.lines);persist();schedule()}}});const cart={getSnapshot:()=>snapshot,subscribe(fn){listeners.add(fn);return()=>{listeners.delete(fn)}},async hydrate(){if(snapshot.isHydrated){resume();return refresh()}const life=lifecycle;hydration??(hydration=(async()=>{const value=await store.get();const target=value.branches.find(b=>b.id===selected||b.slug===selected)??(!selected?value.branches.find(b=>b.isDefault)??value.branches[0]:void 0);if(!target){throw new ZappieError("branch_not_found","Cart branch is unavailable")}let inputs=snapshot.lines;if(!snapshot.isHydrated){const raw=readSaved(target.id);try{const saved=raw?parseCart(raw):void 0;inputs=saved&&Date.now()-saved.updatedAt<=ttl?saved.lines:raw===null?legacy?.(storage.read)??[]:[]}catch{inputs=[]}}const loaded=await deps.workingSet.read(target.id,inputs.map(l=>l.itemId));if(life!==lifecycle){return}choose(loaded);ensure();resume();if(loaded.completeness!=="partial"){await refresh()}})().finally(()=>{hydration=void 0}));return hydration},mount(){mounted++;if(!detach&&typeof window!=="undefined"){const onStorage=event=>{if(branch&&event.key===key()&&storage.accepts(event.storageArea)){const raw=event.newValue;let ids;try{ids=raw?parseCart(raw).lines.map(l=>l.itemId):[]}catch{load(raw,false);return}const cached=deps.workingSet.peek(branch.id,ids);if(cached.completeness!=="partial"||ids.every(id=>cached.items[id])){menu=cached;load(raw,false);schedule();return}const rev=revision;const request=++refreshSequence;const life=lifecycle;void deps.workingSet.read(branch.id,ids).then(value=>{if(life===lifecycle&&rev===revision&&request===refreshSequence){menu=value;load(raw,false);schedule()}}).catch(error=>events.emit("error",{error:asError(error)}))}};const onFocus=()=>{void refresh().catch(error=>events.emit("error",{error:asError(error)}))};window.addEventListener("storage",onStorage);window.addEventListener("focus",onFocus);detach=()=>{window.removeEventListener("storage",onStorage);window.removeEventListener("focus",onFocus)}}if(mounted===1){void cart.hydrate().catch(error=>events.emit("error",{error:asError(error)}))}let active=true;return()=>{if(active){active=false;mounted--;if(mounted===0){detach?.();detach=void 0;cancel()}}}},dispose(){lifecycle++;moveSequence++;offMenu();cancel();detach?.();detach=void 0;listeners.clear()},validate(input){ensure();current(input.itemId);const problems=validateLine(Object.hasOwn(menu.items,input.itemId)?menu.items[input.itemId]:void 0,input,{menu,branch});return problems.length?{ok:false,issues:problems}:{ok:true}},add(item,input={}){ensure();let line=validated({...input,itemId:typeof item==="string"?item:item.id});const existing=snapshot.lines.find(l=>identity(lineInput(l))===identity(lineInput(line)));if(existing){line=validated({...lineInput(line),quantity:existing.quantity+line.quantity},existing.id,existing.addedAt)}else if(snapshot.lines.length>=100){throw new ZappieCartError([issue("quantity_limit","A cart can contain at most 100 lines")])}changed(existing?snapshot.lines.map(l=>l.id===existing.id?line:l):[...snapshot.lines,line]);events.emit("add_to_cart",{itemId:line.itemId,quantity:line.quantity-(existing?.quantity??0),value:multiplyMoney(line.unitPrice,line.quantity-(existing?.quantity??0))});return line},update(lineId,patch){ensure();const old=snapshot.lines.find(l=>l.id===lineId);if(!old){throw new ZappieCartError([issue("item_not_found","Cart line not found")])}const input={...lineInput(old),...patch};if(patch.choices&&!patch.variantId){delete input.variantId}let line=validated(input,old.id,old.addedAt);const duplicate=snapshot.lines.find(l=>l.id!==lineId&&identity(lineInput(l))===identity(lineInput(line)));if(duplicate){line=validated({...lineInput(line),quantity:line.quantity+duplicate.quantity},old.id,old.addedAt)}changed(snapshot.lines.filter(l=>l.id!==duplicate?.id).map(l=>l.id===lineId?line:l));events.emit("update_cart_line",{lineId,itemId:line.itemId,quantity:line.quantity});return line},remove(lineId){ensure();const line=snapshot.lines.find(l=>l.id===lineId);changed(snapshot.lines.filter(l=>l.id!==lineId));if(line){events.emit("remove_from_cart",{itemId:line.itemId,quantity:line.quantity,value:line.lineSubtotal})}},clear(){ensure();changed([],{fulfilment:null,promoCode:null,perks:[]})},setFulfilment(value){ensure();if(!validFulfilment(value)||value.branchId!==branch.id){throw new ZappieCartError([issue("fulfilment_unavailable","Select fulfilment for the cart's branch")])}changed(snapshot.lines,{fulfilment:structuredClone(value)})},setPromoCode(code){ensure();changed(snapshot.lines,{promoCode:code?.trim()||null})},setPerks(perks){ensure();changed(snapshot.lines,{perks:[...perks]})},async moveTo(branchId){ensure();const seq=++moveSequence;cancel();publish({state:attention(snapshot.issues)});const value=await deps.workingSet.read(branchId,snapshot.lines.map(l=>l.itemId));if(seq!==moveSequence){return}const oldKey=key();const oldLines=snapshot.lines;choose(value);const kept=oldLines.filter(line=>!validateLine(value.items[line.itemId],lineInput(line),{menu:value,branch}).length);changed(kept,{fulfilment:null,promoCode:null,perks:[]});const dropped=oldLines.filter(line=>!kept.includes(line)).map(line=>({...issue("item_unavailable",`${line.name} is unavailable at this branch`),severity:"warning",lineId:line.id}));const issues=[...snapshot.issues,...dropped];publish({issues,state:attention(issues)});if(oldKey!==key()){storage.remove(oldKey)}},async quote(opts={}){ensure();clearTimeout(timer);if(opts.force){events.emit("view_cart",{})}const body={branch_id:branch.id,...snapshot.fulfilment?{fulfilment:wireFulfilment(snapshot.fulfilment)}:{},...wire()};const failure=opts.force?void 0:quotes?.failure(body);if(failure!==void 0){throw asError(failure)}const seq=revision;const attempt=++quoteRevision;publish({state:{status:"quoting"}});try{const client=await quoteClient();return await client.get(body,opts.force??false,quote=>{if(seq!==revision){return}const local=snapshot.issues.filter(i=>i.source==="local");const remote=quote.issues.filter(q=>!local.some(l=>l.code===q.code&&l.lineId===q.lineId&&l.groupId===q.groupId));const issues=[...local,...remote];publish({issues,state:attention(issues,quote)});for(const i of remote){events.emit("cart_issue",{code:i.code})}if(quote.menuVersion!==menu.version||quote.issues.some(i=>i.code==="menu_version_stale")){void refresh(quote.menuVersion).catch(error=>events.emit("error",{error:asError(error)}))}})}catch(error){if(seq===revision&&attempt===quoteRevision){const local=snapshot.issues.filter(i=>i.source==="local");publish({issues:local,state:attention(local)});events.emit("quote_failed",{code:asError(error).code})}throw error instanceof Error&&error.name==="AbortError"?error:asError(error)}},applyFix(problem,fix=problem.fixes[0]){if(!snapshot.issues.includes(problem)||!fix||!problem.fixes.some(f=>JSON.stringify(f)===JSON.stringify(fix))){throw new ZappieError("invalid_request","Choose a current cart issue and one of its fixes")}switch(fix.action){case"remove_line":{if(problem.lineId){cart.remove(problem.lineId)}return}case"remove_promo":cart.setPromoCode(null);return;case"remove_perks":cart.setPerks([]);return;case"set_quantity":{if(problem.lineId){cart.update(problem.lineId,{quantity:fix.quantity})}return}case"accept_price":{quotes?.accept(problem);const issues=snapshot.issues.filter(i=>i!==problem);const quote="quote"in snapshot.state?snapshot.state.quote:void 0;const accepted=quote?{...quote,issues:quote.issues.filter(i=>!(i.code===problem.code&&i.lineId===problem.lineId))}:void 0;publish({issues,state:attention(issues,accepted)});return}case"choose_region":throw new ZappieError("invalid_request","Choose a delivery region and call setFulfilment with deliveryRegionId");default:throw new ZappieError("invalid_request",`${fix.action} needs the shopper's selection; use update or setFulfilment`)}},toCheckoutPayload(){ensure();const blocking=snapshot.issues.filter(i=>i.severity==="blocking");if(!snapshot.lines.length||!snapshot.fulfilment){blocking.push(issue("fulfilment_unavailable","Add items and select fulfilment before checkout"))}if(blocking.length){throw new ZappieCartError(blocking)}return{fulfilment:structuredClone(snapshot.fulfilment),...wire()}}};for(const field of Object.keys(EMPTY_CART)){Object.defineProperty(cart,field,{get:()=>snapshot[field]})}return{cart:Object.freeze(cart),cartCatalogue:()=>menu,setLegacyReader(reader){legacy=reader}}}export{EMPTY_CART,createCart};
|
|
783
2
|
//# sourceMappingURL=index.js.map
|