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