Untitled

mail@pastecode.io avatar
unknown
plain_text
9 days ago
30 kB
1
Indexable
Never
import { ChangeDetectorRef, Component, ViewChild } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { MenuItem, MessageService } from 'primeng/api';
import { Api } from '../utils/Model/dashboard/api.interface';
import CommonFunctions from '../utils/Util/CommonFunctions';
import { ApiTemplateService } from './api-template.service';
import { FileUpload, FileUploadEvent } from 'primeng/fileupload';
import * as XLSX from 'xlsx';
import * as JsonToXML from "js2xmlparser";
import { FileSaverService } from 'ngx-filesaver';
import { Sheet } from '../utils/Model/dashboard/sheet.interface';
import { Constants } from '../utils/Constants/Constants';
import { CreateOutstandingBuilder } from '../utils/Model/builders/CreateOutstandingBuilder';
import { OutstandingGeneralData } from '../utils/Model/request/CreateOutstanding/model/OutstandingGeneralData';
import { Calendars } from '../utils/Model/request/CreateOutstanding/model/Calendars';
import { MisCodes } from '../utils/Model/request/CreateOutstanding/model/MisCodes';
import { AdjustForCloseGeneralData } from '../utils/Model/request/AdjustForClose/model/AdjustForCloseGeneralData';
import { AdjustForCloseBuilder } from '../utils/Model/builders/AdjustForCloseBuilder';
import { HttpEvent, HttpEventType } from '@angular/common/http';
import { SheetComponent } from '../utils/Model/dashboard/sheetComponent.interface';
import { AlterMISCodesBuilder } from '../utils/Model/builders/AlterMISCodesBuilder';
import { AlterMISCodesGeneralDataRequest } from '../utils/Model/request/AlterMISCodes/model/AlterMISCodesGeneralDataRequest';

@Component({
  selector: 'app-api-template',
  templateUrl: './api-template.component.html',
  styleUrls: ['./api-template.component.scss'],
  providers: [MessageService]
})
export class ApiTemplateComponent {
  api!: Api;
  loading: boolean = true;
  isSend: boolean = false;
  fileUploading: boolean = false;
  tabs: Array<Sheet> = [];
  visibleMsgArray: Array<boolean> = [];
  checkSuccessArray: any = {};
  checkCommentArray: any = {};
  checkObjectArray: any = {};
  checkSuccessArrayCopy: any = {};
  checkCommentArrayCopy: any = {};
  checkObjectArrayCopy: any = {};
  requestArray: Array<any> = [];
  activeIndex: number = 0;
  items: MenuItem[] | undefined;
  itemsSplit: MenuItem[] = [
    {
      label: 'Clear',
      icon: 'pi pi-refresh',
      command: () => {
        this.clear();
      }
    }
  ];
  home: MenuItem | undefined;
  rows: any = {};
  jsonToSend: any = {};
  pasteMode: boolean = false;

  constructor(
    private changeDetection: ChangeDetectorRef,
    private route: ActivatedRoute,
    private apiTemplateService: ApiTemplateService,
    private messageService: MessageService,
    private fileSaverService: FileSaverService) { }

  @ViewChild('fileUpload') fileUp!: FileUpload;

  ngOnInit() {
    let fileName = Constants.BLANK;
    this.route.params.subscribe(params => {
      fileName = params['fileName'];
    });

    this.apiTemplateService.getFile('assets/plantillas/' + fileName + '.json').subscribe({
      next: (response) => {
        this.api = JSON.parse(response);
      },
      error: (error) => console.error(error),
      complete: () => {
        console.log(fileName + ' loaded');
        this.loading = false;
        this.items = [{ label: this.api.apiName }];
        this.home = { icon: 'pi pi-home', routerLink: '/dashboard' };
        this.loadTabs();
      }
    });
  }

  ngAfterViewInit() {
    this.fileUp.validate = (file: File): boolean => {
      let fileType = false;
      let acceptableTypes = this.fileUp.accept?.split(',').map((type) => type.trim());
      for (let type of acceptableTypes!) {
        let acceptable = this.fileUp.isWildcard(type) ? this.fileUp.getTypeClass(file.type) === this.fileUp.getTypeClass(type) : file.type == type || this.fileUp.getFileExtension(file).toLowerCase() === type.toLowerCase();
        if (acceptable) {
          fileType = true;
        }
      }
      if (this.fileUp.accept && !fileType) {
        this.messageService.add(CommonFunctions.createError(Constants.ERROR_HEADER,
          this.fileUp.invalidFileTypeMessageSummary.replace('{0}', file.name) +
          this.fileUp.invalidFileTypeMessageDetail.replace('{0}', this.fileUp.accept))
        );
        return false;
      }

      if (this.fileUp.maxFileSize && file.size > this.fileUp.maxFileSize) {
        this.messageService.add(CommonFunctions.createError(Constants.ERROR_HEADER,
          this.fileUp.invalidFileSizeMessageSummary.replace('{0}', file.name) +
          this.fileUp.invalidFileSizeMessageDetail.replace('{0}', this.fileUp.formatSize(this.fileUp.maxFileSize)))
        );
        return false;
      }

      return true;
    }
  }

  excelDateToJSDate(serial: string): Date {
    let utc_days = Math.floor(Number(serial) - 25569);
    let utc_value = utc_days * 86400;
    let date_info = new Date(utc_value * 1000);
    let fractional_day = Number(serial) - Math.floor(Number(serial)) + 0.0000001;
    let total_seconds = Math.floor(86400 * fractional_day);
    let seconds = total_seconds % 60;
    total_seconds -= seconds;
    let hours = Math.floor(total_seconds / (60 * 60));
    let minutes = Math.floor(total_seconds / 60) % 60;
    return new Date(date_info.getFullYear(), date_info.getMonth(), date_info.getDate(), hours, minutes, seconds);
  }

  capturarArchivo(event: FileUploadEvent) {
    let misElementos: any[] = [];
    const file: File = event.files[0];
    if (file) {
      let reader: FileReader = new FileReader();
      reader.onloadend = (e) => {
        let json = XLSX.read(reader.result, {
          type: 'binary'
        });
        Object.keys(json.Sheets).forEach((element: any) => {
          if (json.Sheets[element]) {
            const elemento: HTMLElement | null = document.getElementById("table_" + element);
            if (elemento) {
              misElementos = this.transformarObjeto(json.Sheets[element]);
              const filaImput: number = elemento.querySelectorAll('thead tr th').length;
              const keys: number[] = Array.prototype.slice.call(Object.keys(misElementos));
              if (keys.length > 0) {
                const maxRows: number = Math.max(...keys) + 1;
                let maxColumns: number = 0;
                keys.forEach((columns: number) => {
                  const subKeys: number[] = Array.prototype.slice.call(Object.keys(misElementos[columns]));
                  if (Math.max(...subKeys) > maxColumns) {
                    maxColumns = Math.max(...subKeys);
                  }
                });
                if (maxColumns >= filaImput) {
                  this.messageService.add(CommonFunctions.createError(Constants.ERROR_HEADER, 'Bad excell format in the Page ' + element));
                  return;
                }
                this.rows[element] = maxRows;
                this.changeDetection.detectChanges();
                const inputElements: NodeListOf<Element> = elemento.querySelectorAll('tbody input');
                keys.forEach((row: number) => {
                  const subKeys: number[] = Array.prototype.slice.call(Object.keys(misElementos[row]));
                  subKeys.forEach((column: number) => {
                    const input: any = inputElements[(+row) * filaImput + (+column)];
                    input['value'] = misElementos[row][column].value;
                    if (misElementos[row][column].date && (typeof misElementos[row][column].value) == 'number') {
                      input['value'] = this.excelDateToJSDate(misElementos[row][column].value.toString()).toLocaleDateString("en-GB");
                    }
                  });
                });
              }
            } else {
              this.messageService.add(CommonFunctions.createError(Constants.ERROR_HEADER, 'Bad name of the Page ' + element));
            }
          }
        });
        this.fileUploading = false;
      }
      reader.readAsBinaryString(file);
    }
    this.fileUp.clear();
  }

  getColumnNumber(column: string): number {
    let result = 0;
    for (let i = 0; i < column.length; i++) {
      result *= 26;
      result += column.charCodeAt(i) - 'A'.charCodeAt(0) + 1;
    }
    return result;
  }

  transformarObjeto(objetoOriginal: any): any {
    let objetoTransformado: any = {};
    for (let clave in objetoOriginal) {
      if (clave !== "!ref" && clave !== "!margins") {
        let partesClave = clave.match(/([A-Z]+)(\d+)/);
        if (partesClave != null) {
          let indiceFila = parseInt(partesClave[2]) - 1;
          let indiceColumna = this.getColumnNumber(partesClave[1]) - 1;

          if (!objetoTransformado[indiceFila]) {
            objetoTransformado[indiceFila] = {};
          }

          objetoTransformado[indiceFila][indiceColumna] = {
            "value": objetoOriginal[clave]["v"]
          };
          const formatoFechaRegex = /^\d+\/\d+\/\d+$/;
          if (formatoFechaRegex.test(objetoOriginal[clave]["w"])) {
            objetoTransformado[indiceFila][indiceColumna]["date"] = true;
            objetoTransformado[indiceFila][indiceColumna]["value"] = objetoOriginal[clave]["v"];
          }
        }
      }
    }
    delete objetoTransformado['0'];
    Object.keys(objetoTransformado).forEach((key) => {
      const newKey = (parseInt(key) - 1);
      objetoTransformado[newKey] = objetoTransformado[key];
      delete objetoTransformado[key];
    });
    console.log(objetoTransformado);
    return objetoTransformado;
  }

  loadTabs() {
    this.api.structure.forEach((element) => {
      this.tabs.push(element);
    });
  }

  getItems(tab: string) {
    return this.api.structure.filter((sheet) => sheet.sheetName == tab)[0].sheetMap;
  }

  getNumRows(tab: string) {
    if (this.rows[tab] == null || this.rows[tab] == undefined) {
      this.rows[tab] = 1;
    }
    return Array(this.rows[tab]);
  }

  addRow(tab: string) {
    this.rows[tab] += 1;
  }

  checkSuccess(i: number, tab: string): string {
    return this.checkSuccessArray[tab][i];
  }

  showDialog(i: number) {
    this.visibleMsgArray[i] = true;
  }

  getComment(i: number, tab: string): string {
    let finalMsg: string = Constants.BLANK;
    try {
      this.checkCommentArray[tab][i].messagesList.forEach((element: { value: string; }) => {
        finalMsg = finalMsg.concat(element.value);
        finalMsg = finalMsg.concat(" # ");
      });
    } catch (error) {
      //console.log('waiting') ONLY FOR DEVELOPMENT
    }
    return finalMsg;
  }

  removeRow(tab: string, msg?: boolean) {
    if (this.rows[tab] != 1) {
      this.rows[tab] -= 1;
    } else {
      this.isSend = false;
      if (!msg) {
        this.messageService.add(CommonFunctions.createWarn(Constants.WARN_HEADER, 'You can\'t delete more rows.'));
      }
    }
  }

  sendInfo() {
    this.loading = true;
    this.requestArray = [];
    let regexCheck = true;
    this.tabs.forEach((element) => {
      this.deleteBlankRows(element);
      if (regexCheck && this.isPageNotBlank(element)) {
        if (this.isSend) {
          this.checkSuccessArrayCopy[element.sheetName] = this.checkSuccessArray[element.sheetName];
          this.checkCommentArrayCopy[element.sheetName] = this.checkCommentArray[element.sheetName];
          this.checkObjectArrayCopy[element.sheetName] = this.checkObjectArray[element.sheetName];
        }
        this.checkSuccessArray[element.sheetName] = [];
        this.checkCommentArray[element.sheetName] = [];
        this.checkObjectArray[element.sheetName] = [];
        this.jsonToSend[element.sheetName] = [];
        const table = document.getElementById("table_" + element.sheetName);
        if (table) {
          const rows = Array.from(table.querySelectorAll('tbody > tr'));
          rows.forEach((tr) => {
            let tempJson: any = {};
            const inputs = Array.from(tr.getElementsByTagName('input'));
            inputs.forEach((input) => {
              const header = input.getAttribute('header');
              const value = input.value;
              if (header != null) {
                if (this.checkRequired(header, element.sheetName) && value === Constants.BLANK && regexCheck) {
                  regexCheck = false;
                  this.isSend = false;
                  this.handleError('Page ' + element.sheetName + ' ' + header + ' required inputs can\'t be empty');
                } else if (value !== Constants.BLANK && input.checkValidity() === false && regexCheck) {
                  regexCheck = false;
                  this.isSend = false;
                  this.handleError('Page ' + element.sheetName + ' ' + header + ' validation error');
                } else {
                  tempJson[header] = value;
                }
              }
            });
            if (Object.keys(tempJson).length !== 0) {
              this.jsonToSend[element.sheetName].push(tempJson);
            }
          });
        }
      }
    });
    if (regexCheck && this.isPageNotBlank(this.tabs[0])) {
      let finalRequest: any;
      switch (this.api.endPoint) {
        case '/api/loanDrawdown':
          this.jsonToSend['OutstandingGeneralData'].forEach((jsonString: OutstandingGeneralData, index: number) => {
            let arrayPrimaryKeys: Array<string> = ['aliasDealName', 'facilityName', 'alias'];
            finalRequest = new CreateOutstandingBuilder().withOutstandingGeneralData(jsonString);
            if (this.isPageNotBlank(this.tabs[1])) {
              let arrayMisCodes: Array<MisCodes> = [];
              this.jsonToSend['MisCodes'].forEach((misCodeJson: MisCodes) => {
                if (this.checkPrimaryKeys(jsonString, misCodeJson, arrayPrimaryKeys)) {
                  arrayMisCodes.push(misCodeJson);
                }
              });
              finalRequest = finalRequest.withMisCodes(arrayMisCodes);
            }
            if (this.isPageNotBlank(this.tabs[2])) {
              let arrayCalendars: Array<Calendars> = [];
              this.jsonToSend['HolidayCalendar'].forEach((calendarJson: Calendars) => {
                if (this.checkPrimaryKeys(jsonString, calendarJson, arrayPrimaryKeys)) {
                  arrayCalendars.push(calendarJson);
                }
              });
              finalRequest = finalRequest.withCalendars(arrayCalendars);
            }
            finalRequest = finalRequest.build();
            if (finalRequest != null) {
              finalRequest = this.limpiarObjeto(finalRequest);
              console.log(finalRequest);
              this.requestArray.push(finalRequest);
            }
          });
          break;
        case '/api/discount/adjustForClose':
          this.jsonToSend['GeneralData'].forEach((jsonString: AdjustForCloseGeneralData, index: number) => {
            finalRequest = new AdjustForCloseBuilder().withAdjustForCloseGeneralData(jsonString).build();
            if (finalRequest != null) {
              finalRequest = this.limpiarObjeto(finalRequest);
              console.log(finalRequest);
              this.requestArray.push(finalRequest);
            }
          });
          break;
        case '/api/alterMISCodes':
          this.jsonToSend['GeneralData'].forEach((jsonString: AlterMISCodesGeneralDataRequest, index: number) => {
            let arrayPrimaryKeys: Array<string> = ['ownerId'];
            finalRequest = new AlterMISCodesBuilder().withAlterMISCodesGeneralDataRequest(jsonString);
            if (this.isPageNotBlank(this.tabs[1])) {
              let arrayMisCodes: Array<MisCodes> = [];
              this.jsonToSend['MisCodes'].forEach((misCodeJson: MisCodes) => {
                if (this.checkPrimaryKeys(jsonString, misCodeJson, arrayPrimaryKeys)) {
                  arrayMisCodes.push(misCodeJson);
                }
              });
              finalRequest = finalRequest.withMisCodes(arrayMisCodes);
            }
            finalRequest = finalRequest.build();
            if (finalRequest != null) {
              finalRequest = this.limpiarObjeto(finalRequest);
              console.log(finalRequest);
              this.requestArray.push(finalRequest);
            }
          });
          break;
        default:
          this.handleError('Api endpoint not found or this api is not implemented yet.');
          break;
      }
    } else {
      regexCheck = false;
      this.isSend = false;
      this.loading = false;
      this.handleError('Page ' + this.tabs[0].sheetName + ' validation error');
    }
    this.doRequestsInBatch(this.requestArray);
  }

  async doRequest(finalRequest: any, index: number): Promise<any> {
    this.setWait(index);
    if (this.isSend && 
      this.checkSuccessArrayCopy && 
      this.checkSuccessArrayCopy[this.tabs[0].sheetName] && 
      this.checkSuccessArrayCopy[this.tabs[0].sheetName][index] == Constants.TRUE) {
      this.cloneValue(index);
      this.loading = false;
      return Promise.resolve();
    } else {
      return new Promise((resolve, reject) => {
        this.apiTemplateService.postJson(this.api.endPoint, finalRequest).subscribe({
          next: (response) => {
            this.setResponse(index, response, finalRequest);
            this.loading = false;
            this.isSend = true;
            resolve(response); // Resuelve la promesa con la respuesta
          },
          error: (error) => {
            this.loading = false;
            this.isSend = true;
            console.error(error);
            this.handleError(error);
            reject(error); // Rechaza la promesa con el error
          }
        });
      });
    }
  }

  async doRequestsInBatch(requests: any[], startIndex: number = 0) {
    if (startIndex >= requests.length) {
      return;
    }
    const batch = requests.slice(startIndex, startIndex + Constants.OPEN_PORTS_NUMBER);
    const promises = batch.map((request, index) => this.doRequest(request, startIndex + index));
    await Promise.all(promises);
    await this.doRequestsInBatch(requests, startIndex + Constants.OPEN_PORTS_NUMBER);
  }

  limpiarObjeto(obj: any): any {
    for (const clave in obj) {
      if (obj.hasOwnProperty(clave)) {
        const valor = obj[clave];
        if (valor == Constants.BLANK) {
          delete obj[clave];
        } else if (Array.isArray(valor)) {
          obj[clave] = valor.map((elemento: any) => this.limpiarObjeto(elemento));
          obj[clave] = obj[clave].filter((elemento: any) => {
            return Object.keys(elemento).length > 0;
          });
          if (obj[clave].length === 0) {
            delete obj[clave];
          }
        } else if (typeof valor === 'object') {
          obj[clave] = this.limpiarObjeto(valor);
          if (Object.keys(obj[clave]).length === 0) {
            delete obj[clave];
          }
        }
      }
    }
    return obj;
  }

  isPageNotBlank(page: Sheet): boolean {
    const table = document.getElementById("table_" + page.sheetName);
    if (table != null) {
      const rows = Array.from(table.querySelectorAll('tbody > tr'));
      if (rows.length > 1) {
        return true;
      }
      const inputs = Array.from(rows[0].getElementsByTagName('input'));
      return !inputs.every(input => input.value.trim() === Constants.BLANK);
    }
    return true;
  }

  deleteBlankRows(page: Sheet): void {
    const tableId = "table_" + page.sheetName;
    const table = document.getElementById(tableId);
    if (table) {
      const rows = Array.from(table.querySelectorAll('tbody > tr'));
      if (rows.length > 1) {
        const reverseRows = [...rows].reverse();
        for (const row of reverseRows) {
          const inputs = Array.from(row.querySelectorAll('input'));
          if (inputs.every(input => input.value.trim() === Constants.BLANK)) {
            this.removeRow(page.sheetName, true);
            this.changeDetection.detectChanges();
          }
        }
      }
    }
  }

  checkPrimaryKeys(baseObject: any, objectToCheck: any, primaryKeys: Array<string>): boolean {
    for (const objectKey of primaryKeys) {
      if(objectToCheck[objectKey] == undefined) {
        objectToCheck[objectKey] = Constants.BLANK;
      }
      if (baseObject[objectKey] != objectToCheck[objectKey]) {
        return false;
      }
    }
    return true;
  }

  handleError(message: string) {
    this.loading = false;
    this.messageService.add(CommonFunctions.createError(Constants.ERROR_HEADER, message));
  }

  onPaste(event: ClipboardEvent, tab: string) {
    if (this.pasteMode) {
      event.preventDefault();
      const clipboardData = event.clipboardData;
      if (clipboardData) {
        const pastedText = clipboardData.getData('text');
        const rows = pastedText.split('\r\n');
        const table = rows.map(row => row.split('\t'));
        const rowsOld = this.rows[tab];
        this.rows[tab] += rows.length - 1;
        this.changeDetection.detectChanges();
        const tabElement = document.getElementById(`table_${tab}`);
        if (!tabElement) {
          return;
        }

        const inputElements = tabElement.querySelectorAll('tbody input');
        const nInputPorFila = tabElement.querySelectorAll('tbody tr')[0].querySelectorAll('input').length;
        let rowIndex = -1;
        let columnIndex = -1;

        inputElements.forEach((input, index) => {
          if (input == event.target) {
            rowIndex = Math.floor(index / nInputPorFila);
            columnIndex = index % nInputPorFila;
            if (rowsOld < rowIndex + table.length - 1) {
              this.rows[tab] = rowIndex + table.length - 1;
            } else {
              this.rows[tab] = rowsOld;
            }
          }
        });

        if (rowIndex === -1 || columnIndex === -1) {
          return;
        }

        if (columnIndex + table[0].length > nInputPorFila) {
          this.rows[tab] = rowsOld;
          this.messageService.add(CommonFunctions.createWarn(Constants.WARN_HEADER, 'You can\'t paste more column than the ones in the file.'));
          return;
        }
        let rowCounter = 0;
        for (let i = rowIndex; i < rowIndex + table.length - 1; i++) {
          let colCounter = 0;
          for (let j = columnIndex; j < columnIndex + table[0].length; j++) {
            const input: any = inputElements[i * nInputPorFila + j];
            input['value'] = table[rowCounter][colCounter];
            colCounter++;
            if (colCounter == table[0].length) {
              colCounter = 0;
              rowCounter++;
            }
          }
        }
      }
    }
  }

  getCurrentSheetName(): string {
    return this.tabs[this.activeIndex].sheetName;
  }

  checkRequired(input: string, sheet: string): boolean {
    let ret = false;
    this.api.structure.forEach((element) => {
      if (element.sheetName == sheet) {
        element.sheetMap.forEach((campos) => {
          if (campos.keyName == input) {
            ret = campos.required;
          }
        });
      }
    });
    return ret;
  }

  clear() {
    this.isSend = false;
    this.api.structure.forEach((element) => {
      this.rows[element.sheetName] = 1;
    });
    Array.prototype.slice.call(document.getElementsByTagName('input')).forEach((input) => {
      input.value = Constants.BLANK;
    });
  }

  customUpload() {
    this.fileUploading = true;
    this.fileUp.uploading = true;
    this.fileUp.msgs = [];
    let formData = new FormData();

    this.fileUp.onBeforeUpload.emit({
      formData: formData
    });

    for (let i = 0; i < this.fileUp.files.length; i++) {
      formData.append(this.fileUp.name!, this.fileUp.files[i], this.fileUp.files[i].name);
    }
    this.apiTemplateService.postFile(
      this.fileUp.method,
      this.fileUp.url, formData,
      this.fileUp.headers,
      this.fileUp.withCredentials
    ).subscribe({
      next: (event: HttpEvent<any>) => {
        switch (event.type) {
          case HttpEventType.Sent:
            this.fileUp.onSend.emit({
              originalEvent: event,
              formData: formData
            });
            break;
          case HttpEventType.Response:
            this.fileUp.uploading = false;
            this.fileUp.progress = 0;

            if (event['status'] >= 200 && event['status'] < 300) {
              if (this.fileUp.fileLimit) {
                this.fileUp.uploadedFileCount += this.fileUp.files.length;
              }

              this.fileUp.onUpload.emit({ originalEvent: event, files: this.fileUp.files });
            } else {
              this.fileUp.onError.emit({ files: this.fileUp.files });
            }

            this.clear();
            break;
          case HttpEventType.UploadProgress: {
            if (event['loaded']) {
              this.fileUp.progress = Math.round((event['loaded'] * 100) / event['total']!);
            }

            this.fileUp.onProgress.emit({ originalEvent: event, progress: this.fileUp.progress });
            break;
          }
        }

        this.fileUp.cd.markForCheck();
      },
      error: (error: ErrorEvent) => {
        this.fileUploading = false;
        this.fileUp.uploading = false;
        this.fileUp.onError.emit({ files: this.fileUp.files, error: error });
      }
    });
  }

  getUrl(): string {
    return CommonFunctions.findEntorno(Number(localStorage.getItem('entornoId'))).getUrl() + "/api/upload";
  }

  downloadTemplate(): void {
    this.apiTemplateService.getExcel('assets/templates/' + this.api.fileName + '.xlsx').subscribe({
      next: (data) => {
        const blob = new Blob([data], { type: 'application/vnd.ms-excel;charset=utf-8' });
        this.fileSaverService.save(blob, this.api.fileName + '.xlsx');
      },
      error: (error) => console.error(error)
    });
  }

  isSomeDataPending(): { icon: string, msg: string, disabled: boolean } {
    let object: { icon: string, msg: string, disabled: boolean } = {
      icon: "pi pi-database",
      msg: "Results",
      disabled: false
    };
    if (this.checkSuccessArray[this.tabs[0].sheetName].includes('wait')) {
      object = {
        icon: "pi pi-spin pi-cog",
        msg: "Generating",
        disabled: true
      };
    }
    return object;
  }

  uploadIcon(): string {
    let icono = this.fileUploading ? "pi-spin pi-spinner" : "pi-file-import";
    return icono;
  }

  setWait(index: number) {
    this.checkSuccessArray[this.tabs[0].sheetName][index] = Constants.WAIT;
    this.checkCommentArray[this.tabs[0].sheetName][index] = Constants.WAIT;
    this.checkObjectArray[this.tabs[0].sheetName][index] = Constants.WAIT;
  }

  cloneValue(index: number) {
    this.checkSuccessArray[this.tabs[0].sheetName][index] = this.checkSuccessArrayCopy[this.tabs[0].sheetName][index];
    this.checkCommentArray[this.tabs[0].sheetName][index] = this.checkCommentArrayCopy[this.tabs[0].sheetName][index];
    this.checkObjectArray[this.tabs[0].sheetName][index] = this.checkObjectArrayCopy[this.tabs[0].sheetName][index];
  }

  setResponse(index: number, response: any, finalRequest: any) {
    this.checkSuccessArray[this.tabs[0].sheetName][index] = JSON.parse(response).success;
    this.checkCommentArray[this.tabs[0].sheetName][index] = JSON.parse(response).messages;
    this.checkObjectArray[this.tabs[0].sheetName][index] = JSON.stringify(finalRequest);
  }

  getResultString(i: number, tab: string): string {
    if (this.checkSuccessArray[tab][i] == Constants.TRUE) {
      return "OK ✔️";
    } else if (this.checkSuccessArray[tab][i] == Constants.FALSE) {
      return "KO ❌";
    } else if (this.checkSuccessArray[tab][i] == Constants.WAIT) {
      return "IN PROGRESS";
    }
    return "NOT SENT";
  }

  downloadData(): void {
    let resultado: Array<any> = [];
    this.checkSuccessArray[this.tabs[0].sheetName].forEach((element: string, index: number) => {
      let obj: any = {
        row: index + 2,
        response: this.getResultString(index, this.tabs[0].sheetName),
        comments: this.getComment(index, this.tabs[0].sheetName)
      }
      let json = JSON.parse(this.checkObjectArray[this.tabs[0].sheetName][index]);
      this.tabs.forEach((str: Sheet) => {
        if(str.endpointObject in json) {
          str.sheetMap.forEach((sheetComponent: SheetComponent) => {
            if(!Array.isArray(json[str.endpointObject])) {
              if(sheetComponent.keyName in json[str.endpointObject]) {
                obj[str.endpointObject+ '_' +sheetComponent.keyName] = json[str.endpointObject][sheetComponent.keyName]
              }
            } else {
              if(sheetComponent.keyName in json[str.endpointObject][0]) {
                obj[str.endpointObject+ '_' +sheetComponent.keyName] = json[str.endpointObject][0][sheetComponent.keyName]
              }
            }
          });
        }
      });
      obj['json'] = this.checkObjectArray[this.tabs[0].sheetName][index];
      resultado.push(obj);
    });

    const fileName = `${this.api.fileName}.xml`;
    const fileType = this.fileSaverService.genType(fileName);
    const txtBlob = new Blob([
      JsonToXML.parse("resultados", { "resultado": resultado }, {
        format: {
          doubleQuotes: true
        },
        declaration: {
          include: true,
          encoding: 'UTF-8'
        }
      }
      )], { type: fileType });
    this.fileSaverService.save(txtBlob, fileName);
  }
}
Leave a Comment