@shopware/composables 1.8.1 → 1.9.1

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.
@@ -45,6 +45,15 @@ export type CmsElementText = Schemas["CmsSlot"] & {
45
45
  };
46
46
  };
47
47
 
48
+ // HTML
49
+ export type CmsElementHtml = Schemas["CmsSlot"] & {
50
+ type: "html";
51
+ data: {
52
+ content: string;
53
+ apiAlias: "cms_html";
54
+ };
55
+ };
56
+
48
57
  // Image
49
58
 
50
59
  type ImageElementConfig = {
@@ -150,7 +159,7 @@ type YouTubeVideoElementConfig = {
150
159
  previewMedia: ElementConfig<string>;
151
160
  showControls: ElementConfig<boolean>;
152
161
  needsConfirmation: ElementConfig<boolean>;
153
- advancePrivacyMode: ElementConfig<boolean>;
162
+ advancedPrivacyMode: ElementConfig<boolean>;
154
163
  };
155
164
  export type CmsElementYoutubeVideo = Schemas["CmsSlot"] & {
156
165
  type: "youtube-video";
@@ -52,7 +52,7 @@ describe("useBreadcrumbs", () => {
52
52
  { path: "test" } as Schemas["Breadcrumb"],
53
53
  ]);
54
54
 
55
- expect(vm.breadcrumbs[0].path).toBe("/test");
55
+ expect(vm.breadcrumbs[0]?.path).toBe("/test");
56
56
  });
57
57
 
58
58
  it("should push breadcrumb", async () => {
@@ -43,8 +43,8 @@ describe("useCart", () => {
43
43
  expect(vm.totalPrice).toBe(0);
44
44
  expect(vm.subtotal).toBe(0);
45
45
  await vm.addProduct({
46
- id: itemsMock.items[0].referencedId as string,
47
- quantity: itemsMock.items[0].quantity,
46
+ id: itemsMock.items[0]?.referencedId as string,
47
+ quantity: itemsMock.items[0]?.quantity,
48
48
  });
49
49
 
50
50
  expect(injections.apiClient.invoke).toHaveBeenCalledWith(
@@ -53,9 +53,9 @@ describe("useCart", () => {
53
53
  body: {
54
54
  items: [
55
55
  {
56
- type: itemsMock.items[0].type,
57
- id: itemsMock.items[0].referencedId,
58
- quantity: itemsMock.items[0].quantity,
56
+ type: itemsMock.items[0]?.type,
57
+ id: itemsMock.items[0]?.referencedId,
58
+ quantity: itemsMock.items[0]?.quantity,
59
59
  },
60
60
  ],
61
61
  },
@@ -63,7 +63,7 @@ describe("useCart", () => {
63
63
  );
64
64
 
65
65
  await vm.addProduct({
66
- id: itemsMock.items[0].referencedId as string,
66
+ id: itemsMock.items[0]?.referencedId as string,
67
67
  });
68
68
 
69
69
  expect(injections.apiClient.invoke).toHaveBeenCalledWith(
@@ -72,8 +72,8 @@ describe("useCart", () => {
72
72
  body: {
73
73
  items: [
74
74
  {
75
- type: itemsMock.items[0].type,
76
- id: itemsMock.items[0].referencedId,
75
+ type: itemsMock.items[0]?.type,
76
+ id: itemsMock.items[0]?.referencedId,
77
77
  quantity: 0,
78
78
  },
79
79
  ],
@@ -112,7 +112,7 @@ describe("useCart", () => {
112
112
 
113
113
  it("change product quantity", async () => {
114
114
  await vm.changeProductQuantity({
115
- id: itemsMock.items[0].referencedId as string,
115
+ id: itemsMock.items[0]?.referencedId as string,
116
116
  quantity: 4,
117
117
  });
118
118
  expect(injections.apiClient.invoke).toHaveBeenCalledWith(
@@ -121,7 +121,7 @@ describe("useCart", () => {
121
121
  body: {
122
122
  items: [
123
123
  {
124
- id: itemsMock.items[0].referencedId,
124
+ id: itemsMock.items[0]?.referencedId,
125
125
  quantity: 4,
126
126
  },
127
127
  ],
@@ -35,7 +35,7 @@ describe("useCartItem", () => {
35
35
  expect(vm.isRemovable).toBe(true);
36
36
  expect(vm.isStackable).toBe(true);
37
37
  expect(vm.isDigital).toBe(false);
38
- expect(vm.itemImageThumbnailUrl).toBe(lineItem.cover?.url);
38
+ expect(vm.itemImageThumbnailUrl).toBe(lineItem?.cover?.url);
39
39
  expect(vm.itemType).toBe("product");
40
40
  expect(vm.itemQuantity).toBe(1);
41
41
  expect(vm.itemStock).toBe(49485);
@@ -112,7 +112,7 @@ describe("useCartItem", () => {
112
112
 
113
113
  expect(changeProductQuantitySpy).toHaveBeenCalledWith({
114
114
  quantity: 5,
115
- id: lineItem.id,
115
+ id: lineItem?.id,
116
116
  });
117
117
  expect(result).toEqual(mockedResponse);
118
118
 
@@ -120,7 +120,7 @@ describe("useCartItem", () => {
120
120
  vm.changeItemQuantity("6");
121
121
  expect(changeProductQuantitySpy).toHaveBeenCalledWith({
122
122
  quantity: 6,
123
- id: lineItem.id,
123
+ id: lineItem?.id,
124
124
  });
125
125
  });
126
126
 
@@ -28,10 +28,11 @@ export function useCartNotification(): useCartNotificationReturn {
28
28
  if (!errors || Array.isArray(errors)) return;
29
29
 
30
30
  for (const element of Object.keys(errors)) {
31
- if (successCodes.includes(errors[element].messageKey)) {
32
- pushSuccess(errors[element].message);
31
+ const error = errors[element] as Schemas["CartError"];
32
+ if (successCodes.includes(error.messageKey)) {
33
+ pushSuccess(error.message);
33
34
  } else {
34
- pushError(errors[element].message);
35
+ pushError(error.message);
35
36
  }
36
37
  }
37
38
  };
@@ -47,9 +48,8 @@ export function useCartNotification(): useCartNotificationReturn {
47
48
 
48
49
  return Object.keys(errors).reduce(
49
50
  (acc, element) => {
50
- if (!successCodes.includes(errors[element].messageKey))
51
- acc.push(errors[element] as Schemas["CartError"]);
52
-
51
+ const error = errors[element] as Schemas["CartError"];
52
+ if (!successCodes.includes(error.messageKey)) acc.push(error);
53
53
  return acc;
54
54
  },
55
55
  [] as Schemas["CartError"][],
@@ -6,13 +6,13 @@ import { useCmsSection } from "./useCmsSection";
6
6
 
7
7
  describe("useCmsSection", () => {
8
8
  it("search", async () => {
9
+ const section = CmsPage.cmsPage.sections?.[0];
10
+
9
11
  const { vm, injections } = useSetup(() =>
10
- useCmsSection(
11
- CmsPage.cmsPage.sections[0] as unknown as Schemas["CmsSection"],
12
- ),
12
+ useCmsSection(section as unknown as Schemas["CmsSection"]),
13
13
  );
14
14
  injections.apiClient.invoke.mockResolvedValue({ data: {} });
15
15
  const block = await vm.getPositionContent("main");
16
- expect(block).toEqual(CmsPage.cmsPage.sections[0].blocks);
16
+ expect(block).toEqual(section?.blocks);
17
17
  });
18
18
  });
@@ -14,9 +14,9 @@ describe("useCountries", () => {
14
14
  });
15
15
  await vm.fetchCountries();
16
16
 
17
- expect(vm.getStatesForCountry(CountryMock.elements[0].id)).toStrictEqual(
18
- CountryMock.elements[0].states,
19
- );
17
+ expect(
18
+ vm.getStatesForCountry(CountryMock.elements?.[0]?.id as string),
19
+ ).toStrictEqual(CountryMock.elements?.[0]?.states);
20
20
 
21
21
  expect(injections.apiClient.invoke).toHaveBeenCalledWith(
22
22
  expect.stringContaining("readCountry"),
@@ -42,9 +42,9 @@ describe("useCountries", () => {
42
42
  });
43
43
  await vm.fetchCountries();
44
44
 
45
- expect(vm.getStatesForCountry(CountryMock.elements[0].id)).toStrictEqual(
46
- null,
47
- );
45
+ expect(
46
+ vm.getStatesForCountry(CountryMock.elements?.[0]?.id as string),
47
+ ).toStrictEqual(null);
48
48
  });
49
49
 
50
50
  it("useCountries flow - empty", async () => {
@@ -61,4 +61,45 @@ describe("useCountries", () => {
61
61
 
62
62
  expect(vm.getCountries).toStrictEqual([]);
63
63
  });
64
+
65
+ it("useCountries flow - getCountriesOptions", async () => {
66
+ const { vm } = await useSetup(useCountries, {
67
+ apiClient: {
68
+ invoke: vi.fn().mockResolvedValue({
69
+ data: CountryMock,
70
+ }),
71
+ },
72
+ });
73
+
74
+ await vm.fetchCountries();
75
+
76
+ expect(vm.getCountriesOptions).toStrictEqual([
77
+ {
78
+ value: "16bb0446bf094f5d8bebf450652abafc",
79
+ label: "Sweden",
80
+ },
81
+ {
82
+ value: "184eb596425f4d56aa9ed8af9c3dc8d1",
83
+ label: "Ireland",
84
+ },
85
+ {
86
+ value: "20513996f80f4d00b5ebedc51a2deae2",
87
+ label: "Australia",
88
+ },
89
+ ]);
90
+ });
91
+
92
+ it("useCountries flow - getCountriesOptions - empty array", async () => {
93
+ const { vm } = await useSetup(useCountries, {
94
+ apiClient: {
95
+ invoke: vi.fn().mockResolvedValue({
96
+ data: {
97
+ elements: null,
98
+ },
99
+ }),
100
+ },
101
+ });
102
+
103
+ expect(vm.getCountriesOptions).toStrictEqual([]);
104
+ });
64
105
  });
@@ -10,6 +10,12 @@ export type UseCountriesReturn = {
10
10
  operations["readCountry post /country"]["response"]
11
11
  >;
12
12
  getStatesForCountry(countryId: string): Schemas["CountryState"][] | null;
13
+ getCountriesOptions: ComputedRef<
14
+ {
15
+ label: string;
16
+ value: string;
17
+ }[]
18
+ >;
13
19
  };
14
20
 
15
21
  /**
@@ -39,6 +45,15 @@ export function useCountries(): UseCountriesReturn {
39
45
  return _sharedCountries.value ?? [];
40
46
  });
41
47
 
48
+ const getCountriesOptions = computed(() => {
49
+ return (
50
+ _sharedCountries.value?.map((element: Schemas["Country"]) => ({
51
+ label: element.translated.name,
52
+ value: element.id,
53
+ })) ?? []
54
+ );
55
+ });
56
+
42
57
  const mountedCallback = async () => {
43
58
  if (!_sharedCountries.value) {
44
59
  await fetchCountries();
@@ -60,5 +75,6 @@ export function useCountries(): UseCountriesReturn {
60
75
  fetchCountries,
61
76
  getStatesForCountry,
62
77
  getCountries,
78
+ getCountriesOptions,
63
79
  };
64
80
  }
@@ -525,7 +525,9 @@ export function createListingComposable({
525
525
  };
526
526
  }
527
527
 
528
- return search(appliedFilters);
528
+ return search(
529
+ appliedFilters as operations["searchPage post /search"]["body"],
530
+ );
529
531
  };
530
532
 
531
533
  const resetFilters = () => {
@@ -76,6 +76,27 @@ describe("useNavigationSearch", () => {
76
76
  }),
77
77
  );
78
78
  });
79
+ it("should resolve technical url with trailing slash", async () => {
80
+ const { vm, injections } = useSetup(useNavigationSearch);
81
+ injections.apiClient.invoke.mockResolvedValue({ data: { elements: [] } });
82
+
83
+ await vm.resolvePath("/detail/test/");
84
+
85
+ expect(injections.apiClient.invoke).toHaveBeenCalledWith(
86
+ expect.stringContaining("readSeoUrl"),
87
+ expect.objectContaining({
88
+ body: {
89
+ filter: [
90
+ {
91
+ type: "equals",
92
+ field: "pathInfo",
93
+ value: "/detail/test",
94
+ },
95
+ ],
96
+ },
97
+ }),
98
+ );
99
+ });
79
100
  it("should not invoke api call for / search ", async () => {
80
101
  const { vm, injections } = useSetup(useNavigationSearch);
81
102
  injections.apiClient.invoke.mockResolvedValue({
@@ -18,7 +18,7 @@ export function useNavigationSearch(): UseNavigationSearchReturn {
18
18
  const { apiClient } = useShopwareContext();
19
19
  const { sessionContext } = useSessionContext();
20
20
 
21
- async function resolvePath(path: string) {
21
+ async function resolvePath(path: string): Promise<Schemas["SeoUrl"] | null> {
22
22
  if (path === "/") {
23
23
  // please ignore optional chaining for salesChannel object as it's always present (type definition issue)
24
24
  const categoryId =
@@ -35,9 +35,12 @@ export function useNavigationSearch(): UseNavigationSearchReturn {
35
35
  path.startsWith("/detail/") ||
36
36
  path.startsWith("/landingPage/");
37
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);
38
+ // remove leading slash in case of seo url or remove trailing slash in case of technical url
39
+ const normalizedPath = isTechnicalUrl
40
+ ? path.endsWith("/")
41
+ ? path.slice(0, -1)
42
+ : path
43
+ : path.substring(1);
41
44
 
42
45
  const seoResult = await apiClient.invoke("readSeoUrl post /seo-url", {
43
46
  body: {
@@ -51,7 +54,7 @@ export function useNavigationSearch(): UseNavigationSearchReturn {
51
54
  },
52
55
  });
53
56
 
54
- return seoResult.data.elements?.[0];
57
+ return seoResult.data.elements?.[0] ?? null;
55
58
  }
56
59
 
57
60
  return {
@@ -20,7 +20,7 @@ describe("useNotifications", () => {
20
20
  vm.pushWarning("Warning message", { persistent: true });
21
21
 
22
22
  expect(vm.notifications.length).toBe(4);
23
- vm.removeOne(vm.notifications[0].id);
23
+ vm.removeOne(vm.notifications[0]?.id as number);
24
24
  expect(vm.notifications.length).toBe(3);
25
25
  vm.removeAll();
26
26
  expect(vm.notifications.length).toBe(0);
@@ -15,15 +15,15 @@ describe("useOrderDetails", () => {
15
15
  );
16
16
 
17
17
  expect(vm.personalDetails).toEqual({
18
- email: Order.orders.elements[0].orderCustomer.email,
19
- firstName: Order.orders.elements[0].orderCustomer.firstName,
20
- lastName: Order.orders.elements[0].orderCustomer.lastName,
18
+ email: Order.orders.elements?.[0]?.orderCustomer.email,
19
+ firstName: Order.orders.elements?.[0]?.orderCustomer.firstName,
20
+ lastName: Order.orders.elements?.[0]?.orderCustomer.lastName,
21
21
  });
22
22
 
23
23
  expect(vm.billingAddress).toEqual(
24
- Order.orders.elements[0].addresses.find(
24
+ Order.orders.elements?.[0]?.addresses.find(
25
25
  ({ id }: { id: string }) =>
26
- id === Order.orders.elements[0].billingAddressId,
26
+ id === Order.orders.elements?.[0]?.billingAddressId,
27
27
  ),
28
28
  );
29
29
  });
@@ -139,20 +139,17 @@ export function useOrderDetails(
139
139
 
140
140
  const orderAssociations = useDefaultOrderAssociations();
141
141
 
142
- const paymentMethod = computed(() =>
143
- _sharedOrder.value?.transactions?.length
144
- ? _sharedOrder.value.transactions[
145
- _sharedOrder.value.transactions.length - 1
146
- ].paymentMethod
147
- : undefined,
148
- );
142
+ const paymentMethod = computed(() => {
143
+ const transactions = _sharedOrder.value?.transactions;
144
+ if (!transactions?.length) return undefined;
145
+ return transactions[transactions.length - 1]?.paymentMethod;
146
+ });
149
147
 
150
- const shippingMethod = computed(() =>
151
- _sharedOrder.value?.deliveries?.length
152
- ? _sharedOrder.value.deliveries[_sharedOrder.value.deliveries.length - 1]
153
- .shippingMethod
154
- : undefined,
155
- );
148
+ const shippingMethod = computed(() => {
149
+ const deliveries = _sharedOrder.value?.deliveries;
150
+ if (!deliveries?.length) return undefined;
151
+ return deliveries[deliveries.length - 1]?.shippingMethod;
152
+ });
156
153
 
157
154
  const paymentUrl = ref();
158
155
 
@@ -204,7 +201,7 @@ export function useOrderDetails(
204
201
  },
205
202
  );
206
203
  _sharedOrder.value =
207
- orderDetailsResponse.data.orders?.elements?.[0] ?? null;
204
+ orderDetailsResponse.data.orders?.elements?.[0] ?? undefined;
208
205
  paymentChangeableList.value =
209
206
  orderDetailsResponse.data.paymentChangeable ?? {};
210
207
  return orderDetailsResponse.data;
@@ -285,11 +282,7 @@ export function useOrderDetails(
285
282
  const documents = computed(() => _sharedOrder.value?.documents || []);
286
283
 
287
284
  const paymentChangeable = computed(() => {
288
- return Object.keys(paymentChangeableList.value).length
289
- ? (paymentChangeableList.value as { [key: string]: boolean })[
290
- orderId as string
291
- ]
292
- : false;
285
+ return paymentChangeableList.value?.[orderId as string] ?? false;
293
286
  });
294
287
 
295
288
  const getPaymentMethods = async () => {
@@ -10,7 +10,7 @@ describe("useOrderPayment", () => {
10
10
  it("should handle the order payment", async () => {
11
11
  const { vm, injections } = useSetup(() =>
12
12
  useOrderPayment(
13
- computed(() => Order.orders.elements[0]) as unknown as ComputedRef<
13
+ computed(() => Order.orders.elements?.[0]) as unknown as ComputedRef<
14
14
  Schemas["Order"]
15
15
  >,
16
16
  ),
@@ -24,13 +24,13 @@ describe("useOrderPayment", () => {
24
24
  body: {
25
25
  errorUrl: undefined,
26
26
  finishUrl: undefined,
27
- orderId: Order.orders.elements[0].id,
27
+ orderId: Order.orders.elements?.[0]?.id,
28
28
  },
29
29
  }),
30
30
  );
31
31
 
32
32
  expect(vm.activeTransaction).toEqual(
33
- Order.orders.elements[0].transactions[0],
33
+ Order.orders.elements?.[0]?.transactions[0],
34
34
  );
35
35
 
36
36
  vm.changePaymentMethod("test");
@@ -59,19 +59,18 @@ describe("useOrderPayment", () => {
59
59
  it("should be a asynchronous payment", () => {
60
60
  const { vm } = useSetup(() =>
61
61
  useOrderPayment(
62
- computed(() =>
63
- Object.assign(Order.orders.elements[0], {
64
- transactions: [
65
- {
66
- paymentMethod: {
67
- active: true,
68
- asynchronous: true,
69
- afterOrderEnabled: true,
70
- },
62
+ computed(() => ({
63
+ ...Order.orders.elements?.[0],
64
+ transactions: [
65
+ {
66
+ paymentMethod: {
67
+ active: true,
68
+ asynchronous: true,
69
+ afterOrderEnabled: true,
71
70
  },
72
- ],
73
- }),
74
- ) as unknown as ComputedRef<Schemas["Order"]>,
71
+ },
72
+ ],
73
+ })) as unknown as ComputedRef<Schemas["Order"]>,
75
74
  ),
76
75
  );
77
76
 
@@ -2,12 +2,20 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
2
2
  import { ref } from "vue";
3
3
  import { usePrice, useSessionContext } from "#imports";
4
4
  import { useSetup } from "../_test";
5
- const currentNavigator = global.navigator;
5
+
6
+ vi.mock("@vueuse/core", async (importOriginal) => {
7
+ const actual = await importOriginal<typeof import("@vueuse/core")>();
8
+ return {
9
+ ...actual,
10
+ createSharedComposable: (fn: (...args: unknown[]) => unknown) => fn,
11
+ };
12
+ });
6
13
 
7
14
  vi.mock("../useSessionContext/useSessionContext.ts");
8
15
  const sessionContext = ref();
9
16
 
10
17
  beforeEach(() => {
18
+ sessionContext.value = null;
11
19
  vi.clearAllMocks();
12
20
  vi.mocked(useSessionContext).mockReturnValue({
13
21
  sessionContext,
@@ -20,9 +28,6 @@ describe("usePrice", () => {
20
28
  });
21
29
 
22
30
  it("use default locale if locale is not provided", () => {
23
- vi.spyOn(global, "navigator", "get").mockImplementation(
24
- () => ({}) as Navigator,
25
- );
26
31
  const { vm } = useSetup(usePrice);
27
32
  expect(vm.getFormattedPrice(2.55)).toMatchInlineSnapshot('"2.55"');
28
33
  vm.update({
@@ -30,21 +35,23 @@ describe("usePrice", () => {
30
35
  localeCode: undefined,
31
36
  });
32
37
 
38
+ expect(vm.currencyLocale).toBe("en-US");
33
39
  expect(vm.getFormattedPrice(2.55)).toMatchInlineSnapshot('"$2.55"');
34
40
  });
35
41
 
36
42
  it("should use navigator language if locale is not provided", () => {
37
- vi.spyOn(global, "navigator", "get").mockImplementation(
38
- () => currentNavigator,
39
- );
40
- vi.spyOn(navigator, "language", "get").mockImplementation(() => "en-FR");
41
- const { vm } = useSetup(usePrice);
43
+ const { vm } = useSetup(usePrice, {
44
+ shopware: {
45
+ browserLocale: "de-DE",
46
+ },
47
+ });
42
48
  vm.update({
43
49
  currencyCode: "USD",
44
50
  localeCode: undefined,
45
51
  });
46
52
 
47
- expect(vm.getFormattedPrice(2.55)).toMatchInlineSnapshot('"$2.55"');
53
+ expect(vm.currencyLocale).toBe("de-DE");
54
+ expect(vm.getFormattedPrice(2.55)).toMatchInlineSnapshot(`"2,55 $"`);
48
55
  });
49
56
 
50
57
  it("should init price object", () => {
@@ -71,10 +78,14 @@ describe("usePrice", () => {
71
78
  it("should return price with current locale", async () => {
72
79
  const { vm } = useSetup(usePrice);
73
80
 
81
+ await vm.update({
82
+ localeCode: "de-DE",
83
+ currencyCode: "EUR",
84
+ });
85
+
74
86
  await vm.update({
75
87
  currencyCode: "USD",
76
- // @ts-expect-error string expected here
77
- currencyLocale: undefined,
88
+ localeCode: undefined,
78
89
  });
79
90
  expect(vm.getFormattedPrice(2.55)).toMatchInlineSnapshot('"2,55 $"');
80
91
  });
@@ -94,4 +105,28 @@ describe("usePrice", () => {
94
105
  await vm.$nextTick();
95
106
  expect(vm.currencyCode).toBe("PLN");
96
107
  });
108
+
109
+ it("should use default en-US locale if locale is not provided", async () => {
110
+ const { vm } = useSetup(usePrice);
111
+
112
+ await vm.update({
113
+ currencyCode: "USD",
114
+ });
115
+ expect(vm.currencyLocale).toBe("en-US");
116
+ expect(vm.getFormattedPrice(2.55)).toMatchInlineSnapshot('"$2.55"');
117
+ });
118
+
119
+ it("should take locale from shopware context", async () => {
120
+ const { vm } = useSetup(usePrice, {
121
+ shopware: {
122
+ browserLocale: "en-GB",
123
+ },
124
+ });
125
+
126
+ await vm.update({
127
+ currencyCode: "USD",
128
+ });
129
+ expect(vm.currencyLocale).toBe("en-GB");
130
+ expect(vm.getFormattedPrice(2.55)).toMatchInlineSnapshot(`"US$2.55"`);
131
+ });
97
132
  });