All files / projects/organization-management/src/app/components/user-roles-selection user-roles-selection.component.ts

79.59% Statements 39/49
70.58% Branches 12/17
72.41% Functions 21/29
77.77% Lines 35/45

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 1443x 3x 3x               3x 3x   3x                   14x       3x           5x   5x 5x   5x   5x     5x   5x     5x   15x                           5x   5x   5x   5x           5x       15x 15x 10x   15x 15x       5x     15x       5x         15x       10x       10x                               5x 5x                                  
import { ChangeDetectionStrategy, Component, DestroyRef, Input, OnInit, forwardRef, inject } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import {
  AbstractControl,
  ControlValueAccessor,
  FormBuilder,
  FormControl,
  FormGroup,
  NG_VALUE_ACCESSOR,
} from '@angular/forms';
import { Observable, ReplaySubject, noop } from 'rxjs';
import { first, map, shareReplay, startWith, switchMap, take, tap, withLatestFrom } from 'rxjs/operators';
 
import { OrganizationManagementFacade } from '../../facades/organization-management.facade';
 
@Component({
  selector: 'ish-user-roles-selection',
  templateUrl: './user-roles-selection.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush,
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      multi: true,
      useExisting: forwardRef(() => UserRolesSelectionComponent),
    },
  ],
})
export class UserRolesSelectionComponent implements ControlValueAccessor, OnInit {
  @Input() staticRoles: string[];
 
  form$: Observable<FormGroup>;
 
  private onTouched: Function;
  private onChange: (roles: string[]) => void = noop;
 
  private staticRoles$ = new ReplaySubject<string[]>(1);
  private destroyRef = inject(DestroyRef);
 
  isExpanded: boolean[] = [];
 
  constructor(private fb: FormBuilder, private organizationManagementFacade: OrganizationManagementFacade) {}
 
  ngOnInit() {
    this.calculateStaticRoles();
 
    this.form$ = this.organizationManagementFacade.availableRoles$.pipe(
      withLatestFrom(this.staticRoles$),
      map(([roles, staticRoles]) =>
        this.fb.group(
          roles.reduce(
            (acc, role) => ({
              ...acc,
              [role.id]: this.createFormControl(
                staticRoles.includes(role.id),
                ['APP_B2B_OCI_USER', 'APP_B2B_CXML_USER'].includes(role.id)
              ),
            }),
            {}
          )
        )
      ),
      shareReplay(1)
    );
 
    this.form$
      .pipe(
        switchMap(form => form.valueChanges.pipe(startWith(form.value))),
        withLatestFrom(this.staticRoles$),
        map(([value, staticRoles]) => this.modelToRoles(value, staticRoles)),
        tap(() => {
          Iif (this.onTouched) {
            this.onTouched();
          }
        }),
        takeUntilDestroyed(this.destroyRef)
      )
      .subscribe(v => this.onChange(v));
  }
 
  private createFormControl(isStatic: boolean, disable: boolean) {
    const control = new FormControl(isStatic);
    if (isStatic || disable) {
      control.disable();
    }
    this.isExpanded.push(false);
    return control;
  }
 
  private calculateStaticRoles() {
    this.organizationManagementFacade.availableRoles$
      .pipe(
        take(1),
        map(roles => roles.filter(r => r.fixed).map(r => r.id)),
        takeUntilDestroyed(this.destroyRef)
      )
      .subscribe(roles => {
        this.staticRoles$.next(this.staticRoles ? roles.concat(this.staticRoles) : roles);
      });
  }
 
  role$(id: string) {
    return this.organizationManagementFacade.role$(id);
  }
 
  get unsorted() {
    return () => 0;
  }
 
  hideRole(control: AbstractControl): boolean {
    return control.disabled && !control.value;
  }
 
  writeValue(initialRoleIDs: string[]): void {
    Iif (initialRoleIDs?.length) {
      this.form$.pipe(first(), takeUntilDestroyed(this.destroyRef)).subscribe(form => {
        initialRoleIDs
          .filter(id => form.get(id))
          .forEach(id => {
            form.get(id).setValue(true);
          });
      });
    }
  }
 
  private modelToRoles(values: { [id: string]: boolean }, staticRoles: string[]): string[] {
    return Object.entries(values)
      .filter(([, value]) => !!value)
      .map(([key]) => key)
      .concat(staticRoles);
  }
 
  registerOnChange(fn: (roles: string[]) => void): void {
    this.onChange = fn;
  }
 
  registerOnTouched(fn: Function): void {
    this.onTouched = fn;
  }
 
  toggleExpanded(index: number) {
    this.isExpanded[index] = !this.isExpanded[index];
  }
}