All files / src/app/core/services/products products.service.ts

67.67% Statements 67/99
42.18% Branches 27/64
63.82% Functions 30/47
73.03% Lines 65/89

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 36526x 26x 26x 26x 26x   26x 26x 26x         26x 26x             26x 26x 26x 26x   26x           26x 10x                 1x       1x 1x   1x                                 1x       1x             1x       1x               1x 2x             1x                                           1x       1x             1x       1x                                                                                                                                   1x           1x     1x   1x       1x             1x 2x             1x                       2x         2x                     2x       2x   2x                   2x       1x 1x 1x   3x   3x                     1x     2x       2x                 1x     1x   1x                     1x       1x       1x           2x     2x 2x         3x       1x                    
import { HttpParams } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { range } from 'lodash-es';
import { Observable, from, identity, of, throwError } from 'rxjs';
import { defaultIfEmpty, map, mergeMap, switchMap, toArray, withLatestFrom } from 'rxjs/operators';
 
import { AppFacade } from 'ish-core/facades/app.facade';
import { AttributeGroupTypes } from 'ish-core/models/attribute-group/attribute-group.types';
import { CategoryHelper } from 'ish-core/models/category/category.model';
import { Link } from 'ish-core/models/link/link.model';
import { ProductLinksDictionary } from 'ish-core/models/product-links/product-links.model';
import { SortableAttributesType } from 'ish-core/models/product-listing/product-listing.model';
import { ProductData, ProductDataStub, ProductVariationLink } from 'ish-core/models/product/product.interface';
import { ProductMapper } from 'ish-core/models/product/product.mapper';
import {
  Product,
  ProductHelper,
  SkuQuantityType,
  VariationProduct,
  VariationProductMaster,
} from 'ish-core/models/product/product.model';
import { ApiService, unpackEnvelope } from 'ish-core/services/api/api.service';
import { omit } from 'ish-core/utils/functions';
import { mapToProperty } from 'ish-core/utils/operators';
import { URLFormParams, appendFormParamsToHttpParams } from 'ish-core/utils/url-form-params';
 
import STUB_ATTRS from './products-list-attributes';
 
/**
 * The Products Service handles the interaction with the 'products' REST API.
 */
@Injectable({ providedIn: 'root' })
export class ProductsService {
  constructor(private apiService: ApiService, private productMapper: ProductMapper, private appFacade: AppFacade) {}
 
  /**
   * Get the full Product data for the given Product SKU.
   *
   * @param sku  The Product SKU for the product of interest.
   * @returns    The Product data.
   */
  getProduct(sku: string): Observable<Product> {
    Iif (!sku) {
      return throwError(() => new Error('getProduct() called without a sku'));
    }
 
    const params = new HttpParams().set('allImages', true).set('extended', true);
    return this.apiService
      .get<ProductData>(`products/${this.apiService.encodeResourceId(sku)}`, { sendSPGID: true, params })
      .pipe(map(element => this.productMapper.fromData(element)));
  }
 
  /**
   * Get a sorted list of all products (as SKU list) assigned to a given Category respecting pagination.
   *
   * @param categoryUniqueId  The unique Category ID.
   * @param page              The page to request (1-based numbering)
   * @param sortKey           The sortKey to sort the list, default value is ''.
   * @returns                 A list of the categories products SKUs [skus], the unique Category ID [categoryUniqueId] and a list of possible sort keys [sortKeys].
   */
  getCategoryProducts(
    categoryUniqueId: string,
    amount: number,
    sortKey?: string,
    offset = 0
  ): Observable<{ products: Product[]; sortableAttributes: SortableAttributesType[]; total: number }> {
    Iif (!categoryUniqueId) {
      return throwError(() => new Error('getCategoryProducts() called without categoryUniqueId'));
    }
 
    let params = new HttpParams()
      .set('attrs', STUB_ATTRS)
      .set('attributeGroup', AttributeGroupTypes.ProductLabelAttributes)
      .set('amount', amount.toString())
      .set('offset', offset.toString())
      .set('returnSortKeys', 'true')
      .set('productFilter', 'fallback_searchquerydefinition');
    Iif (sortKey && sortKey !== 'default') {
      params = params.set('sortKey', sortKey);
    }
 
    return this.apiService
      .get<{
        elements: ProductDataStub[];
        sortableAttributes: { [id: string]: SortableAttributesType };
        categoryUniqueId: string;
        total: number;
      }>(`categories/${CategoryHelper.getCategoryPath(categoryUniqueId)}/products`, { sendSPGID: true, params })
      .pipe(
        map(response => ({
          products: response.elements.map((element: ProductDataStub) => this.productMapper.fromStubData(element)),
          sortableAttributes: Object.values(response.sortableAttributes || {}),
          total: response.total ? response.total : response.elements.length,
        })),
        withLatestFrom(
          this.appFacade.serverSetting$<boolean>('preferences.ChannelPreferences.EnableAdvancedVariationHandling')
        ),
        map(([{ products, sortableAttributes, total }, advancedVariationHandling]) => ({
          products: this.postProcessMasters(products, advancedVariationHandling),
          sortableAttributes,
          total,
        }))
      );
  }
 
  /**
   * Get products for a given search term respecting pagination.
   *
   * @param searchTerm    The search term to look for matching products.
   * @param page          The page to request (1-based numbering)
   * @param sortKey       The sortKey to sort the list, default value is ''.
   * @returns             A list of matching Product stubs with a list of possible sort keys and the total amount of results.
   */
  searchProducts(
    searchTerm: string,
    amount: number,
    sortKey?: string,
    offset = 0
  ): Observable<{ products: Product[]; sortableAttributes: SortableAttributesType[]; total: number }> {
    Iif (!searchTerm) {
      return throwError(() => new Error('searchProducts() called without searchTerm'));
    }
 
    let params = new HttpParams()
      .set('searchTerm', searchTerm)
      .set('amount', amount.toString())
      .set('offset', offset.toString())
      .set('attrs', STUB_ATTRS)
      .set('attributeGroup', AttributeGroupTypes.ProductLabelAttributes)
      .set('returnSortKeys', 'true');
    Iif (sortKey && sortKey !== 'default') {
      params = params.set('sortKey', sortKey);
    }
 
    return this.apiService
      .get<{
        elements: ProductDataStub[];
        sortKeys: string[];
        sortableAttributes: { [id: string]: SortableAttributesType };
        total: number;
      }>('products', { sendSPGID: true, params })
      .pipe(
        map(response => ({
          products: response.elements.map(element => this.productMapper.fromStubData(element)),
          sortableAttributes: Object.values(response.sortableAttributes || {}),
          total: response.total ? response.total : response.elements.length,
        })),
        withLatestFrom(
          this.appFacade.serverSetting$<boolean>('preferences.ChannelPreferences.EnableAdvancedVariationHandling')
        ),
        map(([{ products, sortableAttributes, total }, advancedVariationHandling]) => ({
          products: this.postProcessMasters(products, advancedVariationHandling),
          sortableAttributes,
          total,
        }))
      );
  }
 
  getProductsForMaster(
    masterSKU: string,
    amount: number,
    sortKey?: string,
    offset = 0
  ): Observable<{ products: Product[]; sortableAttributes: SortableAttributesType[]; total: number }> {
    Iif (!masterSKU) {
      return throwError(() => new Error('getProductsForMaster() called without masterSKU'));
    }
 
    let params = new HttpParams()
      .set('MasterSKU', masterSKU)
      .set('amount', amount.toString())
      .set('offset', offset.toString())
      .set('attrs', STUB_ATTRS)
      .set('attributeGroup', AttributeGroupTypes.ProductLabelAttributes)
      .set('returnSortKeys', 'true');
    Iif (sortKey && sortKey !== 'default') {
      params = params.set('sortKey', sortKey);
    }
 
    return this.apiService
      .get<{
        elements: ProductDataStub[];
        sortableAttributes: { [id: string]: SortableAttributesType };
        total: number;
      }>('products', { sendSPGID: true, params })
      .pipe(
        map(response => ({
          products: response.elements.map(element => this.productMapper.fromStubData(element)) as Product[],
          sortableAttributes: Object.values(response.sortableAttributes || {}),
          total: response.total ? response.total : response.elements.length,
        }))
      );
  }
 
  getFilteredProducts(
    searchParameter: URLFormParams,
    amount: number,
    sortKey?: string,
    offset = 0
  ): Observable<{ total: number; products: Partial<Product>[]; sortableAttributes: SortableAttributesType[] }> {
    let params = new HttpParams()
      .set('amount', amount ? amount.toString() : '')
      .set('offset', offset.toString())
      .set('attrs', STUB_ATTRS)
      .set('attributeGroup', AttributeGroupTypes.ProductLabelAttributes)
      .set('returnSortKeys', 'true');
    Iif (sortKey && sortKey !== 'default') {
      params = params.set('sortKey', sortKey);
    }
    params = appendFormParamsToHttpParams(omit(searchParameter, 'category'), params);
 
    const resource = searchParameter.category
      ? `categories/${this.apiService.encodeResourceId(searchParameter.category[0])}/products`
      : 'products';
 
    return this.apiService
      .get<{
        total: number;
        elements: ProductDataStub[];
        sortableAttributes: { [id: string]: SortableAttributesType };
      }>(resource, { params, sendSPGID: true })
      .pipe(
        map(x => ({
          products: x.elements.map(stub => this.productMapper.fromStubData(stub)),
          total: x.total,
          sortableAttributes: Object.values(x.sortableAttributes || {}),
        })),
        withLatestFrom(
          this.appFacade.serverSetting$<boolean>('preferences.ChannelPreferences.EnableAdvancedVariationHandling')
        ),
        map(([{ products, sortableAttributes, total }, advancedVariationHandling]) => ({
          products: params.has('MasterSKU') ? products : this.postProcessMasters(products, advancedVariationHandling),
          sortableAttributes,
          total,
        }))
      );
  }
 
  /**
   * exchange single-return variation products to master products for B2B
   */
  private postProcessMasters(products: Partial<Product>[], advancedVariationHandling: boolean): Product[] {
    Iif (advancedVariationHandling) {
      return products.map(p =>
        ProductHelper.isVariationProduct(p) ? { sku: p.productMasterSKU, completenessLevel: 0 } : p
      ) as Product[];
    }
    return products as Product[];
  }
 
  /**
   * Get product variations for the given master product sku.
   */
  getProductVariations(sku: string): Observable<{
    products: Partial<VariationProduct>[];
    defaultVariation: string;
    masterProduct: Partial<VariationProductMaster>;
  }> {
    Iif (!sku) {
      return throwError(() => new Error('getProductVariations() called without a sku'));
    }
 
    const params = new HttpParams().set('extended', true);
 
    return this.apiService
      .get<{ elements: Link[]; total: number; amount: number }>(
        `products/${this.apiService.encodeResourceId(sku)}/variations`,
        {
          sendSPGID: true,
          params,
        }
      )
      .pipe(
        switchMap(resp =>
          !resp.total
            ? of(resp.elements)
            : of(resp).pipe(
                mergeMap(res => {
                  const amount = res.amount;
                  const chunks = Math.ceil((res.total - amount) / amount);
                  return from(
                    range(1, chunks + 1)
                      .map(i => [i * amount, Math.min(amount, res.total - amount * i)])
                      .map(([offset, length]) =>
                        this.apiService
                          .get<{ elements: Link[] }>(`products/${this.apiService.encodeResourceId(sku)}/variations`, {
                            sendSPGID: true,
                            params: params.set('amount', length).set('offset', offset),
                          })
                          .pipe(mapToProperty('elements'))
                      )
                  );
                }),
                mergeMap(identity, 2),
                toArray(),
                map(resp2 => [...resp.elements, ...resp2.flat()])
              )
        ),
        map((links: ProductVariationLink[]) => ({
          products: links.map(link => this.productMapper.fromVariationLink(link, sku)),
          defaultVariation: ProductMapper.findDefaultVariation(links),
        })),
        map(data => ({ ...data, masterProduct: ProductMapper.constructMasterStub(sku, data.products) })),
        defaultIfEmpty({ products: [], defaultVariation: undefined, masterProduct: undefined })
      );
  }
 
  /**
   * get product bundle information for the given bundle sku.
   */
  getProductBundles(sku: string): Observable<{ stubs: Partial<Product>[]; bundledProducts: SkuQuantityType[] }> {
    Iif (!sku) {
      return throwError(() => new Error('getProductBundles() called without a sku'));
    }
    return this.apiService.get(`products/${this.apiService.encodeResourceId(sku)}/bundles`, { sendSPGID: true }).pipe(
      unpackEnvelope<Link>(),
      map(links => ({
        stubs: links.map(link => this.productMapper.fromLink(link)),
        bundledProducts: this.productMapper.fromProductBundleData(links),
      }))
    );
  }
 
  /**
   * get product retail set information for the given retail set sku.
   */
  getRetailSetParts(sku: string): Observable<Partial<Product>[]> {
    Iif (!sku) {
      return throwError(() => new Error('getRetailSetParts() called without a sku'));
    }
 
    return this.apiService
      .get(`products/${this.apiService.encodeResourceId(sku)}/partOfRetailSet`, { sendSPGID: true })
      .pipe(
        unpackEnvelope<Link>(),
        map(links => links.map(link => this.productMapper.fromRetailSetLink(link))),
        defaultIfEmpty([])
      );
  }
 
  getProductLinks(sku: string): Observable<ProductLinksDictionary> {
    return this.apiService.get(`products/${this.apiService.encodeResourceId(sku)}/links`, { sendSPGID: true }).pipe(
      unpackEnvelope<{ linkType: string; categoryLinks: Link[]; productLinks: Link[] }>(),
      map(links =>
        links.reduce(
          (acc, link) => ({
            ...acc,
            [link.linkType]: {
              products: !link.productLinks
                ? []
                : link.productLinks.map(pl => pl.uri).map(ProductMapper.parseSkuFromURI),
              categories: !link.categoryLinks
                ? []
                : link.categoryLinks.map(cl =>
                    cl.uri.split('/categories/')[1].replace('/', CategoryHelper.uniqueIdSeparator)
                  ),
            },
          }),
          {}
        )
      )
    );
  }
}