@shopbite-de/storefront 2.2.1 → 2.4.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 (69) hide show
  1. package/.github/workflows/build.yaml +2 -2
  2. package/.github/workflows/ci.yaml +11 -11
  3. package/.nuxtrc +1 -1
  4. package/CLAUDE.md +13 -7
  5. package/app/app.vue +10 -7
  6. package/app/components/Address/Fields.vue +1 -2
  7. package/app/components/Category/Breadcrumb.vue +9 -10
  8. package/app/components/Checkout/Summary.vue +27 -2
  9. package/app/components/Header.vue +6 -2
  10. package/app/components/Menu/BonCard.vue +1 -2
  11. package/app/components/Order/Confirmation.vue +1 -2
  12. package/app/components/Product/QuickView.vue +1 -2
  13. package/app/composables/useBusinessHours.ts +35 -14
  14. package/app/composables/useHolidays.ts +31 -11
  15. package/app/composables/useHomeMenuCategories.ts +6 -34
  16. package/app/composables/useLiveShopData.ts +17 -0
  17. package/app/composables/useNavigation.ts +14 -66
  18. package/app/composables/useNavigationSearch.ts +8 -31
  19. package/app/composables/useRestaurantSchema.ts +2 -13
  20. package/app/composables/useSeoUrlRoute.ts +21 -0
  21. package/app/composables/useShopBiteConfig.ts +50 -6
  22. package/app/composables/useTopSellers.ts +2 -43
  23. package/app/error.vue +4 -0
  24. package/docs/notes/2026-09-10-issue-275-accessibility.md +2 -2
  25. package/docs/notes/2026-09-12-issue-327-home-hero.md +1 -1
  26. package/docs/notes/2026-09-13-issue-332-home-info-cards.md +1 -3
  27. package/docs/notes/2026-09-21-issue-273-cache-and-demo-video.md +1 -1
  28. package/docs/notes/2026-09-21-issue-363-non-fatal-404.md +1 -1
  29. package/docs/notes/2026-09-23-issue-388-home-sections.md +2 -2
  30. package/docs/notes/2026-10-05-issue-401-restaurant-schema-ordering.md +1 -1
  31. package/docs/notes/2026-11-18-dependency-update.md +118 -0
  32. package/modules/theme.ts +1 -1
  33. package/node.dockerfile +7 -7
  34. package/nuxt.config.ts +22 -1
  35. package/package.json +40 -40
  36. package/pnpm-workspace.yaml +0 -2
  37. package/server/api/_cache/purge.post.ts +6 -3
  38. package/server/api/breadcrumb/[categoryId].get.ts +31 -0
  39. package/server/api/navigation/[type].get.ts +97 -0
  40. package/server/api/payment-methods.get.ts +29 -0
  41. package/server/api/seo-url/index.get.ts +17 -0
  42. package/server/api/seo-url/known.get.ts +33 -0
  43. package/server/api/shopbite/business-hours.get.ts +22 -0
  44. package/server/api/shopbite/config.get.ts +6 -0
  45. package/server/api/shopbite/holidays.get.ts +20 -0
  46. package/server/api/top-sellers.get.ts +59 -0
  47. package/server/plugins/ai-crawlers.ts +1 -1
  48. package/server/plugins/site-url.ts +2 -2
  49. package/server/routes/llms.txt.ts +6 -2
  50. package/server/utils/backoff.ts +67 -0
  51. package/server/utils/cachePurge.ts +45 -12
  52. package/server/utils/menuRoot.ts +24 -18
  53. package/server/utils/seoPaths.ts +130 -0
  54. package/server/utils/seoUrlCache.ts +98 -0
  55. package/server/utils/shopBiteConfig.ts +30 -0
  56. package/server/utils/storeApi.ts +25 -1
  57. package/test/a11y/presets.test.ts +3 -1
  58. package/test/layer/nuxt.config.ts +1 -1
  59. package/test/nuxt/CheckoutOnePage.test.ts +2 -0
  60. package/test/nuxt/CheckoutSummary.test.ts +38 -2
  61. package/test/nuxt/HeaderFooterPreset.test.ts +13 -4
  62. package/test/nuxt/liveShopData.test.ts +114 -0
  63. package/test/nuxt/useShopBiteConfig.test.ts +22 -0
  64. package/test/nuxt/useTopSellers.test.ts +10 -27
  65. package/test/unit/cachePurge.spec.ts +41 -0
  66. package/test/unit/layoutCacheRoutes.spec.ts +566 -0
  67. package/test/unit/nitroStubs.ts +99 -0
  68. package/test/unit/seoPaths.spec.ts +117 -0
  69. package/patches/@shopware__nuxt-module@1.5.2.patch +0 -13
@@ -2,33 +2,60 @@ import { timingSafeEqual } from "node:crypto";
2
2
 
3
3
  /**
4
4
  * Cache purge for the backoffice (#484): the cached Store API handlers keep
5
- * products, listings and categories for a day (`cacheTtl`). Nitro stores a
6
- * handler response under `cache:nitro:handlers:<name>:<escaped key>.json`;
7
- * the escaped key keeps the hex ids, so an id finds its entries.
5
+ * products, listings, categories and the layout data of every page for up
6
+ * to a day (`cacheTtl`). Nitro stores a handler response under
7
+ * `cache:nitro:handlers:<name>:<escaped key>.json` (cached functions under
8
+ * `cache:nitro:functions:`); the escaped key keeps the hex ids, so an id
9
+ * finds its entries.
8
10
  */
9
11
 
10
12
  /** Entries of one product: the product, its variants and its extras. */
11
13
  const PER_PRODUCT = ["product", "variant", "cross-selling"];
12
14
  /** Lists that may show any product or category. */
13
- const LISTS = ["listing", "search"];
14
- const ALL = [...PER_PRODUCT, "category", ...LISTS];
15
+ const LISTS = ["listing", "search", "top-sellers"];
16
+ /**
17
+ * Layout data of every page: navigations, SEO URL matches and breadcrumbs
18
+ * (a renamed or moved section changes them), plugin config, hours, closing
19
+ * days and payment methods. Small, so every purge takes all of it.
20
+ */
21
+ export const LAYOUT = [
22
+ "navigation",
23
+ "breadcrumb",
24
+ "business-hours",
25
+ "holidays",
26
+ "payment-methods",
27
+ ];
28
+ /** Always purged: the lists and the layout data. */
29
+ const SHARED = [...LISTS, ...LAYOUT];
30
+ const ALL = [...PER_PRODUCT, "category", ...SHARED];
15
31
  const HANDLERS = "cache:nitro:handlers:";
32
+ /** Cached functions: SEO URL matches, known SEO paths, plugin config. */
33
+ const FUNCTIONS = "cache:nitro:functions:";
34
+ const LAYOUT_FUNCTIONS = ["seo-url", "seo-paths", "shopbite-config"];
16
35
  /** Route rules with `swr` (llms.txt lists the menu). */
17
36
  const ROUTES = "cache:nitro:routes:";
18
37
 
19
38
  export interface PurgeTarget {
20
39
  products?: string[];
21
40
  categories?: string[];
41
+ /**
42
+ * Only the layout data, e.g. after the opening hours, closing days or the
43
+ * checkout switch changed. Combined with products or categories, their
44
+ * entries go as well.
45
+ */
46
+ layout?: boolean;
22
47
  }
23
48
 
24
- const handlerOf = (key: string) =>
25
- key.slice(HANDLERS.length).split(":")[0] ?? "";
49
+ const nameOf = (key: string, prefix: string) =>
50
+ key.slice(prefix.length).split(":")[0] ?? "";
26
51
  const compact = (id: string) => id.toLowerCase().replace(/[^0-9a-f]/g, "");
27
52
 
28
53
  /**
29
54
  * The cache keys to remove: without a target everything; with a target the
30
- * entries of the named products and categories plus every list. An extras
31
- * group change reaches many dishes, so cross-sellings always go completely.
55
+ * entries of the named products and categories plus every list and the
56
+ * layout data. An extras group change reaches many dishes, so
57
+ * cross-sellings always go completely. `layout` alone takes only the
58
+ * layout data.
32
59
  */
33
60
  export function keysToPurge(
34
61
  keys: string[],
@@ -36,13 +63,19 @@ export function keysToPurge(
36
63
  ): string[] {
37
64
  const products = (target.products ?? []).map(compact).filter(Boolean);
38
65
  const categories = (target.categories ?? []).map(compact).filter(Boolean);
39
- const everything = !products.length && !categories.length;
66
+ const menu = products.length > 0 || categories.length > 0;
67
+ const layoutOnly = Boolean(target.layout) && !menu;
68
+ const everything = !menu && !layoutOnly;
40
69
  return keys.filter((key) => {
70
+ if (key.startsWith(FUNCTIONS))
71
+ return LAYOUT_FUNCTIONS.includes(nameOf(key, FUNCTIONS));
41
72
  if (key.startsWith(ROUTES)) return true;
42
73
  if (!key.startsWith(HANDLERS)) return false;
43
- const handler = handlerOf(key);
74
+ const handler = nameOf(key, HANDLERS);
44
75
  if (!ALL.includes(handler)) return false;
45
- if (everything || LISTS.includes(handler) || handler === "cross-selling")
76
+ if (LAYOUT.includes(handler)) return true;
77
+ if (layoutOnly) return false;
78
+ if (everything || SHARED.includes(handler) || handler === "cross-selling")
46
79
  return true;
47
80
  if (handler === "category")
48
81
  return categories.some((id) => key.includes(id));
@@ -1,25 +1,31 @@
1
1
  import { pickMenuRoot } from "../../app/utils/menuRoot";
2
+ import { shopBiteConfig } from "./shopBiteConfig";
2
3
 
3
4
  /**
4
- * Server side of the menu root (#486, see app/utils/menuRoot.ts) for the
5
- * sitemap and llms.txt. The plugin value is kept for five minutes.
5
+ * Server side of the menu root (#486, see app/utils/menuRoot.ts). The plugin
6
+ * value comes from the cached plugin configuration (shopBiteConfig).
6
7
  */
7
- const pluginMenuRoot = defineCachedFunction(
8
- async (): Promise<string | null> => {
9
- const { shopware } = useRuntimeConfig().public;
10
- const config = await $fetch<{ menuCategoryId?: string }>(
11
- `${shopware.endpoint}/shopbite/config`,
12
- { headers: { "sw-access-key": shopware.accessToken } },
13
- ).catch(() => null);
14
- return config?.menuCategoryId ?? null;
15
- },
16
- { maxAge: 300, name: "menu-root", getKey: () => "menu-root" },
17
- );
8
+ function configuredRoot(): string | undefined {
9
+ return (
10
+ (useRuntimeConfig().public.shopBite.menuCategoryId as string | undefined) ||
11
+ undefined
12
+ );
13
+ }
18
14
 
15
+ /** For the sitemap and llms.txt: falls back to the navigation root. */
19
16
  export async function menuRootId(): Promise<string> {
20
- const configured = useRuntimeConfig().public.shopBite.menuCategoryId as
21
- string | undefined;
22
- return configured
23
- ? configured
24
- : pickMenuRoot(undefined, await pluginMenuRoot());
17
+ const configured = configuredRoot();
18
+ if (configured) return configured;
19
+ const config = await shopBiteConfig().catch(() => null);
20
+ return pickMenuRoot(undefined, config?.menuCategoryId);
21
+ }
22
+
23
+ /**
24
+ * For cached navigations: rejects when the plugin configuration cannot be
25
+ * loaded, so a menu built on the fallback root is never cached.
26
+ */
27
+ export async function menuRootIdStrict(): Promise<string> {
28
+ const configured = configuredRoot();
29
+ if (configured) return configured;
30
+ return pickMenuRoot(undefined, (await shopBiteConfig()).menuCategoryId);
25
31
  }
@@ -0,0 +1,130 @@
1
+ /**
2
+ * Known SEO paths of the menu sections (server/utils/seoUrlCache.ts,
3
+ * server/api/seo-url/known.get.ts): lets the server answer a path that no
4
+ * category ever had (`/wp-admin/`, `/.git/HEAD`) with a 404 without asking
5
+ * Shopware four times (canonical and old SEO URL, with and without the
6
+ * trailing slash). Wherever the comparison could differ from Shopware's
7
+ * database lookup, the path is let through.
8
+ */
9
+
10
+ /** Technical URLs (`/navigation/<id>`) are looked up by `pathInfo`. */
11
+ export function isTechnicalPath(path: string): boolean {
12
+ return /^\/(navigation|detail|landingPage)\//.test(path);
13
+ }
14
+
15
+ /** The only shape of a technical URL: prefix, entity id, optional slash. */
16
+ const TECHNICAL_URL = /^\/(navigation|detail|landingPage)\/[0-9a-f]{32}\/?$/i;
17
+
18
+ /**
19
+ * Paths no SEO URL can have, answered with a 404 without any lookup:
20
+ * undecodable or invalid UTF-8 (`/%ff`, `/%c0%ae`), double encoding
21
+ * (`%25`), `..` (path traversal probes) and technical prefixes without an
22
+ * entity id (`/navigation/zzz`).
23
+ */
24
+ export function isHostilePath(path: string): boolean {
25
+ if (/%25/i.test(path) || path.includes("..")) return true;
26
+ let decoded: string;
27
+ try {
28
+ decoded = decodeURIComponent(path);
29
+ } catch {
30
+ return true;
31
+ }
32
+ if (decoded.includes("..")) return true;
33
+ return isTechnicalPath(path) && !TECHNICAL_URL.test(path);
34
+ }
35
+ const CATEGORY_ROUTE = "frontend.navigation.page";
36
+ /** Shopware's default MAX_LIMIT of the Store API. */
37
+ export const SEO_PATH_PAGE_SIZE = 100;
38
+ const MAX_PAGES = 10;
39
+
40
+ function decode(path: string): string {
41
+ try {
42
+ return decodeURIComponent(path);
43
+ } catch {
44
+ return path;
45
+ }
46
+ }
47
+
48
+ /**
49
+ * The form two paths are compared in, close to MySQL's case- and
50
+ * accent-insensitive collation: decoded, lower case, without accents, `ß`,
51
+ * `æ`, `œ` written out, without leading and trailing slashes (the lookup
52
+ * tries both).
53
+ */
54
+ export function seoPathKey(path: string): string {
55
+ return decode(path)
56
+ .toLowerCase()
57
+ .normalize("NFD")
58
+ .replace(/\p{Diacritic}/gu, "")
59
+ .replace(/ß/g, "ss")
60
+ .replace(/æ/g, "ae")
61
+ .replace(/œ/g, "oe")
62
+ .replace(/^\/+|\/+$/g, "");
63
+ }
64
+
65
+ /**
66
+ * Whether a path may resolve to a SEO URL. `known` is null when the list is
67
+ * not available or too long: then every path may, and the lookup decides.
68
+ * A key with characters outside printable ASCII (or an undecodable `%`) is
69
+ * let through, since the collation may match it in ways not mapped here.
70
+ */
71
+ export function mayBeSeoPath(path: string, known: Set<string> | null): boolean {
72
+ if (isHostilePath(path)) return false;
73
+ if (!known || isTechnicalPath(path)) return true;
74
+ const key = seoPathKey(path);
75
+ if (/[^\x20-\x7e]/.test(key) || key.includes("%")) return true;
76
+ return known.has(key);
77
+ }
78
+
79
+ /** Store API criteria for one page of category SEO URLs. */
80
+ export function seoPathCriteria(isCanonical: true | null, page: number) {
81
+ return {
82
+ limit: SEO_PATH_PAGE_SIZE,
83
+ // `/seo-url` pages with `page`; `p` is ignored there
84
+ page,
85
+ // a stable order, so pages neither skip nor repeat rows
86
+ sort: [{ field: "id", order: "ASC" }],
87
+ filter: [
88
+ { type: "equals", field: "routeName", value: CATEGORY_ROUTE },
89
+ // the Store API returns old SEO URLs only when the criteria filter on
90
+ // `isCanonical`
91
+ { type: "equals", field: "isCanonical", value: isCanonical },
92
+ ],
93
+ includes: { seo_url: ["seoPathInfo"] },
94
+ };
95
+ }
96
+
97
+ type FetchPage = (
98
+ criteria: ReturnType<typeof seoPathCriteria>,
99
+ ) => Promise<{ seoPathInfo?: string }[]>;
100
+
101
+ async function pathsOf(
102
+ isCanonical: true | null,
103
+ fetchPage: FetchPage,
104
+ ): Promise<string[] | null> {
105
+ const paths: string[] = [];
106
+ for (let page = 1; page <= MAX_PAGES; page++) {
107
+ const elements = await fetchPage(seoPathCriteria(isCanonical, page));
108
+ paths.push(
109
+ ...elements.map((seoUrl) => seoPathKey(seoUrl.seoPathInfo ?? "")),
110
+ );
111
+ if (elements.length < SEO_PATH_PAGE_SIZE) return paths;
112
+ }
113
+ return null;
114
+ }
115
+
116
+ /**
117
+ * All current and old category SEO paths as `seoPathKey`s; null if there
118
+ * are more than MAX_PAGES pages of one kind (then nothing is filtered).
119
+ * Throws when Shopware fails.
120
+ */
121
+ export async function loadSeoPaths(
122
+ fetchPage: FetchPage,
123
+ ): Promise<string[] | null> {
124
+ const lists = await Promise.all([
125
+ pathsOf(true, fetchPage),
126
+ pathsOf(null, fetchPage),
127
+ ]);
128
+ if (lists.some((list) => list === null)) return null;
129
+ return lists.flatMap((list) => list ?? []);
130
+ }
@@ -0,0 +1,98 @@
1
+ import { createHash } from "node:crypto";
2
+ import type { components } from "../../api-types/storeApiTypes";
3
+ import { createResilientLoader } from "./backoff";
4
+ import { isTechnicalPath, loadSeoPaths } from "./seoPaths";
5
+ type SeoUrl = components["schemas"]["SeoUrl"];
6
+
7
+ type Lookup = { field: "pathInfo" | "seoPathInfo"; value: string };
8
+
9
+ /**
10
+ * What Shopware compares a path with: technical URLs by `pathInfo` (without
11
+ * the trailing slash), SEO URLs by `seoPathInfo` (without the leading one).
12
+ */
13
+ export function seoUrlLookup(path: string): Lookup {
14
+ return isTechnicalPath(path)
15
+ ? { field: "pathInfo", value: path.replace(/\/$/, "") }
16
+ : { field: "seoPathInfo", value: path.substring(1) };
17
+ }
18
+
19
+ // backs off during an outage; nothing is remembered (the cache keeps the
20
+ // exact matches)
21
+ const lookupLoader = createResilientLoader<{ elements?: SeoUrl[] }>(
22
+ () => false,
23
+ );
24
+
25
+ /**
26
+ * One SEO URL lookup. `exact` when the match spells the looked-up value
27
+ * (up to case): Shopware's collation also ignores accents and trailing
28
+ * spaces, and caching those variants would add an entry per spelling.
29
+ */
30
+ const cachedLookup = defineCachedFunction(
31
+ async (
32
+ field: Lookup["field"],
33
+ value: string,
34
+ ): Promise<{ match: SeoUrl | null; exact: boolean }> => {
35
+ const result = await lookupLoader(`${field}:${value}`, () =>
36
+ storeApiPost<{ elements?: SeoUrl[] }>("/seo-url", {
37
+ limit: 1,
38
+ filter: [{ type: "equals", field, value }],
39
+ }),
40
+ );
41
+ const match = result.elements?.[0] ?? null;
42
+ const spelled = match?.[field];
43
+ return {
44
+ match,
45
+ exact:
46
+ typeof spelled === "string" &&
47
+ spelled.toLowerCase() === value.toLowerCase(),
48
+ };
49
+ },
50
+ {
51
+ maxAge: useRuntimeConfig().public.shopBite.cacheTtl.seoUrl,
52
+ // a renamed section must not keep its old match beyond the TTL
53
+ swr: false,
54
+ name: "seo-url",
55
+ // the field keeps `/Navigation/<id>` (a SEO path) apart from the
56
+ // technical `/navigation/<id>`
57
+ getKey: (field: Lookup["field"], value: string) =>
58
+ createHash("sha1")
59
+ .update(`${field}:${value.toLowerCase()}`)
60
+ .digest("hex"),
61
+ // only exact matches: misses and loose spellings (a scanner probing
62
+ // `/wp-admin/` or `/Pizza/%20`) never create an entry
63
+ validate: (entry) =>
64
+ Boolean((entry.value as { exact?: boolean } | undefined)?.exact),
65
+ },
66
+ );
67
+
68
+ /** The canonical SEO URL of a path (/api/seo-url for useNavigationSearch). */
69
+ export async function findSeoUrl(path: string): Promise<SeoUrl | null> {
70
+ const { field, value } = seoUrlLookup(path);
71
+ return (await cachedLookup(field, value)).match;
72
+ }
73
+
74
+ /**
75
+ * All category SEO paths (server/utils/seoPaths.ts). `paths: null` (more
76
+ * than fit the pages) is kept for the TTL like a list; a failure throws and
77
+ * is not cached (/api/seo-url/known backs off instead). `loadedAt` lets the
78
+ * route reuse its Set until the entry changes.
79
+ */
80
+ export const knownSeoPaths = defineCachedFunction(
81
+ async (): Promise<{ paths: string[] | null; loadedAt: number }> => ({
82
+ paths: await loadSeoPaths(async (criteria) => {
83
+ const result = await storeApiPost<{ elements?: SeoUrl[] }>(
84
+ "/seo-url",
85
+ criteria,
86
+ );
87
+ return result.elements ?? [];
88
+ }),
89
+ loadedAt: Date.now(),
90
+ }),
91
+ {
92
+ maxAge: useRuntimeConfig().public.shopBite.cacheTtl.seoUrl,
93
+ // a new section must not 404 beyond the TTL
94
+ swr: false,
95
+ name: "seo-paths",
96
+ getKey: () => "seo-paths",
97
+ },
98
+ );
@@ -0,0 +1,30 @@
1
+ import type { components } from "../../api-types/storeApiTypes";
2
+ import { createResilientLoader } from "./backoff";
3
+ type ShopBiteConfig = components["schemas"]["ShopBiteConfig"];
4
+
5
+ /**
6
+ * `swr: false`: an answer is never older than `cacheTtl.config`. A failed
7
+ * request throws and is not cached.
8
+ */
9
+ const cachedConfig = defineCachedFunction(
10
+ async (): Promise<ShopBiteConfig> => await storeApiGet("/shopbite/config"),
11
+ {
12
+ maxAge: useRuntimeConfig().public.shopBite.cacheTtl.config,
13
+ swr: false,
14
+ name: "shopbite-config",
15
+ getKey: () => "shopbite-config",
16
+ },
17
+ );
18
+
19
+ const load = createResilientLoader<ShopBiteConfig>();
20
+
21
+ /**
22
+ * The ShopBite plugin configuration (delivery time, checkout switch, menu
23
+ * root) for server-side rendering, `/api/shopbite/config` and the menu root.
24
+ * When Shopware fails, the last good configuration is kept (the menu stays
25
+ * on its root) and Shopware is asked again only after a pause, so an outage
26
+ * does not multiply the requests; without one it throws.
27
+ */
28
+ export function shopBiteConfig(): Promise<ShopBiteConfig> {
29
+ return load("shopbite-config", () => cachedConfig());
30
+ }
@@ -26,9 +26,33 @@ export function storeApiPost<T>(
26
26
  ): Promise<T> {
27
27
  const { endpoint, accessToken } = useRuntimeConfig().public.shopware;
28
28
 
29
+ // Nitro's typed $fetch resolves the response type per internal route; for
30
+ // a generic T on an external URL it cannot, so the type is asserted.
29
31
  return $fetch<T>(`${endpoint}${path}`, {
30
32
  method: "POST",
31
33
  headers: { "sw-access-key": accessToken, ...options.headers },
32
34
  body,
33
- });
35
+ // a failing request reaches Shopware once (the cached routes back off
36
+ // instead)
37
+ retry: 0,
38
+ }) as Promise<T>;
39
+ }
40
+
41
+ /**
42
+ * Calls a Store API route that takes no criteria (the ShopBite plugin's
43
+ * config, business hours and holidays) with the storefront's access key.
44
+ */
45
+ export function storeApiGet<T>(
46
+ path: string,
47
+ options: Pick<NitroFetchOptions<string>, "headers" | "query"> = {},
48
+ ): Promise<T> {
49
+ const { endpoint, accessToken } = useRuntimeConfig().public.shopware;
50
+
51
+ return $fetch<T>(`${endpoint}${path}`, {
52
+ headers: { "sw-access-key": accessToken, ...options.headers },
53
+ query: options.query,
54
+ // ofetch retries a GET once by default; during an outage that doubles
55
+ // every request
56
+ retry: 0,
57
+ }) as Promise<T>;
34
58
  }
@@ -141,7 +141,9 @@ const sampleOrder = {
141
141
  };
142
142
 
143
143
  async function mockOrder(page: Page) {
144
- await page.route("**/store-api/order", (route) =>
144
+ // @shopware/composables 1.15 sends checkPromotion as a query parameter
145
+ // (/store-api/order?checkPromotion=true), which a glob would not match.
146
+ await page.route(/\/store-api\/order(\?|$)/, (route) =>
145
147
  route.fulfill({
146
148
  json: {
147
149
  orders: { elements: [sampleOrder], total: 1 },
@@ -1,5 +1,5 @@
1
1
  // A minimal shop that extends the storefront like the real shops do (La
2
- // Fattoria, quickstart, lead demos). CI builds it to catch imports that only
2
+ // Fattoria, the quickstart). CI builds it to catch imports that only
3
3
  // resolve inside the storefront itself, e.g. the `#shared` alias, which in a
4
4
  // layer points to the shop's shared/ folder (2.0.1).
5
5
  export default defineNuxtConfig({
@@ -36,7 +36,9 @@ mockNuxtImport("useUser", () => () => ({
36
36
  }));
37
37
  mockNuxtImport("useShopBiteConfig", () => () => ({
38
38
  isCheckoutEnabled: ref(true),
39
+ deliveryTime: ref(30),
39
40
  refresh: vi.fn(),
41
+ checkCheckoutEnabled: vi.fn().mockResolvedValue(true),
40
42
  }));
41
43
  mockNuxtImport("useTrackEvent", () => () => ({ trackOrder: vi.fn() }));
42
44
  mockNuxtImport("useCheckoutMethodGuard", () => () => ({
@@ -3,7 +3,11 @@ import { mountSuspended, mockNuxtImport } from "@nuxt/test-utils/runtime";
3
3
  import { defineComponent, h, onMounted, ref } from "vue";
4
4
  import Summary from "~/components/Checkout/Summary.vue";
5
5
 
6
- const { state } = vi.hoisted(() => ({
6
+ const { state, mocks } = vi.hoisted(() => ({
7
+ mocks: {
8
+ createOrder: vi.fn(),
9
+ checkCheckoutEnabled: vi.fn(),
10
+ },
7
11
  state: {
8
12
  isLoading: true,
9
13
  hasFailed: false,
@@ -19,7 +23,7 @@ mockNuxtImport("useOpeningHoursData", () => () => ({
19
23
  }));
20
24
 
21
25
  mockNuxtImport("useCheckout", () => () => ({
22
- createOrder: vi.fn(),
26
+ createOrder: mocks.createOrder,
23
27
  selectedPaymentMethod: ref({ id: "pm1" }),
24
28
  selectedShippingMethod: ref({ id: "sm1", name: "Lieferung" }),
25
29
  }));
@@ -37,6 +41,7 @@ mockNuxtImport("useUser", () => () => ({
37
41
  mockNuxtImport("useShopBiteConfig", () => () => ({
38
42
  isCheckoutEnabled: ref(true),
39
43
  refresh: vi.fn(),
44
+ checkCheckoutEnabled: mocks.checkCheckoutEnabled,
40
45
  }));
41
46
 
42
47
  mockNuxtImport("useTrackEvent", () => () => ({
@@ -160,4 +165,35 @@ describe("Checkout Summary order button", () => {
160
165
  );
161
166
  expect(page.querySelector('[role="alert"]')).toBeNull();
162
167
  });
168
+
169
+ it("does not order when Shopware says the checkout was switched off", async () => {
170
+ state.isLoading = false;
171
+ state.validTime = true;
172
+ mocks.checkCheckoutEnabled.mockResolvedValue(false);
173
+
174
+ const button = await mountSummary();
175
+ await button.trigger("click");
176
+ await new Promise((resolve) => setTimeout(resolve, 0));
177
+
178
+ expect(mocks.checkCheckoutEnabled).toHaveBeenCalled();
179
+ expect(mocks.createOrder).not.toHaveBeenCalled();
180
+ expect(button.element.closest(".grid")!.textContent).toContain(
181
+ "Es werden aktuell keine weiteren Bestellungen mehr aufgenommen",
182
+ );
183
+ });
184
+
185
+ it("does not order when the checkout switch cannot be checked", async () => {
186
+ state.isLoading = false;
187
+ state.validTime = true;
188
+ mocks.checkCheckoutEnabled.mockResolvedValue(null);
189
+
190
+ const button = await mountSummary();
191
+ await button.trigger("click");
192
+ await new Promise((resolve) => setTimeout(resolve, 0));
193
+
194
+ expect(mocks.createOrder).not.toHaveBeenCalled();
195
+ expect(button.element.closest(".grid")!.textContent).toContain(
196
+ "konnte nicht geprüft werden",
197
+ );
198
+ });
163
199
  });
@@ -46,10 +46,19 @@ mockNuxtImport("useWishlist", () => () => ({
46
46
  mockNuxtImport("useShopBiteConfig", () => () => ({
47
47
  isCheckoutEnabled: ref(true),
48
48
  }));
49
- mockNuxtImport("useUser", () => () => ({
50
- isLoggedIn: computed(() => state.loggedIn),
51
- isGuestSession: computed(() => false),
52
- logout: mocks.logout,
49
+ function userApi() {
50
+ return {
51
+ isLoggedIn: computed(() => state.loggedIn),
52
+ isGuestSession: computed(() => false),
53
+ logout: mocks.logout,
54
+ };
55
+ }
56
+ mockNuxtImport("useUser", () => () => userApi());
57
+ // Header.vue imports useUser from the package; since @shopware/composables
58
+ // 1.15 the auto-import mock above no longer reaches that import.
59
+ vi.mock("@shopware/composables", async (importOriginal) => ({
60
+ ...(await importOriginal<typeof import("@shopware/composables")>()),
61
+ useUser: () => userApi(),
53
62
  }));
54
63
  mockNuxtImport("useStoreStatus", () => () => ({ status: ref(null) }));
55
64
  mockNuxtImport("useBusinessHours", () => () => ({
@@ -0,0 +1,114 @@
1
+ import { describe, it, expect, vi, beforeEach } from "vitest";
2
+ import {
3
+ mockNuxtImport,
4
+ mountSuspended,
5
+ registerEndpoint,
6
+ } from "@nuxt/test-utils/runtime";
7
+ import { defineComponent, h } from "vue";
8
+ import {
9
+ loadShopBiteConfig,
10
+ SHOPBITE_CONFIG_KEY,
11
+ } from "~/composables/useShopBiteConfig";
12
+ import {
13
+ BUSINESS_HOURS_KEY,
14
+ loadBusinessHours,
15
+ } from "~/composables/useBusinessHours";
16
+ import { HOLIDAYS_KEY, loadHolidays } from "~/composables/useHolidays";
17
+ import { useLiveShopData } from "~/composables/useLiveShopData";
18
+
19
+ const { mockRefreshNuxtData, cached } = vi.hoisted(() => ({
20
+ mockRefreshNuxtData: vi.fn(),
21
+ cached: {
22
+ config: vi.fn(),
23
+ hours: vi.fn(),
24
+ holidays: vi.fn(),
25
+ },
26
+ }));
27
+
28
+ mockNuxtImport("refreshNuxtData", () => mockRefreshNuxtData);
29
+
30
+ registerEndpoint("/api/shopbite/config", () => cached.config());
31
+ registerEndpoint("/api/shopbite/business-hours", () => cached.hours());
32
+ registerEndpoint("/api/shopbite/holidays", () => cached.holidays());
33
+
34
+ const invoke = vi.fn();
35
+ const apiClient = { invoke } as unknown as Parameters<
36
+ typeof loadShopBiteConfig
37
+ >[0];
38
+
39
+ describe("shop data sources", () => {
40
+ beforeEach(() => {
41
+ vi.clearAllMocks();
42
+ });
43
+
44
+ it("renders the config from the server cache, the browser asks Shopware", async () => {
45
+ cached.config.mockReturnValue({ isCheckoutEnabled: false });
46
+ invoke.mockResolvedValue({ data: { isCheckoutEnabled: true } });
47
+
48
+ expect(await loadShopBiteConfig(apiClient, true)).toEqual({
49
+ isCheckoutEnabled: false,
50
+ });
51
+ expect(invoke).not.toHaveBeenCalled();
52
+
53
+ expect(await loadShopBiteConfig(apiClient, false)).toEqual({
54
+ isCheckoutEnabled: true,
55
+ });
56
+ expect(invoke).toHaveBeenCalledWith(
57
+ "shopbite.config.get get /shopbite/config",
58
+ );
59
+ });
60
+
61
+ it("retries the config in the browser like the opening hours", async () => {
62
+ invoke
63
+ .mockRejectedValueOnce(new Error("offline"))
64
+ .mockResolvedValue({ data: { isCheckoutEnabled: true } });
65
+
66
+ expect(await loadShopBiteConfig(apiClient, false, [0])).toEqual({
67
+ isCheckoutEnabled: true,
68
+ });
69
+ expect(invoke).toHaveBeenCalledTimes(2);
70
+ });
71
+
72
+ it("reads business hours and holidays from the cache on the server", async () => {
73
+ const hours = [{ dayOfWeek: 1, openingTime: "11:00" }];
74
+ const holidays = [{ start: "2026-12-24", end: "2026-12-26" }];
75
+ cached.hours.mockReturnValue({ businessHours: hours });
76
+ cached.holidays.mockReturnValue({ holidays });
77
+
78
+ expect(await loadBusinessHours(apiClient, true)).toEqual(hours);
79
+ expect(await loadHolidays(apiClient, true)).toEqual(holidays);
80
+ expect(invoke).not.toHaveBeenCalled();
81
+ });
82
+
83
+ it("asks Shopware for business hours and holidays in the browser", async () => {
84
+ invoke.mockImplementation(async (operation: string) =>
85
+ operation.includes("business-hour")
86
+ ? { data: { businessHours: ["h"] } }
87
+ : { data: { holidays: ["d"] } },
88
+ );
89
+
90
+ expect(await loadBusinessHours(apiClient, false, [])).toEqual(["h"]);
91
+ expect(await loadHolidays(apiClient, false, [])).toEqual(["d"]);
92
+ });
93
+ });
94
+
95
+ describe("useLiveShopData", () => {
96
+ it("reloads config, hours and holidays from Shopware after hydration", async () => {
97
+ await mountSuspended(
98
+ defineComponent({
99
+ setup() {
100
+ useLiveShopData();
101
+ return () => h("div");
102
+ },
103
+ }),
104
+ );
105
+
106
+ // refreshNuxtData waits for the end of hydration; a refresh() during
107
+ // hydration would return the server's (cached) payload
108
+ expect(mockRefreshNuxtData).toHaveBeenCalledWith([
109
+ SHOPBITE_CONFIG_KEY,
110
+ BUSINESS_HOURS_KEY,
111
+ HOLIDAYS_KEY,
112
+ ]);
113
+ });
114
+ });