@wix/himalaya-cli 0.1648.0 → 0.1650.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.
- package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/core/sdk/ui/src/index.d.ts +4 -0
- package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/ui.mjs +1 -0
- package/dist/browser-plane/assets.json +5 -5
- package/dist/browser-plane/preview-deferred/{4ef4d326496b4d7809746936207067b4c921f5db9878ecc7030aa3a9e4d2aaeb.bin → 6ba3f2eb2ac29f4f9eeebd1294a8003820cd260274c5400149d76833b3171555.bin} +1 -1
- package/dist/browser-plane/sw.js +5 -5
- package/dist/cli.mjs +45 -40
- package/dist/preview-assets.generated.bin +0 -0
- package/guides/sdk-reference.json +8 -1
- package/package.json +2 -2
- package/template-icons/wholesale-store.png +0 -0
- package/templates/beauty-salon/config.ts +16 -1
- package/templates/branded-lite/config.ts +16 -1
- package/templates/branded-lite/dev/index.ts +292 -305
- package/templates/branded-lite/l10n/en.json +3 -3
- package/templates/branded-lite/tier5-src/_shared/branded-form.ts +22 -4
- package/templates/branded-lite/tier5-src/himi-branded-lite-form/index.ts +250 -74
- package/templates/community-club/config.ts +16 -1
- package/templates/events-meetups/config.ts +16 -1
- package/templates/gym-fitness/config.ts +16 -1
- package/templates/nonprofit-cause/config.ts +16 -1
- package/templates/podcast-creator/config.ts +16 -1
- package/templates/portfolio-creative/config.ts +16 -1
- package/templates/restaurant/config.ts +16 -1
- package/templates/retail-store/config.ts +16 -1
- package/templates/wholesale-store/README.md +53 -0
- package/templates/wholesale-store/config.ts +247 -0
- package/templates/wholesale-store/dev/index.ts +12194 -0
- package/templates/wholesale-store/himalaya.content.json +43 -0
- package/templates/wholesale-store/himalaya.template.json +14 -0
- package/templates/wholesale-store/icon.png +0 -0
- package/templates/wholesale-store/platforms.json +1 -0
- package/templates/wholesale-store/tier5-src/_shared/app-locale.ts +61 -0
- package/templates/wholesale-store/tier5-src/_shared/branded-lite-hosted.ts +279 -0
- package/templates/wholesale-store/tier5-src/_shared/business-chat-copy.ts +40 -0
- package/templates/wholesale-store/tier5-src/_shared/business-chat-history.ts +51 -0
- package/templates/wholesale-store/tier5-src/_shared/business-chat-message-model.ts +177 -0
- package/templates/wholesale-store/tier5-src/_shared/business-chat-model.ts +56 -0
- package/templates/wholesale-store/tier5-src/_shared/business-chat-presenter.ts +576 -0
- package/templates/wholesale-store/tier5-src/_shared/business-chat-transport.ts +148 -0
- package/templates/wholesale-store/tier5-src/_shared/collection-contract.ts +228 -0
- package/templates/wholesale-store/tier5-src/_shared/collection-query-legacy.ts +194 -0
- package/templates/wholesale-store/tier5-src/_shared/collection-query.ts +252 -0
- package/templates/wholesale-store/tier5-src/_shared/collection-service.ts +423 -0
- package/templates/wholesale-store/tier5-src/_shared/detail-presence.ts +51 -0
- package/templates/wholesale-store/tier5-src/_shared/empty-flags.ts +33 -0
- package/templates/wholesale-store/tier5-src/_shared/engine-intl.ts +508 -0
- package/templates/wholesale-store/tier5-src/_shared/exclusive-writes.ts +66 -0
- package/templates/wholesale-store/tier5-src/_shared/himi-account.ts +164 -0
- package/templates/wholesale-store/tier5-src/_shared/himi-copy.ts +89 -0
- package/templates/wholesale-store/tier5-src/_shared/himi-store-categories.ts +108 -0
- package/templates/wholesale-store/tier5-src/_shared/himi-store-collection.ts +22 -0
- package/templates/wholesale-store/tier5-src/_shared/himi-store-saved.ts +57 -0
- package/templates/wholesale-store/tier5-src/_shared/himi-store.ts +7 -0
- package/templates/wholesale-store/tier5-src/_shared/himi-text.ts +24 -0
- package/templates/wholesale-store/tier5-src/_shared/hosted-checkout.ts +70 -0
- package/templates/wholesale-store/tier5-src/_shared/iap-presentation.ts +207 -0
- package/templates/wholesale-store/tier5-src/_shared/iap-worker.ts +125 -0
- package/templates/wholesale-store/tier5-src/_shared/inbox-rooms.ts +68 -0
- package/templates/wholesale-store/tier5-src/_shared/live-session.ts +172 -0
- package/templates/wholesale-store/tier5-src/_shared/local-preferences.ts +38 -0
- package/templates/wholesale-store/tier5-src/_shared/member-access.ts +52 -0
- package/templates/wholesale-store/tier5-src/_shared/member-account-routes.ts +52 -0
- package/templates/wholesale-store/tier5-src/_shared/member-orders.ts +8 -0
- package/templates/wholesale-store/tier5-src/_shared/member-screen.ts +99 -0
- package/templates/wholesale-store/tier5-src/_shared/online-actions.ts +76 -0
- package/templates/wholesale-store/tier5-src/_shared/owner-editor-value.ts +164 -0
- package/templates/wholesale-store/tier5-src/_shared/owner-load-error.ts +348 -0
- package/templates/wholesale-store/tier5-src/_shared/payment-setup.ts +6 -0
- package/templates/wholesale-store/tier5-src/_shared/read-service.ts +255 -0
- package/templates/wholesale-store/tier5-src/_shared/restaurant-ordering.ts +201 -0
- package/templates/wholesale-store/tier5-src/_shared/rich-body.ts +78 -0
- package/templates/wholesale-store/tier5-src/_shared/rich-content-link.ts +34 -0
- package/templates/wholesale-store/tier5-src/_shared/sign-in-sheet.ts +18 -0
- package/templates/wholesale-store/tier5-src/_shared/store-order-presentation.ts +56 -0
- package/templates/wholesale-store/tier5-src/_shared/store-product-info.ts +50 -0
- package/templates/wholesale-store/tier5-src/business-chat/index.ts +724 -0
- package/templates/wholesale-store/tier5-src/himi-branded-lite-cart/index.ts +602 -0
- package/templates/wholesale-store/tier5-src/himi-branded-lite-order/index.ts +472 -0
- package/templates/wholesale-store/tier5-src/himi-branded-lite-orders/index.ts +327 -0
- package/templates/wholesale-store/tier5-src/himi-store-account/index.ts +998 -0
- package/templates/wholesale-store/tier5-src/himi-store-product/index.ts +889 -0
- package/templates/wholesale-store/tier5-src/himi-store-saved/index.ts +68 -0
- package/templates/wholesale-store/tier5-src/himi-store-shop/index.ts +150 -0
- package/templates/wholesale-store/tier5-src/himi-wholesale-home/index.ts +507 -0
- package/templates/wholesale-store/tier5-src/wix-spaces-collection-detail/index.ts +195 -0
- package/templates/wholesale-store/tokens.json +340 -0
- package/templates/yoga-studio/config.ts +16 -1
|
@@ -0,0 +1,472 @@
|
|
|
1
|
+
import { orderDelivery, orderOptions } from "../_shared/store-order-presentation.js";
|
|
2
|
+
import { withOnlineWrites } from "../_shared/online-actions.js";
|
|
3
|
+
import { createIapCommerce, classifyCart } from "@himalaya/iap-checkout";
|
|
4
|
+
import { getStoreProduct } from "../_shared/himi-store.js";
|
|
5
|
+
import { iapPriceCopy } from "../_shared/iap-worker.js";
|
|
6
|
+
import { defineService as registerService } from "@himalaya/state";
|
|
7
|
+
import { orderMember, assertOrderMember, ownedOrderCache, orderAccessDenied, orderAccessChanged, type OrderMember } from "../_shared/member-orders.js";
|
|
8
|
+
import { addToCurrentCart, getOrder, searchOrders, type WixOrder } from "@himalaya/wix-ecom";
|
|
9
|
+
import { copyParam, copyTemplate, stashCopy } from "../_shared/himi-copy.js";
|
|
10
|
+
import { formatDateTimeMedium } from "../_shared/engine-intl.js";
|
|
11
|
+
import { get, type DbEntity } from "@himalaya/local-db";
|
|
12
|
+
import {
|
|
13
|
+
IDLE_LIVE_SESSION,
|
|
14
|
+
beginLiveSession,
|
|
15
|
+
liveSessionStarted,
|
|
16
|
+
stopLiveSession,
|
|
17
|
+
type LiveSessionFields,
|
|
18
|
+
} from "../_shared/live-session.js";
|
|
19
|
+
|
|
20
|
+
// Offline-first (data-offline): the order detail is a READ-THROUGH — when the live
|
|
21
|
+
// order fetch fails (offline) fall back to the last-synced row the orders list cached
|
|
22
|
+
// under the `orders` entity, so a previously-seen order still opens (line items aside).
|
|
23
|
+
// DEGRADES GRACEFULLY: the local-db read is wrapped so an app without the
|
|
24
|
+
// `local_database` grant behaves exactly as before (online-only).
|
|
25
|
+
const ENTITY = "orders";
|
|
26
|
+
async function readCachedOrder(id: string, member: OrderMember): Promise<DbEntity | null> {
|
|
27
|
+
if (!member.scope) return null;
|
|
28
|
+
try { const row = await get(ENTITY, id); return ownedOrderCache(row, member) ? row : null; } catch { /* capability not granted → online-only */ return null; }
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
interface LineRow {
|
|
32
|
+
id: string;
|
|
33
|
+
title: string;
|
|
34
|
+
name: string;
|
|
35
|
+
quantity: string;
|
|
36
|
+
options: string;
|
|
37
|
+
/** Formatted per-line price (fetched with the order; previously discarded). */
|
|
38
|
+
price: string;
|
|
39
|
+
image: string;
|
|
40
|
+
initial: string;
|
|
41
|
+
hasImage: boolean;
|
|
42
|
+
noImage: boolean;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** What reorder re-adds: catalog item id + quantity per line (internal). */
|
|
46
|
+
interface ReorderRef {
|
|
47
|
+
appId?: string;
|
|
48
|
+
options?: Record<string, unknown>;
|
|
49
|
+
catalogItemId: string;
|
|
50
|
+
quantity: number;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
interface State extends LiveSessionFields {
|
|
54
|
+
status: "loading" | "ready" | "error";
|
|
55
|
+
permissionDenied?: boolean;
|
|
56
|
+
hideLoadError?: boolean;
|
|
57
|
+
hidePermissionError?: boolean;
|
|
58
|
+
/** The order this screen is about. Added for #2050: a followed session has to name
|
|
59
|
+
* its record, and until now the id lived only in `load`'s local scope. */
|
|
60
|
+
id: string;
|
|
61
|
+
title: string;
|
|
62
|
+
placedAt: string;
|
|
63
|
+
deliveryTitle: string;
|
|
64
|
+
deliveryLines: string;
|
|
65
|
+
deliveryMethod: string;
|
|
66
|
+
deliveryAddress: string;
|
|
67
|
+
noDeliveryMethod?: boolean;
|
|
68
|
+
noDeliveryAddress?: boolean;
|
|
69
|
+
noDelivery: boolean;
|
|
70
|
+
fulfillmentStatus: string;
|
|
71
|
+
paymentStatus: string;
|
|
72
|
+
subtotal: string;
|
|
73
|
+
shipping: string;
|
|
74
|
+
tax: string;
|
|
75
|
+
discount: string;
|
|
76
|
+
total: string;
|
|
77
|
+
rows: LineRow[];
|
|
78
|
+
/** Reorder refs (catalog ids + quantities) — drives the reorder CTA. */
|
|
79
|
+
reorderRefs: ReorderRef[];
|
|
80
|
+
canReorder: boolean;
|
|
81
|
+
cannotReorder: boolean;
|
|
82
|
+
reorderMessage: string;
|
|
83
|
+
emptyText: string;
|
|
84
|
+
/** No member session is what stands between the visitor and this order — drives the
|
|
85
|
+
* sign-in CTA, which returns here with `id` once the member has signed in. */
|
|
86
|
+
needsSignIn: boolean;
|
|
87
|
+
noSignIn: boolean;
|
|
88
|
+
isLoading: boolean;
|
|
89
|
+
notLoading: boolean;
|
|
90
|
+
isErrored: boolean;
|
|
91
|
+
notErrored: boolean;
|
|
92
|
+
noEmpty: boolean;
|
|
93
|
+
hideContent: boolean;
|
|
94
|
+
hasShipping: boolean;
|
|
95
|
+
noShipping: boolean;
|
|
96
|
+
hasTax: boolean;
|
|
97
|
+
noTax: boolean;
|
|
98
|
+
hasDiscount: boolean;
|
|
99
|
+
noDiscount: boolean;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function inputId(): string {
|
|
103
|
+
// WS-C — `himalaya.input.id` is the PRIMARY contract: hosts thread the row's
|
|
104
|
+
// `id` nav param (himi.open { screenId: "himi_order", id }) into worker input.
|
|
105
|
+
const input = (globalThis as { himalaya?: { input?: { id?: string; screenId?: string } } }).himalaya?.input;
|
|
106
|
+
if (input?.id) return input.id;
|
|
107
|
+
// #570 back-compat for pre-params releases with baked `himi_order_<id>`
|
|
108
|
+
// screenIds — do not author against this.
|
|
109
|
+
const screenId = input?.screenId ?? "";
|
|
110
|
+
return screenId.startsWith("himi_order_") ? screenId.slice("himi_order_".length) : "";
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function formatDate(value?: string): string {
|
|
114
|
+
if (!value) return "";
|
|
115
|
+
const date = new Date(value);
|
|
116
|
+
if (Number.isNaN(date.getTime())) return "";
|
|
117
|
+
// Was a bare `new Intl.DateTimeFormat` with NO guard and no try/catch. QuickJS-ng (watchOS,
|
|
118
|
+
// Wear OS) has no ECMA-402 at all, so on the wrist this threw an uncaught ReferenceError and
|
|
119
|
+
// KILLED the screen — the hard-failure end of the same class as himi-events-detail's price.
|
|
120
|
+
return formatDateTimeMedium(date);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function titleCase(value?: string): string {
|
|
124
|
+
return (value ?? "").replace(/_/g, " ").toLowerCase().replace(/(^|\s)\S/g, (part) => part.toUpperCase());
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function belongsTo(order: WixOrder, email: string): boolean {
|
|
128
|
+
return !!email && (order.buyerInfo?.email ?? "").trim().toLowerCase() === email;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function mediaUrl(value: unknown): string {
|
|
132
|
+
if (!value || typeof value !== "object") return "";
|
|
133
|
+
const item = value as {
|
|
134
|
+
image?: { url?: string } | string;
|
|
135
|
+
media?: {
|
|
136
|
+
mainMedia?: { image?: { url?: string }; thumbnail?: { url?: string }; url?: string };
|
|
137
|
+
items?: Array<{ image?: { url?: string }; thumbnail?: { url?: string }; url?: string }>;
|
|
138
|
+
};
|
|
139
|
+
};
|
|
140
|
+
const directImage = typeof item.image === "string" ? item.image : item.image?.url;
|
|
141
|
+
return directImage
|
|
142
|
+
?? item.media?.mainMedia?.image?.url
|
|
143
|
+
?? item.media?.mainMedia?.thumbnail?.url
|
|
144
|
+
?? item.media?.mainMedia?.url
|
|
145
|
+
?? item.media?.items?.[0]?.image?.url
|
|
146
|
+
?? item.media?.items?.[0]?.thumbnail?.url
|
|
147
|
+
?? item.media?.items?.[0]?.url
|
|
148
|
+
?? "";
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Formatted per-line price probed off the raw line payload ("" when absent). */
|
|
152
|
+
function linePrice(value: unknown): string {
|
|
153
|
+
const item = value as {
|
|
154
|
+
price?: { formattedAmount?: string };
|
|
155
|
+
totalPriceAfterTax?: { formattedAmount?: string };
|
|
156
|
+
totalPriceBeforeTax?: { formattedAmount?: string };
|
|
157
|
+
} | undefined;
|
|
158
|
+
return item?.totalPriceAfterTax?.formattedAmount
|
|
159
|
+
?? item?.totalPriceBeforeTax?.formattedAmount
|
|
160
|
+
?? (item?.price?.formattedAmount ? copyTemplate("order.unitPrice", "{price} each", { price: item.price.formattedAmount }) : "");
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function lineRows(order: WixOrder): LineRow[] {
|
|
164
|
+
return (order.lineItems ?? []).map((item, index) => {
|
|
165
|
+
const name = item.productName?.original || item.productName?.translated || copyParam("order.itemFallbackName", "Order item");
|
|
166
|
+
const image = mediaUrl(item);
|
|
167
|
+
return {
|
|
168
|
+
id: item.id || `line-${index}`,
|
|
169
|
+
title: name,
|
|
170
|
+
name,
|
|
171
|
+
quantity: copyTemplate("order.quantityLine", "Qty {quantity}", { quantity: item.quantity || 1 }),
|
|
172
|
+
price: linePrice(item),
|
|
173
|
+
options: orderOptions(item),
|
|
174
|
+
image,
|
|
175
|
+
initial: (name.trim()[0] || "O").toUpperCase(),
|
|
176
|
+
hasImage: Boolean(image),
|
|
177
|
+
noImage: !image,
|
|
178
|
+
};
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** Catalog references for the reorder CTA — only store-catalog lines re-add. */
|
|
183
|
+
function reorderRefs(order: WixOrder): ReorderRef[] {
|
|
184
|
+
return (order.lineItems ?? []).flatMap((item) => {
|
|
185
|
+
const ref = (item as { catalogReference?: { catalogItemId?: string; appId?: string; options?: Record<string, unknown> } }).catalogReference;
|
|
186
|
+
const catalogItemId = ref?.catalogItemId;
|
|
187
|
+
return typeof catalogItemId === "string" && catalogItemId
|
|
188
|
+
? [{ catalogItemId, appId: ref.appId, ...(ref.options ? { options: ref.options } : {}), quantity: item.quantity || 1 }]
|
|
189
|
+
: [];
|
|
190
|
+
});
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
function derive(state: State): State {
|
|
194
|
+
const hasContent = state.status === "ready" && !!state.title;
|
|
195
|
+
const canReorder = hasContent && state.reorderRefs.length > 0;
|
|
196
|
+
return {
|
|
197
|
+
...state,
|
|
198
|
+
canReorder,
|
|
199
|
+
cannotReorder: !canReorder,
|
|
200
|
+
isLoading: state.status === "loading",
|
|
201
|
+
notLoading: state.status !== "loading",
|
|
202
|
+
hideLoadError: state.status !== "error" || state.permissionDenied === true || state.needsSignIn,
|
|
203
|
+
hidePermissionError: state.status !== "error" || state.permissionDenied !== true || state.needsSignIn,
|
|
204
|
+
isErrored: state.status === "error",
|
|
205
|
+
notErrored: state.status !== "error",
|
|
206
|
+
noEmpty: state.status !== "ready" || hasContent || state.needsSignIn,
|
|
207
|
+
noSignIn: !state.needsSignIn,
|
|
208
|
+
hideContent: !hasContent,
|
|
209
|
+
noDelivery: !state.deliveryLines,
|
|
210
|
+
noDeliveryMethod: !state.deliveryMethod,
|
|
211
|
+
noDeliveryAddress: !state.deliveryAddress,
|
|
212
|
+
hasShipping: !!state.shipping,
|
|
213
|
+
noShipping: !state.shipping,
|
|
214
|
+
hasTax: !!state.tax,
|
|
215
|
+
noTax: !state.tax,
|
|
216
|
+
hasDiscount: !!state.discount,
|
|
217
|
+
noDiscount: !state.discount,
|
|
218
|
+
// #2050 — the live-session fields come from the MODULE, not from the passed
|
|
219
|
+
// state. `clearOrder` and every error branch rebuild state from a fresh set of
|
|
220
|
+
// blank fields, so a value carried only through the argument would be dropped by
|
|
221
|
+
// whichever branch forgot it — and the row would claim the member had stopped
|
|
222
|
+
// following an order still live on their lock screen.
|
|
223
|
+
...liveSession,
|
|
224
|
+
};
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** #2050 — whether this member is following THIS order, held outside the derived
|
|
228
|
+
* state for the reason above. One per worker instance, which is one order. */
|
|
229
|
+
let liveSession: LiveSessionFields = { ...IDLE_LIVE_SESSION };
|
|
230
|
+
|
|
231
|
+
async function findOwnedOrder(id: string, email: string): Promise<WixOrder | undefined> {
|
|
232
|
+
let directAccessError: unknown;
|
|
233
|
+
try {
|
|
234
|
+
const response = await getOrder(id);
|
|
235
|
+
const order = response.order ?? (response as unknown as WixOrder);
|
|
236
|
+
if (order?.id) {
|
|
237
|
+
if (belongsTo(order, email)) return order;
|
|
238
|
+
// Only an authenticated search may recover an unverifiable direct response.
|
|
239
|
+
// Cached summaries cannot establish current ownership when that search fails.
|
|
240
|
+
directAccessError = orderAccessChanged();
|
|
241
|
+
}
|
|
242
|
+
} catch (error) {
|
|
243
|
+
if (orderAccessDenied(error)) directAccessError = error;
|
|
244
|
+
// Search is the compatibility path when direct order reads are unavailable.
|
|
245
|
+
}
|
|
246
|
+
const response = await searchOrders({
|
|
247
|
+
search: {
|
|
248
|
+
filter: { "buyerInfo.email": { $eq: email }, $or: [
|
|
249
|
+
{ id: { $eq: id } },
|
|
250
|
+
...(/^\d+$/.test(id) && Number.isSafeInteger(Number(id)) ? [{ number: { $eq: Number(id) } }] : []),
|
|
251
|
+
] },
|
|
252
|
+
cursorPaging: { limit: 50 },
|
|
253
|
+
sort: [{ fieldName: "createdDate", order: "DESC" }],
|
|
254
|
+
},
|
|
255
|
+
}).catch(error => {
|
|
256
|
+
// A failed compatibility request cannot turn known denial into cached access.
|
|
257
|
+
throw directAccessError ?? error;
|
|
258
|
+
});
|
|
259
|
+
return (response.orders ?? []).find((order) => belongsTo(order, email) && (order.id === id || String(order.number ?? "") === id));
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
function orderState(order: WixOrder): Partial<State> {
|
|
263
|
+
return {
|
|
264
|
+
...orderDelivery(order),
|
|
265
|
+
title: copyTemplate("order.orderTitle", "Order #{number}", { number: order.number || order.id || "" }),
|
|
266
|
+
placedAt: formatDate(order.createdDate),
|
|
267
|
+
fulfillmentStatus: titleCase(order.fulfillmentStatus) || copyParam("order.statusFallback", "Order placed"),
|
|
268
|
+
paymentStatus: titleCase(order.paymentStatus) || copyParam("order.paymentStatusUnavailable", "Payment status unavailable"),
|
|
269
|
+
subtotal: order.priceSummary?.subtotal?.formattedAmount || "",
|
|
270
|
+
shipping: order.priceSummary?.shipping?.formattedAmount || "",
|
|
271
|
+
tax: order.priceSummary?.tax?.formattedAmount || "",
|
|
272
|
+
discount: order.priceSummary?.discount?.formattedAmount || "",
|
|
273
|
+
total: order.priceSummary?.total?.formattedAmount || copyParam("order.totalUnavailableLabel", "Total unavailable"),
|
|
274
|
+
rows: lineRows(order),
|
|
275
|
+
};
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
let loadVersion = 0;
|
|
279
|
+
let loadedMember: OrderMember | undefined;
|
|
280
|
+
function clearOrder(state: State): State {
|
|
281
|
+
return derive({ ...state, title: "", placedAt: "", deliveryTitle: "", deliveryLines: "", deliveryMethod: "", deliveryAddress: "", fulfillmentStatus: "", paymentStatus: "", subtotal: "", shipping: "", tax: "", discount: "", total: "", rows: [], reorderRefs: [], reorderMessage: "", emptyText: "", needsSignIn: false, permissionDenied: false });
|
|
282
|
+
}
|
|
283
|
+
async function load(state: State, arg?: unknown): Promise<State | undefined> {
|
|
284
|
+
const version = ++loadVersion;
|
|
285
|
+
loadedMember = undefined;
|
|
286
|
+
stashCopy(arg);
|
|
287
|
+
state = clearOrder(state);
|
|
288
|
+
const finish = (next: State) => version === loadVersion ? derive(next) : undefined;
|
|
289
|
+
const id = inputId();
|
|
290
|
+
const member = await orderMember();
|
|
291
|
+
const signInText = copyParam("order.signInEmptyText", "Sign in to view this order.");
|
|
292
|
+
if (!id) return finish({ ...state, status: "ready", emptyText: member.email ? copyParam("order.notFoundEmptyText", "Order not found.") : signInText });
|
|
293
|
+
const signInRequired = (status: State["status"]) => finish({ ...state, id, status, needsSignIn: true, emptyText: signInText });
|
|
294
|
+
if (!member.email) return signInRequired("ready");
|
|
295
|
+
try {
|
|
296
|
+
const order = await findOwnedOrder(id, member.email);
|
|
297
|
+
await assertOrderMember(member);
|
|
298
|
+
if (version !== loadVersion) return undefined;
|
|
299
|
+
if (!order) return finish({ ...state, status: "ready", emptyText: copyParam("order.unavailableEmptyText", "Order details are unavailable.") });
|
|
300
|
+
loadedMember = member;
|
|
301
|
+
return finish({ ...state, ...orderState(order), id, status: "ready", reorderRefs: reorderRefs(order), reorderMessage: "", emptyText: "" });
|
|
302
|
+
} catch (error) {
|
|
303
|
+
if (version !== loadVersion) return undefined;
|
|
304
|
+
try { await assertOrderMember(member); } catch {
|
|
305
|
+
return signInRequired("error");
|
|
306
|
+
}
|
|
307
|
+
const cached = orderAccessDenied(error) ? null : await readCachedOrder(id, member);
|
|
308
|
+
try { await assertOrderMember(member); } catch {
|
|
309
|
+
return signInRequired("error");
|
|
310
|
+
}
|
|
311
|
+
if (cached) {
|
|
312
|
+
return finish({ ...state, status: "ready", title: String(cached.title ?? "") || copyTemplate("order.orderTitle", "Order #{number}", { number: id }),
|
|
313
|
+
placedAt: String(cached.meta ?? ""), fulfillmentStatus: String(cached.status ?? ""),
|
|
314
|
+
total: String(cached.subtitle ?? ""), emptyText: copyParam("order.cachedText", "Saved order summary. Connect to refresh details."),
|
|
315
|
+
});
|
|
316
|
+
}
|
|
317
|
+
return finish({ ...state, status: "error", permissionDenied: orderAccessDenied(error), emptyText: orderAccessDenied(error)
|
|
318
|
+
? copyParam("order.accessErrorText", "Order details are unavailable for this account.")
|
|
319
|
+
: copyParam("order.loadErrorText", "Order details could not be loaded.") });
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/**
|
|
324
|
+
* #2050 — how long a member may follow one order in the background.
|
|
325
|
+
*
|
|
326
|
+
* 24 hours, not "forever": expiry is the only bound that holds when every other arm
|
|
327
|
+
* fails (the app is deleted, the process never runs again, a revocation POST is lost
|
|
328
|
+
* offline), and a delivery a member is actively watching resolves within a day. The
|
|
329
|
+
* registry refuses frames past it and the device refuses them again. Longer than the
|
|
330
|
+
* owner's 12h because a member follows a shipment, not a same-day fulfilment task.
|
|
331
|
+
*/
|
|
332
|
+
const FOLLOW_TTL_SECONDS = 24 * 60 * 60;
|
|
333
|
+
|
|
334
|
+
const reorderPricing = createIapCommerce();
|
|
335
|
+
const defineService = withOnlineWrites(registerService, ["reorder", "follow", "unfollow"], { derive, messageFields: action => action === "reorder" ? ["reorderMessage"] : ["liveNote"] });
|
|
336
|
+
const svc = defineService<State, {
|
|
337
|
+
load: (state: State, arg?: unknown) => Promise<State | undefined>;
|
|
338
|
+
retry: (state: State) => Promise<State | undefined>;
|
|
339
|
+
reorder: (state: State) => Promise<State | undefined>;
|
|
340
|
+
follow: (state: State) => State | undefined;
|
|
341
|
+
onFollowStarted: (state: State, activityId?: string) => State;
|
|
342
|
+
unfollow: (state: State) => State;
|
|
343
|
+
}>("himiBrandedOrder", {
|
|
344
|
+
state: derive({
|
|
345
|
+
status: "loading",
|
|
346
|
+
title: "",
|
|
347
|
+
placedAt: "",
|
|
348
|
+
deliveryTitle: "",
|
|
349
|
+
deliveryLines: "",
|
|
350
|
+
deliveryMethod: "",
|
|
351
|
+
deliveryAddress: "",
|
|
352
|
+
noDelivery: true,
|
|
353
|
+
fulfillmentStatus: "",
|
|
354
|
+
paymentStatus: "",
|
|
355
|
+
subtotal: "",
|
|
356
|
+
shipping: "",
|
|
357
|
+
tax: "",
|
|
358
|
+
discount: "",
|
|
359
|
+
total: "",
|
|
360
|
+
rows: [],
|
|
361
|
+
reorderRefs: [],
|
|
362
|
+
canReorder: false,
|
|
363
|
+
cannotReorder: true,
|
|
364
|
+
reorderMessage: "",
|
|
365
|
+
emptyText: "",
|
|
366
|
+
needsSignIn: false,
|
|
367
|
+
noSignIn: true,
|
|
368
|
+
isLoading: true,
|
|
369
|
+
notLoading: false,
|
|
370
|
+
isErrored: false,
|
|
371
|
+
notErrored: true,
|
|
372
|
+
noEmpty: true,
|
|
373
|
+
hideContent: true,
|
|
374
|
+
hasShipping: false,
|
|
375
|
+
noShipping: true,
|
|
376
|
+
hasTax: false,
|
|
377
|
+
noTax: true,
|
|
378
|
+
hasDiscount: false,
|
|
379
|
+
noDiscount: true,
|
|
380
|
+
id: "",
|
|
381
|
+
...IDLE_LIVE_SESSION,
|
|
382
|
+
}),
|
|
383
|
+
actions: {
|
|
384
|
+
load,
|
|
385
|
+
retry: (state) => load({ ...state, status: "loading", emptyText: "" }),
|
|
386
|
+
// #2050 — follow this order's delivery on the lock screen / status bar. The
|
|
387
|
+
// worker names the RECORD only; the host supplies the account, the site and the
|
|
388
|
+
// push token, so a worker cannot scope a subscription to another member.
|
|
389
|
+
//
|
|
390
|
+
// Guarded on a LOADED order (`!hideContent`) rather than on the id alone: the id
|
|
391
|
+
// survives a failed load, and registering from there would subscribe to a record
|
|
392
|
+
// this member's ownership was never established for — which `findOwnedOrder` and
|
|
393
|
+
// `assertOrderMember` exist to establish.
|
|
394
|
+
follow: (state) => {
|
|
395
|
+
if (state.liveTracking || !state.id || state.hideContent) return undefined;
|
|
396
|
+
liveSession = beginLiveSession({
|
|
397
|
+
activityType: "member_order",
|
|
398
|
+
entityType: "order",
|
|
399
|
+
entityId: state.id,
|
|
400
|
+
headline: state.title || copyParam("order.followHeadline", "Your order"),
|
|
401
|
+
detail: [state.fulfillmentStatus, state.total].filter(Boolean).join(" · "),
|
|
402
|
+
deepLink: `himalaya-himi-branded-lite://screen/himi_order?id=${encodeURIComponent(state.id)}`,
|
|
403
|
+
ttlSeconds: FOLLOW_TTL_SECONDS,
|
|
404
|
+
startingNote: copyParam("order.followStarting", "Starting…"),
|
|
405
|
+
unavailableNote: copyParam("order.followUnavailable", "This device has no live surface."),
|
|
406
|
+
onStarted: (activityId) => { svc.onFollowStarted(activityId); },
|
|
407
|
+
});
|
|
408
|
+
return derive({ ...state });
|
|
409
|
+
},
|
|
410
|
+
onFollowStarted: (state, activityId) => {
|
|
411
|
+
liveSession = liveSessionStarted(
|
|
412
|
+
activityId ?? "",
|
|
413
|
+
copyParam("order.followActive", "Following this order"),
|
|
414
|
+
copyParam("order.followUnavailable", "This device has no live surface."),
|
|
415
|
+
);
|
|
416
|
+
return derive({ ...state });
|
|
417
|
+
},
|
|
418
|
+
// Ending goes through the capability, which retires the local mapping AND revokes
|
|
419
|
+
// the server subscription — so "stop following" actually stops delivery rather
|
|
420
|
+
// than only hiding the surface.
|
|
421
|
+
unfollow: (state) => {
|
|
422
|
+
liveSession = stopLiveSession(
|
|
423
|
+
state.liveActivityId,
|
|
424
|
+
copyParam("order.followStopped", "No longer following"),
|
|
425
|
+
);
|
|
426
|
+
return derive({ ...state });
|
|
427
|
+
},
|
|
428
|
+
reorder: async (state) => {
|
|
429
|
+
const version = loadVersion;
|
|
430
|
+
const member = loadedMember;
|
|
431
|
+
try { if (!member) throw new Error("No current order"); await assertOrderMember(member); }
|
|
432
|
+
catch { return version === loadVersion ? derive({ ...clearOrder(state), status: "error", emptyText: copyParam("order.signInEmptyText", "Sign in to view this order.") }) : undefined; }
|
|
433
|
+
if (version !== loadVersion) return undefined;
|
|
434
|
+
if (!state.reorderRefs.length) return derive({ ...state, reorderMessage: copyParam("order.reorderNoneMessage", "Nothing on this order can be re-added.") });
|
|
435
|
+
try {
|
|
436
|
+
const refs = state.reorderRefs;
|
|
437
|
+
if (refs.some(ref => ref.appId !== "215238eb-22a5-4c36-9e7b-e7c08025e04e")) return derive({ ...state, reorderMessage: iapPriceCopy("order").purchaseUnavailable });
|
|
438
|
+
await reorderPricing.loadPrices(refs.map(ref => ({ reference: { kind: "storesProduct", id: ref.catalogItemId } })));
|
|
439
|
+
const route = classifyCart(refs.map(ref => ({ route: reorderPricing.pricing.view({ kind: "storesProduct", id: ref.catalogItemId }).route, quantity: ref.quantity })));
|
|
440
|
+
const products = await Promise.all(refs.map(async ref => (await getStoreProduct(ref.catalogItemId)).product));
|
|
441
|
+
if (route !== "regular" || products.some(product => product?.productType?.toLowerCase() !== "physical")) return derive({ ...state, reorderMessage: iapPriceCopy("order").purchaseUnavailable });
|
|
442
|
+
await assertOrderMember(member);
|
|
443
|
+
if (version !== loadVersion) return undefined;
|
|
444
|
+
} catch {
|
|
445
|
+
if (version !== loadVersion) return undefined;
|
|
446
|
+
try { await assertOrderMember(member); }
|
|
447
|
+
catch { return derive({ ...clearOrder(state), status: "error", emptyText: copyParam("order.signInEmptyText", "Sign in to view this order.") }); }
|
|
448
|
+
return derive({ ...state, reorderMessage: iapPriceCopy("order").purchaseUnavailable });
|
|
449
|
+
}
|
|
450
|
+
const results = await Promise.allSettled(
|
|
451
|
+
state.reorderRefs.map((ref) => addToCurrentCart(ref.catalogItemId, ref.quantity, ref.options)),
|
|
452
|
+
);
|
|
453
|
+
// A pending mutation must never restore an older order after navigation or sign-out.
|
|
454
|
+
if (version !== loadVersion) return undefined;
|
|
455
|
+
try { await assertOrderMember(member!); }
|
|
456
|
+
catch { return version === loadVersion ? derive({ ...clearOrder(state), status: "error", emptyText: copyParam("order.signInEmptyText", "Sign in to view this order.") }) : undefined; }
|
|
457
|
+
if (version !== loadVersion) return undefined;
|
|
458
|
+
const added = results.filter((result) => result.status === "fulfilled").length;
|
|
459
|
+
if (!added) return derive({ ...state, reorderMessage: copyParam("order.reorderFailedMessage", "These items could not be added to the cart.") });
|
|
460
|
+
const skipped = state.reorderRefs.length - added;
|
|
461
|
+
return derive({
|
|
462
|
+
...state,
|
|
463
|
+
reorderMessage: skipped
|
|
464
|
+
? `Added ${added} of ${state.reorderRefs.length} items to your cart.`
|
|
465
|
+
: `Added ${added} ${added === 1 ? "item" : "items"} to your cart.`,
|
|
466
|
+
});
|
|
467
|
+
},
|
|
468
|
+
},
|
|
469
|
+
});
|
|
470
|
+
|
|
471
|
+
svc.load();
|
|
472
|
+
export { svc };
|