All files / projects/organization-management/src/app/pages/user-create/user-csv-import user-csv-import.component.ts

83.54% Statements 66/79
78.04% Branches 32/41
84.21% Functions 16/19
83.33% Lines 65/78

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 2192x                   2x 2x 2x   2x   2x               2x   6x   6x   6x                                     6x         6x 6x 6x       6x                                                           2x 1x     1x 16x 1x                   1x 16x 16x     1x         16x 6x 10x 5x 5x 5x         16x       10x                   5x                   6x   1x 1x   1x 1x   1x 1x   1x 1x   1x 1x   1x 1x         5x           5x       5x   1x 1x   1x 1x   1x 1x   1x 1x   1x 1x         1x 1x       2x 1x   1x       6x      
import {
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  Component,
  DestroyRef,
  ElementRef,
  OnInit,
  ViewChild,
  inject,
} from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { FormBuilder, FormGroup } from '@angular/forms';
import { v4 as uuid } from 'uuid';
 
import { CsvImportData, CsvImportHandler, CsvImportStatus } from 'ish-core/utils/csv/csv.import-handler';
 
import { OrganizationManagementFacade } from '../../../facades/organization-management.facade';
import { B2bUser } from '../../../models/b2b-user/b2b-user.model';
 
@Component({
  selector: 'ish-user-csv-import',
  templateUrl: './user-csv-import.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class UserCsvImportComponent implements OnInit {
  csvForm: FormGroup;
  status: CsvImportStatus = 'Default';
  // not-dead-code
  parsedUsers: B2bUser[] = [];
  // not-dead-code
  userHeaders: string[] = [
    'title',
    'firstName',
    'lastName',
    'email',
    'phone',
    'active',
    'budgetCurrency',
    'budgetValue',
    'budgetPeriod',
    'orderSpentLimitCurrency',
    'orderSpentLimitValue',
    'APP_B2B_BUYER',
    'APP_B2B_ACCOUNT_OWNER',
    'APP_B2B_APPROVER',
    'APP_B2B_COSTCENTER_OWNER',
    'APP_B2B_COSTOBJECT_MANAGER',
  ];
 
  private readonly destroyRef = inject(DestroyRef);
 
  @ViewChild('fileInput', { static: false }) fileInput: ElementRef<HTMLInputElement>;
 
  constructor(
    private fb: FormBuilder,
    private cdRef: ChangeDetectorRef,
    private organizationManagementFacade: OrganizationManagementFacade
  ) {}
 
  ngOnInit(): void {
    this.csvForm = this.fb.group({
      csvFile: [undefined],
    });
  }
 
  onFileChange(event: Event) {
    const input = event.target as HTMLInputElement;
    const file = input.files?.[0];
    Iif (!file) {
      return;
    }
 
    CsvImportHandler.processCsvFile(file, this.userHeaders)
      .pipe(takeUntilDestroyed(this.destroyRef))
      .subscribe({
        next: fileContent => {
          this.parsedUsers = this.parseCsvData(fileContent);
          this.status = 'Valid';
          this.cdRef.markForCheck();
        },
        error: error => {
          this.status = error;
          this.parsedUsers = [];
          this.cdRef.markForCheck();
        },
      });
  }
 
  // not-dead-code
  parseCsvData(csvData: CsvImportData): B2bUser[] {
    if (!csvData?.data || csvData.data.length === 0) {
      return [];
    }
 
    return csvData.data.map(line => {
      const values = line.split(',').map(v => v.trim());
      const user: B2bUser = {
        businessPartnerNo: `U${uuid()}`,
        roleIDs: [],
        userBudget: {
          budget: { type: 'Money', value: undefined, currency: undefined },
          budgetPeriod: undefined,
          orderSpentLimit: { type: 'Money', value: undefined, currency: undefined },
        },
      };
 
      csvData.headers.forEach((header, index) => {
        const value = values[index] !== undefined ? values[index] : '';
        this.processUserField(user, header, value);
      });
 
      return user;
    });
  }
 
  private processUserField(user: B2bUser, header: string, value: string): void {
    if (this.isPersonalInfoField(header)) {
      this.processPersonalInfo(user, header, value);
    } else if (this.isBudgetField(header)) {
      this.processBudgetInfo(user, header, value);
    } else if (this.isRoleField(header)) {
      this.processRoleInfo(user, header, value);
    }
  }
 
  private isPersonalInfoField(header: string): boolean {
    return ['title', 'firstName', 'lastName', 'email', 'phone', 'active'].includes(header);
  }
 
  private isBudgetField(header: string): boolean {
    return [
      'budgetCurrency',
      'budgetValue',
      'budgetPeriod',
      'orderSpentLimitCurrency',
      'orderSpentLimitValue',
    ].includes(header);
  }
 
  private isRoleField(header: string): boolean {
    return [
      'APP_B2B_BUYER',
      'APP_B2B_ACCOUNT_OWNER',
      'APP_B2B_APPROVER',
      'APP_B2B_COSTCENTER_OWNER',
      'APP_B2B_COSTOBJECT_MANAGER',
    ].includes(header);
  }
 
  private processPersonalInfo(user: B2bUser, header: string, value: string): void {
    switch (header) {
      case 'title':
        user.title = value;
        break;
      case 'firstName':
        user.firstName = value;
        break;
      case 'lastName':
        user.lastName = value;
        break;
      case 'email':
        user.email = value;
        break;
      case 'phone':
        user.phoneHome = value;
        break;
      case 'active':
        user.active = value.toLowerCase() === 'true';
        break;
    }
  }
 
  private processRoleInfo(user: B2bUser, header: string, value: string): void {
    Iif (value.toLowerCase() === 'true') {
      user.roleIDs.push(header);
    }
  }
 
  private processBudgetInfo(user: B2bUser, header: string, value: string): void {
    Iif (!user.userBudget) {
      return;
    }
 
    switch (header) {
      case 'budgetCurrency':
        user.userBudget.budget.currency = value;
        break;
      case 'budgetValue':
        user.userBudget.budget.value = value ? parseInt(value, 10) : undefined;
        break;
      case 'budgetPeriod':
        user.userBudget.budgetPeriod = value;
        break;
      case 'orderSpentLimitCurrency':
        user.userBudget.orderSpentLimit.currency = value;
        break;
      case 'orderSpentLimitValue':
        user.userBudget.orderSpentLimit.value = value ? parseInt(value, 10) : undefined;
        break;
    }
  }
 
  resetInput() {
    this.parsedUsers = [];
    this.status = 'Default';
  }
 
  submitUsers() {
    if (this.parsedUsers.length === 0) {
      return;
    }
    this.organizationManagementFacade.addUsersFromCsv(this.parsedUsers);
  }
 
  get isCsvDisabled() {
    return this.status !== 'Valid';
  }
}