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

87.35% Statements 76/87
75.75% Branches 50/66
87.17% Functions 34/39
89.61% Lines 69/77

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 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 37228x 28x 28x 28x 28x 28x   28x         28x                   28x   28x 28x 28x 28x 28x 28x                                             28x   23x 23x 23x 23x 23x                       5x 5x     4x                           2x 1x   1x   1x         7x     6x       6x     6x                   2x 1x     1x           1x   1x                                                                         1x       1x       1x                     3x 1x     2x             2x                             2x     2x                               4x 1x   3x     3x 1x   2x       2x     2x                             1x                 3x 1x     2x 1x     1x                 1x   1x     1x                                                                             1x         1x                     1x       1x           1x 1x                        
import { HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Store, select } from '@ngrx/store';
import { pick } from 'lodash-es';
import { Observable, combineLatest, defer, forkJoin, of, throwError } from 'rxjs';
import { concatMap, first, map, switchMap, take, tap, withLatestFrom } from 'rxjs/operators';
 
import { AppFacade } from 'ish-core/facades/app.facade';
import { Address } from 'ish-core/models/address/address.model';
import { CostCenter } from 'ish-core/models/cost-center/cost-center.model';
import { Credentials } from 'ish-core/models/credentials/credentials.model';
import { CustomerData, CustomerType } from 'ish-core/models/customer/customer.interface';
import { CustomerMapper } from 'ish-core/models/customer/customer.mapper';
import {
  Customer,
  CustomerLoginType,
  CustomerRegistrationType,
  CustomerUserType,
} from 'ish-core/models/customer/customer.model';
import { PasswordReminderUpdate } from 'ish-core/models/password-reminder-update/password-reminder-update.model';
import { PasswordReminder } from 'ish-core/models/password-reminder/password-reminder.model';
import { UserCostCenter } from 'ish-core/models/user-cost-center/user-cost-center.model';
import { UserMapper } from 'ish-core/models/user/user.mapper';
import { User } from 'ish-core/models/user/user.model';
import { ApiService, AvailableOptions, unpackEnvelope } from 'ish-core/services/api/api.service';
import { TokenService } from 'ish-core/services/token/token.service';
import { getUserPermissions } from 'ish-core/store/customer/authorization';
import { getLoggedInCustomer } from 'ish-core/store/customer/user';
import { ApiTokenService } from 'ish-core/utils/api-token/api-token.service';
import { whenTruthy } from 'ish-core/utils/operators';
 
/**
 * The User Service handles the registration related interaction with the 'customers' REST API.
 */
 
// request data type for create user
interface CreatePrivateCustomerType extends CustomerData {
  address: Address;
  credentials: Credentials;
}
 
interface CreateBusinessCustomerType extends Customer {
  address: Address;
  credentials: Credentials;
  user: User;
  type: CustomerType;
}
 
/**
 * The User Service handles the registration related interaction with the 'customers' REST API.
 */
@Injectable({ providedIn: 'root' })
export class UserService {
  constructor(
    private apiService: ApiService,
    private apiTokenService: ApiTokenService,
    private appFacade: AppFacade,
    private store: Store,
    private tokenService: TokenService
  ) {}
 
  /**
   * Sign in an existing user with the given login credentials (login, password).
   *
   * @param loginCredentials  The users login credentials {login: 'foo', password. 'bar'}.
   * @returns                 The logged in customer data.
   *                          For private customers user data are also returned.
   *                          For business customers user data are returned by a separate call (getCompanyUserData).
   */
  signInUser(loginCredentials: Credentials): Observable<CustomerLoginType> {
    return defer(() =>
      loginCredentials
        ? this.tokenService
            .fetchToken('password', { username: loginCredentials.login, password: loginCredentials.password })
            .pipe(switchMap(() => this.fetchCustomer()))
        : this.fetchCustomer()
    );
  }
 
  /**
   * Sign in an existing user with the given token or if no token is given, using token stored in cookie.
   *
   * @param token             The refresh token that is used to login user.
   * @returns                 The logged in customer data.
   *                          For private customers user data are also returned.
   *                          For business customers user data are returned by a separate call (getCompanyUserData).
   */
  signInUserByToken(token?: string): Observable<CustomerLoginType> {
    if (token) {
      return this.tokenService
        .fetchToken('refresh_token', { refresh_token: token })
        .pipe(switchMap(() => this.fetchCustomer()));
    } else {
      return this.fetchCustomer({ skipApiErrorHandling: true });
    }
  }
 
  private fetchCustomer(options: AvailableOptions = {}): Observable<CustomerUserType> {
    return this.apiService.get<CustomerData>('customers/-', options).pipe(
      withLatestFrom(this.appFacade.isAppTypeREST$),
      concatMap(([data, isAppTypeRest]) =>
        forkJoin([
          isAppTypeRest && data.customerType === 'PRIVATE'
            ? this.apiService.get<CustomerData>('privatecustomers/-', options)
            : of(data),
          this.apiService.get<{ pgid: string }>('personalization', options).pipe(map(data => data.pgid)),
        ])
      ),
      map(([data, pgid]) => ({ ...CustomerMapper.mapLoginData(data), pgid }))
    );
  }
 
  /**
   * Creates a new user for the given data.
   *
   * @param body  The user data (customer, user, credentials, address) to create a new user. The new user is not logged in after creation.
   */
  createUser(body: CustomerRegistrationType): Observable<CustomerUserType> {
    if (!body?.customer || (!body?.user && !body?.userId) || !body?.address) {
      return throwError(() => new Error('createUser() called without required body data'));
    }
 
    const customerAddress = {
      ...body.address,
      mainDivision: body.address.mainDivisionCode,
    };
 
    const newCustomer$: Observable<CreatePrivateCustomerType | CreateBusinessCustomerType> =
      this.appFacade.currentLocale$.pipe(
        map(currentLocale =>
          body.customer.isBusinessCustomer
            ? {
                type: 'SMBCustomer',
                ...body.customer,
                ...(body.user
                  ? {
                      user: {
                        ...body.user,
                        preferredLanguage: currentLocale,
                      },
                    }
                  : {
                      userId: body.userId,
                    }),
                address: customerAddress,
                credentials: body.credentials,
              }
            : {
                type: 'PrivateCustomer',
                ...body.customer,
                ...(body.user
                  ? {
                      firstName: body.user.firstName,
                      lastName: body.user.lastName,
                      email: body.user.email,
                      preferredLanguage: currentLocale,
                    }
                  : {
                      userId: body.userId,
                    }),
                address: customerAddress,
                credentials: body.credentials,
                preferredLanguage: currentLocale,
              }
        )
      );
 
    return this.appFacade.isAppTypeREST$.pipe(
      first(),
      withLatestFrom(newCustomer$.pipe(first())),
      concatMap(([isAppTypeRest, newCustomer]) =>
        this.apiService
          .post<void>(AppFacade.getCustomerRestResource(body.customer.isBusinessCustomer, isAppTypeRest), newCustomer, {
            captcha: pick(body, ['captcha', 'captchaAction']),
          })
          .pipe(map<void, CustomerUserType>(() => ({ customer: body.customer, user: body.user })))
      )
    );
  }
 
  /**
   * Updates the data of the currently logged in user.
   *
   * @param body  The user data (customer, user ) to update the user.
   */
  updateUser(body: CustomerUserType, credentials?: Credentials): Observable<User> {
    if (!body?.customer || !body?.user) {
      return throwError(() => new Error('updateUser() called without required body data'));
    }
 
    const headers = credentials
      ? new HttpHeaders().set(
          ApiService.AUTHORIZATION_HEADER_KEY,
          `BASIC ${window.btoa(`${credentials.login}:${credentials.password}`)}`
        )
      : undefined;
 
    const changedUser: object = {
      type: body.customer.isBusinessCustomer ? 'SMBCustomer' : 'PrivateCustomer',
      ...body.customer,
      ...body.user,
      preferredInvoiceToAddress: { urn: body.user.preferredInvoiceToAddressUrn },
      preferredShipToAddress: { urn: body.user.preferredShipToAddressUrn },
      preferredPaymentInstrument: body.user.preferredPaymentInstrumentId
        ? { id: body.user.preferredPaymentInstrumentId }
        : {},
      preferredInvoiceToAddressUrn: undefined,
      preferredShipToAddressUrn: undefined,
      preferredPaymentInstrumentId: undefined,
      preferredLanguage: body.user.preferredLanguage || 'en_US',
    };
 
    return this.appFacade.customerRestResource$.pipe(
      first(),
      concatMap(restResource =>
        body.customer.isBusinessCustomer
          ? this.apiService.put<User>('customers/-/users/-', changedUser, { headers }).pipe(map(UserMapper.fromData))
          : this.apiService.put<User>(`${restResource}/-`, changedUser, { headers }).pipe(map(UserMapper.fromData))
      )
    );
  }
 
  /**
   * Updates the password of the currently logged in user.
   *
   * @param customer         The current customer.
   * @param user             The current user.
   * @param password         The new password to update to.
   * @param currentPassword  The users old password for verification.
   */
  updateUserPassword(customer: Customer, user: User, password: string, currentPassword: string): Observable<void> {
    if (!customer) {
      return throwError(() => new Error('updateUserPassword() called without customer'));
    }
    Iif (!user) {
      return throwError(() => new Error('updateUserPassword() called without user'));
    }
    if (!password) {
      return throwError(() => new Error('updateUserPassword() called without password'));
    }
    Iif (!currentPassword) {
      return throwError(() => new Error('updateUserPassword() called without currentPassword'));
    }
 
    return this.appFacade.customerRestResource$.pipe(
      first(),
      concatMap(restResource =>
        this.apiService.put<void>(
          customer.isBusinessCustomer
            ? 'customers/-/users/-/credentials/password'
            : `${restResource}/-/credentials/password`,
          { password, currentPassword }
        )
      )
    );
  }
 
  /**
   * Logs out the current user associated with the specified authentication token.
   * All (refresh) tokens issued for this user will expire and become invalid.
   */
  logoutUser() {
    return this.apiService.put('token/logout').pipe(tap(() => this.apiTokenService.removeApiToken()));
  }
 
  /**
   * Updates the customer data of the (currently logged in) b2b customer.
   *
   * @param customer  The customer data to update the customer.
   */
  updateCustomer(customer: Customer): Observable<Customer> {
    if (!customer) {
      return throwError(() => new Error('updateCustomer() called without customer'));
    }
 
    if (!customer.isBusinessCustomer) {
      return throwError(() => new Error('updateCustomer() cannot be called for a private customer)'));
    }
 
    return this.apiService.put('customers/-', { ...customer, type: 'SMBCustomer' }).pipe(map(CustomerMapper.fromData));
  }
 
  /**
   * Get User data for the logged in Business Customer.
   *
   * @returns The related customer user data.
   */
  getCompanyUserData(): Observable<User> {
    return this.store.pipe(
      select(getLoggedInCustomer),
      map(customer => customer?.customerNo || '-'),
      take(1),
      concatMap(customerNo =>
        this.apiService
          .get(`customers/${this.apiService.encodeResourceId(customerNo)}/users/-`)
          .pipe(map(UserMapper.fromData))
      )
    );
  }
 
  /**
   * Request an email for the given data user with a link to reset the users password.
   *
   * @param data  The user data (email, firstName, lastName ) to identify the user.
   */
  requestPasswordReminder(data: PasswordReminder) {
    const options: AvailableOptions = {
      skipApiErrorHandling: true,
      captcha: pick(data, ['captcha', 'captchaAction']),
    };
 
    return this.apiService.post('security/reminder', { answer: '', ...data }, options);
  }
 
  /**
   * set new password with data based on requestPasswordReminder generated email
   *
   * @param data  password, userID, secureCode
   */
  updateUserPasswordByReminder(data: PasswordReminderUpdate) {
    const options: AvailableOptions = {
      skipApiErrorHandling: true,
    };
    return this.apiService.post('security/password', data, options);
  }
 
  /**
   * Get cost centers for the logged in User of a Business Customer.
   *
   * @returns The related cost centers.
   */
  getEligibleCostCenters(): Observable<UserCostCenter[]> {
    return this.apiService
      .b2bUserEndpoint()
      .get(`costcenters`)
      .pipe(
        unpackEnvelope(),
        map((costCenters: UserCostCenter[]) => costCenters)
      );
  }
 
  /**
   * Get cost center data of a business customer for a given cost center id. The logged in user needs permission APP_B2B_VIEW_COSTCENTER.
   *
   * @param   The Id of the cost center.
   * @returns The related cost center.
   */
  getCostCenter(id: string): Observable<CostCenter> {
    Iif (!id) {
      return throwError(() => new Error('getCostCenter() called without id'));
    }
 
    return combineLatest([
      this.store.pipe(select(getLoggedInCustomer), whenTruthy()),
      this.store.pipe(select(getUserPermissions), whenTruthy()),
    ]).pipe(
      take(1),
      switchMap(([customer, permissions]) => {
        if (permissions.includes('APP_B2B_VIEW_COSTCENTER')) {
          return this.apiService.get<CostCenter>(
            `customers/${this.apiService.encodeResourceId(
              customer.customerNo
            )}/costcenters/${this.apiService.encodeResourceId(id)}`
          );
        } else E{
          return of(undefined);
        }
      })
    );
  }
}