All files / src/app/core/facades product-context.facade.ts

71.51% Statements 113/158
59.22% Branches 61/103
61.53% Functions 48/78
72.84% Lines 110/151

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 57675x 75x 75x 75x 75x 75x                           75x       75x   75x               75x 75x 75x   75x 75x                                                 75x                                                     75x                                                                                   75x 75x   75x     2x     75x         75x               75x 75x 75x     75x   75x                 75x         56x   56x 40x                   75x 123x     75x       106x   32x         75x     36x         75x     35x         75x     35x         75x                 33x 33x 3x 30x 2x 28x 1x 27x 1x     26x   33x               75x           51x 51x   18x               75x       34x     34x     75x         35x         75x           51x 51x   18x                                 75x     35x         75x           51x 51x   18x               75x           35x           75x       84x   1092x           75x   37x 666x     666x 666x             75x   75x     226x         75x       75x       323x 323x     50x     50x                     11x             123x         9x                       2428x 3x 3x 3x       2428x                             1x 1x                     2x           2x 2x     2x                                           2428x                                                                                                                       75x 75x   75x      
import { Injectable, InjectionToken, Injector, OnDestroy } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { RxState } from '@rx-angular/state';
import { isEqual, pick } from 'lodash-es';
import { BehaviorSubject, Observable, combineLatest, race } from 'rxjs';
import {
  debounceTime,
  distinctUntilChanged,
  distinctUntilKeyChanged,
  filter,
  first,
  map,
  skip,
  skipWhile,
  startWith,
  switchMap,
  take,
} from 'rxjs/operators';
 
import { AttributeGroupTypes } from 'ish-core/models/attribute-group/attribute-group.types';
import { Image } from 'ish-core/models/image/image.model';
import { Pricing } from 'ish-core/models/price/price.model';
import { ProductLinksDictionary } from 'ish-core/models/product-links/product-links.model';
import { ProductVariationHelper } from 'ish-core/models/product-variation/product-variation.helper';
import { ProductView } from 'ish-core/models/product-view/product-view.model';
import {
  ProductCompletenessLevel,
  ProductHelper,
  SkuQuantityType,
  VariationProduct,
  VariationProductMaster,
} from 'ish-core/models/product/product.model';
import { Promotion } from 'ish-core/models/promotion/promotion.model';
import { generateProductUrl } from 'ish-core/routing/product/product.route';
import { mapToProperty, whenTruthy } from 'ish-core/utils/operators';
import { ProductContextDisplayPropertiesService } from 'ish-core/utils/product-context-display-properties/product-context-display-properties.service';
 
import { AppFacade } from './app.facade';
import { ShoppingFacade } from './shopping.facade';
 
declare type DisplayEval = ((product: ProductView) => boolean) | boolean;
 
export interface ProductContextDisplayProperties<T = boolean> {
  readOnly: T;
  name: T;
  description: T;
  sku: T;
  inventory: T;
  price: T;
  promotions: T;
  quantity: T;
  variations: T;
  bundleParts: T;
  retailSetParts: T;
  shipment: T;
  addToBasket: T;
  addToWishlist: T;
  addToOrderTemplate: T;
  addToCompare: T;
  addToQuote: T;
  addToNotification: T;
}
 
const defaultDisplayProperties: ProductContextDisplayProperties<true | undefined> = {
  readOnly: undefined,
  name: true,
  description: true,
  sku: true,
  inventory: true,
  price: true,
  promotions: true,
  quantity: true,
  variations: true,
  bundleParts: true,
  retailSetParts: true,
  shipment: true,
  addToBasket: true,
  addToWishlist: true,
  addToOrderTemplate: true,
  addToCompare: true,
  addToQuote: true,
  addToNotification: true,
};
 
export interface ExternalDisplayPropertiesProvider {
  setup(
    context$: Observable<Pick<ProductContext, 'product' | 'prices'>>
  ): Observable<Partial<ProductContextDisplayProperties<false>>>;
}
 
export const EXTERNAL_DISPLAY_PROPERTY_PROVIDER = new InjectionToken<ExternalDisplayPropertiesProvider>(
  'externalDisplayPropertiesProvider'
);
 
export interface ProductContext {
  sku: string;
  requiredCompletenessLevel: ProductCompletenessLevel | true;
  product: ProductView;
  prices: Pricing;
  hasProductError: boolean;
  productURL: string;
  loading: boolean;
  label: string;
  categoryId: string;
  displayProperties: Partial<ProductContextDisplayProperties>;
 
  // lazy
  links: ProductLinksDictionary;
  promotions: Promotion[];
  parts: SkuQuantityType[];
  variations: VariationProduct[];
  variationCount: number;
  productMaster: VariationProductMaster;
 
  // quantity
  quantity: number;
  allowZeroQuantity: boolean;
  minQuantity: number;
  maxQuantity: number;
  stepQuantity: number;
  quantityError: string;
  hasQuantityError: boolean;
 
  // child contexts
  propagateActive: boolean;
  children: Record<string | number, ProductContext>;
 
  // selected warranty
  selectedWarranty: string;
}
 
@Injectable()
export class ProductContextFacade extends RxState<ProductContext> implements OnDestroy {
  private privateConfig$ = new BehaviorSubject<Partial<ProductContextDisplayProperties>>({});
  private loggingActive: boolean;
  private lazyFieldsInitialized: string[] = [];
 
  set config(config: Partial<ProductContextDisplayProperties>) {
    this.privateConfig$.next(config);
  }
 
  private validProductSKU$ = this.select('product').pipe(
    filter(p => !!p && !p.failed),
    mapToProperty('sku')
  );
 
  private masterProductSKU$ = this.select('product').pipe(
    switchMap(product =>
      ProductHelper.isMasterProduct(product) ? this.validProductSKU$ : this.select('product', 'productMasterSKU')
    ),
    whenTruthy()
  );
 
  constructor(
    private shoppingFacade: ShoppingFacade,
    private appFacade: AppFacade,
    private translate: TranslateService,
    injector: Injector
  ) {
    super();
 
    this.set({
      requiredCompletenessLevel: ProductCompletenessLevel.List,
      propagateActive: true,
      allowZeroQuantity: false,
      children: {},
      // eslint-disable-next-line unicorn/no-null
      categoryId: null,
    });
 
    this.connect(
      combineLatest([
        this.select('sku').pipe(whenTruthy()),
        this.select('requiredCompletenessLevel').pipe(whenTruthy()),
      ]).pipe(
        filter(([sku, level]) => !!sku && !!level),
        switchMap(([sku, level]) =>
          this.shoppingFacade.product$(sku, level).pipe(
            map(product => ({
              product,
              loading: false,
            })),
            startWith({ loading: true })
          )
        )
      )
    );
 
    this.hold(combineLatest([this.select('product'), this.select('displayProperties')]), args =>
      this.postProductFetch(...args)
    );
 
    this.connect(
      'productURL',
      combineLatest([
        this.select('product'),
        this.select('categoryId').pipe(switchMap(categoryId => this.shoppingFacade.category$(categoryId))),
      ]).pipe(
        map(args => generateProductUrl(...args)),
        distinctUntilChanged()
      )
    );
 
    this.connect(
      'minQuantity',
      combineLatest([this.select('product'), this.select('allowZeroQuantity')]).pipe(
        map(([product, allowZeroQuantity]) => (allowZeroQuantity ? 0 : product.minOrderQuantity || 1)),
        distinctUntilChanged()
      )
    );
 
    this.connect(
      'maxQuantity',
      combineLatest([this.select('product'), this.appFacade.serverSetting$<number>('basket.maxItemQuantity')]).pipe(
        map(([product, fromConfig]) => product?.maxOrderQuantity || fromConfig || 100),
        distinctUntilChanged()
      )
    );
 
    this.connect(
      'stepQuantity',
      this.select('product').pipe(
        map(product => product?.stepQuantity || 1),
        distinctUntilChanged()
      )
    );
 
    this.connect(
      combineLatest([
        this.select('product'),
        this.select('minQuantity'),
        this.select('maxQuantity'),
        this.select('stepQuantity'),
        this.select('quantity').pipe(distinctUntilChanged()),
      ]).pipe(
        map(([product, minOrderQuantity, maxOrderQuantity, stepQuantity, quantity]) => {
          if (product && !product.failed) {
            if (Number.isNaN(quantity)) {
              return this.translate.instant('product.quantity.integer.text');
            } else if (quantity < minOrderQuantity) {
              return this.translate.instant('product.quantity.greaterthan.text', { 0: minOrderQuantity });
            } else if (quantity > maxOrderQuantity) {
              return this.translate.instant('product.quantity.lessthan.text', { 0: maxOrderQuantity });
            } else if (quantity % stepQuantity !== 0) {
              return this.translate.instant('product.quantity.step.text', { 0: stepQuantity });
            }
          }
          return;
        }),
        map(quantityError => ({
          quantityError,
          hasQuantityError: !!quantityError,
        })),
        distinctUntilChanged(isEqual)
      )
    );
 
    this.connect(
      'hasQuantityError',
      this.select('sku').pipe(
        whenTruthy(),
        distinctUntilChanged(),
        switchMap(() =>
          this.select('children').pipe(
            map(children => Object.values(children)),
            debounceTime(300),
            skipWhile(children => !children?.length),
            map(children => !children.length || children.some(child => child.hasQuantityError)),
            distinctUntilChanged()
          )
        )
      )
    );
 
    this.connect(
      'quantity',
      this.select('product').pipe(
        whenTruthy(),
        map(p => p.minOrderQuantity),
        first()
      ),
      (state, minOrderQuantity) => (state.quantity ??= minOrderQuantity)
    );
 
    this.connect(
      'quantity',
      this.select('product').pipe(
        whenTruthy(),
        distinctUntilKeyChanged('sku'),
        map(p => p.minOrderQuantity),
        skip(1)
      )
    );
 
    this.connect(
      'quantity',
      this.select('sku').pipe(
        whenTruthy(),
        distinctUntilChanged(),
        switchMap(() =>
          this.select('children').pipe(
            map(children => Object.values(children)),
            debounceTime(300),
            skipWhile(children => !children?.length),
            map(children =>
              children.reduce(
                (sum, child) =>
                  sum +
                  (Number.isInteger(child.quantity) && !child.hasQuantityError && !child.hasProductError
                    ? child.quantity
                    : 0),
                0
              )
            ),
            distinctUntilChanged()
          )
        )
      )
    );
 
    this.connect(
      'hasProductError',
      this.select('product').pipe(
        map(product => !!product && (!!product.failed || !product.available)),
        distinctUntilChanged()
      )
    );
 
    this.connect(
      'hasProductError',
      this.select('sku').pipe(
        whenTruthy(),
        distinctUntilChanged(),
        switchMap(() =>
          this.select('children').pipe(
            map(children => Object.values(children)),
            debounceTime(300),
            skipWhile(children => !children?.length),
            map(children => !children.length || children.some(child => child.hasProductError)),
            distinctUntilChanged()
          )
        )
      )
    );
 
    this.connect(
      'label',
      this.select('product').pipe(
        map(
          product =>
            // eslint-disable-next-line unicorn/no-null
            ProductHelper.getAttributesOfGroup(product, AttributeGroupTypes.ProductLabelAttributes)?.[0]?.name || null
        ),
        distinctUntilChanged()
      )
    );
 
    const externalDisplayPropertyProviders = [
      injector.get(ProductContextDisplayPropertiesService),
      ...injector.get<ExternalDisplayPropertiesProvider[]>(EXTERNAL_DISPLAY_PROPERTY_PROVIDER, []),
    ].map(edp =>
      edp.setup(
        this.select().pipe(
          map(context => pick(context, 'product', 'prices')),
          distinctUntilChanged(isEqual)
        )
      )
    );
 
    const internalDisplayProperty$ = combineLatest([this.select('product'), this.privateConfig$]).pipe(
      map(([product, privateConfig]) =>
        Object.entries(defaultDisplayProperties)
          .map(([k, v]: [keyof ProductContextDisplayProperties, DisplayEval]) => [k, privateConfig?.[k] ?? v])
          .reduce<Partial<ProductContextDisplayProperties>>(
            (acc, [k, v]: [keyof ProductContextDisplayProperties, DisplayEval]) => {
              acc[k] = typeof v === 'function' ? v(product) : v;
              return acc;
            },
            {}
          )
      )
    );
 
    this.connect('displayProperties', this.privateConfig$);
 
    this.connect(
      'displayProperties',
      combineLatest([internalDisplayProperty$, ...externalDisplayPropertyProviders]).pipe(
        map(props => props.reduce((acc, p) => ({ ...acc, ...p }), {}))
      )
    );
 
    // set display properties for a parent context
    this.connect(
      'displayProperties',
      race(
        this.select('children').pipe(
          skipWhile(children => !children || !Object.values(children)?.length),
          map(() => true)
        ),
        this.select().pipe(
          map(context => context.parts),
          skipWhile(parts => !parts?.length),
          map(() => true)
        ),
        this.select('sku').pipe(map(() => false))
      ).pipe(take(1)),
      (state, setStandaloneProperties) =>
        setStandaloneProperties
          ? {
              ...state.displayProperties,
              readOnly: state.displayProperties.readOnly ?? true,
              addToBasket: state.displayProperties.addToBasket ?? true,
            }
          : state.displayProperties
    );
  }
 
  private get isMaximumLevel(): boolean {
    return (
      this.get('requiredCompletenessLevel') === ProductCompletenessLevel.Detail ||
      this.get('requiredCompletenessLevel') === true
    );
  }
 
  private postProductFetch(product: ProductView, displayProperties: Partial<ProductContextDisplayProperties>) {
    if (
      (ProductHelper.isRetailSet(product) || ProductHelper.isMasterProduct(product)) &&
      displayProperties.price &&
      !this.isMaximumLevel
    ) {
      this.set('requiredCompletenessLevel', () => ProductCompletenessLevel.Detail);
    }
  }
 
  select(): Observable<ProductContext>;
  select<K1 extends keyof ProductContext>(k1: K1): Observable<ProductContext[K1]>;
  select<K1 extends keyof ProductContext, K2 extends keyof ProductContext[K1]>(
    k1: K1,
    k2: K2
  ): Observable<ProductContext[K1][K2]>;
 
  select<K1 extends keyof ProductContext, K2 extends keyof ProductContext[K1]>(k1?: K1, k2?: K2) {
    const wrap = <K extends keyof ProductContext>(key: K, obs: Observable<ProductContext[K]>) => {
      if (!this.lazyFieldsInitialized.includes(key)) {
        this.connect(key, obs);
        this.lazyFieldsInitialized.push(key);
      }
    };
 
    switch (k1) {
      case 'variations':
        wrap('variations', this.shoppingFacade.productVariations$(this.masterProductSKU$));
        break;
      case 'variationCount':
        wrap('variationCount', this.shoppingFacade.productVariationCount$(this.validProductSKU$));
        break;
      case 'productMaster':
        wrap(
          'productMaster',
          this.shoppingFacade
            .product$(this.masterProductSKU$, ProductCompletenessLevel.List)
            .pipe(filter(ProductHelper.isMasterProduct))
        );
      case 'links':
        wrap('links', this.shoppingFacade.productLinks$(this.validProductSKU$));
        break;
      case 'promotions':
        wrap(
          'promotions',
          combineLatest([this.select('displayProperties', 'promotions'), this.select('product', 'promotionIds')]).pipe(
            filter(([visible]) => !!visible),
            switchMap(([, ids]) => this.shoppingFacade.promotions$(ids))
          )
        );
        break;
      case 'parts':
        wrap(
          'parts',
          combineLatest([
            this.select('displayProperties', 'bundleParts'),
            this.select('displayProperties', 'retailSetParts'),
          ]).pipe(
            filter(([a, b]) => a || b),
            switchMap(() => this.shoppingFacade.productParts$(this.validProductSKU$))
          )
        );
        break;
      case 'prices':
        wrap(
          'prices',
          combineLatest([
            this.select('displayProperties', 'price'),
            this.select('product').pipe(
              filter(p => !!p && !p.failed),
              mapToProperty('sku'),
              distinctUntilChanged()
            ),
            this.select('requiredCompletenessLevel').pipe(
              map(completeness => completeness === true),
              distinctUntilChanged()
            ),
          ]).pipe(
            filter(([visible]) => !!visible),
            switchMap(([, sku, fresh]) => this.shoppingFacade.productPrices$(sku, fresh))
          )
        );
        break;
    }
    return k2 ? super.select(k1, k2) : k1 ? super.select(k1) : super.select();
  }
 
  log(val: boolean) {
    Iif (!this.loggingActive) {
      this.hold(this.select().pipe(filter(() => !!val)), ctx => {
        // eslint-disable-next-line no-console
        console.log(ctx);
      });
    }
  }
 
  changeVariationOption(name: string, value: string) {
    this.set('sku', () =>
      ProductVariationHelper.findPossibleVariation(name, value, this.get('product'), this.get('variations'))
    );
  }
 
  addToBasket() {
    let items: SkuQuantityType[];
    if (Object.values(this.get('children'))?.length) {
      items = Object.values(this.get('children'));
    } else if (this.get('parts')?.length && !ProductHelper.isProductBundle(this.get('product'))) {
      items = this.get('parts');
    } else {
      items = [this.get()];
    }
 
    items
      .filter(x => !!x && !!x.quantity)
      .forEach(child => {
        this.shoppingFacade.addProductToBasket(child.sku, child.quantity, this.get('selectedWarranty'));
      });
  }
 
  validDebouncedQuantityUpdate$(time = 800) {
    return this.select('quantity').pipe(
      debounceTime(time),
      filter(() => !this.get('hasQuantityError')),
      distinctUntilChanged(),
      skip(1)
    );
  }
 
  getProductImage$(imageType: string, imageView: string): Observable<Image> {
    return this.select('product').pipe(
      whenTruthy(),
      map(product =>
        imageView
          ? ProductHelper.getImageByImageTypeAndImageView(product, imageType, imageView)
          : ProductHelper.getPrimaryImage(product, imageType)
      )
    );
  }
 
  setSelectedWarranty(selectedWarranty: string) {
    this.set('selectedWarranty', () => selectedWarranty);
  }
 
  ngOnDestroy(): void {
    if (this.get('propagateActive')) {
      this.set('propagateActive', () => false);
    }
    super.ngOnDestroy();
  }
}