{"size": 1541, "ext": "js", "max_stars_repo_path": "src/client/src/selectors/transactions.js", "max_stars_repo_name": "imunitnok/alfa-fullstack-workshop", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/client/src/selectors/transactions.js", "max_issues_repo_name": "imunitnok/alfa-fullstack-workshop", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/client/src/selectors/transactions.js", "max_forks_repo_name": "imunitnok/alfa-fullstack-workshop", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 25.262295082, "max_line_length": 73, "alphanum_fraction": 0.6060999351}
import moment from "moment";
import { createSelector } from "reselect";
import { getActiveCard } from "./cards";

const separateByDates = (transactions, activeCard) => {
  const creditDebitFlag = ({ from, to }) => {
    if (from == null) return 1;
    else if (activeCard.number === from) return 0;
    else if (activeCard.number === to) return 2;
  };

  const getHistoryItemTitle = item => {
    let flag = creditDebitFlag(item);

    if (flag === 1) return "Операция пополнения при открытии";
    else if (flag === 0) return `Операция перевода на ${item.to}`;
    else if (flag === 2) return `Операция перевода с ${item.from}`;
  };

  const sortedData = transactions.sort((a, b) => {
    if (a.dateTime < b.dateTime) return 1;
    else if (a.dateTime > b.dateTime) return -1;
    else return 0;
  });

  return sortedData.reduce((result, item) => {
    const { from, to, dateTime, sum } = item;

    const key = moment(dateTime).format("L");

    let row = result.find(item => item.key === key);

    if (!row) {
      row = {
        key,
        data: []
      };
      result.push(row);
    }

    row.data.push({
      id: dateTime + from,
      hhmm: moment(dateTime).format("HH:mm"),
      title: getHistoryItemTitle({
        from,
        to
      }),
      sum
    });

    return result;
  }, []);
};

const getTransactions = state => state.transactions.data;

export const getTransactionsByDays = createSelector(
  [getTransactions, getActiveCard],
  (transactions, activeCard) => separateByDates(transactions, activeCard)
);
