All files / src/app/core/models/product product.mapper.ts

81.25% Statements 52/64
78.78% Branches 52/66
68.18% Functions 15/22
83.6% Lines 51/61

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 26427x   27x   27x   27x 27x   27x 27x 27x                   209x             32x             4x             27x   49x 49x 49x 49x       17x 17x 17x               3x 2x     3x       2x                                                                                                     14x 14x 1x   13x   13x   13x                                                 13x           19x                                                             19x       32x             3x             13x 13x 13x 13x   13x         13x           13x           13x         19x 2x         17x 1x           16x 2x       14x 1x         13x        
import { Injectable } from '@angular/core';
 
import { AttachmentMapper } from 'ish-core/models/attachment/attachment.mapper';
import { AttributeGroup } from 'ish-core/models/attribute-group/attribute-group.model';
import { AttributeHelper } from 'ish-core/models/attribute/attribute.helper';
import { CategoryData } from 'ish-core/models/category/category.interface';
import { CategoryMapper } from 'ish-core/models/category/category.mapper';
import { ImageMapper } from 'ish-core/models/image/image.mapper';
import { Link } from 'ish-core/models/link/link.model';
import { VariationAttributeMapper } from 'ish-core/models/product-variation/variation-attribute.mapper';
import { SeoAttributesMapper } from 'ish-core/models/seo-attributes/seo-attributes.mapper';
import { WarrantyMapper } from 'ish-core/models/warranty/warranty.mapper';
 
import { SkuQuantityType } from './product.helper';
import { ProductData, ProductDataStub, ProductVariationLink } from './product.interface';
import { AllProductTypes, Product, VariationProduct, VariationProductMaster } from './product.model';
 
/**
 * check if attribute is available and return value, otherwise undefined
 */
function retrieveStubAttributeValue<T>(data: ProductDataStub, attributeName: string) {
  return data ? AttributeHelper.getAttributeValueByAttributeName<T>(data.attributes, attributeName) : undefined;
}
 
/**
 * maps promotion links data to a string array of promotion ids
 */
function mapPromotionIds(data: Link[]): string[] {
  return data ? data.map(promotionLink => promotionLink.itemId) : [];
}
 
/**
 * maps an attribute group and its attribute data to the same format as it is used in a single product call
 */
function mapAttributeGroups(data: ProductDataStub): { [id: string]: AttributeGroup } {
  return { [data.attributeGroup.name]: { attributes: data.attributeGroup.attributes } };
}
 
/**
 * Product Mapper maps data of HTTP requests to model instances and vice versa.
 */
@Injectable({ providedIn: 'root' })
export class ProductMapper {
  constructor(
    private imageMapper: ImageMapper,
    private attachmentMapper: AttachmentMapper,
    private categoryMapper: CategoryMapper,
    private variationAttributeMapper: VariationAttributeMapper
  ) {}
 
  static parseSkuFromURI(uri: string): string {
    const match = /products[^\/]*\/([^\?]*)/.exec(uri);
    if (match) {
      return match[1];
    } else E{
      console.warn(`could not find sku in uri '${uri}'`);
      return;
    }
  }
 
  static findDefaultVariation(variationLinks: Link[]): string {
    const defaultVariation = variationLinks.find(variation =>
      AttributeHelper.getAttributeValueByAttributeName<boolean>(variation.attributes, 'defaultVariation')
    );
 
    return defaultVariation ? ProductMapper.parseSkuFromURI(defaultVariation.uri) : undefined;
  }
 
  static constructMasterStub(sku: string, variations: Partial<VariationProduct>[]): Partial<VariationProductMaster> {
    return variations?.length
      ? {
          type: 'VariationProductMaster',
          sku,
          completenessLevel: 0,
          variationAttributeValues: variations
            .map(v => v.variableVariationAttributes)
            .flat()
            .filter(
              (val, idx, arr) =>
                arr.findIndex(el => el.variationAttributeId === val.variationAttributeId && el.value === val.value) ===
                idx
            ),
        }
      : undefined;
  }
 
  fromLink(link: Link): Partial<Product> {
    return {
      sku: ProductMapper.parseSkuFromURI(link.uri),
      name: link.title,
      shortDescription: link.description,
      type: 'Product',
      completenessLevel: 1,
    };
  }
 
  fromVariationLink(link: ProductVariationLink, productMasterSKU: string): Partial<VariationProduct> {
    return {
      ...this.fromLink(link),
      variableVariationAttributes: this.variationAttributeMapper.fromData(
        link.variableVariationAttributeValuesExtended
      ),
      productMasterSKU,
      type: 'VariationProduct',
      failed: false,
    };
  }
 
  fromRetailSetLink(link: Link): Partial<Product> {
    return {
      sku: ProductMapper.parseSkuFromURI(link.uri),
      name: link.title,
      shortDescription: link.description,
      completenessLevel: 1,
    };
  }
  /**
   * construct a {@link Product} stub from data returned by link list responses with additional data
   */
  fromStubData(data: ProductDataStub): Partial<AllProductTypes> {
    const sku = retrieveStubAttributeValue<string>(data, 'sku');
    if (!sku) {
      throw new Error('cannot construct product stub without SKU');
    }
    const productCategory = retrieveStubAttributeValue<CategoryData>(data, 'defaultCategory');
 
    const promotionLinks = retrieveStubAttributeValue<{ elements: Link[] }>(data, 'promotions')?.elements ?? [];
 
    const product: Partial<Product> = {
      shortDescription: data.description,
      name: data.title,
      sku,
      images: this.imageMapper.fromImageUrl(retrieveStubAttributeValue(data, 'image')),
      manufacturer: retrieveStubAttributeValue(data, 'manufacturer'),
      available: this.calculateAvailable(
        retrieveStubAttributeValue(data, 'availability'),
        retrieveStubAttributeValue(data, 'inStock')
      ),
      longDescription: undefined,
      minOrderQuantity: retrieveStubAttributeValue<{ value: number }>(data, 'minOrderQuantity')?.value,
      maxOrderQuantity: retrieveStubAttributeValue<{ value: number }>(data, 'maxOrderQuantity')?.value,
      stepQuantity: retrieveStubAttributeValue<{ value: number }>(data, 'stepQuantity')?.value,
      packingUnit: retrieveStubAttributeValue(data, 'packingUnit'),
      attributeGroups: data.attributeGroup && mapAttributeGroups(data),
      readyForShipmentMin: undefined,
      readyForShipmentMax: undefined,
      roundedAverageRating: +retrieveStubAttributeValue<string>(data, 'roundedAverageRating') || 0,
      type: 'Product',
      defaultCategoryId: productCategory ? this.categoryMapper.fromDataSingle(productCategory).uniqueId : undefined,
      promotionIds: mapPromotionIds(promotionLinks),
      completenessLevel: 2,
      failed: false,
    };
    return this.appendProductTypeForStubData(data, product);
  }
  /**
   * map API Response to fully qualified {@link Product}s
   */
  fromData(data: ProductData): AllProductTypes {
    const product: Product = {
      type: 'Product',
      name: data.productName,
      shortDescription: data.shortDescription,
      longDescription: data.longDescription,
      available: this.calculateAvailable(data.availability, data.inStock),
      minOrderQuantity: data.minOrderQuantity,
      maxOrderQuantity: data.maxOrderQuantity,
      stepQuantity: data.stepOrderQuantity,
      packingUnit: data.packingUnit,
      availableStock: data.availableStock,
      attributes: data.attributeGroups?.PRODUCT_DETAIL_ATTRIBUTES?.attributes || data.attributes || [],
      attributeGroups: data.attributeGroups,
      attachments: this.attachmentMapper.fromAttachments(data.attachments),
      images: this.imageMapper.fromImages(data.images),
      manufacturer: data.manufacturer,
      readyForShipmentMin: data.readyForShipmentMin,
      readyForShipmentMax: data.readyForShipmentMax,
      roundedAverageRating: +data.roundedAverageRating || 0,
      numberOfReviews: data.numberOfReviews || 0,
      sku: data.sku,
      defaultCategoryId: data.defaultCategory
        ? this.categoryMapper.fromDataSingle(data.defaultCategory).uniqueId
        : undefined,
      promotionIds: mapPromotionIds(data.promotions),
      completenessLevel: 3,
      failed: false,
      seoAttributes: SeoAttributesMapper.fromData(data.seoAttributes),
      availableWarranties: WarrantyMapper.fromLinkData(data.availableWarranties),
    };
 
    return this.appendProductTypeForData(data, product);
  }
 
  private calculateAvailable(availability: boolean, inStock: boolean) {
    return !!availability && (inStock !== undefined ? inStock : true);
  }
 
  /**
   * map product bundle API Response to a link / quantity type
   */
  fromProductBundleData(links: Link[]): SkuQuantityType[] {
    return links.map(link => ({
      sku: ProductMapper.parseSkuFromURI(link.uri),
      quantity: AttributeHelper.getAttributeValueByAttributeName<{ value: number }>(link.attributes, 'quantity').value,
    }));
  }
 
  private appendProductTypeForStubData(data: ProductDataStub, product: Partial<Product>): Partial<AllProductTypes> {
    const mastered = retrieveStubAttributeValue<boolean>(data, 'mastered');
    const productMaster = retrieveStubAttributeValue<boolean>(data, 'productMaster');
    const productMasterSKU = retrieveStubAttributeValue<string>(data, 'productMasterSKU');
    const retailSet = retrieveStubAttributeValue<boolean>(data, 'retailSet');
 
    Iif (productMaster) {
      return {
        ...product,
        type: 'VariationProductMaster',
      };
    } else Iif (mastered) {
      return {
        ...product,
        productMasterSKU,
        type: 'VariationProduct',
      };
    } else Iif (retailSet) {
      return {
        ...product,
        type: 'RetailSet',
      };
    } else {
      return product;
    }
  }
 
  private appendProductTypeForData(data: ProductData, product: Product): AllProductTypes {
    if (data.productMaster) {
      return {
        ...product,
        variationAttributeValues: this.variationAttributeMapper.fromMasterData(data.variationAttributeValuesExtended),
        type: 'VariationProductMaster',
      };
    } else if (data.mastered) {
      return {
        ...product,
        productMasterSKU: data.productMasterSKU,
        variableVariationAttributes: this.variationAttributeMapper.fromData(data.variationAttributeValuesExtended),
        type: 'VariationProduct',
      };
    } else if (data.productTypes?.includes('BUNDLE') || data.productBundle) {
      return {
        ...product,
        type: 'Bundle',
      };
    } else if (data.retailSet) {
      return {
        ...product,
        type: 'RetailSet',
      };
    } else {
      return product;
    }
  }
}