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 ( 6f8b1f...142a48 )
by James
25:51 queued 11:45
created

app/Api/V1/Controllers/Chart/AccountController.php (1 issue)

Severity
1
<?php
2
3
/**
4
 * AccountController.php
5
 * Copyright (c) 2019 [email protected]
6
 *
7
 * This file is part of Firefly III.
8
 *
9
 * Firefly III is free software: you can redistribute it and/or modify
10
 * it under the terms of the GNU General Public License as published by
11
 * the Free Software Foundation, either version 3 of the License, or
12
 * (at your option) any later version.
13
 *
14
 * Firefly III is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
 * GNU General Public License for more details.
18
 *
19
 * You should have received a copy of the GNU General Public License
20
 * along with Firefly III. If not, see <http://www.gnu.org/licenses/>.
21
 */
22
23
declare(strict_types=1);
24
25
namespace FireflyIII\Api\V1\Controllers\Chart;
26
27
use Carbon\Carbon;
28
use FireflyIII\Api\V1\Controllers\Controller;
29
use FireflyIII\Api\V1\Requests\DateRequest;
30
use FireflyIII\Models\Account;
31
use FireflyIII\Models\AccountType;
32
use FireflyIII\Models\TransactionCurrency;
33
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
34
use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface;
35
use FireflyIII\Support\Http\Api\ApiSupport;
36
use FireflyIII\User;
37
use Illuminate\Http\JsonResponse;
38
39
/**
40
 * Class AccountController
41
 */
42
class AccountController extends Controller
43
{
44
    use ApiSupport;
0 ignored issues
show
The trait FireflyIII\Support\Http\Api\ApiSupport requires some properties which are not provided by FireflyIII\Api\V1\Contro...Chart\AccountController: $id, $name
Loading history...
45
    /** @var CurrencyRepositoryInterface */
46
    private $currencyRepository;
47
    /** @var AccountRepositoryInterface */
48
    private $repository;
49
50
    /**
51
     * AccountController constructor.
52
     * @codeCoverageIgnore
53
     */
54
    public function __construct()
55
    {
56
        parent::__construct();
57
        $this->middleware(
58
            function ($request, $next) {
59
                /** @var User $user */
60
                $user             = auth()->user();
61
                $this->repository = app(AccountRepositoryInterface::class);
62
                $this->repository->setUser($user);
63
64
                $this->currencyRepository = app(CurrencyRepositoryInterface::class);
65
                $this->currencyRepository->setUser($user);
66
67
                return $next($request);
68
            }
69
        );
70
    }
71
72
    /**
73
     * @param DateRequest $request
74
     *
75
     * @return JsonResponse
76
     */
77
    public function expenseOverview(DateRequest $request): JsonResponse
78
    {
79
        // parameters for chart:
80
        $dates = $request->getAll();
81
        /** @var Carbon $start */
82
        $start = $dates['start'];
83
        /** @var Carbon $end */
84
        $end = $dates['end'];
85
86
        $start->subDay();
87
88
        // prep some vars:
89
        $currencies = [];
90
        $chartData  = [];
91
        $tempData   = [];
92
93
        // grab all accounts and names
94
        $accounts      = $this->repository->getAccountsByType([AccountType::EXPENSE]);
95
        $accountNames  = $this->extractNames($accounts);
96
        $startBalances = app('steam')->balancesPerCurrencyByAccounts($accounts, $start);
97
        $endBalances   = app('steam')->balancesPerCurrencyByAccounts($accounts, $end);
98
99
        // loop the end balances. This is an array for each account ($expenses)
100
        foreach ($endBalances as $accountId => $expenses) {
101
            $accountId = (int)$accountId;
102
            // loop each expense entry (each entry can be a different currency).
103
            foreach ($expenses as $currencyId => $endAmount) {
104
                $currencyId = (int)$currencyId;
105
106
                // see if there is an accompanying start amount.
107
                // grab the difference and find the currency.
108
                $startAmount             = $startBalances[$accountId][$currencyId] ?? '0';
109
                $diff                    = bcsub($endAmount, $startAmount);
110
                $currencies[$currencyId] = $currencies[$currencyId] ?? $this->currencyRepository->findNull($currencyId);
111
                if (0 !== bccomp($diff, '0')) {
112
                    // store the values in a temporary array.
113
                    $tempData[] = [
114
                        'name'        => $accountNames[$accountId],
115
                        'difference'  => $diff,
116
                        'diff_float'  => (float)$diff,
117
                        'currency_id' => $currencyId,
118
                    ];
119
                }
120
            }
121
        }
122
123
        // sort temp array by amount.
124
        $amounts = array_column($tempData, 'diff_float');
125
        array_multisort($amounts, SORT_DESC, $tempData);
126
127
        // loop all found currencies and build the data array for the chart.
128
        /**
129
         * @var int $currencyId
130
         * @var TransactionCurrency $currency
131
         */
132
        foreach ($currencies as $currencyId => $currency) {
133
            $currentSet             = [
134
                'label'                   => trans('firefly.box_spent_in_currency', ['currency' => $currency->symbol]),
135
                'currency_id'             => $currency->id,
136
                'currency_code'           => $currency->code,
137
                'currency_symbol'         => $currency->symbol,
138
                'currency_decimal_places' => $currency->decimal_places,
139
                'type'                    => 'bar', // line, area or bar
140
                'yAxisID'                 => 0, // 0, 1, 2
141
                'entries'                 => $this->expandNames($tempData),
142
            ];
143
            $chartData[$currencyId] = $currentSet;
144
        }
145
146
        // loop temp data and place data in correct array:
147
        foreach ($tempData as $entry) {
148
            $currencyId                               = $entry['currency_id'];
149
            $name                                     = $entry['name'];
150
            $chartData[$currencyId]['entries'][$name] = round($entry['difference'], $chartData[$currencyId]['currency_decimal_places']);
151
        }
152
        $chartData = array_values($chartData);
153
154
        return response()->json($chartData);
155
    }
156
157
158
    /**
159
     * @param DateRequest $request
160
     *
161
     * @return JsonResponse
162
     */
163
    public function overview(DateRequest $request): JsonResponse
164
    {
165
        // parameters for chart:
166
        $dates = $request->getAll();
167
        /** @var Carbon $start */
168
        $start = $dates['start'];
169
        /** @var Carbon $end */
170
        $end = $dates['end'];
171
172
        // user's preferences
173
        $defaultSet = $this->repository->getAccountsByType([AccountType::ASSET])->pluck('id')->toArray();
174
        $frontPage  = app('preferences')->get('frontPageAccounts', $defaultSet);
175
        $default    = app('amount')->getDefaultCurrency();
176
        // @codeCoverageIgnoreStart
177
        if (0 === count($frontPage->data)) {
178
            $frontPage->data = $defaultSet;
179
            $frontPage->save();
180
        }
181
        // @codeCoverageIgnoreEnd
182
183
        // get accounts:
184
        $accounts  = $this->repository->getAccountsById($frontPage->data);
185
        $chartData = [];
186
        /** @var Account $account */
187
        foreach ($accounts as $account) {
188
            $currency = $this->repository->getAccountCurrency($account);
189
            if (null === $currency) {
190
                $currency = $default; // @codeCoverageIgnore
191
            }
192
            $currentSet = [
193
                'label'                   => $account->name,
194
                'currency_id'             => $currency->id,
195
                'currency_code'           => $currency->code,
196
                'currency_symbol'         => $currency->symbol,
197
                'currency_decimal_places' => $currency->decimal_places,
198
                'type'                    => 'line', // line, area or bar
199
                'yAxisID'                 => 0, // 0, 1, 2
200
                'entries'                 => [],
201
            ];
202
            /** @var Carbon $currentStart */
203
            $currentStart = clone $start;
204
            $range        = app('steam')->balanceInRange($account, $start, clone $end);
205
            $previous     = round(array_values($range)[0], 12);
206
            while ($currentStart <= $end) {
207
                $format   = $currentStart->format('Y-m-d');
208
                $label    = $currentStart->format('Y-m-d');
209
                $balance  = isset($range[$format]) ? round($range[$format], 12) : $previous;
210
                $previous = $balance;
211
                $currentStart->addDay();
212
                $currentSet['entries'][$label] = $balance;
213
            }
214
            $chartData[] = $currentSet;
215
        }
216
217
        return response()->json($chartData);
218
    }
219
220
    /**
221
     * @param DateRequest $request
222
     *
223
     * @return JsonResponse
224
     */
225
    public function revenueOverview(DateRequest $request): JsonResponse
226
    {
227
        // parameters for chart:
228
        $dates = $request->getAll();
229
        /** @var Carbon $start */
230
        $start = $dates['start'];
231
        /** @var Carbon $end */
232
        $end = $dates['end'];
233
234
        $start->subDay();
235
236
        // prep some vars:
237
        $currencies = [];
238
        $chartData  = [];
239
        $tempData   = [];
240
241
        // grab all accounts and names
242
        $accounts      = $this->repository->getAccountsByType([AccountType::REVENUE]);
243
        $accountNames  = $this->extractNames($accounts);
244
        $startBalances = app('steam')->balancesPerCurrencyByAccounts($accounts, $start);
245
        $endBalances   = app('steam')->balancesPerCurrencyByAccounts($accounts, $end);
246
247
        // loop the end balances. This is an array for each account ($expenses)
248
        foreach ($endBalances as $accountId => $expenses) {
249
            $accountId = (int)$accountId;
250
            // loop each expense entry (each entry can be a different currency).
251
            foreach ($expenses as $currencyId => $endAmount) {
252
                $currencyId = (int)$currencyId;
253
254
                // see if there is an accompanying start amount.
255
                // grab the difference and find the currency.
256
                $startAmount             = $startBalances[$accountId][$currencyId] ?? '0';
257
                $diff                    = bcsub($endAmount, $startAmount);
258
                $currencies[$currencyId] = $currencies[$currencyId] ?? $this->currencyRepository->findNull($currencyId);
259
                if (0 !== bccomp($diff, '0')) {
260
                    // store the values in a temporary array.
261
                    $tempData[] = [
262
                        'name'        => $accountNames[$accountId],
263
                        'difference'  => bcmul($diff, '-1'),
264
                        //  For some reason this line is never covered in code coverage:
265
                        'diff_float'  => ((float)$diff) * -1, // @codeCoverageIgnore
266
                        'currency_id' => $currencyId,
267
                    ];
268
                }
269
            }
270
        }
271
272
        // sort temp array by amount.
273
        $amounts = array_column($tempData, 'diff_float');
274
        array_multisort($amounts, SORT_DESC, $tempData);
275
276
        // loop all found currencies and build the data array for the chart.
277
        /**
278
         * @var int $currencyId
279
         * @var TransactionCurrency $currency
280
         */
281
        foreach ($currencies as $currencyId => $currency) {
282
            $currentSet             = [
283
                'label'                   => trans('firefly.box_earned_in_currency', ['currency' => $currency->symbol]),
284
                'currency_id'             => $currency->id,
285
                'currency_code'           => $currency->code,
286
                'currency_symbol'         => $currency->symbol,
287
                'currency_decimal_places' => $currency->decimal_places,
288
                'type'                    => 'bar', // line, area or bar
289
                'yAxisID'                 => 0, // 0, 1, 2
290
                'entries'                 => $this->expandNames($tempData),
291
            ];
292
            $chartData[$currencyId] = $currentSet;
293
        }
294
295
        // loop temp data and place data in correct array:
296
        foreach ($tempData as $entry) {
297
            $currencyId                               = $entry['currency_id'];
298
            $name                                     = $entry['name'];
299
            $chartData[$currencyId]['entries'][$name] = round($entry['difference'], $chartData[$currencyId]['currency_decimal_places']);
300
        }
301
        $chartData = array_values($chartData);
302
303
        return response()->json($chartData);
304
    }
305
306
}
307