@shopbite-de/storefront 2.0.2 → 2.0.3

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.
package/CLAUDE.md CHANGED
@@ -135,7 +135,7 @@ Pages without content throw `createNotFoundError()` (`app/utils/notFound.ts`): f
135
135
  - No toasts (removed in #445, other responses to be designed): results and errors show where they happen, e.g. `role="alert"` boxes in forms and the checkout, `role="status"` regions, the voucher error at its field.
136
136
  - Menu (#441): `Category/Listing.vue` has three columns from `lg` (`MenuCategoryIndex` word list, the list, `MenuCartPanel`), `NavigationMobileTop` below `lg`; `MenuSectionHeader` and `MenuBonCard` (one column, number strip, `photo` for the `bonPhoto` view). The card's button adds a product straight to the cart unless `productNeedsChoice()` (a parent with variants, `childCount` in the listing projection), which opens the quick view; extras stay optional. Cards hydrate on approach (`hydrateWhenVisible`), so a click on a card that has not hydrated yet is lost. Filters live in an `SbSheet`, sorting is an `SbSelect` (`toSortingOptions()`).
137
137
  - Product sheet (#442): `SbSheet` with a bon header (number strip, name as `DialogTitle`, diet and description as `DialogDescription`); `Configurator` shows variants as `SbChoiceGroup` (required), `DeselectIngredient` as `SbChip` ingredient chips (pressed = included), `CrossSelling` as `SbCheckbox` rows with a search, `Detail` a sticky footer with `SbStepper` and the add button.
138
- - Cart and checkout (#443): `MenuOrderMode` (`useOrderMode`) shows the shipping methods as an `SbSegmentedControl` only when there are two to four. The header cart opens an `SbSheet`; `Cart/Item` uses `SbStepper` (remove at 1). The checkout is one page, `/bestellung/kasse` (the old step routes 301 there, `routeRules`): numbered sections Lieferung oder Abholung (`CheckoutPaymentAndDelivery part="shipping"`), Wann, Ihre Angaben (`CheckoutLoginOrRegister` with Reka tabs, `UserRegistrationForm` (logic in `useRegistrationForm`) / `UserLoginForm`, or `UserDetail`), Bezahlung (`part="payment"`) and the order card in `Checkout/Summary.vue`; the order button says "Zahlungspflichtig bestellen" (§ 312j BGB). Forms validate with Zod on submit and show errors at the fields plus a focused summary in form order; `AddressFields` sets `autocomplete`.
138
+ - Cart and checkout (#443): `MenuOrderMode` (`useOrderMode`) and the checkout's shipping section list ALL active shipping methods (`useShippingMethodChoice`, `onlyAvailable: false`), because a delivery-area rule on the shipping city never matches before the guest has an address (La Fattoria, fixed in 2.0.3); `useCheckoutMethodGuard` switches only a blocked payment method, a blocked shipping method is reported in the checkout and never switched to pickup. It shows the shipping methods as an `SbSegmentedControl` only when there are two to four. The header cart opens an `SbSheet`; `Cart/Item` uses `SbStepper` (remove at 1). The checkout is one page, `/bestellung/kasse` (the old step routes 301 there, `routeRules`): numbered sections Lieferung oder Abholung (`CheckoutPaymentAndDelivery part="shipping"`), Wann, Ihre Angaben (`CheckoutLoginOrRegister` with Reka tabs, `UserRegistrationForm` (logic in `useRegistrationForm`) / `UserLoginForm`, or `UserDetail`), Bezahlung (`part="payment"`) and the order card in `Checkout/Summary.vue`; the order button says "Zahlungspflichtig bestellen" (§ 312j BGB). Forms validate with Zod on submit and show errors at the fields plus a focused summary in form order; `AddressFields` sets `autocomplete`.
139
139
  - Order and account (#445): `/bestellung/<id>/erfolg` and `/bestellung/<id>` render `OrderConfirmation` (`OrderDetail`: facts incl. the wished time from the `customerComment`, receipt lines, totals; call card), `/bestellung/<id>/fehler` a payment retry. Login, registration, password pages and the registration confirmation render in `UserAuthPanel`; the account pages in `layouts/account.vue` (link navigation with `aria-current`) with `UserAccountHeader`; `AddressForm` (also used when an address is edited in the checkout). Irreversible actions confirm with `SbConfirmDialog` (focus starts on "Abbrechen"). Search, contact (`useContactForm`), wishlist (`AddToWishlist`), content pages and `error.vue` (with its own `Header`/`Footer`, because the error page replaces `app.vue`) use the same pieces.
140
140
  - Home page (#444): `pages/index.vue` renders `HomeHero` (kicker, `[highlight]{.text-primary}` part in the accent colour via `splitHighlight()`, buttons from `hero.links`, live status, rating card from the Google `usp`; the photo is `hero.image` with the blurred video `hero.poster` as fallback, cropped 4:5 at `hero.imagePosition` (object-position); it sits in a `<picture>` with a `min-width: 640px` source, so phones load a 1 px GIF), `HomeFacts` (`features`), `HomeCategories` (word list, `useHomeMenuCategories`; a wide first category image switches to a full-width photo below the words, and `sizes` asks for the width the crop needs, since thumbnails are picked by width), `HomeHighlights` (top sellers as bon cards), `HomeRestaurant` (`gallery` + opening hours in the SSR HTML) and the two-column `HomeFaq`; `cta` and `mittagstisch` in `content/index.yml` are not shown.
141
141
  - Header and footer (#455): `Header.vue` (logo, main nav, status pill, phone, account, wishlist, cart button opening the cart `SbSheet`, menu `SbSheet` on phones), `Footer.vue` (address, hours, footer navigation columns). `app.vue` has the skip link to `main#inhalt`.
@@ -13,12 +13,12 @@ const {
13
13
  getPaymentMethods,
14
14
  selectedPaymentMethod,
15
15
  setPaymentMethod,
16
- shippingMethods,
17
- getShippingMethods,
18
16
  selectedShippingMethod,
19
17
  setShippingMethod,
20
18
  } = useCheckout();
21
19
 
20
+ const { methods: shippingMethods, load: loadShippingMethods } =
21
+ useShippingMethodChoice();
22
22
  const { refreshCart } = useCart();
23
23
  const { ensureAvailableCheckoutMethods } = useCheckoutMethodGuard();
24
24
 
@@ -55,7 +55,7 @@ const paymentModel = computed({
55
55
 
56
56
  onMounted(async () => {
57
57
  try {
58
- await Promise.all([getPaymentMethods(), getShippingMethods()]);
58
+ await Promise.all([getPaymentMethods(), loadShippingMethods()]);
59
59
  await ensureAvailableCheckoutMethods();
60
60
  } catch (error) {
61
61
  console.error("[checkout][PaymentAndDelivery][onMounted]", error);
@@ -46,6 +46,13 @@ onMounted(() => {
46
46
 
47
47
  useIntervalFn(refresh, 10000);
48
48
 
49
+ const shippingMethodName = computed(
50
+ () =>
51
+ selectedShippingMethod.value?.translated?.name ??
52
+ selectedShippingMethod.value?.name ??
53
+ "Die Versandart",
54
+ );
55
+
49
56
  const createdOrder = ref<Awaited<ReturnType<typeof createOrder>> | null>(null);
50
57
  const { handlePayment, paymentUrl } = useOrderPayment(
51
58
  computed(() => createdOrder.value),
@@ -61,6 +68,13 @@ const { handlePayment, paymentUrl } = useOrderPayment(
61
68
  async function hasAvailableCheckoutMethods(): Promise<boolean> {
62
69
  try {
63
70
  if (await ensureAvailableCheckoutMethods()) return true;
71
+ if (isShippingMethodBlocked.value) {
72
+ reportError({
73
+ title: `${shippingMethodName.value} ist nicht möglich`,
74
+ description: `${shippingMethodName.value} ist für Ihre Adresse oder Ihren Warenkorb nicht möglich. Bitte wählen Sie oben eine andere Bestellart oder ändern Sie Ihre Adresse.`,
75
+ });
76
+ return false;
77
+ }
64
78
  reportError({
65
79
  title: `Keine ${blockedMethodLabel.value} verfügbar`,
66
80
  description: `Für deine Bestellung ist aktuell keine ${blockedMethodLabel.value} verfügbar. Bitte prüfe deine Adresse und deinen Warenkorb.`,
@@ -117,6 +131,18 @@ const customerDataAvailable = computed<boolean>(
117
131
  () => isLoggedIn.value || isGuestSession.value,
118
132
  );
119
133
 
134
+ // Delivery rules need the shipping address: once the guest has saved it,
135
+ // the cart tells whether the chosen method works there.
136
+ watch(
137
+ () => customerDataAvailable.value,
138
+ (available, before) => {
139
+ if (!available || before) return;
140
+ ensureAvailableCheckoutMethods().catch((error) => {
141
+ console.error("[checkout][ensureAvailableCheckoutMethods]", error);
142
+ });
143
+ },
144
+ );
145
+
120
146
  const shippingAndPaymentSet = computed(
121
147
  () => selectedPaymentMethod.value && selectedShippingMethod.value,
122
148
  );
@@ -173,7 +199,11 @@ const checkoutButtonLabel = computed<string>(() => {
173
199
  return "Es werden aktuell keine weiteren Bestellungen mehr aufgenommen";
174
200
  }
175
201
 
176
- if (isShippingMethodBlocked.value || isPaymentMethodBlocked.value) {
202
+ if (isShippingMethodBlocked.value) {
203
+ return `${shippingMethodName.value} ist hier nicht möglich`;
204
+ }
205
+
206
+ if (isPaymentMethodBlocked.value) {
177
207
  return `Aktuell ist keine ${blockedMethodLabel.value} verfügbar`;
178
208
  }
179
209
 
@@ -199,10 +229,28 @@ const checkoutButtonLabel = computed<string>(() => {
199
229
  <span class="text-sb-accent">{{ section.number }}</span>
200
230
  {{ section.title }}
201
231
  </h2>
202
- <CheckoutPaymentAndDelivery
203
- v-if="section.id === 'versand'"
204
- part="shipping"
205
- />
232
+ <template v-if="section.id === 'versand'">
233
+ <CheckoutPaymentAndDelivery part="shipping" />
234
+ <p
235
+ v-if="isShippingMethodBlocked && customerDataAvailable"
236
+ role="alert"
237
+ class="mt-3 flex gap-3 rounded-sb-control border-[1.5px] border-sb-danger p-4 text-sm"
238
+ >
239
+ <span class="font-bold text-sb-danger" aria-hidden="true">!</span>
240
+ <span
241
+ >{{ shippingMethodName }} ist für Ihre Adresse oder Ihren
242
+ Warenkorb leider nicht möglich. Bitte wählen Sie eine andere
243
+ Bestellart oder ändern Sie Ihre Adresse.</span
244
+ >
245
+ </p>
246
+ <p
247
+ v-else-if="isShippingMethodBlocked"
248
+ class="mt-3 text-sm text-sb-ink-muted"
249
+ >
250
+ Ob {{ shippingMethodName }} an Ihre Adresse möglich ist, sehen Sie,
251
+ sobald Sie Ihre Angaben gespeichert haben.
252
+ </p>
253
+ </template>
206
254
  <CheckoutDeliveryTimeSelect
207
255
  v-else-if="section.id === 'zeit'"
208
256
  v-model:valid="isValidTime"
@@ -41,24 +41,24 @@ type MethodGuardConfig<M extends CheckoutMethod> = {
41
41
  };
42
42
 
43
43
  /**
44
- * Detects a blocked shipping or payment method in the cart and switches to
45
- * an available one (sales-channel default first, otherwise the first
44
+ * Detects a blocked payment method in the cart and switches to an
45
+ * available one (sales-channel default first, otherwise the first
46
46
  * available), mirroring what Shopware's own storefront does.
47
47
  *
48
48
  * The Store API does not perform this switch itself. Without it, order
49
- * creation fails with `CHECKOUT__CART_INVALID`
50
- * (`shipping-method-blocked` / `payment-method-blocked`).
49
+ * creation fails with `CHECKOUT__CART_INVALID` (`payment-method-blocked`).
50
+ *
51
+ * A blocked shipping method is only reported, never switched: its rule
52
+ * usually needs the shipping address (delivery area), which a guest enters
53
+ * after choosing delivery or pickup. Switching turned every delivery into
54
+ * a pickup before the address was known (La Fattoria, 2.0.2). With an
55
+ * address the checkout says the method is not possible and the customer
56
+ * picks another one.
51
57
  */
52
58
  export function useCheckoutMethodGuard() {
53
59
  const { cart, refreshCart } = useCart();
54
- const {
55
- getShippingMethods,
56
- setShippingMethod,
57
- selectedShippingMethod,
58
- getPaymentMethods,
59
- setPaymentMethod,
60
- selectedPaymentMethod,
61
- } = useCheckout();
60
+ const { getPaymentMethods, setPaymentMethod, selectedPaymentMethod } =
61
+ useCheckout();
62
62
  const { sessionContext } = useSessionContext();
63
63
 
64
64
  const isShippingMethodBlocked = computed(() =>
@@ -70,15 +70,6 @@ export function useCheckoutMethodGuard() {
70
70
 
71
71
  const isResolving = ref(false);
72
72
 
73
- const shippingConfig: MethodGuardConfig<Schemas["ShippingMethod"]> = {
74
- isBlocked: () => isShippingMethodBlocked.value,
75
- selected: () => selectedShippingMethod.value,
76
- loadAvailable: async () =>
77
- (await getShippingMethods({ forceReload: true })).value,
78
- defaultId: () => sessionContext.value?.salesChannel?.shippingMethodId,
79
- select: (id) => setShippingMethod({ id }),
80
- };
81
-
82
73
  const paymentConfig: MethodGuardConfig<Schemas["PaymentMethod"]> = {
83
74
  isBlocked: () => isPaymentMethodBlocked.value,
84
75
  selected: () => selectedPaymentMethod.value,
@@ -137,11 +128,11 @@ export function useCheckoutMethodGuard() {
137
128
  }
138
129
 
139
130
  /**
140
- * Refreshes the cart and, if the selected shipping method is blocked,
141
- * switches to an available one.
131
+ * Refreshes the cart and tells whether the selected shipping method is
132
+ * available. Never switches it (see above).
142
133
  */
143
134
  function ensureAvailableShippingMethod(): Promise<boolean> {
144
- return run(() => resolve(shippingConfig));
135
+ return run(async () => !isShippingMethodBlocked.value);
145
136
  }
146
137
 
147
138
  /**
@@ -153,17 +144,15 @@ export function useCheckoutMethodGuard() {
153
144
  }
154
145
 
155
146
  /**
156
- * Refreshes the cart and resolves blocked shipping and payment methods.
157
- * Shipping is handled first because payment availability rules may
158
- * depend on the shipping method. If shipping cannot be resolved the
159
- * checkout stays blocked anyway, so payment is left untouched to avoid
160
- * a pointless switch.
147
+ * Refreshes the cart and resolves a blocked payment method. A blocked
148
+ * shipping method stays as it is; payment rules may depend on the
149
+ * shipping method, so payment is then left untouched as well.
161
150
  *
162
151
  * @returns `true` when both methods are available afterwards.
163
152
  */
164
153
  function ensureAvailableCheckoutMethods(): Promise<boolean> {
165
154
  return run(async () => {
166
- if (!(await resolve(shippingConfig))) return false;
155
+ if (isShippingMethodBlocked.value) return false;
167
156
  return resolve(paymentConfig);
168
157
  });
169
158
  }
@@ -5,15 +5,13 @@ import type { Schemas } from "#shopware";
5
5
  * sales channel as a choice before the customer starts ordering. Which
6
6
  * methods exist and which payment methods they allow is decided by the
7
7
  * Shopware rules; after a switch the guard moves a payment method the new
8
- * shipping method blocks.
8
+ * shipping method blocks. All active methods are offered, also those whose
9
+ * rule needs an address the guest has not entered yet.
9
10
  */
10
11
  export function useOrderMode() {
11
- const {
12
- shippingMethods,
13
- getShippingMethods,
14
- selectedShippingMethod,
15
- setShippingMethod,
16
- } = useCheckout();
12
+ const { selectedShippingMethod, setShippingMethod } = useCheckout();
13
+ const { methods: shippingMethods, load: loadShippingMethods } =
14
+ useShippingMethodChoice();
17
15
  const { refreshCart } = useCart();
18
16
  const { ensureAvailableCheckoutMethods } = useCheckoutMethodGuard();
19
17
 
@@ -55,7 +53,7 @@ export function useOrderMode() {
55
53
 
56
54
  async function load() {
57
55
  try {
58
- await getShippingMethods();
56
+ await loadShippingMethods();
59
57
  } catch (error) {
60
58
  console.error("[menu][useOrderMode] shipping methods", error);
61
59
  }
@@ -0,0 +1,37 @@
1
+ import type { Schemas } from "#shopware";
2
+
3
+ /**
4
+ * All active shipping methods of the sales channel, for the order mode
5
+ * above the menu and the shipping section of the checkout.
6
+ *
7
+ * `useCheckout().getShippingMethods()` asks the Store API for the methods
8
+ * whose availability rule matches right now. A rule on the shipping
9
+ * address (La Fattoria: "Valide Lieferung", city Obertshausen, Hausen or
10
+ * Lämmerspiel) never matches before the guest has entered an address, so
11
+ * "Lieferung" vanished from the choice. Whether the chosen method works
12
+ * for the address is checked in the cart (`shipping-method-blocked`).
13
+ */
14
+ export function useShippingMethodChoice() {
15
+ const { apiClient } = useShopwareContext();
16
+ const methods = useState<Schemas["ShippingMethod"][]>(
17
+ "shopbite-shipping-method-choice",
18
+ () => [],
19
+ );
20
+
21
+ async function load({ forceReload } = { forceReload: false }) {
22
+ if (methods.value.length && !forceReload) return methods;
23
+ const response = await apiClient.invoke(
24
+ "readShippingMethod post /shipping-method",
25
+ {
26
+ body: { associations: { prices: {} } },
27
+ query: { onlyAvailable: false },
28
+ },
29
+ );
30
+ methods.value = [...(response.data.elements ?? [])].sort(
31
+ (a, b) => (a.position ?? 0) - (b.position ?? 0),
32
+ );
33
+ return methods;
34
+ }
35
+
36
+ return { methods, load };
37
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shopbite-de/storefront",
3
- "version": "2.0.2",
3
+ "version": "2.0.3",
4
4
  "main": "nuxt.config.ts",
5
5
  "description": "Shopware storefront for food delivery shops",
6
6
  "keywords": [
@@ -40,16 +40,19 @@ mockNuxtImport("useCheckout", () => () => ({
40
40
  { id: "cash", distinguishableName: "Bar" },
41
41
  { id: "ec", distinguishableName: "EC-Karte" },
42
42
  ]),
43
- shippingMethods: ref([
44
- { id: "delivery", name: "Lieferung" },
45
- { id: "pickup", name: "Abholung" },
46
- ]),
47
43
  selectedPaymentMethod,
48
44
  selectedShippingMethod,
49
45
  setPaymentMethod: mocks.setPaymentMethod,
50
46
  setShippingMethod: mocks.setShippingMethod,
51
47
  getPaymentMethods: vi.fn(),
52
- getShippingMethods: vi.fn(),
48
+ }));
49
+ // all active methods, also those whose rule needs an address
50
+ mockNuxtImport("useShippingMethodChoice", () => () => ({
51
+ methods: ref([
52
+ { id: "delivery", name: "Lieferung" },
53
+ { id: "pickup", name: "Abholung" },
54
+ ]),
55
+ load: vi.fn(),
53
56
  }));
54
57
  mockNuxtImport("useCart", () => () => ({
55
58
  refreshCart: mocks.refreshCart,
@@ -8,6 +8,8 @@ const { state } = vi.hoisted(() => ({
8
8
  isLoading: true,
9
9
  hasFailed: false,
10
10
  validTime: false,
11
+ shippingBlocked: false,
12
+ customer: true,
11
13
  },
12
14
  }));
13
15
 
@@ -19,7 +21,7 @@ mockNuxtImport("useOpeningHoursData", () => () => ({
19
21
  mockNuxtImport("useCheckout", () => () => ({
20
22
  createOrder: vi.fn(),
21
23
  selectedPaymentMethod: ref({ id: "pm1" }),
22
- selectedShippingMethod: ref({ id: "sm1" }),
24
+ selectedShippingMethod: ref({ id: "sm1", name: "Lieferung" }),
23
25
  }));
24
26
 
25
27
  mockNuxtImport("useCart", () => () => ({
@@ -28,7 +30,7 @@ mockNuxtImport("useCart", () => () => ({
28
30
 
29
31
  mockNuxtImport("useUser", () => () => ({
30
32
  isLoggedIn: ref(false),
31
- isGuestSession: ref(true),
33
+ isGuestSession: ref(state.customer),
32
34
  refreshUser: vi.fn(),
33
35
  }));
34
36
 
@@ -42,7 +44,7 @@ mockNuxtImport("useTrackEvent", () => () => ({
42
44
  }));
43
45
 
44
46
  mockNuxtImport("useCheckoutMethodGuard", () => () => ({
45
- isShippingMethodBlocked: ref(false),
47
+ isShippingMethodBlocked: ref(state.shippingBlocked),
46
48
  isPaymentMethodBlocked: ref(false),
47
49
  ensureAvailableCheckoutMethods: vi.fn().mockResolvedValue(true),
48
50
  }));
@@ -84,6 +86,8 @@ describe("Checkout Summary order button", () => {
84
86
  state.isLoading = true;
85
87
  state.hasFailed = false;
86
88
  state.validTime = false;
89
+ state.shippingBlocked = false;
90
+ state.customer = true;
87
91
  });
88
92
 
89
93
  it("shows a loading state while the opening hours are not loaded", async () => {
@@ -124,4 +128,36 @@ describe("Checkout Summary order button", () => {
124
128
  expect(button.text()).toBe("Zahlungspflichtig bestellen");
125
129
  expect(button.attributes("disabled")).toBeUndefined();
126
130
  });
131
+
132
+ // La Fattoria: "Lieferung" needs a shipping city in the delivery area
133
+ it("says delivery is not possible once the address is known", async () => {
134
+ state.isLoading = false;
135
+ state.validTime = true;
136
+ state.shippingBlocked = true;
137
+
138
+ const button = await mountSummary();
139
+ const page = button.element.closest(".grid")!;
140
+
141
+ expect(button.text()).toBe("Lieferung ist hier nicht möglich");
142
+ expect(button.attributes("disabled")).toBeDefined();
143
+ expect(page.textContent).toContain(
144
+ "Lieferung ist für Ihre Adresse oder Ihren Warenkorb leider nicht möglich",
145
+ );
146
+ });
147
+
148
+ it("only hints at the address check before the guest entered one", async () => {
149
+ state.isLoading = false;
150
+ state.validTime = true;
151
+ state.shippingBlocked = true;
152
+ state.customer = false;
153
+
154
+ const button = await mountSummary();
155
+ const page = button.element.closest(".grid")!;
156
+
157
+ expect(button.text()).toBe("Bitte zuerst Ihre Angaben speichern");
158
+ expect(page.textContent).toContain(
159
+ "Ob Lieferung an Ihre Adresse möglich ist",
160
+ );
161
+ expect(page.querySelector('[role="alert"]')).toBeNull();
162
+ });
127
163
  });
@@ -28,16 +28,19 @@ mockNuxtImport("useCheckout", () => () => ({
28
28
  { id: "pm1", distinguishableName: "Payment 1" },
29
29
  { id: "pm2", distinguishableName: "Payment 2" },
30
30
  ]),
31
- shippingMethods: ref([
32
- { id: "sm1", name: "Shipping 1" },
33
- { id: "sm2", name: "Shipping 2" },
34
- ]),
35
31
  selectedPaymentMethod,
36
32
  selectedShippingMethod,
37
33
  setPaymentMethod: mockSetPaymentMethod,
38
34
  setShippingMethod: mockSetShippingMethod,
39
35
  getPaymentMethods: vi.fn(),
40
- getShippingMethods: vi.fn(),
36
+ }));
37
+
38
+ mockNuxtImport("useShippingMethodChoice", () => () => ({
39
+ methods: ref([
40
+ { id: "sm1", name: "Shipping 1" },
41
+ { id: "sm2", name: "Shipping 2" },
42
+ ]),
43
+ load: vi.fn(),
41
44
  }));
42
45
 
43
46
  mockNuxtImport("useCart", () => () => ({
@@ -154,66 +154,21 @@ describe("useCheckoutMethodGuard", () => {
154
154
  expect(isShippingMethodBlocked.value).toBe(false);
155
155
  });
156
156
 
157
- it("switches to the sales-channel default shipping method when blocked", async () => {
157
+ it("never switches a blocked shipping method, it only reports it", async () => {
158
+ // La Fattoria: "Lieferung" is blocked until the guest has entered an
159
+ // address in the delivery area; switching made every order a pickup
158
160
  cart.value = cartWith({ [shippingBlocked.key]: shippingBlocked });
159
- mockRefreshCart.mockImplementationOnce(async () => {});
160
- nextRefreshSets({});
161
- const extra = {
162
- id: "sm-extra",
163
- name: "Express",
164
- position: 0,
165
- } as Schemas["ShippingMethod"];
166
- mockGetShippingMethods.mockResolvedValue(ref([extra, delivery, pickup]));
167
-
168
- const { ensureAvailableShippingMethod } = useCheckoutMethodGuard();
169
-
170
- await expect(ensureAvailableShippingMethod()).resolves.toBe(true);
171
-
172
- expect(mockGetShippingMethods).toHaveBeenCalledWith({
173
- forceReload: true,
174
- });
175
- expect(mockSetShippingMethod).toHaveBeenCalledWith({ id: pickup.id });
176
- expect(mockRefreshCart).toHaveBeenCalledTimes(2);
177
- });
178
-
179
- it("falls back to the first available method when the default is not available", async () => {
180
- cart.value = cartWith({ [shippingBlocked.key]: shippingBlocked });
181
- sessionContext.value = {
182
- salesChannel: { shippingMethodId: delivery.id },
183
- };
184
- mockRefreshCart.mockImplementationOnce(async () => {});
185
- nextRefreshSets({});
186
- // The blocked method is still returned by the API in some setups
187
- mockGetShippingMethods.mockResolvedValue(ref([delivery, pickup]));
188
-
189
- const { ensureAvailableShippingMethod } = useCheckoutMethodGuard();
190
-
191
- await expect(ensureAvailableShippingMethod()).resolves.toBe(true);
192
- expect(mockSetShippingMethod).toHaveBeenCalledWith({ id: pickup.id });
193
- });
194
-
195
- it("returns false when no alternative shipping method exists", async () => {
196
- cart.value = cartWith({ [shippingBlocked.key]: shippingBlocked });
197
- mockGetShippingMethods.mockResolvedValue(ref([delivery]));
198
161
 
199
162
  const { ensureAvailableShippingMethod, isShippingMethodBlocked } =
200
163
  useCheckoutMethodGuard();
201
164
 
202
165
  await expect(ensureAvailableShippingMethod()).resolves.toBe(false);
203
166
 
167
+ expect(mockRefreshCart).toHaveBeenCalledTimes(1);
168
+ expect(mockGetShippingMethods).not.toHaveBeenCalled();
204
169
  expect(mockSetShippingMethod).not.toHaveBeenCalled();
205
170
  expect(isShippingMethodBlocked.value).toBe(true);
206
171
  });
207
-
208
- it("returns false when the cart is still blocked after switching", async () => {
209
- cart.value = cartWith({ [shippingBlocked.key]: shippingBlocked });
210
-
211
- const { ensureAvailableShippingMethod } = useCheckoutMethodGuard();
212
-
213
- await expect(ensureAvailableShippingMethod()).resolves.toBe(false);
214
-
215
- expect(mockSetShippingMethod).toHaveBeenCalledWith({ id: pickup.id });
216
- });
217
172
  });
218
173
 
219
174
  describe("ensureAvailablePaymentMethod", () => {
@@ -260,40 +215,17 @@ describe("useCheckoutMethodGuard", () => {
260
215
  expect(mockSetPaymentMethod).not.toHaveBeenCalled();
261
216
  });
262
217
 
263
- it("resolves shipping first, then payment, when both are blocked", async () => {
264
- cart.value = cartWith({
265
- [shippingBlocked.key]: shippingBlocked,
266
- [paymentBlocked.key]: paymentBlocked,
267
- });
268
- mockRefreshCart.mockImplementationOnce(async () => {});
269
- // after shipping switch: only payment still blocked
270
- nextRefreshSets({ [paymentBlocked.key]: paymentBlocked });
271
- // after payment switch: clean
272
- nextRefreshSets({});
273
-
274
- const { ensureAvailableCheckoutMethods } = useCheckoutMethodGuard();
275
-
276
- await expect(ensureAvailableCheckoutMethods()).resolves.toBe(true);
277
-
278
- expect(mockSetShippingMethod).toHaveBeenCalledWith({ id: pickup.id });
279
- expect(mockSetPaymentMethod).toHaveBeenCalledWith({ id: paypal.id });
280
- expect(mockSetShippingMethod.mock.invocationCallOrder[0]).toBeLessThan(
281
- mockSetPaymentMethod.mock.invocationCallOrder[0] as number,
282
- );
283
- expect(mockRefreshCart).toHaveBeenCalledTimes(3);
284
- });
285
-
286
- it("leaves the payment method untouched when shipping cannot be resolved", async () => {
218
+ it("keeps a blocked shipping method and leaves payment untouched", async () => {
287
219
  cart.value = cartWith({
288
220
  [shippingBlocked.key]: shippingBlocked,
289
221
  [paymentBlocked.key]: paymentBlocked,
290
222
  });
291
- mockGetShippingMethods.mockResolvedValue(ref([delivery]));
292
223
 
293
224
  const { ensureAvailableCheckoutMethods } = useCheckoutMethodGuard();
294
225
 
295
226
  await expect(ensureAvailableCheckoutMethods()).resolves.toBe(false);
296
227
 
228
+ expect(mockSetShippingMethod).not.toHaveBeenCalled();
297
229
  expect(mockGetPaymentMethods).not.toHaveBeenCalled();
298
230
  expect(mockSetPaymentMethod).not.toHaveBeenCalled();
299
231
  });
@@ -310,18 +242,18 @@ describe("useCheckoutMethodGuard", () => {
310
242
  });
311
243
 
312
244
  it("serializes concurrent calls so the switch happens only once", async () => {
313
- cart.value = cartWith({ [shippingBlocked.key]: shippingBlocked });
245
+ cart.value = cartWith({ [paymentBlocked.key]: paymentBlocked });
314
246
  let releaseFirstRefresh: () => void = () => {};
315
247
  mockRefreshCart.mockImplementationOnce(
316
248
  () => new Promise<void>((r) => (releaseFirstRefresh = r)),
317
249
  );
318
250
  nextRefreshSets({});
319
251
 
320
- const { ensureAvailableCheckoutMethods, ensureAvailableShippingMethod } =
252
+ const { ensureAvailableCheckoutMethods, ensureAvailablePaymentMethod } =
321
253
  useCheckoutMethodGuard();
322
254
 
323
255
  const first = ensureAvailableCheckoutMethods();
324
- const second = ensureAvailableShippingMethod();
256
+ const second = ensureAvailablePaymentMethod();
325
257
  await Promise.resolve();
326
258
  expect(mockRefreshCart).toHaveBeenCalledTimes(1);
327
259
 
@@ -329,11 +261,11 @@ describe("useCheckoutMethodGuard", () => {
329
261
  await expect(first).resolves.toBe(true);
330
262
  await expect(second).resolves.toBe(true);
331
263
 
332
- expect(mockSetShippingMethod).toHaveBeenCalledTimes(1);
264
+ expect(mockSetPaymentMethod).toHaveBeenCalledTimes(1);
333
265
  // second call re-checked after the first one finished
334
266
  expect(mockRefreshCart).toHaveBeenCalledTimes(3);
335
267
  expect(mockRefreshCart.mock.invocationCallOrder[2]).toBeGreaterThan(
336
- mockSetShippingMethod.mock.invocationCallOrder[0] as number,
268
+ mockSetPaymentMethod.mock.invocationCallOrder[0] as number,
337
269
  );
338
270
  });
339
271
 
@@ -0,0 +1,46 @@
1
+ import { describe, it, expect, vi, beforeEach } from "vitest";
2
+ import { mockNuxtImport } from "@nuxt/test-utils/runtime";
3
+
4
+ const { mockInvoke } = vi.hoisted(() => ({ mockInvoke: vi.fn() }));
5
+
6
+ mockNuxtImport("useShopwareContext", () => () => ({
7
+ apiClient: { invoke: mockInvoke },
8
+ }));
9
+
10
+ describe("useShippingMethodChoice", () => {
11
+ beforeEach(() => {
12
+ vi.clearAllMocks();
13
+ mockInvoke.mockResolvedValue({
14
+ data: {
15
+ elements: [
16
+ { id: "pickup", name: "Abholung", position: 2 },
17
+ { id: "delivery", name: "Lieferung", position: 1 },
18
+ ],
19
+ },
20
+ });
21
+ });
22
+
23
+ it("loads all active methods, also those whose rule needs an address", async () => {
24
+ // "Lieferung" at La Fattoria only matches with a shipping city in the
25
+ // delivery area; onlyAvailable hid it from guests without an address
26
+ const { methods, load } = useShippingMethodChoice();
27
+ await load({ forceReload: true });
28
+
29
+ expect(mockInvoke).toHaveBeenCalledWith(
30
+ "readShippingMethod post /shipping-method",
31
+ expect.objectContaining({ query: { onlyAvailable: false } }),
32
+ );
33
+ expect(methods.value.map((method) => method.name)).toEqual([
34
+ "Lieferung",
35
+ "Abholung",
36
+ ]);
37
+ });
38
+
39
+ it("does not reload once loaded", async () => {
40
+ const { load } = useShippingMethodChoice();
41
+ await load({ forceReload: true });
42
+ await load();
43
+
44
+ expect(mockInvoke).toHaveBeenCalledTimes(1);
45
+ });
46
+ });