Refactor category repositories.

This commit is contained in:
James Cole
2019-08-28 12:28:23 +02:00
parent e11af70f99
commit fa706d27d8
12 changed files with 713 additions and 919 deletions

View File

@@ -32,7 +32,6 @@ use FireflyIII\Repositories\Category\NoCategoryRepositoryInterface;
use FireflyIII\Repositories\Category\OperationsRepositoryInterface; use FireflyIII\Repositories\Category\OperationsRepositoryInterface;
use FireflyIII\User; use FireflyIII\User;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
use Illuminate\Support\Collection;
/** /**
* Class CategoryController * Class CategoryController
@@ -88,131 +87,111 @@ class CategoryController extends Controller
$end = $dates['end']; $end = $dates['end'];
$tempData = []; $tempData = [];
$spent = $this->opsRepository->spentInPeriodPerCurrency(new Collection, new Collection, $start, $end); $spentWith = $this->opsRepository->listExpenses($start, $end);
$earned = $this->opsRepository->earnedInPeriodPerCurrency(new Collection, new Collection, $start, $end); $earnedWith = $this->opsRepository->listIncome($start, $end);
$categories = []; $spentWithout = $this->noCatRepository->listExpenses($start, $end);
$earnedWithout = $this->noCatRepository->listIncome($start, $end);
$categories = [];
// earned:
foreach ($earned as $categoryId => $row) { foreach ([$spentWith, $earnedWith] as $set) {
$categoryName = $row['name']; foreach ($set as $currency) {
foreach ($row['earned'] as $currencyId => $income) { foreach ($currency['categories'] as $category) {
// find or make set for currency: $categories[] = $category['name'];
$key = sprintf('%s-e', $currencyId); $inKey = sprintf('%d-i', $currency['currency_id']);
$decimalPlaces = $income['currency_decimal_places']; $outKey = sprintf('%d-e', $currency['currency_id']);
if (!isset($tempData[$key])) { // make data arrays if not yet present.
$tempData[$key] = [ $tempData[$inKey] = $tempData[$inKey] ?? [
'label' => (string)trans('firefly.box_earned_in_currency', ['currency' => $income['currency_symbol']]), 'currency_id' => $currency['currency_id'],
'currency_id' => $income['currency_id'], 'label' => (string)trans('firefly.box_earned_in_currency', ['currency' => $currency['currency_name']]),
'currency_code' => $income['currency_code'], 'currency_code' => $currency['currency_code'],
'currency_symbol' => $income['currency_symbol'], 'currency_symbol' => $currency['currency_symbol'],
'currency_decimal_places' => $decimalPlaces, '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 'type' => 'bar', // line, area or bar
'yAxisID' => 0, // 0, 1, 2 'yAxisID' => 0, // 0, 1, 2
'entries' => [], 'entries' => [
// per category:
// "category" => 5,
],
]; ];
} $tempData[$outKey] = $tempData[$outKey] ?? [
$amount = round($income['earned'], $decimalPlaces); 'currency_id' => $currency['currency_id'],
$categories[$categoryName] = isset($categories[$categoryName]) ? $categories[$categoryName] + $amount : $amount; 'label' => (string)trans('firefly.box_spent_in_currency', ['currency' => $currency['currency_name']]),
$tempData[$key]['entries'][$categoryName] 'currency_code' => $currency['currency_code'],
= $amount; 'currency_symbol' => $currency['currency_symbol'],
'currency_decimal_places' => $currency['currency_decimal_places'],
}
}
// 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,
'type' => 'bar', // line, area or bar 'type' => 'bar', // line, area or bar
'yAxisID' => 0, // 0, 1, 2 '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. // re-sort every spent array and add 0 for missing entries.
foreach ($tempData as $index => $set) { foreach ($tempData as $index => $set) {
$oldSet = $set['entries']; $oldSet = $set['entries'];
$newSet = []; $newSet = [];
foreach ($keys as $key) { foreach ($categories as $category) {
$value = $oldSet[$key] ?? 0; $value = $oldSet[$category] ?? '0';
$value = $value < 0 ? $value * -1 : $value; $value = -1 === bccomp($value, '0') ? bcmul($value, '-1') : $value;
$newSet[$key] = $value; $newSet[$category] = $value;
} }
$tempData[$index]['entries'] = $newSet; $tempData[$index]['entries'] = $newSet;
} }

View File

@@ -52,9 +52,9 @@ class PopupReport implements PopupReportInterface
/** /**
* Collect the transactions for one account and one budget. * Collect the transactions for one account and one budget.
* *
* @param Budget $budget * @param Budget $budget
* @param Account $account * @param Account $account
* @param array $attributes * @param array $attributes
* *
* @return array * @return array
*/ */
@@ -62,7 +62,11 @@ class PopupReport implements PopupReportInterface
{ {
/** @var GroupCollectorInterface $collector */ /** @var GroupCollectorInterface $collector */
$collector = app(GroupCollectorInterface::class); $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(); return $collector->getExtractedJournals();
} }
@@ -71,7 +75,7 @@ class PopupReport implements PopupReportInterface
* Collect the transactions for one account and no budget. * Collect the transactions for one account and no budget.
* *
* @param Account $account * @param Account $account
* @param array $attributes * @param array $attributes
* *
* @return array * @return array
*/ */
@@ -82,6 +86,8 @@ class PopupReport implements PopupReportInterface
$collector $collector
->setAccounts(new Collection([$account])) ->setAccounts(new Collection([$account]))
->setTypes([TransactionType::WITHDRAWAL]) ->setTypes([TransactionType::WITHDRAWAL])
->withAccountInformation()
->withCategoryInformation()
->setRange($attributes['startDate'], $attributes['endDate']) ->setRange($attributes['startDate'], $attributes['endDate'])
->withoutBudget(); ->withoutBudget();
@@ -92,7 +98,7 @@ class PopupReport implements PopupReportInterface
* Collect the transactions for a budget. * Collect the transactions for a budget.
* *
* @param Budget $budget * @param Budget $budget
* @param array $attributes * @param array $attributes
* *
* @return array * @return array
*/ */
@@ -110,7 +116,11 @@ class PopupReport implements PopupReportInterface
/** @var GroupCollectorInterface $collector */ /** @var GroupCollectorInterface $collector */
$collector = app(GroupCollectorInterface::class); $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) { if (null !== $currency) {
$collector->setCurrency($currency); $collector->setCurrency($currency);
@@ -130,7 +140,7 @@ class PopupReport implements PopupReportInterface
* Collect journals by a category. * Collect journals by a category.
* *
* @param Category $category * @param Category $category
* @param array $attributes * @param array $attributes
* *
* @return array * @return array
*/ */
@@ -150,6 +160,9 @@ class PopupReport implements PopupReportInterface
$collector->setAccounts($attributes['accounts']) $collector->setAccounts($attributes['accounts'])
->setTypes([TransactionType::WITHDRAWAL, TransactionType::TRANSFER, TransactionType::DEPOSIT]) ->setTypes([TransactionType::WITHDRAWAL, TransactionType::TRANSFER, TransactionType::DEPOSIT])
->withAccountInformation()
->withBudgetInformation()
->withCategoryInformation()
->setRange($attributes['startDate'], $attributes['endDate'])->withAccountInformation() ->setRange($attributes['startDate'], $attributes['endDate'])->withAccountInformation()
->setCategory($category); ->setCategory($category);
if (null !== $currency) { if (null !== $currency) {
@@ -163,7 +176,7 @@ class PopupReport implements PopupReportInterface
* Group transactions by expense. * Group transactions by expense.
* *
* @param Account $account * @param Account $account
* @param array $attributes * @param array $attributes
* *
* @return array * @return array
*/ */
@@ -187,6 +200,9 @@ class PopupReport implements PopupReportInterface
$collector->setAccounts(new Collection([$account])) $collector->setAccounts(new Collection([$account]))
->setRange($attributes['startDate'], $attributes['endDate']) ->setRange($attributes['startDate'], $attributes['endDate'])
->withAccountInformation()
->withBudgetInformation()
->withCategoryInformation()
->setTypes([TransactionType::WITHDRAWAL, TransactionType::TRANSFER]); ->setTypes([TransactionType::WITHDRAWAL, TransactionType::TRANSFER]);
if (null !== $currency) { if (null !== $currency) {
@@ -200,7 +216,7 @@ class PopupReport implements PopupReportInterface
* Collect transactions by income. * Collect transactions by income.
* *
* @param Account $account * @param Account $account
* @param array $attributes * @param array $attributes
* *
* @return array * @return array
*/ */
@@ -216,7 +232,11 @@ class PopupReport implements PopupReportInterface
->setDestinationAccounts($attributes['accounts']) ->setDestinationAccounts($attributes['accounts'])
->setRange($attributes['startDate'], $attributes['endDate']) ->setRange($attributes['startDate'], $attributes['endDate'])
->setTypes([TransactionType::DEPOSIT, TransactionType::TRANSFER]) ->setTypes([TransactionType::DEPOSIT, TransactionType::TRANSFER])
->withAccountInformation()
->withBudgetInformation()
->withCategoryInformation()
->withAccountInformation(); ->withAccountInformation();
return $collector->getExtractedJournals(); return $collector->getExtractedJournals();
} }
} }

View File

@@ -28,12 +28,10 @@ use FireflyIII\Generator\Chart\Basic\GeneratorInterface;
use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Controllers\Controller;
use FireflyIII\Models\AccountType; use FireflyIII\Models\AccountType;
use FireflyIII\Models\Category; use FireflyIII\Models\Category;
use FireflyIII\Models\TransactionCurrency;
use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\Category\CategoryRepositoryInterface; use FireflyIII\Repositories\Category\CategoryRepositoryInterface;
use FireflyIII\Repositories\Category\NoCategoryRepositoryInterface; use FireflyIII\Repositories\Category\NoCategoryRepositoryInterface;
use FireflyIII\Repositories\Category\OperationsRepositoryInterface; use FireflyIII\Repositories\Category\OperationsRepositoryInterface;
use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface;
use FireflyIII\Support\CacheProperties; use FireflyIII\Support\CacheProperties;
use FireflyIII\Support\Chart\Category\WholePeriodChartGenerator; use FireflyIII\Support\Chart\Category\WholePeriodChartGenerator;
use FireflyIII\Support\Http\Controllers\AugumentData; 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. * 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 CategoryRepositoryInterface $repository
* @param Category $category * @param Category $category
* *
@@ -82,7 +78,7 @@ class CategoryController extends Controller
$cache->addProperty('chart.category.all'); $cache->addProperty('chart.category.all');
$cache->addProperty($category->id); $cache->addProperty($category->id);
if ($cache->has()) { if ($cache->has()) {
return response()->json($cache->get()); // @codeCoverageIgnore // return response()->json($cache->get()); // @codeCoverageIgnore
} }
$start = $repository->firstUseDate($category) ?? $this->getDate(); $start = $repository->firstUseDate($category) ?? $this->getDate();
$range = app('preferences')->get('viewRange', '1M')->data; $range = app('preferences')->get('viewRange', '1M')->data;
@@ -116,12 +112,10 @@ class CategoryController extends Controller
$cache->addProperty($end); $cache->addProperty($end);
$cache->addProperty('chart.category.frontpage'); $cache->addProperty('chart.category.frontpage');
if ($cache->has()) { if ($cache->has()) {
return response()->json($cache->get()); // @codeCoverageIgnore // return response()->json($cache->get()); // @codeCoverageIgnore
} }
// currency repos: // currency repos:
/** @var CurrencyRepositoryInterface $currencyRepository */
$currencyRepository = app(CurrencyRepositoryInterface::class);
/** @var CategoryRepositoryInterface $repository */ /** @var CategoryRepositoryInterface $repository */
$repository = app(CategoryRepositoryInterface::class); $repository = app(CategoryRepositoryInterface::class);
@@ -134,68 +128,76 @@ class CategoryController extends Controller
/** @var NoCategoryRepositoryInterface $noCatRepository */ /** @var NoCategoryRepositoryInterface $noCatRepository */
$noCatRepository = app(NoCategoryRepositoryInterface::class); $noCatRepository = app(NoCategoryRepositoryInterface::class);
$currencies = [];
$chartData = []; $chartData = [];
$currencies = [];
$tempData = []; $tempData = [];
$categories = $repository->getCategories(); $categories = $repository->getCategories();
$accounts = $accountRepository->getAccountsByType([AccountType::ASSET, AccountType::DEFAULT]); $accounts = $accountRepository->getAccountsByType([AccountType::ASSET, AccountType::DEFAULT]);
/** @var Category $category */ /** @var Category $category */
foreach ($categories as $category) { foreach ($categories as $category) {
$spentArray = $opsRepository->spentInPeriodPerCurrency(new Collection([$category]), $accounts, $start, $end); $collection = new Collection([$category]);
foreach ($spentArray as $categoryId => $spentInfo) { $spent = $opsRepository->sumExpenses($start, $end, $accounts, $collection);
foreach ($spentInfo['spent'] as $currencyId => $row) { //$spentArray = $opsRepository->spentInPeriodPerCurrency(new Collection([$category]), $accounts, $start, $end);
$spent = $row['spent']; foreach ($spent as $currency) {
if (bccomp($spent, '0') === -1) { $currencyId = $currency['currency_id'];
$currencies[$currencyId] = $currencies[$currencyId] ?? $currencyRepository->findNull((int)$currencyId); $currencies[$currencyId] = $currencies[$currencyId] ?? [
$tempData[] = [ 'currency_id' => $currencyId,
'name' => $category->name, 'currency_name' => $currency['currency_name'],
'spent' => bcmul($spent, '-1'), 'currency_symbol' => $currency['currency_symbol'],
'spent_float' => (float)bcmul($spent, '-1'), 'currency_code' => $currency['currency_code'],
'currency_id' => $currencyId, '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: // no category per currency:
$noCategory = $noCatRepository->spentInPeriodPcWoCategory(new Collection, $start, $end); $noCategory = $noCatRepository->sumExpenses($start, $end);
foreach ($noCategory as $currencyId => $spent) {
$currencies[$currencyId] = $currencies[$currencyId] ?? $currencyRepository->findNull($currencyId); 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[] = [ $tempData[] = [
'name' => trans('firefly.no_category'), 'name' => trans('firefly.no_category'),
'spent' => bcmul($spent['spent'], '-1'), 'sum' => $currency['sum'],
'spent_float' => (float)bcmul($spent['spent'], '-1'), 'sum_float' => round($currency['sum'], $currency['currency_decimal_places']),
'currency_id' => $currencyId, 'currency_id' => $currency['currency_id'],
]; ];
} }
// sort temp array by amount. // sort temp array by amount.
$amounts = array_column($tempData, 'spent_float'); $amounts = array_column($tempData, 'sum_float');
array_multisort($amounts, SORT_DESC, $tempData); array_multisort($amounts, SORT_DESC, $tempData);
// loop all found currencies and build the data array for the chart. // loop all found currencies and build the data array for the chart.
/** /** @var array $currency */
* @var int $currencyId foreach ($currencies as $currency) {
* @var TransactionCurrency $currency $dataSet = [
*/ 'label' => sprintf('%s (%s)', (string)trans('firefly.spent'), $currency['currency_name']),
foreach ($currencies as $currencyId => $currency) {
$dataSet = [
'label' => (string)trans('firefly.spent'),
'type' => 'bar', 'type' => 'bar',
'currency_symbol' => $currency->symbol, 'currency_symbol' => $currency['currency_symbol'],
'entries' => $this->expandNames($tempData), 'entries' => $this->expandNames($tempData),
]; ];
$chartData[$currencyId] = $dataSet; $chartData[$currency['currency_id']] = $dataSet;
} }
// loop temp data and place data in correct array: // loop temp data and place data in correct array:
foreach ($tempData as $entry) { foreach ($tempData as $entry) {
$currencyId = $entry['currency_id']; $currencyId = $entry['currency_id'];
$name = $entry['name']; $name = $entry['name'];
$chartData[$currencyId]['entries'][$name] = $entry['spent']; $chartData[$currencyId]['entries'][$name] = bcmul($entry['sum'], '-1');
} }
$data = $this->generator->multiSet($chartData); $data = $this->generator->multiSet($chartData);
$cache->store($data); $cache->store($data);
@@ -206,8 +208,6 @@ class CategoryController extends Controller
/** /**
* Chart report. * Chart report.
* *
* TODO this chart is not multi-currency aware.
*
* @param Category $category * @param Category $category
* @param Collection $accounts * @param Collection $accounts
* @param Carbon $start * @param Carbon $start
@@ -224,44 +224,62 @@ class CategoryController extends Controller
$cache->addProperty($accounts->pluck('id')->toArray()); $cache->addProperty($accounts->pluck('id')->toArray());
$cache->addProperty($category); $cache->addProperty($category);
if ($cache->has()) { if ($cache->has()) {
return response()->json($cache->get());// @codeCoverageIgnore // return response()->json($cache->get());// @codeCoverageIgnore
} }
/** @var OperationsRepositoryInterface $opsRepository */ /** @var OperationsRepositoryInterface $opsRepository */
$opsRepository = app(OperationsRepositoryInterface::class); $opsRepository = app(OperationsRepositoryInterface::class);
$expenses = $opsRepository->periodExpenses(new Collection([$category]), $accounts, $start, $end);
$income = $opsRepository->periodIncome(new Collection([$category]), $accounts, $start, $end); // this gives us all currencies
$periods = app('navigation')->listOfPeriods($start, $end); $collection = new Collection([$category]);
$chartData = [ $expenses = $opsRepository->listExpenses($start, $end, null, $collection);
[ $income = $opsRepository->listIncome($start, $end, null, $collection);
'label' => (string)trans('firefly.spent'), $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' => [], 'entries' => [],
'type' => 'bar', 'type' => 'bar',
'backgroundColor' => 'rgba(219, 68, 55, 0.5)', // red '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' => [], 'entries' => [],
'type' => 'bar', 'type' => 'bar',
'backgroundColor' => 'rgba(0, 141, 76, 0.5)', // green '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]; // loop empty periods:
$spent = $expenses[$category->id]['entries'][$period] ?? '0'; foreach (array_keys($periods) as $period) {
$earned = $income[$category->id]['entries'][$period] ?? '0'; $label = $periods[$period];
$sum = bcadd($spent, $earned); $chartData[$outKey]['entries'][$label] = '0';
$chartData[0]['entries'][$label] = round($spent, 12); $chartData[$inKey]['entries'][$label] = '0';
$chartData[1]['entries'][$label] = round($earned, 12); }
$chartData[2]['entries'][$label] = round($sum, 12); // 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); $data = $this->generator->multiSet($chartData);
@@ -288,7 +306,7 @@ class CategoryController extends Controller
$cache->addProperty('chart.category.period.no-cat'); $cache->addProperty('chart.category.period.no-cat');
$cache->addProperty($accounts->pluck('id')->toArray()); $cache->addProperty($accounts->pluck('id')->toArray());
if ($cache->has()) { if ($cache->has()) {
// return response()->json($cache->get()); // @codeCoverageIgnore return response()->json($cache->get()); // @codeCoverageIgnore
} }
/** @var NoCategoryRepositoryInterface $noCatRepository */ /** @var NoCategoryRepositoryInterface $noCatRepository */
@@ -339,118 +357,13 @@ class CategoryController extends Controller
$inSet = $income[$currencyId] ?? ['transaction_journals' => []]; $inSet = $income[$currencyId] ?? ['transaction_journals' => []];
foreach ($inSet['transaction_journals'] as $journal) { 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]); $chartData[$inKey]['entries'][$date] = bcadd($journal['amount'], $chartData[$inKey]['entries'][$date]);
} }
} }
$data = $this->generator->multiSet($chartData); $data = $this->generator->multiSet($chartData);
$cache->store($data); $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 '<pre>';
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); return response()->json($data);
} }

View File

@@ -69,24 +69,68 @@ class CategoryController extends Controller
/** @var NoCategoryRepositoryInterface $noCatRepos */ /** @var NoCategoryRepositoryInterface $noCatRepos */
$noCatRepos = app(NoCategoryRepositoryInterface::class); $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) // 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. // 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(); $start->startOfYear();
} }
if ('Y-m' === $range) { if ('Y-m' === $format) {
$start->startOfMonth(); $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 { try {
$result = view('reports.partials.category-period', compact('report', 'periods'))->render(); $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('category-period-income-report');
$cache->addProperty($accounts->pluck('id')->toArray()); $cache->addProperty($accounts->pluck('id')->toArray());
if ($cache->has()) { if ($cache->has()) {
return $cache->get(); // @codeCoverageIgnore // return $cache->get(); // @codeCoverageIgnore
} }
/** @var CategoryRepositoryInterface $repository */
$repository = app(CategoryRepositoryInterface::class);
/** @var OperationsRepositoryInterface $opsRepository */ /** @var OperationsRepositoryInterface $opsRepository */
$opsRepository = app(OperationsRepositoryInterface::class); $opsRepository = app(OperationsRepositoryInterface::class);
/** @var NoCategoryRepositoryInterface $noCatRepository */ /** @var NoCategoryRepositoryInterface $noCatRepos */
$noCatRepository = app(NoCategoryRepositoryInterface::class); $noCatRepos = app(NoCategoryRepositoryInterface::class);
$categories = $repository->getCategories();
$data = $opsRepository->periodIncome($categories, $accounts, $start, $end);
$data[0] = $noCatRepository->periodIncomeNoCategory($accounts, $start, $end);
$report = $this->filterPeriodReport($data);
// depending on the carbon format (a reliable way to determine the general date difference) // 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. // 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(); $start->startOfYear();
} }
if ('Y-m' === $range) { if ('Y-m' === $format) {
$start->startOfMonth(); $start->startOfMonth();
} }
$periods = app('navigation')->listOfPeriods($start, $end); $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 { try {
$result = view('reports.partials.category-period', compact('report', 'periods'))->render(); $result = view('reports.partials.category-period', compact('report', 'periods'))->render();
// @codeCoverageIgnoreStart // @codeCoverageIgnoreStart
@@ -157,6 +245,7 @@ class CategoryController extends Controller
$result = sprintf('An error prevented Firefly III from rendering: %s. Apologies.', $e->getMessage()); $result = sprintf('An error prevented Firefly III from rendering: %s. Apologies.', $e->getMessage());
} }
// @codeCoverageIgnoreEnd // @codeCoverageIgnoreEnd
$cache->store($result); $cache->store($result);
return $result; return $result;
@@ -182,7 +271,7 @@ class CategoryController extends Controller
$cache->addProperty('category-report'); $cache->addProperty('category-report');
$cache->addProperty($accounts->pluck('id')->toArray()); $cache->addProperty($accounts->pluck('id')->toArray());
if ($cache->has()) { if ($cache->has()) {
return $cache->get(); // @codeCoverageIgnore // return $cache->get(); // @codeCoverageIgnore
} }
/** @var CategoryRepositoryInterface $repository */ /** @var CategoryRepositoryInterface $repository */
@@ -191,60 +280,120 @@ class CategoryController extends Controller
/** @var OperationsRepositoryInterface $opsRepository */ /** @var OperationsRepositoryInterface $opsRepository */
$opsRepository = app(OperationsRepositoryInterface::class); $opsRepository = app(OperationsRepositoryInterface::class);
$categories = $repository->getCategories(); /** @var NoCategoryRepositoryInterface $noCatRepository */
$report = [ $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' => [], 'categories' => [],
'sums' => [], '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 = []; foreach ([$earnedWithout, $spentWithout] as $data) {
/** foreach ($data as $currencyId => $currencyRow) {
* @var string $categoryId $report['sums'][$currencyId] = $report['sums'][$currencyId] ?? [
* @var array $row 'spent' => '0',
*/ 'earned' => '0',
foreach ($report['categories'] as $categoryId => $row) { 'sum' => '0',
$sum[$categoryId] = (float)$row['spent']; 'currency_id' => $currencyRow['currency_id'],
} 'currency_symbol' => $currencyRow['currency_symbol'],
array_multisort($sum, SORT_ASC, $report['categories']); '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: // sum of spent:
foreach ($report['categories'] as $entry) { $report['sums'][$currencyId]['spent'] = -1 === bccomp($journal['amount'], '0') ? bcadd($report['sums'][$currencyId]['spent'], $journal['amount']): $report['sums'][$currencyId]['spent'];
$currencyId = $entry['currency_id']; // sum of earned
$report['sums'][$currencyId] = $report['sums'][$currencyId] ?? [ $report['sums'][$currencyId]['earned'] = 1 === bccomp($journal['amount'], '0') ? bcadd($report['sums'][$currencyId]['earned'], $journal['amount']): $report['sums'][$currencyId]['earned'];
'spent' => '0',
'earned' => '0', // sum of category
'currency_id' => $entry['currency_id'], $report['categories'][$key]['sum'] = bcadd($report['categories'][$key]['sum'], $journal['amount']);
'currency_code' => $entry['currency_code'], // total spent in no category
'currency_symbol' => $entry['currency_symbol'], $report['categories'][$key]['spent'] = -1 === bccomp($journal['amount'], '0') ? bcadd(
'currency_name' => $entry['currency_name'], $report['categories'][$key]['spent'], $journal['amount']
'cyrrency_decimal_places' => $entry['currency_decimal_places'], ) : $report['categories'][$key]['spent'];
]; // total earned in no category
$report['sums'][$currencyId]['spent'] = bcadd($report['sums'][$currencyId]['spent'], $entry['spent']); $report['categories'][$key]['earned'] = 1 === bccomp($journal['amount'], '0') ? bcadd(
$report['sums'][$currencyId]['earned'] = bcadd($report['sums'][$currencyId]['earned'], $entry['earned']); $report['categories'][$key]['earned'], $journal['amount']
) : $report['categories'][$key]['earned'];
}
}
} }
// @codeCoverageIgnoreStart // @codeCoverageIgnoreStart

View File

@@ -30,7 +30,6 @@ use FireflyIII\Models\TransactionType;
use FireflyIII\User; use FireflyIII\User;
use Illuminate\Support\Collection; use Illuminate\Support\Collection;
use Log; use Log;
use Navigation;
/** /**
* *
@@ -141,83 +140,6 @@ class NoCategoryRepository implements NoCategoryRepositoryInterface
return $array; 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 * @param User $user
*/ */
@@ -226,86 +148,6 @@ class NoCategoryRepository implements NoCategoryRepositoryInterface
$this->user = $user; $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. * 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; 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;
}
} }

View File

@@ -35,18 +35,6 @@ use Illuminate\Support\Collection;
*/ */
interface NoCategoryRepositoryInterface 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 * 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 * 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; 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 * 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 * 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; 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;
} }

View File

@@ -26,12 +26,10 @@ namespace FireflyIII\Repositories\Category;
use Carbon\Carbon; use Carbon\Carbon;
use FireflyIII\Helpers\Collector\GroupCollectorInterface; use FireflyIII\Helpers\Collector\GroupCollectorInterface;
use FireflyIII\Models\Category;
use FireflyIII\Models\TransactionType; use FireflyIII\Models\TransactionType;
use FireflyIII\User; use FireflyIII\User;
use Illuminate\Support\Collection; use Illuminate\Support\Collection;
use Log; use Log;
use Navigation;
/** /**
* *
@@ -53,202 +51,135 @@ class OperationsRepository implements OperationsRepositoryInterface
} }
/** /**
* @param Category $category * This method returns a list of all the withdrawal transaction journals (as arrays) set in that period
* @param Collection $accounts * which have the specified category set to them. It's grouped per currency, with as few details in the array
* @param Carbon $start * as possible. Amounts are always negative.
* @param Carbon $end *
* First currency, then categories.
*
* @param Carbon $start
* @param Carbon $end
* @param Collection|null $accounts
* @param Collection|null $categories
* *
* @return array * @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 */ /** @var GroupCollectorInterface $collector */
$collector = app(GroupCollectorInterface::class); $collector = app(GroupCollectorInterface::class);
$collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionType::WITHDRAWAL]);
if (null !== $accounts && $accounts->count() > 0) {
$collector->setUser($this->user);
$collector->setRange($start, $end)->setTypes([TransactionType::DEPOSIT])->setCategory($category);
if ($accounts->count() > 0) {
$collector->setAccounts($accounts); $collector->setAccounts($accounts);
} }
// collect and group results: if (null !== $categories && $categories->count() > 0) {
$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) {
$collector->setCategories($categories); $collector->setCategories($categories);
} }
if (0 === $categories->count()) { if (null === $categories || (null !== $categories && 0 === $categories->count())) {
$collector->setCategories($this->getCategories()); $collector->setCategories($this->getCategories());
} }
if ($accounts->count() > 0) {
$collector->setAccounts($accounts);
}
$journals = $collector->getExtractedJournals(); $journals = $collector->getExtractedJournals();
$return = []; $array = [];
foreach ($journals as $journal) { foreach ($journals as $journal) {
$categoryId = (int)$journal['category_id'];
$currencyId = (int)$journal['currency_id']; $currencyId = (int)$journal['currency_id'];
$name = $journal['category_name']; $categoryId = (int)$journal['category_id'];
// make array for category:
if (!isset($return[$categoryId])) { // info about the currency:
$return[$categoryId] = [ $array[$currencyId] = $array[$currencyId] ?? [
'name' => $name, 'categories' => [],
'earned' => [],
];
}
if (!isset($return[$categoryId]['earned'][$currencyId])) {
$return[$categoryId]['earned'][$currencyId] = [
'earned' => '0',
'currency_id' => $currencyId, 'currency_id' => $currencyId,
'currency_name' => $journal['currency_name'],
'currency_symbol' => $journal['currency_symbol'], 'currency_symbol' => $journal['currency_symbol'],
'currency_code' => $journal['currency_code'], 'currency_code' => $journal['currency_code'],
'currency_decimal_places' => $journal['currency_decimal_places'], 'currency_decimal_places' => $journal['currency_decimal_places'],
]; ];
}
$return[$categoryId]['earned'][$currencyId]['earned'] // info about the categories:
= bcadd($return[$categoryId]['earned'][$currencyId]['earned'], $journal['amount']); $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 * This method returns a list of all the deposit transaction journals (as arrays) set in that period
* @param Collection $accounts * which have the specified category set to them. It's grouped per currency, with as few details in the array
* @param Carbon $start * as possible. Amounts are always positive.
* @param Carbon $end *
* @param Carbon $start
* @param Carbon $end
* @param Collection|null $accounts
* @param Collection|null $categories
* *
* @return array * @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 */ /** @var GroupCollectorInterface $collector */
$collector = app(GroupCollectorInterface::class); $collector = app(GroupCollectorInterface::class);
$collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionType::DEPOSIT]);
$collector->setAccounts($accounts)->setRange($start, $end); if (null !== $accounts && $accounts->count() > 0) {
$collector->setCategories($categories)->setTypes([TransactionType::WITHDRAWAL, TransactionType::TRANSFER]) $collector->setAccounts($accounts);
->withAccountInformation()->withCategoryInformation(); }
if (null !== $categories && $categories->count() > 0) {
$collector->setCategories($categories);
}
if (null === $categories || (null !== $categories && 0 === $categories->count())) {
$collector->setCategories($this->getCategories());
}
$journals = $collector->getExtractedJournals(); $journals = $collector->getExtractedJournals();
$array = [];
// loop transactions:
foreach ($journals as $journal) { foreach ($journals as $journal) {
$categoryId = (int)$journal['category_id']; $currencyId = (int)$journal['currency_id'];
$date = $journal['date']->format($carbonFormat); $categoryId = (int)$journal['category_id'];
$data[$categoryId]['entries'][$date] = bcadd($data[$categoryId]['entries'][$date] ?? '0', $journal['amount']);
}
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'],
];
/** // info about the categories:
* TODO not multi currency aware. $array[$currencyId]['categories'][$categoryId] = $array[$currencyId]['categories'][$categoryId] ?? [
* 'id' => $categoryId,
* @param Collection $categories 'name' => $journal['category_name'],
* @param Collection $accounts 'transaction_journals' => [],
* @param Carbon $start ];
* @param Carbon $end
* // add journal to array:
* @return array // only a subset of the fields.
*/ $journalId = (int)$journal['transaction_journal_id'];
public function periodIncome(Collection $categories, Collection $accounts, Carbon $start, Carbon $end): array
{
$carbonFormat = Navigation::preferredCarbonFormat($start, $end); $array[$currencyId]['categories'][$categoryId]['transaction_journals'][$journalId] = [
$data = []; 'amount' => app('steam')->positive($journal['amount']),
// prep data array: 'date' => $journal['date'],
/** @var Category $category */
foreach ($categories as $category) {
$data[$category->id] = [
'name' => $category->name,
'sum' => '0',
'entries' => [],
]; ];
} }
// get all transactions: return $array;
/** @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;
} }
/** /**
@@ -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 Carbon $start
* @param Collection $accounts * @param Carbon $end
* @param Carbon $start * @param Collection|null $accounts
* @param Carbon $end * @param Collection|null $categories
* *
* @return array * @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 */ /** @var GroupCollectorInterface $collector */
$collector = app(GroupCollectorInterface::class); $collector = app(GroupCollectorInterface::class);
$collector->setUser($this->user); $collector->setUser($this->user)->setRange($start, $end)
$collector->setRange($start, $end)->setTypes([TransactionType::WITHDRAWAL])->setCategory($category); ->setTypes([TransactionType::WITHDRAWAL]);
if ($accounts->count() > 0) { if (null !== $accounts && $accounts->count() > 0) {
$collector->setAccounts($accounts); $collector->setAccounts($accounts);
} }
// collect and group results: if (null === $categories || (null !== $categories && 0 === $categories->count())) {
$array = $collector->getExtractedJournals(); $categories = $this->getCategories();
$return = []; }
$collector->setCategories($categories);
$journals = $collector->getExtractedJournals();
$array = [];
foreach ($array as $journal) { foreach ($journals as $journal) {
$currencyCode = $journal['currency_code']; $currencyId = (int)$journal['currency_id'];
if (!isset($return[$currencyCode])) { $array[$currencyId] = $array[$currencyId] ?? [
$return[$currencyCode] = [ 'sum' => '0',
'currency_id' => $journal['currency_id'], 'currency_id' => $currencyId,
'currency_code' => $journal['currency_code'],
'currency_name' => $journal['currency_name'], 'currency_name' => $journal['currency_name'],
'currency_symbol' => $journal['currency_symbol'], 'currency_symbol' => $journal['currency_symbol'],
'currency_code' => $journal['currency_code'],
'currency_decimal_places' => $journal['currency_decimal_places'], 'currency_decimal_places' => $journal['currency_decimal_places'],
'spent' => '0',
]; ];
} $array[$currencyId]['sum'] = bcadd($array[$currencyId]['sum'], app('steam')->negative($journal['amount']));
// 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']);
} }
return $return; return $array;
} }
/** /**
* @param Collection $categories * Sum of income journals in period for a set of categories, grouped per currency. Amounts are always positive.
* @param Collection $accounts *
* @param Carbon $start * @param Carbon $start
* @param Carbon $end * @param Carbon $end
* @param Collection|null $accounts
* @param Collection|null $categories
* *
* @return array * @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 */ /** @var GroupCollectorInterface $collector */
$collector = app(GroupCollectorInterface::class); $collector = app(GroupCollectorInterface::class);
$collector->setUser($this->user); $collector->setUser($this->user)->setRange($start, $end)
$collector->setRange($start, $end)->setTypes([TransactionType::WITHDRAWAL]); ->setTypes([TransactionType::DEPOSIT]);
if ($categories->count() > 0) { if (null !== $accounts && $accounts->count() > 0) {
$collector->setCategories($categories);
}
if (0 === $categories->count()) {
$collector->setCategories($this->getCategories());
}
if ($accounts->count() > 0) {
$collector->setAccounts($accounts); $collector->setAccounts($accounts);
} }
if (null === $categories || (null !== $categories && 0 === $categories->count())) {
$categories = $this->getCategories();
}
$collector->setCategories($categories);
$journals = $collector->getExtractedJournals();
$array = [];
$set = $collector->getExtractedJournals(); foreach ($journals as $journal) {
$return = []; $currencyId = (int)$journal['currency_id'];
/** @var array $journal */ $array[$currencyId] = $array[$currencyId] ?? [
foreach ($set as $journal) { 'sum' => '0',
$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',
'currency_id' => $currencyId, 'currency_id' => $currencyId,
'currency_name' => $journal['currency_name'],
'currency_symbol' => $journal['currency_symbol'], 'currency_symbol' => $journal['currency_symbol'],
'currency_code' => $journal['currency_code'], 'currency_code' => $journal['currency_code'],
'currency_decimal_places' => $journal['currency_decimal_places'], 'currency_decimal_places' => $journal['currency_decimal_places'],
]; ];
} $array[$currencyId]['sum'] = bcadd($array[$currencyId]['sum'], app('steam')->positive($journal['amount']));
$return[$categoryId]['spent'][$currencyId]['spent']
= bcadd($return[$categoryId]['spent'][$currencyId]['spent'], $journal['amount']);
} }
return $return; return $array;
} }
/** /**

View File

@@ -24,7 +24,6 @@ declare(strict_types=1);
namespace FireflyIII\Repositories\Category; namespace FireflyIII\Repositories\Category;
use Carbon\Carbon; use Carbon\Carbon;
use FireflyIII\Models\Category;
use FireflyIII\User; use FireflyIII\User;
use Illuminate\Support\Collection; use Illuminate\Support\Collection;
@@ -36,51 +35,32 @@ use Illuminate\Support\Collection;
interface OperationsRepositoryInterface 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 Carbon $start
* @param Collection $accounts * @param Carbon $end
* @param Carbon $start * @param Collection|null $accounts
* @param Carbon $end * @param Collection|null $categories
* *
* @return array * @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 * This method returns a list of all the deposit transaction journals (as arrays) set in that period
* @param Collection $accounts * which have the specified category set to them. It's grouped per currency, with as few details in the array
* @param Carbon $start * as possible. Amounts are always positive.
* @param Carbon $end *
* @param Carbon $start
* @param Carbon $end
* @param Collection|null $accounts
* @param Collection|null $categories
* *
* @return array * @return array
* @deprecated
*/ */
public function earnedInPeriodPerCurrency(Collection $categories, Collection $accounts, Carbon $start, Carbon $end): array; public function listIncome(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $categories = null): 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;
/** /**
* @param User $user * @param User $user
@@ -88,27 +68,26 @@ interface OperationsRepositoryInterface
public function setUser(User $user): void; 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 Carbon $start
* @param Collection $accounts * @param Carbon $end
* @param Carbon $start * @param Collection|null $accounts
* @param Carbon $end * @param Collection|null $categories
* *
* @return array * @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 * Sum of income journals in period for a set of categories, grouped per currency. Amounts are always positive.
* @param Collection $accounts *
* @param Carbon $start * @param Carbon $start
* @param Carbon $end * @param Carbon $end
* @param Collection|null $accounts
* @param Collection|null $categories
* *
* @return array * @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;
} }

View File

@@ -28,6 +28,7 @@ use FireflyIII\Models\Category;
use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\Category\CategoryRepositoryInterface; use FireflyIII\Repositories\Category\CategoryRepositoryInterface;
use FireflyIII\Repositories\Category\OperationsRepositoryInterface; use FireflyIII\Repositories\Category\OperationsRepositoryInterface;
use Illuminate\Support\Collection;
/** /**
* Class WholePeriodChartGenerator * Class WholePeriodChartGenerator
@@ -43,6 +44,7 @@ class WholePeriodChartGenerator
*/ */
public function generate(Category $category, Carbon $start, Carbon $end): array public function generate(Category $category, Carbon $start, Carbon $end): array
{ {
$collection = new Collection([$category]);
/** @var CategoryRepositoryInterface $repository */ /** @var CategoryRepositoryInterface $repository */
$repository = app(CategoryRepositoryInterface::class); $repository = app(CategoryRepositoryInterface::class);
@@ -65,10 +67,11 @@ class WholePeriodChartGenerator
while ($current <= $end) { while ($current <= $end) {
$key = $current->format('Y-m-d'); $key = $current->format('Y-m-d');
$currentEnd = app('navigation')->endOfPeriod($current, $step); $currentEnd = app('navigation')->endOfPeriod($current, $step);
$spent[$key] = $opsRepository->spentInPeriod($category, $accounts, $current, $currentEnd); $spent[$key] = $opsRepository->sumExpenses($current, $currentEnd, $accounts, $collection);
$earned[$key] = $opsRepository->earnedInPeriod($category, $accounts, $current, $currentEnd); $earned[$key] = $opsRepository->sumIncome($current, $currentEnd, $accounts, $collection);
$current = app('navigation')->addPeriod($current, $step, 0); $current = app('navigation')->addPeriod($current, $step, 0);
} }
$currencies = $this->extractCurrencies($spent) + $this->extractCurrencies($earned); $currencies = $this->extractCurrencies($spent) + $this->extractCurrencies($earned);
// generate chart data (for each currency) // generate chart data (for each currency)
@@ -95,21 +98,23 @@ class WholePeriodChartGenerator
$current = clone $start; $current = clone $start;
while ($current <= $end) { while ($current <= $end) {
$key = $current->format('Y-m-d'); $key = $current->format('Y-m-d');
$label = app('navigation')->periodShow($current, $step); $label = app('navigation')->periodShow($current, $step);
/** @var array $currency */ /** @var array $currency */
foreach ($currencies as $currency) { foreach ($currencies as $currency) {
$code = $currency['currency_code']; $code = $currency['currency_code'];
$currencyId = $currency['currency_id'];
$spentInfoKey = sprintf('spent-in-%s', $code); $spentInfoKey = sprintf('spent-in-%s', $code);
$earnedInfoKey = sprintf('earned-in-%s', $code); $earnedInfoKey = sprintf('earned-in-%s', $code);
$spentAmount = $spent[$key][$code]['spent'] ?? '0'; $spentAmount = $spent[$key][$currencyId]['sum'] ?? '0';
$earnedAmount = $earned[$key][$code]['earned'] ?? '0'; $earnedAmount = $earned[$key][$currencyId]['sum'] ?? '0';
$chartData[$spentInfoKey]['entries'][$label] = round($spentAmount, $currency['currency_decimal_places']); $chartData[$spentInfoKey]['entries'][$label] = round($spentAmount, $currency['currency_decimal_places']);
$chartData[$earnedInfoKey]['entries'][$label] = round($earnedAmount, $currency['currency_decimal_places']); $chartData[$earnedInfoKey]['entries'][$label] = round($earnedAmount, $currency['currency_decimal_places']);
} }
$current = app('navigation')->addPeriod($current, $step, 0); $current = app('navigation')->addPeriod($current, $step, 0);
} }
return $chartData; return $chartData;
} }
@@ -150,18 +155,15 @@ class WholePeriodChartGenerator
private function extractCurrencies(array $array): array private function extractCurrencies(array $array): array
{ {
$return = []; $return = [];
foreach ($array as $info) { foreach ($array as $block) {
foreach ($info as $block) { foreach ($block as $currencyId => $currencyRow) {
$currencyId = $block['currency_id']; $return[$currencyId] = $return[$currencyId] ?? [
if (!isset($return[$currencyId])) { 'currency_id' => $currencyId,
$return[$currencyId] = [ 'currency_name' => $currencyRow['currency_name'],
'currency_id' => $block['currency_id'], 'currency_symbol' => $currencyRow['currency_symbol'],
'currency_code' => $block['currency_code'], 'currency_code' => $currencyRow['currency_code'],
'currency_name' => $block['currency_name'], 'currency_decimal_places' => $currencyRow['currency_decimal_places'],
'currency_symbol' => $block['currency_symbol'],
'currency_decimal_places' => $block['currency_decimal_places'],
]; ];
}
} }
} }

View File

@@ -71,8 +71,8 @@ class CategoryTransformer extends AbstractTransformer
$start = $this->parameters->get('start'); $start = $this->parameters->get('start');
$end = $this->parameters->get('end'); $end = $this->parameters->get('end');
if (null !== $start && null !== $end) { if (null !== $start && null !== $end) {
$earned = array_values($this->opsRepository->earnedInPeriod($category, new Collection, $start, $end)); $earned = $this->beautify($this->opsRepository->sumIncome($start, $end, null, new Collection([$category])));
$spent = array_values($this->opsRepository->spentInPeriod($category, new Collection, $start, $end)); $spent = $this->beautify($this->opsRepository->sumExpenses($start, $end, null, new Collection([$category])));
} }
$data = [ $data = [
'id' => (int)$category->id, 'id' => (int)$category->id,
@@ -91,4 +91,20 @@ class CategoryTransformer extends AbstractTransformer
return $data; 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;
}
} }

View File

@@ -4,28 +4,29 @@
<th>{{ 'category'|_ }}</th> <th>{{ 'category'|_ }}</th>
<th style="text-align: right;">{{ 'spent'|_ }}</th> <th style="text-align: right;">{{ 'spent'|_ }}</th>
<th style="text-align: right;">{{ 'earned'|_ }}</th> <th style="text-align: right;">{{ 'earned'|_ }}</th>
<th style="text-align: right;">{{ 'sum'|_ }}</th>
<th>&nbsp;</th> <th>&nbsp;</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
{% for category in report.categories %}
{% for index, category in report.categories %}
{% if loop.index > listLength %} {% if loop.index > listLength %}
<tr class="overListLength"> <tr class="overListLength">
{% else %} {% else %}
<tr> <tr>
{% endif %} {% endif %}
<td> <td>
<a href="{{ route('categories.show', category.id) }}">{{ category.name }}</a> <a href="{{ route('categories.show', category.id) }}">{{ category.title }}</a>
</td> </td>
<td style="text-align: right;">{{ formatAmountBySymbol(category.spent, category.currency_symbol, category.currency_decimal_places, true) }}</td> <td style="text-align: right;">{{ formatAmountBySymbol(category.spent, category.currency_symbol, category.currency_decimal_places, true) }}</td>
<td style="text-align: right;">{{ formatAmountBySymbol(category.earned, category.currency_symbol, category.currency_decimal_places, true) }}</td> <td style="text-align: right;">{{ formatAmountBySymbol(category.earned, category.currency_symbol, category.currency_decimal_places, true) }}</td>
<td style="text-align: right;">{{ formatAmountBySymbol(category.sum, category.currency_symbol, category.currency_decimal_places, true) }}</td>
<td style="width:20px;"> <td style="width:20px;">
<i class="fa fa-fw fa-info-circle text-muted firefly-info-button" <i class="fa fa-fw fa-info-circle text-muted firefly-info-button"
data-location="category-entry" data-category-id="{{ category.id }}" data-currency-id="{{ category.currency_id }}" data-location="category-entry" data-category-id="{{ category.id }}" data-currency-id="{{ category.currency_id }}"
></i> ></i>
</td> </td>
</tr> </tr>
{% endfor %} {% endfor %}
</tbody> </tbody>
<tfoot> <tfoot>
@@ -45,17 +46,10 @@
<td style="text-align: right;"> <td style="text-align: right;">
{{ formatAmountBySymbol(sum.earned, sum.currency_symbol, sum.currency_decimal_places) }} {{ formatAmountBySymbol(sum.earned, sum.currency_symbol, sum.currency_decimal_places) }}
</td> </td>
<td></td> <td style="text-align: right;">
{{ formatAmountBySymbol(sum.sum, sum.currency_symbol, sum.currency_decimal_places) }}
</td>
</tr> </tr>
{% endfor %} {% endfor %}
{#
<tr>
<td><em>{{ 'sum'|_ }}</em></td>
<td style="text-align: right;">{{ sumEarned|formatAmount }}</td>
<td style="text-align: right;">{{ sumSpent|formatAmount }}</td>
<td>&nbsp;</td>
</tr>
TODO fix the sum here.
#}
</tfoot> </tfoot>
</table> </table>

View File

@@ -9,27 +9,27 @@
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
{% for id, info in report %} {% for info in report %}
<tr> <tr>
<td> <td>
{% if id != 0 %} {% if info.id != 0 %}
<a class="btn btn-default btn-xs" href="{{ route('categories.show', [id]) }}"><i class="fa fa-external-link"></i></a> <a class="btn btn-default btn-xs" href="{{ route('categories.show', [info.id]) }}"><i class="fa fa-external-link"></i></a>
{% else %} {% else %}
<a class="btn btn-default btn-xs" href="{{ route('categories.no-category') }}"><i class="fa fa-external-link"></i></a> <a class="btn btn-default btn-xs" href="{{ route('categories.no-category') }}"><i class="fa fa-external-link"></i></a>
{% endif %} {% endif %}
</td> </td>
<td data-value="{{ info.name }}"> <td data-value="{{ info.title }}">
<a title="{{ info.name }}" href="#" data-category="{{ id }}" class="category-chart-activate">{{ info.name }}</a> <a title="{{ info.title }}" href="#" data-currency="{{ info.currency_id }}" data-category="{{ info.id }}" class="category-chart-activate">{{ info.title }}</a>
</td> </td>
{% for key, period in periods %} {% for key, period in periods %}
{# income first #} {# income first #}
{% if(info.entries[key]) %} {% if(info.entries[key]) %}
<td data-value="{{ info.entries[key] }}" style="text-align: right;"> <td data-value="{{ info.entries[key] }}" style="text-align: right;">
{{ info.entries[key]|formatAmount }} {{ formatAmountBySymbol(info.entries[key], info.currency_symbol, info.currency_decimal_places) }}
</td> </td>
{% else %} {% else %}
<td data-value="0" style="text-align: right;"> <td data-value="0" style="text-align: right;">
{{ 0|formatAmount }} {{ formatAmountBySymbol(0, info.currency_symbol, info.currency_decimal_places) }}
</td> </td>
{% endif %} {% endif %}
{% endfor %} {% endfor %}
@@ -37,11 +37,11 @@
{# if sum of income, display: #} {# if sum of income, display: #}
{% if info.sum %} {% if info.sum %}
<td data-value="{{ info.sum }}" style="text-align: right;"> <td data-value="{{ info.sum }}" style="text-align: right;">
{{ info.sum|formatAmount }} {{ formatAmountBySymbol(info.sum, info.currency_symbol, info.currency_decimal_places) }}
</td> </td>
{% else %} {% else %}
<td data-value="0" style="text-align: right;"> <td data-value="0" style="text-align: right;">
{{ 0|formatAmount }} {{ formatAmountBySymbol(0, info.currency_symbol, info.currency_decimal_places) }}
</td> </td>
{% endif %} {% endif %}
</tr> </tr>