All files / src/app/extensions/tacton/services/tacton-self-service-api tacton-self-service-api.service.ts

44.89% Statements 22/49
47.61% Branches 10/21
33.33% Functions 8/24
43.75% Lines 21/48

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 1604x 4x 4x 4x 4x 4x   4x 4x         4x 4x     4x 4x   3x     2x             2x                     2x                   2x   2x           1x                                                               2x     2x                                                                                                                                  
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Store, select } from '@ngrx/store';
import { pick } from 'lodash-es';
import { EMPTY, Observable } from 'rxjs';
import { concatMap, first, map, withLatestFrom } from 'rxjs/operators';
 
import { getLoggedInCustomer, getLoggedInUser } from 'ish-core/store/customer/user';
import { whenTruthy } from 'ish-core/utils/operators';
 
import { TactonProductConfiguration } from '../../models/tacton-product-configuration/tacton-product-configuration.model';
import { TactonSavedConfiguration } from '../../models/tacton-saved-configuration/tacton-saved-configuration.model';
import { TactonSelfServiceApiConfiguration } from '../../models/tacton-self-service-api-configuration/tacton-self-service-api-configuration.model';
import { getCurrentProductConfiguration } from '../../store/product-configuration';
import { getNewExternalId, getSelfServiceApiConfiguration } from '../../store/tacton-config';
 
@Injectable({ providedIn: 'root' })
export class TactonSelfServiceApiService {
  private static FORM_URLENCODED_HEADERS = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
 
  constructor(private http: HttpClient, private store: Store) {}
 
  private apiConfig$(parameters?: { externalId?: string }) {
    return this.store.pipe(
      select(getSelfServiceApiConfiguration),
      whenTruthy(),
      first(),
      withLatestFrom(
        this.store.pipe(
          select(getNewExternalId),
          map(externalId => parameters?.externalId || externalId)
        )
      )
    );
  }
 
  private constructParameters(
    config: TactonSelfServiceApiConfiguration,
    externalId: string,
    parameters?: { [key: string]: string }
  ): string {
    return Object.keys(parameters || {})
      .filter(k => k !== 'externalId')
      .reduce(
        (acc, val) => acc.set(val, parameters[val]),
        new HttpParams().set('_key', config.apiKey).set('_externalId', externalId)
      )
      .toString();
  }
 
  private post<T>(resource: string, parameters?: { [key: string]: string }): Observable<T> {
    return this.apiConfig$(parameters).pipe(
      concatMap(([config, externalId]) =>
        this.http
          .post<T>(
            `${config.endPoint}/self-service-api/${resource}`,
            this.constructParameters(config, externalId, parameters),
            { headers: TactonSelfServiceApiService.FORM_URLENCODED_HEADERS }
          )
          .pipe(map(result => ({ ...result, externalId })))
      )
    );
  }
 
  private put<T>(resource: string, parameters?: { [key: string]: string }): Observable<T> {
    return this.apiConfig$(parameters).pipe(
      concatMap(([config, externalId]) =>
        this.http
          .put<T>(
            `${config.endPoint}/self-service-api/${resource}`,
            this.constructParameters(config, externalId, parameters),
            { headers: TactonSelfServiceApiService.FORM_URLENCODED_HEADERS }
          )
          .pipe(map(result => ({ ...result, externalId })))
      )
    );
  }
 
  private postConfig<T = TactonProductConfiguration>(
    resource: string,
    parameters?: { [key: string]: string }
  ): Observable<T> {
    return this.store.pipe(
      select(getCurrentProductConfiguration),
      whenTruthy(),
      first(),
      concatMap(config => this.post<T>(resource, { ...pick(config, 'configId', 'externalId'), ...parameters }))
    );
  }
 
  startConfiguration(productPath: string): Observable<TactonProductConfiguration> {
    Iif (!productPath) {
      return EMPTY;
    }
    return this.post<TactonProductConfiguration>(`config/start/${productPath}`);
  }
 
  continueConfiguration(savedConfiguration: TactonSavedConfiguration): Observable<TactonProductConfiguration> {
    Iif (!savedConfiguration) {
      return EMPTY;
    }
    Iif (!savedConfiguration.step) {
      return this.startConfiguration(savedConfiguration.productId);
    }
    return this.post('config/step', pick(savedConfiguration, 'externalId', 'step', 'configId'));
  }
 
  commitValue(valueId: string, value: string): Observable<TactonProductConfiguration> {
    return this.postConfig(`config/commit/${valueId}/${value}`);
  }
 
  uncommitValue(valueId: string): Observable<TactonProductConfiguration> {
    return this.postConfig(`config/uncommit/${valueId}`);
  }
 
  acceptConflictResolution(valueId: string, value: string): Observable<TactonProductConfiguration> {
    Iif (!valueId) {
      return EMPTY;
    }
    return this.postConfig('config/accept', { parameter: valueId, value }).pipe(
      map(result => ({
        ...result,
        // override faulty API response
        response: { status: 'OK' as const },
      }))
    );
  }
 
  changeStep(step: string): Observable<TactonProductConfiguration> {
    Iif (!step) {
      return EMPTY;
    }
    return this.postConfig('config/step', { step });
  }
 
  submitConfiguration(savedConfiguration: TactonSavedConfiguration) {
    if (!savedConfiguration) {
      return EMPTY;
    } else {
      return this.post('cart/items', { ...pick(savedConfiguration, 'externalId', 'configId'), qty: '1' }).pipe(
        withLatestFrom(this.store.pipe(select(getLoggedInUser)), this.store.pipe(select(getLoggedInCustomer))),
        concatMap(([, user, customer]) =>
          this.put('cart', {
            externalId: savedConfiguration.externalId,
            customerEmail: user.login,
            customerPhoneNumber: user.phoneHome || 'N/A',
            customerName: `${customer.companyName} - ${user.firstName} ${user.lastName}`,
          }).pipe(
            concatMap(() =>
              this.post('proposal/firm-requests', {
                externalId: savedConfiguration.externalId,
              })
            )
          )
        )
      );
    }
  }
}