react-shopwave-connect 0.2.0 → 0.3.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 +145 -22
- package/dist/core/index.cjs +392 -88
- package/dist/core/index.cjs.map +1 -1
- package/dist/core/index.d.cts +214 -23
- package/dist/core/index.d.ts +214 -23
- package/dist/core/index.js +365 -89
- package/dist/core/index.js.map +1 -1
- package/dist/hooks/index.cjs +281 -111
- package/dist/hooks/index.cjs.map +1 -1
- package/dist/hooks/index.d.cts +34 -11
- package/dist/hooks/index.d.ts +34 -11
- package/dist/hooks/index.js +282 -112
- package/dist/hooks/index.js.map +1 -1
- package/dist/index.cjs +492 -107
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +227 -24
- package/dist/index.d.ts +227 -24
- package/dist/index.js +466 -109
- package/dist/index.js.map +1 -1
- package/dist/next/index.cjs +436 -2
- package/dist/next/index.cjs.map +1 -1
- package/dist/next/index.d.cts +169 -1
- package/dist/next/index.d.ts +169 -1
- package/dist/next/index.js +434 -3
- package/dist/next/index.js.map +1 -1
- package/dist/server/index.cjs +411 -1
- package/dist/server/index.cjs.map +1 -1
- package/dist/server/index.d.cts +170 -1
- package/dist/server/index.d.ts +170 -1
- package/dist/server/index.js +404 -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 = {
|
|
@@ -437,31 +713,59 @@ function buildConsumerMap(consumers) {
|
|
|
437
713
|
exports.DEFAULT_BASKET_FILTERS = DEFAULT_BASKET_FILTERS;
|
|
438
714
|
exports.DEFAULT_PAGINATION = DEFAULT_PAGINATION;
|
|
439
715
|
exports.PromotionRuleSet = PromotionRuleSet;
|
|
716
|
+
exports.SHOPWAVE_ENTITIES = SHOPWAVE_ENTITIES;
|
|
717
|
+
exports.ShopwaveApiError = ShopwaveApiError;
|
|
440
718
|
exports.apiDelete = apiDelete;
|
|
441
719
|
exports.apiGet = apiGet;
|
|
720
|
+
exports.apiRequest = apiRequest;
|
|
442
721
|
exports.apiSend = apiSend;
|
|
722
|
+
exports.assertNoApiErrors = assertNoApiErrors;
|
|
723
|
+
exports.authorizationFor = authorizationFor;
|
|
443
724
|
exports.buildBasketReportQuery = buildBasketReportQuery;
|
|
444
725
|
exports.buildConsumerMap = buildConsumerMap;
|
|
445
726
|
exports.collectConsumerIds = collectConsumerIds;
|
|
446
727
|
exports.collectProductIds = collectProductIds;
|
|
447
728
|
exports.combineBasketRows = combineBasketRows;
|
|
448
729
|
exports.computeBasketSummary = computeBasketSummary;
|
|
730
|
+
exports.deleteCategory = deleteCategory;
|
|
731
|
+
exports.deleteEmployee = deleteEmployee;
|
|
449
732
|
exports.deleteEntity = deleteEntity;
|
|
733
|
+
exports.deleteEntityById = deleteEntityById;
|
|
734
|
+
exports.deleteProduct = deleteProduct;
|
|
735
|
+
exports.deletePromotion = deletePromotion;
|
|
736
|
+
exports.deleteStore = deleteStore;
|
|
450
737
|
exports.fetchCategories = fetchCategories;
|
|
738
|
+
exports.fetchCategory = fetchCategory;
|
|
739
|
+
exports.fetchConsumer = fetchConsumer;
|
|
451
740
|
exports.fetchConsumers = fetchConsumers;
|
|
741
|
+
exports.fetchEmployee = fetchEmployee;
|
|
452
742
|
exports.fetchEmployees = fetchEmployees;
|
|
743
|
+
exports.fetchEntityById = fetchEntityById;
|
|
744
|
+
exports.fetchProduct = fetchProduct;
|
|
453
745
|
exports.fetchProducts = fetchProducts;
|
|
454
746
|
exports.fetchProductsMap = fetchProductsMap;
|
|
747
|
+
exports.fetchPromotion = fetchPromotion;
|
|
455
748
|
exports.fetchPromotions = fetchPromotions;
|
|
456
749
|
exports.fetchReport = fetchReport;
|
|
457
750
|
exports.fetchSession = fetchSession;
|
|
751
|
+
exports.fetchStore = fetchStore;
|
|
458
752
|
exports.fetchStores = fetchStores;
|
|
459
753
|
exports.formatDateForQuery = formatDateForQuery;
|
|
754
|
+
exports.getApiErrorMap = getApiErrorMap;
|
|
460
755
|
exports.getApiErrors = getApiErrors;
|
|
461
756
|
exports.loginPath = loginPath;
|
|
462
757
|
exports.logout = logout;
|
|
463
758
|
exports.logoutPath = logoutPath;
|
|
464
759
|
exports.parseBasketReportData = parseBasketReportData;
|
|
465
760
|
exports.rolesById = rolesById;
|
|
761
|
+
exports.saveCategory = saveCategory;
|
|
762
|
+
exports.saveEmployee = saveEmployee;
|
|
763
|
+
exports.saveEntities = saveEntities;
|
|
764
|
+
exports.saveEntity = saveEntity;
|
|
765
|
+
exports.saveProduct = saveProduct;
|
|
766
|
+
exports.savePromotion = savePromotion;
|
|
767
|
+
exports.saveStore = saveStore;
|
|
466
768
|
exports.submitEntity = submitEntity;
|
|
769
|
+
exports.toShopwaveApiError = toShopwaveApiError;
|
|
770
|
+
exports.withToken = withToken;
|
|
467
771
|
//# sourceMappingURL=index.cjs.map
|