@shopbite-de/storefront 2.6.1 → 2.7.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 (469) hide show
  1. package/.env.example +13 -0
  2. package/.github/workflows/ci.yaml +2 -0
  3. package/CLAUDE.md +54 -30
  4. package/GLOSSARY.md +327 -0
  5. package/README.md +5 -6
  6. package/app/app.vue +50 -40
  7. package/app/components/Address/Card.vue +2 -2
  8. package/app/components/Address/Detail.vue +17 -45
  9. package/app/components/Address/Form.vue +38 -26
  10. package/app/components/BranchSwitch.vue +40 -0
  11. package/app/components/Cart/Bar.vue +9 -9
  12. package/app/components/Cart/Item.vue +27 -36
  13. package/app/components/Cart/QuickView.vue +17 -16
  14. package/app/components/Cart/Upsell.vue +19 -27
  15. package/app/components/Category/Breadcrumb.vue +3 -8
  16. package/app/components/Category/FilterGroup.vue +6 -6
  17. package/app/components/Category/Listing.vue +44 -66
  18. package/app/components/Checkout/DeliveryTimeSelect.vue +21 -48
  19. package/app/components/Checkout/OrderMessage.vue +29 -0
  20. package/app/components/Checkout/OrdererAddress.vue +40 -0
  21. package/app/components/Checkout/PaymentAndDelivery.vue +40 -35
  22. package/app/components/Checkout/Summary.vue +89 -74
  23. package/app/components/Checkout/VoucherInput.vue +8 -8
  24. package/app/components/Contact/Form.vue +97 -13
  25. package/app/components/Footer.vue +2 -2
  26. package/app/components/Header.vue +9 -9
  27. package/app/components/Home/Categories.vue +13 -17
  28. package/app/components/Home/Facts.vue +6 -4
  29. package/app/components/Home/Hero.vue +1 -1
  30. package/app/components/Home/Highlights.vue +8 -8
  31. package/app/components/Home/Restaurant.vue +2 -2
  32. package/app/components/Menu/BonCard.vue +21 -37
  33. package/app/components/Menu/CartPanel.vue +2 -2
  34. package/app/components/Menu/CategoryIndex.vue +8 -12
  35. package/app/components/Menu/OrderMode.vue +2 -2
  36. package/app/components/Menu/SectionHeader.vue +6 -10
  37. package/app/components/Navigation/MobileTop.vue +12 -20
  38. package/app/components/Order/Confirmation.vue +10 -10
  39. package/app/components/Order/Detail.vue +47 -49
  40. package/app/components/Product/Configurator.vue +46 -30
  41. package/app/components/Product/CrossSelling.vue +56 -71
  42. package/app/components/Product/DeselectIngredient.vue +10 -11
  43. package/app/components/Product/Detail.vue +62 -55
  44. package/app/components/Product/FoodLabels.vue +4 -9
  45. package/app/components/Product/QuickView.vue +22 -30
  46. package/app/components/User/Detail.vue +20 -43
  47. package/app/components/User/LoginForm.vue +11 -17
  48. package/app/components/User/RegistrationForm.vue +3 -3
  49. package/app/components/Wishlist.vue +99 -106
  50. package/app/components/WishlistSaveButton.vue +17 -9
  51. package/app/composables/useAccountAddresses.ts +89 -0
  52. package/app/composables/useAccountOrders.ts +35 -0
  53. package/app/composables/useAddToCart.ts +63 -139
  54. package/app/composables/useCartData.ts +55 -0
  55. package/app/composables/useCartMutations.ts +93 -85
  56. package/app/composables/useCartUpsell.ts +27 -71
  57. package/app/composables/useCategoryListing.ts +36 -59
  58. package/app/composables/useCategorySeo.ts +11 -16
  59. package/app/composables/useCheckoutMethodGuard.ts +22 -46
  60. package/app/composables/useCheckoutMethods.ts +89 -0
  61. package/app/composables/useCheckoutOrderMessage.ts +19 -0
  62. package/app/composables/useCheckoutOrderer.ts +69 -0
  63. package/app/composables/useCommercePrice.ts +46 -9
  64. package/app/composables/useContactForm.ts +25 -32
  65. package/app/composables/useCustomer.ts +169 -0
  66. package/app/composables/useDeliveryTime.ts +112 -122
  67. package/app/composables/useHolidays.ts +12 -62
  68. package/app/composables/useHomeMenuCategories.ts +5 -5
  69. package/app/composables/useListingSearch.ts +9 -8
  70. package/app/composables/useLiveShopData.ts +15 -9
  71. package/app/composables/useMenuRootId.ts +3 -6
  72. package/app/composables/useMenuSection.ts +14 -0
  73. package/app/composables/useMenuSectionSchema.ts +23 -30
  74. package/app/composables/useNavigation.ts +24 -29
  75. package/app/composables/useOpeningHours.ts +21 -0
  76. package/app/composables/useOpeningHoursData.ts +9 -9
  77. package/app/composables/useOrder.ts +37 -0
  78. package/app/composables/useOrderMode.ts +18 -16
  79. package/app/composables/usePlaceOrder.ts +37 -0
  80. package/app/composables/useProductCartQuantity.ts +6 -6
  81. package/app/composables/useProductDetail.ts +28 -53
  82. package/app/composables/useProductEvents.ts +6 -5
  83. package/app/composables/useProductQuickView.ts +35 -68
  84. package/app/composables/useRegistrationForm.ts +85 -34
  85. package/app/composables/useRestaurantSchema.ts +7 -7
  86. package/app/composables/useSearchTracking.ts +6 -6
  87. package/app/composables/useSectionRoute.ts +48 -0
  88. package/app/composables/useServiceSchedule.ts +23 -0
  89. package/app/composables/useShippingLeadTime.ts +8 -6
  90. package/app/composables/useShippingMethodChoice.ts +13 -23
  91. package/app/composables/useShippingMethods.ts +31 -0
  92. package/app/composables/useShopConfig.ts +60 -0
  93. package/app/composables/useShopData.ts +20 -0
  94. package/app/composables/useSortingSelection.ts +5 -8
  95. package/app/composables/useStoreStatus.ts +13 -37
  96. package/app/composables/useTopSellers.ts +3 -3
  97. package/app/composables/useTrackEvent.ts +29 -24
  98. package/app/composables/useVoucherCode.ts +47 -12
  99. package/app/composables/useWishlistEntries.ts +233 -177
  100. package/app/error.vue +3 -2
  101. package/app/layouts/account.vue +4 -3
  102. package/app/pages/[...all].vue +6 -16
  103. package/app/pages/account/recover/password/index.vue +6 -14
  104. package/app/pages/anmelden.vue +1 -1
  105. package/app/pages/bestellung/[id]/erfolg.vue +3 -3
  106. package/app/pages/bestellung/[id]/fehler.vue +18 -29
  107. package/app/pages/bestellung/kasse.vue +24 -7
  108. package/app/pages/konto/adressen.vue +95 -40
  109. package/app/pages/konto/bestellungen.vue +10 -13
  110. package/app/pages/konto/index.vue +12 -2
  111. package/app/pages/konto/profil.vue +241 -42
  112. package/app/pages/passwort-vergessen.vue +5 -10
  113. package/app/pages/registrierung/bestaetigen.vue +9 -23
  114. package/app/pages/registrierung/index.vue +19 -11
  115. package/app/pages/suche.vue +29 -29
  116. package/app/plugins/shopware-layer-offline.ts +38 -0
  117. package/app/plugins/visitor-has-session.server.ts +19 -0
  118. package/app/utils/accountMessages.ts +74 -0
  119. package/app/utils/accountReads.ts +34 -0
  120. package/app/utils/bffWrite.ts +89 -0
  121. package/app/utils/dish.ts +121 -0
  122. package/app/utils/leadTime.ts +25 -29
  123. package/app/utils/media.ts +11 -17
  124. package/app/utils/menuGroups.ts +22 -35
  125. package/app/utils/money.ts +41 -0
  126. package/app/utils/openingHours.ts +30 -30
  127. package/app/utils/orderStatus.ts +17 -0
  128. package/app/utils/productUrl.ts +14 -31
  129. package/app/utils/restaurantTime.ts +326 -0
  130. package/app/utils/schema.ts +39 -42
  131. package/app/utils/wishlist.ts +139 -0
  132. package/docs/adr/0001-backend-agnostic-storefront.md +409 -0
  133. package/eslint.config.mjs +42 -2
  134. package/nuxt.config.ts +28 -0
  135. package/package.json +1 -1
  136. package/server/adapters/memory/cart.ts +370 -0
  137. package/server/adapters/memory/catalog.ts +367 -0
  138. package/server/adapters/memory/contact.ts +89 -0
  139. package/server/adapters/memory/customer.ts +458 -0
  140. package/server/adapters/memory/demo-menu.json +1190 -0
  141. package/server/adapters/memory/demoImages.ts +13 -0
  142. package/server/adapters/memory/demoMenu.ts +234 -0
  143. package/server/adapters/memory/demoNavigation.ts +71 -0
  144. package/server/adapters/memory/index.ts +122 -0
  145. package/server/adapters/memory/navigation.ts +168 -0
  146. package/server/adapters/memory/ordering.ts +379 -0
  147. package/server/adapters/memory/seed.ts +136 -0
  148. package/server/adapters/memory/wishlist.ts +166 -0
  149. package/server/adapters/notImplemented.ts +67 -0
  150. package/server/adapters/registry.ts +32 -0
  151. package/server/adapters/runtimeConfig.ts +14 -0
  152. package/server/adapters/shopware/cart.ts +792 -0
  153. package/server/adapters/shopware/catalog.ts +850 -0
  154. package/server/adapters/shopware/checkout.ts +138 -0
  155. package/server/adapters/shopware/contact.ts +255 -0
  156. package/server/adapters/shopware/customer.ts +460 -0
  157. package/server/adapters/shopware/index.ts +165 -0
  158. package/server/adapters/shopware/menuRoot.ts +24 -0
  159. package/server/adapters/shopware/navigation.ts +426 -0
  160. package/server/adapters/shopware/ordering.ts +1185 -0
  161. package/server/adapters/shopware/request.ts +67 -0
  162. package/server/adapters/shopware/shop.ts +249 -0
  163. package/server/adapters/shopware/storeApi.ts +62 -0
  164. package/server/adapters/shopware/wishlist.ts +473 -0
  165. package/server/api/__sitemap__/urls.get.ts +10 -38
  166. package/server/api/account/addresses/[addressId]/default.post.ts +13 -0
  167. package/server/api/account/addresses/[addressId].delete.ts +14 -0
  168. package/server/api/account/addresses/[addressId].patch.ts +15 -0
  169. package/server/api/account/addresses/index.get.ts +6 -0
  170. package/server/api/account/addresses/index.post.ts +9 -0
  171. package/server/api/account/email.post.ts +10 -0
  172. package/server/api/account/index.delete.ts +11 -0
  173. package/server/api/account/index.get.ts +9 -0
  174. package/server/api/account/login.post.ts +14 -0
  175. package/server/api/account/logout.post.ts +11 -0
  176. package/server/api/account/orders.get.ts +13 -0
  177. package/server/api/account/password-reset/confirm.post.ts +13 -0
  178. package/server/api/account/password-reset.post.ts +16 -0
  179. package/server/api/account/password.post.ts +18 -0
  180. package/server/api/account/profile.patch.ts +6 -0
  181. package/server/api/account/register/confirm.post.ts +13 -0
  182. package/server/api/account/register.post.ts +15 -0
  183. package/server/api/breadcrumb/[sectionId].get.ts +33 -0
  184. package/server/api/cart/index.get.ts +4 -0
  185. package/server/api/cart/lines/[lineId].delete.ts +6 -0
  186. package/server/api/cart/lines/[lineId].patch.ts +10 -0
  187. package/server/api/cart/lines.post.ts +10 -0
  188. package/server/api/cart/vouchers/[code].delete.ts +9 -0
  189. package/server/api/cart/vouchers.post.ts +12 -0
  190. package/server/api/checkout/guest.post.ts +13 -0
  191. package/server/api/checkout/orderer/addresses/[addressId].patch.ts +16 -0
  192. package/server/api/checkout/orderer.get.ts +10 -0
  193. package/server/api/checkout/orders.post.ts +60 -0
  194. package/server/api/checkout/payment-methods.get.ts +9 -0
  195. package/server/api/checkout/selection.get.ts +10 -0
  196. package/server/api/checkout/selection.post.ts +14 -0
  197. package/server/api/checkout/shipping-methods.get.ts +9 -0
  198. package/server/api/contact/form.get.ts +13 -0
  199. package/server/api/contact/index.post.ts +24 -0
  200. package/server/api/listing/[sectionId].get.ts +33 -0
  201. package/server/api/menu/dishes/[dishId]/variant.get.ts +29 -0
  202. package/server/api/menu/dishes/[dishId].get.ts +19 -0
  203. package/server/api/menu/dishes/index.get.ts +26 -0
  204. package/server/api/menu/media/[name].get.ts +18 -0
  205. package/server/api/menu/root.get.ts +12 -0
  206. package/server/api/menu/sections/[sectionId].get.ts +18 -0
  207. package/server/api/menu/upsell.get.ts +12 -0
  208. package/server/api/navigation/[kind].get.ts +75 -0
  209. package/server/api/orders/[orderId]/payment.post.ts +24 -0
  210. package/server/api/orders/[orderId].get.ts +13 -0
  211. package/server/api/payment-methods.get.ts +11 -15
  212. package/server/api/resolve-path.get.ts +20 -0
  213. package/server/api/search.get.ts +16 -80
  214. package/server/api/session.post.ts +18 -0
  215. package/server/api/shop/branches.get.ts +9 -0
  216. package/server/api/shop/config.get.ts +9 -0
  217. package/server/api/shop/holidays.get.ts +9 -0
  218. package/server/api/shop/opening-hours.get.ts +9 -0
  219. package/server/api/top-sellers.get.ts +14 -50
  220. package/server/api/wishlist/entries/[entryId].delete.ts +8 -0
  221. package/server/api/wishlist/entries.post.ts +13 -0
  222. package/server/api/wishlist/index.get.ts +13 -0
  223. package/server/api/wishlist/merge.post.ts +12 -0
  224. package/server/plugins/visitor-session.ts +35 -0
  225. package/server/ports/CartPort.ts +48 -0
  226. package/server/ports/CatalogPort.ts +66 -0
  227. package/server/ports/CheckoutPort.ts +128 -0
  228. package/server/ports/ContactPort.ts +38 -0
  229. package/server/ports/CustomerPort.ts +154 -0
  230. package/server/ports/NavigationPort.ts +58 -0
  231. package/server/ports/OrderPort.ts +31 -0
  232. package/server/ports/ShopPort.ts +29 -0
  233. package/server/ports/WishlistPort.ts +47 -0
  234. package/server/ports/index.ts +42 -0
  235. package/server/ports/session.ts +22 -0
  236. package/server/routes/llms.txt.ts +28 -154
  237. package/server/session/forwardedFor.ts +24 -0
  238. package/server/session/sameOrigin.ts +47 -0
  239. package/server/session/seal.ts +147 -0
  240. package/server/session/visitorSession.ts +288 -0
  241. package/server/utils/accountRoutes.ts +173 -0
  242. package/server/utils/backend.ts +21 -0
  243. package/server/utils/backoff.ts +18 -5
  244. package/server/utils/cacheKeys.ts +11 -0
  245. package/server/utils/cachePurge.ts +47 -27
  246. package/server/utils/cartRoutes.ts +124 -0
  247. package/server/utils/catalogData.ts +24 -0
  248. package/server/utils/checkoutRoutes.ts +326 -0
  249. package/server/utils/contactRoutes.ts +86 -0
  250. package/server/utils/domainHttp.ts +73 -0
  251. package/server/utils/listingParams.ts +49 -20
  252. package/server/utils/llmsTxt.ts +64 -19
  253. package/server/utils/navigationData.ts +14 -0
  254. package/server/utils/orderPlacement.ts +322 -0
  255. package/server/utils/outageBreaker.ts +126 -0
  256. package/server/utils/pathRoutes.ts +160 -0
  257. package/server/utils/requestBody.ts +43 -0
  258. package/server/utils/shopData.ts +132 -0
  259. package/server/utils/sitemap.ts +14 -36
  260. package/server/utils/storeApi.ts +71 -23
  261. package/server/utils/visitorSession.ts +209 -0
  262. package/server/utils/wishlistRoutes.ts +55 -0
  263. package/shared/domain/customer/index.ts +2 -0
  264. package/shared/domain/customer/types.ts +88 -0
  265. package/shared/domain/discoverability/index.ts +4 -0
  266. package/shared/domain/discoverability/paths.ts +93 -0
  267. package/shared/domain/discoverability/route.ts +32 -0
  268. package/shared/domain/discoverability/types.ts +75 -0
  269. package/shared/domain/index.ts +11 -0
  270. package/shared/domain/kernel/calendar.ts +88 -0
  271. package/shared/domain/kernel/errors.ts +100 -0
  272. package/shared/domain/kernel/freeze.ts +13 -0
  273. package/shared/domain/kernel/ids.ts +6 -0
  274. package/shared/domain/kernel/index.ts +8 -0
  275. package/shared/domain/kernel/media.ts +17 -0
  276. package/shared/domain/kernel/money.ts +104 -0
  277. package/shared/domain/kernel/timeOfDay.ts +39 -0
  278. package/shared/domain/menu/dishConfiguration.ts +72 -0
  279. package/shared/domain/menu/index.ts +3 -0
  280. package/shared/domain/menu/types.ts +185 -0
  281. package/shared/domain/ordering/index.ts +3 -0
  282. package/shared/domain/ordering/time.ts +114 -0
  283. package/shared/domain/ordering/types.ts +195 -0
  284. package/shared/domain/restaurant/holiday.ts +38 -0
  285. package/shared/domain/restaurant/index.ts +4 -0
  286. package/shared/domain/restaurant/openingInterval.ts +97 -0
  287. package/shared/domain/restaurant/types.ts +75 -0
  288. package/test/a11y/presets.test.ts +49 -31
  289. package/test/contract/cart.contract.ts +592 -0
  290. package/test/contract/cart.spec.ts +5 -0
  291. package/test/contract/cartFixtures.ts +573 -0
  292. package/test/contract/catalog.contract.ts +714 -0
  293. package/test/contract/catalog.spec.ts +5 -0
  294. package/test/contract/catalogFixtures.ts +572 -0
  295. package/test/contract/checkout.contract.ts +123 -0
  296. package/test/contract/checkout.spec.ts +5 -0
  297. package/test/contract/contact.contract.ts +149 -0
  298. package/test/contract/contact.spec.ts +4 -0
  299. package/test/contract/contactFixtures.ts +148 -0
  300. package/test/contract/customer.contract.ts +831 -0
  301. package/test/contract/customer.spec.ts +4 -0
  302. package/test/contract/customerFixtures.ts +468 -0
  303. package/test/contract/fixtures.ts +260 -0
  304. package/test/contract/harness.ts +45 -0
  305. package/test/contract/navigation.contract.ts +336 -0
  306. package/test/contract/navigation.spec.ts +5 -0
  307. package/test/contract/navigationFixtures.ts +311 -0
  308. package/test/contract/ordering.contract.ts +655 -0
  309. package/test/contract/ordering.spec.ts +4 -0
  310. package/test/contract/orderingFixtures.ts +498 -0
  311. package/test/contract/shop.contract.ts +164 -0
  312. package/test/contract/shop.spec.ts +5 -0
  313. package/test/contract/wishlist.contract.ts +375 -0
  314. package/test/contract/wishlist.spec.ts +4 -0
  315. package/test/contract/wishlistFixtures.ts +199 -0
  316. package/test/nuxt/AccountPagesPreset.test.ts +320 -83
  317. package/test/nuxt/AuthPagesPreset.test.ts +17 -24
  318. package/test/nuxt/CartBar.test.ts +12 -8
  319. package/test/nuxt/CartCheckoutPreset.test.ts +36 -33
  320. package/test/nuxt/CartItem.test.ts +39 -20
  321. package/test/nuxt/CartQuickView.test.ts +106 -0
  322. package/test/nuxt/CartUpsell.test.ts +37 -39
  323. package/test/nuxt/CategoryBreadcrumb.test.ts +26 -0
  324. package/test/nuxt/CheckoutFormsPreset.test.ts +92 -13
  325. package/test/nuxt/CheckoutOnePage.test.ts +28 -21
  326. package/test/nuxt/CheckoutPageMessage.test.ts +31 -0
  327. package/test/nuxt/CheckoutSummary.test.ts +163 -48
  328. package/test/nuxt/CheckoutVoucherInput.test.ts +77 -80
  329. package/test/nuxt/ContactFormPreset.test.ts +97 -36
  330. package/test/nuxt/DeliveryTimeSelect.test.ts +72 -45
  331. package/test/nuxt/FooterStoreStatus.test.ts +2 -2
  332. package/test/nuxt/HeaderFooterPreset.test.ts +11 -19
  333. package/test/nuxt/HomeCategories.test.ts +47 -0
  334. package/test/nuxt/HomeLeadTimes.test.ts +3 -3
  335. package/test/nuxt/MenuBonCard.test.ts +45 -32
  336. package/test/nuxt/NavigationMobileTop.test.ts +30 -28
  337. package/test/nuxt/OrderPagesPreset.test.ts +83 -52
  338. package/test/nuxt/PaymentAndDelivery.test.ts +25 -26
  339. package/test/nuxt/ProductConfigurator.test.ts +81 -0
  340. package/test/nuxt/ProductCrossSelling.test.ts +23 -20
  341. package/test/nuxt/ProductDeselectIngredient.test.ts +6 -9
  342. package/test/nuxt/ProductFoodLabels.test.ts +7 -24
  343. package/test/nuxt/ProductSheetPreset.test.ts +24 -24
  344. package/test/nuxt/RegisterConfirmPage.test.ts +26 -45
  345. package/test/nuxt/RegistrationForm.test.ts +57 -53
  346. package/test/nuxt/RegistrationPage.test.ts +37 -0
  347. package/test/nuxt/WishlistPage.test.ts +119 -43
  348. package/test/nuxt/WishlistSaveButton.test.ts +39 -12
  349. package/test/nuxt/accountSwitch.test.ts +106 -0
  350. package/test/nuxt/bffWrite.test.ts +41 -0
  351. package/test/nuxt/liveShopData.test.ts +36 -68
  352. package/test/nuxt/shopwareLayerOffline.test.ts +32 -0
  353. package/test/nuxt/useAddToCart.test.ts +116 -174
  354. package/test/nuxt/useCartMutations.test.ts +165 -113
  355. package/test/nuxt/useCartUpsell.test.ts +36 -63
  356. package/test/nuxt/useCategoryListing.test.ts +75 -118
  357. package/test/nuxt/useCheckoutMethodGuard.test.ts +54 -105
  358. package/test/nuxt/useCustomer.test.ts +127 -0
  359. package/test/nuxt/useDeliveryTime.test.ts +169 -157
  360. package/test/nuxt/useNavigation.test.ts +81 -0
  361. package/test/nuxt/useOpeningHoursData.test.ts +18 -18
  362. package/test/nuxt/useOrder.test.ts +38 -0
  363. package/test/nuxt/usePlaceOrder.test.ts +88 -0
  364. package/test/nuxt/useSearchTracking.test.ts +2 -2
  365. package/test/nuxt/useSectionRoute.test.ts +86 -0
  366. package/test/nuxt/useShippingLeadTime.test.ts +17 -17
  367. package/test/nuxt/useShippingMethodChoice.test.ts +22 -22
  368. package/test/nuxt/useShippingMethods.test.ts +71 -0
  369. package/test/nuxt/useShopConfig.test.ts +64 -0
  370. package/test/nuxt/useStoreStatus.test.ts +34 -50
  371. package/test/nuxt/useTopSellers.test.ts +6 -5
  372. package/test/nuxt/useTrackEvent.test.ts +68 -6
  373. package/test/nuxt/useWishlistEntries.test.ts +392 -128
  374. package/test/support/cart.ts +43 -0
  375. package/test/support/dishes.ts +116 -0
  376. package/test/support/navigation.ts +17 -0
  377. package/test/unit/accountMessages.spec.ts +53 -0
  378. package/test/unit/accountRoutes.spec.ts +637 -0
  379. package/test/unit/adapters/memoryCustomer.spec.ts +67 -0
  380. package/test/unit/adapters/memoryDemoMenu.spec.ts +174 -0
  381. package/test/unit/adapters/registry.spec.ts +100 -0
  382. package/test/unit/adapters/shopwareCart.spec.ts +636 -0
  383. package/test/unit/adapters/shopwareCatalog.spec.ts +486 -0
  384. package/test/unit/adapters/shopwareCheckout.spec.ts +197 -0
  385. package/test/unit/adapters/shopwareContact.spec.ts +296 -0
  386. package/test/unit/adapters/shopwareCustomer.spec.ts +256 -0
  387. package/test/unit/adapters/shopwareNavigation.spec.ts +594 -0
  388. package/test/unit/adapters/shopwareOrdering.spec.ts +620 -0
  389. package/test/unit/adapters/shopwareShop.spec.ts +259 -0
  390. package/test/unit/adapters/shopwareWishlist.spec.ts +306 -0
  391. package/test/unit/adapters/useBackend.spec.ts +41 -0
  392. package/test/unit/backoff.spec.ts +47 -0
  393. package/test/unit/boundedCache.spec.ts +59 -59
  394. package/test/unit/cacheKeys.spec.ts +44 -0
  395. package/test/unit/cachePurge.spec.ts +44 -19
  396. package/test/unit/cartRoutes.spec.ts +567 -0
  397. package/test/unit/catalogRoutes.spec.ts +287 -0
  398. package/test/unit/checkoutRoutes.spec.ts +545 -0
  399. package/test/unit/dish.spec.ts +128 -0
  400. package/test/unit/domain/discoverability.spec.ts +154 -0
  401. package/test/unit/domain/dishConfiguration.spec.ts +85 -0
  402. package/test/unit/domain/money.spec.ts +102 -0
  403. package/test/unit/domain/time.spec.ts +336 -0
  404. package/test/unit/domainHttp.spec.ts +74 -0
  405. package/test/unit/forwardedFor.spec.ts +24 -0
  406. package/test/unit/layoutCacheRoutes.spec.ts +47 -471
  407. package/test/unit/leadTime.spec.ts +28 -23
  408. package/test/unit/llmsTxt.spec.ts +120 -9
  409. package/test/unit/media.spec.ts +25 -26
  410. package/test/unit/menuGroups.spec.ts +31 -21
  411. package/test/unit/navigationRoutes.spec.ts +648 -0
  412. package/test/unit/nitroStubs.ts +6 -1
  413. package/test/unit/openingHours.spec.ts +57 -34
  414. package/test/unit/orderPlacement.spec.ts +362 -0
  415. package/test/unit/outageBreaker.spec.ts +213 -0
  416. package/test/unit/productUrl.spec.ts +10 -28
  417. package/test/unit/requestBody.spec.ts +56 -0
  418. package/test/unit/restaurantTime.spec.ts +295 -0
  419. package/test/unit/schema.spec.ts +58 -26
  420. package/test/unit/session/sameOrigin.spec.ts +76 -0
  421. package/test/unit/session/seal.spec.ts +128 -0
  422. package/test/unit/session/visitorSession.spec.ts +439 -0
  423. package/test/unit/shopRoutes.spec.ts +257 -0
  424. package/test/unit/sitemap.spec.ts +11 -47
  425. package/test/unit/storeApiForVisitor.spec.ts +109 -0
  426. package/test/unit/useCategorySeo.spec.ts +57 -31
  427. package/test/unit/wishlistContactRoutes.spec.ts +607 -0
  428. package/vitest.config.ts +5 -1
  429. package/app/components/SalesChannelSwitch.vue +0 -73
  430. package/app/composables/useBusinessHours.ts +0 -192
  431. package/app/composables/useCategoryById.ts +0 -10
  432. package/app/composables/useNavigationSearch.ts +0 -45
  433. package/app/composables/useProductConfigurator.ts +0 -70
  434. package/app/composables/useProductCrossSelling.ts +0 -42
  435. package/app/composables/useProductVariants.ts +0 -61
  436. package/app/composables/useProductVariantsZwei.ts +0 -62
  437. package/app/composables/useSeoUrlRoute.ts +0 -124
  438. package/app/composables/useShopBiteConfig.ts +0 -69
  439. package/app/composables/useSyncWishlist.ts +0 -119
  440. package/app/types/Association.d.ts +0 -14
  441. package/app/utils/product.ts +0 -139
  442. package/app/utils/seoPath.ts +0 -68
  443. package/app/utils/time.ts +0 -20
  444. package/server/api/breadcrumb/[categoryId].get.ts +0 -31
  445. package/server/api/category/[categoryId].get.ts +0 -37
  446. package/server/api/listing/[categoryId].get.ts +0 -102
  447. package/server/api/navigation/[type].get.ts +0 -97
  448. package/server/api/product/[productId]/cross-selling.get.ts +0 -26
  449. package/server/api/product/[productId].get.ts +0 -76
  450. package/server/api/product/variant.get.ts +0 -98
  451. package/server/api/seo-url/index.get.ts +0 -17
  452. package/server/api/seo-url/known.get.ts +0 -33
  453. package/server/api/shopbite/business-hours.get.ts +0 -22
  454. package/server/api/shopbite/config.get.ts +0 -6
  455. package/server/api/shopbite/holidays.get.ts +0 -20
  456. package/server/utils/menuRoot.ts +0 -31
  457. package/server/utils/seoPaths.ts +0 -130
  458. package/server/utils/seoUrlCache.ts +0 -98
  459. package/server/utils/shopBiteConfig.ts +0 -30
  460. package/test/nuxt/useBusinessHours.test.ts +0 -106
  461. package/test/nuxt/useProductConfigurator.test.ts +0 -87
  462. package/test/nuxt/useProductVariants.test.ts +0 -95
  463. package/test/nuxt/useProductVariantsZwei.test.ts +0 -52
  464. package/test/nuxt/useSeoUrlRoute.test.ts +0 -176
  465. package/test/nuxt/useShopBiteConfig.test.ts +0 -131
  466. package/test/nuxt/useSyncWishlist.test.ts +0 -85
  467. package/test/unit/product.spec.ts +0 -160
  468. package/test/unit/seoPath.spec.ts +0 -161
  469. package/test/unit/seoPaths.spec.ts +0 -117
@@ -0,0 +1,1185 @@
1
+ import {
2
+ addDays,
3
+ deepFreeze,
4
+ dishConfiguration,
5
+ DomainError,
6
+ formatTimeOfDay,
7
+ isDomainError,
8
+ moneyFromDecimal,
9
+ wishedTime,
10
+ zonedDateTime,
11
+ type Address,
12
+ type AddressInput,
13
+ type CheckoutSelection,
14
+ type CurrencyCode,
15
+ type Customer,
16
+ type DomainErrorCode,
17
+ type Fulfillment,
18
+ type GuestDetails,
19
+ type Id,
20
+ type Order,
21
+ type Orderer,
22
+ type OrderLine,
23
+ type OrderStatus,
24
+ type PaymentMethod,
25
+ type PaymentStatus,
26
+ type Salutation,
27
+ type TimeZone,
28
+ type WishedTime,
29
+ } from "../../../shared/domain";
30
+ import type {
31
+ BackendSession,
32
+ CheckoutPort,
33
+ OrderPort,
34
+ PlaceOrderCommand,
35
+ } from "../../ports";
36
+ import {
37
+ deadline,
38
+ keptFor,
39
+ LOOKUP_CRITERIA,
40
+ LOOKUP_HEADERS,
41
+ mainChild,
42
+ messageCode,
43
+ REQUEST_TIMEOUT_MS,
44
+ stringList,
45
+ type SwCart,
46
+ type SwCartError,
47
+ type SwLineItem,
48
+ } from "./cart";
49
+ import { toIngredients, toMedia, type SwProduct } from "./catalog";
50
+ import { errorCodes, statusOf } from "./request";
51
+ import { text, type AdapterLog } from "./shop";
52
+ import type { StoreApi, VisitorStoreApi } from "./storeApi";
53
+
54
+ /*
55
+ * Checkout and orders over the Store API with the visitor's context token
56
+ * (ADR 0001, step 5). What Shopware stores stays as the storefront wrote
57
+ * it before: a guest is a guest customer (`/account/register` with
58
+ * `guest: true`, the request of the 2.x checkout form), the order is
59
+ * `/checkout/order` with only the customer comment, which carries the
60
+ * wished time ("Wunschlieferzeit: 18:40", "Wunschabholzeit: 18:40"; the
61
+ * receipt printer and the backoffice read it), and the payment is
62
+ * `/handle-payment`. The order request is never sent twice.
63
+ */
64
+
65
+ type Translated<T> = T & { translated?: Partial<T> | null };
66
+ type SwSalutation = { salutationKey?: string | null } | null;
67
+ export type SwAddress = {
68
+ id: string;
69
+ salutation?: SwSalutation;
70
+ firstName?: string | null;
71
+ lastName?: string | null;
72
+ company?: string | null;
73
+ department?: string | null;
74
+ street?: string | null;
75
+ additionalAddressLine1?: string | null;
76
+ zipcode?: string | null;
77
+ city?: string | null;
78
+ countryId?: string | null;
79
+ country?: { iso?: string | null } | null;
80
+ phoneNumber?: string | null;
81
+ };
82
+ export type SwCustomer = {
83
+ id: string;
84
+ guest?: boolean;
85
+ active?: boolean;
86
+ doubleOptInRegistration?: boolean;
87
+ /** Set once the double opt-in link was confirmed. */
88
+ doubleOptInConfirmDate?: string | null;
89
+ email?: string;
90
+ salutation?: SwSalutation;
91
+ firstName?: string;
92
+ lastName?: string;
93
+ defaultBillingAddressId?: string | null;
94
+ defaultShippingAddressId?: string | null;
95
+ defaultBillingAddress?: SwAddress | null;
96
+ defaultShippingAddress?: SwAddress | null;
97
+ };
98
+ type SwContext = {
99
+ token?: string;
100
+ shippingMethod?: { id?: string } | null;
101
+ paymentMethod?: { id?: string } | null;
102
+ salesChannel?: {
103
+ paymentMethodId?: string | null;
104
+ domains?: { url?: string; languageId?: string }[] | null;
105
+ } | null;
106
+ context?: { languageIdChain?: string[] } | null;
107
+ };
108
+ type SwPaymentMethod = Translated<{
109
+ id: string;
110
+ name?: string | null;
111
+ description?: string | null;
112
+ asynchronous?: boolean | null;
113
+ media?: Parameters<typeof toMedia>[0];
114
+ }>;
115
+ type SwOrderLineItem = SwLineItem & {
116
+ parentId?: string | null;
117
+ unitPrice?: number;
118
+ totalPrice?: number;
119
+ position?: number;
120
+ };
121
+ type SwState = { technicalName?: string } | null;
122
+ export type SwOrder = {
123
+ id: string;
124
+ orderNumber?: string;
125
+ orderDateTime?: string;
126
+ createdAt?: string;
127
+ customerComment?: string | null;
128
+ amountTotal?: number;
129
+ shippingTotal?: number;
130
+ positionPrice?: number;
131
+ taxStatus?: string;
132
+ price?: {
133
+ positionPrice?: number;
134
+ totalPrice?: number;
135
+ taxStatus?: string;
136
+ calculatedTaxes?: { tax?: number; taxRate?: number }[] | null;
137
+ } | null;
138
+ stateMachineState?: SwState;
139
+ billingAddressId?: string;
140
+ addresses?: SwAddress[] | null;
141
+ orderCustomer?: { email?: string } | null;
142
+ lineItems?: SwOrderLineItem[] | null;
143
+ deliveries?:
144
+ | {
145
+ shippingMethodId?: string;
146
+ shippingMethod?: Translated<{
147
+ id?: string;
148
+ name?: string | null;
149
+ customFields?: Record<string, unknown> | null;
150
+ }> | null;
151
+ shippingOrderAddress?: SwAddress | null;
152
+ }[]
153
+ | null;
154
+ transactions?:
155
+ | {
156
+ createdAt?: string;
157
+ paymentMethodId?: string;
158
+ paymentMethod?: Translated<{
159
+ id?: string;
160
+ name?: string | null;
161
+ }> | null;
162
+ stateMachineState?: SwState;
163
+ }[]
164
+ | null;
165
+ };
166
+
167
+ export const ADDRESS_ASSOCIATIONS = { country: {}, salutation: {} };
168
+
169
+ /** The associations an order answer needs (`/order`). */
170
+ export const ORDER_ASSOCIATIONS = {
171
+ stateMachineState: {},
172
+ lineItems: {},
173
+ addresses: { associations: ADDRESS_ASSOCIATIONS },
174
+ deliveries: {
175
+ associations: {
176
+ shippingMethod: {},
177
+ shippingOrderAddress: { associations: ADDRESS_ASSOCIATIONS },
178
+ },
179
+ },
180
+ transactions: {
181
+ associations: { paymentMethod: {}, stateMachineState: {} },
182
+ },
183
+ };
184
+
185
+ export const CUSTOMER_CRITERIA = {
186
+ associations: {
187
+ salutation: {},
188
+ defaultBillingAddress: { associations: ADDRESS_ASSOCIATIONS },
189
+ defaultShippingAddress: { associations: ADDRESS_ASSOCIATIONS },
190
+ },
191
+ };
192
+
193
+ const PAYMENT_METHOD_CRITERIA = {
194
+ onlyAvailable: true,
195
+ associations: { media: {} },
196
+ };
197
+
198
+ /** "Wunschlieferzeit: 18:40" (the receipt printer and backoffice read it). */
199
+ const WISHED_TIME_WORD: Readonly<Record<Fulfillment, string>> = {
200
+ delivery: "Wunschlieferzeit",
201
+ pickup: "Wunschabholzeit",
202
+ };
203
+
204
+ /** Older orders say "Wunschzeit"; orders before lead times per method always "Wunschlieferzeit". */
205
+ const WISHED_TIME_COMMENT =
206
+ /^Wunsch(?:liefer|abhol)?zeit:\s*(\d{1,2}):(\d{2})\s*(?:\n|$)/;
207
+
208
+ /** The customer comment of an order: the wished time, then the note. */
209
+ export function orderComment(command: PlaceOrderCommand): string {
210
+ const line = `${WISHED_TIME_WORD[command.fulfillment]}: ${formatTimeOfDay(command.wishedTime.time)}`;
211
+ return command.note ? `${line}\n${command.note}` : line;
212
+ }
213
+
214
+ /**
215
+ * The wished time and the note of a customer comment. The comment holds
216
+ * the time only: its service date is the order's date in the restaurant's
217
+ * time zone, or the next day for a time well before the order was placed
218
+ * (an order at 23:50 for 00:20).
219
+ */
220
+ export function readComment(
221
+ comment: string | null | undefined,
222
+ placedAt: string | undefined,
223
+ zone: TimeZone,
224
+ ): { wishedTime: WishedTime | null; note: string | null } {
225
+ const value = comment?.trim() ?? "";
226
+ const match = WISHED_TIME_COMMENT.exec(value);
227
+ const instant = placedAt ? new Date(placedAt) : undefined;
228
+ if (!match || !instant || Number.isNaN(instant.getTime())) {
229
+ return { wishedTime: null, note: value || null };
230
+ }
231
+ const minutes = Number(match[1]) * 60 + Number(match[2]);
232
+ const rest = value.slice(match[0].length).trim();
233
+ try {
234
+ const placed = zonedDateTime(instant, zone);
235
+ const date =
236
+ minutes < placed.time.minutes - 30
237
+ ? addDays(placed.date, 1)
238
+ : placed.date;
239
+ return { wishedTime: wishedTime(date, minutes), note: rest || null };
240
+ } catch {
241
+ return { wishedTime: null, note: value || null };
242
+ }
243
+ }
244
+
245
+ const SALUTATIONS: readonly Salutation[] = ["mr", "mrs", "not_specified"];
246
+
247
+ export const toSalutation = (
248
+ value: SwSalutation | undefined,
249
+ ): Salutation | null => {
250
+ const key = value?.salutationKey;
251
+ return SALUTATIONS.includes(key as Salutation) ? (key as Salutation) : null;
252
+ };
253
+
254
+ const ORDER_STATUS: Readonly<Record<string, OrderStatus>> = {
255
+ open: "open",
256
+ in_progress: "in_progress",
257
+ completed: "completed",
258
+ cancelled: "cancelled",
259
+ };
260
+
261
+ const PAYMENT_STATUS: Readonly<Record<string, PaymentStatus>> = {
262
+ open: "open",
263
+ reminded: "open",
264
+ authorized: "open",
265
+ unconfirmed: "open",
266
+ in_progress: "open",
267
+ paid_partially: "open",
268
+ paid: "paid",
269
+ failed: "failed",
270
+ chargeback: "failed",
271
+ cancelled: "cancelled",
272
+ refunded: "refunded",
273
+ refunded_partially: "refunded",
274
+ };
275
+
276
+ const translatedName = (
277
+ entity: Translated<{ name?: string | null }> | null | undefined,
278
+ ) => text(entity?.translated?.name) ?? text(entity?.name) ?? "";
279
+
280
+ /** The cart errors that keep Shopware from placing an order, as domain codes. */
281
+ const REFUSALS: readonly [string, DomainErrorCode][] = [
282
+ ["ordering_closed", "ordering_closed"],
283
+ ["shipping_method_blocked", "shipping_method_blocked"],
284
+ ["payment_method_blocked", "payment_method_blocked"],
285
+ ["dish_unavailable", "dish_unavailable"],
286
+ ];
287
+
288
+ export const fail = (code: DomainErrorCode, message: string, cause?: unknown) =>
289
+ new DomainError(code, message, {}, cause ? { cause } : undefined);
290
+
291
+ /**
292
+ * A cause for the log that carries no token or URL (status and codes
293
+ * only); a failure without an answer counts as an outage (503) for the
294
+ * BFF's backoff.
295
+ */
296
+ export const causeOf = (error: unknown) => {
297
+ const status = statusOf(error);
298
+ return Object.assign(
299
+ new Error(
300
+ `Shopware ${status ?? "gave no answer"}${errorCodes(error).length ? ` ${errorCodes(error).join(", ")}` : ""} (${(error as Error | null)?.name ?? "Error"})`,
301
+ ),
302
+ { statusCode: status ?? 503 },
303
+ );
304
+ };
305
+
306
+ /** The fields Shopware's validation refused (`/email`, `/billingAddress/zipcode`). */
307
+ export const refusedFields = (error: unknown): string[] =>
308
+ (
309
+ (
310
+ error as {
311
+ data?: { errors?: { source?: { pointer?: string } }[] };
312
+ } | null
313
+ )?.data?.errors ?? []
314
+ ).flatMap((entry) =>
315
+ entry.source?.pointer
316
+ ? [entry.source.pointer.replace(/^\//, "").replaceAll("/", ".")]
317
+ : [],
318
+ );
319
+
320
+ /**
321
+ * What the account (`customer.ts`) shares with the checkout: the visitor's
322
+ * requests, the address and customer mappings, the storefront URL of the
323
+ * sales channel.
324
+ */
325
+ export type ShopwareVisitorTools = Readonly<{
326
+ shop: {
327
+ get<T>(path: string): Promise<T>;
328
+ post<T>(
329
+ path: string,
330
+ body: Record<string, unknown>,
331
+ headers?: Record<string, string>,
332
+ ): Promise<T>;
333
+ };
334
+ send<T>(
335
+ session: BackendSession,
336
+ method: "GET" | "POST" | "PATCH" | "DELETE",
337
+ path: string,
338
+ body?: Record<string, unknown>,
339
+ ): Promise<T>;
340
+ toAddress(address: SwAddress): Promise<Address>;
341
+ toCustomer(
342
+ customer: SwCustomer,
343
+ billingAddress: Address | null,
344
+ deliveryAddress?: Address | null,
345
+ ): Customer;
346
+ addressBody(address: AddressInput): Promise<Record<string, unknown>>;
347
+ salutationId(salutation: Salutation | null): Promise<string>;
348
+ readOrderer(session: BackendSession): Promise<Orderer | null>;
349
+ storefrontUrlFor(preferred: string): Promise<string>;
350
+ }>;
351
+
352
+ /** How long the order request may take: it must not be cut off early. */
353
+ export const ORDER_TIMEOUT_MS = 60_000;
354
+
355
+ export type ShopwareOrderingOptions = Readonly<{
356
+ currency: () => Promise<CurrencyCode>;
357
+ timeZone: TimeZone;
358
+ log: AdapterLog;
359
+ /** ms every Store API request may take (default 10 s). */
360
+ requestTimeoutMs?: number;
361
+ /**
362
+ * ms the order request may take (default 60 s): Shopware may still
363
+ * commit an order the storefront stopped waiting for, so it waits long.
364
+ */
365
+ orderTimeoutMs?: number;
366
+ /** The Shopware id of the shop's country (`public.site.countryId`). */
367
+ countryId?: string;
368
+ /** ms country ids and product facts are kept (default 10 min / 60 s). */
369
+ countryTtlMs?: number;
370
+ lookupTtlMs?: number;
371
+ }>;
372
+
373
+ /**
374
+ * CheckoutPort (but the shipping methods, `checkout.ts`) and OrderPort
375
+ * over the Store API with the visitor's context token.
376
+ */
377
+ export function createShopwareOrdering(
378
+ shopApi: StoreApi,
379
+ visitorApi: VisitorStoreApi,
380
+ options: ShopwareOrderingOptions,
381
+ ): {
382
+ checkout: Omit<CheckoutPort, "listShippingMethods">;
383
+ orders: OrderPort;
384
+ visitor: ShopwareVisitorTools;
385
+ } {
386
+ const timeoutMs = options.requestTimeoutMs ?? REQUEST_TIMEOUT_MS;
387
+ const orderTimeoutMs = options.orderTimeoutMs ?? ORDER_TIMEOUT_MS;
388
+ const shop = {
389
+ get: <T>(path: string) => deadline(shopApi.get<T>(path), timeoutMs),
390
+ post: <T>(
391
+ path: string,
392
+ body: Record<string, unknown>,
393
+ headers?: Record<string, string>,
394
+ ) =>
395
+ deadline(
396
+ headers
397
+ ? shopApi.post<T>(path, body, { headers })
398
+ : shopApi.post<T>(path, body),
399
+ timeoutMs,
400
+ ),
401
+ };
402
+ const countries = keptFor<ReadonlyMap<string, string>>(
403
+ options.countryTtlMs ?? 600_000,
404
+ );
405
+ const salutationIds = keptFor<ReadonlyMap<string, string>>(
406
+ options.countryTtlMs ?? 600_000,
407
+ );
408
+ const ingredients = keptFor<ReadonlyMap<string, Id>>(options.lookupTtlMs);
409
+ /** The sales channel's domains and language (storefront URLs). */
410
+ const channels = keptFor<SwContext>(options.countryTtlMs ?? 600_000);
411
+
412
+ /** A Store API request for the visitor; a new token goes into the session. */
413
+ async function send<T>(
414
+ session: BackendSession,
415
+ method: "GET" | "POST" | "PATCH" | "DELETE",
416
+ path: string,
417
+ body?: Record<string, unknown>,
418
+ ms: number = timeoutMs,
419
+ ): Promise<T> {
420
+ const token = await session.read();
421
+ const answer = await deadline(
422
+ visitorApi.send<T>({
423
+ method,
424
+ path,
425
+ body,
426
+ contextToken: token,
427
+ ...(session.forwardedFor ? { forwardedFor: session.forwardedFor } : {}),
428
+ // the transport's own deadline must not cut the order off earlier
429
+ timeoutMs: ms,
430
+ }),
431
+ ms,
432
+ );
433
+ if (answer.contextToken && answer.contextToken !== token) {
434
+ await session.write(answer.contextToken);
435
+ }
436
+ return answer.data;
437
+ }
438
+
439
+ /**
440
+ * A request as the port answers its failure: the given codes for 403
441
+ * and 404, 400 `invalid_value`, everything else `backend_unavailable`.
442
+ */
443
+ async function ask<T>(
444
+ what: string,
445
+ run: () => Promise<T>,
446
+ codes: Partial<Record<400 | 403 | 404, DomainErrorCode>> = {},
447
+ ): Promise<T> {
448
+ try {
449
+ return await run();
450
+ } catch (error) {
451
+ if (isDomainError(error)) throw error;
452
+ // Shopware answers a missing customer with 401 or 403
453
+ const status = statusOf(error) === 401 ? 403 : statusOf(error);
454
+ const code =
455
+ status === 400 || status === 403 || status === 404
456
+ ? (codes[status] ??
457
+ (status === 400
458
+ ? "invalid_value"
459
+ : status === 404
460
+ ? "not_found"
461
+ : undefined))
462
+ : undefined;
463
+ throw fail(
464
+ code ?? "backend_unavailable",
465
+ code
466
+ ? `Shopware refused ${what}.`
467
+ : `Shopware did not answer for ${what}.`,
468
+ causeOf(error),
469
+ );
470
+ }
471
+ }
472
+
473
+ /**
474
+ * The id of a country of the sales channel by its ISO code, kept a
475
+ * while. Asked by code: the Store API lists at most 100 per request.
476
+ */
477
+ async function countryId(code: string): Promise<string> {
478
+ const iso = code.toUpperCase();
479
+ let id = countries.get(iso)?.get(iso);
480
+ if (!id) {
481
+ const answer = await ask("the country", () =>
482
+ shop.post<{ elements?: { id: string; iso?: string | null }[] }>(
483
+ "/country",
484
+ {
485
+ filter: [{ type: "equals", field: "iso", value: iso }],
486
+ includes: { country: ["id", "iso"] },
487
+ },
488
+ ),
489
+ );
490
+ id = answer.elements?.find(
491
+ (country) => country.iso?.toUpperCase() === iso,
492
+ )?.id;
493
+ if (id) countries.set(iso, new Map([[iso, id]]));
494
+ }
495
+ if (!id) {
496
+ throw new DomainError(
497
+ "invalid_value",
498
+ "The shop does not deliver to this country.",
499
+ { field: "country", value: code },
500
+ );
501
+ }
502
+ return id;
503
+ }
504
+
505
+ /** The id of a salutation; null is Shopware's "not given" (empty id). */
506
+ async function salutationId(salutation: Salutation | null): Promise<string> {
507
+ if (salutation === null) return "";
508
+ let map = salutationIds.get("all");
509
+ if (!map) {
510
+ const answer = await ask("the salutations", () =>
511
+ shop.post<{ elements?: { id: string; salutationKey?: string }[] }>(
512
+ "/salutation",
513
+ { includes: { salutation: ["id", "salutationKey"] } },
514
+ ),
515
+ );
516
+ map = new Map(
517
+ (answer.elements ?? []).flatMap((entry) =>
518
+ entry.salutationKey ? [[entry.salutationKey, entry.id] as const] : [],
519
+ ),
520
+ );
521
+ salutationIds.set("all", map);
522
+ }
523
+ return map.get(salutation) ?? "";
524
+ }
525
+
526
+ async function toAddress(address: SwAddress): Promise<Address> {
527
+ // every read asks for the `country` association
528
+ const country = address.country?.iso?.toUpperCase() ?? null;
529
+ return {
530
+ id: address.id,
531
+ salutation: toSalutation(address.salutation),
532
+ firstName: address.firstName ?? "",
533
+ lastName: address.lastName ?? "",
534
+ company: text(address.company),
535
+ department: text(address.department),
536
+ street: address.street ?? "",
537
+ additionalLine: text(address.additionalAddressLine1),
538
+ postalCode: address.zipcode ?? "",
539
+ city: address.city ?? "",
540
+ country: country ?? "",
541
+ phone: text(address.phoneNumber),
542
+ };
543
+ }
544
+
545
+ /** The country of an address: the shop's own when it has none. */
546
+ async function countryOf(code: string | null): Promise<string> {
547
+ if (code) return countryId(code);
548
+ if (options.countryId) return options.countryId;
549
+ throw new DomainError(
550
+ "invalid_value",
551
+ "The shop has no country for an address without one.",
552
+ { field: "country", value: code },
553
+ );
554
+ }
555
+
556
+ /** The address as the checkout form of 2.x sent it to Shopware. */
557
+ async function addressBody(
558
+ address: AddressInput,
559
+ ): Promise<Record<string, unknown>> {
560
+ return {
561
+ firstName: address.firstName,
562
+ lastName: address.lastName,
563
+ company: address.company ?? "",
564
+ department: address.department ?? "",
565
+ salutationId: await salutationId(address.salutation),
566
+ street: address.street,
567
+ additionalAddressLine1: address.additionalLine ?? "",
568
+ zipcode: address.postalCode,
569
+ city: address.city,
570
+ countryId: await countryOf(address.country),
571
+ phoneNumber: address.phone ?? "",
572
+ };
573
+ }
574
+
575
+ function toCustomer(
576
+ customer: SwCustomer,
577
+ billingAddress: Address | null,
578
+ deliveryAddress: Address | null = billingAddress,
579
+ ): Customer {
580
+ return deepFreeze({
581
+ id: customer.id,
582
+ guest: customer.guest === true,
583
+ email: customer.email ?? "",
584
+ salutation: toSalutation(customer.salutation),
585
+ firstName: customer.firstName ?? "",
586
+ lastName: customer.lastName ?? "",
587
+ phone:
588
+ billingAddress?.phone ??
589
+ text(customer.defaultBillingAddress?.phoneNumber) ??
590
+ null,
591
+ defaultBillingAddressId:
592
+ customer.defaultBillingAddressId ?? billingAddress?.id ?? null,
593
+ defaultDeliveryAddressId:
594
+ customer.defaultShippingAddressId ?? deliveryAddress?.id ?? null,
595
+ });
596
+ }
597
+
598
+ async function toOrderer(customer: SwCustomer): Promise<Orderer> {
599
+ const billingSource =
600
+ customer.defaultBillingAddress ?? customer.defaultShippingAddress;
601
+ const deliverySource =
602
+ customer.defaultShippingAddress ?? customer.defaultBillingAddress;
603
+ if (!billingSource || !deliverySource) {
604
+ throw fail(
605
+ "backend_unavailable",
606
+ "Shopware answered a customer without address.",
607
+ );
608
+ }
609
+ const billingAddress = await toAddress(billingSource);
610
+ const deliveryAddress =
611
+ deliverySource.id === billingSource.id
612
+ ? billingAddress
613
+ : await toAddress(deliverySource);
614
+ const value = toCustomer(customer, billingAddress, deliveryAddress);
615
+ return deepFreeze({ customer: value, billingAddress, deliveryAddress });
616
+ }
617
+
618
+ async function readOrderer(session: BackendSession): Promise<Orderer | null> {
619
+ if (!(await session.read())) return null;
620
+ try {
621
+ const customer = await send<SwCustomer>(
622
+ session,
623
+ "POST",
624
+ "/account/customer",
625
+ CUSTOMER_CRITERIA,
626
+ );
627
+ return await toOrderer(customer);
628
+ } catch (error) {
629
+ if (isDomainError(error)) throw error;
630
+ // a visitor without guest or customer
631
+ if (statusOf(error) === 403 || statusOf(error) === 401) return null;
632
+ throw fail(
633
+ "backend_unavailable",
634
+ "Shopware did not answer for the customer.",
635
+ causeOf(error),
636
+ );
637
+ }
638
+ }
639
+
640
+ async function context(session?: BackendSession): Promise<SwContext> {
641
+ if (session && (await session.read())) {
642
+ return ask("the context", () =>
643
+ send<SwContext>(session, "GET", "/context"),
644
+ );
645
+ }
646
+ return ask("the context", () => shop.get<SwContext>("/context"));
647
+ }
648
+
649
+ const toSelection = (value: SwContext): CheckoutSelection =>
650
+ deepFreeze({
651
+ shippingMethodId: value.shippingMethod?.id ?? null,
652
+ paymentMethodId: value.paymentMethod?.id ?? null,
653
+ });
654
+
655
+ async function select(
656
+ session: BackendSession,
657
+ change: Record<string, string>,
658
+ what: string,
659
+ ): Promise<CheckoutSelection> {
660
+ await ask(what, () => send(session, "PATCH", "/context", change));
661
+ return toSelection(await context(session));
662
+ }
663
+
664
+ /**
665
+ * The storefront URL for Shopware's e-mail links: one of the sales
666
+ * channel's domains, as the Shopware layer chose it (the domain the
667
+ * guest orders on, else the first domain of the context's language).
668
+ */
669
+ async function storefrontUrlFor(preferred: string): Promise<string> {
670
+ let value = channels.get("context");
671
+ if (!value) {
672
+ value = await context().catch(() => undefined);
673
+ if (value) channels.set("context", value);
674
+ }
675
+ value ??= {};
676
+ const domains = value.salesChannel?.domains ?? [];
677
+ const normalized = preferred.replace(/\/$/, "");
678
+ const matching = domains.find(
679
+ (domain) => domain.url?.replace(/\/$/, "") === normalized,
680
+ );
681
+ if (matching?.url) return matching.url;
682
+ const languageId = value.context?.languageIdChain?.[0];
683
+ return (
684
+ domains.find((domain) => domain.languageId === languageId)?.url ??
685
+ preferred
686
+ );
687
+ }
688
+
689
+ /** Ingredient ids by product id and name, for the removed ingredients. */
690
+ async function ingredientIdsOf(
691
+ productIds: readonly Id[],
692
+ ): Promise<ReadonlyMap<string, Id>> {
693
+ const result = new Map<string, Id>();
694
+ const missing = [...new Set(productIds)].filter((id) => {
695
+ const kept = ingredients.get(id);
696
+ kept?.forEach((value, key) => result.set(`${id}|${key}`, value));
697
+ return !kept;
698
+ });
699
+ if (missing.length) {
700
+ try {
701
+ const answer = await shop.post<{ elements?: SwProduct[] }>(
702
+ "/product",
703
+ { ids: missing, ...LOOKUP_CRITERIA },
704
+ LOOKUP_HEADERS,
705
+ );
706
+ for (const product of answer.elements ?? []) {
707
+ const names = new Map(
708
+ toIngredients(product).map((entry) => [entry.name, entry.id]),
709
+ );
710
+ ingredients.set(product.id, names);
711
+ names.forEach((value, key) =>
712
+ result.set(`${product.id}|${key}`, value),
713
+ );
714
+ }
715
+ } catch (error) {
716
+ // the names are shown either way; only the ids are missing
717
+ options.log("[shopware][orders] ingredients of the ordered dishes", {
718
+ error: causeOf(error).message,
719
+ });
720
+ }
721
+ }
722
+ return result;
723
+ }
724
+
725
+ async function toOrder(
726
+ order: SwOrder,
727
+ tokens: readonly (string | undefined)[],
728
+ ): Promise<Order> {
729
+ const currency = await ask("the currency", () =>
730
+ deadline(options.currency(), timeoutMs),
731
+ );
732
+ const money = (amount: number | undefined) =>
733
+ moneyFromDecimal(amount ?? 0, currency);
734
+ const secrets = tokens.filter((token): token is string => !!token);
735
+ const clean = (value: string) =>
736
+ secrets.reduce((result, token) => result.replaceAll(token, "***"), value);
737
+ const items = order.lineItems ?? [];
738
+ const childrenOf = (id: string) =>
739
+ items
740
+ .filter((item) => item.parentId === id)
741
+ .sort((a, b) => (a.position ?? 0) - (b.position ?? 0));
742
+ const top = items
743
+ .filter((item) => !item.parentId)
744
+ .sort((a, b) => (a.position ?? 0) - (b.position ?? 0));
745
+ const dishes = top.filter(
746
+ (item) => item.type === "product" || item.type === "container",
747
+ );
748
+ const withRemovals = dishes.flatMap((item) => {
749
+ if (
750
+ item.type !== "container" ||
751
+ !stringList(item.payload?.without).length
752
+ )
753
+ return [];
754
+ const main = mainChild({ ...item, children: childrenOf(item.id) });
755
+ return main ? [main.referencedId ?? main.id] : [];
756
+ });
757
+ const ingredientIds = withRemovals.length
758
+ ? await ingredientIdsOf(withRemovals)
759
+ : new Map<string, Id>();
760
+
761
+ const lines: OrderLine[] = dishes.flatMap((item) => {
762
+ const container = item.type === "container";
763
+ const children = container
764
+ ? (childrenOf(item.id) as SwOrderLineItem[])
765
+ : [];
766
+ const main = (container ? mainChild({ ...item, children }) : item) as
767
+ SwOrderLineItem | undefined;
768
+ if (!main) return [];
769
+ const productId = main.referencedId ?? main.id;
770
+ const parentId = main.payload?.parentId ?? null;
771
+ const extras = children.filter(
772
+ (child) => child !== main && (child.type ?? "product") === "product",
773
+ );
774
+ const removed = container ? stringList(item.payload?.without) : [];
775
+ return [
776
+ {
777
+ id: item.id,
778
+ configuration: dishConfiguration({
779
+ dishId: parentId ?? productId,
780
+ variantId: parentId ? productId : null,
781
+ extraIds: extras.map((extra) => extra.referencedId ?? extra.id),
782
+ removedIngredientIds: removed.flatMap((name) => {
783
+ const id = ingredientIds.get(`${productId}|${name}`);
784
+ return id ? [id] : [];
785
+ }),
786
+ }),
787
+ dishNumber:
788
+ (container ? item.payload?.productNumber : undefined) ??
789
+ main.payload?.productNumber ??
790
+ "",
791
+ name: main.label ?? item.label ?? "",
792
+ extras: extras.map((extra) => ({
793
+ name: extra.label ?? "",
794
+ unitPrice: money(extra.unitPrice ?? extra.price?.unitPrice),
795
+ })),
796
+ removedIngredients: removed,
797
+ quantity: item.quantity ?? 1,
798
+ unitPrice: money(item.unitPrice ?? item.price?.unitPrice),
799
+ totalPrice: money(item.totalPrice ?? item.price?.totalPrice),
800
+ },
801
+ ];
802
+ });
803
+
804
+ const delivery = order.deliveries?.[0];
805
+ const method = delivery?.shippingMethod;
806
+ const fields =
807
+ method?.translated?.customFields ?? method?.customFields ?? {};
808
+ const fulfillment: Fulfillment =
809
+ fields?.shopbite_fulfillment === "pickup" ? "pickup" : "delivery";
810
+ const transaction = [...(order.transactions ?? [])]
811
+ .sort((a, b) => (a.createdAt ?? "").localeCompare(b.createdAt ?? ""))
812
+ .at(-1);
813
+ const billingSource =
814
+ order.addresses?.find((entry) => entry.id === order.billingAddressId) ??
815
+ order.addresses?.[0];
816
+ if (!billingSource) {
817
+ throw fail(
818
+ "backend_unavailable",
819
+ "Shopware answered an order without billing address.",
820
+ );
821
+ }
822
+ const billingAddress = await toAddress(billingSource);
823
+ const deliveryAddress =
824
+ fulfillment === "pickup" || !delivery?.shippingOrderAddress
825
+ ? null
826
+ : await toAddress(delivery.shippingOrderAddress);
827
+ const placedAt =
828
+ order.orderDateTime ?? order.createdAt ?? new Date().toISOString();
829
+ const { wishedTime: wished, note } = readComment(
830
+ order.customerComment,
831
+ placedAt,
832
+ options.timeZone,
833
+ );
834
+ const taxStatus = order.taxStatus ?? order.price?.taxStatus;
835
+ return deepFreeze({
836
+ id: order.id,
837
+ number: order.orderNumber ?? "",
838
+ placedAt: new Date(placedAt).toISOString(),
839
+ status:
840
+ ORDER_STATUS[order.stateMachineState?.technicalName ?? ""] ?? "open",
841
+ paymentStatus:
842
+ PAYMENT_STATUS[transaction?.stateMachineState?.technicalName ?? ""] ??
843
+ "open",
844
+ fulfillment,
845
+ wishedTime: wished,
846
+ shippingMethod: {
847
+ id: method?.id ?? delivery?.shippingMethodId ?? "",
848
+ name: translatedName(method),
849
+ },
850
+ paymentMethod: {
851
+ id:
852
+ transaction?.paymentMethod?.id ?? transaction?.paymentMethodId ?? "",
853
+ name: translatedName(transaction?.paymentMethod),
854
+ },
855
+ lines,
856
+ discounts: top
857
+ .filter((item) => item.type === "promotion")
858
+ .map((item) => ({
859
+ code: item.payload?.code || item.referencedId || null,
860
+ name: item.label ?? "",
861
+ amount: money(item.totalPrice ?? item.price?.totalPrice),
862
+ })),
863
+ subtotal: money(order.price?.positionPrice ?? order.positionPrice),
864
+ shippingCosts: money(order.shippingTotal),
865
+ total: money(order.amountTotal ?? order.price?.totalPrice),
866
+ taxes: (order.price?.calculatedTaxes ?? []).map((tax) => ({
867
+ rate: tax.taxRate ?? 0,
868
+ amount: money(tax.tax),
869
+ })),
870
+ taxIncluded: taxStatus !== "net",
871
+ billingAddress,
872
+ deliveryAddress,
873
+ email: order.orderCustomer?.email ?? "",
874
+ note: note === null ? null : clean(note),
875
+ });
876
+ }
877
+
878
+ async function readOrders(
879
+ session: BackendSession,
880
+ criteria: Record<string, unknown>,
881
+ ): Promise<{ elements: SwOrder[]; total: number }> {
882
+ const answer = await send<{
883
+ orders?: { elements?: SwOrder[]; total?: number };
884
+ }>(session, "POST", "/order", {
885
+ ...criteria,
886
+ associations: ORDER_ASSOCIATIONS,
887
+ });
888
+ const elements = answer.orders?.elements ?? [];
889
+ return { elements, total: answer.orders?.total ?? elements.length };
890
+ }
891
+
892
+ async function getOrder(
893
+ session: BackendSession,
894
+ orderId: Id,
895
+ ): Promise<Order> {
896
+ const token = await session.read();
897
+ if (!token) throw fail("not_found", "There is no such order.");
898
+ const found = await ask(
899
+ "the order",
900
+ () => readOrders(session, { ids: [orderId] }),
901
+ // another visitor's order or no customer: as if there were none
902
+ { 400: "not_found", 403: "not_found" },
903
+ );
904
+ const order = found.elements.find((entry) => entry.id === orderId);
905
+ if (!order) throw fail("not_found", "There is no such order.");
906
+ return toOrder(order, [token]);
907
+ }
908
+
909
+ /** Why Shopware refuses to place the cart, from its errors. */
910
+ async function refusal(
911
+ session: BackendSession,
912
+ cause: unknown,
913
+ ): Promise<DomainError> {
914
+ let errors: SwCartError[] = [];
915
+ try {
916
+ const cart = await send<SwCart>(session, "GET", "/checkout/cart");
917
+ errors = Object.values(cart.errors ?? {}).filter(
918
+ (error) => (error.level ?? 0) >= 20,
919
+ );
920
+ } catch {
921
+ // the order was refused either way
922
+ }
923
+ const codes = errors.map((error) => messageCode(error) as string);
924
+ const code =
925
+ REFUSALS.find(([cartCode]) => codes.includes(cartCode))?.[1] ??
926
+ "validation_failed";
927
+ return fail(code, "Shopware refused the order.", causeOf(cause));
928
+ }
929
+
930
+ const checkout: Omit<CheckoutPort, "listShippingMethods"> = {
931
+ listPaymentMethods: async (session) => {
932
+ const visitor = session && (await session.read()) ? session : undefined;
933
+ const [methods, current] = await Promise.all([
934
+ ask("the payment methods", () =>
935
+ visitor
936
+ ? send<{ elements?: SwPaymentMethod[] }>(
937
+ visitor,
938
+ "POST",
939
+ "/payment-method",
940
+ PAYMENT_METHOD_CRITERIA,
941
+ )
942
+ : shop.post<{ elements?: SwPaymentMethod[] }>(
943
+ "/payment-method",
944
+ PAYMENT_METHOD_CRITERIA,
945
+ ),
946
+ ),
947
+ // the methods without the shop's default rather than none
948
+ context(visitor).catch((error) => {
949
+ options.log(
950
+ "[shopware][checkout] the shop's default payment method",
951
+ {
952
+ error: (error as Error).message,
953
+ },
954
+ );
955
+ return {} as SwContext;
956
+ }),
957
+ ]);
958
+ const preferred = current.salesChannel?.paymentMethodId ?? null;
959
+ return deepFreeze(
960
+ (methods.elements ?? []).map((method): PaymentMethod => ({
961
+ id: method.id,
962
+ name: translatedName(method),
963
+ description:
964
+ text(method.translated?.description) ?? text(method.description),
965
+ media: toMedia(method.media),
966
+ redirects: method.asynchronous === true,
967
+ preferred: method.id === preferred,
968
+ })),
969
+ );
970
+ },
971
+
972
+ getSelection: async (session) => toSelection(await context(session)),
973
+
974
+ selectShippingMethod: (session, methodId) =>
975
+ select(session, { shippingMethodId: methodId }, "the shipping method"),
976
+
977
+ selectPaymentMethod: (session, methodId) =>
978
+ select(session, { paymentMethodId: methodId }, "the payment method"),
979
+
980
+ getOrderer: readOrderer,
981
+
982
+ registerGuest: async (session, guest: GuestDetails, storefrontUrl) => {
983
+ const [billingAddress, shippingAddress, url] = await Promise.all([
984
+ addressBody({
985
+ ...guest.billingAddress,
986
+ // the form's billing names are the guest's
987
+ firstName: guest.billingAddress.firstName || guest.firstName,
988
+ lastName: guest.billingAddress.lastName || guest.lastName,
989
+ }),
990
+ guest.deliveryAddress ? addressBody(guest.deliveryAddress) : undefined,
991
+ storefrontUrlFor(storefrontUrl),
992
+ ]);
993
+ try {
994
+ await send(session, "POST", "/account/register", {
995
+ accountType: guest.business ? "business" : "private",
996
+ email: guest.email,
997
+ firstName: guest.firstName,
998
+ lastName: guest.lastName,
999
+ guest: true,
1000
+ acceptedDataProtection: true,
1001
+ storefrontUrl: url,
1002
+ billingAddress,
1003
+ ...(shippingAddress ? { shippingAddress } : {}),
1004
+ });
1005
+ } catch (error) {
1006
+ if (statusOf(error) === 400) {
1007
+ throw new DomainError(
1008
+ "validation_failed",
1009
+ "Shopware refused the guest's details.",
1010
+ { fields: refusedFields(error) },
1011
+ { cause: causeOf(error) },
1012
+ );
1013
+ }
1014
+ throw fail(
1015
+ "backend_unavailable",
1016
+ "Shopware did not answer for the guest.",
1017
+ causeOf(error),
1018
+ );
1019
+ }
1020
+ const orderer = await readOrderer(session);
1021
+ if (!orderer) {
1022
+ throw fail("backend_unavailable", "Shopware did not keep the guest.");
1023
+ }
1024
+ return orderer;
1025
+ },
1026
+
1027
+ updateAddress: async (session, address) => {
1028
+ if (!address.id || !(await session.read())) {
1029
+ throw fail("not_found", "There is no such address.");
1030
+ }
1031
+ const { id, ...fields } = address;
1032
+ const body = await addressBody({
1033
+ ...fields,
1034
+ country: fields.country || null,
1035
+ });
1036
+ // the address form of 2.x sent none: a change without one keeps it
1037
+ if (fields.salutation === null) delete body.salutationId;
1038
+ await ask(
1039
+ "the address",
1040
+ async () => {
1041
+ try {
1042
+ return await send(
1043
+ session,
1044
+ "PATCH",
1045
+ `/account/address/${encodeURIComponent(id)}`,
1046
+ { ...body, id },
1047
+ );
1048
+ } catch (error) {
1049
+ // another customer's address: Shopware answers 400
1050
+ if (
1051
+ errorCodes(error).includes("CHECKOUT__CUSTOMER_ADDRESS_NOT_FOUND")
1052
+ ) {
1053
+ throw fail("not_found", "There is no such address.");
1054
+ }
1055
+ throw error;
1056
+ }
1057
+ },
1058
+ { 403: "not_found", 404: "not_found" },
1059
+ );
1060
+ const orderer = await readOrderer(session);
1061
+ if (!orderer) throw fail("not_found", "There is no such address.");
1062
+ return orderer;
1063
+ },
1064
+
1065
+ placeOrder: async (session, command) => {
1066
+ const token = await session.read();
1067
+ if (!token)
1068
+ throw fail("unauthenticated", "Ordering needs a guest or a customer.");
1069
+ let order: SwOrder;
1070
+ try {
1071
+ // sent once: an answer that does not come may still be an order
1072
+ order = await send<SwOrder>(
1073
+ session,
1074
+ "POST",
1075
+ "/checkout/order",
1076
+ { customerComment: orderComment(command) },
1077
+ orderTimeoutMs,
1078
+ );
1079
+ } catch (error) {
1080
+ const status = statusOf(error);
1081
+ const codes = errorCodes(error);
1082
+ if (status === 403 || status === 401) {
1083
+ throw fail(
1084
+ "unauthenticated",
1085
+ "Ordering needs a guest or a customer.",
1086
+ causeOf(error),
1087
+ );
1088
+ }
1089
+ if (codes.includes("CHECKOUT__CART_EMPTY")) {
1090
+ throw fail(
1091
+ "cart_empty",
1092
+ "The cart holds nothing to order.",
1093
+ causeOf(error),
1094
+ );
1095
+ }
1096
+ if (status === 400) throw await refusal(session, error);
1097
+ throw fail(
1098
+ "backend_unavailable",
1099
+ "Shopware did not answer the order; it may have been placed.",
1100
+ causeOf(error),
1101
+ );
1102
+ }
1103
+ try {
1104
+ return await toOrder(order, [token, await session.read()]);
1105
+ } catch (error) {
1106
+ options.log("[shopware][orders] read the placed order again", {
1107
+ error: (error as Error).message,
1108
+ });
1109
+ return getOrder(session, order.id);
1110
+ }
1111
+ },
1112
+
1113
+ changePaymentMethod: async (session, orderId, paymentMethodId) => {
1114
+ await ask(
1115
+ "the payment method of the order",
1116
+ () =>
1117
+ send(session, "POST", "/order/payment", { orderId, paymentMethodId }),
1118
+ { 400: "payment_method_blocked", 403: "not_found" },
1119
+ );
1120
+ return getOrder(session, orderId);
1121
+ },
1122
+
1123
+ startPayment: async (session, orderId, urls) => {
1124
+ const answer = await ask(
1125
+ "the payment",
1126
+ () =>
1127
+ send<{ redirectUrl?: string | null }>(
1128
+ session,
1129
+ "POST",
1130
+ "/handle-payment",
1131
+ {
1132
+ orderId,
1133
+ finishUrl: urls.success,
1134
+ errorUrl: urls.failure,
1135
+ },
1136
+ ),
1137
+ { 403: "not_found" },
1138
+ );
1139
+ return deepFreeze({ redirectUrl: answer?.redirectUrl ?? null });
1140
+ },
1141
+ };
1142
+
1143
+ const orders: OrderPort = {
1144
+ getOrder,
1145
+ listOrders: async (session, page = 1, limit = 10) => {
1146
+ const token = await session.read();
1147
+ if (!token)
1148
+ throw fail("unauthenticated", "Orders need a guest or a customer.");
1149
+ const found = await ask(
1150
+ "the orders",
1151
+ () =>
1152
+ readOrders(session, {
1153
+ page,
1154
+ limit,
1155
+ sort: [{ field: "createdAt", order: "DESC" }],
1156
+ "total-count-mode": "exact",
1157
+ }),
1158
+ { 403: "unauthenticated" },
1159
+ );
1160
+ return deepFreeze({
1161
+ orders: await Promise.all(
1162
+ found.elements.map((order) => toOrder(order, [token])),
1163
+ ),
1164
+ total: found.total,
1165
+ page,
1166
+ limit,
1167
+ });
1168
+ },
1169
+ };
1170
+
1171
+ return {
1172
+ checkout,
1173
+ orders,
1174
+ visitor: {
1175
+ shop,
1176
+ send,
1177
+ toAddress,
1178
+ toCustomer,
1179
+ addressBody,
1180
+ salutationId,
1181
+ readOrderer,
1182
+ storefrontUrlFor,
1183
+ },
1184
+ };
1185
+ }