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

73.91% Statements 51/69
56.66% Branches 17/30
59.09% Functions 13/22
83.05% Lines 49/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 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 24628x 28x 28x 28x 28x 28x       28x   28x 28x   28x 4x   6x 2x 2x       4x 4x                         28x 9x   9x         9x                                         2x   2x       2x                             2x                       2x           1x 1x                   1x           1x                         1x   1x   1x   1x                             1x   1x       1x                               1x   1x       1x       1x                                         1x   1x       1x       1x       1x         3x 2x       1x                 1x      
import { APP_BASE_HREF } from '@angular/common';
import { HttpHeaders, HttpParams } from '@angular/common/http';
import { Inject, Injectable } from '@angular/core';
import { Store, select } from '@ngrx/store';
import { EMPTY, Observable, of, throwError } from 'rxjs';
import { catchError, concatMap, map, withLatestFrom } from 'rxjs/operators';
 
import { OrderIncludeType, OrderListQuery } from 'ish-core/models/order-list-query/order-list-query.model';
import { OrderData } from 'ish-core/models/order/order.interface';
import { OrderMapper } from 'ish-core/models/order/order.mapper';
import { Order } from 'ish-core/models/order/order.model';
import { ApiService } from 'ish-core/services/api/api.service';
import { getCurrentLocale } from 'ish-core/store/core/configuration';
 
export function orderListQueryToHttpParams(query: OrderListQuery): HttpParams {
  return Object.entries(query).reduce(
    (acc, [key, value]: [keyof OrderListQuery, OrderListQuery[keyof OrderListQuery]]) => {
      if (Array.isArray(value)) {
        if (key === 'include') {
          return acc.set(key, value.join(','));
        } else E{
          return (value as string[]).reduce((acc, value) => acc.append(key, value?.toString()), acc);
        }
      } else if (value !== undefined) {
        return acc.set(key, value.toString());
      } else E{
        return acc;
      }
    },
    new HttpParams()
  );
}
 
/**
 * The Order Service handles the interaction with the REST API concerning orders.
 */
@Injectable({ providedIn: 'root' })
export class OrderService {
  constructor(private apiService: ApiService, private store: Store, @Inject(APP_BASE_HREF) private baseHref: string) {}
 
  private orderHeaders = new HttpHeaders({
    'content-type': 'application/json',
    Accept: 'application/vnd.intershop.order.v1+json',
  });
 
  private allOrderIncludes: OrderIncludeType[] = [
    'invoiceToAddress',
    'commonShipToAddress',
    'commonShippingMethod',
    'discounts',
    'lineItems',
    'lineItems_discounts',
    'lineItems_warranty',
    'payments',
    'payments_paymentMethod',
    'payments_paymentInstrument',
  ];
 
  /**
   * Creates an order based on the given basket. If a redirect is necessary for payment, the return URLs will be sent after order creation in case they are required.
   *
   * @param basket                      The (current) basket.
   * @param termsAndConditionsAccepted  indicates whether the user has accepted terms and conditions
   * @returns                           The order.
   */
  createOrder(basketId: string, termsAndConditionsAccepted: boolean = false): Observable<Order> {
    const params = new HttpParams().set('include', this.allOrderIncludes.join());
 
    Iif (!basketId) {
      return throwError(() => new Error('createOrder() called without basketId'));
    }
 
    return this.apiService
      .post<OrderData>(
        'orders',
        {
          basket: basketId,
          termsAndConditionsAccepted,
        },
        {
          headers: this.orderHeaders,
          params,
        }
      )
      .pipe(
        map(OrderMapper.fromData),
        withLatestFrom(this.store.pipe(select(getCurrentLocale))),
        concatMap(([order, currentLocale]) => this.sendRedirectUrlsIfRequired(order, currentLocale))
      );
  }
 
  /**
   *  Checks, if RedirectUrls are requested by the server and sends them if it is necessary.
   *
   * @param order           The order.
   * @param lang            The language code of the current locale, e.g. en_US
   * @returns               The (updated) order.
   */
  private sendRedirectUrlsIfRequired(order: Order, lang: string): Observable<Order> {
    if (
      order.orderCreation &&
      order.orderCreation.status === 'STOPPED' &&
      order.orderCreation.stopAction.type === 'Workflow' &&
      order.orderCreation.stopAction.exitReason === 'redirect_urls_required'
    ) {
      const loc = `${location.origin}${this.baseHref}`;
      const body = {
        orderCreation: {
          redirect: {
            cancelUrl: `${loc}/checkout/payment;lang=${lang}?redirect=cancel&orderId=${order.id}`,
            failureUrl: `${loc}/checkout/payment;lang=${lang}?redirect=failure&orderId=${order.id}`,
            successUrl: `${loc}/checkout/receipt;lang=${lang}?redirect=success&orderId=${order.id}`,
          },
          status: 'CONTINUE',
        },
      };
      return this.apiService
        .patch(`orders/${this.apiService.encodeResourceId(order.id)}`, body, {
          headers: this.orderHeaders,
        })
        .pipe(map(OrderMapper.fromData));
    } else {
      return of(order);
    }
  }
 
  /**
   * Gets the orders of the logged-in user
   *
   * @param query   Additional query parameters
   *                - the number of items that should be fetched
   *                - which data should be included.
   * @returns       A list of the user's orders
   */
  getOrders(query: OrderListQuery): Observable<Order[]> {
    const q = query?.buyer === 'all' ? { ...query, buyer: undefined as string, allBuyers: 'true' } : query;
 
    let params = orderListQueryToHttpParams(q);
    // for 7.10 compliance - ToDo: will be removed in PWA 6.0
    params = params.set('page[limit]', query.limit);
 
    return this.apiService
      .get<OrderData>('orders', {
        headers: this.orderHeaders,
        params,
      })
      .pipe(map(OrderMapper.fromListData));
  }
 
  /**
   * Gets a logged-in user's order with the given id
   *
   * @param orderId The (uuid) of the order.
   * @returns       The order
   */
  getOrder(orderId: string): Observable<Order> {
    const params = new HttpParams().set('include', this.allOrderIncludes.join());
 
    Iif (!orderId) {
      return throwError(() => new Error('getOrder() called without orderId'));
    }
 
    return this.apiService
      .get<OrderData>(`orders/${this.apiService.encodeResourceId(orderId)}`, {
        headers: this.orderHeaders,
        params,
      })
      .pipe(map(OrderMapper.fromData));
  }
 
  /**
   * Gets an anonymous user's order with the given id using the provided apiToken.
   *
   * @param orderId  The (uuid) of the order.
   * @param apiToken The api token of the user's most recent request.
   * @returns        The order
   */
  getOrderByToken(orderId: string, apiToken: string): Observable<Order> {
    const params = new HttpParams().set('include', this.allOrderIncludes.join());
 
    Iif (!orderId) {
      return throwError(() => new Error('getOrderByToken() called without orderId'));
    }
 
    Iif (!apiToken) {
      return throwError(() => new Error('getOrderByToken() called without apiToken'));
    }
 
    return this.apiService
      .get<OrderData>(`orders/${this.apiService.encodeResourceId(orderId)}`, {
        headers: this.orderHeaders.set(ApiService.TOKEN_HEADER_KEY, apiToken),
        params,
        skipApiErrorHandling: true,
      })
      .pipe(
        map(OrderMapper.fromData),
        catchError(() => EMPTY)
      );
  }
 
  /**
   * Updates a payment for an order. Used to set redirect query parameters and status after redirect.
   * If cancel/failure is sent back as redirect status, the order doesn't exist any more.
   *
   * @param orderId      The (uuid) of the order.
     @param queryParams  The payment redirect information (parameters and status).
   * @returns            The orderId
   */
  updateOrderPayment(orderId: string, queryParams: { [key: string]: string }): Observable<string> {
    const params = new HttpParams().set('include', this.allOrderIncludes.join());
 
    Iif (!orderId) {
      return throwError(() => new Error('updateOrderPayment() called without orderId'));
    }
 
    Iif (!queryParams) {
      return throwError(() => new Error('updateOrderPayment() called without query parameter data'));
    }
 
    Iif (!queryParams.redirect) {
      return throwError(() => new Error('updateOrderPayment() called without redirect parameter data'));
    }
 
    const orderCreation = {
      status: 'CONTINUE',
      redirect: {
        status: queryParams.redirect.toUpperCase(),
        parameters: Object.entries(queryParams)
          .filter(([name]) => name !== 'redirect')
          .map(([name, value]) => ({ name, value })),
      },
    };
 
    return this.apiService
      .patch<OrderData>(
        `orders/${this.apiService.encodeResourceId(orderId)}`,
        { orderCreation },
        {
          headers: this.orderHeaders,
          params,
        }
      )
      .pipe(map(() => orderId));
  }
}