basklee-svelte 0.9.4 → 0.9.5

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 (25) hide show
  1. package/README.md +4 -0
  2. package/package.json +2 -2
  3. package/templates/src/lib/components/basklee/account/StorefrontLogout.README.md +2 -0
  4. package/templates/src/lib/components/basklee/orders/OrderDetails.README.md +2 -0
  5. package/templates/src/lib/components/basklee/orders/OrderDetails.svelte +5 -0
  6. package/templates/src/lib/components/basklee/storefront/StorefrontFooter.README.md +6 -0
  7. package/templates/src/lib/components/basklee/storefront/StorefrontFooter.svelte +25 -7
  8. package/templates/src/lib/components/basklee/stores/StorefrontStores.README.md +2 -0
  9. package/templates/src/lib/components/basklee/stores/StorefrontStores.svelte +2 -1
  10. package/templates/src/lib/utils/basklee/browseLabels.ts +12 -0
  11. package/templates/src/lib/utils/basklee/cartLabels.ts +3 -0
  12. package/templates/src/lib/utils/basklee/contactLabels.ts +12 -0
  13. package/templates/src/lib/utils/basklee/directoryLabels.ts +3 -0
  14. package/templates/src/lib/utils/basklee/featureLabels.ts +12 -0
  15. package/templates/src/lib/utils/basklee/footerLabels.ts +3 -0
  16. package/templates/src/lib/utils/basklee/profile.ts +52 -0
  17. package/templates/src/lib/utils/basklee/profileLabels.ts +15 -0
  18. package/templates/src/lib/utils/basklee/reviewLabels.ts +6 -0
  19. package/templates/src/lib/utils/basklee/sellerDirectory.ts +93 -0
  20. package/templates/src/lib/utils/basklee/sessionLabels.ts +6 -6
  21. package/templates/src/lib/utils/basklee/storeDirectory.ts +26 -0
  22. package/templates/src/lib/utils/basklee/subscriptionLabels.ts +3 -0
  23. package/templates/src/lib/utils/basklee/tabLocation.ts +37 -0
  24. package/templates/src/lib/utils/basklee/ticketDraft.ts +56 -0
  25. package/templates/src/routes/browse/+page.svelte +2 -2
package/README.md CHANGED
@@ -641,3 +641,7 @@ The store is scoped to one render on the server and the root layout in the
641
641
  browser. It preserves valid selections when Application Load refreshes. HTTP
642
642
  401 clears account data and refreshes the guest session without repeating the
643
643
  failed mutation. API validation errors remain beside the affected form.
644
+
645
+ ---
646
+
647
+ Powered by [Basklee](https://basklee.com).
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "basklee-svelte",
3
- "version": "0.9.4",
4
- "description": "SvelteKit 2 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.",
3
+ "version": "0.9.5",
4
+ "description": "SvelteKit 2 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. Powered by Basklee: https://basklee.com",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "author": "Basklee",
@@ -10,6 +10,8 @@ running, failed and finished states and sends no other request.
10
10
 
11
11
  Source: `src/lib/components/basklee/account/StorefrontLogout.svelte`.
12
12
 
13
+ The progress and success messages say that the session is ended on all devices: `profile_logout` signs the customer out everywhere, and the page says so.
14
+
13
15
  ## Inputs
14
16
 
15
17
  | Input | Type | Default |
@@ -6,6 +6,8 @@ The details show one placed order in full. The order is handed to the component
6
6
 
7
7
  Source: `src/lib/components/basklee/orders/OrderDetails.svelte`.
8
8
 
9
+ While nothing has left yet, the first step of the rail carries the order's own status word, Processing, in place of Placed: the status card and the rail name one stage, not two.
10
+
9
11
  ## Inputs
10
12
 
11
13
  | Input | Type | Default |
@@ -177,6 +177,11 @@
177
177
  if (step.state === 'partial' && step.key === 'delivered') {
178
178
  return statuses.partlyDelivered;
179
179
  }
180
+ // While nothing has left, the first step carries the order's own status
181
+ // word («Processing»): the card and the rail name one stage, not two.
182
+ if (step.key === 'placed' && step.current) {
183
+ return statuses.processing;
184
+ }
180
185
 
181
186
  return labels.value.steps[step.key];
182
187
  }
@@ -27,3 +27,9 @@ Source: `src/lib/components/basklee/storefront/StorefrontFooter.svelte`.
27
27
  Navigation omits categories with `exclude_from_tree: true` and all their descendants. The full published catalog remains available for product main-category names, links and breadcrumbs.
28
28
 
29
29
  В навигации скрываются категории с `exclude_from_tree: true` и все их подкатегории. Полный каталог опубликованных категорий сохраняется для названий, ссылок и цепочек основной категории товара.
30
+
31
+ ## Powered by Basklee
32
+
33
+ The bottom line of the footer ends with a small link, «Powered by Basklee»: an `<a href="https://basklee.com">` that opens in a new tab and is marked `data-footer-part="PoweredBy"`. Its text is the `powered` label of `footerLabels` (English, Russian, Spanish). The link is external, so the navigation callback is not called for it.
34
+
35
+ Нижняя строка футера заканчивается маленькой ссылкой «Работает на Basklee»: это `<a href="https://basklee.com">`, она открывается в новой вкладке и отмечена `data-footer-part="PoweredBy"`. Её текст — подпись `powered` из `footerLabels` (английский, русский, испанский). Ссылка внешняя, поэтому обработчик навигации для неё не вызывается.
@@ -256,17 +256,35 @@
256
256
  </a>
257
257
  </nav>
258
258
  </div>
259
- <p
259
+ <div
260
260
  class={[
261
261
  `
262
- m-0 pt-6 border-0 border-t border-solid
263
- border-basklee-inverse-text/15 text-xs uppercase leading-6
264
- tracking-[0.08em] text-basklee-inverse-muted
262
+ flex flex-wrap items-baseline justify-between gap-x-6 gap-y-1 pt-6
263
+ border-0 border-t border-solid border-basklee-inverse-text/15
264
+ text-xs uppercase leading-6 tracking-[0.08em]
265
+ text-basklee-inverse-muted
265
266
  `,
266
267
  ]}
267
268
  >
268
- © {inputs.year}
269
- {company.value} · {copy.value.rights}
270
- </p>
269
+ <p class="m-0">
270
+ © {inputs.year}
271
+ {company.value} · {copy.value.rights}
272
+ </p>
273
+ <a
274
+ href="https://basklee.com"
275
+ target="_blank"
276
+ rel="noopener"
277
+ class={[
278
+ `
279
+ text-basklee-inverse-muted no-underline outline-none
280
+ hover:text-basklee-inverse-text
281
+ focus-visible:text-basklee-inverse-text
282
+ `,
283
+ ]}
284
+ data-footer-part="PoweredBy"
285
+ >
286
+ {copy.value.powered}
287
+ </a>
288
+ </div>
271
289
  </div>
272
290
  </footer>
@@ -18,6 +18,8 @@ and `page`, so a reload or Back from a store's products opens the same list.
18
18
 
19
19
  Source: `src/lib/components/basklee/stores/StorefrontStores.svelte`.
20
20
 
21
+ A phone number is shown as people read it: a number typed with its own spaces, brackets or dashes stays as typed, and a bare run of digits is grouped from the end (`+78120000078` reads `+7 812 000 00 78`). The dial link keeps the digits only.
22
+
21
23
  ## Inputs
22
24
 
23
25
  | Input | Type | Default |
@@ -25,6 +25,7 @@
25
25
  storeMapMarkers,
26
26
  storeMarkerId,
27
27
  storePhoneLink,
28
+ storePhoneText,
28
29
  } from '@/lib/utils/basklee/storeDirectory';
29
30
  import type { IApiPagination } from '@/lib/interfaces/basklee/accounts/IProfileData';
30
31
  import type {
@@ -347,7 +348,7 @@
347
348
  href={storePhoneLink(item.phone_number)}
348
349
  class={['op-feature-link self-start']}
349
350
  >
350
- {item.phone_number}
351
+ {storePhoneText(item.phone_number)}
351
352
  </a>
352
353
  {/if}
353
354
 
@@ -19,6 +19,10 @@ export function browseLabels(locale: string) {
19
19
  clear: 'Сбросить',
20
20
  emptyTitle: 'Ничего не найдено',
21
21
  emptyHint: 'Попробуйте изменить запрос или сбросить фильтры.',
22
+ emptyHintPlain: 'Проверьте написание или попробуйте слово покороче.',
23
+ emptyCategoryPlain: 'В этой категории пока нет товаров. Загляните в другие разделы каталога.',
24
+ editSearch: 'Изменить запрос',
25
+ browseCatalog: 'Открыть каталог',
22
26
  emptyCategoryHint:
23
27
  'В этой категории пока нет подходящих товаров. Попробуйте убрать фильтры или выбрать другую категорию.',
24
28
  startTitle: 'Что вы ищете?',
@@ -67,6 +71,10 @@ export function browseLabels(locale: string) {
67
71
  clear: 'Borrar',
68
72
  emptyTitle: 'No se han encontrado productos',
69
73
  emptyHint: 'Prueba otra búsqueda o borra los filtros.',
74
+ emptyHintPlain: 'Revisa la ortografía o prueba con una palabra más corta.',
75
+ emptyCategoryPlain: 'Aún no hay productos en esta categoría. Mira las demás secciones del catálogo.',
76
+ editSearch: 'Cambiar la búsqueda',
77
+ browseCatalog: 'Ver el catálogo',
70
78
  emptyCategoryHint:
71
79
  'Todavía no hay productos que coincidan en esta categoría. Prueba a quitar filtros o elige otra categoría.',
72
80
  startTitle: '¿Qué estás buscando?',
@@ -115,6 +123,10 @@ export function browseLabels(locale: string) {
115
123
  clear: 'Clear',
116
124
  emptyTitle: 'No products found',
117
125
  emptyHint: 'Try another search or clear the filters.',
126
+ emptyHintPlain: 'Check the spelling or try a shorter word.',
127
+ emptyCategoryPlain: 'There are no products in this category yet. Look through the rest of the catalogue.',
128
+ editSearch: 'Change the search',
129
+ browseCatalog: 'Browse the catalogue',
118
130
  emptyCategoryHint:
119
131
  'No matching products in this category yet. Try removing filters or choosing another category.',
120
132
  startTitle: 'What are you looking for?',
@@ -59,6 +59,7 @@ const en = {
59
59
  deliveryDiscount: 'Delivery discount',
60
60
  total: 'Total',
61
61
  promo: 'Promo code',
62
+ promoOptional: 'optional',
62
63
  apply: 'Apply',
63
64
  removePromo: 'Remove',
64
65
  removePromoHint: 'Remove promo code',
@@ -186,6 +187,7 @@ const ru: typeof en = {
186
187
  deliveryDiscount: 'Скидка на доставку',
187
188
  total: 'Итого',
188
189
  promo: 'Промокод',
190
+ promoOptional: 'необязательно',
189
191
  apply: 'Применить',
190
192
  removePromo: 'Удалить',
191
193
  removePromoHint: 'Удалить промокод',
@@ -311,6 +313,7 @@ const es: typeof en = {
311
313
  deliveryDiscount: 'Descuento en el envío',
312
314
  total: 'Total',
313
315
  promo: 'Código promocional',
316
+ promoOptional: 'opcional',
314
317
  apply: 'Aplicar',
315
318
  removePromo: 'Quitar',
316
319
  removePromoHint: 'Quitar el código promocional',
@@ -36,6 +36,10 @@ const en = {
36
36
  newsletter: 'Stop receiving newsletters',
37
37
  products: 'Stop product availability emails',
38
38
  unsubscribeDone: 'You have unsubscribed from these emails.',
39
+ invalidLinkHelp:
40
+ 'No longer have that email? You can switch these emails off in your profile, or write to the shop.',
41
+ emailSettings: 'Email settings',
42
+ writeToShop: 'Contact the shop',
39
43
  invalidLink:
40
44
  'This link is incomplete. Open the unsubscribe link from your email.',
41
45
  event: 'Take part in this offer',
@@ -86,6 +90,10 @@ const ru: typeof en = {
86
90
  newsletter: 'Отказаться от новостной рассылки',
87
91
  products: 'Отказаться от писем о наличии товаров',
88
92
  unsubscribeDone: 'Вы отписались от этих писем.',
93
+ invalidLinkHelp:
94
+ 'Письма уже нет? Отключить рассылку можно в профиле, или напишите в магазин.',
95
+ emailSettings: 'Настройки писем',
96
+ writeToShop: 'Написать в магазин',
89
97
  invalidLink: 'Ссылка неполная. Откройте ссылку отписки из письма.',
90
98
  event: 'Участвовать в акции',
91
99
  eventDescription: 'Подтвердите участие, чтобы получить предложение по почте.',
@@ -135,6 +143,10 @@ const es: typeof en = {
135
143
  newsletter: 'Dejar de recibir boletines',
136
144
  products: 'Dejar de recibir correos de disponibilidad',
137
145
  unsubscribeDone: 'Te has dado de baja de estos correos.',
146
+ invalidLinkHelp:
147
+ '¿Ya no tienes ese correo? Puedes desactivar estos correos en tu perfil o escribir a la tienda.',
148
+ emailSettings: 'Ajustes de correo',
149
+ writeToShop: 'Contactar con la tienda',
138
150
  invalidLink:
139
151
  'Este enlace está incompleto. Abre el enlace de baja desde tu correo.',
140
152
  event: 'Participa en esta oferta',
@@ -11,6 +11,7 @@ const en = {
11
11
  letter: 'Names starting with',
12
12
  rating: 'Seller rating',
13
13
  reviews: 'Reviews',
14
+ noRatings: 'No ratings yet',
14
15
  since: 'Selling since',
15
16
  hours: 'Opening hours',
16
17
  phone: 'Phone',
@@ -75,6 +76,7 @@ const ru: typeof en = {
75
76
  letter: 'Названия на букву',
76
77
  rating: 'Рейтинг продавца',
77
78
  reviews: 'Отзывы',
79
+ noRatings: 'Оценок пока нет',
78
80
  since: 'Продаёт с',
79
81
  hours: 'Часы работы',
80
82
  phone: 'Телефон',
@@ -140,6 +142,7 @@ const es: typeof en = {
140
142
  letter: 'Nombres que empiezan por',
141
143
  rating: 'Valoración del vendedor',
142
144
  reviews: 'Reseñas',
145
+ noRatings: 'Aún sin valoraciones',
143
146
  since: 'Vende desde',
144
147
  hours: 'Horario',
145
148
  phone: 'Teléfono',
@@ -36,6 +36,7 @@ const en = {
36
36
  activity: 'My activity',
37
37
  },
38
38
  logout: 'Logout',
39
+ logoutScope: 'on all devices',
39
40
  addresses: {
40
41
  title: 'My addresses',
41
42
  description: 'Saved addresses for delivery.',
@@ -97,6 +98,9 @@ const en = {
97
98
  paid_subs: 'Subscriptions',
98
99
  empty: 'No payments in this category yet.',
99
100
  unavailable: 'No payment methods are available.',
101
+ unavailableHint:
102
+ 'The wallet cannot be topped up from your account right now: the shop offers no payment method for it. Orders can still be paid at checkout. If you expected to see a method here, write to the shop.',
103
+ contactShop: 'Write to the shop',
100
104
  pay: 'Pay',
101
105
  cancelInvoice: 'Cancel',
102
106
  cancelQuestion: 'Cancel this unpaid invoice?',
@@ -171,6 +175,7 @@ const ru: typeof en = {
171
175
  activity: 'Моя активность',
172
176
  },
173
177
  logout: 'Выйти',
178
+ logoutScope: 'на всех устройствах',
174
179
  addresses: {
175
180
  title: 'Мои адреса',
176
181
  description: 'Сохранённые адреса для доставки.',
@@ -232,6 +237,9 @@ const ru: typeof en = {
232
237
  paid_subs: 'Подписки',
233
238
  empty: 'В этой категории пока нет платежей.',
234
239
  unavailable: 'Нет доступных способов оплаты.',
240
+ unavailableHint:
241
+ 'Сейчас пополнить кошелёк с вашего аккаунта нельзя: магазин не предлагает для этого способа оплаты. Заказы по-прежнему можно оплатить при оформлении. Если способ оплаты здесь должен быть, напишите магазину.',
242
+ contactShop: 'Написать магазину',
235
243
  pay: 'Оплатить',
236
244
  cancelInvoice: 'Отменить',
237
245
  cancelQuestion: 'Отменить этот неоплаченный счёт?',
@@ -304,6 +312,7 @@ const es: typeof en = {
304
312
  activity: 'Mi actividad',
305
313
  },
306
314
  logout: 'Cerrar sesión',
315
+ logoutScope: 'en todos los dispositivos',
307
316
  addresses: {
308
317
  title: 'Mis direcciones',
309
318
  description: 'Direcciones guardadas para la entrega.',
@@ -365,6 +374,9 @@ const es: typeof en = {
365
374
  paid_subs: 'Suscripciones',
366
375
  empty: 'Todavía no hay pagos en esta categoría.',
367
376
  unavailable: 'No hay métodos de pago disponibles.',
377
+ unavailableHint:
378
+ 'Ahora no se puede recargar el monedero desde su cuenta: la tienda no ofrece ningún método de pago para ello. Los pedidos se pueden pagar al finalizar la compra. Si esperaba ver un método aquí, escriba a la tienda.',
379
+ contactShop: 'Escribir a la tienda',
368
380
  pay: 'Pagar',
369
381
  cancelInvoice: 'Cancelar',
370
382
  cancelQuestion: '¿Cancelar esta factura sin pagar?',
@@ -12,6 +12,7 @@ export function footerLabels(locale: string) {
12
12
  profile: 'Личный кабинет',
13
13
  journal: 'Журнал',
14
14
  rights: 'Все права защищены.',
15
+ powered: 'Работает на Basklee',
15
16
  products: 'Товары',
16
17
  discounts: 'Скидки',
17
18
  new: 'Новинки',
@@ -29,6 +30,7 @@ export function footerLabels(locale: string) {
29
30
  profile: 'Mi cuenta',
30
31
  journal: 'Blog',
31
32
  rights: 'Todos los derechos reservados.',
33
+ powered: 'Funciona con Basklee',
32
34
  products: 'Productos',
33
35
  discounts: 'Descuentos',
34
36
  new: 'Novedades',
@@ -45,6 +47,7 @@ export function footerLabels(locale: string) {
45
47
  profile: 'My account',
46
48
  journal: 'Journal',
47
49
  rights: 'All rights reserved.',
50
+ powered: 'Powered by Basklee',
48
51
  products: 'Products',
49
52
  discounts: 'Discounts',
50
53
  new: 'New arrivals',
@@ -150,3 +150,55 @@ export function applyProfileAuthenticationData(
150
150
  state.authEmail = '';
151
151
  }
152
152
  }
153
+
154
+ /**
155
+ * A language by its code, named in the language of the page («English»,
156
+ * «Español», «Русский»). The shop's own short names («Eng») do not tell a
157
+ * customer which language their order letters come in; `fallback` is used
158
+ * when the browser has no name for the code.
159
+ */
160
+ export function profileLanguageName(code: string, locale: string, fallback: string) {
161
+ try {
162
+ const name = new Intl.DisplayNames([locale], { type: 'language' }).of(code);
163
+
164
+ if (name && name.toLowerCase() !== code.toLowerCase()) {
165
+ return name.charAt(0).toLocaleUpperCase(locale) + name.slice(1);
166
+ }
167
+ } catch {
168
+ // An unknown code keeps the shop's own name.
169
+ }
170
+ return fallback;
171
+ }
172
+
173
+ // Personal details typed and not saved yet. They stay in the page's memory
174
+ // while the customer visits other pages, so coming back to the profile shows
175
+ // what was typed. Memory only: a reload starts from the saved profile, the
176
+ // server keeps nothing, and a draft belongs to one customer ID.
177
+ export interface ProfileDetailsDraft {
178
+ first_name: string;
179
+ last_name: string;
180
+ dob: string;
181
+ }
182
+
183
+ const profileDrafts = new Map<number, ProfileDetailsDraft>();
184
+
185
+ export function readProfileDraft(customerId: number | undefined) {
186
+ return typeof window !== 'undefined' && customerId
187
+ ? profileDrafts.get(customerId)
188
+ : undefined;
189
+ }
190
+
191
+ // `null` drops the draft: the details were saved or the customer discarded them.
192
+ export function keepProfileDraft(
193
+ customerId: number | undefined,
194
+ draft: ProfileDetailsDraft | null,
195
+ ) {
196
+ if (typeof window === 'undefined' || !customerId) {
197
+ return;
198
+ }
199
+ if (draft) {
200
+ profileDrafts.set(customerId, { ...draft });
201
+ } else {
202
+ profileDrafts.delete(customerId);
203
+ }
204
+ }
@@ -27,6 +27,11 @@ const en = {
27
27
  email: 'Email address',
28
28
  emailHint:
29
29
  'Verify your address before receiving order updates and email notifications.',
30
+ emailConfirmed: 'Confirmed',
31
+ emailConfirmedHint:
32
+ 'Order updates and notifications are sent to this address. To change it, type a new address and send a code.',
33
+ unsaved: 'You have unsaved changes.',
34
+ discard: 'Discard',
30
35
  sendCode: 'Send',
31
36
  sendCodeHint: 'Send verification code',
32
37
  code: 'Verification code',
@@ -102,6 +107,11 @@ const ru: typeof en = {
102
107
  email: 'Электронная почта',
103
108
  emailHint:
104
109
  'Подтвердите адрес для получения уведомлений о заказах и рассылки.',
110
+ emailConfirmed: 'Подтверждён',
111
+ emailConfirmedHint:
112
+ 'На этот адрес приходят письма о заказах и уведомления. Чтобы сменить его, введите новый адрес и отправьте код.',
113
+ unsaved: 'Есть несохранённые изменения.',
114
+ discard: 'Отменить изменения',
105
115
  sendCode: 'Отправить',
106
116
  sendCodeHint: 'Отправить код подтверждения',
107
117
  code: 'Код подтверждения',
@@ -178,6 +188,11 @@ const es: typeof en = {
178
188
  email: 'Dirección de correo',
179
189
  emailHint:
180
190
  'Verifica tu dirección antes de recibir novedades de pedidos y notificaciones por correo.',
191
+ emailConfirmed: 'Confirmada',
192
+ emailConfirmedHint:
193
+ 'Los avisos de pedidos y las notificaciones llegan a esta dirección. Para cambiarla, escriba una nueva y envíe un código.',
194
+ unsaved: 'Hay cambios sin guardar.',
195
+ discard: 'Descartar',
181
196
  sendCode: 'Enviar',
182
197
  sendCodeHint: 'Enviar código de verificación',
183
198
  code: 'Código de verificación',
@@ -24,6 +24,8 @@ const en = {
24
24
  productPhotos: 'Product photos',
25
25
  openProductPhoto: 'Open the photo full screen',
26
26
  empty: 'No reviews yet.',
27
+ emptyFiltered: 'No reviews match these filters.',
28
+ showAll: 'Show all reviews',
27
29
  emptyImages: 'No customer photos yet.',
28
30
  send: 'Submit',
29
31
  save: 'Save',
@@ -103,6 +105,8 @@ const ru: typeof en = {
103
105
  productPhotos: 'Фотографии товара',
104
106
  openProductPhoto: 'Открыть фотографию на весь экран',
105
107
  empty: 'Отзывов пока нет.',
108
+ emptyFiltered: 'Под эти фильтры не подходит ни один отзыв.',
109
+ showAll: 'Показать все отзывы',
106
110
  emptyImages: 'Покупатели ещё не добавили фотографии.',
107
111
  send: 'Отправить',
108
112
  save: 'Сохранить',
@@ -183,6 +187,8 @@ const es: typeof en = {
183
187
  productPhotos: 'Fotos del producto',
184
188
  openProductPhoto: 'Abrir la foto a pantalla completa',
185
189
  empty: 'Aún no hay reseñas.',
190
+ emptyFiltered: 'Ninguna reseña coincide con estos filtros.',
191
+ showAll: 'Ver todas las reseñas',
186
192
  emptyImages: 'Aún no hay fotos de clientes.',
187
193
  send: 'Enviar',
188
194
  save: 'Guardar',
@@ -41,6 +41,99 @@ export function hasSellerFilters(filters: ISellerDirectoryFilters) {
41
41
  );
42
42
  }
43
43
 
44
+ // Where the seller directory is: its filters, order and page. The directory
45
+ // keeps it in the URL as `?name&rating&cats&sort&page`, so Back from a seller,
46
+ // a reload and a copied address return to the same list.
47
+ export interface SellerDirectoryLocation {
48
+ filters: ISellerDirectoryFilters;
49
+ page: number;
50
+ }
51
+
52
+ type SellerQueryValue = string | null | undefined | readonly (string | null)[];
53
+
54
+ const sellerLocationKeys = ['name', 'rating', 'cats', 'sort', 'page'];
55
+
56
+ function firstSellerQueryValue(value: SellerQueryValue) {
57
+ return Array.isArray(value) ? value[0] : (value as string | null | undefined);
58
+ }
59
+
60
+ function positiveSellerQueryNumber(value: string | null | undefined) {
61
+ const number = Number(value);
62
+
63
+ return Number.isSafeInteger(number) && number > 0 ? number : undefined;
64
+ }
65
+
66
+ // Unknown or damaged values fall back to the full list in the default order.
67
+ export function sellerLocationFromQuery(
68
+ query: Record<string, SellerQueryValue>,
69
+ ): SellerDirectoryLocation {
70
+ const filters = emptySellerFilters();
71
+ const rating = positiveSellerQueryNumber(firstSellerQueryValue(query.rating));
72
+ const cats = (firstSellerQueryValue(query.cats) ?? '')
73
+ .split(',')
74
+ .map((part) => positiveSellerQueryNumber(part))
75
+ .filter((id): id is number => id !== undefined);
76
+
77
+ filters.seller_name = (firstSellerQueryValue(query.name) ?? '').slice(0, 200);
78
+ if (rating !== undefined && rating <= SELLER_RATING_MAXIMUM) {
79
+ filters.seller_rating_from = rating;
80
+ }
81
+ filters.seller_categories = [...new Set(cats)];
82
+ if (firstSellerQueryValue(query.sort) === 'low') {
83
+ filters.ordering = 'seller_raiting';
84
+ }
85
+
86
+ return {
87
+ filters,
88
+ page: positiveSellerQueryNumber(firstSellerQueryValue(query.page)) ?? 1,
89
+ };
90
+ }
91
+
92
+ // The query of `next`: other parameters such as `locale` stay and defaults
93
+ // are left out, so the plain directory keeps its plain address.
94
+ export function sellerLocationQuery(
95
+ query: Record<string, SellerQueryValue>,
96
+ next: SellerDirectoryLocation,
97
+ ) {
98
+ const result: Record<string, string> = {};
99
+ const name = next.filters.seller_name.trim();
100
+
101
+ for (const [key, value] of Object.entries(query)) {
102
+ const text = firstSellerQueryValue(value);
103
+
104
+ if (typeof text === 'string' && !sellerLocationKeys.includes(key)) {
105
+ result[key] = text;
106
+ }
107
+ }
108
+ if (name) {
109
+ result.name = name;
110
+ }
111
+ if (next.filters.seller_rating_from !== null) {
112
+ result.rating = String(next.filters.seller_rating_from);
113
+ }
114
+ if (next.filters.seller_categories.length) {
115
+ result.cats = next.filters.seller_categories.join(',');
116
+ }
117
+ if (next.filters.ordering === 'seller_raiting') {
118
+ result.sort = 'low';
119
+ }
120
+ if (next.page > 1) {
121
+ result.page = String(next.page);
122
+ }
123
+
124
+ return result;
125
+ }
126
+
127
+ export function sameSellerLocation(
128
+ left: SellerDirectoryLocation,
129
+ right: SellerDirectoryLocation,
130
+ ) {
131
+ return (
132
+ left.page === right.page &&
133
+ JSON.stringify(left.filters) === JSON.stringify(right.filters)
134
+ );
135
+ }
136
+
44
137
  export function sellerDirectoryRequest(
45
138
  filters: ISellerDirectoryFilters,
46
139
  page: number,
@@ -2,37 +2,37 @@ export function sessionLabels(locale: string) {
2
2
  return locale.toLowerCase().startsWith('ru')
3
3
  ? {
4
4
  title: 'Выход из аккаунта',
5
- pending: 'Завершаем сеанс…',
5
+ pending: 'Завершаем сеансы на всех устройствах…',
6
6
  hint: 'После выхода вы вернётесь на главную страницу.',
7
7
  failed: 'Не удалось завершить выход',
8
8
  retryHint:
9
9
  'Повторите попытку. Выход подтверждается только ответом сервера.',
10
10
  refreshFailed: 'Сеанс завершён. Не удалось загрузить магазин.',
11
11
  retry: 'Повторить',
12
- done: 'Вы вышли из аккаунта',
12
+ done: 'Вы вышли из аккаунта на всех устройствах',
13
13
  home: 'Главная',
14
14
  }
15
15
  : locale.toLowerCase().startsWith('es') ? {
16
16
  title: 'Cerrando sesión',
17
- pending: 'Terminando tu sesión…',
17
+ pending: 'Cerrando tu sesión en todos los dispositivos…',
18
18
  hint: 'Volverás a la página de inicio de la tienda.',
19
19
  failed: 'No se ha podido cerrar la sesión',
20
20
  retryHint: 'Inténtalo de nuevo. El cierre de sesión lo confirma el servidor.',
21
21
  refreshFailed:
22
22
  'Tu sesión ha terminado. No se ha podido recargar la tienda.',
23
23
  retry: 'Reintentar',
24
- done: 'Has cerrado la sesión',
24
+ done: 'Has cerrado la sesión en todos los dispositivos',
25
25
  home: 'Inicio',
26
26
  } : {
27
27
  title: 'Signing out',
28
- pending: 'Ending your session…',
28
+ pending: 'Ending your sessions on all devices…',
29
29
  hint: 'You will return to the storefront home page.',
30
30
  failed: 'Could not finish signing out',
31
31
  retryHint: 'Please try again. Sign-out is confirmed by the server.',
32
32
  refreshFailed:
33
33
  'Your session has ended. The storefront could not be reloaded.',
34
34
  retry: 'Retry',
35
- done: 'You are signed out',
35
+ done: 'You are signed out on all devices',
36
36
  home: 'Home',
37
37
  };
38
38
  }
@@ -48,3 +48,29 @@ export function storeMapMarkers(
48
48
  export function storePhoneLink(value: string) {
49
49
  return `tel:${value.replace(/[^+0-9]/g, '')}`;
50
50
  }
51
+
52
+ /**
53
+ * A store's telephone as people read it. A number typed with its own spaces,
54
+ * brackets or dashes is shown as typed; a bare run of digits («+78120000078»)
55
+ * is grouped from the end («+7 812 000 00 78»), the way the shop's contact
56
+ * page writes its number. The dial link keeps using `storePhoneLink`.
57
+ */
58
+ export function storePhoneText(value: string) {
59
+ const text = value.trim();
60
+
61
+ if (!/^\+?\d{7,15}$/.test(text)) {
62
+ return text;
63
+ }
64
+ const digits = text.replace('+', '');
65
+ const groups = [digits.slice(-2), digits.slice(-4, -2)];
66
+ let rest = digits.slice(0, -4);
67
+
68
+ while (rest.length > 3) {
69
+ groups.push(rest.slice(-3));
70
+ rest = rest.slice(0, -3);
71
+ }
72
+ if (rest) {
73
+ groups.push(rest);
74
+ }
75
+ return `${text.startsWith('+') ? '+' : ''}${groups.reverse().join(' ')}`;
76
+ }
@@ -21,6 +21,7 @@ const en = {
21
21
  intro:
22
22
  'Choose a plan and a subscription period. Paid periods are charged to the account balance.',
23
23
  noOffers: 'No subscription plans are available yet.',
24
+ toCatalog: 'Browse the catalogue',
24
25
  reset: 'Reset',
25
26
  support: 'Subscription support',
26
27
  wallet: 'Top up balance',
@@ -53,6 +54,7 @@ const ru: typeof en = {
53
54
  intro:
54
55
  'Выберите тариф и период подписки. Платные периоды оплачиваются с баланса аккаунта.',
55
56
  noOffers: 'Тарифов подписок пока нет.',
57
+ toCatalog: 'Открыть каталог',
56
58
  reset: 'Сбросить',
57
59
  support: 'Поддержка по подписке',
58
60
  wallet: 'Пополнить баланс',
@@ -86,6 +88,7 @@ const es: typeof en = {
86
88
  intro:
87
89
  'Elige un plan y un periodo de suscripción. Los periodos de pago se cobran del saldo de la cuenta.',
88
90
  noOffers: 'Todavía no hay planes de suscripción disponibles.',
91
+ toCatalog: 'Ver el catálogo',
89
92
  reset: 'Restablecer',
90
93
  support: 'Soporte de suscripciones',
91
94
  wallet: 'Recargar saldo',
@@ -0,0 +1,37 @@
1
+ // The chosen tab of an account page lives in the address as `?tab=`, so a
2
+ // reload, the browser's Back and a copied link open the view the customer
3
+ // chose. The first tab is the default and leaves the address plain.
4
+ type TabQueryValue = string | null | undefined | readonly (string | null)[];
5
+
6
+ // `tab` from the address; an unknown or missing value is the first tab.
7
+ export function tabFromQuery<T extends string>(
8
+ query: Record<string, TabQueryValue>,
9
+ tabs: readonly T[],
10
+ ): T {
11
+ const raw = query.tab;
12
+ const value = Array.isArray(raw) ? raw[0] : raw;
13
+
14
+ return tabs.find((tab) => tab === value) ?? tabs[0]!;
15
+ }
16
+
17
+ // The query with `tab` chosen: other parameters such as `locale` stay.
18
+ export function tabQuery<T extends string>(
19
+ query: Record<string, TabQueryValue>,
20
+ tab: T,
21
+ tabs: readonly T[],
22
+ ) {
23
+ const result: Record<string, string> = {};
24
+
25
+ for (const [key, raw] of Object.entries(query)) {
26
+ const value = Array.isArray(raw) ? raw[0] : raw;
27
+
28
+ if (typeof value === 'string' && key !== 'tab' && key !== 'page') {
29
+ result[key] = value;
30
+ }
31
+ }
32
+ if (tab !== tabs[0]) {
33
+ result.tab = tab;
34
+ }
35
+
36
+ return result;
37
+ }
@@ -0,0 +1,56 @@
1
+ // An unsent support message: its text, the attached files and the defect
2
+ // mark. It is kept in the page's memory while the customer moves around the
3
+ // shop, so leaving Support for another page and coming back does not lose
4
+ // what was written (the message form reads it when it opens).
5
+ //
6
+ // Memory only, on purpose: nothing is written to browser storage, so a
7
+ // reload or a closed tab starts clean and a shared computer keeps no text.
8
+ // On the server the memory belongs to every visitor at once, so there the
9
+ // functions keep nothing. A draft is the customer's own: its key starts
10
+ // with their ID, and another customer signing in on the same tab never
11
+ // sees it.
12
+ export interface TicketDraft {
13
+ text: string;
14
+ files: File[];
15
+ isDefect: boolean;
16
+ }
17
+
18
+ const drafts = new Map<string, TicketDraft>();
19
+ const inBrowser = typeof window !== 'undefined';
20
+
21
+ // `place` names the form: `new` for a common question, `new:item:15` for a
22
+ // conversation about an order item, `ticket:8` for a reply.
23
+ export function ticketDraftKey(customerId: number | undefined, place: string) {
24
+ return customerId ? `${customerId}:${place}` : '';
25
+ }
26
+
27
+ export function emptyTicketDraft(): TicketDraft {
28
+ return { text: '', files: [], isDefect: false };
29
+ }
30
+
31
+ export function isEmptyTicketDraft(draft: TicketDraft) {
32
+ return !draft.text.trim() && !draft.files.length && !draft.isDefect;
33
+ }
34
+
35
+ export function readTicketDraft(key: string): TicketDraft {
36
+ const draft = inBrowser && key ? drafts.get(key) : undefined;
37
+
38
+ return draft ? { ...draft, files: [...draft.files] } : emptyTicketDraft();
39
+ }
40
+
41
+ // An emptied form leaves no draft behind.
42
+ export function keepTicketDraft(key: string, draft: TicketDraft) {
43
+ if (!inBrowser || !key) {
44
+ return;
45
+ }
46
+ if (isEmptyTicketDraft(draft)) {
47
+ drafts.delete(key);
48
+ } else {
49
+ drafts.set(key, { ...draft, files: [...draft.files] });
50
+ }
51
+ }
52
+
53
+ // The message was sent or the customer pressed Cancel.
54
+ export function dropTicketDraft(key: string) {
55
+ drafts.delete(key);
56
+ }
@@ -12,7 +12,7 @@
12
12
  import { useBaskleeSearchScopeNames } from '@/lib/composables/useBaskleeSearchScopeNames.svelte';
13
13
  import { useBaskleeStorefront } from '@/lib/composables/useBaskleeStorefront.svelte';
14
14
  import { directoryLabels } from '@/lib/utils/basklee/directoryLabels';
15
- import { storeAddress, storePhoneLink } from '@/lib/utils/basklee/storeDirectory';
15
+ import { storeAddress, storePhoneLink, storePhoneText } from '@/lib/utils/basklee/storeDirectory';
16
16
  import { browseLabels } from '@/lib/utils/basklee/browseLabels';
17
17
  import { productListLocationFromQuery } from '@/lib/utils/basklee/productListLocation';
18
18
  import {
@@ -201,7 +201,7 @@
201
201
  href={storePhoneLink(names.value.storeDetails.phone_number)}
202
202
  class="w-fit text-inherit no-underline focus-visible:outline"
203
203
  >
204
- {names.value.storeDetails.phone_number}
204
+ {storePhoneText(names.value.storeDetails.phone_number)}
205
205
  </a>
206
206
  {/if}
207
207
  {#if names.value.storeDetails.working_hours}