diff --git a/app/Api/V1/Controllers/Chart/CategoryController.php b/app/Api/V1/Controllers/Chart/CategoryController.php index 069fa3cb92..d998cfcd86 100644 --- a/app/Api/V1/Controllers/Chart/CategoryController.php +++ b/app/Api/V1/Controllers/Chart/CategoryController.php @@ -32,7 +32,6 @@ use FireflyIII\Repositories\Category\NoCategoryRepositoryInterface; use FireflyIII\Repositories\Category\OperationsRepositoryInterface; use FireflyIII\User; use Illuminate\Http\JsonResponse; -use Illuminate\Support\Collection; /** * Class CategoryController @@ -88,131 +87,111 @@ class CategoryController extends Controller $end = $dates['end']; - $tempData = []; - $spent = $this->opsRepository->spentInPeriodPerCurrency(new Collection, new Collection, $start, $end); - $earned = $this->opsRepository->earnedInPeriodPerCurrency(new Collection, new Collection, $start, $end); - $categories = []; + $tempData = []; + $spentWith = $this->opsRepository->listExpenses($start, $end); + $earnedWith = $this->opsRepository->listIncome($start, $end); + $spentWithout = $this->noCatRepository->listExpenses($start, $end); + $earnedWithout = $this->noCatRepository->listIncome($start, $end); + $categories = []; - // earned: - foreach ($earned as $categoryId => $row) { - $categoryName = $row['name']; - foreach ($row['earned'] as $currencyId => $income) { - // find or make set for currency: - $key = sprintf('%s-e', $currencyId); - $decimalPlaces = $income['currency_decimal_places']; - if (!isset($tempData[$key])) { - $tempData[$key] = [ - 'label' => (string)trans('firefly.box_earned_in_currency', ['currency' => $income['currency_symbol']]), - 'currency_id' => $income['currency_id'], - 'currency_code' => $income['currency_code'], - 'currency_symbol' => $income['currency_symbol'], - 'currency_decimal_places' => $decimalPlaces, + + foreach ([$spentWith, $earnedWith] as $set) { + foreach ($set as $currency) { + foreach ($currency['categories'] as $category) { + $categories[] = $category['name']; + $inKey = sprintf('%d-i', $currency['currency_id']); + $outKey = sprintf('%d-e', $currency['currency_id']); + // make data arrays if not yet present. + $tempData[$inKey] = $tempData[$inKey] ?? [ + 'currency_id' => $currency['currency_id'], + 'label' => (string)trans('firefly.box_earned_in_currency', ['currency' => $currency['currency_name']]), + 'currency_code' => $currency['currency_code'], + 'currency_symbol' => $currency['currency_symbol'], + 'currency_decimal_places' => $currency['currency_decimal_places'], + 'type' => 'bar', // line, area or bar + 'yAxisID' => 0, // 0, 1, 2 + 'entries' => [ + // per category: + // "category" => 5, + ], + ]; + $tempData[$outKey] = $tempData[$outKey] ?? [ + 'currency_id' => $currency['currency_id'], + 'label' => (string)trans('firefly.box_spent_in_currency', ['currency' => $currency['currency_name']]), + 'currency_code' => $currency['currency_code'], + 'currency_symbol' => $currency['currency_symbol'], + 'currency_decimal_places' => $currency['currency_decimal_places'], + 'type' => 'bar', // line, area or bar + 'yAxisID' => 0, // 0, 1, 2 + 'entries' => [ + // per category: + // "category" => 5, + ], + ]; + + foreach ($category['transaction_journals'] as $journal) { + // is it expense or income? + $letter = -1 === bccomp($journal['amount'], '0') ? 'e' : 'i'; + $currentKey = sprintf('%d-%s', $currency['currency_id'], $letter); + $name = $category['name']; + $tempData[$currentKey]['entries'][$name] = $tempData[$currentKey]['entries'][$name] ?? '0'; + $tempData[$currentKey]['entries'][$name] = bcadd($tempData[$currentKey]['entries'][$name], $journal['amount']); + } + } + } + } + + foreach ([$spentWithout, $earnedWithout] as $set) { + foreach ($set as $currency) { + $inKey = sprintf('%d-i', $currency['currency_id']); + $outKey = sprintf('%d-e', $currency['currency_id']); + $categories[] = (string)trans('firefly.no_category'); + // make data arrays if not yet present. + $tempData[$inKey] = $tempData[$inKey] ?? [ + 'currency_id' => $currency['currency_id'], + 'label' => (string)trans('firefly.box_earned_in_currency', ['currency' => $currency['currency_name']]), + 'currency_code' => $currency['currency_code'], + 'currency_symbol' => $currency['currency_symbol'], + 'currency_decimal_places' => $currency['currency_decimal_places'], 'type' => 'bar', // line, area or bar 'yAxisID' => 0, // 0, 1, 2 - 'entries' => [], + 'entries' => [ + // per category: + // "category" => 5, + ], ]; - } - $amount = round($income['earned'], $decimalPlaces); - $categories[$categoryName] = isset($categories[$categoryName]) ? $categories[$categoryName] + $amount : $amount; - $tempData[$key]['entries'][$categoryName] - = $amount; - - } - } - - // earned with no category: - $noCategory = $this->noCatRepository->sumIncome($start, $end); - - foreach ($noCategory as $currencyId => $income) { - $categoryName = (string)trans('firefly.no_category'); - // find or make set for currency: - $key = sprintf('%s-e', $currencyId); - $decimalPlaces = $income['currency_decimal_places']; - if (!isset($tempData[$key])) { - $tempData[$key] = [ - 'label' => (string)trans('firefly.box_earned_in_currency', ['currency' => $income['currency_name']]), - 'currency_id' => $income['currency_id'], - 'currency_code' => $income['currency_code'], - 'currency_symbol' => $income['currency_symbol'], - 'currency_decimal_places' => $decimalPlaces, - 'type' => 'bar', // line, area or bar - 'yAxisID' => 0, // 0, 1, 2 - 'entries' => [], - ]; - } - $amount = round($income['sum'], $decimalPlaces); - $categories[$categoryName] = isset($categories[$categoryName]) ? $categories[$categoryName] + $amount : $amount; - $tempData[$key]['entries'][$categoryName] = $amount; - } - - - // spent - foreach ($spent as $categoryId => $row) { - $categoryName = $row['name']; - // create a new set if necessary, "spent (EUR)": - foreach ($row['spent'] as $currencyId => $expense) { - // find or make set for currency: - $key = sprintf('%s-s', $currencyId); - $decimalPlaces = $expense['currency_decimal_places']; - if (!isset($tempData[$key])) { - $tempData[$key] = [ - 'label' => (string)trans('firefly.box_spent_in_currency', ['currency' => $expense['currency_symbol']]), - 'currency_id' => $expense['currency_id'], - 'currency_code' => $expense['currency_code'], - 'currency_symbol' => $expense['currency_symbol'], - 'currency_decimal_places' => $decimalPlaces, + $tempData[$outKey] = $tempData[$outKey] ?? [ + 'currency_id' => $currency['currency_id'], + 'label' => (string)trans('firefly.box_spent_in_currency', ['currency' => $currency['currency_name']]), + 'currency_code' => $currency['currency_code'], + 'currency_symbol' => $currency['currency_symbol'], + 'currency_decimal_places' => $currency['currency_decimal_places'], 'type' => 'bar', // line, area or bar 'yAxisID' => 0, // 0, 1, 2 - 'entries' => [], + 'entries' => [ + // per category: + // "category" => 5, + ], ]; + foreach ($currency['transaction_journals'] as $journal) { + // is it expense or income? + $letter = -1 === bccomp($journal['amount'], '0') ? 'e' : 'i'; + $currentKey = sprintf('%d-%s', $currency['currency_id'], $letter); + $name = (string)trans('firefly.no_category'); + $tempData[$currentKey]['entries'][$name] = $tempData[$currentKey]['entries'][$name] ?? '0'; + $tempData[$currentKey]['entries'][$name] = bcadd($tempData[$currentKey]['entries'][$name], $journal['amount']); } - $amount = round($expense['spent'], $decimalPlaces); - $categories[$categoryName] = isset($categories[$categoryName]) ? $categories[$categoryName] + $amount : $amount; - $tempData[$key]['entries'][$categoryName] - = $amount; - } } - // spent with no category - $noCategory = $this->noCatRepository->spentInPeriodPcWoCategory(new Collection, $start, $end); - - - foreach ($noCategory as $currencyId => $expense) { - $categoryName = (string)trans('firefly.no_category'); - // find or make set for currency: - $key = sprintf('%s-s', $currencyId); - $decimalPlaces = $expense['currency_decimal_places']; - if (!isset($tempData[$key])) { - $tempData[$key] = [ - 'label' => (string)trans('firefly.box_spent_in_currency', ['currency' => $expense['currency_symbol']]), - 'currency_id' => $expense['currency_id'], - 'currency_code' => $expense['currency_code'], - 'currency_symbol' => $expense['currency_symbol'], - 'currency_decimal_places' => $decimalPlaces, - 'type' => 'bar', // line, area or bar - 'yAxisID' => 0, // 0, 1, 2 - 'entries' => [], - ]; - } - $amount = round($expense['spent'], $decimalPlaces); - $categories[$categoryName] = isset($categories[$categoryName]) ? $categories[$categoryName] + $amount : $amount; - $tempData[$key]['entries'][$categoryName] - = $amount; - } - - - asort($categories); - $keys = array_keys($categories); - // re-sort every spent array and add 0 for missing entries. foreach ($tempData as $index => $set) { $oldSet = $set['entries']; $newSet = []; - foreach ($keys as $key) { - $value = $oldSet[$key] ?? 0; - $value = $value < 0 ? $value * -1 : $value; - $newSet[$key] = $value; + foreach ($categories as $category) { + $value = $oldSet[$category] ?? '0'; + $value = -1 === bccomp($value, '0') ? bcmul($value, '-1') : $value; + $newSet[$category] = $value; } $tempData[$index]['entries'] = $newSet; } diff --git a/app/Helpers/Report/PopupReport.php b/app/Helpers/Report/PopupReport.php index 1b8ab5a0f3..397db5941e 100644 --- a/app/Helpers/Report/PopupReport.php +++ b/app/Helpers/Report/PopupReport.php @@ -52,9 +52,9 @@ class PopupReport implements PopupReportInterface /** * Collect the transactions for one account and one budget. * - * @param Budget $budget + * @param Budget $budget * @param Account $account - * @param array $attributes + * @param array $attributes * * @return array */ @@ -62,7 +62,11 @@ class PopupReport implements PopupReportInterface { /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); - $collector->setAccounts(new Collection([$account]))->setRange($attributes['startDate'], $attributes['endDate'])->setBudget($budget); + $collector->setAccounts(new Collection([$account])) + ->withAccountInformation() + ->withBudgetInformation() + ->withCategoryInformation() + ->setRange($attributes['startDate'], $attributes['endDate'])->setBudget($budget); return $collector->getExtractedJournals(); } @@ -71,7 +75,7 @@ class PopupReport implements PopupReportInterface * Collect the transactions for one account and no budget. * * @param Account $account - * @param array $attributes + * @param array $attributes * * @return array */ @@ -82,6 +86,8 @@ class PopupReport implements PopupReportInterface $collector ->setAccounts(new Collection([$account])) ->setTypes([TransactionType::WITHDRAWAL]) + ->withAccountInformation() + ->withCategoryInformation() ->setRange($attributes['startDate'], $attributes['endDate']) ->withoutBudget(); @@ -92,7 +98,7 @@ class PopupReport implements PopupReportInterface * Collect the transactions for a budget. * * @param Budget $budget - * @param array $attributes + * @param array $attributes * * @return array */ @@ -110,7 +116,11 @@ class PopupReport implements PopupReportInterface /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); - $collector->setAccounts($attributes['accounts'])->setRange($attributes['startDate'], $attributes['endDate']); + $collector->setAccounts($attributes['accounts']) + ->withAccountInformation() + ->withBudgetInformation() + ->withCategoryInformation() + ->setRange($attributes['startDate'], $attributes['endDate']); if (null !== $currency) { $collector->setCurrency($currency); @@ -130,7 +140,7 @@ class PopupReport implements PopupReportInterface * Collect journals by a category. * * @param Category $category - * @param array $attributes + * @param array $attributes * * @return array */ @@ -150,6 +160,9 @@ class PopupReport implements PopupReportInterface $collector->setAccounts($attributes['accounts']) ->setTypes([TransactionType::WITHDRAWAL, TransactionType::TRANSFER, TransactionType::DEPOSIT]) + ->withAccountInformation() + ->withBudgetInformation() + ->withCategoryInformation() ->setRange($attributes['startDate'], $attributes['endDate'])->withAccountInformation() ->setCategory($category); if (null !== $currency) { @@ -163,7 +176,7 @@ class PopupReport implements PopupReportInterface * Group transactions by expense. * * @param Account $account - * @param array $attributes + * @param array $attributes * * @return array */ @@ -187,6 +200,9 @@ class PopupReport implements PopupReportInterface $collector->setAccounts(new Collection([$account])) ->setRange($attributes['startDate'], $attributes['endDate']) + ->withAccountInformation() + ->withBudgetInformation() + ->withCategoryInformation() ->setTypes([TransactionType::WITHDRAWAL, TransactionType::TRANSFER]); if (null !== $currency) { @@ -200,7 +216,7 @@ class PopupReport implements PopupReportInterface * Collect transactions by income. * * @param Account $account - * @param array $attributes + * @param array $attributes * * @return array */ @@ -216,7 +232,11 @@ class PopupReport implements PopupReportInterface ->setDestinationAccounts($attributes['accounts']) ->setRange($attributes['startDate'], $attributes['endDate']) ->setTypes([TransactionType::DEPOSIT, TransactionType::TRANSFER]) + ->withAccountInformation() + ->withBudgetInformation() + ->withCategoryInformation() ->withAccountInformation(); + return $collector->getExtractedJournals(); } } diff --git a/app/Http/Controllers/Chart/CategoryController.php b/app/Http/Controllers/Chart/CategoryController.php index 95934e3432..abd7a44e09 100644 --- a/app/Http/Controllers/Chart/CategoryController.php +++ b/app/Http/Controllers/Chart/CategoryController.php @@ -28,12 +28,10 @@ use FireflyIII\Generator\Chart\Basic\GeneratorInterface; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Models\AccountType; use FireflyIII\Models\Category; -use FireflyIII\Models\TransactionCurrency; use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\Repositories\Category\CategoryRepositoryInterface; use FireflyIII\Repositories\Category\NoCategoryRepositoryInterface; use FireflyIII\Repositories\Category\OperationsRepositoryInterface; -use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface; use FireflyIII\Support\CacheProperties; use FireflyIII\Support\Chart\Category\WholePeriodChartGenerator; use FireflyIII\Support\Http\Controllers\AugumentData; @@ -68,8 +66,6 @@ class CategoryController extends Controller /** * Show an overview for a category for all time, per month/week/year. * - * TODO this chart is not multi-currency aware. - * * @param CategoryRepositoryInterface $repository * @param Category $category * @@ -82,7 +78,7 @@ class CategoryController extends Controller $cache->addProperty('chart.category.all'); $cache->addProperty($category->id); if ($cache->has()) { - return response()->json($cache->get()); // @codeCoverageIgnore + // return response()->json($cache->get()); // @codeCoverageIgnore } $start = $repository->firstUseDate($category) ?? $this->getDate(); $range = app('preferences')->get('viewRange', '1M')->data; @@ -116,12 +112,10 @@ class CategoryController extends Controller $cache->addProperty($end); $cache->addProperty('chart.category.frontpage'); if ($cache->has()) { - return response()->json($cache->get()); // @codeCoverageIgnore + // return response()->json($cache->get()); // @codeCoverageIgnore } // currency repos: - /** @var CurrencyRepositoryInterface $currencyRepository */ - $currencyRepository = app(CurrencyRepositoryInterface::class); /** @var CategoryRepositoryInterface $repository */ $repository = app(CategoryRepositoryInterface::class); @@ -134,68 +128,76 @@ class CategoryController extends Controller /** @var NoCategoryRepositoryInterface $noCatRepository */ $noCatRepository = app(NoCategoryRepositoryInterface::class); - $currencies = []; - - $chartData = []; + $currencies = []; $tempData = []; $categories = $repository->getCategories(); $accounts = $accountRepository->getAccountsByType([AccountType::ASSET, AccountType::DEFAULT]); /** @var Category $category */ foreach ($categories as $category) { - $spentArray = $opsRepository->spentInPeriodPerCurrency(new Collection([$category]), $accounts, $start, $end); - foreach ($spentArray as $categoryId => $spentInfo) { - foreach ($spentInfo['spent'] as $currencyId => $row) { - $spent = $row['spent']; - if (bccomp($spent, '0') === -1) { - $currencies[$currencyId] = $currencies[$currencyId] ?? $currencyRepository->findNull((int)$currencyId); - $tempData[] = [ - 'name' => $category->name, - 'spent' => bcmul($spent, '-1'), - 'spent_float' => (float)bcmul($spent, '-1'), - 'currency_id' => $currencyId, - ]; - } - } + $collection = new Collection([$category]); + $spent = $opsRepository->sumExpenses($start, $end, $accounts, $collection); + //$spentArray = $opsRepository->spentInPeriodPerCurrency(new Collection([$category]), $accounts, $start, $end); + foreach ($spent as $currency) { + $currencyId = $currency['currency_id']; + $currencies[$currencyId] = $currencies[$currencyId] ?? [ + 'currency_id' => $currencyId, + 'currency_name' => $currency['currency_name'], + 'currency_symbol' => $currency['currency_symbol'], + 'currency_code' => $currency['currency_code'], + 'currency_decimal_places' => $currency['currency_decimal_places'], + ]; + $tempData[] = [ + 'name' => $category->name, + 'sum' => $currency['sum'], + 'sum_float' => round($currency['sum'], $currency['currency_decimal_places']), + 'currency_id' => $currencyId, + ]; } } // no category per currency: - $noCategory = $noCatRepository->spentInPeriodPcWoCategory(new Collection, $start, $end); - foreach ($noCategory as $currencyId => $spent) { - $currencies[$currencyId] = $currencies[$currencyId] ?? $currencyRepository->findNull($currencyId); + $noCategory = $noCatRepository->sumExpenses($start, $end); + + foreach ($noCategory as $currency) { + $currencyId = $currency['currency_id']; + $currencies[$currencyId] = $currencies[$currencyId] ?? [ + 'currency_id' => $currency['currency_id'], + 'currency_name' => $currency['currency_name'], + 'currency_symbol' => $currency['currency_symbol'], + 'currency_code' => $currency['currency_code'], + 'currency_decimal_places' => $currency['currency_decimal_places'], + ]; $tempData[] = [ 'name' => trans('firefly.no_category'), - 'spent' => bcmul($spent['spent'], '-1'), - 'spent_float' => (float)bcmul($spent['spent'], '-1'), - 'currency_id' => $currencyId, + 'sum' => $currency['sum'], + 'sum_float' => round($currency['sum'], $currency['currency_decimal_places']), + 'currency_id' => $currency['currency_id'], ]; } // sort temp array by amount. - $amounts = array_column($tempData, 'spent_float'); + $amounts = array_column($tempData, 'sum_float'); array_multisort($amounts, SORT_DESC, $tempData); // loop all found currencies and build the data array for the chart. - /** - * @var int $currencyId - * @var TransactionCurrency $currency - */ - foreach ($currencies as $currencyId => $currency) { - $dataSet = [ - 'label' => (string)trans('firefly.spent'), + /** @var array $currency */ + foreach ($currencies as $currency) { + $dataSet = [ + 'label' => sprintf('%s (%s)', (string)trans('firefly.spent'), $currency['currency_name']), 'type' => 'bar', - 'currency_symbol' => $currency->symbol, + 'currency_symbol' => $currency['currency_symbol'], 'entries' => $this->expandNames($tempData), ]; - $chartData[$currencyId] = $dataSet; + $chartData[$currency['currency_id']] = $dataSet; } + // loop temp data and place data in correct array: foreach ($tempData as $entry) { $currencyId = $entry['currency_id']; $name = $entry['name']; - $chartData[$currencyId]['entries'][$name] = $entry['spent']; + $chartData[$currencyId]['entries'][$name] = bcmul($entry['sum'], '-1'); } $data = $this->generator->multiSet($chartData); $cache->store($data); @@ -206,8 +208,6 @@ class CategoryController extends Controller /** * Chart report. * - * TODO this chart is not multi-currency aware. - * * @param Category $category * @param Collection $accounts * @param Carbon $start @@ -224,44 +224,62 @@ class CategoryController extends Controller $cache->addProperty($accounts->pluck('id')->toArray()); $cache->addProperty($category); if ($cache->has()) { - return response()->json($cache->get());// @codeCoverageIgnore + // return response()->json($cache->get());// @codeCoverageIgnore } /** @var OperationsRepositoryInterface $opsRepository */ $opsRepository = app(OperationsRepositoryInterface::class); - $expenses = $opsRepository->periodExpenses(new Collection([$category]), $accounts, $start, $end); - $income = $opsRepository->periodIncome(new Collection([$category]), $accounts, $start, $end); - $periods = app('navigation')->listOfPeriods($start, $end); - $chartData = [ - [ - 'label' => (string)trans('firefly.spent'), + + // this gives us all currencies + $collection = new Collection([$category]); + $expenses = $opsRepository->listExpenses($start, $end, null, $collection); + $income = $opsRepository->listIncome($start, $end, null, $collection); + $currencies = array_unique(array_merge(array_keys($income), array_keys($expenses))); + $periods = app('navigation')->listOfPeriods($start, $end); + $format = app('navigation')->preferredCarbonLocalizedFormat($start, $end); + $chartData = []; + // make empty data array: + // double foreach (bad) to make empty array: + foreach ($currencies as $currencyId) { + $currencyInfo = $expenses[$currencyId] ?? $income[$currencyId]; + $outKey = sprintf('%d-out', $currencyId); + $inKey = sprintf('%d-in', $currencyId); + $chartData[$outKey] + = [ + 'label' => sprintf('%s (%s)', (string)trans('firefly.spent'), $currencyInfo['currency_name']), 'entries' => [], 'type' => 'bar', 'backgroundColor' => 'rgba(219, 68, 55, 0.5)', // red - ], - [ - 'label' => (string)trans('firefly.earned'), + ]; + + $chartData[$inKey] + = [ + 'label' => sprintf('%s (%s)', (string)trans('firefly.earned'), $currencyInfo['currency_name']), 'entries' => [], 'type' => 'bar', 'backgroundColor' => 'rgba(0, 141, 76, 0.5)', // green - ], - [ - 'label' => (string)trans('firefly.sum'), - 'entries' => [], - 'type' => 'line', - 'fill' => false, - ], - ]; + ]; - foreach (array_keys($periods) as $period) { - $label = $periods[$period]; - $spent = $expenses[$category->id]['entries'][$period] ?? '0'; - $earned = $income[$category->id]['entries'][$period] ?? '0'; - $sum = bcadd($spent, $earned); - $chartData[0]['entries'][$label] = round($spent, 12); - $chartData[1]['entries'][$label] = round($earned, 12); - $chartData[2]['entries'][$label] = round($sum, 12); + + // loop empty periods: + foreach (array_keys($periods) as $period) { + $label = $periods[$period]; + $chartData[$outKey]['entries'][$label] = '0'; + $chartData[$inKey]['entries'][$label] = '0'; + } + // loop income and expenses for this category.: + $outSet = $expenses[$currencyId]['categories'][$category->id] ?? ['transaction_journals' => []]; + foreach ($outSet['transaction_journals'] as $journal) { + $date = $journal['date']->formatLocalized($format); + $chartData[$outKey]['entries'][$date] = bcadd($journal['amount'], $chartData[$outKey]['entries'][$date]); + } + + $inSet = $income[$currencyId]['categories'][$category->id] ?? ['transaction_journals' => []]; + foreach ($inSet['transaction_journals'] as $journal) { + $date = $journal['date']->formatLocalized($format); + $chartData[$inKey]['entries'][$date] = bcadd($journal['amount'], $chartData[$inKey]['entries'][$date]); + } } $data = $this->generator->multiSet($chartData); @@ -288,7 +306,7 @@ class CategoryController extends Controller $cache->addProperty('chart.category.period.no-cat'); $cache->addProperty($accounts->pluck('id')->toArray()); if ($cache->has()) { - // return response()->json($cache->get()); // @codeCoverageIgnore + return response()->json($cache->get()); // @codeCoverageIgnore } /** @var NoCategoryRepositoryInterface $noCatRepository */ @@ -339,118 +357,13 @@ class CategoryController extends Controller $inSet = $income[$currencyId] ?? ['transaction_journals' => []]; foreach ($inSet['transaction_journals'] as $journal) { - $date = $journal['date']->formatLocalized($format); + $date = $journal['date']->formatLocalized($format); $chartData[$inKey]['entries'][$date] = bcadd($journal['amount'], $chartData[$inKey]['entries'][$date]); } } $data = $this->generator->multiSet($chartData); $cache->store($data); - return response()->json($data); - var_dump($chartData); - var_dump(array_values($chartData)); - exit; - - - $format = app('navigation')->preferredCarbonLocalizedFormat($start, $end); - $chartData = []; - - // double foreach (bad) to make empty array: - foreach ($currencies as $currencyId) { - $currencyInfo = $expenses[$currencyId] ?? $income[$currencyId]; - - $spentArray - = [ - 'label' => sprintf('%s (%s)', (string)trans('firefly.spent'), $currencyInfo['currency_name']), - 'entries' => [], - 'type' => 'bar', - 'backgroundColor' => 'rgba(219, 68, 55, 0.5)', // red - ]; - $incomeArray - = [ - 'label' => sprintf('%s (%s)', (string)trans('firefly.earned'), $currencyInfo['currency_name']), - 'entries' => [], - 'type' => 'bar', - 'backgroundColor' => 'rgba(0, 141, 76, 0.5)', // green - ]; - - foreach (array_keys($periods) as $period) { - $label = $periods[$period]; - $spentArray['entries'][$label] = '0'; - $incomeArray['entries'][$label] = '0'; - - // then loop income and then loop expenses, maybe? - $currencyExpenses = $expenses[$currencyId] ?? ['transaction_journals' => []]; - foreach ($currencyExpenses['transaction_journals'] as $row) { - - } - } - $chartData[] = $spentArray; - $chartData[] = $incomeArray; - } - var_dump($chartData); - exit; - - - foreach ($currencies as $currencyId) { - $currencyInfo = $expenses[$currencyId] ?? $income[$currencyId]; - // loop expenses[$currencyId], if set - $spentArray - = [ - 'label' => sprintf('%s (%s)', (string)trans('firefly.spent'), $currencyInfo['currency_name']), - 'entries' => [], - 'type' => 'bar', - 'backgroundColor' => 'rgba(219, 68, 55, 0.5)', // red - ]; - - $current = $expenses[$currencyId] ?? ['transaction_journals' => []]; - foreach ($current['transaction_journals'] as $row) { - $thisPeriod = $row['date']->formatLocalized($format); - $spentArray['entries'][$thisPeriod] = $spentArray['entries'][$thisPeriod] ?? '0'; - $spentArray['entries'][$thisPeriod] = bcadd($spentArray['entries'][$thisPeriod], $row['amount']); - } - $chartData[] = $spentArray; - - // loop income[$currencyId], if set - $incomeArray - = [ - 'label' => sprintf('%s (%s)', (string)trans('firefly.earned'), $currencyInfo['currency_name']), - 'entries' => [], - 'type' => 'bar', - 'backgroundColor' => 'rgba(0, 141, 76, 0.5)', // green - ]; - - $current = $income[$currencyId] ?? ['transaction_journals' => []]; - foreach ($current['transaction_journals'] as $row) { - $thisPeriod = $row['date']->formatLocalized($format); - $incomeArray['entries'][$thisPeriod] = $incomeArray['entries'][$thisPeriod] ?? '0'; - $incomeArray['entries'][$thisPeriod] = bcadd($incomeArray['entries'][$thisPeriod], $row['amount']); - } - $chartData[] = $incomeArray; - - // $chartData[] = [ - // 'label' => sprintf('%s (%s)', (string)trans('firefly.earned'), $currencyInfo['currency_name']), - // 'entries' => [], - // 'type' => 'bar', - // 'backgroundColor' => 'rgba(0, 141, 76, 0.5)', // green - // ]; - } - echo '
';
-        print_r($chartData);
-        exit;
-
-        foreach (array_keys($periods) as $period) {
-            $label                           = $periods[$period];
-            $spent                           = $expenses['entries'][$period] ?? '0';
-            $earned                          = $income['entries'][$period] ?? '0';
-            $sum                             = bcadd($spent, $earned);
-            $chartData[0]['entries'][$label] = bcmul($spent, '-1');
-            $chartData[1]['entries'][$label] = $earned;
-            $chartData[2]['entries'][$label] = $sum;
-        }
-        $data = $this->generator->multiSet($chartData);
-        $cache->store($data);
-
         return response()->json($data);
     }
 
diff --git a/app/Http/Controllers/Report/CategoryController.php b/app/Http/Controllers/Report/CategoryController.php
index 3a81a8a2fa..ddb2023415 100644
--- a/app/Http/Controllers/Report/CategoryController.php
+++ b/app/Http/Controllers/Report/CategoryController.php
@@ -69,24 +69,68 @@ class CategoryController extends Controller
         /** @var NoCategoryRepositoryInterface $noCatRepos */
         $noCatRepos = app(NoCategoryRepositoryInterface::class);
 
-        $periods    = app('navigation')->listOfPeriods($start, $end);
-        $data       = [];
-        $categories = $repository->getCategories();
-        $data       = $opsRepository->periodExpenses($categories, $accounts, $start, $end);
-        $data[0]    = $noCatRepos->periodExpensesNoCategory($accounts, $start, $end);
-        $report     = $this->filterPeriodReport($data);
-
         // depending on the carbon format (a reliable way to determine the general date difference)
         // change the "listOfPeriods" call so the entire period gets included correctly.
-        $range = app('navigation')->preferredCarbonFormat($start, $end);
+        $format = app('navigation')->preferredCarbonFormat($start, $end);
 
-        if ('Y' === $range) {
+        if ('Y' === $format) {
             $start->startOfYear();
         }
-        if ('Y-m' === $range) {
+        if ('Y-m' === $format) {
             $start->startOfMonth();
         }
 
+        $periods = app('navigation')->listOfPeriods($start, $end);
+        $data    = [];
+        $with    = $opsRepository->listExpenses($start, $end, $accounts);
+        $without = $noCatRepos->listExpenses($start, $end, $accounts);
+
+        foreach ($with as $currencyId => $currencyRow) {
+            foreach ($currencyRow['categories'] as $categoryId => $categoryRow) {
+                $key        = sprintf('%d-%d', $currencyId, $categoryId);
+                $data[$key] = $data[$key] ?? [
+                        'id'                      => $categoryRow['id'],
+                        'title'                   => sprintf('%s (%s)', $categoryRow['name'], $currencyRow['currency_name']),
+                        'currency_id'             => $currencyRow['currency_id'],
+                        'currency_symbol'         => $currencyRow['currency_symbol'],
+                        'currency_name'           => $currencyRow['currency_name'],
+                        'currency_code'           => $currencyRow['currency_code'],
+                        'currency_decimal_places' => $currencyRow['currency_decimal_places'],
+                        'sum'                     => '0',
+                        'entries'                 => [],
+
+                    ];
+                foreach ($categoryRow['transaction_journals'] as $journalId => $journal) {
+                    $date                         = $journal['date']->format($format);
+                    $data[$key]['entries'][$date] = $data[$key]['entries'][$date] ?? '0';
+                    $data[$key]['entries'][$date] = bcadd($data[$key]['entries'][$date], $journal['amount']);
+                    $data[$key]['sum']            = bcadd($data[$key]['sum'], $journal['amount']);
+                }
+            }
+        }
+        foreach ($without as $currencyId => $currencyRow) {
+            $key        = sprintf('0-%d', $currencyId);
+            $data[$key] = $data[$key] ?? [
+                    'id'                      => 0,
+                    'title'                   => sprintf('%s (%s)', trans('firefly.noCategory'), $currencyRow['currency_name']),
+                    'currency_id'             => $currencyRow['currency_id'],
+                    'currency_symbol'         => $currencyRow['currency_symbol'],
+                    'currency_name'           => $currencyRow['currency_name'],
+                    'currency_code'           => $currencyRow['currency_code'],
+                    'currency_decimal_places' => $currencyRow['currency_decimal_places'],
+                    'sum'                     => '0',
+                    'entries'                 => [],
+                ];
+            foreach ($currencyRow['transaction_journals'] as $journalId => $journal) {
+                $date                         = $journal['date']->format($format);
+                $data[$key]['entries'][$date] = $data[$key]['entries'][$date] ?? '0';
+                $data[$key]['entries'][$date] = bcadd($data[$key]['entries'][$date], $journal['amount']);
+                $data[$key]['sum']            = bcadd($data[$key]['sum'], $journal['amount']);
+            }
+        }
+        $cache->store($data);
+
+        $report = $data;
 
         try {
             $result = view('reports.partials.category-period', compact('report', 'periods'))->render();
@@ -121,34 +165,78 @@ class CategoryController extends Controller
         $cache->addProperty('category-period-income-report');
         $cache->addProperty($accounts->pluck('id')->toArray());
         if ($cache->has()) {
-            return $cache->get(); // @codeCoverageIgnore
+            // return $cache->get(); // @codeCoverageIgnore
         }
-        /** @var CategoryRepositoryInterface $repository */
-        $repository = app(CategoryRepositoryInterface::class);
 
         /** @var OperationsRepositoryInterface $opsRepository */
         $opsRepository = app(OperationsRepositoryInterface::class);
 
-        /** @var NoCategoryRepositoryInterface $noCatRepository */
-        $noCatRepository = app(NoCategoryRepositoryInterface::class);
-
-        $categories = $repository->getCategories();
-        $data       = $opsRepository->periodIncome($categories, $accounts, $start, $end);
-        $data[0]    = $noCatRepository->periodIncomeNoCategory($accounts, $start, $end);
-        $report     = $this->filterPeriodReport($data);
+        /** @var NoCategoryRepositoryInterface $noCatRepos */
+        $noCatRepos = app(NoCategoryRepositoryInterface::class);
 
         // depending on the carbon format (a reliable way to determine the general date difference)
         // change the "listOfPeriods" call so the entire period gets included correctly.
-        $range = app('navigation')->preferredCarbonFormat($start, $end);
+        $format = app('navigation')->preferredCarbonFormat($start, $end);
 
-        if ('Y' === $range) {
+        if ('Y' === $format) {
             $start->startOfYear();
         }
-        if ('Y-m' === $range) {
+        if ('Y-m' === $format) {
             $start->startOfMonth();
         }
 
         $periods = app('navigation')->listOfPeriods($start, $end);
+        $data    = [];
+        $with    = $opsRepository->listIncome($start, $end, $accounts);
+        $without = $noCatRepos->listIncome($start, $end, $accounts);
+
+        foreach ($with as $currencyId => $currencyRow) {
+            foreach ($currencyRow['categories'] as $categoryId => $categoryRow) {
+                $key        = sprintf('%d-%d', $currencyId, $categoryId);
+                $data[$key] = $data[$key] ?? [
+                        'id'                      => $categoryRow['id'],
+                        'title'                   => sprintf('%s (%s)', $categoryRow['name'], $currencyRow['currency_name']),
+                        'currency_id'             => $currencyRow['currency_id'],
+                        'currency_symbol'         => $currencyRow['currency_symbol'],
+                        'currency_name'           => $currencyRow['currency_name'],
+                        'currency_code'           => $currencyRow['currency_code'],
+                        'currency_decimal_places' => $currencyRow['currency_decimal_places'],
+                        'sum'                     => '0',
+                        'entries'                 => [],
+
+                    ];
+                foreach ($categoryRow['transaction_journals'] as $journalId => $journal) {
+                    $date                         = $journal['date']->format($format);
+                    $data[$key]['entries'][$date] = $data[$key]['entries'][$date] ?? '0';
+                    $data[$key]['entries'][$date] = bcadd($data[$key]['entries'][$date], $journal['amount']);
+                    $data[$key]['sum']            = bcadd($data[$key]['sum'], $journal['amount']);
+                }
+            }
+        }
+        foreach ($without as $currencyId => $currencyRow) {
+            $key        = sprintf('0-%d', $currencyId);
+            $data[$key] = $data[$key] ?? [
+                    'id'                      => 0,
+                    'title'                   => sprintf('%s (%s)', trans('firefly.noCategory'), $currencyRow['currency_name']),
+                    'currency_id'             => $currencyRow['currency_id'],
+                    'currency_symbol'         => $currencyRow['currency_symbol'],
+                    'currency_name'           => $currencyRow['currency_name'],
+                    'currency_code'           => $currencyRow['currency_code'],
+                    'currency_decimal_places' => $currencyRow['currency_decimal_places'],
+                    'sum'                     => '0',
+                    'entries'                 => [],
+                ];
+            foreach ($currencyRow['transaction_journals'] as $journalId => $journal) {
+                $date                         = $journal['date']->format($format);
+                $data[$key]['entries'][$date] = $data[$key]['entries'][$date] ?? '0';
+                $data[$key]['entries'][$date] = bcadd($data[$key]['entries'][$date], $journal['amount']);
+                $data[$key]['sum']            = bcadd($data[$key]['sum'], $journal['amount']);
+            }
+        }
+        $cache->store($data);
+
+        $report = $data;
+
         try {
             $result = view('reports.partials.category-period', compact('report', 'periods'))->render();
             // @codeCoverageIgnoreStart
@@ -157,6 +245,7 @@ class CategoryController extends Controller
             $result = sprintf('An error prevented Firefly III from rendering: %s. Apologies.', $e->getMessage());
         }
         // @codeCoverageIgnoreEnd
+
         $cache->store($result);
 
         return $result;
@@ -182,7 +271,7 @@ class CategoryController extends Controller
         $cache->addProperty('category-report');
         $cache->addProperty($accounts->pluck('id')->toArray());
         if ($cache->has()) {
-            return $cache->get(); // @codeCoverageIgnore
+            // return $cache->get(); // @codeCoverageIgnore
         }
 
         /** @var CategoryRepositoryInterface $repository */
@@ -191,60 +280,120 @@ class CategoryController extends Controller
         /** @var OperationsRepositoryInterface $opsRepository */
         $opsRepository = app(OperationsRepositoryInterface::class);
 
-        $categories = $repository->getCategories();
-        $report     = [
+        /** @var NoCategoryRepositoryInterface $noCatRepository */
+        $noCatRepository = app(NoCategoryRepositoryInterface::class);
+
+        $categories    = $repository->getCategories();
+        $earnedWith    = $opsRepository->listIncome($start, $end, $accounts);
+        $spentWith     = $opsRepository->listExpenses($start, $end, $accounts);
+        $earnedWithout = $noCatRepository->listIncome($start, $end, $accounts);
+        $spentWithout  = $noCatRepository->listExpenses($start, $end, $accounts);
+
+        $report = [
             'categories' => [],
             'sums'       => [],
         ];
-        /** @var Category $category */
-        foreach ($categories as $category) {
-            $spent  = $opsRepository->spentInPeriod($category, $accounts, $start, $end);
-            $earned = $opsRepository->earnedInPeriod($category, $accounts, $start, $end);
-            if (0 === count($spent) && 0 === count($earned)) {
-                continue;
-            }
-            $currencies = array_unique(array_merge(array_keys($spent), array_keys($earned)));
-            foreach ($currencies as $code) {
-                $currencyInfo               = $spent[$code] ?? $earned[$code];
-                $key                        = sprintf('%s-%s', $category->id, $code);
-                $report['categories'][$key] = [
-                    'name'                    => $category->name,
-                    'spent'                   => $spent[$code]['spent'] ?? '0',
-                    'earned'                  => $earned[$code]['earned'] ?? '0',
-                    'id'                      => $category->id,
-                    'currency_id'             => $currencyInfo['currency_id'],
-                    'currency_code'           => $currencyInfo['currency_code'],
-                    'currency_symbol'         => $currencyInfo['currency_symbol'],
-                    'currency_name'           => $currencyInfo['currency_name'],
-                    'currency_decimal_places' => $currencyInfo['currency_decimal_places'],
-                ];
 
+        // needs four for-each loops.
+        // TODO improve this.
+        foreach ([$earnedWith, $spentWith] as $data) {
+            foreach ($data as $currencyId => $currencyRow) {
+                $report['sums'][$currencyId] = $report['sums'][$currencyId] ?? [
+                        'spent'                     => '0',
+                        'earned'                     => '0',
+                        'sum'                     => '0',
+                        'currency_id'             => $currencyRow['currency_id'],
+                        'currency_symbol'         => $currencyRow['currency_symbol'],
+                        'currency_name'           => $currencyRow['currency_name'],
+                        'currency_code'           => $currencyRow['currency_code'],
+                        'currency_decimal_places' => $currencyRow['currency_decimal_places'],
+                    ];
+
+
+                foreach ($currencyRow['categories'] as $categoryId => $categoryRow) {
+                    $key                        = sprintf('%s-%s', $currencyId, $categoryId);
+                    $report['categories'][$key] = $report['categories'][$key] ?? [
+                            'id'                      => $categoryId,
+                            'title'                   => sprintf('%s (%s)', $categoryRow['name'], $currencyRow['currency_name']),
+                            'currency_id'             => $currencyRow['currency_id'],
+                            'currency_symbol'         => $currencyRow['currency_symbol'],
+                            'currency_name'           => $currencyRow['currency_name'],
+                            'currency_code'           => $currencyRow['currency_code'],
+                            'currency_decimal_places' => $currencyRow['currency_decimal_places'],
+                            'spent'                   => '0',
+                            'earned'                  => '0',
+                            'sum'                     => '0',
+                        ];
+                    // loop journals:
+                    foreach ($categoryRow['transaction_journals'] as $journal) {
+                        // sum of sums
+                        $report['sums'][$currencyId]['sum']   = bcadd($report['sums'][$currencyId]['sum'], $journal['amount']);
+                        // sum of spent:
+                        $report['sums'][$currencyId]['spent']   = -1 === bccomp($journal['amount'], '0') ? bcadd($report['sums'][$currencyId]['spent'], $journal['amount']): $report['sums'][$currencyId]['spent'];
+                        // sum of earned
+                        $report['sums'][$currencyId]['earned']   = 1 === bccomp($journal['amount'], '0') ? bcadd($report['sums'][$currencyId]['earned'], $journal['amount']): $report['sums'][$currencyId]['earned'];
+
+                        // sum of category
+                        $report['categories'][$key]['sum']    = bcadd($report['categories'][$key]['sum'], $journal['amount']);
+                        // total spent in category
+                        $report['categories'][$key]['spent']  = -1 === bccomp($journal['amount'], '0') ? bcadd(
+                            $report['categories'][$key]['spent'], $journal['amount']
+                        ) : $report['categories'][$key]['spent'];
+                        // total earned in category
+                        $report['categories'][$key]['earned'] = 1 === bccomp($journal['amount'], '0') ? bcadd(
+                            $report['categories'][$key]['earned'], $journal['amount']
+                        ) : $report['categories'][$key]['earned'];
+                    }
+                }
             }
         }
-        $sum = [];
-        /**
-         * @var string $categoryId
-         * @var array  $row
-         */
-        foreach ($report['categories'] as $categoryId => $row) {
-            $sum[$categoryId] = (float)$row['spent'];
-        }
-        array_multisort($sum, SORT_ASC, $report['categories']);
+        foreach ([$earnedWithout, $spentWithout] as $data) {
+            foreach ($data as $currencyId => $currencyRow) {
+                $report['sums'][$currencyId] = $report['sums'][$currencyId] ?? [
+                        'spent'                   => '0',
+                        'earned'                  => '0',
+                        'sum'                     => '0',
+                        'currency_id'             => $currencyRow['currency_id'],
+                        'currency_symbol'         => $currencyRow['currency_symbol'],
+                        'currency_name'           => $currencyRow['currency_name'],
+                        'currency_code'           => $currencyRow['currency_code'],
+                        'currency_decimal_places' => $currencyRow['currency_decimal_places'],
+                    ];
+                $key                         = sprintf('%s-0', $currencyId);
+                $report['categories'][$key]  = $report['categories'][$key] ?? [
+                        'id'                      => 0,
+                        'title'                   => sprintf('%s (%s)', trans('firefly.noCategory'), $currencyRow['currency_name']),
+                        'currency_id'             => $currencyRow['currency_id'],
+                        'currency_symbol'         => $currencyRow['currency_symbol'],
+                        'currency_name'           => $currencyRow['currency_name'],
+                        'currency_code'           => $currencyRow['currency_code'],
+                        'currency_decimal_places' => $currencyRow['currency_decimal_places'],
+                        'spent'                   => '0',
+                        'earned'                  => '0',
+                        'sum'                     => '0',
+                    ];
+                // loop journals:
+                foreach ($currencyRow['transaction_journals'] as $journal) {
+                    // sum of all
+                    $report['sums'][$currencyId]['sum']   = bcadd($report['sums'][$currencyId]['sum'], $journal['amount']);
 
-        // get sums:
-        foreach ($report['categories'] as $entry) {
-            $currencyId                            = $entry['currency_id'];
-            $report['sums'][$currencyId]           = $report['sums'][$currencyId] ?? [
-                    'spent'                   => '0',
-                    'earned'                  => '0',
-                    'currency_id'             => $entry['currency_id'],
-                    'currency_code'           => $entry['currency_code'],
-                    'currency_symbol'         => $entry['currency_symbol'],
-                    'currency_name'           => $entry['currency_name'],
-                    'cyrrency_decimal_places' => $entry['currency_decimal_places'],
-                ];
-            $report['sums'][$currencyId]['spent']  = bcadd($report['sums'][$currencyId]['spent'], $entry['spent']);
-            $report['sums'][$currencyId]['earned'] = bcadd($report['sums'][$currencyId]['earned'], $entry['earned']);
+                    // sum of spent:
+                    $report['sums'][$currencyId]['spent']   = -1 === bccomp($journal['amount'], '0') ? bcadd($report['sums'][$currencyId]['spent'], $journal['amount']): $report['sums'][$currencyId]['spent'];
+                    // sum of earned
+                    $report['sums'][$currencyId]['earned']   = 1 === bccomp($journal['amount'], '0') ? bcadd($report['sums'][$currencyId]['earned'], $journal['amount']): $report['sums'][$currencyId]['earned'];
+
+                    // sum of category
+                    $report['categories'][$key]['sum']    = bcadd($report['categories'][$key]['sum'], $journal['amount']);
+                    // total spent in no category
+                    $report['categories'][$key]['spent']  = -1 === bccomp($journal['amount'], '0') ? bcadd(
+                        $report['categories'][$key]['spent'], $journal['amount']
+                    ) : $report['categories'][$key]['spent'];
+                    // total earned in no category
+                    $report['categories'][$key]['earned'] = 1 === bccomp($journal['amount'], '0') ? bcadd(
+                        $report['categories'][$key]['earned'], $journal['amount']
+                    ) : $report['categories'][$key]['earned'];
+                }
+            }
         }
 
         // @codeCoverageIgnoreStart
diff --git a/app/Repositories/Category/NoCategoryRepository.php b/app/Repositories/Category/NoCategoryRepository.php
index 22dda6963b..130205c5a1 100644
--- a/app/Repositories/Category/NoCategoryRepository.php
+++ b/app/Repositories/Category/NoCategoryRepository.php
@@ -30,7 +30,6 @@ use FireflyIII\Models\TransactionType;
 use FireflyIII\User;
 use Illuminate\Support\Collection;
 use Log;
-use Navigation;
 
 /**
  *
@@ -141,83 +140,6 @@ class NoCategoryRepository implements NoCategoryRepositoryInterface
         return $array;
     }
 
-    /**
-     * @param Collection $accounts
-     * @param Carbon     $start
-     * @param Carbon     $end
-     *
-     * @return array
-     */
-    public function periodExpensesNoCategory(Collection $accounts, Carbon $start, Carbon $end): array
-    {
-        $carbonFormat = Navigation::preferredCarbonFormat($start, $end);
-
-        /** @var GroupCollectorInterface $collector */
-        $collector = app(GroupCollectorInterface::class);
-
-        $collector->setAccounts($accounts)->setRange($start, $end)->withAccountInformation();
-        $collector->setTypes([TransactionType::WITHDRAWAL, TransactionType::TRANSFER]);
-        $collector->withoutCategory();
-        $journals = $collector->getExtractedJournals();
-        $result   = [
-            'entries' => [],
-            'name'    => (string)trans('firefly.no_category'),
-            'sum'     => '0',
-        ];
-
-        /** @var array $journal */
-        foreach ($journals as $journal) {
-            $date = $journal['date']->format($carbonFormat);
-
-            if (!isset($result['entries'][$date])) {
-                $result['entries'][$date] = '0';
-            }
-            $result['entries'][$date] = bcadd($result['entries'][$date], $journal['amount']);
-        }
-
-        return $result;
-    }
-
-    /**
-     * @param Collection $accounts
-     * @param Carbon     $start
-     * @param Carbon     $end
-     *
-     * @return array
-     */
-    public function periodIncomeNoCategory(Collection $accounts, Carbon $start, Carbon $end): array
-    {
-        Log::debug('Now in periodIncomeNoCategory()');
-        $carbonFormat = Navigation::preferredCarbonFormat($start, $end);
-
-        /** @var GroupCollectorInterface $collector */
-        $collector = app(GroupCollectorInterface::class);
-
-        $collector->setAccounts($accounts)->setRange($start, $end)->withAccountInformation();
-        $collector->setTypes([TransactionType::DEPOSIT, TransactionType::TRANSFER]);
-        $collector->withoutCategory();
-        $journals = $collector->getExtractedJournals();
-        $result   = [
-            'entries' => [],
-            'name'    => (string)trans('firefly.no_category'),
-            'sum'     => '0',
-        ];
-        Log::debug('Looping transactions..');
-
-        foreach ($journals as $journal) {
-            $date = $journal['date']->format($carbonFormat);
-
-            if (!isset($result['entries'][$date])) {
-                $result['entries'][$date] = '0';
-            }
-            $result['entries'][$date] = bcadd($result['entries'][$date], bcmul($journal['amount'], '-1'));
-        }
-        Log::debug('Done looping transactions..');
-        Log::debug('Finished periodIncomeNoCategory()');
-
-        return $result;
-    }
-
     /**
      * @param User $user
      */
@@ -226,86 +148,6 @@ class NoCategoryRepository implements NoCategoryRepositoryInterface
         $this->user = $user;
     }
 
-    /**
-     * A very cryptic method name that means:
-     *
-     * Get me the amount spent in this period, grouped per currency, where no category was set.
-     *
-     * @param Collection $accounts
-     * @param Carbon     $start
-     * @param Carbon     $end
-     *
-     * @return array
-     */
-    public function spentInPeriodPcWoCategory(Collection $accounts, Carbon $start, Carbon $end): array
-    {
-        /** @var GroupCollectorInterface $collector */
-        $collector = app(GroupCollectorInterface::class);
-
-        $collector->setUser($this->user);
-        $collector->setRange($start, $end)->setTypes([TransactionType::WITHDRAWAL])->withoutCategory();
-
-        if ($accounts->count() > 0) {
-            $collector->setAccounts($accounts);
-        }
-
-        $set    = $collector->getExtractedJournals();
-        $return = [];
-        /** @var array $journal */
-        foreach ($set as $journal) {
-            $currencyId = (int)$journal['currency_id'];
-            if (!isset($return[$currencyId])) {
-                $return[$currencyId] = [
-                    'spent'                   => '0',
-                    'currency_id'             => $currencyId,
-                    'currency_symbol'         => $journal['currency_symbol'],
-                    'currency_code'           => $journal['currency_code'],
-                    'currency_decimal_places' => $journal['currency_decimal_places'],
-                ];
-            }
-            $return[$currencyId]['spent'] = bcadd($return[$currencyId]['spent'], $journal['amount']);
-        }
-
-        return $return;
-    }
-
-    /**
-     * Sum of income journals in period without a category, grouped per currency. Amounts are always positive.
-     *
-     * @param Carbon          $start
-     * @param Carbon          $end
-     * @param Collection|null $accounts
-     *
-     * @return array
-     */
-    public function sumIncome(Carbon $start, Carbon $end, ?Collection $accounts = null): array
-    {
-        /** @var GroupCollectorInterface $collector */
-        $collector = app(GroupCollectorInterface::class);
-        $collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionType::DEPOSIT])->withoutCategory();
-
-        if (null !== $accounts && $accounts->count() > 0) {
-            $collector->setAccounts($accounts);
-        }
-        $journals = $collector->getExtractedJournals();
-        $array    = [];
-
-        foreach ($journals as $journal) {
-            $currencyId                = (int)$journal['currency_id'];
-            $array[$currencyId]        = $array[$currencyId] ?? [
-                    'sum'                     => '0',
-                    'currency_id'             => $currencyId,
-                    'currency_name'           => $journal['currency_name'],
-                    'currency_symbol'         => $journal['currency_symbol'],
-                    'currency_code'           => $journal['currency_code'],
-                    'currency_decimal_places' => $journal['currency_decimal_places'],
-                ];
-            $array[$currencyId]['sum'] = bcadd($array[$currencyId]['sum'], app('steam')->positive($journal['amount']));
-        }
-
-        return $array;
-    }
-
     /**
      * Sum of withdrawal journals in period without a category, grouped per currency. Amounts are always negative.
      *
@@ -342,4 +184,41 @@ class NoCategoryRepository implements NoCategoryRepositoryInterface
 
         return $array;
     }
+
+    /**
+     * Sum of income journals in period without a category, grouped per currency. Amounts are always positive.
+     *
+     * @param Carbon          $start
+     * @param Carbon          $end
+     * @param Collection|null $accounts
+     *
+     * @return array
+     */
+    public function sumIncome(Carbon $start, Carbon $end, ?Collection $accounts = null): array
+    {
+        /** @var GroupCollectorInterface $collector */
+        $collector = app(GroupCollectorInterface::class);
+        $collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionType::DEPOSIT])->withoutCategory();
+
+        if (null !== $accounts && $accounts->count() > 0) {
+            $collector->setAccounts($accounts);
+        }
+        $journals = $collector->getExtractedJournals();
+        $array    = [];
+
+        foreach ($journals as $journal) {
+            $currencyId                = (int)$journal['currency_id'];
+            $array[$currencyId]        = $array[$currencyId] ?? [
+                    'sum'                     => '0',
+                    'currency_id'             => $currencyId,
+                    'currency_name'           => $journal['currency_name'],
+                    'currency_symbol'         => $journal['currency_symbol'],
+                    'currency_code'           => $journal['currency_code'],
+                    'currency_decimal_places' => $journal['currency_decimal_places'],
+                ];
+            $array[$currencyId]['sum'] = bcadd($array[$currencyId]['sum'], app('steam')->positive($journal['amount']));
+        }
+
+        return $array;
+    }
 }
\ No newline at end of file
diff --git a/app/Repositories/Category/NoCategoryRepositoryInterface.php b/app/Repositories/Category/NoCategoryRepositoryInterface.php
index 2611cbfee3..c889285753 100644
--- a/app/Repositories/Category/NoCategoryRepositoryInterface.php
+++ b/app/Repositories/Category/NoCategoryRepositoryInterface.php
@@ -35,18 +35,6 @@ use Illuminate\Support\Collection;
  */
 interface NoCategoryRepositoryInterface
 {
-    /**
-     * TODO not multi-currency
-     *
-     * @param Collection $accounts
-     * @param Carbon     $start
-     * @param Carbon     $end
-     *
-     * @return array
-     * @deprecated
-     */
-    public function periodExpensesNoCategory(Collection $accounts, Carbon $start, Carbon $end): array;
-
     /**
      * This method returns a list of all the withdrawal transaction journals (as arrays) set in that period
      * which have no category set to them. It's grouped per currency, with as few details in the array
@@ -60,60 +48,6 @@ interface NoCategoryRepositoryInterface
      */
     public function listExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null): array;
 
-    /**
-     * Sum of withdrawal journals in period without a category, grouped per currency. Amounts are always negative.
-     *
-     * @param Carbon          $start
-     * @param Carbon          $end
-     * @param Collection|null $accounts
-     *
-     * @return array
-     */
-    public function sumExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null): array;
-
-    /**
-     * TODO not multi-currency
-     *
-     * @param Collection $accounts
-     * @param Carbon     $start
-     * @param Carbon     $end
-     *
-     * @return array
-     * @deprecated
-     */
-    public function periodIncomeNoCategory(Collection $accounts, Carbon $start, Carbon $end): array;
-
-    /**
-     * @param User $user
-     */
-    public function setUser(User $user): void;
-
-    /**
-     * A very cryptic method name that means:
-     *
-     * Get me the amount spent in this period, grouped per currency, where no category was set.
-     *
-     * @param Collection $accounts
-     * @param Carbon     $start
-     * @param Carbon     $end
-     *
-     * @return array
-     * @deprecated
-     *
-     */
-    public function spentInPeriodPcWoCategory(Collection $accounts, Carbon $start, Carbon $end): array;
-
-    /**
-     * Sum of income journals in period without a category, grouped per currency. Amounts are always positive.
-     *
-     * @param Carbon          $start
-     * @param Carbon          $end
-     * @param Collection|null $accounts
-     *
-     * @return array
-     */
-    public function sumIncome(Carbon $start, Carbon $end, ?Collection $accounts = null): array;
-
     /**
      * This method returns a list of all the deposit transaction journals (as arrays) set in that period
      * which have no category set to them. It's grouped per currency, with as few details in the array
@@ -127,5 +61,32 @@ interface NoCategoryRepositoryInterface
      */
     public function listIncome(Carbon $start, Carbon $end, ?Collection $accounts = null): array;
 
+    /**
+     * @param User $user
+     */
+    public function setUser(User $user): void;
+
+    /**
+     * Sum of withdrawal journals in period without a category, grouped per currency. Amounts are always negative.
+     *
+     * @param Carbon          $start
+     * @param Carbon          $end
+     * @param Collection|null $accounts
+     *
+     * @return array
+     */
+    public function sumExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null): array;
+
+    /**
+     * Sum of income journals in period without a category, grouped per currency. Amounts are always positive.
+     *
+     * @param Carbon          $start
+     * @param Carbon          $end
+     * @param Collection|null $accounts
+     *
+     * @return array
+     */
+    public function sumIncome(Carbon $start, Carbon $end, ?Collection $accounts = null): array;
+
 
 }
\ No newline at end of file
diff --git a/app/Repositories/Category/OperationsRepository.php b/app/Repositories/Category/OperationsRepository.php
index 04fb867d23..e6fde5812a 100644
--- a/app/Repositories/Category/OperationsRepository.php
+++ b/app/Repositories/Category/OperationsRepository.php
@@ -26,12 +26,10 @@ namespace FireflyIII\Repositories\Category;
 
 use Carbon\Carbon;
 use FireflyIII\Helpers\Collector\GroupCollectorInterface;
-use FireflyIII\Models\Category;
 use FireflyIII\Models\TransactionType;
 use FireflyIII\User;
 use Illuminate\Support\Collection;
 use Log;
-use Navigation;
 
 /**
  *
@@ -53,202 +51,135 @@ class OperationsRepository implements OperationsRepositoryInterface
     }
 
     /**
-     * @param Category   $category
-     * @param Collection $accounts
-     * @param Carbon     $start
-     * @param Carbon     $end
+     * This method returns a list of all the withdrawal transaction journals (as arrays) set in that period
+     * which have the specified category set to them. It's grouped per currency, with as few details in the array
+     * as possible. Amounts are always negative.
+     *
+     * First currency, then categories.
+     *
+     * @param Carbon          $start
+     * @param Carbon          $end
+     * @param Collection|null $accounts
+     * @param Collection|null $categories
      *
      * @return array
      */
-    public function earnedInPeriod(Category $category, Collection $accounts, Carbon $start, Carbon $end): array
+    public function listExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $categories = null): array
     {
         /** @var GroupCollectorInterface $collector */
         $collector = app(GroupCollectorInterface::class);
-
-
-        $collector->setUser($this->user);
-        $collector->setRange($start, $end)->setTypes([TransactionType::DEPOSIT])->setCategory($category);
-
-        if ($accounts->count() > 0) {
+        $collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionType::WITHDRAWAL]);
+        if (null !== $accounts && $accounts->count() > 0) {
             $collector->setAccounts($accounts);
         }
-        // collect and group results:
-        $array  = $collector->getExtractedJournals();
-        $return = [];
-
-        foreach ($array as $journal) {
-            $currencyCode = $journal['currency_code'];
-            if (!isset($return[$currencyCode])) {
-                $return[$currencyCode] = [
-                    'currency_id'             => $journal['currency_id'],
-                    'currency_code'           => $journal['currency_code'],
-                    'currency_name'           => $journal['currency_name'],
-                    'currency_symbol'         => $journal['currency_symbol'],
-                    'currency_decimal_places' => $journal['currency_decimal_places'],
-                    'earned'                  => '0',
-                ];
-            }
-
-            // also extract foreign currency information:
-            if (null !== $journal['foreign_currency_id']) {
-                $currencyCode = $journal['foreign_currency_code'];
-                if (!isset($return[$currencyCode])) {
-                    $return[$currencyCode] = [
-                        'currency_id'             => $journal['foreign_currency_id'],
-                        'currency_code'           => $journal['foreign_currency_code'],
-                        'currency_name'           => $journal['foreign_currency_name'],
-                        'currency_symbol'         => $journal['foreign_currency_symbol'],
-                        'currency_decimal_places' => $journal['foreign_currency_decimal_places'],
-                        'earned'                  => '0',
-                    ];
-                }
-                $return[$currencyCode]['earned'] = bcadd($return[$currencyCode]['earned'], app('steam')->positive($journal['foreign_amount']));
-            }
-            $return[$currencyCode]['earned'] = bcadd($return[$currencyCode]['earned'], app('steam')->positive($journal['amount']));
-        }
-
-        return $return;
-    }
-
-    /**
-     * @param Collection $categories
-     * @param Collection $accounts
-     * @param Carbon     $start
-     * @param Carbon     $end
-     *
-     * @return array
-     */
-    public function earnedInPeriodPerCurrency(Collection $categories, Collection $accounts, Carbon $start, Carbon $end): array
-    {
-        /** @var GroupCollectorInterface $collector */
-        $collector = app(GroupCollectorInterface::class);
-
-        $collector->setUser($this->user);
-        $collector->setRange($start, $end)->setTypes([TransactionType::DEPOSIT]);
-
-        if ($categories->count() > 0) {
+        if (null !== $categories && $categories->count() > 0) {
             $collector->setCategories($categories);
         }
-        if (0 === $categories->count()) {
+        if (null === $categories || (null !== $categories && 0 === $categories->count())) {
             $collector->setCategories($this->getCategories());
         }
-
-        if ($accounts->count() > 0) {
-            $collector->setAccounts($accounts);
-        }
         $journals = $collector->getExtractedJournals();
-        $return   = [];
+        $array    = [];
+
         foreach ($journals as $journal) {
-            $categoryId = (int)$journal['category_id'];
             $currencyId = (int)$journal['currency_id'];
-            $name       = $journal['category_name'];
-            // make array for category:
-            if (!isset($return[$categoryId])) {
-                $return[$categoryId] = [
-                    'name'   => $name,
-                    'earned' => [],
-                ];
-            }
-            if (!isset($return[$categoryId]['earned'][$currencyId])) {
-                $return[$categoryId]['earned'][$currencyId] = [
-                    'earned'                  => '0',
+            $categoryId = (int)$journal['category_id'];
+
+            // info about the currency:
+            $array[$currencyId] = $array[$currencyId] ?? [
+                    'categories'              => [],
                     'currency_id'             => $currencyId,
+                    'currency_name'           => $journal['currency_name'],
                     'currency_symbol'         => $journal['currency_symbol'],
                     'currency_code'           => $journal['currency_code'],
                     'currency_decimal_places' => $journal['currency_decimal_places'],
                 ];
-            }
-            $return[$categoryId]['earned'][$currencyId]['earned']
-                = bcadd($return[$categoryId]['earned'][$currencyId]['earned'], $journal['amount']);
+
+            // info about the categories:
+            $array[$currencyId]['categories'][$categoryId] = $array[$currencyId]['categories'][$categoryId] ?? [
+                    'id'                   => $categoryId,
+                    'name'                 => $journal['category_name'],
+                    'transaction_journals' => [],
+                ];
+
+            // add journal to array:
+            // only a subset of the fields.
+            $journalId = (int)$journal['transaction_journal_id'];
+
+
+            $array[$currencyId]['categories'][$categoryId]['transaction_journals'][$journalId] = [
+                'amount' => app('steam')->negative($journal['amount']),
+                'date'   => $journal['date'],
+            ];
+
         }
 
-        return $return;
+        return $array;
     }
 
     /**
-     * @param Collection $categories
-     * @param Collection $accounts
-     * @param Carbon     $start
-     * @param Carbon     $end
+     * This method returns a list of all the deposit transaction journals (as arrays) set in that period
+     * which have the specified category set to them. It's grouped per currency, with as few details in the array
+     * as possible. Amounts are always positive.
+     *
+     * @param Carbon          $start
+     * @param Carbon          $end
+     * @param Collection|null $accounts
+     * @param Collection|null $categories
      *
      * @return array
      */
-    public function periodExpenses(Collection $categories, Collection $accounts, Carbon $start, Carbon $end): array
+    public function listIncome(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $categories = null): array
     {
-        $carbonFormat = Navigation::preferredCarbonFormat($start, $end);
-        $data         = [];
-        // prep data array:
-        /** @var Category $category */
-        foreach ($categories as $category) {
-            $data[$category->id] = [
-                'name'    => $category->name,
-                'sum'     => '0',
-                'entries' => [],
-            ];
-        }
-
-        // get all transactions:
         /** @var GroupCollectorInterface $collector */
         $collector = app(GroupCollectorInterface::class);
-
-        $collector->setAccounts($accounts)->setRange($start, $end);
-        $collector->setCategories($categories)->setTypes([TransactionType::WITHDRAWAL, TransactionType::TRANSFER])
-                  ->withAccountInformation()->withCategoryInformation();
+        $collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionType::DEPOSIT]);
+        if (null !== $accounts && $accounts->count() > 0) {
+            $collector->setAccounts($accounts);
+        }
+        if (null !== $categories && $categories->count() > 0) {
+            $collector->setCategories($categories);
+        }
+        if (null === $categories || (null !== $categories && 0 === $categories->count())) {
+            $collector->setCategories($this->getCategories());
+        }
         $journals = $collector->getExtractedJournals();
-
-        // loop transactions:
+        $array    = [];
 
         foreach ($journals as $journal) {
-            $categoryId                          = (int)$journal['category_id'];
-            $date                                = $journal['date']->format($carbonFormat);
-            $data[$categoryId]['entries'][$date] = bcadd($data[$categoryId]['entries'][$date] ?? '0', $journal['amount']);
-        }
+            $currencyId = (int)$journal['currency_id'];
+            $categoryId = (int)$journal['category_id'];
 
-        return $data;
-    }
+            // info about the currency:
+            $array[$currencyId] = $array[$currencyId] ?? [
+                    'categories'              => [],
+                    'currency_id'             => $currencyId,
+                    'currency_name'           => $journal['currency_name'],
+                    'currency_symbol'         => $journal['currency_symbol'],
+                    'currency_code'           => $journal['currency_code'],
+                    'currency_decimal_places' => $journal['currency_decimal_places'],
+                ];
 
-    /**
-     * TODO not multi currency aware.
-     *
-     * @param Collection $categories
-     * @param Collection $accounts
-     * @param Carbon     $start
-     * @param Carbon     $end
-     *
-     * @return array
-     */
-    public function periodIncome(Collection $categories, Collection $accounts, Carbon $start, Carbon $end): array
-    {
-        $carbonFormat = Navigation::preferredCarbonFormat($start, $end);
-        $data         = [];
-        // prep data array:
-        /** @var Category $category */
-        foreach ($categories as $category) {
-            $data[$category->id] = [
-                'name'    => $category->name,
-                'sum'     => '0',
-                'entries' => [],
+            // info about the categories:
+            $array[$currencyId]['categories'][$categoryId] = $array[$currencyId]['categories'][$categoryId] ?? [
+                    'id'                   => $categoryId,
+                    'name'                 => $journal['category_name'],
+                    'transaction_journals' => [],
+                ];
+
+            // add journal to array:
+            // only a subset of the fields.
+            $journalId = (int)$journal['transaction_journal_id'];
+
+
+            $array[$currencyId]['categories'][$categoryId]['transaction_journals'][$journalId] = [
+                'amount' => app('steam')->positive($journal['amount']),
+                'date'   => $journal['date'],
             ];
+
         }
 
-        // get all transactions:
-        /** @var GroupCollectorInterface $collector */
-        $collector = app(GroupCollectorInterface::class);
-
-        $collector->setAccounts($accounts)->setRange($start, $end);
-        $collector->setCategories($categories)->setTypes([TransactionType::DEPOSIT, TransactionType::TRANSFER])
-                  ->withAccountInformation();
-        $journals = $collector->getExtractedJournals();
-
-        // loop transactions:
-        /** @var array $journal */
-        foreach ($journals as $journal) {
-            $categoryId                          = (int)$journal['category_id'];
-            $date                                = $journal['date']->format($carbonFormat);
-            $data[$categoryId]['entries'][$date] = bcadd($data[$categoryId]['entries'][$date] ?? '0', bcmul($journal['amount'], '-1'));
-        }
-
-        return $data;
+        return $array;
     }
 
     /**
@@ -260,118 +191,89 @@ class OperationsRepository implements OperationsRepositoryInterface
     }
 
     /**
-     * Returns the amount spent in a category, for a set of accounts, in a specific period.
+     * Sum of withdrawal journals in period for a set of categories, grouped per currency. Amounts are always negative.
      *
-     * @param Category   $category
-     * @param Collection $accounts
-     * @param Carbon     $start
-     * @param Carbon     $end
+     * @param Carbon          $start
+     * @param Carbon          $end
+     * @param Collection|null $accounts
+     * @param Collection|null $categories
      *
      * @return array
      */
-    public function spentInPeriod(Category $category, Collection $accounts, Carbon $start, Carbon $end): array
+    public function sumExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $categories = null): array
     {
         /** @var GroupCollectorInterface $collector */
         $collector = app(GroupCollectorInterface::class);
-        $collector->setUser($this->user);
-        $collector->setRange($start, $end)->setTypes([TransactionType::WITHDRAWAL])->setCategory($category);
+        $collector->setUser($this->user)->setRange($start, $end)
+                  ->setTypes([TransactionType::WITHDRAWAL]);
 
-        if ($accounts->count() > 0) {
+        if (null !== $accounts && $accounts->count() > 0) {
             $collector->setAccounts($accounts);
         }
-        // collect and group results:
-        $array  = $collector->getExtractedJournals();
-        $return = [];
+        if (null === $categories || (null !== $categories && 0 === $categories->count())) {
+            $categories = $this->getCategories();
+        }
+        $collector->setCategories($categories);
+        $journals = $collector->getExtractedJournals();
+        $array    = [];
 
-        foreach ($array as $journal) {
-            $currencyCode = $journal['currency_code'];
-            if (!isset($return[$currencyCode])) {
-                $return[$currencyCode] = [
-                    'currency_id'             => $journal['currency_id'],
-                    'currency_code'           => $journal['currency_code'],
+        foreach ($journals as $journal) {
+            $currencyId                = (int)$journal['currency_id'];
+            $array[$currencyId]        = $array[$currencyId] ?? [
+                    'sum'                     => '0',
+                    'currency_id'             => $currencyId,
                     'currency_name'           => $journal['currency_name'],
                     'currency_symbol'         => $journal['currency_symbol'],
+                    'currency_code'           => $journal['currency_code'],
                     'currency_decimal_places' => $journal['currency_decimal_places'],
-                    'spent'                   => '0',
                 ];
-            }
-
-            // also extract foreign currency information:
-            if (null !== $journal['foreign_currency_id']) {
-                $currencyCode = $journal['foreign_currency_code'];
-                if (!isset($return[$currencyCode])) {
-                    $return[$currencyCode] = [
-                        'currency_id'             => $journal['foreign_currency_id'],
-                        'currency_code'           => $journal['foreign_currency_code'],
-                        'currency_name'           => $journal['foreign_currency_name'],
-                        'currency_symbol'         => $journal['foreign_currency_symbol'],
-                        'currency_decimal_places' => $journal['foreign_currency_decimal_places'],
-                        'spent'                   => '0',
-                    ];
-                }
-                $return[$currencyCode]['spent'] = bcadd($return[$currencyCode]['spent'], $journal['foreign_amount']);
-            }
-            $return[$currencyCode]['spent'] = bcadd($return[$currencyCode]['spent'], $journal['amount']);
+            $array[$currencyId]['sum'] = bcadd($array[$currencyId]['sum'], app('steam')->negative($journal['amount']));
         }
 
-        return $return;
+        return $array;
     }
 
     /**
-     * @param Collection $categories
-     * @param Collection $accounts
-     * @param Carbon     $start
-     * @param Carbon     $end
+     * Sum of income journals in period for a set of categories, grouped per currency. Amounts are always positive.
+     *
+     * @param Carbon          $start
+     * @param Carbon          $end
+     * @param Collection|null $accounts
+     * @param Collection|null $categories
      *
      * @return array
      */
-    public function spentInPeriodPerCurrency(Collection $categories, Collection $accounts, Carbon $start, Carbon $end): array
+    public function sumIncome(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $categories = null): array
     {
         /** @var GroupCollectorInterface $collector */
         $collector = app(GroupCollectorInterface::class);
-        $collector->setUser($this->user);
-        $collector->setRange($start, $end)->setTypes([TransactionType::WITHDRAWAL]);
+        $collector->setUser($this->user)->setRange($start, $end)
+                  ->setTypes([TransactionType::DEPOSIT]);
 
-        if ($categories->count() > 0) {
-            $collector->setCategories($categories);
-        }
-        if (0 === $categories->count()) {
-            $collector->setCategories($this->getCategories());
-        }
-
-        if ($accounts->count() > 0) {
+        if (null !== $accounts && $accounts->count() > 0) {
             $collector->setAccounts($accounts);
         }
+        if (null === $categories || (null !== $categories && 0 === $categories->count())) {
+            $categories = $this->getCategories();
+        }
+        $collector->setCategories($categories);
+        $journals = $collector->getExtractedJournals();
+        $array    = [];
 
-        $set    = $collector->getExtractedJournals();
-        $return = [];
-        /** @var array $journal */
-        foreach ($set as $journal) {
-            $categoryId = (int)$journal['category_id'];
-            $currencyId = (int)$journal['currency_id'];
-            $name       = $journal['category_name'];
-
-            // make array for category:
-            if (!isset($return[$categoryId])) {
-                $return[$categoryId] = [
-                    'name'  => $name,
-                    'spent' => [],
-                ];
-            }
-            if (!isset($return[$categoryId]['spent'][$currencyId])) {
-                $return[$categoryId]['spent'][$currencyId] = [
-                    'spent'                   => '0',
+        foreach ($journals as $journal) {
+            $currencyId                = (int)$journal['currency_id'];
+            $array[$currencyId]        = $array[$currencyId] ?? [
+                    'sum'                     => '0',
                     'currency_id'             => $currencyId,
+                    'currency_name'           => $journal['currency_name'],
                     'currency_symbol'         => $journal['currency_symbol'],
                     'currency_code'           => $journal['currency_code'],
                     'currency_decimal_places' => $journal['currency_decimal_places'],
                 ];
-            }
-            $return[$categoryId]['spent'][$currencyId]['spent']
-                = bcadd($return[$categoryId]['spent'][$currencyId]['spent'], $journal['amount']);
+            $array[$currencyId]['sum'] = bcadd($array[$currencyId]['sum'], app('steam')->positive($journal['amount']));
         }
 
-        return $return;
+        return $array;
     }
 
     /**
diff --git a/app/Repositories/Category/OperationsRepositoryInterface.php b/app/Repositories/Category/OperationsRepositoryInterface.php
index 3cd72991b1..84a082d012 100644
--- a/app/Repositories/Category/OperationsRepositoryInterface.php
+++ b/app/Repositories/Category/OperationsRepositoryInterface.php
@@ -24,7 +24,6 @@ declare(strict_types=1);
 namespace FireflyIII\Repositories\Category;
 
 use Carbon\Carbon;
-use FireflyIII\Models\Category;
 use FireflyIII\User;
 use Illuminate\Support\Collection;
 
@@ -36,51 +35,32 @@ use Illuminate\Support\Collection;
 interface OperationsRepositoryInterface
 {
     /**
-     * Returns the amount earned in a category, for a set of accounts, in a specific period.
+     * This method returns a list of all the withdrawal transaction journals (as arrays) set in that period
+     * which have the specified category set to them. It's grouped per currency, with as few details in the array
+     * as possible. Amounts are always negative.
      *
-     * @param Category   $category
-     * @param Collection $accounts
-     * @param Carbon     $start
-     * @param Carbon     $end
+     * @param Carbon          $start
+     * @param Carbon          $end
+     * @param Collection|null $accounts
+     * @param Collection|null $categories
      *
      * @return array
-     * @deprecated
-     *
      */
-    public function earnedInPeriod(Category $category, Collection $accounts, Carbon $start, Carbon $end): array;
+    public function listExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $categories = null): array;
 
     /**
-     * @param Collection $categories
-     * @param Collection $accounts
-     * @param Carbon     $start
-     * @param Carbon     $end
+     * This method returns a list of all the deposit transaction journals (as arrays) set in that period
+     * which have the specified category set to them. It's grouped per currency, with as few details in the array
+     * as possible. Amounts are always positive.
+     *
+     * @param Carbon          $start
+     * @param Carbon          $end
+     * @param Collection|null $accounts
+     * @param Collection|null $categories
      *
      * @return array
-     * @deprecated
      */
-    public function earnedInPeriodPerCurrency(Collection $categories, Collection $accounts, Carbon $start, Carbon $end): array;
-
-    /**
-     * @param Collection $categories
-     * @param Collection $accounts
-     * @param Carbon     $start
-     * @param Carbon     $end
-     *
-     * @return array
-     * @deprecated
-     */
-    public function periodExpenses(Collection $categories, Collection $accounts, Carbon $start, Carbon $end): array;
-
-    /**
-     * @param Collection $categories
-     * @param Collection $accounts
-     * @param Carbon     $start
-     * @param Carbon     $end
-     *
-     * @return array
-     * @deprecated
-     */
-    public function periodIncome(Collection $categories, Collection $accounts, Carbon $start, Carbon $end): array;
+    public function listIncome(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $categories = null): array;
 
     /**
      * @param User $user
@@ -88,27 +68,26 @@ interface OperationsRepositoryInterface
     public function setUser(User $user): void;
 
     /**
-     * Returns the amount spent in a category, for a set of accounts, in a specific period.
+     * Sum of withdrawal journals in period for a set of categories, grouped per currency. Amounts are always negative.
      *
-     * @param Category   $category
-     * @param Collection $accounts
-     * @param Carbon     $start
-     * @param Carbon     $end
+     * @param Carbon          $start
+     * @param Carbon          $end
+     * @param Collection|null $accounts
+     * @param Collection|null $categories
      *
      * @return array
-     * @deprecated
-     *
      */
-    public function spentInPeriod(Category $category, Collection $accounts, Carbon $start, Carbon $end): array;
+    public function sumExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $categories = null): array;
 
     /**
-     * @param Collection $categories
-     * @param Collection $accounts
-     * @param Carbon     $start
-     * @param Carbon     $end
+     * Sum of income journals in period for a set of categories, grouped per currency. Amounts are always positive.
+     *
+     * @param Carbon          $start
+     * @param Carbon          $end
+     * @param Collection|null $accounts
+     * @param Collection|null $categories
      *
      * @return array
-     * @deprecated
      */
-    public function spentInPeriodPerCurrency(Collection $categories, Collection $accounts, Carbon $start, Carbon $end): array;
+    public function sumIncome(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $categories = null): array;
 }
\ No newline at end of file
diff --git a/app/Support/Chart/Category/WholePeriodChartGenerator.php b/app/Support/Chart/Category/WholePeriodChartGenerator.php
index e067888192..cf22550d51 100644
--- a/app/Support/Chart/Category/WholePeriodChartGenerator.php
+++ b/app/Support/Chart/Category/WholePeriodChartGenerator.php
@@ -28,6 +28,7 @@ use FireflyIII\Models\Category;
 use FireflyIII\Repositories\Account\AccountRepositoryInterface;
 use FireflyIII\Repositories\Category\CategoryRepositoryInterface;
 use FireflyIII\Repositories\Category\OperationsRepositoryInterface;
+use Illuminate\Support\Collection;
 
 /**
  * Class WholePeriodChartGenerator
@@ -43,6 +44,7 @@ class WholePeriodChartGenerator
      */
     public function generate(Category $category, Carbon $start, Carbon $end): array
     {
+        $collection = new Collection([$category]);
         /** @var CategoryRepositoryInterface $repository */
         $repository = app(CategoryRepositoryInterface::class);
 
@@ -65,10 +67,11 @@ class WholePeriodChartGenerator
         while ($current <= $end) {
             $key          = $current->format('Y-m-d');
             $currentEnd   = app('navigation')->endOfPeriod($current, $step);
-            $spent[$key]  = $opsRepository->spentInPeriod($category, $accounts, $current, $currentEnd);
-            $earned[$key] = $opsRepository->earnedInPeriod($category, $accounts, $current, $currentEnd);
+            $spent[$key]  = $opsRepository->sumExpenses($current, $currentEnd, $accounts, $collection);
+            $earned[$key] = $opsRepository->sumIncome($current, $currentEnd, $accounts, $collection);
             $current      = app('navigation')->addPeriod($current, $step, 0);
         }
+
         $currencies = $this->extractCurrencies($spent) + $this->extractCurrencies($earned);
 
         // generate chart data (for each currency)
@@ -95,21 +98,23 @@ class WholePeriodChartGenerator
         $current = clone $start;
 
         while ($current <= $end) {
-            $key        = $current->format('Y-m-d');
-            $label      = app('navigation')->periodShow($current, $step);
+            $key   = $current->format('Y-m-d');
+            $label = app('navigation')->periodShow($current, $step);
 
             /** @var array $currency */
             foreach ($currencies as $currency) {
                 $code                                         = $currency['currency_code'];
+                $currencyId                                   = $currency['currency_id'];
                 $spentInfoKey                                 = sprintf('spent-in-%s', $code);
                 $earnedInfoKey                                = sprintf('earned-in-%s', $code);
-                $spentAmount                                  = $spent[$key][$code]['spent'] ?? '0';
-                $earnedAmount                                 = $earned[$key][$code]['earned'] ?? '0';
+                $spentAmount                                  = $spent[$key][$currencyId]['sum'] ?? '0';
+                $earnedAmount                                 = $earned[$key][$currencyId]['sum'] ?? '0';
                 $chartData[$spentInfoKey]['entries'][$label]  = round($spentAmount, $currency['currency_decimal_places']);
                 $chartData[$earnedInfoKey]['entries'][$label] = round($earnedAmount, $currency['currency_decimal_places']);
             }
             $current = app('navigation')->addPeriod($current, $step, 0);
         }
+
         return $chartData;
     }
 
@@ -150,18 +155,15 @@ class WholePeriodChartGenerator
     private function extractCurrencies(array $array): array
     {
         $return = [];
-        foreach ($array as $info) {
-            foreach ($info as $block) {
-                $currencyId = $block['currency_id'];
-                if (!isset($return[$currencyId])) {
-                    $return[$currencyId] = [
-                        'currency_id'             => $block['currency_id'],
-                        'currency_code'           => $block['currency_code'],
-                        'currency_name'           => $block['currency_name'],
-                        'currency_symbol'         => $block['currency_symbol'],
-                        'currency_decimal_places' => $block['currency_decimal_places'],
+        foreach ($array as $block) {
+            foreach ($block as $currencyId => $currencyRow) {
+                $return[$currencyId] = $return[$currencyId] ?? [
+                        'currency_id'             => $currencyId,
+                        'currency_name'           => $currencyRow['currency_name'],
+                        'currency_symbol'         => $currencyRow['currency_symbol'],
+                        'currency_code'           => $currencyRow['currency_code'],
+                        'currency_decimal_places' => $currencyRow['currency_decimal_places'],
                     ];
-                }
             }
         }
 
diff --git a/app/Transformers/CategoryTransformer.php b/app/Transformers/CategoryTransformer.php
index da13d1b164..cfe3173fd2 100644
--- a/app/Transformers/CategoryTransformer.php
+++ b/app/Transformers/CategoryTransformer.php
@@ -71,8 +71,8 @@ class CategoryTransformer extends AbstractTransformer
         $start  = $this->parameters->get('start');
         $end    = $this->parameters->get('end');
         if (null !== $start && null !== $end) {
-            $earned = array_values($this->opsRepository->earnedInPeriod($category, new Collection, $start, $end));
-            $spent  = array_values($this->opsRepository->spentInPeriod($category, new Collection, $start, $end));
+            $earned = $this->beautify($this->opsRepository->sumIncome($start, $end, null, new Collection([$category])));
+            $spent  = $this->beautify($this->opsRepository->sumExpenses($start, $end, null, new Collection([$category])));
         }
         $data = [
             'id'         => (int)$category->id,
@@ -91,4 +91,20 @@ class CategoryTransformer extends AbstractTransformer
 
         return $data;
     }
+
+    /**
+     * @param array $array
+     *
+     * @return array
+     */
+    private function beautify(array $array): array
+    {
+        $return = [];
+        foreach ($array as $data) {
+            $data['sum'] = round($data['sum'], $data['currency_decimal_places']);
+            $return[]    = $data;
+        }
+
+        return $return;
+    }
 }
diff --git a/resources/views/v1/reports/partials/categories.twig b/resources/views/v1/reports/partials/categories.twig
index 9a07c2d2dc..c2e8c3593e 100644
--- a/resources/views/v1/reports/partials/categories.twig
+++ b/resources/views/v1/reports/partials/categories.twig
@@ -4,28 +4,29 @@
         {{ 'category'|_ }}
         {{ 'spent'|_ }}
         {{ 'earned'|_ }}
+        {{ 'sum'|_ }}
          
     
     
     
-
-    {% for index, category in report.categories %}
+    {% for category in report.categories %}
         {% if loop.index > listLength %}
             
         {% else %}
             
         {% endif %}
         
-            {{ category.name }}
+            {{ category.title }}
         
         {{ formatAmountBySymbol(category.spent, category.currency_symbol, category.currency_decimal_places, true) }}
         {{ formatAmountBySymbol(category.earned, category.currency_symbol, category.currency_decimal_places, true) }}
+        {{ formatAmountBySymbol(category.sum, category.currency_symbol, category.currency_decimal_places, true) }}
         
             
         
-        
+    
     {% endfor %}
     
     
@@ -45,17 +46,10 @@
         
             {{ formatAmountBySymbol(sum.earned, sum.currency_symbol, sum.currency_decimal_places) }}
         
-        
+        
+            {{ formatAmountBySymbol(sum.sum, sum.currency_symbol, sum.currency_decimal_places) }}
+        
     
     {% endfor %}
-    {#
-    
-        {{ 'sum'|_ }}
-        {{ sumEarned|formatAmount }}
-        {{ sumSpent|formatAmount }}
-         
-    
-    TODO fix the sum here.
-    #}
     
 
diff --git a/resources/views/v1/reports/partials/category-period.twig b/resources/views/v1/reports/partials/category-period.twig
index 05d49b3a2f..17dbfbb940 100644
--- a/resources/views/v1/reports/partials/category-period.twig
+++ b/resources/views/v1/reports/partials/category-period.twig
@@ -9,27 +9,27 @@
     
     
     
-    {% for id, info in report %}
+    {% for info in report %}
         
             
-                {% if id != 0 %}
-                    
+                {% if info.id != 0 %}
+                    
                 {% else %}
                     
                 {% endif %}
             
-            
-                {{ info.name }}
+            
+                {{ info.title }}
             
             {% for key, period in periods %}
                 {# income first #}
                 {% if(info.entries[key]) %}
                     
-                        {{ info.entries[key]|formatAmount }}
+                        {{ formatAmountBySymbol(info.entries[key], info.currency_symbol, info.currency_decimal_places) }}
                     
                 {% else %}
                     
-                        {{ 0|formatAmount }}
+                        {{ formatAmountBySymbol(0, info.currency_symbol, info.currency_decimal_places) }}
                     
                 {% endif %}
             {% endfor %}
@@ -37,11 +37,11 @@
             {# if sum of income, display: #}
             {% if info.sum %}
                 
-                    {{ info.sum|formatAmount }}
+                    {{ formatAmountBySymbol(info.sum, info.currency_symbol, info.currency_decimal_places) }}
                 
             {% else %}
                 
-                    {{ 0|formatAmount }}
+                    {{ formatAmountBySymbol(0, info.currency_symbol, info.currency_decimal_places) }}
                 
             {% endif %}