react-shopwave-connect 0.4.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -272,6 +272,64 @@ interface FetchProductsParams {
272
272
  * Fetches products. Returns the flattened `Product[]`.
273
273
  */
274
274
  declare function fetchProducts(params?: FetchProductsParams, options?: RequestOptions): Promise<Product[]>;
275
+ /** An instance as a form or caller holds it: `id` is absent for new rows. */
276
+ type ProductInstanceInput = {
277
+ id?: number | string | null;
278
+ price?: string | number | null;
279
+ taxPercentage?: string | number | null;
280
+ name?: string | null;
281
+ };
282
+ /** Instances as the API returns them (keyed by id) or as a plain list. */
283
+ type ProductInstances<T = ProductInstanceInput> = Readonly<Record<string, T>> | Readonly<Record<number, T>> | ReadonlyArray<T>;
284
+ /**
285
+ * What `saveProduct` accepts: any product fields, with `instances` either as the
286
+ * API returns them or as built by {@link toProductInstancesForSave}. Include `id`
287
+ * to update; leave it out to create.
288
+ */
289
+ type ProductSaveInput = Partial<Omit<Product, "instances">> & {
290
+ instances?: ProductInstances;
291
+ [field: string]: unknown;
292
+ };
293
+ /** True when two instances have the same price and tax (the fields Shopwave won't update). */
294
+ declare function isSameInstancePrice(a: ProductInstanceInput, b: ProductInstanceInput): boolean;
295
+ /** An instance whose price or tax was edited, so saving it will give it a new id. */
296
+ interface RepricedInstance {
297
+ /** Position of the instance in the list that was passed in. */
298
+ index: number;
299
+ /** The id it has now, which Shopwave will replace. */
300
+ id: number | string;
301
+ name: string;
302
+ before: {
303
+ price: string;
304
+ taxPercentage: string;
305
+ };
306
+ after: {
307
+ price: string;
308
+ taxPercentage: string;
309
+ };
310
+ }
311
+ /**
312
+ * Lists the instances whose price or tax differs from the `original` instance
313
+ * with the same id: saving them creates new instances with new ids, which can
314
+ * affect anything that stores instance ids (integrations, reports, modifiers).
315
+ * Use it to warn before saving. New rows (no id) aren't listed.
316
+ */
317
+ declare function findRepricedInstances(instances: ProductInstances | null | undefined, original: ProductInstances | null | undefined): RepricedInstance[];
318
+ /**
319
+ * Builds the `instances` map for a product save:
320
+ * - keyed by position (`"0"`, `"1"`, …), like every other ref in a save;
321
+ * - an instance keeps its `id` only when `original` has an instance with that id
322
+ * and the same price and tax; otherwise the id is removed, so Shopwave creates
323
+ * a new instance instead of re-pointing or rewriting someone else's;
324
+ * - server fields (`timestamp`) are removed.
325
+ *
326
+ * Pass the product as last read from the API as `original`. Leave it out for a
327
+ * new product (including a duplicate): every id is then removed.
328
+ * Instances left out of the list are left out of the save (removed).
329
+ */
330
+ declare function toProductInstancesForSave<T extends ProductInstanceInput>(instances: ProductInstances<T> | null | undefined, original?: ProductInstances | null): Record<string, Omit<T, "id"> & {
331
+ id?: number | string;
332
+ }>;
275
333
  /**
276
334
  * Fetches products by id and returns them keyed by id, transparently batching
277
335
  * the request (default 200 ids per call) to stay within API limits. Extracted
@@ -573,7 +631,16 @@ interface FetchByIdParams {
573
631
  }
574
632
  /** Reads one entity by id, or `null` when there's no such (non-deleted) record. */
575
633
  declare function fetchEntityById<K extends EntityKind>(kind: K, id: EntityId, params?: FetchByIdParams, options?: RequestOptions): Promise<EntityTypes[K] | null>;
576
- declare const saveProduct: (product: EntityInput<Product>, options?: RequestOptions) => Promise<Saved<Product>>;
634
+ /**
635
+ * Creates (no `id`) or updates (with `id`) a product.
636
+ *
637
+ * Shopwave instances (prices) can't be updated, only replaced. Build
638
+ * `instances` with {@link toProductInstancesForSave} (passing the product as last
639
+ * read) so an edited price is sent as a new instance. As a safeguard, a new
640
+ * product (no `id`, e.g. a duplicate) never sends instance ids: an id copied from
641
+ * another product would otherwise point the save at that product's instances.
642
+ */
643
+ declare const saveProduct: (product: ProductSaveInput, options?: RequestOptions) => Promise<Saved<Product>>;
577
644
  declare const deleteProduct: (id: EntityId, options?: RequestOptions) => Promise<void>;
578
645
  declare const fetchProduct: (id: EntityId, params?: FetchByIdParams, options?: RequestOptions) => Promise<Product | null>;
579
646
  declare const saveCategory: (category: EntityInput<Category>, options?: RequestOptions) => Promise<Saved<Category>>;
@@ -1299,5 +1366,5 @@ interface UseBasketReportReturn {
1299
1366
  */
1300
1367
  declare function useBasketReport(options?: RequestOptions): UseBasketReportReturn;
1301
1368
  //#endregion
1302
- export { Basket, BasketFilters, BasketItem, BasketPagination, BasketReportRow, BasketSummary, Category, CategoryResponse, CombineBasketRowsParams, Consumer, ConsumerResponse, CropRect, DEFAULT_BASKET_FILTERS, DEFAULT_PAGINATION, DeletableEntityKind, Employee, EmployeeResponse, EntityDefinition, EntityId, EntityInput, EntityKind, EntityTypes, ErrorMessage, Extras, FetchByIdParams, FetchCategoriesParams, FetchEmployeesParams, FetchProductsParams, FetchPromotionsParams, FetchStoresParams, FitImageOptions, ImageSize, MERCHANT_COLOUR_KEYS, MERCHANT_FIELD_MAX_LENGTH, MERCHANT_IMAGE_SLOTS, MERCHANT_IMAGE_SLOT_KEYS, MERCHANT_LINK_KEYS, MERCHANT_LINK_PATHS, MERCHANT_OBJECT_FIELDS, MERCHANT_READ_ONLY_FIELDS, Merchant, MerchantColourKey, MerchantColourSet, MerchantColours, MerchantImageIds, MerchantImageSlot, MerchantImageSlotDefinition, MerchantLinkKey, MerchantLinks, MerchantPatch, MerchantResponse, MessageInfo, MutationState, ParsedBasket, Product, ProductInstance, ProductResponse, Promotion, PromotionResponse, PromotionRuleSet, QueryState, ReportData, ReportKey, ReportQuery, ReportQueryMap, ReportResponse, RequestOptions, ResourceDefinition, ResourceKind, SHOPWAVE_ENTITIES, SHOPWAVE_IMAGE_BASE_URL, SHOPWAVE_RESOURCES, SHOPWAVE_UPLOAD, Saved, SessionStatus, ShopwaveApiError, ShopwaveErrorMap, Store, StoreResponse, SubmitEntityArgs, SubmitEntityResponse, SuccessMessage, UPLOAD_KINDS, UpdateMerchantOptions, UploadImageParams, UploadKind, UploadMerchantImageOptions, UploadedImage, UseBasketReportReturn, User, UserEmployee, UserResponse, WritableEntityKind, apiDelete, apiGet, apiRequest, apiResponse, apiSend, assertNoApiErrors, authorizationFor, buildBasketReportQuery, buildConsumerMap, collectConsumerIds, collectProductIds, combineBasketRows, computeBasketSummary, coverCrop, deleteCategory, deleteEmployee, deleteEntity, deleteEntityById, deleteProduct, deletePromotion, deleteStore, fetchCategories, fetchCategory, fetchConsumer, fetchConsumers, fetchEmployee, fetchEmployees, fetchEntityById, fetchMerchant, fetchProduct, fetchProducts, fetchProductsMap, fetchPromotion, fetchPromotions, fetchReport, fetchSession, fetchStore, fetchStores, fetchUser, fitImageToSize, formatDateForQuery, getApiErrorMap, getApiErrors, getImageUrl, getMerchantImage, getMerchantImageUrl, imageFileName, isUploadKind, loginPath, logout, logoutPath, merchantLinksFromForm, merchantLinksToForm, normalizeMerchantLinks, parseBasketReportData, readImageSize, rolesById, saveCategory, saveEmployee, saveEntities, saveEntity, saveProduct, savePromotion, saveStore, setMerchantImage, submitEntity, toShopwaveApiError, toStoredImageIds, updateMerchant, uploadImage, uploadMerchantImage, useBasketReport, useCategory, useConsumer, useDelete, useEmployee, useLogout, useMerchant, useProduct, usePromotion, useReport, useSession, useStore, useSubmit, useUpdateMerchant, useUploadImage, useUploadMerchantImage, useUser, validateMerchant, withToken };
1369
+ export { Basket, BasketFilters, BasketItem, BasketPagination, BasketReportRow, BasketSummary, Category, CategoryResponse, CombineBasketRowsParams, Consumer, ConsumerResponse, CropRect, DEFAULT_BASKET_FILTERS, DEFAULT_PAGINATION, DeletableEntityKind, Employee, EmployeeResponse, EntityDefinition, EntityId, EntityInput, EntityKind, EntityTypes, ErrorMessage, Extras, FetchByIdParams, FetchCategoriesParams, FetchEmployeesParams, FetchProductsParams, FetchPromotionsParams, FetchStoresParams, FitImageOptions, ImageSize, MERCHANT_COLOUR_KEYS, MERCHANT_FIELD_MAX_LENGTH, MERCHANT_IMAGE_SLOTS, MERCHANT_IMAGE_SLOT_KEYS, MERCHANT_LINK_KEYS, MERCHANT_LINK_PATHS, MERCHANT_OBJECT_FIELDS, MERCHANT_READ_ONLY_FIELDS, Merchant, MerchantColourKey, MerchantColourSet, MerchantColours, MerchantImageIds, MerchantImageSlot, MerchantImageSlotDefinition, MerchantLinkKey, MerchantLinks, MerchantPatch, MerchantResponse, MessageInfo, MutationState, ParsedBasket, Product, ProductInstance, ProductInstanceInput, ProductInstances, ProductResponse, ProductSaveInput, Promotion, PromotionResponse, PromotionRuleSet, QueryState, ReportData, ReportKey, ReportQuery, ReportQueryMap, ReportResponse, RepricedInstance, RequestOptions, ResourceDefinition, ResourceKind, SHOPWAVE_ENTITIES, SHOPWAVE_IMAGE_BASE_URL, SHOPWAVE_RESOURCES, SHOPWAVE_UPLOAD, Saved, SessionStatus, ShopwaveApiError, ShopwaveErrorMap, Store, StoreResponse, SubmitEntityArgs, SubmitEntityResponse, SuccessMessage, UPLOAD_KINDS, UpdateMerchantOptions, UploadImageParams, UploadKind, UploadMerchantImageOptions, UploadedImage, UseBasketReportReturn, User, UserEmployee, UserResponse, WritableEntityKind, apiDelete, apiGet, apiRequest, apiResponse, apiSend, assertNoApiErrors, authorizationFor, buildBasketReportQuery, buildConsumerMap, collectConsumerIds, collectProductIds, combineBasketRows, computeBasketSummary, coverCrop, deleteCategory, deleteEmployee, deleteEntity, deleteEntityById, deleteProduct, deletePromotion, deleteStore, fetchCategories, fetchCategory, fetchConsumer, fetchConsumers, fetchEmployee, fetchEmployees, fetchEntityById, fetchMerchant, fetchProduct, fetchProducts, fetchProductsMap, fetchPromotion, fetchPromotions, fetchReport, fetchSession, fetchStore, fetchStores, fetchUser, findRepricedInstances, fitImageToSize, formatDateForQuery, getApiErrorMap, getApiErrors, getImageUrl, getMerchantImage, getMerchantImageUrl, imageFileName, isSameInstancePrice, isUploadKind, loginPath, logout, logoutPath, merchantLinksFromForm, merchantLinksToForm, normalizeMerchantLinks, parseBasketReportData, readImageSize, rolesById, saveCategory, saveEmployee, saveEntities, saveEntity, saveProduct, savePromotion, saveStore, setMerchantImage, submitEntity, toProductInstancesForSave, toShopwaveApiError, toStoredImageIds, updateMerchant, uploadImage, uploadMerchantImage, useBasketReport, useCategory, useConsumer, useDelete, useEmployee, useLogout, useMerchant, useProduct, usePromotion, useReport, useSession, useStore, useSubmit, useUpdateMerchant, useUploadImage, useUploadMerchantImage, useUser, validateMerchant, withToken };
1303
1370
  //# sourceMappingURL=index.d.cts.map
package/dist/index.d.ts CHANGED
@@ -272,6 +272,64 @@ interface FetchProductsParams {
272
272
  * Fetches products. Returns the flattened `Product[]`.
273
273
  */
274
274
  declare function fetchProducts(params?: FetchProductsParams, options?: RequestOptions): Promise<Product[]>;
275
+ /** An instance as a form or caller holds it: `id` is absent for new rows. */
276
+ type ProductInstanceInput = {
277
+ id?: number | string | null;
278
+ price?: string | number | null;
279
+ taxPercentage?: string | number | null;
280
+ name?: string | null;
281
+ };
282
+ /** Instances as the API returns them (keyed by id) or as a plain list. */
283
+ type ProductInstances<T = ProductInstanceInput> = Readonly<Record<string, T>> | Readonly<Record<number, T>> | ReadonlyArray<T>;
284
+ /**
285
+ * What `saveProduct` accepts: any product fields, with `instances` either as the
286
+ * API returns them or as built by {@link toProductInstancesForSave}. Include `id`
287
+ * to update; leave it out to create.
288
+ */
289
+ type ProductSaveInput = Partial<Omit<Product, "instances">> & {
290
+ instances?: ProductInstances;
291
+ [field: string]: unknown;
292
+ };
293
+ /** True when two instances have the same price and tax (the fields Shopwave won't update). */
294
+ declare function isSameInstancePrice(a: ProductInstanceInput, b: ProductInstanceInput): boolean;
295
+ /** An instance whose price or tax was edited, so saving it will give it a new id. */
296
+ interface RepricedInstance {
297
+ /** Position of the instance in the list that was passed in. */
298
+ index: number;
299
+ /** The id it has now, which Shopwave will replace. */
300
+ id: number | string;
301
+ name: string;
302
+ before: {
303
+ price: string;
304
+ taxPercentage: string;
305
+ };
306
+ after: {
307
+ price: string;
308
+ taxPercentage: string;
309
+ };
310
+ }
311
+ /**
312
+ * Lists the instances whose price or tax differs from the `original` instance
313
+ * with the same id: saving them creates new instances with new ids, which can
314
+ * affect anything that stores instance ids (integrations, reports, modifiers).
315
+ * Use it to warn before saving. New rows (no id) aren't listed.
316
+ */
317
+ declare function findRepricedInstances(instances: ProductInstances | null | undefined, original: ProductInstances | null | undefined): RepricedInstance[];
318
+ /**
319
+ * Builds the `instances` map for a product save:
320
+ * - keyed by position (`"0"`, `"1"`, …), like every other ref in a save;
321
+ * - an instance keeps its `id` only when `original` has an instance with that id
322
+ * and the same price and tax; otherwise the id is removed, so Shopwave creates
323
+ * a new instance instead of re-pointing or rewriting someone else's;
324
+ * - server fields (`timestamp`) are removed.
325
+ *
326
+ * Pass the product as last read from the API as `original`. Leave it out for a
327
+ * new product (including a duplicate): every id is then removed.
328
+ * Instances left out of the list are left out of the save (removed).
329
+ */
330
+ declare function toProductInstancesForSave<T extends ProductInstanceInput>(instances: ProductInstances<T> | null | undefined, original?: ProductInstances | null): Record<string, Omit<T, "id"> & {
331
+ id?: number | string;
332
+ }>;
275
333
  /**
276
334
  * Fetches products by id and returns them keyed by id, transparently batching
277
335
  * the request (default 200 ids per call) to stay within API limits. Extracted
@@ -573,7 +631,16 @@ interface FetchByIdParams {
573
631
  }
574
632
  /** Reads one entity by id, or `null` when there's no such (non-deleted) record. */
575
633
  declare function fetchEntityById<K extends EntityKind>(kind: K, id: EntityId, params?: FetchByIdParams, options?: RequestOptions): Promise<EntityTypes[K] | null>;
576
- declare const saveProduct: (product: EntityInput<Product>, options?: RequestOptions) => Promise<Saved<Product>>;
634
+ /**
635
+ * Creates (no `id`) or updates (with `id`) a product.
636
+ *
637
+ * Shopwave instances (prices) can't be updated, only replaced. Build
638
+ * `instances` with {@link toProductInstancesForSave} (passing the product as last
639
+ * read) so an edited price is sent as a new instance. As a safeguard, a new
640
+ * product (no `id`, e.g. a duplicate) never sends instance ids: an id copied from
641
+ * another product would otherwise point the save at that product's instances.
642
+ */
643
+ declare const saveProduct: (product: ProductSaveInput, options?: RequestOptions) => Promise<Saved<Product>>;
577
644
  declare const deleteProduct: (id: EntityId, options?: RequestOptions) => Promise<void>;
578
645
  declare const fetchProduct: (id: EntityId, params?: FetchByIdParams, options?: RequestOptions) => Promise<Product | null>;
579
646
  declare const saveCategory: (category: EntityInput<Category>, options?: RequestOptions) => Promise<Saved<Category>>;
@@ -1299,5 +1366,5 @@ interface UseBasketReportReturn {
1299
1366
  */
1300
1367
  declare function useBasketReport(options?: RequestOptions): UseBasketReportReturn;
1301
1368
  //#endregion
1302
- export { Basket, BasketFilters, BasketItem, BasketPagination, BasketReportRow, BasketSummary, Category, CategoryResponse, CombineBasketRowsParams, Consumer, ConsumerResponse, CropRect, DEFAULT_BASKET_FILTERS, DEFAULT_PAGINATION, DeletableEntityKind, Employee, EmployeeResponse, EntityDefinition, EntityId, EntityInput, EntityKind, EntityTypes, ErrorMessage, Extras, FetchByIdParams, FetchCategoriesParams, FetchEmployeesParams, FetchProductsParams, FetchPromotionsParams, FetchStoresParams, FitImageOptions, ImageSize, MERCHANT_COLOUR_KEYS, MERCHANT_FIELD_MAX_LENGTH, MERCHANT_IMAGE_SLOTS, MERCHANT_IMAGE_SLOT_KEYS, MERCHANT_LINK_KEYS, MERCHANT_LINK_PATHS, MERCHANT_OBJECT_FIELDS, MERCHANT_READ_ONLY_FIELDS, Merchant, MerchantColourKey, MerchantColourSet, MerchantColours, MerchantImageIds, MerchantImageSlot, MerchantImageSlotDefinition, MerchantLinkKey, MerchantLinks, MerchantPatch, MerchantResponse, MessageInfo, MutationState, ParsedBasket, Product, ProductInstance, ProductResponse, Promotion, PromotionResponse, PromotionRuleSet, QueryState, ReportData, ReportKey, ReportQuery, ReportQueryMap, ReportResponse, RequestOptions, ResourceDefinition, ResourceKind, SHOPWAVE_ENTITIES, SHOPWAVE_IMAGE_BASE_URL, SHOPWAVE_RESOURCES, SHOPWAVE_UPLOAD, Saved, SessionStatus, ShopwaveApiError, ShopwaveErrorMap, Store, StoreResponse, SubmitEntityArgs, SubmitEntityResponse, SuccessMessage, UPLOAD_KINDS, UpdateMerchantOptions, UploadImageParams, UploadKind, UploadMerchantImageOptions, UploadedImage, UseBasketReportReturn, User, UserEmployee, UserResponse, WritableEntityKind, apiDelete, apiGet, apiRequest, apiResponse, apiSend, assertNoApiErrors, authorizationFor, buildBasketReportQuery, buildConsumerMap, collectConsumerIds, collectProductIds, combineBasketRows, computeBasketSummary, coverCrop, deleteCategory, deleteEmployee, deleteEntity, deleteEntityById, deleteProduct, deletePromotion, deleteStore, fetchCategories, fetchCategory, fetchConsumer, fetchConsumers, fetchEmployee, fetchEmployees, fetchEntityById, fetchMerchant, fetchProduct, fetchProducts, fetchProductsMap, fetchPromotion, fetchPromotions, fetchReport, fetchSession, fetchStore, fetchStores, fetchUser, fitImageToSize, formatDateForQuery, getApiErrorMap, getApiErrors, getImageUrl, getMerchantImage, getMerchantImageUrl, imageFileName, isUploadKind, loginPath, logout, logoutPath, merchantLinksFromForm, merchantLinksToForm, normalizeMerchantLinks, parseBasketReportData, readImageSize, rolesById, saveCategory, saveEmployee, saveEntities, saveEntity, saveProduct, savePromotion, saveStore, setMerchantImage, submitEntity, toShopwaveApiError, toStoredImageIds, updateMerchant, uploadImage, uploadMerchantImage, useBasketReport, useCategory, useConsumer, useDelete, useEmployee, useLogout, useMerchant, useProduct, usePromotion, useReport, useSession, useStore, useSubmit, useUpdateMerchant, useUploadImage, useUploadMerchantImage, useUser, validateMerchant, withToken };
1369
+ export { Basket, BasketFilters, BasketItem, BasketPagination, BasketReportRow, BasketSummary, Category, CategoryResponse, CombineBasketRowsParams, Consumer, ConsumerResponse, CropRect, DEFAULT_BASKET_FILTERS, DEFAULT_PAGINATION, DeletableEntityKind, Employee, EmployeeResponse, EntityDefinition, EntityId, EntityInput, EntityKind, EntityTypes, ErrorMessage, Extras, FetchByIdParams, FetchCategoriesParams, FetchEmployeesParams, FetchProductsParams, FetchPromotionsParams, FetchStoresParams, FitImageOptions, ImageSize, MERCHANT_COLOUR_KEYS, MERCHANT_FIELD_MAX_LENGTH, MERCHANT_IMAGE_SLOTS, MERCHANT_IMAGE_SLOT_KEYS, MERCHANT_LINK_KEYS, MERCHANT_LINK_PATHS, MERCHANT_OBJECT_FIELDS, MERCHANT_READ_ONLY_FIELDS, Merchant, MerchantColourKey, MerchantColourSet, MerchantColours, MerchantImageIds, MerchantImageSlot, MerchantImageSlotDefinition, MerchantLinkKey, MerchantLinks, MerchantPatch, MerchantResponse, MessageInfo, MutationState, ParsedBasket, Product, ProductInstance, ProductInstanceInput, ProductInstances, ProductResponse, ProductSaveInput, Promotion, PromotionResponse, PromotionRuleSet, QueryState, ReportData, ReportKey, ReportQuery, ReportQueryMap, ReportResponse, RepricedInstance, RequestOptions, ResourceDefinition, ResourceKind, SHOPWAVE_ENTITIES, SHOPWAVE_IMAGE_BASE_URL, SHOPWAVE_RESOURCES, SHOPWAVE_UPLOAD, Saved, SessionStatus, ShopwaveApiError, ShopwaveErrorMap, Store, StoreResponse, SubmitEntityArgs, SubmitEntityResponse, SuccessMessage, UPLOAD_KINDS, UpdateMerchantOptions, UploadImageParams, UploadKind, UploadMerchantImageOptions, UploadedImage, UseBasketReportReturn, User, UserEmployee, UserResponse, WritableEntityKind, apiDelete, apiGet, apiRequest, apiResponse, apiSend, assertNoApiErrors, authorizationFor, buildBasketReportQuery, buildConsumerMap, collectConsumerIds, collectProductIds, combineBasketRows, computeBasketSummary, coverCrop, deleteCategory, deleteEmployee, deleteEntity, deleteEntityById, deleteProduct, deletePromotion, deleteStore, fetchCategories, fetchCategory, fetchConsumer, fetchConsumers, fetchEmployee, fetchEmployees, fetchEntityById, fetchMerchant, fetchProduct, fetchProducts, fetchProductsMap, fetchPromotion, fetchPromotions, fetchReport, fetchSession, fetchStore, fetchStores, fetchUser, findRepricedInstances, fitImageToSize, formatDateForQuery, getApiErrorMap, getApiErrors, getImageUrl, getMerchantImage, getMerchantImageUrl, imageFileName, isSameInstancePrice, isUploadKind, loginPath, logout, logoutPath, merchantLinksFromForm, merchantLinksToForm, normalizeMerchantLinks, parseBasketReportData, readImageSize, rolesById, saveCategory, saveEmployee, saveEntities, saveEntity, saveProduct, savePromotion, saveStore, setMerchantImage, submitEntity, toProductInstancesForSave, toShopwaveApiError, toStoredImageIds, updateMerchant, uploadImage, uploadMerchantImage, useBasketReport, useCategory, useConsumer, useDelete, useEmployee, useLogout, useMerchant, useProduct, usePromotion, useReport, useSession, useStore, useSubmit, useUpdateMerchant, useUploadImage, useUploadMerchantImage, useUser, validateMerchant, withToken };
1303
1370
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -42,8 +42,8 @@ function getApiErrorMap(body) {
42
42
  }
43
43
  function describeErrors(errors) {
44
44
  return Object.entries(errors).map(([code, e]) => {
45
- const text = [e?.title, e?.details].filter(Boolean).join(": ");
46
- return text ? `${code} ${text}` : code;
45
+ const text$1 = [e?.title, e?.details].filter(Boolean).join(": ");
46
+ return text$1 ? `${code} ${text$1}` : code;
47
47
  }).join("; ");
48
48
  }
49
49
  /**
@@ -105,12 +105,12 @@ function buildExtras(extras) {
105
105
  }
106
106
  /** Parses a response body as JSON; `null` for an empty body, `{ raw }` for non-JSON. */
107
107
  async function readBody(response) {
108
- const text = await response.text();
109
- if (!text) return null;
108
+ const text$1 = await response.text();
109
+ if (!text$1) return null;
110
110
  try {
111
- return JSON.parse(text);
111
+ return JSON.parse(text$1);
112
112
  } catch {
113
- return { raw: text };
113
+ return { raw: text$1 };
114
114
  }
115
115
  }
116
116
  /**
@@ -258,6 +258,83 @@ async function fetchProducts(params = {}, options = {}) {
258
258
  assertNoApiErrors(json, 200);
259
259
  return Object.values(json?.products ?? {});
260
260
  }
261
+ /** Fields the server sets on an instance; never sent back. */
262
+ const SERVER_INSTANCE_FIELDS = ["timestamp"];
263
+ function instanceList(instances) {
264
+ if (!instances) return [];
265
+ return (Array.isArray(instances) ? [...instances] : Object.values(instances)).filter((inst) => inst != null && typeof inst === "object");
266
+ }
267
+ function hasId(id) {
268
+ return id != null && String(id).trim() !== "";
269
+ }
270
+ /** Same number, so `"422.0"`, `"422"` and `422` are equal; blanks equal each other. */
271
+ function sameAmount(a, b) {
272
+ const blank = (v) => v == null || String(v).trim() === "";
273
+ if (blank(a) || blank(b)) return blank(a) && blank(b);
274
+ const x = Number(a);
275
+ const y = Number(b);
276
+ return Number.isNaN(x) || Number.isNaN(y) ? String(a).trim() === String(b).trim() : x === y;
277
+ }
278
+ /** True when two instances have the same price and tax (the fields Shopwave won't update). */
279
+ function isSameInstancePrice(a, b) {
280
+ return sameAmount(a.price, b.price) && sameAmount(a.taxPercentage, b.taxPercentage);
281
+ }
282
+ const text = (v) => v == null ? "" : String(v);
283
+ /**
284
+ * Lists the instances whose price or tax differs from the `original` instance
285
+ * with the same id: saving them creates new instances with new ids, which can
286
+ * affect anything that stores instance ids (integrations, reports, modifiers).
287
+ * Use it to warn before saving. New rows (no id) aren't listed.
288
+ */
289
+ function findRepricedInstances(instances, original) {
290
+ const byId = new Map(instanceList(original).filter((o) => hasId(o.id)).map((o) => [String(o.id), o]));
291
+ const result = [];
292
+ instanceList(instances).forEach((inst, index) => {
293
+ if (!hasId(inst.id)) return;
294
+ const before = byId.get(String(inst.id));
295
+ if (!before || isSameInstancePrice(inst, before)) return;
296
+ result.push({
297
+ index,
298
+ id: inst.id,
299
+ name: text(inst.name),
300
+ before: {
301
+ price: text(before.price),
302
+ taxPercentage: text(before.taxPercentage)
303
+ },
304
+ after: {
305
+ price: text(inst.price),
306
+ taxPercentage: text(inst.taxPercentage)
307
+ }
308
+ });
309
+ });
310
+ return result;
311
+ }
312
+ /**
313
+ * Builds the `instances` map for a product save:
314
+ * - keyed by position (`"0"`, `"1"`, …), like every other ref in a save;
315
+ * - an instance keeps its `id` only when `original` has an instance with that id
316
+ * and the same price and tax; otherwise the id is removed, so Shopwave creates
317
+ * a new instance instead of re-pointing or rewriting someone else's;
318
+ * - server fields (`timestamp`) are removed.
319
+ *
320
+ * Pass the product as last read from the API as `original`. Leave it out for a
321
+ * new product (including a duplicate): every id is then removed.
322
+ * Instances left out of the list are left out of the save (removed).
323
+ */
324
+ function toProductInstancesForSave(instances, original) {
325
+ const keep = new Map(instanceList(original).filter((o) => hasId(o.id)).map((o) => [String(o.id), o]));
326
+ const out = {};
327
+ instanceList(instances).forEach((inst, index) => {
328
+ const { id,...rest } = inst;
329
+ for (const field of SERVER_INSTANCE_FIELDS) delete rest[field];
330
+ const before = hasId(id) ? keep.get(String(id)) : void 0;
331
+ out[String(index)] = before && isSameInstancePrice(inst, before) ? {
332
+ id,
333
+ ...rest
334
+ } : rest;
335
+ });
336
+ return out;
337
+ }
261
338
  /**
262
339
  * Fetches products by id and returns them keyed by id, transparently batching
263
340
  * the request (default 200 ids per call) to stay within API limits. Extracted
@@ -541,7 +618,21 @@ async function fetchEntityById(kind, id, params = {}, options = {}) {
541
618
  const map = body?.[def.collection] ?? {};
542
619
  return map[String(id)] ?? Object.values(map).find((e) => String(e?.id) === String(id)) ?? null;
543
620
  }
544
- const saveProduct = (product, options) => saveEntity("product", product, options);
621
+ /**
622
+ * Creates (no `id`) or updates (with `id`) a product.
623
+ *
624
+ * Shopwave instances (prices) can't be updated, only replaced. Build
625
+ * `instances` with {@link toProductInstancesForSave} (passing the product as last
626
+ * read) so an edited price is sent as a new instance. As a safeguard, a new
627
+ * product (no `id`, e.g. a duplicate) never sends instance ids: an id copied from
628
+ * another product would otherwise point the save at that product's instances.
629
+ */
630
+ const saveProduct = (product, options) => {
631
+ return saveEntity("product", (product.id == null || String(product.id).trim() === "") && product.instances != null ? {
632
+ ...product,
633
+ instances: toProductInstancesForSave(product.instances)
634
+ } : product, options);
635
+ };
545
636
  const deleteProduct = (id, options) => deleteEntityById("product", id, options);
546
637
  const fetchProduct = (id, params, options) => fetchEntityById("product", id, params, options);
547
638
  const saveCategory = (category, options) => saveEntity("category", category, options);
@@ -1730,5 +1821,5 @@ function useBasketReport(options) {
1730
1821
  }
1731
1822
 
1732
1823
  //#endregion
1733
- export { DEFAULT_BASKET_FILTERS, DEFAULT_PAGINATION, MERCHANT_COLOUR_KEYS, MERCHANT_FIELD_MAX_LENGTH, MERCHANT_IMAGE_SLOTS, MERCHANT_IMAGE_SLOT_KEYS, MERCHANT_LINK_KEYS, MERCHANT_LINK_PATHS, MERCHANT_OBJECT_FIELDS, MERCHANT_READ_ONLY_FIELDS, PromotionRuleSet, SHOPWAVE_ENTITIES, SHOPWAVE_IMAGE_BASE_URL, SHOPWAVE_RESOURCES, SHOPWAVE_UPLOAD, ShopwaveApiError, UPLOAD_KINDS, apiDelete, apiGet, apiRequest, apiSend, assertNoApiErrors, authorizationFor, buildBasketReportQuery, buildConsumerMap, collectConsumerIds, collectProductIds, combineBasketRows, computeBasketSummary, coverCrop, deleteCategory, deleteEmployee, deleteEntity, deleteEntityById, deleteProduct, deletePromotion, deleteStore, fetchCategories, fetchCategory, fetchConsumer, fetchConsumers, fetchEmployee, fetchEmployees, fetchEntityById, fetchMerchant, fetchProduct, fetchProducts, fetchProductsMap, fetchPromotion, fetchPromotions, fetchReport, fetchSession, fetchStore, fetchStores, fetchUser, fitImageToSize, formatDateForQuery, getApiErrorMap, getApiErrors, getImageUrl, getMerchantImage, getMerchantImageUrl, imageFileName, isUploadKind, loginPath, logout, logoutPath, merchantLinksFromForm, merchantLinksToForm, normalizeMerchantLinks, parseBasketReportData, readImageSize, rolesById, saveCategory, saveEmployee, saveEntities, saveEntity, saveProduct, savePromotion, saveStore, setMerchantImage, submitEntity, toShopwaveApiError, toStoredImageIds, updateMerchant, uploadImage, uploadMerchantImage, useBasketReport, useCategory, useConsumer, useDelete, useEmployee, useLogout, useMerchant, useProduct, usePromotion, useReport, useSession, useStore, useSubmit, useUpdateMerchant, useUploadImage, useUploadMerchantImage, useUser, validateMerchant, withToken };
1824
+ export { DEFAULT_BASKET_FILTERS, DEFAULT_PAGINATION, MERCHANT_COLOUR_KEYS, MERCHANT_FIELD_MAX_LENGTH, MERCHANT_IMAGE_SLOTS, MERCHANT_IMAGE_SLOT_KEYS, MERCHANT_LINK_KEYS, MERCHANT_LINK_PATHS, MERCHANT_OBJECT_FIELDS, MERCHANT_READ_ONLY_FIELDS, PromotionRuleSet, SHOPWAVE_ENTITIES, SHOPWAVE_IMAGE_BASE_URL, SHOPWAVE_RESOURCES, SHOPWAVE_UPLOAD, ShopwaveApiError, UPLOAD_KINDS, apiDelete, apiGet, apiRequest, apiSend, assertNoApiErrors, authorizationFor, buildBasketReportQuery, buildConsumerMap, collectConsumerIds, collectProductIds, combineBasketRows, computeBasketSummary, coverCrop, deleteCategory, deleteEmployee, deleteEntity, deleteEntityById, deleteProduct, deletePromotion, deleteStore, fetchCategories, fetchCategory, fetchConsumer, fetchConsumers, fetchEmployee, fetchEmployees, fetchEntityById, fetchMerchant, fetchProduct, fetchProducts, fetchProductsMap, fetchPromotion, fetchPromotions, fetchReport, fetchSession, fetchStore, fetchStores, fetchUser, findRepricedInstances, fitImageToSize, formatDateForQuery, getApiErrorMap, getApiErrors, getImageUrl, getMerchantImage, getMerchantImageUrl, imageFileName, isSameInstancePrice, isUploadKind, loginPath, logout, logoutPath, merchantLinksFromForm, merchantLinksToForm, normalizeMerchantLinks, parseBasketReportData, readImageSize, rolesById, saveCategory, saveEmployee, saveEntities, saveEntity, saveProduct, savePromotion, saveStore, setMerchantImage, submitEntity, toProductInstancesForSave, toShopwaveApiError, toStoredImageIds, updateMerchant, uploadImage, uploadMerchantImage, useBasketReport, useCategory, useConsumer, useDelete, useEmployee, useLogout, useMerchant, useProduct, usePromotion, useReport, useSession, useStore, useSubmit, useUpdateMerchant, useUploadImage, useUploadMerchantImage, useUser, validateMerchant, withToken };
1734
1825
  //# sourceMappingURL=index.js.map