@atomic-solutions/woocommerce-react 0.5.0 → 0.6.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.
@@ -1,4 +1,4 @@
1
- export { A as AppliedCoupon, C as CartTotals, a2 as InfiniteQueryOptions, a3 as MutationOptions, a as PaymentMethod, b as ProcessedCartItem, c as ProcessedCategory, d as ProcessedOrderDetails, e as ProcessedOrderLineItem, f as ProcessedProduct, g as ProcessedProductDetails, h as ProductCartState, i as ProductCategoryTreeNode, a4 as QueryOptions, S as ShippingRate, U as UseCartViewOptions, j as UseCartViewReturn, k as UseOrderViewOptions, l as UseOrderViewReturn, m as UseProductViewOptions, n as UseProductViewReturn, o as UseProductsFeedOptions, p as UseProductsFeedReturn, t as getOrderStatusLabel, y as useAddToCart, z as useApplyCoupon, B as useCart, D as useCartView, E as useCheckout, F as useInfiniteProducts, G as useOrder, H as useOrderView, J as useProcessCheckout, K as useProduct, L as useProductCategories, M as useProductCategoryTree, N as useProductView, O as useProducts, Q as useProductsFeed, R as useRemoveCoupon, T as useRemoveFromCart, V as useSelectShippingRate, W as useStore, X as useStoreFeatures, Y as useStoreLocale, Z as useStoreTheme, _ as useUpdateCartItem, $ as useUpdateCustomer, a0 as useWooCommerceClient, a1 as useWooCommerceQueryKeys } from '../index-DdY_1X-C.cjs';
2
- export { Q as QueryKeys, p as createQueryKeys } from '../types-_8YqnkO-.cjs';
1
+ export { A as AppliedCoupon, C as CartTotals, aj as InfiniteQueryOptions, ak as MutationOptions, a as PaymentMethod, b as ProcessedCartItem, c as ProcessedCategory, d as ProcessedOrderDetails, e as ProcessedOrderLineItem, f as ProcessedProduct, g as ProcessedProductDetails, h as ProductCartState, i as ProductCategoryTreeNode, al as QueryOptions, R as ReorderInputItem, j as ReorderItemView, k as ReorderUnavailableReason, S as ShippingRate, n as UseCartViewOptions, o as UseCartViewReturn, p as UseOrderViewOptions, q as UseOrderViewReturn, r as UseProductViewOptions, s as UseProductViewReturn, t as UseProductsFeedOptions, u as UseProductsFeedReturn, v as UseReorderViewOptions, w as UseReorderViewReturn, E as getOrderStatusLabel, Q as useAddManyToCart, T as useAddToCart, V as useApplyCoupon, W as useCart, X as useCartView, Y as useCheckout, Z as useInfiniteProducts, _ as useOrder, $ as useOrderView, a0 as useProcessCheckout, a1 as useProduct, a2 as useProductCategories, a3 as useProductCategoryTree, a4 as useProductView, a5 as useProducts, a6 as useProductsFeed, a7 as useRemoveCoupon, a8 as useRemoveFromCart, a9 as useReorderView, aa as useSelectShippingRate, ab as useStore, ac as useStoreFeatures, ad as useStoreLocale, ae as useStoreTheme, af as useUpdateCartItem, ag as useUpdateCustomer, ah as useWooCommerceClient, ai as useWooCommerceQueryKeys } from '../index-DEvJWFSF.cjs';
2
+ export { Q as QueryKeys, p as createQueryKeys } from '../types-Dnq60zh-.cjs';
3
3
  export { OrderStatus } from '@atomic-solutions/woocommerce-api-client';
4
4
  import '@tanstack/react-query';
@@ -1,4 +1,4 @@
1
- export { A as AppliedCoupon, C as CartTotals, a2 as InfiniteQueryOptions, a3 as MutationOptions, a as PaymentMethod, b as ProcessedCartItem, c as ProcessedCategory, d as ProcessedOrderDetails, e as ProcessedOrderLineItem, f as ProcessedProduct, g as ProcessedProductDetails, h as ProductCartState, i as ProductCategoryTreeNode, a4 as QueryOptions, S as ShippingRate, U as UseCartViewOptions, j as UseCartViewReturn, k as UseOrderViewOptions, l as UseOrderViewReturn, m as UseProductViewOptions, n as UseProductViewReturn, o as UseProductsFeedOptions, p as UseProductsFeedReturn, t as getOrderStatusLabel, y as useAddToCart, z as useApplyCoupon, B as useCart, D as useCartView, E as useCheckout, F as useInfiniteProducts, G as useOrder, H as useOrderView, J as useProcessCheckout, K as useProduct, L as useProductCategories, M as useProductCategoryTree, N as useProductView, O as useProducts, Q as useProductsFeed, R as useRemoveCoupon, T as useRemoveFromCart, V as useSelectShippingRate, W as useStore, X as useStoreFeatures, Y as useStoreLocale, Z as useStoreTheme, _ as useUpdateCartItem, $ as useUpdateCustomer, a0 as useWooCommerceClient, a1 as useWooCommerceQueryKeys } from '../index-unbfwba0.js';
2
- export { Q as QueryKeys, p as createQueryKeys } from '../types-_8YqnkO-.js';
1
+ export { A as AppliedCoupon, C as CartTotals, aj as InfiniteQueryOptions, ak as MutationOptions, a as PaymentMethod, b as ProcessedCartItem, c as ProcessedCategory, d as ProcessedOrderDetails, e as ProcessedOrderLineItem, f as ProcessedProduct, g as ProcessedProductDetails, h as ProductCartState, i as ProductCategoryTreeNode, al as QueryOptions, R as ReorderInputItem, j as ReorderItemView, k as ReorderUnavailableReason, S as ShippingRate, n as UseCartViewOptions, o as UseCartViewReturn, p as UseOrderViewOptions, q as UseOrderViewReturn, r as UseProductViewOptions, s as UseProductViewReturn, t as UseProductsFeedOptions, u as UseProductsFeedReturn, v as UseReorderViewOptions, w as UseReorderViewReturn, E as getOrderStatusLabel, Q as useAddManyToCart, T as useAddToCart, V as useApplyCoupon, W as useCart, X as useCartView, Y as useCheckout, Z as useInfiniteProducts, _ as useOrder, $ as useOrderView, a0 as useProcessCheckout, a1 as useProduct, a2 as useProductCategories, a3 as useProductCategoryTree, a4 as useProductView, a5 as useProducts, a6 as useProductsFeed, a7 as useRemoveCoupon, a8 as useRemoveFromCart, a9 as useReorderView, aa as useSelectShippingRate, ab as useStore, ac as useStoreFeatures, ad as useStoreLocale, ae as useStoreTheme, af as useUpdateCartItem, ag as useUpdateCustomer, ah as useWooCommerceClient, ai as useWooCommerceQueryKeys } from '../index-Dmlapl9c.js';
2
+ export { Q as QueryKeys, p as createQueryKeys } from '../types-Dnq60zh-.js';
3
3
  export { OrderStatus } from '@atomic-solutions/woocommerce-api-client';
4
4
  import '@tanstack/react-query';
@@ -1,6 +1,6 @@
1
1
  import { createContext, useContext, useMemo, useCallback, useState } from 'react';
2
2
  import { useQuery, useQueryClient, useMutation, useInfiniteQuery } from '@tanstack/react-query';
3
- import { WooCommerceApiError } from '@atomic-solutions/woocommerce-api-client';
3
+ import { WooCommerceApiError, mapWooCommerceCode } from '@atomic-solutions/woocommerce-api-client';
4
4
 
5
5
  // src/hooks/useWooCommerceClient.ts
6
6
  var WooCommerceContext = createContext(null);
@@ -193,6 +193,13 @@ var useCart = (options) => {
193
193
  getQuantity
194
194
  };
195
195
  };
196
+ var toWooError = (error) => error instanceof WooCommerceApiError ? error : new WooCommerceApiError({
197
+ code: "unknown_error",
198
+ message: error instanceof Error ? error.message : "Unknown error",
199
+ url: "",
200
+ method: "POST",
201
+ originalCode: "unknown_error"
202
+ });
196
203
  var useAddToCart = () => {
197
204
  const client = useWooCommerceClient();
198
205
  const queryKeys = useWooCommerceQueryKeys();
@@ -211,15 +218,50 @@ var useAddToCart = () => {
211
218
  },
212
219
  onError: (error) => {
213
220
  if (emitEvent) {
214
- const wooError = error instanceof WooCommerceApiError ? error : new WooCommerceApiError({
215
- code: "unknown_error",
216
- message: error instanceof Error ? error.message : "Unknown error",
217
- statusCode: 500,
218
- url: "",
219
- method: "POST",
220
- originalCode: "unknown_error"
221
- });
222
- emitEvent(createErrorEvent("cart:item_added", wooError));
221
+ emitEvent(createErrorEvent("cart:item_added", toWooError(error)));
222
+ }
223
+ }
224
+ });
225
+ };
226
+ var useAddManyToCart = () => {
227
+ const client = useWooCommerceClient();
228
+ const queryKeys = useWooCommerceQueryKeys();
229
+ const queryClient = useQueryClient();
230
+ const emitEvent = useEventEmitter();
231
+ return useMutation({
232
+ mutationKey: queryKeys.cart.mutations.addItems(),
233
+ mutationFn: (input) => client.cart.addItems(input),
234
+ onSuccess: ({ cart, results }) => {
235
+ queryClient.setQueryData(queryKeys.cart.details(), cart);
236
+ queryClient.invalidateQueries({ queryKey: queryKeys.cart.all });
237
+ if (!emitEvent) return;
238
+ results.forEach((result) => {
239
+ if (result.status >= 200 && result.status < 300) {
240
+ const addedItem = cart.items.find((item) => item.id === result.item.id);
241
+ if (addedItem) {
242
+ emitEvent(createSuccessEvent("cart:item_added", { item: addedItem, cart }));
243
+ }
244
+ return;
245
+ }
246
+ emitEvent(
247
+ createErrorEvent(
248
+ "cart:item_added",
249
+ new WooCommerceApiError({
250
+ code: mapWooCommerceCode(result.code),
251
+ originalCode: result.code ?? "unknown_error",
252
+ message: result.message ?? "Failed to add item to cart",
253
+ statusCode: result.status,
254
+ url: "",
255
+ method: "POST",
256
+ requestBody: result.item
257
+ })
258
+ )
259
+ );
260
+ });
261
+ },
262
+ onError: (error) => {
263
+ if (emitEvent) {
264
+ emitEvent(createErrorEvent("cart:item_added", toWooError(error)));
223
265
  }
224
266
  }
225
267
  });
@@ -242,15 +284,7 @@ var useUpdateCartItem = () => {
242
284
  },
243
285
  onError: (error) => {
244
286
  if (emitEvent) {
245
- const wooError = error instanceof WooCommerceApiError ? error : new WooCommerceApiError({
246
- code: "unknown_error",
247
- message: error instanceof Error ? error.message : "Unknown error",
248
- statusCode: 500,
249
- url: "",
250
- method: "POST",
251
- originalCode: "unknown_error"
252
- });
253
- emitEvent(createErrorEvent("cart:item_updated", wooError));
287
+ emitEvent(createErrorEvent("cart:item_updated", toWooError(error)));
254
288
  }
255
289
  }
256
290
  });
@@ -272,15 +306,7 @@ var useRemoveFromCart = () => {
272
306
  },
273
307
  onError: (error) => {
274
308
  if (emitEvent) {
275
- const wooError = error instanceof WooCommerceApiError ? error : new WooCommerceApiError({
276
- code: "unknown_error",
277
- message: error instanceof Error ? error.message : "Unknown error",
278
- statusCode: 500,
279
- url: "",
280
- method: "POST",
281
- originalCode: "unknown_error"
282
- });
283
- emitEvent(createErrorEvent("cart:item_removed", wooError));
309
+ emitEvent(createErrorEvent("cart:item_removed", toWooError(error)));
284
310
  }
285
311
  }
286
312
  });
@@ -302,15 +328,7 @@ var useApplyCoupon = () => {
302
328
  },
303
329
  onError: (error) => {
304
330
  if (emitEvent) {
305
- const wooError = error instanceof WooCommerceApiError ? error : new WooCommerceApiError({
306
- code: "unknown_error",
307
- message: error instanceof Error ? error.message : "Unknown error",
308
- statusCode: 500,
309
- url: "",
310
- method: "POST",
311
- originalCode: "unknown_error"
312
- });
313
- emitEvent(createErrorEvent("cart:coupon_applied", wooError));
331
+ emitEvent(createErrorEvent("cart:coupon_applied", toWooError(error)));
314
332
  }
315
333
  }
316
334
  });
@@ -332,15 +350,7 @@ var useRemoveCoupon = () => {
332
350
  },
333
351
  onError: (error) => {
334
352
  if (emitEvent) {
335
- const wooError = error instanceof WooCommerceApiError ? error : new WooCommerceApiError({
336
- code: "unknown_error",
337
- message: error instanceof Error ? error.message : "Unknown error",
338
- statusCode: 500,
339
- url: "",
340
- method: "POST",
341
- originalCode: "unknown_error"
342
- });
343
- emitEvent(createErrorEvent("cart:coupon_removed", wooError));
353
+ emitEvent(createErrorEvent("cart:coupon_removed", toWooError(error)));
344
354
  }
345
355
  }
346
356
  });
@@ -362,15 +372,7 @@ var useUpdateCustomer = () => {
362
372
  },
363
373
  onError: (error) => {
364
374
  if (emitEvent) {
365
- const wooError = error instanceof WooCommerceApiError ? error : new WooCommerceApiError({
366
- code: "unknown_error",
367
- message: error instanceof Error ? error.message : "Unknown error",
368
- statusCode: 500,
369
- url: "",
370
- method: "POST",
371
- originalCode: "unknown_error"
372
- });
373
- emitEvent(createErrorEvent("cart:customer_updated", wooError));
375
+ emitEvent(createErrorEvent("cart:customer_updated", toWooError(error)));
374
376
  }
375
377
  }
376
378
  });
@@ -392,15 +394,7 @@ var useSelectShippingRate = () => {
392
394
  },
393
395
  onError: (error) => {
394
396
  if (emitEvent) {
395
- const wooError = error instanceof WooCommerceApiError ? error : new WooCommerceApiError({
396
- code: "unknown_error",
397
- message: error instanceof Error ? error.message : "Unknown error",
398
- statusCode: 500,
399
- url: "",
400
- method: "POST",
401
- originalCode: "unknown_error"
402
- });
403
- emitEvent(createErrorEvent("cart:shipping_selected", wooError));
397
+ emitEvent(createErrorEvent("cart:shipping_selected", toWooError(error)));
404
398
  }
405
399
  }
406
400
  });
@@ -436,7 +430,6 @@ var useProcessCheckout = () => {
436
430
  const wooError = error instanceof WooCommerceApiError ? error : new WooCommerceApiError({
437
431
  code: "unknown_error",
438
432
  message: error instanceof Error ? error.message : "Unknown error",
439
- statusCode: 500,
440
433
  url: "",
441
434
  method: "POST",
442
435
  originalCode: "unknown_error"
@@ -477,6 +470,7 @@ var createQueryKeys = (prefix = ["woocommerce"]) => ({
477
470
  // Mutation keys
478
471
  mutations: {
479
472
  addItem: () => [...prefix, "cart", "mutation", "addItem"],
473
+ addItems: () => [...prefix, "cart", "mutation", "addItems"],
480
474
  updateItem: () => [...prefix, "cart", "mutation", "updateItem"],
481
475
  removeItem: () => [...prefix, "cart", "mutation", "removeItem"],
482
476
  applyCoupon: () => [...prefix, "cart", "mutation", "applyCoupon"],
@@ -697,6 +691,15 @@ function isPurchasable(status, quantity, manageStock = true) {
697
691
  }
698
692
  return true;
699
693
  }
694
+ function unavailableReason(product) {
695
+ if (!product.is_in_stock || product.is_on_backorder || product.add_to_cart.maximum <= 0) {
696
+ return "out_of_stock";
697
+ }
698
+ if (!product.is_purchasable) {
699
+ return "not_purchasable";
700
+ }
701
+ return void 0;
702
+ }
700
703
  function isLowStock(status, quantity, threshold = 5) {
701
704
  return status === "instock" && quantity !== null && quantity !== void 0 && quantity <= threshold && quantity > 0;
702
705
  }
@@ -1133,6 +1136,98 @@ function useCartView(options = {}) {
1133
1136
  isBusy
1134
1137
  };
1135
1138
  }
1139
+ function useReorderView(items, options = {}) {
1140
+ const { imageSize = "thumbnail" } = options;
1141
+ const storeContext = useContext(WooCommerceStoreContext);
1142
+ const storeConfig = storeContext?.config;
1143
+ const localeTag = options.localeTag ?? storeConfig?.locale?.localeTag ?? DEFAULT_STORE_CONFIG.locale.localeTag;
1144
+ const fallbackImageUrl = options.fallbackImageUrl ?? storeConfig?.fallbackImageUrl;
1145
+ const imageUrlTransformer = storeConfig?.imageUrlTransformer;
1146
+ const productIds = useMemo(() => [...new Set(items.map((item) => item.productId))], [items]);
1147
+ const {
1148
+ data: productsPage,
1149
+ isLoading,
1150
+ error
1151
+ } = useProducts(
1152
+ { include: productIds, page: 1, per_page: 100 },
1153
+ { enabled: productIds.length > 0 }
1154
+ );
1155
+ const { data: cart } = useCart();
1156
+ const getProcessedImageUrl = useCallback(
1157
+ (images) => {
1158
+ const baseUrl = getImageUrl(images, imageSize, fallbackImageUrl);
1159
+ if (baseUrl && imageUrlTransformer) {
1160
+ return imageUrlTransformer(baseUrl, imageSize);
1161
+ }
1162
+ return baseUrl;
1163
+ },
1164
+ [imageSize, fallbackImageUrl, imageUrlTransformer]
1165
+ );
1166
+ const views = useMemo(() => {
1167
+ const products = new Map((productsPage?.data ?? []).map((product) => [product.id, product]));
1168
+ return items.map((item) => {
1169
+ const product = products.get(item.productId);
1170
+ if (!product) {
1171
+ return {
1172
+ productId: item.productId,
1173
+ name: "",
1174
+ requestedQuantity: item.quantity,
1175
+ minQuantity: 1,
1176
+ maxQuantity: 0,
1177
+ unitPrice: "-",
1178
+ lineTotal: "-",
1179
+ reason: "missing"
1180
+ };
1181
+ }
1182
+ const currencyCode = product.prices.currency_code;
1183
+ const minQuantity = product.add_to_cart.minimum || 1;
1184
+ const maxQuantity = product.add_to_cart.maximum;
1185
+ const step = product.add_to_cart.multiple_of || 1;
1186
+ const upperQuantity = maxQuantity > 0 ? maxQuantity : item.quantity;
1187
+ const clampedQuantity = Math.min(Math.max(item.quantity, minQuantity), upperQuantity);
1188
+ const requestedQuantity = step > 1 ? Math.max(step, Math.floor(clampedQuantity / step) * step) : clampedQuantity;
1189
+ const unitAmount = Number(product.prices.price);
1190
+ const reason = unavailableReason(product);
1191
+ return {
1192
+ productId: product.id,
1193
+ name: product.name,
1194
+ imageUrl: getProcessedImageUrl(product.images),
1195
+ requestedQuantity,
1196
+ minQuantity,
1197
+ maxQuantity,
1198
+ unitPrice: formatStoreApiPriceIntl(product.prices.price, currencyCode, localeTag),
1199
+ lineTotal: formatStoreApiPriceIntl(
1200
+ Number.isNaN(unitAmount) ? null : String(unitAmount * requestedQuantity),
1201
+ currencyCode,
1202
+ localeTag
1203
+ ),
1204
+ ...reason ? { reason } : {},
1205
+ raw: product
1206
+ };
1207
+ });
1208
+ }, [items, productsPage?.data, localeTag, getProcessedImageUrl]);
1209
+ const cartProductIds = useMemo(
1210
+ () => new Set((cart?.items ?? []).map((item) => item.id)),
1211
+ [cart?.items]
1212
+ );
1213
+ const { addable, inCart, unavailable } = useMemo(
1214
+ () => ({
1215
+ addable: views.filter((view) => !view.reason && !cartProductIds.has(view.productId)),
1216
+ inCart: views.filter((view) => !view.reason && cartProductIds.has(view.productId)),
1217
+ unavailable: views.filter((view) => !!view.reason)
1218
+ }),
1219
+ [views, cartProductIds]
1220
+ );
1221
+ return {
1222
+ addable,
1223
+ inCart,
1224
+ unavailable,
1225
+ availableCount: addable.length + inCart.length,
1226
+ totalCount: views.length,
1227
+ isLoading,
1228
+ error
1229
+ };
1230
+ }
1136
1231
  var ORDER_STATUS_LABELS = {
1137
1232
  pending: "Pending Payment",
1138
1233
  processing: "Processing",
@@ -1182,6 +1277,6 @@ function useOrderView(input, options = {}) {
1182
1277
  };
1183
1278
  }
1184
1279
 
1185
- export { createQueryKeys, getOrderStatusLabel, useAddToCart, useApplyCoupon, useCart, useCartView, useCheckout, useInfiniteProducts, useOrder, useOrderView, useProcessCheckout, useProduct, useProductCategories, useProductCategoryTree, useProductView, useProducts, useProductsFeed, useRemoveCoupon, useRemoveFromCart, useSelectShippingRate, useStore, useStoreFeatures, useStoreLocale, useStoreTheme, useUpdateCartItem, useUpdateCustomer, useWooCommerceClient, useWooCommerceQueryKeys };
1280
+ export { createQueryKeys, getOrderStatusLabel, useAddManyToCart, useAddToCart, useApplyCoupon, useCart, useCartView, useCheckout, useInfiniteProducts, useOrder, useOrderView, useProcessCheckout, useProduct, useProductCategories, useProductCategoryTree, useProductView, useProducts, useProductsFeed, useRemoveCoupon, useRemoveFromCart, useReorderView, useSelectShippingRate, useStore, useStoreFeatures, useStoreLocale, useStoreTheme, useUpdateCartItem, useUpdateCustomer, useWooCommerceClient, useWooCommerceQueryKeys };
1186
1281
  //# sourceMappingURL=index.js.map
1187
1282
  //# sourceMappingURL=index.js.map