react-shopwave-connect 0.2.0 → 0.4.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 +215 -24
- package/dist/core/index.cjs +903 -88
- package/dist/core/index.cjs.map +1 -1
- package/dist/core/index.d.cts +604 -23
- package/dist/core/index.d.ts +604 -23
- package/dist/core/index.js +845 -89
- package/dist/core/index.js.map +1 -1
- package/dist/hooks/index.cjs +735 -109
- package/dist/hooks/index.cjs.map +1 -1
- package/dist/hooks/index.d.cts +263 -12
- package/dist/hooks/index.d.ts +263 -12
- package/dist/hooks/index.js +732 -111
- package/dist/hooks/index.js.map +1 -1
- package/dist/index.cjs +1087 -107
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +670 -24
- package/dist/index.d.ts +670 -24
- package/dist/index.js +1025 -109
- package/dist/index.js.map +1 -1
- package/dist/next/index.cjs +560 -2
- package/dist/next/index.cjs.map +1 -1
- package/dist/next/index.d.cts +249 -1
- package/dist/next/index.d.ts +249 -1
- package/dist/next/index.js +556 -3
- package/dist/next/index.js.map +1 -1
- package/dist/server/index.cjs +531 -1
- package/dist/server/index.cjs.map +1 -1
- package/dist/server/index.d.cts +258 -1
- package/dist/server/index.d.ts +258 -1
- package/dist/server/index.js +521 -2
- package/dist/server/index.js.map +1 -1
- package/package.json +1 -1
package/dist/core/index.cjs
CHANGED
|
@@ -1,87 +1,200 @@
|
|
|
1
1
|
|
|
2
|
+
//#region src/core/errors.ts
|
|
3
|
+
/**
|
|
4
|
+
* Thrown by every `core` function when a request fails, either at the HTTP
|
|
5
|
+
* level (`status` is the HTTP status) or because the Shopwave response carried
|
|
6
|
+
* `api.message.errors` (then `status` is the HTTP status of that response,
|
|
7
|
+
* usually 200/201, and `errors` holds the API errors).
|
|
8
|
+
*
|
|
9
|
+
* Branch on `status` (e.g. `isUnauthorized` → send the user to log in) rather
|
|
10
|
+
* than parsing `message`.
|
|
11
|
+
*/
|
|
12
|
+
var ShopwaveApiError = class extends Error {
|
|
13
|
+
/** HTTP status of the response (0 when the request never got a response). */
|
|
14
|
+
status;
|
|
15
|
+
/** Shopwave API errors, when the response carried any. */
|
|
16
|
+
errors;
|
|
17
|
+
/** Parsed response body, when there was one. */
|
|
18
|
+
body;
|
|
19
|
+
constructor(status, message, details = {}) {
|
|
20
|
+
super(message, details.cause !== void 0 ? { cause: details.cause } : void 0);
|
|
21
|
+
this.name = "ShopwaveApiError";
|
|
22
|
+
this.status = status;
|
|
23
|
+
this.errors = details.errors ?? null;
|
|
24
|
+
this.body = details.body;
|
|
25
|
+
}
|
|
26
|
+
/** 401, or the Shopwave "token expired / invalid" error 908. */
|
|
27
|
+
get isUnauthorized() {
|
|
28
|
+
if (this.status === 401) return true;
|
|
29
|
+
return !!this.errors && Object.entries(this.errors).some(([k, v]) => k === "908" || Number(v?.id) === 908);
|
|
30
|
+
}
|
|
31
|
+
get isNotFound() {
|
|
32
|
+
return this.status === 404;
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
/** The `api.message.errors` (or `api.message.error`) map of a Shopwave response, or `null` when there are none. */
|
|
36
|
+
function getApiErrorMap(body) {
|
|
37
|
+
const message = body?.api?.message;
|
|
38
|
+
const errors = message?.errors ?? message?.error;
|
|
39
|
+
if (errors && typeof errors === "object" && Object.keys(errors).length > 0) return errors;
|
|
40
|
+
return null;
|
|
41
|
+
}
|
|
42
|
+
function describeErrors(errors) {
|
|
43
|
+
return Object.entries(errors).map(([code, e]) => {
|
|
44
|
+
const text = [e?.title, e?.details].filter(Boolean).join(": ");
|
|
45
|
+
return text ? `${code} ${text}` : code;
|
|
46
|
+
}).join("; ");
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Builds a {@link ShopwaveApiError} for a response. Understands the Shopwave
|
|
50
|
+
* envelope (`api.message.errors`) and the `{ error, message }` bodies returned
|
|
51
|
+
* by the `react-shopwave-connect/next` routes.
|
|
52
|
+
*/
|
|
53
|
+
function toShopwaveApiError(status, body, fallback) {
|
|
54
|
+
const errors = getApiErrorMap(body);
|
|
55
|
+
let detail = errors ? describeErrors(errors) : "";
|
|
56
|
+
if (!detail && body && typeof body === "object") {
|
|
57
|
+
const b = body;
|
|
58
|
+
if (typeof b.message === "string") detail = b.message;
|
|
59
|
+
else if (typeof b.error === "string") detail = b.error;
|
|
60
|
+
}
|
|
61
|
+
if (!detail) detail = fallback ?? (status >= 400 ? "request failed" : "API returned errors");
|
|
62
|
+
return new ShopwaveApiError(status, `Shopwave API error (${status}): ${detail}`, {
|
|
63
|
+
errors,
|
|
64
|
+
body
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
/** Throws a {@link ShopwaveApiError} when the response body carries API errors. */
|
|
68
|
+
function assertNoApiErrors(body, status) {
|
|
69
|
+
if (getApiErrorMap(body)) throw toShopwaveApiError(status, body);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
//#endregion
|
|
2
73
|
//#region src/core/request.ts
|
|
3
74
|
function resolveFetch(options) {
|
|
4
75
|
const f = options.fetch ?? (typeof fetch !== "undefined" ? fetch : void 0);
|
|
5
76
|
if (!f) throw new Error("No fetch implementation available. Pass `options.fetch` (e.g. node-fetch / undici) when running outside the browser.");
|
|
6
77
|
return f;
|
|
7
78
|
}
|
|
8
|
-
|
|
79
|
+
/** Options with `token` filled in from a legacy per-call `params.token`, unless `options.token` is set. */
|
|
80
|
+
function withToken(options, token) {
|
|
81
|
+
return token && !options.token ? {
|
|
82
|
+
...options,
|
|
83
|
+
token
|
|
84
|
+
} : options;
|
|
85
|
+
}
|
|
86
|
+
/** `Authorization` header value for a token (`OAuth <token>` unless it already has a scheme). */
|
|
87
|
+
function authorizationFor(token) {
|
|
88
|
+
const t = token.trim();
|
|
89
|
+
return /^(oauth|bearer)\s+\S/i.test(t) ? t : `OAuth ${t}`;
|
|
90
|
+
}
|
|
91
|
+
/** Headers shared by every request: Accept + the token, when one is given. */
|
|
92
|
+
function baseHeaders(options) {
|
|
93
|
+
const headers = { Accept: "application/json" };
|
|
94
|
+
if (options.token) headers.Authorization = authorizationFor(options.token);
|
|
95
|
+
return headers;
|
|
96
|
+
}
|
|
97
|
+
function buildExtras(extras) {
|
|
9
98
|
const merged = {
|
|
10
99
|
"Content-Type": "application/json",
|
|
11
100
|
...extras
|
|
12
101
|
};
|
|
13
|
-
|
|
102
|
+
delete merged.token;
|
|
14
103
|
return merged;
|
|
15
104
|
}
|
|
105
|
+
/** Parses a response body as JSON; `null` for an empty body, `{ raw }` for non-JSON. */
|
|
106
|
+
async function readBody(response) {
|
|
107
|
+
const text = await response.text();
|
|
108
|
+
if (!text) return null;
|
|
109
|
+
try {
|
|
110
|
+
return JSON.parse(text);
|
|
111
|
+
} catch {
|
|
112
|
+
return { raw: text };
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Low-level request: resolves `{ status, body }` for 2xx responses and throws
|
|
117
|
+
* {@link ShopwaveApiError} otherwise. `init.headers` are merged over the
|
|
118
|
+
* standard ones (Accept + Authorization).
|
|
119
|
+
*/
|
|
120
|
+
async function apiRequest(path, init, options = {}) {
|
|
121
|
+
return send(path, {
|
|
122
|
+
...init,
|
|
123
|
+
headers: {
|
|
124
|
+
...baseHeaders(options),
|
|
125
|
+
...init.headers
|
|
126
|
+
}
|
|
127
|
+
}, options);
|
|
128
|
+
}
|
|
129
|
+
async function send(path, init, options) {
|
|
130
|
+
const doFetch = resolveFetch(options);
|
|
131
|
+
const url = (options.baseUrl ?? "") + path;
|
|
132
|
+
let response;
|
|
133
|
+
try {
|
|
134
|
+
response = await doFetch(url, {
|
|
135
|
+
...init,
|
|
136
|
+
signal: options.signal
|
|
137
|
+
});
|
|
138
|
+
} catch (error) {
|
|
139
|
+
if (error?.name === "AbortError") throw error;
|
|
140
|
+
throw new ShopwaveApiError(0, `Shopwave API request failed: ${error?.message ?? error}`, { cause: error });
|
|
141
|
+
}
|
|
142
|
+
const body = await readBody(response);
|
|
143
|
+
if (!response.ok) throw toShopwaveApiError(response.status, body, response.statusText || void 0);
|
|
144
|
+
return {
|
|
145
|
+
status: response.status,
|
|
146
|
+
body
|
|
147
|
+
};
|
|
148
|
+
}
|
|
16
149
|
/**
|
|
17
150
|
* Returns a JSON string of API errors if the response carries any, otherwise
|
|
18
|
-
* `null`.
|
|
151
|
+
* `null`. Kept for backwards compatibility; prefer `ShopwaveApiError`.
|
|
19
152
|
*/
|
|
20
153
|
function getApiErrors(api) {
|
|
21
|
-
const errors = api
|
|
22
|
-
|
|
23
|
-
return null;
|
|
154
|
+
const errors = getApiErrorMap({ api });
|
|
155
|
+
return errors ? JSON.stringify(errors) : null;
|
|
24
156
|
}
|
|
25
157
|
/**
|
|
26
|
-
* GET helper. Sends request metadata via the `extras` header
|
|
27
|
-
*
|
|
158
|
+
* GET helper. Sends request metadata via the `extras` header, parses JSON and
|
|
159
|
+
* returns the payload. Throws {@link ShopwaveApiError} for non-2xx responses.
|
|
28
160
|
*/
|
|
29
161
|
async function apiGet(path, extras, options = {}) {
|
|
30
|
-
const
|
|
31
|
-
const url = (options.baseUrl ?? "") + path;
|
|
32
|
-
const headers = { extras: JSON.stringify(buildExtras(extras, options)) };
|
|
33
|
-
console.log("[API GET]", {
|
|
34
|
-
url,
|
|
35
|
-
headers
|
|
36
|
-
});
|
|
37
|
-
const response = await doFetch(url, {
|
|
162
|
+
const { body } = await send(path, {
|
|
38
163
|
method: "GET",
|
|
39
|
-
headers
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
164
|
+
headers: {
|
|
165
|
+
...baseHeaders(options),
|
|
166
|
+
extras: JSON.stringify(buildExtras(extras))
|
|
167
|
+
}
|
|
168
|
+
}, options);
|
|
169
|
+
return body;
|
|
44
170
|
}
|
|
45
171
|
/**
|
|
46
|
-
* JSON body helper for POST/PUT mutations.
|
|
172
|
+
* JSON body helper for POST/PUT mutations. Returns the parsed body (`null` for
|
|
173
|
+
* an empty one). Throws {@link ShopwaveApiError} for non-2xx responses.
|
|
47
174
|
*/
|
|
48
175
|
async function apiSend(path, method, payload, options = {}) {
|
|
49
|
-
const
|
|
50
|
-
const url = (options.baseUrl ?? "") + path;
|
|
51
|
-
const headers = { "Content-Type": "application/json" };
|
|
52
|
-
if (options.token != null) headers.token = options.token;
|
|
53
|
-
console.log(`[API ${method}]`, {
|
|
54
|
-
url,
|
|
55
|
-
headers,
|
|
56
|
-
payload
|
|
57
|
-
});
|
|
58
|
-
const response = await doFetch(url, {
|
|
176
|
+
const { body } = await send(path, {
|
|
59
177
|
method,
|
|
60
|
-
headers
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
178
|
+
headers: {
|
|
179
|
+
...baseHeaders(options),
|
|
180
|
+
"Content-Type": "application/json"
|
|
181
|
+
},
|
|
182
|
+
body: JSON.stringify(payload)
|
|
183
|
+
}, options);
|
|
184
|
+
return body;
|
|
66
185
|
}
|
|
67
186
|
/**
|
|
68
|
-
* DELETE helper.
|
|
187
|
+
* DELETE helper. Shopwave answers deletes with 205 and an empty body; if a body
|
|
188
|
+
* does come back and carries API errors, they are thrown. Returns the parsed
|
|
189
|
+
* body (`null` when empty).
|
|
69
190
|
*/
|
|
70
191
|
async function apiDelete(path, options = {}) {
|
|
71
|
-
const
|
|
72
|
-
const url = (options.baseUrl ?? "") + path;
|
|
73
|
-
const headers = {};
|
|
74
|
-
if (options.token != null) headers.token = options.token;
|
|
75
|
-
console.log("[API DELETE]", {
|
|
76
|
-
url,
|
|
77
|
-
headers
|
|
78
|
-
});
|
|
79
|
-
const response = await doFetch(url, {
|
|
192
|
+
const { status, body } = await send(path, {
|
|
80
193
|
method: "DELETE",
|
|
81
|
-
headers
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
194
|
+
headers: baseHeaders(options)
|
|
195
|
+
}, options);
|
|
196
|
+
if (getApiErrorMap(body)) throw toShopwaveApiError(status, body);
|
|
197
|
+
return body;
|
|
85
198
|
}
|
|
86
199
|
|
|
87
200
|
//#endregion
|
|
@@ -93,11 +206,9 @@ async function apiDelete(path, options = {}) {
|
|
|
93
206
|
async function fetchCategories(params = {}, options = {}) {
|
|
94
207
|
const extras = { deleted: params.deleted ?? false };
|
|
95
208
|
if (params.categoryIds) extras.categoryIds = params.categoryIds;
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
if (error) throw new Error(error);
|
|
100
|
-
return Object.values(json.categories ?? {});
|
|
209
|
+
const json = await apiGet("/api/categories", extras, withToken(options, params.token));
|
|
210
|
+
assertNoApiErrors(json, 200);
|
|
211
|
+
return Object.values(json?.categories ?? {});
|
|
101
212
|
}
|
|
102
213
|
|
|
103
214
|
//#endregion
|
|
@@ -109,9 +220,8 @@ async function fetchCategories(params = {}, options = {}) {
|
|
|
109
220
|
async function fetchConsumers(consumerIds, options = {}) {
|
|
110
221
|
if (!consumerIds || consumerIds.length === 0) return [];
|
|
111
222
|
const json = await apiGet("/api/consumer", { ids: consumerIds.join(",") }, options);
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
return Object.values(json.consumers ?? {});
|
|
223
|
+
assertNoApiErrors(json, 200);
|
|
224
|
+
return Object.values(json?.consumers ?? {});
|
|
115
225
|
}
|
|
116
226
|
|
|
117
227
|
//#endregion
|
|
@@ -129,10 +239,9 @@ const rolesById = {
|
|
|
129
239
|
async function fetchEmployees(params = {}, options = {}) {
|
|
130
240
|
const extras = { deleted: params.deleted ?? false };
|
|
131
241
|
if (params.employeeIds) extras.employeeIds = params.employeeIds;
|
|
132
|
-
const json = await apiGet("/api/employees", extras, options);
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
return Object.values(json.employees ?? {});
|
|
242
|
+
const json = await apiGet("/api/employees", extras, withToken(options, params.token));
|
|
243
|
+
assertNoApiErrors(json, 200);
|
|
244
|
+
return Object.values(json?.employees ?? {});
|
|
136
245
|
}
|
|
137
246
|
|
|
138
247
|
//#endregion
|
|
@@ -144,11 +253,9 @@ async function fetchProducts(params = {}, options = {}) {
|
|
|
144
253
|
const extras = { deleted: params.deleted ?? false };
|
|
145
254
|
if (params.productIds) extras.productIds = params.productIds;
|
|
146
255
|
if (params.storeId) extras.storeId = params.storeId;
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
if (error) throw new Error(error);
|
|
151
|
-
return Object.values(json.products ?? {});
|
|
256
|
+
const json = await apiGet("/api/products", extras, withToken(options, params.token));
|
|
257
|
+
assertNoApiErrors(json, 200);
|
|
258
|
+
return Object.values(json?.products ?? {});
|
|
152
259
|
}
|
|
153
260
|
/**
|
|
154
261
|
* Fetches products by id and returns them keyed by id, transparently batching
|
|
@@ -184,11 +291,9 @@ async function fetchPromotions(params = {}, options = {}) {
|
|
|
184
291
|
if (params.imminent !== void 0) extras.imminent = params.imminent;
|
|
185
292
|
if (params.active !== void 0) extras.active = params.active;
|
|
186
293
|
if (params.expired !== void 0) extras.expired = params.expired;
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
if (error) throw new Error(error);
|
|
191
|
-
return Object.values(json.promotions ?? {});
|
|
294
|
+
const json = await apiGet("/api/promotions", extras, withToken(options, params.token));
|
|
295
|
+
assertNoApiErrors(json, 200);
|
|
296
|
+
return Object.values(json?.promotions ?? {});
|
|
192
297
|
}
|
|
193
298
|
|
|
194
299
|
//#endregion
|
|
@@ -197,10 +302,11 @@ async function fetchPromotions(params = {}, options = {}) {
|
|
|
197
302
|
* Fetches stores. Returns the flattened `Store[]`.
|
|
198
303
|
*/
|
|
199
304
|
async function fetchStores(params = {}, options = {}) {
|
|
200
|
-
const
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
305
|
+
const extras = { deleted: params.deleted ?? false };
|
|
306
|
+
if (params.storeIds) extras.storeIds = params.storeIds;
|
|
307
|
+
const json = await apiGet("/api/stores", extras, withToken(options, params.token));
|
|
308
|
+
assertNoApiErrors(json, 200);
|
|
309
|
+
return Object.values(json?.stores ?? {});
|
|
204
310
|
}
|
|
205
311
|
|
|
206
312
|
//#endregion
|
|
@@ -212,9 +318,8 @@ async function fetchStores(params = {}, options = {}) {
|
|
|
212
318
|
*/
|
|
213
319
|
async function fetchReport(query, options = {}) {
|
|
214
320
|
const json = await apiGet("/api/report", { query: JSON.stringify(query) }, options);
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
return json.reports ?? {};
|
|
321
|
+
assertNoApiErrors(json, 200);
|
|
322
|
+
return json?.reports ?? {};
|
|
218
323
|
}
|
|
219
324
|
|
|
220
325
|
//#endregion
|
|
@@ -269,10 +374,12 @@ async function logout(options = {}) {
|
|
|
269
374
|
//#endregion
|
|
270
375
|
//#region src/core/entity.ts
|
|
271
376
|
/**
|
|
272
|
-
*
|
|
273
|
-
*
|
|
274
|
-
*
|
|
275
|
-
*
|
|
377
|
+
* Low-level, untyped mutations: the caller supplies the route and payload.
|
|
378
|
+
*
|
|
379
|
+
* Prefer the typed functions in `./entities` (`saveProduct`, `deleteCategory`,
|
|
380
|
+
* …): they know each route, build the request envelope, check the response and
|
|
381
|
+
* return the saved entity with its id. Keep these for routes that have no typed
|
|
382
|
+
* function yet (e.g. `/api/merchant`).
|
|
276
383
|
*/
|
|
277
384
|
/**
|
|
278
385
|
* Deletes `/api/{resourcePath}/{entityId}`.
|
|
@@ -282,13 +389,182 @@ async function deleteEntity(resourcePath, entityId, options = {}) {
|
|
|
282
389
|
await apiDelete(`/api/${resourcePath}/${entityId}`, options);
|
|
283
390
|
}
|
|
284
391
|
/**
|
|
285
|
-
* Sends a create/update mutation
|
|
286
|
-
* (
|
|
392
|
+
* Sends a create/update mutation. Returns the response's `result` field when it
|
|
393
|
+
* has one (older app routes wrapped their answer that way), otherwise the whole
|
|
394
|
+
* parsed response body. Throws `ShopwaveApiError` on HTTP or API errors.
|
|
287
395
|
*/
|
|
288
396
|
async function submitEntity({ endpoint, method = "POST", payload }, options = {}) {
|
|
289
|
-
|
|
397
|
+
const json = await apiSend(endpoint, method, payload, options);
|
|
398
|
+
assertNoApiErrors(json, 200);
|
|
399
|
+
if (json && typeof json === "object" && "result" in json) return json.result;
|
|
400
|
+
return json ?? void 0;
|
|
290
401
|
}
|
|
291
402
|
|
|
403
|
+
//#endregion
|
|
404
|
+
//#region src/core/entities.ts
|
|
405
|
+
/**
|
|
406
|
+
* Addressing per entity, following the Shopwave API reference
|
|
407
|
+
* (https://developer.merchantstack.com/api-reference.html) and checked against
|
|
408
|
+
* the live API where noted:
|
|
409
|
+
* - category/product/store: GET filtered by `<x>Ids`, POST upsert, DELETE with `<x>Id` → 205.
|
|
410
|
+
* - promotion: no DELETE; "deleting" a promotion ends it by setting `endDate` to now.
|
|
411
|
+
* - employee: POST updates `roleId`, `joinedDate`, `exitDate` (names can't be
|
|
412
|
+
* changed); no DELETE (live API: "Cannot DELETE /employee") → retired via `exitDate`.
|
|
413
|
+
* - consumer: read-only (`GET` with `ids`, comma-separated); live POST → 404.
|
|
414
|
+
*/
|
|
415
|
+
const SHOPWAVE_ENTITIES = Object.freeze({
|
|
416
|
+
product: {
|
|
417
|
+
route: "products",
|
|
418
|
+
collection: "products",
|
|
419
|
+
upstream: "product",
|
|
420
|
+
idsHeader: "productIds",
|
|
421
|
+
idHeader: "productId",
|
|
422
|
+
writable: true,
|
|
423
|
+
deleteMode: "delete"
|
|
424
|
+
},
|
|
425
|
+
category: {
|
|
426
|
+
route: "categories",
|
|
427
|
+
collection: "categories",
|
|
428
|
+
upstream: "category",
|
|
429
|
+
idsHeader: "categoryIds",
|
|
430
|
+
idHeader: "categoryId",
|
|
431
|
+
writable: true,
|
|
432
|
+
deleteMode: "delete"
|
|
433
|
+
},
|
|
434
|
+
store: {
|
|
435
|
+
route: "stores",
|
|
436
|
+
collection: "stores",
|
|
437
|
+
upstream: "store",
|
|
438
|
+
idsHeader: "storeIds",
|
|
439
|
+
idHeader: "storeId",
|
|
440
|
+
writable: true,
|
|
441
|
+
deleteMode: "delete"
|
|
442
|
+
},
|
|
443
|
+
promotion: {
|
|
444
|
+
route: "promotions",
|
|
445
|
+
collection: "promotions",
|
|
446
|
+
upstream: "promotion",
|
|
447
|
+
idsHeader: "promotionIds",
|
|
448
|
+
idHeader: "promotionId",
|
|
449
|
+
writable: true,
|
|
450
|
+
deleteMode: "retire",
|
|
451
|
+
retireField: "endDate"
|
|
452
|
+
},
|
|
453
|
+
employee: {
|
|
454
|
+
route: "employees",
|
|
455
|
+
collection: "employees",
|
|
456
|
+
upstream: "employee",
|
|
457
|
+
idsHeader: "employeeIds",
|
|
458
|
+
idHeader: "employeeId",
|
|
459
|
+
writable: true,
|
|
460
|
+
deleteMode: "retire",
|
|
461
|
+
retireField: "exitDate"
|
|
462
|
+
},
|
|
463
|
+
consumer: {
|
|
464
|
+
route: "consumer",
|
|
465
|
+
collection: "consumers",
|
|
466
|
+
upstream: "consumer",
|
|
467
|
+
idsHeader: "ids",
|
|
468
|
+
idHeader: "consumerId",
|
|
469
|
+
writable: false,
|
|
470
|
+
deleteMode: "none"
|
|
471
|
+
}
|
|
472
|
+
});
|
|
473
|
+
function definition(kind) {
|
|
474
|
+
const def = SHOPWAVE_ENTITIES[kind];
|
|
475
|
+
if (!def) throw new Error(`Unknown Shopwave entity "${kind}"`);
|
|
476
|
+
return def;
|
|
477
|
+
}
|
|
478
|
+
function assertId(kind, id) {
|
|
479
|
+
const s = id == null ? "" : String(id).trim();
|
|
480
|
+
if (!s) throw new Error(`${kind} id is missing`);
|
|
481
|
+
return encodeURIComponent(s);
|
|
482
|
+
}
|
|
483
|
+
/**
|
|
484
|
+
* Creates or updates several entities of one kind in a single request and
|
|
485
|
+
* returns them as saved (with their ids), in the order given.
|
|
486
|
+
*
|
|
487
|
+
* The request is `{ <collection>: { "0": item0, "1": item1, … } }`. Shopwave
|
|
488
|
+
* answers 201 and echoes every entity under the ref it was sent with, so each
|
|
489
|
+
* result is matched back by ref. Throws {@link ShopwaveApiError} when the
|
|
490
|
+
* response carries `api.message.errors` or any ref is missing from it.
|
|
491
|
+
*
|
|
492
|
+
* The API's partial-success semantics for multi-entity saves haven't been
|
|
493
|
+
* confirmed yet; single saves (`saveProduct` etc.) are the tested path.
|
|
494
|
+
*/
|
|
495
|
+
async function saveEntities(kind, items, options = {}) {
|
|
496
|
+
const def = definition(kind);
|
|
497
|
+
if (items.length === 0) return [];
|
|
498
|
+
const refs = items.map((_, i) => String(i));
|
|
499
|
+
const payload = { [def.collection]: Object.fromEntries(refs.map((ref, i) => [ref, items[i]])) };
|
|
500
|
+
const { status, body: raw } = await apiRequest(`/api/${def.route}`, {
|
|
501
|
+
method: "POST",
|
|
502
|
+
headers: { "Content-Type": "application/json" },
|
|
503
|
+
body: JSON.stringify(payload)
|
|
504
|
+
}, options);
|
|
505
|
+
const body = raw;
|
|
506
|
+
assertNoApiErrors(body, status);
|
|
507
|
+
const echoed = body?.[def.collection] ?? {};
|
|
508
|
+
return refs.map((ref, i) => {
|
|
509
|
+
const saved = echoed[ref];
|
|
510
|
+
if (!saved || saved.id == null) throw new ShopwaveApiError(status, `Shopwave API error (${status}): the saved ${kind} (ref "${ref}") was not returned`, { body });
|
|
511
|
+
return {
|
|
512
|
+
...items[i],
|
|
513
|
+
...saved,
|
|
514
|
+
id: Number(saved.id)
|
|
515
|
+
};
|
|
516
|
+
});
|
|
517
|
+
}
|
|
518
|
+
/** Creates (no `id`) or updates (with `id`) one entity and returns it with its id. */
|
|
519
|
+
async function saveEntity(kind, item, options = {}) {
|
|
520
|
+
const [saved] = await saveEntities(kind, [item], options);
|
|
521
|
+
return saved;
|
|
522
|
+
}
|
|
523
|
+
/**
|
|
524
|
+
* Deletes one entity (a soft delete: it stays readable with `deleted: true`).
|
|
525
|
+
* Employees and promotions can't be deleted in Shopwave; for them the route
|
|
526
|
+
* sets `exitDate` / `endDate` to now instead (see `SHOPWAVE_ENTITIES`).
|
|
527
|
+
*
|
|
528
|
+
* Shopwave answers 205 with an empty body — also for ids that don't exist — so
|
|
529
|
+
* a resolved promise means "the API accepted the request", not "a record was
|
|
530
|
+
* deleted".
|
|
531
|
+
*/
|
|
532
|
+
async function deleteEntityById(kind, id, options = {}) {
|
|
533
|
+
await apiDelete(`/api/${definition(kind).route}/${assertId(kind, id)}`, options);
|
|
534
|
+
}
|
|
535
|
+
/** Reads one entity by id, or `null` when there's no such (non-deleted) record. */
|
|
536
|
+
async function fetchEntityById(kind, id, params = {}, options = {}) {
|
|
537
|
+
const def = definition(kind);
|
|
538
|
+
const body = await apiGet(`/api/${def.route}/${assertId(kind, id)}`, { deleted: params.deleted ?? false }, options);
|
|
539
|
+
assertNoApiErrors(body, 200);
|
|
540
|
+
const map = body?.[def.collection] ?? {};
|
|
541
|
+
return map[String(id)] ?? Object.values(map).find((e) => String(e?.id) === String(id)) ?? null;
|
|
542
|
+
}
|
|
543
|
+
const saveProduct = (product, options) => saveEntity("product", product, options);
|
|
544
|
+
const deleteProduct = (id, options) => deleteEntityById("product", id, options);
|
|
545
|
+
const fetchProduct = (id, params, options) => fetchEntityById("product", id, params, options);
|
|
546
|
+
const saveCategory = (category, options) => saveEntity("category", category, options);
|
|
547
|
+
const deleteCategory = (id, options) => deleteEntityById("category", id, options);
|
|
548
|
+
const fetchCategory = (id, params, options) => fetchEntityById("category", id, params, options);
|
|
549
|
+
const saveStore = (store, options) => saveEntity("store", store, options);
|
|
550
|
+
const deleteStore = (id, options) => deleteEntityById("store", id, options);
|
|
551
|
+
const fetchStore = (id, params, options) => fetchEntityById("store", id, params, options);
|
|
552
|
+
const savePromotion = (promotion, options) => saveEntity("promotion", promotion, options);
|
|
553
|
+
/** Ends a promotion: Shopwave has no promotion DELETE, so this sets `endDate` to now. */
|
|
554
|
+
const deletePromotion = (id, options) => deleteEntityById("promotion", id, options);
|
|
555
|
+
const fetchPromotion = (id, params, options) => fetchEntityById("promotion", id, params, options);
|
|
556
|
+
/**
|
|
557
|
+
* Creates an employee, or updates one (with `id`). On update Shopwave only
|
|
558
|
+
* applies `roleId`, `joinedDate` and `exitDate` (and store roles); names and
|
|
559
|
+
* email can't be changed, and the echo only carries the updated fields — re-read
|
|
560
|
+
* with `fetchEmployee` if you need the stored record.
|
|
561
|
+
*/
|
|
562
|
+
const saveEmployee = (employee, options) => saveEntity("employee", employee, options);
|
|
563
|
+
/** Retires an employee: Shopwave has no employee DELETE, so this sets `exitDate` to now. */
|
|
564
|
+
const deleteEmployee = (id, options) => deleteEntityById("employee", id, options);
|
|
565
|
+
const fetchEmployee = (id, params, options) => fetchEntityById("employee", id, params, options);
|
|
566
|
+
const fetchConsumer = (id, params, options) => fetchEntityById("consumer", id, params, options);
|
|
567
|
+
|
|
292
568
|
//#endregion
|
|
293
569
|
//#region src/core/basket.ts
|
|
294
570
|
const DEFAULT_BASKET_FILTERS = {
|
|
@@ -433,35 +709,574 @@ function buildConsumerMap(consumers) {
|
|
|
433
709
|
return map;
|
|
434
710
|
}
|
|
435
711
|
|
|
712
|
+
//#endregion
|
|
713
|
+
//#region src/core/resources.ts
|
|
714
|
+
/**
|
|
715
|
+
* - merchant: `GET /merchant`; `POST /merchant` with `{ merchant: { id, … } }`
|
|
716
|
+
* updates it (without an `id` the API would create a second merchant, so the
|
|
717
|
+
* route requires one).
|
|
718
|
+
* - user: `GET /user` (read-only here; the API's `POST /user` invites users and
|
|
719
|
+
* needs the admin scope).
|
|
720
|
+
*/
|
|
721
|
+
const SHOPWAVE_RESOURCES = Object.freeze({
|
|
722
|
+
merchant: {
|
|
723
|
+
route: "merchant",
|
|
724
|
+
key: "merchant",
|
|
725
|
+
upstream: "merchant",
|
|
726
|
+
writable: true
|
|
727
|
+
},
|
|
728
|
+
user: {
|
|
729
|
+
route: "user",
|
|
730
|
+
key: "user",
|
|
731
|
+
upstream: "user",
|
|
732
|
+
writable: false
|
|
733
|
+
}
|
|
734
|
+
});
|
|
735
|
+
/** `UploadKind` → the API's `contentType` value. */
|
|
736
|
+
const UPLOAD_KINDS = Object.freeze({
|
|
737
|
+
merchant: "merchant",
|
|
738
|
+
merchantFeature: "merchantFeature",
|
|
739
|
+
product: "product",
|
|
740
|
+
user: "user",
|
|
741
|
+
applicationLogo: "applicaionLogo",
|
|
742
|
+
applicationImages: "applicaionImages"
|
|
743
|
+
});
|
|
744
|
+
/** How uploads are addressed (app route and Shopwave uploader). */
|
|
745
|
+
const SHOPWAVE_UPLOAD = Object.freeze({
|
|
746
|
+
route: "upload",
|
|
747
|
+
upstream: "uploader",
|
|
748
|
+
kindHeader: "contentType",
|
|
749
|
+
fileField: "file",
|
|
750
|
+
kindField: "kind"
|
|
751
|
+
});
|
|
752
|
+
function isUploadKind(value) {
|
|
753
|
+
return typeof value === "string" && Object.prototype.hasOwnProperty.call(UPLOAD_KINDS, value);
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
//#endregion
|
|
757
|
+
//#region src/core/imageFit.ts
|
|
758
|
+
/**
|
|
759
|
+
* The centred part of a `srcWidth × srcHeight` image with the aspect ratio of
|
|
760
|
+
* `dstWidth × dstHeight` (like CSS `object-fit: cover`).
|
|
761
|
+
*/
|
|
762
|
+
function coverCrop(srcWidth, srcHeight, dstWidth, dstHeight) {
|
|
763
|
+
if (![
|
|
764
|
+
srcWidth,
|
|
765
|
+
srcHeight,
|
|
766
|
+
dstWidth,
|
|
767
|
+
dstHeight
|
|
768
|
+
].every((n) => Number.isFinite(n) && n > 0)) throw new Error("coverCrop: sizes must be positive numbers");
|
|
769
|
+
const srcRatio = srcWidth / srcHeight;
|
|
770
|
+
const dstRatio = dstWidth / dstHeight;
|
|
771
|
+
if (srcRatio > dstRatio) {
|
|
772
|
+
const sw = Math.round(srcHeight * dstRatio);
|
|
773
|
+
return {
|
|
774
|
+
sx: Math.round((srcWidth - sw) / 2),
|
|
775
|
+
sy: 0,
|
|
776
|
+
sw,
|
|
777
|
+
sh: srcHeight
|
|
778
|
+
};
|
|
779
|
+
}
|
|
780
|
+
const sh = Math.round(srcWidth / dstRatio);
|
|
781
|
+
return {
|
|
782
|
+
sx: 0,
|
|
783
|
+
sy: Math.round((srcHeight - sh) / 2),
|
|
784
|
+
sw: srcWidth,
|
|
785
|
+
sh
|
|
786
|
+
};
|
|
787
|
+
}
|
|
788
|
+
function requireBrowserImages(fn) {
|
|
789
|
+
if (typeof createImageBitmap !== "function") throw new Error(`${fn} needs a browser (createImageBitmap is not available)`);
|
|
790
|
+
}
|
|
791
|
+
/** Reads an image file's pixel size (browser only). */
|
|
792
|
+
async function readImageSize(file) {
|
|
793
|
+
requireBrowserImages("readImageSize");
|
|
794
|
+
const bitmap = await createImageBitmap(file);
|
|
795
|
+
try {
|
|
796
|
+
return {
|
|
797
|
+
width: bitmap.width,
|
|
798
|
+
height: bitmap.height
|
|
799
|
+
};
|
|
800
|
+
} finally {
|
|
801
|
+
bitmap.close?.();
|
|
802
|
+
}
|
|
803
|
+
}
|
|
804
|
+
/**
|
|
805
|
+
* Returns the image at exactly `width × height`: scaled and centre-cropped
|
|
806
|
+
* (never stretched). Browser only. The result is a `File` named like the
|
|
807
|
+
* input, with the output type's extension.
|
|
808
|
+
*/
|
|
809
|
+
async function fitImageToSize(file, width, height, options = {}) {
|
|
810
|
+
requireBrowserImages("fitImageToSize");
|
|
811
|
+
const { type = "image/png", quality, keepIfExact = true } = options;
|
|
812
|
+
const name = file.name || "image";
|
|
813
|
+
const ext = type === "image/jpeg" ? "jpg" : type.split("/")[1];
|
|
814
|
+
const outName = `${name.replace(/\.[^.]+$/, "")}.${ext}`;
|
|
815
|
+
const bitmap = await createImageBitmap(file);
|
|
816
|
+
try {
|
|
817
|
+
if (keepIfExact && bitmap.width === width && bitmap.height === height && file.type === type) return file instanceof File ? file : new File([file], outName, { type });
|
|
818
|
+
const { sx, sy, sw, sh } = coverCrop(bitmap.width, bitmap.height, width, height);
|
|
819
|
+
let blob;
|
|
820
|
+
if (typeof OffscreenCanvas === "function") {
|
|
821
|
+
const canvas = new OffscreenCanvas(width, height);
|
|
822
|
+
const ctx = canvas.getContext("2d");
|
|
823
|
+
if (!ctx) throw new Error("fitImageToSize: no 2D canvas context");
|
|
824
|
+
ctx.imageSmoothingQuality = "high";
|
|
825
|
+
ctx.drawImage(bitmap, sx, sy, sw, sh, 0, 0, width, height);
|
|
826
|
+
blob = await canvas.convertToBlob({
|
|
827
|
+
type,
|
|
828
|
+
quality
|
|
829
|
+
});
|
|
830
|
+
} else {
|
|
831
|
+
const canvas = document.createElement("canvas");
|
|
832
|
+
canvas.width = width;
|
|
833
|
+
canvas.height = height;
|
|
834
|
+
const ctx = canvas.getContext("2d");
|
|
835
|
+
if (!ctx) throw new Error("fitImageToSize: no 2D canvas context");
|
|
836
|
+
ctx.imageSmoothingQuality = "high";
|
|
837
|
+
ctx.drawImage(bitmap, sx, sy, sw, sh, 0, 0, width, height);
|
|
838
|
+
blob = await new Promise((resolve, reject) => canvas.toBlob((b) => b ? resolve(b) : reject(/* @__PURE__ */ new Error("fitImageToSize: encoding failed")), type, quality));
|
|
839
|
+
}
|
|
840
|
+
return new File([blob], outName, { type });
|
|
841
|
+
} finally {
|
|
842
|
+
bitmap.close?.();
|
|
843
|
+
}
|
|
844
|
+
}
|
|
845
|
+
|
|
846
|
+
//#endregion
|
|
847
|
+
//#region src/core/upload.ts
|
|
848
|
+
/**
|
|
849
|
+
* HTTPS host that serves the Shopwave CDN's images. The API returns
|
|
850
|
+
* `http://static.merchantstack.com/images/…`, which has no HTTPS endpoint
|
|
851
|
+
* (checked Sep 2026), so pages served over HTTPS can't show it.
|
|
852
|
+
*/
|
|
853
|
+
const SHOPWAVE_IMAGE_BASE_URL = "https://s3-eu-west-1.amazonaws.com/static.merchantstack.com/images";
|
|
854
|
+
const STATIC_HOST = /^https?:\/\/static\.merchantstack\.com\/images\//i;
|
|
855
|
+
/**
|
|
856
|
+
* Turns an image path from the API into a URL a page can load over HTTPS:
|
|
857
|
+
* `http://static.merchantstack.com/images/x.png` → `<base>/x.png`, and a
|
|
858
|
+
* relative path (`merchant/5644/logo/x.png`) → `<base>/merchant/5644/logo/x.png`.
|
|
859
|
+
* Other absolute URLs are returned unchanged; empty input gives `""`.
|
|
860
|
+
*/
|
|
861
|
+
function getImageUrl(path, base = SHOPWAVE_IMAGE_BASE_URL) {
|
|
862
|
+
if (!path) return "";
|
|
863
|
+
const root = base.replace(/\/+$/, "");
|
|
864
|
+
if (STATIC_HOST.test(path)) return `${root}/${path.replace(STATIC_HOST, "")}`;
|
|
865
|
+
if (/^[a-z][a-z0-9+.-]*:/i.test(path) || path.startsWith("//")) return path;
|
|
866
|
+
return `${root}/${path.replace(/^\/+/, "")}`;
|
|
867
|
+
}
|
|
868
|
+
/**
|
|
869
|
+
* Uploads one image to the Shopwave CDN through the app's `/api/upload` route
|
|
870
|
+
* (`createShopwaveApi(...).upload()`), and returns its id and URL.
|
|
871
|
+
*
|
|
872
|
+
* The file only lands on the CDN (under `…/images/<kind>/<merchantId>/…`); a
|
|
873
|
+
* record has to point at it to use it. Live API (Sep 2026): the upload answers
|
|
874
|
+
* 201 `{ fileName, path }`.
|
|
875
|
+
*/
|
|
876
|
+
async function uploadImage(file, params, options = {}) {
|
|
877
|
+
if (!file || typeof file.size !== "number") throw new Error("uploadImage: file must be a File or Blob");
|
|
878
|
+
if (!isUploadKind(params?.kind)) throw new Error(`uploadImage: unknown kind "${params?.kind}"`);
|
|
879
|
+
const name = params.fileName ?? file.name ?? "upload";
|
|
880
|
+
const form = new FormData();
|
|
881
|
+
form.append(SHOPWAVE_UPLOAD.fileField, file, name);
|
|
882
|
+
form.append(SHOPWAVE_UPLOAD.kindField, params.kind);
|
|
883
|
+
const { status, body: raw } = await apiRequest(`/api/${SHOPWAVE_UPLOAD.route}`, {
|
|
884
|
+
method: "POST",
|
|
885
|
+
body: form
|
|
886
|
+
}, options);
|
|
887
|
+
const body = raw;
|
|
888
|
+
assertNoApiErrors(body, status);
|
|
889
|
+
const id = typeof body?.fileName === "string" ? body.fileName : "";
|
|
890
|
+
const path = typeof body?.path === "string" ? body.path : "";
|
|
891
|
+
if (!id) throw new ShopwaveApiError(status, `Shopwave API error (${status}): the upload response has no fileName`, { body });
|
|
892
|
+
return {
|
|
893
|
+
id,
|
|
894
|
+
url: getImageUrl(path),
|
|
895
|
+
path
|
|
896
|
+
};
|
|
897
|
+
}
|
|
898
|
+
|
|
899
|
+
//#endregion
|
|
900
|
+
//#region src/core/merchantImages.ts
|
|
901
|
+
/** The three image slots on the merchant settings page. */
|
|
902
|
+
const MERCHANT_IMAGE_SLOT_KEYS = [
|
|
903
|
+
"receipt",
|
|
904
|
+
"square",
|
|
905
|
+
"featured"
|
|
906
|
+
];
|
|
907
|
+
/**
|
|
908
|
+
* Where each slot lives, its upload kind and its exact size (from adminV1's
|
|
909
|
+
* merchant settings page).
|
|
910
|
+
*/
|
|
911
|
+
const MERCHANT_IMAGE_SLOTS = Object.freeze({
|
|
912
|
+
receipt: {
|
|
913
|
+
field: "logo.receipt",
|
|
914
|
+
uploadKind: "merchant",
|
|
915
|
+
width: 576,
|
|
916
|
+
height: 325
|
|
917
|
+
},
|
|
918
|
+
square: {
|
|
919
|
+
field: "logo.square",
|
|
920
|
+
uploadKind: "merchant",
|
|
921
|
+
width: 1e3,
|
|
922
|
+
height: 1e3
|
|
923
|
+
},
|
|
924
|
+
featured: {
|
|
925
|
+
field: "feature[0]",
|
|
926
|
+
uploadKind: "merchantFeature",
|
|
927
|
+
width: 1200,
|
|
928
|
+
height: 600
|
|
929
|
+
}
|
|
930
|
+
});
|
|
931
|
+
/**
|
|
932
|
+
* The file name in an image value: `"http://…/logo/abc.png"` → `"abc.png"`,
|
|
933
|
+
* `"abc.png"` → `"abc.png"`. Query strings and fragments are ignored.
|
|
934
|
+
* Returns `null` for empty or non-string values.
|
|
935
|
+
*/
|
|
936
|
+
function imageFileName(value) {
|
|
937
|
+
if (typeof value !== "string") return null;
|
|
938
|
+
const last = value.trim().replace(/[?#].*$/, "").split("/").pop() ?? "";
|
|
939
|
+
return last ? decodeURIComponent(last) : null;
|
|
940
|
+
}
|
|
941
|
+
/** The stored value for a slot (a URL when read from the API; a file name right after an upload). */
|
|
942
|
+
function getMerchantImage(imageIds, slot) {
|
|
943
|
+
if (!imageIds || typeof imageIds !== "object") return null;
|
|
944
|
+
let value;
|
|
945
|
+
if (slot === "featured") value = Array.isArray(imageIds.feature) ? imageIds.feature[0] : void 0;
|
|
946
|
+
else {
|
|
947
|
+
const logo = imageIds.logo;
|
|
948
|
+
value = logo && typeof logo === "object" ? logo[slot] : void 0;
|
|
949
|
+
}
|
|
950
|
+
return typeof value === "string" && value.trim() ? value.trim() : null;
|
|
951
|
+
}
|
|
952
|
+
/**
|
|
953
|
+
* An HTTPS URL for a slot's stored image, or `""` when the slot is empty or
|
|
954
|
+
* holds only a file name (a fresh upload not yet saved; use the upload's `url`).
|
|
955
|
+
*/
|
|
956
|
+
function getMerchantImageUrl(imageIds, slot, base) {
|
|
957
|
+
const value = getMerchantImage(imageIds, slot);
|
|
958
|
+
if (!value || !value.includes("/")) return "";
|
|
959
|
+
return getImageUrl(value, base);
|
|
960
|
+
}
|
|
961
|
+
/**
|
|
962
|
+
* Returns a copy of `imageIds` with one slot set to `fileName` (or cleared
|
|
963
|
+
* with `null`). Other slots and unknown keys are kept; an empty `logo` or
|
|
964
|
+
* `feature` is removed.
|
|
965
|
+
*/
|
|
966
|
+
function setMerchantImage(imageIds, slot, fileName) {
|
|
967
|
+
const next = { ...imageIds && typeof imageIds === "object" ? imageIds : {} };
|
|
968
|
+
if (slot === "featured") {
|
|
969
|
+
const rest = Array.isArray(next.feature) ? next.feature.slice(1) : [];
|
|
970
|
+
const feature = fileName ? [fileName, ...rest] : rest;
|
|
971
|
+
if (feature.length > 0) next.feature = feature;
|
|
972
|
+
else delete next.feature;
|
|
973
|
+
} else {
|
|
974
|
+
const logo = { ...next.logo && typeof next.logo === "object" ? next.logo : {} };
|
|
975
|
+
if (fileName) logo[slot] = fileName;
|
|
976
|
+
else delete logo[slot];
|
|
977
|
+
if (Object.keys(logo).length > 0) next.logo = logo;
|
|
978
|
+
else delete next.logo;
|
|
979
|
+
}
|
|
980
|
+
return next;
|
|
981
|
+
}
|
|
982
|
+
function toStored(value) {
|
|
983
|
+
if (typeof value === "string") return imageFileName(value) ?? void 0;
|
|
984
|
+
if (Array.isArray(value)) {
|
|
985
|
+
const items = value.map(toStored).filter((v) => v !== void 0 && v !== null && v !== "");
|
|
986
|
+
return items.length > 0 ? items : void 0;
|
|
987
|
+
}
|
|
988
|
+
if (value && typeof value === "object") {
|
|
989
|
+
const out = {};
|
|
990
|
+
for (const [k, v] of Object.entries(value)) {
|
|
991
|
+
const stored = toStored(v);
|
|
992
|
+
if (stored !== void 0 && stored !== null && stored !== "") out[k] = stored;
|
|
993
|
+
}
|
|
994
|
+
return Object.keys(out).length > 0 ? out : void 0;
|
|
995
|
+
}
|
|
996
|
+
}
|
|
997
|
+
/**
|
|
998
|
+
* The `imageIds` to send on a save: every URL is turned back into its file
|
|
999
|
+
* name (what adminV1 does with images you didn't change) and empty values
|
|
1000
|
+
* are dropped. No images gives `{}`.
|
|
1001
|
+
*/
|
|
1002
|
+
function toStoredImageIds(imageIds) {
|
|
1003
|
+
return toStored(imageIds) ?? {};
|
|
1004
|
+
}
|
|
1005
|
+
/**
|
|
1006
|
+
* Uploads an image for a merchant slot: fits it to the slot's size, uploads
|
|
1007
|
+
* it with the slot's kind, and returns `{ id, url, path }`. Put `id` into
|
|
1008
|
+
* `imageIds` with {@link setMerchantImage} and save with `updateMerchant`.
|
|
1009
|
+
*/
|
|
1010
|
+
async function uploadMerchantImage(file, slot, options = {}) {
|
|
1011
|
+
const def = MERCHANT_IMAGE_SLOTS[slot];
|
|
1012
|
+
if (!def) throw new Error(`uploadMerchantImage: unknown slot "${slot}"`);
|
|
1013
|
+
const { fit = true, fitOptions,...requestOptions } = options;
|
|
1014
|
+
return uploadImage(fit ? await fitImageToSize(file, def.width, def.height, fitOptions) : file, { kind: def.uploadKind }, requestOptions);
|
|
1015
|
+
}
|
|
1016
|
+
|
|
1017
|
+
//#endregion
|
|
1018
|
+
//#region src/core/merchant.ts
|
|
1019
|
+
const MERCHANT_PATH = `/api/${SHOPWAVE_RESOURCES.merchant.route}`;
|
|
1020
|
+
/** Colour keys inside `colours.primary`, in display order. */
|
|
1021
|
+
const MERCHANT_COLOUR_KEYS = [
|
|
1022
|
+
"main",
|
|
1023
|
+
"highlight",
|
|
1024
|
+
"contrast"
|
|
1025
|
+
];
|
|
1026
|
+
/** Flat link fields a form edits, in display order. */
|
|
1027
|
+
const MERCHANT_LINK_KEYS = [
|
|
1028
|
+
"website",
|
|
1029
|
+
"twitter",
|
|
1030
|
+
"facebook",
|
|
1031
|
+
"instagram"
|
|
1032
|
+
];
|
|
1033
|
+
/** Where each flat link field lives in `merchant.links`. */
|
|
1034
|
+
const MERCHANT_LINK_PATHS = Object.freeze({
|
|
1035
|
+
website: ["website", "home"],
|
|
1036
|
+
twitter: ["social", "twitter"],
|
|
1037
|
+
facebook: ["social", "facebook"],
|
|
1038
|
+
instagram: ["social", "instagram"]
|
|
1039
|
+
});
|
|
1040
|
+
function trimmed(value) {
|
|
1041
|
+
return typeof value === "string" && value.trim() ? value.trim() : void 0;
|
|
1042
|
+
}
|
|
1043
|
+
/**
|
|
1044
|
+
* Reads `merchant.links` as flat fields (`{ website, twitter, facebook,
|
|
1045
|
+
* instagram }`), whatever shape it was saved in:
|
|
1046
|
+
* - the nested shape adminV1 saves (`{ website: { home }, social: { … } }`);
|
|
1047
|
+
* - flat keys (`{ website: "…" }`, what SDK 0.4.0 pre-releases sent);
|
|
1048
|
+
* - an array in {@link MERCHANT_LINK_KEYS} order (older AdminUI versions).
|
|
1049
|
+
* Empty values are dropped.
|
|
1050
|
+
*/
|
|
1051
|
+
function merchantLinksToForm(links) {
|
|
1052
|
+
const out = {};
|
|
1053
|
+
if (Array.isArray(links)) {
|
|
1054
|
+
links.forEach((value, i) => {
|
|
1055
|
+
const key = MERCHANT_LINK_KEYS[i];
|
|
1056
|
+
const v = trimmed(value);
|
|
1057
|
+
if (key && v) out[key] = v;
|
|
1058
|
+
});
|
|
1059
|
+
return out;
|
|
1060
|
+
}
|
|
1061
|
+
if (!links || typeof links !== "object") return out;
|
|
1062
|
+
const obj = links;
|
|
1063
|
+
for (const key of MERCHANT_LINK_KEYS) {
|
|
1064
|
+
const [group, field] = MERCHANT_LINK_PATHS[key];
|
|
1065
|
+
const nested = obj[group];
|
|
1066
|
+
const v = nested && typeof nested === "object" && !Array.isArray(nested) ? trimmed(nested[field]) : trimmed(obj[key]);
|
|
1067
|
+
if (v) out[key] = v;
|
|
1068
|
+
}
|
|
1069
|
+
return out;
|
|
1070
|
+
}
|
|
1071
|
+
/**
|
|
1072
|
+
* Builds the stored `links` object from flat fields. Empty values are left
|
|
1073
|
+
* out, and so is a group with nothing in it; no links gives `{}`.
|
|
1074
|
+
*/
|
|
1075
|
+
function merchantLinksFromForm(form) {
|
|
1076
|
+
const out = {};
|
|
1077
|
+
for (const key of MERCHANT_LINK_KEYS) {
|
|
1078
|
+
const v = trimmed(form[key]);
|
|
1079
|
+
if (!v) continue;
|
|
1080
|
+
const [group, field] = MERCHANT_LINK_PATHS[key];
|
|
1081
|
+
(out[group] ??= {})[field] = v;
|
|
1082
|
+
}
|
|
1083
|
+
return out;
|
|
1084
|
+
}
|
|
1085
|
+
/** Reads any stored or older `links` value into the nested shape adminV1 saves. */
|
|
1086
|
+
function normalizeMerchantLinks(links) {
|
|
1087
|
+
return merchantLinksFromForm(merchantLinksToForm(links));
|
|
1088
|
+
}
|
|
1089
|
+
/**
|
|
1090
|
+
* Object fields of the merchant. The API keeps one you leave out, and
|
|
1091
|
+
* replaces it as a whole when you send it.
|
|
1092
|
+
*/
|
|
1093
|
+
const MERCHANT_OBJECT_FIELDS = [
|
|
1094
|
+
"colours",
|
|
1095
|
+
"links",
|
|
1096
|
+
"imageIds"
|
|
1097
|
+
];
|
|
1098
|
+
/** Fields the API sets itself; `updateMerchant` never sends them back. */
|
|
1099
|
+
const MERCHANT_READ_ONLY_FIELDS = ["createdDate", "modifiedDate"];
|
|
1100
|
+
/**
|
|
1101
|
+
* Longest values the API stores. Longer values are cut off silently
|
|
1102
|
+
* (live API, Sep 2026), so `updateMerchant` rejects them instead.
|
|
1103
|
+
* `vatNumber` fits a UK VAT number without the `GB` prefix.
|
|
1104
|
+
*/
|
|
1105
|
+
const MERCHANT_FIELD_MAX_LENGTH = Object.freeze({
|
|
1106
|
+
companyNumber: 11,
|
|
1107
|
+
vatNumber: 9
|
|
1108
|
+
});
|
|
1109
|
+
/** Returns `"<field> is longer than <n> characters"` messages for over-long fields. */
|
|
1110
|
+
function validateMerchant(merchant) {
|
|
1111
|
+
const problems = [];
|
|
1112
|
+
for (const [field, max] of Object.entries(MERCHANT_FIELD_MAX_LENGTH)) {
|
|
1113
|
+
const value = merchant[field];
|
|
1114
|
+
if (typeof value === "string" && value.length > max) problems.push(`${field} is longer than ${max} characters`);
|
|
1115
|
+
}
|
|
1116
|
+
return problems;
|
|
1117
|
+
}
|
|
1118
|
+
/**
|
|
1119
|
+
* Reads the logged-in user's merchant (a user has exactly one), or `null`
|
|
1120
|
+
* when the API returns none.
|
|
1121
|
+
*/
|
|
1122
|
+
async function fetchMerchant(options = {}) {
|
|
1123
|
+
const json = await apiGet(MERCHANT_PATH, {}, options);
|
|
1124
|
+
assertNoApiErrors(json, 200);
|
|
1125
|
+
return json?.merchant ?? null;
|
|
1126
|
+
}
|
|
1127
|
+
/**
|
|
1128
|
+
* Updates the merchant and returns it as stored.
|
|
1129
|
+
*
|
|
1130
|
+
* Shopwave's `POST /merchant` replaces the whole record: a scalar field you
|
|
1131
|
+
* leave out (`companyNumber`, `vatNumber`, `note`, …) is set to null, while
|
|
1132
|
+
* an object field you leave out (`colours`, `links`, `imageIds`) is kept and
|
|
1133
|
+
* one you send replaces the stored one; sending `{}` clears it (live API,
|
|
1134
|
+
* Sep 2026). So by default the
|
|
1135
|
+
* current merchant is read first and the patch is merged over it.
|
|
1136
|
+
*
|
|
1137
|
+
* `imageIds` is always sent as file names ({@link toStoredImageIds}), so you
|
|
1138
|
+
* can pass back what you read. See `MerchantImageIds` for the shape.
|
|
1139
|
+
*
|
|
1140
|
+
* The API answers 205 with an empty body, so the merchant is read again after
|
|
1141
|
+
* the save and that is what's returned (it shows exactly what was kept).
|
|
1142
|
+
* Throws before sending when a value is longer than the API stores
|
|
1143
|
+
* ({@link MERCHANT_FIELD_MAX_LENGTH}).
|
|
1144
|
+
*/
|
|
1145
|
+
async function updateMerchant(patch, options = {}) {
|
|
1146
|
+
const { merge = true,...requestOptions } = options;
|
|
1147
|
+
let merchant = { ...patch };
|
|
1148
|
+
if (merge) {
|
|
1149
|
+
const current = await fetchMerchant(requestOptions);
|
|
1150
|
+
if (!current) throw new ShopwaveApiError(404, "Shopwave API error (404): no merchant to update");
|
|
1151
|
+
if (patch.id != null && String(patch.id) !== String(current.id)) throw new Error(`Merchant id ${patch.id} is not the logged-in merchant (${current.id})`);
|
|
1152
|
+
merchant = {
|
|
1153
|
+
...current,
|
|
1154
|
+
...patch,
|
|
1155
|
+
id: current.id
|
|
1156
|
+
};
|
|
1157
|
+
for (const field of MERCHANT_OBJECT_FIELDS) if (!(field in patch)) delete merchant[field];
|
|
1158
|
+
}
|
|
1159
|
+
if (merchant.imageIds && typeof merchant.imageIds === "object") merchant.imageIds = toStoredImageIds(merchant.imageIds);
|
|
1160
|
+
if (merchant.id == null || merchant.id === "") throw new Error("merchant id is missing");
|
|
1161
|
+
for (const field of MERCHANT_READ_ONLY_FIELDS) delete merchant[field];
|
|
1162
|
+
const problems = validateMerchant(merchant);
|
|
1163
|
+
if (problems.length > 0) throw new Error(`Invalid merchant: ${problems.join("; ")}`);
|
|
1164
|
+
const { status, body: raw } = await apiRequest(MERCHANT_PATH, {
|
|
1165
|
+
method: "PUT",
|
|
1166
|
+
headers: { "Content-Type": "application/json" },
|
|
1167
|
+
body: JSON.stringify({ merchant })
|
|
1168
|
+
}, requestOptions);
|
|
1169
|
+
const body = raw;
|
|
1170
|
+
assertNoApiErrors(body, status);
|
|
1171
|
+
const echoed = body?.merchant && typeof body.merchant === "object" ? body.merchant : null;
|
|
1172
|
+
if (echoed) return {
|
|
1173
|
+
...merchant,
|
|
1174
|
+
...echoed,
|
|
1175
|
+
id: Number(echoed.id ?? merchant.id)
|
|
1176
|
+
};
|
|
1177
|
+
return await fetchMerchant(requestOptions) ?? {
|
|
1178
|
+
...merchant,
|
|
1179
|
+
id: Number(merchant.id)
|
|
1180
|
+
};
|
|
1181
|
+
}
|
|
1182
|
+
|
|
1183
|
+
//#endregion
|
|
1184
|
+
//#region src/core/user.ts
|
|
1185
|
+
/** Reads the logged-in user, or `null` when the API returns none. */
|
|
1186
|
+
async function fetchUser(options = {}) {
|
|
1187
|
+
const json = await apiGet(`/api/${SHOPWAVE_RESOURCES.user.route}`, {}, options);
|
|
1188
|
+
assertNoApiErrors(json, 200);
|
|
1189
|
+
return json?.user ?? null;
|
|
1190
|
+
}
|
|
1191
|
+
|
|
436
1192
|
//#endregion
|
|
437
1193
|
exports.DEFAULT_BASKET_FILTERS = DEFAULT_BASKET_FILTERS;
|
|
438
1194
|
exports.DEFAULT_PAGINATION = DEFAULT_PAGINATION;
|
|
1195
|
+
exports.MERCHANT_COLOUR_KEYS = MERCHANT_COLOUR_KEYS;
|
|
1196
|
+
exports.MERCHANT_FIELD_MAX_LENGTH = MERCHANT_FIELD_MAX_LENGTH;
|
|
1197
|
+
exports.MERCHANT_IMAGE_SLOTS = MERCHANT_IMAGE_SLOTS;
|
|
1198
|
+
exports.MERCHANT_IMAGE_SLOT_KEYS = MERCHANT_IMAGE_SLOT_KEYS;
|
|
1199
|
+
exports.MERCHANT_LINK_KEYS = MERCHANT_LINK_KEYS;
|
|
1200
|
+
exports.MERCHANT_LINK_PATHS = MERCHANT_LINK_PATHS;
|
|
1201
|
+
exports.MERCHANT_OBJECT_FIELDS = MERCHANT_OBJECT_FIELDS;
|
|
1202
|
+
exports.MERCHANT_READ_ONLY_FIELDS = MERCHANT_READ_ONLY_FIELDS;
|
|
439
1203
|
exports.PromotionRuleSet = PromotionRuleSet;
|
|
1204
|
+
exports.SHOPWAVE_ENTITIES = SHOPWAVE_ENTITIES;
|
|
1205
|
+
exports.SHOPWAVE_IMAGE_BASE_URL = SHOPWAVE_IMAGE_BASE_URL;
|
|
1206
|
+
exports.SHOPWAVE_RESOURCES = SHOPWAVE_RESOURCES;
|
|
1207
|
+
exports.SHOPWAVE_UPLOAD = SHOPWAVE_UPLOAD;
|
|
1208
|
+
exports.ShopwaveApiError = ShopwaveApiError;
|
|
1209
|
+
exports.UPLOAD_KINDS = UPLOAD_KINDS;
|
|
440
1210
|
exports.apiDelete = apiDelete;
|
|
441
1211
|
exports.apiGet = apiGet;
|
|
1212
|
+
exports.apiRequest = apiRequest;
|
|
442
1213
|
exports.apiSend = apiSend;
|
|
1214
|
+
exports.assertNoApiErrors = assertNoApiErrors;
|
|
1215
|
+
exports.authorizationFor = authorizationFor;
|
|
443
1216
|
exports.buildBasketReportQuery = buildBasketReportQuery;
|
|
444
1217
|
exports.buildConsumerMap = buildConsumerMap;
|
|
445
1218
|
exports.collectConsumerIds = collectConsumerIds;
|
|
446
1219
|
exports.collectProductIds = collectProductIds;
|
|
447
1220
|
exports.combineBasketRows = combineBasketRows;
|
|
448
1221
|
exports.computeBasketSummary = computeBasketSummary;
|
|
1222
|
+
exports.coverCrop = coverCrop;
|
|
1223
|
+
exports.deleteCategory = deleteCategory;
|
|
1224
|
+
exports.deleteEmployee = deleteEmployee;
|
|
449
1225
|
exports.deleteEntity = deleteEntity;
|
|
1226
|
+
exports.deleteEntityById = deleteEntityById;
|
|
1227
|
+
exports.deleteProduct = deleteProduct;
|
|
1228
|
+
exports.deletePromotion = deletePromotion;
|
|
1229
|
+
exports.deleteStore = deleteStore;
|
|
450
1230
|
exports.fetchCategories = fetchCategories;
|
|
1231
|
+
exports.fetchCategory = fetchCategory;
|
|
1232
|
+
exports.fetchConsumer = fetchConsumer;
|
|
451
1233
|
exports.fetchConsumers = fetchConsumers;
|
|
1234
|
+
exports.fetchEmployee = fetchEmployee;
|
|
452
1235
|
exports.fetchEmployees = fetchEmployees;
|
|
1236
|
+
exports.fetchEntityById = fetchEntityById;
|
|
1237
|
+
exports.fetchMerchant = fetchMerchant;
|
|
1238
|
+
exports.fetchProduct = fetchProduct;
|
|
453
1239
|
exports.fetchProducts = fetchProducts;
|
|
454
1240
|
exports.fetchProductsMap = fetchProductsMap;
|
|
1241
|
+
exports.fetchPromotion = fetchPromotion;
|
|
455
1242
|
exports.fetchPromotions = fetchPromotions;
|
|
456
1243
|
exports.fetchReport = fetchReport;
|
|
457
1244
|
exports.fetchSession = fetchSession;
|
|
1245
|
+
exports.fetchStore = fetchStore;
|
|
458
1246
|
exports.fetchStores = fetchStores;
|
|
1247
|
+
exports.fetchUser = fetchUser;
|
|
1248
|
+
exports.fitImageToSize = fitImageToSize;
|
|
459
1249
|
exports.formatDateForQuery = formatDateForQuery;
|
|
1250
|
+
exports.getApiErrorMap = getApiErrorMap;
|
|
460
1251
|
exports.getApiErrors = getApiErrors;
|
|
1252
|
+
exports.getImageUrl = getImageUrl;
|
|
1253
|
+
exports.getMerchantImage = getMerchantImage;
|
|
1254
|
+
exports.getMerchantImageUrl = getMerchantImageUrl;
|
|
1255
|
+
exports.imageFileName = imageFileName;
|
|
1256
|
+
exports.isUploadKind = isUploadKind;
|
|
461
1257
|
exports.loginPath = loginPath;
|
|
462
1258
|
exports.logout = logout;
|
|
463
1259
|
exports.logoutPath = logoutPath;
|
|
1260
|
+
exports.merchantLinksFromForm = merchantLinksFromForm;
|
|
1261
|
+
exports.merchantLinksToForm = merchantLinksToForm;
|
|
1262
|
+
exports.normalizeMerchantLinks = normalizeMerchantLinks;
|
|
464
1263
|
exports.parseBasketReportData = parseBasketReportData;
|
|
1264
|
+
exports.readImageSize = readImageSize;
|
|
465
1265
|
exports.rolesById = rolesById;
|
|
1266
|
+
exports.saveCategory = saveCategory;
|
|
1267
|
+
exports.saveEmployee = saveEmployee;
|
|
1268
|
+
exports.saveEntities = saveEntities;
|
|
1269
|
+
exports.saveEntity = saveEntity;
|
|
1270
|
+
exports.saveProduct = saveProduct;
|
|
1271
|
+
exports.savePromotion = savePromotion;
|
|
1272
|
+
exports.saveStore = saveStore;
|
|
1273
|
+
exports.setMerchantImage = setMerchantImage;
|
|
466
1274
|
exports.submitEntity = submitEntity;
|
|
1275
|
+
exports.toShopwaveApiError = toShopwaveApiError;
|
|
1276
|
+
exports.toStoredImageIds = toStoredImageIds;
|
|
1277
|
+
exports.updateMerchant = updateMerchant;
|
|
1278
|
+
exports.uploadImage = uploadImage;
|
|
1279
|
+
exports.uploadMerchantImage = uploadMerchantImage;
|
|
1280
|
+
exports.validateMerchant = validateMerchant;
|
|
1281
|
+
exports.withToken = withToken;
|
|
467
1282
|
//# sourceMappingURL=index.cjs.map
|