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

32.69% Statements 17/52
48.38% Branches 15/31
18.18% Functions 2/11
32.69% Lines 17/52

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 168102x 102x 102x   102x   102x           102x   102x 102x 102x       102x   2x 2x 2x 2x 2x     2x                     1x                                                                                                                                                                                                                                                              
import { DOCUMENT } from '@angular/common';
import { HttpHeaders } from '@angular/common/http';
import { Inject, Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
 
import { ContentConfigurationParameterMapper } from 'ish-core/models/content-configuration-parameter/content-configuration-parameter.mapper';
import { ContentPageletEntryPointData } from 'ish-core/models/content-pagelet-entry-point/content-pagelet-entry-point.interface';
import {
  CustomFieldDefinitionEntities,
  CustomFieldDefinitions,
} from 'ish-core/models/custom-field-definition/custom-field-definition.model';
import { ServerConfigMapper } from 'ish-core/models/server-config/server-config.mapper';
import { ServerConfig } from 'ish-core/models/server-config/server-config.model';
import { ApiService } from 'ish-core/services/api/api.service';
import { LocalizationsService } from 'ish-core/services/localizations/localizations.service';
import { DomService } from 'ish-core/utils/dom/dom.service';
import { Translations } from 'ish-core/utils/translate/translations.type';
 
@Injectable({ providedIn: 'root' })
export class ConfigurationService {
  constructor(
    private apiService: ApiService,
    private domService: DomService,
    private localizationService: LocalizationsService,
    private contentConfigurationParameterMapper: ContentConfigurationParameterMapper,
    @Inject(DOCUMENT) private document: Document
  ) {}
 
  private configHeaders = new HttpHeaders({
    'content-type': 'application/json',
    Accept: 'application/vnd.intershop.configuration.v1+json',
  });
 
  /**
   * Gets the ICM configuration parameters.
   *
   * @returns           The configuration object.
   */
  getServerConfiguration(): Observable<[ServerConfig, CustomFieldDefinitions]> {
    return this.apiService
      .get(`configurations`, {
        headers: this.configHeaders,
        sendLocale: false,
        sendCurrency: false,
      })
      .pipe(map(ServerConfigMapper.fromData));
  }
 
  /**
   * Retrieves and transforms custom field translations for a specified language.
   *
   * @param lang - The language code for which to fetch translations.
   * @param existingEntities - The existing custom field definition entities to be transformed.
   * @returns An Observable emitting the transformed custom field definitions with applied translations.
   */
  getCustomFieldsTranslations(lang: string, existingEntities: CustomFieldDefinitionEntities) {
    return this.localizationService
      .getServerTranslations(lang, 'customfield.')
      .pipe(map(translations => this.updateCustomDefinitionTranslations(translations, existingEntities)));
  }
 
  /**
   * Gets additional storefront configuration parameters managed via CMS configuration include.
   *
   * @returns           The configuration object.
   */
  getExtraConfiguration(): Observable<ServerConfig> {
    return this.apiService
      .get<ContentPageletEntryPointData>(`cms/includes/include.configuration.pagelet2-Include`, {
        skipApiErrorHandling: true,
        sendPGID: true,
        sendLocale: true,
        sendCurrency: false,
      })
      .pipe(
        map(data =>
          data?.pagelets?.length
            ? (this.contentConfigurationParameterMapper.fromData(
                data?.pagelets[0].configurationParameters
              ) as ServerConfig)
            : undefined
        )
      );
  }
 
  /**
   * Sets the theme configuration from additional storefront configuration parameters.
   */
  setThemeConfiguration(config: ServerConfig) {
    // Logo
    Iif (config?.Logo) {
      this.domService.setCssCustomProperty('logo', `url(${config.Logo.toString()})`);
    }
 
    // Logo Mobile
    Iif (config?.LogoMobile) {
      this.domService.setCssCustomProperty('logo-mobile', `url(${config.LogoMobile.toString()})`);
    }
 
    // Favicon
    Iif (config?.Favicon) {
      this.domService.setAttributeForSelector('link[rel="icon"]', 'href', config.Favicon.toString());
    }
 
    // CSS Custom Properties
    Iif (config?.CSSProperties) {
      config.CSSProperties.toString()
        .split(/\r?\n/)
        .filter(Boolean)
        .forEach(property => {
          const propertyKeyValue = property.split(':');
          this.domService.setCssCustomProperty(propertyKeyValue[0].trim(), propertyKeyValue[1].trim());
        });
    }
 
    // CSS Fonts embedding
    Iif (config?.CSSFonts) {
      config.CSSFonts.toString()
        .split(/\r?\n/)
        .filter(Boolean)
        .forEach(font => {
          const link = this.domService.createElement<HTMLLinkElement>('link', this.document.head);
          this.domService.setProperty(link, 'rel', 'stylesheet');
          this.domService.setProperty(link, 'href', font.toString());
        });
    }
 
    // CSS File
    Iif (config?.CSSFile) {
      const link = this.domService.createElement<HTMLLinkElement>('link', this.document.head);
      this.domService.setProperty(link, 'rel', 'stylesheet');
      this.domService.setProperty(link, 'href', config.CSSFile.toString());
    }
 
    // CSS Styling
    Iif (config?.CSSStyling) {
      const style = this.domService.createElement<HTMLStyleElement>('style', this.document.head);
      this.domService.createTextNode(config.CSSStyling.toString(), style);
    }
  }
 
  private updateCustomDefinitionTranslations(
    translations: Translations,
    existingEntities: CustomFieldDefinitionEntities
  ): CustomFieldDefinitionEntities {
    const updatedEntities = { ...existingEntities };
 
    Object.entries(translations).forEach(([fullKey, value]) => {
      // Split key into field and property, e.g. 'commissionNumber.description'
      const match = fullKey.match(/^([^.:]+)[.:](.+)$/);
      Iif (!match) {
        return;
      }
      const [, fieldKey, property] = match;
 
      Iif (updatedEntities[fieldKey]) {
        updatedEntities[fieldKey] = {
          ...updatedEntities[fieldKey],
          [property]: value,
        };
      }
    });
 
    return updatedEntities;
  }
}