All files / projects/requisition-management/src/app/facades requisition-context.facade.ts

38.09% Statements 8/21
50% Branches 3/6
0% Functions 0/7
38.09% Lines 8/21

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 751x 1x 1x 1x     1x 1x     1x                 1x                                                                                                              
import { Injectable, OnDestroy } from '@angular/core';
import { Store, select } from '@ngrx/store';
import { RxState } from '@rx-angular/state';
import { distinctUntilChanged, map, switchMap, tap } from 'rxjs/operators';
 
import { HttpError } from 'ish-core/models/http-error/http-error.model';
import { selectRouteParam, selectUrl } from 'ish-core/store/core/router';
import { whenTruthy } from 'ish-core/utils/operators';
 
import { Requisition } from '../models/requisition/requisition.model';
import {
  getRequisition,
  getRequisitionsError,
  getRequisitionsLoading,
  loadRequisition,
  updateRequisitionStatus,
} from '../store/requisitions';
 
@Injectable()
export class RequisitionContextFacade
  extends RxState<{
    id: string;
    loading: boolean;
    error: HttpError;
    entity: Requisition;
    view: 'buyer' | 'approver';
  }>
  implements OnDestroy
{
  constructor(private store: Store) {
    super();
 
    this.connect('id', this.store.pipe(select(selectRouteParam('requisitionId'))));
 
    this.connect('loading', this.store.pipe(select(getRequisitionsLoading)));
 
    this.connect('error', this.store.pipe(select(getRequisitionsError)));
 
    this.connect(
      'entity',
      this.select('id').pipe(
        whenTruthy(),
        distinctUntilChanged(),
        tap(requisitionId => this.store.dispatch(loadRequisition({ requisitionId }))),
        switchMap(requisitionId =>
          this.store.pipe(
            select(getRequisition(requisitionId)),
            whenTruthy(),
            map(entity => entity as Requisition)
          )
        ),
        whenTruthy()
      )
    );
 
    this.connect(
      'view',
      this.store.pipe(
        select(selectUrl),
        map(url => (url.includes('/buyer') ? 'buyer' : 'approver'))
      )
    );
  }
 
  approveRequisition$() {
    this.store.dispatch(updateRequisitionStatus({ requisitionId: this.get('entity', 'id'), status: 'APPROVED' }));
  }
 
  rejectRequisition$(comment?: string) {
    this.store.dispatch(
      updateRequisitionStatus({ requisitionId: this.get('entity', 'id'), status: 'REJECTED', approvalComment: comment })
    );
  }
}