@shopware/composables 0.0.0-canary-20250116155626

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.
Files changed (137) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +172 -0
  3. package/composables/index.ts +1 -0
  4. package/dist/index.d.mts +2239 -0
  5. package/dist/index.d.ts +2239 -0
  6. package/dist/index.mjs +2686 -0
  7. package/nuxt.config.ts +14 -0
  8. package/package.json +83 -0
  9. package/src/_test/index.ts +1 -0
  10. package/src/_test/useSetup.ts +43 -0
  11. package/src/cms/README.md +9 -0
  12. package/src/cms/cmsAssociations.ts +28 -0
  13. package/src/cms/index.ts +2 -0
  14. package/src/cms/useCmsElementConfig.test.ts +145 -0
  15. package/src/cms/useCmsElementConfig.ts +29 -0
  16. package/src/cms/useCmsElementImage.test.ts +179 -0
  17. package/src/cms/useCmsElementImage.ts +103 -0
  18. package/src/cms/useCmsElementProductBox.test.ts +15 -0
  19. package/src/cms/useCmsElementProductBox.ts +25 -0
  20. package/src/createShopwareContext.test.ts +23 -0
  21. package/src/createShopwareContext.ts +43 -0
  22. package/src/devtools/plugin.ts +201 -0
  23. package/src/helpers/ContextError.spec.ts +20 -0
  24. package/src/helpers/ContextError.ts +6 -0
  25. package/src/index.test.ts +54 -0
  26. package/src/index.ts +111 -0
  27. package/src/mocks/Cart.ts +774 -0
  28. package/src/mocks/CmsPage.ts +544 -0
  29. package/src/mocks/CmsProductBox.ts +377 -0
  30. package/src/mocks/Configurator.ts +123 -0
  31. package/src/mocks/Country.ts +184 -0
  32. package/src/mocks/CrossSellingResponse.ts +552 -0
  33. package/src/mocks/LandingPage.ts +62 -0
  34. package/src/mocks/Menu.ts +598 -0
  35. package/src/mocks/Order.ts +1151 -0
  36. package/src/mocks/Product.ts +473 -0
  37. package/src/mocks/ProductTierPrices.ts +771 -0
  38. package/src/mocks/Salutations.ts +51 -0
  39. package/src/mocks/Search.ts +518 -0
  40. package/src/types/cmsBlockTypes.ts +80 -0
  41. package/src/types/cmsElementTypes.ts +381 -0
  42. package/src/types/cmsSectionTypes.ts +15 -0
  43. package/src/types/index.ts +52 -0
  44. package/src/useAddToCart/useAddToCart.test.ts +39 -0
  45. package/src/useAddToCart/useAddToCart.ts +90 -0
  46. package/src/useAddress/useAddress.test.ts +134 -0
  47. package/src/useAddress/useAddress.ts +202 -0
  48. package/src/useB2bQuoteManagement/useB2bQuoteManagement.test.ts +137 -0
  49. package/src/useB2bQuoteManagement/useB2bQuoteManagement.ts +225 -0
  50. package/src/useBreadcrumbs/useBreadcrumbs.test.ts +71 -0
  51. package/src/useBreadcrumbs/useBreadcrumbs.ts +89 -0
  52. package/src/useCart/useCart.test.ts +251 -0
  53. package/src/useCart/useCart.ts +314 -0
  54. package/src/useCartErrorParamsResolver/useCartErrorParamsResolver.test.ts +122 -0
  55. package/src/useCartErrorParamsResolver/useCartErrorParamsResolver.ts +80 -0
  56. package/src/useCartItem/useCartItem.test.ts +168 -0
  57. package/src/useCartItem/useCartItem.ts +157 -0
  58. package/src/useCartNotification/useCartNotification.test.ts +129 -0
  59. package/src/useCartNotification/useCartNotification.ts +63 -0
  60. package/src/useCategory/useCategory.test.ts +14 -0
  61. package/src/useCategory/useCategory.ts +32 -0
  62. package/src/useCategorySearch/useCategorySearch.test.ts +98 -0
  63. package/src/useCategorySearch/useCategorySearch.ts +81 -0
  64. package/src/useCheckout/useCheckout.test.ts +104 -0
  65. package/src/useCheckout/useCheckout.ts +163 -0
  66. package/src/useCmsBlock/useCmsBlock.test.ts +25 -0
  67. package/src/useCmsBlock/useCmsBlock.ts +36 -0
  68. package/src/useCmsMeta/useCmsMeta.test.ts +17 -0
  69. package/src/useCmsMeta/useCmsMeta.ts +46 -0
  70. package/src/useCmsSection/useCmsSection.test.ts +18 -0
  71. package/src/useCmsSection/useCmsSection.ts +39 -0
  72. package/src/useCmsTranslations/useCmsTranslations.test.ts +10 -0
  73. package/src/useCmsTranslations/useCmsTranslations.ts +9 -0
  74. package/src/useContext/useContext.ts +36 -0
  75. package/src/useCountries/useCountries.test.ts +64 -0
  76. package/src/useCountries/useCountries.ts +64 -0
  77. package/src/useCustomerOrders/useCustomerOrders.test.ts +47 -0
  78. package/src/useCustomerOrders/useCustomerOrders.ts +89 -0
  79. package/src/useCustomerPassword/useCustomerPassword.test.ts +164 -0
  80. package/src/useCustomerPassword/useCustomerPassword.ts +57 -0
  81. package/src/useDefaultOrderAssociations/useDefaultOrderAssociations.test.ts +41 -0
  82. package/src/useDefaultOrderAssociations/useDefaultOrderAssociations.ts +45 -0
  83. package/src/useInternationalization/useInternationalization.test.ts +155 -0
  84. package/src/useInternationalization/useInternationalization.ts +159 -0
  85. package/src/useLandingSearch/useLandingSearch.test.ts +30 -0
  86. package/src/useLandingSearch/useLandingSearch.ts +58 -0
  87. package/src/useListing/useListing.test.ts +249 -0
  88. package/src/useListing/useListing.ts +592 -0
  89. package/src/useLocalWishlist/useLocalWishlist.test.ts +54 -0
  90. package/src/useLocalWishlist/useLocalWishlist.ts +95 -0
  91. package/src/useNavigation/useNavigation.test.ts +68 -0
  92. package/src/useNavigation/useNavigation.ts +83 -0
  93. package/src/useNavigationContext/useNavigationContext.test.ts +48 -0
  94. package/src/useNavigationContext/useNavigationContext.ts +39 -0
  95. package/src/useNavigationSearch/useNavigationSearch.test.ts +110 -0
  96. package/src/useNavigationSearch/useNavigationSearch.ts +60 -0
  97. package/src/useNewsletter/useNewsletter.test.ts +55 -0
  98. package/src/useNewsletter/useNewsletter.ts +109 -0
  99. package/src/useNotifications/useNotifications.test.ts +56 -0
  100. package/src/useNotifications/useNotifications.ts +119 -0
  101. package/src/useOrderDetails/useOrderDetails.test.ts +224 -0
  102. package/src/useOrderDetails/useOrderDetails.ts +329 -0
  103. package/src/useOrderPayment/useOrderPayment.test.ts +80 -0
  104. package/src/useOrderPayment/useOrderPayment.ts +119 -0
  105. package/src/usePrice/usePrice.test.ts +97 -0
  106. package/src/usePrice/usePrice.ts +106 -0
  107. package/src/useProduct/useProduct.test.ts +36 -0
  108. package/src/useProduct/useProduct.ts +56 -0
  109. package/src/useProductAssociations/useProductAssociations.spec.ts +105 -0
  110. package/src/useProductAssociations/useProductAssociations.ts +107 -0
  111. package/src/useProductConfigurator/useProductConfigurator.spec.ts +77 -0
  112. package/src/useProductConfigurator/useProductConfigurator.ts +134 -0
  113. package/src/useProductPrice/useProductPrice.test.ts +126 -0
  114. package/src/useProductPrice/useProductPrice.ts +131 -0
  115. package/src/useProductReviews/useProductReviews.test.ts +45 -0
  116. package/src/useProductReviews/useProductReviews.ts +80 -0
  117. package/src/useProductSearch/useProductSearch.test.ts +37 -0
  118. package/src/useProductSearch/useProductSearch.ts +58 -0
  119. package/src/useProductSearchSuggest/useProductSearchSuggest.test.ts +19 -0
  120. package/src/useProductSearchSuggest/useProductSearchSuggest.ts +67 -0
  121. package/src/useProductWishlist/useProductWishlist.test.ts +63 -0
  122. package/src/useProductWishlist/useProductWishlist.ts +74 -0
  123. package/src/useSalutations/useSalutations.spec.ts +37 -0
  124. package/src/useSalutations/useSalutations.ts +55 -0
  125. package/src/useSessionContext/useSessionContext.test.ts +221 -0
  126. package/src/useSessionContext/useSessionContext.ts +281 -0
  127. package/src/useShopwareContext/useShopwareContext.test.ts +8 -0
  128. package/src/useShopwareContext/useShopwareContext.ts +31 -0
  129. package/src/useSyncWishlist/useSyncWishlist.test.ts +117 -0
  130. package/src/useSyncWishlist/useSyncWishlist.ts +117 -0
  131. package/src/useUrlResolver/useUrlResolver.test.ts +25 -0
  132. package/src/useUrlResolver/useUrlResolver.ts +31 -0
  133. package/src/useUser/useUser.test.ts +290 -0
  134. package/src/useUser/useUser.ts +321 -0
  135. package/src/useWishlist/useWishlist.test.ts +178 -0
  136. package/src/useWishlist/useWishlist.ts +128 -0
  137. package/types/api-types.ts +11 -0
@@ -0,0 +1,106 @@
1
+ import { createSharedComposable } from "@vueuse/core";
2
+ import { computed, ref, watch } from "vue";
3
+ import type { ComputedRef } from "vue";
4
+ import { useSessionContext } from "#imports";
5
+
6
+ export type UsePriceReturn = {
7
+ /**
8
+ * Format price i.e. (2) -> 2.00 $
9
+ */
10
+ getFormattedPrice(value: number | string | undefined): string;
11
+ /**
12
+ * Update configuration
13
+ */
14
+ update(params: {
15
+ localeCode: string | undefined;
16
+ currencyCode: string;
17
+ }): void;
18
+ /**
19
+ * Currency code
20
+ */
21
+ currencyCode: ComputedRef<string>;
22
+ };
23
+
24
+ /**
25
+ * Composable for getting formatted price
26
+ * Set the default currency code and locale in order to format a price correctly
27
+ *
28
+ * @public
29
+ * @category Product
30
+ */
31
+ function _usePrice(params?: {
32
+ localeCode: string | undefined;
33
+ currencyCode: string;
34
+ }): UsePriceReturn {
35
+ const { sessionContext } = useSessionContext();
36
+ const currencyLocale = ref<string | undefined>();
37
+ const currencyCode = ref<string>("");
38
+
39
+ if (params) {
40
+ currencyCode.value = params.currencyCode;
41
+ currencyLocale.value = params.localeCode;
42
+ }
43
+
44
+ function update(params: {
45
+ localeCode?: string | undefined;
46
+ currencyCode: string;
47
+ }) {
48
+ _setCurrencyCode(params.currencyCode);
49
+ _setLocaleCode(
50
+ params.localeCode ||
51
+ currencyLocale.value ||
52
+ (typeof navigator !== "undefined" && navigator?.language) ||
53
+ "en-US",
54
+ );
55
+ }
56
+
57
+ function _setCurrencyCode(code: string) {
58
+ currencyCode.value = code;
59
+ }
60
+
61
+ function _setLocaleCode(locale: string) {
62
+ currencyLocale.value = locale;
63
+ }
64
+
65
+ /**
66
+ * Format price (2) -> $ 2.00
67
+ */
68
+ function getFormattedPrice(value: number | string | undefined): string {
69
+ if (typeof value === "undefined") {
70
+ return "";
71
+ }
72
+
73
+ if (!currencyLocale.value) {
74
+ return value.toString();
75
+ }
76
+
77
+ return new Intl.NumberFormat(currencyLocale.value, {
78
+ style: "currency",
79
+ currency: currencyCode.value,
80
+ }).format(+value);
81
+ }
82
+
83
+ watch(
84
+ () => sessionContext.value?.currency,
85
+ (newCurrency) => {
86
+ if (newCurrency)
87
+ update({
88
+ // locale code is read only once on SSR because it's unavailable in the context
89
+ currencyCode: newCurrency?.isoCode,
90
+ });
91
+ },
92
+ {
93
+ immediate: true,
94
+ },
95
+ );
96
+
97
+ return {
98
+ getFormattedPrice,
99
+ update,
100
+ currencyCode: computed(() => currencyCode.value),
101
+ };
102
+ }
103
+ /**
104
+ * @category Product
105
+ */
106
+ export const usePrice = createSharedComposable(_usePrice);
@@ -0,0 +1,36 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { ref } from "vue";
3
+ import { useSetup } from "../_test";
4
+ import mockedProduct from "../mocks/Product";
5
+ import { useProduct } from "./useProduct";
6
+
7
+ describe("useProduct", () => {
8
+ it("should return product object", () => {
9
+ const { vm } = useSetup(() => useProduct(mockedProduct));
10
+
11
+ expect(vm.product).toStrictEqual(mockedProduct);
12
+ });
13
+
14
+ it("changeVariant - should merge the current product with the new variant data", () => {
15
+ const { vm } = useSetup(() => useProduct(mockedProduct));
16
+ expect(vm.changeVariant()).toBeUndefined();
17
+ });
18
+
19
+ it("changeVariant - empty", () => {
20
+ const { vm } = useSetup(useProduct);
21
+
22
+ vm.changeVariant(Object.assign({ ...mockedProduct }, { id: "new-id" }));
23
+ expect(vm.product.id).toBe("new-id");
24
+ });
25
+
26
+ it("init without product should throw an error", () => {
27
+ expect(() =>
28
+ useSetup(() =>
29
+ useProduct(
30
+ // @ts-expect-error if API returns null we want to be prepared for it
31
+ ref(null),
32
+ ),
33
+ ),
34
+ ).toThrowError("Product context is not provided");
35
+ });
36
+ });
@@ -0,0 +1,56 @@
1
+ import { computed } from "vue";
2
+ import type { ComputedRef, Ref } from "vue";
3
+ import { useContext } from "#imports";
4
+ import type { Schemas } from "#shopware";
5
+ import ContextError from "../helpers/ContextError";
6
+
7
+ export type UseProductReturn = {
8
+ /**
9
+ * Returns product object
10
+ * {@link Product} object
11
+ */
12
+ product: ComputedRef<Schemas["Product"]>;
13
+ /**
14
+ * {@link PropertyGroup} array that defines the product possible configurations
15
+ */
16
+ configurator: ComputedRef<Schemas["PropertyGroup"][]>;
17
+ /**
18
+ * Merges the current product with the new variant data
19
+ * @param variant - {@link Product} object with the new variant data
20
+ */
21
+ changeVariant(variant?: Partial<Schemas["Product"]>): void;
22
+ };
23
+
24
+ /**
25
+ * Composable for product management.
26
+ * @public
27
+ * @category Product
28
+ */
29
+ export function useProduct(
30
+ product?: Ref<Schemas["Product"]> | Schemas["Product"],
31
+ configurator?: Ref<Schemas["PropertyGroup"][]> | Schemas["PropertyGroup"][],
32
+ ): UseProductReturn {
33
+ const _product = useContext("product", { context: product });
34
+ if (!_product.value) {
35
+ // TODO link docs with composables context usage
36
+ throw new ContextError("Product");
37
+ }
38
+
39
+ const _configurator = useContext("configurator", {
40
+ context: product && configurator,
41
+ });
42
+
43
+ function changeVariant(variant?: Partial<Schemas["Product"]>) {
44
+ if (!variant) {
45
+ console.warn("[useProduct][changeVariant]: Provided variant is empty");
46
+ return;
47
+ }
48
+ _product.value = Object.assign({}, _product.value, variant);
49
+ }
50
+
51
+ return {
52
+ product: computed(() => _product.value),
53
+ configurator: computed(() => _configurator.value),
54
+ changeVariant,
55
+ };
56
+ }
@@ -0,0 +1,105 @@
1
+ import { describe, expect, it, vi } from "vitest";
2
+ import { computed, ref } from "vue";
3
+ import { useSetup } from "../_test";
4
+ import mockedCrossSelling from "../mocks/CrossSellingResponse";
5
+ import mockedProduct from "../mocks/Product";
6
+ import { useProductAssociations } from "./useProductAssociations";
7
+
8
+ describe("useProductAssociations", () => {
9
+ console.error = vi.fn();
10
+
11
+ it("productAssociations should be empty", () => {
12
+ const { vm } = useSetup(() =>
13
+ useProductAssociations(
14
+ computed(() => mockedProduct),
15
+ {
16
+ associationContext: "cross-selling",
17
+ },
18
+ ),
19
+ );
20
+
21
+ expect(vm.productAssociations).toStrictEqual([]);
22
+ });
23
+
24
+ it("load productAssociations - GET - Error", async () => {
25
+ const { vm, injections } = useSetup(() =>
26
+ useProductAssociations(
27
+ computed(() => mockedProduct),
28
+ {
29
+ associationContext: "cross-selling",
30
+ },
31
+ ),
32
+ );
33
+ injections.apiClient.invoke.mockRejectedValue("PROBLEM");
34
+
35
+ await vm.loadAssociations({
36
+ searchParams: {},
37
+ });
38
+ expect(vm.productAssociations).toStrictEqual([]);
39
+ expect(console.error).toBeCalledWith(
40
+ "[useProductAssociations][loadAssociations][error]:",
41
+ "PROBLEM",
42
+ );
43
+ });
44
+
45
+ it("load productAssociations - POST", async () => {
46
+ const { vm, injections } = useSetup(() =>
47
+ useProductAssociations(
48
+ computed(() => mockedProduct),
49
+ {
50
+ associationContext: "cross-selling",
51
+ },
52
+ ),
53
+ );
54
+ injections.apiClient.invoke.mockResolvedValue({ data: mockedCrossSelling });
55
+
56
+ await vm.loadAssociations({
57
+ method: "post",
58
+ searchParams: {
59
+ associations: {
60
+ media: {},
61
+ cover: {
62
+ associations: {
63
+ media: {},
64
+ },
65
+ },
66
+ },
67
+ },
68
+ });
69
+
70
+ expect(vm.productAssociations).toStrictEqual(mockedCrossSelling);
71
+ });
72
+
73
+ it("load productAssociations - POST - no search params", async () => {
74
+ const { vm, injections } = useSetup(() =>
75
+ useProductAssociations(
76
+ computed(() => mockedProduct),
77
+ {
78
+ associationContext: "cross-selling",
79
+ },
80
+ ),
81
+ );
82
+ injections.apiClient.invoke.mockResolvedValue({ data: mockedCrossSelling });
83
+
84
+ await vm.loadAssociations({
85
+ method: "post",
86
+ searchParams: {},
87
+ });
88
+
89
+ expect(vm.productAssociations).toStrictEqual(mockedCrossSelling);
90
+ });
91
+
92
+ it("init without product should throw an error", () => {
93
+ expect(() =>
94
+ useSetup(() =>
95
+ useProductAssociations(
96
+ // @ts-expect-error if API returns null we want to be prepared for it
97
+ ref(null),
98
+ {
99
+ associationContext: "cross-selling",
100
+ },
101
+ ),
102
+ ),
103
+ ).toThrowError("[useProductAssociations]: Product is not provided.");
104
+ });
105
+ });
@@ -0,0 +1,107 @@
1
+ import { computed, ref } from "vue";
2
+ import type { ComputedRef } from "vue";
3
+ import { useShopwareContext } from "#imports";
4
+ import type { Schemas } from "#shopware";
5
+
6
+ export type UseProductAssociationsReturn = {
7
+ /**
8
+ * Start loading resources. Search Parameters and HTTP method can be passed.
9
+ *
10
+ */
11
+ loadAssociations(params: {
12
+ method?: "post" | "get";
13
+ searchParams: Schemas["Criteria"];
14
+ }): Promise<void>;
15
+ /**
16
+ * If it's loading - indicator
17
+ */
18
+ isLoading: ComputedRef<boolean>;
19
+ /**
20
+ * Product associations, like CrossSelling[]
21
+ */
22
+ productAssociations: ComputedRef<Schemas["CrossSellingElementCollection"]>;
23
+ };
24
+
25
+ /**
26
+ * Get product association entity.
27
+ * @public
28
+ * @category Product
29
+ */
30
+ export function useProductAssociations(
31
+ product: ComputedRef<Schemas["Product"]>,
32
+ options: {
33
+ associationContext: "cross-selling" | "reviews";
34
+ },
35
+ ): UseProductAssociationsReturn {
36
+ if (!product.value)
37
+ throw new Error("[useProductAssociations]: Product is not provided.");
38
+
39
+ // @ts-ignore: temporary until fixed or removed
40
+ const association = options.associationContext;
41
+
42
+ const { apiClient } = useShopwareContext();
43
+ const isLoading = ref(false);
44
+ const associations = ref<Schemas["CrossSellingElementCollection"]>([]);
45
+
46
+ // params: {
47
+ // method?: "post" | "get";
48
+ // searchParams: Schemas["Criteria"];
49
+ // }
50
+ const loadAssociations = async () => {
51
+ isLoading.value = true;
52
+ // const method = params.method || "get";
53
+ try {
54
+ // TODO: someting might be wrong with the endpoint, figure it out and fix definitions
55
+ // if (method && method === "get") {
56
+ // // const response = await invokeGet(
57
+ // // {
58
+ // // address: `${getProductDetailsEndpoint(
59
+ // // product.value.id as string,
60
+ // // )}/${association}${params.searchParams || ""}`,
61
+ // // },
62
+ // // apiInstance,
63
+ // // );
64
+ // const response = await apiClient.invoke(
65
+ // "readProductDetail post /product/{productId}",
66
+ // {
67
+ // productId: product.value.id,
68
+ // },
69
+ // );
70
+
71
+ // associations.value = response?.data as [];
72
+ // return;
73
+ // }
74
+
75
+ // const response = await invokePost(
76
+ // {
77
+ // address: `${getProductDetailsEndpoint(
78
+ // product.value.id as string,
79
+ // )}/${association}`,
80
+ // payload: params?.searchParams || {},
81
+ // },
82
+ // apiInstance,
83
+ // );
84
+ const response = await apiClient.invoke(
85
+ "readProductCrossSellings post /product/{productId}/cross-selling",
86
+ {
87
+ pathParams: { productId: product.value.id },
88
+ },
89
+ );
90
+
91
+ associations.value = response.data;
92
+ } catch (error) {
93
+ console.error(
94
+ "[useProductAssociations][loadAssociations][error]:",
95
+ error,
96
+ );
97
+ } finally {
98
+ isLoading.value = false;
99
+ }
100
+ };
101
+
102
+ return {
103
+ isLoading: computed(() => isLoading.value),
104
+ productAssociations: computed(() => associations.value),
105
+ loadAssociations,
106
+ };
107
+ }
@@ -0,0 +1,77 @@
1
+ import { describe, expect, it, vi } from "vitest";
2
+ import { ref } from "vue";
3
+ import { useProduct, useProductConfigurator } from "#imports";
4
+ import { useSetup } from "../_test";
5
+ import mockedConfigurator from "../mocks/Configurator";
6
+ import mockedProduct from "../mocks/Product";
7
+
8
+ vi.mock("../useProduct/useProduct.ts");
9
+
10
+ describe("useProductConfigurator", () => {
11
+ vi.mocked(useProduct).mockReturnValue({
12
+ configurator: ref(mockedConfigurator),
13
+ product: ref(mockedProduct),
14
+ } as unknown as ReturnType<typeof useProduct>);
15
+
16
+ it("handleChange callback function was called", () => {
17
+ const { vm } = useSetup(useProductConfigurator);
18
+ const mockedFn = vi.fn();
19
+
20
+ vm.handleChange("test", "test", mockedFn);
21
+ expect(mockedFn).toHaveBeenCalled();
22
+ });
23
+
24
+ it("findVariantForSelectedOptions", async () => {
25
+ const { vm, injections } = useSetup(useProductConfigurator);
26
+ injections.apiClient.invoke.mockResolvedValue({
27
+ data: {
28
+ elements: [mockedProduct],
29
+ },
30
+ });
31
+
32
+ expect(
33
+ await vm.findVariantForSelectedOptions({
34
+ test: "test",
35
+ }),
36
+ ).toStrictEqual(mockedProduct);
37
+
38
+ expect(await vm.findVariantForSelectedOptions()).toStrictEqual(
39
+ mockedProduct,
40
+ );
41
+ });
42
+
43
+ it("findVariantForSelectedOptions - error", async () => {
44
+ console.error = vi.fn();
45
+ const { vm, injections } = useSetup(useProductConfigurator);
46
+ injections.apiClient.invoke.mockRejectedValue("PROBLEM");
47
+
48
+ await vm.findVariantForSelectedOptions({
49
+ test: "test",
50
+ });
51
+ expect(console.error).toBeCalledWith(
52
+ "SwProductDetails:findVariantForSelectedOptions",
53
+ "PROBLEM",
54
+ );
55
+ });
56
+
57
+ it("product - with options", () => {
58
+ vi.mocked(useProduct).mockReturnValue({
59
+ configurator: ref(null),
60
+ product: ref({
61
+ options: [
62
+ {
63
+ id: "cc02c6cf39ad43d5856a25f8928490bf",
64
+ },
65
+ {
66
+ id: "aa02c6cf39ad43d5856a25f8928490bf",
67
+ },
68
+ ],
69
+ }),
70
+ } as unknown as ReturnType<typeof useProduct>);
71
+
72
+ const { vm } = useSetup(useProductConfigurator);
73
+
74
+ expect(vm.isLoadingOptions).toBe(true);
75
+ expect(vm.getOptionGroups).toStrictEqual([]);
76
+ });
77
+ });
@@ -0,0 +1,134 @@
1
+ import { getTranslatedProperty } from "@shopware-pwa/helpers-next";
2
+ import { computed, ref } from "vue";
3
+ import type { ComputedRef, Ref } from "vue";
4
+ import { useProduct, useShopwareContext } from "#imports";
5
+ import type { Schemas } from "#shopware";
6
+
7
+ export type UseProductConfiguratorReturn = {
8
+ /**
9
+ * Handler for action when the selected option is changed
10
+ */
11
+ handleChange(
12
+ attribute: string,
13
+ option: string,
14
+ onChangeHandled: () => void,
15
+ ): Promise<void>;
16
+
17
+ findVariantForSelectedOptions(options?: {
18
+ [key: string]: string;
19
+ }): Promise<Schemas["Product"] | undefined>;
20
+
21
+ /**
22
+ * Indicates if the options are being (re)loaded
23
+ */
24
+ isLoadingOptions: Ref<boolean>;
25
+ /**
26
+ * Object of currently selected options
27
+ */
28
+ getSelectedOptions: ComputedRef<{
29
+ [key: string]: string;
30
+ }>;
31
+ /**
32
+ * All assigned properties which the variant can be made of
33
+ */
34
+ getOptionGroups: ComputedRef<Schemas["PropertyGroup"][]>;
35
+ };
36
+
37
+ /**
38
+ * Composable to change product variant.
39
+ * @public
40
+ * @category Product
41
+ */
42
+ export function useProductConfigurator(): UseProductConfiguratorReturn {
43
+ const { apiClient } = useShopwareContext();
44
+
45
+ const { configurator, product } = useProduct();
46
+
47
+ const selected = ref<{
48
+ [key: string]: string;
49
+ }>({});
50
+ const isLoadingOptions = ref(!!product.value.options?.length);
51
+ const parentProductId = computed(() => product.value?.parentId);
52
+ const getOptionGroups = computed<Schemas["PropertyGroup"][]>(() => {
53
+ return configurator.value || [];
54
+ });
55
+
56
+ const findGroupCodeForOption = (optionId: string) => {
57
+ const group = getOptionGroups.value.find((optionGroup) => {
58
+ const optionFound = optionGroup.options?.find((option) => {
59
+ return option.id === optionId;
60
+ });
61
+ return !!optionFound;
62
+ });
63
+
64
+ return getTranslatedProperty(group, "name");
65
+ };
66
+
67
+ // create a group -> optionId map
68
+ for (const optionId of product.value.optionIds || []) {
69
+ const optionGroupCode = findGroupCodeForOption(optionId);
70
+ if (optionGroupCode) {
71
+ selected.value[optionGroupCode] = optionId;
72
+ }
73
+ }
74
+
75
+ async function findVariantForSelectedOptions(options?: {
76
+ [code: string]: string;
77
+ }): Promise<Schemas["Product"] | undefined> {
78
+ const filter: Schemas["Filters"] = [
79
+ {
80
+ type: "equals",
81
+ field: "parentId",
82
+ value: parentProductId.value as string,
83
+ },
84
+ ...Object.values(options || selected.value).map(
85
+ (id) =>
86
+ ({
87
+ type: "equals",
88
+ field: "optionIds",
89
+ value: id as string,
90
+ }) as Schemas["EqualsFilter"],
91
+ ),
92
+ ];
93
+ try {
94
+ const response = await apiClient.invoke("readProduct post /product", {
95
+ body: {
96
+ filter,
97
+ limit: 1,
98
+ includes: {
99
+ product: ["id", "translated", "productNumber", "seoUrls"],
100
+ seo_url: ["seoPathInfo"],
101
+ },
102
+ associations: {
103
+ seoUrls: {},
104
+ },
105
+ },
106
+ });
107
+ return response.data.elements?.[0]; // return first matching product
108
+ } catch (e) {
109
+ console.error("SwProductDetails:findVariantForSelectedOptions", e);
110
+ }
111
+ }
112
+
113
+ const handleChange = async (
114
+ group: string,
115
+ option: string,
116
+ onChangeHandled?: () => void,
117
+ ): Promise<void> => {
118
+ selected.value = Object.assign({}, selected.value, {
119
+ [group]: option,
120
+ });
121
+ if (typeof onChangeHandled === "function") {
122
+ // run passed callback
123
+ await onChangeHandled();
124
+ }
125
+ };
126
+
127
+ return {
128
+ handleChange,
129
+ findVariantForSelectedOptions,
130
+ isLoadingOptions,
131
+ getOptionGroups,
132
+ getSelectedOptions: computed(() => selected.value),
133
+ };
134
+ }