@shopbite-de/storefront 2.1.1 → 2.2.1

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/.env.example CHANGED
@@ -50,4 +50,6 @@ NUXT_AI_CRAWLERS_SEARCH=true
50
50
  NUXT_AI_CRAWLERS_TRAINING=true
51
51
 
52
52
  NUXT_STORE_NAME="ShopBite"
53
- STORE_DESCRIPTION="Reduziere deine Kosten und steigere deinen Umsatz"
53
+ STORE_DESCRIPTION="Reduziere deine Kosten und steigere deinen Umsatz"
54
+ # Secret of POST /api/_cache/purge, the backoffice empties the Store API caches after menu changes (empty = off)
55
+ NUXT_CACHE_PURGE_SECRET=
@@ -65,7 +65,7 @@ jobs:
65
65
  - name: Install pnpm
66
66
  uses: pnpm/action-setup@v6
67
67
  with:
68
- version: 12.9.1
68
+ version: 12.11.2
69
69
 
70
70
  - name: Install Node.js
71
71
  uses: actions/setup-node@v7
@@ -25,7 +25,7 @@ jobs:
25
25
 
26
26
  - uses: pnpm/action-setup@v6
27
27
  with:
28
- version: 12.9.1
28
+ version: 12.11.2
29
29
 
30
30
  - uses: actions/setup-node@v7
31
31
  with:
@@ -69,7 +69,7 @@ jobs:
69
69
 
70
70
  - uses: pnpm/action-setup@v6
71
71
  with:
72
- version: 12.9.1
72
+ version: 12.11.2
73
73
 
74
74
  - uses: actions/setup-node@v7
75
75
  with:
@@ -105,7 +105,7 @@ jobs:
105
105
 
106
106
  - uses: pnpm/action-setup@v6
107
107
  with:
108
- version: 12.9.1
108
+ version: 12.11.2
109
109
 
110
110
  - uses: actions/setup-node@v7
111
111
  with:
@@ -134,7 +134,7 @@ jobs:
134
134
 
135
135
  - uses: pnpm/action-setup@v6
136
136
  with:
137
- version: 12.9.1
137
+ version: 12.11.2
138
138
 
139
139
  - uses: actions/setup-node@v7
140
140
  with:
@@ -172,7 +172,7 @@ jobs:
172
172
 
173
173
  - uses: pnpm/action-setup@v6
174
174
  with:
175
- version: 12.9.1
175
+ version: 12.11.2
176
176
 
177
177
  - uses: actions/setup-node@v7
178
178
  with:
package/CLAUDE.md CHANGED
@@ -98,10 +98,11 @@ Key custom composables:
98
98
 
99
99
  The storefront reads plain Shopware entities with fixed names; seed data must match them exactly (`shopware/scripts/seed-demo-menu.py` is a working example):
100
100
 
101
- - **Navigation:** menu sections are the children of the sales channel navigation root (`readNavigation main-navigation`), optionally scoped by `runtimeConfig.public.shopBite.menuCategoryId`. Category icon comes from the custom field `shopbite_category_icon` (icones.js.org name such as `i-lucide-pizza`), set by the ShopBite plugin.
101
+ - **Navigation:** menu sections are the children of the sales channel navigation root (`readNavigation main-navigation`), scoped to the menu root: `runtimeConfig.public.shopBite.menuCategoryId` if set, else `menuCategoryId` from `/store-api/shopbite/config` (plugin configuration per sales channel, #486). Always resolve it through `useMenuRootId()` (app) or `menuRootId()` (server), never read the env directly. Category icon comes from the custom field `shopbite_category_icon` (icones.js.org name such as `i-lucide-pizza`), set by the ShopBite plugin.
102
102
  - **Property groups:** `Hauptzutaten` (ingredients on the card, deselectable on the detail page, removed ones are appended to the cart label with "-"), `Vegetarisch` and `Vegan` with the option `Ja` (diet badges), `Küche` (kitchen badge). Filterable groups appear as listing filters.
103
103
  - **Extras:** product cross-sellings of type `productList`; the cross-selling name is the label ("Extras", "Beilagen"), the assigned products need a price and sales-channel visibility but no category. In the quick view each cross-selling is a collapsible checkbox list that shows 6 entries of a long list and a search field above 15 entries (`Product/CrossSelling.vue`). Selected extras are sent as children of a `container` line item (`useAddToCart.ts`, handled by the ShopBite plugin). The bon card opens the quick view sheet (`Product/QuickView.vue`), whose state is the `produkt` query parameter (product number) via `useProductQuickView` (#325). That deep link is the product URL (#289, no product pages): `productDeepLink()` (`app/utils/productUrl.ts`) takes the product SEO URL when it carries `?produkt=` (the ShopBite plugin sets the template, shopware-plugin#28; the number must be `|url_encode|raw` in the template, the SEO escaper slugifies `ß`) and otherwise builds it from the category SEO URL. The card name is a stretched link to it (a plain click stays in place); a number not in the list (a variant) is loaded and opens with its options selected. The quick view keeps its configuration in the URL (#411): `ohne` (deselected ingredients by name) and `extras` (extras by product number), written live with `router.replace` by `useQuickViewConfiguration`; a variant switch updates `produkt` without swapping the sheet's product (numbers the sheet switched to itself are pinned). The share button (`useShareLink`) uses the Web Share API, else copies the link.
104
104
  - **Custom fields on products:** `shopbite_receipt_print_type` (`number` prints the menu number on the receipt, `label` prints the name) and `shopbite_delivery_time_factor` (int) and `shopbite_cart_upsell` (bool, suggests the product on the order confirmation step `/bestellung/bestaetigen` via `useCartUpsell`; variant parents are never suggested, a flag on a parent applies to its variants), all from the ShopBite plugin.
105
+ - **Allergens and additives (#485):** property groups `Allergene` and `Zusatzstoffe` from the ShopBite plugin (shopware-plugin#36, maintained in the backoffice), code in the option custom field `shopbite_code` (A-R, 1-12), product custom field `shopbite_allergens_checked` = lists complete. `getFoodLabels()`/`foodLabelText()`/`allergensChecked()` in `app/utils/product.ts`. Shown only on request (#500): the bon card and the list show nothing, `Product/FoodLabels.vue` is an info button in the sheet's toolbar that opens a Reka popover (not teleported, so the dialog's focus trap holds) with the names written out; without `shopbite_allergens_checked` the sheet points to the restaurant's phone and never says "no allergens". **Includes filter `translated` too:** custom fields only come back when `customFields` is in the `product` and `property_group_option` includes (listing, search, product route, quick view, top sellers).
105
106
  - **Variants:** standard configurator settings (`Product/Configurator.vue`); `server/api/product/variant.get.ts` resolves a variant by option ids.
106
107
 
107
108
  ### Server routes
@@ -113,6 +114,8 @@ The storefront reads plain Shopware entities with fixed names; seed data must ma
113
114
  `server/utils/storeApi.ts` — `storeApiPost()` and `MEDIA_INCLUDES` for the routes above. Always send Store API criteria as a POST body (also via `apiClient.invoke("… post …", { body })`): as `_criteria` query parameters Shopware ignores the `includes` projection and returns every field (#312).
114
115
  Pages without content throw `createNotFoundError()` (`app/utils/notFound.ts`): fatal only in the browser, because a fatal error makes Nitro log a `[request error] [fatal]` block per scanner request (#363).
115
116
  `modules/dev-tooling.ts` registers `@nuxt/eslint`, `@nuxt/hints` and `@nuxt/test-utils/module` only when the storefront itself is the project (not for shops extending the layer, not inside `node_modules`); they are devDependencies, so never add them to `modules` in `nuxt.config.ts` (#378).
117
+ The cached Store API handlers (`defineCachedEventHandler`, TTL `public.shopBite.cacheTtl`, a day for products, listings, categories) can be emptied by the backoffice: `POST /api/_cache/purge` with `Authorization: Bearer $NUXT_CACHE_PURGE_SECRET` (route off without the secret, #484). `server/utils/cachePurge.ts` picks the Nitro keys (`cache:nitro:handlers:<name>:<escaped key>`) by id, so a new cached handler needs its `name` in `ALL` there and the id in its `getKey`.
118
+
116
119
  `modules/public-cache.ts` (local module, also active in shops extending the layer) adds a 30-day `Cache-Control` route rule for every file in the `public/` folders of all layers; Nitro serves them without one. `image.ipx.maxAge` gives resized logos the same lifetime. Replace a public file under a new name (#273).
117
120
  `server/api/content/*.get.ts` — Nuxt Content queries for the pages. Do not call `queryCollection()` in page code: in the browser it downloads the SQLite WASM build (865 KB) on client-side navigation (#314).
118
121
 
@@ -134,7 +137,7 @@ Pages without content throw `createNotFoundError()` (`app/utils/notFound.ts`): f
134
137
  - Components style only with the `--sb-*` colour tokens and `--font-sb-display`/`--font-sb-body` (the `--font` prefix makes @nuxt/fonts resolve the family and add metric fallbacks) through the `sb-*` utilities (`bg-sb-surface`, `text-sb-ink-muted`, `font-display`, `rounded-sb-control`). No colour mode switch: the preset fixes light or dark.
135
138
  - Base components live in `app/components/Sb/` (`SbButton`, `SbIconButton`, `SbSegmentedControl`, `SbSheet`, `SbChoiceGroup`, `SbCheckbox`, `SbField` + `SbInput`, `SbSelect` (native), `SbStepper`, `SbChip`, `SbStatusPill`, `SbStars`, `SbConfirmDialog`, `SbIcon` with inline stroke icons). Behaviour and accessibility come from Reka UI (radio groups, checkbox, dialog and alert dialog with focus trap). Every control is at least 44 px and has a visible focus ring; icon-only buttons need a `label`; toggles use `aria-pressed` with a stable name. Hide a base component responsively with a wrapper (`<span class="hidden sm:block">`): its own `inline-flex` wins over a `hidden` passed as class. Elements focused only by script (`tabindex="-1"`) get no focus ring. Entry animations go behind `motion-safe:` (a `motion-reduce:animate-none` loses against `data-[state=open]:animate-…`).
136
139
  - 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.
137
- - Menu (#441): `Category/Listing.vue` has three columns from `lg` (`MenuCategoryIndex` word list, the list, `MenuCartPanel`), `NavigationMobileTop` below `lg` (section chips; the open section's sub-categories as a second chip row led by "Alle", the current chip scrolls into view); `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()`).
140
+ - Menu (#441): `Category/Listing.vue` has three columns from `lg` (`MenuCategoryIndex` word list, the list, `MenuCartPanel`), `NavigationMobileTop` below `lg` (section chips; the open section's sub-categories as a second chip row led by "Alle", the current chip scrolls into view); `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()`). A section with sub-sections (#487) lists its dishes grouped: direct dishes first, then an `h2` per sub-section in navigation order (`groupBySubsections()`/`findCategory()` in `app/utils/menuGroups.ts`, needs `categoryIds` in the listing projection); the sub-section pages stay.
138
141
  - Product sheet (#442): `SbSheet` with a bon header (a custom `#header` gets the full width below a toolbar with the `#actions` and the close button; next to the buttons a long name broke after four letters on a 393 px phone) (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.
139
142
  - 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`.
140
143
  - 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 (`useWishlistEntries`, #467), content pages and `error.vue` (with its own `Header`/`Footer`, because the error page replaces `app.vue`) use the same pieces.
@@ -10687,6 +10687,11 @@
10687
10687
  "type": "integer",
10688
10688
  "minimum": 1,
10689
10689
  "description": "Default delivery time in minutes"
10690
+ },
10691
+ "menuCategoryId": {
10692
+ "type": "string",
10693
+ "pattern": "^[0-9a-f]{32}$",
10694
+ "description": "Root category of the menu: the configured menu category, else the navigation category of the sales channel"
10690
10695
  }
10691
10696
  },
10692
10697
  "required": ["isCheckoutEnabled", "deliveryTime"]
@@ -5362,6 +5362,8 @@ export type Schemas = {
5362
5362
  deliveryTime: number;
5363
5363
  /** Whether checkout is enabled for ShopBite */
5364
5364
  isCheckoutEnabled: boolean;
5365
+ /** Root category of the menu: the configured menu category, else the navigation category of the sales channel (plugin 2026-10, missing in older plugins) */
5366
+ menuCategoryId?: string;
5365
5367
  };
5366
5368
  ShopBiteWishlistItem: {
5367
5369
  /** Format: date-time */
@@ -46,6 +46,18 @@ useMenuSectionSchema(category, elements);
46
46
 
47
47
  const quickView = useProductQuickView(elements);
48
48
 
49
+ // A section with sub-sections lists its dishes under their sub-section (#487):
50
+ // direct dishes first, then one heading per sub-section in backoffice order.
51
+ // Navigation to them is the chip row (phones) and the word-list index (desktop).
52
+ const { menuCardNavigation } = useNavigation(true);
53
+ const grouped = computed(() =>
54
+ groupBySubsections(
55
+ elements.value,
56
+ findCategory(menuCardNavigation.value ?? undefined, props.id)?.children ??
57
+ undefined,
58
+ ),
59
+ );
60
+
49
61
  // Derived from the listing data instead of snapshotted at setup time, which
50
62
  // would be a hydration mismatch (#239); see useSortingSelection.
51
63
  const { currentSorting } = useSortingSelection(currentSortingOrder);
@@ -209,6 +221,46 @@ async function openFilterDrawer() {
209
221
  >
210
222
  <LazyProductCardSkeleton v-for="i in 6" :key="i" />
211
223
  </div>
224
+ <div
225
+ v-else-if="grouped"
226
+ class="flex flex-col gap-6 transition-opacity duration-200"
227
+ :class="{ 'pointer-events-none opacity-40': loading }"
228
+ >
229
+ <div v-if="grouped.direct.length" class="grid grid-cols-1 gap-3">
230
+ <MenuBonCardWhenVisible
231
+ v-for="product in grouped.direct"
232
+ :key="product.id"
233
+ :product="product"
234
+ :photo="menuView === 'bonPhoto'"
235
+ :href="productDeepLink(product, category?.seoUrl)"
236
+ @select="quickView.show"
237
+ />
238
+ </div>
239
+ <section
240
+ v-for="group in grouped.groups"
241
+ :id="`u-${group.id}`"
242
+ :key="group.id"
243
+ :aria-labelledby="`u-${group.id}-titel`"
244
+ class="scroll-mt-28"
245
+ >
246
+ <h2
247
+ :id="`u-${group.id}-titel`"
248
+ class="mb-3 font-display text-xl text-sb-ink"
249
+ >
250
+ {{ group.name }}
251
+ </h2>
252
+ <div class="grid grid-cols-1 gap-3">
253
+ <MenuBonCardWhenVisible
254
+ v-for="product in group.products"
255
+ :key="product.id"
256
+ :product="product"
257
+ :photo="menuView === 'bonPhoto'"
258
+ :href="productDeepLink(product, category?.seoUrl)"
259
+ @select="quickView.show"
260
+ />
261
+ </div>
262
+ </section>
263
+ </div>
212
264
  <div
213
265
  v-else
214
266
  class="grid grid-cols-1 gap-3 transition-opacity duration-200"
@@ -0,0 +1,66 @@
1
+ <script setup lang="ts">
2
+ import type { Schemas } from "#shopware";
3
+ import {
4
+ PopoverContent,
5
+ PopoverPortal,
6
+ PopoverRoot,
7
+ PopoverTrigger,
8
+ } from "reka-ui";
9
+
10
+ /**
11
+ * Allergens and additives of a dish behind an info button in the sheet's
12
+ * toolbar (#500): reachable before ordering, shown only to guests who look
13
+ * for them. Without the restaurant's confirmation an empty list is "not
14
+ * entered yet", so it never claims "free of allergens" then and points to
15
+ * the phone (#485). The content stays inside the sheet (no teleport), so
16
+ * the dialog's focus trap keeps working.
17
+ */
18
+ const props = defineProps<{ product: Schemas["Product"] }>();
19
+
20
+ const { site } = useRuntimeConfig().public;
21
+ const labels = computed(() =>
22
+ getFoodLabels(
23
+ props.product.sortedProperties as Schemas["PropertyGroup"][] | undefined,
24
+ ),
25
+ );
26
+ const checked = computed(() => allergensChecked(props.product));
27
+ const text = computed(() => foodLabelText(labels.value));
28
+ </script>
29
+
30
+ <template>
31
+ <PopoverRoot>
32
+ <PopoverTrigger as-child>
33
+ <SbIconButton label="Allergene und Zusatzstoffe">
34
+ <SbIcon name="info" />
35
+ </SbIconButton>
36
+ </PopoverTrigger>
37
+ <PopoverPortal disabled>
38
+ <PopoverContent
39
+ side="bottom"
40
+ align="end"
41
+ :side-offset="6"
42
+ :collision-padding="16"
43
+ class="z-50 w-72 max-w-[calc(100vw-32px)] rounded-sb-card border border-sb-line bg-sb-surface p-4 text-sm text-sb-ink shadow-lg focus-visible:outline-none"
44
+ data-testid="food-labels"
45
+ >
46
+ <p class="mb-1 font-semibold">Allergene und Zusatzstoffe</p>
47
+ <p class="text-sb-ink-muted">
48
+ <template v-if="text">{{ text }}</template>
49
+ <template v-else-if="checked"
50
+ >Ohne kennzeichnungspflichtige Allergene und Zusatzstoffe.</template
51
+ >
52
+ <template v-else>
53
+ Angaben erhalten Sie im Restaurant<template v-if="site.telephone"
54
+ >:
55
+ <a
56
+ :href="toTelHref(site.telephone)"
57
+ class="font-semibold text-sb-ink underline underline-offset-4"
58
+ >{{ site.telephone }}</a
59
+ ></template
60
+ >.
61
+ </template>
62
+ </p>
63
+ </PopoverContent>
64
+ </PopoverPortal>
65
+ </PopoverRoot>
66
+ </template>
@@ -93,6 +93,7 @@ function onVariantSelected(variant: Schemas["Product"]) {
93
93
  </div>
94
94
  </template>
95
95
  <template #actions>
96
+ <ProductFoodLabels v-if="product" :product="product" />
96
97
  <WishlistSaveButton :selection="selection" :name="label" />
97
98
  <SbIconButton
98
99
  :label="canShare ? 'Teilen' : 'Link kopieren'"
@@ -16,7 +16,8 @@ type IconName =
16
16
  | "phone"
17
17
  | "heart"
18
18
  | "bag"
19
- | "chevron-up";
19
+ | "chevron-up"
20
+ | "info";
20
21
 
21
22
  withDefaults(
22
23
  defineProps<{ name: IconName; size?: number; filled?: boolean }>(),
@@ -38,6 +39,7 @@ const PATHS: Record<IconName, string[]> = {
38
39
  "M16 10a4 4 0 0 1-8 0",
39
40
  ],
40
41
  "chevron-up": ["m18 15-6-6-6 6"],
42
+ info: ["M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20z", "M12 16v-4", "M12 8h.01"],
41
43
  heart: [
42
44
  "M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4.05 3 5.5l7 7Z",
43
45
  ],
@@ -1,12 +1,11 @@
1
1
  /**
2
2
  * The menu sections of the home page (#388, #444): the children of the menu
3
- * root (`menuCategoryId`, else the navigation root) with their photo
3
+ * root (useMenuRootId: env, plugin configuration, navigation root) with their photo
4
4
  * (`category.media`). Shared by the tiles and the word list of the presets.
5
5
  */
6
6
  export async function useHomeMenuCategories() {
7
7
  const { apiClient } = useShopwareContext();
8
- const config = useRuntimeConfig();
9
- const rootId = config.public.shopBite.menuCategoryId || "main-navigation";
8
+ const menuRootId = useMenuRootId();
10
9
 
11
10
  const { data: categories } = await useAsyncData(
12
11
  "home-menu-categories",
@@ -30,7 +29,10 @@ export async function useHomeMenuCategories() {
30
29
  media_thumbnail: ["url", "width"],
31
30
  },
32
31
  },
33
- pathParams: { activeId: "main-navigation", rootId },
32
+ pathParams: {
33
+ activeId: "main-navigation",
34
+ rootId: await menuRootId(),
35
+ },
34
36
  },
35
37
  );
36
38
  return response.data;
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Resolves the menu root once per visit (app/utils/menuRoot.ts). Call the
3
+ * returned function inside `useAsyncData` handlers; without the environment
4
+ * variable it asks the plugin configuration a single time.
5
+ */
6
+ export function useMenuRootId() {
7
+ const { apiClient } = useShopwareContext();
8
+ const configured = useRuntimeConfig().public.shopBite.menuCategoryId as
9
+ string | undefined;
10
+ const root = useState<string | null>("menu-root-id", () =>
11
+ configured ? configured : null,
12
+ );
13
+
14
+ return async (): Promise<string> => {
15
+ if (root.value) return root.value;
16
+ try {
17
+ const { data } = await apiClient.invoke(
18
+ "shopbite.config.get get /shopbite/config",
19
+ );
20
+ root.value = pickMenuRoot(configured, data.menuCategoryId);
21
+ return root.value;
22
+ } catch {
23
+ // not remembered: the next call tries again
24
+ return pickMenuRoot(configured, undefined);
25
+ }
26
+ };
27
+ }
@@ -11,10 +11,7 @@ export interface NavigationMenuItem {
11
11
 
12
12
  export function useNavigation(withChildren: boolean | undefined) {
13
13
  const { apiClient } = useShopwareContext();
14
- const config = useRuntimeConfig();
15
- const menuCategoryId = computed(
16
- () => config.public.shopBite.menuCategoryId ?? "main-navigation",
17
- );
14
+ const menuRootId = useMenuRootId();
18
15
 
19
16
  // Sent as a POST body: as `_criteria` query parameters the projection is
20
17
  // ignored and every category arrives with media, translations, cms page
@@ -101,7 +98,7 @@ export function useNavigation(withChildren: boolean | undefined) {
101
98
  body: criteria,
102
99
  pathParams: {
103
100
  activeId: "main-navigation",
104
- rootId: menuCategoryId.value,
101
+ rootId: await menuRootId(),
105
102
  },
106
103
  },
107
104
  );
@@ -190,9 +190,12 @@ async function loadProductByNumber(
190
190
  "translated",
191
191
  "description",
192
192
  "sortedProperties",
193
+ // Allergens checked (#485); includes filter `translated` as well,
194
+ // so custom fields only come back when listed here.
195
+ "customFields",
193
196
  ],
194
197
  property_group: ["id", "name", "translated", "options"],
195
- property_group_option: ["id", "name", "translated"],
198
+ property_group_option: ["id", "name", "translated", "customFields"],
196
199
  },
197
200
  associations: {
198
201
  properties: { associations: { group: {} } },
@@ -30,6 +30,9 @@ export function useTopSellers(): useTopSellersReturn {
30
30
  "available",
31
31
  "cover",
32
32
  "sortedProperties",
33
+ // Allergens checked (#485); includes filter `translated` as well,
34
+ // so custom fields only come back when listed here.
35
+ "customFields",
33
36
  // Card link to the quick view deep link (#289).
34
37
  "seoUrls",
35
38
  ],
@@ -38,7 +41,7 @@ export function useTopSellers(): useTopSellersReturn {
38
41
  media: ["url", "thumbnails"],
39
42
  media_thumbnail: ["width", "url"],
40
43
  property_group: ["id", "name", "translated", "options"],
41
- property_group_option: ["id", "name", "translated"],
44
+ property_group_option: ["id", "name", "translated", "customFields"],
42
45
  },
43
46
  associations: {
44
47
  cover: { associations: { media: {} } },
@@ -0,0 +1,57 @@
1
+ import type { Schemas } from "#shopware";
2
+
3
+ /** A sub-section of a menu section with its dishes (#487). */
4
+ export interface MenuGroup {
5
+ id: string;
6
+ name: string;
7
+ products: Schemas["Product"][];
8
+ }
9
+
10
+ /** The category with this id anywhere in a navigation tree. */
11
+ export function findCategory(
12
+ tree: Schemas["Category"][] | undefined,
13
+ id: string,
14
+ ): Schemas["Category"] | undefined {
15
+ for (const category of tree ?? []) {
16
+ if (category.id === id) return category;
17
+ const found = findCategory(category.children, id);
18
+ if (found) return found;
19
+ }
20
+ return undefined;
21
+ }
22
+
23
+ function idsBelow(category: Schemas["Category"]): string[] {
24
+ return [category.id, ...(category.children ?? []).flatMap(idsBelow)];
25
+ }
26
+
27
+ /**
28
+ * Splits the dishes of a section into the ones directly in it and one group
29
+ * per sub-section, in the order of the navigation (= backoffice order).
30
+ * Deeper levels count to their sub-section; empty groups are left out, so a
31
+ * filter or search shows only what matches. Without sub-sections: null.
32
+ */
33
+ export function groupBySubsections(
34
+ products: Schemas["Product"][],
35
+ subsections: Schemas["Category"][] | undefined,
36
+ ): { direct: Schemas["Product"][]; groups: MenuGroup[] } | null {
37
+ if (!subsections?.length) return null;
38
+ const buckets = subsections.map((category) => ({
39
+ group: {
40
+ id: category.id,
41
+ name: category.translated?.name ?? category.name ?? "",
42
+ products: [] as Schemas["Product"][],
43
+ },
44
+ ids: new Set(idsBelow(category)),
45
+ }));
46
+ const direct: Schemas["Product"][] = [];
47
+ for (const product of products) {
48
+ const bucket = buckets.find((b) =>
49
+ (product.categoryIds ?? []).some((id) => b.ids.has(id)),
50
+ );
51
+ (bucket?.group.products ?? direct).push(product);
52
+ }
53
+ return {
54
+ direct,
55
+ groups: buckets.map((b) => b.group).filter((g) => g.products.length),
56
+ };
57
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * The root category of the menu (#486): NUXT_PUBLIC_SHOP_BITE_MENU_CATEGORY_ID
3
+ * if set (existing installations), else `menuCategoryId` of the plugin
4
+ * configuration (`/store-api/shopbite/config`, shopware-plugin#35, which
5
+ * falls back to the sales channel's navigation category), else the
6
+ * navigation root.
7
+ */
8
+ export const NAVIGATION_ROOT = "main-navigation";
9
+
10
+ export function pickMenuRoot(
11
+ configured: string | undefined,
12
+ fromPlugin: string | undefined | null,
13
+ ): string {
14
+ return configured || fromPlugin || NAVIGATION_ROOT;
15
+ }
@@ -66,3 +66,74 @@ export function getDiets(
66
66
  hasYesOption(sortedProperties, DIET_GROUPS[diet]),
67
67
  );
68
68
  }
69
+
70
+ // Mandatory food information (#485): property groups and custom fields of the
71
+ // ShopBite plugin (shopware-plugin#36), maintained in the backoffice.
72
+ const ALLERGEN_GROUP = "Allergene";
73
+ const ADDITIVE_GROUP = "Zusatzstoffe";
74
+
75
+ export interface FoodLabel {
76
+ code: string;
77
+ name: string;
78
+ }
79
+
80
+ export interface FoodLabels {
81
+ allergens: FoodLabel[];
82
+ additives: FoodLabel[];
83
+ }
84
+
85
+ function customFieldsOf(entity: {
86
+ customFields?: unknown;
87
+ translated?: unknown;
88
+ }): Record<string, unknown> {
89
+ const translated = (entity.translated as { customFields?: unknown })
90
+ ?.customFields;
91
+ return ((translated ?? entity.customFields) as Record<string, unknown>) ?? {};
92
+ }
93
+
94
+ function labelsOf(
95
+ sortedProperties: Schemas["PropertyGroup"][] | undefined,
96
+ groupName: string,
97
+ ): FoodLabel[] {
98
+ const group = sortedProperties?.find(
99
+ (propertyGroup) => propertyGroup.translated.name === groupName,
100
+ );
101
+ return (group?.options ?? []).map((option) => ({
102
+ code: String(customFieldsOf(option).shopbite_code ?? ""),
103
+ name: option.translated?.name ?? option.name ?? "",
104
+ }));
105
+ }
106
+
107
+ /** Allergens and additives of a product, in the order of the catalogue. */
108
+ export function getFoodLabels(
109
+ sortedProperties: Schemas["PropertyGroup"][] | undefined,
110
+ ): FoodLabels {
111
+ return {
112
+ allergens: labelsOf(sortedProperties, ALLERGEN_GROUP),
113
+ additives: labelsOf(sortedProperties, ADDITIVE_GROUP),
114
+ };
115
+ }
116
+
117
+ /**
118
+ * Whether the restaurant confirmed the lists as complete. Without it an
119
+ * empty list means "not entered yet", never "free of allergens".
120
+ */
121
+ export function allergensChecked(product: Schemas["Product"]): boolean {
122
+ return customFieldsOf(product).shopbite_allergens_checked === true;
123
+ }
124
+
125
+ /** Plain text for the info popover of the product sheet (#500). */
126
+ export function foodLabelText(labels: FoodLabels): string {
127
+ const parts: string[] = [];
128
+ if (labels.allergens.length) {
129
+ parts.push(
130
+ `Enthält: ${labels.allergens.map((label) => label.name).join(", ")}.`,
131
+ );
132
+ }
133
+ if (labels.additives.length) {
134
+ parts.push(
135
+ `Zusatzstoffe: ${labels.additives.map((label) => label.name).join(", ")}.`,
136
+ );
137
+ }
138
+ return parts.join(" ");
139
+ }
package/nuxt.config.ts CHANGED
@@ -56,6 +56,9 @@ export default defineNuxtConfig({
56
56
  adminEndpoint: "",
57
57
  },
58
58
  apiClientConfig: {},
59
+ // Secret of POST /api/_cache/purge (#484), the backoffice empties the
60
+ // Store API caches after menu changes. Empty = route off.
61
+ cachePurgeSecret: "",
59
62
  geoapifyApiKey: "",
60
63
  // AI crawlers named in robots.txt (#403, server/plugins/ai-crawlers.ts):
61
64
  // search = AI search and assistant fetches, training = model training.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shopbite-de/storefront",
3
- "version": "2.1.1",
3
+ "version": "2.2.1",
4
4
  "main": "nuxt.config.ts",
5
5
  "description": "Shopware storefront for food delivery shops",
6
6
  "keywords": [
@@ -44,7 +44,7 @@
44
44
  "@axe-core/playwright": "^4.13.0",
45
45
  "@nuxt/devtools-kit": "^3.4.2",
46
46
  "@nuxt/eslint": "^1.17.0",
47
- "@nuxt/hints": "1.1.4",
47
+ "@nuxt/hints": "1.1.5",
48
48
  "@nuxt/test-utils": "^4.3.2",
49
49
  "@playwright/test": "^1.63.0",
50
50
  "@types/js-cookie": "^3.0.6",
@@ -21,10 +21,7 @@ const NAVIGATION_CRITERIA = {
21
21
  */
22
22
  export default defineSitemapEventHandler(async () => {
23
23
  const { shopware, shopBite } = useRuntimeConfig().public;
24
- const rootIds = new Set([
25
- "main-navigation",
26
- shopBite.menuCategoryId || "main-navigation",
27
- ]);
24
+ const rootIds = new Set(["main-navigation", await menuRootId()]);
28
25
 
29
26
  const trees = await Promise.all(
30
27
  [...rootIds].map((rootId) =>
@@ -0,0 +1,31 @@
1
+ import { z } from "zod";
2
+
3
+ const Id = z.string().regex(/^[0-9a-f]{32}$/i);
4
+ const Body = z
5
+ .object({
6
+ products: z.array(Id).max(1000).optional(),
7
+ categories: z.array(Id).max(1000).optional(),
8
+ })
9
+ .default({});
10
+
11
+ /**
12
+ * Empties the Store API caches after the backoffice changed the menu (#484).
13
+ * Protected by NUXT_CACHE_PURGE_SECRET; without the variable the route is
14
+ * off. An empty body purges everything.
15
+ */
16
+ export default defineEventHandler(async (event) => {
17
+ const secret = useRuntimeConfig(event).cachePurgeSecret;
18
+ if (!secret) throw createError({ statusCode: 404 });
19
+ if (!hasPurgeSecret(getHeader(event, "authorization"), secret)) {
20
+ throw createError({ statusCode: 401, statusMessage: "Unauthorized" });
21
+ }
22
+ const raw = await readBody(event).catch(() => undefined);
23
+ const parsed = Body.safeParse(raw ?? {});
24
+ if (!parsed.success)
25
+ throw createError({ statusCode: 400, statusMessage: "Invalid body" });
26
+
27
+ const storage = useStorage();
28
+ const keys = keysToPurge(await storage.getKeys("cache:nitro"), parsed.data);
29
+ await Promise.all(keys.map((key) => storage.removeItem(key)));
30
+ return { purged: keys.length };
31
+ });
@@ -15,7 +15,12 @@ const BASE_CRITERIA = {
15
15
  // `properties` would repeat every option with its group. The quick view
16
16
  // loads its own product (/api/product/[productId]).
17
17
  "sortedProperties",
18
+ // Allergens checked (#485); includes filter `translated` as well,
19
+ // so custom fields only come back when listed here.
20
+ "customFields",
18
21
  "cover",
22
+ // Groups the dishes of a section by sub-section (#487).
23
+ "categoryIds",
19
24
  // "Ausverkauft" on the card (#325).
20
25
  "available",
21
26
  // Product deep link (#289); the request sends `sw-include-seo-urls`.
@@ -28,7 +33,14 @@ const BASE_CRITERIA = {
28
33
  // The entity is `property_group`: under `property` the groups came back
29
34
  // with every field, nested once more in each option.
30
35
  property_group: ["id", "name", "translated", "displayType", "options"],
31
- property_group_option: ["id", "name", "translated", "media", "mediaId"],
36
+ property_group_option: [
37
+ "id",
38
+ "name",
39
+ "translated",
40
+ "customFields",
41
+ "media",
42
+ "mediaId",
43
+ ],
32
44
  product_option: ["id", "groupId", "name", "translated", "group"],
33
45
  ...MEDIA_INCLUDES,
34
46
  },
@@ -20,13 +20,22 @@ const criteria = {
20
20
  "children",
21
21
  "parentId",
22
22
  "sortedProperties",
23
+ // Allergens checked (#485); includes filter `translated` as well,
24
+ // so custom fields only come back when listed here.
25
+ "customFields",
23
26
  "cover",
24
27
  ],
25
28
  // The entity is `property_group`: under `property` the groups came back
26
29
  // with every field. Options keep their group for the configurator and
27
30
  // the ingredient selection (`option.group.name`).
28
31
  property_group: ["id", "name", "translated", "options"],
29
- property_group_option: ["id", "name", "translated", "group"],
32
+ property_group_option: [
33
+ "id",
34
+ "name",
35
+ "translated",
36
+ "customFields",
37
+ "group",
38
+ ],
30
39
  product_configurator_setting: ["id", "optionId", "option", "productId"],
31
40
  category: ["id", "name", "translated"],
32
41
  ...MEDIA_INCLUDES,
@@ -15,6 +15,9 @@ const BASE_CRITERIA = {
15
15
  // `properties` would repeat every option with its group. The quick view
16
16
  // loads its own product (/api/product/[productId]).
17
17
  "sortedProperties",
18
+ // Allergens checked (#485); includes filter `translated` as well,
19
+ // so custom fields only come back when listed here.
20
+ "customFields",
18
21
  "cover",
19
22
  // "Ausverkauft" on the card (#325).
20
23
  "available",
@@ -22,7 +25,14 @@ const BASE_CRITERIA = {
22
25
  // The entity is `property_group`: under `property` the groups came back
23
26
  // with every field, nested once more in each option.
24
27
  property_group: ["id", "name", "translated", "displayType", "options"],
25
- property_group_option: ["id", "name", "translated", "media", "mediaId"],
28
+ property_group_option: [
29
+ "id",
30
+ "name",
31
+ "translated",
32
+ "customFields",
33
+ "media",
34
+ "mediaId",
35
+ ],
26
36
  },
27
37
  associations: {
28
38
  cover: {
@@ -52,10 +52,10 @@ const PRODUCT_CRITERIA = {
52
52
  * its section out instead of failing the file.
53
53
  */
54
54
  export default defineEventHandler(async (event) => {
55
- const { shopware, shopBite, site } = useRuntimeConfig(event).public;
55
+ const { shopware, site } = useRuntimeConfig(event).public;
56
56
  const siteUrl = getSiteConfig(event).url;
57
57
  const headers = { "sw-access-key": shopware.accessToken };
58
- const menuRootId = shopBite.menuCategoryId || "main-navigation";
58
+ const menuRoot = await menuRootId();
59
59
 
60
60
  const storeApi = <T>(path: string, body?: Record<string, unknown>) =>
61
61
  $fetch<T>(`${shopware.endpoint}${path}`, {
@@ -67,7 +67,7 @@ export default defineEventHandler(async (event) => {
67
67
  const [navigation, products, hours, holidays, config, context, pages, home] =
68
68
  await Promise.allSettled([
69
69
  storeApi<Schemas["Category"][]>(
70
- `/navigation/${menuRootId}/${menuRootId}`,
70
+ `/navigation/${menuRoot}/${menuRoot}`,
71
71
  NAVIGATION_CRITERIA,
72
72
  ),
73
73
  loadProducts((page) =>
@@ -0,0 +1,62 @@
1
+ import { timingSafeEqual } from "node:crypto";
2
+
3
+ /**
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.
8
+ */
9
+
10
+ /** Entries of one product: the product, its variants and its extras. */
11
+ const PER_PRODUCT = ["product", "variant", "cross-selling"];
12
+ /** Lists that may show any product or category. */
13
+ const LISTS = ["listing", "search"];
14
+ const ALL = [...PER_PRODUCT, "category", ...LISTS];
15
+ const HANDLERS = "cache:nitro:handlers:";
16
+ /** Route rules with `swr` (llms.txt lists the menu). */
17
+ const ROUTES = "cache:nitro:routes:";
18
+
19
+ export interface PurgeTarget {
20
+ products?: string[];
21
+ categories?: string[];
22
+ }
23
+
24
+ const handlerOf = (key: string) =>
25
+ key.slice(HANDLERS.length).split(":")[0] ?? "";
26
+ const compact = (id: string) => id.toLowerCase().replace(/[^0-9a-f]/g, "");
27
+
28
+ /**
29
+ * 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.
32
+ */
33
+ export function keysToPurge(
34
+ keys: string[],
35
+ target: PurgeTarget = {},
36
+ ): string[] {
37
+ const products = (target.products ?? []).map(compact).filter(Boolean);
38
+ const categories = (target.categories ?? []).map(compact).filter(Boolean);
39
+ const everything = !products.length && !categories.length;
40
+ return keys.filter((key) => {
41
+ if (key.startsWith(ROUTES)) return true;
42
+ if (!key.startsWith(HANDLERS)) return false;
43
+ const handler = handlerOf(key);
44
+ if (!ALL.includes(handler)) return false;
45
+ if (everything || LISTS.includes(handler) || handler === "cross-selling")
46
+ return true;
47
+ if (handler === "category")
48
+ return categories.some((id) => key.includes(id));
49
+ return products.some((id) => key.includes(id));
50
+ });
51
+ }
52
+
53
+ /** Constant-time check of the `Authorization: Bearer <secret>` header. */
54
+ export function hasPurgeSecret(
55
+ header: string | undefined,
56
+ secret: string,
57
+ ): boolean {
58
+ if (!secret || !header?.startsWith("Bearer ")) return false;
59
+ const given = Buffer.from(header.slice("Bearer ".length));
60
+ const wanted = Buffer.from(secret);
61
+ return given.length === wanted.length && timingSafeEqual(given, wanted);
62
+ }
@@ -0,0 +1,25 @@
1
+ import { pickMenuRoot } from "../../app/utils/menuRoot";
2
+
3
+ /**
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.
6
+ */
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
+ );
18
+
19
+ 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());
25
+ }
@@ -0,0 +1,70 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { mountSuspended } from "@nuxt/test-utils/runtime";
3
+ import { flushPromises } from "@vue/test-utils";
4
+ import type { Schemas } from "#shopware";
5
+ import ProductFoodLabels from "~/components/Product/FoodLabels.vue";
6
+
7
+ const option = (code: string, name: string) => ({
8
+ name,
9
+ translated: { name, customFields: { shopbite_code: code } },
10
+ });
11
+
12
+ const dish = (
13
+ allergens: [string, string][],
14
+ checked = false,
15
+ ): Schemas["Product"] =>
16
+ ({
17
+ translated: {
18
+ customFields: checked ? { shopbite_allergens_checked: true } : {},
19
+ },
20
+ sortedProperties: allergens.length
21
+ ? [
22
+ {
23
+ translated: { name: "Allergene" },
24
+ options: allergens.map(([code, name]) => option(code, name)),
25
+ },
26
+ ]
27
+ : [],
28
+ }) as unknown as Schemas["Product"];
29
+
30
+ async function openPopover(product: Schemas["Product"]) {
31
+ const wrapper = await mountSuspended(ProductFoodLabels, {
32
+ props: { product },
33
+ attachTo: document.body,
34
+ });
35
+ const button = wrapper.get("button");
36
+ expect(button.attributes("aria-label")).toBe("Allergene und Zusatzstoffe");
37
+ expect(wrapper.find('[data-testid="food-labels"]').exists()).toBe(false);
38
+ await button.trigger("click");
39
+ await flushPromises();
40
+ return wrapper;
41
+ }
42
+
43
+ describe("food labels behind the info button (#500)", () => {
44
+ it("shows the allergens only after a click", async () => {
45
+ const wrapper = await openPopover(
46
+ dish([
47
+ ["A", "Weizen"],
48
+ ["G", "Milch (inkl. Laktose)"],
49
+ ]),
50
+ );
51
+ expect(wrapper.get('[data-testid="food-labels"]').text()).toContain(
52
+ "Enthält: Weizen, Milch (inkl. Laktose).",
53
+ );
54
+ wrapper.unmount();
55
+ });
56
+
57
+ it("says 'without' only when the restaurant checked the lists", async () => {
58
+ const checked = await openPopover(dish([], true));
59
+ expect(checked.get('[data-testid="food-labels"]').text()).toContain(
60
+ "Ohne kennzeichnungspflichtige Allergene und Zusatzstoffe.",
61
+ );
62
+ checked.unmount();
63
+
64
+ const unchecked = await openPopover(dish([]));
65
+ const text = unchecked.get('[data-testid="food-labels"]').text();
66
+ expect(text).toContain("Angaben erhalten Sie im Restaurant");
67
+ expect(text).not.toContain("Ohne");
68
+ unchecked.unmount();
69
+ });
70
+ });
@@ -0,0 +1,65 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { hasPurgeSecret, keysToPurge } from "../../server/utils/cachePurge";
3
+
4
+ const PIZZA = "018dadb399837af3aa669c8fff4f4d6c";
5
+ const MARGHERITA = "0197baf0a6a971eaada59ed5c84138de";
6
+ const SCHNITZEL = "018dbccef8257618b0b3a541f513aa9e";
7
+ // keys as Nitro stores them (escaped custom key, see server/utils/cachePurge.ts)
8
+ const KEYS = [
9
+ `cache:nitro:handlers:product:product${MARGHERITA}.json`,
10
+ `cache:nitro:handlers:product:product${SCHNITZEL}.json`,
11
+ `cache:nitro:handlers:variant:variant${MARGHERITA}a1b2.json`,
12
+ `cache:nitro:handlers:cross-selling:crossselling${SCHNITZEL}.json`,
13
+ `cache:nitro:handlers:category:category${PIZZA}.json`,
14
+ `cache:nitro:handlers:listing:${PIZZA}1.json`,
15
+ `cache:nitro:handlers:search:pizza1.json`,
16
+ `cache:nitro:handlers:sitemap:urls.json`,
17
+ `cache:nitro:routes:_:llmstxt.json`,
18
+ ];
19
+
20
+ describe("keysToPurge", () => {
21
+ it("purges every Store API cache without a target", () => {
22
+ expect(keysToPurge(KEYS)).toEqual(
23
+ KEYS.filter((k) => !k.includes("sitemap")),
24
+ );
25
+ });
26
+
27
+ it("purges one product, its variants, all extras and all lists", () => {
28
+ expect(keysToPurge(KEYS, { products: [MARGHERITA] })).toEqual([
29
+ KEYS[0],
30
+ KEYS[2],
31
+ KEYS[3],
32
+ KEYS[5],
33
+ KEYS[6],
34
+ KEYS[8],
35
+ ]);
36
+ });
37
+
38
+ it("purges a category and the lists, not the products", () => {
39
+ expect(keysToPurge(KEYS, { categories: [PIZZA] })).toEqual([
40
+ KEYS[3],
41
+ KEYS[4],
42
+ KEYS[5],
43
+ KEYS[6],
44
+ KEYS[8],
45
+ ]);
46
+ });
47
+
48
+ it("finds ids written with dashes or upper case", () => {
49
+ const dashed = `0197BAF0-A6A9-71EA-ADA5-9ED5C84138DE`;
50
+ expect(keysToPurge(KEYS, { products: [dashed] })).toContain(KEYS[0]);
51
+ });
52
+ });
53
+
54
+ describe("hasPurgeSecret", () => {
55
+ it("accepts only the exact bearer secret", () => {
56
+ expect(hasPurgeSecret("Bearer geheim", "geheim")).toBe(true);
57
+ expect(hasPurgeSecret("Bearer geheim2", "geheim")).toBe(false);
58
+ expect(hasPurgeSecret("geheim", "geheim")).toBe(false);
59
+ expect(hasPurgeSecret(undefined, "geheim")).toBe(false);
60
+ });
61
+
62
+ it("is off without a configured secret", () => {
63
+ expect(hasPurgeSecret("Bearer ", "")).toBe(false);
64
+ });
65
+ });
@@ -0,0 +1,56 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import type { Schemas } from "#shopware";
3
+ import { findCategory, groupBySubsections } from "../../app/utils/menuGroups";
4
+
5
+ const category = (
6
+ id: string,
7
+ name: string,
8
+ children: Schemas["Category"][] = [],
9
+ ) =>
10
+ ({
11
+ id,
12
+ name,
13
+ translated: { name },
14
+ children,
15
+ }) as unknown as Schemas["Category"];
16
+ const product = (id: string, categoryIds: string[]) =>
17
+ ({ id, categoryIds }) as unknown as Schemas["Product"];
18
+
19
+ const nudeln = category("nudeln", "Nudeln", [
20
+ category("spaghetti", "Spaghetti"),
21
+ category("penne", "Penne", [category("penne-al-forno", "Al forno")]),
22
+ category("leer", "Leer"),
23
+ ]);
24
+
25
+ describe("groupBySubsections (#487)", () => {
26
+ it("groups dishes by sub-section in navigation order, direct dishes first", () => {
27
+ const result = groupBySubsections(
28
+ [
29
+ product("p1", ["penne"]),
30
+ product("p2", ["spaghetti"]),
31
+ product("p3", ["nudeln"]),
32
+ product("p4", ["penne-al-forno"]),
33
+ ],
34
+ nudeln.children,
35
+ );
36
+ expect(result?.direct.map((p) => p.id)).toEqual(["p3"]);
37
+ expect(
38
+ result?.groups.map((g) => [g.name, g.products.map((p) => p.id)]),
39
+ ).toEqual([
40
+ ["Spaghetti", ["p2"]],
41
+ ["Penne", ["p1", "p4"]],
42
+ ]);
43
+ });
44
+
45
+ it("is null for a section without sub-sections", () => {
46
+ expect(groupBySubsections([product("p1", ["pizza"])], [])).toBeNull();
47
+ });
48
+
49
+ it("finds a category anywhere in the tree", () => {
50
+ expect(
51
+ findCategory([category("pizza", "Pizza"), nudeln], "penne-al-forno")
52
+ ?.name,
53
+ ).toBe("Al forno");
54
+ expect(findCategory([nudeln], "x")).toBeUndefined();
55
+ });
56
+ });
@@ -0,0 +1,21 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { NAVIGATION_ROOT, pickMenuRoot } from "../../app/utils/menuRoot";
3
+
4
+ const ENV = "211cf9b2d1725130a517bbadf753a43c";
5
+ const PLUGIN = "018dadb399837af3aa669c8fff4f4d6c";
6
+
7
+ describe("pickMenuRoot", () => {
8
+ it("keeps the environment variable of existing installations", () => {
9
+ expect(pickMenuRoot(ENV, PLUGIN)).toBe(ENV);
10
+ });
11
+
12
+ it("takes the plugin configuration without the variable", () => {
13
+ expect(pickMenuRoot("", PLUGIN)).toBe(PLUGIN);
14
+ expect(pickMenuRoot(undefined, PLUGIN)).toBe(PLUGIN);
15
+ });
16
+
17
+ it("falls back to the navigation root (older plugin, no answer)", () => {
18
+ expect(pickMenuRoot("", undefined)).toBe(NAVIGATION_ROOT);
19
+ expect(pickMenuRoot(undefined, null)).toBe(NAVIGATION_ROOT);
20
+ });
21
+ });
@@ -1,7 +1,10 @@
1
1
  import { describe, expect, it } from "vitest";
2
2
  import type { Schemas } from "#shopware";
3
3
  import {
4
+ allergensChecked,
5
+ foodLabelText,
4
6
  getDiets,
7
+ getFoodLabels,
5
8
  getMainIngredients,
6
9
  hasYesOption,
7
10
  lineItemHoldsProduct,
@@ -102,3 +105,56 @@ describe("getDiets", () => {
102
105
  expect(getDiets([group("Hauptzutaten", ["Salami"])])).toEqual([]);
103
106
  });
104
107
  });
108
+
109
+ const labelGroup = (name: string, options: [string, string][]) =>
110
+ ({
111
+ translated: { name },
112
+ options: options.map(([code, option], i) => ({
113
+ id: `${name}${i}`,
114
+ translated: { name: option, customFields: { shopbite_code: code } },
115
+ })),
116
+ }) as unknown as Schemas["PropertyGroup"];
117
+
118
+ const withLabels = () => [
119
+ group("Hauptzutaten", ["Tomaten"]),
120
+ labelGroup("Allergene", [
121
+ ["A", "Weizen"],
122
+ ["A", "Dinkel"],
123
+ ["G", "Milch (inkl. Laktose)"],
124
+ ]),
125
+ labelGroup("Zusatzstoffe", [["2", "mit Konservierungsstoff"]]),
126
+ ];
127
+
128
+ describe("food labels (#485)", () => {
129
+ it("reads allergens and additives with their codes", () => {
130
+ const labels = getFoodLabels(withLabels());
131
+ expect(labels.allergens.map((label) => label.code)).toEqual([
132
+ "A",
133
+ "A",
134
+ "G",
135
+ ]);
136
+ expect(labels.additives).toEqual([
137
+ { code: "2", name: "mit Konservierungsstoff" },
138
+ ]);
139
+ expect(getFoodLabels(undefined)).toEqual({ allergens: [], additives: [] });
140
+ });
141
+
142
+ it("writes plain text", () => {
143
+ const labels = getFoodLabels(withLabels());
144
+ expect(foodLabelText(labels)).toBe(
145
+ "Enthält: Weizen, Dinkel, Milch (inkl. Laktose). Zusatzstoffe: mit Konservierungsstoff.",
146
+ );
147
+ expect(foodLabelText({ allergens: [], additives: [] })).toBe("");
148
+ });
149
+
150
+ it("knows whether the restaurant checked the lists", () => {
151
+ expect(
152
+ allergensChecked(
153
+ product({
154
+ translated: { customFields: { shopbite_allergens_checked: true } },
155
+ } as unknown as Partial<Schemas["Product"]>),
156
+ ),
157
+ ).toBe(true);
158
+ expect(allergensChecked(product())).toBe(false);
159
+ });
160
+ });
package/.gitignore DELETED
@@ -1,45 +0,0 @@
1
- # Nuxt dev/build outputs
2
- .output
3
- .data
4
- .nuxt
5
- .nitro
6
- .cache
7
- dist
8
-
9
- # Node dependencies
10
- node_modules
11
-
12
- # Logs
13
- logs
14
- *.log
15
-
16
- # Misc
17
- .DS_Store
18
- .fleet
19
- .idea
20
-
21
- # Local env files
22
- .env
23
- .env.*
24
- !.env.example
25
- coverage
26
- test-results
27
- playwright-report
28
-
29
- # Playwright
30
- /playwright-report/
31
- /blob-report/
32
- /playwright/.cache/
33
- /playwright/.auth/
34
-
35
- # Performance tooling (scripts/perf)
36
- scripts/perf/out
37
- scripts/perf/exp
38
- scripts/perf/*.pem
39
- test/visual/__snapshots__
40
- test/visual/results
41
-
42
- # build output of the layer fixture (CI job layer-build)
43
- test/layer/.nuxt
44
- test/layer/.output
45
- test/layer/.data