basklee-react 0.9.0 → 0.9.2

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 (24) hide show
  1. package/README.md +6 -6
  2. package/package.json +2 -2
  3. package/runtime/marketplace.mjs +58 -4
  4. package/src/project-readme.mjs +11 -7
  5. package/templates/app/_storefront/StorefrontProductStructuredData.tsx +6 -0
  6. package/templates/basklee/COMPONENTS.md +7 -7
  7. package/templates/components/basklee/cart/CartDeliverySelector.README.md +1 -1
  8. package/templates/components/basklee/cart/CartItemOptions.README.md +1 -1
  9. package/templates/components/basklee/cart/CartLineItem.README.md +1 -1
  10. package/templates/components/basklee/orders/OrderPaymentForm.README.md +1 -1
  11. package/templates/components/basklee/payments/PaymentPanel.README.md +1 -1
  12. package/templates/components/basklee/search/SearchFilters.README.md +8 -0
  13. package/templates/components/basklee/search/SearchFilters.tsx +8 -0
  14. package/templates/components/basklee/subscriptions/StorefrontSubscriptions.README.md +1 -1
  15. package/templates/components/basklee/subscriptions/SubscriptionPlanSummary.README.md +1 -1
  16. package/templates/components/basklee/subscriptions/SubscriptionRemoteDetails.README.md +1 -1
  17. package/templates/components/basklee/subscriptions/SubscriptionRenewalDialog.README.md +1 -1
  18. package/templates/components/basklee/wallet/StorefrontWallet.README.md +1 -1
  19. package/templates/interfaces/basklee/products/IProductSearchApi.ts +2 -0
  20. package/templates/interfaces/basklee/products/IProductSearchFacets.ts +2 -0
  21. package/templates/lib/basklee/appLoadServer.ts +1 -0
  22. package/templates/lib/basklee/browseLabels.ts +3 -0
  23. package/templates/lib/basklee/productStructuredData.ts +18 -4
  24. package/templates/lib/basklee/serverApi.ts +1 -0
package/README.md CHANGED
@@ -43,7 +43,7 @@ page, or leaves the app on the first page. With `@capacitor/filesystem` and
43
43
  `@capacitor/share`, a purchased file is saved in the app and opened from the
44
44
  Android share sheet. Without the variable the website
45
45
  build is unchanged. Setup, build and release steps:
46
- [Android app guide](https://basklee.com/en/sandbox/android-app?framework=react).
46
+ [Android app guide](https://docs.basklee.com/en/sandbox/android-app?framework=react).
47
47
 
48
48
  ```bash
49
49
  BASKLEE_APP_ORIGIN=https://shop.example.com npx next build
@@ -184,7 +184,7 @@ Browse categories, search results and product sources.
184
184
  | **Catalog component** | `StorefrontCatalog` | The component shows store categories, subcategories and product links. |
185
185
  | **Category page** | `StorefrontCategory` | A category with its breadcrumb path, subcategories, filters and paginated product cards. |
186
186
  | **Search results** | `ProductSearchResults` | Filters, products, loading and empty states for search, category, seller and recommendation results. |
187
- | **Search filters** | `SearchFilters` | Price, discount, rating, review, category, seller, manufacturer and variant facets with selectable values and optional result counts. |
187
+ | **Search filters** | `SearchFilters` | Price, discount, stock, rating, review, category, seller, manufacturer and variant facets with selectable values and optional result counts. |
188
188
  | **Sellers** | `StorefrontSellers` | Seller directory with filters and sorting, and a seller profile with its products. |
189
189
  | **Seller filters** | `SellerFilters` | Seller name, minimum rating and category filters for the seller directory. |
190
190
  | **Seller summary** | `SellerSummary` | Seller logo, name, rating, selling-since badge, product count and description. |
@@ -354,7 +354,7 @@ storefront on your server; see [Install on your server](#install-on-your-server)
354
354
 
355
355
  Prepare a Linux server once with the Basklee server script: it installs
356
356
  Node.js, nginx and certbot and adds the `basklee` command
357
- ([server guide](https://basklee.com/en/sandbox/install)).
357
+ ([server guide](https://docs.basklee.com/en/sandbox/install)).
358
358
 
359
359
  ```bash
360
360
  curl -fsSLo basklee.sh https://basklee.com/downloads/basklee.sh
@@ -378,7 +378,7 @@ certificate. Run it again after code or package updates; the service keeps its
378
378
  port. Options: `--name <service>`, `--port <port>`, `--user <user>`,
379
379
  `--no-build` (install the build already in the folder), `--no-domains`, `--yes`,
380
380
  `--dry-run`. Full guide:
381
- [Install a storefront](https://basklee.com/en/sandbox/install/storefront?framework=react).
381
+ [Install a storefront](https://docs.basklee.com/en/sandbox/install/storefront?framework=react).
382
382
 
383
383
  ### Manage the service
384
384
 
@@ -599,8 +599,8 @@ installation fails after source generation, run `npm install` and retry `update`
599
599
 
600
600
  ## Documentation
601
601
 
602
- - [Create a Next.js frontend](https://basklee.com/en/sandbox/new-project/react)
603
- - [Marketplace API documentation](https://basklee.com/en/sandbox/)
602
+ - [Create a Next.js frontend](https://docs.basklee.com/en/sandbox/new-project/react)
603
+ - [Marketplace API documentation](https://docs.basklee.com/en/sandbox/)
604
604
 
605
605
  ## Development
606
606
 
package/package.json CHANGED
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "name": "basklee-react",
3
- "version": "0.9.0",
3
+ "version": "0.9.2",
4
4
  "description": "Next.js 16 storefront for your Basklee marketplace: setup CLI, server API gateway, typed store and ready-made catalog, cart, checkout and account components in English, Russian and Spanish, plus an Android app build.",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "author": "Basklee",
8
- "homepage": "https://basklee.com/en/sandbox/new-project/react",
8
+ "homepage": "https://docs.basklee.com/en/sandbox/new-project/react",
9
9
  "keywords": [
10
10
  "react",
11
11
  "next",
@@ -1,6 +1,7 @@
1
1
  import { chown, mkdir, readFile, readdir, rename, stat, unlink, writeFile } from 'node:fs/promises';
2
2
  import { dirname, relative, resolve } from 'node:path';
3
3
  import {
4
+ BlockList,
4
5
  getDefaultAutoSelectFamilyAttemptTimeout,
5
6
  isIP,
6
7
  setDefaultAutoSelectFamilyAttemptTimeout,
@@ -24,6 +25,62 @@ if (getDefaultAutoSelectFamilyAttemptTimeout() < connectTimeout) {
24
25
  const requestTimeout = 30_000;
25
26
  const uploadTimeout = 300_000;
26
27
 
28
+ // Cloudflare's edge addresses (https://www.cloudflare.com/ips-v4 and /ips-v6,
29
+ // checked 2026-11-18). A storefront behind Cloudflare is reached from one of
30
+ // them, so the address a proxy in front of it passes on is Cloudflare's, not
31
+ // the visitor's. Cloudflare puts the visitor's address into CF-Connecting-IP
32
+ // and overwrites any value a visitor sends; the header is taken only when the
33
+ // address it came with is a Cloudflare one. Nothing to set up: a storefront
34
+ // that is not behind Cloudflare keeps the address it gets.
35
+ const cloudflareRanges = [
36
+ '173.245.48.0/20', '103.21.244.0/22', '103.22.200.0/22', '103.31.4.0/22',
37
+ '141.101.64.0/18', '108.162.192.0/18', '190.93.240.0/20', '188.114.96.0/20',
38
+ '197.234.240.0/22', '198.41.128.0/17', '162.158.0.0/15', '104.16.0.0/13',
39
+ '104.24.0.0/14', '172.64.0.0/13', '131.0.72.0/22',
40
+ '2400:cb00::/32', '2606:4700::/32', '2803:f800::/32', '2405:b500::/32',
41
+ '2405:8100::/32', '2a06:98c0::/29', '2c0f:f248::/32',
42
+ ];
43
+ const cloudflare = new BlockList();
44
+ for (const range of cloudflareRanges) {
45
+ const [address, prefix] = range.split('/');
46
+ cloudflare.addSubnet(address, Number(prefix), address.includes(':') ? 'ipv6' : 'ipv4');
47
+ }
48
+
49
+ /** One address written plainly ('::ffff:1.2.3.4' as 1.2.3.4), or ''. */
50
+ function plainAddress(value) {
51
+ let address = String(value ?? '').trim();
52
+ const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/i.exec(address);
53
+ if (mapped) {
54
+ address = mapped[1];
55
+ }
56
+ return isIP(address) ? address : '';
57
+ }
58
+
59
+ /** True for an address of Cloudflare's edge. */
60
+ export function isCloudflareAddress(value) {
61
+ const address = plainAddress(value);
62
+ if (!address) {
63
+ return false;
64
+ }
65
+ return cloudflare.check(address, isIP(address) === 6 ? 'ipv6' : 'ipv4');
66
+ }
67
+
68
+ /**
69
+ * The visitor's address for the backend: X-Init-Ip, X-Real-IP or the first
70
+ * X-Forwarded-For entry, and CF-Connecting-IP instead when that address is a
71
+ * Cloudflare edge (or there is no proxy address at all) and Cloudflare sent one.
72
+ * @param {Headers} headers
73
+ */
74
+ export function marketplaceClientIp(headers) {
75
+ const proxied = headers.get('x-init-ip') || headers.get('x-real-ip');
76
+ const forwarded = headers.get('x-forwarded-for')?.split(',')[0]?.trim();
77
+ const visitor = plainAddress(headers.get('cf-connecting-ip'));
78
+ if (visitor && (!proxied || isCloudflareAddress(proxied))) {
79
+ return visitor;
80
+ }
81
+ return proxied || forwarded || '';
82
+ }
83
+
27
84
  /** @param {Request} request */
28
85
  export function marketplaceRequestTimeout(request) {
29
86
  const contentType = request.headers.get('content-type') ?? '';
@@ -320,10 +377,7 @@ export async function forwardMarketplace(request, configuration = {}) {
320
377
  headers.set('origin', `https://${tenant.domain}`);
321
378
  }
322
379
  headers.set('Accept-Encoding', 'identity');
323
- const clientIp =
324
- request.headers.get('x-init-ip') ||
325
- request.headers.get('x-real-ip') ||
326
- request.headers.get('x-forwarded-for')?.split(',')[0]?.trim();
380
+ const clientIp = marketplaceClientIp(request.headers);
327
381
  if (clientIp) {
328
382
  headers.set('X-Init-Ip', clientIp);
329
383
  }
@@ -299,7 +299,7 @@ The shared client renews the token for the next action and returns the failed
299
299
  request; the customer retries explicitly. After confirmed login/logout, reset and refresh Application Load; these actions
300
300
  change application data and do not log in/out or delete cookies.
301
301
 
302
- [Cookie lifecycle and browser request example](https://basklee.com/en/sandbox/appload/react#session-cookies)
302
+ [Cookie lifecycle and browser request example](https://docs.basklee.com/en/sandbox/appload/react#session-cookies)
303
303
 
304
304
  ### Rendering, navigation and failures
305
305
 
@@ -353,7 +353,7 @@ If installation fails after source generation, run \`npm install\` and retry.
353
353
  The quickest way: prepare the server with the Basklee server script,
354
354
  then run \`sudo npx basklee-react install\` in this folder. It builds the
355
355
  project, runs it as a system service and connects your domains with nginx and
356
- HTTPS. Steps: [Install a storefront](https://basklee.com/en/sandbox/install/storefront?framework=react).
356
+ HTTPS. Steps: [Install a storefront](https://docs.basklee.com/en/sandbox/install/storefront?framework=react).
357
357
  Then manage it from this folder: \`npx basklee-react status\`, \`sudo npx basklee-react restart\`,
358
358
  \`sudo npx basklee-react stop\`, \`sudo npx basklee-react start\` and \`sudo npx basklee-react logs\`.
359
359
  \`sudo npx basklee-react uninstall\` (or \`cleanup\`) stops and removes the service; this folder stays.
@@ -390,6 +390,9 @@ location / {
390
390
 
391
391
  Here localhost is your frontend process on your VPS. That process selects the
392
392
  remote personal API from the domain file. The proxy must overwrite those headers.
393
+ Behind Cloudflare, \`$remote_addr\` is a Cloudflare address: the storefront
394
+ notices it and sends the customer's own address from \`CF-Connecting-IP\`
395
+ instead, with nothing to set up.
393
396
  An unknown domain never falls back to another tenant. \`/robots.txt\` points
394
397
  crawlers to \`/sitemap.xml\`, which lists the public pages, categories, products
395
398
  on sale and journal publications in every storefront language (each publication
@@ -412,8 +415,9 @@ pages answer with \`X-Robots-Tag: noindex, follow\` and the sitemap leaves them
412
415
  out; the journal and other pages stay indexable. Leave it empty on a live shop.
413
416
 
414
417
  Every product page carries schema.org product data for Google and Yandex: the
415
- price, the crossed-out old price, stock, photos, brand, seller, rating and the
416
- return terms the page shows. The return terms name the shop's shipping
418
+ price, the crossed-out old price, stock (a product open for preorder is a
419
+ preorder, not sold out), photos, brand (the manufacturer, otherwise the seller),
420
+ seller, rating and the return terms the page shows. The return terms name the shop's shipping
417
421
  countries, which Application Load sends in \`init.shipping_countries\`; without
418
422
  a shipping country they are left out. The delivery cost is not included: it
419
423
  depends on the buyer's address.
@@ -427,7 +431,7 @@ Deploy the website first, then build the app with Capacitor 8. With
427
431
  client-only and sends every API request to that storefront through Capacitor's
428
432
  native HTTP (\`lib/basklee/nativeApp.ts\`). Without the variable the
429
433
  website build is unchanged. Steps:
430
- [Android app guide](https://basklee.com/en/sandbox/android-app?framework=react).
434
+ [Android app guide](https://docs.basklee.com/en/sandbox/android-app?framework=react).
431
435
 
432
436
  \`\`\`bash
433
437
  BASKLEE_APP_ORIGIN=https://shop.example.com npx next build
@@ -436,7 +440,7 @@ npx cap sync android
436
440
 
437
441
  ## More documentation
438
442
 
439
- - [React package installation and domain setup](https://basklee.com/en/sandbox/new-project/react)
440
- - [Application Load](https://basklee.com/en/sandbox)
443
+ - [React package installation and domain setup](https://docs.basklee.com/en/sandbox/new-project/react)
444
+ - [Application Load](https://docs.basklee.com/en/sandbox)
441
445
  `;
442
446
  }
@@ -16,6 +16,7 @@ import {
16
16
  storefrontAbsoluteUrl,
17
17
  storefrontCanonicalUrl,
18
18
  } from '@/lib/basklee/pageSeo';
19
+ import { productAvailability } from '@/lib/basklee/productAvailability';
19
20
  import {
20
21
  shippingCountryCodes,
21
22
  storefrontProductStructuredData,
@@ -62,6 +63,11 @@ export function StorefrontProductStructuredData({
62
63
  // The backend's shipping countries, for the return terms.
63
64
  shippingCountries: shippingCountryCodes(init?.shipping_countries),
64
65
  showSeller: !init?.visual_settings?.single_seller_mode,
66
+ // A preorder offered instead of «Add to cart» is PreOrder, not OutOfStock.
67
+ preorder: productAvailability(
68
+ product,
69
+ init?.variables?.allow_preorder,
70
+ ).canPreorder,
65
71
  absoluteUrl: (value) => storefrontAbsoluteUrl(value, origin),
66
72
  })
67
73
  : undefined,
@@ -20,13 +20,13 @@ The API response tables also explain the following contracts / Таблицы о
20
20
 
21
21
  | API | Contract / Контракт |
22
22
  | --- | --- |
23
- | [cart_guest_get](https://basklee.com/en/sandbox/api/cart_guest_get) · [RU](https://basklee.com/ru/sandbox/api/cart_guest_get) | Checkout options and saved choices / Опции оформления и сохранённый выбор |
24
- | [invoices_get](https://basklee.com/en/sandbox/api/invoices_get) · [RU](https://basklee.com/ru/sandbox/api/invoices_get) | Transaction direction and refunds / Направление платежей и возвраты |
25
- | [subscriptions_get](https://basklee.com/en/sandbox/api/subscriptions_get) · [RU](https://basklee.com/ru/sandbox/api/subscriptions_get) | Subscription state, renewal and service data / Состояние подписки, продление и данные сервиса |
26
- | [profile_promocodes_get](https://basklee.com/en/sandbox/api/profile_promocodes_get) · [RU](https://basklee.com/ru/sandbox/api/profile_promocodes_get) | Issued codes and promotion conditions / Выданные коды и условия акций |
27
- | [orders_create](https://basklee.com/en/sandbox/api/orders_create) · [RU](https://basklee.com/ru/sandbox/api/orders_create) | Failure fields and recovery / Поля ошибок и исправление |
28
- | [profile_orders_get](https://basklee.com/en/sandbox/api/profile_orders_get) · [RU](https://basklee.com/ru/sandbox/api/profile_orders_get) | Ordered options, returns and downloads / Купленные опции, возвраты и загрузки |
29
- | [subscriptions_guest_search](https://basklee.com/en/sandbox/api/subscriptions_guest_search) · [RU](https://basklee.com/ru/sandbox/api/subscriptions_guest_search) | Plan parameters, units and headings / Параметры тарифа, единицы и подписи |
23
+ | [cart_guest_get](https://docs.basklee.com/en/sandbox/api/cart_guest_get) · [RU](https://docs.basklee.com/ru/sandbox/api/cart_guest_get) | Checkout options and saved choices / Опции оформления и сохранённый выбор |
24
+ | [invoices_get](https://docs.basklee.com/en/sandbox/api/invoices_get) · [RU](https://docs.basklee.com/ru/sandbox/api/invoices_get) | Transaction direction and refunds / Направление платежей и возвраты |
25
+ | [subscriptions_get](https://docs.basklee.com/en/sandbox/api/subscriptions_get) · [RU](https://docs.basklee.com/ru/sandbox/api/subscriptions_get) | Subscription state, renewal and service data / Состояние подписки, продление и данные сервиса |
26
+ | [profile_promocodes_get](https://docs.basklee.com/en/sandbox/api/profile_promocodes_get) · [RU](https://docs.basklee.com/ru/sandbox/api/profile_promocodes_get) | Issued codes and promotion conditions / Выданные коды и условия акций |
27
+ | [orders_create](https://docs.basklee.com/en/sandbox/api/orders_create) · [RU](https://docs.basklee.com/ru/sandbox/api/orders_create) | Failure fields and recovery / Поля ошибок и исправление |
28
+ | [profile_orders_get](https://docs.basklee.com/en/sandbox/api/profile_orders_get) · [RU](https://docs.basklee.com/ru/sandbox/api/profile_orders_get) | Ordered options, returns and downloads / Купленные опции, возвраты и загрузки |
29
+ | [subscriptions_guest_search](https://docs.basklee.com/en/sandbox/api/subscriptions_guest_search) · [RU](https://docs.basklee.com/ru/sandbox/api/subscriptions_guest_search) | Plan parameters, units and headings / Параметры тарифа, единицы и подписи |
30
30
 
31
31
  ## Cart loading / Загрузка корзины
32
32
 
@@ -157,7 +157,7 @@ The following tables describe the response and the supplied composition’s foll
157
157
  | Выбрать пункт выдачи | Запрос `cart_customer_delivery_points_get` получает те же ID отправления и типа, возвращая `page_data.items`. Передайте выбранный объект `point`, включая код, код города и адрес, вместе с этими ID в `cart_customer_delivery_pickup_set`. |
158
158
  | После успешного сохранения | Ответ содержит `page_data.delivery_price_is_estimate`, без обновлённого отправления. Контроллер корзины закрывает выбор и вызывает `cart_guest_get`, чтобы получить подтверждённые способ, адрес, даты и итоги. При отказе показывается ошибка. Если не удалась только повторная загрузка, обновите корзину без повторения успешного сохранения. |
159
159
 
160
- [English guide](https://basklee.com/en/sandbox/components/react/cart-delivery-selector) · [Русский](https://basklee.com/ru/sandbox/components/react/cart-delivery-selector)
160
+ [English guide](https://docs.basklee.com/en/sandbox/components/react/cart-delivery-selector) · [Русский](https://docs.basklee.com/ru/sandbox/components/react/cart-delivery-selector)
161
161
 
162
162
  ## Parent cart loading / Загрузка корзины
163
163
 
@@ -169,4 +169,4 @@ The following tables describe the response and the supplied composition’s foll
169
169
  | `option_group_required` | True помечает группу обязательной. Для текста нужен непустой сохранённый текст, для файла — сохранённое имя, для товарной группы — опция с положительным количеством. |
170
170
  | Очистка | `cart_customer_option_cleanup_additional` получает `option_group_id: group.id` и очищает сохранённые текст/файл. Ошибка сохранения сохраняет локальный ввод; подтверждённое сохранение обновляет корзину. |
171
171
 
172
- [English guide](https://basklee.com/en/sandbox/components/react/cart-item-options) · [Русский](https://basklee.com/ru/sandbox/components/react/cart-item-options)
172
+ [English guide](https://docs.basklee.com/en/sandbox/components/react/cart-item-options) · [Русский](https://docs.basklee.com/ru/sandbox/components/react/cart-item-options)
@@ -135,4 +135,4 @@ The following tables describe the response and the supplied composition’s foll
135
135
  | Удаление в CHECKOUT | Передайте `product.dlf_id` как `dlf_item_id` в `cart_customer_remove_by_dlf_item`. После подтверждения загрузите все отправки и суммы корзины заново. |
136
136
  | Недоступные или неполные данные | `unavailable` скрывает редактирование количества. Если суммы позиции отправки/корзины отсутствуют, выводится `product.product_price_dict`; эта цена не подтверждает итог оформления. |
137
137
 
138
- [English guide](https://basklee.com/en/sandbox/components/react/cart-line-item) · [Русский](https://basklee.com/ru/sandbox/components/react/cart-line-item)
138
+ [English guide](https://docs.basklee.com/en/sandbox/components/react/cart-line-item) · [Русский](https://docs.basklee.com/ru/sandbox/components/react/cart-line-item)
@@ -89,4 +89,4 @@ The following tables describe the response and the supplied composition’s foll
89
89
  | Полученные `link` и `link_type` | Описывают следующую страницу оплаты. Родитель при необходимости передаёт их в `PaymentPanel` и загружает `profile_orders_get`. Пустая ссылка может означать, что внешняя страница не нужна; результат подтверждает обновлённое состояние платежа/заказа. |
90
90
  | `onCancel` / `pending` | Cancel без данных просит родителя закрыть форму. Pending блокирует выбор и обе кнопки. Ошибка сохранения оставляет форму и выбранный способ для исправления. |
91
91
 
92
- [English guide](https://basklee.com/en/sandbox/components/react/order-payment-form) · [Русский](https://basklee.com/ru/sandbox/components/react/order-payment-form)
92
+ [English guide](https://docs.basklee.com/en/sandbox/components/react/order-payment-form) · [Русский](https://docs.basklee.com/ru/sandbox/components/react/order-payment-form)
@@ -111,4 +111,4 @@ The following tables describe the response and the supplied composition’s foll
111
111
  | `onRefresh` | Событие без данных при проверке состояния. Кошелёк обновляет платежи и баланс профиля; страница заказов загружает `profile_orders_get`. |
112
112
  | `onClose` | Событие без данных. Готовый родитель скрывает панель и обновляет те же данные кошелька или заказа. Закрытие меняет видимость панели, а завершение оплаты определяется полученным состоянием платежа/заказа. |
113
113
 
114
- [English guide](https://basklee.com/en/sandbox/components/react/payment-panel) · [Русский](https://basklee.com/ru/sandbox/components/react/payment-panel)
114
+ [English guide](https://docs.basklee.com/en/sandbox/components/react/payment-panel) · [Русский](https://docs.basklee.com/ru/sandbox/components/react/payment-panel)
@@ -34,6 +34,10 @@ multiplier: 20 percent becomes `0.8`; an empty or zero value removes the
34
34
  condition. The additional checkboxes set `avg_raiting_from = 4.5`,
35
35
  `owner_rating_from = 4.5` and `c_aprooved_feedbacks_from = 1` when their
36
36
  corresponding choices are available.
37
+ The first additional checkbox, “In stock only”, sets `only_in_stock = true`:
38
+ products whose stock is out leave the results. It is offered when
39
+ `selects.out_of_stock` of the search is above zero, so a list where every
40
+ product can be bought does not show it.
37
41
  All names retain the API's physical spelling.
38
42
 
39
43
  `disabled` disables every editable control. When the confirmed selector set has
@@ -87,6 +91,10 @@ HTML и после гидратации. Без этих свойств исто
87
91
  удаляет условие. Дополнительные флажки задают `avg_raiting_from = 4.5`,
88
92
  `owner_rating_from = 4.5` и `c_aprooved_feedbacks_from = 1`, когда
89
93
  соответствующие варианты доступны.
94
+ Первый дополнительный флажок, «Только в наличии», задаёт
95
+ `only_in_stock = true`: товары, у которых закончился запас, уходят из
96
+ результатов. Он показан, когда `selects.out_of_stock` поиска больше нуля,
97
+ поэтому в списке, где можно купить каждый товар, его нет.
90
98
  Физическое написание полей API сохранено.
91
99
 
92
100
  `disabled` блокирует все редактируемые элементы. Если в подтверждённом наборе
@@ -142,6 +142,14 @@ export function SearchFilters({
142
142
  }, [facets, fixedFilters, hideCategories, init, labels, locale]);
143
143
 
144
144
  const specialOptions = [
145
+ {
146
+ // Out-of-stock products stay listed; the option is offered when the scope has some.
147
+ key: 'only_in_stock',
148
+ title: labels.inStock,
149
+ value: 'true',
150
+ visible: (facets?.selects.out_of_stock ?? 0) > 0 ||
151
+ filters.only_in_stock === 'true',
152
+ },
145
153
  {
146
154
  key: 'avg_raiting_from',
147
155
  title: labels.ratedProducts,
@@ -180,4 +180,4 @@ The following tables describe the response and the supplied composition’s foll
180
180
  | Отмена продления | Подписка активна, `cancelled_date` отсутствует, у тарифа есть периоды или уже настроено продление. |
181
181
  | После подтверждённого изменения | Загрузите `subscriptions_get` и `profile_get`: используйте полученные тариф, даты, продление, признак ожидания и баланс. Если обновление не удалось, повторите его до следующего действия с оплатой. |
182
182
 
183
- [English guide](https://basklee.com/en/sandbox/components/react/subscriptions) · [Русский](https://basklee.com/ru/sandbox/components/react/subscriptions)
183
+ [English guide](https://docs.basklee.com/en/sandbox/components/react/subscriptions) · [Русский](https://docs.basklee.com/ru/sandbox/components/react/subscriptions)
@@ -113,4 +113,4 @@ The following tables describe the response and the supplied composition’s foll
113
113
  | `sales_module`, `blog_module`, `qr_module` | Логические признаки модулей продаж, блога и QR-маркировки остатков. Справочник встроенных параметров находится в `subscriptions_guest_search`. |
114
114
  | Параметр уже показан рядом с использованием | Его предел исключается из отдельного списка параметров тарифа, чтобы выводиться один раз. |
115
115
 
116
- [English guide](https://basklee.com/en/sandbox/components/react/subscription-plan) · [Русский](https://basklee.com/ru/sandbox/components/react/subscription-plan)
116
+ [English guide](https://docs.basklee.com/en/sandbox/components/react/subscription-plan) · [Русский](https://docs.basklee.com/ru/sandbox/components/react/subscription-plan)
@@ -114,7 +114,7 @@ The following tables describe the response and the supplied composition’s foll
114
114
  | Пример пакета | `host: shop.example` и `enabled: false` дают две строки. Вложенный объект `settings` по умолчанию не выводится. Явный список fields только с `host` оставляет лишь это сведение. |
115
115
  | Собственные сведения | `renderDetails(data, entries)` получает исходные данные сервиса и отфильтрованные записи. Выберите поля для отображения. |
116
116
 
117
- [English guide](https://basklee.com/en/sandbox/components/react/subscription-remote) · [Русский](https://basklee.com/ru/sandbox/components/react/subscription-remote)
117
+ [English guide](https://docs.basklee.com/en/sandbox/components/react/subscription-remote) · [Русский](https://docs.basklee.com/ru/sandbox/components/react/subscription-remote)
118
118
 
119
119
  ## Initial service setup / Первичная настройка сервиса
120
120
 
@@ -106,4 +106,4 @@ The following tables describe the response and the supplied composition’s foll
106
106
  | Нет доступного оплаченного периода; средств недостаточно | Настройка продления успешно сохраняется, но период не покупается. Покажите текущую дату окончания и баланс; для оплаты продления покупателю нужно пополнить баланс. |
107
107
  | После `onSubmit` | Родитель отправляет запрос и загружает `subscriptions_get` и `profile_get`. `renew_period` подтверждает настройку; `active_until` и признак синхронизации определяют состояние доступа. Успех сам по себе подтверждает сохранение настройки, но не новый оплаченный доступ. |
108
108
 
109
- [English guide](https://basklee.com/en/sandbox/components/react/subscription-renewal) · [Русский](https://basklee.com/ru/sandbox/components/react/subscription-renewal)
109
+ [English guide](https://docs.basklee.com/en/sandbox/components/react/subscription-renewal) · [Русский](https://docs.basklee.com/ru/sandbox/components/react/subscription-renewal)
@@ -151,4 +151,4 @@ The following tables describe the response and the supplied composition’s foll
151
151
  | `refunds[].status.int` | Позиция возврата описывает операцию возврата. Завершение подтверждает только `EInvoiceStatus.COMPLETED`; `to_balance` указывает возврат на баланс или исходный способ оплаты. |
152
152
  | Проверка состояния или закрытие | Готовый кошелёк загружает `invoices_get` и `profile_get`, затем берёт баланс из `wallet` текущего профиля. Оплату подтверждает полученное состояние; открытие или закрытие `PaymentPanel` само по себе её не подтверждает. |
153
153
 
154
- [English guide](https://basklee.com/en/sandbox/components/react/wallet) · [Русский](https://basklee.com/ru/sandbox/components/react/wallet)
154
+ [English guide](https://docs.basklee.com/en/sandbox/components/react/wallet) · [Русский](https://docs.basklee.com/ru/sandbox/components/react/wallet)
@@ -33,6 +33,7 @@ export interface IProductSearchFilters {
33
33
  only_featured?: boolean;
34
34
  only_new?: boolean;
35
35
  with_discount?: boolean;
36
+ only_in_stock?: boolean;
36
37
  is_good_for_promo?: number;
37
38
  price_currency?: number;
38
39
  price_from?: number;
@@ -110,6 +111,7 @@ export interface IProductSearchChoices {
110
111
  any: number;
111
112
  };
112
113
  raiting_above_45: number;
114
+ out_of_stock: number;
113
115
  }
114
116
 
115
117
  export interface IProductSearchResponse {
@@ -12,6 +12,8 @@ export interface IProductSearchFacets {
12
12
  };
13
13
  discounts?: { any: number };
14
14
  raiting_above_45?: number;
15
+ // Listed products that cannot be bought now; the in-stock filter hides them.
16
+ out_of_stock?: number;
15
17
  manufacture?: { id: number; name: string; count: number }[];
16
18
  };
17
19
  variants?: Record<
@@ -32,6 +32,7 @@ const FORWARDED = [
32
32
  'x-init-ip',
33
33
  'x-real-ip',
34
34
  'x-forwarded-for',
35
+ 'cf-connecting-ip',
35
36
  'x-tz',
36
37
  ];
37
38
 
@@ -9,6 +9,7 @@ export function browseLabels(locale: string) {
9
9
  applyPrice: 'Применить',
10
10
  moreFilters: 'Дополнительно',
11
11
  discountFrom: 'Скидка от, %',
12
+ inStock: 'Только в наличии',
12
13
  ratedProducts: 'Товары с оценкой от 4,5',
13
14
  ratedSellers: 'Продавцы с оценкой от 4,5',
14
15
  withReviews: 'Только с отзывами',
@@ -56,6 +57,7 @@ export function browseLabels(locale: string) {
56
57
  applyPrice: 'Aplicar',
57
58
  moreFilters: 'Más filtros',
58
59
  discountFrom: 'Descuento mínimo, %',
60
+ inStock: 'Solo en stock',
59
61
  ratedProducts: 'Productos con valoración de 4,5 o más',
60
62
  ratedSellers: 'Vendedores con valoración de 4,5 o más',
61
63
  withReviews: 'Solo con reseñas',
@@ -103,6 +105,7 @@ export function browseLabels(locale: string) {
103
105
  applyPrice: 'Apply',
104
106
  moreFilters: 'More filters',
105
107
  discountFrom: 'Minimum discount, %',
108
+ inStock: 'In stock only',
106
109
  ratedProducts: 'Products rated 4.5 and above',
107
110
  ratedSellers: 'Sellers rated 4.5 and above',
108
111
  withReviews: 'With reviews only',
@@ -1,8 +1,8 @@
1
1
  // The product page's schema.org data for search engines: Google merchant
2
2
  // listings and Yandex product snippets read the same block. Every value
3
3
  // repeats what the page shows: the price and the crossed-out old price,
4
- // stock, return terms, photos, brand, seller and rating. The delivery cost is
5
- // left out: it depends on the buyer's address.
4
+ // stock (or a preorder), return terms, photos, brand, seller and rating. The
5
+ // delivery cost is left out: it depends on the buyer's address.
6
6
  // The same file is in the three packages; it has no imports so that it stays
7
7
  // identical.
8
8
 
@@ -49,6 +49,12 @@ export interface StorefrontProductDataOptions {
49
49
  shippingCountries: string[];
50
50
  /** False when the page hides the seller (single-seller storefront). */
51
51
  showSeller: boolean;
52
+ /**
53
+ * True when the page offers a preorder instead of «Add to cart»
54
+ * (productAvailability().canPreorder): the offer is PreOrder, not OutOfStock.
55
+ * Yandex hides the price of an out-of-stock offer.
56
+ */
57
+ preorder?: boolean;
52
58
  /** Makes an image address complete (storefrontAbsoluteUrl). */
53
59
  absoluteUrl: (value: string | undefined) => string | undefined;
54
60
  }
@@ -158,8 +164,16 @@ export function storefrontProductStructuredData(
158
164
  ON_SALE_STATUSES.includes(product.status?.status) &&
159
165
  product.c_real_left > 0;
160
166
  const returns = productReturnPolicy(product, options.shippingCountries);
161
- const brand = product.manufacture?.name?.trim();
167
+ // Yandex requires a brand: without a manufacturer the seller (in a
168
+ // single-seller storefront, the shop itself) made the product.
169
+ const brand =
170
+ product.manufacture?.name?.trim() || product.seller?.name?.trim();
162
171
  const seller = options.showSeller ? product.seller?.name?.trim() : '';
172
+ const availability = inStock
173
+ ? 'InStock'
174
+ : options.preorder
175
+ ? 'PreOrder'
176
+ : 'OutOfStock';
163
177
  const reviews = Number(product.feedback_stat?.c_feedbacks ?? 0);
164
178
  const rating = Number(product.feedback_stat?.avg_raiting ?? 0);
165
179
  const offer =
@@ -180,7 +194,7 @@ export function storefrontProductStructuredData(
180
194
  },
181
195
  }
182
196
  : {}),
183
- 'availability': `${SCHEMA_ORG}${inStock ? 'InStock' : 'OutOfStock'}`,
197
+ 'availability': `${SCHEMA_ORG}${availability}`,
184
198
  'itemCondition': `${SCHEMA_ORG}NewCondition`,
185
199
  ...(returns ? { hasMerchantReturnPolicy: returns } : {}),
186
200
  ...(seller
@@ -89,6 +89,7 @@ export const getBaskleeServerApi = cache(async () => {
89
89
  'x-init-ip',
90
90
  'x-real-ip',
91
91
  'x-forwarded-for',
92
+ 'cf-connecting-ip',
92
93
  'x-tz',
93
94
  ]) {
94
95
  const value = incoming.get(name);