GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Passed
Push — master ( 37b02e...ebbbe1 )
by James
08:59
created

app/Http/Controllers/BudgetController.php (2 issues)

Severity
1
<?php
2
/**
3
 * BudgetController.php
4
 * Copyright (c) 2017 [email protected]
5
 *
6
 * This file is part of Firefly III.
7
 *
8
 * Firefly III is free software: you can redistribute it and/or modify
9
 * it under the terms of the GNU General Public License as published by
10
 * the Free Software Foundation, either version 3 of the License, or
11
 * (at your option) any later version.
12
 *
13
 * Firefly III is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
 * GNU General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU General Public License
19
 * along with Firefly III. If not, see <http://www.gnu.org/licenses/>.
20
 */
21
declare(strict_types=1);
22
23
namespace FireflyIII\Http\Controllers;
24
25
use Carbon\Carbon;
26
use Exception;
27
use FireflyIII\Exceptions\FireflyException;
28
use FireflyIII\Helpers\Collector\JournalCollectorInterface;
29
use FireflyIII\Http\Requests\BudgetFormRequest;
30
use FireflyIII\Http\Requests\BudgetIncomeRequest;
31
use FireflyIII\Models\Budget;
32
use FireflyIII\Models\BudgetLimit;
33
use FireflyIII\Models\TransactionType;
34
use FireflyIII\Repositories\Budget\BudgetRepositoryInterface;
35
use FireflyIII\Repositories\Journal\JournalRepositoryInterface;
36
use FireflyIII\Support\CacheProperties;
37
use Illuminate\Http\Request;
38
use Illuminate\Pagination\LengthAwarePaginator;
39
use Illuminate\Support\Collection;
40
use Log;
41
use Preferences;
42
use View;
43
44
/**
45
 * Class BudgetController.
46
 *
47
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
48
 * @SuppressWarnings(PHPMD.TooManyPublicMethods)
49
 */
50
class BudgetController extends Controller
51
{
52
    /** @var BudgetRepositoryInterface */
53
    private $repository;
54
55
    /**
56
     *
57
     */
58
    public function __construct()
59
    {
60
        parent::__construct();
61
62
        View::share('hideBudgets', true);
63
64
        $this->middleware(
65
            function ($request, $next) {
66
                app('view')->share('title', trans('firefly.budgets'));
67
                app('view')->share('mainTitleIcon', 'fa-tasks');
68
                $this->repository = app(BudgetRepositoryInterface::class);
69
70
                return $next($request);
71
            }
72
        );
73
    }
74
75
    /**
76
     * @param Request                   $request
77
     * @param BudgetRepositoryInterface $repository
78
     * @param Budget                    $budget
79
     *
80
     * @return \Illuminate\Http\JsonResponse
81
     */
82
    public function amount(Request $request, BudgetRepositoryInterface $repository, Budget $budget)
83
    {
84
        $amount      = (string)$request->get('amount');
85
        $start       = Carbon::createFromFormat('Y-m-d', $request->get('start'));
86
        $end         = Carbon::createFromFormat('Y-m-d', $request->get('end'));
87
        $budgetLimit = $this->repository->updateLimitAmount($budget, $start, $end, $amount);
88
        $largeDiff   = false;
89
        $warnText    = '';
90
        $average     = '0';
91
        $current     = '0';
92
        if (0 === bccomp($amount, '0')) {
93
            $budgetLimit = null;
94
        }
95
96
        // calculate left in budget:
97
        $spent    = $repository->spentInPeriod(new Collection([$budget]), new Collection, $start, $end);
98
        $currency = app('amount')->getDefaultCurrency();
99
        $left     = app('amount')->formatAnything($currency, bcadd($amount, $spent), true);
100
101
102
        // over or under budgeting, compared to previous budgets?
103
        $average = $this->repository->budgetedPerDay($budget);
104
        // current average per day:
105
        $diff    = $start->diffInDays($end);
106
        $current = $amount;
107
        if ($diff > 0) {
108
            $current = bcdiv($amount, (string)$diff);
109
        }
110
        if (bccomp(bcmul('1.1', $average), $current) === -1) {
111
            $largeDiff = true;
112
            $warnText  = (string)trans(
113
                'firefly.over_budget_warn',
114
                [
115
                    'amount'      => app('amount')->formatAnything($currency, $average, false),
116
                    'over_amount' => app('amount')->formatAnything($currency, $current, false),
117
                ]
118
            );
119
        }
120
121
        Preferences::mark();
122
123
        return response()->json(
124
            [
125
                'left'       => $left,
126
                'name'       => $budget->name,
127
                'limit'      => $budgetLimit ? $budgetLimit->id : 0,
128
                'amount'     => $amount,
129
                'current'    => $current,
130
                'average'    => $average,
131
                'large_diff' => $largeDiff,
132
                'warn_text'  => $warnText,
133
134
            ]
135
        );
136
    }
137
138
    /**
139
     * @param Request $request
140
     *
141
     * @return View
142
     */
143
    public function create(Request $request)
144
    {
145
        // put previous url in session if not redirect from store (not "create another").
146
        if (true !== session('budgets.create.fromStore')) {
147
            $this->rememberPreviousUri('budgets.create.uri');
148
        }
149
        $request->session()->forget('budgets.create.fromStore');
150
        $subTitle = (string)trans('firefly.create_new_budget');
151
152
        return view('budgets.create', compact('subTitle'));
153
    }
154
155
    /**
156
     * @param Budget $budget
157
     *
158
     * @return View
159
     */
160
    public function delete(Budget $budget)
161
    {
162
        $subTitle = trans('firefly.delete_budget', ['name' => $budget->name]);
163
164
        // put previous url in session
165
        $this->rememberPreviousUri('budgets.delete.uri');
166
167
        return view('budgets.delete', compact('budget', 'subTitle'));
168
    }
169
170
    /**
171
     * @param Request $request
172
     * @param Budget  $budget
173
     *
174
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
175
     */
176
    public function destroy(Request $request, Budget $budget)
177
    {
178
        $name = $budget->name;
179
        $this->repository->destroy($budget);
180
        $request->session()->flash('success', (string)trans('firefly.deleted_budget', ['name' => $name]));
181
        Preferences::mark();
182
183
        return redirect($this->getPreviousUri('budgets.delete.uri'));
184
    }
185
186
    /**
187
     * @param Request $request
188
     * @param Budget  $budget
189
     *
190
     * @return View
191
     */
192
    public function edit(Request $request, Budget $budget)
193
    {
194
        $subTitle = trans('firefly.edit_budget', ['name' => $budget->name]);
195
196
        // put previous url in session if not redirect from store (not "return_to_edit").
197
        if (true !== session('budgets.edit.fromUpdate')) {
198
            $this->rememberPreviousUri('budgets.edit.uri');
199
        }
200
        $request->session()->forget('budgets.edit.fromUpdate');
201
202
        return view('budgets.edit', compact('budget', 'subTitle'));
203
    }
204
205
    /**
206
     * @param Request     $request
207
     * @param string|null $moment
208
     *
209
     * @return View
210
     *
211
     * @SuppressWarnings(PHPMD.CyclomaticComplexity) complex because of while loop
212
     * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
213
     */
214
    public function index(Request $request, string $moment = null)
215
    {
216
        $range    = Preferences::get('viewRange', '1M')->data;
217
        $start    = session('start', new Carbon);
218
        $end      = session('end', new Carbon);
219
        $page     = 0 === (int)$request->get('page') ? 1 : (int)$request->get('page');
220
        $pageSize = (int)Preferences::get('listPageSize', 50)->data;
221
222
        // make date if present:
223
        if (null !== $moment || '' !== (string)$moment) {
224
            try {
225
                $start = new Carbon($moment);
226
                $end   = app('navigation')->endOfPeriod($start, $range);
227
            } catch (Exception $e) {
228
                // start and end are already defined.
229
                Log::debug('start and end are already defined.');
230
            }
231
        }
232
        $next = clone $end;
233
        $next->addDay();
234
        $prev = clone $start;
235
        $prev->subDay();
236
        $prev = app('navigation')->startOfPeriod($prev, $range);
237
        $this->repository->cleanupBudgets();
238
        $allBudgets        = $this->repository->getActiveBudgets();
239
        $total             = $allBudgets->count();
240
        $budgets           = $allBudgets->slice(($page - 1) * $pageSize, $pageSize);
241
        $inactive          = $this->repository->getInactiveBudgets();
242
        $periodStart       = $start->formatLocalized($this->monthAndDayFormat);
243
        $periodEnd         = $end->formatLocalized($this->monthAndDayFormat);
244
        $budgetInformation = $this->repository->collectBudgetInformation($allBudgets, $start, $end);
245
        $defaultCurrency   = app('amount')->getDefaultCurrency();
246
        $available         = $this->repository->getAvailableBudget($defaultCurrency, $start, $end);
247
        $spent             = array_sum(array_column($budgetInformation, 'spent'));
248
        $budgeted          = array_sum(array_column($budgetInformation, 'budgeted'));
249
250
        // paginate budgets
251
        $budgets = new LengthAwarePaginator($budgets, $total, $pageSize, $page);
252
        $budgets->setPath(route('budgets.index'));
253
254
        // select thing for last 12 periods:
255
        $previousLoop = [];
256
        $previousDate = clone $start;
257
        $count        = 0;
258
        while ($count < 12) {
259
            $previousDate->subDay();
260
            $previousDate          = app('navigation')->startOfPeriod($previousDate, $range);
261
            $format                = $previousDate->format('Y-m-d');
262
            $previousLoop[$format] = app('navigation')->periodShow($previousDate, $range);
263
            ++$count;
264
        }
265
266
        // select thing for next 12 periods:
267
        $nextLoop = [];
268
        $nextDate = clone $end;
269
        $nextDate->addDay();
270
        $count = 0;
271
272
        while ($count < 12) {
273
            $format            = $nextDate->format('Y-m-d');
274
            $nextLoop[$format] = app('navigation')->periodShow($nextDate, $range);
275
            $nextDate          = app('navigation')->endOfPeriod($nextDate, $range);
276
            ++$count;
277
            $nextDate->addDay();
278
        }
279
280
        // display info
281
        $currentMonth = app('navigation')->periodShow($start, $range);
282
        $nextText     = app('navigation')->periodShow($next, $range);
283
        $prevText     = app('navigation')->periodShow($prev, $range);
284
285
        return view(
286
            'budgets.index',
287
            compact(
288
                'available',
289
                'currentMonth',
290
                'next',
291
                'nextText',
292
                'prev', 'allBudgets',
293
                'prevText',
294
                'periodStart',
295
                'periodEnd',
296
                'page',
297
                'budgetInformation',
298
                'inactive',
299
                'budgets',
300
                'spent',
301
                'budgeted',
302
                'previousLoop',
303
                'nextLoop',
304
                'start',
305
                'end'
306
            )
307
        );
308
    }
309
310
    /**
311
     * @param Carbon $start
312
     * @param Carbon $end
313
     * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
314
     *
315
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
316
     */
317
    public function infoIncome(Carbon $start, Carbon $end)
318
    {
319
        // properties for cache
320
        $cache = new CacheProperties;
321
        $cache->addProperty($start);
322
        $cache->addProperty($end);
323
        $cache->addProperty('info-income');
324
325
        Log::debug(sprintf('infoIncome start is %s', $start->format('Y-m-d')));
326
        Log::debug(sprintf('infoIncome end is %s', $end->format('Y-m-d')));
327
328
        if ($cache->has()) {
329
            // @codeCoverageIgnoreStart
330
            $result = $cache->get();
331
332
            return view('budgets.info', compact('result'));
333
            // @codeCoverageIgnoreEnd
334
        }
335
        $result   = [
336
            'available' => '0',
337
            'earned'    => '0',
338
            'suggested' => '0',
339
        ];
340
        $currency = app('amount')->getDefaultCurrency();
341
        $range    = Preferences::get('viewRange', '1M')->data;
342
        $begin    = app('navigation')->subtractPeriod($start, $range, 3);
343
344
        Log::debug(sprintf('Range is %s', $range));
345
        Log::debug(sprintf('infoIncome begin is %s', $begin->format('Y-m-d')));
346
347
        // get average amount available.
348
        $total        = '0';
349
        $count        = 0;
350
        $currentStart = clone $begin;
351
        while ($currentStart < $start) {
352
            Log::debug(sprintf('Loop: currentStart is %s', $currentStart->format('Y-m-d')));
353
            $currentEnd   = app('navigation')->endOfPeriod($currentStart, $range);
354
            $total        = bcadd($total, $this->repository->getAvailableBudget($currency, $currentStart, $currentEnd));
355
            $currentStart = app('navigation')->addPeriod($currentStart, $range, 0);
356
            ++$count;
357
        }
358
        Log::debug('Loop end');
359
360
        if (0 === $count) {
361
            $count = 1;
362
        }
363
        $result['available'] = bcdiv($total, (string)$count);
364
365
        // amount earned in this period:
366
        $subDay = clone $end;
367
        $subDay->subDay();
368
        /** @var JournalCollectorInterface $collector */
369
        $collector = app(JournalCollectorInterface::class);
370
        $collector->setAllAssetAccounts()->setRange($begin, $subDay)->setTypes([TransactionType::DEPOSIT])->withOpposingAccount();
371
        $result['earned'] = bcdiv((string)$collector->getJournals()->sum('transaction_amount'), (string)$count);
372
373
        // amount spent in period
374
        /** @var JournalCollectorInterface $collector */
375
        $collector = app(JournalCollectorInterface::class);
376
        $collector->setAllAssetAccounts()->setRange($begin, $subDay)->setTypes([TransactionType::WITHDRAWAL])->withOpposingAccount();
377
        $result['spent'] = bcdiv((string)$collector->getJournals()->sum('transaction_amount'), (string)$count);
378
        // suggestion starts with the amount spent
379
        $result['suggested'] = bcmul($result['spent'], '-1');
380
        $result['suggested'] = 1 === bccomp($result['suggested'], $result['earned']) ? $result['earned'] : $result['suggested'];
381
        // unless it's more than you earned. So min() of suggested/earned
382
383
        $cache->store($result);
384
385
        return view('budgets.info', compact('result', 'begin', 'currentEnd'));
386
    }
387
388
    /**
389
     * @param Request                    $request
390
     * @param JournalRepositoryInterface $repository
391
     * @param string                     $moment
392
     *
393
     * @return View
394
     *
395
     * @SuppressWarnings(PHPMD.CyclomaticComplexity)
396
     * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
397
     */
398
    public function noBudget(Request $request, JournalRepositoryInterface $repository, string $moment = '')
399
    {
400
        // default values:
401
        $range   = Preferences::get('viewRange', '1M')->data;
402
        $start   = null;
403
        $end     = null;
404
        $periods = new Collection;
405
406
        // prep for "all" view.
407
        if ('all' === $moment) {
408
            $subTitle = trans('firefly.all_journals_without_budget');
409
            $first    = $repository->first();
0 ignored issues
show
Deprecated Code introduced by
The function FireflyIII\Repositories\...itoryInterface::first() has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

409
            $first    = /** @scrutinizer ignore-deprecated */ $repository->first();
Loading history...
410
            $start    = $first->date ?? new Carbon;
411
            $end      = new Carbon;
412
        }
413
414
        // prep for "specific date" view.
415
        if (strlen($moment) > 0 && 'all' !== $moment) {
416
            $start    = new Carbon($moment);
417
            $end      = app('navigation')->endOfPeriod($start, $range);
418
            $subTitle = trans(
419
                'firefly.without_budget_between',
420
                ['start' => $start->formatLocalized($this->monthAndDayFormat), 'end' => $end->formatLocalized($this->monthAndDayFormat)]
421
            );
422
            $periods  = $this->getPeriodOverview();
423
        }
424
425
        // prep for current period
426
        if (0 === strlen($moment)) {
427
            $start    = clone session('start', app('navigation')->startOfPeriod(new Carbon, $range));
428
            $end      = clone session('end', app('navigation')->endOfPeriod(new Carbon, $range));
429
            $periods  = $this->getPeriodOverview();
430
            $subTitle = trans(
431
                'firefly.without_budget_between',
432
                ['start' => $start->formatLocalized($this->monthAndDayFormat), 'end' => $end->formatLocalized($this->monthAndDayFormat)]
433
            );
434
        }
435
436
        $page     = (int)$request->get('page');
437
        $pageSize = (int)Preferences::get('listPageSize', 50)->data;
438
439
        /** @var JournalCollectorInterface $collector */
440
        $collector = app(JournalCollectorInterface::class);
441
        $collector->setAllAssetAccounts()->setRange($start, $end)->setTypes([TransactionType::WITHDRAWAL])->setLimit($pageSize)->setPage($page)
442
                  ->withoutBudget()->withOpposingAccount();
443
        $transactions = $collector->getPaginatedJournals();
444
        $transactions->setPath(route('budgets.no-budget'));
445
446
        return view('budgets.no-budget', compact('transactions', 'subTitle', 'moment', 'periods', 'start', 'end'));
447
    }
448
449
    /**
450
     * @param BudgetIncomeRequest $request
451
     *
452
     * @return \Illuminate\Http\RedirectResponse
453
     */
454
    public function postUpdateIncome(BudgetIncomeRequest $request)
455
    {
456
        $start           = Carbon::createFromFormat('Y-m-d', $request->string('start'));
457
        $end             = Carbon::createFromFormat('Y-m-d', $request->string('end'));
458
        $defaultCurrency = app('amount')->getDefaultCurrency();
459
        $amount          = $request->get('amount');
460
        $page            = $request->integer('page') === 0 ? 1 : $request->integer('page');
461
        $this->repository->cleanupBudgets();
462
        $this->repository->setAvailableBudget($defaultCurrency, $start, $end, $amount);
463
        Preferences::mark();
464
465
        return redirect(route('budgets.index', [$start->format('Y-m-d')]) . '?page=' . $page);
466
    }
467
468
    /**
469
     * @param Request $request
470
     * @param Budget  $budget
471
     *
472
     * @return View
473
     */
474
    public function show(Request $request, Budget $budget)
475
    {
476
        /** @var Carbon $start */
477
        $start      = session('first', Carbon::create()->startOfYear());
478
        $end        = new Carbon;
479
        $page       = (int)$request->get('page');
480
        $pageSize   = (int)Preferences::get('listPageSize', 50)->data;
481
        $limits     = $this->getLimits($budget, $start, $end);
482
        $repetition = null;
483
484
        // collector:
485
        /** @var JournalCollectorInterface $collector */
486
        $collector = app(JournalCollectorInterface::class);
487
        $collector->setAllAssetAccounts()->setRange($start, $end)->setBudget($budget)->setLimit($pageSize)->setPage($page)->withBudgetInformation();
488
        $transactions = $collector->getPaginatedJournals();
489
        $transactions->setPath(route('budgets.show', [$budget->id]));
490
491
        $subTitle = trans('firefly.all_journals_for_budget', ['name' => $budget->name]);
492
493
        return view('budgets.show', compact('limits', 'budget', 'repetition', 'transactions', 'subTitle'));
494
    }
495
496
    /**
497
     * @param Request     $request
498
     * @param Budget      $budget
499
     * @param BudgetLimit $budgetLimit
500
     *
501
     * @return View
502
     *
503
     * @throws FireflyException
504
     */
505
    public function showByBudgetLimit(Request $request, Budget $budget, BudgetLimit $budgetLimit)
506
    {
507
        if ($budgetLimit->budget->id !== $budget->id) {
508
            throw new FireflyException('This budget limit is not part of this budget.');
509
        }
510
511
        $page     = (int)$request->get('page');
512
        $pageSize = (int)Preferences::get('listPageSize', 50)->data;
513
        $subTitle = trans(
514
            'firefly.budget_in_period',
515
            [
516
                'name'  => $budget->name,
517
                'start' => $budgetLimit->start_date->formatLocalized($this->monthAndDayFormat),
518
                'end'   => $budgetLimit->end_date->formatLocalized($this->monthAndDayFormat),
519
            ]
520
        );
521
522
        // collector:
523
        /** @var JournalCollectorInterface $collector */
524
        $collector = app(JournalCollectorInterface::class);
525
        $collector->setAllAssetAccounts()->setRange($budgetLimit->start_date, $budgetLimit->end_date)
526
                  ->setBudget($budget)->setLimit($pageSize)->setPage($page)->withBudgetInformation();
527
        $transactions = $collector->getPaginatedJournals();
528
        $transactions->setPath(route('budgets.show', [$budget->id, $budgetLimit->id]));
529
        $start  = session('first', Carbon::create()->startOfYear());
530
        $end    = new Carbon;
531
        $limits = $this->getLimits($budget, $start, $end);
532
533
        return view('budgets.show', compact('limits', 'budget', 'budgetLimit', 'transactions', 'subTitle'));
534
    }
535
536
    /**
537
     * @param BudgetFormRequest $request
538
     *
539
     * @return \Illuminate\Http\RedirectResponse
540
     */
541
    public function store(BudgetFormRequest $request)
542
    {
543
        $data   = $request->getBudgetData();
544
        $budget = $this->repository->store($data);
545
        $this->repository->cleanupBudgets();
546
        $request->session()->flash('success', (string)trans('firefly.stored_new_budget', ['name' => $budget->name]));
547
        Preferences::mark();
548
549
        if (1 === (int)$request->get('create_another')) {
550
            // @codeCoverageIgnoreStart
551
            $request->session()->put('budgets.create.fromStore', true);
552
553
            return redirect(route('budgets.create'))->withInput();
554
            // @codeCoverageIgnoreEnd
555
        }
556
557
        return redirect($this->getPreviousUri('budgets.create.uri'));
558
    }
559
560
    /**
561
     * @param BudgetFormRequest $request
562
     * @param Budget            $budget
563
     *
564
     * @return \Illuminate\Http\RedirectResponse
565
     */
566
    public function update(BudgetFormRequest $request, Budget $budget)
567
    {
568
        $data = $request->getBudgetData();
569
        $this->repository->update($budget, $data);
570
571
        $request->session()->flash('success', (string)trans('firefly.updated_budget', ['name' => $budget->name]));
572
        $this->repository->cleanupBudgets();
573
        Preferences::mark();
574
575
        if (1 === (int)$request->get('return_to_edit')) {
576
            // @codeCoverageIgnoreStart
577
            $request->session()->put('budgets.edit.fromUpdate', true);
578
579
            return redirect(route('budgets.edit', [$budget->id]))->withInput(['return_to_edit' => 1]);
580
            // @codeCoverageIgnoreEnd
581
        }
582
583
        return redirect($this->getPreviousUri('budgets.edit.uri'));
584
    }
585
586
    /**
587
     * @param Request $request
588
     * @param Carbon  $start
589
     * @param Carbon  $end
590
     *
591
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
592
     */
593
    public function updateIncome(Request $request, Carbon $start, Carbon $end)
594
    {
595
        $defaultCurrency = app('amount')->getDefaultCurrency();
596
        $available       = $this->repository->getAvailableBudget($defaultCurrency, $start, $end);
597
        $available       = round($available, $defaultCurrency->decimal_places);
598
        $page            = (int)$request->get('page');
599
600
        return view('budgets.income', compact('available', 'start', 'end', 'page'));
601
    }
602
603
    /**
604
     * @param Budget $budget
605
     * @param Carbon $start
606
     * @param Carbon $end
607
     *
608
     * @return Collection
609
     */
610
    private function getLimits(Budget $budget, Carbon $start, Carbon $end): Collection
611
    {
612
        // properties for cache
613
        $cache = new CacheProperties;
614
        $cache->addProperty($start);
615
        $cache->addProperty($end);
616
        $cache->addProperty($budget->id);
617
        $cache->addProperty('get-limits');
618
619
        if ($cache->has()) {
620
            return $cache->get(); // @codeCoverageIgnore
621
        }
622
623
        $set    = $this->repository->getBudgetLimits($budget, $start, $end);
624
        $limits = new Collection();
625
626
        /** @var BudgetLimit $entry */
627
        foreach ($set as $entry) {
628
            $entry->spent = $this->repository->spentInPeriod(new Collection([$budget]), new Collection(), $entry->start_date, $entry->end_date);
629
            $limits->push($entry);
630
        }
631
        $cache->store($limits);
632
633
        return $set;
634
    }
635
636
    /**
637
     * @return Collection
638
     */
639
    private function getPeriodOverview(): Collection
640
    {
641
        $repository = app(JournalRepositoryInterface::class);
642
        $first      = $repository->first();
0 ignored issues
show
Deprecated Code introduced by
The function FireflyIII\Repositories\...itoryInterface::first() has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

642
        $first      = /** @scrutinizer ignore-deprecated */ $repository->first();
Loading history...
643
        $start      = $first->date ?? new Carbon;
644
        $range      = Preferences::get('viewRange', '1M')->data;
645
        $start      = app('navigation')->startOfPeriod($start, $range);
646
        $end        = app('navigation')->endOfX(new Carbon, $range, null);
647
        $entries    = new Collection;
648
        $cache      = new CacheProperties;
649
        $cache->addProperty($start);
650
        $cache->addProperty($end);
651
        $cache->addProperty('no-budget-period-entries');
652
653
        if ($cache->has()) {
654
            return $cache->get(); // @codeCoverageIgnore
655
        }
656
        $dates = app('navigation')->blockPeriods($start, $end, $range);
657
        foreach ($dates as $date) {
658
            /** @var JournalCollectorInterface $collector */
659
            $collector = app(JournalCollectorInterface::class);
660
            $collector->setAllAssetAccounts()->setRange($date['start'], $date['end'])->withoutBudget()->withOpposingAccount()->setTypes(
661
                [TransactionType::WITHDRAWAL]
662
            );
663
            $set      = $collector->getJournals();
664
            $sum      = (string)($set->sum('transaction_amount') ?? '0');
665
            $journals = $set->count();
666
            $dateStr  = $date['end']->format('Y-m-d');
667
            $dateName = app('navigation')->periodShow($date['end'], $date['period']);
668
            $entries->push(['string' => $dateStr, 'name' => $dateName, 'count' => $journals, 'sum' => $sum, 'date' => clone $date['end']]);
669
        }
670
        $cache->store($entries);
671
672
        return $entries;
673
    }
674
}
675