All files / src/app/core/models/product-variation product-variation.helper.ts

93.93% Statements 62/66
81.08% Branches 30/37
100% Functions 38/38
93.22% Lines 55/59

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 218177x         177x           177x                 4x         4x 18x                 4x 38x             38x                   38x     4x   85x 18x                             4x         4x   20x 51x     6x               4x 3x 3x           1x       3x       7x 1x 6x 1x     5x 9x   8x   5x       5x 25x   25x     77x     34x                                   38x       38x 174x       38x       18x       20x 40x           78x         225x 630x             1316x       38x         639x       10x 30x       30x       6x 12x     12x      
import { groupBy } from 'lodash-es';
 
import { FilterNavigation } from 'ish-core/models/filter-navigation/filter-navigation.model';
import { ProductView } from 'ish-core/models/product-view/product-view.model';
import { VariationProduct, VariationProductMaster } from 'ish-core/models/product/product.model';
import { omit } from 'ish-core/utils/functions';
 
import { VariationAttribute } from './variation-attribute.model';
import { VariationOptionGroup } from './variation-option-group.model';
import { VariationSelectOption } from './variation-select-option.model';
 
export class ProductVariationHelper {
  /**
   * Build select value structure
   */
  static buildVariationOptionGroups(
    variationProduct: VariationProduct,
    productMaster: VariationProductMaster,
    variations: VariationProduct[]
  ): VariationOptionGroup[] {
    Iif (!variationProduct?.variableVariationAttributes?.length) {
      return [];
    }
 
    // transform currently selected variation attribute list to object with the attributeId as key
    const currentSettings = variationProduct.variableVariationAttributes.reduce<{ [id: string]: VariationAttribute }>(
      (acc, attr) => ({
        ...acc,
        [attr.variationAttributeId]: attr,
      }),
      {}
    );
 
    // transform all variation attribute values to selectOptions
    // each with information about alternative combinations and active status (active status comes from currently selected variation)
    const options: VariationSelectOption[] = (productMaster?.variationAttributeValues || [])
      .map(attr => ({
        label: ProductVariationHelper.toDisplayValue(attr.value),
        value: ProductVariationHelper.toValue(attr.value)?.toString(),
        type: attr.variationAttributeId,
        metaData: attr.metaData,
        active: ProductVariationHelper.isEqual(currentSettings?.[attr.variationAttributeId]?.value, attr.value),
      }))
      .map(option => ({
        ...option,
        alternativeCombination: ProductVariationHelper.alternativeCombinationCheck(
          option,
          variationProduct,
          variations
        ),
      }));
 
    // group options list by attributeId
    const groupedOptions = groupBy(options, option => option.type);
 
    // go through those groups and transform them to more complex objects
    return Object.keys(groupedOptions).map(attrId => {
      // we need to get one of the original attributes again here, because we lost the attribute name
      const attribute = productMaster.variationAttributeValues.find(a => a.variationAttributeId === attrId);
      return {
        id: attribute.variationAttributeId,
        label: attribute.name,
        attributeType: attribute.attributeType,
        options: groupedOptions[attrId],
      };
    });
  }
 
  static findPossibleVariation(
    name: string,
    value: string,
    product: ProductView,
    variations: VariationProduct[]
  ): string {
    const target = omit(
      ProductVariationHelper.simplifyVariableVariationAttributes(product.variableVariationAttributes),
      name
    );
 
    const candidates = variations
      .filter(variation =>
        variation.variableVariationAttributes.some(
          attr => attr.variationAttributeId === name && ProductVariationHelper.isEqual(attr.value, value)
        )
      )
      .map(variation => ({
        sku: variation.sku,
        opts: omit(
          ProductVariationHelper.simplifyVariableVariationAttributes(variation.variableVariationAttributes),
          name
        ),
      }));
 
    if (candidates.length) {
      return candidates.reduce((min, cur) =>
        ProductVariationHelper.difference(cur.opts, target) < ProductVariationHelper.difference(min.opts, target)
          ? cur
          : min
      ).sku;
    }
 
    return product.sku;
  }
 
  static hasDefaultVariation(product: ProductView): boolean {
    return product && !!product.defaultVariationSKU;
  }
 
  static productVariationCount(variations: VariationProduct[], filters: FilterNavigation): number {
    if (!variations?.length) {
      return 0;
    } else if (!filters?.filter) {
      return variations?.length;
    }
 
    const selectedFacets = filters.filter
      .map(filter => filter.facets.filter(facet => facet.selected).map(facet => facet.name))
      .flat()
      .map(selected => selected.split('='));
 
    Iif (!selectedFacets.length) {
      return variations?.length;
    }
 
    return variations
      .map(p => p.variableVariationAttributes)
      .filter(attrs =>
        attrs.every(
          attr =>
            // attribute is not selected
            !selectedFacets.find(([key]) => key === attr.variationAttributeId) ||
            // selection is variation
            selectedFacets.find(
              ([key, val]) => key === attr.variationAttributeId && ProductVariationHelper.isEqual(val, attr.value)
            )
        )
      ).length;
  }
 
  /**
   * Check specific option if perfect variant match is not existing.
   *
   * @param option  The select option to check.
   * @param product The given product containing the related product variations
   * @returns       Indicates if no perfect match is found.
   */
  private static alternativeCombinationCheck(
    option: VariationSelectOption,
    product: ProductView,
    variations: VariationProduct[]
  ): boolean {
    Iif (!product.variableVariationAttributes?.length) {
      return;
    }
 
    const comparisonAttributes = product.variableVariationAttributes.map(attribute =>
      attribute.variationAttributeId === option.type ? { ...attribute, value: option.value } : attribute
    );
 
    // check if the current product has the same attributes as the attributes to be compared
    if (
      ProductVariationHelper.variationAttributeArrayEquals(product.variableVariationAttributes, comparisonAttributes)
    ) {
      // perfect match found
      return false;
    }
 
    // check if one of the variation products has the same attributes as the attributes to be compared
    return !variations.some(variation =>
      ProductVariationHelper.variationAttributeArrayEquals(variation.variableVariationAttributes, comparisonAttributes)
    );
  }
 
  // determines whether both arrays have the same variation attributes
  private static variationAttributeArrayEquals(array1: VariationAttribute[], array2: VariationAttribute[]): boolean {
    return (
      Array.isArray(array1) &&
      Array.isArray(array2) &&
      array1.length === array2.length &&
      array1.every(val =>
        array2.find(
          attribute => attribute.name === val.name && ProductVariationHelper.isEqual(attribute.value, val.value)
        )
      )
    );
  }
 
  private static toValue(input: VariationAttribute['value']): string | number {
    return typeof input === 'object' ? input.value : input;
  }
 
  private static toDisplayValue(input: VariationAttribute['value']): string {
    return typeof input === 'object' ? `${input.value} ${input.unit}` : input.toString();
  }
 
  private static isEqual(obj1: VariationAttribute['value'], obj2: VariationAttribute['value']): boolean {
    // eslint-disable-next-line eqeqeq -- needed for comparison of string, integers and floats
    return ProductVariationHelper.toValue(obj1) == ProductVariationHelper.toValue(obj2);
  }
 
  private static simplifyVariableVariationAttributes(attrs: VariationAttribute[]): { [name: string]: string } {
    return attrs
      .map(attr => ({
        name: attr.variationAttributeId,
        value: attr.value,
      }))
      .reduce((acc, val) => ({ ...acc, [val.name]: val.value }), {});
  }
 
  private static difference(obj1: { [name: string]: string }, obj2: { [name: string]: string }): number {
    const keys = Object.keys(obj1);
    Iif (keys.length !== Object.keys(obj2).length || keys.some(k => Object.keys(obj2).indexOf(k) < 0)) {
      throw new Error("cannot calculate difference if objects don't have the same keys");
    }
    return keys.reduce((sum, key) => (obj1[key] !== obj2[key] ? sum + 1 : sum), 0);
  }
}