@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,95 @@
1
+ import { computed, ref } from "vue";
2
+ import type { ComputedRef, Ref } from "vue";
3
+
4
+ export type UseLocalWishlistReturn = {
5
+ /**
6
+ * Get wishlist products from localstorage
7
+ */
8
+ getWishlistProducts(): void;
9
+ /**
10
+ * Add product to wishlist by its id
11
+ */
12
+ addToWishlist(id: string): Promise<void>;
13
+ /**
14
+ * Remove product from wishlist by its id
15
+ */
16
+ removeFromWishlist(id: string): Promise<void>;
17
+ /**
18
+ * Remove all products from wishlist
19
+ */
20
+ clearWishlist(): Promise<void>;
21
+ /**
22
+ * List of wishlist items
23
+ */
24
+ items: ComputedRef<string[]>;
25
+ /**
26
+ * Count of wishlist items
27
+ */
28
+ count: ComputedRef<number>;
29
+ };
30
+
31
+ const _wishlistItems: Ref<string[]> = ref([]);
32
+
33
+ /**
34
+ * Composable for wishlist management.
35
+ * @public
36
+ * @category Wishlist
37
+ */
38
+ export function useLocalWishlist(): UseLocalWishlistReturn {
39
+ // update wishlist in localstorage
40
+ const updateStorage = (): void => {
41
+ localStorage.setItem(
42
+ "sw-wishlist-items",
43
+ JSON.stringify(_wishlistItems.value),
44
+ );
45
+ };
46
+ /* istanbul ignore next */
47
+ const getFromStorage = () => {
48
+ if (typeof window !== "undefined" && localStorage) {
49
+ return JSON.parse(localStorage.getItem("sw-wishlist-items") ?? "[]");
50
+ }
51
+ };
52
+
53
+ // removes item from the list
54
+ async function removeFromWishlist(id: string) {
55
+ _wishlistItems.value = _wishlistItems.value?.filter(
56
+ (itemId: string) => itemId !== id,
57
+ );
58
+
59
+ updateStorage();
60
+ }
61
+
62
+ // add product id to wishlist array and trigger to update localstorage
63
+ async function addToWishlist(id: string) {
64
+ if (!_wishlistItems.value.includes(id)) {
65
+ _wishlistItems.value.push(id);
66
+
67
+ updateStorage();
68
+ }
69
+ }
70
+
71
+ // remove all items from wishlist
72
+ async function clearWishlist() {
73
+ _wishlistItems.value = [];
74
+ updateStorage();
75
+ }
76
+
77
+ function getWishlistProducts() {
78
+ const currentWishlist = getFromStorage();
79
+ if (Array.isArray(currentWishlist) && currentWishlist.length) {
80
+ _wishlistItems.value = currentWishlist;
81
+ }
82
+ }
83
+
84
+ const items = computed(() => _wishlistItems.value);
85
+ const count = computed(() => items.value.length);
86
+
87
+ return {
88
+ getWishlistProducts,
89
+ addToWishlist,
90
+ removeFromWishlist,
91
+ clearWishlist,
92
+ items,
93
+ count,
94
+ };
95
+ }
@@ -0,0 +1,68 @@
1
+ import { describe, expect, it, vi } from "vitest";
2
+ import { useSetup } from "../_test";
3
+ import Menu from "../mocks/Menu";
4
+ import { useNavigation } from "./useNavigation";
5
+
6
+ describe("useNavigation", () => {
7
+ it("should set the menu", async () => {
8
+ const { vm, injections } = useSetup(useNavigation);
9
+ injections.apiClient.invoke.mockResolvedValue({ data: Menu });
10
+
11
+ await vm.loadNavigationElements({
12
+ depth: 3,
13
+ });
14
+ expect(injections.apiClient.invoke).toHaveBeenCalledWith(
15
+ expect.stringContaining("readNavigation"),
16
+ expect.anything(),
17
+ );
18
+ expect(vm.navigationElements).not.toBeNull();
19
+ expect(vm.navigationElements?.length).toBe(Menu.length);
20
+ });
21
+
22
+ it("menu is empty because of the error", async () => {
23
+ const { vm, injections } = useSetup(useNavigation);
24
+ vi.spyOn(console, "error").mockImplementation(() => {});
25
+
26
+ injections.apiClient.invoke.mockRejectedValue(null);
27
+
28
+ await vm.loadNavigationElements({
29
+ depth: 3,
30
+ });
31
+ expect(vm.navigationElements?.length).toBe(0);
32
+ expect(console.error).toHaveBeenCalledWith(
33
+ "[useNavigation][loadNavigationElements]",
34
+ null,
35
+ );
36
+ });
37
+
38
+ it("should set the menu - empty return", async () => {
39
+ const { vm, injections } = useSetup(useNavigation);
40
+ injections.apiClient.invoke.mockResolvedValue({ data: undefined });
41
+
42
+ await vm.loadNavigationElements({
43
+ depth: 3,
44
+ });
45
+ expect(injections.apiClient.invoke).toHaveBeenCalledWith(
46
+ expect.stringContaining("readNavigation"),
47
+ expect.anything(),
48
+ );
49
+ expect(vm.navigationElements).toStrictEqual([]);
50
+ });
51
+
52
+ it("should pass criteria to the api call", async () => {
53
+ const { vm, injections } = useSetup(useNavigation);
54
+ injections.apiClient.invoke.mockResolvedValue({ data: undefined });
55
+ vi.spyOn(injections.apiClient, "invoke").mockImplementation(() => {});
56
+
57
+ await vm.loadNavigationElements({
58
+ depth: 2,
59
+ includes: { category: ["name"] },
60
+ });
61
+ expect(injections.apiClient.invoke).toHaveBeenCalledWith(
62
+ expect.stringContaining("readNavigation"),
63
+ expect.objectContaining({
64
+ body: { depth: 2, includes: { category: ["name"] } },
65
+ }),
66
+ );
67
+ });
68
+ });
@@ -0,0 +1,83 @@
1
+ import { computed, inject, provide, ref } from "vue";
2
+ import type { ComputedRef, Ref } from "vue";
3
+ import { useShopwareContext } from "#imports";
4
+ import type { Schemas, operations } from "#shopware";
5
+
6
+ /**
7
+ *
8
+ * Provides state for navigation trees depending on navigation type.
9
+ */
10
+ export type UseNavigationReturn = {
11
+ /**
12
+ * List of navigation elements
13
+ */
14
+ navigationElements: ComputedRef<Schemas["NavigationRouteResponse"] | null>;
15
+ /**
16
+ * Load navigation elements
17
+ */
18
+ loadNavigationElements(
19
+ params: operations["readNavigation post /navigation/{activeId}/{rootId}"]["body"],
20
+ ): Promise<Schemas["NavigationRouteResponse"]>;
21
+ };
22
+
23
+ /**
24
+ * Composable for navigation.
25
+ * Provides state for navigation trees depending on navigation type.
26
+ *
27
+ * @example
28
+ * ```
29
+ * // get main navigation
30
+ * useNavigation()
31
+ * // get footer navigation
32
+ * useNavigation({ type: "footer-navigation" } )
33
+ * ```
34
+ * @public
35
+ * @category Navigation & Routing
36
+ */
37
+ export function useNavigation(params?: {
38
+ type?: Schemas["NavigationType"] | string;
39
+ }): UseNavigationReturn {
40
+ const type = params?.type || "main-navigation";
41
+
42
+ const { apiClient } = useShopwareContext();
43
+
44
+ const sharedElements: Ref<Schemas["NavigationRouteResponse"]> = inject(
45
+ `swNavigation-${type}`,
46
+ ref([]),
47
+ );
48
+ provide(`swNavigation-${type}`, sharedElements);
49
+
50
+ const navigationElements = computed(() => sharedElements.value);
51
+
52
+ async function loadNavigationElements(
53
+ params: operations["readNavigation post /navigation/{activeId}/{rootId}"]["body"],
54
+ ) {
55
+ try {
56
+ const navigationResponse = await apiClient.invoke(
57
+ "readNavigation post /navigation/{activeId}/{rootId}",
58
+ {
59
+ headers: {
60
+ "sw-include-seo-urls": true,
61
+ },
62
+ pathParams: {
63
+ activeId: type,
64
+ rootId: type,
65
+ },
66
+ body: params,
67
+ },
68
+ );
69
+
70
+ sharedElements.value = navigationResponse.data || [];
71
+ return sharedElements.value;
72
+ } catch (e) {
73
+ sharedElements.value = [];
74
+ console.error("[useNavigation][loadNavigationElements]", e);
75
+ return [];
76
+ }
77
+ }
78
+
79
+ return {
80
+ navigationElements,
81
+ loadNavigationElements,
82
+ };
83
+ }
@@ -0,0 +1,48 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { ref } from "vue";
3
+ import { useSetup } from "../_test";
4
+ import { useNavigationContext } from "./useNavigationContext";
5
+
6
+ describe("useNavigationContext", () => {
7
+ it("notification flow", async () => {
8
+ const { vm } = useSetup(() =>
9
+ useNavigationContext(
10
+ ref({
11
+ createdAt: "2020-08-06T06:26:52.576+00:00",
12
+ foreignKey: "7e117859f69b4ee08947e1ae4fce1f69",
13
+ id: "dd38c5ed443544e28818e967809c8914",
14
+ isCanonical: true,
15
+ isDeleted: false,
16
+ isModified: false,
17
+ languageId: "2fbb5fe2e29a4d70aa5854ce7ce3e20b",
18
+ pathInfo: "/detail/7e117859f69b4ee08947e1ae4fce1f69",
19
+ routeName: "frontend.detail.page",
20
+ updatedAt: "2022-08-03T08:07:04.512+00:00",
21
+ salesChannelId: "98432def39fc4624b33213a56b8c944d",
22
+ seoPathInfo: "Cigar-Special-40/SW10044",
23
+ }),
24
+ ),
25
+ );
26
+
27
+ expect(vm.foreignKey).toBe("7e117859f69b4ee08947e1ae4fce1f69");
28
+ expect(vm.routeName).toBe("frontend.detail.page");
29
+ });
30
+
31
+ it("should return empty string if no foreignKey", async () => {
32
+ const { vm } = useSetup(() =>
33
+ useNavigationContext(
34
+ ref({
35
+ createdAt: "2020-08-06T06:26:52.576+00:00",
36
+ foreignKey: "",
37
+ id: "dd38c5ed443544e28818e967809c8914",
38
+ languageId: "2fbb5fe2e29a4d70aa5854ce7ce3e20b",
39
+ pathInfo: "/detail/7e117859f69b4ee08947e1ae4fce1f69",
40
+ routeName: "frontend.detail.page",
41
+ seoPathInfo: "Cigar-Special-40/SW10044",
42
+ }),
43
+ ),
44
+ );
45
+
46
+ expect(vm.foreignKey).toBe("");
47
+ });
48
+ });
@@ -0,0 +1,39 @@
1
+ import { computed } from "vue";
2
+ import type { ComputedRef, Ref } from "vue";
3
+ import { useContext } from "#imports";
4
+ import type { Schemas } from "#shopware";
5
+
6
+ export type UseNavigationContextReturn = {
7
+ /**
8
+ * SEO URL from the navigation context
9
+ */
10
+ navigationContext: ComputedRef<Schemas["SeoUrl"] | null>;
11
+ /**
12
+ * Route name from the navigation context
13
+ */
14
+ routeName: ComputedRef<Schemas["SeoUrl"]["routeName"] | undefined>;
15
+ /**
16
+ * Foreign key (ID) for current navigation context
17
+ */
18
+ foreignKey: ComputedRef<string>;
19
+ };
20
+
21
+ /**
22
+ * Composable to get navigation context from the URL.
23
+ * @public
24
+ * @category Navigation & Routing
25
+ */
26
+ export function useNavigationContext(
27
+ context?: Ref<Schemas["SeoUrl"] | null>,
28
+ ): UseNavigationContextReturn {
29
+ const _context = useContext("navigation", { context: context });
30
+
31
+ const routeName = computed(() => _context.value?.routeName);
32
+ const foreignKey = computed(() => _context.value?.foreignKey || "");
33
+
34
+ return {
35
+ navigationContext: computed(() => _context.value),
36
+ routeName,
37
+ foreignKey,
38
+ };
39
+ }
@@ -0,0 +1,110 @@
1
+ import { describe, expect, it, vi } from "vitest";
2
+ import { ref } from "vue";
3
+ import { useNavigationSearch, useSessionContext } from "#imports";
4
+ import { useSetup } from "../_test";
5
+
6
+ vi.mock("../useSessionContext/useSessionContext.ts");
7
+ const sessionContext = ref();
8
+
9
+ vi.mocked(useSessionContext).mockReturnValue({
10
+ sessionContext,
11
+ } as unknown as ReturnType<typeof useSessionContext>);
12
+
13
+ const mockedResponse = {
14
+ translated: [],
15
+ createdAt: "2020-08-06T06:26:42.505+00:00",
16
+ updatedAt: "2022-08-03T08:07:03.941+00:00",
17
+ salesChannelId: "98432def39fc4624b33213a56b8c944d",
18
+ languageId: "2fbb5fe2e29a4d70aa5854ce7ce3e20b",
19
+ routeName: "frontend.detail.page",
20
+ foreignKey: "e05e9340aff4484f9009646dfd572df9",
21
+ pathInfo: "/detail/e05e9340aff4484f9009646dfd572df9",
22
+ seoPathInfo: "Fred-3-Burner-Gas-Grill/941044",
23
+ isCanonical: true,
24
+ isModified: false,
25
+ isDeleted: false,
26
+ isValid: null,
27
+ url: null,
28
+ customFields: null,
29
+ id: "59d47f52be96461193a3d6fcf2fe46e6",
30
+ apiAlias: "seo_url",
31
+ };
32
+
33
+ describe("useNavigationSearch", () => {
34
+ it("should resolve path from api response", async () => {
35
+ const { vm, injections } = useSetup(useNavigationSearch);
36
+ injections.apiClient.invoke.mockResolvedValue({
37
+ data: {
38
+ elements: [mockedResponse],
39
+ },
40
+ });
41
+
42
+ expect(await vm.resolvePath("/test")).toStrictEqual(mockedResponse);
43
+ expect(injections.apiClient.invoke).toHaveBeenCalledWith(
44
+ expect.stringContaining("readSeoUrl"),
45
+ expect.objectContaining({
46
+ body: {
47
+ filter: [
48
+ {
49
+ type: "equals",
50
+ field: "seoPathInfo",
51
+ value: "test",
52
+ },
53
+ ],
54
+ },
55
+ }),
56
+ );
57
+ });
58
+ it("should resolve technical url", async () => {
59
+ const { vm, injections } = useSetup(useNavigationSearch);
60
+ injections.apiClient.invoke.mockResolvedValue({ data: { elements: [] } });
61
+
62
+ await vm.resolvePath("/landingPage/test");
63
+
64
+ expect(injections.apiClient.invoke).toHaveBeenCalledWith(
65
+ expect.stringContaining("readSeoUrl"),
66
+ expect.objectContaining({
67
+ body: {
68
+ filter: [
69
+ {
70
+ type: "equals",
71
+ field: "pathInfo",
72
+ value: "/landingPage/test",
73
+ },
74
+ ],
75
+ },
76
+ }),
77
+ );
78
+ });
79
+ it("should not invoke api call for / search ", async () => {
80
+ const { vm, injections } = useSetup(useNavigationSearch);
81
+ injections.apiClient.invoke.mockResolvedValue({
82
+ data: {
83
+ elements: [mockedResponse],
84
+ },
85
+ });
86
+
87
+ const result = await vm.resolvePath("/");
88
+ expect(result).toMatchInlineSnapshot(`
89
+ {
90
+ "foreignKey": undefined,
91
+ "routeName": "frontend.navigation.page",
92
+ }
93
+ `);
94
+ expect(injections.apiClient.invoke).not.toHaveBeenCalled();
95
+ });
96
+
97
+ it("resolvePath with categoryId", async () => {
98
+ const { vm } = useSetup(useNavigationSearch);
99
+ sessionContext.value = {
100
+ salesChannel: {
101
+ navigationCategoryId: "categoryIdTest",
102
+ },
103
+ };
104
+
105
+ expect(await vm.resolvePath("/")).toStrictEqual({
106
+ foreignKey: "categoryIdTest",
107
+ routeName: "frontend.navigation.page",
108
+ });
109
+ });
110
+ });
@@ -0,0 +1,60 @@
1
+ import { useSessionContext, useShopwareContext } from "#imports";
2
+ import type { Schemas } from "#shopware";
3
+
4
+ export type UseNavigationSearchReturn = {
5
+ /**
6
+ * Get {@link SeoUrl} entity for given path
7
+ * @example resolvePath("/my-category/my-product") or resolvePath("/") for home page
8
+ */
9
+ resolvePath(path: string): Promise<Schemas["SeoUrl"] | null>;
10
+ };
11
+
12
+ /**
13
+ * Composable to get search for SeoUrl entity for given path.
14
+ * @public
15
+ * @category Navigation & Routing
16
+ */
17
+ export function useNavigationSearch(): UseNavigationSearchReturn {
18
+ const { apiClient } = useShopwareContext();
19
+ const { sessionContext } = useSessionContext();
20
+
21
+ async function resolvePath(path: string) {
22
+ if (path === "/") {
23
+ // please ignore optional chaining for salesChannel object as it's always present (type definition issue)
24
+ const categoryId =
25
+ sessionContext.value?.salesChannel?.navigationCategoryId;
26
+
27
+ return {
28
+ routeName: "frontend.navigation.page",
29
+ foreignKey: categoryId,
30
+ } as Schemas["SeoUrl"];
31
+ }
32
+
33
+ const isTechnicalUrl =
34
+ path.startsWith("/navigation/") ||
35
+ path.startsWith("/detail/") ||
36
+ path.startsWith("/landingPage/");
37
+
38
+ // remove leading slash in case of seo url
39
+ const normalizedPath = isTechnicalUrl ? path : path.substring(1);
40
+ // console.error("looking for path", normalizedPath);
41
+
42
+ const seoResult = await apiClient.invoke("readSeoUrl post /seo-url", {
43
+ body: {
44
+ filter: [
45
+ {
46
+ type: "equals",
47
+ field: isTechnicalUrl ? "pathInfo" : "seoPathInfo",
48
+ value: normalizedPath,
49
+ },
50
+ ],
51
+ },
52
+ });
53
+
54
+ return seoResult.data.elements?.[0];
55
+ }
56
+
57
+ return {
58
+ resolvePath,
59
+ };
60
+ }
@@ -0,0 +1,55 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { useSetup } from "../_test";
3
+ import { useNewsletter } from "./useNewsletter";
4
+
5
+ describe("useNewsletter", () => {
6
+ it("newsletter subscribe", async () => {
7
+ const { vm, injections } = useSetup(useNewsletter);
8
+ injections.apiClient.invoke.mockResolvedValue({ data: {} });
9
+
10
+ await vm.newsletterSubscribe({
11
+ email: "test@shopware.com",
12
+ option: "subscribe",
13
+ });
14
+
15
+ expect(injections.apiClient.invoke).toHaveBeenCalledWith(
16
+ expect.stringContaining("subscribeToNewsletter"),
17
+ expect.anything(),
18
+ );
19
+ });
20
+
21
+ it("newsletter unsubscribe", async () => {
22
+ const { vm, injections } = useSetup(useNewsletter);
23
+ injections.apiClient.invoke.mockResolvedValue({ data: {} });
24
+
25
+ await vm.newsletterUnsubscribe("sometestemail@shopware.com");
26
+
27
+ expect(injections.apiClient.invoke).toHaveBeenCalledWith(
28
+ expect.stringContaining("unsubscribeToNewsletter"),
29
+ {
30
+ body: {
31
+ email: "sometestemail@shopware.com",
32
+ },
33
+ },
34
+ );
35
+ });
36
+
37
+ it("getNewsletterStatus", async () => {
38
+ const { vm, injections } = useSetup(useNewsletter);
39
+ injections.apiClient.invoke.mockResolvedValue({ data: {} });
40
+
41
+ await vm.getNewsletterStatus();
42
+
43
+ expect(injections.apiClient.invoke).toHaveBeenCalledWith(
44
+ expect.stringContaining("readNewsletterRecipient"),
45
+ );
46
+ });
47
+
48
+ it("isNewsletterSubscriber", async () => {
49
+ const { vm } = useSetup(useNewsletter);
50
+
51
+ expect(vm.isNewsletterSubscriber).toBe(false);
52
+ vm.newsletterStatus = "direct";
53
+ expect(vm.isNewsletterSubscriber).toBe(true);
54
+ });
55
+ });
@@ -0,0 +1,109 @@
1
+ import { computed, ref } from "vue";
2
+ import type { ComputedRef, Ref } from "vue";
3
+ import { useInternationalization, useShopwareContext } from "#imports";
4
+ import type { Schemas, operations } from "#shopware";
5
+
6
+ export type UseNewsletterReturn = {
7
+ /**
8
+ * Subscribes the user to the newsletter
9
+ * @param params {@link operations['subscribeToNewsletter post /newsletter/subscribe']['body']}
10
+ */
11
+ newsletterSubscribe(
12
+ params: Omit<
13
+ operations["subscribeToNewsletter post /newsletter/subscribe"]["body"],
14
+ "storefrontUrl"
15
+ >,
16
+ ): Promise<void>;
17
+ /**
18
+ * Removes the email from the newsletter
19
+ * @param email
20
+ */
21
+ newsletterUnsubscribe(email: string): Promise<void>;
22
+ /**
23
+ * Get newsletter status from the API call
24
+ */
25
+ getNewsletterStatus(): Promise<Schemas["AccountNewsletterRecipient"]>;
26
+ /**
27
+ * Indicates if the user is subscribed to the newsletter
28
+ *
29
+ * Returns `true` if the user is subscribed to the newsletter, `false` otherwise
30
+ */
31
+ isNewsletterSubscriber: ComputedRef<boolean>;
32
+ /**
33
+ * Newsletter status
34
+ */
35
+ newsletterStatus: Ref<Schemas["AccountNewsletterRecipient"]["status"]>;
36
+ /**
37
+ * Inform about newsletter confirmation
38
+ */
39
+ confirmationNeeded: ComputedRef<boolean>;
40
+ };
41
+
42
+ /**
43
+ * Composable for newsletter subscription.
44
+ * @public
45
+ * @category Customer & Account
46
+ */
47
+ export function useNewsletter(): UseNewsletterReturn {
48
+ const { apiClient } = useShopwareContext();
49
+ const { getStorefrontUrl } = useInternationalization();
50
+ const newsletterStatus =
51
+ ref<Schemas["AccountNewsletterRecipient"]["status"]>("undefined");
52
+
53
+ async function newsletterSubscribe(
54
+ params: Omit<
55
+ operations["subscribeToNewsletter post /newsletter/subscribe"]["body"],
56
+ "storefrontUrl"
57
+ >,
58
+ ) {
59
+ const result = await apiClient.invoke(
60
+ "subscribeToNewsletter post /newsletter/subscribe",
61
+ {
62
+ body: {
63
+ ...params,
64
+ storefrontUrl: getStorefrontUrl(),
65
+ },
66
+ },
67
+ );
68
+ return result.data;
69
+ }
70
+
71
+ async function newsletterUnsubscribe(email: string) {
72
+ await apiClient.invoke(
73
+ "unsubscribeToNewsletter post /newsletter/unsubscribe",
74
+ {
75
+ body: { email },
76
+ },
77
+ );
78
+ }
79
+
80
+ async function getNewsletterStatus() {
81
+ const response = await apiClient.invoke(
82
+ "readNewsletterRecipient post /account/newsletter-recipient",
83
+ );
84
+ newsletterStatus.value = response.data.status;
85
+ return response.data;
86
+ }
87
+
88
+ const isNewsletterSubscriber = computed(
89
+ () =>
90
+ !(
91
+ ["optOut", "undefined"] as Array<
92
+ Schemas["AccountNewsletterRecipient"]["status"]
93
+ >
94
+ ).includes(newsletterStatus.value),
95
+ );
96
+
97
+ const confirmationNeeded = computed(
98
+ () => newsletterStatus.value === "notSet",
99
+ );
100
+
101
+ return {
102
+ newsletterSubscribe,
103
+ newsletterUnsubscribe,
104
+ isNewsletterSubscriber,
105
+ getNewsletterStatus,
106
+ newsletterStatus,
107
+ confirmationNeeded,
108
+ };
109
+ }