lodash#indexOf TypeScript Examples

The following examples show how to use lodash#indexOf. 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: util.ts    From gio-design with Apache License 2.0 7 votes vote down vote up
getResultValue = (value?: (string | number)[], val?: string | number) => {
  if (indexOf(value, val) !== -1) {
    return difference(value, [val]);
  }
  if (typeof val === 'string') {
    return concat(value, val);
  }
  return value;
  //  ?  :
}
Example #2
Source File: sort-action.ts    From S2 with MIT License 6 votes vote down vote up
sortByFunc = (params: SortActionParams): string[] => {
  const { originValues, measureValues, sortParam, dataSet } = params;
  const { sortFunc, sortFieldId } = sortParam;

  const sortResult = sortFunc({
    data: measureValues,
    ...sortParam,
  }) as string[];

  if (!sortResult?.length) {
    return originValues;
  }

  if (
    (dataSet.fields.rows.indexOf(sortFieldId) > 0 ||
      dataSet.fields.columns.indexOf(sortFieldId) > 0) &&
    !includes(sortResult[0], ID_SEPARATOR)
  ) {
    /**
     * 当被排序字段为 行、列维度的非首维度,且用户返回的结果没有 [&] 连接符,把使用 sortResult 按照手动排序进行兜底处理
     * 如 行维度=[province, city],sortFieldId=city
     * sortResult 返回的为 ['成都', '杭州'],而不是 ['浙江[&]杭州', '四川[&]成都']
     */
    return sortByCustom({
      sortByValues: sortResult,
      originValues,
    });
  }
  return sortResult;
}
Example #3
Source File: sort-action.ts    From S2 with MIT License 6 votes vote down vote up
createTotalParams = (
  originValue: string,
  fields: Fields,
  sortFieldId: string,
) => {
  const totalParams = {};
  const isMultipleDimensionValue = includes(originValue, ID_SEPARATOR);

  if (isMultipleDimensionValue) {
    // 获取行/列小计时,需要将所有行/列维度的值作为 params
    const realOriginValue = split(originValue, ID_SEPARATOR);
    const keys = fields?.rows?.includes(sortFieldId)
      ? fields.rows
      : fields.columns;

    for (let i = 0; i <= indexOf(keys, sortFieldId); i++) {
      totalParams[keys[i]] = realOriginValue[i];
    }
  } else {
    totalParams[sortFieldId] = originValue;
  }
  return totalParams;
}
Example #4
Source File: transactions-outbox.service.ts    From fyle-mobile-app with MIT License 6 votes vote down vote up
async removeDataExtractionEntry(expense, dataUrls) {
    const entry = {
      transaction: expense,
      dataUrls,
    };

    const idx = this.dataExtractionQueue.indexOf(entry);
    this.dataExtractionQueue.splice(idx, 1);
    await this.saveDataExtractionQueue();
  }
Example #5
Source File: util.ts    From gio-design with Apache License 2.0 6 votes vote down vote up
selectStatus = (value?: string | number, values?: MaybeArray<string | number>) => {
  if (!isNil(value)) {
    return isArray(values) ? (values as (string | number)[])?.indexOf(value) !== -1 : values === value;
  }
  return false;
}
Example #6
Source File: sort-action.ts    From S2 with MIT License 5 votes vote down vote up
sortByCustom = (params: SortActionParams): string[] => {
  const { sortByValues, originValues } = params;

  // 从 originValues 中过滤出所有包含 sortByValue 的 id
  const idWithPre = originValues.filter((originItem) =>
    sortByValues.find((value) => endsWith(originItem, value)),
  );
  // 将 id 拆分为父节点和目标节点
  const idListWithPre = idWithPre.map((idStr) => {
    const ids = idStr.split(ID_SEPARATOR);
    if (ids.length > 1) {
      const parentId = ids.slice(0, ids.length - 1).join(ID_SEPARATOR);
      return [parentId, ids[ids.length - 1]];
    }
    return ids;
  });
  // 获取父节点顺序
  const parentOrder = Array.from(new Set(idListWithPre.map((id) => id[0])));
  // 排序
  idListWithPre.sort((a: string[], b: string[]) => {
    const aParent = a.slice(0, a.length - 1);
    const bParent = b.slice(0, b.length - 1);
    // 父节点不同时,按 parentOrder 排序
    if (aParent.join() !== bParent.join()) {
      const aParentIndex = parentOrder.indexOf(aParent[0]);
      const bParentIndex = parentOrder.indexOf(bParent[0]);
      return aParentIndex - bParentIndex;
    }
    // 父节点相同时,按 sortByValues 排序
    const aIndex = sortByValues.indexOf(a[a.length - 1]);
    const bIndex = sortByValues.indexOf(b[b.length - 1]);
    return aIndex - bIndex;
  });
  // 拼接 id
  const sortedIdWithPre = idListWithPre.map((idArr) =>
    idArr.join(ID_SEPARATOR),
  );

  return getListBySorted(originValues, sortedIdWithPre);
}
Example #7
Source File: transactions-outbox.service.ts    From fyle-mobile-app with MIT License 5 votes vote down vote up
removeEntry(entry) {
    const idx = this.queue.indexOf(entry);
    this.queue.splice(idx, 1);
    this.saveQueue();
  }
Example #8
Source File: transactions-outbox.service.ts    From fyle-mobile-app with MIT License 5 votes vote down vote up
deleteBulkOfflineExpenses(pendingTransactions: Expense[], deleteExpenses: Expense[]) {
    const indexes = deleteExpenses.map((offlineExpense) => indexOf(pendingTransactions, offlineExpense));
    // We need to delete last element of this list first
    indexes.sort((a, b) => b - a);
    indexes.forEach((index) => {
      this.deleteOfflineExpense(index);
    });
  }
Example #9
Source File: transactions-outbox.service.ts    From fyle-mobile-app with MIT License 5 votes vote down vote up
isDataExtractionPending(txnId) {
    const txnIds = this.dataExtractionQueue.map((entry) => entry.transaction.id);

    return txnIds.indexOf(txnId) > -1;
  }
Example #10
Source File: transactions-outbox.service.ts    From fyle-mobile-app with MIT License 5 votes vote down vote up
isPDF(type: string) {
    return ['application/pdf', 'pdf'].indexOf(type) > -1;
  }
Example #11
Source File: scenes.tsx    From erda-ui with GNU Affero General Public License v3.0 4 votes vote down vote up
getPreviewData = (d: {
  meta: {
    metadata: Array<{ type: string; value: string; name: string }>;
    errors: Array<{ name: string; value: string; msg: string }>;
  };
}) => {
  const { metadata = [], errors = [] } = d?.meta || {};

  const fileDownload: React.ReactNode[] = [];
  const resultData: ResultDataItem[] = [];
  (metadata || []).forEach((item) => {
    if (item.type === 'DiceFile') {
      fileDownload.push(
        <div key={`${fileDownload.length}`}>
          <a download={item.value} href={`/api/files/${item.value}`}>
            {item.name || item.value}
          </a>
        </div>,
      );
    } else {
      resultData.push({
        key: [item.name],
        value: {
          data: apiResultKeys.includes(item.name) ? getJsonObj(item as IJsonObjVal) : item,
          render: {
            type: 'FileEditor',
            dataIndex: `${encodeURIComponent(item.name)}.value`, // 此处name存在 a.ba[0]的方式,对取值有影响;
            props: {
              title: labelMap[item.name] || item.name,
              minHeight: 40,
              actions: { copy: true },
            },
          },
        },
      });
    }
  });
  const resKeys = map(resultData, 'key');
  const dataObj = {} as Obj;
  const renderList = [];

  if (errors.length) {
    dataObj._errors = errors.map((err, idx: number) => (
      <div key={`error-${String(idx)}`} className="test-case-node-msg">
        <span className="">{err.name || 'error'}: </span>
        {err.value || err.msg}
      </div>
    ));
    renderList.push({
      type: 'custom',
      dataIndex: '_errors',
      props: {
        title: i18n.t('error detail'),
      },
    });
  }

  map(
    sortBy(resKeys, (sKey) => {
      const idx = indexOf([...apiResultKeys, 'status', 'result'], sKey);
      return idx === -1 ? resKeys.length : idx;
    }),
    (key) => {
      const curData = get(find(resultData, { key }), 'value') || {};
      if (curData?.data !== undefined || curData?.data !== null) {
        // 对应上方的key转换
        dataObj[encodeURIComponent(key)] = curData?.data;
        renderList.push(curData?.render);
      }
    },
  );

  if (fileDownload.length) {
    dataObj._fileDownLoad = fileDownload;
    renderList.push({
      type: 'custom',
      dataIndex: '_fileDownLoad',
      props: {
        title: i18n.t('Download'),
      },
    });
  }

  const previewData = {
    data: {
      info: {
        _drawerTitle: i18n.t('dop:execute result'),
        ...dataObj,
      },
    },
    props: {
      render: [{ type: 'Title', dataIndex: '_drawerTitle' }, ...renderList],
    },
  } as Obj as CP_INFO_PREVIEW.Props;

  return previewData;
}
Example #12
Source File: backlog.tsx    From erda-ui with GNU Affero General Public License v3.0 4 votes vote down vote up
Backlog = () => {
  const [backlogIssues, backlogIssuesPaging] = iterationStore.useStore((s) => [s.backlogIssues, s.backlogIssuesPaging]);
  const { pageSize, total, pageNo } = backlogIssuesPaging;
  const { getBacklogIssues, createIssue } = iterationStore.effects;
  const { clearBacklogIssues } = iterationStore.reducers;
  const { deleteIssue, updateIssue } = issueStore.effects;
  const labelList = labelStore.useStore((s) => s.list);
  const { getLabels } = labelStore.effects;
  const [loading] = useLoading(iterationStore, ['getBacklogIssues']);
  const [{ projectId }, { id: queryId, issueType: queryType, ...restQuery }] = routeInfoStore.getState((s) => [
    s.params,
    s.query,
  ]);
  const workflowStateList = issueWorkflowStore.useStore((s) => s.workflowStateList);

  const allStateIds = React.useRef<number[]>([]);

  const [{ isAdding, curIssueDetail, drawerVisible, filterState }, updater, update] = useUpdate({
    isAdding: false,
    curIssueDetail: {} as ISSUE.Issue,
    drawerVisible: false,
    filterState: { ...restQuery } as Obj,
  });

  const stateCollection: Array<{ label: string | React.ReactNode; children: Array<{ label: string; value: string }> }> =
    React.useMemo(() => {
      const stateIds: number[] = [];
      const initState: string[] = [];
      const typeArr = ['REQUIREMENT', 'TASK', 'BUG'];
      const collection =
        workflowStateList?.reduce((acc, current) => {
          const { issueType, stateName, stateID, stateBelong } = current;
          if (!typeArr.includes(issueType)) {
            return acc;
          }
          if (!['CLOSED', 'DONE'].includes(stateBelong)) {
            initState.push(`${stateID}`);
          }
          if (acc[issueType]) {
            acc[issueType].push({ label: stateName, value: `${stateID}` });
          } else {
            acc[issueType] = [{ label: stateName, value: `${stateID}` }];
          }
          if (!allStateIds.current.length) {
            stateIds.push(stateID);
          }
          return acc;
        }, {}) || {};
      if (!allStateIds.current.length) {
        allStateIds.current = stateIds;
      }

      updater.filterState((prev: Obj) => ({ state: initState, ...prev }));
      const options = sortBy(
        map(collection, (stateArray, issueType) => {
          const label = ISSUE_TYPE_ICON_MAP[issueType];
          return {
            label: (
              <span className="flex-h-center">
                {label.icon}
                {label.name}
              </span>
            ),
            labelValue: label.value,
            children: stateArray,
          };
        }),
        (item) => indexOf(typeArr, item.labelValue),
      );
      return options;
    }, [workflowStateList]);

  React.useEffect(() => {
    getList();
  }, [stateCollection]);

  useEffectOnce(() => {
    if (!labelList.length) {
      getLabels({ type: 'issue' });
    }
    if (queryId && queryType) {
      update({
        curIssueDetail: { id: queryId, type: queryType } as ISSUE.Issue,
        drawerVisible: true,
      });
    }
    return () => {
      clearBacklogIssues();
    };
  });

  const addAuth = usePerm((s) => s.project.requirement.create.pass); // 目前迭代、任务、缺陷添加权限都一致

  const onIssueDrop = (val: ISSUE.IssueType) => {
    return updateIssue({ ...val, iterationID: -1 }).then(() => {
      getList({ pageNo: 1 });
    });
  };

  const [{ isOver }, drop] = useDrop({
    accept: BACKLOG_ISSUE_TYPE.iterationIssue,
    drop: (item: any) => ({ res: onIssueDrop(item.data) }), // drop需要返回一个Obj,如果直接返回Promise是无效的
    collect: (monitor) => ({
      isOver: monitor.isOver(),
    }),
  });

  React.useEffect(() => {
    updateSearch(filterState);
  }, [filterState]);

  const getList = React.useCallback(
    (filters: Obj = {}, goTop = true) => {
      goTop && (listRef.current.scrollTop = 0);
      const submitValues = { ...filterState, ...filters };
      const { finishedAtStartEnd, createdAtStartEnd, state } = submitValues;
      if (finishedAtStartEnd) {
        unset(submitValues, 'finishedAtStartEnd');
        submitValues.startFinishedAt = finishedAtStartEnd[0];
        submitValues.endFinishedAt = finishedAtStartEnd[1];
      }
      if (createdAtStartEnd) {
        unset(submitValues, 'createdAtStartEnd');
        submitValues.startCreatedAt = createdAtStartEnd[0];
        submitValues.endCreatedAt = createdAtStartEnd[1];
      }
      return getBacklogIssues({ ...submitValues, state: (state as number[])?.length ? state : allStateIds.current });
    },
    [filterState, getBacklogIssues],
  );

  const onDelete = (val: ISSUE.Issue) => {
    deleteIssue(val.id).then(() => {
      getList({ pageNo: 1 });
    });
  };

  const onAdd = () => updater.isAdding(true);

  const onClickIssue = (val: ISSUE.Issue) => {
    update({
      drawerVisible: true,
      curIssueDetail: val,
    });
  };

  const closeDrawer = ({ hasEdited, isCreate, isDelete }: CloseDrawerParam) => {
    update({
      drawerVisible: false,
      curIssueDetail: {} as ISSUE.Issue,
    });
    if (hasEdited || isCreate || isDelete) {
      getList();
    }
  };
  const conditionsFilter = React.useMemo(
    () => [
      {
        type: 'select',
        key: 'type',
        label: i18n.t('Type'),
        placeholder: i18n.t('filter by {name}', { name: i18n.t('Type') }),
        fixed: false,
        emptyText: i18n.t('dop:All'),
        showIndex: 1,
        options: [ISSUE_TYPE_MAP.REQUIREMENT, ISSUE_TYPE_MAP.TASK, ISSUE_TYPE_MAP.BUG],
      },
      {
        key: 'priority',
        label: i18n.t('dop:Priority'),
        emptyText: i18n.t('dop:All'),
        fixed: false,
        showIndex: 2,
        type: 'select' as const,
        placeholder: i18n.t('filter by {name}', { name: i18n.t('dop:Priority') }),
        options: map(ISSUE_PRIORITY_MAP),
      },
      {
        key: 'state',
        label: i18n.t('dop:Status'),
        type: 'select' as const,
        options: stateCollection,
        allowClear: false,
        fixed: false,
        showIndex: 3,
      },
      {
        key: 'label',
        label: i18n.t('label'),
        emptyText: i18n.t('dop:All'),
        fixed: false,
        haveFilter: true,
        type: 'select' as const,
        placeholder: i18n.t('filter by {name}', { name: i18n.t('label') }),
        options: map(labelList, (item) => ({ label: item.name, value: `${item.id}` })),
      },
      {
        key: 'assignee',
        label: i18n.t('dop:assignee'),
        fixed: false,
        type: 'memberSelector',
        customProps: {
          mode: 'multiple',
        },
      },
      {
        key: 'creator',
        label: i18n.t('Creator'),
        fixed: false,
        type: 'memberSelector',
        customProps: {
          mode: 'multiple',
        },
      },
      {
        key: 'finishedAtStartEnd',
        label: i18n.t('End date'),
        fixed: false,
        type: 'dateRange',
      },
      {
        key: 'createdAtStartEnd',
        label: i18n.t('dop:creation date'),
        fixed: false,
        type: 'dateRange',
      },
      {
        key: 'title',
        emptyText: i18n.t('dop:All'),
        fixed: true,
        placeholder: i18n.t('dop:please enter the title or ID'),
        type: 'input' as const,
      },
    ],
    [labelList, stateCollection],
  );

  const onFilter = (val: Obj) => {
    updater.filterState(val);
    getList({ ...val, pageNo: 1 });
  };

  const curType = isEmpty(filterState.type) ? map(ISSUE_OPTION) : filterState.type;

  const handleChangePage = (curPage: number, curSize?: number) => {
    getList({
      pageNo: curPage,
      pageSize: curSize,
    });
  };

  const listRef = React.useRef<{ scrollTop: number }>(null);
  const isHide = !!listRef.current && listRef.current.scrollTop;

  const tabs = [
    {
      key: 'export',
      text: i18n.t('Export'),
    },
    {
      key: 'record',
      text: i18n.t('Records'),
    },
  ];
  return (
    <div className="backlog-issues flex flex-col justify-center h-full" ref={drop}>
      <div className="backlog-issues-title flex justify-between items-center mb-2">
        <div className="flex items-center">
          <span className="font-bold text-base mr-2">{i18n.t('dop:Backlog')}</span>
          <Tooltip
            placement="right"
            title={i18n.t('dop:For issues that have not been scheduled for a specific iteration')}
          >
            <ErdaIcon type="help" className="cursor-pointer mr-2" />
          </Tooltip>
          <span className="text-desc">{i18n.t('{num} issues', { num: total })}</span>
        </div>
        <div>
          <ImportExport
            tabs={tabs}
            title={i18n.t('Export')}
            extraQuery={{ iterationID: -1 }}
            queryObj={{ ...filterState, projectID: +projectId }}
            issueType={curType}
            projectId={projectId}
          />

          <WithAuth pass={addAuth}>
            <Button className="ml-2" type="primary" onClick={onAdd}>
              <CustomIcon type="cir-add" className="mr-1" />
              {i18n.t('Add')}
            </Button>
          </WithAuth>
        </div>
      </div>
      <div className={'backlog-filter'}>
        <ContractiveFilter delay={1000} conditions={conditionsFilter} initValue={filterState} onChange={onFilter} />
      </div>
      <div className={`backlog-issues-content spin-full-height ${isOver ? 'drag-over' : ''}`} ref={drop}>
        <Spin spinning={!isHide && loading}>
          {isEmpty(backlogIssues) && !isAdding && <EmptyBacklog addAuth={addAuth} onAdd={onAdd} />}
          <div className="list-container">
            {
              <div className="backlog-issues-list p-2 bg-default-02" ref={listRef}>
                {isAdding ? (
                  <IssueForm
                    key="add"
                    className="backlog-issue-item hover-active-bg"
                    onCancel={() => updater.isAdding(false)}
                    onOk={(val: ISSUE.BacklogIssueCreateBody) => {
                      return createIssue({ ...val }).finally(() => {
                        updater.isAdding(true);
                        getList();
                      });
                    }}
                  />
                ) : null}
                {map(backlogIssues, (item) => (
                  <IssueItem
                    data={item}
                    key={item.id}
                    onDelete={onDelete}
                    issueType={BACKLOG_ISSUE_TYPE.undoneIssue}
                    onDragDelete={() => {
                      getList({ pageNo: 1 });
                    }}
                    onClickIssue={onClickIssue}
                  />
                ))}
              </div>
            }
            <Pagination
              className="flex items-center flex-wrap justify-end pt-2"
              showSizeChanger
              total={total}
              current={pageNo}
              pageSize={pageSize}
              onChange={handleChangePage}
            />
          </div>
        </Spin>
      </div>

      {drawerVisible ? (
        <EditIssueDrawer
          iterationID={-1}
          id={curIssueDetail.id}
          shareLink={`${location.href.split('?')[0]}?${mergeSearch(
            { id: curIssueDetail.id, type: curIssueDetail.type },
            true,
          )}`}
          issueType={curIssueDetail.type}
          visible={drawerVisible}
          closeDrawer={closeDrawer}
        />
      ) : null}
    </div>
  );
}
Example #13
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();
  }