All files / projects/organization-management/src/app/pages/cost-center-buyers cost-center-buyers-page.component.ts

81.81% Statements 36/44
54.54% Branches 12/22
76.92% Functions 10/13
81.39% Lines 35/43

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 1831x 1x 1x   1x 1x 1x   1x     1x 1x 1x   1x                       1x         5x 5x     5x                         5x   5x     5x 5x 5x       5x 5x       5x   5x     5x 5x         5x 5x 8x                           5x                                                                                                               2x 4x         2x 2x                                               13x      
import { ChangeDetectionStrategy, Component, DestroyRef, OnInit, inject } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { FormGroup } from '@angular/forms';
import { FormlyFieldConfig } from '@ngx-formly/core';
import { TranslateService } from '@ngx-translate/core';
import { Observable, merge } from 'rxjs';
import { take, withLatestFrom } from 'rxjs/operators';
 
import { AppFacade } from 'ish-core/facades/app.facade';
import { CostCenterBuyer } from 'ish-core/models/cost-center/cost-center.model';
import { HttpError } from 'ish-core/models/http-error/http-error.model';
import { PriceHelper } from 'ish-core/models/price/price.model';
import { markAsDirtyRecursive } from 'ish-shared/forms/utils/form-utils';
import { FormsService } from 'ish-shared/forms/utils/forms.service';
 
import { OrganizationManagementFacade } from '../../facades/organization-management.facade';
import { B2bUser } from '../../models/b2b-user/b2b-user.model';
 
/**
 * The Cost Center Buyers Page Component displays all the users that are not yet assigned to this cost center. The user can enter user budgets and add these users to the cost center.
 *
 */
@Component({
  selector: 'ish-cost-center-buyers-page',
  templateUrl: './cost-center-buyers-page.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class CostCenterBuyersPageComponent implements OnInit {
  loading$: Observable<boolean>;
  error$: Observable<HttpError>;
  buyers$: Observable<B2bUser[]>;
 
  form: FormGroup = new FormGroup({});
  private submitted = false;
 
  fields: FormlyFieldConfig[];
  model: {
    addBuyers: {
      selected: boolean;
      name: string;
      login: string;
      budgetValue: number;
      currency: string;
      budgetPeriod: string;
    }[];
  } = {
    addBuyers: [],
  };
 
  selectAll = true;
 
  private destroyRef = inject(DestroyRef);
 
  constructor(
    private appFacade: AppFacade,
    private organizationManagementFacade: OrganizationManagementFacade,
    private translateService: TranslateService
  ) {}
 
  ngOnInit() {
    this.loading$ = this.organizationManagementFacade.costCentersLoading$;
    this.error$ = merge(
      this.organizationManagementFacade.costCentersError$,
      this.organizationManagementFacade.usersError$
    );
    this.buyers$ = this.organizationManagementFacade.costCenterUnassignedBuyers$();
    // set model and form fields
    this.buyers$
      .pipe(withLatestFrom(this.appFacade.currentCurrency$), take(1), takeUntilDestroyed(this.destroyRef))
      .subscribe(([buyers, currency]) => {
        this.model = this.getModel(buyers, currency);
        this.fields = this.getFields();
      });
  }
 
  private getModel(buyers: B2bUser[], currency: string) {
    const inactiveText = this.translateService.instant('account.user.list.status.inactive');
    return {
      addBuyers: buyers.map(buyer => ({
        selected: false,
        name: `${buyer.firstName} ${buyer.lastName} ${
          !buyer.active ? `<p class="input-help">${inactiveText}</p>` : ''
        } `,
        login: buyer.login,
        budgetValue: undefined,
        currency,
        budgetPeriod: FormsService.getCostCenterBudgetPeriodOptions()[0].value,
      })),
    };
  }
 
  private getFields() {
    return [
      {
        key: 'addBuyers',
        type: 'repeatCostCenterBuyers',
        props: {},
        fieldArray: {
          fieldGroupClassName: 'row list-item-row',
          fieldGroup: [
            {
              type: 'ish-checkbox-field',
              key: 'selected',
              defaultValue: false,
              className: 'col-1 col-md-2 list-item pb-0',
              props: {
                fieldClass: 'offset-md-2 col-2 mt-1',
                ariaLabel: 'Select buyer to add to costcenter',
              },
            },
            {
              key: 'name',
              type: 'ish-html-text-field',
              className: 'col-11 col-sm-10 col-md-3 list-item pb-0',
              props: {
                inputClass: 'col-form-label pb-0',
              },
            },
            {
              key: 'budgetValue',
              type: 'ish-text-input-field',
              className: 'col-6 col-md-4 list-item',
              props: {
                fieldClass: 'col-12',
                postWrappers: [{ wrapper: 'input-addon', index: -1 }],
                addonLeft: {
                  text: this.appFacade.currencySymbol$(),
                },
                mask: 'separator.2',
                ariaLabel: 'Buyer budget',
              },
            },
            {
              key: 'budgetPeriod',
              type: 'ish-select-field',
              className: 'col-6 col-md-3 list-item',
              props: {
                fieldClass: 'col-12',
                options: FormsService.getCostCenterBudgetPeriodOptions(),
              },
            },
          ],
        },
      },
    ];
  }
 
  toggleItemSelection() {
    this.model = {
      addBuyers: this.model.addBuyers.map(line => ({
        ...line,
        selected: this.selectAll,
      })),
    };
    this.form.updateValueAndValidity();
    this.selectAll = !this.selectAll;
  }
 
  submitForm() {
    Iif (this.form.invalid) {
      this.submitted = true;
      markAsDirtyRecursive(this.form);
      return;
    }
    const buyers: CostCenterBuyer[] = this.model.addBuyers
      .map(item =>
        item.selected
          ? {
              login: item.login,
              budget: PriceHelper.getPrice(item.currency, item.budgetValue || 0),
              budgetPeriod: item.budgetPeriod,
            }
          : undefined
      )
      .filter(item => item !== undefined);
    this.organizationManagementFacade.addBuyersToCostCenter(buyers);
  }
 
  get formDisabled() {
    return (this.form.invalid && this.submitted) || !this.model.addBuyers.some(buyer => buyer.selected);
  }
}