/** * Returns a chart of what has been spent in this period in each category * grouped by month. * * @param CRI $repository * @param $reportType * @param Carbon $start * @param Carbon $end * @param Collection $accounts * * @return \Illuminate\Http\JsonResponse */ 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); $cache->addProperty($reportType); $cache->addProperty($accounts); $cache->addProperty('category'); $cache->addProperty('spent-in-period'); if ($cache->has()) { return Response::json($cache->get()); // @codeCoverageIgnore } $set = $repository->spentForAccountsPerMonth($accounts, $start, $end); $categories = $set->unique('id')->sortBy(function (Category $category) { return $category->name; }); $entries = new Collection(); while ($start < $end) { // filter the set: $row = [clone $start]; // get possibly relevant entries from the big $set $currentSet = $set->filter(function (Category $category) use($start) { return $category->dateFormatted == $start->format("Y-m"); }); // check for each category if its in the current set. /** @var Category $category */ foreach ($categories as $category) { // if its in there, use the value. $entry = $currentSet->filter(function (Category $cat) use($category) { return $cat->id == $category->id; })->first(); if (!is_null($entry)) { $row[] = round($entry->spent * -1, 2); } else { $row[] = 0; } } $entries->push($row); $start->addMonth(); } $data = $this->generator->spentInPeriod($categories, $entries); $cache->store($data); return $data; }