react-shopwave-connect 0.4.3 → 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.
- package/README.md +6 -4
- package/dist/core/index.cjs +484 -424
- package/dist/core/index.cjs.map +1 -1
- package/dist/core/index.d.cts +56 -2
- package/dist/core/index.d.ts +56 -2
- package/dist/core/index.js +481 -425
- package/dist/core/index.js.map +1 -1
- package/dist/hooks/index.cjs +159 -145
- package/dist/hooks/index.cjs.map +1 -1
- package/dist/hooks/index.d.cts +19 -0
- package/dist/hooks/index.d.ts +19 -0
- package/dist/hooks/index.js +159 -145
- package/dist/hooks/index.js.map +1 -1
- package/dist/index.cjs +484 -424
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +56 -2
- package/dist/index.d.ts +56 -2
- package/dist/index.js +481 -425
- package/dist/index.js.map +1 -1
- package/dist/next/index.cjs +75 -57
- package/dist/next/index.cjs.map +1 -1
- package/dist/next/index.d.cts +21 -4
- package/dist/next/index.d.ts +21 -4
- package/dist/next/index.js +75 -58
- package/dist/next/index.js.map +1 -1
- package/dist/server/index.cjs +75 -57
- package/dist/server/index.cjs.map +1 -1
- package/dist/server/index.d.cts +26 -5
- package/dist/server/index.d.ts +26 -5
- package/dist/server/index.js +75 -58
- package/dist/server/index.js.map +1 -1
- package/package.json +1 -1
package/dist/core/index.cjs
CHANGED
|
@@ -382,17 +382,29 @@ const UPLOAD_KINDS = Object.freeze({
|
|
|
382
382
|
applicationLogo: "applicaionLogo",
|
|
383
383
|
applicationImages: "applicaionImages"
|
|
384
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
|
+
]);
|
|
385
392
|
/** How uploads are addressed (app route and Shopwave uploader). */
|
|
386
393
|
const SHOPWAVE_UPLOAD = Object.freeze({
|
|
387
394
|
route: "upload",
|
|
388
395
|
upstream: "uploader",
|
|
389
396
|
kindHeader: "contentType",
|
|
397
|
+
prefixHeader: "prefix",
|
|
390
398
|
fileField: "file",
|
|
391
|
-
kindField: "kind"
|
|
399
|
+
kindField: "kind",
|
|
400
|
+
prefixField: "prefix"
|
|
392
401
|
});
|
|
393
402
|
function isUploadKind(value) {
|
|
394
403
|
return typeof value === "string" && Object.prototype.hasOwnProperty.call(UPLOAD_KINDS, value);
|
|
395
404
|
}
|
|
405
|
+
function isUploadPrefix(value) {
|
|
406
|
+
return typeof value === "string" && UPLOAD_PREFIXES.includes(value);
|
|
407
|
+
}
|
|
396
408
|
const SHOPWAVE_LOOKUPS = Object.freeze({
|
|
397
409
|
productTags: {
|
|
398
410
|
route: "products/tags",
|
|
@@ -578,443 +590,109 @@ async function submitEntity({ endpoint, method = "POST", payload }, options = {}
|
|
|
578
590
|
}
|
|
579
591
|
|
|
580
592
|
//#endregion
|
|
581
|
-
//#region src/core/
|
|
593
|
+
//#region src/core/imageFit.ts
|
|
582
594
|
/**
|
|
583
|
-
*
|
|
584
|
-
* (
|
|
585
|
-
* the live API where noted:
|
|
586
|
-
* - category/product/store: GET filtered by `<x>Ids`, POST upsert, DELETE with `<x>Id` → 205.
|
|
587
|
-
* - promotion: no DELETE; promotions are never deleted, only expired. Expiring
|
|
588
|
-
* reads the promotion and saves the whole record back with `endDate` = now (and
|
|
589
|
-
* `startDate` = now too if it hadn't started); the live API rejects a partial
|
|
590
|
-
* `{ id, endDate }` save with error 899. Dates are UTC `YYYY-MM-DD HH:mm:ss`.
|
|
591
|
-
* - employee: POST updates `roleId`, `joinedDate`, `exitDate` (names can't be
|
|
592
|
-
* changed); no DELETE (live API: "Cannot DELETE /employee") → retired via `exitDate`.
|
|
593
|
-
* - 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`).
|
|
594
597
|
*/
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
deleteMode: "delete"
|
|
613
|
-
},
|
|
614
|
-
store: {
|
|
615
|
-
route: "stores",
|
|
616
|
-
collection: "stores",
|
|
617
|
-
upstream: "store",
|
|
618
|
-
idsHeader: "storeIds",
|
|
619
|
-
idHeader: "storeId",
|
|
620
|
-
writable: true,
|
|
621
|
-
deleteMode: "delete"
|
|
622
|
-
},
|
|
623
|
-
promotion: {
|
|
624
|
-
route: "promotions",
|
|
625
|
-
collection: "promotions",
|
|
626
|
-
upstream: "promotion",
|
|
627
|
-
idsHeader: "promotionIds",
|
|
628
|
-
idHeader: "promotionId",
|
|
629
|
-
writable: true,
|
|
630
|
-
deleteMode: "retire",
|
|
631
|
-
retireField: "endDate",
|
|
632
|
-
retireWithRecord: true,
|
|
633
|
-
retireStartField: "startDate"
|
|
634
|
-
},
|
|
635
|
-
employee: {
|
|
636
|
-
route: "employees",
|
|
637
|
-
collection: "employees",
|
|
638
|
-
upstream: "employee",
|
|
639
|
-
idsHeader: "employeeIds",
|
|
640
|
-
idHeader: "employeeId",
|
|
641
|
-
writable: true,
|
|
642
|
-
deleteMode: "retire",
|
|
643
|
-
retireField: "exitDate"
|
|
644
|
-
},
|
|
645
|
-
consumer: {
|
|
646
|
-
route: "consumer",
|
|
647
|
-
collection: "consumers",
|
|
648
|
-
upstream: "consumer",
|
|
649
|
-
idsHeader: "ids",
|
|
650
|
-
idHeader: "consumerId",
|
|
651
|
-
writable: false,
|
|
652
|
-
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
|
+
};
|
|
653
615
|
}
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
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
|
+
};
|
|
659
623
|
}
|
|
660
|
-
function
|
|
661
|
-
|
|
662
|
-
if (!s) throw new Error(`${kind} id is missing`);
|
|
663
|
-
return encodeURIComponent(s);
|
|
624
|
+
function requireBrowserImages(fn) {
|
|
625
|
+
if (typeof createImageBitmap !== "function") throw new Error(`${fn} needs a browser (createImageBitmap is not available)`);
|
|
664
626
|
}
|
|
665
|
-
/**
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
* answers 201 and echoes every entity under the ref it was sent with, so each
|
|
671
|
-
* result is matched back by ref. Throws {@link ShopwaveApiError} when the
|
|
672
|
-
* response carries `api.message.errors` or any ref is missing from it.
|
|
673
|
-
*
|
|
674
|
-
* The API's partial-success semantics for multi-entity saves haven't been
|
|
675
|
-
* confirmed yet; single saves (`saveProduct` etc.) are the tested path.
|
|
676
|
-
*/
|
|
677
|
-
async function saveEntities(kind, items, options = {}) {
|
|
678
|
-
const def = definition(kind);
|
|
679
|
-
if (items.length === 0) return [];
|
|
680
|
-
const refs = items.map((_, i) => String(i));
|
|
681
|
-
const payload = { [def.collection]: Object.fromEntries(refs.map((ref, i) => [ref, items[i]])) };
|
|
682
|
-
const { status, body: raw } = await apiRequest(`/api/${def.route}`, {
|
|
683
|
-
method: "POST",
|
|
684
|
-
headers: { "Content-Type": "application/json" },
|
|
685
|
-
body: JSON.stringify(payload)
|
|
686
|
-
}, options);
|
|
687
|
-
const body = raw;
|
|
688
|
-
assertNoApiErrors(body, status);
|
|
689
|
-
const echoed = body?.[def.collection] ?? {};
|
|
690
|
-
return refs.map((ref, i) => {
|
|
691
|
-
const saved = echoed[ref];
|
|
692
|
-
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 {
|
|
693
632
|
return {
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
id: Number(saved.id)
|
|
633
|
+
width: bitmap.width,
|
|
634
|
+
height: bitmap.height
|
|
697
635
|
};
|
|
698
|
-
}
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
async function saveEntity(kind, item, options = {}) {
|
|
702
|
-
const [saved] = await saveEntities(kind, [item], options);
|
|
703
|
-
return saved;
|
|
636
|
+
} finally {
|
|
637
|
+
bitmap.close?.();
|
|
638
|
+
}
|
|
704
639
|
}
|
|
705
640
|
/**
|
|
706
|
-
*
|
|
707
|
-
*
|
|
708
|
-
*
|
|
709
|
-
* promotion is saved back whole (see {@link deletePromotion}).
|
|
710
|
-
*
|
|
711
|
-
* Shopwave answers 205 with an empty body — also for ids that don't exist — so
|
|
712
|
-
* a resolved promise means "the API accepted the request", not "a record was
|
|
713
|
-
* deleted".
|
|
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.
|
|
714
644
|
*/
|
|
715
|
-
async function
|
|
716
|
-
|
|
717
|
-
}
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
const
|
|
721
|
-
const
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
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
|
+
}
|
|
725
680
|
}
|
|
681
|
+
|
|
682
|
+
//#endregion
|
|
683
|
+
//#region src/core/upload.ts
|
|
726
684
|
/**
|
|
727
|
-
*
|
|
728
|
-
*
|
|
729
|
-
*
|
|
730
|
-
* `instances` with {@link toProductInstancesForSave} (passing the product as last
|
|
731
|
-
* read) so an edited price is sent as a new instance. As a safeguard, a new
|
|
732
|
-
* product (no `id`, e.g. a duplicate) never sends instance ids: an id copied from
|
|
733
|
-
* another product would otherwise point the save at that product's instances.
|
|
734
|
-
*/
|
|
735
|
-
const saveProduct = (product, options) => {
|
|
736
|
-
return saveEntity("product", (product.id == null || String(product.id).trim() === "") && product.instances != null ? {
|
|
737
|
-
...product,
|
|
738
|
-
instances: toProductInstancesForSave(product.instances)
|
|
739
|
-
} : product, options);
|
|
740
|
-
};
|
|
741
|
-
const deleteProduct = (id, options) => deleteEntityById("product", id, options);
|
|
742
|
-
const fetchProduct = (id, params, options) => fetchEntityById("product", id, params, options);
|
|
743
|
-
const saveCategory = (category, options) => saveEntity("category", category, options);
|
|
744
|
-
const deleteCategory = (id, options) => deleteEntityById("category", id, options);
|
|
745
|
-
const fetchCategory = (id, params, options) => fetchEntityById("category", id, params, options);
|
|
746
|
-
const saveStore = (store, options) => saveEntity("store", store, options);
|
|
747
|
-
const deleteStore = (id, options) => deleteEntityById("store", id, options);
|
|
748
|
-
const fetchStore = (id, params, options) => fetchEntityById("store", id, params, options);
|
|
749
|
-
const savePromotion = (promotion, options) => saveEntity("promotion", promotion, options);
|
|
750
|
-
/**
|
|
751
|
-
* Expires a promotion (Shopwave never deletes promotions). The route reads the
|
|
752
|
-
* promotion and saves it back with `endDate` set to now; a promotion that hasn't
|
|
753
|
-
* started yet gets `startDate` = `endDate` = now. Rejects if the promotion doesn't
|
|
754
|
-
* 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.
|
|
755
688
|
*/
|
|
756
|
-
const
|
|
757
|
-
const
|
|
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;
|
|
758
691
|
/**
|
|
759
|
-
*
|
|
760
|
-
*
|
|
761
|
-
*
|
|
762
|
-
*
|
|
763
|
-
*/
|
|
764
|
-
const saveEmployee = (employee, options) => saveEntity("employee", employee, options);
|
|
765
|
-
/** Retires an employee: Shopwave has no employee DELETE, so this sets `exitDate` to now. */
|
|
766
|
-
const deleteEmployee = (id, options) => deleteEntityById("employee", id, options);
|
|
767
|
-
const fetchEmployee = (id, params, options) => fetchEntityById("employee", id, params, options);
|
|
768
|
-
const fetchConsumer = (id, params, options) => fetchEntityById("consumer", id, params, options);
|
|
769
|
-
|
|
770
|
-
//#endregion
|
|
771
|
-
//#region src/core/basket.ts
|
|
772
|
-
const DEFAULT_BASKET_FILTERS = {
|
|
773
|
-
search: "",
|
|
774
|
-
dateRange: {
|
|
775
|
-
start: null,
|
|
776
|
-
end: null
|
|
777
|
-
},
|
|
778
|
-
consumerId: null,
|
|
779
|
-
status: "all"
|
|
780
|
-
};
|
|
781
|
-
const DEFAULT_PAGINATION = {
|
|
782
|
-
page: 0,
|
|
783
|
-
pageSize: 25,
|
|
784
|
-
total: 0
|
|
785
|
-
};
|
|
786
|
-
/** Formats a date as `YYYY-MM-DD HH:mm:ss` for the report query. */
|
|
787
|
-
function formatDateForQuery(date, isEndOfDay = false) {
|
|
788
|
-
return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")} ${isEndOfDay ? "23:59:59" : "00:00:00"}`;
|
|
789
|
-
}
|
|
790
|
-
/** Builds the `Basket` report query from a set of filters. */
|
|
791
|
-
function buildBasketReportQuery(filters) {
|
|
792
|
-
const whereConditions = [];
|
|
793
|
-
const today = /* @__PURE__ */ new Date();
|
|
794
|
-
const startDate = filters.dateRange.start ?? today;
|
|
795
|
-
const endDate = filters.dateRange.end ?? today;
|
|
796
|
-
whereConditions.push(`Basket.completeDate > '${formatDateForQuery(startDate, false)}'`);
|
|
797
|
-
whereConditions.push(`Basket.completeDate < '${formatDateForQuery(endDate, true)}'`);
|
|
798
|
-
if (filters.consumerId) whereConditions.push(`Basket.consumerId = ${filters.consumerId}`);
|
|
799
|
-
if (filters.status !== "all") whereConditions.push(`Basket.status = '${filters.status}'`);
|
|
800
|
-
return { baskets: {
|
|
801
|
-
FROM: "Basket",
|
|
802
|
-
WHERE: whereConditions.length > 0 ? { AND: whereConditions } : void 0
|
|
803
|
-
} };
|
|
804
|
-
}
|
|
805
|
-
/** Flattens the raw report rows/keys into structured baskets. */
|
|
806
|
-
function parseBasketReportData(reports) {
|
|
807
|
-
if (!reports?.baskets?.data || !reports?.baskets?.keys) return [];
|
|
808
|
-
const { keys, data } = reports.baskets;
|
|
809
|
-
const keyIndices = {};
|
|
810
|
-
keys.forEach((key, index) => {
|
|
811
|
-
keyIndices[key.name] = index;
|
|
812
|
-
});
|
|
813
|
-
const productKey = keys.find((k) => k.name === "Basket.Product");
|
|
814
|
-
const productSubKeys = {};
|
|
815
|
-
if (productKey?.item) productKey.item.forEach((subKey, index) => {
|
|
816
|
-
productSubKeys[subKey.name] = index;
|
|
817
|
-
});
|
|
818
|
-
return data.map((row) => {
|
|
819
|
-
const products = (row[keyIndices["Basket.Product"]] || []).map((productRow) => ({
|
|
820
|
-
productId: productRow[productSubKeys["Basket.Product.productId"]],
|
|
821
|
-
productName: `Product #${productRow[productSubKeys["Basket.Product.productId"]]}`,
|
|
822
|
-
quantity: productRow[productSubKeys["Basket.Product.quantity"]] || 1,
|
|
823
|
-
price: productRow[productSubKeys["Basket.Product.productPrice"]] || 0,
|
|
824
|
-
tax: productRow[productSubKeys["Basket.Product.productTaxPercentage"]] || 0
|
|
825
|
-
}));
|
|
826
|
-
const total = products.reduce((sum, p) => sum + p.price * p.quantity, 0);
|
|
827
|
-
const taxTotal = products.reduce((sum, p) => sum + p.price * p.quantity * p.tax, 0);
|
|
828
|
-
const completeDateTimestamp = row[keyIndices["Basket.completeDate"]];
|
|
829
|
-
const completeDate = completeDateTimestamp ? new Date(completeDateTimestamp).toISOString() : "";
|
|
830
|
-
return {
|
|
831
|
-
id: row[keyIndices["Basket.id"]],
|
|
832
|
-
name: row[keyIndices["Basket.name"]],
|
|
833
|
-
consumerId: row[keyIndices["Basket.consumerId"]],
|
|
834
|
-
products,
|
|
835
|
-
total,
|
|
836
|
-
taxTotal,
|
|
837
|
-
status: "completed",
|
|
838
|
-
completeDate
|
|
839
|
-
};
|
|
840
|
-
});
|
|
841
|
-
}
|
|
842
|
-
/** Unique non-null consumer ids referenced by a set of baskets. */
|
|
843
|
-
function collectConsumerIds(baskets) {
|
|
844
|
-
if (!baskets.length) return null;
|
|
845
|
-
const ids = baskets.map((b) => b.consumerId).filter((id) => id != null);
|
|
846
|
-
return ids.length > 0 ? [...new Set(ids)] : null;
|
|
847
|
-
}
|
|
848
|
-
/** Unique product ids referenced by a set of baskets. */
|
|
849
|
-
function collectProductIds(baskets) {
|
|
850
|
-
if (!baskets.length) return null;
|
|
851
|
-
const ids = /* @__PURE__ */ new Set();
|
|
852
|
-
baskets.forEach((basket) => {
|
|
853
|
-
basket.products.forEach((product) => {
|
|
854
|
-
if (product.productId) ids.add(product.productId);
|
|
855
|
-
});
|
|
856
|
-
});
|
|
857
|
-
return ids.size > 0 ? [...ids] : null;
|
|
858
|
-
}
|
|
859
|
-
/** Joins baskets with consumer + product lookups, applies search, sorts. */
|
|
860
|
-
function combineBasketRows({ baskets, consumerMap, productMap, search }) {
|
|
861
|
-
if (!baskets.length) return [];
|
|
862
|
-
let combinedRows = baskets.map((basket) => {
|
|
863
|
-
const consumer = basket.consumerId ? consumerMap[basket.consumerId] : null;
|
|
864
|
-
const productsWithNames = basket.products.map((p) => {
|
|
865
|
-
const product = productMap[p.productId];
|
|
866
|
-
return {
|
|
867
|
-
...p,
|
|
868
|
-
productName: product?.name || `Product #${p.productId}`
|
|
869
|
-
};
|
|
870
|
-
});
|
|
871
|
-
return {
|
|
872
|
-
id: basket.id,
|
|
873
|
-
basketId: basket.id,
|
|
874
|
-
basketName: basket.name || `Basket #${basket.id}`,
|
|
875
|
-
consumerId: basket.consumerId,
|
|
876
|
-
consumerName: consumer ? `${consumer.firstName} ${consumer.lastName}` : "Unknown",
|
|
877
|
-
consumerEmail: consumer?.email || "-",
|
|
878
|
-
products: productsWithNames,
|
|
879
|
-
basketTotal: (basket.total || 0) / 100,
|
|
880
|
-
tax: basket.taxTotal || 0,
|
|
881
|
-
dateTime: basket.completeDate,
|
|
882
|
-
status: basket.status || "pending"
|
|
883
|
-
};
|
|
884
|
-
});
|
|
885
|
-
if (search) {
|
|
886
|
-
const searchLower = search.toLowerCase();
|
|
887
|
-
combinedRows = combinedRows.filter((row) => row.basketId.toString().includes(searchLower) || row.basketName.toLowerCase().includes(searchLower) || row.consumerName.toLowerCase().includes(searchLower) || row.consumerEmail.toLowerCase().includes(searchLower));
|
|
888
|
-
}
|
|
889
|
-
combinedRows.sort((a, b) => {
|
|
890
|
-
const dateA = new Date(a.dateTime).getTime();
|
|
891
|
-
return new Date(b.dateTime).getTime() - dateA;
|
|
892
|
-
});
|
|
893
|
-
return combinedRows;
|
|
894
|
-
}
|
|
895
|
-
/** Aggregate totals for a set of report rows. */
|
|
896
|
-
function computeBasketSummary(rows) {
|
|
897
|
-
const uniqueConsumerIds = new Set(rows.map((row) => row.consumerId));
|
|
898
|
-
return {
|
|
899
|
-
totalBaskets: rows.length,
|
|
900
|
-
totalRevenue: rows.reduce((sum, row) => sum + row.basketTotal, 0),
|
|
901
|
-
totalTax: rows.reduce((sum, row) => sum + row.tax, 0),
|
|
902
|
-
uniqueConsumers: uniqueConsumerIds.size
|
|
903
|
-
};
|
|
904
|
-
}
|
|
905
|
-
/** Builds a consumer id → consumer lookup. */
|
|
906
|
-
function buildConsumerMap(consumers) {
|
|
907
|
-
const map = {};
|
|
908
|
-
if (consumers) consumers.forEach((consumer) => {
|
|
909
|
-
map[consumer.id] = consumer;
|
|
910
|
-
});
|
|
911
|
-
return map;
|
|
912
|
-
}
|
|
913
|
-
|
|
914
|
-
//#endregion
|
|
915
|
-
//#region src/core/imageFit.ts
|
|
916
|
-
/**
|
|
917
|
-
* The centred part of a `srcWidth × srcHeight` image with the aspect ratio of
|
|
918
|
-
* `dstWidth × dstHeight` (like CSS `object-fit: cover`).
|
|
919
|
-
*/
|
|
920
|
-
function coverCrop(srcWidth, srcHeight, dstWidth, dstHeight) {
|
|
921
|
-
if (![
|
|
922
|
-
srcWidth,
|
|
923
|
-
srcHeight,
|
|
924
|
-
dstWidth,
|
|
925
|
-
dstHeight
|
|
926
|
-
].every((n) => Number.isFinite(n) && n > 0)) throw new Error("coverCrop: sizes must be positive numbers");
|
|
927
|
-
const srcRatio = srcWidth / srcHeight;
|
|
928
|
-
const dstRatio = dstWidth / dstHeight;
|
|
929
|
-
if (srcRatio > dstRatio) {
|
|
930
|
-
const sw = Math.round(srcHeight * dstRatio);
|
|
931
|
-
return {
|
|
932
|
-
sx: Math.round((srcWidth - sw) / 2),
|
|
933
|
-
sy: 0,
|
|
934
|
-
sw,
|
|
935
|
-
sh: srcHeight
|
|
936
|
-
};
|
|
937
|
-
}
|
|
938
|
-
const sh = Math.round(srcWidth / dstRatio);
|
|
939
|
-
return {
|
|
940
|
-
sx: 0,
|
|
941
|
-
sy: Math.round((srcHeight - sh) / 2),
|
|
942
|
-
sw: srcWidth,
|
|
943
|
-
sh
|
|
944
|
-
};
|
|
945
|
-
}
|
|
946
|
-
function requireBrowserImages(fn) {
|
|
947
|
-
if (typeof createImageBitmap !== "function") throw new Error(`${fn} needs a browser (createImageBitmap is not available)`);
|
|
948
|
-
}
|
|
949
|
-
/** Reads an image file's pixel size (browser only). */
|
|
950
|
-
async function readImageSize(file) {
|
|
951
|
-
requireBrowserImages("readImageSize");
|
|
952
|
-
const bitmap = await createImageBitmap(file);
|
|
953
|
-
try {
|
|
954
|
-
return {
|
|
955
|
-
width: bitmap.width,
|
|
956
|
-
height: bitmap.height
|
|
957
|
-
};
|
|
958
|
-
} finally {
|
|
959
|
-
bitmap.close?.();
|
|
960
|
-
}
|
|
961
|
-
}
|
|
962
|
-
/**
|
|
963
|
-
* Returns the image at exactly `width × height`: scaled and centre-cropped
|
|
964
|
-
* (never stretched). Browser only. The result is a `File` named like the
|
|
965
|
-
* input, with the output type's extension.
|
|
966
|
-
*/
|
|
967
|
-
async function fitImageToSize(file, width, height, options = {}) {
|
|
968
|
-
requireBrowserImages("fitImageToSize");
|
|
969
|
-
const { type = "image/png", quality, keepIfExact = true } = options;
|
|
970
|
-
const name = file.name || "image";
|
|
971
|
-
const ext = type === "image/jpeg" ? "jpg" : type.split("/")[1];
|
|
972
|
-
const outName = `${name.replace(/\.[^.]+$/, "")}.${ext}`;
|
|
973
|
-
const bitmap = await createImageBitmap(file);
|
|
974
|
-
try {
|
|
975
|
-
if (keepIfExact && bitmap.width === width && bitmap.height === height && file.type === type) return file instanceof File ? file : new File([file], outName, { type });
|
|
976
|
-
const { sx, sy, sw, sh } = coverCrop(bitmap.width, bitmap.height, width, height);
|
|
977
|
-
let blob;
|
|
978
|
-
if (typeof OffscreenCanvas === "function") {
|
|
979
|
-
const canvas = new OffscreenCanvas(width, height);
|
|
980
|
-
const ctx = canvas.getContext("2d");
|
|
981
|
-
if (!ctx) throw new Error("fitImageToSize: no 2D canvas context");
|
|
982
|
-
ctx.imageSmoothingQuality = "high";
|
|
983
|
-
ctx.drawImage(bitmap, sx, sy, sw, sh, 0, 0, width, height);
|
|
984
|
-
blob = await canvas.convertToBlob({
|
|
985
|
-
type,
|
|
986
|
-
quality
|
|
987
|
-
});
|
|
988
|
-
} else {
|
|
989
|
-
const canvas = document.createElement("canvas");
|
|
990
|
-
canvas.width = width;
|
|
991
|
-
canvas.height = height;
|
|
992
|
-
const ctx = canvas.getContext("2d");
|
|
993
|
-
if (!ctx) throw new Error("fitImageToSize: no 2D canvas context");
|
|
994
|
-
ctx.imageSmoothingQuality = "high";
|
|
995
|
-
ctx.drawImage(bitmap, sx, sy, sw, sh, 0, 0, width, height);
|
|
996
|
-
blob = await new Promise((resolve, reject) => canvas.toBlob((b) => b ? resolve(b) : reject(/* @__PURE__ */ new Error("fitImageToSize: encoding failed")), type, quality));
|
|
997
|
-
}
|
|
998
|
-
return new File([blob], outName, { type });
|
|
999
|
-
} finally {
|
|
1000
|
-
bitmap.close?.();
|
|
1001
|
-
}
|
|
1002
|
-
}
|
|
1003
|
-
|
|
1004
|
-
//#endregion
|
|
1005
|
-
//#region src/core/upload.ts
|
|
1006
|
-
/**
|
|
1007
|
-
* HTTPS host that serves the Shopwave CDN's images. The API returns
|
|
1008
|
-
* `http://static.merchantstack.com/images/…`, which has no HTTPS endpoint
|
|
1009
|
-
* (checked Sep 2026), so pages served over HTTPS can't show it.
|
|
1010
|
-
*/
|
|
1011
|
-
const SHOPWAVE_IMAGE_BASE_URL = "https://s3-eu-west-1.amazonaws.com/static.merchantstack.com/images";
|
|
1012
|
-
const STATIC_HOST = /^https?:\/\/static\.merchantstack\.com\/images\//i;
|
|
1013
|
-
/**
|
|
1014
|
-
* Turns an image path from the API into a URL a page can load over HTTPS:
|
|
1015
|
-
* `http://static.merchantstack.com/images/x.png` → `<base>/x.png`, and a
|
|
1016
|
-
* relative path (`merchant/5644/logo/x.png`) → `<base>/merchant/5644/logo/x.png`.
|
|
1017
|
-
* Other absolute URLs are returned unchanged; empty input gives `""`.
|
|
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 `""`.
|
|
1018
696
|
*/
|
|
1019
697
|
function getImageUrl(path, base = SHOPWAVE_IMAGE_BASE_URL) {
|
|
1020
698
|
if (!path) return "";
|
|
@@ -1034,10 +712,12 @@ function getImageUrl(path, base = SHOPWAVE_IMAGE_BASE_URL) {
|
|
|
1034
712
|
async function uploadImage(file, params, options = {}) {
|
|
1035
713
|
if (!file || typeof file.size !== "number") throw new Error("uploadImage: file must be a File or Blob");
|
|
1036
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}"`);
|
|
1037
716
|
const name = params.fileName ?? file.name ?? "upload";
|
|
1038
717
|
const form = new FormData();
|
|
1039
718
|
form.append(SHOPWAVE_UPLOAD.fileField, file, name);
|
|
1040
719
|
form.append(SHOPWAVE_UPLOAD.kindField, params.kind);
|
|
720
|
+
if (params.prefix != null) form.append(SHOPWAVE_UPLOAD.prefixField, params.prefix);
|
|
1041
721
|
const { status, body: raw } = await apiRequest(`/api/${SHOPWAVE_UPLOAD.route}`, {
|
|
1042
722
|
method: "POST",
|
|
1043
723
|
body: form
|
|
@@ -1172,6 +852,382 @@ async function uploadMerchantImage(file, slot, options = {}) {
|
|
|
1172
852
|
return uploadImage(fit ? await fitImageToSize(file, def.width, def.height, fitOptions) : file, { kind: def.uploadKind }, requestOptions);
|
|
1173
853
|
}
|
|
1174
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
|
+
|
|
1175
1231
|
//#endregion
|
|
1176
1232
|
//#region src/core/merchant.ts
|
|
1177
1233
|
const MERCHANT_PATH = `/api/${SHOPWAVE_RESOURCES.merchant.route}`;
|
|
@@ -1366,6 +1422,7 @@ exports.SHOPWAVE_RESOURCES = SHOPWAVE_RESOURCES;
|
|
|
1366
1422
|
exports.SHOPWAVE_UPLOAD = SHOPWAVE_UPLOAD;
|
|
1367
1423
|
exports.ShopwaveApiError = ShopwaveApiError;
|
|
1368
1424
|
exports.UPLOAD_KINDS = UPLOAD_KINDS;
|
|
1425
|
+
exports.UPLOAD_PREFIXES = UPLOAD_PREFIXES;
|
|
1369
1426
|
exports.apiDelete = apiDelete;
|
|
1370
1427
|
exports.apiGet = apiGet;
|
|
1371
1428
|
exports.apiRequest = apiRequest;
|
|
@@ -1417,6 +1474,7 @@ exports.getMerchantImageUrl = getMerchantImageUrl;
|
|
|
1417
1474
|
exports.imageFileName = imageFileName;
|
|
1418
1475
|
exports.isSameInstancePrice = isSameInstancePrice;
|
|
1419
1476
|
exports.isUploadKind = isUploadKind;
|
|
1477
|
+
exports.isUploadPrefix = isUploadPrefix;
|
|
1420
1478
|
exports.loginPath = loginPath;
|
|
1421
1479
|
exports.logout = logout;
|
|
1422
1480
|
exports.logoutPath = logoutPath;
|
|
@@ -1425,6 +1483,7 @@ exports.merchantLinksToForm = merchantLinksToForm;
|
|
|
1425
1483
|
exports.normalizeMerchantLinks = normalizeMerchantLinks;
|
|
1426
1484
|
exports.normalizeTagList = normalizeTagList;
|
|
1427
1485
|
exports.parseBasketReportData = parseBasketReportData;
|
|
1486
|
+
exports.productImageRole = productImageRole;
|
|
1428
1487
|
exports.readImageSize = readImageSize;
|
|
1429
1488
|
exports.rolesById = rolesById;
|
|
1430
1489
|
exports.saveCategory = saveCategory;
|
|
@@ -1439,6 +1498,7 @@ exports.submitEntity = submitEntity;
|
|
|
1439
1498
|
exports.toProductInstancesForSave = toProductInstancesForSave;
|
|
1440
1499
|
exports.toShopwaveApiError = toShopwaveApiError;
|
|
1441
1500
|
exports.toStoredImageIds = toStoredImageIds;
|
|
1501
|
+
exports.toStoredProductImages = toStoredProductImages;
|
|
1442
1502
|
exports.updateMerchant = updateMerchant;
|
|
1443
1503
|
exports.uploadImage = uploadImage;
|
|
1444
1504
|
exports.uploadMerchantImage = uploadMerchantImage;
|