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

37.68% Statements 26/69
25% Branches 3/12
2.43% Functions 1/41
40% Lines 26/65

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 24245x 45x 45x 45x 45x     45x 45x 45x 45x       45x           45x                         45x                                     45x 16x   16x 16x 16x 16x   16x 16x   16x   16x 16x 16x 16x                                                                                                                                                                                                                               16x                                                                                                                          
import { Injectable } from '@angular/core';
import { Store, select } from '@ngrx/store';
import { differenceBy } from 'lodash-es';
import { Observable, combineLatest } from 'rxjs';
import { distinctUntilChanged, filter, map, switchMap, take, withLatestFrom } from 'rxjs/operators';
 
import { CostCenter, CostCenterBase, CostCenterBuyer } from 'ish-core/models/cost-center/cost-center.model';
import { getUserPermissions, getUserRoles } from 'ish-core/store/customer/authorization';
import { getLoggedInUser } from 'ish-core/store/customer/user';
import { toObservable } from 'ish-core/utils/functions';
import { mapToProperty, whenTruthy } from 'ish-core/utils/operators';
 
import { B2bUser } from '../models/b2b-user/b2b-user.model';
import { UserBudget } from '../models/user-budget/user-budget.model';
import {
  getCurrentUserBudget,
  getCurrentUserBudgetError,
  getCurrentUserBudgetLoading,
  loadBudget,
} from '../store/budget';
import {
  addCostCenter,
  addCostCenterBuyers,
  deleteCostCenter,
  deleteCostCenterBuyer,
  getCostCenters,
  getCostCentersError,
  getCostCentersLoading,
  getSelectedCostCenter,
  loadCostCenters,
  updateCostCenter,
  updateCostCenterBuyer,
} from '../store/cost-centers';
import {
  addUser,
  deleteUser,
  getCostCenterManagers,
  getRole,
  getRoles,
  getSelectedUser,
  getSystemUserRoles,
  getUsers,
  getUsersError,
  getUsersLoading,
  loadUsers,
  setUserBudget,
  setUserRoles,
  updateUser,
} from '../store/users';
 
/* eslint-disable @typescript-eslint/member-ordering */
@Injectable({ providedIn: 'root' })
export class OrganizationManagementFacade {
  constructor(private store: Store) {}
 
  usersError$ = this.store.pipe(select(getUsersError));
  usersLoading$ = this.store.pipe(select(getUsersLoading));
  selectedUser$ = this.store.pipe(select(getSelectedUser));
  users$ = this.store.pipe(select(getUsers));
 
  loggedInUserBudgetLoading$ = this.store.pipe(select(getCurrentUserBudgetLoading));
  loggedInUserBudgetError$ = this.store.pipe(select(getCurrentUserBudgetError));
 
  availableRoles$ = this.store.pipe(select(getSystemUserRoles));
 
  costCenters$ = this.store.pipe(select(getCostCenters));
  costCentersError$ = this.store.pipe(select(getCostCentersError));
  costCentersLoading$ = this.store.pipe(select(getCostCentersLoading));
  selectedCostCenter$ = this.store.pipe(select(getSelectedCostCenter));
 
  /**
   * user methods
   */
  loggedInUserBudget$() {
    this.store.dispatch(loadBudget());
    return this.store.pipe(select(getCurrentUserBudget));
  }
 
  fetchUsers() {
    this.store.dispatch(loadUsers());
  }
 
  addUser(user: B2bUser) {
    this.store.dispatch(
      addUser({
        user,
      })
    );
  }
 
  updateUser(user: B2bUser) {
    this.store.dispatch(
      updateUser({
        user,
      })
    );
  }
 
  deleteUser(login: string) {
    this.store.dispatch(deleteUser({ login }));
  }
 
  roles$(roleIDs: string[] | Observable<string[]>) {
    return toObservable(roleIDs).pipe(switchMap(ids => this.store.pipe(select(getRoles(ids)))));
  }
 
  role$(roleID: string) {
    return this.store.pipe(select(getRole(roleID)));
  }
 
  setSelectedUserRoles(roleIDs: string[]) {
    this.selectedUser$
      .pipe(take(1), whenTruthy(), mapToProperty('login'))
      .subscribe(login => this.store.dispatch(setUserRoles({ login, roles: roleIDs })));
  }
 
  setSelectedUserBudget(budget: UserBudget) {
    this.selectedUser$
      .pipe(take(1), whenTruthy(), mapToProperty('login'))
      .subscribe(login => this.store.dispatch(setUserBudget({ login, budget })));
  }
 
  costCenterManagerSelectOptions$() {
    return this.store.pipe(select(getUserPermissions), whenTruthy()).pipe(
      take(1),
      switchMap(permissions =>
        permissions.includes('APP_B2B_MANAGE_USERS')
          ? this.costCenterManagerSelectOptionsForAccountAdmin$()
          : this.costCenterManagerSelectOptionsForCCOwner$()
      )
    );
  }
 
  /**
   * cost center methods
   */
  private costCenterManagerSelectOptionsForAccountAdmin$() {
    this.store.dispatch(loadUsers());
    return this.store.pipe(
      select(getCostCenterManagers),
      whenTruthy(),
      filter(users => !!users?.length),
      map(users => users.map(user => ({ label: `${user.firstName} ${user.lastName}`, value: user.login }))),
      distinctUntilChanged()
    );
  }
 
  private costCenterManagerSelectOptionsForCCOwner$() {
    return this.store.pipe(
      select(getLoggedInUser),
      whenTruthy(),
      map(user => [{ label: `${user.firstName} ${user.lastName}`, value: user.login }])
    );
  }
 
  costCenterUnassignedBuyers$() {
    return this.store.pipe(
      select(getUsers),
      whenTruthy(),
      withLatestFrom(this.selectedCostCenter$),
      filter(([buyers, costCenter]) => !!buyers.length && !!costCenter),
      map(([buyers, costCenter]) => differenceBy(buyers, costCenter.buyers, 'login'))
    );
  }
 
  costCentersOfCurrentUser$() {
    this.store.dispatch(loadCostCenters());
    return this.costCenters$.pipe(
      withLatestFrom(this.store.pipe(select(getLoggedInUser))),
      map(([costCenters, currentUser]) => costCenters.filter(cc => cc.costCenterOwner.login === currentUser.login))
    );
  }
 
  isCostCenterEditable(costCenter$: Observable<CostCenter>) {
    return combineLatest([costCenter$, this.store.pipe(select(getLoggedInUser)), this.isAccountAdmin$]).pipe(
      filter(([costCenter, user]) => !!costCenter && !!user),
      map(([costCenter, user, isAdmin]) => isAdmin || costCenter.costCenterOwner.login === user?.login)
    );
  }
 
  private isAccountAdmin$ = this.store
    .pipe(select(getUserRoles))
    .pipe(map(roles => roles?.some(role => role.roleId === 'APP_B2B_ACCOUNT_OWNER')));
 
  addCostCenter(costCenter: CostCenterBase) {
    this.store.dispatch(
      addCostCenter({
        costCenter,
      })
    );
  }
 
  updateCostCenter(costCenter: CostCenterBase) {
    this.store.dispatch(
      updateCostCenter({
        costCenter,
      })
    );
  }
 
  deleteCostCenter(id: string) {
    this.store.dispatch(
      deleteCostCenter({
        id,
      })
    );
  }
 
  addBuyersToCostCenter(buyers: CostCenterBuyer[]) {
    this.selectedCostCenter$.pipe(take(1), whenTruthy(), mapToProperty('id')).subscribe(costCenterId =>
      this.store.dispatch(
        addCostCenterBuyers({
          costCenterId,
          buyers,
        })
      )
    );
  }
 
  updateCostCenterBuyer(buyer: CostCenterBuyer) {
    this.selectedCostCenter$.pipe(take(1), whenTruthy(), mapToProperty('id')).subscribe(costCenterId =>
      this.store.dispatch(
        updateCostCenterBuyer({
          costCenterId,
          buyer,
        })
      )
    );
  }
 
  removeBuyerFromCostCenter(login: string) {
    this.selectedCostCenter$.pipe(take(1), whenTruthy(), mapToProperty('id')).subscribe(costCenterId =>
      this.store.dispatch(
        deleteCostCenterBuyer({
          costCenterId,
          login,
        })
      )
    );
  }
}