@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
@@ -2,7 +2,7 @@ import { defu } from "defu";
2
2
  import { computed, inject, provide, ref } from "vue";
3
3
  import type { ComputedRef, Ref } from "vue";
4
4
  import { useDefaultOrderAssociations, useShopwareContext } from "#imports";
5
- import type { Schemas } from "#shopware";
5
+ import type { Schemas, operations } from "#shopware";
6
6
 
7
7
  export type UseOrderDetailsReturn = {
8
8
  /**
@@ -97,12 +97,12 @@ export type UseOrderDetailsReturn = {
97
97
  * Get order documents
98
98
  * @param {string} documentId
99
99
  * @param {string} deepLinkCode
100
- * @returns
100
+ * @returns Binary document content (PDF, HTML, or XML)
101
101
  */
102
102
  getDocumentFile: (
103
103
  documentId: string,
104
104
  deepLinkCode: string,
105
- ) => Promise<Schemas["Document"]>;
105
+ ) => Promise<Blob | string>;
106
106
  /**
107
107
  * Check if order has documents
108
108
  */
@@ -182,17 +182,11 @@ export function useOrderDetails(
182
182
  orderAssociations,
183
183
  associations ? associations : {},
184
184
  );
185
- const params = {
186
- filter: [
187
- {
188
- type: "equals",
189
- field: "id",
190
- value: orderId,
191
- },
192
- ],
193
- associations: mergedAssociations.associations,
185
+ const params: operations["readOrder post /order"]["body"] = {
186
+ ids: [orderId],
187
+ associations: mergedAssociations,
194
188
  checkPromotion: true,
195
- } as Schemas["Criteria"];
189
+ };
196
190
 
197
191
  const orderDetailsResponse = await apiClient.invoke(
198
192
  "readOrder post /order",
@@ -264,7 +258,10 @@ export function useOrderDetails(
264
258
  return response.data;
265
259
  }
266
260
 
267
- async function getDocumentFile(documentId: string, deepLinkCode: string) {
261
+ async function getDocumentFile(
262
+ documentId: string,
263
+ deepLinkCode: string,
264
+ ): Promise<Blob | string> {
268
265
  const response = await apiClient.invoke(
269
266
  "download post /document/download/{documentId}/{deepLinkCode}",
270
267
  {
@@ -272,6 +269,7 @@ export function useOrderDetails(
272
269
  documentId,
273
270
  deepLinkCode,
274
271
  },
272
+ accept: "application/pdf",
275
273
  },
276
274
  );
277
275
 
@@ -32,6 +32,8 @@ describe("useOrderPayment", () => {
32
32
  expect(vm.activeTransaction).toEqual(
33
33
  Order.orders.elements?.[0]?.transactions[0],
34
34
  );
35
+ expect(vm.paymentMethod).toBeDefined();
36
+ expect(vm.state).toBeDefined();
35
37
 
36
38
  vm.changePaymentMethod("test");
37
39
 
@@ -47,13 +49,45 @@ describe("useOrderPayment", () => {
47
49
  });
48
50
 
49
51
  it("should not invoke API calls for empty order", async () => {
50
- const { vm } = useSetup(() =>
52
+ const { vm, injections } = useSetup(() =>
51
53
  useOrderPayment(
52
54
  computed(() => null) as unknown as ComputedRef<Schemas["Order"]>,
53
55
  ),
54
56
  );
55
57
  await expect(vm.changePaymentMethod("test")).resolves.toBeUndefined();
56
58
  await expect(vm.handlePayment()).resolves.toBeUndefined();
59
+ expect(injections.apiClient.invoke).not.toHaveBeenCalled();
60
+ });
61
+
62
+ it("handlePayment returns response", async () => {
63
+ const { vm, injections } = useSetup(() =>
64
+ useOrderPayment(
65
+ computed(() => Order.orders.elements?.[0]) as unknown as ComputedRef<
66
+ Schemas["Order"]
67
+ >,
68
+ ),
69
+ );
70
+ const response = { data: { redirectUrl: "https://pay.example.com" } };
71
+ injections.apiClient.invoke.mockResolvedValue(response);
72
+ const result = await vm.handlePayment();
73
+
74
+ expect(result).toEqual(response);
75
+ expect(vm.paymentUrl).toBe("https://pay.example.com");
76
+ });
77
+
78
+ it("changePaymentMethod returns response data", async () => {
79
+ const { vm, injections } = useSetup(() =>
80
+ useOrderPayment(
81
+ computed(() => Order.orders.elements?.[0]) as unknown as ComputedRef<
82
+ Schemas["Order"]
83
+ >,
84
+ ),
85
+ );
86
+ const responseData = { success: true };
87
+ injections.apiClient.invoke.mockResolvedValue({ data: responseData });
88
+ const result = await vm.changePaymentMethod("new-method-id");
89
+
90
+ expect(result).toEqual(responseData);
57
91
  });
58
92
 
59
93
  it("should be a asynchronous payment", () => {
@@ -76,4 +110,24 @@ describe("useOrderPayment", () => {
76
110
 
77
111
  expect(vm.isAsynchronous).toBe(true);
78
112
  });
113
+
114
+ it("should be synchronous when afterOrderEnabled is false", () => {
115
+ const { vm } = useSetup(() =>
116
+ useOrderPayment(
117
+ computed(() => ({
118
+ transactions: [
119
+ {
120
+ paymentMethod: {
121
+ active: true,
122
+ asynchronous: true,
123
+ afterOrderEnabled: false,
124
+ },
125
+ },
126
+ ],
127
+ })) as unknown as ComputedRef<Schemas["Order"]>,
128
+ ),
129
+ );
130
+
131
+ expect(vm.isAsynchronous).toBeFalsy();
132
+ });
79
133
  });
@@ -64,6 +64,7 @@ export function useOrderPayment(
64
64
  const state = computed(() => activeTransaction.value?.stateMachineState);
65
65
  const isAsynchronous = computed(
66
66
  () =>
67
+ // @ts-expect-error TODO: [MAJOR] Removed since 6.7
67
68
  activeTransaction.value?.paymentMethod?.asynchronous &&
68
69
  activeTransaction.value?.paymentMethod?.afterOrderEnabled,
69
70
  );
@@ -65,6 +65,16 @@ describe("usePrice", () => {
65
65
  expect(vm.getFormattedPrice("2")).toBe("$2.00");
66
66
  });
67
67
 
68
+ it("should init price object with params and undefined localeCode", () => {
69
+ const { vm } = useSetup(() =>
70
+ usePrice({
71
+ currencyCode: "EUR",
72
+ }),
73
+ );
74
+
75
+ expect(vm.currencyCode).toBe("EUR");
76
+ });
77
+
68
78
  it("should update config", async () => {
69
79
  const { vm } = useSetup(usePrice);
70
80
 
@@ -38,13 +38,8 @@ function _usePrice(params?: {
38
38
  }): UsePriceReturn {
39
39
  const { sessionContext } = useSessionContext();
40
40
  const { browserLocale } = useShopwareContext();
41
- const currencyLocale = ref<string>(browserLocale);
42
- const currencyCode = ref<string>("");
43
-
44
- if (params) {
45
- currencyCode.value = params.currencyCode;
46
- _setLocaleCode(params.localeCode);
47
- }
41
+ const currencyCode = ref<string>(params?.currencyCode ?? "");
42
+ const currencyLocale = ref<string>(params?.localeCode || browserLocale);
48
43
 
49
44
  function update(params: {
50
45
  localeCode?: string | undefined;
@@ -1,6 +1,8 @@
1
1
  import { describe, expect, it } from "vitest";
2
2
  import { ref } from "vue";
3
+ import type { Schemas } from "#shopware";
3
4
  import { useSetup } from "../_test";
5
+ import mockedConfigurator from "../mocks/Configurator";
4
6
  import mockedProduct from "../mocks/Product";
5
7
  import { useProduct } from "./useProduct";
6
8
 
@@ -11,13 +13,24 @@ describe("useProduct", () => {
11
13
  expect(vm.product).toStrictEqual(mockedProduct);
12
14
  });
13
15
 
16
+ it("should return configurator when provided", () => {
17
+ const { vm } = useSetup(() =>
18
+ useProduct(
19
+ mockedProduct,
20
+ mockedConfigurator as unknown as Schemas["PropertyGroup"][],
21
+ ),
22
+ );
23
+
24
+ expect(vm.configurator).toStrictEqual(mockedConfigurator);
25
+ });
26
+
14
27
  it("changeVariant - should merge the current product with the new variant data", () => {
15
28
  const { vm } = useSetup(() => useProduct(mockedProduct));
16
29
  expect(vm.changeVariant()).toBeUndefined();
17
30
  });
18
31
 
19
32
  it("changeVariant - empty", () => {
20
- const { vm } = useSetup(useProduct);
33
+ const { vm } = useSetup(() => useProduct(mockedProduct));
21
34
 
22
35
  vm.changeVariant(Object.assign({ ...mockedProduct }, { id: "new-id" }));
23
36
  expect(vm.product.id).toBe("new-id");
@@ -19,6 +19,7 @@ describe("useProductAssociations", () => {
19
19
  );
20
20
 
21
21
  expect(vm.productAssociations).toStrictEqual([]);
22
+ expect(vm.isLoading).toBe(false);
22
23
  });
23
24
 
24
25
  it("load productAssociations - GET - Error", async () => {
@@ -74,4 +74,42 @@ describe("useProductConfigurator", () => {
74
74
  expect(vm.isLoadingOptions).toBe(true);
75
75
  expect(vm.getOptionGroups).toStrictEqual([]);
76
76
  });
77
+
78
+ it("getSelectedOptions returns selected options", () => {
79
+ vi.mocked(useProduct).mockReturnValue({
80
+ configurator: ref(mockedConfigurator),
81
+ product: ref(mockedProduct),
82
+ } as unknown as ReturnType<typeof useProduct>);
83
+ const { vm } = useSetup(useProductConfigurator);
84
+
85
+ expect(vm.getSelectedOptions).toEqual({
86
+ Colour: "cc02c6cf39ad43d5856a25f8928490bf",
87
+ });
88
+ });
89
+
90
+ it("handleChange without callback", async () => {
91
+ vi.mocked(useProduct).mockReturnValue({
92
+ configurator: ref(mockedConfigurator),
93
+ product: ref(mockedProduct),
94
+ } as unknown as ReturnType<typeof useProduct>);
95
+ const { vm } = useSetup(useProductConfigurator);
96
+
97
+ await vm.handleChange("test-group", "test-option");
98
+ expect(vm.getSelectedOptions).toMatchObject({
99
+ "test-group": "test-option",
100
+ });
101
+ });
102
+
103
+ it("getSelectedOptions skips optionIds not in configurator", () => {
104
+ vi.mocked(useProduct).mockReturnValue({
105
+ configurator: ref(mockedConfigurator),
106
+ product: ref({
107
+ ...mockedProduct,
108
+ optionIds: ["non-existent-option-id"],
109
+ }),
110
+ } as unknown as ReturnType<typeof useProduct>);
111
+ const { vm } = useSetup(useProductConfigurator);
112
+
113
+ expect(vm.getSelectedOptions).toEqual({});
114
+ });
77
115
  });
@@ -11,7 +11,7 @@ export type UseProductConfiguratorReturn = {
11
11
  handleChange(
12
12
  attribute: string,
13
13
  option: string,
14
- onChangeHandled: () => void,
14
+ onChangeHandled?: () => void,
15
15
  ): Promise<void>;
16
16
 
17
17
  findVariantForSelectedOptions(options?: {
@@ -22,7 +22,7 @@ describe("useProductPrice", () => {
22
22
  expect(vm.referencePrice).toStrictEqual(
23
23
  mockedProduct.calculatedPrice?.referencePrice,
24
24
  );
25
- expect(vm.isListPrice).toBe(false);
25
+ expect(vm.hasListPrice).toBe(false);
26
26
  expect(vm.regulationPrice).toBe(80);
27
27
  });
28
28
 
@@ -60,10 +60,10 @@ describe("useProductPrice", () => {
60
60
  ),
61
61
  );
62
62
  expect(vm.displayFrom).toBe(false);
63
- expect(vm.isListPrice).toBe(false);
63
+ expect(vm.hasListPrice).toBe(false);
64
64
  });
65
65
 
66
- it("isListPrice should be false with more than one calculatedPrices value", () => {
66
+ it("hasListPrice should be false with more than one calculatedPrices value", () => {
67
67
  const { vm } = useSetup(() =>
68
68
  useProductPrice(
69
69
  ref(
@@ -85,10 +85,10 @@ describe("useProductPrice", () => {
85
85
  ),
86
86
  );
87
87
  expect(vm.displayFrom).toBe(true);
88
- expect(vm.isListPrice).toBe(false);
88
+ expect(vm.hasListPrice).toBe(false);
89
89
  });
90
90
 
91
- it("isListPrice should be true with one calculatedPrices value", () => {
91
+ it("hasListPrice should be true with one calculatedPrices value", () => {
92
92
  const { vm } = useSetup(() =>
93
93
  useProductPrice(
94
94
  ref({
@@ -103,7 +103,7 @@ describe("useProductPrice", () => {
103
103
  ),
104
104
  );
105
105
  expect(vm.displayFrom).toBe(false);
106
- expect(vm.isListPrice).toBe(true);
106
+ expect(vm.hasListPrice).toBe(true);
107
107
  });
108
108
 
109
109
  it("displayFrom - second variant", async () => {
@@ -121,6 +121,6 @@ describe("useProductPrice", () => {
121
121
  ),
122
122
  );
123
123
  expect(vm.displayFrom).toBe(false);
124
- expect(vm.isListPrice).toBe(false);
124
+ expect(vm.hasListPrice).toBe(false);
125
125
  });
126
126
  });
@@ -18,7 +18,7 @@ export type UseProductPriceReturn = {
18
18
  */
19
19
  unitPrice: ComputedRef<number | undefined>;
20
20
  /**
21
- * Can be used if isListPrice is set to true
21
+ * Can be used if hasListPrice is set to true
22
22
  */
23
23
  referencePrice: ComputedRef<
24
24
  Schemas["CalculatedPrice"]["referencePrice"] | undefined
@@ -36,7 +36,13 @@ export type UseProductPriceReturn = {
36
36
  */
37
37
  tierPrices: ComputedRef<TierPrice[]>;
38
38
  /**
39
- * determines whether a discount price is set
39
+ * Whether the product currently has a list price reduction / discount
40
+ * (e.g. for strikethrough / discount display, typically based on `listPrice.percentage`).
41
+ */
42
+ hasListPrice: ComputedRef<boolean>;
43
+ /**
44
+ * Whether the product currently has a list price reduction / discount.
45
+ * @deprecated Use `hasListPrice` instead. Will be removed in a future version.
40
46
  */
41
47
  isListPrice: ComputedRef<boolean>;
42
48
  /**
@@ -107,7 +113,7 @@ export function useProductPrice(
107
113
  () => _price.value,
108
114
  );
109
115
 
110
- const isListPrice: ComputedRef<boolean> = computed(() => {
116
+ const hasListPrice: ComputedRef<boolean> = computed(() => {
111
117
  return !!_price.value?.listPrice?.percentage;
112
118
  });
113
119
 
@@ -125,7 +131,9 @@ export function useProductPrice(
125
131
  displayFrom,
126
132
  tierPrices,
127
133
  referencePrice,
128
- isListPrice,
134
+ hasListPrice,
135
+ /** @deprecated Use hasListPrice instead */
136
+ isListPrice: hasListPrice,
129
137
  regulationPrice,
130
138
  };
131
139
  }
@@ -6,19 +6,31 @@ import { useProductReviews } from "./useProductReviews";
6
6
 
7
7
  describe("useProductReviews", () => {
8
8
  it("load product reviews", async () => {
9
- const { vm, injections } = await useSetup(() =>
9
+ const { vm, injections } = useSetup(() =>
10
10
  useProductReviews(ref(ProductMock)),
11
11
  );
12
- injections.apiClient.invoke.mockResolvedValue({ data: {} });
12
+ injections.apiClient.invoke.mockResolvedValue({
13
+ data: { elements: [{ id: "1", content: "Great!" }] },
14
+ });
13
15
  await vm.loadProductReviews();
14
16
  expect(injections.apiClient.invoke).toHaveBeenCalledWith(
15
17
  expect.stringContaining("readProductReviews"),
16
18
  expect.objectContaining({}),
17
19
  );
20
+ expect(vm.productReviews).toEqual([{ id: "1", content: "Great!" }]);
21
+ });
22
+
23
+ it("load product reviews with empty elements", async () => {
24
+ const { vm, injections } = useSetup(() =>
25
+ useProductReviews(ref(ProductMock)),
26
+ );
27
+ injections.apiClient.invoke.mockResolvedValue({ data: {} });
28
+ await vm.loadProductReviews();
29
+ expect(vm.productReviews).toEqual([]);
18
30
  });
19
31
 
20
32
  it("add product review", async () => {
21
- const { vm, injections } = await useSetup(() =>
33
+ const { vm, injections } = useSetup(() =>
22
34
  useProductReviews(ref(ProductMock)),
23
35
  );
24
36
 
@@ -1,5 +1,5 @@
1
1
  import { computed } from "vue";
2
- import type { Ref } from "vue";
2
+ import type { ComputedRef } from "vue";
3
3
  import { useLocalWishlist, useSyncWishlist, useUser } from "#imports";
4
4
 
5
5
  export type UseProductWishlistReturn = {
@@ -14,7 +14,7 @@ export type UseProductWishlistReturn = {
14
14
  /**
15
15
  * Indicates whether a product is in wishlist
16
16
  */
17
- isInWishlist: Ref<boolean>;
17
+ isInWishlist: ComputedRef<boolean>;
18
18
  };
19
19
 
20
20
  /**
@@ -1,5 +1,6 @@
1
1
  import { flushPromises } from "@vue/test-utils";
2
2
  import { describe, expect, it, vi } from "vitest";
3
+ import { ref } from "vue";
3
4
  import { useSetup } from "../_test";
4
5
  import Salutations from "../mocks/Salutations";
5
6
  import { useSalutations } from "./useSalutations";
@@ -34,4 +35,16 @@ describe("useSalutations", () => {
34
35
 
35
36
  expect(vm.getSalutations).toStrictEqual([]);
36
37
  });
38
+
39
+ it("should not fetch when swSalutations already populated", async () => {
40
+ const preloadedSalutations = ref(Salutations);
41
+ const { vm, injections } = useSetup(useSalutations, {
42
+ apiClient: { invoke: vi.fn() },
43
+ swSalutations: preloadedSalutations,
44
+ } as Parameters<typeof useSetup>[1]);
45
+ await flushPromises();
46
+
47
+ expect(injections.apiClient.invoke).not.toHaveBeenCalled();
48
+ expect(vm.getSalutations).toStrictEqual(Salutations);
49
+ });
37
50
  });
@@ -70,7 +70,7 @@ describe("useSessionContext", () => {
70
70
  it("setShippingMethod", async () => {
71
71
  const { vm, injections } = useSetup(() => useSessionContext());
72
72
  injections.apiClient.invoke.mockResolvedValue({ data: {} });
73
- vm.setShippingMethod({ id: "test" });
73
+ await vm.setShippingMethod({ id: "test" });
74
74
  expect(injections.apiClient.invoke).toHaveBeenCalledWith(
75
75
  expect.stringContaining("updateContext"),
76
76
  expect.objectContaining({
@@ -90,10 +90,19 @@ describe("useSessionContext", () => {
90
90
  );
91
91
  });
92
92
 
93
+ it("setShippingMethod - error without id", async () => {
94
+ const { vm } = useSetup(() => useSessionContext());
95
+ await expect(
96
+ vm.setShippingMethod({} as { id: string }),
97
+ ).rejects.toThrowError(
98
+ "You need to provide shipping method id in order to set shipping method.",
99
+ );
100
+ });
101
+
93
102
  it("setPaymentMethod", async () => {
94
103
  const { vm, injections } = useSetup(() => useSessionContext());
95
104
  injections.apiClient.invoke.mockResolvedValue({ data: {} });
96
- vm.setPaymentMethod({ id: "test" });
105
+ await vm.setPaymentMethod({ id: "test" });
97
106
  expect(injections.apiClient.invoke).toHaveBeenCalledWith(
98
107
  expect.stringContaining("updateContext"),
99
108
  expect.objectContaining({
@@ -113,6 +122,15 @@ describe("useSessionContext", () => {
113
122
  );
114
123
  });
115
124
 
125
+ it("setPaymentMethod - error without id", async () => {
126
+ const { vm } = useSetup(() => useSessionContext());
127
+ await expect(
128
+ vm.setPaymentMethod({} as { id: string }),
129
+ ).rejects.toThrowError(
130
+ "You need to provide payment method id in order to set payment method.",
131
+ );
132
+ });
133
+
116
134
  it("setCurrency", async () => {
117
135
  const { vm, injections } = useSetup(() => useSessionContext());
118
136
  injections.apiClient.invoke.mockResolvedValue({ data: {} });
@@ -134,10 +152,19 @@ describe("useSessionContext", () => {
134
152
  expect(consoleErrorSpy).toHaveBeenCalled();
135
153
  });
136
154
 
155
+ it("setCurrency - undefined id", async () => {
156
+ const { vm, injections } = useSetup(() => useSessionContext());
157
+ await vm.setCurrency({ id: undefined } as unknown as { id: string });
158
+ expect(consoleErrorSpy).toHaveBeenCalled();
159
+ expect(injections.apiClient.invoke).not.toHaveBeenCalledWith(
160
+ expect.stringContaining("updateContext"),
161
+ );
162
+ });
163
+
137
164
  it("setActiveShippingAddress", async () => {
138
165
  const { vm, injections } = useSetup(() => useSessionContext());
139
166
  injections.apiClient.invoke.mockResolvedValue({ data: {} });
140
- vm.setActiveShippingAddress({ id: "test" });
167
+ await vm.setActiveShippingAddress({ id: "test" });
141
168
  expect(injections.apiClient.invoke).toHaveBeenCalledWith(
142
169
  expect.stringContaining("updateContext"),
143
170
  expect.objectContaining({
@@ -156,10 +183,17 @@ describe("useSessionContext", () => {
156
183
  );
157
184
  });
158
185
 
186
+ it("setActiveShippingAddress - error without id", async () => {
187
+ const { vm } = useSetup(() => useSessionContext());
188
+ await expect(vm.setActiveShippingAddress({})).rejects.toThrowError(
189
+ "You need to provide address id in order to set the address.",
190
+ );
191
+ });
192
+
159
193
  it("setActiveBillingAddress", async () => {
160
194
  const { vm, injections } = useSetup(() => useSessionContext());
161
195
  injections.apiClient.invoke.mockResolvedValue({ data: {} });
162
- vm.setActiveBillingAddress({ id: "test" });
196
+ await vm.setActiveBillingAddress({ id: "test" });
163
197
  expect(injections.apiClient.invoke).toHaveBeenCalledWith(
164
198
  expect.stringContaining("updateContext"),
165
199
  expect.objectContaining({
@@ -178,6 +212,13 @@ describe("useSessionContext", () => {
178
212
  );
179
213
  });
180
214
 
215
+ it("setActiveBillingAddress - error without id", async () => {
216
+ const { vm } = useSetup(() => useSessionContext());
217
+ await expect(vm.setActiveBillingAddress({})).rejects.toThrowError(
218
+ "You need to provide address id in order to set the address.",
219
+ );
220
+ });
221
+
181
222
  it("setContext", () => {
182
223
  const { vm } = useSetup(() => useSessionContext());
183
224
  vm.setContext({
@@ -218,4 +259,81 @@ describe("useSessionContext", () => {
218
259
  city: "test",
219
260
  });
220
261
  });
262
+
263
+ it("countryId, salesChannelCountryId, languageId, languageIdChain, taxState", () => {
264
+ const { vm } = useSetup(() => useSessionContext());
265
+ vm.setContext({
266
+ shippingLocation: {
267
+ country: { id: "country-1" },
268
+ },
269
+ salesChannel: { countryId: "sales-country-1", languageId: "lang-1" },
270
+ context: { languageIdChain: ["chain-1"], taxState: "net" },
271
+ } as unknown as Schemas["SalesChannelContext"]);
272
+
273
+ expect(vm.countryId).toBe("country-1");
274
+ expect(vm.salesChannelCountryId).toBe("sales-country-1");
275
+ expect(vm.languageId).toBe("lang-1");
276
+ expect(vm.languageIdChain).toBe("chain-1");
277
+ expect(vm.taxState).toBe("net");
278
+ });
279
+
280
+ it("languageIdChain - empty when no chain", () => {
281
+ const { vm } = useSetup(() => useSessionContext());
282
+ vm.setContext({
283
+ context: {},
284
+ } as unknown as Schemas["SalesChannelContext"]);
285
+
286
+ expect(vm.languageIdChain).toBe("");
287
+ });
288
+
289
+ it("setLanguage - undefined id", () => {
290
+ const { vm, injections } = useSetup(() => useSessionContext());
291
+ vm.setLanguage({ id: undefined } as unknown as { id: string });
292
+ expect(injections.apiClient.invoke).not.toHaveBeenCalledWith(
293
+ expect.stringContaining("updateContext"),
294
+ );
295
+ });
296
+
297
+ it("selectedShippingMethod, selectedPaymentMethod, currency, activeBillingAddress, userFromContext", () => {
298
+ const { vm } = useSetup(() => useSessionContext());
299
+
300
+ expect(vm.selectedShippingMethod).toBeNull();
301
+ expect(vm.selectedPaymentMethod).toBeNull();
302
+ expect(vm.currency).toBeNull();
303
+ expect(vm.activeBillingAddress).toBeNull();
304
+ expect(vm.userFromContext).toBeUndefined();
305
+
306
+ vm.setContext({
307
+ shippingMethod: { id: "ship-1", name: "Standard" },
308
+ paymentMethod: { id: "pay-1", name: "Invoice" },
309
+ currency: { id: "curr-1", isoCode: "EUR" },
310
+ customer: {
311
+ activeBillingAddress: { city: "Berlin" },
312
+ id: "cust-1",
313
+ },
314
+ } as unknown as Schemas["SalesChannelContext"]);
315
+
316
+ expect(vm.selectedShippingMethod).toStrictEqual({
317
+ id: "ship-1",
318
+ name: "Standard",
319
+ });
320
+ expect(vm.selectedPaymentMethod).toStrictEqual({
321
+ id: "pay-1",
322
+ name: "Invoice",
323
+ });
324
+ expect(vm.currency).toStrictEqual({ id: "curr-1", isoCode: "EUR" });
325
+ expect(vm.activeBillingAddress).toStrictEqual({ city: "Berlin" });
326
+ expect(vm.userFromContext).toStrictEqual({
327
+ activeBillingAddress: { city: "Berlin" },
328
+ id: "cust-1",
329
+ });
330
+ });
331
+
332
+ it("useSessionContext with initial context", () => {
333
+ const initialContext = {
334
+ shippingLocation: { country: { id: "initial-country" } },
335
+ } as unknown as Schemas["SalesChannelContext"];
336
+ const { vm } = useSetup(() => useSessionContext(initialContext));
337
+ expect(vm.countryId).toBe("initial-country");
338
+ });
221
339
  });
@@ -86,17 +86,27 @@ export type UseSessionContextReturn = {
86
86
  */
87
87
  salesChannelCountryId: ComputedRef<string | undefined>;
88
88
  /**
89
- * current language id
89
+ * @deprecated use salesChannelLanguageId instead
90
+ * sales channel language id
90
91
  */
91
92
  languageId: ComputedRef<string | undefined>;
92
93
  /**
94
+ * sales channel language code
95
+ */
96
+ salesChannelLanguageId: ComputedRef<string | undefined>;
97
+ /**
98
+ * @deprecated use currentLanguageId instead
93
99
  * current language id chain
94
100
  */
95
101
  languageIdChain: ComputedRef<string>;
102
+ /**
103
+ * current language code
104
+ */
105
+ currentLanguageId: ComputedRef<string | undefined>;
96
106
  /**
97
107
  * current context's customer object
98
108
  */
99
- userFromContext: ComputedRef<Schemas["Customer"] | undefined>;
109
+ userFromContext: ComputedRef<Schemas["Customer"] | undefined | null>;
100
110
  };
101
111
 
102
112
  /**
@@ -275,6 +285,8 @@ export function useSessionContext(
275
285
  setLanguage,
276
286
  languageId,
277
287
  languageIdChain,
288
+ salesChannelLanguageId: languageId,
289
+ currentLanguageId: languageIdChain,
278
290
  setCountry,
279
291
  setContext,
280
292
  };