react-shopwave-connect 0.3.0 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +73 -4
- package/dist/core/index.cjs +612 -7
- package/dist/core/index.cjs.map +1 -1
- package/dist/core/index.d.cts +459 -2
- package/dist/core/index.d.ts +459 -2
- package/dist/core/index.js +579 -8
- package/dist/core/index.js.map +1 -1
- package/dist/hooks/index.cjs +456 -0
- package/dist/hooks/index.cjs.map +1 -1
- package/dist/hooks/index.d.cts +229 -1
- package/dist/hooks/index.d.ts +229 -1
- package/dist/hooks/index.js +452 -1
- package/dist/hooks/index.js.map +1 -1
- package/dist/index.cjs +696 -7
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +512 -2
- package/dist/index.d.ts +512 -2
- package/dist/index.js +658 -8
- package/dist/index.js.map +1 -1
- package/dist/next/index.cjs +126 -2
- package/dist/next/index.cjs.map +1 -1
- package/dist/next/index.d.cts +82 -2
- package/dist/next/index.d.ts +82 -2
- package/dist/next/index.js +125 -3
- package/dist/next/index.js.map +1 -1
- package/dist/server/index.cjs +122 -2
- package/dist/server/index.cjs.map +1 -1
- package/dist/server/index.d.cts +90 -2
- package/dist/server/index.d.ts +90 -2
- package/dist/server/index.js +120 -3
- package/dist/server/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -42,8 +42,8 @@ function getApiErrorMap(body) {
|
|
|
42
42
|
}
|
|
43
43
|
function describeErrors(errors) {
|
|
44
44
|
return Object.entries(errors).map(([code, e]) => {
|
|
45
|
-
const text = [e?.title, e?.details].filter(Boolean).join(": ");
|
|
46
|
-
return text ? `${code} ${text}` : code;
|
|
45
|
+
const text$1 = [e?.title, e?.details].filter(Boolean).join(": ");
|
|
46
|
+
return text$1 ? `${code} ${text$1}` : code;
|
|
47
47
|
}).join("; ");
|
|
48
48
|
}
|
|
49
49
|
/**
|
|
@@ -105,12 +105,12 @@ function buildExtras(extras) {
|
|
|
105
105
|
}
|
|
106
106
|
/** Parses a response body as JSON; `null` for an empty body, `{ raw }` for non-JSON. */
|
|
107
107
|
async function readBody(response) {
|
|
108
|
-
const text = await response.text();
|
|
109
|
-
if (!text) return null;
|
|
108
|
+
const text$1 = await response.text();
|
|
109
|
+
if (!text$1) return null;
|
|
110
110
|
try {
|
|
111
|
-
return JSON.parse(text);
|
|
111
|
+
return JSON.parse(text$1);
|
|
112
112
|
} catch {
|
|
113
|
-
return { raw: text };
|
|
113
|
+
return { raw: text$1 };
|
|
114
114
|
}
|
|
115
115
|
}
|
|
116
116
|
/**
|
|
@@ -258,6 +258,83 @@ async function fetchProducts(params = {}, options = {}) {
|
|
|
258
258
|
assertNoApiErrors(json, 200);
|
|
259
259
|
return Object.values(json?.products ?? {});
|
|
260
260
|
}
|
|
261
|
+
/** Fields the server sets on an instance; never sent back. */
|
|
262
|
+
const SERVER_INSTANCE_FIELDS = ["timestamp"];
|
|
263
|
+
function instanceList(instances) {
|
|
264
|
+
if (!instances) return [];
|
|
265
|
+
return (Array.isArray(instances) ? [...instances] : Object.values(instances)).filter((inst) => inst != null && typeof inst === "object");
|
|
266
|
+
}
|
|
267
|
+
function hasId(id) {
|
|
268
|
+
return id != null && String(id).trim() !== "";
|
|
269
|
+
}
|
|
270
|
+
/** Same number, so `"422.0"`, `"422"` and `422` are equal; blanks equal each other. */
|
|
271
|
+
function sameAmount(a, b) {
|
|
272
|
+
const blank = (v) => v == null || String(v).trim() === "";
|
|
273
|
+
if (blank(a) || blank(b)) return blank(a) && blank(b);
|
|
274
|
+
const x = Number(a);
|
|
275
|
+
const y = Number(b);
|
|
276
|
+
return Number.isNaN(x) || Number.isNaN(y) ? String(a).trim() === String(b).trim() : x === y;
|
|
277
|
+
}
|
|
278
|
+
/** True when two instances have the same price and tax (the fields Shopwave won't update). */
|
|
279
|
+
function isSameInstancePrice(a, b) {
|
|
280
|
+
return sameAmount(a.price, b.price) && sameAmount(a.taxPercentage, b.taxPercentage);
|
|
281
|
+
}
|
|
282
|
+
const text = (v) => v == null ? "" : String(v);
|
|
283
|
+
/**
|
|
284
|
+
* Lists the instances whose price or tax differs from the `original` instance
|
|
285
|
+
* with the same id: saving them creates new instances with new ids, which can
|
|
286
|
+
* affect anything that stores instance ids (integrations, reports, modifiers).
|
|
287
|
+
* Use it to warn before saving. New rows (no id) aren't listed.
|
|
288
|
+
*/
|
|
289
|
+
function findRepricedInstances(instances, original) {
|
|
290
|
+
const byId = new Map(instanceList(original).filter((o) => hasId(o.id)).map((o) => [String(o.id), o]));
|
|
291
|
+
const result = [];
|
|
292
|
+
instanceList(instances).forEach((inst, index) => {
|
|
293
|
+
if (!hasId(inst.id)) return;
|
|
294
|
+
const before = byId.get(String(inst.id));
|
|
295
|
+
if (!before || isSameInstancePrice(inst, before)) return;
|
|
296
|
+
result.push({
|
|
297
|
+
index,
|
|
298
|
+
id: inst.id,
|
|
299
|
+
name: text(inst.name),
|
|
300
|
+
before: {
|
|
301
|
+
price: text(before.price),
|
|
302
|
+
taxPercentage: text(before.taxPercentage)
|
|
303
|
+
},
|
|
304
|
+
after: {
|
|
305
|
+
price: text(inst.price),
|
|
306
|
+
taxPercentage: text(inst.taxPercentage)
|
|
307
|
+
}
|
|
308
|
+
});
|
|
309
|
+
});
|
|
310
|
+
return result;
|
|
311
|
+
}
|
|
312
|
+
/**
|
|
313
|
+
* Builds the `instances` map for a product save:
|
|
314
|
+
* - keyed by position (`"0"`, `"1"`, …), like every other ref in a save;
|
|
315
|
+
* - an instance keeps its `id` only when `original` has an instance with that id
|
|
316
|
+
* and the same price and tax; otherwise the id is removed, so Shopwave creates
|
|
317
|
+
* a new instance instead of re-pointing or rewriting someone else's;
|
|
318
|
+
* - server fields (`timestamp`) are removed.
|
|
319
|
+
*
|
|
320
|
+
* Pass the product as last read from the API as `original`. Leave it out for a
|
|
321
|
+
* new product (including a duplicate): every id is then removed.
|
|
322
|
+
* Instances left out of the list are left out of the save (removed).
|
|
323
|
+
*/
|
|
324
|
+
function toProductInstancesForSave(instances, original) {
|
|
325
|
+
const keep = new Map(instanceList(original).filter((o) => hasId(o.id)).map((o) => [String(o.id), o]));
|
|
326
|
+
const out = {};
|
|
327
|
+
instanceList(instances).forEach((inst, index) => {
|
|
328
|
+
const { id,...rest } = inst;
|
|
329
|
+
for (const field of SERVER_INSTANCE_FIELDS) delete rest[field];
|
|
330
|
+
const before = hasId(id) ? keep.get(String(id)) : void 0;
|
|
331
|
+
out[String(index)] = before && isSameInstancePrice(inst, before) ? {
|
|
332
|
+
id,
|
|
333
|
+
...rest
|
|
334
|
+
} : rest;
|
|
335
|
+
});
|
|
336
|
+
return out;
|
|
337
|
+
}
|
|
261
338
|
/**
|
|
262
339
|
* Fetches products by id and returns them keyed by id, transparently batching
|
|
263
340
|
* the request (default 200 ids per call) to stay within API limits. Extracted
|
|
@@ -541,7 +618,21 @@ async function fetchEntityById(kind, id, params = {}, options = {}) {
|
|
|
541
618
|
const map = body?.[def.collection] ?? {};
|
|
542
619
|
return map[String(id)] ?? Object.values(map).find((e) => String(e?.id) === String(id)) ?? null;
|
|
543
620
|
}
|
|
544
|
-
|
|
621
|
+
/**
|
|
622
|
+
* Creates (no `id`) or updates (with `id`) a product.
|
|
623
|
+
*
|
|
624
|
+
* Shopwave instances (prices) can't be updated, only replaced. Build
|
|
625
|
+
* `instances` with {@link toProductInstancesForSave} (passing the product as last
|
|
626
|
+
* read) so an edited price is sent as a new instance. As a safeguard, a new
|
|
627
|
+
* product (no `id`, e.g. a duplicate) never sends instance ids: an id copied from
|
|
628
|
+
* another product would otherwise point the save at that product's instances.
|
|
629
|
+
*/
|
|
630
|
+
const saveProduct = (product, options) => {
|
|
631
|
+
return saveEntity("product", (product.id == null || String(product.id).trim() === "") && product.instances != null ? {
|
|
632
|
+
...product,
|
|
633
|
+
instances: toProductInstancesForSave(product.instances)
|
|
634
|
+
} : product, options);
|
|
635
|
+
};
|
|
545
636
|
const deleteProduct = (id, options) => deleteEntityById("product", id, options);
|
|
546
637
|
const fetchProduct = (id, params, options) => fetchEntityById("product", id, params, options);
|
|
547
638
|
const saveCategory = (category, options) => saveEntity("category", category, options);
|
|
@@ -710,6 +801,486 @@ function buildConsumerMap(consumers) {
|
|
|
710
801
|
return map;
|
|
711
802
|
}
|
|
712
803
|
|
|
804
|
+
//#endregion
|
|
805
|
+
//#region src/core/resources.ts
|
|
806
|
+
/**
|
|
807
|
+
* - merchant: `GET /merchant`; `POST /merchant` with `{ merchant: { id, … } }`
|
|
808
|
+
* updates it (without an `id` the API would create a second merchant, so the
|
|
809
|
+
* route requires one).
|
|
810
|
+
* - user: `GET /user` (read-only here; the API's `POST /user` invites users and
|
|
811
|
+
* needs the admin scope).
|
|
812
|
+
*/
|
|
813
|
+
const SHOPWAVE_RESOURCES = Object.freeze({
|
|
814
|
+
merchant: {
|
|
815
|
+
route: "merchant",
|
|
816
|
+
key: "merchant",
|
|
817
|
+
upstream: "merchant",
|
|
818
|
+
writable: true
|
|
819
|
+
},
|
|
820
|
+
user: {
|
|
821
|
+
route: "user",
|
|
822
|
+
key: "user",
|
|
823
|
+
upstream: "user",
|
|
824
|
+
writable: false
|
|
825
|
+
}
|
|
826
|
+
});
|
|
827
|
+
/** `UploadKind` → the API's `contentType` value. */
|
|
828
|
+
const UPLOAD_KINDS = Object.freeze({
|
|
829
|
+
merchant: "merchant",
|
|
830
|
+
merchantFeature: "merchantFeature",
|
|
831
|
+
product: "product",
|
|
832
|
+
user: "user",
|
|
833
|
+
applicationLogo: "applicaionLogo",
|
|
834
|
+
applicationImages: "applicaionImages"
|
|
835
|
+
});
|
|
836
|
+
/** How uploads are addressed (app route and Shopwave uploader). */
|
|
837
|
+
const SHOPWAVE_UPLOAD = Object.freeze({
|
|
838
|
+
route: "upload",
|
|
839
|
+
upstream: "uploader",
|
|
840
|
+
kindHeader: "contentType",
|
|
841
|
+
fileField: "file",
|
|
842
|
+
kindField: "kind"
|
|
843
|
+
});
|
|
844
|
+
function isUploadKind(value) {
|
|
845
|
+
return typeof value === "string" && Object.prototype.hasOwnProperty.call(UPLOAD_KINDS, value);
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
//#endregion
|
|
849
|
+
//#region src/core/imageFit.ts
|
|
850
|
+
/**
|
|
851
|
+
* The centred part of a `srcWidth × srcHeight` image with the aspect ratio of
|
|
852
|
+
* `dstWidth × dstHeight` (like CSS `object-fit: cover`).
|
|
853
|
+
*/
|
|
854
|
+
function coverCrop(srcWidth, srcHeight, dstWidth, dstHeight) {
|
|
855
|
+
if (![
|
|
856
|
+
srcWidth,
|
|
857
|
+
srcHeight,
|
|
858
|
+
dstWidth,
|
|
859
|
+
dstHeight
|
|
860
|
+
].every((n) => Number.isFinite(n) && n > 0)) throw new Error("coverCrop: sizes must be positive numbers");
|
|
861
|
+
const srcRatio = srcWidth / srcHeight;
|
|
862
|
+
const dstRatio = dstWidth / dstHeight;
|
|
863
|
+
if (srcRatio > dstRatio) {
|
|
864
|
+
const sw = Math.round(srcHeight * dstRatio);
|
|
865
|
+
return {
|
|
866
|
+
sx: Math.round((srcWidth - sw) / 2),
|
|
867
|
+
sy: 0,
|
|
868
|
+
sw,
|
|
869
|
+
sh: srcHeight
|
|
870
|
+
};
|
|
871
|
+
}
|
|
872
|
+
const sh = Math.round(srcWidth / dstRatio);
|
|
873
|
+
return {
|
|
874
|
+
sx: 0,
|
|
875
|
+
sy: Math.round((srcHeight - sh) / 2),
|
|
876
|
+
sw: srcWidth,
|
|
877
|
+
sh
|
|
878
|
+
};
|
|
879
|
+
}
|
|
880
|
+
function requireBrowserImages(fn) {
|
|
881
|
+
if (typeof createImageBitmap !== "function") throw new Error(`${fn} needs a browser (createImageBitmap is not available)`);
|
|
882
|
+
}
|
|
883
|
+
/** Reads an image file's pixel size (browser only). */
|
|
884
|
+
async function readImageSize(file) {
|
|
885
|
+
requireBrowserImages("readImageSize");
|
|
886
|
+
const bitmap = await createImageBitmap(file);
|
|
887
|
+
try {
|
|
888
|
+
return {
|
|
889
|
+
width: bitmap.width,
|
|
890
|
+
height: bitmap.height
|
|
891
|
+
};
|
|
892
|
+
} finally {
|
|
893
|
+
bitmap.close?.();
|
|
894
|
+
}
|
|
895
|
+
}
|
|
896
|
+
/**
|
|
897
|
+
* Returns the image at exactly `width × height`: scaled and centre-cropped
|
|
898
|
+
* (never stretched). Browser only. The result is a `File` named like the
|
|
899
|
+
* input, with the output type's extension.
|
|
900
|
+
*/
|
|
901
|
+
async function fitImageToSize(file, width, height, options = {}) {
|
|
902
|
+
requireBrowserImages("fitImageToSize");
|
|
903
|
+
const { type = "image/png", quality, keepIfExact = true } = options;
|
|
904
|
+
const name = file.name || "image";
|
|
905
|
+
const ext = type === "image/jpeg" ? "jpg" : type.split("/")[1];
|
|
906
|
+
const outName = `${name.replace(/\.[^.]+$/, "")}.${ext}`;
|
|
907
|
+
const bitmap = await createImageBitmap(file);
|
|
908
|
+
try {
|
|
909
|
+
if (keepIfExact && bitmap.width === width && bitmap.height === height && file.type === type) return file instanceof File ? file : new File([file], outName, { type });
|
|
910
|
+
const { sx, sy, sw, sh } = coverCrop(bitmap.width, bitmap.height, width, height);
|
|
911
|
+
let blob;
|
|
912
|
+
if (typeof OffscreenCanvas === "function") {
|
|
913
|
+
const canvas = new OffscreenCanvas(width, height);
|
|
914
|
+
const ctx = canvas.getContext("2d");
|
|
915
|
+
if (!ctx) throw new Error("fitImageToSize: no 2D canvas context");
|
|
916
|
+
ctx.imageSmoothingQuality = "high";
|
|
917
|
+
ctx.drawImage(bitmap, sx, sy, sw, sh, 0, 0, width, height);
|
|
918
|
+
blob = await canvas.convertToBlob({
|
|
919
|
+
type,
|
|
920
|
+
quality
|
|
921
|
+
});
|
|
922
|
+
} else {
|
|
923
|
+
const canvas = document.createElement("canvas");
|
|
924
|
+
canvas.width = width;
|
|
925
|
+
canvas.height = height;
|
|
926
|
+
const ctx = canvas.getContext("2d");
|
|
927
|
+
if (!ctx) throw new Error("fitImageToSize: no 2D canvas context");
|
|
928
|
+
ctx.imageSmoothingQuality = "high";
|
|
929
|
+
ctx.drawImage(bitmap, sx, sy, sw, sh, 0, 0, width, height);
|
|
930
|
+
blob = await new Promise((resolve, reject) => canvas.toBlob((b) => b ? resolve(b) : reject(/* @__PURE__ */ new Error("fitImageToSize: encoding failed")), type, quality));
|
|
931
|
+
}
|
|
932
|
+
return new File([blob], outName, { type });
|
|
933
|
+
} finally {
|
|
934
|
+
bitmap.close?.();
|
|
935
|
+
}
|
|
936
|
+
}
|
|
937
|
+
|
|
938
|
+
//#endregion
|
|
939
|
+
//#region src/core/upload.ts
|
|
940
|
+
/**
|
|
941
|
+
* HTTPS host that serves the Shopwave CDN's images. The API returns
|
|
942
|
+
* `http://static.merchantstack.com/images/…`, which has no HTTPS endpoint
|
|
943
|
+
* (checked Sep 2026), so pages served over HTTPS can't show it.
|
|
944
|
+
*/
|
|
945
|
+
const SHOPWAVE_IMAGE_BASE_URL = "https://s3-eu-west-1.amazonaws.com/static.merchantstack.com/images";
|
|
946
|
+
const STATIC_HOST = /^https?:\/\/static\.merchantstack\.com\/images\//i;
|
|
947
|
+
/**
|
|
948
|
+
* Turns an image path from the API into a URL a page can load over HTTPS:
|
|
949
|
+
* `http://static.merchantstack.com/images/x.png` → `<base>/x.png`, and a
|
|
950
|
+
* relative path (`merchant/5644/logo/x.png`) → `<base>/merchant/5644/logo/x.png`.
|
|
951
|
+
* Other absolute URLs are returned unchanged; empty input gives `""`.
|
|
952
|
+
*/
|
|
953
|
+
function getImageUrl(path, base = SHOPWAVE_IMAGE_BASE_URL) {
|
|
954
|
+
if (!path) return "";
|
|
955
|
+
const root = base.replace(/\/+$/, "");
|
|
956
|
+
if (STATIC_HOST.test(path)) return `${root}/${path.replace(STATIC_HOST, "")}`;
|
|
957
|
+
if (/^[a-z][a-z0-9+.-]*:/i.test(path) || path.startsWith("//")) return path;
|
|
958
|
+
return `${root}/${path.replace(/^\/+/, "")}`;
|
|
959
|
+
}
|
|
960
|
+
/**
|
|
961
|
+
* Uploads one image to the Shopwave CDN through the app's `/api/upload` route
|
|
962
|
+
* (`createShopwaveApi(...).upload()`), and returns its id and URL.
|
|
963
|
+
*
|
|
964
|
+
* The file only lands on the CDN (under `…/images/<kind>/<merchantId>/…`); a
|
|
965
|
+
* record has to point at it to use it. Live API (Sep 2026): the upload answers
|
|
966
|
+
* 201 `{ fileName, path }`.
|
|
967
|
+
*/
|
|
968
|
+
async function uploadImage(file, params, options = {}) {
|
|
969
|
+
if (!file || typeof file.size !== "number") throw new Error("uploadImage: file must be a File or Blob");
|
|
970
|
+
if (!isUploadKind(params?.kind)) throw new Error(`uploadImage: unknown kind "${params?.kind}"`);
|
|
971
|
+
const name = params.fileName ?? file.name ?? "upload";
|
|
972
|
+
const form = new FormData();
|
|
973
|
+
form.append(SHOPWAVE_UPLOAD.fileField, file, name);
|
|
974
|
+
form.append(SHOPWAVE_UPLOAD.kindField, params.kind);
|
|
975
|
+
const { status, body: raw } = await apiRequest(`/api/${SHOPWAVE_UPLOAD.route}`, {
|
|
976
|
+
method: "POST",
|
|
977
|
+
body: form
|
|
978
|
+
}, options);
|
|
979
|
+
const body = raw;
|
|
980
|
+
assertNoApiErrors(body, status);
|
|
981
|
+
const id = typeof body?.fileName === "string" ? body.fileName : "";
|
|
982
|
+
const path = typeof body?.path === "string" ? body.path : "";
|
|
983
|
+
if (!id) throw new ShopwaveApiError(status, `Shopwave API error (${status}): the upload response has no fileName`, { body });
|
|
984
|
+
return {
|
|
985
|
+
id,
|
|
986
|
+
url: getImageUrl(path),
|
|
987
|
+
path
|
|
988
|
+
};
|
|
989
|
+
}
|
|
990
|
+
|
|
991
|
+
//#endregion
|
|
992
|
+
//#region src/core/merchantImages.ts
|
|
993
|
+
/** The three image slots on the merchant settings page. */
|
|
994
|
+
const MERCHANT_IMAGE_SLOT_KEYS = [
|
|
995
|
+
"receipt",
|
|
996
|
+
"square",
|
|
997
|
+
"featured"
|
|
998
|
+
];
|
|
999
|
+
/**
|
|
1000
|
+
* Where each slot lives, its upload kind and its exact size (from adminV1's
|
|
1001
|
+
* merchant settings page).
|
|
1002
|
+
*/
|
|
1003
|
+
const MERCHANT_IMAGE_SLOTS = Object.freeze({
|
|
1004
|
+
receipt: {
|
|
1005
|
+
field: "logo.receipt",
|
|
1006
|
+
uploadKind: "merchant",
|
|
1007
|
+
width: 576,
|
|
1008
|
+
height: 325
|
|
1009
|
+
},
|
|
1010
|
+
square: {
|
|
1011
|
+
field: "logo.square",
|
|
1012
|
+
uploadKind: "merchant",
|
|
1013
|
+
width: 1e3,
|
|
1014
|
+
height: 1e3
|
|
1015
|
+
},
|
|
1016
|
+
featured: {
|
|
1017
|
+
field: "feature[0]",
|
|
1018
|
+
uploadKind: "merchantFeature",
|
|
1019
|
+
width: 1200,
|
|
1020
|
+
height: 600
|
|
1021
|
+
}
|
|
1022
|
+
});
|
|
1023
|
+
/**
|
|
1024
|
+
* The file name in an image value: `"http://…/logo/abc.png"` → `"abc.png"`,
|
|
1025
|
+
* `"abc.png"` → `"abc.png"`. Query strings and fragments are ignored.
|
|
1026
|
+
* Returns `null` for empty or non-string values.
|
|
1027
|
+
*/
|
|
1028
|
+
function imageFileName(value) {
|
|
1029
|
+
if (typeof value !== "string") return null;
|
|
1030
|
+
const last = value.trim().replace(/[?#].*$/, "").split("/").pop() ?? "";
|
|
1031
|
+
return last ? decodeURIComponent(last) : null;
|
|
1032
|
+
}
|
|
1033
|
+
/** The stored value for a slot (a URL when read from the API; a file name right after an upload). */
|
|
1034
|
+
function getMerchantImage(imageIds, slot) {
|
|
1035
|
+
if (!imageIds || typeof imageIds !== "object") return null;
|
|
1036
|
+
let value;
|
|
1037
|
+
if (slot === "featured") value = Array.isArray(imageIds.feature) ? imageIds.feature[0] : void 0;
|
|
1038
|
+
else {
|
|
1039
|
+
const logo = imageIds.logo;
|
|
1040
|
+
value = logo && typeof logo === "object" ? logo[slot] : void 0;
|
|
1041
|
+
}
|
|
1042
|
+
return typeof value === "string" && value.trim() ? value.trim() : null;
|
|
1043
|
+
}
|
|
1044
|
+
/**
|
|
1045
|
+
* An HTTPS URL for a slot's stored image, or `""` when the slot is empty or
|
|
1046
|
+
* holds only a file name (a fresh upload not yet saved; use the upload's `url`).
|
|
1047
|
+
*/
|
|
1048
|
+
function getMerchantImageUrl(imageIds, slot, base) {
|
|
1049
|
+
const value = getMerchantImage(imageIds, slot);
|
|
1050
|
+
if (!value || !value.includes("/")) return "";
|
|
1051
|
+
return getImageUrl(value, base);
|
|
1052
|
+
}
|
|
1053
|
+
/**
|
|
1054
|
+
* Returns a copy of `imageIds` with one slot set to `fileName` (or cleared
|
|
1055
|
+
* with `null`). Other slots and unknown keys are kept; an empty `logo` or
|
|
1056
|
+
* `feature` is removed.
|
|
1057
|
+
*/
|
|
1058
|
+
function setMerchantImage(imageIds, slot, fileName) {
|
|
1059
|
+
const next = { ...imageIds && typeof imageIds === "object" ? imageIds : {} };
|
|
1060
|
+
if (slot === "featured") {
|
|
1061
|
+
const rest = Array.isArray(next.feature) ? next.feature.slice(1) : [];
|
|
1062
|
+
const feature = fileName ? [fileName, ...rest] : rest;
|
|
1063
|
+
if (feature.length > 0) next.feature = feature;
|
|
1064
|
+
else delete next.feature;
|
|
1065
|
+
} else {
|
|
1066
|
+
const logo = { ...next.logo && typeof next.logo === "object" ? next.logo : {} };
|
|
1067
|
+
if (fileName) logo[slot] = fileName;
|
|
1068
|
+
else delete logo[slot];
|
|
1069
|
+
if (Object.keys(logo).length > 0) next.logo = logo;
|
|
1070
|
+
else delete next.logo;
|
|
1071
|
+
}
|
|
1072
|
+
return next;
|
|
1073
|
+
}
|
|
1074
|
+
function toStored(value) {
|
|
1075
|
+
if (typeof value === "string") return imageFileName(value) ?? void 0;
|
|
1076
|
+
if (Array.isArray(value)) {
|
|
1077
|
+
const items = value.map(toStored).filter((v) => v !== void 0 && v !== null && v !== "");
|
|
1078
|
+
return items.length > 0 ? items : void 0;
|
|
1079
|
+
}
|
|
1080
|
+
if (value && typeof value === "object") {
|
|
1081
|
+
const out = {};
|
|
1082
|
+
for (const [k, v] of Object.entries(value)) {
|
|
1083
|
+
const stored = toStored(v);
|
|
1084
|
+
if (stored !== void 0 && stored !== null && stored !== "") out[k] = stored;
|
|
1085
|
+
}
|
|
1086
|
+
return Object.keys(out).length > 0 ? out : void 0;
|
|
1087
|
+
}
|
|
1088
|
+
}
|
|
1089
|
+
/**
|
|
1090
|
+
* The `imageIds` to send on a save: every URL is turned back into its file
|
|
1091
|
+
* name (what adminV1 does with images you didn't change) and empty values
|
|
1092
|
+
* are dropped. No images gives `{}`.
|
|
1093
|
+
*/
|
|
1094
|
+
function toStoredImageIds(imageIds) {
|
|
1095
|
+
return toStored(imageIds) ?? {};
|
|
1096
|
+
}
|
|
1097
|
+
/**
|
|
1098
|
+
* Uploads an image for a merchant slot: fits it to the slot's size, uploads
|
|
1099
|
+
* it with the slot's kind, and returns `{ id, url, path }`. Put `id` into
|
|
1100
|
+
* `imageIds` with {@link setMerchantImage} and save with `updateMerchant`.
|
|
1101
|
+
*/
|
|
1102
|
+
async function uploadMerchantImage(file, slot, options = {}) {
|
|
1103
|
+
const def = MERCHANT_IMAGE_SLOTS[slot];
|
|
1104
|
+
if (!def) throw new Error(`uploadMerchantImage: unknown slot "${slot}"`);
|
|
1105
|
+
const { fit = true, fitOptions,...requestOptions } = options;
|
|
1106
|
+
return uploadImage(fit ? await fitImageToSize(file, def.width, def.height, fitOptions) : file, { kind: def.uploadKind }, requestOptions);
|
|
1107
|
+
}
|
|
1108
|
+
|
|
1109
|
+
//#endregion
|
|
1110
|
+
//#region src/core/merchant.ts
|
|
1111
|
+
const MERCHANT_PATH = `/api/${SHOPWAVE_RESOURCES.merchant.route}`;
|
|
1112
|
+
/** Colour keys inside `colours.primary`, in display order. */
|
|
1113
|
+
const MERCHANT_COLOUR_KEYS = [
|
|
1114
|
+
"main",
|
|
1115
|
+
"highlight",
|
|
1116
|
+
"contrast"
|
|
1117
|
+
];
|
|
1118
|
+
/** Flat link fields a form edits, in display order. */
|
|
1119
|
+
const MERCHANT_LINK_KEYS = [
|
|
1120
|
+
"website",
|
|
1121
|
+
"twitter",
|
|
1122
|
+
"facebook",
|
|
1123
|
+
"instagram"
|
|
1124
|
+
];
|
|
1125
|
+
/** Where each flat link field lives in `merchant.links`. */
|
|
1126
|
+
const MERCHANT_LINK_PATHS = Object.freeze({
|
|
1127
|
+
website: ["website", "home"],
|
|
1128
|
+
twitter: ["social", "twitter"],
|
|
1129
|
+
facebook: ["social", "facebook"],
|
|
1130
|
+
instagram: ["social", "instagram"]
|
|
1131
|
+
});
|
|
1132
|
+
function trimmed(value) {
|
|
1133
|
+
return typeof value === "string" && value.trim() ? value.trim() : void 0;
|
|
1134
|
+
}
|
|
1135
|
+
/**
|
|
1136
|
+
* Reads `merchant.links` as flat fields (`{ website, twitter, facebook,
|
|
1137
|
+
* instagram }`), whatever shape it was saved in:
|
|
1138
|
+
* - the nested shape adminV1 saves (`{ website: { home }, social: { … } }`);
|
|
1139
|
+
* - flat keys (`{ website: "…" }`, what SDK 0.4.0 pre-releases sent);
|
|
1140
|
+
* - an array in {@link MERCHANT_LINK_KEYS} order (older AdminUI versions).
|
|
1141
|
+
* Empty values are dropped.
|
|
1142
|
+
*/
|
|
1143
|
+
function merchantLinksToForm(links) {
|
|
1144
|
+
const out = {};
|
|
1145
|
+
if (Array.isArray(links)) {
|
|
1146
|
+
links.forEach((value, i) => {
|
|
1147
|
+
const key = MERCHANT_LINK_KEYS[i];
|
|
1148
|
+
const v = trimmed(value);
|
|
1149
|
+
if (key && v) out[key] = v;
|
|
1150
|
+
});
|
|
1151
|
+
return out;
|
|
1152
|
+
}
|
|
1153
|
+
if (!links || typeof links !== "object") return out;
|
|
1154
|
+
const obj = links;
|
|
1155
|
+
for (const key of MERCHANT_LINK_KEYS) {
|
|
1156
|
+
const [group, field] = MERCHANT_LINK_PATHS[key];
|
|
1157
|
+
const nested = obj[group];
|
|
1158
|
+
const v = nested && typeof nested === "object" && !Array.isArray(nested) ? trimmed(nested[field]) : trimmed(obj[key]);
|
|
1159
|
+
if (v) out[key] = v;
|
|
1160
|
+
}
|
|
1161
|
+
return out;
|
|
1162
|
+
}
|
|
1163
|
+
/**
|
|
1164
|
+
* Builds the stored `links` object from flat fields. Empty values are left
|
|
1165
|
+
* out, and so is a group with nothing in it; no links gives `{}`.
|
|
1166
|
+
*/
|
|
1167
|
+
function merchantLinksFromForm(form) {
|
|
1168
|
+
const out = {};
|
|
1169
|
+
for (const key of MERCHANT_LINK_KEYS) {
|
|
1170
|
+
const v = trimmed(form[key]);
|
|
1171
|
+
if (!v) continue;
|
|
1172
|
+
const [group, field] = MERCHANT_LINK_PATHS[key];
|
|
1173
|
+
(out[group] ??= {})[field] = v;
|
|
1174
|
+
}
|
|
1175
|
+
return out;
|
|
1176
|
+
}
|
|
1177
|
+
/** Reads any stored or older `links` value into the nested shape adminV1 saves. */
|
|
1178
|
+
function normalizeMerchantLinks(links) {
|
|
1179
|
+
return merchantLinksFromForm(merchantLinksToForm(links));
|
|
1180
|
+
}
|
|
1181
|
+
/**
|
|
1182
|
+
* Object fields of the merchant. The API keeps one you leave out, and
|
|
1183
|
+
* replaces it as a whole when you send it.
|
|
1184
|
+
*/
|
|
1185
|
+
const MERCHANT_OBJECT_FIELDS = [
|
|
1186
|
+
"colours",
|
|
1187
|
+
"links",
|
|
1188
|
+
"imageIds"
|
|
1189
|
+
];
|
|
1190
|
+
/** Fields the API sets itself; `updateMerchant` never sends them back. */
|
|
1191
|
+
const MERCHANT_READ_ONLY_FIELDS = ["createdDate", "modifiedDate"];
|
|
1192
|
+
/**
|
|
1193
|
+
* Longest values the API stores. Longer values are cut off silently
|
|
1194
|
+
* (live API, Sep 2026), so `updateMerchant` rejects them instead.
|
|
1195
|
+
* `vatNumber` fits a UK VAT number without the `GB` prefix.
|
|
1196
|
+
*/
|
|
1197
|
+
const MERCHANT_FIELD_MAX_LENGTH = Object.freeze({
|
|
1198
|
+
companyNumber: 11,
|
|
1199
|
+
vatNumber: 9
|
|
1200
|
+
});
|
|
1201
|
+
/** Returns `"<field> is longer than <n> characters"` messages for over-long fields. */
|
|
1202
|
+
function validateMerchant(merchant) {
|
|
1203
|
+
const problems = [];
|
|
1204
|
+
for (const [field, max] of Object.entries(MERCHANT_FIELD_MAX_LENGTH)) {
|
|
1205
|
+
const value = merchant[field];
|
|
1206
|
+
if (typeof value === "string" && value.length > max) problems.push(`${field} is longer than ${max} characters`);
|
|
1207
|
+
}
|
|
1208
|
+
return problems;
|
|
1209
|
+
}
|
|
1210
|
+
/**
|
|
1211
|
+
* Reads the logged-in user's merchant (a user has exactly one), or `null`
|
|
1212
|
+
* when the API returns none.
|
|
1213
|
+
*/
|
|
1214
|
+
async function fetchMerchant(options = {}) {
|
|
1215
|
+
const json = await apiGet(MERCHANT_PATH, {}, options);
|
|
1216
|
+
assertNoApiErrors(json, 200);
|
|
1217
|
+
return json?.merchant ?? null;
|
|
1218
|
+
}
|
|
1219
|
+
/**
|
|
1220
|
+
* Updates the merchant and returns it as stored.
|
|
1221
|
+
*
|
|
1222
|
+
* Shopwave's `POST /merchant` replaces the whole record: a scalar field you
|
|
1223
|
+
* leave out (`companyNumber`, `vatNumber`, `note`, …) is set to null, while
|
|
1224
|
+
* an object field you leave out (`colours`, `links`, `imageIds`) is kept and
|
|
1225
|
+
* one you send replaces the stored one; sending `{}` clears it (live API,
|
|
1226
|
+
* Sep 2026). So by default the
|
|
1227
|
+
* current merchant is read first and the patch is merged over it.
|
|
1228
|
+
*
|
|
1229
|
+
* `imageIds` is always sent as file names ({@link toStoredImageIds}), so you
|
|
1230
|
+
* can pass back what you read. See `MerchantImageIds` for the shape.
|
|
1231
|
+
*
|
|
1232
|
+
* The API answers 205 with an empty body, so the merchant is read again after
|
|
1233
|
+
* the save and that is what's returned (it shows exactly what was kept).
|
|
1234
|
+
* Throws before sending when a value is longer than the API stores
|
|
1235
|
+
* ({@link MERCHANT_FIELD_MAX_LENGTH}).
|
|
1236
|
+
*/
|
|
1237
|
+
async function updateMerchant(patch, options = {}) {
|
|
1238
|
+
const { merge = true,...requestOptions } = options;
|
|
1239
|
+
let merchant = { ...patch };
|
|
1240
|
+
if (merge) {
|
|
1241
|
+
const current = await fetchMerchant(requestOptions);
|
|
1242
|
+
if (!current) throw new ShopwaveApiError(404, "Shopwave API error (404): no merchant to update");
|
|
1243
|
+
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})`);
|
|
1244
|
+
merchant = {
|
|
1245
|
+
...current,
|
|
1246
|
+
...patch,
|
|
1247
|
+
id: current.id
|
|
1248
|
+
};
|
|
1249
|
+
for (const field of MERCHANT_OBJECT_FIELDS) if (!(field in patch)) delete merchant[field];
|
|
1250
|
+
}
|
|
1251
|
+
if (merchant.imageIds && typeof merchant.imageIds === "object") merchant.imageIds = toStoredImageIds(merchant.imageIds);
|
|
1252
|
+
if (merchant.id == null || merchant.id === "") throw new Error("merchant id is missing");
|
|
1253
|
+
for (const field of MERCHANT_READ_ONLY_FIELDS) delete merchant[field];
|
|
1254
|
+
const problems = validateMerchant(merchant);
|
|
1255
|
+
if (problems.length > 0) throw new Error(`Invalid merchant: ${problems.join("; ")}`);
|
|
1256
|
+
const { status, body: raw } = await apiRequest(MERCHANT_PATH, {
|
|
1257
|
+
method: "PUT",
|
|
1258
|
+
headers: { "Content-Type": "application/json" },
|
|
1259
|
+
body: JSON.stringify({ merchant })
|
|
1260
|
+
}, requestOptions);
|
|
1261
|
+
const body = raw;
|
|
1262
|
+
assertNoApiErrors(body, status);
|
|
1263
|
+
const echoed = body?.merchant && typeof body.merchant === "object" ? body.merchant : null;
|
|
1264
|
+
if (echoed) return {
|
|
1265
|
+
...merchant,
|
|
1266
|
+
...echoed,
|
|
1267
|
+
id: Number(echoed.id ?? merchant.id)
|
|
1268
|
+
};
|
|
1269
|
+
return await fetchMerchant(requestOptions) ?? {
|
|
1270
|
+
...merchant,
|
|
1271
|
+
id: Number(merchant.id)
|
|
1272
|
+
};
|
|
1273
|
+
}
|
|
1274
|
+
|
|
1275
|
+
//#endregion
|
|
1276
|
+
//#region src/core/user.ts
|
|
1277
|
+
/** Reads the logged-in user, or `null` when the API returns none. */
|
|
1278
|
+
async function fetchUser(options = {}) {
|
|
1279
|
+
const json = await apiGet(`/api/${SHOPWAVE_RESOURCES.user.route}`, {}, options);
|
|
1280
|
+
assertNoApiErrors(json, 200);
|
|
1281
|
+
return json?.user ?? null;
|
|
1282
|
+
}
|
|
1283
|
+
|
|
713
1284
|
//#endregion
|
|
714
1285
|
//#region src/hooks/shared.ts
|
|
715
1286
|
function toMessage(e) {
|
|
@@ -1067,6 +1638,85 @@ function useSession(options) {
|
|
|
1067
1638
|
}), [options?.baseUrl]);
|
|
1068
1639
|
}
|
|
1069
1640
|
|
|
1641
|
+
//#endregion
|
|
1642
|
+
//#region src/hooks/useMerchant.ts
|
|
1643
|
+
/**
|
|
1644
|
+
* The logged-in user's merchant, fetched on mount. `data` is `null` while
|
|
1645
|
+
* loading or when the API has no merchant.
|
|
1646
|
+
*
|
|
1647
|
+
* @example
|
|
1648
|
+
* const { data: merchant, loading, refetch } = useMerchant();
|
|
1649
|
+
*/
|
|
1650
|
+
function useMerchant(options) {
|
|
1651
|
+
return useQuery((signal) => fetchMerchant({
|
|
1652
|
+
...options,
|
|
1653
|
+
signal
|
|
1654
|
+
}), [options?.baseUrl, options?.token]);
|
|
1655
|
+
}
|
|
1656
|
+
/**
|
|
1657
|
+
* Manually-triggered merchant update (see `updateMerchant`: the patch is merged
|
|
1658
|
+
* over the current merchant by default). Resolves to the saved merchant, or
|
|
1659
|
+
* `null` on error (then `error` / `errorStatus` are set).
|
|
1660
|
+
*
|
|
1661
|
+
* @example
|
|
1662
|
+
* const { mutate: saveMerchant, loading: saving } = useUpdateMerchant();
|
|
1663
|
+
* const saved = await saveMerchant({ vatNumber: "GB123" });
|
|
1664
|
+
*/
|
|
1665
|
+
function useUpdateMerchant(options) {
|
|
1666
|
+
return useMutation((patch) => updateMerchant(patch, options), [
|
|
1667
|
+
options?.baseUrl,
|
|
1668
|
+
options?.token,
|
|
1669
|
+
options?.merge
|
|
1670
|
+
]);
|
|
1671
|
+
}
|
|
1672
|
+
|
|
1673
|
+
//#endregion
|
|
1674
|
+
//#region src/hooks/useUser.ts
|
|
1675
|
+
/**
|
|
1676
|
+
* The logged-in user, fetched on mount. `errorStatus` is 401 when logged out.
|
|
1677
|
+
*
|
|
1678
|
+
* @example
|
|
1679
|
+
* const { data: user } = useUser();
|
|
1680
|
+
*/
|
|
1681
|
+
function useUser(options) {
|
|
1682
|
+
const enabled = options?.enabled ?? true;
|
|
1683
|
+
return useQuery((signal) => fetchUser({
|
|
1684
|
+
...options,
|
|
1685
|
+
signal
|
|
1686
|
+
}), [options?.baseUrl, options?.token], enabled);
|
|
1687
|
+
}
|
|
1688
|
+
|
|
1689
|
+
//#endregion
|
|
1690
|
+
//#region src/hooks/useUploadImage.ts
|
|
1691
|
+
/**
|
|
1692
|
+
* Manually-triggered image upload. Resolves to `{ id, url }`, or `null` on
|
|
1693
|
+
* error (then `error` / `errorStatus` are set).
|
|
1694
|
+
*
|
|
1695
|
+
* @example
|
|
1696
|
+
* const { mutate: upload, loading: uploading } = useUploadImage();
|
|
1697
|
+
* const image = await upload(file, { kind: "merchant" });
|
|
1698
|
+
*/
|
|
1699
|
+
function useUploadImage(options) {
|
|
1700
|
+
return useMutation((file, params) => uploadImage(file, params, options), [options?.baseUrl, options?.token]);
|
|
1701
|
+
}
|
|
1702
|
+
/**
|
|
1703
|
+
* Manually-triggered upload for a merchant image slot (`receipt`, `square`,
|
|
1704
|
+
* `featured`): fits the image to the slot's exact size, uploads it with the
|
|
1705
|
+
* slot's kind, and resolves to `{ id, url }`. Put `id` into `imageIds` with
|
|
1706
|
+
* `setMerchantImage`.
|
|
1707
|
+
*
|
|
1708
|
+
* @example
|
|
1709
|
+
* const { mutate: upload } = useUploadMerchantImage();
|
|
1710
|
+
* const image = await upload(file, "square");
|
|
1711
|
+
*/
|
|
1712
|
+
function useUploadMerchantImage(options) {
|
|
1713
|
+
return useMutation((file, slot) => uploadMerchantImage(file, slot, options), [
|
|
1714
|
+
options?.baseUrl,
|
|
1715
|
+
options?.token,
|
|
1716
|
+
options?.fit
|
|
1717
|
+
]);
|
|
1718
|
+
}
|
|
1719
|
+
|
|
1070
1720
|
//#endregion
|
|
1071
1721
|
//#region src/hooks/useBasketReport.ts
|
|
1072
1722
|
/**
|
|
@@ -1171,5 +1821,5 @@ function useBasketReport(options) {
|
|
|
1171
1821
|
}
|
|
1172
1822
|
|
|
1173
1823
|
//#endregion
|
|
1174
|
-
export { DEFAULT_BASKET_FILTERS, DEFAULT_PAGINATION, PromotionRuleSet, SHOPWAVE_ENTITIES, ShopwaveApiError, apiDelete, apiGet, apiRequest, apiSend, assertNoApiErrors, authorizationFor, buildBasketReportQuery, buildConsumerMap, collectConsumerIds, collectProductIds, combineBasketRows, computeBasketSummary, deleteCategory, deleteEmployee, deleteEntity, deleteEntityById, deleteProduct, deletePromotion, deleteStore, fetchCategories, fetchCategory, fetchConsumer, fetchConsumers, fetchEmployee, fetchEmployees, fetchEntityById, fetchProduct, fetchProducts, fetchProductsMap, fetchPromotion, fetchPromotions, fetchReport, fetchSession, fetchStore, fetchStores, formatDateForQuery, getApiErrorMap, getApiErrors, loginPath, logout, logoutPath, parseBasketReportData, rolesById, saveCategory, saveEmployee, saveEntities, saveEntity, saveProduct, savePromotion, saveStore, submitEntity, toShopwaveApiError, useBasketReport, useCategory, useConsumer, useDelete, useEmployee, useLogout, useProduct, usePromotion, useReport, useSession, useStore, useSubmit, withToken };
|
|
1824
|
+
export { DEFAULT_BASKET_FILTERS, DEFAULT_PAGINATION, MERCHANT_COLOUR_KEYS, MERCHANT_FIELD_MAX_LENGTH, MERCHANT_IMAGE_SLOTS, MERCHANT_IMAGE_SLOT_KEYS, MERCHANT_LINK_KEYS, MERCHANT_LINK_PATHS, MERCHANT_OBJECT_FIELDS, MERCHANT_READ_ONLY_FIELDS, PromotionRuleSet, SHOPWAVE_ENTITIES, SHOPWAVE_IMAGE_BASE_URL, SHOPWAVE_RESOURCES, SHOPWAVE_UPLOAD, ShopwaveApiError, UPLOAD_KINDS, apiDelete, apiGet, apiRequest, apiSend, assertNoApiErrors, authorizationFor, buildBasketReportQuery, buildConsumerMap, collectConsumerIds, collectProductIds, combineBasketRows, computeBasketSummary, coverCrop, deleteCategory, deleteEmployee, deleteEntity, deleteEntityById, deleteProduct, deletePromotion, deleteStore, fetchCategories, fetchCategory, fetchConsumer, fetchConsumers, fetchEmployee, fetchEmployees, fetchEntityById, fetchMerchant, fetchProduct, fetchProducts, fetchProductsMap, fetchPromotion, fetchPromotions, fetchReport, fetchSession, fetchStore, fetchStores, fetchUser, findRepricedInstances, fitImageToSize, formatDateForQuery, getApiErrorMap, getApiErrors, getImageUrl, getMerchantImage, getMerchantImageUrl, imageFileName, isSameInstancePrice, isUploadKind, loginPath, logout, logoutPath, merchantLinksFromForm, merchantLinksToForm, normalizeMerchantLinks, parseBasketReportData, readImageSize, rolesById, saveCategory, saveEmployee, saveEntities, saveEntity, saveProduct, savePromotion, saveStore, setMerchantImage, submitEntity, toProductInstancesForSave, toShopwaveApiError, toStoredImageIds, updateMerchant, uploadImage, uploadMerchantImage, useBasketReport, useCategory, useConsumer, useDelete, useEmployee, useLogout, useMerchant, useProduct, usePromotion, useReport, useSession, useStore, useSubmit, useUpdateMerchant, useUploadImage, useUploadMerchantImage, useUser, validateMerchant, withToken };
|
|
1175
1825
|
//# sourceMappingURL=index.js.map
|