@angular/common#getCurrencySymbol TypeScript Examples

The following examples show how to use @angular/common#getCurrencySymbol. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: stats.component.ts    From fyle-mobile-app with MIT License 6 votes vote down vote up
/*
   * This is required because ionic dosnt reload the page every time we enter, it initializes via ngOnInit only on first entry.
   * The ionViewWillEnter is an alternative for this but not present in child pages.
   * Here, I am setting up the initialize method to be called from the parent's ionViewWillEnter method.
   * **/
  init() {
    const that = this;
    that.homeCurrency$ = that.currencyService.getHomeCurrency().pipe(shareReplay(1));
    that.currencySymbol$ = that.homeCurrency$.pipe(
      map((homeCurrency: string) => getCurrencySymbol(homeCurrency, 'wide'))
    );

    that.initializeReportStats();
    that.initializeExpensesStats();
    that.offlineService.getOrgSettings().subscribe((orgSettings) => {
      if (orgSettings.corporate_credit_card_settings.enabled) {
        this.isUnifyCCCExpensesSettings =
          orgSettings.unify_ccce_expenses_settings &&
          orgSettings.unify_ccce_expenses_settings.allowed &&
          orgSettings.unify_ccce_expenses_settings.enabled;
        that.isCCCStatsLoading = true;
        that.initializeCCCStats();
      } else {
        this.cardTransactionsAndDetails$ = of(null);
        this.cardTransactionsAndDetailsNonUnifyCCC$ = of(null);
      }
    });
  }
Example #2
Source File: humanize-currency.pipe.ts    From fyle-mobile-app with MIT License 6 votes vote down vote up
transform(value: number, currencyCode: string, fraction: number, skipSymbol = false): any {
    const sign = value < 0 ? '-' : '';
    const amount = Math.abs(value) || 0;
    const si = ['', 'K', 'M', 'B', 't', 'q', 'Q', 's', 'S', 'o', 'n'];
    const exp = Math.max(0, Math.floor(Math.log(amount) / Math.log(1000)));
    const result = amount / Math.pow(1000, exp);
    let fixedResult;

    const currency = getCurrencySymbol(currencyCode, 'wide', 'en');
    if (currency) {
      const fractionSize = fraction;
      if (fractionSize) {
        fixedResult = result.toFixed(fraction);
      } else {
        // will implemnt later if no fraction passed
      }
      if (!skipSymbol) {
        fixedResult = currency + fixedResult;
      }
    }

    fixedResult = fixedResult + si[exp];
    return sign + fixedResult;
  }
Example #3
Source File: fy-add-to-report-modal.component.ts    From fyle-mobile-app with MIT License 6 votes vote down vote up
ngOnInit() {
    if (this.currentSelection) {
      this.options = this.options
        .map((option) =>
          isEqual(option.value, this.currentSelection) ? { ...option, selected: true } : { ...option, selected: false }
        )
        .sort((a, b) => (a.selected === b.selected ? 0 : a.selected ? -1 : 1));
    }

    this.offlineService.getHomeCurrency().subscribe((homeCurrency) => {
      this.reportCurrencySymbol = getCurrencySymbol(homeCurrency, 'wide');
    });
  }
Example #4
Source File: create-new-report.component.ts    From fyle-mobile-app with MIT License 6 votes vote down vote up
ngOnInit() {
    this.selectedTotalAmount = 0;
    this.submitReportLoader = false;
    this.saveDraftReportLoader = false;
    this.isSelectedAll = true;
    this.expenseFields$ = this.offlineService.getExpenseFieldsMap();
    this.selectedElements = this.selectedExpensesToReport;
    this.offlineService.getHomeCurrency().subscribe((homeCurrency) => {
      this.homeCurrency = homeCurrency;
      this.homeCurrencySymbol = getCurrencySymbol(homeCurrency, 'wide');
    });
  }
Example #5
Source File: my-view-advance.page.ts    From fyle-mobile-app with MIT License 6 votes vote down vote up
ionViewWillEnter() {
    const id = this.activatedRoute.snapshot.params.id;

    this.advance$ = from(this.loaderService.showLoader()).pipe(
      switchMap(() => this.advanceService.getAdvance(id)),
      finalize(() => from(this.loaderService.hideLoader())),
      shareReplay(1)
    );

    this.advance$.subscribe((advance) => {
      this.currencySymbol = getCurrencySymbol(advance?.adv_currency, 'wide');
    });

    this.getAndUpdateProjectName();
  }
Example #6
Source File: my-advances-card.component.ts    From fyle-mobile-app with MIT License 6 votes vote down vote up
ngOnInit() {
    if (this.advanceRequest && this.prevDate) {
      this.showDate = moment(this.advanceRequest.created_at).isSame(this.prevDate, 'day');
    }
    this.currencySymbol = getCurrencySymbol(this.advanceRequest.currency, 'wide');
    this.internalState =
      this.advanceRequest.type === 'request'
        ? this.advanceRequestService.getInternalStateAndDisplayName(this.advanceRequest)
        : {
            state: 'paid',
            name: 'Paid',
          };
  }
Example #7
Source File: add-txn-to-report-dialog.component.ts    From fyle-mobile-app with MIT License 5 votes vote down vote up
ngOnInit() {
    this.offlineService.getHomeCurrency().subscribe((homeCurrency) => {
      this.reportCurrencySymbol = getCurrencySymbol(homeCurrency, 'wide');
    });
  }
Example #8
Source File: stat-badge.component.ts    From fyle-mobile-app with MIT License 5 votes vote down vote up
ngOnInit() {
    this.currencySymbol = getCurrencySymbol(this.currency, 'wide');
  }
Example #9
Source File: personal-card-transaction.component.ts    From fyle-mobile-app with MIT License 5 votes vote down vote up
ngOnInit(): void {
    this.currency = getCurrencySymbol(this.currency, 'wide');
    const currentDate = new Date(this.txnDate).toDateString();
    const previousDate = new Date(this.previousTxnDate).toDateString();
    this.showDt = currentDate !== previousDate;
  }
Example #10
Source File: tasks-card.component.ts    From fyle-mobile-app with MIT License 5 votes vote down vote up
ngOnInit(): void {
    this.homeCurrency$ = this.offlineService.getHomeCurrency();
    this.currencySymbol$ = this.homeCurrency$.pipe(
      map((homeCurrency: string) => getCurrencySymbol(homeCurrency, 'wide'))
    );
  }
Example #11
Source File: expenses-card.component.ts    From fyle-mobile-app with MIT License 5 votes vote down vote up
ngOnInit() {
    this.setupNetworkWatcher();
    const orgSettings$ = this.offlineService.getOrgSettings().pipe(shareReplay(1));

    this.isSycing$ = this.isConnected$.pipe(
      map((isConnected) => isConnected && this.transactionOutboxService.isSyncInProgress() && this.isOutboxExpense)
    );

    this.isMileageExpense =
      this.expense?.tx_fyle_category && this.expense?.tx_fyle_category?.toLowerCase() === 'mileage';
    this.isPerDiem = this.expense?.tx_fyle_category && this.expense?.tx_fyle_category?.toLowerCase() === 'per diem';

    this.category = this.expense.tx_org_category?.toLowerCase();
    this.expense.isDraft = this.transactionService.getIsDraft(this.expense);
    this.expense.isPolicyViolated = this.expense.tx_manual_flag || this.expense.tx_policy_flag;
    this.expense.isCriticalPolicyViolated = this.transactionService.getIsCriticalPolicyViolated(this.expense);
    this.expense.vendorDetails = this.transactionService.getVendorDetails(this.expense);
    this.expenseFields$ = this.offlineService.getExpenseFieldsMap();

    this.offlineService
      .getHomeCurrency()
      .pipe(
        map((homeCurrency) => {
          this.homeCurrency = homeCurrency;
          this.homeCurrencySymbol = getCurrencySymbol(homeCurrency, 'wide');
          this.foreignCurrencySymbol = getCurrencySymbol(this.expense.tx_orig_currency, 'wide');
        })
      )
      .subscribe(noop);

    this.isProjectEnabled$ = orgSettings$.pipe(
      map((orgSettings) => orgSettings.projects && orgSettings.projects.allowed && orgSettings.projects.enabled),
      shareReplay(1)
    );

    orgSettings$.subscribe(
      (orgSettings) =>
        (this.isUnifyCcceExpensesSettings =
          orgSettings.unify_ccce_expenses_settings &&
          orgSettings.unify_ccce_expenses_settings.allowed &&
          orgSettings.unify_ccce_expenses_settings.enabled)
    );

    if (!this.expense.tx_id) {
      this.showDt = !!this.isFirstOfflineExpense;
    } else if (this.previousExpenseTxnDate || this.previousExpenseCreatedAt) {
      const currentDate = this.expense && new Date(this.expense.tx_txn_dt || this.expense.tx_created_at).toDateString();
      const previousDate = new Date(this.previousExpenseTxnDate || this.previousExpenseCreatedAt).toDateString();
      this.showDt = currentDate !== previousDate;
    }

    this.canShowPaymentModeIcon();

    this.getReceipt();

    this.handleScanStatus();

    this.setOtherData();

    this.isIos = this.platform.is('ios');
  }
Example #12
Source File: view-team-report.page.ts    From fyle-mobile-app with MIT License 5 votes vote down vote up
ionViewWillEnter() {
    this.isExpensesLoading = true;
    this.setupNetworkWatcher();

    this.navigateBack = this.activatedRoute.snapshot.params.navigate_back;

    this.erpt$ = this.refreshApprovals$.pipe(
      switchMap(() =>
        from(this.loaderService.showLoader()).pipe(
          switchMap(() => this.reportService.getTeamReport(this.activatedRoute.snapshot.params.id))
        )
      ),
      shareReplay(1),
      finalize(() => from(this.loaderService.hideLoader()))
    );

    this.erpt$.subscribe((res) => {
      this.reportCurrencySymbol = getCurrencySymbol(res.rp_currency, 'wide');
      this.reportName = res.rp_purpose;
      /**
       * if current user is remove from approver, erpt call will go again to fetch current report details
       * so checking if report details are available in erpt than continue execution
       * else redirect them to team reports
       */
      if (res) {
        this.isReportReported = ['APPROVER_PENDING'].indexOf(res.rp_state) > -1;
      } else {
        this.router.navigate(['/', 'enterprise', 'team_reports']);
      }
    });

    this.sharedWith$ = this.reportService.getExports(this.activatedRoute.snapshot.params.id).pipe(
      map((pdfExports) =>
        pdfExports.results
          .sort((a, b) => (a.created_at < b.created_at ? 1 : b.created_at < a.created_at ? -1 : 0))
          .map((pdfExport) => pdfExport.sent_to)
          .filter((item, index, inputArray) => inputArray.indexOf(item) === index)
      )
    );

    this.reportApprovals$ = this.refreshApprovals$.pipe(
      startWith(true),
      switchMap(() => this.reportService.getApproversByReportId(this.activatedRoute.snapshot.params.id)),
      map((reportApprovals) =>
        reportApprovals
          .filter((approval) => ['APPROVAL_PENDING', 'APPROVAL_DONE'].indexOf(approval.state) > -1)
          .map((approval) => approval)
      )
    );

    this.etxns$ = from(this.authService.getEou()).pipe(
      switchMap((eou) => this.reportService.getReportETxnc(this.activatedRoute.snapshot.params.id, eou.ou.id)),
      map((etxns) =>
        etxns.map((etxn) => {
          etxn.vendor = this.getVendorName(etxn);
          etxn.violation = this.getShowViolation(etxn);
          return etxn;
        })
      ),
      shareReplay(1),
      finalize(() => (this.isExpensesLoading = false))
    );

    this.etxnAmountSum$ = this.etxns$.pipe(map((etxns) => etxns.reduce((acc, curr) => acc + curr.tx_amount, 0)));

    this.actions$ = this.reportService.actions(this.activatedRoute.snapshot.params.id).pipe(shareReplay(1));

    this.canEdit$ = this.actions$.pipe(map((actions) => actions.can_edit));
    this.canDelete$ = this.actions$.pipe(map((actions) => actions.can_delete));
    this.canResubmitReport$ = this.actions$.pipe(map((actions) => actions.can_resubmit));

    this.etxns$.subscribe((etxns) => (this.reportEtxnIds = etxns.map((etxn) => etxn.tx_id)));
    this.refreshApprovals$.next();
  }
Example #13
Source File: team-report-card.component.ts    From fyle-mobile-app with MIT License 5 votes vote down vote up
ngOnInit() {
    this.showDate =
      (this.erpt && new Date(this.erpt.rp_created_at).toDateString()) !==
      (this.prevDate && new Date(this.prevDate).toDateString());

    this.reportCurrencySymbol = getCurrencySymbol(this.erpt.rp_currency, 'wide');
  }
Example #14
Source File: team-adv-card.component.ts    From fyle-mobile-app with MIT License 5 votes vote down vote up
ngOnInit() {
    if (this.advanceRequest && this.prevDate) {
      this.showDate = moment(this.advanceRequest.areq_created_at).isSame(this.prevDate, 'day');
    }
    this.currencySymbol = getCurrencySymbol(this.advanceRequest.areq_currency, 'wide');
    this.internalState = this.advanceRequestService.getInternalStateAndDisplayName(this.advanceRequest);
  }
Example #15
Source File: my-view-report.page.ts    From fyle-mobile-app with MIT License 5 votes vote down vote up
ionViewWillEnter() {
    this.setupNetworkWatcher();
    this.isExpensesLoading = true;
    this.navigateBack = !!this.activatedRoute.snapshot.params.navigateBack;

    this.erpt$.subscribe((erpt) => {
      this.reportCurrencySymbol = getCurrencySymbol(erpt?.rp_currency, 'wide');
      this.reportName = erpt?.rp_purpose;
      this.reportId = erpt?.rp_id;
    });

    this.sharedWith$ = this.reportService.getExports(this.activatedRoute.snapshot.params.id).pipe(
      map((pdfExports) =>
        pdfExports.results
          .sort((a, b) => (a.created_at < b.created_at ? 1 : b.created_at < a.created_at ? -1 : 0))
          .map((pdfExport) => pdfExport.sent_to)
          .filter((item, index, inputArray) => inputArray.indexOf(item) === index)
      )
    );

    this.reportApprovals$ = this.reportService
      .getApproversByReportId(this.activatedRoute.snapshot.params.id)
      .pipe(map((reportApprovals) => reportApprovals));

    this.etxns$ = from(this.authService.getEou()).pipe(
      switchMap((eou) =>
        this.transactionService.getAllETxnc({
          tx_org_user_id: 'eq.' + eou.ou.id,
          tx_report_id: 'eq.' + this.activatedRoute.snapshot.params.id,
          order: 'tx_txn_dt.desc,tx_id.desc',
        })
      ),
      map((etxns) =>
        etxns.map((etxn) => {
          etxn.vendor = this.getVendorName(etxn);
          etxn.violation = this.getShowViolation(etxn);
          return etxn;
        })
      ),
      shareReplay(1),
      finalize(() => (this.isExpensesLoading = false))
    );

    const actions$ = this.reportService.actions(this.activatedRoute.snapshot.params.id).pipe(shareReplay(1));

    this.canEdit$ = actions$.pipe(map((actions) => actions.can_edit));
    this.canDelete$ = actions$.pipe(map((actions) => actions.can_delete));
    this.canResubmitReport$ = actions$.pipe(map((actions) => actions.can_resubmit));

    this.etxns$.subscribe((etxns) => (this.reportEtxnIds = etxns.map((etxn) => etxn.tx_id)));

    const queryParams = {
      tx_report_id: 'is.null',
      tx_state: 'in.(COMPLETE)',
      order: 'tx_txn_dt.desc',
      or: ['(tx_policy_amount.is.null,tx_policy_amount.gt.0.0001)'],
    };

    this.transactionService
      .getAllExpenses({ queryParams })
      .pipe(
        map((etxns) => cloneDeep(etxns)),
        map((etxns: Expense[]) => {
          etxns.forEach((etxn, i) => {
            etxn.vendorDetails = this.getVendorName(etxn);
            etxn.showDt = true;
            etxn.isSelected = false;
            if (i > 0 && etxn.tx_txn_dt === etxns[i - 1].tx_txn_dt) {
              etxn.showDt = false;
            }
          });
          this.unReportedEtxns = etxns;
        })
      )
      .subscribe(noop);
  }
Example #16
Source File: my-view-advance-request.page.ts    From fyle-mobile-app with MIT License 5 votes vote down vote up
ionViewWillEnter() {
    const id = this.activatedRoute.snapshot.params.id;
    this.advanceRequest$ = from(this.loaderService.showLoader()).pipe(
      switchMap(() => this.advanceRequestService.getAdvanceRequest(id)),
      finalize(() => from(this.loaderService.hideLoader())),
      shareReplay(1)
    );

    this.advanceRequest$.subscribe((advanceRequest) => {
      this.internalState = this.advanceRequestService.getInternalStateAndDisplayName(advanceRequest);
      this.currencySymbol = getCurrencySymbol(advanceRequest?.areq_currency, 'wide');
    });

    this.actions$ = this.advanceRequestService.getActions(id).pipe(shareReplay(1));
    this.activeApprovals$ = this.advanceRequestService.getActiveApproversByAdvanceRequestId(id);
    this.attachedFiles$ = this.fileService.findByAdvanceRequestId(id).pipe(
      switchMap((res) => from(res)),
      concatMap((fileObj: any) =>
        this.fileService.downloadUrl(fileObj.id).pipe(
          map((downloadUrl) => {
            fileObj.url = downloadUrl;
            const details = this.getReceiptDetails(fileObj);
            fileObj.type = details.type;
            fileObj.thumbnail = details.thumbnail;
            return fileObj;
          })
        )
      ),
      reduce((acc, curr) => acc.concat(curr), [] as File[])
    );

    this.customFields$ = this.advanceRequestsCustomFieldsService.getAll();

    this.advanceRequestCustomFields$ = forkJoin({
      advanceRequest: this.advanceRequest$,
      customFields: this.customFields$,
    }).pipe(
      map((res) => {
        let customFieldValues = [];
        if (
          res.advanceRequest.areq_custom_field_values !== null &&
          res.advanceRequest.areq_custom_field_values.length > 0
        ) {
          customFieldValues = this.advanceRequestService.modifyAdvanceRequestCustomFields(
            JSON.parse(res.advanceRequest.areq_custom_field_values)
          );
        }

        res.customFields.map((customField) => {
          customFieldValues.filter((customFieldValue) => {
            if (customField.id === customFieldValue.id) {
              customField.value = customFieldValue.value;
            }
          });
        });

        return res.customFields;
      })
    );

    this.getAndUpdateProjectName();
  }
Example #17
Source File: my-create-report.page.ts    From fyle-mobile-app with MIT License 5 votes vote down vote up
ngOnInit() {
    this.offlineService.getHomeCurrency().subscribe((homeCurrency) => {
      this.homeCurrency = homeCurrency;
      this.homeCurrencySymbol = getCurrencySymbol(homeCurrency, 'wide');
    });
  }
Example #18
Source File: my-reports-card.component.ts    From fyle-mobile-app with MIT License 5 votes vote down vote up
ngOnInit() {
    this.showDate =
      (this.erpt && new Date(this.erpt.rp_created_at).toDateString()) !==
      (this.prevDate && new Date(this.prevDate).toDateString());

    this.reportCurrencySymbol = getCurrencySymbol(this.erpt.rp_currency, 'wide');
  }
Example #19
Source File: add-expenses-to-report.component.ts    From fyle-mobile-app with MIT License 5 votes vote down vote up
ngOnInit() {
    this.offlineService.getHomeCurrency().subscribe((homeCurrency) => {
      this.homeCurrency = homeCurrency;
      this.homeCurrencySymbol = getCurrencySymbol(homeCurrency, 'wide');
    });
  }
Example #20
Source File: view-expense.page.ts    From fyle-mobile-app with MIT License 4 votes vote down vote up
ionViewWillEnter() {
    this.setupNetworkWatcher();
    const txId = this.activatedRoute.snapshot.params.id;

    this.etxnWithoutCustomProperties$ = this.updateFlag$.pipe(
      switchMap(() => this.transactionService.getEtxn(txId)),
      shareReplay(1)
    );

    this.etxnWithoutCustomProperties$.subscribe((res) => {
      this.reportId = res.tx_report_id;
    });

    this.customProperties$ = this.etxnWithoutCustomProperties$.pipe(
      concatMap((etxn) =>
        this.customInputsService.fillCustomProperties(etxn.tx_org_category_id, etxn.tx_custom_properties, true)
      ),
      shareReplay(1)
    );

    this.etxn$ = combineLatest([this.etxnWithoutCustomProperties$, this.customProperties$]).pipe(
      map((res) => {
        res[0].tx_custom_properties = res[1];
        return res[0];
      }),
      finalize(() => this.loaderService.hideLoader()),
      shareReplay(1)
    );

    this.etxn$.subscribe((etxn) => {
      this.isExpenseFlagged = etxn.tx_manual_flag;

      if (etxn.tx_amount && etxn.tx_orig_amount) {
        this.exchangeRate = etxn.tx_amount / etxn.tx_orig_amount;
      }

      if (etxn.source_account_type === 'PERSONAL_ADVANCE_ACCOUNT') {
        this.paymentMode = 'Advance';
        this.paymentModeIcon = 'fy-non-reimbursable';
      } else if (etxn.source_account_type === 'PERSONAL_CORPORATE_CREDIT_CARD_ACCOUNT') {
        this.paymentMode = 'Corporate Card';
        this.paymentModeIcon = 'fy-unmatched';
        this.isCCCTransaction = true;
      } else if (etxn.tx_skip_reimbursement) {
        this.paymentMode = 'Paid by Company';
        this.paymentModeIcon = 'fy-non-reimbursable';
      } else {
        this.paymentMode = 'Paid by Employee';
        this.paymentModeIcon = 'fy-reimbursable';
      }

      if (this.isCCCTransaction) {
        this.matchingCCCTransaction$ = this.corporateCreditCardExpenseService
          .getEccceByGroupId(etxn.tx_corporate_credit_card_expense_group_id)
          .pipe(
            map(
              (matchedExpense) => matchedExpense[0] && (this.paymentModeIcon = 'fy-matched') && matchedExpense[0].ccce
            )
          );
        this.matchingCCCTransaction$.subscribe((cardTxn) => {
          this.cardNumber = cardTxn?.card_or_account_number;
        });
      }
      this.foreignCurrencySymbol = getCurrencySymbol(etxn.tx_orig_currency, 'wide');
      this.etxnCurrencySymbol = getCurrencySymbol(etxn.tx_currency, 'wide');
    });

    forkJoin([this.offlineService.getExpenseFieldsMap(), this.etxn$.pipe(take(1))])
      .pipe(
        map(([expenseFieldsMap, etxn]) => {
          this.projectFieldName = expenseFieldsMap?.project_id[0]?.field_name;
          const isProjectMandatory = expenseFieldsMap?.project_id && expenseFieldsMap?.project_id[0]?.is_mandatory;
          this.isProjectShown = this.orgSettings?.projects?.enabled && (etxn.tx_project_name || isProjectMandatory);
        })
      )
      .subscribe(noop);

    this.policyViloations$ = this.etxnWithoutCustomProperties$.pipe(
      concatMap((etxn) => this.statusService.find('transactions', etxn.tx_id)),
      map((comments) => comments.filter(this.isPolicyComment))
    );

    this.comments$ = this.statusService.find('transactions', txId);
    this.view = this.activatedRoute.snapshot.params.view;

    this.canFlagOrUnflag$ = this.etxnWithoutCustomProperties$.pipe(
      filter(() => this.view === ExpenseView.team),
      map(
        (etxn) =>
          ['COMPLETE', 'POLICY_APPROVED', 'APPROVER_PENDING', 'APPROVED', 'PAYMENT_PENDING'].indexOf(etxn.tx_state) > -1
      )
    );

    this.canDelete$ = this.etxnWithoutCustomProperties$.pipe(
      filter(() => this.view === ExpenseView.team),
      switchMap((etxn) =>
        this.reportService.getTeamReport(etxn.tx_report_id).pipe(map((report) => ({ report, etxn })))
      ),
      map(({ report, etxn }) => {
        if (report.rp_num_transactions === 1) {
          return false;
        }
        return ['PAYMENT_PENDING', 'PAYMENT_PROCESSING', 'PAID'].indexOf(etxn.tx_state) < 0;
      })
    );

    this.isAmountCapped$ = this.etxn$.pipe(
      map((etxn) => this.isNumber(etxn.tx_admin_amount) || this.isNumber(etxn.tx_policy_amount))
    );

    this.offlineService.getOrgSettings().subscribe((orgSettings) => {
      this.orgSettings = orgSettings;
      this.isUnifyCcceExpensesSettingsEnabled =
        this.orgSettings?.unify_ccce_expenses_settings?.allowed &&
        this.orgSettings?.unify_ccce_expenses_settings?.enabled;
    });

    this.offlineService
      .getExpenseFieldsMap()
      .pipe(
        map((expenseFieldsMap) => {
          this.merchantFieldName = expenseFieldsMap.vendor_id[0]?.field_name;
        })
      )
      .subscribe(noop);

    this.isCriticalPolicyViolated$ = this.etxn$.pipe(
      map((etxn) => this.isNumber(etxn.tx_policy_amount) && etxn.tx_policy_amount < 0.0001)
    );

    this.getPolicyDetails(txId);

    const editExpenseAttachments = this.etxn$.pipe(
      take(1),
      switchMap((etxn) => this.fileService.findByTransactionId(etxn.tx_id)),
      switchMap((fileObjs) => from(fileObjs)),
      concatMap((fileObj: any) =>
        this.fileService.downloadUrl(fileObj.id).pipe(
          map((downloadUrl) => {
            fileObj.url = downloadUrl;
            const details = this.getReceiptDetails(fileObj);
            fileObj.type = details.type;
            fileObj.thumbnail = details.thumbnail;
            return fileObj;
          })
        )
      ),
      reduce((acc, curr) => acc.concat(curr), [])
    );

    this.attachments$ = editExpenseAttachments;
    this.updateFlag$.next();
    this.attachments$.subscribe(noop, noop, () => {
      this.isLoading = false;
    });

    const etxnIds =
      this.activatedRoute.snapshot.params.txnIds && JSON.parse(this.activatedRoute.snapshot.params.txnIds);
    this.numEtxnsInReport = etxnIds.length;
    this.activeEtxnIndex = parseInt(this.activatedRoute.snapshot.params.activeIndex, 10);
  }
Example #21
Source File: view-mileage.page.ts    From fyle-mobile-app with MIT License 4 votes vote down vote up
ionViewWillEnter() {
    this.setupNetworkWatcher();
    const id = this.activatedRoute.snapshot.params.id;

    this.extendedMileage$ = this.updateFlag$.pipe(
      switchMap(() =>
        from(this.loaderService.showLoader()).pipe(switchMap(() => this.transactionService.getExpenseV2(id)))
      ),
      finalize(() => from(this.loaderService.hideLoader())),
      shareReplay(1)
    );

    this.extendedMileage$.subscribe((extendedMileage) => {
      this.reportId = extendedMileage.tx_report_id;

      if (extendedMileage.source_account_type === 'PERSONAL_ADVANCE_ACCOUNT') {
        this.paymentMode = 'Paid from Advance';
        this.paymentModeIcon = 'fy-non-reimbursable';
      } else if (extendedMileage.tx_skip_reimbursement) {
        this.paymentMode = 'Paid by Company';
        this.paymentModeIcon = 'fy-non-reimbursable';
      } else {
        this.paymentMode = 'Paid by Employee';
        this.paymentModeIcon = 'fy-reimbursable';
      }

      if (
        extendedMileage.tx_mileage_vehicle_type.indexOf('four') > -1 ||
        extendedMileage.tx_mileage_vehicle_type.indexOf('car') > -1
      ) {
        this.vehicleType = 'car';
      } else {
        this.vehicleType = 'bike';
      }

      this.etxnCurrencySymbol = getCurrencySymbol(extendedMileage.tx_currency, 'wide');
    });

    forkJoin([this.offlineService.getExpenseFieldsMap(), this.extendedMileage$.pipe(take(1))])
      .pipe(
        map(([expenseFieldsMap, extendedMileage]) => {
          this.projectFieldName = expenseFieldsMap?.project_id && expenseFieldsMap?.project_id[0]?.field_name;
          const isProjectMandatory = expenseFieldsMap?.project_id && expenseFieldsMap?.project_id[0]?.is_mandatory;
          this.isProjectShown =
            this.orgSettings?.projects?.enabled && (extendedMileage.tx_project_name || isProjectMandatory);
        })
      )
      .subscribe(noop);

    this.offlineService
      .getOrgSettings()
      .pipe(shareReplay(1))
      .subscribe((orgSettings) => {
        this.orgSettings = orgSettings;
      });

    this.mileageCustomFields$ = this.extendedMileage$.pipe(
      switchMap((res) =>
        this.customInputsService.fillCustomProperties(res.tx_org_category_id, res.tx_custom_properties, true)
      ),
      map((res) =>
        res.map((customProperties) => {
          customProperties.displayValue = this.customInputsService.getCustomPropertyDisplayValue(customProperties);
          return customProperties;
        })
      )
    );

    this.view = this.activatedRoute.snapshot.params.view;

    this.canFlagOrUnflag$ = this.extendedMileage$.pipe(
      filter(() => this.view === ExpenseView.team),
      map(
        (etxn) =>
          ['COMPLETE', 'POLICY_APPROVED', 'APPROVER_PENDING', 'APPROVED', 'PAYMENT_PENDING'].indexOf(etxn.tx_state) > -1
      )
    );

    this.canDelete$ = this.extendedMileage$.pipe(
      filter(() => this.view === ExpenseView.team),
      switchMap((etxn) =>
        this.reportService.getTeamReport(etxn.tx_report_id).pipe(map((report) => ({ report, etxn })))
      ),
      map(({ report, etxn }) => {
        if (report.rp_num_transactions === 1) {
          return false;
        }
        return ['PAYMENT_PENDING', 'PAYMENT_PROCESSING', 'PAID'].indexOf(etxn.tx_state) < 0;
      })
    );

    if (id) {
      this.policyViloations$ = this.policyService.getPolicyViolationRules(id);
    } else {
      this.policyViloations$ = of(null);
    }

    this.comments$ = this.statusService.find('transactions', id);

    this.isCriticalPolicyViolated$ = this.extendedMileage$.pipe(
      map((res) => this.isNumber(res.tx_policy_amount) && res.tx_policy_amount < 0.0001)
    );

    this.getPolicyDetails(id);

    this.isAmountCapped$ = this.extendedMileage$.pipe(
      map((res) => this.isNumber(res.tx_admin_amount) || this.isNumber(res.tx_policy_amount))
    );

    this.extendedMileage$.subscribe((etxn) => {
      this.isExpenseFlagged = etxn.tx_manual_flag;
    });

    this.updateFlag$.next();

    const etxnIds =
      this.activatedRoute.snapshot.params.txnIds && JSON.parse(this.activatedRoute.snapshot.params.txnIds);
    this.numEtxnsInReport = etxnIds.length;
    this.activeEtxnIndex = parseInt(this.activatedRoute.snapshot.params.activeIndex, 10);
  }
Example #22
Source File: view-per-diem.page.ts    From fyle-mobile-app with MIT License 4 votes vote down vote up
ionViewWillEnter() {
    const id = this.activatedRoute.snapshot.params.id;

    this.extendedPerDiem$ = this.updateFlag$.pipe(
      switchMap(() =>
        from(this.loaderService.showLoader()).pipe(switchMap(() => this.transactionService.getExpenseV2(id)))
      ),
      finalize(() => from(this.loaderService.hideLoader())),
      shareReplay(1)
    );

    this.extendedPerDiem$.subscribe((extendedPerDiem) => {
      this.reportId = extendedPerDiem.tx_report_id;

      if (extendedPerDiem.source_account_type === 'PERSONAL_ADVANCE_ACCOUNT') {
        this.paymentMode = 'Paid from Advance';
        this.paymentModeIcon = 'fy-non-reimbursable';
      } else if (extendedPerDiem.tx_skip_reimbursement) {
        this.paymentMode = 'Paid by Company';
        this.paymentModeIcon = 'fy-non-reimbursable';
      } else {
        this.paymentMode = 'Paid by Employee';
        this.paymentModeIcon = 'fy-reimbursable';
      }

      this.etxnCurrencySymbol = getCurrencySymbol(extendedPerDiem.tx_currency, 'wide');
    });

    forkJoin([this.offlineService.getExpenseFieldsMap(), this.extendedPerDiem$.pipe(take(1))])
      .pipe(
        map(([expenseFieldsMap, extendedPerDiem]) => {
          this.projectFieldName = expenseFieldsMap?.project_id && expenseFieldsMap?.project_id[0]?.field_name;
          const isProjectMandatory = expenseFieldsMap?.project_id && expenseFieldsMap?.project_id[0]?.is_mandatory;
          this.isProjectShown =
            this.orgSettings?.projects?.enabled && (extendedPerDiem.tx_project_name || isProjectMandatory);
        })
      )
      .subscribe(noop);

    this.offlineService
      .getOrgSettings()
      .pipe(shareReplay(1))
      .subscribe((orgSettings) => {
        this.orgSettings = orgSettings;
      });

    this.perDiemCustomFields$ = this.extendedPerDiem$.pipe(
      switchMap((res) =>
        this.customInputsService.fillCustomProperties(res.tx_org_category_id, res.tx_custom_properties, true)
      ),
      map((res) =>
        res.map((customProperties) => {
          customProperties.displayValue = this.customInputsService.getCustomPropertyDisplayValue(customProperties);
          return customProperties;
        })
      )
    );

    this.perDiemRate$ = this.extendedPerDiem$.pipe(
      switchMap((res) => {
        const perDiemRateId = parseInt(res.tx_per_diem_rate_id, 10);
        return this.perDiemService.getRate(perDiemRateId);
      })
    );

    this.view = this.activatedRoute.snapshot.params.view;

    this.canFlagOrUnflag$ = this.extendedPerDiem$.pipe(
      filter(() => this.view === ExpenseView.team),
      map(
        (etxn) =>
          ['COMPLETE', 'POLICY_APPROVED', 'APPROVER_PENDING', 'APPROVED', 'PAYMENT_PENDING'].indexOf(etxn.tx_state) > -1
      )
    );

    this.canDelete$ = this.extendedPerDiem$.pipe(
      filter(() => this.view === ExpenseView.team),
      switchMap((etxn) =>
        this.reportService.getTeamReport(etxn.tx_report_id).pipe(map((report) => ({ report, etxn })))
      ),
      map(({ report, etxn }) => {
        if (report.rp_num_transactions === 1) {
          return false;
        }
        return ['PAYMENT_PENDING', 'PAYMENT_PROCESSING', 'PAID'].indexOf(etxn.tx_state) < 0;
      })
    );

    if (id) {
      this.policyViloations$ = this.policyService.getPolicyViolationRules(id);
    } else {
      this.policyViloations$ = of(null);
    }

    this.comments$ = this.statusService.find('transactions', id);

    this.isCriticalPolicyViolated$ = this.extendedPerDiem$.pipe(
      map((res) => this.isNumber(res.tx_policy_amount) && res.tx_policy_amount < 0.0001)
    );

    this.getPolicyDetails(id);

    this.isAmountCapped$ = this.extendedPerDiem$.pipe(
      map((res) => this.isNumber(res.tx_admin_amount) || this.isNumber(res.tx_policy_amount))
    );

    this.extendedPerDiem$.subscribe((etxn) => {
      this.isExpenseFlagged = etxn.tx_manual_flag;
    });

    this.updateFlag$.next();

    const etxnIds =
      this.activatedRoute.snapshot.params.txnIds && JSON.parse(this.activatedRoute.snapshot.params.txnIds);
    this.numEtxnsInReport = etxnIds.length;
    this.activeEtxnIndex = parseInt(this.activatedRoute.snapshot.params.activeIndex, 10);
  }
Example #23
Source File: my-expenses.page.ts    From fyle-mobile-app with MIT License 4 votes vote down vote up
ionViewWillEnter() {
    this.tasksService.getExpensesTaskCount().subscribe((expensesTaskCount) => {
      this.expensesTaskCount = expensesTaskCount;
    });

    this.isInstaFyleEnabled$ = this.offlineService
      .getOrgUserSettings()
      .pipe(
        map(
          (orgUserSettings) =>
            orgUserSettings?.insta_fyle_settings?.allowed && orgUserSettings?.insta_fyle_settings?.enabled
        )
      );

    this.isBulkFyleEnabled$ = this.offlineService
      .getOrgUserSettings()
      .pipe(map((orgUserSettings) => orgUserSettings?.bulk_fyle_settings?.enabled));

    this.isMileageEnabled$ = this.offlineService
      .getOrgSettings()
      .pipe(map((orgSettings) => orgSettings.mileage.enabled));
    this.isPerDiemEnabled$ = this.offlineService
      .getOrgSettings()
      .pipe(map((orgSettings) => orgSettings.per_diem.enabled));

    this.offlineService.getOrgSettings().subscribe((orgSettings) => {
      this.isUnifyCCCExpensesSettings =
        orgSettings.unify_ccce_expenses_settings &&
        orgSettings.unify_ccce_expenses_settings.allowed &&
        orgSettings.unify_ccce_expenses_settings.enabled;
      this.setupActionSheet(orgSettings);
    });

    this.allCardTransactionsAndDetailsNonUnifyCCC$ = this.getNonUnifyCCCDetails().pipe(
      map((res) => res),
      shareReplay(1)
    );

    this.isUnifyCCCEnabled$ = this.offlineService
      .getOrgSettings()
      .pipe(
        map(
          (orgSettings) =>
            orgSettings.unify_ccce_expenses_settings?.allowed && orgSettings.unify_ccce_expenses_settings?.enabled
        )
      );

    forkJoin({
      isConnected: this.isConnected$.pipe(take(1)),
      isUnifyCCCEnabled: this.isUnifyCCCEnabled$.pipe(take(1)),
    })
      .pipe(
        filter(({ isConnected, isUnifyCCCEnabled }) => isConnected && isUnifyCCCEnabled),
        switchMap(() => this.corporateCreditCardService.getAssignedCards()),
        switchMap((unifyCards) => this.getNonUnifyCCCDetails().pipe(map((allCards) => ({ unifyCards, allCards }))))
      )
      .subscribe(({ unifyCards, allCards }) => {
        const cards = this.getCardDetail(unifyCards.cardDetails);

        this.cardNumbers = [];
        cards.forEach((card) => {
          this.cardNumbers.push({ label: this.maskNumber.transform(card.cardNumber), value: card.cardNumber });
        });

        allCards.forEach((detail) => {
          if (
            this.cardNumbers.filter(
              (cardDetail) => cardDetail.label === this.maskNumber.transform(detail.ba_account_number)
            ).length === 0
          ) {
            this.cardNumbers.push({
              label: this.maskNumber.transform(detail.ba_account_number),
              value: detail.ba_account_number,
            });
          }
        });
      });

    this.headerState = HeaderState.base;

    this.isLoading = true;
    this.reviewMode = false;

    from(this.tokenService.getClusterDomain()).subscribe((clusterDomain) => {
      this.clusterDomain = clusterDomain;
    });

    this.ROUTER_API_ENDPOINT = environment.ROUTER_API_ENDPOINT;

    this.navigateBack = !!this.activatedRoute.snapshot.params.navigateBack;
    this.acc = [];
    this.simpleSearchText = '';

    this.currentPageNumber = 1;
    this.loadData$ = new BehaviorSubject({
      pageNumber: 1,
    });

    this.selectionMode = false;
    this.selectedElements = [];

    this.syncOutboxExpenses();

    this.isConnected$.pipe(takeUntil(this.onPageExit$.asObservable())).subscribe((connected) => {
      if (connected) {
        this.syncOutboxExpenses();
      }
    });

    this.homeCurrency$ = this.offlineService.getHomeCurrency();

    this.offlineService.getHomeCurrency().subscribe((homeCurrency) => {
      this.homeCurrencySymbol = getCurrencySymbol(homeCurrency, 'wide');
    });

    this.simpleSearchInput.nativeElement.value = '';
    fromEvent(this.simpleSearchInput.nativeElement, 'keyup')
      .pipe(
        map((event: any) => event.srcElement.value as string),
        distinctUntilChanged(),
        debounceTime(400)
      )
      .subscribe((searchString) => {
        const currentParams = this.loadData$.getValue();
        currentParams.searchString = searchString;
        this.currentPageNumber = 1;
        currentParams.pageNumber = this.currentPageNumber;
        this.loadData$.next(currentParams);
      });

    const paginatedPipe = this.loadData$.pipe(
      switchMap((params) => {
        let queryParams = params.queryParams || {};

        queryParams.tx_report_id = queryParams.tx_report_id || 'is.null';
        queryParams.tx_state = 'in.(COMPLETE,DRAFT)';
        queryParams = this.apiV2Service.extendQueryParamsForTextSearch(queryParams, params.searchString);
        const orderByParams = params.sortParam && params.sortDir ? `${params.sortParam}.${params.sortDir}` : null;
        this.isLoadingDataInInfiniteScroll = true;
        return this.transactionService.getMyExpensesCount(queryParams).pipe(
          switchMap((count) => {
            if (count > (params.pageNumber - 1) * 10) {
              return this.transactionService.getMyExpenses({
                offset: (params.pageNumber - 1) * 10,
                limit: 10,
                queryParams,
                order: orderByParams,
              });
            } else {
              return of({
                data: [],
              });
            }
          })
        );
      }),
      map((res) => {
        this.isLoadingDataInInfiniteScroll = false;
        if (this.currentPageNumber === 1) {
          this.acc = [];
        }
        this.acc = this.acc.concat(res.data);
        return this.acc;
      }),
      tap(() => {
        this.pendingTransactions = this.formatTransactions(this.transactionOutboxService.getPendingTransactions());
      })
    );

    this.myExpenses$ = paginatedPipe.pipe(shareReplay(1));

    this.count$ = this.loadData$.pipe(
      switchMap((params) => {
        let queryParams = params.queryParams || {};

        queryParams.tx_report_id = queryParams.tx_report_id || 'is.null';
        queryParams.tx_state = 'in.(COMPLETE,DRAFT)';
        queryParams = this.apiV2Service.extendQueryParamsForTextSearch(queryParams, params.searchString);
        return this.transactionService.getMyExpensesCount(queryParams);
      }),
      shareReplay(1)
    );

    this.isNewUser$ = this.transactionService.getPaginatedETxncCount().pipe(map((res) => res.count === 0));

    const paginatedScroll$ = this.myExpenses$.pipe(
      switchMap((etxns) => this.count$.pipe(map((count) => count > etxns.length)))
    );

    this.isInfiniteScrollRequired$ = this.loadData$.pipe(switchMap((_) => paginatedScroll$));

    this.setAllExpensesCountAndAmount();

    this.allExpenseCountHeader$ = this.loadData$.pipe(
      switchMap(() =>
        this.transactionService.getTransactionStats('count(tx_id),sum(tx_amount)', {
          scalar: true,
          tx_state: 'in.(COMPLETE,DRAFT)',
          tx_report_id: 'is.null',
        })
      ),
      map((stats) => {
        const count = stats && stats[0] && stats[0].aggregates.find((stat) => stat.function_name === 'count(tx_id)');
        return count && count.function_value;
      })
    );

    this.draftExpensesCount$ = this.loadData$.pipe(
      switchMap(() =>
        this.transactionService.getTransactionStats('count(tx_id),sum(tx_amount)', {
          scalar: true,
          tx_report_id: 'is.null',
          tx_state: 'in.(DRAFT)',
        })
      ),
      map((stats) => {
        const count = stats && stats[0] && stats[0].aggregates.find((stat) => stat.function_name === 'count(tx_id)');
        return count && count.function_value;
      })
    );

    this.loadData$.subscribe((params) => {
      const queryParams: Params = { filters: JSON.stringify(this.filters) };
      this.router.navigate([], {
        relativeTo: this.activatedRoute,
        queryParams,
        replaceUrl: true,
      });
    });

    this.myExpenses$.subscribe(noop);
    this.count$.subscribe(noop);
    this.isInfiniteScrollRequired$.subscribe(noop);
    if (this.activatedRoute.snapshot.queryParams.filters) {
      this.filters = Object.assign({}, this.filters, JSON.parse(this.activatedRoute.snapshot.queryParams.filters));
      this.currentPageNumber = 1;
      const params = this.addNewFiltersToParams();
      this.loadData$.next(params);
      this.filterPills = this.generateFilterPills(this.filters);
    } else if (this.activatedRoute.snapshot.params.state) {
      let filters = {};
      if (this.activatedRoute.snapshot.params.state.toLowerCase() === 'needsreceipt') {
        filters = { tx_receipt_required: 'eq.true', state: 'NEEDS_RECEIPT' };
      } else if (this.activatedRoute.snapshot.params.state.toLowerCase() === 'policyviolated') {
        filters = {
          tx_policy_flag: 'eq.true',
          or: '(tx_policy_amount.is.null,tx_policy_amount.gt.0.0001)',
          state: 'POLICY_VIOLATED',
        };
      } else if (this.activatedRoute.snapshot.params.state.toLowerCase() === 'cannotreport') {
        filters = { tx_policy_amount: 'lt.0.0001', state: 'CANNOT_REPORT' };
      }
      this.filters = Object.assign({}, this.filters, filters);
      this.currentPageNumber = 1;
      const params = this.addNewFiltersToParams();
      this.loadData$.next(params);
      this.filterPills = this.generateFilterPills(this.filters);
    } else {
      this.clearFilters();
    }

    setTimeout(() => {
      this.isLoading = false;
    }, 500);

    const queryParams = { rp_state: 'in.(DRAFT,APPROVER_PENDING,APPROVER_INQUIRY)' };

    this.openReports$ = this.reportService.getAllExtendedReports({ queryParams }).pipe(
      map((openReports) =>
        openReports.filter(
          (openReport) =>
            // JSON.stringify(openReport.report_approvals).indexOf('APPROVAL_DONE') -> Filter report if any approver approved this report.
            // Converting this object to string and checking If `APPROVAL_DONE` is present in the string, removing the report from the list
            !openReport.report_approvals ||
            (openReport.report_approvals &&
              !(JSON.stringify(openReport.report_approvals).indexOf('APPROVAL_DONE') > -1))
        )
      )
    );
    this.doRefresh();
  }