@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,329 @@
1
+ import { defu } from "defu";
2
+ import { computed, inject, provide, ref } from "vue";
3
+ import type { ComputedRef, Ref } from "vue";
4
+ import { useDefaultOrderAssociations, useShopwareContext } from "#imports";
5
+ import type { Schemas } from "#shopware";
6
+
7
+ export type UseOrderDetailsReturn = {
8
+ /**
9
+ * {@link Schemas['Order']} object
10
+ */
11
+ order: ComputedRef<Schemas["Order"] | undefined | null>;
12
+ /**
13
+ * Order status (e.g. 'Open', 'Cancelled')
14
+ */
15
+ status: ComputedRef<string | undefined>;
16
+ /**
17
+ * Order status technical name (e.g. 'open', 'cancelled')
18
+ */
19
+ statusTechnicalName: ComputedRef<string | undefined>;
20
+ /**
21
+ * Order total price
22
+ */
23
+ total: ComputedRef<number | undefined>;
24
+ /**
25
+ * Order subtotal price for all items
26
+ */
27
+ subtotal: ComputedRef<number | undefined>;
28
+ /**
29
+ * Order shipping costs
30
+ */
31
+ shippingCosts: ComputedRef<number | undefined>;
32
+ /**
33
+ * Shipping address
34
+ */
35
+ shippingAddress: ComputedRef<Schemas["OrderAddress"] | undefined>;
36
+ /**
37
+ * Billing address
38
+ */
39
+ billingAddress: ComputedRef<Schemas["OrderAddress"] | undefined>;
40
+ /**
41
+ * Basic personal details
42
+ */
43
+ personalDetails: ComputedRef<{
44
+ email: string | undefined;
45
+ firstName: string | undefined;
46
+ lastName: string | undefined;
47
+ }>;
48
+ /**
49
+ * Payment URL for external payment methods (e.g. async payment in external payment gateway)
50
+ */
51
+ paymentUrl: Ref<null | string>;
52
+ /**
53
+ * Returns current selected shipping method for the order. Last element in delivery array.
54
+ */
55
+ shippingMethod: ComputedRef<Schemas["ShippingMethod"] | undefined | null>;
56
+ /**
57
+ * Returns current selected payment method for the order. Last element in transactions array.
58
+ */
59
+ paymentMethod: ComputedRef<Schemas["PaymentMethod"] | undefined | null>;
60
+ /**
61
+ * Get order object including additional associations.
62
+ * useDefaults describes what order object should look like.
63
+ */
64
+ loadOrderDetails(): Promise<Schemas["OrderRouteResponse"]>;
65
+ /**
66
+ * Handle payment for existing error.
67
+ *
68
+ * Pass custom success and error URLs (optionally).
69
+ */
70
+ handlePayment(
71
+ successUrl?: string,
72
+ errorUrl?: string,
73
+ paymentDetails?: unknown,
74
+ ): void;
75
+ /**
76
+ * Cancel an order.
77
+ *
78
+ * Action cannot be reverted.
79
+ */
80
+ cancel(): Promise<Schemas["StateMachineState"]>;
81
+ /**
82
+ * Changes the payment method for current cart.
83
+ * @param paymentMethodId - ID of the payment method to be set
84
+ * @returns
85
+ */
86
+ changePaymentMethod(
87
+ paymentMethodId: string,
88
+ ): Promise<Schemas["SuccessResponse"]>;
89
+ /**
90
+ * Get media content
91
+ *
92
+ * @param {string} downloadId
93
+ * @returns {Blob}
94
+ */
95
+ getMediaFile: (downloadId: string) => Promise<Blob>;
96
+ /**
97
+ * Get order documents
98
+ * @param {string} documentId
99
+ * @param {string} deepLinkCode
100
+ * @returns
101
+ */
102
+ getDocumentFile: (
103
+ documentId: string,
104
+ deepLinkCode: string,
105
+ ) => Promise<Schemas["Document"]>;
106
+ /**
107
+ * Check if order has documents
108
+ */
109
+ hasDocuments: ComputedRef<boolean>;
110
+ /**
111
+ * Get order documents
112
+ */
113
+ documents: ComputedRef<Schemas["Document"][]>;
114
+ /**
115
+ * Fetches all available payment methods
116
+ */
117
+ getPaymentMethods(): Promise<Schemas["PaymentMethod"][]>;
118
+
119
+ paymentChangeable: ComputedRef<boolean>;
120
+ };
121
+
122
+ /**
123
+ * Composable for managing an existing order.
124
+ * @public
125
+ * @category Customer & Account
126
+ */
127
+ export function useOrderDetails(
128
+ orderId: string,
129
+ associations?: Schemas["Criteria"]["associations"],
130
+ ): UseOrderDetailsReturn {
131
+ const { apiClient } = useShopwareContext();
132
+
133
+ const paymentChangeableList: Ref<{ [key: string]: boolean }> = ref({});
134
+ const _sharedOrder = inject<Ref<Schemas["Order"] | undefined>>(
135
+ "swOrderDetails",
136
+ ref(),
137
+ );
138
+ provide("swOrderDetails", _sharedOrder);
139
+
140
+ const orderAssociations = useDefaultOrderAssociations();
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
+ );
149
+
150
+ const shippingMethod = computed(() =>
151
+ _sharedOrder.value?.deliveries?.length
152
+ ? _sharedOrder.value.deliveries[_sharedOrder.value.deliveries.length - 1]
153
+ .shippingMethod
154
+ : undefined,
155
+ );
156
+
157
+ const paymentUrl = ref();
158
+
159
+ const personalDetails = computed(() => ({
160
+ email: _sharedOrder.value?.orderCustomer?.email,
161
+ firstName: _sharedOrder.value?.orderCustomer?.firstName,
162
+ lastName: _sharedOrder.value?.orderCustomer?.lastName,
163
+ }));
164
+ const billingAddress = computed(() =>
165
+ _sharedOrder.value?.addresses?.find(
166
+ ({ id }: { id: string }) => id === _sharedOrder.value?.billingAddressId,
167
+ ),
168
+ );
169
+ const shippingAddress = computed(
170
+ () => _sharedOrder.value?.deliveries?.[0]?.shippingOrderAddress,
171
+ );
172
+
173
+ const shippingCosts = computed(() => _sharedOrder.value?.shippingTotal);
174
+ const subtotal = computed(() => _sharedOrder.value?.price?.positionPrice);
175
+ const total = computed(() => _sharedOrder.value?.price?.totalPrice);
176
+ const status = computed(
177
+ () => _sharedOrder.value?.stateMachineState?.translated.name,
178
+ );
179
+ const statusTechnicalName = computed(
180
+ () => _sharedOrder.value?.stateMachineState?.technicalName,
181
+ );
182
+
183
+ async function loadOrderDetails() {
184
+ const mergedAssociations = defu(
185
+ orderAssociations,
186
+ associations ? associations : {},
187
+ );
188
+ const params = {
189
+ filter: [
190
+ {
191
+ type: "equals",
192
+ field: "id",
193
+ value: orderId,
194
+ },
195
+ ],
196
+ associations: mergedAssociations.associations,
197
+ checkPromotion: true,
198
+ } as Schemas["Criteria"];
199
+
200
+ const orderDetailsResponse = await apiClient.invoke(
201
+ "readOrder post /order",
202
+ {
203
+ body: params,
204
+ },
205
+ );
206
+ _sharedOrder.value =
207
+ orderDetailsResponse.data.orders?.elements?.[0] ?? null;
208
+ paymentChangeableList.value =
209
+ orderDetailsResponse.data.paymentChangeable ?? {};
210
+ return orderDetailsResponse.data;
211
+ }
212
+
213
+ async function handlePayment(finishUrl?: string, errorUrl?: string) {
214
+ const resp = await apiClient.invoke(
215
+ "handlePaymentMethod post /handle-payment",
216
+ {
217
+ body: {
218
+ orderId,
219
+ finishUrl,
220
+ errorUrl,
221
+ },
222
+ },
223
+ );
224
+
225
+ paymentUrl.value = resp.data.redirectUrl;
226
+ }
227
+
228
+ async function cancel() {
229
+ const resp = await apiClient.invoke(
230
+ "cancelOrder post /order/state/cancel",
231
+ {
232
+ body: {
233
+ orderId,
234
+ },
235
+ },
236
+ );
237
+ await loadOrderDetails();
238
+ return resp.data;
239
+ }
240
+ async function changePaymentMethod(paymentMethodId: string) {
241
+ const response = await apiClient.invoke(
242
+ "orderSetPayment post /order/payment",
243
+ {
244
+ body: {
245
+ orderId: orderId,
246
+ paymentMethodId: paymentMethodId,
247
+ },
248
+ },
249
+ );
250
+
251
+ await loadOrderDetails();
252
+ return response.data;
253
+ }
254
+
255
+ async function getMediaFile(downloadId: string) {
256
+ const response = await apiClient.invoke(
257
+ "orderDownloadFile get /order/download/{orderId}/{downloadId}",
258
+ {
259
+ accept: "application/octet-stream",
260
+ pathParams: {
261
+ orderId,
262
+ downloadId,
263
+ },
264
+ },
265
+ );
266
+
267
+ return response.data;
268
+ }
269
+
270
+ async function getDocumentFile(documentId: string, deepLinkCode: string) {
271
+ const response = await apiClient.invoke(
272
+ "download post /document/download/{documentId}/{deepLinkCode}",
273
+ {
274
+ pathParams: {
275
+ documentId,
276
+ deepLinkCode,
277
+ },
278
+ },
279
+ );
280
+
281
+ return response.data;
282
+ }
283
+
284
+ const hasDocuments = computed(() => !!_sharedOrder.value?.documents.length);
285
+ const documents = computed(() => _sharedOrder.value?.documents || []);
286
+
287
+ const paymentChangeable = computed(() => {
288
+ return Object.keys(paymentChangeableList.value).length
289
+ ? (paymentChangeableList.value as { [key: string]: boolean })[
290
+ orderId as string
291
+ ]
292
+ : false;
293
+ });
294
+
295
+ const getPaymentMethods = async () => {
296
+ const response = await apiClient.invoke(
297
+ "readPaymentMethod post /payment-method",
298
+ {
299
+ body: { onlyAvailable: true },
300
+ },
301
+ );
302
+ return response.data.elements || [];
303
+ };
304
+
305
+ return {
306
+ order: computed(() => _sharedOrder.value),
307
+ status,
308
+ statusTechnicalName,
309
+ total,
310
+ subtotal,
311
+ shippingCosts,
312
+ shippingAddress,
313
+ billingAddress,
314
+ personalDetails,
315
+ paymentUrl,
316
+ shippingMethod,
317
+ paymentMethod,
318
+ hasDocuments,
319
+ documents,
320
+ loadOrderDetails,
321
+ handlePayment,
322
+ cancel,
323
+ changePaymentMethod,
324
+ getMediaFile,
325
+ getDocumentFile,
326
+ paymentChangeable,
327
+ getPaymentMethods,
328
+ };
329
+ }
@@ -0,0 +1,80 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { computed } from "vue";
3
+ import type { ComputedRef } from "vue";
4
+ import type { Schemas } from "#shopware";
5
+ import { useSetup } from "../_test";
6
+ import Order from "../mocks/Order";
7
+ import { useOrderPayment } from "./useOrderPayment";
8
+
9
+ describe("useOrderPayment", () => {
10
+ it("should handle the order payment", async () => {
11
+ const { vm, injections } = useSetup(() =>
12
+ useOrderPayment(
13
+ computed(() => Order.orders.elements[0]) as unknown as ComputedRef<
14
+ Schemas["Order"]
15
+ >,
16
+ ),
17
+ );
18
+ injections.apiClient.invoke.mockResolvedValue({ data: {} });
19
+ await vm.handlePayment();
20
+
21
+ expect(injections.apiClient.invoke).toHaveBeenCalledWith(
22
+ expect.stringContaining("handlePaymentMethod"),
23
+ expect.objectContaining({
24
+ body: {
25
+ errorUrl: undefined,
26
+ finishUrl: undefined,
27
+ orderId: Order.orders.elements[0].id,
28
+ },
29
+ }),
30
+ );
31
+
32
+ expect(vm.activeTransaction).toEqual(
33
+ Order.orders.elements[0].transactions[0],
34
+ );
35
+
36
+ vm.changePaymentMethod("test");
37
+
38
+ expect(injections.apiClient.invoke).toHaveBeenCalledWith(
39
+ expect.stringContaining("orderSetPayment"),
40
+ expect.objectContaining({
41
+ body: {
42
+ orderId: "018c6832f1a1731db276839b3f251fc2",
43
+ paymentMethodId: "test",
44
+ },
45
+ }),
46
+ );
47
+ });
48
+
49
+ it("should not invoke API calls for empty order", async () => {
50
+ const { vm } = useSetup(() =>
51
+ useOrderPayment(
52
+ computed(() => null) as unknown as ComputedRef<Schemas["Order"]>,
53
+ ),
54
+ );
55
+ await expect(vm.changePaymentMethod("test")).resolves.toBeUndefined();
56
+ await expect(vm.handlePayment()).resolves.toBeUndefined();
57
+ });
58
+
59
+ it("should be a asynchronous payment", () => {
60
+ const { vm } = useSetup(() =>
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
+ },
71
+ },
72
+ ],
73
+ }),
74
+ ) as unknown as ComputedRef<Schemas["Order"]>,
75
+ ),
76
+ );
77
+
78
+ expect(vm.isAsynchronous).toBe(true);
79
+ });
80
+ });
@@ -0,0 +1,119 @@
1
+ import { computed, ref } from "vue";
2
+ import type { ComputedRef, Ref } from "vue";
3
+ import { useShopwareContext } from "#imports";
4
+ import type { Schemas } from "#shopware";
5
+
6
+ export type UseOrderPaymentReturn = {
7
+ /**
8
+ * If the payment can be done after the order is placed
9
+ */
10
+ isAsynchronous: ComputedRef<boolean | undefined>;
11
+ /**
12
+ * Active payment transaction
13
+ */
14
+ activeTransaction: ComputedRef<Schemas["OrderTransaction"] | undefined>;
15
+ /**
16
+ * Payment status
17
+ */
18
+ state: ComputedRef<Schemas["StateMachineState"] | null | undefined>;
19
+ paymentUrl: Ref<null | string>;
20
+ /**
21
+ * Payment method set for the order
22
+ */
23
+ paymentMethod: ComputedRef<Schemas["PaymentMethod"] | undefined | null>;
24
+
25
+ /**
26
+ * Invokes the payment process for the order in the backend
27
+ */
28
+ handlePayment(
29
+ /**
30
+ * URL to redirect after successful payment
31
+ */
32
+ successUrl?: string,
33
+ /**
34
+ * URL to redirect after failed payment
35
+ */
36
+ errorUrl?: string,
37
+ /**
38
+ * additional payment details to provide
39
+ */
40
+ paymentDetails?: unknown,
41
+ ): Promise<undefined | unknown>;
42
+ /**
43
+ * Change a payment method for the order
44
+ */
45
+ changePaymentMethod(
46
+ paymentMethodId: string,
47
+ ): Promise<Schemas["SuccessResponse"] | undefined>;
48
+ };
49
+
50
+ /**
51
+ * Composable for managing an existing order.
52
+ * @public
53
+ * @category Customer & Account
54
+ */
55
+ export function useOrderPayment(
56
+ order: ComputedRef<Schemas["Order"] | null | undefined>,
57
+ ): UseOrderPaymentReturn {
58
+ const { apiClient } = useShopwareContext();
59
+ const activeTransaction = computed(() =>
60
+ order.value?.transactions?.find((t) => t.paymentMethod?.active === true),
61
+ );
62
+ const paymentMethod = computed(() => activeTransaction.value?.paymentMethod);
63
+ const paymentUrl = ref();
64
+ const state = computed(() => activeTransaction.value?.stateMachineState);
65
+ const isAsynchronous = computed(
66
+ () =>
67
+ activeTransaction.value?.paymentMethod?.asynchronous &&
68
+ activeTransaction.value?.paymentMethod?.afterOrderEnabled,
69
+ );
70
+
71
+ async function handlePayment(
72
+ finishUrl?: string,
73
+ errorUrl?: string,
74
+ ): Promise<undefined | unknown> {
75
+ if (!order.value) {
76
+ return;
77
+ }
78
+ const resp = await apiClient.invoke(
79
+ "handlePaymentMethod post /handle-payment",
80
+ {
81
+ body: {
82
+ orderId: order.value.id,
83
+ errorUrl,
84
+ finishUrl,
85
+ },
86
+ },
87
+ );
88
+
89
+ paymentUrl.value = resp.data.redirectUrl;
90
+
91
+ return resp;
92
+ }
93
+
94
+ async function changePaymentMethod(paymentMethodId: string) {
95
+ if (!order.value) {
96
+ return;
97
+ }
98
+ const response = await apiClient.invoke(
99
+ "orderSetPayment post /order/payment",
100
+ {
101
+ body: {
102
+ orderId: order.value.id,
103
+ paymentMethodId,
104
+ },
105
+ },
106
+ );
107
+ return response.data;
108
+ }
109
+
110
+ return {
111
+ isAsynchronous,
112
+ activeTransaction,
113
+ state,
114
+ paymentUrl,
115
+ paymentMethod,
116
+ handlePayment,
117
+ changePaymentMethod,
118
+ };
119
+ }
@@ -0,0 +1,97 @@
1
+ import { beforeEach, describe, expect, it, vi } from "vitest";
2
+ import { ref } from "vue";
3
+ import { usePrice, useSessionContext } from "#imports";
4
+ import { useSetup } from "../_test";
5
+ const currentNavigator = global.navigator;
6
+
7
+ vi.mock("../useSessionContext/useSessionContext.ts");
8
+ const sessionContext = ref();
9
+
10
+ beforeEach(() => {
11
+ vi.clearAllMocks();
12
+ vi.mocked(useSessionContext).mockReturnValue({
13
+ sessionContext,
14
+ } as unknown as ReturnType<typeof useSessionContext>);
15
+ });
16
+
17
+ describe("usePrice", () => {
18
+ it("should be defined", () => {
19
+ expect(usePrice).toBeDefined();
20
+ });
21
+
22
+ it("use default locale if locale is not provided", () => {
23
+ vi.spyOn(global, "navigator", "get").mockImplementation(
24
+ () => ({}) as Navigator,
25
+ );
26
+ const { vm } = useSetup(usePrice);
27
+ expect(vm.getFormattedPrice(2.55)).toMatchInlineSnapshot('"2.55"');
28
+ vm.update({
29
+ currencyCode: "USD",
30
+ localeCode: undefined,
31
+ });
32
+
33
+ expect(vm.getFormattedPrice(2.55)).toMatchInlineSnapshot('"$2.55"');
34
+ });
35
+
36
+ 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);
42
+ vm.update({
43
+ currencyCode: "USD",
44
+ localeCode: undefined,
45
+ });
46
+
47
+ expect(vm.getFormattedPrice(2.55)).toMatchInlineSnapshot('"$2.55"');
48
+ });
49
+
50
+ it("should init price object", () => {
51
+ const { vm } = useSetup(() =>
52
+ usePrice({
53
+ localeCode: "en-US",
54
+ currencyCode: "USD",
55
+ }),
56
+ );
57
+
58
+ expect(vm.getFormattedPrice("2")).toBe("$2.00");
59
+ });
60
+
61
+ it("should update config", async () => {
62
+ const { vm } = useSetup(usePrice);
63
+
64
+ await vm.update({
65
+ localeCode: "de-DE",
66
+ currencyCode: "EUR",
67
+ });
68
+ expect(vm.getFormattedPrice(4.1)).toMatchInlineSnapshot('"4,10 €"');
69
+ });
70
+
71
+ it("should return price with current locale", async () => {
72
+ const { vm } = useSetup(usePrice);
73
+
74
+ await vm.update({
75
+ currencyCode: "USD",
76
+ // @ts-expect-error string expected here
77
+ currencyLocale: undefined,
78
+ });
79
+ expect(vm.getFormattedPrice(2.55)).toMatchInlineSnapshot('"2,55 $"');
80
+ });
81
+
82
+ it("getFormattedPrice", () => {
83
+ const { vm } = useSetup(usePrice);
84
+ expect(vm.getFormattedPrice(undefined)).toBe("");
85
+ });
86
+
87
+ it("watch currency change", async () => {
88
+ const { vm } = useSetup(usePrice);
89
+ sessionContext.value = {
90
+ currency: {
91
+ isoCode: "PLN",
92
+ },
93
+ };
94
+ await vm.$nextTick();
95
+ expect(vm.currencyCode).toBe("PLN");
96
+ });
97
+ });