@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,126 @@
1
+ import { beforeEach, describe, expect, it, vi } from "vitest";
2
+ import { ref } from "vue";
3
+ import type { Schemas } from "#shopware";
4
+ import { useSetup } from "../_test";
5
+ import mockedProduct from "../mocks/Product";
6
+ import productTierPrices from "../mocks/ProductTierPrices";
7
+ import { useProductPrice } from "./useProductPrice";
8
+
9
+ describe("useProductPrice", () => {
10
+ beforeEach(() => {
11
+ vi.resetAllMocks();
12
+ });
13
+ it("product price are displayed - standard product", () => {
14
+ const { vm } = useSetup(() => useProductPrice(ref(mockedProduct)));
15
+
16
+ expect(vm.price).toStrictEqual(mockedProduct.calculatedPrice);
17
+ expect(vm.totalPrice).toBe(14.45);
18
+ expect(vm.unitPrice).toBe(14.45);
19
+ expect(vm.displayFromVariants).toBe(false);
20
+ expect(vm.displayFrom).toBe(false);
21
+ expect(vm.tierPrices).toStrictEqual([]);
22
+ expect(vm.referencePrice).toStrictEqual(
23
+ mockedProduct.calculatedPrice?.referencePrice,
24
+ );
25
+ expect(vm.isListPrice).toBe(false);
26
+ expect(vm.regulationPrice).toBe(80);
27
+ });
28
+
29
+ it("product price are displayed - product with tier prices", () => {
30
+ const { vm } = useSetup(() =>
31
+ useProductPrice(
32
+ ref(productTierPrices.product as unknown as Schemas["Product"]),
33
+ ),
34
+ );
35
+
36
+ expect(vm.price).toStrictEqual(
37
+ productTierPrices.product.calculatedPrices[2],
38
+ );
39
+ expect(vm.referencePrice).toStrictEqual(
40
+ productTierPrices.product.calculatedPrices[0].referencePrice,
41
+ );
42
+ expect(vm.displayFrom).toBe(true);
43
+ expect(vm.displayFromVariants).toBe(20);
44
+ });
45
+
46
+ it("displayFrom should be false if displayParent is true", () => {
47
+ const { vm } = useSetup(() =>
48
+ useProductPrice(
49
+ ref(
50
+ Object.assign(
51
+ { ...productTierPrices.product },
52
+ {
53
+ calculatedPrices: null,
54
+ variantListingConfig: {
55
+ displayParent: true,
56
+ },
57
+ },
58
+ ) as unknown as Schemas["Product"],
59
+ ),
60
+ ),
61
+ );
62
+ expect(vm.displayFrom).toBe(false);
63
+ expect(vm.isListPrice).toBe(false);
64
+ });
65
+
66
+ it("isListPrice should be false with more than one calculatedPrices value", () => {
67
+ const { vm } = useSetup(() =>
68
+ useProductPrice(
69
+ ref(
70
+ Object.assign(
71
+ { ...productTierPrices.product },
72
+ {
73
+ listPrice: 80,
74
+ calculatedPrices: [
75
+ {
76
+ unitPrice: 10,
77
+ },
78
+ {
79
+ unitPrice: 20,
80
+ },
81
+ ],
82
+ },
83
+ ) as unknown as Schemas["Product"],
84
+ ),
85
+ ),
86
+ );
87
+ expect(vm.displayFrom).toBe(true);
88
+ expect(vm.isListPrice).toBe(false);
89
+ });
90
+
91
+ it("isListPrice should be true with one calculatedPrices value", () => {
92
+ const { vm } = useSetup(() =>
93
+ useProductPrice(
94
+ ref({
95
+ calculatedPrices: [
96
+ {
97
+ listPrice: {
98
+ percentage: 10,
99
+ },
100
+ },
101
+ ],
102
+ } as unknown as Schemas["Product"]),
103
+ ),
104
+ );
105
+ expect(vm.displayFrom).toBe(false);
106
+ expect(vm.isListPrice).toBe(true);
107
+ });
108
+
109
+ it("displayFrom - second variant", async () => {
110
+ const { vm } = useSetup(() =>
111
+ useProductPrice(
112
+ ref({
113
+ variantListingConfig: {
114
+ displayParent: true,
115
+ },
116
+ parentId: null,
117
+ calculatedCheapestPrice: {
118
+ hasRange: true,
119
+ },
120
+ } as unknown as Schemas["Product"]),
121
+ ),
122
+ );
123
+ expect(vm.displayFrom).toBe(false);
124
+ expect(vm.isListPrice).toBe(false);
125
+ });
126
+ });
@@ -0,0 +1,131 @@
1
+ import { getProductTierPrices } from "@shopware-pwa/helpers-next";
2
+ import type { TierPrice } from "@shopware-pwa/helpers-next";
3
+ import { computed } from "vue";
4
+ import type { ComputedRef, Ref } from "vue";
5
+ import type { Schemas } from "#shopware";
6
+
7
+ export type UseProductPriceReturn = {
8
+ /**
9
+ * Whole calculated price object
10
+ */
11
+ price: ComputedRef<Schemas["CalculatedPrice"] | undefined>;
12
+ /**
13
+ * Calculated price value for one selling unit
14
+ */
15
+ totalPrice: ComputedRef<number | undefined>;
16
+ /**
17
+ * Current unit price value
18
+ */
19
+ unitPrice: ComputedRef<number | undefined>;
20
+ /**
21
+ * Can be used if isListPrice is set to true
22
+ */
23
+ referencePrice: ComputedRef<
24
+ Schemas["CalculatedPrice"]["referencePrice"] | undefined
25
+ >;
26
+ /**
27
+ * determines if `price` contains the minimum tier price
28
+ */
29
+ displayFrom: ComputedRef<boolean>;
30
+ /**
31
+ * cheapest price value for a variant if exists
32
+ */
33
+ displayFromVariants: ComputedRef<number | false | undefined>;
34
+ /**
35
+ * array of TierPrice object
36
+ */
37
+ tierPrices: ComputedRef<TierPrice[]>;
38
+ /**
39
+ * determines whether a discount price is set
40
+ */
41
+ isListPrice: ComputedRef<boolean>;
42
+ /**
43
+ * price for products with regulation price
44
+ */
45
+ regulationPrice: ComputedRef<number | undefined>;
46
+ };
47
+
48
+ /**
49
+ * The purpose of the `useProductPrice` function is to abstract the logic to expose most useful helpers for price displaying.
50
+ *
51
+ * @public
52
+ * @category Product
53
+ */
54
+ export function useProductPrice(
55
+ product: Ref<Schemas["Product"] | undefined>,
56
+ ): UseProductPriceReturn {
57
+ const _cheapest: ComputedRef<
58
+ Schemas["Product"]["calculatedCheapestPrice"] | undefined
59
+ > = computed(() => product.value?.calculatedCheapestPrice);
60
+
61
+ /**
62
+ * calculatedPrices are used for product with tier prices
63
+ */
64
+ const _real: ComputedRef<Schemas["CalculatedPrice"] | undefined> = computed(
65
+ () =>
66
+ (product.value?.calculatedPrices?.length ?? 0) > 0
67
+ ? product.value?.calculatedPrices?.[0]
68
+ : product.value?.calculatedPrice,
69
+ );
70
+ const referencePrice: ComputedRef<
71
+ Schemas["CalculatedPrice"]["referencePrice"] | undefined
72
+ > = computed(() => _real?.value?.referencePrice);
73
+
74
+ const displayFrom: ComputedRef<boolean> = computed(() => {
75
+ return (product.value?.calculatedPrices?.length ?? 0) > 1;
76
+ });
77
+
78
+ const displayFromVariants: ComputedRef<number | false | undefined> = computed(
79
+ () => {
80
+ return (
81
+ !!product.value?.parentId &&
82
+ product.value?.calculatedCheapestPrice?.hasRange &&
83
+ _real?.value?.unitPrice !== _cheapest?.value?.unitPrice &&
84
+ _cheapest?.value?.unitPrice
85
+ );
86
+ },
87
+ );
88
+
89
+ const _price: ComputedRef<Schemas["CalculatedPrice"] | undefined> = computed(
90
+ () => {
91
+ if (displayFrom.value && getProductTierPrices(product.value).length > 1) {
92
+ return product.value?.calculatedPrices?.reduce((previous, current) => {
93
+ return current.unitPrice < previous.unitPrice ? current : previous;
94
+ });
95
+ }
96
+ return _real.value;
97
+ },
98
+ );
99
+
100
+ const unitPrice: ComputedRef<number | undefined> = computed(
101
+ () => _price.value?.unitPrice,
102
+ );
103
+ const totalPrice: ComputedRef<number | undefined> = computed(
104
+ () => _price.value?.totalPrice,
105
+ );
106
+ const price: ComputedRef<Schemas["CalculatedPrice"] | undefined> = computed(
107
+ () => _price.value,
108
+ );
109
+
110
+ const isListPrice: ComputedRef<boolean> = computed(() => {
111
+ return !!_price.value?.listPrice?.percentage;
112
+ });
113
+
114
+ const regulationPrice: ComputedRef<number | undefined> = computed(
115
+ () => product.value?.calculatedPrice?.regulationPrice?.price,
116
+ );
117
+
118
+ const tierPrices = computed(() => getProductTierPrices(product.value));
119
+
120
+ return {
121
+ price,
122
+ totalPrice,
123
+ unitPrice,
124
+ displayFromVariants,
125
+ displayFrom,
126
+ tierPrices,
127
+ referencePrice,
128
+ isListPrice,
129
+ regulationPrice,
130
+ };
131
+ }
@@ -0,0 +1,45 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { ref } from "vue";
3
+ import { useSetup } from "../_test";
4
+ import ProductMock from "../mocks/Product";
5
+ import { useProductReviews } from "./useProductReviews";
6
+
7
+ describe("useProductReviews", () => {
8
+ it("load product reviews", async () => {
9
+ const { vm, injections } = await useSetup(() =>
10
+ useProductReviews(ref(ProductMock)),
11
+ );
12
+ injections.apiClient.invoke.mockResolvedValue({ data: {} });
13
+ await vm.loadProductReviews();
14
+ expect(injections.apiClient.invoke).toHaveBeenCalledWith(
15
+ expect.stringContaining("readProductReviews"),
16
+ expect.objectContaining({}),
17
+ );
18
+ });
19
+
20
+ it("add product review", async () => {
21
+ const { vm, injections } = await useSetup(() =>
22
+ useProductReviews(ref(ProductMock)),
23
+ );
24
+
25
+ await vm.addReview({
26
+ title: "Title",
27
+ content: "Content",
28
+ points: 5,
29
+ });
30
+
31
+ expect(injections.apiClient.invoke).toHaveBeenCalledWith(
32
+ expect.stringContaining("saveProductReview"),
33
+ expect.objectContaining({
34
+ body: {
35
+ content: "Content",
36
+ points: 5,
37
+ title: "Title",
38
+ },
39
+ pathParams: {
40
+ productId: ProductMock.id,
41
+ },
42
+ }),
43
+ );
44
+ });
45
+ });
@@ -0,0 +1,80 @@
1
+ import { computed, ref } from "vue";
2
+ import type { ComputedRef, Ref } from "vue";
3
+ import { useShopwareContext } from "#imports";
4
+ import type { Schemas, operations } from "#shopware";
5
+
6
+ export type UseProductReviewsReturn = {
7
+ /**
8
+ * All reviews added to the product
9
+ */
10
+ productReviews: ComputedRef<Schemas["ProductReview"][]>;
11
+ /**
12
+ * Adds a review to the product
13
+ * @param data `title` - review title, `content` - review content, `points` - review points (range of 1-5)
14
+ * @returns
15
+ */
16
+ addReview(data: {
17
+ title: string;
18
+ content: string;
19
+ points: number;
20
+ }): Promise<void>;
21
+ /**
22
+ * Fetches the reviews list and assigns the result to the `productReviews` property
23
+ * @param parameters {@link Schemas["Criteria"]}
24
+ * @returns
25
+ */
26
+ loadProductReviews(
27
+ parameters?: Schemas["Criteria"],
28
+ ): Promise<
29
+ operations["readProductReviews post /product/{productId}/reviews"]["response"]
30
+ >;
31
+ };
32
+
33
+ /**
34
+ * Composable for listing customer orders.
35
+ * @public
36
+ * @category Product
37
+ */
38
+ export function useProductReviews(
39
+ product: Ref<Schemas["Product"]>,
40
+ ): UseProductReviewsReturn {
41
+ const { apiClient } = useShopwareContext();
42
+
43
+ const productReviews: Ref<Schemas["ProductReview"][]> = ref([]);
44
+
45
+ const loadProductReviews = async (
46
+ parameters: Schemas["Criteria"] = {},
47
+ ): Promise<
48
+ operations["readProductReviews post /product/{productId}/reviews"]["response"]
49
+ > => {
50
+ const fetchedReviews = await apiClient.invoke(
51
+ "readProductReviews post /product/{productId}/reviews",
52
+ {
53
+ pathParams: { productId: product.value.id },
54
+ body: parameters,
55
+ },
56
+ );
57
+ productReviews.value = fetchedReviews.data.elements ?? [];
58
+ return fetchedReviews.data;
59
+ };
60
+
61
+ const addReview = async (data: {
62
+ title: string;
63
+ content: string;
64
+ points: number;
65
+ }) => {
66
+ await apiClient.invoke(
67
+ "saveProductReview post /product/{productId}/review",
68
+ {
69
+ pathParams: { productId: product.value.id },
70
+ body: data,
71
+ },
72
+ );
73
+ };
74
+
75
+ return {
76
+ productReviews: computed(() => productReviews.value),
77
+ loadProductReviews,
78
+ addReview,
79
+ };
80
+ }
@@ -0,0 +1,37 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { useSetup } from "../_test";
3
+ import { cmsAssociations } from "../cms/cmsAssociations";
4
+ import { useProductSearch } from "./useProductSearch";
5
+
6
+ describe("useProductSearch", () => {
7
+ it("search", async () => {
8
+ const { vm, injections } = useSetup(() => useProductSearch());
9
+ injections.apiClient.invoke.mockResolvedValue({ data: {} });
10
+ await vm.search("test");
11
+ expect(injections.apiClient.invoke).toHaveBeenCalledWith(
12
+ expect.stringContaining("readProductDetail"),
13
+ expect.objectContaining({
14
+ pathParams: {
15
+ productId: "test",
16
+ },
17
+ }),
18
+ );
19
+ });
20
+
21
+ it("search with associations", async () => {
22
+ const { vm, injections } = useSetup(() => useProductSearch());
23
+ injections.apiClient.invoke.mockResolvedValue({ data: {} });
24
+ await vm.search("test", {
25
+ withCmsAssociations: true,
26
+ });
27
+ expect(injections.apiClient.invoke).toHaveBeenCalledWith(
28
+ expect.stringContaining("readProductDetail"),
29
+ expect.objectContaining({
30
+ body: cmsAssociations,
31
+ pathParams: {
32
+ productId: "test",
33
+ },
34
+ }),
35
+ );
36
+ });
37
+ });
@@ -0,0 +1,58 @@
1
+ import { defu } from "defu";
2
+ import { useShopwareContext } from "#imports";
3
+ import type { Schemas } from "#shopware";
4
+ import { cmsAssociations } from "../cms/cmsAssociations";
5
+
6
+ type UseProductSearchReturnOptions = {
7
+ withCmsAssociations?: boolean;
8
+ criteria?: Partial<Schemas["Criteria"]>;
9
+ associations?: Partial<Schemas["Association"]>;
10
+ };
11
+
12
+ export type UseProductSearchReturn = {
13
+ /**
14
+ * Searches for a product by its id
15
+ * @param productId
16
+ * @param options - optional parameters accepts `withCmsAssociations` flag to fetch cms-related associations and criteria
17
+ * @returns {Promise<Schemas['ProductDetailResponse']>}
18
+ */
19
+ search: (
20
+ productId: string,
21
+ options?: UseProductSearchReturnOptions,
22
+ ) => Promise<Schemas["ProductDetailResponse"]>;
23
+ };
24
+
25
+ /**
26
+ * Composable for product search.
27
+ * @public
28
+ * @category Navigation & Routing
29
+ */
30
+ export function useProductSearch(): UseProductSearchReturn {
31
+ const { apiClient } = useShopwareContext();
32
+
33
+ const search = async (
34
+ productId: string,
35
+ options?: UseProductSearchReturnOptions,
36
+ ) => {
37
+ const associations = defu(
38
+ options?.withCmsAssociations ? cmsAssociations : {},
39
+ options?.criteria,
40
+ { associations: options?.associations ?? {} },
41
+ );
42
+ const result = await apiClient.invoke(
43
+ "readProductDetail post /product/{productId}",
44
+ {
45
+ headers: {
46
+ "sw-include-seo-urls": true,
47
+ },
48
+ pathParams: { productId },
49
+ body: associations,
50
+ },
51
+ );
52
+ return result.data;
53
+ };
54
+
55
+ return {
56
+ search,
57
+ };
58
+ }
@@ -0,0 +1,19 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { useSetup } from "../_test";
3
+ import { useProductSearchSuggest } from "./useProductSearchSuggest";
4
+
5
+ describe("useProductSearchSuggest", () => {
6
+ it("search", async () => {
7
+ const { vm, injections } = useSetup(() => useProductSearchSuggest());
8
+ injections.apiClient.invoke.mockResolvedValue({ data: {} });
9
+ await vm.search();
10
+ expect(injections.apiClient.invoke).toHaveBeenCalledWith(
11
+ expect.stringContaining("searchPage"),
12
+ expect.objectContaining({
13
+ body: {
14
+ search: "",
15
+ },
16
+ }),
17
+ );
18
+ });
19
+ });
@@ -0,0 +1,67 @@
1
+ import { ref } from "vue";
2
+ import type { ComputedRef, Ref } from "vue";
3
+ import { useProductSearchListing } from "#imports";
4
+ import type { Schemas, operations } from "#shopware";
5
+
6
+ export type UseProductSearchSuggestReturn = {
7
+ /**
8
+ * Current search term
9
+ */
10
+ searchTerm: Ref<string>;
11
+ /**
12
+ * Indicates if the search is in progress
13
+ */
14
+ loading: ComputedRef<boolean>;
15
+ /**
16
+ * Performs the search
17
+ * @param additionalCriteria - additional search criteria of type {@link ShopwareSearchParams}
18
+ * @returns
19
+ */
20
+ search(
21
+ additionalCriteria?: Partial<operations["searchPage post /search"]["body"]>,
22
+ ): Promise<void>;
23
+ /**
24
+ * Loads more products for current search criteria
25
+ */
26
+ loadMore(
27
+ criteria: operations["searchPage post /search"]["body"],
28
+ ): Promise<void>;
29
+ /**
30
+ * Returns the product list found by the search
31
+ */
32
+ getProducts: ComputedRef<Schemas["ProductListingResult"]["elements"]>;
33
+ /**
34
+ * Returns the total number of products found by the search
35
+ */
36
+ getTotal: ComputedRef<number>;
37
+ };
38
+
39
+ /**
40
+ * Composable for product suggest search.
41
+ * @public
42
+ * @category Product
43
+ */
44
+ export function useProductSearchSuggest(): UseProductSearchSuggestReturn {
45
+ const searchTerm = ref("");
46
+
47
+ const listingComposable = useProductSearchListing();
48
+
49
+ const search = async (
50
+ additionalCriteria = {} as operations["searchPage post /search"]["body"],
51
+ ) => {
52
+ const searchCriteria: operations["searchPage post /search"]["body"] = {
53
+ ...additionalCriteria,
54
+ search: searchTerm.value,
55
+ };
56
+ return listingComposable.search(searchCriteria);
57
+ };
58
+
59
+ return {
60
+ searchTerm,
61
+ loading: listingComposable.loading,
62
+ search,
63
+ loadMore: listingComposable.loadMore,
64
+ getProducts: listingComposable.getElements,
65
+ getTotal: listingComposable.getTotal,
66
+ };
67
+ }
@@ -0,0 +1,63 @@
1
+ import { describe, expect, it, vi } from "vitest";
2
+ import { ref } from "vue";
3
+ import { useProductWishlist, useUser } from "#imports";
4
+ import { useSetup } from "../_test";
5
+
6
+ vi.mock("../useUser/useUser.ts");
7
+
8
+ describe("useProductWishlist", () => {
9
+ describe("methods not logged in", () => {
10
+ describe("addToWishlist", () => {
11
+ it("wishlist add product", async () => {
12
+ const { vm } = useSetup(() => useProductWishlist("test1"));
13
+
14
+ await expect(vm.addToWishlist()).resolves.toEqual(undefined);
15
+ });
16
+ });
17
+
18
+ describe("addToWishlist - id only", () => {
19
+ it("wishlist add product", async () => {
20
+ const { vm } = useSetup(() => useProductWishlist("test3"));
21
+
22
+ await expect(vm.addToWishlist()).resolves.toEqual(undefined);
23
+ });
24
+ });
25
+
26
+ it("removeFromWishlist", async () => {
27
+ vi.mocked(useUser).mockReturnValue({
28
+ isLoggedIn: ref(false),
29
+ isGuestSession: ref(true),
30
+ } as ReturnType<typeof useUser>);
31
+ const { vm } = useSetup(() => useProductWishlist("test3"));
32
+
33
+ await expect(vm.removeFromWishlist()).resolves.toEqual(undefined);
34
+ expect(vm.isInWishlist).toEqual(false);
35
+ });
36
+ });
37
+
38
+ describe("methods logged in", () => {
39
+ vi.mocked(useUser).mockReturnValue({
40
+ isLoggedIn: ref(true),
41
+ isGuestSession: ref(false),
42
+ } as ReturnType<typeof useUser>);
43
+
44
+ describe("addToWishlist - id only", () => {
45
+ it("wishlist add product", async () => {
46
+ const { vm } = useSetup(() => useProductWishlist("test3"));
47
+
48
+ await expect(vm.addToWishlist()).resolves.toEqual(undefined);
49
+ });
50
+ });
51
+
52
+ it("removeFromWishlist", async () => {
53
+ vi.mocked(useUser).mockReturnValue({
54
+ isLoggedIn: ref(true),
55
+ isGuestSession: ref(false),
56
+ } as ReturnType<typeof useUser>);
57
+ const { vm } = useSetup(() => useProductWishlist("test3"));
58
+
59
+ await expect(vm.removeFromWishlist()).resolves.toEqual(undefined);
60
+ expect(vm.isInWishlist).toEqual(false);
61
+ });
62
+ });
63
+ });
@@ -0,0 +1,74 @@
1
+ import { computed } from "vue";
2
+ import type { Ref } from "vue";
3
+ import { useLocalWishlist, useSyncWishlist, useUser } from "#imports";
4
+
5
+ export type UseProductWishlistReturn = {
6
+ /**
7
+ * Removes product from wishlist
8
+ */
9
+ removeFromWishlist(): Promise<void>;
10
+ /**
11
+ * Adds product to wishlist
12
+ */
13
+ addToWishlist(): Promise<void>;
14
+ /**
15
+ * Indicates whether a product is in wishlist
16
+ */
17
+ isInWishlist: Ref<boolean>;
18
+ };
19
+
20
+ /**
21
+ * Manage wishlist for a single product.
22
+ *
23
+ * @public
24
+ * @category Product
25
+ */
26
+ export function useProductWishlist(
27
+ productId: string,
28
+ ): UseProductWishlistReturn {
29
+ const { isLoggedIn } = useUser();
30
+ const {
31
+ addToWishlist: addItem,
32
+ removeFromWishlist: removeItem,
33
+ items,
34
+ } = useLocalWishlist();
35
+
36
+ const {
37
+ addToWishlistSync: addItemSync,
38
+ removeFromWishlistSync: removeItemSync,
39
+ items: itemsSync,
40
+ getWishlistProducts,
41
+ } = useSyncWishlist();
42
+
43
+ // removes item from the list
44
+ async function removeFromWishlist() {
45
+ if (isLoggedIn.value) {
46
+ await removeItemSync(productId);
47
+ await getWishlistProducts();
48
+ } else {
49
+ await removeItem(productId);
50
+ }
51
+ }
52
+
53
+ async function addToWishlist() {
54
+ if (isLoggedIn.value) {
55
+ await addItemSync(productId);
56
+ await getWishlistProducts();
57
+ } else {
58
+ await addItem(productId);
59
+ }
60
+ }
61
+
62
+ // return true or false if product id is in wishlist array
63
+ const isInWishlist = computed(() =>
64
+ isLoggedIn.value
65
+ ? itemsSync.value?.includes(productId)
66
+ : items.value?.includes(productId),
67
+ );
68
+
69
+ return {
70
+ addToWishlist,
71
+ removeFromWishlist,
72
+ isInWishlist,
73
+ };
74
+ }