react-shopwave-connect 0.4.2 → 0.4.4

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.
@@ -350,6 +350,118 @@ async function fetchProductsMap(productIds, options = {}, batchSize = 200) {
350
350
  return result;
351
351
  }
352
352
 
353
+ //#endregion
354
+ //#region src/core/resources.ts
355
+ /**
356
+ * - merchant: `GET /merchant`; `POST /merchant` with `{ merchant: { id, … } }`
357
+ * updates it (without an `id` the API would create a second merchant, so the
358
+ * route requires one).
359
+ * - user: `GET /user` (read-only here; the API's `POST /user` invites users and
360
+ * needs the admin scope).
361
+ */
362
+ const SHOPWAVE_RESOURCES = Object.freeze({
363
+ merchant: {
364
+ route: "merchant",
365
+ key: "merchant",
366
+ upstream: "merchant",
367
+ writable: true
368
+ },
369
+ user: {
370
+ route: "user",
371
+ key: "user",
372
+ upstream: "user",
373
+ writable: false
374
+ }
375
+ });
376
+ /** `UploadKind` → the API's `contentType` value. */
377
+ const UPLOAD_KINDS = Object.freeze({
378
+ merchant: "merchant",
379
+ merchantFeature: "merchantFeature",
380
+ product: "product",
381
+ user: "user",
382
+ applicationLogo: "applicaionLogo",
383
+ applicationImages: "applicaionImages"
384
+ });
385
+ /** Every `UploadPrefix`, longest first so a name check never takes `product` for `product_thumbnail`. */
386
+ const UPLOAD_PREFIXES = Object.freeze([
387
+ "product_thumbnail",
388
+ "variant_thumbnail",
389
+ "product",
390
+ "variant"
391
+ ]);
392
+ /** How uploads are addressed (app route and Shopwave uploader). */
393
+ const SHOPWAVE_UPLOAD = Object.freeze({
394
+ route: "upload",
395
+ upstream: "uploader",
396
+ kindHeader: "contentType",
397
+ prefixHeader: "prefix",
398
+ fileField: "file",
399
+ kindField: "kind",
400
+ prefixField: "prefix"
401
+ });
402
+ function isUploadKind(value) {
403
+ return typeof value === "string" && Object.prototype.hasOwnProperty.call(UPLOAD_KINDS, value);
404
+ }
405
+ function isUploadPrefix(value) {
406
+ return typeof value === "string" && UPLOAD_PREFIXES.includes(value);
407
+ }
408
+ const SHOPWAVE_LOOKUPS = Object.freeze({
409
+ productTags: {
410
+ route: "products/tags",
411
+ key: "tags",
412
+ upstream: "product/tags"
413
+ },
414
+ productInstanceTags: {
415
+ route: "products/instance-tags",
416
+ key: "tags",
417
+ upstream: "product/instance/tags"
418
+ }
419
+ });
420
+
421
+ //#endregion
422
+ //#region src/core/productTags.ts
423
+ /**
424
+ * Turns a tag list from the API into clean strings: trims each tag, drops
425
+ * blanks and anything that isn't text, and removes exact duplicates (first one
426
+ * wins). The API's own order is kept. A map is accepted too (its values are
427
+ * used), in case the API ever answers keyed by id.
428
+ */
429
+ function normalizeTagList(value) {
430
+ const list = Array.isArray(value) ? value : value && typeof value === "object" ? Object.values(value) : [];
431
+ const seen = /* @__PURE__ */ new Set();
432
+ const out = [];
433
+ for (const item of list) {
434
+ if (typeof item !== "string" && typeof item !== "number") continue;
435
+ const tag = String(item).trim();
436
+ if (!tag || seen.has(tag)) continue;
437
+ seen.add(tag);
438
+ out.push(tag);
439
+ }
440
+ return out;
441
+ }
442
+ async function fetchLookup(kind, options) {
443
+ const def = SHOPWAVE_LOOKUPS[kind];
444
+ if (!def) throw new Error(`Unknown Shopwave lookup "${kind}"`);
445
+ const json = await apiGet(`/api/${def.route}`, {}, options);
446
+ assertNoApiErrors(json, 200);
447
+ return normalizeTagList(json?.[def.key]);
448
+ }
449
+ /**
450
+ * Every distinct tag used on the merchant's products (`GET /product/tags`),
451
+ * for a tag field's suggestions. Returns `[]` when there are none.
452
+ */
453
+ function fetchProductTags(options = {}) {
454
+ return fetchLookup("productTags", options);
455
+ }
456
+ /**
457
+ * Every distinct tag used on the merchant's price instances
458
+ * (`GET /product/instance/tags`): the channel names (Eat In, Takeout, …).
459
+ * Returns `[]` when there are none.
460
+ */
461
+ function fetchProductInstanceTags(options = {}) {
462
+ return fetchLookup("productInstanceTags", options);
463
+ }
464
+
353
465
  //#endregion
354
466
  //#region src/core/promotion.ts
355
467
  /** Promotion rule identifiers as stored by the Shopwave API. */
@@ -478,537 +590,161 @@ async function submitEntity({ endpoint, method = "POST", payload }, options = {}
478
590
  }
479
591
 
480
592
  //#endregion
481
- //#region src/core/entities.ts
593
+ //#region src/core/imageFit.ts
482
594
  /**
483
- * Addressing per entity, following the Shopwave API reference
484
- * (https://developer.merchantstack.com/api-reference.html) and checked against
485
- * the live API where noted:
486
- * - category/product/store: GET filtered by `<x>Ids`, POST upsert, DELETE with `<x>Id` → 205.
487
- * - promotion: no DELETE; promotions are never deleted, only expired. Expiring
488
- * reads the promotion and saves the whole record back with `endDate` = now (and
489
- * `startDate` = now too if it hadn't started); the live API rejects a partial
490
- * `{ id, endDate }` save with error 899. Dates are UTC `YYYY-MM-DD HH:mm:ss`.
491
- * - employee: POST updates `roleId`, `joinedDate`, `exitDate` (names can't be
492
- * changed); no DELETE (live API: "Cannot DELETE /employee") → retired via `exitDate`.
493
- * - consumer: read-only (`GET` with `ids`, comma-separated); live POST → 404.
595
+ * The centred part of a `srcWidth × srcHeight` image with the aspect ratio of
596
+ * `dstWidth × dstHeight` (like CSS `object-fit: cover`).
494
597
  */
495
- const SHOPWAVE_ENTITIES = Object.freeze({
496
- product: {
497
- route: "products",
498
- collection: "products",
499
- upstream: "product",
500
- idsHeader: "productIds",
501
- idHeader: "productId",
502
- writable: true,
503
- deleteMode: "delete"
504
- },
505
- category: {
506
- route: "categories",
507
- collection: "categories",
508
- upstream: "category",
509
- idsHeader: "categoryIds",
510
- idHeader: "categoryId",
511
- writable: true,
512
- deleteMode: "delete"
513
- },
514
- store: {
515
- route: "stores",
516
- collection: "stores",
517
- upstream: "store",
518
- idsHeader: "storeIds",
519
- idHeader: "storeId",
520
- writable: true,
521
- deleteMode: "delete"
522
- },
523
- promotion: {
524
- route: "promotions",
525
- collection: "promotions",
526
- upstream: "promotion",
527
- idsHeader: "promotionIds",
528
- idHeader: "promotionId",
529
- writable: true,
530
- deleteMode: "retire",
531
- retireField: "endDate",
532
- retireWithRecord: true,
533
- retireStartField: "startDate"
534
- },
535
- employee: {
536
- route: "employees",
537
- collection: "employees",
538
- upstream: "employee",
539
- idsHeader: "employeeIds",
540
- idHeader: "employeeId",
541
- writable: true,
542
- deleteMode: "retire",
543
- retireField: "exitDate"
544
- },
545
- consumer: {
546
- route: "consumer",
547
- collection: "consumers",
548
- upstream: "consumer",
549
- idsHeader: "ids",
550
- idHeader: "consumerId",
551
- writable: false,
552
- deleteMode: "none"
598
+ function coverCrop(srcWidth, srcHeight, dstWidth, dstHeight) {
599
+ if (![
600
+ srcWidth,
601
+ srcHeight,
602
+ dstWidth,
603
+ dstHeight
604
+ ].every((n) => Number.isFinite(n) && n > 0)) throw new Error("coverCrop: sizes must be positive numbers");
605
+ const srcRatio = srcWidth / srcHeight;
606
+ const dstRatio = dstWidth / dstHeight;
607
+ if (srcRatio > dstRatio) {
608
+ const sw = Math.round(srcHeight * dstRatio);
609
+ return {
610
+ sx: Math.round((srcWidth - sw) / 2),
611
+ sy: 0,
612
+ sw,
613
+ sh: srcHeight
614
+ };
553
615
  }
554
- });
555
- function definition(kind) {
556
- const def = SHOPWAVE_ENTITIES[kind];
557
- if (!def) throw new Error(`Unknown Shopwave entity "${kind}"`);
558
- return def;
616
+ const sh = Math.round(srcWidth / dstRatio);
617
+ return {
618
+ sx: 0,
619
+ sy: Math.round((srcHeight - sh) / 2),
620
+ sw: srcWidth,
621
+ sh
622
+ };
559
623
  }
560
- function assertId(kind, id) {
561
- const s = id == null ? "" : String(id).trim();
562
- if (!s) throw new Error(`${kind} id is missing`);
563
- return encodeURIComponent(s);
624
+ function requireBrowserImages(fn) {
625
+ if (typeof createImageBitmap !== "function") throw new Error(`${fn} needs a browser (createImageBitmap is not available)`);
564
626
  }
565
- /**
566
- * Creates or updates several entities of one kind in a single request and
567
- * returns them as saved (with their ids), in the order given.
568
- *
569
- * The request is `{ <collection>: { "0": item0, "1": item1, … } }`. Shopwave
570
- * answers 201 and echoes every entity under the ref it was sent with, so each
571
- * result is matched back by ref. Throws {@link ShopwaveApiError} when the
572
- * response carries `api.message.errors` or any ref is missing from it.
573
- *
574
- * The API's partial-success semantics for multi-entity saves haven't been
575
- * confirmed yet; single saves (`saveProduct` etc.) are the tested path.
576
- */
577
- async function saveEntities(kind, items, options = {}) {
578
- const def = definition(kind);
579
- if (items.length === 0) return [];
580
- const refs = items.map((_, i) => String(i));
581
- const payload = { [def.collection]: Object.fromEntries(refs.map((ref, i) => [ref, items[i]])) };
582
- const { status, body: raw } = await apiRequest(`/api/${def.route}`, {
583
- method: "POST",
584
- headers: { "Content-Type": "application/json" },
585
- body: JSON.stringify(payload)
586
- }, options);
587
- const body = raw;
588
- assertNoApiErrors(body, status);
589
- const echoed = body?.[def.collection] ?? {};
590
- return refs.map((ref, i) => {
591
- const saved = echoed[ref];
592
- if (!saved || saved.id == null) throw new ShopwaveApiError(status, `Shopwave API error (${status}): the saved ${kind} (ref "${ref}") was not returned`, { body });
627
+ /** Reads an image file's pixel size (browser only). */
628
+ async function readImageSize(file) {
629
+ requireBrowserImages("readImageSize");
630
+ const bitmap = await createImageBitmap(file);
631
+ try {
593
632
  return {
594
- ...items[i],
595
- ...saved,
596
- id: Number(saved.id)
633
+ width: bitmap.width,
634
+ height: bitmap.height
597
635
  };
598
- });
599
- }
600
- /** Creates (no `id`) or updates (with `id`) one entity and returns it with its id. */
601
- async function saveEntity(kind, item, options = {}) {
602
- const [saved] = await saveEntities(kind, [item], options);
603
- return saved;
604
- }
605
- /**
606
- * Deletes one entity (a soft delete: it stays readable with `deleted: true`).
607
- * Employees and promotions can't be deleted in Shopwave; for them the route
608
- * sets `exitDate` / `endDate` to now instead (see `SHOPWAVE_ENTITIES`), and a
609
- * promotion is saved back whole (see {@link deletePromotion}).
610
- *
611
- * Shopwave answers 205 with an empty body — also for ids that don't exist — so
612
- * a resolved promise means "the API accepted the request", not "a record was
613
- * deleted".
614
- */
615
- async function deleteEntityById(kind, id, options = {}) {
616
- await apiDelete(`/api/${definition(kind).route}/${assertId(kind, id)}`, options);
617
- }
618
- /** Reads one entity by id, or `null` when there's no such (non-deleted) record. */
619
- async function fetchEntityById(kind, id, params = {}, options = {}) {
620
- const def = definition(kind);
621
- const body = await apiGet(`/api/${def.route}/${assertId(kind, id)}`, { deleted: params.deleted ?? false }, options);
622
- assertNoApiErrors(body, 200);
623
- const map = body?.[def.collection] ?? {};
624
- return map[String(id)] ?? Object.values(map).find((e) => String(e?.id) === String(id)) ?? null;
636
+ } finally {
637
+ bitmap.close?.();
638
+ }
625
639
  }
626
640
  /**
627
- * Creates (no `id`) or updates (with `id`) a product.
628
- *
629
- * Shopwave instances (prices) can't be updated, only replaced. Build
630
- * `instances` with {@link toProductInstancesForSave} (passing the product as last
631
- * read) so an edited price is sent as a new instance. As a safeguard, a new
632
- * product (no `id`, e.g. a duplicate) never sends instance ids: an id copied from
633
- * another product would otherwise point the save at that product's instances.
641
+ * Returns the image at exactly `width × height`: scaled and centre-cropped
642
+ * (never stretched). Browser only. The result is a `File` named like the
643
+ * input, with the output type's extension.
634
644
  */
635
- const saveProduct = (product, options) => {
636
- return saveEntity("product", (product.id == null || String(product.id).trim() === "") && product.instances != null ? {
637
- ...product,
638
- instances: toProductInstancesForSave(product.instances)
639
- } : product, options);
640
- };
641
- const deleteProduct = (id, options) => deleteEntityById("product", id, options);
642
- const fetchProduct = (id, params, options) => fetchEntityById("product", id, params, options);
643
- const saveCategory = (category, options) => saveEntity("category", category, options);
644
- const deleteCategory = (id, options) => deleteEntityById("category", id, options);
645
- const fetchCategory = (id, params, options) => fetchEntityById("category", id, params, options);
646
- const saveStore = (store, options) => saveEntity("store", store, options);
647
- const deleteStore = (id, options) => deleteEntityById("store", id, options);
648
- const fetchStore = (id, params, options) => fetchEntityById("store", id, params, options);
649
- const savePromotion = (promotion, options) => saveEntity("promotion", promotion, options);
645
+ async function fitImageToSize(file, width, height, options = {}) {
646
+ requireBrowserImages("fitImageToSize");
647
+ const { type = "image/png", quality, keepIfExact = true } = options;
648
+ const name = file.name || "image";
649
+ const ext = type === "image/jpeg" ? "jpg" : type.split("/")[1];
650
+ const outName = `${name.replace(/\.[^.]+$/, "")}.${ext}`;
651
+ const bitmap = await createImageBitmap(file);
652
+ try {
653
+ if (keepIfExact && bitmap.width === width && bitmap.height === height && file.type === type) return file instanceof File ? file : new File([file], outName, { type });
654
+ const { sx, sy, sw, sh } = coverCrop(bitmap.width, bitmap.height, width, height);
655
+ let blob;
656
+ if (typeof OffscreenCanvas === "function") {
657
+ const canvas = new OffscreenCanvas(width, height);
658
+ const ctx = canvas.getContext("2d");
659
+ if (!ctx) throw new Error("fitImageToSize: no 2D canvas context");
660
+ ctx.imageSmoothingQuality = "high";
661
+ ctx.drawImage(bitmap, sx, sy, sw, sh, 0, 0, width, height);
662
+ blob = await canvas.convertToBlob({
663
+ type,
664
+ quality
665
+ });
666
+ } else {
667
+ const canvas = document.createElement("canvas");
668
+ canvas.width = width;
669
+ canvas.height = height;
670
+ const ctx = canvas.getContext("2d");
671
+ if (!ctx) throw new Error("fitImageToSize: no 2D canvas context");
672
+ ctx.imageSmoothingQuality = "high";
673
+ ctx.drawImage(bitmap, sx, sy, sw, sh, 0, 0, width, height);
674
+ blob = await new Promise((resolve, reject) => canvas.toBlob((b) => b ? resolve(b) : reject(/* @__PURE__ */ new Error("fitImageToSize: encoding failed")), type, quality));
675
+ }
676
+ return new File([blob], outName, { type });
677
+ } finally {
678
+ bitmap.close?.();
679
+ }
680
+ }
681
+
682
+ //#endregion
683
+ //#region src/core/upload.ts
650
684
  /**
651
- * Expires a promotion (Shopwave never deletes promotions). The route reads the
652
- * promotion and saves it back with `endDate` set to now; a promotion that hasn't
653
- * started yet gets `startDate` = `endDate` = now. Rejects if the promotion doesn't
654
- * exist or the save fails.
685
+ * HTTPS host that serves the Shopwave CDN's images. The API returns
686
+ * `http://static.merchantstack.com/images/…`, which has no HTTPS endpoint
687
+ * (checked Sep 2026), so pages served over HTTPS can't show it.
655
688
  */
656
- const deletePromotion = (id, options) => deleteEntityById("promotion", id, options);
657
- const fetchPromotion = (id, params, options) => fetchEntityById("promotion", id, params, options);
689
+ const SHOPWAVE_IMAGE_BASE_URL = "https://s3-eu-west-1.amazonaws.com/static.merchantstack.com/images";
690
+ const STATIC_HOST = /^https?:\/\/static\.merchantstack\.com\/images\//i;
658
691
  /**
659
- * Creates an employee, or updates one (with `id`). On update Shopwave only
660
- * applies `roleId`, `joinedDate` and `exitDate` (and store roles); names and
661
- * email can't be changed, and the echo only carries the updated fields — re-read
662
- * with `fetchEmployee` if you need the stored record.
692
+ * Turns an image path from the API into a URL a page can load over HTTPS:
693
+ * `http://static.merchantstack.com/images/x.png` → `<base>/x.png`, and a
694
+ * relative path (`merchant/5644/logo/x.png`) → `<base>/merchant/5644/logo/x.png`.
695
+ * Other absolute URLs are returned unchanged; empty input gives `""`.
663
696
  */
664
- const saveEmployee = (employee, options) => saveEntity("employee", employee, options);
665
- /** Retires an employee: Shopwave has no employee DELETE, so this sets `exitDate` to now. */
666
- const deleteEmployee = (id, options) => deleteEntityById("employee", id, options);
667
- const fetchEmployee = (id, params, options) => fetchEntityById("employee", id, params, options);
668
- const fetchConsumer = (id, params, options) => fetchEntityById("consumer", id, params, options);
669
-
670
- //#endregion
671
- //#region src/core/basket.ts
672
- const DEFAULT_BASKET_FILTERS = {
673
- search: "",
674
- dateRange: {
675
- start: null,
676
- end: null
677
- },
678
- consumerId: null,
679
- status: "all"
680
- };
681
- const DEFAULT_PAGINATION = {
682
- page: 0,
683
- pageSize: 25,
684
- total: 0
685
- };
686
- /** Formats a date as `YYYY-MM-DD HH:mm:ss` for the report query. */
687
- function formatDateForQuery(date, isEndOfDay = false) {
688
- return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")} ${isEndOfDay ? "23:59:59" : "00:00:00"}`;
689
- }
690
- /** Builds the `Basket` report query from a set of filters. */
691
- function buildBasketReportQuery(filters) {
692
- const whereConditions = [];
693
- const today = /* @__PURE__ */ new Date();
694
- const startDate = filters.dateRange.start ?? today;
695
- const endDate = filters.dateRange.end ?? today;
696
- whereConditions.push(`Basket.completeDate > '${formatDateForQuery(startDate, false)}'`);
697
- whereConditions.push(`Basket.completeDate < '${formatDateForQuery(endDate, true)}'`);
698
- if (filters.consumerId) whereConditions.push(`Basket.consumerId = ${filters.consumerId}`);
699
- if (filters.status !== "all") whereConditions.push(`Basket.status = '${filters.status}'`);
700
- return { baskets: {
701
- FROM: "Basket",
702
- WHERE: whereConditions.length > 0 ? { AND: whereConditions } : void 0
703
- } };
704
- }
705
- /** Flattens the raw report rows/keys into structured baskets. */
706
- function parseBasketReportData(reports) {
707
- if (!reports?.baskets?.data || !reports?.baskets?.keys) return [];
708
- const { keys, data } = reports.baskets;
709
- const keyIndices = {};
710
- keys.forEach((key, index) => {
711
- keyIndices[key.name] = index;
712
- });
713
- const productKey = keys.find((k) => k.name === "Basket.Product");
714
- const productSubKeys = {};
715
- if (productKey?.item) productKey.item.forEach((subKey, index) => {
716
- productSubKeys[subKey.name] = index;
717
- });
718
- return data.map((row) => {
719
- const products = (row[keyIndices["Basket.Product"]] || []).map((productRow) => ({
720
- productId: productRow[productSubKeys["Basket.Product.productId"]],
721
- productName: `Product #${productRow[productSubKeys["Basket.Product.productId"]]}`,
722
- quantity: productRow[productSubKeys["Basket.Product.quantity"]] || 1,
723
- price: productRow[productSubKeys["Basket.Product.productPrice"]] || 0,
724
- tax: productRow[productSubKeys["Basket.Product.productTaxPercentage"]] || 0
725
- }));
726
- const total = products.reduce((sum, p) => sum + p.price * p.quantity, 0);
727
- const taxTotal = products.reduce((sum, p) => sum + p.price * p.quantity * p.tax, 0);
728
- const completeDateTimestamp = row[keyIndices["Basket.completeDate"]];
729
- const completeDate = completeDateTimestamp ? new Date(completeDateTimestamp).toISOString() : "";
730
- return {
731
- id: row[keyIndices["Basket.id"]],
732
- name: row[keyIndices["Basket.name"]],
733
- consumerId: row[keyIndices["Basket.consumerId"]],
734
- products,
735
- total,
736
- taxTotal,
737
- status: "completed",
738
- completeDate
739
- };
740
- });
741
- }
742
- /** Unique non-null consumer ids referenced by a set of baskets. */
743
- function collectConsumerIds(baskets) {
744
- if (!baskets.length) return null;
745
- const ids = baskets.map((b) => b.consumerId).filter((id) => id != null);
746
- return ids.length > 0 ? [...new Set(ids)] : null;
747
- }
748
- /** Unique product ids referenced by a set of baskets. */
749
- function collectProductIds(baskets) {
750
- if (!baskets.length) return null;
751
- const ids = /* @__PURE__ */ new Set();
752
- baskets.forEach((basket) => {
753
- basket.products.forEach((product) => {
754
- if (product.productId) ids.add(product.productId);
755
- });
756
- });
757
- return ids.size > 0 ? [...ids] : null;
758
- }
759
- /** Joins baskets with consumer + product lookups, applies search, sorts. */
760
- function combineBasketRows({ baskets, consumerMap, productMap, search }) {
761
- if (!baskets.length) return [];
762
- let combinedRows = baskets.map((basket) => {
763
- const consumer = basket.consumerId ? consumerMap[basket.consumerId] : null;
764
- const productsWithNames = basket.products.map((p) => {
765
- const product = productMap[p.productId];
766
- return {
767
- ...p,
768
- productName: product?.name || `Product #${p.productId}`
769
- };
770
- });
771
- return {
772
- id: basket.id,
773
- basketId: basket.id,
774
- basketName: basket.name || `Basket #${basket.id}`,
775
- consumerId: basket.consumerId,
776
- consumerName: consumer ? `${consumer.firstName} ${consumer.lastName}` : "Unknown",
777
- consumerEmail: consumer?.email || "-",
778
- products: productsWithNames,
779
- basketTotal: (basket.total || 0) / 100,
780
- tax: basket.taxTotal || 0,
781
- dateTime: basket.completeDate,
782
- status: basket.status || "pending"
783
- };
784
- });
785
- if (search) {
786
- const searchLower = search.toLowerCase();
787
- combinedRows = combinedRows.filter((row) => row.basketId.toString().includes(searchLower) || row.basketName.toLowerCase().includes(searchLower) || row.consumerName.toLowerCase().includes(searchLower) || row.consumerEmail.toLowerCase().includes(searchLower));
788
- }
789
- combinedRows.sort((a, b) => {
790
- const dateA = new Date(a.dateTime).getTime();
791
- return new Date(b.dateTime).getTime() - dateA;
792
- });
793
- return combinedRows;
697
+ function getImageUrl(path, base = SHOPWAVE_IMAGE_BASE_URL) {
698
+ if (!path) return "";
699
+ const root = base.replace(/\/+$/, "");
700
+ if (STATIC_HOST.test(path)) return `${root}/${path.replace(STATIC_HOST, "")}`;
701
+ if (/^[a-z][a-z0-9+.-]*:/i.test(path) || path.startsWith("//")) return path;
702
+ return `${root}/${path.replace(/^\/+/, "")}`;
794
703
  }
795
- /** Aggregate totals for a set of report rows. */
796
- function computeBasketSummary(rows) {
797
- const uniqueConsumerIds = new Set(rows.map((row) => row.consumerId));
704
+ /**
705
+ * Uploads one image to the Shopwave CDN through the app's `/api/upload` route
706
+ * (`createShopwaveApi(...).upload()`), and returns its id and URL.
707
+ *
708
+ * The file only lands on the CDN (under `…/images/<kind>/<merchantId>/…`); a
709
+ * record has to point at it to use it. Live API (Sep 2026): the upload answers
710
+ * 201 `{ fileName, path }`.
711
+ */
712
+ async function uploadImage(file, params, options = {}) {
713
+ if (!file || typeof file.size !== "number") throw new Error("uploadImage: file must be a File or Blob");
714
+ if (!isUploadKind(params?.kind)) throw new Error(`uploadImage: unknown kind "${params?.kind}"`);
715
+ if (params.prefix != null && !isUploadPrefix(params.prefix)) throw new Error(`uploadImage: unknown prefix "${params.prefix}"`);
716
+ const name = params.fileName ?? file.name ?? "upload";
717
+ const form = new FormData();
718
+ form.append(SHOPWAVE_UPLOAD.fileField, file, name);
719
+ form.append(SHOPWAVE_UPLOAD.kindField, params.kind);
720
+ if (params.prefix != null) form.append(SHOPWAVE_UPLOAD.prefixField, params.prefix);
721
+ const { status, body: raw } = await apiRequest(`/api/${SHOPWAVE_UPLOAD.route}`, {
722
+ method: "POST",
723
+ body: form
724
+ }, options);
725
+ const body = raw;
726
+ assertNoApiErrors(body, status);
727
+ const id = typeof body?.fileName === "string" ? body.fileName : "";
728
+ const path = typeof body?.path === "string" ? body.path : "";
729
+ if (!id) throw new ShopwaveApiError(status, `Shopwave API error (${status}): the upload response has no fileName`, { body });
798
730
  return {
799
- totalBaskets: rows.length,
800
- totalRevenue: rows.reduce((sum, row) => sum + row.basketTotal, 0),
801
- totalTax: rows.reduce((sum, row) => sum + row.tax, 0),
802
- uniqueConsumers: uniqueConsumerIds.size
731
+ id,
732
+ url: getImageUrl(path),
733
+ path
803
734
  };
804
735
  }
805
- /** Builds a consumer id → consumer lookup. */
806
- function buildConsumerMap(consumers) {
807
- const map = {};
808
- if (consumers) consumers.forEach((consumer) => {
809
- map[consumer.id] = consumer;
810
- });
811
- return map;
812
- }
813
736
 
814
737
  //#endregion
815
- //#region src/core/resources.ts
738
+ //#region src/core/merchantImages.ts
739
+ /** The three image slots on the merchant settings page. */
740
+ const MERCHANT_IMAGE_SLOT_KEYS = [
741
+ "receipt",
742
+ "square",
743
+ "featured"
744
+ ];
816
745
  /**
817
- * - merchant: `GET /merchant`; `POST /merchant` with `{ merchant: { id, … } }`
818
- * updates it (without an `id` the API would create a second merchant, so the
819
- * route requires one).
820
- * - user: `GET /user` (read-only here; the API's `POST /user` invites users and
821
- * needs the admin scope).
822
- */
823
- const SHOPWAVE_RESOURCES = Object.freeze({
824
- merchant: {
825
- route: "merchant",
826
- key: "merchant",
827
- upstream: "merchant",
828
- writable: true
829
- },
830
- user: {
831
- route: "user",
832
- key: "user",
833
- upstream: "user",
834
- writable: false
835
- }
836
- });
837
- /** `UploadKind` → the API's `contentType` value. */
838
- const UPLOAD_KINDS = Object.freeze({
839
- merchant: "merchant",
840
- merchantFeature: "merchantFeature",
841
- product: "product",
842
- user: "user",
843
- applicationLogo: "applicaionLogo",
844
- applicationImages: "applicaionImages"
845
- });
846
- /** How uploads are addressed (app route and Shopwave uploader). */
847
- const SHOPWAVE_UPLOAD = Object.freeze({
848
- route: "upload",
849
- upstream: "uploader",
850
- kindHeader: "contentType",
851
- fileField: "file",
852
- kindField: "kind"
853
- });
854
- function isUploadKind(value) {
855
- return typeof value === "string" && Object.prototype.hasOwnProperty.call(UPLOAD_KINDS, value);
856
- }
857
-
858
- //#endregion
859
- //#region src/core/imageFit.ts
860
- /**
861
- * The centred part of a `srcWidth × srcHeight` image with the aspect ratio of
862
- * `dstWidth × dstHeight` (like CSS `object-fit: cover`).
863
- */
864
- function coverCrop(srcWidth, srcHeight, dstWidth, dstHeight) {
865
- if (![
866
- srcWidth,
867
- srcHeight,
868
- dstWidth,
869
- dstHeight
870
- ].every((n) => Number.isFinite(n) && n > 0)) throw new Error("coverCrop: sizes must be positive numbers");
871
- const srcRatio = srcWidth / srcHeight;
872
- const dstRatio = dstWidth / dstHeight;
873
- if (srcRatio > dstRatio) {
874
- const sw = Math.round(srcHeight * dstRatio);
875
- return {
876
- sx: Math.round((srcWidth - sw) / 2),
877
- sy: 0,
878
- sw,
879
- sh: srcHeight
880
- };
881
- }
882
- const sh = Math.round(srcWidth / dstRatio);
883
- return {
884
- sx: 0,
885
- sy: Math.round((srcHeight - sh) / 2),
886
- sw: srcWidth,
887
- sh
888
- };
889
- }
890
- function requireBrowserImages(fn) {
891
- if (typeof createImageBitmap !== "function") throw new Error(`${fn} needs a browser (createImageBitmap is not available)`);
892
- }
893
- /** Reads an image file's pixel size (browser only). */
894
- async function readImageSize(file) {
895
- requireBrowserImages("readImageSize");
896
- const bitmap = await createImageBitmap(file);
897
- try {
898
- return {
899
- width: bitmap.width,
900
- height: bitmap.height
901
- };
902
- } finally {
903
- bitmap.close?.();
904
- }
905
- }
906
- /**
907
- * Returns the image at exactly `width × height`: scaled and centre-cropped
908
- * (never stretched). Browser only. The result is a `File` named like the
909
- * input, with the output type's extension.
910
- */
911
- async function fitImageToSize(file, width, height, options = {}) {
912
- requireBrowserImages("fitImageToSize");
913
- const { type = "image/png", quality, keepIfExact = true } = options;
914
- const name = file.name || "image";
915
- const ext = type === "image/jpeg" ? "jpg" : type.split("/")[1];
916
- const outName = `${name.replace(/\.[^.]+$/, "")}.${ext}`;
917
- const bitmap = await createImageBitmap(file);
918
- try {
919
- if (keepIfExact && bitmap.width === width && bitmap.height === height && file.type === type) return file instanceof File ? file : new File([file], outName, { type });
920
- const { sx, sy, sw, sh } = coverCrop(bitmap.width, bitmap.height, width, height);
921
- let blob;
922
- if (typeof OffscreenCanvas === "function") {
923
- const canvas = new OffscreenCanvas(width, 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 canvas.convertToBlob({
929
- type,
930
- quality
931
- });
932
- } else {
933
- const canvas = document.createElement("canvas");
934
- canvas.width = width;
935
- canvas.height = height;
936
- const ctx = canvas.getContext("2d");
937
- if (!ctx) throw new Error("fitImageToSize: no 2D canvas context");
938
- ctx.imageSmoothingQuality = "high";
939
- ctx.drawImage(bitmap, sx, sy, sw, sh, 0, 0, width, height);
940
- blob = await new Promise((resolve, reject) => canvas.toBlob((b) => b ? resolve(b) : reject(/* @__PURE__ */ new Error("fitImageToSize: encoding failed")), type, quality));
941
- }
942
- return new File([blob], outName, { type });
943
- } finally {
944
- bitmap.close?.();
945
- }
946
- }
947
-
948
- //#endregion
949
- //#region src/core/upload.ts
950
- /**
951
- * HTTPS host that serves the Shopwave CDN's images. The API returns
952
- * `http://static.merchantstack.com/images/…`, which has no HTTPS endpoint
953
- * (checked Sep 2026), so pages served over HTTPS can't show it.
954
- */
955
- const SHOPWAVE_IMAGE_BASE_URL = "https://s3-eu-west-1.amazonaws.com/static.merchantstack.com/images";
956
- const STATIC_HOST = /^https?:\/\/static\.merchantstack\.com\/images\//i;
957
- /**
958
- * Turns an image path from the API into a URL a page can load over HTTPS:
959
- * `http://static.merchantstack.com/images/x.png` → `<base>/x.png`, and a
960
- * relative path (`merchant/5644/logo/x.png`) → `<base>/merchant/5644/logo/x.png`.
961
- * Other absolute URLs are returned unchanged; empty input gives `""`.
962
- */
963
- function getImageUrl(path, base = SHOPWAVE_IMAGE_BASE_URL) {
964
- if (!path) return "";
965
- const root = base.replace(/\/+$/, "");
966
- if (STATIC_HOST.test(path)) return `${root}/${path.replace(STATIC_HOST, "")}`;
967
- if (/^[a-z][a-z0-9+.-]*:/i.test(path) || path.startsWith("//")) return path;
968
- return `${root}/${path.replace(/^\/+/, "")}`;
969
- }
970
- /**
971
- * Uploads one image to the Shopwave CDN through the app's `/api/upload` route
972
- * (`createShopwaveApi(...).upload()`), and returns its id and URL.
973
- *
974
- * The file only lands on the CDN (under `…/images/<kind>/<merchantId>/…`); a
975
- * record has to point at it to use it. Live API (Sep 2026): the upload answers
976
- * 201 `{ fileName, path }`.
977
- */
978
- async function uploadImage(file, params, options = {}) {
979
- if (!file || typeof file.size !== "number") throw new Error("uploadImage: file must be a File or Blob");
980
- if (!isUploadKind(params?.kind)) throw new Error(`uploadImage: unknown kind "${params?.kind}"`);
981
- const name = params.fileName ?? file.name ?? "upload";
982
- const form = new FormData();
983
- form.append(SHOPWAVE_UPLOAD.fileField, file, name);
984
- form.append(SHOPWAVE_UPLOAD.kindField, params.kind);
985
- const { status, body: raw } = await apiRequest(`/api/${SHOPWAVE_UPLOAD.route}`, {
986
- method: "POST",
987
- body: form
988
- }, options);
989
- const body = raw;
990
- assertNoApiErrors(body, status);
991
- const id = typeof body?.fileName === "string" ? body.fileName : "";
992
- const path = typeof body?.path === "string" ? body.path : "";
993
- if (!id) throw new ShopwaveApiError(status, `Shopwave API error (${status}): the upload response has no fileName`, { body });
994
- return {
995
- id,
996
- url: getImageUrl(path),
997
- path
998
- };
999
- }
1000
-
1001
- //#endregion
1002
- //#region src/core/merchantImages.ts
1003
- /** The three image slots on the merchant settings page. */
1004
- const MERCHANT_IMAGE_SLOT_KEYS = [
1005
- "receipt",
1006
- "square",
1007
- "featured"
1008
- ];
1009
- /**
1010
- * Where each slot lives, its upload kind and its exact size (from adminV1's
1011
- * merchant settings page).
746
+ * Where each slot lives, its upload kind and its exact size (from adminV1's
747
+ * merchant settings page).
1012
748
  */
1013
749
  const MERCHANT_IMAGE_SLOTS = Object.freeze({
1014
750
  receipt: {
@@ -1116,6 +852,382 @@ async function uploadMerchantImage(file, slot, options = {}) {
1116
852
  return uploadImage(fit ? await fitImageToSize(file, def.width, def.height, fitOptions) : file, { kind: def.uploadKind }, requestOptions);
1117
853
  }
1118
854
 
855
+ //#endregion
856
+ //#region src/core/productImages.ts
857
+ /**
858
+ * Product images, as the live API stores them (merchant 5644, 4 Nov 2026):
859
+ * - A product's `images` is a list. **Reads return full URLs**
860
+ * (`http://static.merchantstack.com/images/merchant/<id>/product/<file>`);
861
+ * **writes take the uploader's file names** ({@link toStoredProductImages};
862
+ * `saveProduct` does this for you).
863
+ * - The uploader takes one file per request. With a `prefix` (see
864
+ * `UploadPrefix`) it names the file `<prefix>_<hash>.<ext>`
865
+ * (`product_thumbnail_1bdd…41090b.png`); without one, `<hash>.<ext>`. So an
866
+ * image's role can be read back from its name ({@link productImageRole}).
867
+ */
868
+ /**
869
+ * The role in an image's file name or URL, from the uploader's `prefix`:
870
+ * `"…/product_thumbnail_1bdd.png"` → `"product_thumbnail"`. `null` for a name
871
+ * without one (images uploaded without a prefix, e.g. before prefixes existed).
872
+ */
873
+ function productImageRole(value) {
874
+ const name = imageFileName(value);
875
+ if (!name) return null;
876
+ return UPLOAD_PREFIXES.find((prefix) => name.startsWith(`${prefix}_`)) ?? null;
877
+ }
878
+ /**
879
+ * A product's `images` as the API takes them on a save: file names, not the
880
+ * URLs a read returns. Non-strings, blanks and duplicates are dropped; the
881
+ * order is kept.
882
+ */
883
+ function toStoredProductImages(images) {
884
+ if (!Array.isArray(images)) return [];
885
+ const names = images.map(imageFileName).filter((name) => Boolean(name));
886
+ return Array.from(new Set(names));
887
+ }
888
+
889
+ //#endregion
890
+ //#region src/core/entities.ts
891
+ /**
892
+ * Addressing per entity, following the Shopwave API reference
893
+ * (https://developer.merchantstack.com/api-reference.html) and checked against
894
+ * the live API where noted:
895
+ * - category/product/store: GET filtered by `<x>Ids`, POST upsert, DELETE with `<x>Id` → 205.
896
+ * - promotion: no DELETE; promotions are never deleted, only expired. Expiring
897
+ * reads the promotion and saves the whole record back with `endDate` = now (and
898
+ * `startDate` = now too if it hadn't started); the live API rejects a partial
899
+ * `{ id, endDate }` save with error 899. Dates are UTC `YYYY-MM-DD HH:mm:ss`.
900
+ * - employee: POST updates `roleId`, `joinedDate`, `exitDate` (names can't be
901
+ * changed); no DELETE (live API: "Cannot DELETE /employee") → retired via `exitDate`.
902
+ * - consumer: read-only (`GET` with `ids`, comma-separated); live POST → 404.
903
+ */
904
+ const SHOPWAVE_ENTITIES = Object.freeze({
905
+ product: {
906
+ route: "products",
907
+ collection: "products",
908
+ upstream: "product",
909
+ idsHeader: "productIds",
910
+ idHeader: "productId",
911
+ writable: true,
912
+ deleteMode: "delete"
913
+ },
914
+ category: {
915
+ route: "categories",
916
+ collection: "categories",
917
+ upstream: "category",
918
+ idsHeader: "categoryIds",
919
+ idHeader: "categoryId",
920
+ writable: true,
921
+ deleteMode: "delete"
922
+ },
923
+ store: {
924
+ route: "stores",
925
+ collection: "stores",
926
+ upstream: "store",
927
+ idsHeader: "storeIds",
928
+ idHeader: "storeId",
929
+ writable: true,
930
+ deleteMode: "delete"
931
+ },
932
+ promotion: {
933
+ route: "promotions",
934
+ collection: "promotions",
935
+ upstream: "promotion",
936
+ idsHeader: "promotionIds",
937
+ idHeader: "promotionId",
938
+ writable: true,
939
+ deleteMode: "retire",
940
+ retireField: "endDate",
941
+ retireWithRecord: true,
942
+ retireStartField: "startDate"
943
+ },
944
+ employee: {
945
+ route: "employees",
946
+ collection: "employees",
947
+ upstream: "employee",
948
+ idsHeader: "employeeIds",
949
+ idHeader: "employeeId",
950
+ writable: true,
951
+ deleteMode: "retire",
952
+ retireField: "exitDate"
953
+ },
954
+ consumer: {
955
+ route: "consumer",
956
+ collection: "consumers",
957
+ upstream: "consumer",
958
+ idsHeader: "ids",
959
+ idHeader: "consumerId",
960
+ writable: false,
961
+ deleteMode: "none"
962
+ }
963
+ });
964
+ function definition(kind) {
965
+ const def = SHOPWAVE_ENTITIES[kind];
966
+ if (!def) throw new Error(`Unknown Shopwave entity "${kind}"`);
967
+ return def;
968
+ }
969
+ function assertId(kind, id) {
970
+ const s = id == null ? "" : String(id).trim();
971
+ if (!s) throw new Error(`${kind} id is missing`);
972
+ return encodeURIComponent(s);
973
+ }
974
+ /**
975
+ * Creates or updates several entities of one kind in a single request and
976
+ * returns them as saved (with their ids), in the order given.
977
+ *
978
+ * The request is `{ <collection>: { "0": item0, "1": item1, … } }`. Shopwave
979
+ * answers 201 and echoes every entity under the ref it was sent with, so each
980
+ * result is matched back by ref. Throws {@link ShopwaveApiError} when the
981
+ * response carries `api.message.errors` or any ref is missing from it.
982
+ *
983
+ * The API's partial-success semantics for multi-entity saves haven't been
984
+ * confirmed yet; single saves (`saveProduct` etc.) are the tested path.
985
+ */
986
+ async function saveEntities(kind, items, options = {}) {
987
+ const def = definition(kind);
988
+ if (items.length === 0) return [];
989
+ const refs = items.map((_, i) => String(i));
990
+ const payload = { [def.collection]: Object.fromEntries(refs.map((ref, i) => [ref, items[i]])) };
991
+ const { status, body: raw } = await apiRequest(`/api/${def.route}`, {
992
+ method: "POST",
993
+ headers: { "Content-Type": "application/json" },
994
+ body: JSON.stringify(payload)
995
+ }, options);
996
+ const body = raw;
997
+ assertNoApiErrors(body, status);
998
+ const echoed = body?.[def.collection] ?? {};
999
+ return refs.map((ref, i) => {
1000
+ const saved = echoed[ref];
1001
+ if (!saved || saved.id == null) throw new ShopwaveApiError(status, `Shopwave API error (${status}): the saved ${kind} (ref "${ref}") was not returned`, { body });
1002
+ return {
1003
+ ...items[i],
1004
+ ...saved,
1005
+ id: Number(saved.id)
1006
+ };
1007
+ });
1008
+ }
1009
+ /** Creates (no `id`) or updates (with `id`) one entity and returns it with its id. */
1010
+ async function saveEntity(kind, item, options = {}) {
1011
+ const [saved] = await saveEntities(kind, [item], options);
1012
+ return saved;
1013
+ }
1014
+ /**
1015
+ * Deletes one entity (a soft delete: it stays readable with `deleted: true`).
1016
+ * Employees and promotions can't be deleted in Shopwave; for them the route
1017
+ * sets `exitDate` / `endDate` to now instead (see `SHOPWAVE_ENTITIES`), and a
1018
+ * promotion is saved back whole (see {@link deletePromotion}).
1019
+ *
1020
+ * Shopwave answers 205 with an empty body — also for ids that don't exist — so
1021
+ * a resolved promise means "the API accepted the request", not "a record was
1022
+ * deleted".
1023
+ */
1024
+ async function deleteEntityById(kind, id, options = {}) {
1025
+ await apiDelete(`/api/${definition(kind).route}/${assertId(kind, id)}`, options);
1026
+ }
1027
+ /** Reads one entity by id, or `null` when there's no such (non-deleted) record. */
1028
+ async function fetchEntityById(kind, id, params = {}, options = {}) {
1029
+ const def = definition(kind);
1030
+ const body = await apiGet(`/api/${def.route}/${assertId(kind, id)}`, { deleted: params.deleted ?? false }, options);
1031
+ assertNoApiErrors(body, 200);
1032
+ const map = body?.[def.collection] ?? {};
1033
+ return map[String(id)] ?? Object.values(map).find((e) => String(e?.id) === String(id)) ?? null;
1034
+ }
1035
+ /**
1036
+ * Creates (no `id`) or updates (with `id`) a product.
1037
+ *
1038
+ * Shopwave instances (prices) can't be updated, only replaced. Build
1039
+ * `instances` with {@link toProductInstancesForSave} (passing the product as last
1040
+ * read) so an edited price is sent as a new instance. As a safeguard, a new
1041
+ * product (no `id`, e.g. a duplicate) never sends instance ids: an id copied from
1042
+ * another product would otherwise point the save at that product's instances.
1043
+ *
1044
+ * `images` is sent as file names ({@link toStoredProductImages}), so the URLs a
1045
+ * read returns can be passed straight back; leaving `images` out keeps them.
1046
+ */
1047
+ const saveProduct = (product, options) => {
1048
+ let toSave = (product.id == null || String(product.id).trim() === "") && product.instances != null ? {
1049
+ ...product,
1050
+ instances: toProductInstancesForSave(product.instances)
1051
+ } : product;
1052
+ if (Array.isArray(toSave.images)) toSave = {
1053
+ ...toSave,
1054
+ images: toStoredProductImages(toSave.images)
1055
+ };
1056
+ return saveEntity("product", toSave, options);
1057
+ };
1058
+ const deleteProduct = (id, options) => deleteEntityById("product", id, options);
1059
+ const fetchProduct = (id, params, options) => fetchEntityById("product", id, params, options);
1060
+ const saveCategory = (category, options) => saveEntity("category", category, options);
1061
+ const deleteCategory = (id, options) => deleteEntityById("category", id, options);
1062
+ const fetchCategory = (id, params, options) => fetchEntityById("category", id, params, options);
1063
+ const saveStore = (store, options) => saveEntity("store", store, options);
1064
+ const deleteStore = (id, options) => deleteEntityById("store", id, options);
1065
+ const fetchStore = (id, params, options) => fetchEntityById("store", id, params, options);
1066
+ const savePromotion = (promotion, options) => saveEntity("promotion", promotion, options);
1067
+ /**
1068
+ * Expires a promotion (Shopwave never deletes promotions). The route reads the
1069
+ * promotion and saves it back with `endDate` set to now; a promotion that hasn't
1070
+ * started yet gets `startDate` = `endDate` = now. Rejects if the promotion doesn't
1071
+ * exist or the save fails.
1072
+ */
1073
+ const deletePromotion = (id, options) => deleteEntityById("promotion", id, options);
1074
+ const fetchPromotion = (id, params, options) => fetchEntityById("promotion", id, params, options);
1075
+ /**
1076
+ * Creates an employee, or updates one (with `id`). On update Shopwave only
1077
+ * applies `roleId`, `joinedDate` and `exitDate` (and store roles); names and
1078
+ * email can't be changed, and the echo only carries the updated fields — re-read
1079
+ * with `fetchEmployee` if you need the stored record.
1080
+ */
1081
+ const saveEmployee = (employee, options) => saveEntity("employee", employee, options);
1082
+ /** Retires an employee: Shopwave has no employee DELETE, so this sets `exitDate` to now. */
1083
+ const deleteEmployee = (id, options) => deleteEntityById("employee", id, options);
1084
+ const fetchEmployee = (id, params, options) => fetchEntityById("employee", id, params, options);
1085
+ const fetchConsumer = (id, params, options) => fetchEntityById("consumer", id, params, options);
1086
+
1087
+ //#endregion
1088
+ //#region src/core/basket.ts
1089
+ const DEFAULT_BASKET_FILTERS = {
1090
+ search: "",
1091
+ dateRange: {
1092
+ start: null,
1093
+ end: null
1094
+ },
1095
+ consumerId: null,
1096
+ status: "all"
1097
+ };
1098
+ const DEFAULT_PAGINATION = {
1099
+ page: 0,
1100
+ pageSize: 25,
1101
+ total: 0
1102
+ };
1103
+ /** Formats a date as `YYYY-MM-DD HH:mm:ss` for the report query. */
1104
+ function formatDateForQuery(date, isEndOfDay = false) {
1105
+ return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")} ${isEndOfDay ? "23:59:59" : "00:00:00"}`;
1106
+ }
1107
+ /** Builds the `Basket` report query from a set of filters. */
1108
+ function buildBasketReportQuery(filters) {
1109
+ const whereConditions = [];
1110
+ const today = /* @__PURE__ */ new Date();
1111
+ const startDate = filters.dateRange.start ?? today;
1112
+ const endDate = filters.dateRange.end ?? today;
1113
+ whereConditions.push(`Basket.completeDate > '${formatDateForQuery(startDate, false)}'`);
1114
+ whereConditions.push(`Basket.completeDate < '${formatDateForQuery(endDate, true)}'`);
1115
+ if (filters.consumerId) whereConditions.push(`Basket.consumerId = ${filters.consumerId}`);
1116
+ if (filters.status !== "all") whereConditions.push(`Basket.status = '${filters.status}'`);
1117
+ return { baskets: {
1118
+ FROM: "Basket",
1119
+ WHERE: whereConditions.length > 0 ? { AND: whereConditions } : void 0
1120
+ } };
1121
+ }
1122
+ /** Flattens the raw report rows/keys into structured baskets. */
1123
+ function parseBasketReportData(reports) {
1124
+ if (!reports?.baskets?.data || !reports?.baskets?.keys) return [];
1125
+ const { keys, data } = reports.baskets;
1126
+ const keyIndices = {};
1127
+ keys.forEach((key, index) => {
1128
+ keyIndices[key.name] = index;
1129
+ });
1130
+ const productKey = keys.find((k) => k.name === "Basket.Product");
1131
+ const productSubKeys = {};
1132
+ if (productKey?.item) productKey.item.forEach((subKey, index) => {
1133
+ productSubKeys[subKey.name] = index;
1134
+ });
1135
+ return data.map((row) => {
1136
+ const products = (row[keyIndices["Basket.Product"]] || []).map((productRow) => ({
1137
+ productId: productRow[productSubKeys["Basket.Product.productId"]],
1138
+ productName: `Product #${productRow[productSubKeys["Basket.Product.productId"]]}`,
1139
+ quantity: productRow[productSubKeys["Basket.Product.quantity"]] || 1,
1140
+ price: productRow[productSubKeys["Basket.Product.productPrice"]] || 0,
1141
+ tax: productRow[productSubKeys["Basket.Product.productTaxPercentage"]] || 0
1142
+ }));
1143
+ const total = products.reduce((sum, p) => sum + p.price * p.quantity, 0);
1144
+ const taxTotal = products.reduce((sum, p) => sum + p.price * p.quantity * p.tax, 0);
1145
+ const completeDateTimestamp = row[keyIndices["Basket.completeDate"]];
1146
+ const completeDate = completeDateTimestamp ? new Date(completeDateTimestamp).toISOString() : "";
1147
+ return {
1148
+ id: row[keyIndices["Basket.id"]],
1149
+ name: row[keyIndices["Basket.name"]],
1150
+ consumerId: row[keyIndices["Basket.consumerId"]],
1151
+ products,
1152
+ total,
1153
+ taxTotal,
1154
+ status: "completed",
1155
+ completeDate
1156
+ };
1157
+ });
1158
+ }
1159
+ /** Unique non-null consumer ids referenced by a set of baskets. */
1160
+ function collectConsumerIds(baskets) {
1161
+ if (!baskets.length) return null;
1162
+ const ids = baskets.map((b) => b.consumerId).filter((id) => id != null);
1163
+ return ids.length > 0 ? [...new Set(ids)] : null;
1164
+ }
1165
+ /** Unique product ids referenced by a set of baskets. */
1166
+ function collectProductIds(baskets) {
1167
+ if (!baskets.length) return null;
1168
+ const ids = /* @__PURE__ */ new Set();
1169
+ baskets.forEach((basket) => {
1170
+ basket.products.forEach((product) => {
1171
+ if (product.productId) ids.add(product.productId);
1172
+ });
1173
+ });
1174
+ return ids.size > 0 ? [...ids] : null;
1175
+ }
1176
+ /** Joins baskets with consumer + product lookups, applies search, sorts. */
1177
+ function combineBasketRows({ baskets, consumerMap, productMap, search }) {
1178
+ if (!baskets.length) return [];
1179
+ let combinedRows = baskets.map((basket) => {
1180
+ const consumer = basket.consumerId ? consumerMap[basket.consumerId] : null;
1181
+ const productsWithNames = basket.products.map((p) => {
1182
+ const product = productMap[p.productId];
1183
+ return {
1184
+ ...p,
1185
+ productName: product?.name || `Product #${p.productId}`
1186
+ };
1187
+ });
1188
+ return {
1189
+ id: basket.id,
1190
+ basketId: basket.id,
1191
+ basketName: basket.name || `Basket #${basket.id}`,
1192
+ consumerId: basket.consumerId,
1193
+ consumerName: consumer ? `${consumer.firstName} ${consumer.lastName}` : "Unknown",
1194
+ consumerEmail: consumer?.email || "-",
1195
+ products: productsWithNames,
1196
+ basketTotal: (basket.total || 0) / 100,
1197
+ tax: basket.taxTotal || 0,
1198
+ dateTime: basket.completeDate,
1199
+ status: basket.status || "pending"
1200
+ };
1201
+ });
1202
+ if (search) {
1203
+ const searchLower = search.toLowerCase();
1204
+ combinedRows = combinedRows.filter((row) => row.basketId.toString().includes(searchLower) || row.basketName.toLowerCase().includes(searchLower) || row.consumerName.toLowerCase().includes(searchLower) || row.consumerEmail.toLowerCase().includes(searchLower));
1205
+ }
1206
+ combinedRows.sort((a, b) => {
1207
+ const dateA = new Date(a.dateTime).getTime();
1208
+ return new Date(b.dateTime).getTime() - dateA;
1209
+ });
1210
+ return combinedRows;
1211
+ }
1212
+ /** Aggregate totals for a set of report rows. */
1213
+ function computeBasketSummary(rows) {
1214
+ const uniqueConsumerIds = new Set(rows.map((row) => row.consumerId));
1215
+ return {
1216
+ totalBaskets: rows.length,
1217
+ totalRevenue: rows.reduce((sum, row) => sum + row.basketTotal, 0),
1218
+ totalTax: rows.reduce((sum, row) => sum + row.tax, 0),
1219
+ uniqueConsumers: uniqueConsumerIds.size
1220
+ };
1221
+ }
1222
+ /** Builds a consumer id → consumer lookup. */
1223
+ function buildConsumerMap(consumers) {
1224
+ const map = {};
1225
+ if (consumers) consumers.forEach((consumer) => {
1226
+ map[consumer.id] = consumer;
1227
+ });
1228
+ return map;
1229
+ }
1230
+
1119
1231
  //#endregion
1120
1232
  //#region src/core/merchant.ts
1121
1233
  const MERCHANT_PATH = `/api/${SHOPWAVE_RESOURCES.merchant.route}`;
@@ -1305,10 +1417,12 @@ exports.MERCHANT_READ_ONLY_FIELDS = MERCHANT_READ_ONLY_FIELDS;
1305
1417
  exports.PromotionRuleSet = PromotionRuleSet;
1306
1418
  exports.SHOPWAVE_ENTITIES = SHOPWAVE_ENTITIES;
1307
1419
  exports.SHOPWAVE_IMAGE_BASE_URL = SHOPWAVE_IMAGE_BASE_URL;
1420
+ exports.SHOPWAVE_LOOKUPS = SHOPWAVE_LOOKUPS;
1308
1421
  exports.SHOPWAVE_RESOURCES = SHOPWAVE_RESOURCES;
1309
1422
  exports.SHOPWAVE_UPLOAD = SHOPWAVE_UPLOAD;
1310
1423
  exports.ShopwaveApiError = ShopwaveApiError;
1311
1424
  exports.UPLOAD_KINDS = UPLOAD_KINDS;
1425
+ exports.UPLOAD_PREFIXES = UPLOAD_PREFIXES;
1312
1426
  exports.apiDelete = apiDelete;
1313
1427
  exports.apiGet = apiGet;
1314
1428
  exports.apiRequest = apiRequest;
@@ -1338,6 +1452,8 @@ exports.fetchEmployees = fetchEmployees;
1338
1452
  exports.fetchEntityById = fetchEntityById;
1339
1453
  exports.fetchMerchant = fetchMerchant;
1340
1454
  exports.fetchProduct = fetchProduct;
1455
+ exports.fetchProductInstanceTags = fetchProductInstanceTags;
1456
+ exports.fetchProductTags = fetchProductTags;
1341
1457
  exports.fetchProducts = fetchProducts;
1342
1458
  exports.fetchProductsMap = fetchProductsMap;
1343
1459
  exports.fetchPromotion = fetchPromotion;
@@ -1358,13 +1474,16 @@ exports.getMerchantImageUrl = getMerchantImageUrl;
1358
1474
  exports.imageFileName = imageFileName;
1359
1475
  exports.isSameInstancePrice = isSameInstancePrice;
1360
1476
  exports.isUploadKind = isUploadKind;
1477
+ exports.isUploadPrefix = isUploadPrefix;
1361
1478
  exports.loginPath = loginPath;
1362
1479
  exports.logout = logout;
1363
1480
  exports.logoutPath = logoutPath;
1364
1481
  exports.merchantLinksFromForm = merchantLinksFromForm;
1365
1482
  exports.merchantLinksToForm = merchantLinksToForm;
1366
1483
  exports.normalizeMerchantLinks = normalizeMerchantLinks;
1484
+ exports.normalizeTagList = normalizeTagList;
1367
1485
  exports.parseBasketReportData = parseBasketReportData;
1486
+ exports.productImageRole = productImageRole;
1368
1487
  exports.readImageSize = readImageSize;
1369
1488
  exports.rolesById = rolesById;
1370
1489
  exports.saveCategory = saveCategory;
@@ -1379,6 +1498,7 @@ exports.submitEntity = submitEntity;
1379
1498
  exports.toProductInstancesForSave = toProductInstancesForSave;
1380
1499
  exports.toShopwaveApiError = toShopwaveApiError;
1381
1500
  exports.toStoredImageIds = toStoredImageIds;
1501
+ exports.toStoredProductImages = toStoredProductImages;
1382
1502
  exports.updateMerchant = updateMerchant;
1383
1503
  exports.uploadImage = uploadImage;
1384
1504
  exports.uploadMerchantImage = uploadMerchantImage;