@shopware/composables 1.9.1 → 1.11.0

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 (60) hide show
  1. package/README.md +12 -5
  2. package/dist/index.d.mts +116 -34
  3. package/dist/index.d.ts +116 -34
  4. package/dist/index.mjs +117 -74
  5. package/package.json +13 -12
  6. package/src/cms/cmsAssociations.ts +5 -1
  7. package/src/cms/useCmsElementConfig.test.ts +8 -0
  8. package/src/cms/useCmsElementConfig.ts +4 -1
  9. package/src/cms/useCmsElementImage.test.ts +23 -0
  10. package/src/cms/useCmsElementProductBox.test.ts +21 -0
  11. package/src/devtools/plugin.ts +1 -2
  12. package/src/mocks/Configurator.ts +36 -36
  13. package/src/types/cmsBlockTypes.ts +2 -0
  14. package/src/types/cmsElementTypes.ts +24 -18
  15. package/src/useAddToCart/useAddToCart.test.ts +18 -1
  16. package/src/useAddress/useAddress.test.ts +41 -2
  17. package/src/useAddress/useAddress.ts +1 -1
  18. package/src/useCart/useCart.test.ts +42 -0
  19. package/src/useCart/useCart.ts +17 -0
  20. package/src/useCartNotification/useCartNotification.test.ts +30 -0
  21. package/src/useCheckout/useCheckout.test.ts +43 -1
  22. package/src/useCmsMeta/useCmsMeta.test.ts +26 -0
  23. package/src/useCountries/useCountries.test.ts +14 -0
  24. package/src/useCustomerOrders/useCustomerOrders.ts +1 -1
  25. package/src/useDefaultOrderAssociations/useDefaultOrderAssociations.test.ts +19 -21
  26. package/src/useDefaultOrderAssociations/useDefaultOrderAssociations.ts +23 -30
  27. package/src/useLandingSearch/useLandingSearch.test.ts +1 -1
  28. package/src/useLandingSearch/useLandingSearch.ts +1 -1
  29. package/src/useListing/useListing.test.ts +73 -0
  30. package/src/useListing/useListing.ts +10 -3
  31. package/src/useLocalWishlist/useLocalWishlist.test.ts +44 -5
  32. package/src/useLocalWishlist/useLocalWishlist.ts +3 -2
  33. package/src/useNavigationContext/useNavigationContext.test.ts +25 -24
  34. package/src/useNewsletter/useNewsletter.test.ts +16 -0
  35. package/src/useNewsletter/useNewsletter.ts +13 -0
  36. package/src/useOrderDetails/useOrderDetails.test.ts +92 -3
  37. package/src/useOrderDetails/useOrderDetails.ts +12 -14
  38. package/src/useOrderPayment/useOrderPayment.test.ts +55 -1
  39. package/src/useOrderPayment/useOrderPayment.ts +1 -0
  40. package/src/usePrice/usePrice.test.ts +10 -0
  41. package/src/usePrice/usePrice.ts +2 -7
  42. package/src/useProduct/useProduct.test.ts +14 -1
  43. package/src/useProductAssociations/useProductAssociations.spec.ts +1 -0
  44. package/src/useProductConfigurator/useProductConfigurator.spec.ts +38 -0
  45. package/src/useProductConfigurator/useProductConfigurator.ts +1 -1
  46. package/src/useProductPrice/useProductPrice.test.ts +7 -7
  47. package/src/useProductPrice/useProductPrice.ts +12 -4
  48. package/src/useProductReviews/useProductReviews.test.ts +15 -3
  49. package/src/useProductWishlist/useProductWishlist.ts +2 -2
  50. package/src/useSalutations/useSalutations.spec.ts +13 -0
  51. package/src/useSessionContext/useSessionContext.test.ts +122 -4
  52. package/src/useSessionContext/useSessionContext.ts +14 -2
  53. package/src/useSyncWishlist/useSyncWishlist.test.ts +94 -25
  54. package/src/useSyncWishlist/useSyncWishlist.ts +27 -8
  55. package/src/useUrlResolver/useUrlResolver.test.ts +6 -12
  56. package/src/useUrlResolver/useUrlResolver.ts +4 -6
  57. package/src/useUser/useUser.test.ts +233 -18
  58. package/src/useUser/useUser.ts +6 -1
  59. package/src/useWishlist/useWishlist.test.ts +133 -26
  60. package/src/useWishlist/useWishlist.ts +22 -6
@@ -14,20 +14,29 @@ describe("useSyncWishlist", () => {
14
14
  describe("methods", () => {
15
15
  describe("addToWishlist", () => {
16
16
  it("should add product to the wishlist", async () => {
17
- const { vm } = useSetup(() => useSyncWishlist());
17
+ const { vm, injections } = useSetup(() => useSyncWishlist());
18
+ injections.apiClient.invoke.mockResolvedValue({});
19
+
20
+ await vm.addToWishlistSync("some-id");
18
21
 
19
- await expect(vm.addToWishlistSync("some-id")).resolves.toBe(undefined);
22
+ expect(injections.apiClient.invoke).toHaveBeenCalledWith(
23
+ "addProductOnWishlist post /customer/wishlist/add/{productId}",
24
+ { pathParams: { productId: "some-id" } },
25
+ );
20
26
  });
21
27
  });
22
28
 
23
29
  describe("removeFromWishlist", () => {
24
- it("should remove product from the wishlist", () => {
25
- const { vm } = useSetup(() => useSyncWishlist());
30
+ it("should remove product from the wishlist", async () => {
31
+ const { vm, injections } = useSetup(() => useSyncWishlist());
32
+ injections.apiClient.invoke.mockResolvedValue({});
26
33
 
27
- vm.getWishlistProducts();
28
- vm.removeFromWishlistSync("some-id");
29
- // Mocked value
30
- expect(vm.count).toBe(vm.count);
34
+ await vm.removeFromWishlistSync("some-id");
35
+
36
+ expect(injections.apiClient.invoke).toHaveBeenCalledWith(
37
+ "deleteProductOnWishlist delete /customer/wishlist/delete/{productId}",
38
+ { pathParams: { productId: "some-id" } },
39
+ );
31
40
  });
32
41
  });
33
42
 
@@ -84,32 +93,92 @@ describe("useSyncWishlist", () => {
84
93
  );
85
94
  expect(vm.count).toBe(9);
86
95
  expect(vm.items.length).toBe(1);
96
+ expect(vm.products).toStrictEqual([{ id: "test-id" }]);
97
+ });
98
+
99
+ it("getWishlistProducts with custom criteria", async () => {
100
+ const { vm, injections } = useSetup(() => useSyncWishlist());
101
+ injections.apiClient.invoke.mockResolvedValue({
102
+ data: {
103
+ products: {
104
+ elements: [],
105
+ total: 0,
106
+ },
107
+ },
108
+ });
109
+
110
+ await vm.getWishlistProducts({ limit: 10, page: 2 });
111
+
112
+ expect(injections.apiClient.invoke).toHaveBeenCalledWith(
113
+ expect.stringContaining("readCustomerWishlist"),
114
+ expect.objectContaining({
115
+ body: expect.objectContaining({
116
+ limit: 10,
117
+ page: 2,
118
+ "total-count-mode": "exact",
119
+ }),
120
+ }),
121
+ );
122
+ });
123
+
124
+ it("getWishlistProducts with null total, page, limit uses defaults", async () => {
125
+ const { vm, injections } = useSetup(() => useSyncWishlist());
126
+ injections.apiClient.invoke.mockResolvedValue({
127
+ data: {
128
+ products: {
129
+ elements: [{ id: "id-1" }],
130
+ },
131
+ },
132
+ });
133
+
134
+ await vm.getWishlistProducts();
135
+
136
+ expect(vm.count).toBe(0);
137
+ expect(vm.currentPage).toBe(1);
138
+ expect(vm.limit).toBe(15);
87
139
  });
88
140
  });
89
141
 
90
142
  describe("getWishlistProducts - error", () => {
91
143
  it("should handle error after fetching product wishlist", async () => {
92
- const { vm } = useSetup(() => useSyncWishlist(), {
93
- apiClient: {
94
- invoke: vi.fn().mockImplementation(() => {
95
- throw new ApiClientError({
96
- status: 500,
97
- _data: {
98
- errors: [
99
- {
100
- title: "Test error",
101
- },
102
- ],
144
+ const { vm, injections } = useSetup(() => useSyncWishlist());
145
+ // First, set up a successful call to populate state
146
+ injections.apiClient.invoke.mockResolvedValueOnce({
147
+ data: {
148
+ products: {
149
+ total: 9,
150
+ page: 1,
151
+ elements: [
152
+ {
153
+ id: "test-id",
103
154
  },
104
- } as unknown as FetchResponse<{
105
- errors: Array<{ title: string }>;
106
- }>);
107
- }),
155
+ ],
156
+ },
108
157
  },
109
158
  });
110
- vm.getWishlistProducts();
111
- expect(consoleErrorSpy).toHaveBeenCalledTimes(1);
159
+ await vm.getWishlistProducts();
112
160
  expect(vm.count).toBe(9);
161
+ expect(vm.items.length).toBe(1);
162
+
163
+ // Now test error handling - state should be cleared on error
164
+ injections.apiClient.invoke.mockImplementation(() => {
165
+ throw new ApiClientError({
166
+ status: 500,
167
+ _data: {
168
+ errors: [
169
+ {
170
+ title: "Test error",
171
+ },
172
+ ],
173
+ },
174
+ } as unknown as FetchResponse<{
175
+ errors: Array<{ title: string }>;
176
+ }>);
177
+ });
178
+ await vm.getWishlistProducts();
179
+ expect(consoleErrorSpy).toHaveBeenCalledTimes(1);
180
+ // State should be cleared when error occurs
181
+ expect(vm.count).toBe(0);
113
182
  expect(vm.items.length).toBe(0);
114
183
  });
115
184
  });
@@ -1,4 +1,3 @@
1
- import { ApiClientError } from "@shopware/api-client";
2
1
  import { computed, ref } from "vue";
3
2
  import type { ComputedRef, Ref } from "vue";
4
3
  import { useShopwareContext } from "#imports";
@@ -35,12 +34,26 @@ export type UseSyncWishlistReturn = {
35
34
  * Current page number
36
35
  */
37
36
  currentPage: ComputedRef<number>;
37
+ /**
38
+ * Limit number of products per page
39
+ */
40
+ limit: ComputedRef<number>;
41
+ /**
42
+ * Wishlist products
43
+ */
44
+ products: ComputedRef<Schemas["Product"][]>;
45
+ /**
46
+ * Indicates if the wishlist is loading
47
+ */
48
+ isLoading: Ref<boolean>;
38
49
  };
39
50
 
40
51
  const _wishlistItems: Ref<string[]> = ref([]);
52
+ const _wishlistProducts: Ref<Schemas["Product"][]> = ref([]);
41
53
  const _currentPage: Ref<number> = ref(1);
54
+ const _limit: Ref<number> = ref(15);
42
55
  const totalWishlistItemsCount: Ref<number> = ref(0);
43
-
56
+ const isLoading: Ref<boolean> = ref(false);
44
57
  /**
45
58
  * Composable to manage wishlist via API
46
59
  * @public
@@ -81,14 +94,15 @@ export function useSyncWishlist(): UseSyncWishlistReturn {
81
94
  _wishlistItems.value = [
82
95
  ...response.data.products.elements.map((element) => element.id),
83
96
  ];
97
+ _wishlistProducts.value = response.data.products.elements;
84
98
  totalWishlistItemsCount.value = response.data.products.total ?? 0;
85
99
  _currentPage.value = response.data.products.page ?? 1;
86
- } catch (e) {
87
- if (e instanceof ApiClientError) {
88
- // If 404 ignore printing error and reset wishlist
89
- if (e.status !== 404) console.error(e);
90
- _wishlistItems.value = [];
91
- }
100
+ _limit.value = response.data.products.limit ?? 15;
101
+ } catch (error) {
102
+ console.error("[useSyncWishlist][getWishlistProducts][error]:", error);
103
+ _wishlistItems.value = [];
104
+ _wishlistProducts.value = [];
105
+ totalWishlistItemsCount.value = 0;
92
106
  }
93
107
  }
94
108
 
@@ -104,14 +118,19 @@ export function useSyncWishlist(): UseSyncWishlistReturn {
104
118
  const items = computed(() => _wishlistItems.value);
105
119
  const count = computed(() => totalWishlistItemsCount.value);
106
120
  const currentPage = computed(() => _currentPage.value);
121
+ const products = computed(() => _wishlistProducts.value);
122
+ const limit = computed(() => _limit.value);
107
123
 
108
124
  return {
109
125
  getWishlistProducts,
110
126
  addToWishlistSync,
111
127
  removeFromWishlistSync,
112
128
  mergeWishlistProducts,
129
+ products,
113
130
  items,
114
131
  count,
115
132
  currentPage,
133
+ isLoading,
134
+ limit,
116
135
  };
117
136
  }
@@ -1,14 +1,7 @@
1
- import { buildUrlPrefix } from "@shopware/helpers";
2
- import { describe, expect, it, vi } from "vitest";
1
+ import { describe, expect, it } from "vitest";
3
2
  import { useSetup } from "../_test";
4
3
  import { useUrlResolver } from "./useUrlResolver";
5
4
 
6
- vi.mock("@shopware/helpers", async () => {
7
- return {
8
- buildUrlPrefix: vi.fn(),
9
- };
10
- });
11
-
12
5
  describe("useUrlResolver", () => {
13
6
  it("resolve url", async () => {
14
7
  const { vm } = await useSetup(useUrlResolver);
@@ -16,10 +9,11 @@ describe("useUrlResolver", () => {
16
9
  expect(() => vm.resolveUrl("x".repeat(2084))).toThrow();
17
10
  });
18
11
 
19
- it("resolve url with navigation pattern", async () => {
20
- const { vm } = await useSetup(useUrlResolver);
21
- vm.resolveUrl("/de/navigation/123");
12
+ it("resolve url with navigation pattern and urlPrefix", async () => {
13
+ const { vm } = await useSetup(useUrlResolver, {
14
+ urlPrefix: "shop",
15
+ } as Parameters<typeof useSetup>[1]);
22
16
 
23
- expect(buildUrlPrefix).toHaveBeenCalled();
17
+ expect(vm.resolveUrl("/en/navigation/123")).toBe("/shop/en/navigation/123");
24
18
  });
25
19
  });
@@ -2,7 +2,8 @@ import { buildUrlPrefix } from "@shopware/helpers";
2
2
  import { inject } from "vue";
3
3
 
4
4
  export function useUrlResolver() {
5
- const getUrlPrefix = () => inject("urlPrefix", "");
5
+ const urlPrefix = inject("urlPrefix", "");
6
+ const getUrlPrefix = () => urlPrefix;
6
7
 
7
8
  const resolveUrl = (url: string) => {
8
9
  // @see: https://codeql.github.com/codeql-query-help/javascript/js-polynomial-redos/
@@ -11,14 +12,11 @@ export function useUrlResolver() {
11
12
  }
12
13
 
13
14
  const navigationPattern = /[a-zA-Z0-9]+\/navigation\/[a-zA-Z0-9]+/;
14
- const urlPrefix = getUrlPrefix();
15
+ const prefix = getUrlPrefix();
15
16
 
16
17
  if (navigationPattern.test(url)) {
17
18
  const newUrl = url.split("/").slice(1);
18
-
19
- if (newUrl.length > 0) {
20
- return `${buildUrlPrefix(newUrl.join("/"), urlPrefix)}`;
21
- }
19
+ return buildUrlPrefix(newUrl.join("/"), prefix).path;
22
20
  }
23
21
 
24
22
  return url;
@@ -1,5 +1,5 @@
1
1
  import type { operations } from "@shopware/api-client/api-types";
2
- import { describe, expect, it, vi } from "vitest";
2
+ import { afterEach, describe, expect, it, vi } from "vitest";
3
3
  import { ref } from "vue";
4
4
  import { useSetup } from "../_test";
5
5
  import { useUser } from "./useUser";
@@ -16,12 +16,13 @@ vi.mock("../useCart/useCart.ts", async () => {
16
16
  });
17
17
 
18
18
  const refreshSessionContextSpy = vi.fn();
19
+ const userFromContextRef = ref();
19
20
  vi.mock("../useSessionContext/useSessionContext.ts", async () => {
20
21
  return {
21
22
  useSessionContext: () => {
22
23
  return {
23
24
  refreshSessionContext: refreshSessionContextSpy,
24
- userFromContext: ref(),
25
+ userFromContext: userFromContextRef,
25
26
  };
26
27
  },
27
28
  };
@@ -52,6 +53,10 @@ const REGISTRATION_DATA: Omit<
52
53
  };
53
54
 
54
55
  describe("useUser", () => {
56
+ afterEach(() => {
57
+ userFromContextRef.value = undefined;
58
+ });
59
+
55
60
  it("login function", async () => {
56
61
  const { vm, injections } = useSetup(() => useUser());
57
62
 
@@ -68,8 +73,10 @@ describe("useUser", () => {
68
73
 
69
74
  it("register function", async () => {
70
75
  const { vm, injections } = useSetup(() => useUser());
71
- injections.apiClient.invoke.mockResolvedValue({ data: {} });
72
- await vm.register(REGISTRATION_DATA);
76
+ const registeredCustomer = { id: "reg-1", email: "test@test.testwwww" };
77
+ injections.apiClient.invoke.mockResolvedValue({ data: registeredCustomer });
78
+
79
+ const result = await vm.register(REGISTRATION_DATA);
73
80
 
74
81
  expect(injections.apiClient.invoke).toHaveBeenCalledWith(
75
82
  expect.stringContaining("register"),
@@ -80,6 +87,7 @@ describe("useUser", () => {
80
87
  },
81
88
  }),
82
89
  );
90
+ expect(result).toEqual(registeredCustomer);
83
91
  });
84
92
 
85
93
  it("register function with refresh", async () => {
@@ -133,26 +141,32 @@ describe("useUser", () => {
133
141
 
134
142
  it("logout", async () => {
135
143
  const { vm, injections } = useSetup(() => useUser());
136
- injections.apiClient.invoke.mockResolvedValue({ data: {} });
137
- await vm.logout();
144
+ const logoutResponse = { data: { redirectUrl: "/" } };
145
+ injections.apiClient.invoke.mockResolvedValue(logoutResponse);
146
+
147
+ const result = await vm.logout();
138
148
 
139
149
  expect(injections.apiClient.invoke).toHaveBeenCalledWith(
140
150
  expect.stringContaining("logoutCustomer"),
141
151
  );
152
+ expect(result).toEqual(logoutResponse.data);
142
153
  });
143
154
 
144
155
  it("refreshUser", async () => {
145
156
  const { vm, injections } = useSetup(() => useUser());
146
- injections.apiClient.invoke.mockResolvedValue({ data: {} });
147
- await vm.refreshUser();
157
+ const customerData = { id: "cust-1", email: "test@test.com" };
158
+ injections.apiClient.invoke.mockResolvedValue({ data: customerData });
159
+
160
+ const result = await vm.refreshUser();
148
161
 
149
162
  expect(injections.apiClient.invoke).toHaveBeenCalledWith(
150
163
  expect.stringContaining("readCustomer"),
151
164
  expect.anything(),
152
165
  );
166
+ expect(result).toEqual(customerData);
153
167
  });
154
168
 
155
- it("refreshUser - error", async () => {
169
+ it("refreshUser - error clears user", async () => {
156
170
  const { vm } = useSetup(() => useUser(), {
157
171
  apiClient: {
158
172
  invoke: vi.fn().mockImplementation(() => {
@@ -160,10 +174,10 @@ describe("useUser", () => {
160
174
  }),
161
175
  },
162
176
  });
177
+ userFromContextRef.value = { id: "existing", active: true, guest: false };
163
178
 
164
- await expect(async () => {
165
- await vm.refreshUser();
166
- }).rejects.toThrowError();
179
+ await expect(vm.refreshUser()).rejects.toThrowError();
180
+ expect(vm.user).toBeUndefined();
167
181
  });
168
182
 
169
183
  it("loadCountry", async () => {
@@ -201,14 +215,18 @@ describe("useUser", () => {
201
215
  expect(vm.country).toEqual({ name: "Poland", id: "2de9ecc24e" });
202
216
  });
203
217
 
204
- it("updatePersonalInfo", async () => {
218
+ it("updatePersonalInfo - business", async () => {
205
219
  const { vm, injections } = useSetup(() => useUser());
206
220
  injections.apiClient.invoke.mockResolvedValue({ data: {} });
221
+
207
222
  await vm.updatePersonalInfo({
208
223
  firstName: "test",
209
224
  lastName: "test",
210
225
  salutationId: "d5e543063dd642b48ef94b02d68e5785",
211
226
  title: "",
227
+ accountType: "business",
228
+ company: "test",
229
+ vatIds: ["1234567890"],
212
230
  });
213
231
 
214
232
  expect(injections.apiClient.invoke).toHaveBeenCalledWith(
@@ -219,6 +237,59 @@ describe("useUser", () => {
219
237
  lastName: "test",
220
238
  salutationId: "d5e543063dd642b48ef94b02d68e5785",
221
239
  title: "",
240
+ accountType: "business",
241
+ company: "test",
242
+ vatIds: ["1234567890"],
243
+ },
244
+ }),
245
+ );
246
+
247
+ await vm.updatePersonalInfo({
248
+ firstName: "test",
249
+ lastName: "test",
250
+ salutationId: "d5e543063dd642b48ef94b02d68e5785",
251
+ title: "",
252
+ accountType: "business",
253
+ company: "test",
254
+ vatIds: "1234567890" as unknown as [string, ...string[]],
255
+ });
256
+
257
+ expect(injections.apiClient.invoke).toHaveBeenCalledWith(
258
+ expect.stringContaining("changeProfile"),
259
+ expect.objectContaining({
260
+ body: {
261
+ firstName: "test",
262
+ lastName: "test",
263
+ salutationId: "d5e543063dd642b48ef94b02d68e5785",
264
+ title: "",
265
+ accountType: "business",
266
+ company: "test",
267
+ vatIds: ["1234567890"],
268
+ },
269
+ }),
270
+ );
271
+ });
272
+
273
+ it("updatePersonalInfo - private", async () => {
274
+ const { vm, injections } = useSetup(() => useUser());
275
+ injections.apiClient.invoke.mockResolvedValue({ data: {} });
276
+ await vm.updatePersonalInfo({
277
+ firstName: "test",
278
+ lastName: "test",
279
+ salutationId: "d5e543063dd642b48ef94b02d68e5785",
280
+ title: "",
281
+ accountType: "private",
282
+ });
283
+
284
+ expect(injections.apiClient.invoke).toHaveBeenCalledWith(
285
+ expect.stringContaining("changeProfile"),
286
+ expect.objectContaining({
287
+ body: {
288
+ firstName: "test",
289
+ lastName: "test",
290
+ salutationId: "d5e543063dd642b48ef94b02d68e5785",
291
+ title: "",
292
+ accountType: "private",
222
293
  },
223
294
  }),
224
295
  );
@@ -262,8 +333,12 @@ describe("useUser", () => {
262
333
 
263
334
  it("loadSalutation", async () => {
264
335
  const { vm, injections } = useSetup(() => useUser());
265
- injections.apiClient.invoke.mockResolvedValue({ data: {} });
266
- await vm.loadSalutation("test");
336
+ const salutationData = { elements: [{ id: "test", name: "test" }] };
337
+ injections.apiClient.invoke.mockResolvedValue({
338
+ data: salutationData,
339
+ });
340
+
341
+ const result = await vm.loadSalutation("test");
267
342
 
268
343
  expect(injections.apiClient.invoke).toHaveBeenCalledWith(
269
344
  expect.stringContaining("readSalutation"),
@@ -279,12 +354,152 @@ describe("useUser", () => {
279
354
  },
280
355
  }),
281
356
  );
357
+ expect(vm.salutation).toEqual({ id: "test", name: "test" });
358
+ expect(result).toEqual(salutationData);
359
+ });
282
360
 
361
+ it("loadSalutation with empty elements sets salutation to null", async () => {
362
+ const { vm, injections } = useSetup(() => useUser());
283
363
  injections.apiClient.invoke.mockResolvedValue({
284
- data: { elements: [{ id: "test", name: "test" }] },
364
+ data: { elements: [] },
285
365
  });
286
- await vm.loadSalutation("test");
287
366
 
288
- expect(vm.salutation).toEqual({ id: "test", name: "test" });
367
+ await vm.loadSalutation("non-existent");
368
+
369
+ expect(vm.salutation).toBeNull();
370
+ });
371
+
372
+ it("userDefaultPaymentMethod - should fallback to legacy defaultPaymentMethod when lastPaymentMethod is not available", () => {
373
+ const { vm } = useSetup(() => useUser());
374
+
375
+ // Mock the sessionContext to return a user with only legacy defaultPaymentMethod
376
+ const mockUser = {
377
+ // No lastPaymentMethod property (undefined)
378
+ defaultPaymentMethod: {
379
+ translated: { name: "Legacy Payment Method" },
380
+ },
381
+ };
382
+
383
+ // Set the userFromContext ref that the composable uses
384
+ userFromContextRef.value = mockUser;
385
+
386
+ expect(vm.userDefaultPaymentMethod).toEqual({
387
+ name: "Legacy Payment Method",
388
+ });
389
+
390
+ // Clean up
391
+ userFromContextRef.value = undefined;
392
+ });
393
+
394
+ it("isLoggedIn - false when user has id but active is false", () => {
395
+ const { vm } = useSetup(() => useUser());
396
+ userFromContextRef.value = {
397
+ id: "user-1",
398
+ active: false,
399
+ guest: false,
400
+ };
401
+
402
+ expect(vm.isLoggedIn).toBe(false);
403
+
404
+ userFromContextRef.value = undefined;
405
+ });
406
+
407
+ it("userDefaultPaymentMethod - should return null when no payment methods are available", () => {
408
+ const { vm } = useSetup(() => useUser());
409
+
410
+ // Mock user with no payment methods at all
411
+ const mockUser = {
412
+ // No lastPaymentMethod and no defaultPaymentMethod
413
+ };
414
+
415
+ userFromContextRef.value = mockUser;
416
+
417
+ expect(vm.userDefaultPaymentMethod).toBeNull();
418
+
419
+ // Clean up
420
+ userFromContextRef.value = undefined;
421
+ });
422
+
423
+ it("register function with inactive user", async () => {
424
+ const { vm, injections } = useSetup(() => useUser());
425
+ injections.apiClient.invoke.mockResolvedValue({
426
+ data: { active: false, id: "inactive-1" },
427
+ });
428
+ const result = await vm.register(REGISTRATION_DATA);
429
+ expect(result).toEqual({ active: false, id: "inactive-1" });
430
+ expect(vm.isLoggedIn).toBe(false);
431
+ });
432
+
433
+ it("loadCountry with empty elements", async () => {
434
+ const { vm, injections } = useSetup(() => useUser());
435
+ injections.apiClient.invoke.mockResolvedValue({
436
+ data: { elements: [] },
437
+ });
438
+ await vm.loadCountry("non-existent");
439
+ expect(vm.country).toBeNull();
440
+ });
441
+
442
+ it("isCustomerSession and isGuestSession", () => {
443
+ const { vm } = useSetup(() => useUser());
444
+ userFromContextRef.value = { id: "cust-1", active: true, guest: false };
445
+ expect(vm.isCustomerSession).toBe(true);
446
+ expect(vm.isGuestSession).toBe(false);
447
+
448
+ userFromContextRef.value = { id: "guest-1", active: true, guest: true };
449
+ expect(vm.isCustomerSession).toBe(false);
450
+ expect(vm.isGuestSession).toBe(true);
451
+ });
452
+
453
+ it("userDefaultBillingAddress and userDefaultShippingAddress", () => {
454
+ const { vm } = useSetup(() => useUser());
455
+
456
+ expect(vm.userDefaultBillingAddress).toBeNull();
457
+ expect(vm.userDefaultShippingAddress).toBeNull();
458
+
459
+ userFromContextRef.value = {
460
+ id: "cust-1",
461
+ defaultBillingAddress: { city: "Berlin" },
462
+ defaultShippingAddress: { city: "Munich" },
463
+ };
464
+ expect(vm.userDefaultBillingAddress).toStrictEqual({ city: "Berlin" });
465
+ expect(vm.userDefaultShippingAddress).toStrictEqual({ city: "Munich" });
466
+ });
467
+
468
+ it("defaultBillingAddressId and defaultShippingAddressId", () => {
469
+ const { vm } = useSetup(() => useUser());
470
+
471
+ expect(vm.defaultBillingAddressId).toBeNull();
472
+ expect(vm.defaultShippingAddressId).toBeNull();
473
+
474
+ userFromContextRef.value = {
475
+ id: "cust-1",
476
+ defaultBillingAddressId: "billing-1",
477
+ defaultShippingAddressId: "shipping-1",
478
+ };
479
+ expect(vm.defaultBillingAddressId).toBe("billing-1");
480
+ expect(vm.defaultShippingAddressId).toBe("shipping-1");
481
+ });
482
+
483
+ it("userDefaultPaymentMethod - should fallback when lastPaymentMethod.translated is falsy", () => {
484
+ const { vm } = useSetup(() => useUser());
485
+
486
+ // Mock user with falsy lastPaymentMethod.translated but valid defaultPaymentMethod
487
+ const mockUser = {
488
+ lastPaymentMethod: {
489
+ translated: null, // falsy translated
490
+ },
491
+ defaultPaymentMethod: {
492
+ translated: { name: "Fallback Payment Method" },
493
+ },
494
+ };
495
+
496
+ userFromContextRef.value = mockUser;
497
+
498
+ expect(vm.userDefaultPaymentMethod).toEqual({
499
+ name: "Fallback Payment Method",
500
+ });
501
+
502
+ // Clean up
503
+ userFromContextRef.value = undefined;
289
504
  });
290
505
  });
@@ -141,7 +141,11 @@ export function useUser(): UseUserReturn {
141
141
  const { refreshCart } = useCart();
142
142
 
143
143
  const userDefaultPaymentMethod = computed(
144
- () => user.value?.defaultPaymentMethod?.translated || null,
144
+ () =>
145
+ user.value?.lastPaymentMethod?.translated ||
146
+ // @ts-expect-error TODO: [MAJOR] Removed since 6.7
147
+ user.value?.defaultPaymentMethod?.translated ||
148
+ null,
145
149
  );
146
150
  const userDefaultBillingAddress = computed(
147
151
  () => user.value?.defaultBillingAddress || null,
@@ -277,6 +281,7 @@ export function useUser(): UseUserReturn {
277
281
  paymentMethodId: string,
278
282
  ): Promise<void> {
279
283
  await apiClient.invoke(
284
+ // @ts-expect-error TODO: [MAJOR] Removed since 6.7
280
285
  "changePaymentMethod post /account/change-payment-method/{paymentMethodId}",
281
286
  {
282
287
  pathParams: { paymentMethodId },