@misiki/gocommerce-connector 0.1.0 → 0.2.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/README.md +155 -152
- package/dist/index-CJ836ZI3.d.cts +5424 -0
- package/dist/index-CJ836ZI3.d.ts +5424 -0
- package/dist/index.cjs +2308 -2066
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +85 -1
- package/dist/index.d.ts +85 -1
- package/dist/index.js +2273 -2037
- package/dist/index.js.map +1 -1
- package/dist/services/index.cjs +2256 -2061
- package/dist/services/index.cjs.map +1 -1
- package/dist/services/index.d.cts +1 -4742
- package/dist/services/index.d.ts +1 -4742
- package/dist/services/index.js +2247 -2027
- package/dist/services/index.js.map +1 -1
- package/package.json +9 -7
package/dist/services/index.cjs
CHANGED
|
@@ -1,2352 +1,2571 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
// src/
|
|
4
|
-
var API_PROXY_PREFIX = "/proxy/gocommerce";
|
|
3
|
+
// src/errors.ts
|
|
5
4
|
var GoCommerceError = class extends Error {
|
|
5
|
+
status;
|
|
6
6
|
code;
|
|
7
7
|
details;
|
|
8
|
-
status
|
|
9
|
-
constructor(message, code = "internal_error", status = 0, details) {
|
|
8
|
+
constructor(message, status, code, details) {
|
|
10
9
|
super(message);
|
|
11
10
|
this.name = "GoCommerceError";
|
|
12
|
-
this.code = code;
|
|
13
11
|
this.status = status;
|
|
12
|
+
this.code = code;
|
|
14
13
|
this.details = details;
|
|
15
14
|
}
|
|
16
15
|
};
|
|
17
|
-
var
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
this.
|
|
16
|
+
var NotSupportedError = class extends Error {
|
|
17
|
+
service;
|
|
18
|
+
method;
|
|
19
|
+
constructor(service, method, detail) {
|
|
20
|
+
super(`${service}.${method}() is not supported by GoCommerce${detail ? `: ${detail}` : "."}`);
|
|
21
|
+
this.name = "NotSupportedError";
|
|
22
|
+
this.service = service;
|
|
23
|
+
this.method = method;
|
|
23
24
|
}
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
// src/rest-guard.ts
|
|
28
|
+
var COLLECTION_SEGMENTS = /* @__PURE__ */ new Set([
|
|
29
|
+
"all",
|
|
30
|
+
"list",
|
|
31
|
+
"list-by-parent",
|
|
32
|
+
"list-public",
|
|
33
|
+
"latest",
|
|
34
|
+
"search",
|
|
35
|
+
"public",
|
|
36
|
+
"public-details",
|
|
37
|
+
"me",
|
|
38
|
+
"multiple"
|
|
39
|
+
]);
|
|
40
|
+
var emptyResult = () => ({ data: [], count: 0, pageSize: 0, noOfPage: 0, page: 1 });
|
|
41
|
+
var addressesOneRecord = (url) => {
|
|
42
|
+
const segments = url.split("?")[0].split("/").filter(Boolean);
|
|
43
|
+
if (segments.length < 3) return false;
|
|
44
|
+
return !COLLECTION_SEGMENTS.has(segments[segments.length - 1].toLowerCase());
|
|
45
|
+
};
|
|
46
|
+
var reported = /* @__PURE__ */ new Set();
|
|
47
|
+
var report = (method, url) => {
|
|
48
|
+
const key = `${method} ${url.split("?")[0]}`;
|
|
49
|
+
if (reported.has(key)) return;
|
|
50
|
+
reported.add(key);
|
|
51
|
+
console.warn(
|
|
52
|
+
`[gocommerce] no native implementation for \`${key}\` \u2014 that is a Litekart REST path, and it was not called.`
|
|
53
|
+
);
|
|
54
|
+
};
|
|
55
|
+
var localResolver;
|
|
56
|
+
var resolveRestLocally = async (method, url) => {
|
|
57
|
+
if (method === "get") {
|
|
58
|
+
const local = await localResolver?.(url);
|
|
59
|
+
if (local !== void 0) return local;
|
|
60
|
+
}
|
|
61
|
+
report(method, url);
|
|
62
|
+
if (method !== "get" || addressesOneRecord(url)) {
|
|
63
|
+
throw new Error(`This feature is not available on this store (gocommerce).`);
|
|
64
|
+
}
|
|
65
|
+
return emptyResult();
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
// src/browser.ts
|
|
69
|
+
var inBrowser = () => typeof window !== "undefined" && typeof document !== "undefined";
|
|
70
|
+
function readLocal(key) {
|
|
71
|
+
if (!inBrowser()) return null;
|
|
72
|
+
try {
|
|
73
|
+
return window.localStorage.getItem(key);
|
|
74
|
+
} catch {
|
|
75
|
+
return null;
|
|
27
76
|
}
|
|
28
|
-
|
|
29
|
-
|
|
77
|
+
}
|
|
78
|
+
function writeLocal(key, value) {
|
|
79
|
+
if (!inBrowser()) return;
|
|
80
|
+
try {
|
|
81
|
+
window.localStorage.setItem(key, value);
|
|
82
|
+
} catch {
|
|
30
83
|
}
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
return
|
|
84
|
+
}
|
|
85
|
+
function removeLocal(key) {
|
|
86
|
+
if (!inBrowser()) return;
|
|
87
|
+
try {
|
|
88
|
+
window.localStorage.removeItem(key);
|
|
89
|
+
} catch {
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
function readJSON(key) {
|
|
93
|
+
const raw = readLocal(key);
|
|
94
|
+
if (!raw) return null;
|
|
95
|
+
try {
|
|
96
|
+
return JSON.parse(raw);
|
|
97
|
+
} catch {
|
|
98
|
+
return null;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
var YEAR = 60 * 60 * 24 * 365;
|
|
102
|
+
function setCookie(name, value, maxAge = YEAR) {
|
|
103
|
+
if (!inBrowser()) return;
|
|
104
|
+
document.cookie = `${name}=${value}; path=/; max-age=${maxAge}; samesite=lax`;
|
|
105
|
+
}
|
|
106
|
+
function clearCookie(name) {
|
|
107
|
+
if (!inBrowser()) return;
|
|
108
|
+
document.cookie = `${name}=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT`;
|
|
109
|
+
}
|
|
110
|
+
function readCookie(name) {
|
|
111
|
+
if (!inBrowser()) return null;
|
|
112
|
+
for (const pair of document.cookie.split(";")) {
|
|
113
|
+
const at = pair.indexOf("=");
|
|
114
|
+
if (at < 0) continue;
|
|
115
|
+
if (pair.slice(0, at).trim() === name) return pair.slice(at + 1).trim();
|
|
116
|
+
}
|
|
117
|
+
return null;
|
|
118
|
+
}
|
|
119
|
+
var TOKEN = "gocommerce_token";
|
|
120
|
+
var sessionToken = () => readLocal(TOKEN);
|
|
121
|
+
function toMe(c) {
|
|
122
|
+
const [firstName, ...rest] = (c.name ?? "").trim().split(/\s+/);
|
|
123
|
+
return {
|
|
124
|
+
id: String(c.id),
|
|
125
|
+
userId: String(c.id),
|
|
126
|
+
email: c.email,
|
|
127
|
+
phone: c.phone || null,
|
|
128
|
+
firstName: firstName || "",
|
|
129
|
+
lastName: rest.join(" "),
|
|
130
|
+
name: c.name ?? "",
|
|
131
|
+
fullName: c.name ?? "",
|
|
132
|
+
avatar: null,
|
|
133
|
+
role: "USER",
|
|
134
|
+
emailVerified: c.email_verified,
|
|
135
|
+
storeId: null
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
function startSession(auth) {
|
|
139
|
+
writeLocal(TOKEN, auth.token);
|
|
140
|
+
const me = toMe(auth.record);
|
|
141
|
+
const expires = Math.max(60, Math.floor((Date.parse(auth.expires_at) - Date.now()) / 1e3)) || YEAR;
|
|
142
|
+
setCookie("me", encodeURIComponent(JSON.stringify(me)), expires);
|
|
143
|
+
setCookie("connect.sid", "gocommerce", expires);
|
|
144
|
+
return me;
|
|
145
|
+
}
|
|
146
|
+
function updateMe(c) {
|
|
147
|
+
const me = toMe(c);
|
|
148
|
+
setCookie("me", encodeURIComponent(JSON.stringify(me)));
|
|
149
|
+
return me;
|
|
150
|
+
}
|
|
151
|
+
function endSession() {
|
|
152
|
+
removeLocal(TOKEN);
|
|
153
|
+
clearCookie("me");
|
|
154
|
+
clearCookie("connect.sid");
|
|
155
|
+
}
|
|
156
|
+
function currentMe() {
|
|
157
|
+
const raw = readCookie("me");
|
|
158
|
+
if (!raw) return null;
|
|
159
|
+
try {
|
|
160
|
+
return JSON.parse(decodeURIComponent(raw));
|
|
161
|
+
} catch {
|
|
162
|
+
return null;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
function storedCartId() {
|
|
166
|
+
const v = readLocal("cart_id");
|
|
167
|
+
if (!v || v === "undefined" || v === "null") return null;
|
|
168
|
+
return v;
|
|
169
|
+
}
|
|
170
|
+
var rememberCartId = (id) => writeLocal("cart_id", id);
|
|
171
|
+
var extrasKey = (cartId) => `gocommerce_cart_${cartId}`;
|
|
172
|
+
var cartExtras = (cartId) => readJSON(extrasKey(cartId)) ?? {};
|
|
173
|
+
function saveCartExtras(cartId, patch) {
|
|
174
|
+
const next = { ...cartExtras(cartId), ...patch };
|
|
175
|
+
writeLocal(extrasKey(cartId), JSON.stringify(next));
|
|
176
|
+
return next;
|
|
177
|
+
}
|
|
178
|
+
var forgetCartExtras = (cartId) => removeLocal(extrasKey(cartId));
|
|
179
|
+
var ORDERS = "gocommerce_orders";
|
|
180
|
+
var placedOrders = () => readJSON(ORDERS) ?? [];
|
|
181
|
+
function rememberOrder(o) {
|
|
182
|
+
const kept = placedOrders().filter((p) => p.number !== o.number);
|
|
183
|
+
writeLocal(ORDERS, JSON.stringify([o, ...kept].slice(0, 50)));
|
|
184
|
+
}
|
|
185
|
+
var placedOrder = (number) => placedOrders().find((p) => p.number === number);
|
|
186
|
+
var placedOrderForCart = (cartId) => placedOrders().find((p) => p.cartId === cartId);
|
|
187
|
+
var placedOrderByReference = (reference) => placedOrders().find((p) => p.reference === reference);
|
|
188
|
+
var WISHLIST = "gocommerce_wishlist";
|
|
189
|
+
var wishlistToken = () => readLocal(WISHLIST);
|
|
190
|
+
var rememberWishlistToken = (token) => writeLocal(WISHLIST, token);
|
|
191
|
+
var forgetWishlistToken = () => removeLocal(WISHLIST);
|
|
192
|
+
|
|
193
|
+
// src/services/base.service.ts
|
|
194
|
+
var BaseService = class _BaseService {
|
|
195
|
+
static _credentials = { apiUrl: "" };
|
|
196
|
+
_fetch;
|
|
197
|
+
constructor(fetchFn) {
|
|
198
|
+
this._fetch = fetchFn ?? ((input, init) => globalThis.fetch(input, init));
|
|
44
199
|
}
|
|
45
|
-
/**
|
|
46
|
-
* The hook the storefront's `src/lib/core/connectors/init.ts` calls with `PUBLIC_GOCOMMERCE_*`. Merges, so a
|
|
47
|
-
* later call with a subset never erases the base url an earlier one established.
|
|
48
|
-
*/
|
|
49
200
|
static setCredentials(creds) {
|
|
50
201
|
_BaseService._credentials = { ..._BaseService._credentials, ...creds };
|
|
51
202
|
}
|
|
52
203
|
static getCredentials() {
|
|
53
204
|
return _BaseService._credentials;
|
|
54
205
|
}
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
}
|
|
58
|
-
/** Trailing slashes stripped so `${base}/api/products` never doubles up. */
|
|
59
|
-
static getBaseUrl() {
|
|
60
|
-
return (_BaseService._credentials.apiUrl || "").replace(/\/+$/, "");
|
|
61
|
-
}
|
|
62
|
-
static setLanguageCode(code) {
|
|
63
|
-
_BaseService._languageCode = code;
|
|
64
|
-
}
|
|
65
|
-
static getLanguageCode() {
|
|
66
|
-
return _BaseService._languageCode;
|
|
67
|
-
}
|
|
68
|
-
setBaseUrl(url) {
|
|
69
|
-
_BaseService.setBaseUrl(url);
|
|
70
|
-
return this;
|
|
71
|
-
}
|
|
72
|
-
getBaseUrl() {
|
|
73
|
-
return _BaseService.getBaseUrl();
|
|
206
|
+
get creds() {
|
|
207
|
+
return _BaseService._credentials;
|
|
74
208
|
}
|
|
75
209
|
/**
|
|
76
|
-
*
|
|
77
|
-
*
|
|
78
|
-
* GoCommerce sends no CORS headers and answers a preflight with 405, so a browser cannot reach
|
|
79
|
-
* it cross-origin at all — and neither can a universal `+page.ts` load, because SvelteKit
|
|
80
|
-
* simulates the same CORS check server-side for consistency. So anything the browser issues goes
|
|
81
|
-
* through this storefront's own origin (`src/routes/proxy/gocommerce/[...path]`), which is
|
|
82
|
-
* same-origin and needs no headers from the API.
|
|
83
|
-
*
|
|
84
|
-
* On the server there is no such rule, and the extra hop through the storefront's own handler
|
|
85
|
-
* would be a request the process makes to itself, so it calls the API directly.
|
|
210
|
+
* The engine's base URL from wherever this code runs. In the browser a
|
|
211
|
+
* configured proxy path wins, because the engine answers no CORS preflight.
|
|
86
212
|
*/
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
const base = _BaseService.getBaseUrl();
|
|
92
|
-
if (!base) {
|
|
93
|
-
throw new GoCommerceError("PUBLIC_GOCOMMERCE_API_URL is not configured \u2014 add it to .env (see docs/GOCOMMERCE.md).", "not_ready");
|
|
213
|
+
engineBase() {
|
|
214
|
+
const { apiUrl, proxyPath } = this.creds;
|
|
215
|
+
if (proxyPath && typeof window !== "undefined" && window.location) {
|
|
216
|
+
return new URL(proxyPath, window.location.origin).href.replace(/\/+$/, "");
|
|
94
217
|
}
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
* to be reachable from. A url that is already absolute belongs to someone else's host and is
|
|
104
|
-
* left exactly as it is.
|
|
105
|
-
*/
|
|
106
|
-
static mediaUrl(path) {
|
|
107
|
-
if (/^https?:\/\//i.test(path)) return path;
|
|
108
|
-
return `${API_PROXY_PREFIX}${path.startsWith("/") ? path : `/${path}`}`;
|
|
218
|
+
const url = (apiUrl ?? "").trim();
|
|
219
|
+
if (!url) {
|
|
220
|
+
throw new GoCommerceError(
|
|
221
|
+
"PUBLIC_GOCOMMERCE_API_URL is not set, so this storefront does not know where its commerce engine is. Point it at a running GoCommerce, e.g. http://127.0.0.1:8080.",
|
|
222
|
+
0
|
|
223
|
+
);
|
|
224
|
+
}
|
|
225
|
+
return url.replace(/\/+$/, "");
|
|
109
226
|
}
|
|
110
|
-
|
|
111
|
-
|
|
227
|
+
/** An absolute engine URL for a path and query, without sending anything. */
|
|
228
|
+
engineURL(path, query) {
|
|
229
|
+
return this.engineBase() + path + qs(query);
|
|
112
230
|
}
|
|
113
231
|
/**
|
|
114
|
-
* One request
|
|
232
|
+
* One request to the engine, envelope and all.
|
|
115
233
|
*
|
|
116
|
-
*
|
|
117
|
-
*
|
|
118
|
-
* stale, and that sentence is what the shopper needs to see.
|
|
234
|
+
* The body is read as text first, so a proxy's HTML error page is reported
|
|
235
|
+
* as what it is rather than as a JSON parse error three frames away.
|
|
119
236
|
*/
|
|
120
|
-
async
|
|
121
|
-
const url =
|
|
122
|
-
const
|
|
237
|
+
async engine(path, req = {}) {
|
|
238
|
+
const url = this.engineURL(path, req.query);
|
|
239
|
+
const headers = { Accept: "application/json", ...req.headers };
|
|
240
|
+
if (req.body !== void 0) headers["Content-Type"] = "application/json";
|
|
241
|
+
if (this.creds.store) headers["X-Store"] = this.creds.store;
|
|
242
|
+
if (req.auth) {
|
|
243
|
+
const token = sessionToken();
|
|
244
|
+
if (!token) throw new GoCommerceError("Please sign in to continue.", 401, "unauthorized");
|
|
245
|
+
headers.Authorization = `Bearer ${token}`;
|
|
246
|
+
}
|
|
247
|
+
const init = {
|
|
248
|
+
method: req.method ?? "GET",
|
|
249
|
+
headers,
|
|
250
|
+
body: req.body === void 0 ? void 0 : JSON.stringify(req.body)
|
|
251
|
+
};
|
|
123
252
|
let res;
|
|
124
253
|
try {
|
|
125
|
-
res = await this.
|
|
126
|
-
method,
|
|
127
|
-
headers: {
|
|
128
|
-
Accept: "application/json",
|
|
129
|
-
...body === void 0 ? {} : { "Content-Type": "application/json" },
|
|
130
|
-
...lang ? { "Accept-Language": lang } : {},
|
|
131
|
-
...headers
|
|
132
|
-
},
|
|
133
|
-
...body === void 0 ? {} : { body: JSON.stringify(body) }
|
|
134
|
-
});
|
|
254
|
+
res = await this._fetch.call(globalThis, url, init);
|
|
135
255
|
} catch (cause) {
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
256
|
+
if (typeof window === "undefined" && /CORS/i.test(String(cause?.message))) {
|
|
257
|
+
try {
|
|
258
|
+
res = await globalThis.fetch(url, init);
|
|
259
|
+
} catch (again) {
|
|
260
|
+
throw unreachable(this.engineBase(), again);
|
|
261
|
+
}
|
|
262
|
+
} else {
|
|
263
|
+
throw unreachable(this.engineBase(), cause);
|
|
264
|
+
}
|
|
143
265
|
}
|
|
266
|
+
return this.unwrap(res);
|
|
267
|
+
}
|
|
268
|
+
/** The envelope opened: the payload, or the engine's error as a GoCommerceError. */
|
|
269
|
+
async unwrap(res) {
|
|
144
270
|
const text = await res.text();
|
|
145
|
-
let parsed =
|
|
271
|
+
let parsed = null;
|
|
146
272
|
if (text) {
|
|
147
273
|
try {
|
|
148
274
|
parsed = JSON.parse(text);
|
|
149
275
|
} catch {
|
|
150
|
-
throw new GoCommerceError(
|
|
276
|
+
throw new GoCommerceError(
|
|
277
|
+
`The commerce engine answered ${res.status} with something that is not JSON: ${text.slice(0, 120)}`,
|
|
278
|
+
res.status
|
|
279
|
+
);
|
|
151
280
|
}
|
|
152
281
|
}
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
const error = envelope.error;
|
|
282
|
+
if (!res.ok) {
|
|
283
|
+
const err = parsed?.error ?? {};
|
|
156
284
|
throw new GoCommerceError(
|
|
157
|
-
|
|
158
|
-
error?.code || "internal_error",
|
|
285
|
+
err.message ?? `The commerce engine answered ${res.status}.`,
|
|
159
286
|
res.status,
|
|
160
|
-
|
|
287
|
+
err.code,
|
|
288
|
+
err.details
|
|
161
289
|
);
|
|
162
290
|
}
|
|
163
|
-
return { data:
|
|
291
|
+
return parsed ?? { data: null };
|
|
292
|
+
}
|
|
293
|
+
/** The bare payload, for the many callers that never look at `meta`. */
|
|
294
|
+
async data(path, req = {}) {
|
|
295
|
+
return (await this.engine(path, req)).data;
|
|
164
296
|
}
|
|
165
297
|
/**
|
|
166
|
-
*
|
|
167
|
-
*
|
|
168
|
-
*
|
|
298
|
+
* Prices a cart at the signed-in shopper's customer-group prices. The
|
|
299
|
+
* engine does this only for an account whose email is confirmed (403
|
|
300
|
+
* otherwise), and the cart stays the shopper's either way — so a refusal
|
|
301
|
+
* is not an error, and neither is a build without ext/identity.
|
|
169
302
|
*/
|
|
170
|
-
async
|
|
171
|
-
|
|
172
|
-
|
|
303
|
+
async claimCartForAccount(cartId) {
|
|
304
|
+
try {
|
|
305
|
+
await this.engine("/x/identity/me/carts", { method: "POST", body: { cart_id: cartId }, auth: true });
|
|
306
|
+
} catch {
|
|
307
|
+
}
|
|
173
308
|
}
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
309
|
+
// ------------------------------------------------------------ Litekart verbs
|
|
310
|
+
/**
|
|
311
|
+
* The family's path-addressed verbs. An absolute URL is fetched as-is; a
|
|
312
|
+
* relative one is a Litekart REST path, answered from the storefront's own
|
|
313
|
+
* data where it has some and refused otherwise (rest-guard.ts).
|
|
314
|
+
*/
|
|
315
|
+
get(path) {
|
|
316
|
+
return this.raw("get", path);
|
|
181
317
|
}
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
method: "PUT",
|
|
185
|
-
headers: { "Content-Type": "application/json", Accept: "application/json" },
|
|
186
|
-
body: JSON.stringify(data)
|
|
187
|
-
});
|
|
188
|
-
return await res.json();
|
|
318
|
+
post(path, data) {
|
|
319
|
+
return this.raw("post", path, data);
|
|
189
320
|
}
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
method: "PATCH",
|
|
193
|
-
headers: { "Content-Type": "application/json", Accept: "application/json" },
|
|
194
|
-
body: JSON.stringify(data)
|
|
195
|
-
});
|
|
196
|
-
return await res.json();
|
|
321
|
+
put(path, data) {
|
|
322
|
+
return this.raw("put", path, data);
|
|
197
323
|
}
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
return await res.json();
|
|
324
|
+
patch(path, data) {
|
|
325
|
+
return this.raw("patch", path, data);
|
|
201
326
|
}
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
}
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
if (!
|
|
327
|
+
delete(path) {
|
|
328
|
+
return this.raw("delete", path);
|
|
329
|
+
}
|
|
330
|
+
async raw(method, path, data) {
|
|
331
|
+
if (!/^https?:\/\//i.test(path)) return await resolveRestLocally(method, path);
|
|
332
|
+
const res = await this._fetch.call(globalThis, path, {
|
|
333
|
+
method: method.toUpperCase(),
|
|
334
|
+
headers: { Accept: "application/json", ...data === void 0 ? {} : { "Content-Type": "application/json" } },
|
|
335
|
+
body: data === void 0 ? void 0 : JSON.stringify(data)
|
|
336
|
+
});
|
|
337
|
+
const body = await res.json().catch(() => ({}));
|
|
338
|
+
if (!res.ok)
|
|
339
|
+
throw new GoCommerceError(body?.error?.message ?? `Request failed with status ${res.status}`, res.status);
|
|
340
|
+
return body;
|
|
341
|
+
}
|
|
342
|
+
};
|
|
343
|
+
var unreachable = (base, cause) => new GoCommerceError(`Could not reach the commerce engine at ${base}: ${cause?.message ?? cause}`, 0);
|
|
344
|
+
function qs(query) {
|
|
345
|
+
if (!query) return "";
|
|
346
|
+
const sp = new URLSearchParams();
|
|
347
|
+
for (const [key, value] of Object.entries(query)) {
|
|
348
|
+
if (value === void 0 || value === null || value === "") continue;
|
|
349
|
+
if (Array.isArray(value)) for (const v of value) sp.append(key, String(v));
|
|
350
|
+
else sp.append(key, String(value));
|
|
351
|
+
}
|
|
352
|
+
const s = sp.toString();
|
|
353
|
+
return s ? `?${s}` : "";
|
|
354
|
+
}
|
|
355
|
+
function toPage(env, map) {
|
|
356
|
+
const rows = env.data ?? [];
|
|
357
|
+
const meta = env.meta;
|
|
221
358
|
return {
|
|
222
|
-
|
|
223
|
-
|
|
359
|
+
data: rows.map(map),
|
|
360
|
+
count: meta?.total ?? rows.length,
|
|
361
|
+
pageSize: meta?.limit ?? rows.length,
|
|
362
|
+
noOfPage: meta?.total_pages ?? 1,
|
|
363
|
+
page: meta?.page ?? 1
|
|
224
364
|
};
|
|
225
|
-
}
|
|
226
|
-
var
|
|
365
|
+
}
|
|
366
|
+
var emptyPage = () => ({ data: [], count: 0, pageSize: 0, noOfPage: 0, page: 1 });
|
|
227
367
|
|
|
228
|
-
// src/
|
|
229
|
-
var
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
368
|
+
// src/money.ts
|
|
369
|
+
var ZERO_DECIMAL = /* @__PURE__ */ new Set([
|
|
370
|
+
"BIF",
|
|
371
|
+
"CLP",
|
|
372
|
+
"DJF",
|
|
373
|
+
"GNF",
|
|
374
|
+
"ISK",
|
|
375
|
+
"JPY",
|
|
376
|
+
"KMF",
|
|
377
|
+
"KRW",
|
|
378
|
+
"PYG",
|
|
379
|
+
"RWF",
|
|
380
|
+
"UGX",
|
|
381
|
+
"VND",
|
|
382
|
+
"VUV",
|
|
383
|
+
"XAF",
|
|
384
|
+
"XOF",
|
|
385
|
+
"XPF"
|
|
386
|
+
]);
|
|
387
|
+
var THREE_DECIMAL = /* @__PURE__ */ new Set(["BHD", "IQD", "JOD", "KWD", "LYD", "OMR", "TND"]);
|
|
388
|
+
function currencyExponent(code) {
|
|
389
|
+
const c = (code ?? "").toUpperCase();
|
|
390
|
+
if (ZERO_DECIMAL.has(c)) return 0;
|
|
391
|
+
if (THREE_DECIMAL.has(c)) return 3;
|
|
392
|
+
return 2;
|
|
393
|
+
}
|
|
394
|
+
function toMajor(money) {
|
|
395
|
+
if (!money) return 0;
|
|
396
|
+
return minorToMajor(money.amount_minor, money.currency);
|
|
397
|
+
}
|
|
398
|
+
function minorToMajor(minor, currency) {
|
|
399
|
+
if (minor === null || minor === void 0 || !Number.isFinite(minor)) return 0;
|
|
400
|
+
const exp = currencyExponent(currency);
|
|
401
|
+
if (exp === 0) return minor;
|
|
402
|
+
return Number((minor / 10 ** exp).toFixed(exp));
|
|
403
|
+
}
|
|
404
|
+
function toMinor(amount, currency) {
|
|
405
|
+
const exp = currencyExponent(currency);
|
|
406
|
+
return Math.round(amount * 10 ** exp);
|
|
407
|
+
}
|
|
250
408
|
|
|
251
|
-
// src/
|
|
252
|
-
var
|
|
253
|
-
var
|
|
254
|
-
var
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
}
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
noOfPage: 0,
|
|
267
|
-
page
|
|
268
|
-
});
|
|
269
|
-
var fromListMeta = (data, meta, fallbackPage = 1) => {
|
|
270
|
-
const count = meta?.total ?? data.length;
|
|
271
|
-
const pageSize = meta?.limit || data.length || PAGE_SIZE;
|
|
272
|
-
return {
|
|
273
|
-
data,
|
|
274
|
-
count,
|
|
275
|
-
pageSize,
|
|
276
|
-
noOfPage: meta?.total_pages ?? (Math.ceil(count / pageSize) || (count ? 1 : 0)),
|
|
277
|
-
page: meta?.page ?? fallbackPage
|
|
409
|
+
// src/map.ts
|
|
410
|
+
var str = (v) => v === null || v === void 0 ? "" : String(v);
|
|
411
|
+
var arr = (v) => v ?? [];
|
|
412
|
+
var liveVariants = (p) => arr(p.variants).filter((v) => v.active);
|
|
413
|
+
function variantImages(v) {
|
|
414
|
+
const out = [];
|
|
415
|
+
for (const img of [v.image, ...arr(v.images)]) {
|
|
416
|
+
if (img?.url && (img.kind ?? "image") === "image" && !out.includes(img.url)) out.push(img.url);
|
|
417
|
+
}
|
|
418
|
+
return out;
|
|
419
|
+
}
|
|
420
|
+
function productImages(p) {
|
|
421
|
+
const out = [];
|
|
422
|
+
const push = (url) => {
|
|
423
|
+
if (url && !out.includes(url)) out.push(url);
|
|
278
424
|
};
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
const available = Math.max(0, variant.available ?? 0);
|
|
287
|
-
return available === 0 && variant.continue_selling ? UNTRACKED_STOCK : available;
|
|
288
|
-
};
|
|
289
|
-
var productImages = (product) => {
|
|
290
|
-
const seen = /* @__PURE__ */ new Set();
|
|
291
|
-
const featured = absoluteMedia(product?.image_url);
|
|
292
|
-
if (featured) seen.add(featured);
|
|
293
|
-
for (const variant of product?.variants || []) {
|
|
294
|
-
const url = absoluteMedia(variant?.image?.url);
|
|
295
|
-
if (url) seen.add(url);
|
|
296
|
-
}
|
|
297
|
-
return [...seen];
|
|
298
|
-
};
|
|
299
|
-
var flattenMetadata = (metadata) => {
|
|
300
|
-
if (!metadata || typeof metadata !== "object") return null;
|
|
301
|
-
const out = {};
|
|
302
|
-
const printable = (value) => {
|
|
303
|
-
if (value === null || value === void 0 || value === "") return void 0;
|
|
304
|
-
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") return String(value);
|
|
305
|
-
if (Array.isArray(value)) {
|
|
306
|
-
const items = value.map(printable).filter(Boolean);
|
|
307
|
-
return items.length ? items.join(", ") : void 0;
|
|
308
|
-
}
|
|
309
|
-
return void 0;
|
|
310
|
-
};
|
|
311
|
-
const walk = (node, namespace = "") => {
|
|
312
|
-
for (const [key, value] of Object.entries(node)) {
|
|
313
|
-
const text = printable(value);
|
|
314
|
-
if (text !== void 0) {
|
|
315
|
-
out[key in out && namespace ? `${namespace} ${key}` : key] = text;
|
|
316
|
-
continue;
|
|
317
|
-
}
|
|
318
|
-
if (value && typeof value === "object" && !Array.isArray(value)) walk(value, key);
|
|
319
|
-
}
|
|
320
|
-
};
|
|
321
|
-
walk(metadata);
|
|
322
|
-
return Object.keys(out).length ? out : null;
|
|
323
|
-
};
|
|
324
|
-
var optionValueId = (product, optionIndex, value) => product?.options?.[optionIndex]?.values?.find((v) => v.value === value)?.id ?? `${optionIndex}-${value}`;
|
|
325
|
-
var mapVariant = (product, variant) => {
|
|
326
|
-
const price = fromMoney(variant.price);
|
|
327
|
-
const compareAt = fromMoney(variant.compare_at_price);
|
|
328
|
-
const image = absoluteMedia(variant.image?.url) || absoluteMedia(product.image_url);
|
|
425
|
+
push(p.image_url);
|
|
426
|
+
for (const v of arr(p.variants)) for (const url of variantImages(v)) push(url);
|
|
427
|
+
return out;
|
|
428
|
+
}
|
|
429
|
+
function toVariant(v, p, optionless) {
|
|
430
|
+
const images = variantImages(v);
|
|
431
|
+
const options = arr(p.options);
|
|
329
432
|
return {
|
|
330
|
-
id:
|
|
331
|
-
|
|
332
|
-
//
|
|
333
|
-
//
|
|
334
|
-
title:
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
height: null,
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
// No compare-at price recorded means nothing is on sale; mrp equals price so the components
|
|
357
|
-
// print one number instead of a struck-through duplicate.
|
|
358
|
-
mrp: compareAt > price ? compareAt : price,
|
|
359
|
-
img: image,
|
|
360
|
-
description: null,
|
|
361
|
-
storeId: null,
|
|
362
|
-
len: null,
|
|
363
|
-
rank: variant.position ?? 0,
|
|
364
|
-
shippingWeight: null,
|
|
365
|
-
shippingHeight: null,
|
|
366
|
-
shippingLen: null,
|
|
367
|
-
shippingWidth: null,
|
|
368
|
-
shippingCost: null,
|
|
369
|
-
metadata: variant.metadata ?? null,
|
|
370
|
-
variantRank: variant.position ?? 0,
|
|
371
|
-
// A variant's `options` are the VALUES, positionally aligned with the product's option list.
|
|
372
|
-
options: (variant.options || []).map((value, index) => ({
|
|
373
|
-
id: optionValueId(product, index, value),
|
|
374
|
-
optionId: product.options?.[index]?.id ?? index,
|
|
375
|
-
value,
|
|
376
|
-
variantId: variant.id
|
|
377
|
-
}))
|
|
433
|
+
id: str(v.id),
|
|
434
|
+
productId: str(v.product_id),
|
|
435
|
+
// The storefront picks the default variant of an optionless product by
|
|
436
|
+
// this exact title, and hides the variant name when it sees it.
|
|
437
|
+
title: optionless ? "default" : v.label || v.sku,
|
|
438
|
+
sku: v.sku,
|
|
439
|
+
barcode: v.barcode ?? null,
|
|
440
|
+
price: toMajor(v.price),
|
|
441
|
+
mrp: toMajor(v.compare_at_price ?? v.price),
|
|
442
|
+
// The engine's own vocabulary, unchanged: `available` is on hand minus
|
|
443
|
+
// reserved; an untracked variant is never managed, so its count is moot.
|
|
444
|
+
stock: v.active ? v.available : 0,
|
|
445
|
+
manageInventory: v.active ? v.track_inventory : true,
|
|
446
|
+
allowBackorder: v.active && v.continue_selling,
|
|
447
|
+
active: v.active,
|
|
448
|
+
weight: v.weight_grams ?? null,
|
|
449
|
+
length: v.dimensions?.length_mm ?? null,
|
|
450
|
+
width: v.dimensions?.width_mm ?? null,
|
|
451
|
+
height: v.dimensions?.height_mm ?? null,
|
|
452
|
+
images: images.join(","),
|
|
453
|
+
img: images[0] ?? null,
|
|
454
|
+
image: images[0] ?? null,
|
|
455
|
+
thumbnail: images[0] ?? null,
|
|
456
|
+
// Values in option order — `options[i]` answers `p.options[i]`.
|
|
457
|
+
options: arr(v.options).map((value, i) => ({ optionId: str(options[i]?.id), value })),
|
|
458
|
+
metadata: v.metadata ?? null
|
|
378
459
|
};
|
|
379
|
-
}
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
const
|
|
383
|
-
const
|
|
384
|
-
const
|
|
385
|
-
const
|
|
386
|
-
const
|
|
387
|
-
const
|
|
388
|
-
const
|
|
389
|
-
const featured = images[0] || null;
|
|
390
|
-
const first = primaryVariant(product);
|
|
460
|
+
}
|
|
461
|
+
function toProduct(p, extra = {}) {
|
|
462
|
+
const live = liveVariants(p);
|
|
463
|
+
const lead = live[0] ?? arr(p.variants)[0];
|
|
464
|
+
const optionless = arr(p.options).length === 0;
|
|
465
|
+
const images = productImages(p);
|
|
466
|
+
const prices = live.map((v) => toMajor(v.price));
|
|
467
|
+
const tracked = live.filter((v) => v.track_inventory);
|
|
468
|
+
const category = p.category;
|
|
469
|
+
const tags = arr(p.tags);
|
|
391
470
|
return {
|
|
392
|
-
id:
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
active:
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
471
|
+
id: str(p.id),
|
|
472
|
+
slug: p.slug,
|
|
473
|
+
title: p.title,
|
|
474
|
+
name: p.title,
|
|
475
|
+
subtitle: null,
|
|
476
|
+
description: p.description ?? "",
|
|
477
|
+
status: p.status === "active" ? "published" : p.status,
|
|
478
|
+
active: p.status === "active",
|
|
479
|
+
type: p.product_type ?? "",
|
|
480
|
+
currency: p.currency,
|
|
481
|
+
currencyCode: p.currency,
|
|
482
|
+
price: lead ? toMajor(lead.price) : 0,
|
|
483
|
+
mrp: lead ? toMajor(lead.compare_at_price ?? lead.price) : 0,
|
|
484
|
+
minPrice: prices.length ? Math.min(...prices) : 0,
|
|
485
|
+
maxPrice: prices.length ? Math.max(...prices) : 0,
|
|
486
|
+
sku: lead?.sku ?? null,
|
|
487
|
+
barcode: lead?.barcode ?? null,
|
|
488
|
+
weight: lead?.weight_grams ?? null,
|
|
489
|
+
originCountry: lead?.origin_country ?? null,
|
|
490
|
+
thumbnail: images[0] ?? null,
|
|
491
|
+
image_url: images[0] ?? null,
|
|
408
492
|
images: images.join(","),
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
replaceAllowed: false,
|
|
436
|
-
originCountry: first?.origin_country || null,
|
|
437
|
-
weightUnit: first?.weight_unit || "g",
|
|
438
|
-
dimensionUnit: "cm",
|
|
439
|
-
metadata: flattenMetadata(product.metadata),
|
|
440
|
-
collectionId: product.collections?.[0]?.id ?? null,
|
|
441
|
-
tags: product.tags || [],
|
|
442
|
-
vendor: product.vendor || null,
|
|
443
|
-
categories: product.category ? [{ category: { id: product.category.id, name: product.category.title, slug: product.category.slug } }] : [],
|
|
444
|
-
createdAt: product.created_at || null,
|
|
445
|
-
updatedAt: product.updated_at || null,
|
|
446
|
-
options: (product.options || []).map((option) => ({
|
|
447
|
-
id: option.id,
|
|
448
|
-
title: option.name,
|
|
449
|
-
type: "radio",
|
|
450
|
-
values: (option.values || []).map((v) => ({ id: v.id, value: v.value }))
|
|
493
|
+
imageList: images,
|
|
494
|
+
// Product-level stock is what a card shows before a variant is picked:
|
|
495
|
+
// buyable when any live variant is, counted only where counting means
|
|
496
|
+
// something.
|
|
497
|
+
manageInventory: live.length > 0 && tracked.length === live.length,
|
|
498
|
+
allowBackorder: live.some((v) => v.continue_selling),
|
|
499
|
+
stock: tracked.reduce((n, v) => n + Math.max(0, v.available), 0),
|
|
500
|
+
hasStock: live.some((v) => !v.track_inventory || v.continue_selling || v.available > 0),
|
|
501
|
+
categoryId: category ? str(category.id) : null,
|
|
502
|
+
category: category ? { id: str(category.id), name: category.title, slug: category.slug } : null,
|
|
503
|
+
categories: category ? [{ category: { id: str(category.id), name: category.title, slug: category.slug } }] : [],
|
|
504
|
+
categoryHierarchy: extra.categoryHierarchy ?? (category ? [{ name: category.title, slug: category.slug }] : []),
|
|
505
|
+
collections: arr(p.collections).map((c) => ({ id: str(c.id), name: c.title, slug: c.slug })),
|
|
506
|
+
// Free text on the engine's product, not a vendor record.
|
|
507
|
+
vendor: p.vendor ? { businessName: p.vendor } : null,
|
|
508
|
+
productTags: tags.join(","),
|
|
509
|
+
keywords: tags.join(","),
|
|
510
|
+
metaTitle: p.seo_title || p.title,
|
|
511
|
+
metaDescription: p.seo_description || null,
|
|
512
|
+
link: `/products/${p.slug}`,
|
|
513
|
+
options: arr(p.options).map((o) => ({
|
|
514
|
+
id: str(o.id),
|
|
515
|
+
title: o.name,
|
|
516
|
+
name: o.name,
|
|
517
|
+
type: "text",
|
|
518
|
+
values: arr(o.values).map((val) => ({ id: str(val.id), value: val.value }))
|
|
451
519
|
})),
|
|
452
|
-
variants:
|
|
520
|
+
variants: live.map((v) => toVariant(v, p, optionless)),
|
|
521
|
+
// Filled by the product page from ext/reviews when it is installed.
|
|
522
|
+
ratings: [],
|
|
523
|
+
rating: null,
|
|
524
|
+
ratingCount: 0,
|
|
525
|
+
reviewCount: 0,
|
|
526
|
+
attributes: [],
|
|
527
|
+
metadata: p.metadata ?? null,
|
|
528
|
+
createdAt: p.created_at,
|
|
529
|
+
updatedAt: p.updated_at
|
|
453
530
|
};
|
|
454
|
-
}
|
|
455
|
-
|
|
456
|
-
|
|
531
|
+
}
|
|
532
|
+
function fromSearchDoc(d) {
|
|
533
|
+
const price = minorToMajor(d.price_minor, d.currency);
|
|
534
|
+
return {
|
|
535
|
+
id: str(d.id),
|
|
536
|
+
slug: d.slug,
|
|
537
|
+
title: d.title,
|
|
538
|
+
name: d.title,
|
|
539
|
+
description: d.description,
|
|
540
|
+
currency: d.currency,
|
|
541
|
+
price,
|
|
542
|
+
mrp: price,
|
|
543
|
+
minPrice: price,
|
|
544
|
+
maxPrice: minorToMajor(d.price_max_minor, d.currency),
|
|
545
|
+
thumbnail: d.image ?? null,
|
|
546
|
+
image_url: d.image ?? null,
|
|
547
|
+
images: d.image ?? "",
|
|
548
|
+
stock: d.in_stock ? 1 : 0,
|
|
549
|
+
hasStock: d.in_stock,
|
|
550
|
+
// The index cannot say how much is left, only whether any is; a card
|
|
551
|
+
// built from it must not claim to count.
|
|
552
|
+
manageInventory: false,
|
|
553
|
+
allowBackorder: false,
|
|
554
|
+
productTags: arr(d.tags).join(","),
|
|
555
|
+
category: d.category ? { name: d.category.split(" / ").pop() ?? d.category, slug: "" } : null,
|
|
556
|
+
vendor: d.vendor ? { businessName: d.vendor } : null,
|
|
557
|
+
variants: [],
|
|
558
|
+
options: [],
|
|
559
|
+
ratings: [],
|
|
560
|
+
link: `/products/${d.slug}`,
|
|
561
|
+
updatedAt: new Date(d.updated_at * 1e3).toISOString()
|
|
562
|
+
};
|
|
563
|
+
}
|
|
564
|
+
function toCategory(c) {
|
|
457
565
|
return {
|
|
458
|
-
id:
|
|
566
|
+
id: str(c.id),
|
|
567
|
+
name: c.title,
|
|
568
|
+
title: c.title,
|
|
569
|
+
slug: c.slug,
|
|
570
|
+
link: `/${c.slug}`,
|
|
571
|
+
parentCategoryId: c.parent_id === null || c.parent_id === void 0 ? null : str(c.parent_id),
|
|
572
|
+
path: c.full_name,
|
|
573
|
+
level: c.depth,
|
|
574
|
+
rank: c.position,
|
|
575
|
+
childCount: c.child_count,
|
|
576
|
+
thumbnail: c.metadata?.image ?? null,
|
|
577
|
+
description: c.metadata?.description ?? null,
|
|
459
578
|
isActive: true,
|
|
460
|
-
isInternal: false,
|
|
461
|
-
isMegamenu: false,
|
|
462
|
-
thumbnail: null,
|
|
463
|
-
path: category.full_name || null,
|
|
464
|
-
level: category.depth ?? 0,
|
|
465
|
-
description: null,
|
|
466
579
|
isFeatured: false,
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
metaTitle: null,
|
|
473
|
-
name: category.title,
|
|
474
|
-
// The storefront's filter composable rebuilds the tree from this field.
|
|
475
|
-
parentCategoryId: category.parent_id ?? null,
|
|
476
|
-
store: null,
|
|
477
|
-
slug: category.slug,
|
|
478
|
-
userId: "",
|
|
479
|
-
activeProducts: 0,
|
|
480
|
-
inactiveProducts: 0,
|
|
481
|
-
createdAt: category.created_at || null,
|
|
482
|
-
updatedAt: category.updated_at || null
|
|
580
|
+
isMegamenu: false,
|
|
581
|
+
metaTitle: c.title,
|
|
582
|
+
children: arr(c.children).map(toCategory),
|
|
583
|
+
createdAt: c.created_at,
|
|
584
|
+
updatedAt: c.updated_at
|
|
483
585
|
};
|
|
484
|
-
}
|
|
485
|
-
|
|
486
|
-
if (!collection) return null;
|
|
487
|
-
const products = collection.products || [];
|
|
586
|
+
}
|
|
587
|
+
function toCollection(c) {
|
|
488
588
|
return {
|
|
489
|
-
id:
|
|
490
|
-
name:
|
|
491
|
-
|
|
492
|
-
|
|
589
|
+
id: str(c.id),
|
|
590
|
+
name: c.title,
|
|
591
|
+
title: c.title,
|
|
592
|
+
slug: c.slug,
|
|
593
|
+
description: c.description || null,
|
|
594
|
+
subTitle: null,
|
|
595
|
+
rank: str(c.position),
|
|
596
|
+
thumbnail: c.metadata?.image ?? null,
|
|
493
597
|
isActive: true,
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
metaDescription: null,
|
|
499
|
-
rank: collection.position ?? 0,
|
|
500
|
-
collectionvalues: products.map((product) => {
|
|
501
|
-
const mapped = mapProduct(product);
|
|
502
|
-
return {
|
|
503
|
-
products: {
|
|
504
|
-
id: product.id,
|
|
505
|
-
name: product.title,
|
|
506
|
-
title: product.title,
|
|
507
|
-
slug: product.slug,
|
|
508
|
-
thumbnail: mapped?.thumbnail || null,
|
|
509
|
-
price: mapped?.price ?? 0,
|
|
510
|
-
mrp: mapped?.mrp ?? 0
|
|
511
|
-
}
|
|
512
|
-
};
|
|
513
|
-
}),
|
|
514
|
-
productCount: products.length,
|
|
515
|
-
createdAt: collection.created_at || null,
|
|
516
|
-
updatedAt: collection.updated_at || null
|
|
598
|
+
metaTitle: c.title,
|
|
599
|
+
metaDescription: c.description || null,
|
|
600
|
+
createdAt: c.created_at,
|
|
601
|
+
updatedAt: c.updated_at
|
|
517
602
|
};
|
|
518
|
-
}
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
const
|
|
522
|
-
const mapped = product ? mapProduct(product) : null;
|
|
523
|
-
const variant = product?.variants?.find((v) => v.id === line.variant_id);
|
|
524
|
-
const price = fromMoney(line.unit_price);
|
|
525
|
-
const compareAt = fromMoney(variant?.compare_at_price);
|
|
526
|
-
const thumbnail = absoluteMedia(variant?.image?.url) || mapped?.thumbnail || null;
|
|
603
|
+
}
|
|
604
|
+
function fromEngineAddress(a, email) {
|
|
605
|
+
if (!a) return null;
|
|
606
|
+
const [firstName, ...rest] = (a.name ?? "").trim().split(/\s+/);
|
|
527
607
|
return {
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
608
|
+
firstName: firstName || "",
|
|
609
|
+
lastName: rest.join(" "),
|
|
610
|
+
email: email ?? null,
|
|
611
|
+
phone: a.phone ?? null,
|
|
612
|
+
address_1: a.line1,
|
|
613
|
+
address_2: a.line2 ?? "",
|
|
614
|
+
city: a.city,
|
|
615
|
+
state: a.state ?? "",
|
|
616
|
+
zip: a.postal_code,
|
|
617
|
+
country: a.country,
|
|
618
|
+
countryCode: a.country
|
|
619
|
+
};
|
|
620
|
+
}
|
|
621
|
+
function toEngineAddress(a) {
|
|
622
|
+
const name = [a.firstName, a.lastName].filter(Boolean).join(" ").trim();
|
|
623
|
+
return {
|
|
624
|
+
...name ? { name } : {},
|
|
625
|
+
...a.phone ? { phone: String(a.phone) } : {},
|
|
626
|
+
line1: String(a.address_1 ?? "").trim(),
|
|
627
|
+
...a.address_2 || a.locality ? { line2: [a.address_2, a.locality].filter(Boolean).join(", ") } : {},
|
|
628
|
+
city: String(a.city ?? "").trim(),
|
|
629
|
+
...a.state ? { state: String(a.state) } : {},
|
|
630
|
+
postal_code: String(a.zip ?? "").trim(),
|
|
631
|
+
country: String(a.countryCode || a.country || "").trim().toUpperCase()
|
|
632
|
+
};
|
|
633
|
+
}
|
|
634
|
+
function fromIdentityAddress(a, email) {
|
|
635
|
+
const [firstName, ...rest] = (a.name ?? "").trim().split(/\s+/);
|
|
636
|
+
return {
|
|
637
|
+
id: str(a.id),
|
|
638
|
+
firstName: firstName || "",
|
|
639
|
+
lastName: rest.join(" "),
|
|
640
|
+
email: email ?? null,
|
|
641
|
+
phone: a.phone || null,
|
|
642
|
+
address_1: a.line1,
|
|
643
|
+
address_2: a.line2,
|
|
644
|
+
city: a.city,
|
|
645
|
+
state: a.state,
|
|
646
|
+
zip: a.postal_code,
|
|
647
|
+
country: a.country,
|
|
648
|
+
countryCode: a.country,
|
|
649
|
+
label: a.label,
|
|
650
|
+
isPrimary: a.is_default,
|
|
651
|
+
createdAt: a.created_at,
|
|
652
|
+
updatedAt: a.updated_at
|
|
653
|
+
};
|
|
654
|
+
}
|
|
655
|
+
function toIdentityAddress(a) {
|
|
656
|
+
const e = toEngineAddress(a);
|
|
657
|
+
return {
|
|
658
|
+
name: e.name ?? "",
|
|
659
|
+
phone: e.phone ?? "",
|
|
660
|
+
line1: e.line1,
|
|
661
|
+
line2: e.line2 ?? "",
|
|
662
|
+
city: e.city,
|
|
663
|
+
state: e.state ?? "",
|
|
664
|
+
postal_code: e.postal_code,
|
|
665
|
+
country: e.country,
|
|
666
|
+
...a.label ? { label: String(a.label) } : {},
|
|
667
|
+
...a.isPrimary ? { is_default: true } : {}
|
|
668
|
+
};
|
|
669
|
+
}
|
|
670
|
+
function toCartLine(l, extra = {}) {
|
|
671
|
+
return {
|
|
672
|
+
id: str(l.id),
|
|
673
|
+
productId: str(l.product_id),
|
|
674
|
+
variantId: str(l.variant_id),
|
|
675
|
+
sku: l.sku,
|
|
676
|
+
title: l.title,
|
|
677
|
+
name: l.title,
|
|
678
|
+
slug: extra.slug ?? "",
|
|
679
|
+
thumbnail: extra.thumbnail ?? null,
|
|
680
|
+
variantTitle: l.variant_label ?? "",
|
|
681
|
+
qty: l.quantity,
|
|
682
|
+
price: toMajor(l.unit_price),
|
|
683
|
+
mrp: toMajor(l.unit_price),
|
|
684
|
+
subtotal: toMajor(l.total),
|
|
685
|
+
total: toMajor(l.total),
|
|
686
|
+
inStock: l.in_stock,
|
|
687
|
+
priceChanged: l.price_changed,
|
|
688
|
+
currentPrice: toMajor(l.current_price),
|
|
689
|
+
// The storefront's review step lists only lines marked for checkout. The
|
|
690
|
+
// engine checks a cart out whole, so every line is.
|
|
555
691
|
isSelectedForCheckout: true,
|
|
556
|
-
// Surfaced so the cart can warn, instead of letting checkout refuse the whole order later.
|
|
557
|
-
priceChanged: Boolean(line.price_changed),
|
|
558
|
-
inStock: line.in_stock !== false,
|
|
559
|
-
createdAt: null,
|
|
560
|
-
product: {
|
|
561
|
-
id: line.product_id,
|
|
562
|
-
title: line.title || mapped?.title || "",
|
|
563
|
-
thumbnail,
|
|
564
|
-
slug: mapped?.slug || "",
|
|
565
|
-
sku: line.sku || "",
|
|
566
|
-
categories: mapped?.categories || []
|
|
567
|
-
},
|
|
568
692
|
variant: {
|
|
569
|
-
id:
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
height: null,
|
|
574
|
-
width: null,
|
|
575
|
-
len: null,
|
|
576
|
-
shippingWeight: null,
|
|
577
|
-
shippingHeight: null,
|
|
578
|
-
shippingLen: null,
|
|
579
|
-
shippingWidth: null,
|
|
580
|
-
sku: line.sku || "",
|
|
581
|
-
title: line.variant_label || variant?.label || "default",
|
|
582
|
-
options: variant && product ? mapVariant(product, variant).options : []
|
|
583
|
-
}
|
|
693
|
+
id: str(l.variant_id),
|
|
694
|
+
options: l.variant_label ? l.variant_label.split(" / ").map((value) => ({ option: { title: "" }, value })) : []
|
|
695
|
+
},
|
|
696
|
+
product: { id: str(l.product_id), categories: [] }
|
|
584
697
|
};
|
|
585
|
-
}
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
const currency =
|
|
589
|
-
const
|
|
590
|
-
const
|
|
591
|
-
const
|
|
592
|
-
const
|
|
698
|
+
}
|
|
699
|
+
function toCart(c, extras = {}, lineExtra = () => ({})) {
|
|
700
|
+
const lines = c.status === "converted" ? [] : arr(c.line_items);
|
|
701
|
+
const currency = c.currency;
|
|
702
|
+
const subtotalMinor = lines.reduce((n, l) => n + l.total.amount_minor, 0);
|
|
703
|
+
const discountMinor = extras.discount && !extras.discount.free_shipping ? extras.discount.amount_minor : 0;
|
|
704
|
+
const shippingMinor = extras.discount?.free_shipping ? 0 : extras.shippingRate?.minor ?? 0;
|
|
705
|
+
const totalMinor = Math.max(0, subtotalMinor - discountMinor) + shippingMinor;
|
|
706
|
+
const money = (minor) => minorToMajor(minor, currency);
|
|
707
|
+
const ship = extras.shippingAddress ?? null;
|
|
593
708
|
return {
|
|
594
|
-
id:
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
709
|
+
id: c.id,
|
|
710
|
+
status: c.status,
|
|
711
|
+
email: c.email ?? ship?.email ?? null,
|
|
712
|
+
phone: extras.phone ?? ship?.phone ?? null,
|
|
713
|
+
name: ship ? [ship.firstName, ship.lastName].filter(Boolean).join(" ") : null,
|
|
714
|
+
lineItems: lines.map((l) => toCartLine(l, lineExtra(l))),
|
|
715
|
+
qty: lines.reduce((n, l) => n + l.quantity, 0),
|
|
716
|
+
currencyCode: currency,
|
|
717
|
+
currency,
|
|
718
|
+
subtotal: money(subtotalMinor),
|
|
719
|
+
discountAmount: money(discountMinor),
|
|
720
|
+
savingAmount: money(discountMinor),
|
|
721
|
+
couponCode: extras.discount?.code ?? null,
|
|
722
|
+
discount: extras.discount ?? null,
|
|
723
|
+
shippingCharges: money(shippingMinor),
|
|
724
|
+
shippingRateId: extras.shippingRateId ?? null,
|
|
725
|
+
shippingMethod: extras.shippingRate?.name ?? null,
|
|
726
|
+
tax: 0,
|
|
727
|
+
taxIncluded: false,
|
|
728
|
+
codCharges: 0,
|
|
729
|
+
total: money(totalMinor),
|
|
730
|
+
shippingAddress: ship,
|
|
731
|
+
shippingAddressId: ship ? ship.id && ship.id !== "new" ? String(ship.id) : "cart" : null,
|
|
732
|
+
billingAddress: extras.billingAddress ?? ship,
|
|
733
|
+
billingAddressId: extras.billingAddress ? extras.billingAddress.id && extras.billingAddress.id !== "new" ? String(extras.billingAddress.id) : "cart-billing" : ship ? ship.id && ship.id !== "new" ? String(ship.id) : "cart" : null,
|
|
734
|
+
paymentMethod: null,
|
|
735
|
+
needAddress: lines.length > 0,
|
|
736
|
+
completedAt: c.status === "converted" ? c.updated_at : null,
|
|
737
|
+
createdAt: c.created_at,
|
|
738
|
+
updatedAt: c.updated_at,
|
|
739
|
+
expiresAt: c.expires_at
|
|
740
|
+
};
|
|
741
|
+
}
|
|
742
|
+
function emptyCart(currency = "USD") {
|
|
743
|
+
return {
|
|
744
|
+
id: "",
|
|
745
|
+
status: "open",
|
|
746
|
+
email: null,
|
|
747
|
+
phone: null,
|
|
748
|
+
lineItems: [],
|
|
749
|
+
qty: 0,
|
|
750
|
+
currencyCode: currency,
|
|
751
|
+
subtotal: 0,
|
|
605
752
|
discountAmount: 0,
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
isCodAvailable: true,
|
|
609
|
-
paymentId: null,
|
|
610
|
-
type: null,
|
|
611
|
-
completedAt: cart.status === "converted" ? cart.updated_at || null : null,
|
|
612
|
-
paymentAuthorizedAt: null,
|
|
613
|
-
idempotencyKey: null,
|
|
614
|
-
salesChannelId: null,
|
|
615
|
-
qty: cart.item_count ?? lines.reduce((sum, l) => sum + (l.quantity || 0), 0),
|
|
616
|
-
// GoCommerce prices shipping at checkout, not on the cart, so there is nothing honest to put
|
|
617
|
-
// here yet — and a fabricated number is the one the shopper would check the total against.
|
|
753
|
+
savingAmount: 0,
|
|
754
|
+
couponCode: null,
|
|
618
755
|
shippingCharges: 0,
|
|
619
|
-
paymentMethod: null,
|
|
620
|
-
shippingMethod: null,
|
|
621
|
-
subtotal,
|
|
622
|
-
codCharges: 0,
|
|
623
756
|
tax: 0,
|
|
624
|
-
total:
|
|
625
|
-
|
|
626
|
-
|
|
757
|
+
total: 0,
|
|
758
|
+
shippingAddress: null,
|
|
759
|
+
shippingAddressId: null,
|
|
760
|
+
billingAddress: null,
|
|
761
|
+
billingAddressId: null
|
|
762
|
+
};
|
|
763
|
+
}
|
|
764
|
+
var STATUS = {
|
|
765
|
+
pending: "Pending",
|
|
766
|
+
confirmed: "Confirmed",
|
|
767
|
+
partial: "Partially shipped",
|
|
768
|
+
shipped: "Shipped",
|
|
769
|
+
delivered: "Delivered",
|
|
770
|
+
cancelled: "Cancelled"
|
|
771
|
+
};
|
|
772
|
+
var PAYMENT_STATUS = {
|
|
773
|
+
pending: "Pending",
|
|
774
|
+
paid: "Paid",
|
|
775
|
+
failed: "Failed",
|
|
776
|
+
refunded: "Refunded"
|
|
777
|
+
};
|
|
778
|
+
function toOrderLine(l, currency) {
|
|
779
|
+
return {
|
|
780
|
+
id: str(l.id),
|
|
781
|
+
productId: str(l.product_id),
|
|
782
|
+
variantId: str(l.variant_id),
|
|
783
|
+
sku: l.sku,
|
|
784
|
+
title: l.title,
|
|
785
|
+
name: l.title,
|
|
786
|
+
slug: "",
|
|
787
|
+
thumbnail: l.image_url ?? null,
|
|
788
|
+
img: l.image_url ?? null,
|
|
789
|
+
variantTitle: l.variant_label ?? "",
|
|
790
|
+
qty: l.quantity,
|
|
791
|
+
shippedQty: l.shipped_quantity,
|
|
792
|
+
price: toMajor(l.unit_price),
|
|
793
|
+
mrp: toMajor(l.unit_price),
|
|
794
|
+
subtotal: toMajor(l.total),
|
|
795
|
+
total: toMajor(l.total),
|
|
627
796
|
currencyCode: currency,
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
storeId: store?.id ?? null,
|
|
632
|
-
status: cart.status || "open",
|
|
633
|
-
createdAt: cart.created_at || null,
|
|
634
|
-
updatedAt: cart.updated_at || null,
|
|
635
|
-
deletedAt: null,
|
|
636
|
-
lineItems: lines.map((line) => mapCartLine(line, index)),
|
|
637
|
-
shippingAddress,
|
|
638
|
-
billingAddress
|
|
797
|
+
status: l.shipped_quantity >= l.quantity ? "Shipped" : "Pending",
|
|
798
|
+
files: [],
|
|
799
|
+
usedOptions: []
|
|
639
800
|
};
|
|
640
|
-
}
|
|
641
|
-
|
|
642
|
-
const
|
|
643
|
-
|
|
644
|
-
};
|
|
645
|
-
var toStorefrontAddress = (address, email, phone) => {
|
|
646
|
-
if (!address) return null;
|
|
647
|
-
const { firstName, lastName } = splitName(address.name);
|
|
801
|
+
}
|
|
802
|
+
function toOrder(o) {
|
|
803
|
+
const address = fromEngineAddress(o.address, o.email);
|
|
804
|
+
const code = (o.discounts ?? []).find((d) => d.code)?.code;
|
|
648
805
|
return {
|
|
649
|
-
id:
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
806
|
+
id: str(o.id),
|
|
807
|
+
orderNo: o.number,
|
|
808
|
+
orderNumber: o.number,
|
|
809
|
+
number: o.number,
|
|
810
|
+
// The storefront links an order by this; the engine has no sub-orders,
|
|
811
|
+
// so an order is its own parent.
|
|
812
|
+
parentOrderNo: o.number,
|
|
813
|
+
status: STATUS[o.status] ?? o.status,
|
|
814
|
+
engineStatus: o.status,
|
|
815
|
+
paymentStatus: PAYMENT_STATUS[o.payment_status] ?? o.payment_status,
|
|
816
|
+
paymentMethod: o.payment_provider.toUpperCase(),
|
|
817
|
+
currencyCode: o.currency,
|
|
818
|
+
subtotal: toMajor(o.subtotal),
|
|
819
|
+
shippingCharges: toMajor(o.shipping),
|
|
820
|
+
discount: toMajor(o.discount),
|
|
821
|
+
tax: toMajor(o.tax),
|
|
822
|
+
taxIncluded: o.tax_inclusive,
|
|
823
|
+
total: toMajor(o.total),
|
|
824
|
+
refunded: toMajor(o.refunded),
|
|
825
|
+
codCharges: 0,
|
|
826
|
+
coupon: code ? { code } : null,
|
|
827
|
+
userEmail: o.email,
|
|
828
|
+
email: o.email,
|
|
829
|
+
phone: o.phone ?? null,
|
|
830
|
+
shippingAddress: address,
|
|
831
|
+
billingAddress: address,
|
|
832
|
+
shippingMethod: o.shipping_method ?? null,
|
|
833
|
+
shippingRate: o.shipping_method ? { name: o.shipping_method } : null,
|
|
834
|
+
lineItems: arr(o.line_items).map((l) => toOrderLine(l, o.currency)),
|
|
835
|
+
fulfillments: arr(o.fulfillments).map((f) => ({
|
|
836
|
+
id: str(f.id),
|
|
837
|
+
status: f.status,
|
|
838
|
+
carrier: f.carrier_name || f.carrier || f.provider,
|
|
839
|
+
trackingNumber: f.tracking ?? null,
|
|
840
|
+
trackingUrl: f.tracking_url ?? null,
|
|
841
|
+
lineItems: arr(f.lines).map((l) => ({ id: str(l.order_line_id), title: l.title, qty: l.quantity })),
|
|
842
|
+
createdAt: f.created_at
|
|
843
|
+
})),
|
|
844
|
+
tracking: [],
|
|
845
|
+
orderHistory: [],
|
|
846
|
+
isReplaceOrReturn: false,
|
|
847
|
+
createdAt: o.created_at,
|
|
848
|
+
updatedAt: o.updated_at
|
|
664
849
|
};
|
|
665
|
-
}
|
|
666
|
-
|
|
667
|
-
if (!address) return null;
|
|
668
|
-
const name = [address.firstName, address.lastName].filter(Boolean).join(" ").trim() || address.name || "";
|
|
669
|
-
const line1 = address.address_1 || address.line1 || "";
|
|
670
|
-
const city = address.city || "";
|
|
671
|
-
const postal = address.zip || address.postal_code || "";
|
|
672
|
-
const country = address.countryCode || address.country_code || address.country || "";
|
|
673
|
-
if (!line1 || !city || !postal || !country) return null;
|
|
850
|
+
}
|
|
851
|
+
function toRating(r) {
|
|
674
852
|
return {
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
853
|
+
id: str(r.id),
|
|
854
|
+
rating: r.rating,
|
|
855
|
+
name: r.name,
|
|
856
|
+
title: r.title ?? "",
|
|
857
|
+
review: r.body,
|
|
858
|
+
message: r.body,
|
|
859
|
+
reply: r.reply ?? null,
|
|
860
|
+
verified: r.verified,
|
|
861
|
+
img: "",
|
|
862
|
+
createdAt: r.created_at
|
|
684
863
|
};
|
|
685
|
-
}
|
|
686
|
-
|
|
687
|
-
if (!order) return null;
|
|
688
|
-
const shippingAddress = toStorefrontAddress(order.address, order.email, order.phone);
|
|
864
|
+
}
|
|
865
|
+
function toCmsPage(p) {
|
|
689
866
|
return {
|
|
690
|
-
id:
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
discount: fromMoney(order.discount),
|
|
705
|
-
total: fromMoney(order.total),
|
|
706
|
-
currencyCode: order.currency,
|
|
707
|
-
currencyDecimalDigits: currencyFractionDigits(order.currency),
|
|
708
|
-
shippingRate: null,
|
|
709
|
-
fulfillments: (order.fulfillments || []).map((f) => ({
|
|
710
|
-
id: f.id,
|
|
711
|
-
status: f.status || "",
|
|
712
|
-
provider: f.provider || "",
|
|
713
|
-
trackingNumber: f.tracking || "",
|
|
714
|
-
labelUrl: f.label_url || "",
|
|
715
|
-
createdAt: f.created_at || null
|
|
716
|
-
})),
|
|
717
|
-
shippingAddress,
|
|
718
|
-
billingAddress: shippingAddress,
|
|
719
|
-
lineItems: (order.line_items || []).map((line) => {
|
|
720
|
-
const product = lineProduct(index, line.product_id);
|
|
721
|
-
const mapped = product ? mapProduct(product) : null;
|
|
722
|
-
const variant = product?.variants?.find((v) => v.id === line.variant_id);
|
|
723
|
-
return {
|
|
724
|
-
id: line.id,
|
|
725
|
-
productId: line.product_id,
|
|
726
|
-
variantId: line.variant_id,
|
|
727
|
-
title: line.title || mapped?.title || "",
|
|
728
|
-
variantTitle: line.variant_label || line.sku || "",
|
|
729
|
-
slug: mapped?.slug || "",
|
|
730
|
-
sku: line.sku || "",
|
|
731
|
-
thumbnail: absoluteMedia(variant?.image?.url) || mapped?.thumbnail || null,
|
|
732
|
-
qty: line.quantity,
|
|
733
|
-
price: fromMoney(line.unit_price),
|
|
734
|
-
// The orders list prints `total`; the confirmation page prints `subtotal`.
|
|
735
|
-
subtotal: fromMoney(line.total),
|
|
736
|
-
total: fromMoney(line.total)
|
|
737
|
-
};
|
|
738
|
-
})
|
|
867
|
+
id: str(p.id),
|
|
868
|
+
slug: p.slug,
|
|
869
|
+
name: p.title,
|
|
870
|
+
title: p.title,
|
|
871
|
+
content: p.body,
|
|
872
|
+
excerpt: p.excerpt ?? null,
|
|
873
|
+
layouts: [],
|
|
874
|
+
language: p.language,
|
|
875
|
+
metaTitle: p.seo?.title || p.title,
|
|
876
|
+
metaDescription: p.seo?.description || p.excerpt || null,
|
|
877
|
+
metaKeywords: p.seo?.keywords || null,
|
|
878
|
+
publishedAt: p.published_at ?? null,
|
|
879
|
+
createdAt: p.created_at,
|
|
880
|
+
updatedAt: p.updated_at
|
|
739
881
|
};
|
|
740
|
-
}
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
};
|
|
774
|
-
var writeCheckoutDetails = (cartId, patch) => {
|
|
775
|
-
if (!cartId) return patch;
|
|
776
|
-
const merged = { ...readCheckoutDetails(cartId), ...patch };
|
|
777
|
-
writeJson(`${DETAILS_PREFIX}${cartId}`, merged);
|
|
778
|
-
return merged;
|
|
779
|
-
};
|
|
780
|
-
var clearCheckoutDetails = (cartId) => {
|
|
781
|
-
const store = storage();
|
|
782
|
-
if (!store || !cartId) return;
|
|
783
|
-
try {
|
|
784
|
-
store.removeItem(`${DETAILS_PREFIX}${cartId}`);
|
|
785
|
-
} catch {
|
|
786
|
-
}
|
|
787
|
-
};
|
|
788
|
-
var rememberOrderToken = (orderNumber, token) => {
|
|
789
|
-
if (!orderNumber || !token) return;
|
|
790
|
-
const tokens = readJson(ORDER_TOKENS_KEY) ?? {};
|
|
791
|
-
tokens[orderNumber] = token;
|
|
792
|
-
writeJson(ORDER_TOKENS_KEY, tokens);
|
|
793
|
-
};
|
|
794
|
-
var readOrderToken = (orderNumber) => {
|
|
795
|
-
if (!orderNumber) return void 0;
|
|
796
|
-
return (readJson(ORDER_TOKENS_KEY) ?? {})[orderNumber];
|
|
797
|
-
};
|
|
798
|
-
var readOrderNumbers = () => Object.keys(readJson(ORDER_TOKENS_KEY) ?? {});
|
|
882
|
+
}
|
|
883
|
+
function toVendor(v) {
|
|
884
|
+
return {
|
|
885
|
+
id: str(v.id),
|
|
886
|
+
slug: v.slug,
|
|
887
|
+
name: v.name,
|
|
888
|
+
businessName: v.name,
|
|
889
|
+
about: v.about,
|
|
890
|
+
description: v.about,
|
|
891
|
+
website: v.website,
|
|
892
|
+
address: v.address,
|
|
893
|
+
banners: [],
|
|
894
|
+
rating: null
|
|
895
|
+
};
|
|
896
|
+
}
|
|
897
|
+
function toUser(c) {
|
|
898
|
+
const [firstName, ...rest] = (c.name ?? "").trim().split(/\s+/);
|
|
899
|
+
return {
|
|
900
|
+
id: str(c.id),
|
|
901
|
+
userId: str(c.id),
|
|
902
|
+
email: c.email,
|
|
903
|
+
emailVerified: c.email_verified,
|
|
904
|
+
phone: c.phone || null,
|
|
905
|
+
firstName: firstName || "",
|
|
906
|
+
lastName: rest.join(" "),
|
|
907
|
+
name: c.name,
|
|
908
|
+
fullName: c.name,
|
|
909
|
+
avatar: null,
|
|
910
|
+
role: "USER",
|
|
911
|
+
createdAt: c.created_at,
|
|
912
|
+
updatedAt: c.updated_at
|
|
913
|
+
};
|
|
914
|
+
}
|
|
799
915
|
|
|
800
|
-
// src/
|
|
801
|
-
var
|
|
802
|
-
var
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
}
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
const raw = store.getItem(ADDRESSES_KEY);
|
|
814
|
-
const parsed = raw ? JSON.parse(raw) : [];
|
|
815
|
-
return Array.isArray(parsed) ? parsed : [];
|
|
816
|
-
} catch {
|
|
817
|
-
return [];
|
|
818
|
-
}
|
|
819
|
-
};
|
|
820
|
-
var writeAll = (addresses) => {
|
|
821
|
-
const store = storage2();
|
|
822
|
-
if (!store) return;
|
|
823
|
-
try {
|
|
824
|
-
store.setItem(ADDRESSES_KEY, JSON.stringify(addresses));
|
|
825
|
-
} catch {
|
|
826
|
-
}
|
|
827
|
-
};
|
|
828
|
-
var isSavedId = (id) => typeof id === "string" && id.length > 0 && id !== "new";
|
|
829
|
-
var newId = () => `addr_${Math.random().toString(36).slice(2, 10)}${Date.now().toString(36)}`;
|
|
830
|
-
var listAddresses = () => readAll();
|
|
831
|
-
var findAddress = (id) => readAll().find((a) => a.id === id);
|
|
832
|
-
var putAddress = (address) => {
|
|
833
|
-
const addresses = readAll();
|
|
834
|
-
const id = isSavedId(address.id) ? address.id : newId();
|
|
835
|
-
const saved = { ...address, id };
|
|
836
|
-
const index = addresses.findIndex((a) => a.id === id);
|
|
837
|
-
if (index >= 0) addresses[index] = saved;
|
|
838
|
-
else addresses.push(saved);
|
|
839
|
-
writeAll(addresses);
|
|
840
|
-
return saved;
|
|
841
|
-
};
|
|
842
|
-
var patchAddress = (id, patch) => {
|
|
843
|
-
const existing = findAddress(id);
|
|
844
|
-
if (!existing) return void 0;
|
|
845
|
-
return putAddress({ ...existing, ...patch, id });
|
|
846
|
-
};
|
|
847
|
-
var removeAddress = (id) => {
|
|
848
|
-
writeAll(readAll().filter((a) => a.id !== id));
|
|
849
|
-
};
|
|
850
|
-
var SESSION_COOKIES = ["connect.sid", "me"];
|
|
851
|
-
var clearPhantomSession = () => {
|
|
852
|
-
if (typeof document === "undefined") return;
|
|
853
|
-
for (const name of SESSION_COOKIES) {
|
|
854
|
-
document.cookie = `${name}=; Max-Age=0; path=/`;
|
|
855
|
-
document.cookie = `${name}=; Max-Age=0`;
|
|
856
|
-
}
|
|
857
|
-
};
|
|
858
|
-
var hasPhantomSession = () => typeof document !== "undefined" && SESSION_COOKIES.some((name) => new RegExp(`(^|;\\s*)${name.replace(".", "\\.")}=`).test(document.cookie));
|
|
916
|
+
// src/cache.ts
|
|
917
|
+
var TTL_MS = 6e4;
|
|
918
|
+
var entries = /* @__PURE__ */ new Map();
|
|
919
|
+
function remember(key, load, ttl = TTL_MS) {
|
|
920
|
+
const hit = entries.get(key);
|
|
921
|
+
if (hit && Date.now() - hit.at < ttl) return hit.value;
|
|
922
|
+
const value = load();
|
|
923
|
+
entries.set(key, { at: Date.now(), value });
|
|
924
|
+
value.catch(() => {
|
|
925
|
+
if (entries.get(key)?.value === value) entries.delete(key);
|
|
926
|
+
});
|
|
927
|
+
return value;
|
|
928
|
+
}
|
|
859
929
|
|
|
860
|
-
// src/services/
|
|
861
|
-
var
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
for (const category of categories) {
|
|
872
|
-
if (category?.id != null && category.slug) categorySlugById.set(category.id, category.slug);
|
|
873
|
-
if (category?.children?.length) rememberCategories(category.children);
|
|
930
|
+
// src/services/facts.ts
|
|
931
|
+
var StoreFacts = class extends BaseService {
|
|
932
|
+
key(name) {
|
|
933
|
+
return `${this.engineBase()}|${this.creds.store ?? ""}|${name}`;
|
|
934
|
+
}
|
|
935
|
+
/** Enabled plugins by key. A module that is not installed has no key here. */
|
|
936
|
+
plugins() {
|
|
937
|
+
return remember(this.key("plugins"), async () => {
|
|
938
|
+
const list = await this.data("/api/plugins") ?? [];
|
|
939
|
+
return new Map(list.map((p) => [p.key, p]));
|
|
940
|
+
});
|
|
874
941
|
}
|
|
875
|
-
|
|
876
|
-
};
|
|
877
|
-
var query = (params) => {
|
|
878
|
-
const search = new URLSearchParams();
|
|
879
|
-
for (const [key, value] of Object.entries(params)) {
|
|
880
|
-
if (value === void 0 || value === "") continue;
|
|
881
|
-
search.set(key, String(value));
|
|
882
|
-
}
|
|
883
|
-
const qs = search.toString();
|
|
884
|
-
return qs ? `?${qs}` : "";
|
|
885
|
-
};
|
|
886
|
-
var ProductService = class _ProductService extends BaseService {
|
|
887
|
-
static instance;
|
|
888
|
-
static getInstance() {
|
|
889
|
-
if (!_ProductService.instance) _ProductService.instance = new _ProductService();
|
|
890
|
-
return _ProductService.instance;
|
|
891
|
-
}
|
|
892
|
-
/** One window of the catalogue, raw. Everything else in this file is built on it. */
|
|
893
|
-
async fetchProducts({ q, page = 1, limit = PAGE_SIZE } = {}) {
|
|
894
|
-
const res = await this.api("GET", `/api/products${query({ q, page, limit })}`);
|
|
895
|
-
return { products: remember(res.data || []), meta: res.meta };
|
|
896
|
-
}
|
|
897
|
-
/** A product by its numeric id — how a cart line names what is in it. */
|
|
898
|
-
async fetchProductById(id) {
|
|
899
|
-
const cached = productCache.get(id);
|
|
900
|
-
if (cached) return cached;
|
|
942
|
+
async pluginOn(key) {
|
|
901
943
|
try {
|
|
902
|
-
|
|
903
|
-
if (res.data) remember([res.data]);
|
|
904
|
-
return res.data ?? null;
|
|
944
|
+
return (await this.plugins()).has(key);
|
|
905
945
|
} catch {
|
|
906
|
-
return
|
|
907
|
-
}
|
|
908
|
-
}
|
|
909
|
-
async fetchProductBySlug(slug) {
|
|
910
|
-
const res = await this.api("GET", `/api/products/slug/${encodeURIComponent(slug)}`);
|
|
911
|
-
if (res.data) remember([res.data]);
|
|
912
|
-
return res.data ?? null;
|
|
913
|
-
}
|
|
914
|
-
async list({ page = 1, search = "", sort = "" } = {}) {
|
|
915
|
-
if (sortNeedsWholeCatalogue(sort)) {
|
|
916
|
-
const { products: products2, meta: meta2 } = await this.fetchProducts({ q: search, page: 1, limit: MAX_LIMIT });
|
|
917
|
-
const sorted = sortProducts(products2, sort);
|
|
918
|
-
const start = (page - 1) * PAGE_SIZE;
|
|
919
|
-
return paginated(sorted.slice(start, start + PAGE_SIZE).map(mapProduct), meta2?.total ?? sorted.length, page);
|
|
946
|
+
return false;
|
|
920
947
|
}
|
|
921
|
-
const { products, meta } = await this.fetchProducts({ q: search, page, limit: PAGE_SIZE });
|
|
922
|
-
return fromListMeta(products.map(mapProduct), meta, page);
|
|
923
948
|
}
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
return this.list({ page, sort });
|
|
949
|
+
/** The store's settlement currency and default language. */
|
|
950
|
+
ready() {
|
|
951
|
+
return remember(this.key("ready"), () => this.data("/health/ready"));
|
|
928
952
|
}
|
|
929
|
-
|
|
930
|
-
return this.
|
|
953
|
+
checkoutOptions() {
|
|
954
|
+
return remember(this.key("checkout"), () => this.data("/api/checkout"));
|
|
931
955
|
}
|
|
932
|
-
/**
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
return
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
}
|
|
943
|
-
/** A product's variants, for a PDP that wants them without re-reading the product. */
|
|
944
|
-
async listVariants(productId) {
|
|
945
|
-
const res = await this.api("GET", `/api/variants${query({ product_id: productId, limit: MAX_LIMIT })}`);
|
|
946
|
-
return fromListMeta(res.data || [], res.meta);
|
|
947
|
-
}
|
|
948
|
-
// GoCommerce ships no review API, and a silent success would tell the shopper their review was
|
|
949
|
-
// saved when nothing left the browser.
|
|
950
|
-
async addReview(_params) {
|
|
951
|
-
throw new Error("Product reviews are not available on this store.");
|
|
956
|
+
/**
|
|
957
|
+
* The whole tree, flat and depth-first. Past 500 categories the engine
|
|
958
|
+
* answers a truncated list; the tree then serves what it has, and a
|
|
959
|
+
* breadcrumb for a category outside it falls back to the category alone.
|
|
960
|
+
*/
|
|
961
|
+
categories() {
|
|
962
|
+
return remember(
|
|
963
|
+
this.key("categories"),
|
|
964
|
+
async () => await this.data("/api/categories", { query: { flat: 1 } }) ?? []
|
|
965
|
+
);
|
|
952
966
|
}
|
|
953
|
-
|
|
954
|
-
|
|
967
|
+
/** Root → `slug`, by walking parents in the flat tree. */
|
|
968
|
+
async hierarchy(slug) {
|
|
969
|
+
const all = await this.categories().catch(() => []);
|
|
970
|
+
const byId = new Map(all.map((c2) => [c2.id, c2]));
|
|
971
|
+
const out = [];
|
|
972
|
+
let c = all.find((x) => x.slug === slug);
|
|
973
|
+
while (c) {
|
|
974
|
+
out.unshift({ name: c.title, slug: c.slug });
|
|
975
|
+
c = c.parent_id === null ? void 0 : byId.get(c.parent_id);
|
|
976
|
+
}
|
|
977
|
+
return out;
|
|
978
|
+
}
|
|
979
|
+
/** `slug` and every category under it — what a category page sells. */
|
|
980
|
+
async subtree(slug) {
|
|
981
|
+
const all = await this.categories();
|
|
982
|
+
const root = all.find((c) => c.slug === slug);
|
|
983
|
+
if (!root) return [];
|
|
984
|
+
const ids = /* @__PURE__ */ new Set([root.id]);
|
|
985
|
+
const out = [root];
|
|
986
|
+
for (const c of all) {
|
|
987
|
+
if (c.parent_id !== null && ids.has(c.parent_id) && !ids.has(c.id)) {
|
|
988
|
+
ids.add(c.id);
|
|
989
|
+
out.push(c);
|
|
990
|
+
}
|
|
991
|
+
}
|
|
992
|
+
return out;
|
|
955
993
|
}
|
|
956
994
|
};
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
return
|
|
995
|
+
|
|
996
|
+
// src/services/catalog.ts
|
|
997
|
+
var PAGE_SIZE = 24;
|
|
998
|
+
function indexSort(sort) {
|
|
999
|
+
if (!sort) return void 0;
|
|
1000
|
+
const s = sort.trim();
|
|
1001
|
+
const [field, dir] = s.startsWith("-") ? [s.slice(1), "desc"] : s.includes(":") ? s.split(":") : [s, "asc"];
|
|
1002
|
+
const d = dir === "desc" ? "desc" : "asc";
|
|
1003
|
+
switch (field) {
|
|
1004
|
+
case "price":
|
|
1005
|
+
return `price_minor:${d}`;
|
|
1006
|
+
case "updatedAt":
|
|
1007
|
+
case "updated_at":
|
|
1008
|
+
case "createdAt":
|
|
1009
|
+
case "created_at":
|
|
1010
|
+
return `updated_at:${d}`;
|
|
1011
|
+
case "title":
|
|
1012
|
+
case "name":
|
|
1013
|
+
return `title:${d}`;
|
|
1014
|
+
default:
|
|
1015
|
+
return void 0;
|
|
1016
|
+
}
|
|
1017
|
+
}
|
|
1018
|
+
var NATURAL = /* @__PURE__ */ new Set([
|
|
1019
|
+
"-createdAt",
|
|
1020
|
+
"createdAt:desc",
|
|
1021
|
+
"-updatedAt",
|
|
1022
|
+
"updatedAt:desc",
|
|
1023
|
+
"-popularity",
|
|
1024
|
+
"popularity:desc"
|
|
1025
|
+
]);
|
|
1026
|
+
var quote = (s) => `"${s.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
|
|
1027
|
+
var CatalogService = class extends BaseService {
|
|
1028
|
+
facts = new StoreFacts(this._fetch);
|
|
1029
|
+
async queryCatalog(q) {
|
|
1030
|
+
const page = Math.max(1, Number(q.page) || 1);
|
|
1031
|
+
const limit = Math.min(100, Math.max(1, Number(q.limit) || PAGE_SIZE));
|
|
1032
|
+
const search = q.search?.trim() || void 0;
|
|
1033
|
+
const wantsRange = Number.isFinite(q.priceFrom) || Number.isFinite(q.priceTo);
|
|
1034
|
+
const sortKey = q.sort && !NATURAL.has(q.sort) ? indexSort(q.sort) : void 0;
|
|
1035
|
+
const hierarchy = q.category ? await this.facts.hierarchy(q.category) : [];
|
|
1036
|
+
if ((sortKey || wantsRange) && await this.facts.pluginOn("meilisearch")) {
|
|
1037
|
+
const filters = [];
|
|
1038
|
+
if (q.category) {
|
|
1039
|
+
const names = (await this.facts.subtree(q.category).catch(() => [])).map(
|
|
1040
|
+
(c) => quote(c.full_name)
|
|
1041
|
+
);
|
|
1042
|
+
if (!names.length) return { ...emptyCatalog(limit), categoryHierarchy: hierarchy, sorted: true };
|
|
1043
|
+
filters.push(`category IN [${names.join(", ")}]`);
|
|
1044
|
+
}
|
|
1045
|
+
if (wantsRange) {
|
|
1046
|
+
const { currency } = await this.facts.ready();
|
|
1047
|
+
if (Number.isFinite(q.priceFrom)) filters.push(`price_minor >= ${toMinor(q.priceFrom, currency)}`);
|
|
1048
|
+
if (Number.isFinite(q.priceTo)) filters.push(`price_minor <= ${toMinor(q.priceTo, currency)}`);
|
|
1049
|
+
}
|
|
1050
|
+
const res = await this.data("/x/meilisearch/search", {
|
|
1051
|
+
query: {
|
|
1052
|
+
q: search ?? "",
|
|
1053
|
+
limit,
|
|
1054
|
+
offset: (page - 1) * limit,
|
|
1055
|
+
filter: filters.join(" AND ") || void 0,
|
|
1056
|
+
sort: sortKey
|
|
1057
|
+
}
|
|
1058
|
+
});
|
|
1059
|
+
const total = res.total ?? 0;
|
|
1060
|
+
return {
|
|
1061
|
+
data: (res.hits ?? []).map(fromSearchDoc),
|
|
1062
|
+
count: total,
|
|
1063
|
+
pageSize: limit,
|
|
1064
|
+
noOfPage: Math.max(1, Math.ceil(total / limit)),
|
|
1065
|
+
page,
|
|
1066
|
+
categoryHierarchy: hierarchy,
|
|
1067
|
+
sorted: true
|
|
1068
|
+
};
|
|
1069
|
+
}
|
|
1070
|
+
const sorted = !sortKey && !wantsRange;
|
|
1071
|
+
if (q.category && !search) {
|
|
1072
|
+
const env2 = await this.engine(
|
|
1073
|
+
`/api/categories/${encodeURIComponent(q.category)}`,
|
|
1074
|
+
{ query: { page, limit } }
|
|
1075
|
+
);
|
|
1076
|
+
const products = env2.data?.products ?? [];
|
|
1077
|
+
return {
|
|
1078
|
+
...toPage({ data: products, meta: env2.meta }, (p) => toProduct(p)),
|
|
1079
|
+
categoryHierarchy: hierarchy,
|
|
1080
|
+
sorted
|
|
1081
|
+
};
|
|
973
1082
|
}
|
|
974
|
-
|
|
1083
|
+
const env = await this.engine("/api/products", {
|
|
1084
|
+
query: { q: search, page, limit, channel: this.creds.channel }
|
|
1085
|
+
});
|
|
1086
|
+
return { ...toPage(env, (p) => toProduct(p)), categoryHierarchy: hierarchy, sorted };
|
|
975
1087
|
}
|
|
1088
|
+
};
|
|
1089
|
+
function emptyCatalog(limit = PAGE_SIZE) {
|
|
1090
|
+
return { data: [], count: 0, pageSize: limit, noOfPage: 0, page: 1 };
|
|
1091
|
+
}
|
|
1092
|
+
|
|
1093
|
+
// src/services/product-service.ts
|
|
1094
|
+
var ProductService = class extends CatalogService {
|
|
976
1095
|
/**
|
|
977
|
-
*
|
|
1096
|
+
* A product page. `slug` may also be a numeric id or a variant SKU, which is
|
|
1097
|
+
* how an old link or a search hit sometimes arrives.
|
|
978
1098
|
*
|
|
979
|
-
*
|
|
980
|
-
*
|
|
981
|
-
* imported a full retail taxonomy has far more nodes than that; the ones a shopper reaches are
|
|
982
|
-
* still reachable, because a listing page looks its category up by slug directly.
|
|
1099
|
+
* Reviews ride along when ext/reviews is installed and switched on; a review
|
|
1100
|
+
* failure never costs the shopper the product page.
|
|
983
1101
|
*/
|
|
984
|
-
async
|
|
985
|
-
const
|
|
986
|
-
const
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
return
|
|
1000
|
-
}
|
|
1001
|
-
async fetchFooterCategories({ page = 1, q = "" } = {}) {
|
|
1002
|
-
const all = await this.fetchAllCategories();
|
|
1003
|
-
const filtered = q ? all.data.filter((c) => c?.name?.toLowerCase().includes(q.toLowerCase())) : all.data;
|
|
1004
|
-
const start = (page - 1) * PAGE_SIZE;
|
|
1005
|
-
return paginated(filtered.slice(start, start + PAGE_SIZE), filtered.length, page);
|
|
1006
|
-
}
|
|
1007
|
-
/** The homepage grid: the roots of the taxonomy, which is what a shopper navigates from. */
|
|
1008
|
-
async fetchFeaturedCategories({ limit = 18 } = {}) {
|
|
1009
|
-
const all = await this.fetchAllCategories();
|
|
1010
|
-
const roots = all.data.filter((c) => c && c.parentCategoryId == null);
|
|
1011
|
-
const picked = (roots.length ? roots : all.data).slice(0, limit);
|
|
1012
|
-
return paginated(picked, picked.length, 1, limit);
|
|
1013
|
-
}
|
|
1014
|
-
async fetchAllProductsOfCategories(slugOrId) {
|
|
1015
|
-
const slug = await resolveCategorySlug(slugOrId) || String(slugOrId);
|
|
1016
|
-
const { products, meta } = await this.fetchCategoryPage(slug);
|
|
1017
|
-
return fromListMeta(products.map(mapProduct), meta);
|
|
1102
|
+
async getOne(slug) {
|
|
1103
|
+
const p = await this.findProduct(String(slug));
|
|
1104
|
+
const product = toProduct(p, {
|
|
1105
|
+
categoryHierarchy: p.category ? await this.facts.hierarchy(p.category.slug) : []
|
|
1106
|
+
});
|
|
1107
|
+
if (await this.facts.pluginOn("product-reviews")) {
|
|
1108
|
+
try {
|
|
1109
|
+
const res = await this.data("/x/reviews", { query: { product_id: p.id, limit: 50 } });
|
|
1110
|
+
product.ratings = (res.reviews ?? []).map(toRating);
|
|
1111
|
+
product.rating = res.summary?.count ? res.summary.average : null;
|
|
1112
|
+
product.ratingCount = res.summary?.count ?? 0;
|
|
1113
|
+
product.reviewCount = res.summary?.count ?? 0;
|
|
1114
|
+
} catch {
|
|
1115
|
+
}
|
|
1116
|
+
}
|
|
1117
|
+
return product;
|
|
1018
1118
|
}
|
|
1019
|
-
async
|
|
1020
|
-
|
|
1119
|
+
async findProduct(slug) {
|
|
1120
|
+
try {
|
|
1121
|
+
return await this.data(`/api/products/slug/${encodeURIComponent(slug)}`);
|
|
1122
|
+
} catch (err) {
|
|
1123
|
+
if (!(err instanceof GoCommerceError) || err.status !== 404) throw err;
|
|
1124
|
+
const fallback = /^\d+$/.test(slug) ? `/api/products/${slug}` : `/api/products/sku/${encodeURIComponent(slug)}`;
|
|
1125
|
+
try {
|
|
1126
|
+
return await this.data(fallback);
|
|
1127
|
+
} catch {
|
|
1128
|
+
throw err;
|
|
1129
|
+
}
|
|
1130
|
+
}
|
|
1021
1131
|
}
|
|
1022
|
-
}
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
};
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
);
|
|
1132
|
+
/** The shop's listing: `{ page, search, sort }`, newest first unless the index can reorder it. */
|
|
1133
|
+
async list({
|
|
1134
|
+
page = 1,
|
|
1135
|
+
search,
|
|
1136
|
+
q,
|
|
1137
|
+
sort,
|
|
1138
|
+
limit,
|
|
1139
|
+
categories
|
|
1140
|
+
} = {}) {
|
|
1141
|
+
const res = await this.queryCatalog({ page, search: search ?? q, sort, limit, category: categories || void 0 });
|
|
1142
|
+
return { data: res.data, count: res.count, pageSize: res.pageSize, noOfPage: res.noOfPage, page: res.page };
|
|
1143
|
+
}
|
|
1144
|
+
async listFeaturedProducts({ page = 1, sort, limit } = {}) {
|
|
1145
|
+
return this.shelf("featured", { page, sort, limit });
|
|
1146
|
+
}
|
|
1147
|
+
async listTrendingProducts({ page = 1, limit } = {}) {
|
|
1148
|
+
return this.shelf("trending", { page, limit });
|
|
1149
|
+
}
|
|
1150
|
+
/** More from this product's category. */
|
|
1151
|
+
async listRelatedProducts({
|
|
1152
|
+
page = 1,
|
|
1153
|
+
categoryId,
|
|
1154
|
+
limit
|
|
1155
|
+
} = {}) {
|
|
1156
|
+
if (!categoryId) return this.list({ page, limit });
|
|
1157
|
+
const category = (await this.facts.categories()).find((c) => String(c.id) === String(categoryId));
|
|
1158
|
+
if (!category) return this.list({ page, limit });
|
|
1159
|
+
return this.list({ page, limit, categories: category.slug });
|
|
1160
|
+
}
|
|
1161
|
+
async shelf(slug, { page, sort, limit }) {
|
|
1162
|
+
const size = Math.min(100, Math.max(1, Number(limit) || PAGE_SIZE));
|
|
1163
|
+
try {
|
|
1164
|
+
const env = await this.engine(`/api/collections/${slug}`, {
|
|
1165
|
+
query: { page, limit: size }
|
|
1166
|
+
});
|
|
1167
|
+
const rows = env.data?.products ?? [];
|
|
1168
|
+
return {
|
|
1169
|
+
data: rows.map((p) => toProduct(p)),
|
|
1170
|
+
count: env.meta?.total ?? rows.length,
|
|
1171
|
+
pageSize: env.meta?.limit ?? size,
|
|
1172
|
+
noOfPage: env.meta?.total_pages ?? 1,
|
|
1173
|
+
page: env.meta?.page ?? page
|
|
1174
|
+
};
|
|
1175
|
+
} catch (err) {
|
|
1176
|
+
if (!(err instanceof GoCommerceError) || err.status !== 404) throw err;
|
|
1177
|
+
return this.list({ page, sort, limit: size });
|
|
1178
|
+
}
|
|
1048
1179
|
}
|
|
1049
1180
|
/**
|
|
1050
|
-
* A
|
|
1051
|
-
*
|
|
1181
|
+
* A review, through ext/reviews. The engine asks for a name and an email
|
|
1182
|
+
* with every review, so a signed-out shopper is asked to sign in rather
|
|
1183
|
+
* than having one made up for them. Uploaded photos have nowhere to go: the
|
|
1184
|
+
* module stores text.
|
|
1052
1185
|
*/
|
|
1053
|
-
async
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1186
|
+
async addReview({
|
|
1187
|
+
productId,
|
|
1188
|
+
rating,
|
|
1189
|
+
review,
|
|
1190
|
+
title
|
|
1191
|
+
}) {
|
|
1192
|
+
const me = currentMe();
|
|
1193
|
+
if (!me?.email) throw new GoCommerceError("Please sign in to write a review.", 401, "unauthorized");
|
|
1194
|
+
const name = [me.firstName, me.lastName].filter(Boolean).join(" ") || me.email.split("@")[0];
|
|
1195
|
+
return this.data("/x/reviews", {
|
|
1196
|
+
method: "POST",
|
|
1197
|
+
body: {
|
|
1198
|
+
product_id: Number(productId),
|
|
1199
|
+
name,
|
|
1200
|
+
email: me.email,
|
|
1201
|
+
rating: Math.round(Number(rating)),
|
|
1202
|
+
...title ? { title } : {},
|
|
1203
|
+
body: String(review ?? "")
|
|
1204
|
+
}
|
|
1205
|
+
});
|
|
1066
1206
|
}
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
return {
|
|
1070
|
-
id: null,
|
|
1071
|
-
name: "All Ratings",
|
|
1072
|
-
slug: "all-ratings",
|
|
1073
|
-
description: null,
|
|
1074
|
-
isActive: true,
|
|
1075
|
-
isFeatured: false,
|
|
1076
|
-
userId: "",
|
|
1077
|
-
productCount: 0,
|
|
1078
|
-
thumbnail: null,
|
|
1079
|
-
metaTitle: null,
|
|
1080
|
-
metaDescription: null,
|
|
1081
|
-
collectionvalues: [],
|
|
1082
|
-
createdAt: null,
|
|
1083
|
-
updatedAt: null
|
|
1084
|
-
};
|
|
1207
|
+
async fetchReels() {
|
|
1208
|
+
throw new NotSupportedError("ProductService", "fetchReels", "the engine has no reels");
|
|
1085
1209
|
}
|
|
1086
1210
|
};
|
|
1087
|
-
var
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
if (!sortNeedsWholeCatalogue(sort)) return products;
|
|
1095
|
-
const leadingMinus = sort.startsWith("-");
|
|
1096
|
-
const [rawKey, rawDirection] = sort.replace(/^-/, "").split(":");
|
|
1097
|
-
const descending = leadingMinus || rawDirection === "desc";
|
|
1098
|
-
const value = (product) => {
|
|
1099
|
-
if (rawKey === "price") {
|
|
1100
|
-
const prices = (product.variants || []).filter((v) => v.active !== false).map((v) => v.price?.amount_minor ?? 0);
|
|
1101
|
-
return prices.length ? Math.min(...prices) : 0;
|
|
1102
|
-
}
|
|
1103
|
-
const stamp = rawKey === "createdAt" ? product.created_at : product.updated_at;
|
|
1104
|
-
return stamp ? Date.parse(stamp) : 0;
|
|
1105
|
-
};
|
|
1106
|
-
return [...products].sort((a, b) => descending ? value(b) - value(a) : value(a) - value(b));
|
|
1107
|
-
};
|
|
1108
|
-
var productPrice = (product) => {
|
|
1109
|
-
const prices = (product.variants || []).filter((v) => v.active !== false).map((v) => v.price?.amount_minor ?? 0);
|
|
1110
|
-
return prices.length ? Math.min(...prices) : 0;
|
|
1111
|
-
};
|
|
1112
|
-
var countBy = (items, key) => {
|
|
1113
|
-
const counts = /* @__PURE__ */ new Map();
|
|
1114
|
-
for (const item of items) {
|
|
1115
|
-
const entry = key(item);
|
|
1116
|
-
if (!entry?.name) continue;
|
|
1117
|
-
const id = entry.slug || entry.name;
|
|
1118
|
-
const existing = counts.get(id);
|
|
1119
|
-
if (existing) existing.count += 1;
|
|
1120
|
-
else counts.set(id, { ...entry, count: 1 });
|
|
1121
|
-
}
|
|
1122
|
-
return [...counts.values()].sort((a, b) => b.count - a.count);
|
|
1211
|
+
var productService = new ProductService();
|
|
1212
|
+
|
|
1213
|
+
// src/services/search-service.ts
|
|
1214
|
+
var num = (v) => {
|
|
1215
|
+
if (v === null || v.trim() === "") return void 0;
|
|
1216
|
+
const n = Number(v);
|
|
1217
|
+
return Number.isFinite(n) ? n : void 0;
|
|
1123
1218
|
};
|
|
1124
|
-
var SearchService = class
|
|
1125
|
-
static instance;
|
|
1126
|
-
static getInstance() {
|
|
1127
|
-
if (!_SearchService.instance) _SearchService.instance = new _SearchService();
|
|
1128
|
-
return _SearchService.instance;
|
|
1129
|
-
}
|
|
1219
|
+
var SearchService = class extends CatalogService {
|
|
1130
1220
|
emptyResult() {
|
|
1131
1221
|
return {
|
|
1132
1222
|
data: [],
|
|
1133
1223
|
count: 0,
|
|
1134
1224
|
totalPages: 0,
|
|
1135
1225
|
categoryHierarchy: [],
|
|
1136
|
-
facets: { priceStat: {
|
|
1226
|
+
facets: { priceStat: {}, categories: [], tags: [], allFilters: {} }
|
|
1137
1227
|
};
|
|
1138
1228
|
}
|
|
1139
|
-
/**
|
|
1140
|
-
* The listing page: `/products`, `/[slug]` for a category, and every filter the sidebar sets.
|
|
1141
|
-
*
|
|
1142
|
-
* Term and category are pushed to the API. Tags, the price range and the sort control are
|
|
1143
|
-
* applied here, because GoCommerce has no parameter for them — so when any of those is active
|
|
1144
|
-
* the request asks for the whole window rather than one page, and the result is paged locally.
|
|
1145
|
-
*/
|
|
1146
1229
|
async searchWithUrl(url, slug) {
|
|
1147
1230
|
try {
|
|
1148
|
-
const
|
|
1149
|
-
const
|
|
1150
|
-
const
|
|
1151
|
-
const
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
let meta;
|
|
1160
|
-
let category;
|
|
1161
|
-
if (categorySlug) {
|
|
1162
|
-
const res = await categoryService.fetchCategoryPage(categorySlug, { limit: MAX_LIMIT });
|
|
1163
|
-
products = res.products;
|
|
1164
|
-
meta = res.meta;
|
|
1165
|
-
category = res.category;
|
|
1166
|
-
if (term) {
|
|
1167
|
-
const needle = term.toLowerCase();
|
|
1168
|
-
products = products.filter((p) => `${p.title} ${p.description || ""}`.toLowerCase().includes(needle));
|
|
1169
|
-
}
|
|
1170
|
-
} else {
|
|
1171
|
-
const res = await productService.fetchProducts({
|
|
1172
|
-
q: term,
|
|
1173
|
-
page: needsWholeWindow ? 1 : page,
|
|
1174
|
-
limit: needsWholeWindow ? MAX_LIMIT : PAGE_SIZE
|
|
1175
|
-
});
|
|
1176
|
-
products = res.products;
|
|
1177
|
-
meta = res.meta;
|
|
1178
|
-
}
|
|
1179
|
-
const facetSource = products;
|
|
1180
|
-
const priceMinor = facetSource.map(productPrice).filter((n) => Number.isFinite(n));
|
|
1181
|
-
const currency = facetSource[0]?.variants?.[0]?.price?.currency || facetSource[0]?.currency;
|
|
1182
|
-
const digits = currency ? 10 ** currencyFractionDigits(currency) : 100;
|
|
1183
|
-
let filtered = products;
|
|
1184
|
-
if (tags.length) {
|
|
1185
|
-
filtered = filtered.filter((p) => (p.tags || []).some((tag) => tags.includes(tag.toLowerCase())));
|
|
1186
|
-
}
|
|
1187
|
-
if (priceFrom !== void 0) filtered = filtered.filter((p) => productPrice(p) / digits >= priceFrom);
|
|
1188
|
-
if (priceTo !== void 0) filtered = filtered.filter((p) => productPrice(p) / digits <= priceTo);
|
|
1189
|
-
filtered = sortProducts(filtered, sort);
|
|
1190
|
-
const paged = needsWholeWindow ? filtered.slice((page - 1) * PAGE_SIZE, page * PAGE_SIZE) : filtered;
|
|
1191
|
-
const count = needsWholeWindow ? filtered.length : meta?.total ?? filtered.length;
|
|
1231
|
+
const u = typeof url === "string" ? new URL(url, "http://localhost") : url;
|
|
1232
|
+
const p = u.searchParams;
|
|
1233
|
+
const [from, to] = (p.get("price") ?? "").split(/[,-]/);
|
|
1234
|
+
const res = await this.queryCatalog({
|
|
1235
|
+
page: num(p.get("page")),
|
|
1236
|
+
search: p.get("search") ?? p.get("q") ?? void 0,
|
|
1237
|
+
sort: p.get("sort") ?? void 0,
|
|
1238
|
+
category: slug || p.get("categories")?.split(",")[0] || void 0,
|
|
1239
|
+
priceFrom: num(p.get("priceFrom")) ?? num(from ?? null),
|
|
1240
|
+
priceTo: num(p.get("priceTo")) ?? num(to ?? null)
|
|
1241
|
+
});
|
|
1192
1242
|
return {
|
|
1193
|
-
data:
|
|
1194
|
-
count,
|
|
1195
|
-
totalPages:
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
categoryHierarchy: category ? [{ name: category.title, slug: category.slug }] : [],
|
|
1200
|
-
facets: {
|
|
1201
|
-
priceStat: priceMinor.length ? { min: Math.min(...priceMinor) / digits, max: Math.max(...priceMinor) / digits } : { min: void 0, max: void 0 },
|
|
1202
|
-
categories: countBy(facetSource, (p) => p.category ? { name: p.category.title, slug: p.category.slug } : void 0),
|
|
1203
|
-
tags: countBy(
|
|
1204
|
-
facetSource.flatMap((p) => (p.tags || []).map((tag) => ({ tag }))),
|
|
1205
|
-
({ tag }) => ({ name: tag, slug: tag })
|
|
1206
|
-
),
|
|
1207
|
-
allFilters: {}
|
|
1208
|
-
}
|
|
1243
|
+
data: res.data,
|
|
1244
|
+
count: res.count,
|
|
1245
|
+
totalPages: res.noOfPage,
|
|
1246
|
+
page: res.page,
|
|
1247
|
+
categoryHierarchy: res.categoryHierarchy,
|
|
1248
|
+
facets: { priceStat: {}, categories: [], tags: [], allFilters: {} }
|
|
1209
1249
|
};
|
|
1210
|
-
} catch (
|
|
1211
|
-
if (
|
|
1212
|
-
|
|
1250
|
+
} catch (err) {
|
|
1251
|
+
if (err?.status === 404) return this.emptyResult();
|
|
1252
|
+
throw err;
|
|
1213
1253
|
}
|
|
1214
1254
|
}
|
|
1215
|
-
async searchWithQuery(queryString) {
|
|
1216
|
-
const url = new URL("https://storefront.local/products");
|
|
1217
|
-
if (queryString) url.searchParams.set("search", queryString);
|
|
1218
|
-
return this.searchWithUrl(url);
|
|
1219
|
-
}
|
|
1220
1255
|
};
|
|
1221
|
-
var searchService = SearchService
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
});
|
|
1235
|
-
const hits = products.map(mapProduct);
|
|
1256
|
+
var searchService = new SearchService();
|
|
1257
|
+
|
|
1258
|
+
// src/services/meilisearch-service.ts
|
|
1259
|
+
var MeilisearchService = class extends CatalogService {
|
|
1260
|
+
/** `{ query, categories, page }` → a Meilisearch-shaped answer: `hits`, `totalHits`, `totalPages`. */
|
|
1261
|
+
async search({
|
|
1262
|
+
query,
|
|
1263
|
+
search,
|
|
1264
|
+
categories,
|
|
1265
|
+
page = 1,
|
|
1266
|
+
limit
|
|
1267
|
+
} = {}) {
|
|
1268
|
+
const res = await this.queryCatalog({ page, limit, search: query ?? search, category: categories || void 0 });
|
|
1236
1269
|
return {
|
|
1237
|
-
hits,
|
|
1238
|
-
|
|
1239
|
-
estimatedTotalHits:
|
|
1240
|
-
|
|
1241
|
-
page,
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
facetDistribution: {},
|
|
1245
|
-
processingTimeMs: 0,
|
|
1246
|
-
query: params.q || ""
|
|
1270
|
+
hits: res.data,
|
|
1271
|
+
totalHits: res.count,
|
|
1272
|
+
estimatedTotalHits: res.count,
|
|
1273
|
+
totalPages: res.noOfPage,
|
|
1274
|
+
page: res.page,
|
|
1275
|
+
categories: res.categoryHierarchy,
|
|
1276
|
+
facetDistribution: {}
|
|
1247
1277
|
};
|
|
1248
1278
|
}
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
const
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
})
|
|
1258
|
-
return {
|
|
1259
|
-
}
|
|
1260
|
-
};
|
|
1261
|
-
var meilisearchService = MeilisearchService.getInstance();
|
|
1262
|
-
var AutocompleteService = class _AutocompleteService extends BaseService {
|
|
1263
|
-
static instance;
|
|
1264
|
-
static getInstance() {
|
|
1265
|
-
if (!_AutocompleteService.instance) _AutocompleteService.instance = new _AutocompleteService();
|
|
1266
|
-
return _AutocompleteService.instance;
|
|
1267
|
-
}
|
|
1268
|
-
async list({ page = 1, q = "" } = {}) {
|
|
1269
|
-
const { products, meta } = await productService.fetchProducts({ q, page, limit: 10 });
|
|
1270
|
-
return fromListMeta(
|
|
1271
|
-
products.map((product) => ({ id: product.id, name: product.title, slug: product.slug })),
|
|
1272
|
-
meta,
|
|
1273
|
-
page
|
|
1274
|
-
);
|
|
1279
|
+
/** The header's type-ahead: `{ data: [{ slug, title, thumbnail, price }] }`. */
|
|
1280
|
+
async searchAutoComplete({ query, search, limit = 8 } = {}) {
|
|
1281
|
+
const q = (query ?? search ?? "").trim();
|
|
1282
|
+
if (!q) return { data: [] };
|
|
1283
|
+
if (await this.facts.pluginOn("meilisearch")) {
|
|
1284
|
+
const res = await this.data("/x/meilisearch/search", { query: { q, limit } });
|
|
1285
|
+
return { data: (res.hits ?? []).map(fromSearchDoc) };
|
|
1286
|
+
}
|
|
1287
|
+
const rows = await this.data("/api/products", { query: { q, limit, channel: this.creds.channel } }) ?? [];
|
|
1288
|
+
return { data: rows.map((p) => toProduct(p)) };
|
|
1275
1289
|
}
|
|
1276
1290
|
};
|
|
1277
|
-
var
|
|
1278
|
-
var resolveProductIndex = async (ids, fetchFn) => {
|
|
1279
|
-
const wanted = [...new Set(ids.filter((id) => typeof id === "number"))];
|
|
1280
|
-
const service = fetchFn ? new ProductService(fetchFn) : productService;
|
|
1281
|
-
await Promise.all(wanted.filter((id) => !productCache.has(id)).map((id) => service.fetchProductById(id)));
|
|
1282
|
-
const index = /* @__PURE__ */ new Map();
|
|
1283
|
-
for (const id of wanted) {
|
|
1284
|
-
const product = productCache.get(id);
|
|
1285
|
-
if (product) index.set(id, product);
|
|
1286
|
-
}
|
|
1287
|
-
return index;
|
|
1288
|
-
};
|
|
1291
|
+
var meilisearchService = new MeilisearchService();
|
|
1289
1292
|
|
|
1290
|
-
// src/services/
|
|
1291
|
-
var
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
} catch {
|
|
1293
|
+
// src/services/category-service.ts
|
|
1294
|
+
var asList = (rows) => ({
|
|
1295
|
+
data: rows,
|
|
1296
|
+
count: rows.length,
|
|
1297
|
+
pageSize: rows.length,
|
|
1298
|
+
noOfPage: 1,
|
|
1299
|
+
page: 1
|
|
1300
|
+
});
|
|
1301
|
+
var CategoryService = class extends BaseService {
|
|
1302
|
+
facts = new StoreFacts(this._fetch);
|
|
1303
|
+
/** Every category, flat, each naming its parent. The storefront builds the tree. */
|
|
1304
|
+
async fetchAllCategories(_args = {}) {
|
|
1305
|
+
const all = await this.facts.categories();
|
|
1306
|
+
return asList(all.map(flat));
|
|
1305
1307
|
}
|
|
1306
|
-
}
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
window?.localStorage?.removeItem(CART_ID_KEY);
|
|
1310
|
-
} catch {
|
|
1308
|
+
async fetchFeaturedCategories({ limit = 18 } = {}) {
|
|
1309
|
+
const roots = (await this.facts.categories()).filter((c) => c.parent_id === null);
|
|
1310
|
+
return asList(roots.slice(0, Math.max(0, Number(limit) || 18)).map(flat));
|
|
1311
1311
|
}
|
|
1312
|
-
}
|
|
1313
|
-
|
|
1314
|
-
var CartService = class _CartService extends BaseService {
|
|
1315
|
-
static instance;
|
|
1316
|
-
static getInstance() {
|
|
1317
|
-
if (!_CartService.instance) _CartService.instance = new _CartService();
|
|
1318
|
-
return _CartService.instance;
|
|
1319
|
-
}
|
|
1320
|
-
/** Turns a GoCommerce cart into the shape the storefront's cart, drawer and checkout read. */
|
|
1321
|
-
async present(cart) {
|
|
1322
|
-
if (!cart) return {};
|
|
1323
|
-
storeCartId(cart.id);
|
|
1324
|
-
const [index, store] = await Promise.all([
|
|
1325
|
-
// Cart lines name a product by id only, so slug and image are filled in from the catalogue.
|
|
1326
|
-
resolveProductIndex(
|
|
1327
|
-
(cart.line_items || []).map((line) => line.product_id),
|
|
1328
|
-
this.getFetch()
|
|
1329
|
-
),
|
|
1330
|
-
readStaticStore()
|
|
1331
|
-
]);
|
|
1332
|
-
return mapCart(cart, readCheckoutDetails(cart.id), index, store);
|
|
1312
|
+
async fetchFooterCategories(args = {}) {
|
|
1313
|
+
return this.fetchFeaturedCategories(args);
|
|
1333
1314
|
}
|
|
1334
|
-
/**
|
|
1335
|
-
async
|
|
1336
|
-
const
|
|
1337
|
-
|
|
1338
|
-
return res.data;
|
|
1315
|
+
/** The nested tree, roots first. */
|
|
1316
|
+
async getMegamenu(_args = {}) {
|
|
1317
|
+
const tree = await this.data("/api/categories") ?? [];
|
|
1318
|
+
return tree.map(toCategory);
|
|
1339
1319
|
}
|
|
1340
|
-
async
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
const res = await this.api("GET", `/api/carts/${encodeURIComponent(cartId)}`);
|
|
1344
|
-
cart = res.data ?? null;
|
|
1345
|
-
} catch {
|
|
1346
|
-
return null;
|
|
1347
|
-
}
|
|
1348
|
-
if (cart && cart.status && cart.status !== "open") {
|
|
1349
|
-
forgetCartId();
|
|
1350
|
-
return null;
|
|
1351
|
-
}
|
|
1352
|
-
return cart;
|
|
1320
|
+
async fetchCategory(slug) {
|
|
1321
|
+
const c = await this.data(`/api/categories/${encodeURIComponent(slug)}`, { query: { limit: 1 } });
|
|
1322
|
+
return toCategory(c);
|
|
1353
1323
|
}
|
|
1354
1324
|
/**
|
|
1355
|
-
*
|
|
1356
|
-
*
|
|
1357
|
-
*
|
|
1358
|
-
* reports several unrelated things the same way: a dead cart and an unknown payment code are both
|
|
1359
|
-
* `404 not_found`. The status is the fact; the message is prose.
|
|
1325
|
+
* kitcommerce-core's category filter asks for `/api/categories/all` by path,
|
|
1326
|
+
* through the family's raw `get`. That is a Litekart path the rest-guard
|
|
1327
|
+
* would swallow, so it is answered here, from the engine's tree.
|
|
1360
1328
|
*/
|
|
1361
|
-
async
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
return !res.data || Boolean(res.data.status) && res.data.status !== "open";
|
|
1365
|
-
} catch {
|
|
1366
|
-
return true;
|
|
1367
|
-
}
|
|
1329
|
+
async get(path) {
|
|
1330
|
+
if (path.split("?")[0] === "/api/categories/all") return await this.fetchAllCategories();
|
|
1331
|
+
return super.get(path);
|
|
1368
1332
|
}
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
}
|
|
1377
|
-
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1333
|
+
};
|
|
1334
|
+
var flat = (c) => ({ ...toCategory(c), children: [] });
|
|
1335
|
+
var categoryService = new CategoryService();
|
|
1336
|
+
|
|
1337
|
+
// src/services/collection-service.ts
|
|
1338
|
+
var CollectionService = class extends BaseService {
|
|
1339
|
+
async list({ page = 1, limit = 24 } = {}) {
|
|
1340
|
+
const env = await this.engine("/api/collections", { query: { page, limit } });
|
|
1341
|
+
return toPage(env, toCollection);
|
|
1342
|
+
}
|
|
1343
|
+
/** A collection page: the collection, and its products in the merchant's order. */
|
|
1344
|
+
async getOne(slug, { page = 1, limit = 48 } = {}) {
|
|
1345
|
+
const env = await this.engine(
|
|
1346
|
+
`/api/collections/${encodeURIComponent(slug)}`,
|
|
1347
|
+
{ query: { page, limit } }
|
|
1348
|
+
);
|
|
1349
|
+
const products = (env.data.products ?? []).map((p) => toProduct(p));
|
|
1350
|
+
return {
|
|
1351
|
+
...toCollection(env.data),
|
|
1352
|
+
products,
|
|
1353
|
+
// The family's shape for a collection's members.
|
|
1354
|
+
collectionvalues: products.map((p) => ({ products: p })),
|
|
1355
|
+
count: env.meta?.total ?? products.length,
|
|
1356
|
+
noOfPage: env.meta?.total_pages ?? 1,
|
|
1357
|
+
page: env.meta?.page ?? page
|
|
1358
|
+
};
|
|
1359
|
+
}
|
|
1360
|
+
/** Collection-level ratings are a Litekart aggregate; the engine has none to report. */
|
|
1361
|
+
async getAllRatings() {
|
|
1362
|
+
return { data: [] };
|
|
1383
1363
|
}
|
|
1364
|
+
};
|
|
1365
|
+
var collectionService = new CollectionService();
|
|
1366
|
+
|
|
1367
|
+
// src/services/cart-service.ts
|
|
1368
|
+
var REMOVE = -9999999;
|
|
1369
|
+
var CartService = class extends BaseService {
|
|
1370
|
+
facts = new StoreFacts(this._fetch);
|
|
1384
1371
|
async getCartByCartId(cartId) {
|
|
1385
|
-
const id =
|
|
1386
|
-
if (!id) return
|
|
1387
|
-
|
|
1372
|
+
const id = clean(cartId);
|
|
1373
|
+
if (!id) return emptyCart(await this.currency());
|
|
1374
|
+
try {
|
|
1375
|
+
return await this.present(await this.data(`/api/carts/${encodeURIComponent(id)}`));
|
|
1376
|
+
} catch (err) {
|
|
1377
|
+
if (err instanceof GoCommerceError && err.status === 404) return emptyCart(await this.currency());
|
|
1378
|
+
throw err;
|
|
1379
|
+
}
|
|
1388
1380
|
}
|
|
1389
|
-
async fetchCartData() {
|
|
1390
|
-
|
|
1391
|
-
if (!id) return {};
|
|
1392
|
-
return this.present(await this.readCart(id));
|
|
1381
|
+
async fetchCartData(cartId) {
|
|
1382
|
+
return this.getCartByCartId(cartId ?? storedCartId());
|
|
1393
1383
|
}
|
|
1384
|
+
/**
|
|
1385
|
+
* The cart after an order: the engine marks it `converted` and keeps its
|
|
1386
|
+
* lines, and this answers it with none — which is how the storefront knows
|
|
1387
|
+
* to clear the bag on the success page.
|
|
1388
|
+
*/
|
|
1394
1389
|
async refereshCart() {
|
|
1395
|
-
|
|
1390
|
+
const id = storedCartId();
|
|
1391
|
+
const cart = await this.getCartByCartId(id);
|
|
1392
|
+
if (id && cart.status === "converted") forgetCartExtras(id);
|
|
1393
|
+
return cart;
|
|
1396
1394
|
}
|
|
1397
1395
|
/**
|
|
1398
|
-
*
|
|
1399
|
-
*
|
|
1400
|
-
* `qty` is the line's new quantity, not a delta — which is how the shared cart store calls it
|
|
1401
|
-
* (its stepper sends `qty ± 1`), and what `PATCH .../line-items/{lineId}` takes. A quantity of
|
|
1402
|
-
* zero removes the line, and so does the store's `REMOVE_LINE` sentinel.
|
|
1403
|
-
*
|
|
1404
|
-
* A cart token in this browser can be dead — expired, wiped server-side, or already checked out —
|
|
1405
|
-
* and the API then answers "cart not found", which is what the shopper was shown when they
|
|
1406
|
-
* clicked Add to bag. That is a token this storefront is holding, not anything they did, so a
|
|
1407
|
-
* dead one is dropped and the item is added to a fresh cart instead of reporting it.
|
|
1396
|
+
* `qty` is a change, not a total: +1 from a product page, −1 from a card's
|
|
1397
|
+
* minus button. With no cart yet, one is opened and remembered.
|
|
1408
1398
|
*/
|
|
1409
1399
|
async addToCart({
|
|
1410
|
-
variantId,
|
|
1411
|
-
qty,
|
|
1412
1400
|
cartId,
|
|
1413
|
-
lineId
|
|
1401
|
+
lineId,
|
|
1402
|
+
qty = 1,
|
|
1403
|
+
variantId
|
|
1414
1404
|
}) {
|
|
1415
|
-
|
|
1416
|
-
if (
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
cart = await this.writeLine(id, { variantId, qty, lineId, removing });
|
|
1423
|
-
} catch (error) {
|
|
1424
|
-
if (!await this.cartIsSpent(id)) throw error;
|
|
1425
|
-
spent = true;
|
|
1405
|
+
let id = clean(cartId) ?? storedCartId();
|
|
1406
|
+
if (lineId && id) {
|
|
1407
|
+
const cart = await this.data(`/api/carts/${encodeURIComponent(id)}`);
|
|
1408
|
+
const line = (cart.line_items ?? []).find((l) => String(l.id) === String(lineId));
|
|
1409
|
+
if (line) {
|
|
1410
|
+
const next = qty === REMOVE ? 0 : line.quantity + Number(qty);
|
|
1411
|
+
return this.setQuantity(id, line.id, next);
|
|
1426
1412
|
}
|
|
1427
|
-
if (!spent) return this.present(cart);
|
|
1428
|
-
forgetCartId();
|
|
1429
|
-
id = null;
|
|
1430
1413
|
}
|
|
1431
|
-
if (
|
|
1432
|
-
|
|
1433
|
-
if (!
|
|
1434
|
-
|
|
1414
|
+
if (qty === REMOVE || Number(qty) <= 0) return this.getCartByCartId(id);
|
|
1415
|
+
if (!variantId) throw new GoCommerceError("Please choose an option before adding this to your bag.", 400);
|
|
1416
|
+
if (!id) id = await this.open();
|
|
1417
|
+
try {
|
|
1418
|
+
return await this.present(
|
|
1419
|
+
await this.data(`/api/carts/${encodeURIComponent(id)}/line-items`, {
|
|
1420
|
+
method: "POST",
|
|
1421
|
+
body: { variant_id: Number(variantId), quantity: Number(qty) }
|
|
1422
|
+
})
|
|
1423
|
+
);
|
|
1424
|
+
} catch (err) {
|
|
1425
|
+
if (err instanceof GoCommerceError && (err.status === 404 || /checked out/.test(err.message))) {
|
|
1426
|
+
const fresh = await this.open();
|
|
1427
|
+
return this.present(
|
|
1428
|
+
await this.data(`/api/carts/${encodeURIComponent(fresh)}/line-items`, {
|
|
1429
|
+
method: "POST",
|
|
1430
|
+
body: { variant_id: Number(variantId), quantity: Number(qty) }
|
|
1431
|
+
})
|
|
1432
|
+
);
|
|
1433
|
+
}
|
|
1434
|
+
throw err;
|
|
1435
|
+
}
|
|
1435
1436
|
}
|
|
1437
|
+
/** `qty` is the new total; 0 takes the line out. */
|
|
1436
1438
|
async updateCart({
|
|
1437
|
-
qty,
|
|
1438
1439
|
cartId,
|
|
1439
|
-
lineId
|
|
1440
|
-
|
|
1441
|
-
variantId
|
|
1440
|
+
lineId,
|
|
1441
|
+
qty
|
|
1442
1442
|
}) {
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1443
|
+
const id = clean(cartId) ?? storedCartId();
|
|
1444
|
+
if (!id) return emptyCart(await this.currency());
|
|
1445
|
+
return this.setQuantity(id, lineId, Number(qty));
|
|
1446
|
+
}
|
|
1447
|
+
async removeCart({ cartId, lineId }) {
|
|
1448
|
+
const id = clean(cartId) ?? storedCartId();
|
|
1449
|
+
if (!id) return emptyCart(await this.currency());
|
|
1450
|
+
return this.present(
|
|
1451
|
+
await this.data(`/api/carts/${encodeURIComponent(id)}/line-items/${encodeURIComponent(String(lineId))}`, {
|
|
1452
|
+
method: "DELETE"
|
|
1453
|
+
})
|
|
1454
|
+
);
|
|
1447
1455
|
}
|
|
1448
1456
|
/**
|
|
1449
|
-
*
|
|
1450
|
-
*
|
|
1451
|
-
*
|
|
1452
|
-
* fields are arguments to checkout. They are kept against this cart id in the browser and sent
|
|
1453
|
-
* when the order is placed — see checkout-details.ts. The email additionally seeds a cart that
|
|
1454
|
-
* has not been opened yet, which is the one moment GoCommerce does accept it.
|
|
1457
|
+
* Contact details and addresses, from the checkout's address step. The
|
|
1458
|
+
* email goes to the engine — it is how an abandoned cart is followed up —
|
|
1459
|
+
* and the rest is kept for the checkout request.
|
|
1455
1460
|
*/
|
|
1456
|
-
async updateCart2({
|
|
1457
|
-
cartId
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
shippingAddress
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
let id = usableId(cartId) || readStoredCartId();
|
|
1465
|
-
let cart = id ? await this.readCart(id) : null;
|
|
1466
|
-
if (!cart) {
|
|
1467
|
-
cart = await this.openCart(email);
|
|
1468
|
-
id = cart?.id ?? null;
|
|
1461
|
+
async updateCart2(args) {
|
|
1462
|
+
const id = clean(args.cartId) ?? storedCartId();
|
|
1463
|
+
if (!id) return emptyCart(await this.currency());
|
|
1464
|
+
const patch = {};
|
|
1465
|
+
if (args.phone !== void 0) patch.phone = args.phone || void 0;
|
|
1466
|
+
if (args.shippingAddress !== void 0) {
|
|
1467
|
+
patch.shippingAddress = args.shippingAddress;
|
|
1468
|
+
if (args.shippingAddress?.phone && !patch.phone) patch.phone = String(args.shippingAddress.phone);
|
|
1469
1469
|
}
|
|
1470
|
-
if (
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
|
|
1470
|
+
if (args.billingAddress !== void 0 || args.isBillingAddressSameAsShipping) {
|
|
1471
|
+
patch.billingAddress = args.isBillingAddressSameAsShipping ? null : args.billingAddress ?? null;
|
|
1472
|
+
}
|
|
1473
|
+
const before = cartExtras(id);
|
|
1474
|
+
const country = (a) => String(a?.countryCode || a?.country || "").toUpperCase();
|
|
1475
|
+
if (args.shippingAddress !== void 0 && country(args.shippingAddress) !== country(before.shippingAddress)) {
|
|
1476
|
+
patch.shippingRateId = null;
|
|
1477
|
+
patch.shippingRate = null;
|
|
1478
|
+
}
|
|
1479
|
+
saveCartExtras(id, patch);
|
|
1480
|
+
const email = args.email ?? (args.shippingAddress?.email ? String(args.shippingAddress.email) : void 0);
|
|
1481
|
+
if (email !== void 0) {
|
|
1482
|
+
return this.present(
|
|
1483
|
+
await this.data(`/api/carts/${encodeURIComponent(id)}/email`, { method: "PUT", body: { email } })
|
|
1484
|
+
);
|
|
1485
|
+
}
|
|
1486
|
+
return this.getCartByCartId(id);
|
|
1487
|
+
}
|
|
1488
|
+
/**
|
|
1489
|
+
* A discount code. The engine prices it against the basket now and decides
|
|
1490
|
+
* it again at checkout; what it answers is kept so the bag can show it,
|
|
1491
|
+
* because the cart itself does not carry the code.
|
|
1492
|
+
*/
|
|
1493
|
+
async applyCoupon({ cartId, couponCode }) {
|
|
1494
|
+
const id = clean(cartId) ?? storedCartId();
|
|
1495
|
+
if (!id) throw new GoCommerceError("Add something to your bag before applying a code.", 400);
|
|
1496
|
+
const cart = await this.data(`/api/carts/${encodeURIComponent(id)}`);
|
|
1497
|
+
const discount = await this.data(`/api/carts/${encodeURIComponent(id)}/discount`, {
|
|
1498
|
+
method: "PUT",
|
|
1499
|
+
body: { code: String(couponCode ?? "").trim(), ...cart.email ? { email: cart.email } : {} }
|
|
1478
1500
|
});
|
|
1501
|
+
saveCartExtras(id, { discount: { ...discount, code: discount.code || String(couponCode).trim() } });
|
|
1479
1502
|
return this.present(cart);
|
|
1480
1503
|
}
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
return this.
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
|
|
1488
|
-
|
|
1489
|
-
|
|
1490
|
-
const
|
|
1491
|
-
if (
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
throw new
|
|
1504
|
+
async removeCoupon(cartId) {
|
|
1505
|
+
const id = clean(cartId) ?? storedCartId();
|
|
1506
|
+
if (!id) return emptyCart(await this.currency());
|
|
1507
|
+
await this.engine(`/api/carts/${encodeURIComponent(id)}/discount`, { method: "DELETE" });
|
|
1508
|
+
saveCartExtras(id, { discount: null });
|
|
1509
|
+
return this.getCartByCartId(id);
|
|
1510
|
+
}
|
|
1511
|
+
/** The delivery option the shopper picked, priced from the engine's own quote. */
|
|
1512
|
+
async updateShippingRate({ cartId, shippingRateId }) {
|
|
1513
|
+
const id = clean(cartId) ?? storedCartId();
|
|
1514
|
+
if (!id) return emptyCart(await this.currency());
|
|
1515
|
+
const ship = cartExtras(id).shippingAddress;
|
|
1516
|
+
const country = String(ship?.countryCode || ship?.country || "").toUpperCase();
|
|
1517
|
+
if (!country) throw new GoCommerceError("Add a delivery address first.", 400);
|
|
1518
|
+
const quote2 = await this.data("/api/checkout/rates", { query: { cart: id, country, state: ship?.state ? String(ship.state) : void 0 } });
|
|
1519
|
+
const rate = (quote2.rates ?? []).find((r) => String(r.rate_id) === String(shippingRateId));
|
|
1520
|
+
if (!rate) throw new GoCommerceError("That delivery option is not available for this address any more.", 409);
|
|
1521
|
+
saveCartExtras(id, {
|
|
1522
|
+
shippingRateId: String(rate.rate_id),
|
|
1523
|
+
shippingRate: {
|
|
1524
|
+
id: String(rate.rate_id),
|
|
1525
|
+
name: rate.name,
|
|
1526
|
+
minor: rate.price.amount_minor,
|
|
1527
|
+
currency: rate.price.currency
|
|
1528
|
+
}
|
|
1529
|
+
});
|
|
1530
|
+
return this.getCartByCartId(id);
|
|
1531
|
+
}
|
|
1532
|
+
/** The payment method is chosen at checkout, by which checkout route is called. */
|
|
1533
|
+
async updateCartPaymentMethod({ cartId }) {
|
|
1534
|
+
return this.getCartByCartId(clean(cartId) ?? storedCartId());
|
|
1535
|
+
}
|
|
1536
|
+
async completeCart() {
|
|
1537
|
+
throw new NotSupportedError("CartService", "completeCart", "an order is placed through checkoutService");
|
|
1538
|
+
}
|
|
1539
|
+
// ------------------------------------------------------------ internals
|
|
1540
|
+
async setQuantity(cartId, lineId, qty) {
|
|
1541
|
+
const path = `/api/carts/${encodeURIComponent(cartId)}/line-items/${encodeURIComponent(String(lineId))}`;
|
|
1542
|
+
if (qty <= 0) return this.present(await this.data(path, { method: "DELETE" }));
|
|
1543
|
+
return this.present(await this.data(path, { method: "PATCH", body: { quantity: qty } }));
|
|
1544
|
+
}
|
|
1545
|
+
/** A new cart, remembered — and priced for the signed-in shopper's group when the engine allows it. */
|
|
1546
|
+
async open() {
|
|
1547
|
+
const channel = this.creds.channel;
|
|
1548
|
+
const cart = await this.data("/api/carts", { method: "POST", ...channel ? { body: { channel } } : {} });
|
|
1549
|
+
rememberCartId(cart.id);
|
|
1550
|
+
if (sessionToken()) await this.claimCartForAccount(cart.id);
|
|
1551
|
+
return cart.id;
|
|
1552
|
+
}
|
|
1553
|
+
async currency() {
|
|
1554
|
+
try {
|
|
1555
|
+
return (await this.facts.ready()).currency;
|
|
1556
|
+
} catch {
|
|
1557
|
+
return "USD";
|
|
1558
|
+
}
|
|
1498
1559
|
}
|
|
1499
|
-
|
|
1500
|
-
|
|
1560
|
+
/** The engine's cart with the browser-held extras and each line's picture and link. */
|
|
1561
|
+
async present(cart) {
|
|
1562
|
+
const ids = [...new Set((cart.line_items ?? []).map((l) => l.product_id))];
|
|
1563
|
+
const products = /* @__PURE__ */ new Map();
|
|
1564
|
+
await Promise.all(
|
|
1565
|
+
ids.map(async (pid) => {
|
|
1566
|
+
products.set(pid, await this.productFor(pid));
|
|
1567
|
+
})
|
|
1568
|
+
);
|
|
1569
|
+
return toCart(cart, cartExtras(cart.id), (l) => {
|
|
1570
|
+
const p = products.get(l.product_id);
|
|
1571
|
+
if (!p) return {};
|
|
1572
|
+
const v = (p.variants ?? []).find((x) => x.id === l.variant_id);
|
|
1573
|
+
return { slug: p.slug, thumbnail: v?.image?.url ?? p.image_url ?? null };
|
|
1574
|
+
});
|
|
1501
1575
|
}
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1576
|
+
productFor(id) {
|
|
1577
|
+
return remember(
|
|
1578
|
+
`${this.engineBase()}|product|${id}`,
|
|
1579
|
+
() => this.data(`/api/products/${id}`).catch(() => null)
|
|
1580
|
+
);
|
|
1505
1581
|
}
|
|
1506
1582
|
};
|
|
1507
|
-
var
|
|
1583
|
+
var clean = (id) => id && id !== "undefined" && id !== "null" ? id : null;
|
|
1584
|
+
var cartService = new CartService();
|
|
1508
1585
|
|
|
1509
|
-
// src/services/checkout.ts
|
|
1510
|
-
var
|
|
1511
|
-
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
|
|
1517
|
-
};
|
|
1518
|
-
|
|
1519
|
-
|
|
1520
|
-
|
|
1521
|
-
|
|
1522
|
-
|
|
1523
|
-
|
|
1524
|
-
|
|
1525
|
-
|
|
1526
|
-
|
|
1527
|
-
|
|
1528
|
-
|
|
1529
|
-
|
|
1530
|
-
|
|
1531
|
-
};
|
|
1532
|
-
var titleCase = (code) => code.charAt(0).toUpperCase() + code.slice(1);
|
|
1533
|
-
var PaymentMethodService = class _PaymentMethodService extends BaseService {
|
|
1534
|
-
static instance;
|
|
1535
|
-
static getInstance() {
|
|
1536
|
-
if (!_PaymentMethodService.instance) _PaymentMethodService.instance = new _PaymentMethodService();
|
|
1537
|
-
return _PaymentMethodService.instance;
|
|
1538
|
-
}
|
|
1539
|
-
/**
|
|
1540
|
-
* What this store accepts, from `GET /api/checkout`.
|
|
1541
|
-
*
|
|
1542
|
-
* The storefront branches on an uppercase code (`COD`, `STRIPE`, …) while GoCommerce installs
|
|
1543
|
-
* them lowercase, so the code is uppercased for the UI and the original kept for the API call.
|
|
1544
|
-
*/
|
|
1545
|
-
async list(_params = {}) {
|
|
1546
|
-
const res = await this.api("GET", "/api/checkout");
|
|
1547
|
-
const codes = res.data?.payment_methods || [];
|
|
1548
|
-
installedCodes = codes;
|
|
1549
|
-
const data = codes.map((code, index) => ({
|
|
1550
|
-
id: code,
|
|
1551
|
-
code: code.toUpperCase(),
|
|
1552
|
-
name: METHOD_NAMES[code.toLowerCase()] || titleCase(code),
|
|
1553
|
-
description: "",
|
|
1554
|
-
active: true,
|
|
1555
|
-
isTest: false,
|
|
1556
|
-
img: null,
|
|
1557
|
-
rank: index,
|
|
1558
|
-
currency: res.data?.currency || null
|
|
1559
|
-
}));
|
|
1560
|
-
return { data, count: data.length, pageSize: data.length, noOfPage: data.length ? 1 : 0, page: 1 };
|
|
1586
|
+
// src/services/checkout-service.ts
|
|
1587
|
+
var CheckoutService = class extends BaseService {
|
|
1588
|
+
/** Delivery options for the address on the cart: `{ data: [{ id, name, base_rate }] }`. */
|
|
1589
|
+
async getShippingRates({ cartId } = {}) {
|
|
1590
|
+
const id = cartId || storedCartId();
|
|
1591
|
+
const ship = id ? cartExtras(id).shippingAddress : null;
|
|
1592
|
+
const country = String(ship?.countryCode || ship?.country || "").toUpperCase();
|
|
1593
|
+
if (!id || !country) return { data: [] };
|
|
1594
|
+
const quote2 = await this.data("/api/checkout/rates", { query: { cart: id, country, state: ship?.state ? String(ship.state) : void 0 } });
|
|
1595
|
+
return {
|
|
1596
|
+
data: (quote2.rates ?? []).map((r) => ({
|
|
1597
|
+
id: String(r.rate_id),
|
|
1598
|
+
name: r.name,
|
|
1599
|
+
description: null,
|
|
1600
|
+
base_rate: minorToMajor(r.price.amount_minor, r.price.currency),
|
|
1601
|
+
price: minorToMajor(r.price.amount_minor, r.price.currency),
|
|
1602
|
+
currencyCode: r.price.currency,
|
|
1603
|
+
// The engine's rates carry no delivery estimate; none is made up.
|
|
1604
|
+
estimated_min_days: null,
|
|
1605
|
+
estimated_max_days: null
|
|
1606
|
+
}))
|
|
1607
|
+
};
|
|
1561
1608
|
}
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
|
|
1565
|
-
|
|
1566
|
-
|
|
1567
|
-
|
|
1568
|
-
|
|
1609
|
+
/** Cash on delivery: the order is confirmed at once and paid on the doorstep. */
|
|
1610
|
+
async checkoutCOD({ cartId } = {}) {
|
|
1611
|
+
const result = await this.place("cod", cartId);
|
|
1612
|
+
return {
|
|
1613
|
+
order_no: result.order.number,
|
|
1614
|
+
orderNo: result.order.number,
|
|
1615
|
+
id: String(result.order.id),
|
|
1616
|
+
status: result.order.status
|
|
1617
|
+
};
|
|
1569
1618
|
}
|
|
1570
1619
|
/**
|
|
1571
|
-
*
|
|
1572
|
-
*
|
|
1573
|
-
*
|
|
1574
|
-
*
|
|
1575
|
-
* error rather than sent as blanks, because GoCommerce's own validation message ("address.line1
|
|
1576
|
-
* is required") does not tell a shopper which screen to go back to.
|
|
1620
|
+
* Razorpay's modal. The engine has already created the Razorpay order; this
|
|
1621
|
+
* hands the storefront what the modal needs. A store running Razorpay's
|
|
1622
|
+
* hosted (redirect) mode cannot be driven from this storefront's modal flow,
|
|
1623
|
+
* and says so rather than opening a modal on an order it cannot pay.
|
|
1577
1624
|
*/
|
|
1578
|
-
async
|
|
1579
|
-
const
|
|
1580
|
-
|
|
1581
|
-
|
|
1582
|
-
|
|
1583
|
-
|
|
1584
|
-
|
|
1585
|
-
const code = goCommerceCode(storefrontCode);
|
|
1586
|
-
let res;
|
|
1587
|
-
try {
|
|
1588
|
-
res = await this.api(
|
|
1589
|
-
"POST",
|
|
1590
|
-
`/api/checkout/${encodeURIComponent(code)}`,
|
|
1591
|
-
{
|
|
1592
|
-
cart_id: id,
|
|
1593
|
-
email: details.email,
|
|
1594
|
-
...details.name ? { name: details.name } : {},
|
|
1595
|
-
...details.phone ? { phone: details.phone } : {},
|
|
1596
|
-
address,
|
|
1597
|
-
...returnUrl || origin ? { return_url: returnUrl || `${origin}/checkout/process` } : {}
|
|
1598
|
-
},
|
|
1599
|
-
// A double-submitted Place Order must not become two orders and two inventory holds.
|
|
1600
|
-
{ "Idempotency-Key": `${id}:${code}` }
|
|
1625
|
+
async checkoutRazorpay({ cartId } = {}) {
|
|
1626
|
+
const result = await this.place("razorpay", cartId);
|
|
1627
|
+
const data = result.payment.client_data ?? {};
|
|
1628
|
+
if (result.payment.kind !== "client_action" || !data.razorpay_order_id) {
|
|
1629
|
+
throw new GoCommerceError(
|
|
1630
|
+
"This store takes Razorpay payments on Razorpay\u2019s own page, which this storefront does not support yet.",
|
|
1631
|
+
0
|
|
1601
1632
|
);
|
|
1602
|
-
} catch (error) {
|
|
1603
|
-
if (await cartService.cartIsSpent(id)) {
|
|
1604
|
-
throw new Error("This cart is no longer available \u2014 it has expired or was already checked out. Add the items to a new bag and try again.");
|
|
1605
|
-
}
|
|
1606
|
-
throw error;
|
|
1607
1633
|
}
|
|
1608
|
-
const order = res.data?.order;
|
|
1609
|
-
const payment = res.data?.payment;
|
|
1610
|
-
rememberOrderToken(order?.number, order?.access_token);
|
|
1611
|
-
clearCheckoutDetails(id);
|
|
1612
|
-
const index = await resolveProductIndex(
|
|
1613
|
-
(order?.line_items || []).map((line) => line.product_id),
|
|
1614
|
-
this.getFetch()
|
|
1615
|
-
);
|
|
1616
1634
|
return {
|
|
1617
|
-
|
|
1618
|
-
|
|
1619
|
-
|
|
1620
|
-
|
|
1621
|
-
|
|
1622
|
-
payment: payment ?? null,
|
|
1623
|
-
paymentKind: payment?.kind ?? "none",
|
|
1624
|
-
// A gateway's own fields (a Razorpay order id, a Stripe client secret, a redirect url)
|
|
1625
|
-
// ride on `client_data`; spreading them is what lets the storefront's per-gateway
|
|
1626
|
-
// branches find what they look for without this connector naming each gateway.
|
|
1627
|
-
...payment?.client_data ?? {}
|
|
1635
|
+
order_no: result.order.number,
|
|
1636
|
+
id: data.razorpay_order_id,
|
|
1637
|
+
key_id: data.key_id,
|
|
1638
|
+
amount: Number(data.amount),
|
|
1639
|
+
currency: data.currency
|
|
1628
1640
|
};
|
|
1629
1641
|
}
|
|
1630
|
-
|
|
1631
|
-
|
|
1632
|
-
|
|
1633
|
-
|
|
1634
|
-
return
|
|
1635
|
-
}
|
|
1636
|
-
|
|
1637
|
-
|
|
1638
|
-
|
|
1639
|
-
|
|
1640
|
-
|
|
1641
|
-
|
|
1642
|
-
|
|
1643
|
-
|
|
1642
|
+
/** The modal closed with a payment. The engine learns of it from Razorpay itself. */
|
|
1643
|
+
async captureRazorpayPayment({ razorpay_order_id }) {
|
|
1644
|
+
const order = placedOrderByReference(razorpay_order_id);
|
|
1645
|
+
if (!order) throw new GoCommerceError("That payment does not belong to an order placed from this browser.", 404);
|
|
1646
|
+
return { order_no: order.number, status: "processing" };
|
|
1647
|
+
}
|
|
1648
|
+
// The family's other gateways. GoCommerce's Stripe is a Payment Element
|
|
1649
|
+
// (a client secret, not a hosted page), and PayPal, Cashfree, PhonePe and
|
|
1650
|
+
// Affirm are not engine gateways at all; paymentMethodService never lists
|
|
1651
|
+
// them, so these are reached only by a storefront that hard-codes one.
|
|
1652
|
+
async checkoutStripe() {
|
|
1653
|
+
throw unsupported(
|
|
1654
|
+
"checkoutStripe",
|
|
1655
|
+
"GoCommerce\u2019s Stripe gateway uses the Payment Element, not a hosted checkout page"
|
|
1656
|
+
);
|
|
1644
1657
|
}
|
|
1645
|
-
async
|
|
1646
|
-
|
|
1658
|
+
async checkoutStripeCapture() {
|
|
1659
|
+
throw unsupported("checkoutStripeCapture", "Stripe confirms payments to the engine by webhook");
|
|
1647
1660
|
}
|
|
1648
|
-
async
|
|
1649
|
-
|
|
1661
|
+
async checkoutPaypal() {
|
|
1662
|
+
throw unsupported("checkoutPaypal", "the engine has no PayPal gateway");
|
|
1650
1663
|
}
|
|
1651
|
-
async
|
|
1652
|
-
|
|
1653
|
-
origin
|
|
1654
|
-
}) {
|
|
1655
|
-
return this.place("affirm", { cartId, origin });
|
|
1664
|
+
async capturePaypalPayment() {
|
|
1665
|
+
throw unsupported("capturePaypalPayment", "the engine has no PayPal gateway");
|
|
1656
1666
|
}
|
|
1657
|
-
|
|
1658
|
-
|
|
1659
|
-
// the storefront's redirect moving with the order number it already has rather than pretending
|
|
1660
|
-
// to perform a capture that this API does not offer.
|
|
1661
|
-
settled(orderNo) {
|
|
1662
|
-
return { order_no: orderNo || "", orderNo: orderNo || "", captured: false };
|
|
1667
|
+
async checkoutCashfree() {
|
|
1668
|
+
throw unsupported("checkoutCashfree", "the engine has no Cashfree gateway");
|
|
1663
1669
|
}
|
|
1664
|
-
async
|
|
1665
|
-
|
|
1670
|
+
async captureCashfreePayment() {
|
|
1671
|
+
throw unsupported("captureCashfreePayment", "the engine has no Cashfree gateway");
|
|
1666
1672
|
}
|
|
1667
|
-
async
|
|
1668
|
-
|
|
1673
|
+
async checkoutPhonepe() {
|
|
1674
|
+
throw unsupported("checkoutPhonepe", "the engine has no PhonePe gateway");
|
|
1669
1675
|
}
|
|
1670
|
-
async
|
|
1671
|
-
|
|
1676
|
+
async createAffirmPayOrder() {
|
|
1677
|
+
throw unsupported("createAffirmPayOrder", "the engine has no Affirm gateway");
|
|
1672
1678
|
}
|
|
1673
|
-
async
|
|
1674
|
-
|
|
1679
|
+
async confirmAffirmOrder() {
|
|
1680
|
+
throw unsupported("confirmAffirmOrder", "the engine has no Affirm gateway");
|
|
1675
1681
|
}
|
|
1676
|
-
async
|
|
1677
|
-
|
|
1682
|
+
async cancelAffirmOrder() {
|
|
1683
|
+
throw unsupported("cancelAffirmOrder", "the engine has no Affirm gateway");
|
|
1678
1684
|
}
|
|
1679
|
-
async
|
|
1680
|
-
throw
|
|
1685
|
+
async checkoutPOS() {
|
|
1686
|
+
throw unsupported("checkoutPOS", "point-of-sale orders are placed from the admin panel");
|
|
1681
1687
|
}
|
|
1682
1688
|
/**
|
|
1683
|
-
*
|
|
1684
|
-
*
|
|
1685
|
-
*
|
|
1689
|
+
* One checkout attempt.
|
|
1690
|
+
*
|
|
1691
|
+
* The Idempotency-Key is kept with the cart and reused while the request is
|
|
1692
|
+
* the same, because a payment gateway that fails after the engine has
|
|
1693
|
+
* created the order leaves the cart converted: only a retry under the same
|
|
1694
|
+
* key resumes that order, and without one the shopper is stuck. A changed
|
|
1695
|
+
* request — a different address, a different method — gets a new key, since
|
|
1696
|
+
* the engine refuses a key replayed with a different body.
|
|
1686
1697
|
*/
|
|
1687
|
-
async
|
|
1688
|
-
|
|
1698
|
+
async place(code, cartId) {
|
|
1699
|
+
const id = cartId || storedCartId();
|
|
1700
|
+
if (!id) throw new GoCommerceError("Your bag is empty.", 400);
|
|
1701
|
+
const extras = cartExtras(id);
|
|
1702
|
+
const ship = extras.shippingAddress;
|
|
1703
|
+
if (!ship) throw new GoCommerceError("Add a delivery address first.", 400);
|
|
1704
|
+
const cart = await this.data(`/api/carts/${encodeURIComponent(id)}`);
|
|
1705
|
+
const email = cart.email || (ship.email ? String(ship.email) : "");
|
|
1706
|
+
if (!email) throw new GoCommerceError("Add an email address so we can send your receipt.", 400);
|
|
1707
|
+
const address = toEngineAddress(ship);
|
|
1708
|
+
const body = {
|
|
1709
|
+
cart_id: id,
|
|
1710
|
+
email,
|
|
1711
|
+
...extras.phone || address.phone ? { phone: String(extras.phone || address.phone) } : {},
|
|
1712
|
+
...address.name ? { name: address.name } : {},
|
|
1713
|
+
address,
|
|
1714
|
+
...extras.shippingRateId ? { shipping_rate_id: Number(extras.shippingRateId) } : {}
|
|
1715
|
+
};
|
|
1716
|
+
const serialised = JSON.stringify(body);
|
|
1717
|
+
const key = extras.attempt?.body === `${code}:${serialised}` ? extras.attempt.key : newKey();
|
|
1718
|
+
saveCartExtras(id, { attempt: { key, body: `${code}:${serialised}` } });
|
|
1719
|
+
const result = await this.data(`/api/checkout/${encodeURIComponent(code)}`, {
|
|
1720
|
+
method: "POST",
|
|
1721
|
+
body,
|
|
1722
|
+
headers: { "Idempotency-Key": key }
|
|
1723
|
+
});
|
|
1724
|
+
if (result.order.access_token) {
|
|
1725
|
+
rememberOrder({
|
|
1726
|
+
number: result.order.number,
|
|
1727
|
+
token: result.order.access_token,
|
|
1728
|
+
cartId: id,
|
|
1729
|
+
reference: result.payment.client_data?.razorpay_order_id ?? result.payment.reference
|
|
1730
|
+
});
|
|
1731
|
+
if (sessionToken()) {
|
|
1732
|
+
await this.engine("/x/identity/me/orders", {
|
|
1733
|
+
method: "POST",
|
|
1734
|
+
body: { number: result.order.number, token: result.order.access_token },
|
|
1735
|
+
auth: true
|
|
1736
|
+
}).catch(() => void 0);
|
|
1737
|
+
}
|
|
1738
|
+
}
|
|
1739
|
+
saveCartExtras(id, { attempt: null });
|
|
1740
|
+
return result;
|
|
1689
1741
|
}
|
|
1690
1742
|
};
|
|
1691
|
-
var
|
|
1743
|
+
var unsupported = (method, why) => new NotSupportedError("CheckoutService", method, why);
|
|
1744
|
+
function newKey() {
|
|
1745
|
+
const c = globalThis.crypto;
|
|
1746
|
+
if (c?.randomUUID) return c.randomUUID();
|
|
1747
|
+
return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`;
|
|
1748
|
+
}
|
|
1749
|
+
var checkoutService = new CheckoutService();
|
|
1692
1750
|
|
|
1693
|
-
// src/services/
|
|
1694
|
-
var
|
|
1695
|
-
|
|
1696
|
-
|
|
1697
|
-
|
|
1698
|
-
|
|
1699
|
-
|
|
1700
|
-
|
|
1701
|
-
async
|
|
1702
|
-
|
|
1703
|
-
|
|
1704
|
-
|
|
1705
|
-
|
|
1706
|
-
|
|
1707
|
-
|
|
1751
|
+
// src/services/payment-method-service.ts
|
|
1752
|
+
var DRIVABLE = {
|
|
1753
|
+
cod: { code: "COD", img: "/payment/cod.svg" },
|
|
1754
|
+
razorpay: { code: "RAZORPAY" }
|
|
1755
|
+
};
|
|
1756
|
+
var reported2 = /* @__PURE__ */ new Set();
|
|
1757
|
+
var PaymentMethodService = class extends BaseService {
|
|
1758
|
+
facts = new StoreFacts(this._fetch);
|
|
1759
|
+
async list(_args = {}) {
|
|
1760
|
+
const options = await this.facts.checkoutOptions();
|
|
1761
|
+
const methods = options.methods ?? [];
|
|
1762
|
+
const data = methods.filter((m) => {
|
|
1763
|
+
if (DRIVABLE[m.code]) return true;
|
|
1764
|
+
if (!reported2.has(m.code)) {
|
|
1765
|
+
reported2.add(m.code);
|
|
1766
|
+
console.warn(
|
|
1767
|
+
`[gocommerce] payment method "${m.code}" is switched on but this storefront cannot drive its flow, so it is not offered.`
|
|
1768
|
+
);
|
|
1769
|
+
}
|
|
1770
|
+
return false;
|
|
1771
|
+
}).map((m, i) => ({
|
|
1772
|
+
id: m.code,
|
|
1773
|
+
code: DRIVABLE[m.code].code,
|
|
1774
|
+
engineCode: m.code,
|
|
1775
|
+
name: m.name,
|
|
1776
|
+
title: m.name,
|
|
1777
|
+
description: "",
|
|
1778
|
+
img: DRIVABLE[m.code].img ?? null,
|
|
1779
|
+
rank: i,
|
|
1780
|
+
active: true,
|
|
1781
|
+
isActive: true
|
|
1782
|
+
}));
|
|
1783
|
+
return { data, count: data.length, pageSize: data.length, noOfPage: 1, page: 1 };
|
|
1708
1784
|
}
|
|
1709
|
-
|
|
1710
|
-
|
|
1711
|
-
|
|
1712
|
-
|
|
1713
|
-
|
|
1714
|
-
|
|
1715
|
-
return
|
|
1785
|
+
};
|
|
1786
|
+
var paymentMethodService = new PaymentMethodService();
|
|
1787
|
+
|
|
1788
|
+
// src/services/coupon-service.ts
|
|
1789
|
+
var CouponService = class extends BaseService {
|
|
1790
|
+
async listCoupons(_args = {}) {
|
|
1791
|
+
return emptyPage();
|
|
1716
1792
|
}
|
|
1793
|
+
};
|
|
1794
|
+
var couponService = new CouponService();
|
|
1795
|
+
|
|
1796
|
+
// src/services/order-service.ts
|
|
1797
|
+
var OrderService = class extends BaseService {
|
|
1717
1798
|
/**
|
|
1718
|
-
* The
|
|
1799
|
+
* The order-success page's lookup, by the number and cart in its URL.
|
|
1719
1800
|
*
|
|
1720
|
-
*
|
|
1721
|
-
*
|
|
1801
|
+
* It runs on the server, where neither the token nor the session exists —
|
|
1802
|
+
* they live in the shopper's browser — so there it answers nothing and the
|
|
1803
|
+
* page says the details are not available yet. In the browser it answers
|
|
1804
|
+
* the order. Inventing a server-side credential from the cart token in the
|
|
1805
|
+
* URL would make that URL, which lands in history and referrers, a key to
|
|
1806
|
+
* the shopper's address.
|
|
1722
1807
|
*/
|
|
1723
|
-
async
|
|
1724
|
-
|
|
1808
|
+
async listOrdersByParent({ orderNo, cartId } = {}) {
|
|
1809
|
+
const number = clean2(orderNo) ?? (clean2(cartId) ? placedOrderForCart(clean2(cartId))?.number : void 0);
|
|
1810
|
+
if (!number) return { data: [] };
|
|
1725
1811
|
try {
|
|
1726
|
-
|
|
1727
|
-
|
|
1728
|
-
|
|
1729
|
-
|
|
1812
|
+
return { data: [await this.getOrder(number)] };
|
|
1813
|
+
} catch (err) {
|
|
1814
|
+
if (err instanceof GoCommerceError && (err.status === 404 || err.status === 401)) return { data: [] };
|
|
1815
|
+
throw err;
|
|
1730
1816
|
}
|
|
1731
|
-
if (!cart) return null;
|
|
1732
|
-
const lines = cart.line_items || [];
|
|
1733
|
-
const index = await resolveProductIndex(
|
|
1734
|
-
lines.map((line) => line.product_id),
|
|
1735
|
-
this.getFetch()
|
|
1736
|
-
);
|
|
1737
|
-
const subtotal = fromMoney(cart.subtotal);
|
|
1738
|
-
return {
|
|
1739
|
-
id: null,
|
|
1740
|
-
orderNo: orderNumber,
|
|
1741
|
-
order_no: orderNumber,
|
|
1742
|
-
parentOrderNo: orderNumber,
|
|
1743
|
-
status: cart.status === "converted" ? "confirmed" : "pending",
|
|
1744
|
-
paymentStatus: "pending",
|
|
1745
|
-
paymentMethod: null,
|
|
1746
|
-
createdAt: cart.updated_at || cart.created_at || null,
|
|
1747
|
-
updatedAt: cart.updated_at || null,
|
|
1748
|
-
userEmail: cart.email || "",
|
|
1749
|
-
phone: "",
|
|
1750
|
-
subtotal,
|
|
1751
|
-
shippingCharges: 0,
|
|
1752
|
-
discount: 0,
|
|
1753
|
-
total: subtotal,
|
|
1754
|
-
currencyCode: cart.currency,
|
|
1755
|
-
shippingRate: null,
|
|
1756
|
-
fulfillments: [],
|
|
1757
|
-
shippingAddress: null,
|
|
1758
|
-
billingAddress: null,
|
|
1759
|
-
lineItems: lines.map((line) => {
|
|
1760
|
-
const product = line.product_id == null ? void 0 : index.get(line.product_id);
|
|
1761
|
-
const mapped = product ? mapProduct(product) : null;
|
|
1762
|
-
const variant = product?.variants?.find((v) => v.id === line.variant_id);
|
|
1763
|
-
return {
|
|
1764
|
-
id: line.id,
|
|
1765
|
-
productId: line.product_id,
|
|
1766
|
-
variantId: line.variant_id,
|
|
1767
|
-
title: line.title || mapped?.title || "",
|
|
1768
|
-
variantTitle: line.variant_label || line.sku || "",
|
|
1769
|
-
slug: mapped?.slug || "",
|
|
1770
|
-
sku: line.sku || "",
|
|
1771
|
-
thumbnail: absoluteMedia(variant?.image?.url) || mapped?.thumbnail || null,
|
|
1772
|
-
qty: line.quantity,
|
|
1773
|
-
price: fromMoney(line.unit_price),
|
|
1774
|
-
subtotal: fromMoney(line.total),
|
|
1775
|
-
total: fromMoney(line.total)
|
|
1776
|
-
};
|
|
1777
|
-
})
|
|
1778
|
-
};
|
|
1779
1817
|
}
|
|
1780
|
-
/**
|
|
1781
|
-
|
|
1782
|
-
|
|
1783
|
-
|
|
1784
|
-
|
|
1785
|
-
|
|
1786
|
-
|
|
1787
|
-
const
|
|
1788
|
-
|
|
1789
|
-
|
|
1790
|
-
|
|
1791
|
-
|
|
1792
|
-
return token ? this.present(await this.readOrder(number, token)) : null;
|
|
1793
|
-
})
|
|
1794
|
-
);
|
|
1795
|
-
return paginated(orders.filter(Boolean), numbers.length, page);
|
|
1796
|
-
}
|
|
1797
|
-
/** What the confirmation page loads with, server-side, straight after checkout. */
|
|
1798
|
-
async listOrdersByParent({ orderNo, cartId }) {
|
|
1799
|
-
const number = usable(orderNo);
|
|
1800
|
-
if (!number) return emptyPage();
|
|
1801
|
-
const token = readOrderToken(number);
|
|
1802
|
-
if (token) {
|
|
1803
|
-
const order = await this.present(await this.readOrder(number, token));
|
|
1804
|
-
if (order) return paginated([order], 1, 1, 1);
|
|
1818
|
+
/** The signed-in shopper's orders, newest claim first. */
|
|
1819
|
+
async list({ page = 1, limit = 20 } = {}) {
|
|
1820
|
+
const env = await this.engine("/x/identity/me/orders", { query: { page, limit }, auth: true });
|
|
1821
|
+
return toPage(env, toOrder);
|
|
1822
|
+
}
|
|
1823
|
+
/** One order by number: the account's when signed in, otherwise one this browser placed. */
|
|
1824
|
+
async getOrder(number) {
|
|
1825
|
+
const kept = placedOrder(number);
|
|
1826
|
+
if (kept) {
|
|
1827
|
+
return toOrder(
|
|
1828
|
+
await this.data(`/api/orders/${encodeURIComponent(number)}`, { query: { token: kept.token } })
|
|
1829
|
+
);
|
|
1805
1830
|
}
|
|
1806
|
-
|
|
1807
|
-
|
|
1808
|
-
const reconstructed = await this.orderFromCart(cart, number);
|
|
1809
|
-
if (reconstructed) return paginated([reconstructed], 1, 1, 1);
|
|
1831
|
+
if (sessionToken()) {
|
|
1832
|
+
return toOrder(await this.data(`/x/identity/me/orders/${encodeURIComponent(number)}`, { auth: true }));
|
|
1810
1833
|
}
|
|
1811
|
-
|
|
1834
|
+
throw new GoCommerceError(
|
|
1835
|
+
inBrowser() ? "Sign in to see this order, or open it from the browser that placed it." : "order not found",
|
|
1836
|
+
404,
|
|
1837
|
+
"not_found"
|
|
1838
|
+
);
|
|
1812
1839
|
}
|
|
1813
|
-
|
|
1814
|
-
|
|
1815
|
-
|
|
1816
|
-
const
|
|
1817
|
-
|
|
1818
|
-
|
|
1840
|
+
/** Everything the signed-in shopper has bought, once each, most recent first. */
|
|
1841
|
+
async buyAgain() {
|
|
1842
|
+
const orders = await this.data("/x/identity/me/orders", { query: { limit: 20 }, auth: true }) ?? [];
|
|
1843
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1844
|
+
const lines = [];
|
|
1845
|
+
for (const o of orders) {
|
|
1846
|
+
for (const l of o.line_items ?? []) {
|
|
1847
|
+
if (!l.product_id || !l.variant_id || seen.has(l.variant_id)) continue;
|
|
1848
|
+
seen.add(l.variant_id);
|
|
1849
|
+
lines.push({
|
|
1850
|
+
productId: l.product_id,
|
|
1851
|
+
variantId: l.variant_id,
|
|
1852
|
+
title: l.title,
|
|
1853
|
+
img: l.image_url ?? null,
|
|
1854
|
+
price: toMajor(l.unit_price),
|
|
1855
|
+
qty: l.quantity
|
|
1856
|
+
});
|
|
1857
|
+
}
|
|
1858
|
+
}
|
|
1859
|
+
const live = await Promise.all(
|
|
1860
|
+
lines.map((l) => this.data(`/api/products/${l.productId}`).catch(() => null))
|
|
1861
|
+
);
|
|
1862
|
+
return lines.flatMap((l, i) => {
|
|
1863
|
+
const p = live[i];
|
|
1864
|
+
if (!p) return [];
|
|
1865
|
+
return [{ ...l, productId: String(l.productId), variantId: String(l.variantId), slug: p.slug }];
|
|
1866
|
+
});
|
|
1819
1867
|
}
|
|
1820
|
-
|
|
1821
|
-
|
|
1868
|
+
/** The "someone just bought" popup would publish other shoppers' purchases; the engine offers none. */
|
|
1869
|
+
async listPublic(_args = {}) {
|
|
1870
|
+
return emptyPage();
|
|
1822
1871
|
}
|
|
1823
|
-
async
|
|
1824
|
-
|
|
1872
|
+
async getOrderByEmailAndOTP() {
|
|
1873
|
+
throw new NotSupportedError(
|
|
1874
|
+
"OrderService",
|
|
1875
|
+
"getOrderByEmailAndOTP",
|
|
1876
|
+
"the engine sends no one-time codes; a guest reads an order with its access token"
|
|
1877
|
+
);
|
|
1825
1878
|
}
|
|
1826
|
-
|
|
1827
|
-
|
|
1879
|
+
};
|
|
1880
|
+
var clean2 = (v) => v && v !== "undefined" && v !== "null" ? v : void 0;
|
|
1881
|
+
var orderService = new OrderService();
|
|
1882
|
+
|
|
1883
|
+
// src/services/user-service.ts
|
|
1884
|
+
var UserService = class extends BaseService {
|
|
1885
|
+
/** Email and password. The answer is the user object the storefront keeps in its `me` cookie. */
|
|
1886
|
+
async login({ email, password }) {
|
|
1887
|
+
const auth = await this.account("/x/identity/login", {
|
|
1888
|
+
method: "POST",
|
|
1889
|
+
body: { email: String(email ?? "").trim(), password: String(password ?? "") }
|
|
1890
|
+
});
|
|
1891
|
+
return this.signedIn(auth);
|
|
1828
1892
|
}
|
|
1829
|
-
|
|
1830
|
-
|
|
1831
|
-
|
|
1893
|
+
async signup({
|
|
1894
|
+
email,
|
|
1895
|
+
password,
|
|
1896
|
+
firstName,
|
|
1897
|
+
lastName,
|
|
1898
|
+
phone
|
|
1899
|
+
}) {
|
|
1900
|
+
const name = [firstName, lastName].filter(Boolean).join(" ").trim();
|
|
1901
|
+
const auth = await this.account("/x/identity/register", {
|
|
1902
|
+
method: "POST",
|
|
1903
|
+
body: {
|
|
1904
|
+
email: String(email ?? "").trim(),
|
|
1905
|
+
password: String(password ?? ""),
|
|
1906
|
+
...name ? { name } : {},
|
|
1907
|
+
...phone ? { phone: String(phone) } : {}
|
|
1908
|
+
}
|
|
1909
|
+
});
|
|
1910
|
+
return this.signedIn(auth);
|
|
1832
1911
|
}
|
|
1833
|
-
|
|
1834
|
-
async
|
|
1835
|
-
|
|
1912
|
+
/** Signs out here and on the engine. The storefront assigns the answer to its user: `null`. */
|
|
1913
|
+
async logout() {
|
|
1914
|
+
await this.engine("/x/identity/logout", { method: "POST", auth: true }).catch(() => void 0);
|
|
1915
|
+
endSession();
|
|
1916
|
+
return null;
|
|
1836
1917
|
}
|
|
1837
|
-
async
|
|
1838
|
-
return
|
|
1918
|
+
async getMe() {
|
|
1919
|
+
return toUser(await this.account("/x/identity/me", { auth: true }));
|
|
1839
1920
|
}
|
|
1840
|
-
async
|
|
1841
|
-
|
|
1921
|
+
async updateProfile(user) {
|
|
1922
|
+
const name = user.name ?? [user.firstName, user.lastName].filter((v) => v !== void 0).join(" ").trim();
|
|
1923
|
+
const c = await this.account("/x/identity/me", {
|
|
1924
|
+
method: "PATCH",
|
|
1925
|
+
auth: true,
|
|
1926
|
+
body: {
|
|
1927
|
+
...name !== void 0 ? { name } : {},
|
|
1928
|
+
...user.email ? { email: String(user.email).trim() } : {},
|
|
1929
|
+
...user.phone !== void 0 && user.phone !== null ? { phone: String(user.phone) } : {}
|
|
1930
|
+
}
|
|
1931
|
+
});
|
|
1932
|
+
updateMe(c);
|
|
1933
|
+
return toUser(c);
|
|
1842
1934
|
}
|
|
1843
|
-
|
|
1844
|
-
|
|
1845
|
-
|
|
1846
|
-
|
|
1935
|
+
/**
|
|
1936
|
+
* A password change ends every session the account had, this one included,
|
|
1937
|
+
* and the engine answers a fresh one — which is kept, so the shopper stays
|
|
1938
|
+
* signed in here and nowhere else.
|
|
1939
|
+
*/
|
|
1940
|
+
async changePassword({ old, oldPassword, password }) {
|
|
1941
|
+
const auth = await this.account("/x/identity/me/password", {
|
|
1942
|
+
method: "PUT",
|
|
1943
|
+
auth: true,
|
|
1944
|
+
body: { current_password: String(old ?? oldPassword ?? ""), password: String(password ?? "") }
|
|
1945
|
+
});
|
|
1946
|
+
startSession(auth);
|
|
1947
|
+
return toUser(auth.record);
|
|
1847
1948
|
}
|
|
1848
|
-
async
|
|
1849
|
-
throw new
|
|
1949
|
+
async deleteUser() {
|
|
1950
|
+
throw new NotSupportedError("UserService", "deleteUser", "an account is closed by the store, on request");
|
|
1850
1951
|
}
|
|
1851
|
-
async
|
|
1852
|
-
throw new
|
|
1952
|
+
async checkEmail() {
|
|
1953
|
+
throw new NotSupportedError("UserService", "checkEmail", "the engine does not say which addresses have accounts");
|
|
1853
1954
|
}
|
|
1854
|
-
async
|
|
1855
|
-
throw new
|
|
1955
|
+
async joinAsVendor() {
|
|
1956
|
+
throw new NotSupportedError("UserService", "joinAsVendor", "sellers are invited by the store");
|
|
1856
1957
|
}
|
|
1857
|
-
async
|
|
1858
|
-
|
|
1958
|
+
async signedIn(auth) {
|
|
1959
|
+
const me = startSession(auth);
|
|
1960
|
+
const cartId = storedCartId();
|
|
1961
|
+
if (cartId) await this.claimCartForAccount(cartId);
|
|
1962
|
+
return me;
|
|
1859
1963
|
}
|
|
1860
|
-
|
|
1861
|
-
|
|
1862
|
-
|
|
1863
|
-
|
|
1864
|
-
|
|
1865
|
-
|
|
1866
|
-
|
|
1867
|
-
|
|
1868
|
-
|
|
1869
|
-
|
|
1870
|
-
}
|
|
1871
|
-
async getStoreByIdOrDomain(_params = {}) {
|
|
1872
|
-
const store = await readStaticStoreDetails();
|
|
1873
|
-
if (!store) {
|
|
1874
|
-
throw new Error("No store configuration is registered \u2014 check kitcommerce.config.ts (see docs/GOCOMMERCE.md).");
|
|
1964
|
+
/** An identity call, with a 404 from a build without the module said in words. */
|
|
1965
|
+
async account(path, req = {}) {
|
|
1966
|
+
try {
|
|
1967
|
+
return await this.data(path, req);
|
|
1968
|
+
} catch (err) {
|
|
1969
|
+
if (err instanceof GoCommerceError && err.status === 404 && /no route/i.test(err.message)) {
|
|
1970
|
+
throw new GoCommerceError("Accounts are not available on this store.", 404, "not_found");
|
|
1971
|
+
}
|
|
1972
|
+
if (err instanceof GoCommerceError && err.status === 401 && req.auth) endSession();
|
|
1973
|
+
throw err;
|
|
1875
1974
|
}
|
|
1876
|
-
return store;
|
|
1877
|
-
}
|
|
1878
|
-
/** The settings store asks for the record by id; there is only ever the configured one. */
|
|
1879
|
-
async getStore(_storeId) {
|
|
1880
|
-
return this.getStoreByIdOrDomain({});
|
|
1881
1975
|
}
|
|
1882
1976
|
};
|
|
1883
|
-
var
|
|
1884
|
-
|
|
1885
|
-
|
|
1886
|
-
|
|
1887
|
-
|
|
1888
|
-
|
|
1889
|
-
}
|
|
1890
|
-
/** The nav reads `response.data` and filters it on `menuId`, the way the Litekart API served it. */
|
|
1891
|
-
async list() {
|
|
1892
|
-
const store = await readStaticStore();
|
|
1893
|
-
return { data: store?.menu ?? [] };
|
|
1977
|
+
var AuthService = class extends UserService {
|
|
1978
|
+
async forgotPassword({ email }) {
|
|
1979
|
+
return this.account("/x/identity/password-reset", {
|
|
1980
|
+
method: "POST",
|
|
1981
|
+
body: { email: String(email ?? "").trim() }
|
|
1982
|
+
});
|
|
1894
1983
|
}
|
|
1895
|
-
|
|
1896
|
-
|
|
1897
|
-
|
|
1898
|
-
|
|
1899
|
-
|
|
1900
|
-
|
|
1901
|
-
return
|
|
1984
|
+
/** The token arrives in the link the engine emailed (`GOCOMMERCE_IDENTITY_RESET_URL`). */
|
|
1985
|
+
async resetPassword({ token, password }) {
|
|
1986
|
+
const auth = await this.account("/x/identity/password-reset/confirm", {
|
|
1987
|
+
method: "POST",
|
|
1988
|
+
body: { token: String(token ?? ""), password: String(password ?? "") }
|
|
1989
|
+
});
|
|
1990
|
+
return startSession(auth);
|
|
1902
1991
|
}
|
|
1903
|
-
|
|
1904
|
-
async
|
|
1905
|
-
|
|
1992
|
+
/** Answers `{ errorCode, message }` on failure rather than throwing: that is how the page reads it. */
|
|
1993
|
+
async verifyEmail(_email, token) {
|
|
1994
|
+
try {
|
|
1995
|
+
const c = await this.account("/x/identity/email-verification/confirm", {
|
|
1996
|
+
method: "POST",
|
|
1997
|
+
body: { token: String(token ?? "") }
|
|
1998
|
+
});
|
|
1999
|
+
return { ...toUser(c), message: "Your email address is confirmed." };
|
|
2000
|
+
} catch (err) {
|
|
2001
|
+
return { errorCode: err.code ?? "invalid_token", message: err.message };
|
|
2002
|
+
}
|
|
1906
2003
|
}
|
|
1907
|
-
|
|
1908
|
-
|
|
1909
|
-
var CurrencyService = class _CurrencyService extends BaseService {
|
|
1910
|
-
static instance;
|
|
1911
|
-
static getInstance() {
|
|
1912
|
-
if (!_CurrencyService.instance) _CurrencyService.instance = new _CurrencyService();
|
|
1913
|
-
return _CurrencyService.instance;
|
|
1914
|
-
}
|
|
1915
|
-
/** One currency: GoCommerce prices a store in the currency its catalogue is recorded in. */
|
|
1916
|
-
async listCurrencies() {
|
|
1917
|
-
const store = await readStaticStore();
|
|
1918
|
-
return listOf(store?.currency ? [store.currency] : []);
|
|
2004
|
+
async getOtp() {
|
|
2005
|
+
throw new NotSupportedError("AuthService", "getOtp", "sign in with an email and password");
|
|
1919
2006
|
}
|
|
1920
|
-
|
|
1921
|
-
|
|
1922
|
-
var RegionService = class _RegionService extends BaseService {
|
|
1923
|
-
static instance;
|
|
1924
|
-
static getInstance() {
|
|
1925
|
-
if (!_RegionService.instance) _RegionService.instance = new _RegionService();
|
|
1926
|
-
return _RegionService.instance;
|
|
2007
|
+
async verifyOtp() {
|
|
2008
|
+
throw new NotSupportedError("AuthService", "verifyOtp", "sign in with an email and password");
|
|
1927
2009
|
}
|
|
1928
|
-
|
|
1929
|
-
|
|
1930
|
-
return {};
|
|
2010
|
+
async joinAsAdmin() {
|
|
2011
|
+
throw new NotSupportedError("AuthService", "joinAsAdmin", "operators are invited from the admin panel");
|
|
1931
2012
|
}
|
|
1932
2013
|
};
|
|
1933
|
-
var
|
|
1934
|
-
|
|
1935
|
-
|
|
1936
|
-
static getInstance() {
|
|
1937
|
-
if (!_PluginService.instance) _PluginService.instance = new _PluginService();
|
|
1938
|
-
return _PluginService.instance;
|
|
2014
|
+
var ProfileService = class extends UserService {
|
|
2015
|
+
async getOne() {
|
|
2016
|
+
return this.getMe();
|
|
1939
2017
|
}
|
|
1940
|
-
async
|
|
1941
|
-
|
|
1942
|
-
return listOf(store?.plugins ?? []);
|
|
2018
|
+
async save(profile) {
|
|
2019
|
+
return this.updateProfile(profile);
|
|
1943
2020
|
}
|
|
1944
2021
|
};
|
|
1945
|
-
var
|
|
1946
|
-
var
|
|
1947
|
-
var
|
|
1948
|
-
|
|
1949
|
-
|
|
1950
|
-
|
|
1951
|
-
|
|
1952
|
-
|
|
1953
|
-
|
|
1954
|
-
|
|
1955
|
-
|
|
2022
|
+
var userService = new UserService();
|
|
2023
|
+
var authService = new AuthService();
|
|
2024
|
+
var profileService = new ProfileService();
|
|
2025
|
+
|
|
2026
|
+
// src/services/address-service.ts
|
|
2027
|
+
var AddressService = class extends BaseService {
|
|
2028
|
+
async list({
|
|
2029
|
+
page = 1,
|
|
2030
|
+
limit = 20
|
|
2031
|
+
} = {}) {
|
|
2032
|
+
const env = await this.engine("/x/identity/me/addresses", {
|
|
2033
|
+
query: { page, limit },
|
|
2034
|
+
auth: true
|
|
2035
|
+
});
|
|
2036
|
+
const email = currentMe()?.email;
|
|
2037
|
+
const rows = env.data ?? [];
|
|
2038
|
+
return {
|
|
2039
|
+
data: rows.map((a) => fromIdentityAddress(a, email)),
|
|
2040
|
+
count: env.meta?.total ?? rows.length,
|
|
2041
|
+
pageSize: env.meta?.limit ?? limit,
|
|
2042
|
+
noOfPage: env.meta?.total_pages ?? 1,
|
|
2043
|
+
page: env.meta?.page ?? page
|
|
2044
|
+
};
|
|
1956
2045
|
}
|
|
1957
|
-
|
|
1958
|
-
|
|
1959
|
-
|
|
2046
|
+
async fetchAddress(id) {
|
|
2047
|
+
return fromIdentityAddress(
|
|
2048
|
+
await this.data(`/x/identity/me/addresses/${enc(id)}`, { auth: true }),
|
|
2049
|
+
currentMe()?.email
|
|
2050
|
+
);
|
|
1960
2051
|
}
|
|
1961
|
-
|
|
1962
|
-
|
|
2052
|
+
/** New when it has no id (or the form's `'new'`), an edit when it has one — the storefront saves both here. */
|
|
2053
|
+
async saveAddress(address) {
|
|
2054
|
+
const id = address?.id && address.id !== "new" ? String(address.id) : null;
|
|
2055
|
+
if (id) return this.editAddress(id, address);
|
|
2056
|
+
const a = await this.data("/x/identity/me/addresses", {
|
|
2057
|
+
method: "POST",
|
|
2058
|
+
auth: true,
|
|
2059
|
+
body: toIdentityAddress(address)
|
|
2060
|
+
});
|
|
2061
|
+
return fromIdentityAddress(a, currentMe()?.email);
|
|
1963
2062
|
}
|
|
1964
|
-
|
|
1965
|
-
|
|
1966
|
-
|
|
1967
|
-
|
|
1968
|
-
|
|
1969
|
-
|
|
1970
|
-
|
|
1971
|
-
return _InitService.instance;
|
|
2063
|
+
async editAddress(id, address) {
|
|
2064
|
+
const a = await this.data(`/x/identity/me/addresses/${enc(id)}`, {
|
|
2065
|
+
method: "PATCH",
|
|
2066
|
+
auth: true,
|
|
2067
|
+
body: toIdentityAddress(address)
|
|
2068
|
+
});
|
|
2069
|
+
return fromIdentityAddress(a, currentMe()?.email);
|
|
1972
2070
|
}
|
|
1973
|
-
async
|
|
1974
|
-
|
|
1975
|
-
return
|
|
2071
|
+
async deleteAddress(id) {
|
|
2072
|
+
await this.engine(`/x/identity/me/addresses/${enc(id)}`, { method: "DELETE", auth: true });
|
|
2073
|
+
return { id: String(id), deleted: true };
|
|
1976
2074
|
}
|
|
1977
2075
|
};
|
|
1978
|
-
var
|
|
1979
|
-
var
|
|
1980
|
-
|
|
1981
|
-
|
|
1982
|
-
|
|
1983
|
-
|
|
1984
|
-
|
|
1985
|
-
|
|
1986
|
-
|
|
1987
|
-
|
|
2076
|
+
var enc = (id) => encodeURIComponent(String(id));
|
|
2077
|
+
var addressService = new AddressService();
|
|
2078
|
+
|
|
2079
|
+
// src/services/wishlist-service.ts
|
|
2080
|
+
var WishlistService = class extends BaseService {
|
|
2081
|
+
async fetchWishlist(_args = {}) {
|
|
2082
|
+
const list = await this.current();
|
|
2083
|
+
if (!list) return { data: [], count: 0 };
|
|
2084
|
+
const items = (list.items ?? []).filter((i) => !i.deleted);
|
|
2085
|
+
const products = await Promise.all(
|
|
2086
|
+
items.map((i) => this.data(`/api/products/${i.product_id}`).catch(() => null))
|
|
2087
|
+
);
|
|
2088
|
+
const data = items.flatMap((item, n) => {
|
|
2089
|
+
const p = products[n];
|
|
2090
|
+
if (!p) return [];
|
|
2091
|
+
return [
|
|
2092
|
+
{
|
|
2093
|
+
id: String(item.id),
|
|
2094
|
+
productId: String(item.product_id),
|
|
2095
|
+
variantId: item.variant_id ? String(item.variant_id) : null,
|
|
2096
|
+
product: toProduct(p),
|
|
2097
|
+
variant: { id: item.variant_id ? String(item.variant_id) : null },
|
|
2098
|
+
createdAt: item.created_at
|
|
2099
|
+
}
|
|
2100
|
+
];
|
|
2101
|
+
});
|
|
2102
|
+
return { data, count: data.length };
|
|
2103
|
+
}
|
|
2104
|
+
/** Saved → removed, removed → saved. `{ active }` is the state after the click. */
|
|
2105
|
+
async toggleWishlist({ productId, variantId }) {
|
|
2106
|
+
const list = await this.current() ?? await this.create();
|
|
2107
|
+
const item = (list.items ?? []).find((i) => String(i.product_id) === String(productId));
|
|
2108
|
+
if (item) {
|
|
2109
|
+
await this.data(`/x/wishlist/${enc2(list.token)}/items/${item.id}`, { method: "DELETE" });
|
|
2110
|
+
return { active: false, id: String(item.id) };
|
|
2111
|
+
}
|
|
2112
|
+
const next = await this.data(`/x/wishlist/${enc2(list.token)}/items`, {
|
|
2113
|
+
method: "POST",
|
|
2114
|
+
body: { product_id: Number(productId), ...variantId ? { variant_id: Number(variantId) } : {} }
|
|
2115
|
+
});
|
|
2116
|
+
const added = (next.items ?? []).find((i) => String(i.product_id) === String(productId));
|
|
2117
|
+
return { active: true, id: added ? String(added.id) : null };
|
|
1988
2118
|
}
|
|
1989
|
-
}
|
|
1990
|
-
|
|
1991
|
-
|
|
1992
|
-
static instance;
|
|
1993
|
-
static getInstance() {
|
|
1994
|
-
if (!_PopularSearchService.instance) _PopularSearchService.instance = new _PopularSearchService();
|
|
1995
|
-
return _PopularSearchService.instance;
|
|
2119
|
+
async checkWishlist({ productId }) {
|
|
2120
|
+
const list = await this.current();
|
|
2121
|
+
return !!list && (list.items ?? []).some((i) => String(i.product_id) === String(productId));
|
|
1996
2122
|
}
|
|
1997
|
-
|
|
1998
|
-
|
|
1999
|
-
|
|
2123
|
+
async checkWishlistInBulk(pairs) {
|
|
2124
|
+
const list = await this.current();
|
|
2125
|
+
const saved = new Set((list?.items ?? []).map((i) => String(i.product_id)));
|
|
2126
|
+
return (pairs ?? []).map((p) => ({ ...p, exists: saved.has(String(p.productId)) }));
|
|
2000
2127
|
}
|
|
2001
|
-
|
|
2002
|
-
|
|
2003
|
-
|
|
2004
|
-
|
|
2005
|
-
|
|
2006
|
-
|
|
2007
|
-
|
|
2128
|
+
async current() {
|
|
2129
|
+
const token = wishlistToken();
|
|
2130
|
+
if (!token) return null;
|
|
2131
|
+
try {
|
|
2132
|
+
return { ...await this.data(`/x/wishlist/${enc2(token)}`), token };
|
|
2133
|
+
} catch (err) {
|
|
2134
|
+
if (err instanceof GoCommerceError && err.status === 404 && !/no wishlist|no route/i.test(err.message)) {
|
|
2135
|
+
forgetWishlistToken();
|
|
2136
|
+
return null;
|
|
2137
|
+
}
|
|
2138
|
+
throw err;
|
|
2139
|
+
}
|
|
2008
2140
|
}
|
|
2009
|
-
|
|
2010
|
-
|
|
2011
|
-
|
|
2141
|
+
async create() {
|
|
2142
|
+
const email = currentMe()?.email;
|
|
2143
|
+
const list = await this.data("/x/wishlist", { method: "POST", ...email ? { body: { email } } : {} });
|
|
2144
|
+
if (!list.token) throw new GoCommerceError("The store did not return a wishlist token.", 500);
|
|
2145
|
+
rememberWishlistToken(list.token);
|
|
2146
|
+
return { ...list, token: list.token };
|
|
2012
2147
|
}
|
|
2013
2148
|
};
|
|
2014
|
-
var
|
|
2149
|
+
var enc2 = (s) => encodeURIComponent(s);
|
|
2150
|
+
var wishlistService = new WishlistService();
|
|
2015
2151
|
|
|
2016
|
-
// src/services/
|
|
2017
|
-
var
|
|
2018
|
-
|
|
2019
|
-
|
|
2020
|
-
|
|
2021
|
-
|
|
2022
|
-
|
|
2023
|
-
|
|
2024
|
-
|
|
2025
|
-
|
|
2026
|
-
|
|
2027
|
-
|
|
2028
|
-
|
|
2029
|
-
|
|
2030
|
-
|
|
2031
|
-
|
|
2032
|
-
|
|
2033
|
-
|
|
2152
|
+
// src/services/review-service.ts
|
|
2153
|
+
var ReviewService = class extends BaseService {
|
|
2154
|
+
async fetchReviews({
|
|
2155
|
+
productId,
|
|
2156
|
+
currentPage = 1,
|
|
2157
|
+
page,
|
|
2158
|
+
limit = 20
|
|
2159
|
+
} = {}) {
|
|
2160
|
+
if (!productId) return { data: [], count: 0, pageSize: limit, noOfPage: 0, page: 1 };
|
|
2161
|
+
const p = Math.max(1, Number(page ?? currentPage) || 1);
|
|
2162
|
+
const res = await this.data("/x/reviews", { query: { product_id: productId, page: p, limit } });
|
|
2163
|
+
const total = res.meta?.total ?? res.summary?.count ?? 0;
|
|
2164
|
+
return {
|
|
2165
|
+
data: (res.reviews ?? []).map(toRating),
|
|
2166
|
+
count: total,
|
|
2167
|
+
pageSize: limit,
|
|
2168
|
+
noOfPage: Math.max(1, Math.ceil(total / limit)),
|
|
2169
|
+
page: p,
|
|
2170
|
+
summary: res.summary ?? null
|
|
2171
|
+
};
|
|
2034
2172
|
}
|
|
2035
|
-
async
|
|
2036
|
-
|
|
2173
|
+
async allReviews(args = {}) {
|
|
2174
|
+
return this.fetchReviews(args);
|
|
2037
2175
|
}
|
|
2038
|
-
|
|
2039
|
-
|
|
2176
|
+
};
|
|
2177
|
+
var reviewService = new ReviewService();
|
|
2178
|
+
|
|
2179
|
+
// src/services/menu-service.ts
|
|
2180
|
+
function linkFor(item) {
|
|
2181
|
+
const t = item.target ?? "";
|
|
2182
|
+
switch (item.kind) {
|
|
2183
|
+
case "home":
|
|
2184
|
+
return "/";
|
|
2185
|
+
case "product":
|
|
2186
|
+
return t ? `/products/${t}` : item.url;
|
|
2187
|
+
case "collection":
|
|
2188
|
+
return t ? `/collections/${t}` : item.url;
|
|
2189
|
+
case "category":
|
|
2190
|
+
return t ? `/${t}` : item.url;
|
|
2191
|
+
case "page":
|
|
2192
|
+
return t ? `/p/${t}` : item.url;
|
|
2193
|
+
default:
|
|
2194
|
+
return item.url;
|
|
2195
|
+
}
|
|
2196
|
+
}
|
|
2197
|
+
var toItem = (item, i) => ({
|
|
2198
|
+
id: String(item.id ?? i),
|
|
2199
|
+
name: item.title,
|
|
2200
|
+
link: linkFor(item),
|
|
2201
|
+
items: (item.children ?? []).map(toItem)
|
|
2202
|
+
});
|
|
2203
|
+
var MenuService = class extends BaseService {
|
|
2204
|
+
facts = new StoreFacts(this._fetch);
|
|
2205
|
+
async list(_args = {}) {
|
|
2206
|
+
const menus = await this.engineMenus();
|
|
2207
|
+
if (menus) return { data: menus };
|
|
2208
|
+
return resolveRestLocally("get", "/api/menu");
|
|
2209
|
+
}
|
|
2210
|
+
/** The header and footer menus, or `null` when the module is not there. Cached: a menu is store-level. */
|
|
2211
|
+
async engineMenus() {
|
|
2212
|
+
if (!await this.facts.pluginOn("navigation")) return null;
|
|
2213
|
+
return remember(`${this.engineBase()}|${this.creds.store ?? ""}|menus`, async () => {
|
|
2214
|
+
const out = [];
|
|
2215
|
+
for (const handle of ["header", "footer"]) {
|
|
2216
|
+
try {
|
|
2217
|
+
const m = await this.data(`/x/navigation/menus/${handle}`);
|
|
2218
|
+
out.push({ menuId: handle, name: m.title, items: (m.items ?? []).map(toItem) });
|
|
2219
|
+
} catch {
|
|
2220
|
+
}
|
|
2221
|
+
}
|
|
2222
|
+
return out;
|
|
2223
|
+
}).catch(() => null);
|
|
2040
2224
|
}
|
|
2041
|
-
|
|
2042
|
-
|
|
2225
|
+
};
|
|
2226
|
+
var menuService = new MenuService();
|
|
2227
|
+
var readStaticStore = async () => {
|
|
2228
|
+
return {};
|
|
2229
|
+
};
|
|
2230
|
+
|
|
2231
|
+
// src/services/store-service.ts
|
|
2232
|
+
function symbolFor(code) {
|
|
2233
|
+
try {
|
|
2234
|
+
const part = new Intl.NumberFormat("en", { style: "currency", currency: code }).formatToParts(0).find((p) => p.type === "currency");
|
|
2235
|
+
return part?.value ?? code;
|
|
2236
|
+
} catch {
|
|
2237
|
+
return code;
|
|
2043
2238
|
}
|
|
2044
|
-
|
|
2045
|
-
|
|
2239
|
+
}
|
|
2240
|
+
var StoreService = class extends BaseService {
|
|
2241
|
+
facts = new StoreFacts(this._fetch);
|
|
2242
|
+
async getStoreByIdOrDomain(_args = {}) {
|
|
2243
|
+
const base = await readStaticStore();
|
|
2244
|
+
const live = await this.live().catch(() => ({}));
|
|
2245
|
+
return { ...base, ...live, id: base.id || "gocommerce" };
|
|
2046
2246
|
}
|
|
2047
|
-
async
|
|
2048
|
-
|
|
2247
|
+
async getStore(storeId) {
|
|
2248
|
+
return this.getStoreByIdOrDomain({ storeId });
|
|
2049
2249
|
}
|
|
2050
|
-
|
|
2051
|
-
|
|
2250
|
+
/**
|
|
2251
|
+
* The storefront's sitemap route asks for `/api/stores/<id>` and serves the
|
|
2252
|
+
* `sitemap` path it gets back from `PUBLIC_SITEMAP_URL`. With ext/sitemaps
|
|
2253
|
+
* installed, `/sitemaps/sitemap.xml` under `PUBLIC_SITEMAP_URL=<engine>/x`
|
|
2254
|
+
* is the engine's own sitemap; without it, an empty path is the route's
|
|
2255
|
+
* clean 404 rather than a crash.
|
|
2256
|
+
*/
|
|
2257
|
+
async get(path) {
|
|
2258
|
+
if (path.split("?")[0].startsWith("/api/stores/")) {
|
|
2259
|
+
const on = await this.facts.pluginOn("sitemap");
|
|
2260
|
+
return { sitemap: on ? "/sitemaps/sitemap.xml" : "" };
|
|
2261
|
+
}
|
|
2262
|
+
return super.get(path);
|
|
2052
2263
|
}
|
|
2053
|
-
async
|
|
2054
|
-
|
|
2264
|
+
async live() {
|
|
2265
|
+
const [ready, plugins, menus, base] = await Promise.all([
|
|
2266
|
+
this.facts.ready(),
|
|
2267
|
+
this.facts.plugins().catch(() => /* @__PURE__ */ new Map()),
|
|
2268
|
+
new MenuService(this._fetch).engineMenus(),
|
|
2269
|
+
readStaticStore()
|
|
2270
|
+
]);
|
|
2271
|
+
const code = ready.currency;
|
|
2272
|
+
const sameCurrency = (base.currency?.code ?? base.currencyCode) === code;
|
|
2273
|
+
const flag = (on) => ({ ...on ? { active: true } : { active: false } });
|
|
2274
|
+
const basePlugins = base.plugins ?? {};
|
|
2275
|
+
return {
|
|
2276
|
+
currencyCode: code,
|
|
2277
|
+
currencySymbol: sameCurrency ? base.currencySymbol ?? symbolFor(code) : symbolFor(code),
|
|
2278
|
+
currency: {
|
|
2279
|
+
...base.currency ?? {},
|
|
2280
|
+
code,
|
|
2281
|
+
symbol: sameCurrency ? base.currency?.symbol ?? symbolFor(code) : symbolFor(code)
|
|
2282
|
+
},
|
|
2283
|
+
language: ready.language,
|
|
2284
|
+
plugins: {
|
|
2285
|
+
...basePlugins,
|
|
2286
|
+
// Features this connector serves from a module: on exactly when the
|
|
2287
|
+
// module is installed and switched on, whatever the static record says.
|
|
2288
|
+
isWishlist: { ...basePlugins.isWishlist, ...flag(plugins.has("wishlist")) },
|
|
2289
|
+
isProductReviewsAndRatings: {
|
|
2290
|
+
...basePlugins.isProductReviewsAndRatings,
|
|
2291
|
+
...flag(plugins.has("product-reviews"))
|
|
2292
|
+
}
|
|
2293
|
+
},
|
|
2294
|
+
...menus?.length ? { menu: menus } : {}
|
|
2295
|
+
};
|
|
2055
2296
|
}
|
|
2056
|
-
|
|
2057
|
-
|
|
2297
|
+
};
|
|
2298
|
+
var storeService = new StoreService();
|
|
2299
|
+
|
|
2300
|
+
// src/services/page-service.ts
|
|
2301
|
+
var PageService = class extends BaseService {
|
|
2302
|
+
async getOne(slug) {
|
|
2303
|
+
return toCmsPage(await this.data(`/x/cms/pages/${encodeURIComponent(String(slug))}`));
|
|
2304
|
+
}
|
|
2305
|
+
async list({ page = 1, limit = 50 } = {}) {
|
|
2306
|
+
const env = await this.engine("/x/cms/pages", { query: { page, limit } });
|
|
2307
|
+
return toPage(env, toCmsPage);
|
|
2308
|
+
}
|
|
2309
|
+
};
|
|
2310
|
+
var FaqService = class extends BaseService {
|
|
2311
|
+
async listFaqs(_args = {}) {
|
|
2312
|
+
const faq = await this.data("/x/faq");
|
|
2313
|
+
const data = (faq.sections ?? []).flatMap(
|
|
2314
|
+
(s) => (s.entries ?? []).map((e) => ({
|
|
2315
|
+
id: String(e.id),
|
|
2316
|
+
question: e.question,
|
|
2317
|
+
answer: e.answer,
|
|
2318
|
+
category: s.section || null
|
|
2319
|
+
}))
|
|
2320
|
+
);
|
|
2321
|
+
return { data, count: data.length, heading: faq.heading, blurb: faq.blurb };
|
|
2058
2322
|
}
|
|
2059
|
-
async
|
|
2060
|
-
return
|
|
2323
|
+
async list(args = {}) {
|
|
2324
|
+
return this.listFaqs(args);
|
|
2061
2325
|
}
|
|
2062
|
-
|
|
2063
|
-
|
|
2326
|
+
};
|
|
2327
|
+
var pageService = new PageService();
|
|
2328
|
+
var faqService = new FaqService();
|
|
2329
|
+
|
|
2330
|
+
// src/services/vendor-service.ts
|
|
2331
|
+
var VendorService = class extends BaseService {
|
|
2332
|
+
async list({
|
|
2333
|
+
page = 1,
|
|
2334
|
+
limit = 24,
|
|
2335
|
+
q,
|
|
2336
|
+
search
|
|
2337
|
+
} = {}) {
|
|
2338
|
+
const env = await this.engine("/api/vendors", { query: { page, limit, q: q ?? search } });
|
|
2339
|
+
return toPage(env, toVendor);
|
|
2340
|
+
}
|
|
2341
|
+
async getVendor(slug) {
|
|
2342
|
+
return toVendor(await this.data(`/api/vendors/${encodeURIComponent(String(slug))}`));
|
|
2064
2343
|
}
|
|
2065
2344
|
/**
|
|
2066
|
-
*
|
|
2067
|
-
*
|
|
2068
|
-
*
|
|
2069
|
-
* is a trap. The shared user store decides who is signed in by reading the `connect.sid` and `me`
|
|
2070
|
-
* cookies straight from `document.cookie`, not by asking a service. A pair left behind by running
|
|
2071
|
-
* this storefront against a backend that does have accounts therefore makes GoCommerce look
|
|
2072
|
-
* signed-in, which sends the checkout down the saved-address path instead of the guest one. The
|
|
2073
|
-
* checkout page already knows to call `logout()` and retry when that happens — so this has to
|
|
2074
|
-
* actually clear them, or that recovery does nothing.
|
|
2345
|
+
* A seller's shelf. The engine's vendors sell through offers on the shop's
|
|
2346
|
+
* own variants and the public API lists no products by seller, so the shelf
|
|
2347
|
+
* is empty — the seller's page still renders, with their details.
|
|
2075
2348
|
*/
|
|
2076
|
-
async
|
|
2077
|
-
|
|
2078
|
-
return { success: true };
|
|
2349
|
+
async fetchProductsOfVendor(_vendorId) {
|
|
2350
|
+
return emptyPage();
|
|
2079
2351
|
}
|
|
2080
2352
|
};
|
|
2081
|
-
var
|
|
2082
|
-
|
|
2083
|
-
|
|
2084
|
-
|
|
2085
|
-
|
|
2086
|
-
|
|
2087
|
-
|
|
2088
|
-
|
|
2353
|
+
var vendorService = new VendorService();
|
|
2354
|
+
|
|
2355
|
+
// src/services/misc-services.ts
|
|
2356
|
+
var refuse = (service, method, why) => new NotSupportedError(service, method, why);
|
|
2357
|
+
var ContactService = class extends BaseService {
|
|
2358
|
+
async submitContactUsForm({
|
|
2359
|
+
name,
|
|
2360
|
+
email,
|
|
2361
|
+
phone,
|
|
2362
|
+
message,
|
|
2363
|
+
subject
|
|
2364
|
+
}) {
|
|
2365
|
+
return this.data("/x/contact/messages", {
|
|
2366
|
+
method: "POST",
|
|
2367
|
+
body: {
|
|
2368
|
+
name: String(name ?? ""),
|
|
2369
|
+
email: String(email ?? ""),
|
|
2370
|
+
...phone ? { phone: String(phone) } : {},
|
|
2371
|
+
...subject ? { subject: String(subject) } : {},
|
|
2372
|
+
body: String(message ?? "")
|
|
2373
|
+
}
|
|
2374
|
+
});
|
|
2089
2375
|
}
|
|
2090
2376
|
};
|
|
2091
|
-
var
|
|
2092
|
-
|
|
2093
|
-
|
|
2094
|
-
|
|
2095
|
-
|
|
2096
|
-
|
|
2097
|
-
|
|
2098
|
-
|
|
2377
|
+
var EnquiryService = class extends ContactService {
|
|
2378
|
+
async create({
|
|
2379
|
+
name,
|
|
2380
|
+
email,
|
|
2381
|
+
phone,
|
|
2382
|
+
message,
|
|
2383
|
+
productId
|
|
2384
|
+
}) {
|
|
2385
|
+
return this.submitContactUsForm({
|
|
2386
|
+
name,
|
|
2387
|
+
email,
|
|
2388
|
+
phone,
|
|
2389
|
+
subject: productId ? `Enquiry about product ${productId}` : "Enquiry",
|
|
2390
|
+
message
|
|
2391
|
+
});
|
|
2099
2392
|
}
|
|
2100
2393
|
};
|
|
2101
|
-
var
|
|
2102
|
-
|
|
2103
|
-
|
|
2104
|
-
|
|
2105
|
-
|
|
2106
|
-
const page = Math.max(1, Number(params.page || 1) || 1);
|
|
2107
|
-
const start = (page - 1) * PAGE_SIZE;
|
|
2108
|
-
return paginated(addresses.slice(start, start + PAGE_SIZE), addresses.length, page);
|
|
2109
|
-
}
|
|
2110
|
-
async fetchAddress(id) {
|
|
2111
|
-
const address = findAddress(id);
|
|
2112
|
-
if (!address) throw new Error("That address is no longer saved on this device.");
|
|
2113
|
-
return address;
|
|
2114
|
-
}
|
|
2115
|
-
async saveAddress(address) {
|
|
2116
|
-
return putAddress(address);
|
|
2117
|
-
}
|
|
2118
|
-
async editAddress(id, address) {
|
|
2119
|
-
const saved = patchAddress(id, address);
|
|
2120
|
-
if (!saved) throw new Error("That address is no longer saved on this device.");
|
|
2121
|
-
return saved;
|
|
2122
|
-
}
|
|
2123
|
-
async deleteAddress(id) {
|
|
2124
|
-
removeAddress(id);
|
|
2394
|
+
var PluginService = class extends BaseService {
|
|
2395
|
+
facts = new StoreFacts(this._fetch);
|
|
2396
|
+
async list(_args = {}) {
|
|
2397
|
+
const data = [...(await this.facts.plugins()).values()];
|
|
2398
|
+
return { data, count: data.length, pageSize: data.length, noOfPage: 1, page: 1 };
|
|
2125
2399
|
}
|
|
2126
2400
|
};
|
|
2127
|
-
var
|
|
2128
|
-
|
|
2129
|
-
|
|
2130
|
-
async fetchWishlist(_params = {}) {
|
|
2131
|
-
return emptyPage();
|
|
2132
|
-
}
|
|
2133
|
-
async checkWishlist(_params = {}) {
|
|
2134
|
-
return { data: false };
|
|
2135
|
-
}
|
|
2136
|
-
/** The product grid asks about many ids at once; nothing is on a list that cannot exist. */
|
|
2137
|
-
async checkWishlistInBulk(_ids) {
|
|
2138
|
-
return { data: [] };
|
|
2401
|
+
var SettingService = class extends BaseService {
|
|
2402
|
+
async fetchSettings(_args = {}) {
|
|
2403
|
+
return new StoreService(this._fetch).getStoreByIdOrDomain();
|
|
2139
2404
|
}
|
|
2140
|
-
async
|
|
2141
|
-
|
|
2405
|
+
async list(args = {}) {
|
|
2406
|
+
return this.fetchSettings(args);
|
|
2142
2407
|
}
|
|
2143
2408
|
};
|
|
2144
|
-
var
|
|
2145
|
-
|
|
2146
|
-
|
|
2147
|
-
|
|
2148
|
-
async listCoupons(_params = {}) {
|
|
2149
|
-
return emptyPage();
|
|
2150
|
-
}
|
|
2151
|
-
async searchCoupons(_params = {}) {
|
|
2152
|
-
return emptyPage();
|
|
2409
|
+
var InitService = class extends SettingService {
|
|
2410
|
+
async fetchInit(_args = {}) {
|
|
2411
|
+
const store = await this.fetchSettings();
|
|
2412
|
+
return { storeOne: store, store, settings: store };
|
|
2153
2413
|
}
|
|
2154
|
-
|
|
2155
|
-
|
|
2414
|
+
};
|
|
2415
|
+
var HomeService = class extends BaseService {
|
|
2416
|
+
/** A homepage is assembled by the storefront from shelves; the engine has no page of its own for it. */
|
|
2417
|
+
async getHome(_args = {}) {
|
|
2418
|
+
return { banners: [], groupByBanner: [], categories: [], products: [] };
|
|
2156
2419
|
}
|
|
2157
|
-
|
|
2158
|
-
|
|
2420
|
+
};
|
|
2421
|
+
var CountryService = class extends BaseService {
|
|
2422
|
+
async list(_args = {}) {
|
|
2423
|
+
return resolveRestLocally("get", "/api/countries");
|
|
2159
2424
|
}
|
|
2160
|
-
|
|
2161
|
-
|
|
2425
|
+
};
|
|
2426
|
+
var CurrencyService = class extends BaseService {
|
|
2427
|
+
facts = new StoreFacts(this._fetch);
|
|
2428
|
+
async listCurrencies(_args = {}) {
|
|
2429
|
+
const { currency } = await this.facts.ready();
|
|
2430
|
+
const data = [{ code: currency, name: currency, isDefault: true }];
|
|
2431
|
+
return { data, count: 1, pageSize: 1, noOfPage: 1, page: 1 };
|
|
2162
2432
|
}
|
|
2163
|
-
async
|
|
2164
|
-
|
|
2433
|
+
async list(args = {}) {
|
|
2434
|
+
return this.listCurrencies(args);
|
|
2165
2435
|
}
|
|
2166
2436
|
};
|
|
2167
|
-
var
|
|
2168
|
-
|
|
2169
|
-
static getInstance = singleton(_DealService);
|
|
2170
|
-
async fetchDeals() {
|
|
2437
|
+
var StateService = class extends BaseService {
|
|
2438
|
+
async list(_args = {}) {
|
|
2171
2439
|
return emptyPage();
|
|
2172
2440
|
}
|
|
2173
2441
|
};
|
|
2174
|
-
var
|
|
2175
|
-
|
|
2176
|
-
static getInstance = singleton(_ReviewService);
|
|
2177
|
-
async fetchReviews(_params = {}) {
|
|
2178
|
-
return emptyPage();
|
|
2179
|
-
}
|
|
2180
|
-
async allReviews(_params = {}) {
|
|
2181
|
-
return emptyPage();
|
|
2182
|
-
}
|
|
2183
|
-
async fetchProducrReviews(_productId) {
|
|
2442
|
+
var RegionService = class extends BaseService {
|
|
2443
|
+
async list(_args = {}) {
|
|
2184
2444
|
return emptyPage();
|
|
2185
2445
|
}
|
|
2186
|
-
async saveReview(_review) {
|
|
2187
|
-
throw unavailable("Product reviews");
|
|
2188
|
-
}
|
|
2189
2446
|
};
|
|
2190
|
-
var
|
|
2191
|
-
|
|
2192
|
-
|
|
2193
|
-
async list(_params = {}) {
|
|
2194
|
-
return emptyPage();
|
|
2447
|
+
var AutocompleteService = class extends MeilisearchService {
|
|
2448
|
+
async list({ q, search } = {}) {
|
|
2449
|
+
return this.searchAutoComplete({ query: q ?? search });
|
|
2195
2450
|
}
|
|
2196
|
-
|
|
2451
|
+
};
|
|
2452
|
+
var PopularSearchService = class extends BaseService {
|
|
2453
|
+
async list(_args = {}) {
|
|
2197
2454
|
return emptyPage();
|
|
2198
2455
|
}
|
|
2199
|
-
|
|
2200
|
-
|
|
2201
|
-
|
|
2202
|
-
|
|
2203
|
-
* request for something that was never required.
|
|
2204
|
-
*/
|
|
2205
|
-
async getOne(_id) {
|
|
2206
|
-
return {};
|
|
2456
|
+
};
|
|
2457
|
+
var PopularityService = class extends BaseService {
|
|
2458
|
+
async updatePopularity(_args = {}) {
|
|
2459
|
+
return void 0;
|
|
2207
2460
|
}
|
|
2208
2461
|
};
|
|
2209
|
-
var
|
|
2210
|
-
|
|
2211
|
-
static getInstance = singleton(_BlogService);
|
|
2212
|
-
async list(_params = {}) {
|
|
2462
|
+
var BlogService = class extends BaseService {
|
|
2463
|
+
async list(_args = {}) {
|
|
2213
2464
|
return emptyPage();
|
|
2214
2465
|
}
|
|
2215
|
-
async getOne(
|
|
2216
|
-
throw
|
|
2466
|
+
async getOne(_slug) {
|
|
2467
|
+
throw refuse("BlogService", "getOne", "the engine has no blog; publish articles as pages");
|
|
2217
2468
|
}
|
|
2218
2469
|
};
|
|
2219
|
-
var
|
|
2220
|
-
|
|
2221
|
-
static getInstance = singleton(_BannerService);
|
|
2222
|
-
async list() {
|
|
2470
|
+
var BannerService = class extends BaseService {
|
|
2471
|
+
async list(_args = {}) {
|
|
2223
2472
|
return emptyPage();
|
|
2224
2473
|
}
|
|
2225
|
-
async
|
|
2226
|
-
return
|
|
2474
|
+
async listBanners(args = {}) {
|
|
2475
|
+
return this.list(args);
|
|
2227
2476
|
}
|
|
2228
|
-
}
|
|
2229
|
-
|
|
2230
|
-
var GalleryService = class _GalleryService extends BaseService {
|
|
2231
|
-
static getInstance = singleton(_GalleryService);
|
|
2232
|
-
async fetchGallery() {
|
|
2233
|
-
return [];
|
|
2477
|
+
async fetchBanners(args = {}) {
|
|
2478
|
+
return this.list(args);
|
|
2234
2479
|
}
|
|
2235
2480
|
};
|
|
2236
|
-
var
|
|
2237
|
-
|
|
2238
|
-
static getInstance = singleton(_ReelsService);
|
|
2239
|
-
async list() {
|
|
2481
|
+
var ReelsService = class extends BaseService {
|
|
2482
|
+
async list(_args = {}) {
|
|
2240
2483
|
return emptyPage();
|
|
2241
2484
|
}
|
|
2242
2485
|
};
|
|
2243
|
-
var
|
|
2244
|
-
|
|
2245
|
-
static getInstance = singleton(_FaqService);
|
|
2246
|
-
async listFaqs(_params = {}) {
|
|
2486
|
+
var DealService = class extends BaseService {
|
|
2487
|
+
async fetchDeals(_args = {}) {
|
|
2247
2488
|
return emptyPage();
|
|
2248
2489
|
}
|
|
2249
2490
|
};
|
|
2250
|
-
var
|
|
2251
|
-
|
|
2252
|
-
static getInstance = singleton(_FeedbackService);
|
|
2253
|
-
async listFeedbacks(_params = {}) {
|
|
2491
|
+
var GalleryService = class extends BaseService {
|
|
2492
|
+
async list(_args = {}) {
|
|
2254
2493
|
return emptyPage();
|
|
2255
2494
|
}
|
|
2256
2495
|
};
|
|
2257
|
-
var
|
|
2258
|
-
|
|
2259
|
-
|
|
2260
|
-
async submitContactUsForm(_params) {
|
|
2261
|
-
throw unavailable("The contact form");
|
|
2262
|
-
}
|
|
2263
|
-
};
|
|
2264
|
-
var contactService = ContactService.getInstance();
|
|
2265
|
-
var EnquiryService = class _EnquiryService extends BaseService {
|
|
2266
|
-
static getInstance = singleton(_EnquiryService);
|
|
2267
|
-
async create(_params) {
|
|
2268
|
-
throw unavailable("Product enquiries");
|
|
2269
|
-
}
|
|
2270
|
-
};
|
|
2271
|
-
var enquiryService = EnquiryService.getInstance();
|
|
2272
|
-
var ChatService = class _ChatService extends BaseService {
|
|
2273
|
-
static getInstance = singleton(_ChatService);
|
|
2274
|
-
async list() {
|
|
2275
|
-
return [];
|
|
2496
|
+
var ChatService = class extends BaseService {
|
|
2497
|
+
async list(_args = {}) {
|
|
2498
|
+
return emptyPage();
|
|
2276
2499
|
}
|
|
2277
2500
|
async chats() {
|
|
2278
|
-
|
|
2501
|
+
throw refuse("ChatService", "chats", "the engine has no shopper chat");
|
|
2279
2502
|
}
|
|
2280
|
-
async save(
|
|
2281
|
-
throw
|
|
2503
|
+
async save() {
|
|
2504
|
+
throw refuse("ChatService", "save", "the engine has no shopper chat");
|
|
2282
2505
|
}
|
|
2283
2506
|
};
|
|
2284
|
-
var
|
|
2285
|
-
|
|
2286
|
-
|
|
2287
|
-
// Media in GoCommerce is an operator's, uploaded through the admin API. A storefront holds no
|
|
2288
|
-
// admin credential and must not act as though it does.
|
|
2289
|
-
async uploadToS3(_params) {
|
|
2290
|
-
throw unavailable("File uploads");
|
|
2291
|
-
}
|
|
2292
|
-
async uploadMultipleToS3(_params) {
|
|
2293
|
-
throw unavailable("File uploads");
|
|
2294
|
-
}
|
|
2295
|
-
async deleteFromS3(_params) {
|
|
2296
|
-
throw unavailable("File uploads");
|
|
2507
|
+
var FeedbackService = class extends BaseService {
|
|
2508
|
+
async save() {
|
|
2509
|
+
throw refuse("FeedbackService", "save", "use the contact form");
|
|
2297
2510
|
}
|
|
2298
2511
|
};
|
|
2299
|
-
var
|
|
2300
|
-
|
|
2301
|
-
|
|
2302
|
-
async list(_params = {}) {
|
|
2303
|
-
return emptyPage();
|
|
2304
|
-
}
|
|
2305
|
-
async getVendor(_id) {
|
|
2306
|
-
throw unavailable("Vendor pages");
|
|
2307
|
-
}
|
|
2308
|
-
async fetchMyVendorDetails() {
|
|
2309
|
-
throw unavailable("Vendor accounts");
|
|
2310
|
-
}
|
|
2311
|
-
async fetchDashboard() {
|
|
2312
|
-
throw unavailable("Vendor accounts");
|
|
2313
|
-
}
|
|
2314
|
-
async fetchProductsOfVendor(_vendorId) {
|
|
2315
|
-
return [];
|
|
2316
|
-
}
|
|
2317
|
-
async getAllVendorRatings(_vendorId) {
|
|
2318
|
-
return [];
|
|
2512
|
+
var DemoRequestService = class extends BaseService {
|
|
2513
|
+
async save() {
|
|
2514
|
+
throw refuse("DemoRequestService", "save", "use the contact form");
|
|
2319
2515
|
}
|
|
2320
|
-
|
|
2321
|
-
|
|
2516
|
+
};
|
|
2517
|
+
var UploadService = class extends BaseService {
|
|
2518
|
+
async uploadMultipleToS3() {
|
|
2519
|
+
throw refuse("UploadService", "uploadMultipleToS3", "shoppers cannot upload files to the engine");
|
|
2322
2520
|
}
|
|
2323
|
-
async
|
|
2324
|
-
throw
|
|
2521
|
+
async upload() {
|
|
2522
|
+
throw refuse("UploadService", "upload", "shoppers cannot upload files to the engine");
|
|
2325
2523
|
}
|
|
2326
2524
|
};
|
|
2327
|
-
var
|
|
2328
|
-
|
|
2329
|
-
|
|
2330
|
-
async submitForm(_formDetails) {
|
|
2331
|
-
throw unavailable("Custom design requests");
|
|
2525
|
+
var WarrantyService = class extends BaseService {
|
|
2526
|
+
async submitWarrantyRegistration() {
|
|
2527
|
+
throw refuse("WarrantyService", "submitWarrantyRegistration", "the engine has no warranty registrations");
|
|
2332
2528
|
}
|
|
2333
2529
|
};
|
|
2334
|
-
var
|
|
2335
|
-
|
|
2336
|
-
|
|
2337
|
-
async checkForCombinationWith(_args) {
|
|
2338
|
-
return { data: [], count: 0, pageSize: PAGE_SIZE, noOfPage: 0, page: 1 };
|
|
2339
|
-
}
|
|
2340
|
-
async createCustomOrderChat(_productId) {
|
|
2341
|
-
throw unavailable("Custom product chat");
|
|
2530
|
+
var VarniCustomDesignService = class extends BaseService {
|
|
2531
|
+
async submitForm() {
|
|
2532
|
+
throw refuse("VarniCustomDesignService", "submitForm", "custom design requests are a Litekart feature");
|
|
2342
2533
|
}
|
|
2343
|
-
|
|
2344
|
-
|
|
2534
|
+
};
|
|
2535
|
+
var VarniCustomProductService = class extends BaseService {
|
|
2536
|
+
async list(_args = {}) {
|
|
2537
|
+
return emptyPage();
|
|
2345
2538
|
}
|
|
2346
2539
|
};
|
|
2347
|
-
var
|
|
2540
|
+
var staticStore = () => readStaticStore();
|
|
2541
|
+
var contactService = new ContactService();
|
|
2542
|
+
var enquiryService = new EnquiryService();
|
|
2543
|
+
var pluginService = new PluginService();
|
|
2544
|
+
var settingService = new SettingService();
|
|
2545
|
+
var initService = new InitService();
|
|
2546
|
+
var homeService = new HomeService();
|
|
2547
|
+
var countryService = new CountryService();
|
|
2548
|
+
var currencyService = new CurrencyService();
|
|
2549
|
+
var stateService = new StateService();
|
|
2550
|
+
var regionService = new RegionService();
|
|
2551
|
+
var autocompleteService = new AutocompleteService();
|
|
2552
|
+
var popularSearchService = new PopularSearchService();
|
|
2553
|
+
var popularityService = new PopularityService();
|
|
2554
|
+
var blogService = new BlogService();
|
|
2555
|
+
var bannerService = new BannerService();
|
|
2556
|
+
var reelsService = new ReelsService();
|
|
2557
|
+
var dealService = new DealService();
|
|
2558
|
+
var galleryService = new GalleryService();
|
|
2559
|
+
var chatService = new ChatService();
|
|
2560
|
+
var feedbackService = new FeedbackService();
|
|
2561
|
+
var demoRequestService = new DemoRequestService();
|
|
2562
|
+
var uploadService = new UploadService();
|
|
2563
|
+
var warrantyService = new WarrantyService();
|
|
2564
|
+
var varniCustomDesignService = new VarniCustomDesignService();
|
|
2565
|
+
var varniCustomProductService = new VarniCustomProductService();
|
|
2566
|
+
var pluginsService = pluginService;
|
|
2567
|
+
var settingsService = settingService;
|
|
2348
2568
|
|
|
2349
|
-
exports.API_PROXY_PREFIX = API_PROXY_PREFIX;
|
|
2350
2569
|
exports.AddressService = AddressService;
|
|
2351
2570
|
exports.AuthService = AuthService;
|
|
2352
2571
|
exports.AutocompleteService = AutocompleteService;
|
|
@@ -2354,26 +2573,26 @@ exports.BannerService = BannerService;
|
|
|
2354
2573
|
exports.BaseService = BaseService;
|
|
2355
2574
|
exports.BlogService = BlogService;
|
|
2356
2575
|
exports.CartService = CartService;
|
|
2576
|
+
exports.CatalogService = CatalogService;
|
|
2357
2577
|
exports.CategoryService = CategoryService;
|
|
2358
2578
|
exports.ChatService = ChatService;
|
|
2359
2579
|
exports.CheckoutService = CheckoutService;
|
|
2360
2580
|
exports.CollectionService = CollectionService;
|
|
2361
2581
|
exports.ContactService = ContactService;
|
|
2582
|
+
exports.CountryService = CountryService;
|
|
2362
2583
|
exports.CouponService = CouponService;
|
|
2363
2584
|
exports.CurrencyService = CurrencyService;
|
|
2364
2585
|
exports.DealService = DealService;
|
|
2586
|
+
exports.DemoRequestService = DemoRequestService;
|
|
2365
2587
|
exports.EnquiryService = EnquiryService;
|
|
2366
2588
|
exports.FaqService = FaqService;
|
|
2367
2589
|
exports.FeedbackService = FeedbackService;
|
|
2368
2590
|
exports.GalleryService = GalleryService;
|
|
2369
|
-
exports.GoCommerceError = GoCommerceError;
|
|
2370
2591
|
exports.HomeService = HomeService;
|
|
2371
2592
|
exports.InitService = InitService;
|
|
2372
|
-
exports.MAX_LIMIT = MAX_LIMIT;
|
|
2373
2593
|
exports.MeilisearchService = MeilisearchService;
|
|
2374
2594
|
exports.MenuService = MenuService;
|
|
2375
2595
|
exports.OrderService = OrderService;
|
|
2376
|
-
exports.PAGE_SIZE = PAGE_SIZE;
|
|
2377
2596
|
exports.PageService = PageService;
|
|
2378
2597
|
exports.PaymentMethodService = PaymentMethodService;
|
|
2379
2598
|
exports.PluginService = PluginService;
|
|
@@ -2395,8 +2614,8 @@ exports.UserService = UserService;
|
|
|
2395
2614
|
exports.VarniCustomDesignService = VarniCustomDesignService;
|
|
2396
2615
|
exports.VarniCustomProductService = VarniCustomProductService;
|
|
2397
2616
|
exports.VendorService = VendorService;
|
|
2617
|
+
exports.WarrantyService = WarrantyService;
|
|
2398
2618
|
exports.WishlistService = WishlistService;
|
|
2399
|
-
exports.absoluteMedia = absoluteMedia;
|
|
2400
2619
|
exports.addressService = addressService;
|
|
2401
2620
|
exports.authService = authService;
|
|
2402
2621
|
exports.autocompleteService = autocompleteService;
|
|
@@ -2406,72 +2625,48 @@ exports.cartService = cartService;
|
|
|
2406
2625
|
exports.categoryService = categoryService;
|
|
2407
2626
|
exports.chatService = chatService;
|
|
2408
2627
|
exports.checkoutService = checkoutService;
|
|
2409
|
-
exports.clearCheckoutDetails = clearCheckoutDetails;
|
|
2410
|
-
exports.clearPhantomSession = clearPhantomSession;
|
|
2411
2628
|
exports.collectionService = collectionService;
|
|
2412
2629
|
exports.contactService = contactService;
|
|
2630
|
+
exports.countryService = countryService;
|
|
2413
2631
|
exports.couponService = couponService;
|
|
2414
|
-
exports.currencyFractionDigits = currencyFractionDigits;
|
|
2415
2632
|
exports.currencyService = currencyService;
|
|
2416
2633
|
exports.dealService = dealService;
|
|
2634
|
+
exports.demoRequestService = demoRequestService;
|
|
2417
2635
|
exports.emptyPage = emptyPage;
|
|
2418
2636
|
exports.enquiryService = enquiryService;
|
|
2419
2637
|
exports.faqService = faqService;
|
|
2420
2638
|
exports.feedbackService = feedbackService;
|
|
2421
|
-
exports.findAddress = findAddress;
|
|
2422
|
-
exports.flattenMetadata = flattenMetadata;
|
|
2423
|
-
exports.fromMoney = fromMoney;
|
|
2424
2639
|
exports.galleryService = galleryService;
|
|
2425
|
-
exports.hasPhantomSession = hasPhantomSession;
|
|
2426
|
-
exports.hasStaticStore = hasStaticStore;
|
|
2427
2640
|
exports.homeService = homeService;
|
|
2428
2641
|
exports.initService = initService;
|
|
2429
|
-
exports.listAddresses = listAddresses;
|
|
2430
|
-
exports.mapCart = mapCart;
|
|
2431
|
-
exports.mapCategory = mapCategory;
|
|
2432
|
-
exports.mapCollection = mapCollection;
|
|
2433
|
-
exports.mapOrder = mapOrder;
|
|
2434
|
-
exports.mapProduct = mapProduct;
|
|
2435
2642
|
exports.meilisearchService = meilisearchService;
|
|
2436
2643
|
exports.menuService = menuService;
|
|
2437
2644
|
exports.orderService = orderService;
|
|
2438
2645
|
exports.pageService = pageService;
|
|
2439
|
-
exports.paginated = paginated;
|
|
2440
|
-
exports.patchAddress = patchAddress;
|
|
2441
2646
|
exports.paymentMethodService = paymentMethodService;
|
|
2442
2647
|
exports.pluginService = pluginService;
|
|
2443
2648
|
exports.pluginsService = pluginsService;
|
|
2444
2649
|
exports.popularSearchService = popularSearchService;
|
|
2445
2650
|
exports.popularityService = popularityService;
|
|
2446
|
-
exports.productImages = productImages;
|
|
2447
2651
|
exports.productService = productService;
|
|
2448
2652
|
exports.profileService = profileService;
|
|
2449
|
-
exports.
|
|
2450
|
-
exports.readCheckoutDetails = readCheckoutDetails;
|
|
2451
|
-
exports.readOrderNumbers = readOrderNumbers;
|
|
2452
|
-
exports.readOrderToken = readOrderToken;
|
|
2453
|
-
exports.readStaticStore = readStaticStore;
|
|
2454
|
-
exports.readStaticStoreDetails = readStaticStoreDetails;
|
|
2653
|
+
exports.qs = qs;
|
|
2455
2654
|
exports.reelsService = reelsService;
|
|
2456
2655
|
exports.regionService = regionService;
|
|
2457
|
-
exports.rememberOrderToken = rememberOrderToken;
|
|
2458
|
-
exports.removeAddress = removeAddress;
|
|
2459
|
-
exports.resolveProductIndex = resolveProductIndex;
|
|
2460
2656
|
exports.reviewService = reviewService;
|
|
2461
2657
|
exports.searchService = searchService;
|
|
2462
|
-
exports.setStaticStore = setStaticStore;
|
|
2463
2658
|
exports.settingService = settingService;
|
|
2464
2659
|
exports.settingsService = settingsService;
|
|
2465
2660
|
exports.stateService = stateService;
|
|
2661
|
+
exports.staticStore = staticStore;
|
|
2466
2662
|
exports.storeService = storeService;
|
|
2467
|
-
exports.
|
|
2468
|
-
exports.toStorefrontAddress = toStorefrontAddress;
|
|
2663
|
+
exports.toPage = toPage;
|
|
2469
2664
|
exports.uploadService = uploadService;
|
|
2470
2665
|
exports.userService = userService;
|
|
2471
2666
|
exports.varniCustomDesignService = varniCustomDesignService;
|
|
2472
2667
|
exports.varniCustomProductService = varniCustomProductService;
|
|
2473
2668
|
exports.vendorService = vendorService;
|
|
2669
|
+
exports.warrantyService = warrantyService;
|
|
2474
2670
|
exports.wishlistService = wishlistService;
|
|
2475
|
-
exports.writeCheckoutDetails = writeCheckoutDetails;
|
|
2476
2671
|
//# sourceMappingURL=index.cjs.map
|
|
2477
2672
|
//# sourceMappingURL=index.cjs.map
|