@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,321 @@
1
+ import { syncRefs } from "@vueuse/core";
2
+ import { computed, ref } from "vue";
3
+ import type { ComputedRef, Ref } from "vue";
4
+ import {
5
+ useCart,
6
+ useContext,
7
+ useInternationalization,
8
+ useSessionContext,
9
+ useShopwareContext,
10
+ } from "#imports";
11
+ import type { Schemas, operations } from "#shopware";
12
+
13
+ export type UseUserReturn = {
14
+ /**
15
+ * Logs-in user with given credentials
16
+ * @param params - username and password
17
+ *
18
+ * @see https://github.com/shopware/frontends/issues/112 if login fails due to missing context token
19
+ */
20
+ login(params: { username: string; password: string }): Promise<void>;
21
+ /**
22
+ * Registers the user for given credentials
23
+ * @param params {@link CustomerRegistrationParams}
24
+ * @returns {@link Customer} object on success
25
+ */
26
+ register(
27
+ params: Omit<
28
+ operations["register post /account/register"]["body"],
29
+ "storefrontUrl"
30
+ >,
31
+ ): Promise<Schemas["Customer"]>;
32
+ /**
33
+ * Whole {@link Customer} object
34
+ */
35
+ user: ComputedRef<Schemas["Customer"] | undefined>;
36
+ /**
37
+ * Indicates if the user is logged in
38
+ */
39
+ isLoggedIn: ComputedRef<boolean>;
40
+ /**
41
+ * Indicates if the user is logged in as a customer (not a guest)
42
+ */
43
+ isCustomerSession: ComputedRef<boolean>;
44
+ /**
45
+ * Indicates if the user is logged in as a guest
46
+ */
47
+ isGuestSession: ComputedRef<boolean>;
48
+ /**
49
+ * {@link Country} of the user
50
+ */
51
+ country: Ref<Schemas["Country"] | null>;
52
+ /**
53
+ * {@link Salutation} of the user
54
+ */
55
+ salutation: Ref<Schemas["Salutation"] | null>;
56
+ /**
57
+ * Default billing address id
58
+ */
59
+ defaultBillingAddressId: ComputedRef<string | null>;
60
+ /**
61
+ * Default shipping address id
62
+ */
63
+ defaultShippingAddressId: ComputedRef<string | null>;
64
+ /**
65
+ * Fetches the user data from the API
66
+ */
67
+ refreshUser(params?: Schemas["Criteria"]): Promise<Schemas["Customer"]>;
68
+ /**
69
+ * Logs out the user
70
+ */
71
+ logout(): Promise<
72
+ operations["logoutCustomer post /account/logout"]["response"]
73
+ >;
74
+ /**
75
+ * Loads the {@link Country} of the user
76
+ */
77
+ loadCountry(
78
+ countryId: string,
79
+ ): Promise<operations["readCountry post /country"]["response"]>;
80
+ /**
81
+ * Loads the {@link Salutation} for given id
82
+ */
83
+ loadSalutation(
84
+ salutationId: string,
85
+ ): Promise<operations["readSalutation post /salutation"]["response"]>;
86
+ /**
87
+ * Updates the user profile data
88
+ * @param personals {@link RequestParameters<'changeProfile'>}
89
+ * @returns
90
+ */
91
+ updatePersonalInfo(
92
+ personals: operations["changeProfile post /account/change-profile"]["body"],
93
+ ): Promise<void>;
94
+ /**
95
+ * Updates the user email
96
+ * @param updateEmailData - {@link RequestParameters<'changeEmail'>}
97
+ * @returns
98
+ */
99
+ updateEmail(
100
+ updateEmailData: operations["changeEmail post /account/change-email"]["body"],
101
+ ): Promise<void>;
102
+ /**
103
+ * Sets the default payment method for given id
104
+ * @param paymentMethodId
105
+ * @returns
106
+ */
107
+ setDefaultPaymentMethod(paymentMethodId: string): Promise<void>;
108
+ /**
109
+ * Default payment method for the user
110
+ */
111
+ userDefaultPaymentMethod: ComputedRef<
112
+ Schemas["PaymentMethod"]["translated"] | null
113
+ >;
114
+ /**
115
+ * Default billing address for the user
116
+ */
117
+ userDefaultBillingAddress: ComputedRef<Schemas["CustomerAddress"] | null>;
118
+ /**
119
+ * Default shipping address for the user
120
+ */
121
+ userDefaultShippingAddress: ComputedRef<Schemas["CustomerAddress"] | null>;
122
+ };
123
+
124
+ /**
125
+ * Composable for user management.
126
+ * @public
127
+ * @category Customer & Account
128
+ */
129
+ export function useUser(): UseUserReturn {
130
+ const { apiClient } = useShopwareContext();
131
+ const { userFromContext, refreshSessionContext } = useSessionContext();
132
+
133
+ const _user = useContext<Schemas["Customer"] | undefined>("customer");
134
+ syncRefs(userFromContext, _user, {
135
+ immediate: true,
136
+ });
137
+
138
+ const { getStorefrontUrl } = useInternationalization();
139
+ const { refreshCart } = useCart();
140
+
141
+ const userDefaultPaymentMethod = computed(
142
+ () => user.value?.defaultPaymentMethod?.translated || null,
143
+ );
144
+ const userDefaultBillingAddress = computed(
145
+ () => user.value?.defaultBillingAddress || null,
146
+ );
147
+ const userDefaultShippingAddress = computed(
148
+ () => user.value?.defaultShippingAddress || null,
149
+ );
150
+ const country: Ref<Schemas["Country"] | null> = ref(null);
151
+ const salutation: Ref<Schemas["Salutation"] | null> = ref(null);
152
+ const user = computed(() => _user.value);
153
+
154
+ async function login({
155
+ username,
156
+ password,
157
+ }: {
158
+ username: string;
159
+ password: string;
160
+ }): Promise<void> {
161
+ await apiClient.invoke("loginCustomer post /account/login", {
162
+ body: {
163
+ username,
164
+ password,
165
+ },
166
+ });
167
+ await refreshSessionContext();
168
+ refreshCart();
169
+ }
170
+
171
+ async function register(
172
+ params: Omit<
173
+ operations["register post /account/register"]["body"],
174
+ "storefrontUrl"
175
+ >,
176
+ ): Promise<Schemas["Customer"]> {
177
+ const { data } = await apiClient.invoke("register post /account/register", {
178
+ body: {
179
+ ...(params as operations["register post /account/register"]["body"]),
180
+ storefrontUrl: getStorefrontUrl(),
181
+ },
182
+ });
183
+ // Update the user data in the context if the user is active and not using double opt-in registration set in the Shopware Admin
184
+ if (data.active && !data.doubleOptInRegistration) {
185
+ _user.value = data;
186
+ }
187
+ await refreshSessionContext();
188
+ return data;
189
+ }
190
+
191
+ async function logout(): Promise<
192
+ operations["logoutCustomer post /account/logout"]["response"]
193
+ > {
194
+ const response = await apiClient.invoke(
195
+ "logoutCustomer post /account/logout",
196
+ );
197
+ await refreshSessionContext();
198
+ refreshCart();
199
+ return response.data;
200
+ }
201
+
202
+ async function refreshUser(
203
+ params: Schemas["Criteria"] = {},
204
+ ): Promise<Schemas["Customer"]> {
205
+ try {
206
+ const response = await apiClient.invoke(
207
+ "readCustomer post /account/customer",
208
+ { body: params },
209
+ );
210
+ _user.value = response.data;
211
+ return response.data;
212
+ } catch (e) {
213
+ _user.value = undefined;
214
+ throw e;
215
+ }
216
+ }
217
+
218
+ async function loadCountry(
219
+ countryId: string,
220
+ ): Promise<operations["readCountry post /country"]["response"]> {
221
+ const countries = await apiClient.invoke("readCountry post /country", {
222
+ body: {
223
+ filter: [
224
+ {
225
+ field: "id",
226
+ type: "equals",
227
+ value: countryId,
228
+ },
229
+ ],
230
+ },
231
+ });
232
+
233
+ country.value = countries.data.elements?.[0] ?? null;
234
+ return countries.data;
235
+ }
236
+
237
+ async function loadSalutation(
238
+ salutationId: string,
239
+ ): Promise<operations["readSalutation post /salutation"]["response"]> {
240
+ const salutations = await apiClient.invoke(
241
+ "readSalutation post /salutation",
242
+ {
243
+ body: {
244
+ filter: [
245
+ {
246
+ field: "id",
247
+ type: "equals",
248
+ value: salutationId,
249
+ },
250
+ ],
251
+ },
252
+ },
253
+ );
254
+ salutation.value = salutations.data.elements?.[0] ?? null;
255
+ return salutations.data;
256
+ }
257
+
258
+ async function updatePersonalInfo(
259
+ personals: operations["changeProfile post /account/change-profile"]["body"],
260
+ ): Promise<void> {
261
+ await apiClient.invoke("changeProfile post /account/change-profile", {
262
+ body: personals,
263
+ });
264
+ }
265
+
266
+ async function updateEmail(
267
+ updateEmailData: operations["changeEmail post /account/change-email"]["body"],
268
+ ): Promise<void> {
269
+ await apiClient.invoke("changeEmail post /account/change-email", {
270
+ body: updateEmailData,
271
+ });
272
+ }
273
+
274
+ async function setDefaultPaymentMethod(
275
+ paymentMethodId: string,
276
+ ): Promise<void> {
277
+ await apiClient.invoke(
278
+ "changePaymentMethod post /account/change-payment-method/{paymentMethodId}",
279
+ {
280
+ pathParams: { paymentMethodId },
281
+ },
282
+ );
283
+ }
284
+ const defaultBillingAddressId = computed(
285
+ () => user.value?.defaultBillingAddressId || null,
286
+ );
287
+ const defaultShippingAddressId = computed(
288
+ () => user.value?.defaultShippingAddressId || null,
289
+ );
290
+ const isLoggedIn = computed(
291
+ () => !!user.value?.id && !!user.value.active && !user.value.guest,
292
+ );
293
+
294
+ const isCustomerSession = computed(
295
+ () => !!user.value?.id && !user.value.guest,
296
+ );
297
+ const isGuestSession = computed(() => !!user.value?.guest);
298
+
299
+ return {
300
+ login,
301
+ register,
302
+ user,
303
+ isLoggedIn,
304
+ isCustomerSession,
305
+ isGuestSession,
306
+ refreshUser,
307
+ logout,
308
+ updateEmail,
309
+ updatePersonalInfo,
310
+ setDefaultPaymentMethod,
311
+ loadSalutation,
312
+ salutation,
313
+ loadCountry,
314
+ country,
315
+ defaultBillingAddressId,
316
+ defaultShippingAddressId,
317
+ userDefaultPaymentMethod,
318
+ userDefaultBillingAddress,
319
+ userDefaultShippingAddress,
320
+ };
321
+ }
@@ -0,0 +1,178 @@
1
+ import { describe, expect, it, vi } from "vitest";
2
+ import { computed, ref } from "vue";
3
+ import { useSyncWishlist, useUser, useWishlist } from "#imports";
4
+ import type { Schemas } from "#shopware";
5
+ import { useSetup } from "../_test";
6
+
7
+ const getMockedUser = (isLoggedIn: boolean, isGuestSession: boolean) =>
8
+ ({
9
+ isLoggedIn: ref(isLoggedIn),
10
+ isGuestSession: ref(isGuestSession),
11
+ }) as ReturnType<typeof useUser>;
12
+
13
+ vi.mock("../useLocalWishlist/useLocalWishlist.ts", () => ({
14
+ useLocalWishlist() {
15
+ return {
16
+ getWishlistProducts: () => undefined,
17
+ items: {
18
+ value: [
19
+ "local-testId-1",
20
+ "local-testId-2",
21
+ "local-testId-3",
22
+ "local-testId-4",
23
+ "local-testId-5",
24
+ "local-testId-6",
25
+ "local-testId-7",
26
+ "local-testId-8",
27
+ "local-testId-9",
28
+ "local-testId-10",
29
+ "local-testId-11",
30
+ "local-testId-12",
31
+ "local-testId-13",
32
+ "local-testId-14",
33
+ "local-testId-15",
34
+ "local-testId-16",
35
+ "local-testId-17",
36
+ ],
37
+ },
38
+ clearWishlist: () => undefined,
39
+ count: ref(17),
40
+ };
41
+ },
42
+ }));
43
+
44
+ vi.mock("../useSyncWishlist/useSyncWishlist.ts");
45
+ vi.mock("../useUser/useUser.ts");
46
+
47
+ describe("useWishlist - not logged in user", () => {
48
+ it("should merge wishlist products", () => {
49
+ vi.mocked(useUser).mockReturnValue(getMockedUser(false, true));
50
+ vi.mocked(useSyncWishlist).mockReturnValue({
51
+ getWishlistProducts: () => new Promise<void>((resolve) => resolve()),
52
+ items: computed((): string[] => []),
53
+ addToWishlistSync: () => undefined,
54
+ mergeWishlistProducts: () => undefined,
55
+ removeFromWishlistSync: () => undefined,
56
+ count: computed(() => 17),
57
+ currentPage: computed(() => 2),
58
+ });
59
+ const { vm } = useSetup(() => useWishlist());
60
+
61
+ vm.clearWishlist();
62
+ vm.getWishlistProducts({ page: 2, limit: 15 });
63
+ vm.mergeWishlistProducts();
64
+
65
+ expect(vm.items.length).toBe(17);
66
+ expect(vm.count).toBe(17);
67
+ expect(Number(vm.totalPagesCount)).toBe(2);
68
+ });
69
+
70
+ it("should get wishlist products", async () => {
71
+ vi.mocked(useUser).mockReturnValue(getMockedUser(false, true));
72
+ vi.mocked(useSyncWishlist).mockReturnValue({
73
+ getWishlistProducts: () => new Promise<void>((resolve) => resolve()),
74
+ items: computed((): string[] => ["test1"]),
75
+ addToWishlistSync: () => undefined,
76
+ mergeWishlistProducts: () => undefined,
77
+ removeFromWishlistSync: () => undefined,
78
+ count: computed(() => 15),
79
+ currentPage: computed(() => 2),
80
+ });
81
+ const { vm } = useSetup(() => useWishlist());
82
+
83
+ vm.getWishlistProducts();
84
+
85
+ expect(vm.items).toEqual([
86
+ "local-testId-1",
87
+ "local-testId-2",
88
+ "local-testId-3",
89
+ "local-testId-4",
90
+ "local-testId-5",
91
+ "local-testId-6",
92
+ "local-testId-7",
93
+ "local-testId-8",
94
+ "local-testId-9",
95
+ "local-testId-10",
96
+ "local-testId-11",
97
+ "local-testId-12",
98
+ "local-testId-13",
99
+ "local-testId-14",
100
+ "local-testId-15",
101
+ "local-testId-16",
102
+ "local-testId-17",
103
+ ]);
104
+
105
+ const query = {
106
+ limit: 1,
107
+ page: 2,
108
+ } as Schemas["Criteria"];
109
+ vm.getWishlistProducts(query);
110
+
111
+ expect(Number(vm.currentPage)).toBe(2);
112
+ });
113
+ });
114
+
115
+ describe("useWishlist - logged in user", () => {
116
+ it("should merge wishlist products", () => {
117
+ vi.mocked(useUser).mockReturnValue(getMockedUser(true, false));
118
+ vi.mocked(useSyncWishlist).mockReturnValue({
119
+ getWishlistProducts: () => new Promise<void>((resolve) => resolve()),
120
+ items: computed((): string[] => {
121
+ return [
122
+ "local-test-1",
123
+ "local-test-2",
124
+ "local-test-3",
125
+ "local-test-4",
126
+ "local-test-5",
127
+ "local-test-6",
128
+ "local-test-7",
129
+ "local-test-8",
130
+ "local-test-9",
131
+ "local-test-10",
132
+ "local-test-11",
133
+ "local-test-12",
134
+ "local-test-13",
135
+ "local-test-14",
136
+ "local-test-15",
137
+ ];
138
+ }),
139
+ addToWishlistSync: () => undefined,
140
+ mergeWishlistProducts: () => undefined,
141
+ removeFromWishlistSync: () => undefined,
142
+ count: computed(() => 15),
143
+ currentPage: computed(() => 1),
144
+ });
145
+ const { vm } = useSetup(() => useWishlist());
146
+
147
+ vm.clearWishlist();
148
+ vm.getWishlistProducts();
149
+ vm.mergeWishlistProducts();
150
+
151
+ expect(vm.items.length).toBe(15);
152
+ expect(vm.count).toBe(15);
153
+ });
154
+
155
+ it("should get wishlist products", () => {
156
+ vi.mocked(useUser).mockReturnValue(getMockedUser(true, false));
157
+ const { vm } = useSetup(() => useWishlist());
158
+ vm.getWishlistProducts();
159
+
160
+ expect(vm.items).toEqual([
161
+ "local-test-1",
162
+ "local-test-2",
163
+ "local-test-3",
164
+ "local-test-4",
165
+ "local-test-5",
166
+ "local-test-6",
167
+ "local-test-7",
168
+ "local-test-8",
169
+ "local-test-9",
170
+ "local-test-10",
171
+ "local-test-11",
172
+ "local-test-12",
173
+ "local-test-13",
174
+ "local-test-14",
175
+ "local-test-15",
176
+ ]);
177
+ });
178
+ });
@@ -0,0 +1,128 @@
1
+ import { defu } from "defu";
2
+ /**
3
+ * Template composable
4
+ */
5
+ import { computed, ref } from "vue";
6
+ import type { ComputedRef } from "vue";
7
+ import { useLocalWishlist, useSyncWishlist, useUser } from "#imports";
8
+ import type { Schemas } from "#shopware";
9
+
10
+ export type UseWishlistReturn = {
11
+ /**
12
+ * Merge products with wishlist between async (API) and sync (localstorage) wishlists
13
+ */
14
+ mergeWishlistProducts(): void;
15
+ /**
16
+ * Get products list added to wishlist
17
+ */
18
+ getWishlistProducts(query?: Schemas["Criteria"]): Promise<void>;
19
+ /**
20
+ * Clear wishlist
21
+ */
22
+ clearWishlist(): void;
23
+ /**
24
+ * Wishlist items (Product IDs)
25
+ */
26
+ items: ComputedRef<string[]>;
27
+ /**
28
+ * Current page number
29
+ */
30
+ currentPage: ComputedRef<number>;
31
+ /**
32
+ * total pages count
33
+ */
34
+ totalPagesCount: ComputedRef<number>;
35
+ /**
36
+ * total wishlist items count
37
+ */
38
+ count: ComputedRef<number>;
39
+ /**
40
+ * Indicates if the wishlist can be synced
41
+ */
42
+ canSyncWishlist: ComputedRef<boolean>;
43
+ };
44
+
45
+ /**
46
+ * Composable to manage wishlist
47
+ * @public
48
+ * @category Wishlist
49
+ */
50
+ export function useWishlist(): UseWishlistReturn {
51
+ const { isLoggedIn, isGuestSession } = useUser();
52
+ const canSyncWishlist = computed(
53
+ () => isLoggedIn.value && !isGuestSession.value,
54
+ );
55
+ const {
56
+ getWishlistProducts: getWishlistProductsLocal,
57
+ items: itemsLocal,
58
+ clearWishlist: clearWishlistLocal,
59
+ } = useLocalWishlist();
60
+
61
+ const {
62
+ getWishlistProducts: getWishlistProductsSync,
63
+ items: itemsSync,
64
+ mergeWishlistProducts: mergeWishlistProductsSync,
65
+ removeFromWishlistSync,
66
+ count: countSync,
67
+ currentPage,
68
+ } = useSyncWishlist();
69
+
70
+ const limit = ref<number>(15);
71
+
72
+ const getWishlistProducts = async (query?: Schemas["Criteria"]) => {
73
+ const wishlistQuery = {} as Schemas["Criteria"];
74
+ if (query) {
75
+ defu(wishlistQuery, query);
76
+ }
77
+ if (query?.limit) {
78
+ limit.value = query.limit;
79
+ }
80
+
81
+ if (canSyncWishlist.value) {
82
+ await getWishlistProductsSync(query);
83
+ } else {
84
+ getWishlistProductsLocal();
85
+ }
86
+ };
87
+
88
+ const items = computed(() =>
89
+ canSyncWishlist.value ? itemsSync.value : itemsLocal.value,
90
+ );
91
+
92
+ const totalPagesCount = computed(() => Math.ceil(count.value / limit.value));
93
+
94
+ const clearWishlist = async () => {
95
+ if (canSyncWishlist.value) {
96
+ await Promise.all(items.value.map((id) => removeFromWishlistSync(id)));
97
+ await getWishlistProductsSync();
98
+ } else {
99
+ clearWishlistLocal();
100
+ }
101
+ };
102
+
103
+ const mergeWishlistProducts = async () => {
104
+ if (itemsLocal.value?.length) {
105
+ await mergeWishlistProductsSync(itemsLocal.value);
106
+ clearWishlist();
107
+ }
108
+ await getWishlistProductsSync();
109
+ };
110
+
111
+ const count = computed(() => {
112
+ if (canSyncWishlist.value) {
113
+ return countSync.value;
114
+ }
115
+ return items.value.length;
116
+ });
117
+
118
+ return {
119
+ mergeWishlistProducts,
120
+ getWishlistProducts,
121
+ clearWishlist,
122
+ items,
123
+ currentPage,
124
+ totalPagesCount,
125
+ count,
126
+ canSyncWishlist,
127
+ };
128
+ }
@@ -0,0 +1,11 @@
1
+ import type { createAPIClient } from "@shopware/api-client";
2
+ import type {
3
+ components as defaultComponents,
4
+ operations as defaultOperations,
5
+ } from "@shopware/api-client/store-api-types";
6
+
7
+ export type operations = defaultOperations;
8
+
9
+ export type Schemas = defaultComponents["schemas"];
10
+
11
+ export type ApiClient = ReturnType<typeof createAPIClient<operations>>;