Untitled

 avatar
unknown
plain_text
5 months ago
30 kB
7
Indexable
import {
  Component,
  ElementRef,
  OnDestroy,
  OnInit,
  ViewChild,
} from '@angular/core';
import { AbstractControl, FormBuilder, FormGroup } from '@angular/forms';
import { Observable, Subject, catchError, map, of, takeUntil } from 'rxjs';

import {
  sy_add_circle,
  sy_contact_reply,
  sy_tools_search,
} from '@aab/sc-aab-icon-set';
import { g670, n670 } from '@aab/sc-styles-colors';

import {
  LeaseStateService,
  NewContractsStateService,
  RequestedAssetsStateService,
} from '@state';
import {
  CommonService,
  LeaseTab,
  PopoverConfig,
  PopoverType,
  PopoversComponent,
  PopulateDomainDataType,
  TableWithSearchServiceType,
  transformForSelect,
} from '@shared';
import { AssetService, ItpService } from '@shared/services';
import { SelectOption } from '@ui-components';

import {
  dataFields,
  fields,
  items,
  loadITPTable,
} from './itp.component.constants';
import { ITPFormField } from './interface/form-field';
import { ITPFormControls } from './constants/form.constants';
import { IconType, Language } from './interface/form-field';
import { LeaseRequestFormField } from 'src/app/modules/lease/lease-request/interface/form.fields';
import { CONTRACT_ITP_MESSAGES } from './constants/error-message';
import {
  NcItp,
  NewContractsTab,
} from 'src/app/shared/interfaces/assets/new-contracts/nc-tab-payload';
import { CAOIFormField } from 'src/app/modules/lease/contact-and-other-info/interface/form-fields';
import { NcTabsService } from '../../service/nc-tabs.service';
import { TabId } from '../../constants/tabs';
// import { ClientFormField } from '../client/interfaces/form-fields';

@Component({
  selector: 'app-itp',
  templateUrl: './itp.component.html',
  styleUrls: ['./itp.component.scss'],
})
export class ItpComponent implements OnInit, OnDestroy {
  fields = fields;
  items = items;
  itpFields = dataFields;

  private readonly destroy$: Subject<void> = new Subject<void>();
  formField: typeof ITPFormField = ITPFormField;
  ITPForm: FormGroup = this.fb.group(ITPFormControls);

  //popover variables
  @ViewChild('popoversComponent', { static: true })
  popoversComponent: PopoversComponent;
  popoverConfig: PopoverConfig;
  popoverhServiceType: typeof TableWithSearchServiceType =
    TableWithSearchServiceType;

  @ViewChild('notification') notification: ElementRef;
  notificationMessage: string;

  drpdownAssetCodeMainGroup$: Observable<SelectOption[]> = of([]);
  AssetCodeMainGroupIdDetails$: Observable<SelectOption[]> = of([]);
  AssetCodeSubGroupDetails$: Observable<SelectOption[]> = of([]);
  uniqueIdType$: Observable<SelectOption[]> = of([]);
  supplierBusinessPartner$: Observable<SelectOption[]> = of([]);
  getItpData$: Observable<any>;

  iconColor = g670;
  add = sy_add_circle;
  backButton = sy_contact_reply;
  search = sy_tools_search;
  searchIconColour = n670;

  isOpenForm = false;
  language: typeof Language = Language;
  ITPTableRow: any = [];
  selectedserialNumberId: number = 0;
  newITP: boolean = false;
  rawITPData: any = [];

  constructor(
    private fb: FormBuilder,
    private commonService: CommonService,
    private itpService: ItpService,
    private leaseStateService: LeaseStateService,
    private newContractsStateService: NewContractsStateService,
    private assetService: AssetService,
    private requestedAssetsStateService: RequestedAssetsStateService,
    private ncTabsService: NcTabsService
  ) {
    // const id = this.leaseStateService.leaseDetails?.id;
    // const serialNumberId =
    //   this.newContractsStateService.selectedNewContract
    //     ?.requestObjectSerialNumberId;
    const language =
      this.leaseDetailsPayload[LeaseTab.ContactAndOtherInfo]?.[
        CAOIFormField.Language
      ];
    this.setUniqueIdType();
    //TODO need to check
    // this.setItpObjectData(id, serialNumberId);
    this.setAssetCodeMainGroup(this.lessorId, language);
  }

  setUniqueIdType() {
    this.uniqueIdType$ = this.commonService
      .getPopulateDomainDataForDropdown(PopulateDomainDataType.RegistratieSrt)
      .pipe(
        map(uniqueIdTypeDetails => transformForSelect(uniqueIdTypeDetails)),
        catchError(() => of([]))
      );
  }

  setItpObjectData(itpId: number, serialNumberId: number) {
    const id = this.leaseStateService.leaseDetails?.id;
    this.itpService
      .getItpObjectData(itpId, serialNumberId)
      .subscribe((value: any) => {
        value.forEach((element: any, index: number) => {
          this.ITPTableRow = [
            ...this.ITPTableRow,
            loadITPTable(element, index + 1, NewContractsTab.ITP, id),
          ];
        });
      });
  }

  get leaseDetailsPayload() {
    return this.leaseStateService.leaseDetailsPayload;
  }
  get lessorId() {
    return this.leaseDetailsPayload?.[LeaseTab.LeaseRequest]?.[
      LeaseRequestFormField.Lessor
    ];
  }

  get f(): { [key: string]: AbstractControl } {
    return this.ITPForm.controls;
  }
  get NcAssetTabData() {
    return this.newContractsStateService.newContractsPayload[
      NewContractsTab.NCAsset
    ];
  }
  get ITPPayload() {
    return this.newContractsStateService.newContractsPayload?.[
      NewContractsTab.ITP
    ];
  }

  disableField(formField: ITPFormField): void {
    this.f[formField]?.disable();
  }

  enabledField(formField: ITPFormField): void {
    this.f[formField]?.enable();
  }

  ngOnInit(): void {
    this.initialiseFieldsValues();
    this.setUpITPState();
    this.validateQuantity();
  }

  initialiseFieldsValues() {
    const id = this.leaseStateService.leaseDetails?.id;
    const rawITPData = this.ITPPayload?.[ITPFormField.itpDTO];
    if (rawITPData?.length > 0) {
      this.ITPTableRow = rawITPData?.map((row: any, index: number) =>
        loadITPTable(row, index + 1, NewContractsTab.ITP, id)
      );
    }
    this.ITPPayload[ITPFormField.itpDTO] = this.ITPTableRow;
  }

  setUpITPState() {
    this.ITPForm.valueChanges
      .pipe(takeUntil(this.destroy$))
      .subscribe(formFieldsValues => {
        formFieldsValues = this.ITPForm.getRawValue();
        this.newContractsStateService.itpForm = this.ITPForm;
        this.rawITPData = this.setupItpPayload(formFieldsValues as NcItp);
      });
  }

  setupItpPayload(values: NcItp) {
    return {
      [ITPFormField.Brand]: values?.[ITPFormField.Brand],
      [ITPFormField.Type]: values?.[ITPFormField.Type],
      [ITPFormField.LicensePlateNumber]:
        values?.[ITPFormField.LicensePlateNumber],
      [ITPFormField.YearOfManufacturing]:
        values?.[ITPFormField.YearOfManufacturing],
      [ITPFormField.Month]: values?.[ITPFormField.Month],
      [ITPFormField.Quantity]: values?.[ITPFormField.Quantity],
      [ITPFormField.AssetCode]: values?.[ITPFormField.AssetCode],
      [ITPFormField.AssetCode2]: values?.[ITPFormField.AssetCode2],
      [ITPFormField.AssetDescription]: values?.[ITPFormField.AssetDescription],
      [ITPFormField.UniqueID]: values?.[ITPFormField.UniqueID],
      [ITPFormField.UniqueID2]: values?.[ITPFormField.UniqueID2],
      [ITPFormField.UniqueIDType]: values?.[ITPFormField.UniqueIDType],
      [ITPFormField.SupplierBusinessPartner]:
        values?.[ITPFormField.SupplierBusinessPartner],
      [ITPFormField.SupplierBusinessPartnerDropdown]:
        values?.[ITPFormField.SupplierBusinessPartnerDropdown],
      [ITPFormField.InvoiceNumber]: values?.[ITPFormField.InvoiceNumber],
      [ITPFormField.InvoiceDate]: values?.[ITPFormField.InvoiceDate],
      [ITPFormField.Text]: values?.[ITPFormField.Text],
      [ITPFormField.AssetCodeMainGroup]:
        values?.[ITPFormField.AssetCodeMainGroup],
      [ITPFormField.AssetCodeMainGroupIdDetails]:
        values?.[ITPFormField.AssetCodeMainGroupIdDetails],
      [ITPFormField.AssetCodeSubGroupDetails]:
        values?.[ITPFormField.AssetCodeSubGroupDetails],
      [ITPFormField.HistoricId]:
        this.newContractsStateService.newContractsPayload.historicId,
      [ITPFormField.CalledOffObjectSerialNumberId]:
        this.newContractsStateService.newContractsPayload.serialNumberId,
    };
  }

  //set AssetCode MainGroup Details first dropdown
  setAssetCodeMainGroup(lessorId: number, language: string) {
    this.drpdownAssetCodeMainGroup$ = this.assetService
      .getAssetCodeMainGroup(lessorId, language)
      .pipe(
        map(drpdownAssetCodeMainGroup =>
          this.transformFunctionSelectChange(drpdownAssetCodeMainGroup)
        ),
        catchError(() => of([]))
      );
  }

  // set Asset Code Main GroupId Details
  setAssetCodeMainGroupId(
    lessorId: number,
    mainGroupId: string,
    language: string
  ) {
    this.AssetCodeMainGroupIdDetails$ = this.assetService
      .getAssetCodeSubGroupId(lessorId, mainGroupId, language)
      .pipe(
        map(AssetCodeMainGroupIdDetails =>
          this.transformFunctionSelectChange(AssetCodeMainGroupIdDetails)
        ),
        catchError(() => of([]))
      );
  }

  // set Asset Code Sub GroupId Details
  setAssetCodeSubGroupId(
    lessorId: number,
    subGroupId: string,
    language: string
  ) {
    this.AssetCodeSubGroupDetails$ = this.assetService
      .getAssetCodeObject(lessorId, subGroupId, language)
      .pipe(
        map(AssetCodeSubGroupDetails =>
          this.transformFunctionSelectChange(AssetCodeSubGroupDetails)
        ),
        catchError(() => of([]))
      );
  }

  inputChange($event: Event, formControlName: ITPFormField): void {
    const inputChangevalue = ($event.target as HTMLInputElement).value;
    this.f[formControlName]?.setValue(inputChangevalue, {
      onlySelf: true,
    });
    this.f[formControlName]?.updateValueAndValidity();
    this.applyValidationAfterChange(inputChangevalue, formControlName);
  }

  // Select change method for assigning selected value
  selectChange($event: Event, formControlName: ITPFormField): void {
    const event: { detail: { value: string } } = $event as CustomEvent;
    const selectChangevalue = event?.detail?.value || '';
    this.f[formControlName]?.setValue(selectChangevalue.toString(), {
      onlySelf: true,
    });
    this.f[formControlName]?.updateValueAndValidity();
    this.applyValidationAfterChange(selectChangevalue, formControlName);
  }

  applyValidationAfterChange(value: string, formField: ITPFormField): void {
    switch (formField) {
      case ITPFormField.LicensePlateNumber: {
        this.validateLicenseNo(value);
        break;
      }
      case ITPFormField.UniqueID: {
        this.validateUniqueId(value);
        break;
      }
      case ITPFormField.AssetCodeMainGroup: {
        this.mainGroupIdDetails();
        break;
      }
      case ITPFormField.AssetCodeMainGroupIdDetails: {
        this.subGroupIdDetails();
        break;
      }
      case ITPFormField.AssetCodeSubGroupDetails: {
        this.setObjectDeatils();
        this.ShowPopupMessageAfterFillingAssetCode();
        break;
      }
      case ITPFormField.Quantity: {
        this.validateQuantity();
        break;
      }
      default:
        break;
    }
  }

  validateQuantity() {
    const assetQuantity = this.NcAssetTabData?.objectQuantity ?? 0;
    let totalQuantity = 0;
    this.ITPTableRow?.forEach((item: any) => {
      if (item.serialNumberId === this.selectedserialNumberId) {
        totalQuantity = totalQuantity + 0;
      } else {
        totalQuantity =
          totalQuantity +
          parseInt(item.objectQuantity ? item.objectQuantity : 0);
      }
    });
    const currentObjectQuantity = parseInt(
      this.f[ITPFormField.Quantity].getRawValue()
    );
    const totalItpObjectQuantity = totalQuantity + currentObjectQuantity;
    if (totalItpObjectQuantity > assetQuantity) {
      this.f[ITPFormField.Quantity].setErrors({
        invalidValue: true,
        errorMessage:
          CONTRACT_ITP_MESSAGES.QUANTITY_ERROR_MSG1 +
          totalItpObjectQuantity +
          CONTRACT_ITP_MESSAGES.QUANTITY_ERROR_MSG2 +
          assetQuantity,
      });
    }
  }

  iconClicked($event: Event): void {
    const event: {
      detail: {
        name: string;
        data: number;
      };
    } = $event as CustomEvent;
    switch (event.detail.name) {
      case IconType.Remove: {
        this.removeITP(event.detail?.['data']);
        break;
      }
    }
  }

  // remove api called only when user tries to remove the already existing data in database
  // else only data removed from list
  removeITP(serialNumberId: number) {
    const arrayIndex = this.ITPTableRow.findIndex(
      (row: any) => row.serialNumberId === serialNumberId
    );
    const itpId = this.leaseStateService.leaseDetails?.id;
    this.itpService
      .getRemoveItp(itpId, serialNumberId, serialNumberId)
      .pipe(takeUntil(this.destroy$))
      .subscribe({
        next: () => {
          // this.removeRelationIds(this.relationNumber);
          // this.removeRelationIdButton = false;
        },
      });
    this.ITPTableRow.splice(arrayIndex, 1);
    this.ITPTableRow = this.ITPTableRow.map((item: any, index: number) => {
      return loadITPTable(
        item,
        index + 1,
        NewContractsTab.ITP,
        this.leaseStateService.leaseDetails?.id
      );
    });
    this.newContractsStateService.newContractsPayload[NewContractsTab.ITP][
      ITPFormField.itpDTO
    ] = this.ITPTableRow;
  }

  //populate address
  setSupplierPopulateAddress(relationId?: number): void {
    const relationNumber = relationId;
    if (relationNumber) {
      this.supplierBusinessPartner$ = this.commonService
        .populateAddresses(relationNumber)
        .pipe(
          map(supplierBusinessPartnerDetails =>
            this.transformFunctionAddress(supplierBusinessPartnerDetails)
          )
        );
      this.supplierBusinessPartner$.subscribe((event: SelectOption[]) => {
        this.f[ITPFormField.SupplierBusinessPartnerDropdown].setValue(
          event[0].data
        );
      });
    } else {
      this.supplierBusinessPartner$ = of({} as SelectOption[]);
    }
  }

  transformFunctionAddress(arrayDetails: any) {
    return arrayDetails.map((element: any) => ({
      ...element,
      name: element.label,
      value: element.data,
      id: element.id,
      serialNumber: element.calledOffObjectSerialNumberId,
    }));
  }

  validateLicenseNo(value: string) {
    if (value) {
      const rawData: any = {
        licenseNumber: value,
      };
      const params = new URLSearchParams(rawData).toString();
      this.itpService
        .validateLicenseNo(`?${params}`)
        .pipe(takeUntil(this.destroy$))
        .subscribe({
          next: res => {
            if (res.length > 0) {
              this.f[ITPFormField.LicensePlateNumber].setErrors({
                invalidValue: true,
                errorMessage:
                  CONTRACT_ITP_MESSAGES.LICENSE_NUMBER_ALREADY_EXISTS,
              });
            } else {
              this.f[ITPFormField.LicensePlateNumber].setErrors(null);
            }
          },
          error: () => {
            // handle errors
          },
          // complete: () => {
          //   // handle functions when completed
          // },
        });
    }
  }

  validateUniqueId(value: string) {
    if (value) {
      const rawData: any = {
        registrationNumber: value,
      };
      const params = new URLSearchParams(rawData).toString();
      this.itpService
        .validateUniqueId(`?${params}`)
        .pipe(takeUntil(this.destroy$))
        .subscribe({
          next: res => {
            if (res?.length > 0) {
              this.f[ITPFormField.UniqueID].setErrors({
                invalidSelection: true,
                errorMessage: CONTRACT_ITP_MESSAGES.UNIQUE_ID_ALREADY_EXISTS,
              });
            } else {
              this.f[ITPFormField.UniqueID].setErrors(null);
            }
          },
          error: () => {
            // handle errors
          },
          // complete: () => {
          //   // handle functions when completed
          // },
        });
    }
  }

  addNewITP() {
    this.newITP = true;
    const NCAssetObjectQuantity =
      this.newContractsStateService.newContractsAsset.objectQuantity;
    const requestedAssetFormValue =
      this.requestedAssetsStateService.requestedAssetForm?.value;
    let totalQuantity = 0;
    if (this.ITPTableRow?.length <= 0) {
      this.showForm(requestedAssetFormValue, 0, NCAssetObjectQuantity);
    } else {
      totalQuantity = this.ITPTableRow.reduce(
        (sum: number, row: any) => sum + row?.objectQuantity,
        0
      );
      if (totalQuantity >= parseInt(NCAssetObjectQuantity)) {
        this.openPopup();
      } else {
        this.showForm(
          requestedAssetFormValue,
          totalQuantity,
          NCAssetObjectQuantity
        );
      }
    }
  }

  showForm(
    requestedAssetFormValue: any,
    totalQuantity: number,
    NCAssetObjectQuantity: any
  ) {
    const objectQuantity = parseInt(NCAssetObjectQuantity) - totalQuantity;
    this.isOpenForm = true;
    this.ITPForm.reset();
    this.selectedserialNumberId = 0;
    const NCAssetFormValue = this.newContractsStateService.newContractsAsset;
    this.f[ITPFormField.AssetDescription].setValue(
      NCAssetFormValue?.description
    );
    this.f[ITPFormField.Quantity].setValue(objectQuantity);
    this.f[ITPFormField.AssetCode].setValue(NCAssetFormValue?.objectCode);
    this.f[ITPFormField.YearOfManufacturing].setValue(
      requestedAssetFormValue?.yearOfManufacturing
    );
    this.f[ITPFormField.Month].setValue(
      requestedAssetFormValue?.monthOfManufacturing
    );
    this.f[ITPFormField.SupplierBusinessPartner].setValue(
      this.newContractsStateService.newContractsPayload?.ncClient
        ?.supplierBusinessRelationNo
    );
    this.setSupplierPopulateAddress(
      this.newContractsStateService.newContractsPayload?.ncClient
        ?.supplierBusinessRelationNo
    );
  }

  openPopup() {
    this.notification.nativeElement.show();
    this.notificationMessage =
      'Failure adding ITP object : Adding ITP object prohibited, the object quantity of the contract object is reached. Contract object quantity is ' +
      this.newContractsStateService.newContractsAsset.objectQuantity +
      ' used quantity by other ITP objects is ' +
      this.newContractsStateService.newContractsAsset.objectQuantity;
  }

  updateITP(fromOnDestroy?: boolean) {
    this.isOpenForm = false;
    if (this.newITP) {
      this.newITP = false;
      const maxSerialNumberId = Math.max(
        this.ITPTableRow?.map((row: any) => row.serialNumberId)
      );
      this.setITPList(this.rawITPData, maxSerialNumberId);
    } else {
      this.setITPList(this.rawITPData, this.selectedserialNumberId);
    }
    if (fromOnDestroy) {
      this.ncTabsService.setCacheRequestForCurrentTabInNC(
        TabId.Itp,
        this.selectedserialNumberId
      );
    }
  }

  setITPList(formFieldsValues: NcItp, serialNumberId: number) {
    const id = this.leaseStateService.leaseDetails?.id;
    const index = this.ITPTableRow?.findIndex(
      (row: any) => row.serialNumberId === this.selectedserialNumberId
    );
    this.ITPTableRow[index === -1 ? this.ITPTableRow.length : index] =
      loadITPTable(
        formFieldsValues as NcItp,
        serialNumberId,
        NewContractsTab.ITP,
        id
      );
    this.newContractsStateService.newContractsPayload[NewContractsTab.ITP][
      ITPFormField.itpDTO
    ] = this.ITPTableRow;
  }
  //row click
  itpRowClicked($event: Event) {
    let eventDetails = ($event as CustomEvent).detail;
    this.isOpenForm = true;
    if (eventDetails?.row?.objectCode) {
      this.getAssetCodeDescription(eventDetails?.row?.objectCode);
    }
    eventDetails = this.setObjectQuantity(eventDetails);
    this.ITPForm.patchValue(eventDetails?.row);
    const clientData =
      this.newContractsStateService?.newContractsPayload?.[
        NewContractsTab.Client
      ];
    if (clientData?.supplierBusinessRelationNo) {
      this.f[ITPFormField.SupplierBusinessPartner].setValue(
        clientData?.supplierBusinessRelationNo
      );
      this.setSupplierPopulateAddress(clientData?.supplierBusinessRelationNo);
    } else {
      this.f[ITPFormField.SupplierBusinessPartner].setValue('');
      this.f[ITPFormField.SupplierBusinessPartnerDropdown].setValue('');
    }

    this.selectedserialNumberId = eventDetails?.row?.serialNumberId;
  }

  setObjectQuantity(eventDetails) {
    const ncAsset =
      this.newContractsStateService.newContractsPayload?.[
        NewContractsTab.NCAsset
      ];
    if (this.ITPPayload?.[ITPFormField.itpDTO]?.length > 1) {
      eventDetails.row.objectQuantity = eventDetails?.row?.objectQuantity
        ? eventDetails?.row?.objectQuantity
        : ncAsset?.objectQuantity;
      eventDetails.row.licenseNumber = eventDetails?.row?.licenseNumber
        ? eventDetails?.row?.licenseNumber
        : ncAsset?.licenseNumber;
    } else {
      eventDetails.row.objectQuantity = ncAsset?.objectQuantity;
      eventDetails.row.licenseNumber = ncAsset?.licenseNumber;
    }
    return eventDetails;
  }

  transformFunctionSelectChange(arrayDetails: any) {
    return arrayDetails.map((element: any) => ({
      ...element,
      value: element.id,
      name: element.description,
    }));
  }

  getAssetCodeDescription(objectCode: string) {
    const language =
      this.leaseDetailsPayload[LeaseTab.ContactAndOtherInfo]?.[
        CAOIFormField.Language
      ];
    this.setAssetCodeSearchValue(this.lessorId, objectCode, language);
  }

  setAssetCodeSearchValue(
    lessorId: number,
    searchValue: string,
    language: string
  ) {
    this.assetService
      .getAssetCodeSearchObject(lessorId, searchValue, language)
      .subscribe(data => {
        if (data?.errors) {
          this.f[ITPFormField.AssetCode].setErrors({
            invalidError: true,
            errorMessage: 'The object code is not a valid code.',
          });
          this.f[ITPFormField.AssetCode2].setValue('');
        } else {
          this.f[ITPFormField.AssetCode].setValue(data.objectId);
          this.f[ITPFormField.AssetCode2].setValue(data.objectDescription);
          if (
            data.objectDescription === searchValue ||
            data.objectId === searchValue
          ) {
            this.f[ITPFormField.AssetCodeMainGroup].setValue(data.mainGroupId);
            this.setAssetCodeMainGroupId(lessorId, data.mainGroupId, language);
            this.f[ITPFormField.AssetCodeMainGroupIdDetails].setValue(
              data.subGroupId
            );
            this.setAssetCodeSubGroupId(lessorId, data.subGroupId, language);
            this.f[ITPFormField.AssetCodeSubGroupDetails].setValue(
              data.objectId
            );
          }
        }
      });
  }

  validationAfterFocusOut(value: string, formField: ITPFormField): void {
    switch (formField) {
      case ITPFormField.Month: {
        this.validateMonth();
        break;
      }
      case ITPFormField.AssetCode: {
        this.getAssetCodeDescription(value);
        break;
      }
      case ITPFormField.SupplierBusinessPartner: {
        this.setSupplierPopulateAddress(parseInt(value));
        break;
      }
    }
  }

  onFocusOut($event: Event, formControlName: ITPFormField) {
    const value = ($event.target as HTMLInputElement).value;
    this.f[formControlName]?.setValue(value, {
      onlySelf: true,
    });
    this.f[formControlName]?.updateValueAndValidity();
    this.validationAfterFocusOut(value, formControlName);
  }

  mainGroupIdDetails() {
    const assetCodeValue =
      this.f[ITPFormField.AssetCodeMainGroup].getRawValue();
    this.f[ITPFormField.AssetCodeMainGroupIdDetails].reset();
    this.f[ITPFormField.AssetCodeSubGroupDetails].reset();
    this.setAssetCodeMainGroupId(
      this.lessorId,
      assetCodeValue,
      this.leaseDetailsPayload[LeaseTab.ContactAndOtherInfo]?.[
        CAOIFormField.Language
      ]
    );
  }

  subGroupIdDetails() {
    const mainGroupIdDetailsAssetCodeValue =
      this.f[ITPFormField.AssetCodeMainGroupIdDetails].getRawValue();
    this.f[ITPFormField.AssetCodeSubGroupDetails].reset();
    this.setAssetCodeSubGroupId(
      this.lessorId,
      mainGroupIdDetailsAssetCodeValue,
      this.leaseDetailsPayload[LeaseTab.ContactAndOtherInfo]?.[
        CAOIFormField.Language
      ]
    );
  }

  setObjectDeatils() {
    const mainGroupIdDetailsAssetCodeValue =
      this.f[ITPFormField.AssetCodeMainGroupIdDetails].getRawValue();
    const assetCodeSubGroupDetails =
      this.f[ITPFormField.AssetCodeSubGroupDetails].getRawValue();
    this.f[ITPFormField.AssetCode].setValue(assetCodeSubGroupDetails);

    this.assetService
      .getAssetCodeObject(
        this.lessorId,
        mainGroupIdDetailsAssetCodeValue,
        this.leaseDetailsPayload[LeaseTab.ContactAndOtherInfo]?.[
          CAOIFormField.Language
        ]
      )
      .subscribe((response: any) => {
        response.forEach((element: any) => {
          if (assetCodeSubGroupDetails === element.id) {
            this.f[ITPFormField.AssetCode2].setValue(element.description);
          }
        });
      });
  }

  ShowPopupMessageAfterFillingAssetCode() {
    this.popoverConfig = {
      title:
        'Please note that residual value is calculated using the started as date of manufacturing',
      type: PopoverType.supplier,
      modalSize: 'medium',
    };
    this.popoversComponent.openModal();
  }

  //Clear Assest Code Details
  clearAssestCodeDetails(): void {
    this.f[this.formField.AssetCode].setValue('');
    this.f[this.formField.AssetCode2].setValue('');
    this.f[this.formField.AssetCode].updateValueAndValidity();
  }

  clearSupplierBusinessDetails() {
    this.f[this.formField.SupplierBusinessPartner].setValue('');
    this.f[this.formField.SupplierBusinessPartnerDropdown].setValue('');
    this.supplierBusinessPartner$ = of({} as SelectOption[]);
  }

  // validateMonth(): void {
  //   const value = this.f[ITPFormField.Month].getRawValue();
  //   if (value == Math.floor(value) || value == '') {
  //     this.f[ITPFormField.Month].setErrors({
  //       invalidError: false,
  //     });
  //     if (value <= 12 || value == '') {
  //       this.f[ITPFormField.Month].setErrors({
  //         invalidError: false,
  //       });
  //       if (value > 0 || value == '') {
  //         this.f[ITPFormField.Month].setErrors({
  //           invalidError: false,
  //         });
  //       } else {
  //         this.showMonthErrorMsg(value);
  //       }
  //     } else {
  //       this.showMonthErrorMsg(value);
  //     }
  //   } else {
  //     this.showMonthErrorMsg("This property is mandatory.");
  //   }
  // }

  validateMonth(): void {
    const value = this.f[ITPFormField.Month].getRawValue();
    if (value == '' || value == 0) {
      this.f[ITPFormField.Month].setErrors({
        invalidError: true,
        errorMessage: 'This property is mandatory.',
      });
    }
    if (Number(value) > 12 || Number(value) < 0) {
      this.f[ITPFormField.Month].setErrors({
        invalidError: true,
      });
      this.showMonthErrorMsg(value);
    }
  }

  showMonthErrorMsg(value: any) {
    this.f[ITPFormField.Month].setErrors({
      invalidError: true,
      errorMessage:
        CONTRACT_ITP_MESSAGES.MONTH_ERROR_MSG +
        value +
        CONTRACT_ITP_MESSAGES.MONTH_ERROR_MSG1,
    });
  }

  openPopover(popoverServiceType?: TableWithSearchServiceType) {
    switch (popoverServiceType) {
      case TableWithSearchServiceType.UltimateCompany: {
        const popoverReqBody = {
          relationNumber:
            this.f[ITPFormField.SupplierBusinessPartner].getRawValue(),
        };
        this.popoverConfig = {
          title: 'Search a relation',
          type: PopoverType.TableWithSearch,
          tableWithSearchInput: {
            currentValue: popoverReqBody,
            serviceType: TableWithSearchServiceType.UltimateCompany,
          },
          id: ITPFormField.SupplierBusinessPartner,
        };

        break;
      }
      case TableWithSearchServiceType.IndustyrId:
        {
          this.popoverConfig = {
            title: '',
            type: PopoverType.ErrorPopup,
            modalSize: 'medium',
          };
        }
        break;
    }
    this.popoversComponent.openModal();
  }

  selectedPopoverValue(event: any): void {
    // TODO: we need to set popover value into formfields
    this.popoversComponent.closeModal();
    this.fillFormFields(event.event.row);
    this.setSupplierPopulateAddress(event.event.row.relationNumber);
  }

  // method to append form fields based on value selected or refresh button click
  fillFormFields(event: any) {
    if (event) {
      this.ITPForm.patchValue({
        [ITPFormField.SupplierBusinessPartner]: event.relationNumber,
      });
    }
  }

  ngOnDestroy(): void {
    if (this.isOpenForm) {
      this.updateITP(true);
    }
    this.newContractsStateService.setContractsObject();
    this.destroy$.next();
    this.destroy$.complete();
  }
}
Editor is loading...
Leave a Comment