Skip to content

Firefly III: a personal finances manager

New stuff for categories and transactions.

James Cole98e683329e49
diff --git a/app/Helpers/Csv/Converter/CategoryId.php b/app/Helpers/Csv/Converter/CategoryId.php
index b28b62a224..0e9266f047 100644
--- a/app/Helpers/Csv/Converter/CategoryId.php
+++ b/app/Helpers/Csv/Converter/CategoryId.php
@@ -3,7 +3,7 @@ declare(strict_types = 1);
namespace FireflyIII\Helpers\Csv\Converter;
use FireflyIII\Models\Category;
-use FireflyIII\Repositories\Category\SingleCategoryRepositoryInterface;
+use FireflyIII\Repositories\Category\CategoryRepositoryInterface;
/**
* Class CategoryId
@@ -18,8 +18,8 @@ class CategoryId extends BasicConverter implements ConverterInterface
*/
public function convert(): Category
{
- /** @var SingleCategoryRepositoryInterface $repository */
- $repository = app(SingleCategoryRepositoryInterface::class);
+ /** @var CategoryRepositoryInterface $repository */
+ $repository = app(CategoryRepositoryInterface::class);
$value = isset($this->mapped[$this->index][$this->value]) ? $this->mapped[$this->index][$this->value] : $this->value;
$category = $repository->find($value);
diff --git a/app/Helpers/Csv/Converter/CategoryName.php b/app/Helpers/Csv/Converter/CategoryName.php
index c987bc3192..971cc745c1 100644
--- a/app/Helpers/Csv/Converter/CategoryName.php
+++ b/app/Helpers/Csv/Converter/CategoryName.php
@@ -4,7 +4,7 @@ namespace FireflyIII\Helpers\Csv\Converter;
use Auth;
use FireflyIII\Models\Category;
-use FireflyIII\Repositories\Category\SingleCategoryRepositoryInterface;
+use FireflyIII\Repositories\Category\CategoryRepositoryInterface;
/**
* Class CategoryName
@@ -19,8 +19,8 @@ class CategoryName extends BasicConverter implements ConverterInterface
*/
public function convert(): Category
{
- /** @var SingleCategoryRepositoryInterface $repository */
- $repository = app(SingleCategoryRepositoryInterface::class);
+ /** @var CategoryRepositoryInterface $repository */
+ $repository = app(CategoryRepositoryInterface::class);
// is mapped? Then it's easy!
if (isset($this->mapped[$this->index][$this->value])) {
diff --git a/app/Helpers/Report/BudgetReportHelper.php b/app/Helpers/Report/BudgetReportHelper.php
index ae5e9b459d..68449f2b39 100644
--- a/app/Helpers/Report/BudgetReportHelper.php
+++ b/app/Helpers/Report/BudgetReportHelper.php
@@ -141,7 +141,7 @@ class BudgetReportHelper implements BudgetReportHelperInterface
}
/**
- * Take the array as returned by SingleCategoryRepositoryInterface::spentPerDay and SingleCategoryRepositoryInterface::earnedByDay
+ * Take the array as returned by CategoryRepositoryInterface::spentPerDay and CategoryRepositoryInterface::earnedByDay
* and sum up everything in the array in the given range.
*
* @param Carbon $start
diff --git a/app/Helpers/Report/BudgetReportHelperInterface.php b/app/Helpers/Report/BudgetReportHelperInterface.php
index 6bc376f2e4..9858655153 100644
--- a/app/Helpers/Report/BudgetReportHelperInterface.php
+++ b/app/Helpers/Report/BudgetReportHelperInterface.php
@@ -39,4 +39,13 @@ interface BudgetReportHelperInterface
* @return Collection
*/
public function getBudgetsWithExpenses(Carbon $start, Carbon $end, Collection $accounts): Collection;
+
+ /**
+ * @param $start
+ * @param $end
+ * @param $accounts
+ *
+ * @return Collection
+ */
+ public function getCategoriesWithTransactions($start, $end, $accounts): Collection;
}
diff --git a/app/Helpers/Report/ReportHelper.php b/app/Helpers/Report/ReportHelper.php
index f3d942c580..ec79046336 100644
--- a/app/Helpers/Report/ReportHelper.php
+++ b/app/Helpers/Report/ReportHelper.php
@@ -103,35 +103,35 @@ class ReportHelper implements ReportHelperInterface
}
/**
+ * Find all transactions and IF we have spent money in them
+ * with either transactions or journals.
+ *
* @param Carbon $start
* @param Carbon $end
* @param Collection $accounts
*
* @return Collection
*/
- public function getCategoriesWithExpenses(Carbon $start, Carbon $end, Collection $accounts): Collection
+ public function getCategoriesWithTransactions(Carbon $start, Carbon $end, Collection $accounts): Collection
{
/** @var CategoryRepositoryInterface $repository */
$repository = app(CategoryRepositoryInterface::class);
- $collection = $repository->earnedForAccountsPerMonth($accounts, $start, $end);
- $second = $repository->spentForAccountsPerMonth($accounts, $start, $end);
- $collection = $collection->merge($second);
- $array = [];
- /** @var Category $category */
- foreach ($collection as $category) {
- $id = $category->id;
- $array[$id] = $category;
-
+ $categories = $repository->getCategories();
+ $return = new Collection;
+ foreach ($categories as $category) {
+ $lastUseDate = $repository->lastUseDate($category, $accounts);
+ if ($lastUseDate >= $start && $lastUseDate <= $end) {
+ $return->push($category);
+ }
}
- $set = new Collection($array);
- $set = $set->sortBy(
+ $return = $return->sortBy(
function (Category $category) {
return $category->name;
}
);
- return $set;
+ return $return;
}
/**
@@ -144,15 +144,15 @@ class ReportHelper implements ReportHelperInterface
public function getCategoryReport(Carbon $start, Carbon $end, Collection $accounts): CategoryCollection
{
$object = new CategoryCollection;
-
- /**
- * GET CATEGORIES:
- */
- /** @var \FireflyIII\Repositories\Category\CategoryRepositoryInterface $repository */
+ /** @var CategoryRepositoryInterface $repository */
$repository = app(CategoryRepositoryInterface::class);
+ $categories = $repository->getCategories();
- $set = $repository->spentForAccountsPerMonth($accounts, $start, $end);
- foreach ($set as $category) {
+ /** @var Category $category */
+ foreach ($categories as $category) {
+ $spent = $repository->spentInPeriod(new Collection([$category]), $accounts, $start, $end);
+ // CategoryCollection expects the amount in $spent:
+ $category->spent = $spent;
$object->addCategory($category);
}
@@ -312,7 +312,7 @@ class ReportHelper implements ReportHelperInterface
}
/**
- * Take the array as returned by SingleCategoryRepositoryInterface::spentPerDay and SingleCategoryRepositoryInterface::earnedByDay
+ * Take the array as returned by CategoryRepositoryInterface::spentPerDay and CategoryRepositoryInterface::earnedByDay
* and sum up everything in the array in the given range.
*
* @param Carbon $start
diff --git a/app/Http/Controllers/CategoryController.php b/app/Http/Controllers/CategoryController.php
index 896451a850..dc23f9614d 100644
--- a/app/Http/Controllers/CategoryController.php
+++ b/app/Http/Controllers/CategoryController.php
@@ -3,9 +3,9 @@
use Auth;
use Carbon\Carbon;
use FireflyIII\Http\Requests\CategoryFormRequest;
+use FireflyIII\Models\Account;
use FireflyIII\Models\Category;
use FireflyIII\Repositories\Category\CategoryRepositoryInterface as CRI;
-use FireflyIII\Repositories\Category\SingleCategoryRepositoryInterface as SCRI;
use FireflyIII\Support\CacheProperties;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
@@ -69,12 +69,12 @@ class CategoryController extends Controller
}
/**
- * @param SCRI $repository
+ * @param CRI $repository
* @param Category $category
*
* @return \Illuminate\Http\RedirectResponse
*/
- public function destroy(SCRI $repository, Category $category)
+ public function destroy(CRI $repository, Category $category)
{
$name = $category->name;
@@ -108,18 +108,17 @@ class CategoryController extends Controller
}
/**
- * @param CRI $repository
- * @param SCRI $singleRepository
+ * @param CRI $repository
*
* @return \Illuminate\View\View
*/
- public function index(CRI $repository, SCRI $singleRepository)
+ public function index(CRI $repository)
{
$categories = $repository->getCategories();
$categories->each(
- function (Category $category) use ($singleRepository) {
- $category->lastActivity = $singleRepository->getLatestActivity($category);
+ function (Category $category) use ($repository) {
+ $category->lastActivity = $repository->lastUseDate($category, new Collection);
}
);
@@ -137,7 +136,7 @@ class CategoryController extends Controller
$start = session('start', Carbon::now()->startOfMonth());
/** @var Carbon $end */
$end = session('end', Carbon::now()->startOfMonth());
- $list = $repository->listNoCategory($start, $end);
+ $list = $repository->journalsInPeriodWithoutCategory(new Collection(), $start, $end);
$subTitle = trans(
'firefly.without_category_between',
['start' => $start->formatLocalized($this->monthAndDayFormat), 'end' => $end->formatLocalized($this->monthAndDayFormat)]
@@ -147,26 +146,24 @@ class CategoryController extends Controller
}
/**
- * @param SCRI $repository
+ * @param CRI $repository
* @param Category $category
*
* @return \Illuminate\View\View
*/
- public function show(SCRI $repository, Category $category)
+ public function show(CRI $repository, Category $category)
{
$hideCategory = true; // used in list.
$pageSize = Preferences::get('transactionPageSize', 50)->data;
$page = intval(Input::get('page'));
- $set = $repository->getJournals($category, $page, $pageSize);
- $count = $repository->countJournals($category);
- $subTitle = $category->name;
- $journals = new LengthAwarePaginator($set, $count, $pageSize, $page);
+ $journals = $repository->getJournals($category, $page, $pageSize);
$journals->setPath('categories/show/' . $category->id);
// list of ranges for list of periods:
// oldest transaction in category:
- $start = $repository->getFirstActivityDate($category);
+ //$start = $repository->getFirstActivityDate($category);
+ $start = $repository->firstUseDate($category, new Account);
$range = Preferences::get('viewRange', '1M')->data;
$start = Navigation::startOfPeriod($start, $range);
$end = Navigation::endOfX(new Carbon, $range);
@@ -179,26 +176,22 @@ class CategoryController extends Controller
$cache->addProperty('category-show');
$cache->addProperty($category->id);
- // get all spent and earned data:
- // get amount earned in period, grouped by day.
- $spentArray = $repository->spentPerDay($category, $start, $end, new Collection);
- $earnedArray = $repository->earnedPerDay($category, $start, $end, new Collection);
if ($cache->has()) {
- $entries = $cache->get();
-
- return view('categories.show', compact('category', 'journals', 'entries', 'hideCategory', 'subTitle'));
+ //$entries = $cache->get();
+ //return view('categories.show', compact('category', 'journals', 'entries', 'hideCategory', 'subTitle'));
}
+
+ $categoryCollection = new Collection([$category]);
+ $empty = new Collection;
while ($end >= $start) {
$end = Navigation::startOfPeriod($end, $range);
$currentEnd = Navigation::endOfPeriod($end, $range);
-
- // get data from spentArray:
- $spent = $this->getSumOfRange($end, $currentEnd, $spentArray);
- $earned = $this->getSumOfRange($end, $currentEnd, $earnedArray);
- $dateStr = $end->format('Y-m-d');
- $dateName = Navigation::periodShow($end, $range);
+ $spent = $repository->spentInPeriod($categoryCollection, $empty, $end, $currentEnd);
+ $earned = $repository->earnedInPeriod($categoryCollection, $empty, $end, $currentEnd);
+ $dateStr = $end->format('Y-m-d');
+ $dateName = Navigation::periodShow($end, $range);
$entries->push([$dateStr, $dateName, $spent, $earned]);
$end = Navigation::subtractPeriod($end, $range, 1);
@@ -210,28 +203,28 @@ class CategoryController extends Controller
}
/**
- * @param SCRI $repository
+ * @param CRI $repository
* @param Category $category
*
* @param $date
*
* @return \Illuminate\View\View
*/
- public function showWithDate(SCRI $repository, Category $category, string $date)
+ public function showWithDate(CRI $repository, Category $category, string $date)
{
- $carbon = new Carbon($date);
- $range = Preferences::get('viewRange', '1M')->data;
- $start = Navigation::startOfPeriod($carbon, $range);
- $end = Navigation::endOfPeriod($carbon, $range);
- $subTitle = $category->name;
-
+ $carbon = new Carbon($date);
+ $range = Preferences::get('viewRange', '1M')->data;
+ $start = Navigation::startOfPeriod($carbon, $range);
+ $end = Navigation::endOfPeriod($carbon, $range);
+ $subTitle = $category->name;
$hideCategory = true; // used in list.
$page = intval(Input::get('page'));
$pageSize = Preferences::get('transactionPageSize', 50)->data;
-
- $set = $repository->getJournalsInRange($category, $start, $end, $page, $pageSize);
- $count = $repository->countJournals($category, $start, $end);
- $journals = new LengthAwarePaginator($set, $count, $pageSize, $page);
+ $offset = ($page - 1) * $pageSize;
+ $set = $repository->journalsInPeriod(new Collection([$category]), new Collection, [], $start, $end);
+ $count = $set->count();
+ $subSet = $set->splice($offset, $pageSize);
+ $journals = new LengthAwarePaginator($subSet, $count, $pageSize, $page);
$journals->setPath('categories/show/' . $category->id . '/' . $date);
return view('categories.show_with_date', compact('category', 'journals', 'hideCategory', 'subTitle', 'carbon'));
@@ -239,11 +232,11 @@ class CategoryController extends Controller
/**
* @param CategoryFormRequest $request
- * @param SCRI $repository
+ * @param CRI $repository
*
* @return \Illuminate\Http\RedirectResponse
*/
- public function store(CategoryFormRequest $request, SCRI $repository)
+ public function store(CategoryFormRequest $request, CRI $repository)
{
$categoryData = [
'name' => $request->input('name'),
@@ -266,12 +259,12 @@ class CategoryController extends Controller
/**
* @param CategoryFormRequest $request
- * @param SCRI $repository
+ * @param CRI $repository
* @param Category $category
*
* @return \Illuminate\Http\RedirectResponse
*/
- public function update(CategoryFormRequest $request, SCRI $repository, Category $category)
+ public function update(CategoryFormRequest $request, CRI $repository, Category $category)
{
$categoryData = [
'name' => $request->input('name'),
diff --git a/app/Http/Controllers/Chart/CategoryController.php b/app/Http/Controllers/Chart/CategoryController.php
index a84fccd578..b7c974efab 100644
--- a/app/Http/Controllers/Chart/CategoryController.php
+++ b/app/Http/Controllers/Chart/CategoryController.php
@@ -10,8 +10,6 @@ use FireflyIII\Http\Controllers\Controller;
use FireflyIII\Models\Category;
use FireflyIII\Repositories\Account\AccountRepositoryInterface as ARI;
use FireflyIII\Repositories\Category\CategoryRepositoryInterface as CRI;
-use FireflyIII\Repositories\Category\SingleCategoryRepositoryInterface;
-use FireflyIII\Repositories\Category\SingleCategoryRepositoryInterface as SCRI;
use FireflyIII\Support\CacheProperties;
use Illuminate\Support\Collection;
use Navigation;
@@ -47,13 +45,14 @@ class CategoryController extends Controller
/**
* Show an overview for a category for all time, per month/week/year.
*
- * @param SCRI $repository
+ * @param CRI $repository
* @param Category $category
*
* @return \Symfony\Component\HttpFoundation\Response
*/
- public function all(SCRI $repository, Category $category)
+ public function all(CRI $repository, Category $category)
{
+ /**
// oldest transaction in category:
$start = $repository->getFirstActivityDate($category);
$range = Preferences::get('viewRange', '1M')->data;
@@ -87,21 +86,24 @@ class CategoryController extends Controller
$cache->store($data);
return Response::json($data);
+ * **/
}
/**
- * @param SCRI $repository
+ * @param CRI $repository
* @param Category $category
*
* @return \Symfony\Component\HttpFoundation\Response
*/
- public function currentPeriod(SCRI $repository, Category $category)
+ public function currentPeriod(CRI $repository, Category $category)
{
+ /**
$start = clone session('start', Carbon::now()->startOfMonth());
$end = session('end', Carbon::now()->endOfMonth());
$data = $this->makePeriodChart($repository, $category, $start, $end);
return Response::json($data);
+ * **/
}
/**
@@ -118,6 +120,7 @@ class CategoryController extends Controller
*/
public function earnedInPeriod(CRI $repository, string $reportType, Carbon $start, Carbon $end, Collection $accounts)
{
+ /**
$cache = new CacheProperties; // chart properties for cache:
$cache->addProperty($start);
$cache->addProperty($end);
@@ -140,7 +143,7 @@ class CategoryController extends Controller
$cache->store($data);
return $data;
-
+ **/
}
/**
@@ -154,7 +157,7 @@ class CategoryController extends Controller
*/
public function frontpage(CRI $repository, ARI $accountRepository)
{
-
+ /**
$start = session('start', Carbon::now()->startOfMonth());
$end = session('end', Carbon::now()->endOfMonth());
@@ -184,7 +187,7 @@ class CategoryController extends Controller
$cache->store($data);
return Response::json($data);
-
+ **/
}
/**
@@ -198,8 +201,9 @@ class CategoryController extends Controller
*/
public function multiYear(string $reportType, Carbon $start, Carbon $end, Collection $accounts, Collection $categories)
{
- /** @var CRI $repository */
- $repository = app(CRI::class);
+ /**
+ // /** @var CRI $repository
+ // $repository = app(CRI::class);
// chart properties for cache:
$cache = new CacheProperties();
@@ -217,7 +221,7 @@ class CategoryController extends Controller
$entries = new Collection;
$set = $repository->listMultiYear($categories, $accounts, $start, $end);
- /** @var Category $category */
+ /** @var Category $category
foreach ($categories as $category) {
$entry = ['name' => '', 'spent' => [], 'earned' => []];
@@ -268,6 +272,8 @@ class CategoryController extends Controller
$cache->store($data);
return Response::json($data);
+ *
+ */
}
@@ -282,6 +288,7 @@ class CategoryController extends Controller
*/
public function period(Category $category, string $reportType, Carbon $start, Carbon $end, Collection $accounts)
{
+ /**
// chart properties for cache:
$cache = new CacheProperties();
$cache->addProperty($start);
@@ -295,8 +302,8 @@ class CategoryController extends Controller
return Response::json($cache->get());
}
- /** @var SingleCategoryRepositoryInterface $repository */
- $repository = app(SingleCategoryRepositoryInterface::class);
+ /** @var CategoryRepositoryInterface $repository
+ $repository = app(CategoryRepositoryInterface::class);
// loop over period, add by users range:
$current = clone $start;
$viewRange = Preferences::get('viewRange', '1M')->data;
@@ -324,19 +331,21 @@ class CategoryController extends Controller
$cache->store($data);
return Response::json($data);
+ * **/
}
/**
- * @param SCRI $repository
+ * @param CRI $repository
* @param Category $category
*
* @param $date
*
* @return \Symfony\Component\HttpFoundation\Response
*/
- public function specificPeriod(SCRI $repository, Category $category, $date)
+ public function specificPeriod(CRI $repository, Category $category, $date)
{
+ /**
$carbon = new Carbon($date);
$range = Preferences::get('viewRange', '1M')->data;
$start = Navigation::startOfPeriod($carbon, $range);
@@ -345,7 +354,7 @@ class CategoryController extends Controller
return Response::json($data);
-
+ **/
}
/**
@@ -363,6 +372,7 @@ class CategoryController extends Controller
*/
public function spentInPeriod(CRI $repository, $reportType, Carbon $start, Carbon $end, Collection $accounts)
{
+ /**
$cache = new CacheProperties; // chart properties for cache:
$cache->addProperty($start);
$cache->addProperty($end);
@@ -387,6 +397,7 @@ class CategoryController extends Controller
$cache->store($data);
return $data;
+ * */
}
/**
@@ -399,6 +410,7 @@ class CategoryController extends Controller
*/
private function filterCollection(Carbon $start, Carbon $end, Collection $set, Collection $categories): Collection
{
+ /**
$entries = new Collection;
while ($start < $end) { // filter the set:
@@ -408,7 +420,7 @@ class CategoryController extends Controller
return $category->dateFormatted == $start->format('Y-m');
}
);
- /** @var Category $category */
+ /** @var Category $category
foreach ($categories as $category) { // check for each category if its in the current set.
$entry = $currentSet->filter( // if its in there, use the value.
function (Category $cat) use ($category) {
@@ -426,6 +438,7 @@ class CategoryController extends Controller
}
return $entries;
+ * */
}
/**
@@ -437,6 +450,7 @@ class CategoryController extends Controller
*/
private function invertSelection(Collection $entries): Collection
{
+ /**
$result = new Collection;
foreach ($entries as $entry) {
$new = [$entry[0]];
@@ -448,19 +462,21 @@ class CategoryController extends Controller
}
return $result;
+ * **/
}
/**
- * @param SCRI $repository
+ * @param CRI $repository
* @param Category $category
* @param Carbon $start
* @param Carbon $end
*
* @return array
*/
- private function makePeriodChart(SCRI $repository, Category $category, Carbon $start, Carbon $end)
+ private function makePeriodChart(CRI $repository, Category $category, Carbon $start, Carbon $end)
{
+ /**
// chart properties for cache:
$cache = new CacheProperties;
$cache->addProperty($start);
@@ -490,6 +506,7 @@ class CategoryController extends Controller
$cache->store($data);
return $data;
+ */
}
}
diff --git a/app/Http/Controllers/Controller.php b/app/Http/Controllers/Controller.php
index 669caf9485..d9947d723b 100644
--- a/app/Http/Controllers/Controller.php
+++ b/app/Http/Controllers/Controller.php
@@ -73,7 +73,7 @@ class Controller extends BaseController
}
/**
- * Take the array as returned by SingleCategoryRepositoryInterface::spentPerDay and SingleCategoryRepositoryInterface::earnedByDay
+ * Take the array as returned by CategoryRepositoryInterface::spentPerDay and CategoryRepositoryInterface::earnedByDay
* and sum up everything in the array in the given range.
*
* @param Carbon $start
diff --git a/app/Http/Controllers/Popup/ReportController.php b/app/Http/Controllers/Popup/ReportController.php
index cbf4bc3010..07280a4a3e 100644
--- a/app/Http/Controllers/Popup/ReportController.php
+++ b/app/Http/Controllers/Popup/ReportController.php
@@ -18,7 +18,7 @@ use FireflyIII\Http\Controllers\Controller;
use FireflyIII\Models\TransactionJournal;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\Budget\BudgetRepositoryInterface;
-use FireflyIII\Repositories\Category\SingleCategoryRepositoryInterface;
+use FireflyIII\Repositories\Category\CategoryRepositoryInterface;
use FireflyIII\Support\Binder\AccountList;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
@@ -160,10 +160,10 @@ class ReportController extends Controller
*/
private function categoryEntry(array $attributes): string
{
- /** @var SingleCategoryRepositoryInterface $repository */
- $repository = app(SingleCategoryRepositoryInterface::class);
+ /** @var CategoryRepositoryInterface $repository */
+ $repository = app(CategoryRepositoryInterface::class);
$category = $repository->find(intval($attributes['categoryId']));
- $journals = $repository->getJournalsForAccountsInRange($category, $attributes['accounts'], $attributes['startDate'], $attributes['endDate']);
+ $journals = $repository->journalsInPeriod(new Collection([$category]), $attributes['accounts'], [], $attributes['startDate'], $attributes['endDate']);
$view = view('popup.report.category-entry', compact('journals', 'category'))->render();
return $view;
diff --git a/app/Http/Controllers/ReportController.php b/app/Http/Controllers/ReportController.php
index ce34559df8..21e76eef1d 100644
--- a/app/Http/Controllers/ReportController.php
+++ b/app/Http/Controllers/ReportController.php
@@ -317,7 +317,7 @@ class ReportController extends Controller
$budgets = $this->budgetHelper->getBudgetsWithExpenses($start, $end, $accounts);
// find the categories we've spent money on this period with these accounts:
- $categories = $this->helper->getCategoriesWithExpenses($start, $end, $accounts);
+ $categories = $this->helper->getCategoriesWithTransactions($start, $end, $accounts);
Session::flash('gaEventCategory', 'report');
Session::flash('gaEventAction', 'year');
diff --git a/app/Providers/CategoryServiceProvider.php b/app/Providers/CategoryServiceProvider.php
index 7da232890c..0278b3f472 100644
--- a/app/Providers/CategoryServiceProvider.php
+++ b/app/Providers/CategoryServiceProvider.php
@@ -44,19 +44,5 @@ class CategoryServiceProvider extends ServiceProvider
}
);
- $this->app->bind(
- 'FireflyIII\Repositories\Category\SingleCategoryRepositoryInterface',
- function (Application $app, array $arguments) {
- if (!isset($arguments[0]) && $app->auth->check()) {
- return app('FireflyIII\Repositories\Category\SingleCategoryRepository', [$app->auth->user()]);
- }
- if (!isset($arguments[0]) && !$app->auth->check()) {
- throw new FireflyException('There is no user present.');
- }
-
- return app('FireflyIII\Repositories\Category\SingleCategoryRepository', $arguments);
- }
- );
-
}
}
diff --git a/app/Repositories/Category/CategoryRepository.php b/app/Repositories/Category/CategoryRepository.php
index 0b8209b76d..2bfb97930d 100644
--- a/app/Repositories/Category/CategoryRepository.php
+++ b/app/Repositories/Category/CategoryRepository.php
@@ -4,11 +4,11 @@ declare(strict_types = 1);
namespace FireflyIII\Repositories\Category;
use Carbon\Carbon;
-use DB;
use FireflyIII\Models\Category;
+use FireflyIII\Models\TransactionJournal;
use FireflyIII\Models\TransactionType;
use FireflyIII\User;
-use Illuminate\Database\Query\JoinClause;
+use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
/**
@@ -18,8 +18,8 @@ use Illuminate\Support\Collection;
*/
class CategoryRepository implements CategoryRepositoryInterface
{
- const SPENT = 1;
- const EARNED = 2;
+ // const SPENT = 1;
+ // const EARNED = 2;
/** @var User */
@@ -35,54 +35,577 @@ class CategoryRepository implements CategoryRepositoryInterface
$this->user = $user;
}
+ // /**
+ // * Returns a collection of Categories appended with the amount of money that has been earned
+ // * in these categories, based on the $accounts involved, in period X, grouped per month.
+ // * The amount earned in category X in period X is saved in field "earned".
+ // *
+ // * @param $accounts
+ // * @param $start
+ // * @param $end
+ // *
+ // * @return Collection
+ // */
+ // public function earnedForAccountsPerMonth(Collection $accounts, Carbon $start, Carbon $end): Collection
+ // {
+ //
+ // $collection = $this->user->categories()
+ // ->leftJoin('category_transaction_journal', 'category_transaction_journal.category_id', '=', 'categories.id')
+ // ->leftJoin('transaction_journals', 'category_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id')
+ // ->leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id')
+ // ->leftJoin(
+ // 'transactions AS t_src', function (JoinClause $join) {
+ // $join->on('t_src.transaction_journal_id', '=', 'transaction_journals.id')->where('t_src.amount', '<', 0);
+ // }
+ // )
+ // ->leftJoin(
+ // 'transactions AS t_dest', function (JoinClause $join) {
+ // $join->on('t_dest.transaction_journal_id', '=', 'transaction_journals.id')->where('t_dest.amount', '>', 0);
+ // }
+ // )
+ // ->whereIn('t_dest.account_id', $accounts->pluck('id')->toArray())// to these accounts (earned)
+ // ->whereNotIn('t_src.account_id', $accounts->pluck('id')->toArray())//-- but not from these accounts
+ // ->whereIn(
+ // 'transaction_types.type', [TransactionType::DEPOSIT, TransactionType::TRANSFER, TransactionType::OPENING_BALANCE]
+ // )
+ // ->where('transaction_journals.date', '>=', $start->format('Y-m-d'))
+ // ->where('transaction_journals.date', '<=', $end->format('Y-m-d'))
+ // ->groupBy('categories.id')
+ // ->groupBy('dateFormatted')
+ // ->get(
+ // [
+ // 'categories.*',
+ // DB::raw('DATE_FORMAT(`transaction_journals`.`date`,"%Y-%m") as `dateFormatted`'),
+ // DB::raw('SUM(`t_dest`.`amount`) AS `earned`'),
+ // ]
+ // );
+ //
+ // return $collection;
+ //
+ //
+ // }
+
+ // /**
+ // * @param Category $category
+ // * @param Carbon|null $start
+ // * @param Carbon|null $end
+ // *
+ // * @return int
+ // */
+ // public function countJournals(Category $category, Carbon $start = null, Carbon $end = null): int
+ // {
+ // $query = $category->transactionjournals();
+ // if (!is_null($start)) {
+ // $query->after($start);
+ // }
+ // if (!is_null($end)) {
+ // $query->before($end);
+ // }
+ //
+ // return $query->count();
+ //
+ // }
+
+ // /**
+ // * This method returns a very special collection for each category:
+ // *
+ // * category, year, expense/earned, amount
+ // *
+ // * categories can be duplicated.
+ // *
+ // * @param Collection $categories
+ // * @param Collection $accounts
+ // * @param Carbon $start
+ // * @param Carbon $end
+ // *
+ // * @return Collection
+ // */
+ // public function listMultiYear(Collection $categories, Collection $accounts, Carbon $start, Carbon $end): Collection
+ // {
+ //
+ // $set = $this->user->categories()
+ // ->leftJoin('category_transaction_journal', 'category_transaction_journal.category_id', '=', 'categories.id')
+ // ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'category_transaction_journal.transaction_journal_id')
+ // ->leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id')
+ // ->leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id')
+ // ->whereIn('transaction_types.type', [TransactionType::DEPOSIT, TransactionType::WITHDRAWAL])
+ // ->whereIn('transactions.account_id', $accounts->pluck('id')->toArray())
+ // ->whereIn('categories.id', $categories->pluck('id')->toArray())
+ // ->where('transaction_journals.date', '>=', $start->format('Y-m-d'))
+ // ->where('transaction_journals.date', '<=', $end->format('Y-m-d'))
+ // ->groupBy('categories.id')
+ // ->groupBy('transaction_types.type')
+ // ->groupBy('dateFormatted')
+ // ->get(
+ // [
+ // 'categories.*',
+ // DB::raw('DATE_FORMAT(`transaction_journals`.`date`,"%Y") as `dateFormatted`'),
+ // 'transaction_types.type',
+ // DB::raw('SUM(`amount`) as `sum`'),
+ // ]
+ // );
+ //
+ // return $set;
+ //
+ // }
+
+ // /**
+ // * Returns a list of transaction journals in the range (all types, all accounts) that have no category
+ // * associated to them.
+ // *
+ // * @param Carbon $start
+ // * @param Carbon $end
+ // *
+ // * @return Collection
+ // */
+ // public function listNoCategory(Carbon $start, Carbon $end): Collection
+ // {
+ // return $this->user
+ // ->transactionjournals()
+ // ->leftJoin('category_transaction_journal', 'category_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id')
+ // ->whereNull('category_transaction_journal.id')
+ // ->before($end)
+ // ->after($start)
+ // ->orderBy('transaction_journals.date', 'DESC')
+ // ->orderBy('transaction_journals.order', 'ASC')
+ // ->orderBy('transaction_journals.id', 'DESC')
+ // ->get(['transaction_journals.*']);
+ // }
+
+ // /**
+ // * Returns a collection of Categories appended with the amount of money that has been spent
+ // * in these categories, based on the $accounts involved, in period X, grouped per month.
+ // * The amount spent in category X in period X is saved in field "spent".
+ // *
+ // * @param $accounts
+ // * @param $start
+ // * @param $end
+ // *
+ // * @return Collection
+ // */
+ // public function spentForAccountsPerMonth(Collection $accounts, Carbon $start, Carbon $end): Collection
+ // {
+ // $accountIds = $accounts->pluck('id')->toArray();
+ // $query = $this->user->categories()
+ // ->leftJoin('category_transaction_journal', 'category_transaction_journal.category_id', '=', 'categories.id')
+ // ->leftJoin('transaction_journals', 'category_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id')
+ // ->leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id')
+ // ->leftJoin(
+ // 'transactions AS t_src', function (JoinClause $join) {
+ // $join->on('t_src.transaction_journal_id', '=', 'transaction_journals.id')->where('t_src.amount', '<', 0);
+ // }
+ // )
+ // ->leftJoin(
+ // 'transactions AS t_dest', function (JoinClause $join) {
+ // $join->on('t_dest.transaction_journal_id', '=', 'transaction_journals.id')->where('t_dest.amount', '>', 0);
+ // }
+ // )
+ // ->whereIn(
+ // 'transaction_types.type', [TransactionType::WITHDRAWAL, TransactionType::TRANSFER, TransactionType::OPENING_BALANCE]
+ // )// spent on these things.
+ // ->where('transaction_journals.date', '>=', $start->format('Y-m-d'))
+ // ->where('transaction_journals.date', '<=', $end->format('Y-m-d'))
+ // ->groupBy('categories.id')
+ // ->groupBy('dateFormatted');
+ //
+ // if (count($accountIds) > 0) {
+ // $query->whereIn('t_src.account_id', $accountIds)// from these accounts (spent)
+ // ->whereNotIn('t_dest.account_id', $accountIds);//-- but not from these accounts (spent internally)
+ // }
+ //
+ // $collection = $query->get(
+ // [
+ // 'categories.*',
+ // DB::raw('DATE_FORMAT(`transaction_journals`.`date`,"%Y-%m") as `dateFormatted`'),
+ // DB::raw('SUM(`t_src`.`amount`) AS `spent`'),
+ // ]
+ // );
+ //
+ // return $collection;
+ // }
+
+ // /**
+ // * Returns the total amount of money related to transactions without any category connected to
+ // * it. Returns either the earned amount.
+ // *
+ // * @param Collection $accounts
+ // * @param Carbon $start
+ // * @param Carbon $end
+ // *
+ // * @return string
+ // */
+ // public function sumEarnedNoCategory(Collection $accounts, Carbon $start, Carbon $end): string
+ // {
+ // return $this->sumNoCategory($accounts, $start, $end, self::EARNED);
+ // }
+
+ // /**
+ // * Returns the total amount of money related to transactions without any category connected to
+ // * it. Returns either the spent amount.
+ // *
+ // * @param Collection $accounts
+ // * @param Carbon $start
+ // * @param Carbon $end
+ // *
+ // * @return string
+ // */
+ // public function sumSpentNoCategory(Collection $accounts, Carbon $start, Carbon $end): string
+ // {
+ // $sum = $this->sumNoCategory($accounts, $start, $end, self::SPENT);
+ // if (is_null($sum)) {
+ // return '0';
+ // }
+ //
+ // return $sum;
+ // }
+
+ // /**
+ // * Returns the total amount of money related to transactions without any category connected to
+ // * it. Returns either the earned or the spent amount.
+ // *
+ // * @param Collection $accounts
+ // * @param Carbon $start
+ // * @param Carbon $end
+ // * @param int $group
+ // *
+ // * @return string
+ // */
+ // protected function sumNoCategory(Collection $accounts, Carbon $start, Carbon $end, $group = self::EARNED)
+ // {
+ // $accountIds = $accounts->pluck('id')->toArray();
+ // if ($group == self::EARNED) {
+ // $types = [TransactionType::DEPOSIT];
+ // } else {
+ // $types = [TransactionType::WITHDRAWAL];
+ // }
+ //
+ // // is withdrawal or transfer AND account_from is in the list of $accounts
+ // $query = $this->user
+ // ->transactionjournals()
+ // ->leftJoin('category_transaction_journal', 'category_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id')
+ // ->whereNull('category_transaction_journal.id')
+ // ->before($end)
+ // ->after($start)
+ // ->leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id')
+ // ->having('transaction_count', '=', 1)
+ // ->transactionTypes($types);
+ //
+ // if (count($accountIds) > 0) {
+ // $query->whereIn('transactions.account_id', $accountIds);
+ // }
+ //
+ //
+ // $single = $query->first(
+ // [
+ // DB::raw('SUM(`transactions`.`amount`) as `sum`'),
+ // DB::raw('COUNT(`transactions`.`id`) as `transaction_count`'),
+ // ]
+ // );
+ // if (!is_null($single)) {
+ // return $single->sum;
+ // }
+ //
+ // return '0';
+ //
+ // }
+
/**
- * Returns a collection of Categories appended with the amount of money that has been earned
- * in these categories, based on the $accounts involved, in period X, grouped per month.
- * The amount earned in category X in period X is saved in field "earned".
+ * @param Category $category
*
- * @param $accounts
- * @param $start
- * @param $end
+ * @return bool
+ */
+ public function destroy(Category $category): bool
+ {
+ $category->delete();
+
+ return true;
+ }
+
+ // /**
+ // * Returns an array with the following key:value pairs:
+ // *
+ // * yyyy-mm-dd:<amount>
+ // *
+ // * Where yyyy-mm-dd is the date and <amount> is the money earned using DEPOSITS in the $category
+ // * from all the users $accounts.
+ // *
+ // * @param Category $category
+ // * @param Carbon $start
+ // * @param Carbon $end
+ // * @param Collection $accounts
+ // *
+ // * @return array
+ // */
+ // public function earnedPerDay(Category $category, Carbon $start, Carbon $end, Collection $accounts): array
+ // {
+ // /** @var Collection $query */
+ // $query = $category->transactionjournals()
+ // ->expanded()
+ // ->transactionTypes([TransactionType::DEPOSIT])
+ // ->before($end)
+ // ->after($start)
+ // ->groupBy('transaction_journals.date');
+ //
+ // $query->leftJoin(
+ // 'transactions as destination', function (JoinClause $join) {
+ // $join->on('destination.transaction_journal_id', '=', 'transaction_journals.id')->where('destination.amount', '>', 0);
+ // }
+ // );
+ //
+ //
+ // if ($accounts->count() > 0) {
+ // $ids = $accounts->pluck('id')->toArray();
+ // $query->whereIn('destination.account.id', $ids);
+ // }
+ //
+ // $result = $query->get(['transaction_journals.date as dateFormatted', DB::raw('SUM(`destination`.`amount`) AS `sum`')]);
+ //
+ // $return = [];
+ // foreach ($result->toArray() as $entry) {
+ // $return[$entry['dateFormatted']] = $entry['sum'];
+ // }
+ //
+ // return $return;
+ // }
+
+ /**
+ * @param Collection $categories
+ * @param Collection $accounts
+ * @param Carbon $start
+ * @param Carbon $end
*
- * @return Collection
+ * @return string
*/
- public function earnedForAccountsPerMonth(Collection $accounts, Carbon $start, Carbon $end): Collection
+ public function earnedInPeriod(Collection $categories, Collection $accounts, Carbon $start, Carbon $end): string
{
+ $types = [TransactionType::WITHDRAWAL, TransactionType::TRANSFER];
+ $journals = $this->journalsInPeriod($categories, $accounts, $types, $start, $end);
+ $sum = '0';
+ foreach ($journals as $journal) {
+ $sum = bcadd(TransactionJournal::amount($journal), $sum);
+ }
- $collection = $this->user->categories()
- ->leftJoin('category_transaction_journal', 'category_transaction_journal.category_id', '=', 'categories.id')
- ->leftJoin('transaction_journals', 'category_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id')
- ->leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id')
- ->leftJoin(
- 'transactions AS t_src', function (JoinClause $join) {
- $join->on('t_src.transaction_journal_id', '=', 'transaction_journals.id')->where('t_src.amount', '<', 0);
- }
- )
- ->leftJoin(
- 'transactions AS t_dest', function (JoinClause $join) {
- $join->on('t_dest.transaction_journal_id', '=', 'transaction_journals.id')->where('t_dest.amount', '>', 0);
- }
- )
- ->whereIn('t_dest.account_id', $accounts->pluck('id')->toArray())// to these accounts (earned)
- ->whereNotIn('t_src.account_id', $accounts->pluck('id')->toArray())//-- but not from these accounts
- ->whereIn(
- 'transaction_types.type', [TransactionType::DEPOSIT, TransactionType::TRANSFER, TransactionType::OPENING_BALANCE]
- )
- ->where('transaction_journals.date', '>=', $start->format('Y-m-d'))
- ->where('transaction_journals.date', '<=', $end->format('Y-m-d'))
- ->groupBy('categories.id')
- ->groupBy('dateFormatted')
- ->get(
- [
- 'categories.*',
- DB::raw('DATE_FORMAT(`transaction_journals`.`date`,"%Y-%m") as `dateFormatted`'),
- DB::raw('SUM(`t_dest`.`amount`) AS `earned`'),
- ]
- );
-
- return $collection;
+ return $sum;
+ }
+ /**
+ * Find a category
+ *
+ * @param int $categoryId
+ *
+ * @return Category
+ */
+ public function find(int $categoryId) : Category
+ {
+ $category = $this->user->categories()->find($categoryId);
+ if (is_null($category)) {
+ $category = new Category;
+ }
+ return $category;
+ }
+
+ // /**
+ // * @param Category $category
+ // *
+ // * @return Carbon
+ // */
+ // public function getFirstActivityDate(Category $category): Carbon
+ // {
+ // /** @var TransactionJournal $first */
+ // $first = $category->transactionjournals()->orderBy('date', 'ASC')->first();
+ // if ($first) {
+ // return $first->date;
+ // }
+ //
+ // return new Carbon;
+ //
+ // }
+
+ // /**
+ // * @param Category $category
+ // * @param int $page
+ // * @param int $pageSize
+ // *
+ // * @return Collection
+ // */
+ // public function getJournals(Category $category, int $page, int $pageSize = 50): Collection
+ // {
+ // $offset = $page > 0 ? $page * $pageSize : 0;
+ //
+ // return $category->transactionjournals()->expanded()->take($pageSize)->offset($offset)->get(TransactionJournal::queryFields());
+ //
+ // }
+ //
+ // /**
+ // * @param Category $category
+ // * @param Collection $accounts
+ // *
+ // * @param Carbon $start
+ // * @param Carbon $end
+ // *
+ // * @return Collection
+ // */
+ // public function getJournalsForAccountsInRange(Category $category, Collection $accounts, Carbon $start, Carbon $end): Collection
+ // {
+ // $ids = $accounts->pluck('id')->toArray();
+ //
+ // return $category->transactionjournals()
+ // ->after($start)
+ // ->before($end)
+ // ->expanded()
+ // ->whereIn('source_account.id', $ids)
+ // ->whereNotIn('destination_account.id', $ids)
+ // ->get(TransactionJournal::queryFields());
+ // }
+
+ // /**
+ // * @param Category $category
+ // * @param Carbon $start
+ // * @param Carbon $end
+ // * @param int $page
+ // * @param int $pageSize
+ // *
+ // *
+ // * @return Collection
+ // */
+ // public function getJournalsInRange(Category $category, Carbon $start, Carbon $end, int $page, int $pageSize = 50): Collection
+ // {
+ // $offset = $page > 0 ? $page * $pageSize : 0;
+ //
+ // return $category->transactionjournals()
+ // ->after($start)
+ // ->before($end)
+ // ->expanded()
+ // ->take($pageSize)
+ // ->offset($offset)
+ // ->get(TransactionJournal::queryFields());
+ // }
+
+ // /**
+ // * @param Category $category
+ // *
+ // * @return Carbon
+ // */
+ // public function getLatestActivity(Category $category): Carbon
+ // {
+ // $first = new Carbon('1900-01-01');
+ // $second = new Carbon('1900-01-01');
+ // $latest = $category->transactionjournals()
+ // ->orderBy('transaction_journals.date', 'DESC')
+ // ->orderBy('transaction_journals.order', 'ASC')
+ // ->orderBy('transaction_journals.id', 'DESC')
+ // ->first();
+ // if ($latest) {
+ // $first = $latest->date;
+ // }
+ //
+ // // could also be a transaction, nowadays:
+ // $latestTransaction = $category->transactions()
+ // ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id')
+ // ->orderBy('transaction_journals.date', 'DESC')
+ // ->orderBy('transaction_journals.order', 'ASC')
+ // ->orderBy('transaction_journals.id', 'DESC')
+ // ->first(['transactions.*', 'transaction_journals.date']);
+ // if ($latestTransaction) {
+ // $second = new Carbon($latestTransaction->date);
+ // }
+ // if ($first > $second) {
+ // return $first;
+ // }
+ //
+ // return $second;
+ // }
+
+ // /**
+ // * Returns an array with the following key:value pairs:
+ // *
+ // * yyyy-mm-dd:<amount>
+ // *
+ // * Where yyyy-mm-dd is the date and <amount> is the money spent using DEPOSITS in the $category
+ // * from all the users accounts.
+ // *
+ // * @param Category $category
+ // * @param Carbon $start
+ // * @param Carbon $end
+ // * @param Collection $accounts
+ // *
+ // * @return array
+ // */
+ // public function spentPerDay(Category $category, Carbon $start, Carbon $end, Collection $accounts): array
+ // {
+ // /** @var Collection $query */
+ // $query = $category->transactionjournals()
+ // ->expanded()
+ // ->transactionTypes([TransactionType::WITHDRAWAL])
+ // ->before($end)
+ // ->after($start)
+ // ->groupBy('transaction_journals.date');
+ // $query->leftJoin(
+ // 'transactions as source', function (JoinClause $join) {
+ // $join->on('source.transaction_journal_id', '=', 'transaction_journals.id')->where('source.amount', '<', 0);
+ // }
+ // );
+ //
+ // if ($accounts->count() > 0) {
+ // $ids = $accounts->pluck('id')->toArray();
+ // $query->whereIn('source.account_id', $ids);
+ // }
+ //
+ // $result = $query->get(['transaction_journals.date as dateFormatted', DB::raw('SUM(`source`.`amount`) AS `sum`')]);
+ //
+ // $return = [];
+ // foreach ($result->toArray() as $entry) {
+ // $return[$entry['dateFormatted']] = $entry['sum'];
+ // }
+ //
+ // return $return;
+ // }
+
+ /**
+ * @param Category $category
+ * @param Collection $accounts
+ *
+ * @return Carbon
+ */
+ public function firstUseDate(Category $category, Collection $accounts): Carbon
+ {
+ $first = null;
+
+ /** @var TransactionJournal $first */
+ $firstJournalQuery = $category->transactionjournals()->orderBy('date', 'DESC');
+
+ if ($accounts->count() > 0) {
+ // filter journals:
+ $ids = $accounts->pluck('id')->toArray();
+ $firstJournalQuery->leftJoin('transactions as t', 't.transaction_journal_id', '=', 'transaction_journals.id');
+ $firstJournalQuery->whereIn('t.account_id', $ids);
+ }
+
+ $firstJournal = $firstJournalQuery->first(['transaction_journals.*']);
+
+ if ($firstJournal) {
+ $first = $firstJournal->date;
+ }
+
+ // check transactions:
+
+ $firstTransactionQuery = $category->transactions()
+ ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id')
+ ->orderBy('transaction_journals.date', 'ASC');
+ if ($accounts->count() > 0) {
+ // filter journals:
+ $ids = $accounts->pluck('id')->toArray();
+ $firstTransactionQuery->whereIn('transactions.account_id', $ids);
+ }
+
+ $firstTransaction = $firstJournalQuery->first(['transaction_journals.*']);
+
+ if (!is_null($firstTransaction) && !is_null($first) && $firstTransaction->date < $first) {
+ $first = $firstTransaction->date;
+ }
+
+ return $first;
}
/**
@@ -104,205 +627,249 @@ class CategoryRepository implements CategoryRepositoryInterface
}
/**
- * This method returns a very special collection for each category:
- *
- * category, year, expense/earned, amount
+ * @param Category $category
+ * @param int $page
+ * @param int $pageSize
*
- * categories can be duplicated.
+ * @return LengthAwarePaginator
+ */
+ public function getJournals(Category $category, int $page, int $pageSize): LengthAwarePaginator
+ {
+ $complete = new Collection;
+ // first collect actual transaction journals (fairly easy)
+ $query = $this->user->transactionjournals()->expanded();
+ $query->leftJoin('category_transaction_journal', 'category_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id');
+ $query->where('category_transaction_journal.category_id', $category->id);
+ $first = $query->get(TransactionJournal::queryFields());
+
+ // then collection transactions (harder)
+ $query = $this->user->transactions()
+ ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.id');
+ $query->leftJoin('category_transaction', 'category_transaction.transaction_id', '=', 'transactions.id');
+ $query->where('category_transaction.category_id', $category->id);
+ $second = $query->get('transaction_journals.*');
+
+
+ $complete = $complete->merge($first);
+ $complete = $complete->merge($second);
+
+ return $complete;
+ }
+
+ /**
+ * Get all transactions in a category in a range.
*
* @param Collection $categories
* @param Collection $accounts
+ * @param array $types
* @param Carbon $start
* @param Carbon $end
*
* @return Collection
*/
- public function listMultiYear(Collection $categories, Collection $accounts, Carbon $start, Carbon $end): Collection
+ public function journalsInPeriod(Collection $categories, Collection $accounts, array $types, Carbon $start, Carbon $end): Collection
{
+ $complete = new Collection;
+ // first collect actual transaction journals (fairly easy)
+ $query = $this->user->transactionjournals()->expanded();
- $set = $this->user->categories()
- ->leftJoin('category_transaction_journal', 'category_transaction_journal.category_id', '=', 'categories.id')
- ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'category_transaction_journal.transaction_journal_id')
- ->leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id')
- ->leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id')
- ->whereIn('transaction_types.type', [TransactionType::DEPOSIT, TransactionType::WITHDRAWAL])
- ->whereIn('transactions.account_id', $accounts->pluck('id')->toArray())
- ->whereIn('categories.id', $categories->pluck('id')->toArray())
- ->where('transaction_journals.date', '>=', $start->format('Y-m-d'))
- ->where('transaction_journals.date', '<=', $end->format('Y-m-d'))
- ->groupBy('categories.id')
- ->groupBy('transaction_types.type')
- ->groupBy('dateFormatted')
- ->get(
- [
- 'categories.*',
- DB::raw('DATE_FORMAT(`transaction_journals`.`date`,"%Y") as `dateFormatted`'),
- 'transaction_types.type',
- DB::raw('SUM(`amount`) as `sum`'),
- ]
- );
+ if ($end > $start) {
+ $query->before($end)->after($start);
+ }
- return $set;
+ if (count($types) > 0) {
+ $query->transactionTypes($types);
+ }
+ if ($accounts->count() > 0) {
+ $accountIds = $accounts->pluck('id')->toArray();
+ $query->leftJoin('transactions as t', 't.transaction_journal_id', '=', 'transaction_journals.id');
+ $query->whereIn('t.account_id', $accountIds);
+ }
+ if ($categories->count() > 0) {
+ $categoryIds = $categories->pluck('id')->toArray();
+ $query->leftJoin('category_transaction_journal', 'category_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id');
+ $query->whereIn('category_transaction_journal.category_id', $categoryIds);
+ }
+
+ // that should do it:
+ $first = $query->get(TransactionJournal::queryFields());
+
+ // then collection transactions (harder)
+ $query = $this->user->transactions()
+ ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.id')
+ ->where('transaction_journals.date', '>=', $start->format('Y-m-d 00:00:00'))
+ ->where('transaction_journals.date', '<=', $end->format('Y-m-d 23:59:59'));
+ if (count($types) > 0) {
+ $query->leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id');
+ $query->whereIn('transaction_types.type', $types);
+ }
+ if ($accounts->count() > 0) {
+ $accountIds = $accounts->pluck('id')->toArray();
+ $query->whereIn('transactions.account_id', $accountIds);
+ }
+ if ($categories->count() > 0) {
+ $categoryIds = $categories->pluck('id')->toArray();
+ $query->leftJoin('category_transaction', 'category_transaction.transaction_id', '=', 'transactions.id');
+ $query->whereIn('category_transaction.category_id', $categoryIds);
+ }
+ $second = $query->get('transaction_journals.*');
+ $complete = $complete->merge($first);
+ $complete = $complete->merge($second);
+ return $complete;
}
/**
- * Returns a list of transaction journals in the range (all types, all accounts) that have no category
- * associated to them.
- *
- * @param Carbon $start
- * @param Carbon $end
+ * @param Collection $accounts
+ * @param Carbon $start
+ * @param Carbon $end
*
* @return Collection
*/
- public function listNoCategory(Carbon $start, Carbon $end): Collection
+ public function journalsInPeriodWithoutCategory(Collection $accounts, Carbon $start, Carbon $end) : Collection
{
- return $this->user
+ /** @var Collection $set */
+ $query = $this->user
->transactionjournals()
->leftJoin('category_transaction_journal', 'category_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id')
->whereNull('category_transaction_journal.id')
->before($end)
- ->after($start)
- ->orderBy('transaction_journals.date', 'DESC')
- ->orderBy('transaction_journals.order', 'ASC')
- ->orderBy('transaction_journals.id', 'DESC')
- ->get(['transaction_journals.*']);
- }
+ ->after($start);
- /**
- * Returns a collection of Categories appended with the amount of money that has been spent
- * in these categories, based on the $accounts involved, in period X, grouped per month.
- * The amount spent in category X in period X is saved in field "spent".
- *
- * @param $accounts
- * @param $start
- * @param $end
- *
- * @return Collection
- */
- public function spentForAccountsPerMonth(Collection $accounts, Carbon $start, Carbon $end): Collection
- {
- $accountIds = $accounts->pluck('id')->toArray();
- $query = $this->user->categories()
- ->leftJoin('category_transaction_journal', 'category_transaction_journal.category_id', '=', 'categories.id')
- ->leftJoin('transaction_journals', 'category_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id')
- ->leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id')
- ->leftJoin(
- 'transactions AS t_src', function (JoinClause $join) {
- $join->on('t_src.transaction_journal_id', '=', 'transaction_journals.id')->where('t_src.amount', '<', 0);
- }
- )
- ->leftJoin(
- 'transactions AS t_dest', function (JoinClause $join) {
- $join->on('t_dest.transaction_journal_id', '=', 'transaction_journals.id')->where('t_dest.amount', '>', 0);
- }
- )
- ->whereIn(
- 'transaction_types.type', [TransactionType::WITHDRAWAL, TransactionType::TRANSFER, TransactionType::OPENING_BALANCE]
- )// spent on these things.
- ->where('transaction_journals.date', '>=', $start->format('Y-m-d'))
- ->where('transaction_journals.date', '<=', $end->format('Y-m-d'))
- ->groupBy('categories.id')
- ->groupBy('dateFormatted');
-
- if (count($accountIds) > 0) {
- $query->whereIn('t_src.account_id', $accountIds)// from these accounts (spent)
- ->whereNotIn('t_dest.account_id', $accountIds);//-- but not from these accounts (spent internally)
+ if ($accounts->count() > 0) {
+ $accountIds = $accounts->pluck('id')->toArray();
+ $query->leftJoin('transactions as t', 't.transaction_journal_id', '=', 'transaction_journals.id');
+ $query->whereIn('t.account_id', $accountIds);
}
- $collection = $query->get(
- [
- 'categories.*',
- DB::raw('DATE_FORMAT(`transaction_journals`.`date`,"%Y-%m") as `dateFormatted`'),
- DB::raw('SUM(`t_src`.`amount`) AS `spent`'),
- ]
- );
+ $set = $query->get(['transaction_journals.*']);
+
+ if ($set->count() == 0) {
+ return new Collection;
+ }
+
+ // grab all the transactions from this set.
+ // take only the journals with transactions that all have no category.
+ // select transactions left join journals where id in this set
+ // and left join transaction-category where null category
+ $journalIds = $set->pluck('id')->toArray();
+ $secondQuery = $this->user->transactions()
+ ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transaction.transaction_journal_id')
+ ->leftJoin('category_transaction', 'category_transaction.transaction_id', '=', 'transactions.id')
+ ->whereNull('category_transaction.id')
+ ->whereIn('transaction_journals.id', $journalIds);
+
+ if ($accounts->count() > 0) {
+ $accountIds = $accounts->pluck('id')->toArray();
+ $secondQuery->whereIn('transactions.account_id', $accountIds);
+ }
+
+ // this second set REALLY doesn't have any categories.
+ $secondSet = $secondQuery->get(['transactions.transaction_journal_id']);
+ $allIds = $secondSet->pluck('transaction_journal_id')->toArray();
+ $return = $this->user->transactionjournals()->expanded()->whereIn('transaction_journals.id', $allIds)->get(TransactionJournal::queryFields());
+
+ return $return;
+
- return $collection;
}
/**
- * Returns the total amount of money related to transactions without any category connected to
- * it. Returns either the earned amount.
- *
+ * @param Category $category
* @param Collection $accounts
- * @param Carbon $start
- * @param Carbon $end
*
- * @return string
+ * @return Carbon
*/
- public function sumEarnedNoCategory(Collection $accounts, Carbon $start, Carbon $end): string
+ public function lastUseDate(Category $category, Collection $accounts): Carbon
{
- return $this->sumNoCategory($accounts, $start, $end, self::EARNED);
+ $last = null;
+
+ /** @var TransactionJournal $first */
+ $lastJournalQuery = $category->transactionjournals()->orderBy('date', 'ASC');
+
+ if ($accounts->count() > 0) {
+ // filter journals:
+ $ids = $accounts->pluck('id')->toArray();
+ $lastJournalQuery->leftJoin('transactions as t', 't.transaction_journal_id', '=', 'transaction_journals.id');
+ $lastJournalQuery->whereIn('t.account_id', $ids);
+ }
+
+ $lastJournal = $lastJournalQuery->first(['transaction_journals.*']);
+
+ if ($lastJournal) {
+ $last = $lastJournal->date;
+ }
+
+ // check transactions:
+
+ $lastTransactionQuery = $category->transactions()
+ ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id')
+ ->orderBy('transaction_journals.date', 'ASC');
+ if ($accounts->count() > 0) {
+ // filter journals:
+ $ids = $accounts->pluck('id')->toArray();
+ $lastTransactionQuery->whereIn('transactions.account_id', $ids);
+ }
+
+ $lastTransaction = $lastJournalQuery->first(['transaction_journals.*']);
+
+ if (!is_null($lastTransaction) && !is_null($last) && $lastTransaction->date < $last) {
+ $last = $lastTransaction->date;
+ }
+
+ return $last;
}
/**
- * Returns the total amount of money related to transactions without any category connected to
- * it. Returns either the spent amount.
- *
+ * @param Collection $categories
* @param Collection $accounts
* @param Carbon $start
* @param Carbon $end
*
* @return string
*/
- public function sumSpentNoCategory(Collection $accounts, Carbon $start, Carbon $end): string
+ public function spentInPeriod(Collection $categories, Collection $accounts, Carbon $start, Carbon $end): string
{
- $sum = $this->sumNoCategory($accounts, $start, $end, self::SPENT);
- if (is_null($sum)) {
- return '0';
+ $types = [TransactionType::DEPOSIT, TransactionType::TRANSFER];
+ $journals = $this->journalsInPeriod($categories, $accounts, $types, $start, $end);
+ $sum = '0';
+ foreach ($journals as $journal) {
+ $sum = bcadd(TransactionJournal::amount($journal), $sum);
}
return $sum;
}
/**
- * Returns the total amount of money related to transactions without any category connected to
- * it. Returns either the earned or the spent amount.
+ * @param array $data
*
- * @param Collection $accounts
- * @param Carbon $start
- * @param Carbon $end
- * @param int $group
- *
- * @return string
+ * @return Category
*/
- protected function sumNoCategory(Collection $accounts, Carbon $start, Carbon $end, $group = self::EARNED)
+ public function store(array $data): Category
{
- $accountIds = $accounts->pluck('id')->toArray();
- if ($group == self::EARNED) {
- $types = [TransactionType::DEPOSIT];
- } else {
- $types = [TransactionType::WITHDRAWAL];
- }
-
- // is withdrawal or transfer AND account_from is in the list of $accounts
- $query = $this->user
- ->transactionjournals()
- ->leftJoin('category_transaction_journal', 'category_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id')
- ->whereNull('category_transaction_journal.id')
- ->before($end)
- ->after($start)
- ->leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id')
- ->having('transaction_count', '=', 1)
- ->transactionTypes($types);
-
- if (count($accountIds) > 0) {
- $query->whereIn('transactions.account_id', $accountIds);
- }
-
-
- $single = $query->first(
+ $newCategory = Category::firstOrCreateEncrypted(
[
- DB::raw('SUM(`transactions`.`amount`) as `sum`'),
- DB::raw('COUNT(`transactions`.`id`) as `transaction_count`'),
+ 'user_id' => $data['user'],
+ 'name' => $data['name'],
]
);
- if (!is_null($single)) {
- return $single->sum;
- }
+ $newCategory->save();
+
+ return $newCategory;
+ }
- return '0';
+ /**
+ * @param Category $category
+ * @param array $data
+ *
+ * @return Category
+ */
+ public function update(Category $category, array $data): Category
+ {
+ // update the account:
+ $category->name = $data['name'];
+ $category->save();
+ return $category;
}
}
diff --git a/app/Repositories/Category/CategoryRepositoryInterface.php b/app/Repositories/Category/CategoryRepositoryInterface.php
index 5c5966c8b7..e49dd8cb85 100644
--- a/app/Repositories/Category/CategoryRepositoryInterface.php
+++ b/app/Repositories/Category/CategoryRepositoryInterface.php
@@ -4,6 +4,8 @@ declare(strict_types = 1);
namespace FireflyIII\Repositories\Category;
use Carbon\Carbon;
+use FireflyIII\Models\Category;
+use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
/**
@@ -15,18 +17,149 @@ interface CategoryRepositoryInterface
{
+ // /**
+ // * Returns a collection of Categories appended with the amount of money that has been earned
+ // * in these categories, based on the $accounts involved, in period X, grouped per month.
+ // * The amount earned in category X in period X is saved in field "earned".
+ // *
+ // * @param $accounts
+ // * @param $start
+ // * @param $end
+ // *
+ // * @return Collection
+ // */
+ // public function earnedForAccountsPerMonth(Collection $accounts, Carbon $start, Carbon $end): Collection;
+
+ /**
+ * @param Category $category
+ *
+ * @return bool
+ */
+ public function destroy(Category $category): bool;
+
+ // /**
+ // * This method returns a very special collection for each category:
+ // *
+ // * category, year, expense/earned, amount
+ // *
+ // * categories can be duplicated.
+ // *
+ // * @param Collection $categories
+ // * @param Collection $accounts
+ // * @param Carbon $start
+ // * @param Carbon $end
+ // *
+ // * @return Collection
+ // */
+ // public function listMultiYear(Collection $categories, Collection $accounts, Carbon $start, Carbon $end): Collection;
+
+ // /**
+ // * Returns a list of transaction journals in the range (all types, all accounts) that have no category
+ // * associated to them.
+ // *
+ // * @param Carbon $start
+ // * @param Carbon $end
+ // *
+ // * @return Collection
+ // */
+ // public function listNoCategory(Carbon $start, Carbon $end): Collection;
+
+ // /**
+ // * Returns a collection of Categories appended with the amount of money that has been spent
+ // * in these categories, based on the $accounts involved, in period X, grouped per month.
+ // * The amount earned in category X in period X is saved in field "spent".
+ // *
+ // * @param $accounts
+ // * @param $start
+ // * @param $end
+ // *
+ // * @return Collection
+ // */
+ // public function spentForAccountsPerMonth(Collection $accounts, Carbon $start, Carbon $end): Collection;
+
+ // /**
+ // * Returns the total amount of money related to transactions without any category connected to
+ // * it. Returns either the earned amount.
+ // *
+ // * @param Collection $accounts
+ // * @param Carbon $start
+ // * @param Carbon $end
+ // *
+ // * @return string
+ // */
+ // public function sumEarnedNoCategory(Collection $accounts, Carbon $start, Carbon $end): string;
+
+ // /**
+ // * Returns the total amount of money related to transactions without any category connected to
+ // * it. Returns either the spent amount.
+ // *
+ // * @param Collection $accounts
+ // * @param Carbon $start
+ // * @param Carbon $end
+ // *
+ // * @return string
+ // */
+ // public function sumSpentNoCategory(Collection $accounts, Carbon $start, Carbon $end): string;
+
+
+ // /**
+ // * @param Category $category
+ // * @param Carbon|null $start
+ // * @param Carbon|null $end
+ // *
+ // * @return int
+ // */
+ // public function countJournals(Category $category, Carbon $start = null, Carbon $end = null): int;
+
+ /**
+ * @param Collection $categories
+ * @param Collection $accounts
+ * @param Carbon $start
+ * @param Carbon $end
+ *
+ * @return string
+ */
+ public function earnedInPeriod(Collection $categories, Collection $accounts, Carbon $start, Carbon $end): string;
+
+ // /**
+ // * Returns an array with the following key:value pairs:
+ // *
+ // * yyyy-mm-dd:<amount>
+ // *
+ // * Where yyyy-mm-dd is the date and <amount> is the money earned using DEPOSITS in the $category
+ // * from all the users accounts.
+ // *
+ // * @param Category $category
+ // * @param Carbon $start
+ // * @param Carbon $end
+ // * @param Collection $accounts
+ // *
+ // * @return array
+ // */
+ // public function earnedPerDay(Category $category, Carbon $start, Carbon $end, Collection $accounts): array;
+
/**
- * Returns a collection of Categories appended with the amount of money that has been earned
- * in these categories, based on the $accounts involved, in period X, grouped per month.
- * The amount earned in category X in period X is saved in field "earned".
+ * Find a category
*
- * @param $accounts
- * @param $start
- * @param $end
+ * @param int $categoryId
*
- * @return Collection
+ * @return Category
*/
- public function earnedForAccountsPerMonth(Collection $accounts, Carbon $start, Carbon $end): Collection;
+ public function find(int $categoryId) : Category;
+
+ // /**
+ // * @param Category $category
+ // *
+ // * @return Carbon
+ // */
+
+ /**
+ * @param Category $category
+ * @param Collection $accounts
+ *
+ * @return Carbon
+ */
+ public function firstUseDate(Category $category, Collection $accounts): Carbon;
/**
* Returns a list of all the categories belonging to a user.
@@ -36,67 +169,119 @@ interface CategoryRepositoryInterface
public function getCategories(): Collection;
/**
- * This method returns a very special collection for each category:
- *
- * category, year, expense/earned, amount
- *
- * categories can be duplicated.
+ * @param Category $category
+ * @param int $page
+ * @param int $pageSize
*
+ * @return LengthAwarePaginator
+ */
+ public function getJournals(Category $category, int $page, int $pageSize): LengthAwarePaginator;
+
+ /**
* @param Collection $categories
* @param Collection $accounts
+ * @param array $types
* @param Carbon $start
* @param Carbon $end
*
* @return Collection
*/
- public function listMultiYear(Collection $categories, Collection $accounts, Carbon $start, Carbon $end): Collection;
+ public function journalsInPeriod(Collection $categories, Collection $accounts, array $types, Carbon $start, Carbon $end): Collection;
/**
- * Returns a list of transaction journals in the range (all types, all accounts) that have no category
- * associated to them.
- *
- * @param Carbon $start
- * @param Carbon $end
+ * @param Collection $accounts
+ * @param Carbon $start
+ * @param Carbon $end
*
* @return Collection
*/
- public function listNoCategory(Carbon $start, Carbon $end): Collection;
+ public function journalsInPeriodWithoutCategory(Collection $accounts, Carbon $start, Carbon $end) : Collection;
/**
- * Returns a collection of Categories appended with the amount of money that has been spent
- * in these categories, based on the $accounts involved, in period X, grouped per month.
- * The amount earned in category X in period X is saved in field "spent".
- *
- * @param $accounts
- * @param $start
- * @param $end
+ * @param Category $category
+ * @param Collection $accounts
*
- * @return Collection
+ * @return Carbon
*/
- public function spentForAccountsPerMonth(Collection $accounts, Carbon $start, Carbon $end): Collection;
+ public function lastUseDate(Category $category, Collection $accounts): Carbon;
/**
- * Returns the total amount of money related to transactions without any category connected to
- * it. Returns either the earned amount.
- *
+ * @param Collection $categories
* @param Collection $accounts
* @param Carbon $start
* @param Carbon $end
*
* @return string
*/
- public function sumEarnedNoCategory(Collection $accounts, Carbon $start, Carbon $end): string;
+ public function spentInPeriod(Collection $categories, Collection $accounts, Carbon $start, Carbon $end): string;
+ // /**
+ // * @param Category $category
+ // * @param int $page
+ // * @param int $pageSize
+ // *
+ // * @return Collection
+ // */
+ // public function getJournals(Category $category, int $page, int $pageSize = 50): Collection;
+
+ // /**
+ // * @param Category $category
+ // * @param Collection $accounts
+ // *
+ // * @param Carbon $start
+ // * @param Carbon $end
+ // *
+ // * @return Collection
+ // */
+ // public function getJournalsForAccountsInRange(Category $category, Collection $accounts, Carbon $start, Carbon $end): Collection;
+
+ // /**
+ // * @param Category $category
+ // * @param Carbon $start
+ // * @param Carbon $end
+ // * @param int $page
+ // * @param int $pageSize
+ // *
+ // *
+ // * @return Collection
+ // */
+ // public function getJournalsInRange(Category $category, Carbon $start, Carbon $end, int $page, int $pageSize = 50): Collection;
+
+ // /**
+ // * @param Category $category
+ // *
+ // * @return Carbon
+ // */
+ // public function getLatestActivity(Category $category): Carbon;
+
+ // /**
+ // * Returns an array with the following key:value pairs:
+ // *
+ // * yyyy-mm-dd:<amount>
+ // *
+ // * Where yyyy-mm-dd is the date and <amount> is the money spent using WITHDRAWALS in the $category
+ // * from all the users accounts.
+ // *
+ // * @param Category $category
+ // * @param Carbon $start
+ // * @param Carbon $end
+ // * @param Collection $accounts
+ // *
+ // * @return array
+ // */
+ // public function spentPerDay(Category $category, Carbon $start, Carbon $end, Collection $accounts): array;
/**
- * Returns the total amount of money related to transactions without any category connected to
- * it. Returns either the spent amount.
+ * @param array $data
*
- * @param Collection $accounts
- * @param Carbon $start
- * @param Carbon $end
- *
- * @return string
+ * @return Category
*/
- public function sumSpentNoCategory(Collection $accounts, Carbon $start, Carbon $end): string;
+ public function store(array $data): Category;
+ /**
+ * @param Category $category
+ * @param array $data
+ *
+ * @return Category
+ */
+ public function update(Category $category, array $data): Category;
}
diff --git a/app/Repositories/Category/SingleCategoryRepository.php b/app/Repositories/Category/SingleCategoryRepository.php
deleted file mode 100644
index 7918ceac72..0000000000
--- a/app/Repositories/Category/SingleCategoryRepository.php
+++ /dev/null
@@ -1,322 +0,0 @@
-<?php
-declare(strict_types = 1);
-
-namespace FireflyIII\Repositories\Category;
-
-use Carbon\Carbon;
-use DB;
-use FireflyIII\Models\Category;
-use FireflyIII\Models\TransactionJournal;
-use FireflyIII\Models\TransactionType;
-use FireflyIII\Repositories\Shared\ComponentRepository;
-use FireflyIII\User;
-use Illuminate\Database\Query\JoinClause;
-use Illuminate\Support\Collection;
-
-/**
- * Class SingleCategoryRepository
- *
- * @package FireflyIII\Repositories\Category
- */
-class SingleCategoryRepository extends ComponentRepository implements SingleCategoryRepositoryInterface
-{
- /** @var User */
- private $user;
-
- /**
- * SingleCategoryRepository constructor.
- *
- * @param User $user
- */
- public function __construct(User $user)
- {
- $this->user = $user;
- }
-
- /**
- * @param Category $category
- * @param Carbon|null $start
- * @param Carbon|null $end
- *
- * @return int
- */
- public function countJournals(Category $category, Carbon $start = null, Carbon $end = null): int
- {
- $query = $category->transactionjournals();
- if (!is_null($start)) {
- $query->after($start);
- }
- if (!is_null($end)) {
- $query->before($end);
- }
-
- return $query->count();
-
- }
-
- /**
- * @param Category $category
- *
- * @return bool
- */
- public function destroy(Category $category): bool
- {
- $category->delete();
-
- return true;
- }
-
- /**
- * Returns an array with the following key:value pairs:
- *
- * yyyy-mm-dd:<amount>
- *
- * Where yyyy-mm-dd is the date and <amount> is the money earned using DEPOSITS in the $category
- * from all the users $accounts.
- *
- * @param Category $category
- * @param Carbon $start
- * @param Carbon $end
- * @param Collection $accounts
- *
- * @return array
- */
- public function earnedPerDay(Category $category, Carbon $start, Carbon $end, Collection $accounts): array
- {
- /** @var Collection $query */
- $query = $category->transactionjournals()
- ->expanded()
- ->transactionTypes([TransactionType::DEPOSIT])
- ->before($end)
- ->after($start)
- ->groupBy('transaction_journals.date');
-
- $query->leftJoin(
- 'transactions as destination', function (JoinClause $join) {
- $join->on('destination.transaction_journal_id', '=', 'transaction_journals.id')->where('destination.amount', '>', 0);
- }
- );
-
-
- if ($accounts->count() > 0) {
- $ids = $accounts->pluck('id')->toArray();
- $query->whereIn('destination.account.id', $ids);
- }
-
- $result = $query->get(['transaction_journals.date as dateFormatted', DB::raw('SUM(`destination`.`amount`) AS `sum`')]);
-
- $return = [];
- foreach ($result->toArray() as $entry) {
- $return[$entry['dateFormatted']] = $entry['sum'];
- }
-
- return $return;
- }
-
- /**
- * Find a category
- *
- * @param int $categoryId
- *
- * @return Category
- */
- public function find(int $categoryId) : Category
- {
- $category = $this->user->categories()->find($categoryId);
- if (is_null($category)) {
- $category = new Category;
- }
-
- return $category;
- }
-
- /**
- * @param Category $category
- *
- * @return Carbon
- */
- public function getFirstActivityDate(Category $category): Carbon
- {
- /** @var TransactionJournal $first */
- $first = $category->transactionjournals()->orderBy('date', 'ASC')->first();
- if ($first) {
- return $first->date;
- }
-
- return new Carbon;
-
- }
-
- /**
- * @param Category $category
- * @param int $page
- * @param int $pageSize
- *
- * @return Collection
- */
- public function getJournals(Category $category, int $page, int $pageSize = 50): Collection
- {
- $offset = $page > 0 ? $page * $pageSize : 0;
-
- return $category->transactionjournals()->expanded()->take($pageSize)->offset($offset)->get(TransactionJournal::queryFields());
-
- }
-
- /**
- * @param Category $category
- * @param Collection $accounts
- *
- * @param Carbon $start
- * @param Carbon $end
- *
- * @return Collection
- */
- public function getJournalsForAccountsInRange(Category $category, Collection $accounts, Carbon $start, Carbon $end): Collection
- {
- $ids = $accounts->pluck('id')->toArray();
-
- return $category->transactionjournals()
- ->after($start)
- ->before($end)
- ->expanded()
- ->whereIn('source_account.id', $ids)
- ->whereNotIn('destination_account.id', $ids)
- ->get(TransactionJournal::queryFields());
- }
-
- /**
- * @param Category $category
- * @param Carbon $start
- * @param Carbon $end
- * @param int $page
- * @param int $pageSize
- *
- *
- * @return Collection
- */
- public function getJournalsInRange(Category $category, Carbon $start, Carbon $end, int $page, int $pageSize = 50): Collection
- {
- $offset = $page > 0 ? $page * $pageSize : 0;
-
- return $category->transactionjournals()
- ->after($start)
- ->before($end)
- ->expanded()
- ->take($pageSize)
- ->offset($offset)
- ->get(TransactionJournal::queryFields());
- }
-
- /**
- * @param Category $category
- *
- * @return Carbon
- */
- public function getLatestActivity(Category $category): Carbon
- {
- $first = new Carbon('1900-01-01');
- $second = new Carbon('1900-01-01');
- $latest = $category->transactionjournals()
- ->orderBy('transaction_journals.date', 'DESC')
- ->orderBy('transaction_journals.order', 'ASC')
- ->orderBy('transaction_journals.id', 'DESC')
- ->first();
- if ($latest) {
- $first = $latest->date;
- }
-
- // could also be a transaction, nowadays:
- $latestTransaction = $category->transactions()
- ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id')
- ->orderBy('transaction_journals.date', 'DESC')
- ->orderBy('transaction_journals.order', 'ASC')
- ->orderBy('transaction_journals.id', 'DESC')
- ->first(['transactions.*', 'transaction_journals.date']);
- if ($latestTransaction) {
- $second = new Carbon($latestTransaction->date);
- }
- if ($first > $second) {
- return $first;
- }
-
- return $second;
- }
-
- /**
- * Returns an array with the following key:value pairs:
- *
- * yyyy-mm-dd:<amount>
- *
- * Where yyyy-mm-dd is the date and <amount> is the money spent using DEPOSITS in the $category
- * from all the users accounts.
- *
- * @param Category $category
- * @param Carbon $start
- * @param Carbon $end
- * @param Collection $accounts
- *
- * @return array
- */
- public function spentPerDay(Category $category, Carbon $start, Carbon $end, Collection $accounts): array
- {
- /** @var Collection $query */
- $query = $category->transactionjournals()
- ->expanded()
- ->transactionTypes([TransactionType::WITHDRAWAL])
- ->before($end)
- ->after($start)
- ->groupBy('transaction_journals.date');
- $query->leftJoin(
- 'transactions as source', function (JoinClause $join) {
- $join->on('source.transaction_journal_id', '=', 'transaction_journals.id')->where('source.amount', '<', 0);
- }
- );
-
- if ($accounts->count() > 0) {
- $ids = $accounts->pluck('id')->toArray();
- $query->whereIn('source.account_id', $ids);
- }
-
- $result = $query->get(['transaction_journals.date as dateFormatted', DB::raw('SUM(`source`.`amount`) AS `sum`')]);
-
- $return = [];
- foreach ($result->toArray() as $entry) {
- $return[$entry['dateFormatted']] = $entry['sum'];
- }
-
- return $return;
- }
-
- /**
- * @param array $data
- *
- * @return Category
- */
- public function store(array $data): Category
- {
- $newCategory = Category::firstOrCreateEncrypted(
- [
- 'user_id' => $data['user'],
- 'name' => $data['name'],
- ]
- );
- $newCategory->save();
-
- return $newCategory;
- }
-
- /**
- * @param Category $category
- * @param array $data
- *
- * @return Category
- */
- public function update(Category $category, array $data): Category
- {
- // update the account:
- $category->name = $data['name'];
- $category->save();
-
- return $category;
- }
-}
diff --git a/app/Repositories/Category/SingleCategoryRepositoryInterface.php b/app/Repositories/Category/SingleCategoryRepositoryInterface.php
deleted file mode 100644
index 0aa59aa5e0..0000000000
--- a/app/Repositories/Category/SingleCategoryRepositoryInterface.php
+++ /dev/null
@@ -1,138 +0,0 @@
-<?php
-declare(strict_types = 1);
-
-namespace FireflyIII\Repositories\Category;
-
-use Carbon\Carbon;
-use FireflyIII\Models\Category;
-use Illuminate\Support\Collection;
-
-/**
- * Interface SingleCategoryRepositoryInterface
- *
- * @package FireflyIII\Repositories\Category
- */
-interface SingleCategoryRepositoryInterface
-{
-
- /**
- * @param Category $category
- * @param Carbon|null $start
- * @param Carbon|null $end
- *
- * @return int
- */
- public function countJournals(Category $category, Carbon $start = null, Carbon $end = null): int;
-
- /**
- * @param Category $category
- *
- * @return bool
- */
- public function destroy(Category $category): bool;
-
- /**
- * Returns an array with the following key:value pairs:
- *
- * yyyy-mm-dd:<amount>
- *
- * Where yyyy-mm-dd is the date and <amount> is the money earned using DEPOSITS in the $category
- * from all the users accounts.
- *
- * @param Category $category
- * @param Carbon $start
- * @param Carbon $end
- * @param Collection $accounts
- *
- * @return array
- */
- public function earnedPerDay(Category $category, Carbon $start, Carbon $end, Collection $accounts): array;
-
- /**
- * Find a category
- *
- * @param int $categoryId
- *
- * @return Category
- */
- public function find(int $categoryId) : Category;
-
- /**
- * @param Category $category
- *
- * @return Carbon
- */
- public function getFirstActivityDate(Category $category): Carbon;
-
- /**
- * @param Category $category
- * @param int $page
- * @param int $pageSize
- *
- * @return Collection
- */
- public function getJournals(Category $category, int $page, int $pageSize = 50): Collection;
-
- /**
- * @param Category $category
- * @param Collection $accounts
- *
- * @param Carbon $start
- * @param Carbon $end
- *
- * @return Collection
- */
- public function getJournalsForAccountsInRange(Category $category, Collection $accounts, Carbon $start, Carbon $end): Collection;
-
- /**
- * @param Category $category
- * @param Carbon $start
- * @param Carbon $end
- * @param int $page
- * @param int $pageSize
- *
- *
- * @return Collection
- */
- public function getJournalsInRange(Category $category, Carbon $start, Carbon $end, int $page, int $pageSize = 50): Collection;
-
- /**
- * @param Category $category
- *
- * @return Carbon
- */
- public function getLatestActivity(Category $category): Carbon;
-
- /**
- * Returns an array with the following key:value pairs:
- *
- * yyyy-mm-dd:<amount>
- *
- * Where yyyy-mm-dd is the date and <amount> is the money spent using WITHDRAWALS in the $category
- * from all the users accounts.
- *
- * @param Category $category
- * @param Carbon $start
- * @param Carbon $end
- * @param Collection $accounts
- *
- * @return array
- */
- public function spentPerDay(Category $category, Carbon $start, Carbon $end, Collection $accounts): array;
-
-
- /**
- * @param array $data
- *
- * @return Category
- */
- public function store(array $data): Category;
-
- /**
- * @param Category $category
- * @param array $data
- *
- * @return Category
- */
- public function update(Category $category, array $data): Category;
-}