All files / src/app/core/services/recurring-orders recurring-orders.service.ts

97.36% Statements 37/38
81.25% Branches 13/16
100% Functions 15/15
97.14% Lines 34/35

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 14025x 25x 25x 25x       25x 25x 25x           25x 10x   10x   10x                   7x   7x         7x 7x 6x     6x         1x   7x                       3x   3x   3x                           2x   2x   2x                                   2x 1x     1x   1x   1x                                 2x 1x     1x   1x              
import { HttpHeaders, HttpParams } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Store, select } from '@ngrx/store';
import { combineLatest, filter, map, switchMap, take, throwError } from 'rxjs';
 
import { OrderIncludeType } from 'ish-core/models/order-list-query/order-list-query.model';
import { RecurringOrderData, RecurringOrderListData } from 'ish-core/models/recurring-order/recurring-order.interface';
import { RecurringOrderMapper } from 'ish-core/models/recurring-order/recurring-order.mapper';
import { ApiService, unpackEnvelope } from 'ish-core/services/api/api.service';
import { getLoggedInCustomer, getLoggedInUser } from 'ish-core/store/customer/user';
 
/**
 * The Recurring Orders Service handles the interaction with the REST API concerning recurring orders.
 */
@Injectable({ providedIn: 'root' })
export class RecurringOrdersService {
  constructor(private apiService: ApiService, private store: Store) {}
 
  private recurringOrderHeaderV2 = new HttpHeaders({ Accept: 'application/vnd.intershop.recurringorder.v2+json' });
 
  private recurringOrderIncludes: OrderIncludeType[] = ['discounts', 'lineItems_discounts'];
 
  /**
   * Returns the REST API endpoint for recurring orders of the customer or the logged-in user.
   *
   * @param context  This value decides whether the recurring orders of the customer or the logged-in user are returned.
   *                 In case of a business customer and the context 'ADMIN' the endpoint for the customer, otherwise the endpoint of the logged-in user (B2B/ B2C) is returned.
   * @returns        The endpoint for the recurring orders.
   */
  private getRecurringOrdersEndpoint(context?: string) {
    return combineLatest([this.store.pipe(select(getLoggedInCustomer)), this.store.pipe(select(getLoggedInUser))])
      .pipe(
        filter(([customer, user]) => !!customer && !!user),
        take(1)
      )
      .pipe(
        map(([customer, user]) => {
          let apiEndpoint: string = undefined;
          if (customer.isBusinessCustomer) {
            Iif (context === 'ADMIN') {
              apiEndpoint = `customers/${this.apiService.encodeResourceId(customer.customerNo)}/recurringorders`;
            } else {
              apiEndpoint = `customers/${this.apiService.encodeResourceId(
                customer.customerNo
              )}/users/${this.apiService.encodeResourceId(user.login)}/recurringorders`;
            }
          } else {
            apiEndpoint = `privatecustomers/${this.apiService.encodeResourceId(customer.customerNo)}/recurringorders`;
          }
          return apiEndpoint;
        })
      );
  }
 
  /**
   * Get all recurring orders of the customer or the logged-in user.
   *
   * @param context  This value decides whether the recurring orders of the customer or the logged-in user are returned.
   * @returns        A list of recurring orders.
   */
  getRecurringOrders(context?: string) {
    return this.getRecurringOrdersEndpoint(context).pipe(
      switchMap(apiEndpoint =>
        this.apiService.get(apiEndpoint, { headers: this.recurringOrderHeaderV2 }).pipe(
          unpackEnvelope<RecurringOrderListData>('data'),
          map(data => RecurringOrderMapper.fromListData(data))
        )
      )
    );
  }
 
  /**
   * Get a specific recurring order .
   *
   * @param recurringOrderId  The ID of the recurring order.
   * @param context           The value indicates whether the recurring order that should be searched for is an order of the customer or the logged-in user.
   * @returns                 The recurring order.
   */
  getRecurringOrder(recurringOrderId: string, context?: string) {
    const params = new HttpParams().set('include', this.recurringOrderIncludes.join());
 
    return this.getRecurringOrdersEndpoint(context).pipe(
      switchMap(apiEndpoint =>
        this.apiService
          .get<RecurringOrderData>(`${apiEndpoint}/${this.apiService.encodeResourceId(recurringOrderId)}`, {
            headers: this.recurringOrderHeaderV2,
            params,
          })
          .pipe(map(RecurringOrderMapper.fromData))
      )
    );
  }
 
  /**
   * Updates a recurring order.
   *
   * @param recurringOrderId  The recurring order id.
   * @param context           The value indicates whether the recurring order that should be updated is an order of the customer or the logged-in user.
   * @returns                 The updated recurring order.
   */
  updateRecurringOrder(recurringOrderId: string, active: boolean, context?: string) {
    if (!recurringOrderId) {
      return throwError(() => new Error('updateRecurringOrder() called without recurringOrderId'));
    }
 
    const params = new HttpParams().set('include', this.recurringOrderIncludes.join());
 
    return this.getRecurringOrdersEndpoint(context).pipe(
      switchMap(apiEndpoint =>
        this.apiService
          .patch<RecurringOrderData>(
            `${apiEndpoint}/${this.apiService.encodeResourceId(recurringOrderId)}`,
            { active },
            { headers: this.recurringOrderHeaderV2, params }
          )
          .pipe(map(RecurringOrderMapper.fromData))
      )
    );
  }
 
  /**
   * Deletes a recurring order
   * @param recurringOrderId  The recurring order id.
   * @param context           The value indicates whether the recurring order that should be deleted is an order of the customer or the logged-in user.
   */
  deleteRecurringOrder(recurringOrderId: string, context?: string) {
    if (!recurringOrderId) {
      return throwError(() => new Error('deleteRecurringOrder() called without recurringOrderId'));
    }
 
    return this.getRecurringOrdersEndpoint(context).pipe(
      switchMap(apiEndpoint =>
        this.apiService.delete(`${apiEndpoint}/${this.apiService.encodeResourceId(recurringOrderId)}`, {
          headers: this.recurringOrderHeaderV2,
        })
      )
    );
  }
}