@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,37 @@
1
+ import { flushPromises } from "@vue/test-utils";
2
+ import { describe, expect, it, vi } from "vitest";
3
+ import { useSetup } from "../_test";
4
+ import Salutations from "../mocks/Salutations";
5
+ import { useSalutations } from "./useSalutations";
6
+
7
+ describe("useSalutations", () => {
8
+ it("should init value on init", async () => {
9
+ const { vm, injections } = useSetup(useSalutations, {
10
+ apiClient: {
11
+ invoke: vi.fn().mockResolvedValue({
12
+ data: {
13
+ elements: Salutations,
14
+ },
15
+ }),
16
+ },
17
+ });
18
+ await flushPromises();
19
+
20
+ expect(injections.apiClient.invoke).toBeCalledTimes(1);
21
+ expect(vm.getSalutations).toStrictEqual(Salutations);
22
+ });
23
+
24
+ it("should return empty array if no salutations", async () => {
25
+ const { vm } = useSetup(useSalutations, {
26
+ apiClient: {
27
+ invoke: vi.fn().mockResolvedValue({
28
+ data: {
29
+ elements: null,
30
+ },
31
+ }),
32
+ },
33
+ });
34
+
35
+ expect(vm.getSalutations).toStrictEqual([]);
36
+ });
37
+ });
@@ -0,0 +1,55 @@
1
+ import { computed, inject, onMounted, provide, ref } from "vue";
2
+ import type { ComputedRef } from "vue";
3
+ import { useShopwareContext } from "#imports";
4
+ import type { Schemas, operations } from "#shopware";
5
+
6
+ export type UseSalutationsReturn = {
7
+ /**
8
+ * All available salutations
9
+ */
10
+ getSalutations: ComputedRef<Schemas["Salutation"][]>;
11
+ /**
12
+ * Fetches the salutations list and assigns the result to the `salutations` property
13
+ */
14
+ fetchSalutations(): Promise<
15
+ operations["readSalutation post /salutation"]["response"]
16
+ >;
17
+ };
18
+
19
+ /**
20
+ * Composable for fetching the salutations list.
21
+ * @public
22
+ * @category Context & Language
23
+ */
24
+ export function useSalutations(): UseSalutationsReturn {
25
+ const { apiClient } = useShopwareContext();
26
+
27
+ const _salutations = inject("swSalutations", ref());
28
+ provide("swSalutations", _salutations);
29
+
30
+ const fetchSalutations = async (): Promise<
31
+ operations["readSalutation post /salutation"]["response"]
32
+ > => {
33
+ const result = await apiClient.invoke("readSalutation post /salutation");
34
+ _salutations.value = result.data.elements;
35
+ return result.data;
36
+ };
37
+
38
+ // created separate function for testing proposes
39
+ const mountedCallback = async () => {
40
+ if (!_salutations.value) {
41
+ await fetchSalutations();
42
+ }
43
+ };
44
+
45
+ const getSalutations = computed(() => {
46
+ return _salutations.value || [];
47
+ });
48
+
49
+ onMounted(mountedCallback);
50
+
51
+ return {
52
+ fetchSalutations,
53
+ getSalutations,
54
+ };
55
+ }
@@ -0,0 +1,221 @@
1
+ import { describe, expect, it, vi } from "vitest";
2
+ import type { Schemas } from "#shopware";
3
+ import { useSetup } from "../_test";
4
+ import { useSessionContext } from "./useSessionContext";
5
+
6
+ const consoleErrorSpy = vi.spyOn(console, "error");
7
+ consoleErrorSpy.mockImplementation(() => {});
8
+
9
+ describe("useSessionContext", () => {
10
+ const consoleErrorSpy = vi.spyOn(console, "error");
11
+ it("setLanguage", () => {
12
+ const { vm, injections } = useSetup(() => useSessionContext());
13
+ injections.apiClient.invoke.mockResolvedValue({ data: {} });
14
+ vm.setLanguage({ id: "test" });
15
+ expect(injections.apiClient.invoke).toHaveBeenCalledWith(
16
+ expect.stringContaining("updateContext"),
17
+ expect.objectContaining({
18
+ body: {
19
+ languageId: "test",
20
+ },
21
+ }),
22
+ );
23
+ });
24
+
25
+ it("setLanguage - no id", () => {
26
+ const { vm, injections } = useSetup(() => useSessionContext());
27
+ injections.apiClient.invoke.mockResolvedValue({ data: {} });
28
+ vm.setLanguage({ id: "" });
29
+ expect(injections.apiClient.invoke).not.toHaveBeenCalledWith(
30
+ expect.stringContaining("updateContext"),
31
+ );
32
+ });
33
+
34
+ it("setCountry", async () => {
35
+ const { vm, injections } = useSetup(() => useSessionContext());
36
+ injections.apiClient.invoke.mockResolvedValue({ data: {} });
37
+ await vm.setCountry("test");
38
+ expect(injections.apiClient.invoke).toHaveBeenCalledWith(
39
+ expect.stringContaining("updateContext"),
40
+ expect.objectContaining({
41
+ body: {
42
+ countryId: "test",
43
+ },
44
+ }),
45
+ );
46
+ });
47
+
48
+ it("refreshSessionContext", async () => {
49
+ const { vm, injections } = useSetup(() => useSessionContext());
50
+ injections.apiClient.invoke.mockResolvedValue({ data: {} });
51
+ await vm.refreshSessionContext();
52
+ expect(injections.apiClient.invoke).toHaveBeenCalledWith(
53
+ expect.stringContaining("readContext"),
54
+ );
55
+ });
56
+
57
+ it("refreshSessionContext - error", async () => {
58
+ const { vm } = useSetup(() => useSessionContext(), {
59
+ apiClient: {
60
+ invoke: vi.fn().mockImplementation(() => {
61
+ throw new Error("error test");
62
+ }),
63
+ },
64
+ });
65
+ consoleErrorSpy.mockImplementation(() => {});
66
+ await vm.refreshSessionContext();
67
+ expect(consoleErrorSpy).toHaveBeenCalledTimes(1);
68
+ });
69
+
70
+ it("setShippingMethod", async () => {
71
+ const { vm, injections } = useSetup(() => useSessionContext());
72
+ injections.apiClient.invoke.mockResolvedValue({ data: {} });
73
+ vm.setShippingMethod({ id: "test" });
74
+ expect(injections.apiClient.invoke).toHaveBeenCalledWith(
75
+ expect.stringContaining("updateContext"),
76
+ expect.objectContaining({
77
+ body: {
78
+ shippingMethodId: "test",
79
+ },
80
+ }),
81
+ );
82
+ });
83
+
84
+ it("setShippingMethod - error", async () => {
85
+ const { vm, injections } = useSetup(() => useSessionContext());
86
+ injections.apiClient.invoke.mockResolvedValue({ data: {} });
87
+
88
+ await expect(vm.setShippingMethod({ id: undefined })).rejects.toThrowError(
89
+ "You need to provide shipping method id in order to set shipping method.",
90
+ );
91
+ });
92
+
93
+ it("setPaymentMethod", async () => {
94
+ const { vm, injections } = useSetup(() => useSessionContext());
95
+ injections.apiClient.invoke.mockResolvedValue({ data: {} });
96
+ vm.setPaymentMethod({ id: "test" });
97
+ expect(injections.apiClient.invoke).toHaveBeenCalledWith(
98
+ expect.stringContaining("updateContext"),
99
+ expect.objectContaining({
100
+ body: {
101
+ paymentMethodId: "test",
102
+ },
103
+ }),
104
+ );
105
+ });
106
+
107
+ it("setPaymentMethod - error", async () => {
108
+ const { vm, injections } = useSetup(() => useSessionContext());
109
+ injections.apiClient.invoke.mockResolvedValue({ data: {} });
110
+
111
+ await expect(vm.setPaymentMethod({ id: "" })).rejects.toThrowError(
112
+ "You need to provide payment method id in order to set payment method.",
113
+ );
114
+ });
115
+
116
+ it("setCurrency", async () => {
117
+ const { vm, injections } = useSetup(() => useSessionContext());
118
+ injections.apiClient.invoke.mockResolvedValue({ data: {} });
119
+ vm.setCurrency({ id: "test" });
120
+ expect(injections.apiClient.invoke).toHaveBeenCalledWith(
121
+ expect.stringContaining("updateContext"),
122
+ expect.objectContaining({
123
+ body: {
124
+ currencyId: "test",
125
+ },
126
+ }),
127
+ );
128
+ });
129
+
130
+ it("setCurrency - error", async () => {
131
+ const { vm, injections } = useSetup(() => useSessionContext());
132
+ injections.apiClient.invoke.mockResolvedValue({ data: {} });
133
+ vm.setCurrency({ id: "" });
134
+ expect(consoleErrorSpy).toHaveBeenCalled();
135
+ });
136
+
137
+ it("setActiveShippingAddress", async () => {
138
+ const { vm, injections } = useSetup(() => useSessionContext());
139
+ injections.apiClient.invoke.mockResolvedValue({ data: {} });
140
+ vm.setActiveShippingAddress({ id: "test" });
141
+ expect(injections.apiClient.invoke).toHaveBeenCalledWith(
142
+ expect.stringContaining("updateContext"),
143
+ expect.objectContaining({
144
+ body: {
145
+ shippingAddressId: "test",
146
+ },
147
+ }),
148
+ );
149
+ });
150
+
151
+ it("setActiveShippingAddress - error", async () => {
152
+ const { vm, injections } = useSetup(() => useSessionContext());
153
+ injections.apiClient.invoke.mockResolvedValue({ data: {} });
154
+ await expect(vm.setActiveShippingAddress({ id: "" })).rejects.toThrowError(
155
+ "You need to provide address id in order to set the address.",
156
+ );
157
+ });
158
+
159
+ it("setActiveBillingAddress", async () => {
160
+ const { vm, injections } = useSetup(() => useSessionContext());
161
+ injections.apiClient.invoke.mockResolvedValue({ data: {} });
162
+ vm.setActiveBillingAddress({ id: "test" });
163
+ expect(injections.apiClient.invoke).toHaveBeenCalledWith(
164
+ expect.stringContaining("updateContext"),
165
+ expect.objectContaining({
166
+ body: {
167
+ billingAddressId: "test",
168
+ },
169
+ }),
170
+ );
171
+ });
172
+
173
+ it("setActiveBillingAddress - error", async () => {
174
+ const { vm, injections } = useSetup(() => useSessionContext());
175
+ injections.apiClient.invoke.mockResolvedValue({ data: {} });
176
+ await expect(vm.setActiveBillingAddress({ id: "" })).rejects.toThrowError(
177
+ "You need to provide address id in order to set the address.",
178
+ );
179
+ });
180
+
181
+ it("setContext", () => {
182
+ const { vm } = useSetup(() => useSessionContext());
183
+ vm.setContext({
184
+ countryId: "test",
185
+ } as unknown as Schemas["SalesChannelContext"]);
186
+ expect(vm.sessionContext).toStrictEqual({
187
+ countryId: "test",
188
+ });
189
+ expect(vm.activeShippingAddress).toBe(null);
190
+ });
191
+
192
+ it("activeShippingAddress - active address", () => {
193
+ const { vm } = useSetup(() => useSessionContext());
194
+ vm.setContext({
195
+ customer: {
196
+ activeShippingAddress: {
197
+ city: "test",
198
+ },
199
+ },
200
+ } as unknown as Schemas["SalesChannelContext"]);
201
+
202
+ expect(vm.activeShippingAddress).toStrictEqual({
203
+ city: "test",
204
+ });
205
+ });
206
+
207
+ it("activeShippingAddress - shipping location", () => {
208
+ const { vm } = useSetup(() => useSessionContext());
209
+ vm.setContext({
210
+ shippingLocation: {
211
+ address: {
212
+ city: "test",
213
+ },
214
+ },
215
+ } as unknown as Schemas["SalesChannelContext"]);
216
+
217
+ expect(vm.activeShippingAddress).toStrictEqual({
218
+ city: "test",
219
+ });
220
+ });
221
+ });
@@ -0,0 +1,281 @@
1
+ import { computed } from "vue";
2
+ import type { ComputedRef } from "vue";
3
+
4
+ import { useContext, useShopwareContext } from "#imports";
5
+ import type { Schemas } from "#shopware";
6
+
7
+ export type UseSessionContextReturn = {
8
+ /**
9
+ * Patches the context in order to use new language
10
+ */
11
+ setLanguage(language: Partial<Schemas["Language"]>): Promise<void>;
12
+ /**
13
+ * Patches the context in order to use new countryId
14
+ *
15
+ * @param {string} countryId
16
+ */
17
+ setCountry(countryId: string): Promise<void>;
18
+ /**
19
+ * current context's language
20
+ */
21
+ sessionContext: ComputedRef<Schemas["SalesChannelContext"] | undefined>;
22
+ /**
23
+ * Fetches the session context and assigns the result to the `sessionContext` property
24
+ */
25
+ refreshSessionContext(): Promise<void>;
26
+ /**
27
+ * current context's language
28
+ */
29
+ selectedShippingMethod: ComputedRef<Schemas["ShippingMethod"] | null>;
30
+ /**
31
+ * Patches the context in order to use new shipping method
32
+ */
33
+ setShippingMethod(
34
+ shippingMethod: Partial<Schemas["ShippingMethod"]>,
35
+ ): Promise<void>;
36
+ /**
37
+ * current context's payment method
38
+ */
39
+ selectedPaymentMethod: ComputedRef<Schemas["PaymentMethod"] | null>;
40
+ /**
41
+ * Patches the context in order to use new payment method
42
+ */
43
+ setPaymentMethod(paymentMethod: { id: string }): Promise<void>;
44
+ /**
45
+ * current context's currency
46
+ */
47
+ currency: ComputedRef<Schemas["Currency"] | null>;
48
+ /**
49
+ * Patches the context in order to use new currency
50
+ */
51
+ setCurrency(currency: Partial<Schemas["Currency"]>): Promise<void>;
52
+ /**
53
+ * current context's shipping address
54
+ */
55
+ activeShippingAddress: ComputedRef<Schemas["CustomerAddress"] | null>;
56
+ /**
57
+ * Patches the context in order to use new shipping address
58
+ */
59
+ setActiveShippingAddress(
60
+ address: Partial<Schemas["CustomerAddress"]>,
61
+ ): Promise<void>;
62
+ /**
63
+ * current context's billing address
64
+ */
65
+ activeBillingAddress: ComputedRef<Schemas["CustomerAddress"] | null>;
66
+ /**
67
+ * current context's tax state
68
+ */
69
+ taxState: ComputedRef<string | undefined>;
70
+ /**
71
+ * Patches the context in order to use new billing address
72
+ */
73
+ setActiveBillingAddress(
74
+ address: Partial<Schemas["CustomerAddress"]>,
75
+ ): Promise<void>;
76
+ /**
77
+ * Patches the context with new context
78
+ */
79
+ setContext(context: Schemas["SalesChannelContext"]): void;
80
+ /**
81
+ * current context's country id
82
+ */
83
+ countryId: ComputedRef<string | undefined>;
84
+ /**
85
+ * current sales channel country id
86
+ */
87
+ salesChannelCountryId: ComputedRef<string | undefined>;
88
+ /**
89
+ * current language id
90
+ */
91
+ languageId: ComputedRef<string | undefined>;
92
+ /**
93
+ * current language id chain
94
+ */
95
+ languageIdChain: ComputedRef<string>;
96
+ /**
97
+ * current context's customer object
98
+ */
99
+ userFromContext: ComputedRef<Schemas["Customer"] | undefined>;
100
+ };
101
+
102
+ /**
103
+ * Composable for session management.
104
+ * SessionContext contain all related data like user, currency, country, shippingMethod, paymentMethod etc.
105
+ * @public
106
+ * @category Context & Language
107
+ */
108
+ export function useSessionContext(
109
+ newContext?: Schemas["SalesChannelContext"],
110
+ ): UseSessionContextReturn {
111
+ const { apiClient } = useShopwareContext();
112
+
113
+ const _sessionContext = useContext("swSessionContext", {
114
+ replace: newContext,
115
+ });
116
+
117
+ const sessionContext = computed(() => _sessionContext.value);
118
+ const refreshSessionContext = async () => {
119
+ try {
120
+ const { data } = await apiClient.invoke("readContext get /context");
121
+ _sessionContext.value = data;
122
+ } catch (e) {
123
+ console.error("[UseSessionContext][refreshSessionContext]", e);
124
+ }
125
+ };
126
+
127
+ const selectedShippingMethod = computed(
128
+ () => sessionContext.value?.shippingMethod || null,
129
+ );
130
+ const setShippingMethod = async (shippingMethod: { id: string }) => {
131
+ if (!shippingMethod?.id) {
132
+ throw new Error(
133
+ "You need to provide shipping method id in order to set shipping method.",
134
+ );
135
+ }
136
+ await apiClient.invoke("updateContext patch /context", {
137
+ body: { shippingMethodId: shippingMethod.id },
138
+ });
139
+ await refreshSessionContext();
140
+ };
141
+
142
+ const selectedPaymentMethod = computed(
143
+ () => sessionContext.value?.paymentMethod || null,
144
+ );
145
+ const setPaymentMethod = async (paymentMethod: { id: string }) => {
146
+ if (!paymentMethod?.id) {
147
+ throw new Error(
148
+ "You need to provide payment method id in order to set payment method.",
149
+ );
150
+ }
151
+ await apiClient.invoke("updateContext patch /context", {
152
+ body: { paymentMethodId: paymentMethod.id },
153
+ });
154
+ await refreshSessionContext();
155
+ };
156
+
157
+ const currency = computed(() => sessionContext.value?.currency || null);
158
+ const setCurrency = async (currency: Partial<Schemas["Currency"]>) => {
159
+ if (!currency.id) {
160
+ console.error(
161
+ "You need to provide currency id in order to set currency.",
162
+ currency,
163
+ );
164
+ return;
165
+ }
166
+ await apiClient.invoke("updateContext patch /context", {
167
+ body: {
168
+ currencyId: currency.id,
169
+ },
170
+ });
171
+ await refreshSessionContext();
172
+ };
173
+
174
+ const setLanguage = async (language: Partial<Schemas["Language"]>) => {
175
+ if (!language.id) {
176
+ return;
177
+ }
178
+ await apiClient.invoke("updateContext patch /context", {
179
+ body: {
180
+ languageId: language.id,
181
+ },
182
+ });
183
+ await refreshSessionContext();
184
+ };
185
+
186
+ const setCountry = async (countryId: string) => {
187
+ await apiClient.invoke("updateContext patch /context", {
188
+ body: {
189
+ countryId,
190
+ },
191
+ });
192
+ await refreshSessionContext();
193
+ };
194
+
195
+ const activeShippingAddress = computed(
196
+ () =>
197
+ sessionContext.value?.customer?.activeShippingAddress ||
198
+ sessionContext.value?.shippingLocation?.address ||
199
+ null,
200
+ );
201
+ const setActiveShippingAddress = async (
202
+ address: Partial<Schemas["CustomerAddress"]>,
203
+ ) => {
204
+ if (!address?.id) {
205
+ throw new Error(
206
+ "You need to provide address id in order to set the address.",
207
+ );
208
+ }
209
+ await apiClient.invoke("updateContext patch /context", {
210
+ body: {
211
+ shippingAddressId: address.id,
212
+ },
213
+ });
214
+ refreshSessionContext();
215
+ };
216
+
217
+ // TODO: replace the source from defaultBillingAddress by new value once NEXT-28627 is solved
218
+ const activeBillingAddress = computed(
219
+ () => sessionContext.value?.customer?.activeBillingAddress || null,
220
+ );
221
+ const setActiveBillingAddress = async (
222
+ address: Partial<Schemas["CustomerAddress"]>,
223
+ ) => {
224
+ if (!address?.id) {
225
+ throw new Error(
226
+ "You need to provide address id in order to set the address.",
227
+ );
228
+ }
229
+ await apiClient.invoke("updateContext patch /context", {
230
+ body: {
231
+ billingAddressId: address.id,
232
+ },
233
+ });
234
+ refreshSessionContext();
235
+ };
236
+
237
+ const setContext = (context: Schemas["SalesChannelContext"]) => {
238
+ _sessionContext.value = context;
239
+ };
240
+
241
+ const countryId = computed(
242
+ () => sessionContext.value?.shippingLocation?.country?.id,
243
+ );
244
+
245
+ const salesChannelCountryId = computed(
246
+ () => sessionContext.value?.salesChannel?.countryId,
247
+ );
248
+
249
+ const languageId = computed(
250
+ () => sessionContext.value?.salesChannel?.languageId,
251
+ );
252
+ const languageIdChain = computed(
253
+ () => sessionContext.value?.context?.languageIdChain?.[0] || "",
254
+ );
255
+ const taxState = computed(() => sessionContext.value?.context?.taxState);
256
+ const userFromContext = computed(() => sessionContext.value?.customer);
257
+
258
+ return {
259
+ sessionContext,
260
+ refreshSessionContext,
261
+ selectedShippingMethod,
262
+ setShippingMethod,
263
+ selectedPaymentMethod,
264
+ setPaymentMethod,
265
+ currency,
266
+ setCurrency,
267
+ activeShippingAddress,
268
+ setActiveShippingAddress,
269
+ activeBillingAddress,
270
+ setActiveBillingAddress,
271
+ countryId,
272
+ salesChannelCountryId,
273
+ taxState,
274
+ userFromContext,
275
+ setLanguage,
276
+ languageId,
277
+ languageIdChain,
278
+ setCountry,
279
+ setContext,
280
+ };
281
+ }
@@ -0,0 +1,8 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { useShopwareContext } from "./useShopwareContext";
3
+
4
+ describe("useShopwareContext", () => {
5
+ it("no context error", () => {
6
+ expect(() => useShopwareContext()).toThrow();
7
+ });
8
+ });
@@ -0,0 +1,31 @@
1
+ import { inject } from "vue";
2
+ import type { ApiClient } from "#shopware";
3
+ import ContextError from "../helpers/ContextError";
4
+
5
+ export type ShopwareContext = {
6
+ devStorefrontUrl: string | null;
7
+ /**
8
+ * Shopware API client
9
+ */
10
+ apiClient: ApiClient;
11
+ };
12
+
13
+ /**
14
+ * @public
15
+ * @category Context & Language
16
+ */
17
+ export function useShopwareContext(): ShopwareContext {
18
+ const shopwareContext = inject<ShopwareContext | null>("shopware", null);
19
+
20
+ const apiClient = inject<ApiClient>("apiClient");
21
+
22
+ if (!shopwareContext || !apiClient) {
23
+ console.error("[Error][Shopware] API Client is not provided.");
24
+ throw new ContextError("Shopware or apiClient");
25
+ }
26
+
27
+ return {
28
+ apiClient,
29
+ devStorefrontUrl: shopwareContext.devStorefrontUrl,
30
+ };
31
+ }