@snabcentr/client-core 4.21.3 → 4.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,21 +1,21 @@
1
1
  import * as i1 from 'rxjs';
2
- import { of, startWith as startWith$1, Subject, ReplaySubject, partition, combineLatest, map as map$1, debounceTime, switchMap, tap, filter, shareReplay, distinctUntilChanged, BehaviorSubject, materialize, dematerialize, merge, distinctUntilKeyChanged, skip, first, catchError as catchError$1, throwError, expand, takeWhile, toArray, EMPTY, take, defaultIfEmpty, concatMap, finalize, takeUntil, timeout, ignoreElements, interval, share, scan, defer, from, lastValueFrom, TimeoutError } from 'rxjs';
2
+ import { of, Subject, BehaviorSubject, map as map$1, distinctUntilChanged, concatMap, catchError as catchError$1, EMPTY, finalize, defer, AsyncSubject, tap, startWith as startWith$1, ReplaySubject, partition, combineLatest, debounceTime, switchMap, filter, shareReplay, materialize, dematerialize, merge, distinctUntilKeyChanged, skip, first, throwError, expand, takeWhile, toArray, take, defaultIfEmpty, takeUntil, timeout, ignoreElements, interval, pipe, timer, exhaustMap, share, scan, from, lastValueFrom, TimeoutError } from 'rxjs';
3
3
  import { map, startWith, catchError } from 'rxjs/operators';
4
4
  import { parseISO, parse, isValid, format } from 'date-fns';
5
5
  import { isString, constant, isNil, isObject, isDate, isMatch, isArray, omit, get, isNumber, isBoolean } from 'lodash-es';
6
6
  import * as i0 from '@angular/core';
7
- import { InjectionToken, inject, PLATFORM_ID, Inject, Optional, Injectable, EventEmitter, DestroyRef, LOCALE_ID, Pipe, RESPONSE_INIT, provideAppInitializer, assertInInjectionContext, RendererFactory2, makeEnvironmentProviders } from '@angular/core';
8
- import { WA_LOCAL_STORAGE, WA_USER_AGENT, WA_WINDOW } from '@ng-web-apis/common';
7
+ import { Injectable, InjectionToken, inject, PLATFORM_ID, Inject, Optional, EventEmitter, DestroyRef, LOCALE_ID, Pipe, RESPONSE_INIT, provideAppInitializer, assertInInjectionContext, RendererFactory2, makeEnvironmentProviders } from '@angular/core';
8
+ import { WA_LOCAL_STORAGE, WA_USER_AGENT, WA_PAGE_VISIBILITY, WA_WINDOW } from '@ng-web-apis/common';
9
9
  import { filterByKey, toValue, WA_STORAGE_EVENT, WaStorageService } from '@ng-web-apis/storage';
10
10
  import { isPlatformBrowser, isPlatformServer, DOCUMENT, formatDate } from '@angular/common';
11
11
  import * as i1$1 from '@angular/common/http';
12
- import { HttpContextToken, HttpContext, HttpHeaders, HttpClient, HttpParams, HttpErrorResponse, HttpResponse, FetchBackend, HttpXhrBackend, HttpStatusCode, HttpBackend } from '@angular/common/http';
12
+ import { HttpContextToken, HttpContext, HttpHeaders, HttpClient, HttpParams, HttpErrorResponse, HttpResponse, HttpStatusCode, FetchBackend, HttpXhrBackend, HttpBackend } from '@angular/common/http';
13
13
  import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
14
14
  import { tuiRound, tuiIsPresent, TuiDay, TUI_TRUE_HANDLER } from '@taiga-ui/cdk';
15
15
  import { tuiFormatNumber } from '@taiga-ui/core';
16
16
  import { tuiCleanObject } from '@taiga-ui/addon-doc/utils';
17
17
  import * as i2 from '@angular/router';
18
- import { Router, NavigationEnd, ActivatedRoute } from '@angular/router';
18
+ import { Router, NavigationEnd, ActivatedRoute, NavigationError, NavigationCancel, NavigationCancellationCode } from '@angular/router';
19
19
  import { toSnake, objectToSnake, objectToCamel } from 'ts-case-convert';
20
20
  import { Meta, Title } from '@angular/platform-browser';
21
21
 
@@ -248,6 +248,168 @@ class ScPrimaryCatalogableItem extends ScHiddenCatalogableItem {
248
248
  }
249
249
  }
250
250
 
251
+ /**
252
+ * Очередь запросов: каждый следующий запрос начинается только после завершения предыдущего.
253
+ */
254
+ class ScRequestQueue {
255
+ /**
256
+ * Инициализирует экземпляр класса {@link ScRequestQueue}.
257
+ */
258
+ constructor() {
259
+ /**
260
+ * {@link Subject} запросов в порядке постановки в очередь.
261
+ */
262
+ this.requests$ = new Subject();
263
+ /**
264
+ * {@link BehaviorSubject} количества ожидающих и выполняемых запросов.
265
+ */
266
+ this.size$ = new BehaviorSubject(0);
267
+ /**
268
+ * Признаки запросов, поставленных через {@link pushOnce}, которые ждут очереди или выполняются.
269
+ */
270
+ this.pendingTags = new Set();
271
+ /**
272
+ * {@link Observable} признака, что в очереди есть ожидающие или выполняемые запросы.
273
+ */
274
+ this.isBusy$ = this.size$.pipe(map$1((size) => size > 0), distinctUntilChanged());
275
+ this.requests$
276
+ .pipe(concatMap((request$) => request$.pipe(catchError$1(() => EMPTY), finalize(() => {
277
+ this.resize(-1);
278
+ }))))
279
+ .subscribe();
280
+ }
281
+ /**
282
+ * Возвращает {@link Observable}, который при подписке ставит запрос в очередь и выдаёт его результат.
283
+ * Ошибка запроса передаётся подписчику и не останавливает очередь, отписка не отменяет поставленный запрос.
284
+ *
285
+ * @param request$ Запрос.
286
+ */
287
+ enqueue$(request$) {
288
+ return defer(() => {
289
+ const result$ = new AsyncSubject();
290
+ this.push(request$.pipe(tap({
291
+ next: (value) => {
292
+ result$.next(value);
293
+ },
294
+ error: (error) => {
295
+ result$.error(error);
296
+ },
297
+ complete: () => {
298
+ result$.complete();
299
+ },
300
+ })));
301
+ return result$.asObservable();
302
+ });
303
+ }
304
+ /**
305
+ * Ставит запрос в очередь без подписки на его результат.
306
+ *
307
+ * @param request$ Запрос.
308
+ */
309
+ push(request$) {
310
+ this.resize(1);
311
+ this.requests$.next(request$);
312
+ }
313
+ /**
314
+ * Ставит запрос в очередь без подписки на его результат, если запрос с тем же признаком ещё не ждёт очереди и не выполняется.
315
+ *
316
+ * @param tag Признак запроса, например «перезапрос».
317
+ * @param request$ Запрос.
318
+ */
319
+ pushOnce(tag, request$) {
320
+ if (this.pendingTags.has(tag)) {
321
+ return;
322
+ }
323
+ this.pendingTags.add(tag);
324
+ this.push(request$.pipe(finalize(() => {
325
+ this.pendingTags.delete(tag);
326
+ })));
327
+ }
328
+ /**
329
+ * Изменяет количество ожидающих и выполняемых запросов.
330
+ *
331
+ * @param delta Изменение количества.
332
+ */
333
+ resize(delta) {
334
+ this.size$.next(this.size$.value + delta);
335
+ }
336
+ }
337
+
338
+ /**
339
+ * Сервис очередей запросов по ключу, например по номеру черновика. Запросы с одним ключом выполняются по одному и применяются
340
+ * в порядке постановки, запросы с разными ключами друг от друга не зависят. Ключ должен быть уникальным в приложении,
341
+ * поэтому в нём указывается, к чему относится очередь: «order-draft:307». Очереди удаляет владелец ключей методом {@link clear}, например при выходе пользователя.
342
+ */
343
+ class ScRequestQueuesService {
344
+ constructor() {
345
+ /**
346
+ * Очереди запросов по ключу. Очередь создаётся при первом обращении.
347
+ */
348
+ this.queues = new Map();
349
+ }
350
+ /**
351
+ * Возвращает оператор, который выполняет запрос в очереди с указанным ключом: запрос встаёт в очередь при подписке,
352
+ * результат и ошибка передаются подписчику, отписка не отменяет поставленный запрос.
353
+ *
354
+ * @param key Ключ очереди.
355
+ */
356
+ inQueue(key) {
357
+ return (request$) => defer(() => this.getQueue(key).enqueue$(request$));
358
+ }
359
+ /**
360
+ * Ставит запрос в очередь с указанным ключом без подписки на его результат, если запрос с тем же признаком ещё не ждёт очереди и не выполняется.
361
+ *
362
+ * @param key Ключ очереди.
363
+ * @param tag Признак запроса, например «перезапрос».
364
+ * @param request$ Запрос.
365
+ */
366
+ pushOnce(key, tag, request$) {
367
+ this.getQueue(key).pushOnce(tag, request$);
368
+ }
369
+ /**
370
+ * Возвращает {@link Observable} признака, что в очереди с указанным ключом есть ожидающие или выполняемые запросы.
371
+ *
372
+ * @param key Ключ очереди.
373
+ */
374
+ isBusy$(key) {
375
+ return this.getQueue(key).isBusy$;
376
+ }
377
+ /**
378
+ * Удаляет очереди, ключ которых начинается с указанного префикса. Запросы, уже поставленные в удалённые очереди, выполняются до конца,
379
+ * новые запросы с теми же ключами встают в новые очереди.
380
+ *
381
+ * @param prefix Префикс ключа очереди, например «order-draft:».
382
+ */
383
+ clear(prefix) {
384
+ [...this.queues.keys()]
385
+ .filter((key) => key.startsWith(prefix))
386
+ .forEach((key) => {
387
+ this.queues.delete(key);
388
+ });
389
+ }
390
+ /**
391
+ * Возвращает очередь запросов с указанным ключом, создавая её при первом обращении.
392
+ *
393
+ * @param key Ключ очереди.
394
+ */
395
+ getQueue(key) {
396
+ let queue = this.queues.get(key);
397
+ if (!queue) {
398
+ queue = new ScRequestQueue();
399
+ this.queues.set(key, queue);
400
+ }
401
+ return queue;
402
+ }
403
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.16", ngImport: i0, type: ScRequestQueuesService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
404
+ static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.16", ngImport: i0, type: ScRequestQueuesService, providedIn: 'root' }); }
405
+ }
406
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.16", ngImport: i0, type: ScRequestQueuesService, decorators: [{
407
+ type: Injectable,
408
+ args: [{
409
+ providedIn: 'root',
410
+ }]
411
+ }] });
412
+
251
413
  /**
252
414
  * Токен, указывающий ключ токена доступа пользователя к API в {@link Storage}.
253
415
  */
@@ -540,6 +702,13 @@ const SC_IS_HIDDEN_ERROR_ALERT = new HttpContextToken(constant(false));
540
702
  */
541
703
  const SC_IS_HIDDEN_ERROR_ALERT_HTTP_CONTEXT = new HttpContext().set(SC_IS_HIDDEN_ERROR_ALERT, true);
542
704
 
705
+ /**
706
+ * Токен контекста запроса с запасным текстом ошибки. Если текст задан, перехватчик уведомлений приложения показывает ошибку запроса и при ответах,
707
+ * о которых обычно не сообщает (нет ответа сервера, 400, 403, 404, 5xx): текст из ответа, а если его нет, этот текст. Токен скрытия уведомления
708
+ * SC_IS_HIDDEN_ERROR_ALERT главнее.
709
+ */
710
+ const SC_ERROR_ALERT_FALLBACK_MESSAGE = new HttpContextToken(() => null);
711
+
543
712
  /**
544
713
  * Единицы измерения линейной величины по умолчанию.
545
714
  */
@@ -551,6 +720,16 @@ const SC_LINEAR_VALUES_TOKEN = new InjectionToken('SC_LINEAR_VALUES_TOKEN', {
551
720
  factory: () => SC_LINEAR_VALUES,
552
721
  });
553
722
 
723
+ /**
724
+ * Токен внедрения путей страниц, закрытых от индексирования мета-тегом robots.
725
+ *
726
+ * Страница закрыта, если её адрес начинается с одного из путей. Задаётся через {@link provideNoIndexPaths}.
727
+ * Нужен для страниц, которые отрисовываются: страница, первую навигацию на которую отклонил защитник маршрута, закрывается и без списка.
728
+ */
729
+ const SC_NO_INDEX_PATHS = new InjectionToken('SC_NO_INDEX_PATHS', {
730
+ factory: () => [],
731
+ });
732
+
554
733
  /**
555
734
  * Токен внедрения пути до изображения 'Товар не найден'.
556
735
  */
@@ -757,6 +936,24 @@ var ScUserMetrikaGoalsEnum;
757
936
  * В качестве параметра должен быть указан идентификатор КП/черновика (параметр "offer_id").
758
937
  */
759
938
  ScUserMetrikaGoalsEnum["orderDraftDeleted"] = "ORDER_DRAFT_DELETED";
939
+ /**
940
+ * Черновик заказа создан из файла программы «Профстрой».
941
+ *
942
+ * В качестве параметра должен быть указан идентификатор черновика (параметр "offer_id").
943
+ */
944
+ ScUserMetrikaGoalsEnum["orderDraftProfstroyCreated"] = "ORDER_DRAFT_PROFSTROY_CREATED";
945
+ /**
946
+ * Запущена актуализация черновика Профстрой.
947
+ *
948
+ * В качестве параметра должен быть указан идентификатор черновика (параметр "offer_id").
949
+ */
950
+ ScUserMetrikaGoalsEnum["orderDraftProfstroyActualized"] = "ORDER_DRAFT_PROFSTROY_ACTUALIZED";
951
+ /**
952
+ * Запущена пересборка черновика Профстрой из файла.
953
+ *
954
+ * В качестве параметра должен быть указан идентификатор черновика (параметр "offer_id").
955
+ */
956
+ ScUserMetrikaGoalsEnum["orderDraftProfstroyReloaded"] = "ORDER_DRAFT_PROFSTROY_RELOADED";
760
957
  /**
761
958
  * Открыто диалоговое окно/страница конфигуратора товара.
762
959
  *
@@ -1696,6 +1893,46 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.16", ngImpo
1696
1893
  }]
1697
1894
  }] });
1698
1895
 
1896
+ /**
1897
+ * Сервис для получения статей блога.
1898
+ */
1899
+ class ScBlogService {
1900
+ constructor() {
1901
+ /**
1902
+ * HTTP-клиент.
1903
+ */
1904
+ this.http = inject(HttpClient);
1905
+ /**
1906
+ * Список ссылок приложения.
1907
+ */
1908
+ this.urls = inject(SC_URLS);
1909
+ }
1910
+ /**
1911
+ * Возвращает {@link Observable} списка статей блога с пагинацией.
1912
+ *
1913
+ * @param params Параметры пагинации.
1914
+ */
1915
+ getBlogPosts$(params) {
1916
+ return this.http.get(`${this.urls.apiUrl}/blog`, { params: { ...params } });
1917
+ }
1918
+ /**
1919
+ * Возвращает {@link Observable} полных данных о статье блога.
1920
+ *
1921
+ * @param slug Символьное обозначение статьи.
1922
+ */
1923
+ getBlogPost$(slug) {
1924
+ return this.http.get(`${this.urls.apiUrl}/blog/${encodeURIComponent(slug)}`);
1925
+ }
1926
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.16", ngImport: i0, type: ScBlogService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
1927
+ static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.16", ngImport: i0, type: ScBlogService, providedIn: 'root' }); }
1928
+ }
1929
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.16", ngImport: i0, type: ScBlogService, decorators: [{
1930
+ type: Injectable,
1931
+ args: [{
1932
+ providedIn: 'root',
1933
+ }]
1934
+ }] });
1935
+
1699
1936
  const EMPTY_CART = { items: [], result_sum: { rub: 0 } };
1700
1937
 
1701
1938
  /**
@@ -1725,7 +1962,7 @@ class ScCatalogItem extends ScCatalogableItem {
1725
1962
  super(data);
1726
1963
  this.properties = data?.properties;
1727
1964
  // eslint-disable-next-line @typescript-eslint/no-explicit-any,@typescript-eslint/no-unsafe-assignment,no-underscore-dangle,@typescript-eslint/no-unsafe-member-access
1728
- this.seo = data._Seo ?? data?.seo;
1965
+ this.seo = data?._Seo ?? data?.seo;
1729
1966
  this.image = data?.image;
1730
1967
  }
1731
1968
  }
@@ -1914,6 +2151,18 @@ class ScCategory extends ScCatalogItem {
1914
2151
  * Модель данных товара/услуги.
1915
2152
  */
1916
2153
  class ScProduct extends ScCatalogItem {
2154
+ /**
2155
+ * Возвращает товар, не найденный в каталоге, с известными названием и артикулом поставщика.
2156
+ *
2157
+ * @param name Название товара.
2158
+ * @param supplierSku Артикул поставщика.
2159
+ */
2160
+ static createNotFound(name, supplierSku) {
2161
+ const product = new ScProduct(null);
2162
+ product.name = name ?? product.name;
2163
+ product.supplierSku = supplierSku;
2164
+ return product;
2165
+ }
1917
2166
  /**
1918
2167
  * Инициализирует экземпляр класса {@link ScProduct}.
1919
2168
  *
@@ -2067,10 +2316,56 @@ class ScProduct extends ScCatalogItem {
2067
2316
  }
2068
2317
  }
2069
2318
 
2319
+ /**
2320
+ * Класс-помощник для работы со значениями единиц измерения товара.
2321
+ */
2322
+ class ScUnitsHelper {
2323
+ /**
2324
+ * Возвращает признак, что указанный товар имеет линейную единицу измерения. Для товара, не найденного в каталоге, возвращает `false`.
2325
+ *
2326
+ * @param product Данные о товаре для которого нужно проверить линейность его единицы измерения.
2327
+ */
2328
+ static productIsMeasurable(product) {
2329
+ return !product.isNull && (product.unit.isLinear || product.unit.isSquare);
2330
+ }
2331
+ /**
2332
+ * Возвращает кратность количества для указанного товара.
2333
+ *
2334
+ * Кратность равна {@link ScProduct.minCount} и не зависит от {@link ScIProperties.ignoreMinCountCheck}:
2335
+ * этот признак только снимает валидацию кратности/минимума при ручном вводе, но начальное количество
2336
+ * и шаг кнопок +/- остаются кратны minCount.
2337
+ *
2338
+ * @param product Данные о товаре для которого необходимо вернуть кратность количества.
2339
+ */
2340
+ static getProductMultiplicity(product) {
2341
+ return product.minCount && !ScUnitsHelper.productIsMeasurable(product) ? product.minCount : 1;
2342
+ }
2343
+ /**
2344
+ * Возвращает кратность длины для указанного товара.
2345
+ *
2346
+ * @param product Данные о товаре для которого необходимо вернуть кратность длины.
2347
+ */
2348
+ static getProductLengthMultiplicity(product) {
2349
+ if (product.properties?.lengthStep) {
2350
+ return product.properties.lengthStep;
2351
+ }
2352
+ return !product.properties?.ignoreMinCountCheck && product.minCount ? product.minCount : 0.01;
2353
+ }
2354
+ }
2355
+
2356
+ /* eslint-disable class-methods-use-this,@typescript-eslint/class-literal-property-style */
2070
2357
  /**
2071
2358
  * Данные о единичной позиции товара/услуги в заказе (корзине / черновике).
2072
2359
  */
2073
2360
  class ScOrderItem {
2361
+ /**
2362
+ * Возвращает сумму стоимости позиций в рублях, округлённую до копеек.
2363
+ *
2364
+ * @param items Позиции.
2365
+ */
2366
+ static getCostSum(items) {
2367
+ return ScNumberHelper.roundMoney(items.reduce((sum, item) => sum + item.costRub, 0));
2368
+ }
2074
2369
  /**
2075
2370
  * Инициализирует экземпляр класса {@link ScOrderItem}.
2076
2371
  *
@@ -2092,6 +2387,40 @@ class ScOrderItem {
2092
2387
  this.specificationImgUrl = data.specificationImgUrl;
2093
2388
  this.configurator = data.configurator;
2094
2389
  this.configuratorParams = data.configuratorParams;
2390
+ this.ord = data.ord;
2391
+ }
2392
+ /**
2393
+ * Признак, что позиция может попасть в заказ: товар есть в каталоге и предоставляется.
2394
+ */
2395
+ get isOrderable() {
2396
+ return !this.product.isNull && !this.product.isHidden;
2397
+ }
2398
+ /**
2399
+ * Признак неактивной позиции, у которой нельзя менять количество и параметры: товар не найден в каталоге или больше не предоставляется.
2400
+ */
2401
+ get isInactive() {
2402
+ return this.product.isNull || this.product.isHidden;
2403
+ }
2404
+ /**
2405
+ * Признак, что причину, по которой позиция не попадёт в заказ, нужно показывать нейтрально, а не как предупреждение.
2406
+ */
2407
+ get isUnavailableReasonNeutral() {
2408
+ return false;
2409
+ }
2410
+ /**
2411
+ * Шаг изменения количества позиции.
2412
+ */
2413
+ get quantityStep() {
2414
+ return ScUnitsHelper.getProductMultiplicity(this.product);
2415
+ }
2416
+ /**
2417
+ * Возвращает причину, по которой позиция не может попасть в заказ, или пустую строку.
2418
+ */
2419
+ getUnavailableReason() {
2420
+ if (this.product.isNull) {
2421
+ return 'Товар не найден в каталоге';
2422
+ }
2423
+ return this.product.isHidden ? 'Товар больше не предоставляется' : '';
2095
2424
  }
2096
2425
  /**
2097
2426
  * @inheritDoc
@@ -4758,6 +5087,14 @@ class ScImageHelper {
4758
5087
  }
4759
5088
  return undefined;
4760
5089
  }
5090
+ /**
5091
+ * Возвращает полный URI изображения обложки статьи блога или `undefined`, если обложки нет или она видео.
5092
+ *
5093
+ * @param cover Обложка статьи блога.
5094
+ */
5095
+ getBlogCoverImage(cover) {
5096
+ return cover?.mediaType === 'image' ? this.mediaImageTransformerPipe.transform(cover.url) : undefined;
5097
+ }
4761
5098
  /**
4762
5099
  * Возвращает признак того, что файл является изображением.
4763
5100
  *
@@ -4777,43 +5114,6 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.16", ngImpo
4777
5114
  }]
4778
5115
  }] });
4779
5116
 
4780
- /**
4781
- * Класс-помощник для работы со значениями единиц измерения товара.
4782
- */
4783
- class ScUnitsHelper {
4784
- /**
4785
- * Возвращает признак, что указанный товар имеет линейную единицу измерения.
4786
- *
4787
- * @param product Данные о товаре для которого нужно проверить линейность его единицы измерения.
4788
- */
4789
- static productIsMeasurable(product) {
4790
- return product.unit.isLinear || product.unit.isSquare;
4791
- }
4792
- /**
4793
- * Возвращает кратность количества для указанного товара.
4794
- *
4795
- * Кратность равна {@link ScProduct.minCount} и не зависит от {@link ScIProperties.ignoreMinCountCheck}:
4796
- * этот признак только снимает валидацию кратности/минимума при ручном вводе, но начальное количество
4797
- * и шаг кнопок +/- остаются кратны minCount.
4798
- *
4799
- * @param product Данные о товаре для которого необходимо вернуть кратность количества.
4800
- */
4801
- static getProductMultiplicity(product) {
4802
- return product.minCount && !ScUnitsHelper.productIsMeasurable(product) ? product.minCount : 1;
4803
- }
4804
- /**
4805
- * Возвращает кратность длины для указанного товара.
4806
- *
4807
- * @param product Данные о товаре для которого необходимо вернуть кратность длины.
4808
- */
4809
- static getProductLengthMultiplicity(product) {
4810
- if (product.properties?.lengthStep) {
4811
- return product.properties.lengthStep;
4812
- }
4813
- return !product.properties?.ignoreMinCountCheck && product.minCount ? product.minCount : 0.01;
4814
- }
4815
- }
4816
-
4817
5117
  /**
4818
5118
  * Возвращает текущий маршрут.
4819
5119
  * Функция проходит по дереву маршрутов начиная с переданного route и возвращает самый вложенный активный маршрут.
@@ -4828,6 +5128,25 @@ const scGetCurrentRoute = (route) => {
4828
5128
  return currentRoute;
4829
5129
  };
4830
5130
 
5131
+ /**
5132
+ * Класс-помощник для работы с датами.
5133
+ */
5134
+ class ScDateHelper {
5135
+ /**
5136
+ * Возвращает дату, полученную из строки в указанном формате, или `undefined`, если значение отсутствует или не является датой.
5137
+ *
5138
+ * @param value Дата строкой.
5139
+ * @param format Формат даты строкой (например, {@link ScIDateFormat.api}).
5140
+ */
5141
+ static parse(value, format) {
5142
+ if (!value) {
5143
+ return undefined;
5144
+ }
5145
+ const date = parse(value, format, new Date());
5146
+ return isValid(date) ? date : undefined;
5147
+ }
5148
+ }
5149
+
4831
5150
  /**
4832
5151
  * Токен состояния запроса данных о категории (загрузка / успех / ошибка).
4833
5152
  */
@@ -6260,8 +6579,9 @@ function formatDatesInErrors(error, dateFormats) {
6260
6579
  function ScDateFormatInterceptor(request, next) {
6261
6580
  const dateFormats = inject(SC_DATE_FORMAT);
6262
6581
  return next(request).pipe(catchError$1((error) => {
6263
- const errorData = error.error;
6264
- formatDatesInErrors(errorData, dateFormats);
6582
+ if (isObject(error.error)) {
6583
+ formatDatesInErrors(error.error, dateFormats);
6584
+ }
6265
6585
  return throwError(() => error);
6266
6586
  }));
6267
6587
  }
@@ -6961,43 +7281,236 @@ class ScOrderBase {
6961
7281
  }
6962
7282
 
6963
7283
  /**
6964
- * Данные о коммерческом предложении/черновике заказа.
7284
+ * Перечисление статусов актуализации черновика Профстрой.
6965
7285
  */
6966
- class ScOrderDraft {
7286
+ // eslint-disable-next-line no-shadow
7287
+ var ScOrderDraftActualizationStatus;
7288
+ (function (ScOrderDraftActualizationStatus) {
6967
7289
  /**
6968
- * Инициализирует экземпляр класса {@link ScOrderDraft}.
6969
- *
6970
- * @param data Данные для первоначальной инициализации.
7290
+ * Выполняется обработка файла или актуализация позиций.
6971
7291
  */
6972
- constructor(data) {
6973
- /**
6974
- * Дата последнего обновления данных.
6975
- */
6976
- this.lastUpdateDate = new Date();
6977
- this.id = data.id;
6978
- this.name = data.name;
6979
- this.type = data.type;
6980
- this.createdAt = data.createdAt;
6981
- this.sum = data.sum;
6982
- this.products = data.products.map((item) => new ScOrderItem(item));
6983
- }
7292
+ ScOrderDraftActualizationStatus["processing"] = "processing";
6984
7293
  /**
6985
- * @inheritDoc
7294
+ * Последняя актуализация завершена успешно.
6986
7295
  */
6987
- getSumStr() {
6988
- return this.sum > 0 ? `${ScNumberHelper.formatMoney(this.sum)} ₽` : '-';
6989
- }
7296
+ ScOrderDraftActualizationStatus["completed"] = "completed";
6990
7297
  /**
6991
- * @inheritDoc
7298
+ * Обработка завершилась с ошибкой.
6992
7299
  */
6993
- getSumMessage() {
6994
- return this.sum === 0 ? 'Цена требует уточнения' : '';
6995
- }
7300
+ ScOrderDraftActualizationStatus["error"] = "error";
6996
7301
  /**
6997
- * @inheritDoc
7302
+ * Состав черновика изменён после последней успешной актуализации.
6998
7303
  */
6999
- cachedDataIsActual(lifeTime) {
7000
- return this.lastUpdateDate.getTime() >= Date.now() - lifeTime;
7304
+ ScOrderDraftActualizationStatus["needsActualization"] = "needs_actualization";
7305
+ })(ScOrderDraftActualizationStatus || (ScOrderDraftActualizationStatus = {}));
7306
+
7307
+ /**
7308
+ * Данные об актуализации черновика Профстрой.
7309
+ */
7310
+ class ScOrderDraftActualization {
7311
+ /**
7312
+ * Инициализирует экземпляр класса {@link ScOrderDraftActualization}.
7313
+ *
7314
+ * @param data Данные от API.
7315
+ * @param apiDateFormat Формат дат в данных API.
7316
+ */
7317
+ constructor(data, apiDateFormat) {
7318
+ this.status = data.status;
7319
+ this.actualizedAt = ScDateHelper.parse(data.actualizedAt, apiDateFormat);
7320
+ this.expiresAt = ScDateHelper.parse(data.expiresAt, apiDateFormat);
7321
+ this.error = data.status === ScOrderDraftActualizationStatus.error ? (data.error ?? undefined) : undefined;
7322
+ }
7323
+ /**
7324
+ * Признак, что выполняется обработка.
7325
+ */
7326
+ get isProcessing() {
7327
+ return this.status === ScOrderDraftActualizationStatus.processing;
7328
+ }
7329
+ /**
7330
+ * Возвращает признак, что данные актуализации устарели на указанный момент: актуализация не завершена успешно или истёк срок её действия.
7331
+ * Момент, равный сроку действия, ещё допустим. Если срок не известен, данные считаются актуальными.
7332
+ *
7333
+ * @param now Момент проверки.
7334
+ */
7335
+ isOutdatedAt(now) {
7336
+ if (this.status !== ScOrderDraftActualizationStatus.completed || !this.actualizedAt) {
7337
+ return true;
7338
+ }
7339
+ return this.expiresAt !== undefined && this.expiresAt.getTime() < now.getTime();
7340
+ }
7341
+ /**
7342
+ * Возвращает признак, что на указанный момент из черновика можно оформить заказ.
7343
+ *
7344
+ * @param now Момент проверки.
7345
+ */
7346
+ isOrderAllowedAt(now) {
7347
+ return this.status === ScOrderDraftActualizationStatus.completed && !this.isOutdatedAt(now);
7348
+ }
7349
+ /**
7350
+ * Возвращает признак, что данные актуализации совпадают с другими: статус, даты актуализации и срока действия, текст ошибки.
7351
+ *
7352
+ * @param other Данные актуализации для сравнения.
7353
+ */
7354
+ isSameAs(other) {
7355
+ return (this.status === other?.status &&
7356
+ this.actualizedAt?.getTime() === other.actualizedAt?.getTime() &&
7357
+ this.expiresAt?.getTime() === other.expiresAt?.getTime() &&
7358
+ this.error === other.error);
7359
+ }
7360
+ }
7361
+
7362
+ /**
7363
+ * Данные о кратком коммерческом предложении/черновике заказа.
7364
+ */
7365
+ class ScOrderDraftShort extends ScOrderBase {
7366
+ /**
7367
+ * Инициализирует экземпляр класса {@link ScOrderDraftShort}.
7368
+ *
7369
+ * @param data Данные для первоначальной инициализации.
7370
+ * @param apiDateFormat Формат дат в данных API.
7371
+ */
7372
+ constructor(data, apiDateFormat) {
7373
+ super(data);
7374
+ this.name = data.name;
7375
+ this.type = data.type;
7376
+ this.isProfstroy = data.isProfstroy === true;
7377
+ this.actualization = this.isProfstroy && data.actualization ? new ScOrderDraftActualization(data.actualization, apiDateFormat) : undefined;
7378
+ this.file = data.file ?? undefined;
7379
+ }
7380
+ }
7381
+
7382
+ /**
7383
+ * Данные о позиции черновика Профстрой.
7384
+ */
7385
+ class ScProfstroyOrderItem extends ScOrderItem {
7386
+ /**
7387
+ * Шаг количества позиции, для которой не найден товар каталога и кратность не известна.
7388
+ */
7389
+ static { this.stubQuantityStep = 0.001; }
7390
+ /**
7391
+ * Возвращает признак, что вместо товара каталога пришла заглушка.
7392
+ *
7393
+ * @param product Данные о товаре.
7394
+ */
7395
+ static isStub(product) {
7396
+ return !product || !('id' in product);
7397
+ }
7398
+ /**
7399
+ * Инициализирует экземпляр класса {@link ScProfstroyOrderItem}.
7400
+ *
7401
+ * @param data Данные от API.
7402
+ */
7403
+ constructor(data) {
7404
+ const isProductStub = ScProfstroyOrderItem.isStub(data.product);
7405
+ // eslint-disable-next-line @typescript-eslint/no-misused-spread
7406
+ super({ ...data, product: isProductStub ? null : data.product });
7407
+ this.groupName = data.groupName?.trim() ? data.groupName.trim() : undefined;
7408
+ this.isIgnored = data.isIgnored ?? false;
7409
+ this.lineError = data.lineError?.trim() ? data.lineError.trim() : undefined;
7410
+ if (isProductStub) {
7411
+ const supplierSku = data.supplierSku ?? data.product?.supplierSku ?? undefined;
7412
+ this.product = ScProduct.createNotFound(data.product?.name, supplierSku);
7413
+ }
7414
+ }
7415
+ /**
7416
+ * Признак нейтральной причины: позиции из группы, которая не участвует в заказе, показываются серым, как у сотрудников.
7417
+ */
7418
+ get isUnavailableReasonNeutral() {
7419
+ return this.isIgnored;
7420
+ }
7421
+ /**
7422
+ * @inheritDoc
7423
+ */
7424
+ get isOrderable() {
7425
+ return !this.isIgnored && !this.lineError && super.isOrderable;
7426
+ }
7427
+ /**
7428
+ * Признак неактивной позиции: группа не участвует в заказе или товар не найден в каталоге. Позиция с ошибкой строки остаётся активной.
7429
+ */
7430
+ get isInactive() {
7431
+ return this.isIgnored || super.isInactive;
7432
+ }
7433
+ /**
7434
+ * @inheritDoc
7435
+ */
7436
+ get quantityStep() {
7437
+ return this.product.isNull ? ScProfstroyOrderItem.stubQuantityStep : super.quantityStep;
7438
+ }
7439
+ /**
7440
+ * @inheritDoc
7441
+ */
7442
+ getUnavailableReason() {
7443
+ if (this.isIgnored) {
7444
+ return 'Группа не участвует в заказе';
7445
+ }
7446
+ if (this.lineError) {
7447
+ return this.lineError;
7448
+ }
7449
+ return super.getUnavailableReason();
7450
+ }
7451
+ }
7452
+
7453
+ /**
7454
+ * Данные о коммерческом предложении/черновике заказа.
7455
+ */
7456
+ class ScOrderDraft extends ScOrderDraftShort {
7457
+ /**
7458
+ * Инициализирует экземпляр класса {@link ScOrderDraft}.
7459
+ *
7460
+ * @param data Данные для первоначальной инициализации.
7461
+ * @param apiDateFormat Формат дат в данных API.
7462
+ */
7463
+ constructor(data, apiDateFormat) {
7464
+ super(data, apiDateFormat);
7465
+ /**
7466
+ * Дата последнего обновления данных.
7467
+ */
7468
+ this.lastUpdateDate = new Date();
7469
+ this.products = data.products.map((item) => (this.isProfstroy ? new ScProfstroyOrderItem(item) : new ScOrderItem(item)));
7470
+ }
7471
+ /**
7472
+ * Возвращает причину, по которой из черновика нельзя оформить заказ на указанный момент, или пустую строку.
7473
+ * У обычного черновика причина есть, только если переданы выбранные позиции и ни одной из них нет в черновике.
7474
+ *
7475
+ * @param now Момент проверки.
7476
+ * @param itemsIds Идентификаторы выбранных для заказа позиций. Если не указаны, выбор позиций не проверяется у обычного черновика, а у черновика Профстрой проверяются все позиции.
7477
+ */
7478
+ getOrderBlockReason(now, itemsIds) {
7479
+ if (!this.isProfstroy) {
7480
+ return itemsIds && this.getOrderItems(itemsIds).length === 0 ? 'Выбранных позиций нет в черновике.' : '';
7481
+ }
7482
+ if (!this.actualization?.isOrderAllowedAt(now)) {
7483
+ return 'Оформление доступно после успешной актуализации.';
7484
+ }
7485
+ if (!this.products.some((item) => item.isOrderable)) {
7486
+ return 'В заявке нет позиций, которые могут попасть в заказ.';
7487
+ }
7488
+ return itemsIds && this.getOrderItems(itemsIds).length === 0 ? 'Выбранные позиции не могут попасть в заказ.' : '';
7489
+ }
7490
+ /**
7491
+ * Возвращает выбранные позиции, которые попадут в заказ. Из черновика Профстрой в заказ попадают только позиции, которые могут в него попасть.
7492
+ *
7493
+ * @param itemsIds Идентификаторы выбранных позиций.
7494
+ */
7495
+ getOrderItems(itemsIds) {
7496
+ return this.products.filter((item) => itemsIds.includes(item.id) && (!this.isProfstroy || item.isOrderable));
7497
+ }
7498
+ /**
7499
+ * Возвращает копию черновика с указанными позициями и суммой по ним. Исходный черновик не меняется.
7500
+ *
7501
+ * @param products Позиции копии.
7502
+ */
7503
+ withProducts(products) {
7504
+ const copy = Object.assign(Object.create(ScOrderDraft.prototype), this);
7505
+ copy.products = products;
7506
+ copy.sum = ScOrderItem.getCostSum(products);
7507
+ return copy;
7508
+ }
7509
+ /**
7510
+ * @inheritDoc
7511
+ */
7512
+ cachedDataIsActual(lifeTime) {
7513
+ return this.lastUpdateDate.getTime() >= Date.now() - lifeTime;
7001
7514
  }
7002
7515
  /**
7003
7516
  * @inheritDoc
@@ -7019,18 +7532,54 @@ class ScOrderDraft {
7019
7532
  }
7020
7533
 
7021
7534
  /**
7022
- * Данные о кратком коммерческом предложении/черновике заказа.
7535
+ * Группа позиций заказа с итогами по позициям, которые попадут в заказ.
7023
7536
  */
7024
- class ScOrderDraftShort extends ScOrderBase {
7537
+ class ScOrderItemsGroup {
7025
7538
  /**
7026
- * Инициализирует экземпляр класса {@link ScOrderDraftShort}.
7539
+ * Название группы для позиций без группы.
7540
+ */
7541
+ static { this.ungroupedName = 'Без группы'; }
7542
+ /**
7543
+ * Возвращает название группы позиции: её группу, например группу из файла заявки Профстрой, иначе «Без группы».
7027
7544
  *
7028
- * @param data Данные для первоначальной инициализации.
7545
+ * @param item Позиция заказа.
7029
7546
  */
7030
- constructor(data) {
7031
- super(data);
7032
- this.name = data.name;
7033
- this.type = data.type;
7547
+ static getTitle(item) {
7548
+ return item.groupName ?? ScOrderItemsGroup.ungroupedName;
7549
+ }
7550
+ /**
7551
+ * Возвращает позиции, разбитые на группы по группе позиции (без группы в «Без группы»). Позиции идут по порядковому номеру (без номера в конце), группы в порядке первого появления.
7552
+ *
7553
+ * @param items Позиции заказа.
7554
+ */
7555
+ static fromItems(items) {
7556
+ const groups = new Map();
7557
+ [...items]
7558
+ .sort((first, second) => (first.ord ?? Number.MAX_SAFE_INTEGER) - (second.ord ?? Number.MAX_SAFE_INTEGER))
7559
+ .forEach((item) => {
7560
+ const name = ScOrderItemsGroup.getTitle(item);
7561
+ const groupItems = groups.get(name);
7562
+ if (groupItems) {
7563
+ groupItems.push(item);
7564
+ }
7565
+ else {
7566
+ groups.set(name, [item]);
7567
+ }
7568
+ });
7569
+ return [...groups].map(([name, groupItems]) => new ScOrderItemsGroup(name, groupItems));
7570
+ }
7571
+ /**
7572
+ * Инициализирует экземпляр класса {@link ScOrderItemsGroup} и считает итоги по позициям, которые попадут в заказ.
7573
+ *
7574
+ * @param name Название группы.
7575
+ * @param items Позиции группы.
7576
+ */
7577
+ constructor(name, items) {
7578
+ const orderableItems = items.filter((item) => item.isOrderable);
7579
+ this.name = name;
7580
+ this.items = items;
7581
+ this.orderableCount = orderableItems.length;
7582
+ this.orderableSum = ScOrderItem.getCostSum(orderableItems);
7034
7583
  }
7035
7584
  }
7036
7585
 
@@ -7051,6 +7600,7 @@ class ScOrderShort extends ScOrderBase {
7051
7600
  this.payment = data.payment;
7052
7601
  this.numberDoc = data.numberDoc;
7053
7602
  this.barcode = data.barcode;
7603
+ this.isProfstroy = data.isProfstroy === true;
7054
7604
  }
7055
7605
  /**
7056
7606
  * @inheritDoc
@@ -7061,6 +7611,7 @@ class ScOrderShort extends ScOrderBase {
7061
7611
  this.payment = order.payment;
7062
7612
  this.sum = order.sum;
7063
7613
  this.delivery = order.delivery;
7614
+ this.isProfstroy = order.isProfstroy;
7064
7615
  }
7065
7616
  }
7066
7617
 
@@ -7230,6 +7781,30 @@ class ScOrder extends ScOrderShort {
7230
7781
  * Данные о сервисе коммерческих предложений и черновиков заказов.
7231
7782
  */
7232
7783
  class ScOrderDraftsService {
7784
+ /**
7785
+ * Префикс ключей очередей запросов черновиков.
7786
+ */
7787
+ static { this.queueKeyPrefix = 'order-draft:'; }
7788
+ /**
7789
+ * Коды отказа, после которых черновик перезапрашивается.
7790
+ */
7791
+ static { this.rejectionStatuses = [HttpStatusCode.Forbidden, HttpStatusCode.Conflict]; }
7792
+ /**
7793
+ * Возвращает ключ очереди запросов черновика.
7794
+ *
7795
+ * @param draftId Идентификатор черновика.
7796
+ */
7797
+ static getQueueKey(draftId) {
7798
+ return `${ScOrderDraftsService.queueKeyPrefix}${draftId}`;
7799
+ }
7800
+ /**
7801
+ * Возвращает контекст изменяющего запроса черновика с запасным текстом ошибки: перехватчик приложения покажет ошибку запроса и там, где обычно молчит.
7802
+ *
7803
+ * @param message Запасной текст ошибки.
7804
+ */
7805
+ static getErrorContext(message) {
7806
+ return new HttpContext().set(SC_ERROR_ALERT_FALLBACK_MESSAGE, message);
7807
+ }
7233
7808
  /**
7234
7809
  * Инициализирует экземпляр класса {@link ScOrderDraftsService}.
7235
7810
  */
@@ -7258,12 +7833,30 @@ class ScOrderDraftsService {
7258
7833
  * Сервис для сбора метрик о действиях пользователей.
7259
7834
  */
7260
7835
  this.userMetrikaService = inject(ScUserMetrikaService);
7836
+ /**
7837
+ * Форматы дат.
7838
+ */
7839
+ this.dateFormats = inject(SC_DATE_FORMAT);
7840
+ /**
7841
+ * Сервис конвертации данных.
7842
+ */
7843
+ this.convertersService = inject(ScConvertersService);
7844
+ /**
7845
+ * {@link Observable} признака, что вкладка браузера видна.
7846
+ */
7847
+ this.pageVisibility$ = inject(WA_PAGE_VISIBILITY);
7261
7848
  /**
7262
7849
  * Коллекция пар ключ-значение для кэшированных коммерческих предложений/черновиков пользователя.
7263
7850
  */
7264
7851
  this.offerMap = new Map();
7852
+ /**
7853
+ * Сервис очередей запросов. Запросы, которые меняют или перечитывают черновик, идут в очереди этого черновика: ответ каждого такого запроса
7854
+ * содержит черновик целиком, поэтому запросы выполняются по одному и применяются в порядке отправки.
7855
+ */
7856
+ this.requestQueues = inject(ScRequestQueuesService);
7265
7857
  this.user$.pipe(filter((user) => user.isGuest)).subscribe(() => {
7266
7858
  this.offerMap.clear();
7859
+ this.requestQueues.clear(ScOrderDraftsService.queueKeyPrefix);
7267
7860
  });
7268
7861
  }
7269
7862
  /**
@@ -7272,24 +7865,103 @@ class ScOrderDraftsService {
7272
7865
  * @param params Параметры запроса получения списка.
7273
7866
  */
7274
7867
  getList$(params) {
7275
- return this.http.get(`${this.urls.apiUrl}/orders/offers`, { params: params }).pipe(map$1((offersPaginateDTO) => {
7276
- offersPaginateDTO.data = offersPaginateDTO.data.map((item) => new ScOrderDraftShort(item));
7277
- return offersPaginateDTO;
7868
+ return this.requestList$(params);
7869
+ }
7870
+ /**
7871
+ * Возвращает краткие данные черновиков с указанными номерами. Используется для лёгкого опроса состояния актуализации без загрузки позиций,
7872
+ * поэтому об ошибках запроса уведомление не показывается.
7873
+ *
7874
+ * @param ids Номера черновиков.
7875
+ */
7876
+ getShortList$(ids) {
7877
+ if (ids.length === 0) {
7878
+ return of([]);
7879
+ }
7880
+ const params = { perPage: ids.length, filters: { number: { in: ids } } };
7881
+ return this.requestList$(this.convertersService.toHttpParams(params, { nonNullable: true }), SC_IS_HIDDEN_ERROR_ALERT_HTTP_CONTEXT).pipe(map$1((response) => response.data));
7882
+ }
7883
+ /**
7884
+ * Периодически запрашивает краткие данные черновиков с указанными номерами, пока есть подписка.
7885
+ * Пока вкладка браузера скрыта, запросы не выполняются, после возврата на вкладку запрос выполняется сразу; новый запрос не начинается до завершения предыдущего.
7886
+ *
7887
+ * @param ids Номера черновиков.
7888
+ */
7889
+ watchShortList$(ids) {
7890
+ return this.poll$(this.updateInterval.orderDraftStatus, () => this.getShortList$(ids));
7891
+ }
7892
+ /**
7893
+ * Периодически перезапрашивает страницу списка черновиков в фоне, пока есть подписка. Условия запросов как у {@link watchShortList$}, об ошибках уведомление не показывается.
7894
+ *
7895
+ * @param params Параметры запроса получения списка.
7896
+ */
7897
+ watchList$(params) {
7898
+ return this.poll$(this.updateInterval.orderDraftsList, () => this.requestList$(params, SC_IS_HIDDEN_ERROR_ALERT_HTTP_CONTEXT));
7899
+ }
7900
+ /**
7901
+ * Возвращает {@link Observable} признака, что для черновика выполняются или ждут очереди запросы изменения или перечитывания.
7902
+ *
7903
+ * @param offerId Идентификатор черновика.
7904
+ */
7905
+ isBusy$(offerId) {
7906
+ return this.requestQueues.isBusy$(ScOrderDraftsService.getQueueKey(offerId));
7907
+ }
7908
+ /**
7909
+ * Создаёт черновик заказа из файла программы «Профстрой» и запускает его обработку.
7910
+ *
7911
+ * @param data Данные для создания.
7912
+ */
7913
+ createProfstroy$(data) {
7914
+ return this.http.post(`${this.urls.apiUrl}/orders/offers/profstroy`, data, { context: SC_IS_HIDDEN_ERROR_ALERT_HTTP_CONTEXT }).pipe(map$1((offerDTO) => new ScOrderDraft(offerDTO, this.dateFormats.api)), tap((offer) => {
7915
+ this.userMetrikaService.emitUserMetrikaEvent({
7916
+ target: ScUserMetrikaGoalsEnum.orderDraftProfstroyCreated,
7917
+ params: { offer_id: offer.id },
7918
+ });
7919
+ this.cacheCreated(offer);
7278
7920
  }));
7279
7921
  }
7922
+ /**
7923
+ * Запускает актуализацию черновика Профстрой по текущему составу без повторного разбора файла.
7924
+ *
7925
+ * @param offerId Идентификатор черновика.
7926
+ */
7927
+ actualizeProfstroy$(offerId) {
7928
+ return this.http
7929
+ .post(`${this.urls.apiUrl}/orders/offers/${offerId}/profstroy/actualize`, {}, { context: ScOrderDraftsService.getErrorContext('Не удалось запустить актуализацию заявки.') })
7930
+ .pipe(tap(() => {
7931
+ this.userMetrikaService.emitUserMetrikaEvent({
7932
+ target: ScUserMetrikaGoalsEnum.orderDraftProfstroyActualized,
7933
+ params: { offer_id: offerId },
7934
+ });
7935
+ }), this.updatesDraft(offerId));
7936
+ }
7937
+ /**
7938
+ * Запускает пересборку черновика Профстрой из ранее загруженного файла.
7939
+ *
7940
+ * @param offerId Идентификатор черновика.
7941
+ */
7942
+ reloadProfstroy$(offerId) {
7943
+ return this.http
7944
+ .post(`${this.urls.apiUrl}/orders/offers/${offerId}/profstroy/reload`, {}, { context: ScOrderDraftsService.getErrorContext('Не удалось собрать заявку заново.') })
7945
+ .pipe(tap(() => {
7946
+ this.userMetrikaService.emitUserMetrikaEvent({
7947
+ target: ScUserMetrikaGoalsEnum.orderDraftProfstroyReloaded,
7948
+ params: { offer_id: offerId },
7949
+ });
7950
+ }), this.updatesDraft(offerId));
7951
+ }
7280
7952
  /**
7281
7953
  * Создаёт новое коммерческое предложение/черновик заказа.
7282
7954
  *
7283
7955
  * @param data Данные для создания.
7284
7956
  */
7285
7957
  create$(data) {
7286
- return this.http.post(`${this.urls.apiUrl}/orders/offers`, data).pipe(map$1((offerDTO) => new ScOrderDraft(offerDTO)), tap((offer) => {
7958
+ return this.http.post(`${this.urls.apiUrl}/orders/offers`, data).pipe(map$1((offerDTO) => new ScOrderDraft(offerDTO, this.dateFormats.api)), tap((offer) => {
7287
7959
  this.userMetrikaService.emitUserMetrikaEvent({
7288
7960
  target: ScUserMetrikaGoalsEnum.orderDraftCreated,
7289
7961
  params: { offer_id: offer.id },
7290
7962
  });
7291
7963
  this.cartService.updateCart();
7292
- this.offerMap.set(offer.id, new ScCachedItem(this.updateInterval.orderData, of(offer), loadingPlaceholder));
7964
+ this.cacheCreated(offer);
7293
7965
  }));
7294
7966
  }
7295
7967
  /**
@@ -7301,16 +7973,25 @@ class ScOrderDraftsService {
7301
7973
  get$(draftId, cacheable = true) {
7302
7974
  let cachedItem = this.offerMap.get(draftId);
7303
7975
  if (!cachedItem) {
7304
- cachedItem = new ScCachedItem(this.updateInterval.orderData, this.http.get(`${this.urls.apiUrl}/orders/offers/${draftId}`).pipe(map$1((data) => new ScOrderDraft(data))), loadingPlaceholder);
7976
+ cachedItem = this.createCachedDraft(draftId);
7305
7977
  if (cacheable) {
7306
7978
  this.offerMap.set(draftId, cachedItem);
7307
7979
  }
7308
7980
  }
7981
+ // Устаревшие данные перечитываются через очередь черновика, чтобы ответ не перезаписал результат изменения, отправленного раньше.
7309
7982
  if (cacheable && !cachedItem.cachedDataIsActual()) {
7310
- cachedItem.update();
7983
+ this.enqueueRefresh(draftId);
7311
7984
  }
7312
7985
  return cachedItem.item$;
7313
7986
  }
7987
+ /**
7988
+ * Запрашивает полную информацию о черновике в обход кэша и обновляет кэш полученными данными. Запрос встаёт в очередь запросов черновика.
7989
+ *
7990
+ * @param draftId Идентификатор записи.
7991
+ */
7992
+ fetch$(draftId) {
7993
+ return this.refreshDraft$(draftId).pipe(this.inDraftQueue(draftId));
7994
+ }
7314
7995
  /**
7315
7996
  * Возвращает список элементов коммерческого предложения/черновика.
7316
7997
  *
@@ -7326,37 +8007,40 @@ class ScOrderDraftsService {
7326
8007
  * @param patch Данные для обновления.
7327
8008
  */
7328
8009
  update$(draftId, patch) {
7329
- const cachedItem = this.offerMap.get(draftId);
7330
- return this.http.patch(`${this.urls.apiUrl}/orders/offers/${draftId}`, patch).pipe(map$1((offerDTO) => new ScOrderDraft(offerDTO)), tap((offer) => {
8010
+ return this.http
8011
+ .patch(`${this.urls.apiUrl}/orders/offers/${draftId}`, patch, { context: ScOrderDraftsService.getErrorContext('Не удалось изменить черновик.') })
8012
+ .pipe(tap(() => {
7331
8013
  this.userMetrikaService.emitUserMetrikaEvent({
7332
8014
  target: ScUserMetrikaGoalsEnum.orderDraftUpdated,
7333
8015
  params: { offer_id: draftId },
7334
8016
  });
7335
- cachedItem?.setValue(offer);
7336
- }));
8017
+ }), this.updatesDraft(draftId));
7337
8018
  }
7338
8019
  /**
7339
- * Удаляет коммерческое предложение/черновик.
8020
+ * Удаляет коммерческое предложение/черновик. Запрос встаёт в очередь черновика после его изменений, после отказа 403 или 409 черновик перезапрашивается.
7340
8021
  *
7341
8022
  * @param offerId Идентификатор записи.
7342
8023
  */
7343
8024
  delete$(offerId) {
7344
- return this.http.delete(`${this.urls.apiUrl}/orders/offers/${offerId}`).pipe(tap(() => {
8025
+ return this.http.delete(`${this.urls.apiUrl}/orders/offers/${offerId}`, { context: ScOrderDraftsService.getErrorContext('Не удалось удалить черновик.') }).pipe(tap(() => {
7345
8026
  this.userMetrikaService.emitUserMetrikaEvent({
7346
8027
  target: ScUserMetrikaGoalsEnum.orderDraftDeleted,
7347
8028
  params: { offer_id: offerId },
7348
8029
  });
7349
8030
  this.offerMap.delete(offerId);
7350
- }));
8031
+ }), this.refreshOnRejection(offerId), this.inDraftQueue(offerId));
7351
8032
  }
7352
8033
  /**
7353
- * Создаёт заказ на основе коммерческого предложения/черновика.
8034
+ * Создаёт заказ на основе коммерческого предложения/черновика. Запрос встаёт в очередь черновика, чтобы ответ перезапроса,
8035
+ * отправленного раньше, не вернул в кэш заказанные позиции. После отказа 403 или 409 черновик перезапрашивается.
7354
8036
  *
7355
8037
  * @param offerId Идентификатор записи.
7356
8038
  * @param data Данные заказа.
7357
8039
  */
7358
8040
  createOrder$(offerId, data) {
7359
- return this.http.post(`${this.urls.apiUrl}/orders/offers/${offerId}/create-order`, data).pipe(map$1((orders) => orders.map((item) => new ScOrderShort(item))), tap((orders) => {
8041
+ return this.http
8042
+ .post(`${this.urls.apiUrl}/orders/offers/${offerId}/create-order`, data, { context: ScOrderDraftsService.getErrorContext('Не удалось оформить заказ.') })
8043
+ .pipe(map$1((orders) => orders.map((item) => new ScOrderShort(item))), tap((orders) => {
7360
8044
  orders.forEach((order) => {
7361
8045
  this.userMetrikaService.emitUserMetrikaEvent({
7362
8046
  target: ScUserMetrikaGoalsEnum.orderCreatedFromDraft,
@@ -7364,7 +8048,7 @@ class ScOrderDraftsService {
7364
8048
  });
7365
8049
  });
7366
8050
  this.removeOrderedProductsFromCache(offerId, data.items ?? []);
7367
- }));
8051
+ }), this.refreshOnRejection(offerId), this.inDraftQueue(offerId));
7368
8052
  }
7369
8053
  /**
7370
8054
  * Убирает заказанные позиции из кэша черновика локально (сервер сразу после заказа ещё может вернуть их в списке).
@@ -7383,14 +8067,15 @@ class ScOrderDraftsService {
7383
8067
  return;
7384
8068
  }
7385
8069
  const currentDraft = draft;
8070
+ // Из черновика Профстрой позиции после оформления заказа не удаляются.
8071
+ if (currentDraft.isProfstroy) {
8072
+ return;
8073
+ }
7386
8074
  const remainingProducts = currentDraft.products.filter((product) => !orderedIds.has(product.id));
7387
8075
  if (remainingProducts.length === currentDraft.products.length) {
7388
8076
  return;
7389
8077
  }
7390
- const updatedDraft = new ScOrderDraft(currentDraft);
7391
- updatedDraft.products = remainingProducts;
7392
- updatedDraft.sum = ScNumberHelper.roundMoney(remainingProducts.reduce((sum, product) => sum + product.costRub, 0));
7393
- cachedItem.setValue(updatedDraft);
8078
+ cachedItem.setValue(currentDraft.withProducts(remainingProducts));
7394
8079
  });
7395
8080
  }
7396
8081
  /**
@@ -7400,11 +8085,11 @@ class ScOrderDraftsService {
7400
8085
  * @param offerId Идентификатор коммерческого предложения/черновика.
7401
8086
  */
7402
8087
  addProduct$(productData, offerId) {
7403
- return this.http.post(`${this.urls.apiUrl}/orders/offers/${offerId}/products`, productData).pipe(map$1((offerDTO) => new ScOrderDraft(offerDTO)), tap((offer) => {
7404
- if (this.offerMap.has(offerId)) {
7405
- this.offerMap.get(offerId)?.setValue(offer);
7406
- }
7407
- }));
8088
+ return this.http
8089
+ .post(`${this.urls.apiUrl}/orders/offers/${offerId}/products`, productData, {
8090
+ context: ScOrderDraftsService.getErrorContext('Не удалось добавить позицию.'),
8091
+ })
8092
+ .pipe(this.updatesDraft(offerId));
7408
8093
  }
7409
8094
  /**
7410
8095
  * Изменяет продукт в коммерческом предложении/черновике.
@@ -7414,11 +8099,11 @@ class ScOrderDraftsService {
7414
8099
  * @param offerId Идентификатор коммерческого предложения/черновика.
7415
8100
  */
7416
8101
  updateProduct$(productId, patch, offerId) {
7417
- return this.http.patch(`${this.urls.apiUrl}/orders/offers/${offerId}/products/${productId}`, patch).pipe(map$1((offerDTO) => new ScOrderDraft(offerDTO)), tap((offer) => {
7418
- if (this.offerMap.has(offerId)) {
7419
- this.offerMap.get(offerId)?.setValue(offer);
7420
- }
7421
- }));
8102
+ return this.http
8103
+ .patch(`${this.urls.apiUrl}/orders/offers/${offerId}/products/${productId}`, patch, {
8104
+ context: ScOrderDraftsService.getErrorContext('Не удалось сохранить позицию.'),
8105
+ })
8106
+ .pipe(this.updatesDraft(offerId));
7422
8107
  }
7423
8108
  /**
7424
8109
  * Удаляет продукт из коммерческого предложения/черновика.
@@ -7427,12 +8112,138 @@ class ScOrderDraftsService {
7427
8112
  * @param offerId Идентификатор коммерческого предложения/черновика.
7428
8113
  */
7429
8114
  deleteProduct$(item, offerId) {
7430
- return this.http.delete(`${this.urls.apiUrl}/orders/offers/${offerId}/products/${item.id}`).pipe(map$1((offerDTO) => new ScOrderDraft(offerDTO)), tap((offer) => {
7431
- if (this.offerMap.has(offerId)) {
7432
- this.offerMap.get(offerId)?.setValue(offer);
7433
- }
8115
+ return this.http
8116
+ .delete(`${this.urls.apiUrl}/orders/offers/${offerId}/products/${item.id}`, {
8117
+ context: ScOrderDraftsService.getErrorContext('Не удалось удалить позицию.'),
8118
+ })
8119
+ .pipe(this.updatesDraft(offerId));
8120
+ }
8121
+ /**
8122
+ * Удаляет несколько позиций одним запросом: удаляются все или ни одна. После 404 черновик тоже перезапрашивается.
8123
+ *
8124
+ * @param items Удаляемые позиции.
8125
+ * @param offerId Идентификатор коммерческого предложения/черновика.
8126
+ */
8127
+ deleteProducts$(items, offerId) {
8128
+ const body = { items: items.map((item) => item.id) };
8129
+ return this.http
8130
+ .delete(`${this.urls.apiUrl}/orders/offers/${offerId}/products`, {
8131
+ body,
8132
+ context: ScOrderDraftsService.getErrorContext('Не удалось удалить позиции.'),
8133
+ })
8134
+ .pipe(this.updatesDraft(offerId, [...ScOrderDraftsService.rejectionStatuses, HttpStatusCode.NotFound]));
8135
+ }
8136
+ /**
8137
+ * Возвращает оператор запроса, который отвечает черновиком целиком: ответ кладётся в кэш, после отказа черновик перезапрашивается,
8138
+ * запрос выполняется в очереди черновика.
8139
+ *
8140
+ * @param draftId Идентификатор черновика.
8141
+ * @param statuses Коды отказа для перезапроса.
8142
+ */
8143
+ updatesDraft(draftId, statuses = ScOrderDraftsService.rejectionStatuses) {
8144
+ return pipe(map$1((offerDTO) => new ScOrderDraft(offerDTO, this.dateFormats.api)), tap((offer) => {
8145
+ this.offerMap.get(draftId)?.setValue(offer);
8146
+ }), this.refreshOnRejection(draftId, statuses), this.inDraftQueue(draftId));
8147
+ }
8148
+ /**
8149
+ * Возвращает оператор, который после отказа ставит в очередь перезапрос черновика. Ошибка передаётся подписчику.
8150
+ *
8151
+ * @param draftId Идентификатор черновика.
8152
+ * @param statuses Коды отказа для перезапроса.
8153
+ */
8154
+ refreshOnRejection(draftId, statuses = ScOrderDraftsService.rejectionStatuses) {
8155
+ return tap({
8156
+ error: (error) => {
8157
+ if (error instanceof HttpErrorResponse && statuses.includes(error.status)) {
8158
+ this.enqueueRefresh(draftId);
8159
+ }
8160
+ },
8161
+ });
8162
+ }
8163
+ /**
8164
+ * Возвращает оператор, который выполняет запрос в очереди черновика.
8165
+ *
8166
+ * @param draftId Идентификатор черновика.
8167
+ */
8168
+ inDraftQueue(draftId) {
8169
+ return this.requestQueues.inQueue(ScOrderDraftsService.getQueueKey(draftId));
8170
+ }
8171
+ /**
8172
+ * Ставит в очередь черновика перезапрос, если такой перезапрос ещё не ждёт очереди и не выполняется. Ответ обновляет кэш.
8173
+ *
8174
+ * @param draftId Идентификатор черновика.
8175
+ */
8176
+ enqueueRefresh(draftId) {
8177
+ this.requestQueues.pushOnce(ScOrderDraftsService.getQueueKey(draftId), 'refresh', this.refreshDraft$(draftId));
8178
+ }
8179
+ /**
8180
+ * Возвращает запрос списка черновиков с пагинацией.
8181
+ *
8182
+ * @param params Параметры запроса получения списка.
8183
+ * @param context Контекст запроса.
8184
+ */
8185
+ requestList$(params, context) {
8186
+ return this.http
8187
+ .get(`${this.urls.apiUrl}/orders/offers`, { params, context })
8188
+ .pipe(map$1((offersPaginateDTO) => ({ ...offersPaginateDTO, data: offersPaginateDTO.data.map((item) => new ScOrderDraftShort(item, this.dateFormats.api)) })));
8189
+ }
8190
+ /**
8191
+ * Возвращает запрос полной информации о черновике.
8192
+ *
8193
+ * @param draftId Идентификатор черновика.
8194
+ */
8195
+ requestDraft$(draftId) {
8196
+ return this.http.get(`${this.urls.apiUrl}/orders/offers/${draftId}`).pipe(map$1((offerDTO) => new ScOrderDraft(offerDTO, this.dateFormats.api)));
8197
+ }
8198
+ /**
8199
+ * Возвращает запрос полной информации о черновике, который обновляет кэш полученными данными. Новую запись кэша запрос не создаёт:
8200
+ * ответ, пришедший после выхода пользователя, не должен попасть в кэш.
8201
+ *
8202
+ * @param draftId Идентификатор черновика.
8203
+ */
8204
+ refreshDraft$(draftId) {
8205
+ return this.requestDraft$(draftId).pipe(tap((offer) => {
8206
+ this.offerMap.get(draftId)?.setValue(offer);
7434
8207
  }));
7435
8208
  }
8209
+ /**
8210
+ * Возвращает запись кэша, которая загружает черновик с сервера. Если загрузка не удалась, запись убирается из кэша (если в кэше всё ещё она),
8211
+ * чтобы следующее обращение загрузило черновик заново.
8212
+ *
8213
+ * @param draftId Идентификатор черновика.
8214
+ */
8215
+ createCachedDraft(draftId) {
8216
+ const cachedItem = new ScCachedItem(this.updateInterval.orderData, this.requestDraft$(draftId).pipe(tap({
8217
+ error: () => {
8218
+ if (this.offerMap.get(draftId) === cachedItem) {
8219
+ this.offerMap.delete(draftId);
8220
+ }
8221
+ },
8222
+ })), loadingPlaceholder);
8223
+ return cachedItem;
8224
+ }
8225
+ /**
8226
+ * Кладёт в кэш черновик из ответа создания, чтобы страница созданного черновика открылась без повторного запроса.
8227
+ *
8228
+ * @param offer Созданный черновик.
8229
+ */
8230
+ cacheCreated(offer) {
8231
+ this.offerMap.set(offer.id, new ScCachedItem(this.updateInterval.orderData, of(offer), loadingPlaceholder));
8232
+ }
8233
+ /**
8234
+ * Выполняет запрос с указанным интервалом, пока вкладка браузера видна. Первый запрос идёт через интервал, на скрытой вкладке запросов нет,
8235
+ * после возврата на вкладку запрос выполняется сразу. Новый запрос не начинается до завершения предыдущего. Ошибки пропускаются:
8236
+ * фоновый запрос повторится на следующем шаге.
8237
+ *
8238
+ * @param period Интервал запросов (ms).
8239
+ * @param request Функция, возвращающая запрос.
8240
+ */
8241
+ poll$(period, request) {
8242
+ return this.pageVisibility$.pipe(switchMap((isVisible, index) => {
8243
+ const delay = index === 0 ? period : 0;
8244
+ return isVisible ? timer(delay, period) : EMPTY;
8245
+ }), exhaustMap(() => request().pipe(catchError$1(() => EMPTY))));
8246
+ }
7436
8247
  static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.16", ngImport: i0, type: ScOrderDraftsService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
7437
8248
  static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.16", ngImport: i0, type: ScOrderDraftsService, providedIn: 'root' }); }
7438
8249
  }
@@ -7531,10 +8342,9 @@ class ScOrdersService {
7531
8342
  * @param params Параметры запроса получения заказов.
7532
8343
  */
7533
8344
  getOrders$(params) {
7534
- return this.http.get(`${this.urls.apiUrl}/orders`, { params: params }).pipe(map$1((ordersPaginateDTO) => {
7535
- ordersPaginateDTO.data = ordersPaginateDTO.data.map((item) => new ScOrderShort(item));
7536
- return ordersPaginateDTO;
7537
- }));
8345
+ return this.http
8346
+ .get(`${this.urls.apiUrl}/orders`, { params: params })
8347
+ .pipe(map$1((ordersPaginateDTO) => ({ ...ordersPaginateDTO, data: ordersPaginateDTO.data.map((item) => new ScOrderShort(item)) })));
7538
8348
  }
7539
8349
  /**
7540
8350
  * Возвращает полную информацию о заказе.
@@ -7653,12 +8463,13 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.16", ngImpo
7653
8463
  const SC_PAGE_QUERY_PARAM = 'page';
7654
8464
  /**
7655
8465
  * Преобразует значение query-параметра {@link SC_PAGE_QUERY_PARAM} в номер страницы пагинации.
7656
- * Нечисловые, дробные и меньшие единицы значения приводятся к первой странице.
8466
+ * Нечисловые, слишком большие и меньшие единицы значения приводятся к первой странице, дробные округляются вниз.
7657
8467
  *
7658
8468
  * @param value Значение query-параметра номера страницы пагинации.
7659
8469
  */
7660
8470
  function scParsePageQueryParam(value) {
7661
- return Math.max(1, Math.trunc(Number(value) || 1));
8471
+ const page = Math.trunc(Number(value));
8472
+ return Number.isSafeInteger(page) && page > 1 ? page : 1;
7662
8473
  }
7663
8474
  /**
7664
8475
  * Возвращает {@link Observable} изменения номера страницы пагинации из query-параметра {@link SC_PAGE_QUERY_PARAM}.
@@ -8128,6 +8939,10 @@ class SchemaOrgFactory {
8128
8939
  * Пайп для формирования полного URI изображения на media сервере.
8129
8940
  */
8130
8941
  this.mediaImageTransformerPipe = inject(ScMediaImageTransformerPipe);
8942
+ /**
8943
+ * Класс с вспомогательными методами для работы с изображениями.
8944
+ */
8945
+ this.imageHelper = inject(ScImageHelper);
8131
8946
  }
8132
8947
  /**
8133
8948
  * Генерирует и возвращает схему данных для указанного продукта.
@@ -8305,19 +9120,48 @@ class SchemaOrgFactory {
8305
9120
  ...(articleBody && { articleBody }),
8306
9121
  url: newsUrl,
8307
9122
  mainEntityOfPage: newsUrl,
8308
- author: {
8309
- '@type': 'Organization',
8310
- name: this.companyInfo.name,
8311
- url: this.urls.siteUrl,
8312
- },
8313
- publisher: {
8314
- '@type': 'Organization',
8315
- name: this.companyInfo.name,
8316
- logo: {
8317
- '@type': 'ImageObject',
8318
- url: this.urls.logoUrl,
8319
- },
8320
- },
9123
+ author: this.createArticleAuthor(),
9124
+ publisher: this.createArticlePublisher(),
9125
+ };
9126
+ }
9127
+ /**
9128
+ * Генерирует и возвращает схему данных для указанной статьи блога.
9129
+ *
9130
+ * @param post Данные о статье блога.
9131
+ * @param postPath Url путь к статье. В пути должен присутствовать шаблон ':slug', обозначающий символьное обозначение статьи для подстановки.
9132
+ * @param id Необязательный идентификатор сущности для поля `@id` в JSON-LD.
9133
+ */
9134
+ generateForBlogPosting(post, postPath, id) {
9135
+ const item = this.createBlogPostingItem(post, postPath);
9136
+ const articleBody = post.content ? this.stripHtml(post.content) : undefined;
9137
+ return {
9138
+ '@context': 'https://schema.org',
9139
+ ...item,
9140
+ ...(id && { '@id': id }),
9141
+ ...(articleBody && { articleBody }),
9142
+ mainEntityOfPage: item.url,
9143
+ author: this.createArticleAuthor(),
9144
+ publisher: this.createArticlePublisher(),
9145
+ };
9146
+ }
9147
+ /**
9148
+ * Генерирует и возвращает схему данных блога со списком статей.
9149
+ *
9150
+ * @param posts Список статей блога.
9151
+ * @param blogPath Url путь к блогу.
9152
+ * @param postPath Url путь к статье. В пути должен присутствовать шаблон ':slug', обозначающий символьное обозначение статьи для подстановки.
9153
+ * @param name Необязательное название блога.
9154
+ */
9155
+ generateForBlog(posts, blogPath, postPath, name) {
9156
+ const blogUrl = `${this.urls.siteUrl}${blogPath}`;
9157
+ return {
9158
+ '@context': 'https://schema.org',
9159
+ '@type': 'Blog',
9160
+ ...(name && { name }),
9161
+ url: blogUrl,
9162
+ mainEntityOfPage: blogUrl,
9163
+ publisher: this.createArticlePublisher(),
9164
+ blogPost: posts.map((post) => this.createBlogPostingItem(post, postPath)),
8321
9165
  };
8322
9166
  }
8323
9167
  /**
@@ -8358,6 +9202,46 @@ class SchemaOrgFactory {
8358
9202
  '@graph': data.map((item) => omit(item, '@context')),
8359
9203
  };
8360
9204
  }
9205
+ /**
9206
+ * Формирует автора статьи от имени компании.
9207
+ */
9208
+ createArticleAuthor() {
9209
+ return {
9210
+ '@type': 'Organization',
9211
+ name: this.companyInfo.name,
9212
+ url: this.urls.siteUrl,
9213
+ };
9214
+ }
9215
+ /**
9216
+ * Формирует издателя статьи от имени компании.
9217
+ */
9218
+ createArticlePublisher() {
9219
+ return {
9220
+ '@type': 'Organization',
9221
+ name: this.companyInfo.name,
9222
+ logo: {
9223
+ '@type': 'ImageObject',
9224
+ url: this.urls.logoUrl,
9225
+ },
9226
+ };
9227
+ }
9228
+ /**
9229
+ * Формирует краткую схему статьи блога.
9230
+ *
9231
+ * @param post Краткие данные о статье блога.
9232
+ * @param postPath Url путь к статье с шаблоном ':slug'.
9233
+ */
9234
+ createBlogPostingItem(post, postPath) {
9235
+ const image = this.imageHelper.getBlogCoverImage(post.cover);
9236
+ const datePublished = this.normalizeSchemaDate(post.publishedAt ?? undefined);
9237
+ return {
9238
+ '@type': 'BlogPosting',
9239
+ ...(post.title && { headline: post.title }),
9240
+ ...(image && { image }),
9241
+ ...(datePublished && { datePublished }),
9242
+ url: `${this.urls.siteUrl}${postPath.replace(':slug', () => post.slug)}`,
9243
+ };
9244
+ }
8361
9245
  /**
8362
9246
  * Формирует PostalAddress из структурированного адреса компании.
8363
9247
  *
@@ -8463,7 +9347,8 @@ class SchemaOrgFactory {
8463
9347
  return undefined;
8464
9348
  }
8465
9349
  if (/^\d{4}-\d{2}-\d{2}/.test(dateValue)) {
8466
- return dateValue;
9350
+ // Формат API "Y-m-d H:i:s" приводится к ISO 8601.
9351
+ return dateValue.replace(/^(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2})/, '$1T$2');
8467
9352
  }
8468
9353
  const withTimeMatch = /^(\d{2})\.(\d{2})\.(\d{4}) (\d{2}):(\d{2})$/.exec(dateValue);
8469
9354
  if (withTimeMatch) {
@@ -8670,6 +9555,15 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.16", ngImpo
8670
9555
  * Сервис управления SEO-параметрами.
8671
9556
  */
8672
9557
  class ScSeoService {
9558
+ /**
9559
+ * Инициализирует экземпляр класса {@link ScSeoService}.
9560
+ *
9561
+ * Запрещает индексирование закрытой страницы после навигации на неё, а также любой страницы, если первую навигацию отклонил защитник маршрута,
9562
+ * резолвер не вернул данные или произошла ошибка: страница без содержимого не должна индексироваться.
9563
+ * Так на сервере отсекаются страницы личного кабинета: их компоненты не создаются, и без этого страница получила бы стартовые robots-теги из index.html.
9564
+ * Перенаправление и замена навигации новой отказом не считаются: за ними следует навигация на другую страницу.
9565
+ * Отмена последующих навигаций оставляет пользователя на текущей странице, поэтому её robots-теги не меняются.
9566
+ */
8673
9567
  constructor() {
8674
9568
  /**
8675
9569
  * Данные о компании.
@@ -8687,6 +9581,10 @@ class ScSeoService {
8687
9581
  * Список ссылок приложения.
8688
9582
  */
8689
9583
  this.urls = inject(SC_URLS);
9584
+ /**
9585
+ * Пути страниц, закрытых от индексирования.
9586
+ */
9587
+ this.noIndexPaths = inject(SC_NO_INDEX_PATHS);
8690
9588
  /**
8691
9589
  * Пайп, возвращающий идентификатор или символьное обозначение (slug) исходя из настроек окружения.
8692
9590
  */
@@ -8723,6 +9621,18 @@ class ScSeoService {
8723
9621
  * Экземпляр {@link Renderer2} для безопасной работы с DOM.
8724
9622
  */
8725
9623
  this.renderer = this.rendererFactory.createRenderer(null, null);
9624
+ /**
9625
+ * Список robots-тегов страницы, закрытой от индексирования.
9626
+ */
9627
+ this.noIndexRobots = ['noindex', 'nofollow', 'noarchive'];
9628
+ const navigationEnd$ = this.router.events.pipe(filter((event) => event instanceof NavigationEnd));
9629
+ const firstNavigationRejected$ = this.router.events.pipe(filter((event) => event instanceof NavigationError ||
9630
+ (event instanceof NavigationCancel && event.code !== NavigationCancellationCode.Redirect && event.code !== NavigationCancellationCode.SupersededByNewNavigation)), takeUntil(navigationEnd$));
9631
+ merge(navigationEnd$.pipe(filter((event) => this.isNoIndexUrl(event.urlAfterRedirects))), firstNavigationRejected$)
9632
+ .pipe(takeUntilDestroyed())
9633
+ .subscribe(() => {
9634
+ this.metaService.updateTag({ name: 'robots', content: this.noIndexRobots.join(', ') });
9635
+ });
8726
9636
  }
8727
9637
  /**
8728
9638
  * Устанавливает seo параметры на основе указанного ресурса. Если какого-то тега нет, будет установлено значение по умолчанию.
@@ -8734,8 +9644,8 @@ class ScSeoService {
8734
9644
  */
8735
9645
  setFromResource(resource, img, robots, schemaOrgData) {
8736
9646
  const updatedResource = {
8737
- title: this.replaceTemplates(resource?.title ?? this.defaultSeo.title, resource?.instanceData ?? {}),
8738
- description: this.replaceTemplates(resource?.description ?? this.defaultSeo.description, resource?.instanceData ?? {}),
9647
+ title: this.addPageNumber(this.replaceTemplates(resource?.title ?? this.defaultSeo.title, resource?.instanceData ?? {})),
9648
+ description: this.addPageNumber(this.replaceTemplates(resource?.description ?? this.defaultSeo.description, resource?.instanceData ?? {})),
8739
9649
  keywords: resource?.keywords ?? this.defaultSeo.keywords,
8740
9650
  meta: resource?.meta ?? [],
8741
9651
  };
@@ -8765,7 +9675,7 @@ class ScSeoService {
8765
9675
  * @param title Заголовок страницы.
8766
9676
  */
8767
9677
  setByDefaultAsNoIndexed(title) {
8768
- this.setByDefault(title, ['noindex', 'nofollow', 'noarchive']);
9678
+ this.setByDefault(title, this.noIndexRobots);
8769
9679
  }
8770
9680
  /**
8771
9681
  * Устанавливает seo-параметры для указанного элемента каталога.
@@ -8777,15 +9687,15 @@ class ScSeoService {
8777
9687
  setForCatalogItem(item, urlPath, schemaOrgData) {
8778
9688
  const url = `${this.urls.siteUrl}${urlPath.replace(':id', this.idOrSlugPipe.transform(item).toString())}`;
8779
9689
  // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
8780
- const title = this.replaceTemplates(item.seo?.title ?? this.catalogItemDefaultSeo.title ?? `${item.name} - Купить в ${this.companyInfo.name}`, item);
8781
- const description = this.replaceTemplates(
9690
+ const title = this.addPageNumber(this.replaceTemplates(item.seo?.title ?? this.catalogItemDefaultSeo.title ?? `${item.name} - Купить в ${this.companyInfo.name}`, item));
9691
+ const description = this.addPageNumber(this.replaceTemplates(
8782
9692
  // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
8783
- item.seo?.description ?? this.catalogItemDefaultSeo.description ?? `${item.name} - Купить по выгодным ценам в ${this.companyInfo.name}`, item);
9693
+ item.seo?.description ?? this.catalogItemDefaultSeo.description ?? `${item.name} - Купить по выгодным ценам в ${this.companyInfo.name}`, item));
8784
9694
  const keywords = item.seo?.keywords ?? `${item.name}, ${this.catalogItemDefaultSeo.keywords}`;
8785
9695
  const meta = item.seo?.meta ?? [];
8786
9696
  // Устанавливаем стандартные seo-параметры, в том числе и каноническую ссылку.
8787
9697
  // Страницы пагинации индексируются отдельно, поэтому каноническая ссылка содержит номер страницы из query-параметров.
8788
- const page = scParsePageQueryParam(this.router.parseUrl(this.router.url).queryParamMap.get(SC_PAGE_QUERY_PARAM));
9698
+ const page = this.getPage();
8789
9699
  const canonicalUrl = page > 1 ? `${url}?${SC_PAGE_QUERY_PARAM}=${page}` : url;
8790
9700
  this.setMetaTags(title, description, keywords, meta, ['index', 'follow']);
8791
9701
  this.setOpenGraphMetaTags(title, description, url, this.mediaImageTransformerPipe.transform(item.image, true));
@@ -8817,6 +9727,29 @@ class ScSeoService {
8817
9727
  return '';
8818
9728
  });
8819
9729
  }
9730
+ /**
9731
+ * Возвращает признак, что страница по указанному адресу закрыта от индексирования.
9732
+ *
9733
+ * @param url Адрес страницы.
9734
+ */
9735
+ isNoIndexUrl(url) {
9736
+ return this.noIndexPaths.some((path) => url.startsWith(path));
9737
+ }
9738
+ /**
9739
+ * Возвращает номер страницы пагинации из query-параметров текущего адреса.
9740
+ */
9741
+ getPage() {
9742
+ return scParsePageQueryParam(this.router.parseUrl(this.router.url).queryParamMap.get(SC_PAGE_QUERY_PARAM));
9743
+ }
9744
+ /**
9745
+ * Добавляет в конец текста номер страницы пагинации из текущего адреса. На первой странице текст не меняется.
9746
+ *
9747
+ * @param text Текст заголовка или описания страницы.
9748
+ */
9749
+ addPageNumber(text) {
9750
+ const page = this.getPage();
9751
+ return page > 1 ? `${text} (Страница ${page})` : text;
9752
+ }
8820
9753
  /**
8821
9754
  * Устанавливает все meta-теги страницы. Если какой-либо из параметров не указан, для него устанавливается значение по умолчанию.
8822
9755
  *
@@ -8824,13 +9757,13 @@ class ScSeoService {
8824
9757
  * @param description Описание страницы.
8825
9758
  * @param keywords Ключевые слова страницы.
8826
9759
  * @param meta Массив дополнительных значений метатегов.
8827
- * @param robots Список robots тегов для страницы.
9760
+ * @param robots Список robots тегов для страницы. На закрытой от индексирования странице заменяется запретом индексирования.
8828
9761
  */
8829
9762
  setMetaTags(title = this.defaultSeo.title, description = this.defaultSeo.description, keywords = this.defaultSeo.keywords, meta = [], robots = ['index', 'follow']) {
8830
9763
  this.titleService.setTitle(title);
8831
9764
  this.metaService.updateTag({ name: 'description', content: description });
8832
9765
  this.metaService.updateTag({ name: 'keywords', content: keywords });
8833
- this.metaService.updateTag({ name: 'robots', content: robots.join(', ') });
9766
+ this.metaService.updateTag({ name: 'robots', content: (this.isNoIndexUrl(this.router.url) ? this.noIndexRobots : robots).join(', ') });
8834
9767
  meta.forEach((tag) => {
8835
9768
  this.metaService.updateTag({ name: tag.name, content: tag.content });
8836
9769
  });
@@ -8856,10 +9789,11 @@ class ScSeoService {
8856
9789
  * @param url URL который необходимо использовать в качестве ссылки.
8857
9790
  */
8858
9791
  setCanonicalLink(url) {
8859
- // Удаляем существующий link canonical.
9792
+ // Обновляем существующий link canonical, а не пересоздаём: рендерер анимаций откладывает удаление, и при повторном вызове в том же цикле осталось бы два тега.
8860
9793
  const existingLink = this.document.querySelector('link[rel="canonical"]');
8861
- if (existingLink?.parentNode) {
8862
- this.renderer.removeChild(existingLink.parentNode, existingLink);
9794
+ if (existingLink) {
9795
+ this.renderer.setAttribute(existingLink, 'href', url);
9796
+ return;
8863
9797
  }
8864
9798
  // Создаём и устанавливаем новый тег.
8865
9799
  // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
@@ -8886,7 +9820,8 @@ class ScSeoService {
8886
9820
  const script = this.renderer.createElement('script');
8887
9821
  this.renderer.setAttribute(script, 'type', 'application/ld+json');
8888
9822
  this.renderer.setAttribute(script, projectAttributeName, '');
8889
- this.renderer.appendChild(script, this.document.createTextNode(JSON.stringify(data)));
9823
+ // Экранируем «<», чтобы строки из данных не закрыли тег script в HTML серверного рендеринга.
9824
+ this.renderer.appendChild(script, this.document.createTextNode(JSON.stringify(data).replaceAll('<', String.raw `\u003c`)));
8890
9825
  this.renderer.appendChild(this.document.head, script);
8891
9826
  }
8892
9827
  static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.16", ngImport: i0, type: ScSeoService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
@@ -8897,7 +9832,22 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.16", ngImpo
8897
9832
  args: [{
8898
9833
  providedIn: 'root',
8899
9834
  }]
8900
- }] });
9835
+ }], ctorParameters: () => [] });
9836
+
9837
+ /**
9838
+ * Возвращает провайдеры запрета индексирования страниц по списку путей.
9839
+ * Создаёт {@link ScSeoService} при старте приложения, чтобы он обработал и первую навигацию, которую отклонил защитник маршрута.
9840
+ *
9841
+ * @param paths Пути страниц, закрытых от индексирования. Страница закрыта, если её адрес начинается с одного из путей.
9842
+ */
9843
+ function provideNoIndexPaths(paths) {
9844
+ return makeEnvironmentProviders([
9845
+ { provide: SC_NO_INDEX_PATHS, useValue: paths },
9846
+ provideAppInitializer(() => {
9847
+ inject(ScSeoService);
9848
+ }),
9849
+ ]);
9850
+ }
8901
9851
 
8902
9852
  /**
8903
9853
  * Кэш ответов API, один на процесс: переживает пересоздание инжектора между SSR-рендерами.
@@ -9512,5 +10462,5 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.16", ngImpo
9512
10462
  * Generated bundle index. Do not edit.
9513
10463
  */
9514
10464
 
9515
- export { CATEGORY_PROVIDERS, EMPTY_CART, IS_BROWSER, IS_RUNNING_ON_TERMINAL, IS_SERVER, SC_ACCESS_AUTH_TOKEN_STORAGE_KEY, SC_API_KEYS, SC_AUTH_ADD_HEADER_REQUIRED, SC_AUTH_AS_CLIENT_DEFAULT_OPTIONS, SC_AUTH_AS_CLIENT_OPTIONS, SC_CACHE_LIFETIME, SC_CACHE_SETTINGS, SC_CANONICAL_REDIRECT_ENABLED, SC_CATALOG_ITEM_PAGE_META, SC_CATALOG_ROOT_PAGE_META, SC_CATEGORY_INFO, SC_CATEGORY_STATE, SC_COMPANY_INFO, SC_COMPANY_NAME, SC_CONFIGURATOR_COMPONENTS, SC_CONFIGURATOR_SETTINGS, SC_COUNT_FIRST_DISCOUNTED_PRODUCTS, SC_COUNT_LAST_NEWS, SC_DATE_FORMAT, SC_DEFAULT_PAGE_META, SC_FEEDBACK_API, SC_GUEST_ENDPOINTS_TOKEN, SC_GUEST_PARAMETER_NAME_TOKEN, SC_GUEST_TOKEN_STORAGE_KEY, SC_ID_OR_SLUG_IN_ROUTE, SC_IS_HEADER_REQUIRED, SC_IS_HIDDEN_ERROR_ALERT, SC_IS_HIDDEN_ERROR_ALERT_HTTP_CONTEXT, SC_IS_LOGOUT_REQUEST, SC_IS_REFRESH_REQUIRED, SC_LINEAR_VALUES, SC_LINEAR_VALUES_TOKEN, SC_MAX_LENGTH_SEARCH_TERM, SC_MIN_LENGTH_SEARCH_TERM, SC_NEXT_PAGE_PAGINATION_CLICK, SC_ORDER_LOADER, SC_ORDER_LOADING, SC_PAGE_QUERY_PARAM, SC_PATH_IMAGE_NOT_FOUND, SC_PRODUCTS_PAGINATION_LOADER, SC_PRODUCT_PAGINATION_DEFAULT_OPTIONS, SC_PRODUCT_PAGINATION_OPTIONS, SC_REFRESH_AUTH_TOKEN_STORAGE_KEY, SC_RELEASE, SC_SSR_HTTP_TIMEOUT, SC_SSR_RESPONSE_CACHE, SC_SSR_RESPONSE_CACHE_SETTINGS, SC_UPDATE_INTERVAL, SC_URLS, SC_USER_INFO, SC_VACANCIES_DATA_SOURCE, SC_VIRTUAL_CATEGORY_INFO, SC_VIRTUAL_CATEGORY_PROVIDERS, SEARCH_TERM, SEARCH_TERM_PROVIDERS, ScAuthAsClientGuard, ScAuthInterceptor, ScAuthService, ScBanner, ScBannerService, ScCacheInterceptor, ScCacheSettings, ScCachedData, ScCachedItem, ScCart, ScCartService, ScCatalogFilterService, ScCatalogFormat, ScCatalogItem, ScCatalogRedirectService, ScCatalogService, ScCatalogableItem, ScCategory, ScClientType, ScCodedIdentity, ScConfiguratorService, ScContactsService, ScContragentService, ScConvertInterceptor, ScConvertersService, ScDateFormatInterceptor, ScDeletableNamedIdentity, ScDeliveryAddressService, ScDeliveryCost, ScDeliveryType, ScDocumentInfoNode, ScDocumentInfoTypesEnum, ScErrorRequestState, ScErrorsInterceptor, ScFavoriteService, ScFeedbackForms, ScFeedbackService, ScFilesService, ScFrequentlyAskedQuestionsService, ScGuestInterceptor, ScHiddenCatalogableItem, ScIBreadcrumbItem, ScISuggestionType, ScIconTypesEnum, ScIdOrSlugGuard, ScIdOrSlugPipe, ScIdentity, ScImage, ScImageHelper, ScLoadingRequestState, ScLocationsService, ScMediaImageTransformerPipe, ScMimeTypes, ScNamedIdentity, ScNews, ScNewsService, ScNotificationActionTypes, ScNotificationLevelNames, ScNotificationsService, ScNumberHelper, ScOpfList, ScOptionsInterceptor, ScOrder, ScOrderBase, ScOrderDraft, ScOrderDraftShort, ScOrderDraftType, ScOrderDraftsService, ScOrderItem, ScOrderShort, ScOrderStateStatus, ScOrdersService, ScPaginationPageQueryParamService, ScPaginationService, ScPaymentStatus, ScPaymentType, ScPhoneService, ScPrimaryCatalogableItem, ScProduct, ScProductTileType, ScQuestionnaireService, ScQuestionnaireStatusEnum, ScReclamationService, ScReclamationStatus, ScRecommendationService, ScRedirectStatusEnum, ScReference, ScReferenceName, ScReferencesService, ScRequestStateStatusEnum, ScRequisitesService, ScRouteKeys, ScSearchService, ScSeoService, ScSocialType, ScSsrResponseCache, ScSsrResponseCacheBackend, ScSsrTimeoutInterceptor, ScSuccessRequestState, ScSuggestionAddressQuality, ScSuggestionService, ScSum, ScTokenService, ScUIService, ScUTMService, ScUnitsHelper, ScUpdatableNamedIdentity, ScUploadedFile, ScUser, ScUserMetadata, ScUserMetrikaGoalsEnum, ScUserMetrikaService, ScUserService, ScUserType, ScVCardService, ScVacanciesList, ScVacanciesService, ScVacancy, ScVerificationService, ScVirtualCategory, ScWarehouseService, SchemaOrgFactory, TERMINAL_PROVIDERS, USER_AGENT_TERMINAL, filterChangedByKey, loadingPlaceholder, mapRequestStateToDataOrNull, mapToRequestState, provideRubPrecision, provideSsrResponseCache, runningOnTerminalFactory, scGetCurrentRoute, scGetPageQueryParamChanges, scOrderIsLoaded, scParsePageQueryParam, searchTermFactory };
10465
+ export { CATEGORY_PROVIDERS, EMPTY_CART, IS_BROWSER, IS_RUNNING_ON_TERMINAL, IS_SERVER, SC_ACCESS_AUTH_TOKEN_STORAGE_KEY, SC_API_KEYS, SC_AUTH_ADD_HEADER_REQUIRED, SC_AUTH_AS_CLIENT_DEFAULT_OPTIONS, SC_AUTH_AS_CLIENT_OPTIONS, SC_CACHE_LIFETIME, SC_CACHE_SETTINGS, SC_CANONICAL_REDIRECT_ENABLED, SC_CATALOG_ITEM_PAGE_META, SC_CATALOG_ROOT_PAGE_META, SC_CATEGORY_INFO, SC_CATEGORY_STATE, SC_COMPANY_INFO, SC_COMPANY_NAME, SC_CONFIGURATOR_COMPONENTS, SC_CONFIGURATOR_SETTINGS, SC_COUNT_FIRST_DISCOUNTED_PRODUCTS, SC_COUNT_LAST_NEWS, SC_DATE_FORMAT, SC_DEFAULT_PAGE_META, SC_ERROR_ALERT_FALLBACK_MESSAGE, SC_FEEDBACK_API, SC_GUEST_ENDPOINTS_TOKEN, SC_GUEST_PARAMETER_NAME_TOKEN, SC_GUEST_TOKEN_STORAGE_KEY, SC_ID_OR_SLUG_IN_ROUTE, SC_IS_HEADER_REQUIRED, SC_IS_HIDDEN_ERROR_ALERT, SC_IS_HIDDEN_ERROR_ALERT_HTTP_CONTEXT, SC_IS_LOGOUT_REQUEST, SC_IS_REFRESH_REQUIRED, SC_LINEAR_VALUES, SC_LINEAR_VALUES_TOKEN, SC_MAX_LENGTH_SEARCH_TERM, SC_MIN_LENGTH_SEARCH_TERM, SC_NEXT_PAGE_PAGINATION_CLICK, SC_NO_INDEX_PATHS, SC_ORDER_LOADER, SC_ORDER_LOADING, SC_PAGE_QUERY_PARAM, SC_PATH_IMAGE_NOT_FOUND, SC_PRODUCTS_PAGINATION_LOADER, SC_PRODUCT_PAGINATION_DEFAULT_OPTIONS, SC_PRODUCT_PAGINATION_OPTIONS, SC_REFRESH_AUTH_TOKEN_STORAGE_KEY, SC_RELEASE, SC_SSR_HTTP_TIMEOUT, SC_SSR_RESPONSE_CACHE, SC_SSR_RESPONSE_CACHE_SETTINGS, SC_UPDATE_INTERVAL, SC_URLS, SC_USER_INFO, SC_VACANCIES_DATA_SOURCE, SC_VIRTUAL_CATEGORY_INFO, SC_VIRTUAL_CATEGORY_PROVIDERS, SEARCH_TERM, SEARCH_TERM_PROVIDERS, ScAuthAsClientGuard, ScAuthInterceptor, ScAuthService, ScBanner, ScBannerService, ScBlogService, ScCacheInterceptor, ScCacheSettings, ScCachedData, ScCachedItem, ScCart, ScCartService, ScCatalogFilterService, ScCatalogFormat, ScCatalogItem, ScCatalogRedirectService, ScCatalogService, ScCatalogableItem, ScCategory, ScClientType, ScCodedIdentity, ScConfiguratorService, ScContactsService, ScContragentService, ScConvertInterceptor, ScConvertersService, ScDateFormatInterceptor, ScDateHelper, ScDeletableNamedIdentity, ScDeliveryAddressService, ScDeliveryCost, ScDeliveryType, ScDocumentInfoNode, ScDocumentInfoTypesEnum, ScErrorRequestState, ScErrorsInterceptor, ScFavoriteService, ScFeedbackForms, ScFeedbackService, ScFilesService, ScFrequentlyAskedQuestionsService, ScGuestInterceptor, ScHiddenCatalogableItem, ScIBreadcrumbItem, ScISuggestionType, ScIconTypesEnum, ScIdOrSlugGuard, ScIdOrSlugPipe, ScIdentity, ScImage, ScImageHelper, ScLoadingRequestState, ScLocationsService, ScMediaImageTransformerPipe, ScMimeTypes, ScNamedIdentity, ScNews, ScNewsService, ScNotificationActionTypes, ScNotificationLevelNames, ScNotificationsService, ScNumberHelper, ScOpfList, ScOptionsInterceptor, ScOrder, ScOrderBase, ScOrderDraft, ScOrderDraftActualization, ScOrderDraftActualizationStatus, ScOrderDraftShort, ScOrderDraftType, ScOrderDraftsService, ScOrderItem, ScOrderItemsGroup, ScOrderShort, ScOrderStateStatus, ScOrdersService, ScPaginationPageQueryParamService, ScPaginationService, ScPaymentStatus, ScPaymentType, ScPhoneService, ScPrimaryCatalogableItem, ScProduct, ScProductTileType, ScProfstroyOrderItem, ScQuestionnaireService, ScQuestionnaireStatusEnum, ScReclamationService, ScReclamationStatus, ScRecommendationService, ScRedirectStatusEnum, ScReference, ScReferenceName, ScReferencesService, ScRequestQueue, ScRequestQueuesService, ScRequestStateStatusEnum, ScRequisitesService, ScRouteKeys, ScSearchService, ScSeoService, ScSocialType, ScSsrResponseCache, ScSsrResponseCacheBackend, ScSsrTimeoutInterceptor, ScSuccessRequestState, ScSuggestionAddressQuality, ScSuggestionService, ScSum, ScTokenService, ScUIService, ScUTMService, ScUnitsHelper, ScUpdatableNamedIdentity, ScUploadedFile, ScUser, ScUserMetadata, ScUserMetrikaGoalsEnum, ScUserMetrikaService, ScUserService, ScUserType, ScVCardService, ScVacanciesList, ScVacanciesService, ScVacancy, ScVerificationService, ScVirtualCategory, ScWarehouseService, SchemaOrgFactory, TERMINAL_PROVIDERS, USER_AGENT_TERMINAL, filterChangedByKey, loadingPlaceholder, mapRequestStateToDataOrNull, mapToRequestState, provideNoIndexPaths, provideRubPrecision, provideSsrResponseCache, runningOnTerminalFactory, scGetCurrentRoute, scGetPageQueryParamChanges, scOrderIsLoaded, scParsePageQueryParam, searchTermFactory };
9516
10466
  //# sourceMappingURL=snabcentr-client-core.mjs.map