Fatura

Fatura Script

(async () => {
  try {
    
    if (this.opener.route.snapshot.params.mode == 'mustahsil') {
      this.recordService.formGroup.controls.TYPEID.setValue(9); //sadece e-müstahsiil seçeneği görünüp disabled ediliyor.
      this.recordService.formGroup.controls.InvoiceTypeCode.setValue(
        'MUSTAHSILMAKBUZ'
      );
      this.recordService.formGroup.controls.ProfileID.setValue('EARSIVBELGE');
      this.recordService.formGroup.controls.TYPEID.disable();
      this.recordService.children.faturaTab.component.tabGroupService.children[0].componentRef.instance.hide = true; //alt gruptaki indirimler tabının gizlenmesi
      this.recordService.children.faturaTab.component.updateTabs();
      this.recordService.children.faturaUstBilgileri.children[1].label = angus.languageService.dynamicTranslator.translate(
        'e-Müstahsil'
      );
      this.recordService.children.faturaUstBilgileri.children[2].label = angus.languageService.dynamicTranslator.translate(
        'e-Müstahsil Log'
      );
      this.recordService.children.faturaBilgileri.header = angus.languageService.dynamicTranslator.translate(
        'Müstahsil Bilgileri'
      ); //panelin adını değiştireceğiz.
      this.recordService.header = angus.languageService.dynamicTranslator.translate(
        'Müstahsil Makbuzu'
      );
      this.recordService.children.faturaUstBilgileri.component.tabGroup.selectedTabChange.subscribe(
        (x) => {
          try {
            document.getElementById('gonderim2').disabled = false;
            document
              .getElementById('gonderim2')
              .classList.remove('mat-button-disabled', 'mat-disabled-button');

            document.getElementById('sorgula2').disabled = false;
            document
              .getElementById('sorgula2')
              .classList.remove('mat-button-disabled', 'mat-disabled-button');

            document.getElementById('iptal2').disabled = false;
            document
              .getElementById('iptal2')
              .classList.remove('mat-button-disabled', 'mat-disabled-button');
          } catch (e) {
            console.error('nextStateBtn not found', e);
          }
        }
      );
    }
    var destroyed = new window.rxjs.Subject();
    var currencyRateIsManuel = false;
    var lastcurrencyRateAutomatic = 0;

    if (this.recordService.lastData) {
      rxjs
        .combineLatest(
          this.recordService.formGroup.controls.CURRENCY_CURRENCYID.valueChanges.pipe(
            rxjs.startWith(
              this.recordService.formGroup.controls.CURRENCY_CURRENCYID.value
            )
          ),
          this.recordService.formGroup.controls.IssueDate.valueChanges.pipe(
            rxjs.startWith(
              this.recordService.formGroup.controls.IssueDate.value
            )
          )
        )
        
        .subscribe(([CurrId, IssueDate]) => {
          
          if (currencyRateIsManuel == false) {
                        if (
              this.recordService.formGroup.controls.CURRENCY_CURRENCYID.value !=
              142
            ) {
              console.log('this:::', this);
              this.recordService._curFind();
            } else {
              this.recordService.formGroup.controls.CURRENCYRATE.setValue(1);
              this.recordService.formGroup.controls.CURRENCYRATE.markAsDirty();
            }
          }
        });
      this.recordService.formGroup.controls.CURRENCY_CURRENCYID.valueChanges.subscribe(
        (x) => {
          currencyRateIsManuel = false;
        }
      );
      this.recordService.formGroup.controls.CURRENCYRATE.valueChanges
        .pipe(rxjs.debounceTime(300))
        .subscribe((x) => {
          
          if (!x) {
            currencyRateIsManuel = false;
          } else {
            if (
              !this.lastcurrencyRateAutomatic ||
              this.lastcurrencyRateAutomatic != x
            ) {
              if (!(x == 0 || x == 1)) currencyRateIsManuel = true;
            }
          }
        }); //CURRENCYRATE
    }
    this.recordService.children.faturaUstBilgileri.component.tabGroup.selectedTabChange.subscribe(
      (x) => {
        const enabled = this.api.tenant.EINVOICEENABLED;
        const controls = this.recordService.formGroup.controls;
        if (!enabled) {
          try {
            document.querySelector(
              recordClass + ' div.group.ang-group-EInvoiceButtons'
            ).style.display = 'none';
          } catch (e) {}
        } else {
          rxjs
            .combineLatest(
              controls.SENDINGSTATUS.valueChanges.pipe(
                rxjs.startWith(controls.SENDINGSTATUS.value)
              ),
              controls.TYPEID.valueChanges.pipe(
                rxjs.startWith(controls.TYPEID.value)
              ),
              controls.ProfileID.valueChanges.pipe(
                rxjs.startWith(controls.ProfileID.value)
              )
            )
            .pipe(rxjs.debounceTime(100))
            .subscribe(([sendingStatusValue, typeValue, profileId]) => {
              debugger;
              
              if (
                typeValue == 2 ||
                typeValue == 4 ||
                typeValue == 6 ||
                typeValue == 21 ||
                typeValue == 23 ||
                typeValue == 25
              ) {
                disabledButton('btninvoiceRejectAcceptBtn', false);
                disabledButton('prnt-btn', false);
                disabledButton('fatura-record-fatOnzBtn', true);
                disabledButton('btnInvoiceSend', true);
              } else {
                disabledButton('btninvoiceRejectAcceptBtn', true);
                disabledButton('prnt-btn', true);
                disabledButton('fatura-record-fatOnzBtn', false);
                disabledButton('btnInvoiceSend', false);
              }

              
              if (
                [2, 4, 6, 21, 23, 25].indexOf(typeValue) !== -1 ||
                sendingStatusValue == 255 ||
                sendingStatusValue == 6
              ) {
                //if (sendingStatusValue == 6 || typeValue == 21 || typeValue == 23 || typeValue == 25 || sendingStatusValue == 255 ) {
                disabledButton('btnInvoiceSend', true);
              } else {
                disabledButton('btnInvoiceSend', false);
              }

              
              if (sendingStatusValue < 2 || sendingStatusValue > 5) {
                disabledButton('btnInvoiceInQuery', true);
              } else {
                disabledButton('btnInvoiceInQuery', false);
              }

             
              if (
                sendingStatusValue < 2 ||
                sendingStatusValue > 5 ||
                profileId != 'EARSIVFATURA'
              ) {
                disabledButton('btnInvoiceCancel', true);
              } else {
                disabledButton('btnInvoiceCancel', false);
              }
            });
        }

        if (
          angus.permissionService.isAuthorized([
            'Accounting Full',
            'Administrator',
            'Accounting',
            'HotelOwner',
          ]) &&
          angus.api.tenant.ENABLE_EFATURASUPPLIER_ONINVOICEFORM
        ) {
          this.recordService.formGroup.controls.SUPPLIERID_NAME.enable();
          this.recordService.formGroup.controls.SUPPLIERID_NAME.markAsDirty();
        } else {
          this.recordService.formGroup.controls.SUPPLIERID_NAME.disable();
          this.recordService.formGroup.controls.SUPPLIERID_NAME.markAsDirty();
        }
      }
    );

    /*const awaitIf = async (fn, ms = 100) => {
      await new Promise(async (resolve, reject) => {
        let result = false;
        try {
          result = fn();
        } catch (e) {
          console.error(e);
        }

        if (result) {
          resolve(true);
        } else {
          await rxjs.timer(ms).toPromise();
          resolve(await awaitIf(fn));
        }
      });
    };*/

    const awaitIf = async (fn, ms = 100) => {
      let result = false;
      while (!result) {
        try {
          result = fn();
        } catch (e) {
          console.error(e);
        }
        if (!result) await rxjs.timer(ms).toPromise();
      }
    };

    const recordClass = '.ang-record-' + this.recordService.component.recordID;

    function disabledButton(id, disabled = false) {
      try {
        const btn = document.querySelector(recordClass + ' #' + id);
        if (!disabled) {
          btn.disabled = false;
          btn.classList.remove('mat-button-disabled', 'mat-disabled-button');
        } else {
          btn.disabled = true;
          btn.classList.add('mat-button-disabled', 'mat-disabled-button');
        }
      } catch (e) {
        console.error('query not found', query, e);
      }
      
    }

    this._setColumnVisibility = (typeId) => {
      let faturaRecGrid = this.allGrids['stock-invoice-line'];
      if (document.getElementById('openStocks'))
        document.getElementById('openStocks').disabled = true;

      
      if ([3, 4, 23, 24, 9].indexOf(typeId) !== -1) {
        if (document.getElementById('openStocks'))
          document.getElementById('openStocks').disabled = false;
        this.recordService.formGroup.controls.IGNOREQUANTITY.enable();
        faturaRecGrid.grid.agGrid.columnApi.setColumnsVisible(
          ['ACCOUNTID_ACC'],
          false
        );
        faturaRecGrid.grid.agGrid.columnApi.setColumnsVisible(
          ['STOCKID_NAME'],
          true
        );
        faturaRecGrid.grid.agGrid.columnApi.setColumnsVisible(
          ['DEPID_DEPARTMENTNAME', 'REVID_REVENUENAME'],
          false
        );
        this.recordService.formGroup.controls.STOCKSTOREID_NAME.enable();
      }
      
      else if ([5, 6, 25, 26].indexOf(typeId) !== -1) {
        this.recordService.formGroup.controls.IGNOREQUANTITY.disable();
        this.recordService.formGroup.controls.IGNOREQUANTITY.setValue(0);
        this.recordService.formGroup.controls.IGNOREQUANTITY.markAsDirty();
        faturaRecGrid.grid.agGrid.columnApi.setColumnsVisible(
          ['ACCOUNTID_ACC'],
          true
        );
        faturaRecGrid.grid.agGrid.columnApi.setColumnsVisible(
          ['STOCKID_NAME'],
          false
        );
        faturaRecGrid.grid.agGrid.columnApi.setColumnsVisible(
          ['DEPID_DEPARTMENTNAME', 'REVID_REVENUENAME'],
          false
        );

        this.recordService.formGroup.controls.STOCKSTOREID.setValue(0);
        this.recordService.formGroup.controls.STOCKSTOREID.setValue(null);
        this.recordService.formGroup.controls.STOCKSTOREID_NAME.setValue(null);
        this.recordService.formGroup.controls.STOCKSTOREID_NAME.markAsDirty();
        this.recordService.formGroup.controls.STOCKSTOREID.markAsDirty();
        this.recordService.formGroup.controls.STOCKSTOREID_NAME.disable();
        this.recordService.formGroup.controls.STOCKSTOREID.disable();

        /* this.allFormControls['STOCKSTOREID_NAME'].markAsPristine();
        this.allFormControls['STOCKSTOREID_NAME'].setValue(null);
        this.allFormControls['STOCKSTOREID'].setValue(null);
        this.allFormControls['STOCKSTOREID_NAME'].disable();
        this.allFormControls['STOCKSTOREID_NAME'].setValidators(null);*/
      }
      
      else if ([1, 2, 21, 22].indexOf(typeId) !== -1) {
        this.recordService.formGroup.controls.IGNOREQUANTITY.disable();
        this.recordService.formGroup.controls.IGNOREQUANTITY.setValue(0);
        faturaRecGrid.grid.agGrid.columnApi.setColumnsVisible(
          ['ACCOUNTID_ACC'],
          false
        );
        faturaRecGrid.grid.agGrid.columnApi.setColumnsVisible(
          ['STOCKID_NAME'],
          false
        );
        faturaRecGrid.grid.agGrid.columnApi.setColumnsVisible(
          ['DEPID_DEPARTMENTNAME', 'REVID_REVENUENAME'],
          true
        );

        this.recordService.formGroup.controls.STOCKSTOREID.setValue(0);
        this.recordService.formGroup.controls.STOCKSTOREID.setValue(null);
        this.recordService.formGroup.controls.STOCKSTOREID_NAME.setValue(null);
        

        
        this.recordService.formGroup.controls.STOCKSTOREID_NAME.markAsDirty();
        this.recordService.formGroup.controls.STOCKSTOREID.markAsDirty();
        this.recordService.formGroup.controls.STOCKSTOREID_NAME.disable();
        this.recordService.formGroup.controls.STOCKSTOREID.disable();

        /*this.allFormControls['STOCKSTOREID_NAME'].markAsPristine();
        this.allFormControls['STOCKSTOREID_NAME'].setValue(null);
        this.allFormControls['STOCKSTOREID'].setValue(null);
        this.allFormControls['STOCKSTOREID_NAME'].disable();
        this.allFormControls['STOCKSTOREID_NAME'].setValidators(null);*/
      }

      let invoiceDescriptionVisible = [3, 24, 5, 26].indexOf(typeId) !== -1;
      faturaRecGrid.grid.agGrid.columnApi.setColumnsVisible(
        ['ItemName'],
        invoiceDescriptionVisible
      );
    };

    this.TypeIdChange = async () => {
      let faturaRecGrid = this.allGrids['stock-invoice-line'];
      await awaitIf(() => faturaRecGrid.grid && faturaRecGrid.grid.agGrid); //grid yüklenene kadar bekle
      await awaitIf(() => faturaRecGrid.grid && faturaRecGrid.grid.agGrid);
      await awaitIf(() => faturaRecGrid.grid && faturaRecGrid.grid.agGrid);
      await faturaRecGrid.grid.gridShareds.onRowLoad
        .pipe(rxjs.first((x) => x))
        .toPromise(); //grid data yüklenene kadar bekle

      faturaRecGrid.grid.agGrid.api.forEachNode((rowNode) => {
        if (rowNode.data.TaxExemptionReasonCode_DISPLAYNAME !== null) {
          let taxExemptionReasonType = rowNode.data.TaxExemptionReasonCode_TYPE;
          if (taxExemptionReasonType == 0) {
            this.recordService.formGroup
              .get('InvoiceTypeCode')
              .setValue('ISTISNA');
          } else if (taxExemptionReasonType == 2) {
            this.recordService.formGroup
              .get('InvoiceTypeCode')
              .setValue('TEVKIFAT');
          } else if (
            [1, 3, 5].indexOf(
              this.recordService.formGroup.controls.TYPEID.value
            ) != -1 &&
            taxExemptionReasonType != 0 &&
            taxExemptionReasonType != 2
          ) {
            this.recordService.formGroup
              .get('InvoiceTypeCode')
              .setValue('SATIS');
          } else if (
            [22, 24, 26].indexOf(
              this.recordService.formGroup.controls.TYPEID.value
            ) != -1 &&
            taxExemptionReasonType != 0 &&
            taxExemptionReasonType != 2
          ) {
            this.recordService.formGroup
              .get('InvoiceTypeCode')
              .setValue('IADE');
            
          }
        }
      });
    };
    this.disabledFieldsOrGrids = async (isActive) => {
      
      debugger;
      if (!this.recordService.formGroup.controls.ID.value) isActive = true;

      const sendingStatus = this.recordService.formGroup.controls.SENDINGSTATUS
        .value;
      const typeId = this.recordService.formGroup.controls.TYPEID.value;
      console.log('TYPEID:::::: ', typeId);
      if (typeId == 4 || typeId == 2 || typeId == 6 || typeId == 25) return;

      console.log('sendingStatus: ' + sendingStatus + ' typeId: ' + typeId);
      if ([0, 1, 2].indexOf(sendingStatus) != -1) return;
      const I =
        [0, 1, 2].indexOf(sendingStatus) != -1 &&
        [1, 3, 5, 7, 9, 22, 24, 26, 28].indexOf(typeId) != -1;
      if (isActive == null)
        if (I) {
          isActive = true;
        } else {
          isActive = false;
        }

      const fields = [
        'IssueDate',
        'BRANCHID_NAME',
        'APPCARDID_ACC',
        'InvoiceId',
        'ADDRESSID_ADDRESSINFO',
        'OID',
      ]; 
      const grids = [
        'stock-invoice-line',
        'stock-invoice-allowance',
        'efatvatgroup',
      ];
      
      try {
        try {
          
          grids.forEach(async (grid) => {
            var _Grid = this.allGrids[grid];
            console.log('Grid: ', grid);

            if (_Grid) {
              
              _Grid.grid.buttonsForTemplate.addButton = isActive;
              _Grid.grid.buttonsForTemplate.saveButton = isActive;
              _Grid.grid.buttonsForTemplate.deleteButton = isActive;
              _Grid.grid.buttonsForTemplate.editButton = isActive;
              
                         

            
              await rxjs.timer(10).toPromise();
              
          

              console.log(
                'grid : ' + grid + ' property settings complete successfully'
              );
            }
          });
        } catch (e) {
          console.log('Grid enabled/disabled error: ', e);
        }
        try {
          if (isActive == true) {
            fields.forEach((input) => {
              console.log('input: ', input);
              this.recordService.formGroup.controls[input].enable();
            });
          } else {
            fields.forEach((input) => {
              console.log('input2: ', input);
              this.recordService.formGroup.controls[input].disable();
            });
          }
        } catch (e) {
          console.log('input enabled/disabled error: ', e);
        }
      } catch (e) {
        console.log('disabledFieldsOrGrids error: ', e);
      }
    };

    /*let efatvatgroupGrid = this.allGrids['efatvatgroup'];
    await awaitIf(() => efatvatgroupGrid.grid && efatvatgroupGrid.grid.agGrid && efatvatgroupGrid.grid.agGridReady, 0);
    await efatvatgroupGrid.grid.loadData(false);*/

    if (!angus.api.tenant.ACCOUNTING_USESUBACCOUNT) {
      this.allFormControls['SUBACCOUNTID_CODENAME'].disable();
      
    }

    document.querySelector(
      '.ang-record-AllInvoices .ang-panel-stocks'
    ).style.display = 'none';
    document.querySelector(
      '.ang-record-AllInvoices .ang-panel-stocks'
    ).parentElement.style.display = 'none';
    document.querySelector(
      '.ang-record-AllInvoices .dynamic-container'
    ).style.gridTemplateAreas = `"faturaUstBilgileri faturaUstBilgileri faturaBilgileri" "faturaSatirlari faturaSatirlari faturaSatirlari" "faturaTab faturaTab faturaAltBilgi"`;
    document.querySelector('#openStocks .mat-icon').style.transform =
      'rotate(0deg)';

    await awaitIf(
      () =>
        this.recordService.elements.storeLookup.api.innerComponent
          .innerComponent.formControl,
      100
    );
    const stockStoreControl = this.recordService.elements.storeLookup.api
      .innerComponent.innerComponent.formControl;
    this.allFormControls['BRANCHID'].valueChanges
      .pipe(
        rxjs.filter(
          (value, index) => index > 1 || this.mode.value === 'insert'
        ),
        rxjs.distinctUntilChanged()
      )
      .subscribe((branchID) => {
        this.recordService.formGroup.controls.STOCKSTOREID.setValue(null);
        stockStoreControl.setValue('abc');
        stockStoreControl.setValue('');
      });

    /* this.recordService.formGroup.controls.BRANCHID.valueChanges.subscribe((x) => {
      
      if (x) {
        this.recordService.formGroup.controls.STOCKSTOREID.markAsDirty();
        this.recordService.formGroup.controls.STOCKSTOREID.setValue(null);
        stockStoreControl.setValue("abc"); //depo lookubına bir kere istek attırmak için abc yazıp siliyoruz
        stockStoreControl.setValue("");
      }
    });*/

    const subAccountControl = this.recordService.elements.subAccountLookup.api
      .formControl;
    this.recordService.formGroup.controls.APPCARDID.valueChanges.subscribe(
      (x) => {
        if (x) {
          this.recordService.formGroup.controls.SUBACCOUNTID.setValue(null);
          this.recordService.formGroup.controls.SUBACCOUNTID.markAsDirty();
          subAccountControl.setValue('abc'); //alt cari lookubına bir kere istek attırmak için abc yazıp siliyoruz
          subAccountControl.setValue('');
        }
      }
    );

    rxjs
      .combineLatest(
        this.recordService.formGroup.controls.APPCARDID_PT.valueChanges.pipe(
          rxjs.startWith(
            this.recordService.formGroup.controls.APPCARDID_PT.value
          )
        ),
        this.recordService.formGroup.controls.IssueDate.valueChanges.pipe(
          rxjs.startWith(this.recordService.formGroup.controls.IssueDate.value)
        )
      )

      .subscribe(([appcardid_pt, IssueDate]) => {
        if (this.recordService.component.mode.value === 'insert') {
          let Payment_TermDays = this.recordService.formGroup.controls
            .APPCARDID_PT.value;

          if (Payment_TermDays) {
            let IssueDate = this.recordService.formGroup.controls.IssueDate
              .value;
            let Payment_PaymentDueDate = this.recordService.formGroup.controls
              .Payment_PaymentDueDate.value;
            this.allFormControls['Payment_PaymentDueDate'].setValue(
              moment(IssueDate)
                .add(parseInt(Payment_TermDays), 'd')
                .format('YYYY-MM-DD'),
              {
                emitEvent: false,
              }
            );
          }
        }
      });

    let faturaRecGrid = this.allGrids['stock-invoice-line'];
    await awaitIf(
      () =>
        faturaRecGrid.grid &&
        faturaRecGrid.grid.agGrid &&
        faturaRecGrid.grid.agGridReady,
      0
    );

    
    faturaRecGrid.grid.agGridReady.subscribe((_) => {
      this.recordService.formGroup.controls.TYPEID.valueChanges
        .pipe(
          window.rxjs.skipUntil(destroyed),
          window.rxjs.takeUntil(this.close),
          window.rxjs.startWith(this.allFormControls['TYPEID'].value)
        )
        .subscribe(async (value) => {
          await rxjs.timer(0).toPromise();
          if (this.recordService.formGroup.controls.TYPEID.touched) {
            this.disabledFieldsOrGrids(null);
            this.TypeIdChange();
            this._setColumnVisibility(value);
          }
        });
    });

    var glb_line_midTotal = 0; //satırların indirimsiz toplamı sum(adet*fiyat)
    var glb_line_taxExclusiveTotal = 0; //matrah toplamı
    var glb_line_taxTotal = 0; //kdv toplamı
    var glb_line_allowanceTotalAmount = 0; //satirlardan gelen indirim toplami.

   
    this.recordService.calcTotals = (gridInstance) => {
      //debugger;
      if (!gridInstance) {
        gridInstance = this.allGrids['stock-invoice-line'].grid;
      }
      const formGroup = this.recordService.formGroup;
      
      glb_line_midTotal = 0;
      glb_line_taxExclusiveTotal = 0;
      glb_line_taxTotal = 0;
      glb_line_allowanceTotalAmount = 0;

      
      let midTotal = 0; 
      let taxExclusiveTotal = 0; 
      let taxTotal = 0; 
      let taxInclusiveTotal = 0; 
      gridInstance.agGrid.api.forEachNode((rowNode) => {
        try {
          if (!rowNode.toBeDeleted)
            if (rowNode.data.UNITPRICE > 0) {
              midTotal +=
                (rowNode.data.UNITPRICE || 0) *
                (rowNode.data.InvoicedQuantity_Value || 0);
              taxExclusiveTotal += rowNode.data.LineExtensionAmount_Value || 0;
              taxTotal += rowNode.data.TaxAmount || 0; 
              taxInclusiveTotal += rowNode.data.TAXINCLUSIVEAMOUNT || 0;
            }
        } catch (e) {
          console.log('err: ', e);
        }
      });
      glb_line_midTotal = midTotal;
      glb_line_taxExclusiveTotal = taxExclusiveTotal;
      glb_line_taxTotal = taxTotal;
      glb_line_allowanceTotalAmount = midTotal - taxExclusiveTotal;

      
      formGroup.get('LineExtensionAmount_Value').setValue(midTotal);
      formGroup.get('TaxExclusiveAmount').setValue(taxExclusiveTotal);
      formGroup.get('TaxInclusiveAmount').setValue(taxInclusiveTotal);
     
      

      let payableRoundingAmount = formGroup.get('PayableRoundingAmount').value;
      formGroup
        .get('PayableAmount')
        .setValue(
          formGroup.get('TaxInclusiveAmount').value + payableRoundingAmount
        );

      this.recordService.calcDiscount(
        this.allGrids['stock-invoice-allowance'].grid,
        glb_line_taxExclusiveTotal,
        glb_line_allowanceTotalAmount,
        glb_line_taxTotal
      );
    };
    
    this.recordService.calcDiscount = (
      gridInstance,
      glb_line_taxExclusiveTotal = 0,
      glb_line_allowanceTotalAmount = 0,
      glb_line_taxTotal = 0
    ) => {
      
      if (!gridInstance) {
        gridInstance = this.allGrids['stock-invoice-allowance'].grid;
      }
      const recordFormGroup = this.recordService.formGroup;
      
      let taxExclusiveTotal_calc = glb_line_taxExclusiveTotal; 

      
      let chargeAmountTotal_bottom = 0,
        discountAmountTotal_bottom = 0;
      gridInstance.agGrid.api.forEachNode((rowNode) => {
        if (rowNode.data.Amount > 0 || rowNode.data.PERCENT > 0) {
          if (rowNode.data.ChargeIndicator) {
            let chargeAmount =
              rowNode.data.Amount && !rowNode.data.PERCENT
                ? rowNode.data.Amount
                : taxExclusiveTotal_calc * (rowNode.data.PERCENT / 100);
            taxExclusiveTotal_calc += chargeAmount;
            chargeAmountTotal_bottom += chargeAmount;
          } else {
            
            let discountAmount =
              rowNode.data.Amount && !rowNode.data.PERCENT
                ? rowNode.data.Amount
                : taxExclusiveTotal_calc * (rowNode.data.PERCENT / 100);
            taxExclusiveTotal_calc -= discountAmount;
            discountAmountTotal_bottom += discountAmount;
          }
        }
      });

      
      let rate = taxExclusiveTotal_calc / glb_line_taxExclusiveTotal;

      if (!rate) {
        rate = 0;
      }

      recordFormGroup
        .get('AllowanceTotalAmount')
        .setValue(
          Math.round(
            (glb_line_allowanceTotalAmount + discountAmountTotal_bottom) * 100
          ) / 100
        );
      recordFormGroup
        .get('ChargeTotalAmount')
        .setValue(Math.round(chargeAmountTotal_bottom, 2));

      recordFormGroup
        .get('TaxExclusiveAmount')
        .setValue(taxExclusiveTotal_calc);

      recordFormGroup
        .get('TaxAmount_Value')
        .setValue(Math.round(glb_line_taxTotal * rate * 100) / 100);
      recordFormGroup
        .get('TaxInclusiveAmount')
        .setValue(
          taxExclusiveTotal_calc +
            Math.round(glb_line_taxTotal * rate * 100) / 100
        );
      let payableRoundingAmount = recordFormGroup.get('PayableRoundingAmount')
        .value;
      recordFormGroup
        .get('PayableAmount')
        .setValue(
          recordFormGroup.get('TaxInclusiveAmount').value +
            payableRoundingAmount
        );
    };

    let allowanceGrid = this.allGrids['stock-invoice-allowance'];
    await awaitIf(
      () =>
        allowanceGrid.grid &&
        allowanceGrid.grid.agGrid &&
        allowanceGrid.grid.agGridReady,
      0
    );
    
    this.allGrids['stock-invoice-allowance'].grid.rowDeleted.subscribe((_) => {
      this.recordService.calcTotals();
    });
    
    this.allGrids['stock-invoice-line'].grid.rowDeleted.subscribe((_) => {
      this.recordService.calcTotals();
    });

    let startValue = this.recordService.formGroup.controls.TYPEID.value;
    this.allFormControls['TYPEID'].valueChanges
      .pipe(rxjs.startWith(startValue))
      .subscribe(async (typeId) => {
        
        if ([1, 3, 5].indexOf(typeId) != -1) {
          
          this.allFormControls['InvoiceTypeCode'].setValue('SATIS'); 
        } else if ([22, 24, 26].indexOf(typeId) != -1) {
          this.allFormControls['InvoiceTypeCode'].setValue('IADE');
        }
        this.disabledFieldsOrGrids(null);
        this.TypeIdChange();
        this._setColumnVisibility(typeId);
      });

    this.allFormControls['ID'].valueChanges
      .pipe(rxjs.startWith(startValue))
      .subscribe(async (typeId) => {
        console.log('!!!!!!!!!!!!!!!!!!!!!!!!!!');
        this.disabledFieldsOrGrids(null);
        this.TypeIdChange();
        this._setColumnVisibility(
          this.recordService.formGroup.controls.TYPEID.value
        );
      });

    this.allFormControls['SENDINGSTATUS'].valueChanges
      .pipe(rxjs.startWith(startValue))
      .subscribe(async (typeId) => {
       
        this.disabledFieldsOrGrids(null);
      });

       
    this.isUsedInvoice = false;

    let invoiceId = this.allFormControls['InvoiceId'];
    let typeId = this.allFormControls['TYPEID'];
    let appCardId = this.allFormControls['APPCARDID'];
    let fatId = this.allFormControls['ID'];
    if (!fatId.value) {
      let checkInvoiceId$ = rxjs.combineLatest(
        invoiceId.valueChanges.pipe(rxjs.debounceTime(500)),
        typeId.valueChanges.pipe(rxjs.startWith(typeId.value)),
        appCardId.valueChanges.pipe(rxjs.startWith(appCardId.value))
      );
      const unsubscribe$ = new rxjs.Subject();

      checkInvoiceId$
        .pipe(
          rxjs.distinctUntilChanged(),
          rxjs.takeUntil(unsubscribe$ || this.isDestroy$)
        )
        .subscribe((val) => {
          this.isUsedInvoice = false;

          if (val[0] !== '' && val[2] && [2, 4, 6].indexOf(val[1]) === 0) {
            let appCardId = val[2].ID ? val[2].ID : val[2];
            this.api
              .select({
                Object: 'EFATURA_INVOICE',
                Select: ['ID'],
                Where: [
                  {
                    Column: 'InvoiceId',
                    Operator: '=',
                    Value: val[0],
                  },
                  {
                    Column: 'APPCARDID',
                    Operator: '=',
                    Value: appCardId,
                  },
                ],
              })
              .then((x) => {
                if (
                  x &&
                  x.ResultSets &&
                  x.ResultSets[0] &&
                  x.ResultSets[0][0]
                ) {
                  angus.serviceWorkerService.snackBar.open(
                    this.languageService.staticTranslator.translate(
                      'This invoice number has been used before'
                    ),
                    '(x)',
                    { duration: 5e3 }
                  );
                  this.isUsedInvoice = true;
                }
              });
          }
        });

      fatId.valueChanges
        .pipe(rxjs.takeUntil(this.isDestroy$))
        .subscribe((id) => {
          if (id) {
            unsubscribe$.next();
          }
        });
    }
  } catch (e) {
    console.error('faturaUstBilgileri selectedTabChange not found', e);
  }
})();



(async () => {
  let curIssueDateFC = this.recordService.formGroup.controls.IssueDate;
  let currencyFC = this.recordService.formGroup.controls.CURRENCY_CURRENCYID;
  console.log('currencyFC:::', currencyFC);
  let curRateFC = this.recordService.formGroup.controls.CURRENCYRATE;
  this.recordService._curFind = () => {
    debugger;
    let loading = this.recordService.component.loadingService.showLoadingOverlay(); //angus.loadingService.showLoadingOverlay();
    if (currencyFC.value && curIssueDateFC.value) {
      this.api
        .func({
          Object: 'FN_HOTEL_EXCHANGERATES',
          Parameters: {
            DATE: curIssueDateFC.value,
            TARGETCURRENCYID: currencyFC.value,
            BASECURRENCYID: window.angus.api.tenant.DEFAULTCURRENCYID,
          },
        })
        .subscribe(
          (resp) => {
          
            if (resp?.[0]?.length) {
              curRateFC.setValue(1 / resp[0][0].BUYRATE);
              this.lastcurrencyRateAutomatic = 1 / resp[0][0].BUYRATE;
            }
          },
          (err) => {
            console.error('FN_HOTEL_EXCHANGERATES', err);
            angus.api.angusDialog.error(err);
          },
          () => {
            loading.destroy();
          }
        );

      loading.destroy();
    } else {
      loading.destroy();
    }
  };
})();

Last updated