Skip to content

Commit

Permalink
Expand chart api
Browse files Browse the repository at this point in the history
  • Loading branch information
JC5 committed May 20, 2024
1 parent 7170931 commit 79b91e2
Show file tree
Hide file tree
Showing 8 changed files with 455 additions and 289 deletions.
177 changes: 98 additions & 79 deletions app/Api/V2/Controllers/Chart/AccountController.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,14 @@

namespace FireflyIII\Api\V2\Controllers\Chart;

use Carbon\Carbon;
use FireflyIII\Api\V2\Controllers\Controller;
use FireflyIII\Api\V2\Request\Chart\DashboardChartRequest;
use FireflyIII\Api\V2\Request\Chart\ChartRequest;
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Models\Account;
use FireflyIII\Models\AccountType;
use FireflyIII\Models\TransactionCurrency;
use FireflyIII\Repositories\UserGroups\Account\AccountRepositoryInterface;
use FireflyIII\Support\Chart\ChartData;
use FireflyIII\Support\Http\Api\CleansChartData;
use FireflyIII\Support\Http\Api\ValidatesUserGroupTrait;
use Illuminate\Http\JsonResponse;
Expand All @@ -46,6 +46,8 @@ class AccountController extends Controller
use ValidatesUserGroupTrait;

private AccountRepositoryInterface $repository;
private ChartData $chartData;
private TransactionCurrency $default;

public function __construct()
{
Expand All @@ -54,44 +56,58 @@ public function __construct()
function ($request, $next) {
$this->repository = app(AccountRepositoryInterface::class);
$this->repository->setUserGroup($this->validateUserGroup($request));
$this->chartData = new ChartData();
$this->default = app('amount')->getDefaultCurrency();

return $next($request);
}
);
}

/**
* This endpoint is documented at
* https://api-docs.firefly-iii.org/?urls.primaryName=2.0.0%20(v2)#/charts/getChartAccountOverview
*
* The native currency is the preferred currency on the page /currencies.
*
* If a transaction has foreign currency = native currency, the foreign amount will be used, no conversion
* will take place.
*
* TODO validate and set user_group_id from request
*
* TODO fix documentation
* @throws FireflyException
*/
public function dashboard(DashboardChartRequest $request): JsonResponse
public function dashboard(ChartRequest $request): JsonResponse
{
/** @var Carbon $start */
$start = $this->parameters->get('start');
$queryParameters = $request->getParameters();
$accounts = $this->getAccountList($queryParameters);

// move date to end of day
$queryParameters['start']->startOfDay();
$queryParameters['end']->endOfDay();

// loop each account, and collect info:
/** @var Account $account */
foreach ($accounts as $account) {
$this->renderAccountData($queryParameters, $account);
}

/** @var Carbon $end */
$end = $this->parameters->get('end');
$end->endOfDay();
return response()->json($this->chartData->render());
}

/** @var TransactionCurrency $default */
$default = app('amount')->getDefaultCurrency();
$params = $request->getAll();
/**
* TODO Duplicate function but I think it belongs here or in a separate trait
*
*/
private function getAccountList(array $queryParameters): Collection
{
$collection = new Collection();

/** @var Collection $accounts */
$accounts = $params['accounts'];
$chartData = [];
// always collect from the query parameter, even when it's empty.
foreach ($queryParameters['accounts'] as $accountId) {
$account = $this->repository->find((int) $accountId);
if (null !== $account) {
$collection->push($account);
}
}

// user's preferences
if (0 === $accounts->count()) {
// if no "preselected", and found accounts
if ('empty' === $queryParameters['preselected'] && $collection->count() > 0) {
return $collection;
}
// if no preselected, but no accounts:
if ('empty' === $queryParameters['preselected'] && 0 === $collection->count()) {
$defaultSet = $this->repository->getAccountsByType([AccountType::ASSET, AccountType::DEFAULT])->pluck('id')->toArray();
$frontpage = app('preferences')->get('frontpageAccounts', $defaultSet);

Expand All @@ -100,66 +116,69 @@ public function dashboard(DashboardChartRequest $request): JsonResponse
$frontpage->save();
}

$accounts = $this->repository->getAccountsById($frontpage->data);
return $this->repository->getAccountsById($frontpage->data);
}

// both options are overruled by "preselected"
if ('all' === $params['preselected']) {
$accounts = $this->repository->getAccountsByType([AccountType::ASSET, AccountType::DEFAULT, AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE]);
if ('all' === $queryParameters['preselected']) {
return $this->repository->getAccountsByType([AccountType::ASSET, AccountType::DEFAULT, AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE]);
}
if ('assets' === $params['preselected']) {
$accounts = $this->repository->getAccountsByType([AccountType::ASSET, AccountType::DEFAULT]);
if ('assets' === $queryParameters['preselected']) {
return $this->repository->getAccountsByType([AccountType::ASSET, AccountType::DEFAULT]);
}
if ('liabilities' === $params['preselected']) {
$accounts = $this->repository->getAccountsByType([AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE]);
if ('liabilities' === $queryParameters['preselected']) {
return $this->repository->getAccountsByType([AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE]);
}

/** @var Account $account */
foreach ($accounts as $account) {
$currency = $this->repository->getAccountCurrency($account);
if (null === $currency) {
$currency = $default;
}
$currentSet = [
'label' => $account->name,
// the currency that belongs to the account.
'currency_id' => (string)$currency->id,
'currency_code' => $currency->code,
'currency_symbol' => $currency->symbol,
'currency_decimal_places' => $currency->decimal_places,

// the default currency of the user (could be the same!)
'native_currency_id' => (string)$default->id,
'native_currency_code' => $default->code,
'native_currency_symbol' => $default->symbol,
'native_currency_decimal_places' => $default->decimal_places,
'start' => $start->toAtomString(),
'end' => $end->toAtomString(),
'period' => '1D',
'entries' => [],
'native_entries' => [],
];
$currentStart = clone $start;
$range = app('steam')->balanceInRange($account, $start, clone $end, $currency);
$rangeConverted = app('steam')->balanceInRangeConverted($account, $start, clone $end, $default);

$previous = array_values($range)[0];
$previousConverted = array_values($rangeConverted)[0];
while ($currentStart <= $end) {
$format = $currentStart->format('Y-m-d');
$label = $currentStart->toAtomString();
$balance = array_key_exists($format, $range) ? $range[$format] : $previous;
$balanceConverted = array_key_exists($format, $rangeConverted) ? $rangeConverted[$format] : $previousConverted;
$previous = $balance;
$previousConverted = $balanceConverted;

$currentStart->addDay();
$currentSet['entries'][$label] = $balance;
$currentSet['native_entries'][$label] = $balanceConverted;
}
$chartData[] = $currentSet;
}
return $collection;
}

return response()->json($this->clean($chartData));
/**
* @throws FireflyException
*/
private function renderAccountData(array $params, Account $account): void {
$currency = $this->repository->getAccountCurrency($account);
if (null === $currency) {
$currency = $this->default;
}
$currentSet = [
'label' => $account->name,

// the currency that belongs to the account.
'currency_id' => (string) $currency->id,
'currency_code' => $currency->code,
'currency_symbol' => $currency->symbol,
'currency_decimal_places' => $currency->decimal_places,

// the default currency of the user (could be the same!)
'native_currency_id' => (string) $this->default->id,
'native_currency_code' => $this->default->code,
'native_currency_symbol' => $this->default->symbol,
'native_currency_decimal_places' => $this->default->decimal_places,
'start' => $params['start']->toAtomString(),
'end' => $params['end']->toAtomString(),
'period' => '1D',
'entries' => [],
'native_entries' => [],
];
$currentStart = clone $params['start'];
$range = app('steam')->balanceInRange($account, $params['start'], clone $params['end'], $currency);
$rangeConverted = app('steam')->balanceInRangeConverted($account, $params['start'], clone $params['end'], $this->default);

$previous = array_values($range)[0];
$previousConverted = array_values($rangeConverted)[0];
while ($currentStart <= $params['end']) {
$format = $currentStart->format('Y-m-d');
$label = $currentStart->toAtomString();
$balance = array_key_exists($format, $range) ? $range[$format] : $previous;
$balanceConverted = array_key_exists($format, $rangeConverted) ? $rangeConverted[$format] : $previousConverted;
$previous = $balance;
$previousConverted = $balanceConverted;

$currentStart->addDay();
$currentSet['entries'][$label] = $balance;
$currentSet['native_entries'][$label] = $balanceConverted;
}
$this->chartData->add($currentSet);
}
}
22 changes: 15 additions & 7 deletions app/Api/V2/Request/Chart/ChartRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@

use FireflyIII\Enums\UserRoleEnum;
use FireflyIII\JsonApi\Rules\IsValidFilter;
use FireflyIII\Rules\IsFilterValueIn;
use FireflyIII\Support\Http\Api\ParsesQueryFilters;
use FireflyIII\Support\Http\Api\ValidatesUserGroupTrait;
use FireflyIII\Support\Request\ChecksLogin;
Expand All @@ -50,17 +51,19 @@ class ChartRequest extends FormRequest
public function getParameters(): array
{
$queryParameters = QueryParameters::cast($this->all());

return [
'start' => $this->dateOrToday($queryParameters, 'start'),
'end' => $this->dateOrToday($queryParameters, 'end'),

// preselected heeft maar een paar toegestane waardes.

'start' => $this->dateOrToday($queryParameters, 'start'),
'end' => $this->dateOrToday($queryParameters, 'end'),
'preselected' => $this->stringFromQueryParams($queryParameters, 'preselected', 'empty'),
'accounts' => $this->arrayOfStrings($queryParameters, 'accounts'),
// preselected heeft maar een paar toegestane waardes, dat moet ook goed gaan.
// 'query' => $this->arrayOfStrings($queryParameters, 'query'),
// 'size' => $this->integerFromQueryParams($queryParameters,'size', 50),
// 'account_types' => $this->getAccountTypeParameter($this->arrayOfStrings($queryParameters, 'account_types')),
];
// collect accounts based on this list?

}

// return [
Expand All @@ -76,7 +79,12 @@ public function rules(): array
{
return [
'fields' => JsonApiRule::notSupported(),
'filter' => ['nullable', 'array', new IsValidFilter(['start', 'end', 'preselected', 'accounts'])],
'filter' => ['nullable', 'array',
new IsValidFilter(['start', 'end', 'preselected', 'accounts']),
new IsFilterValueIn('preselected', config('firefly.preselected_accounts')),


],
'include' => JsonApiRule::notSupported(),
'page' => JsonApiRule::notSupported(),
'sort' => JsonApiRule::notSupported(),
Expand Down
58 changes: 58 additions & 0 deletions app/Rules/IsFilterValueIn.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
<?php
/*
* IsFilterValueIn.php
* Copyright (c) 2024 [email protected].
*
* This file is part of Firefly III (https://github.com/firefly-iii).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*/

declare(strict_types=1);

namespace FireflyIII\Rules;

use Illuminate\Contracts\Validation\ValidationRule;

class IsFilterValueIn implements ValidationRule
{
private string $key;
private array $values;
public function __construct(string $key, array $values) {
$this->key = $key;
$this->values = $values;
}
/**
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function validate(string $attribute, mixed $value, \Closure $fail): void
{
if(!is_array($value)) {
return;
}
if(!array_key_exists($this->key, $value)) {
return;
}
$value = $value[$this->key] ?? null;

if(!is_string($value) && !is_null($value)) {
$fail('validation.filter_not_string')->translate(['filter' => $this->key]);
}
if(!in_array($value, $this->values)) {
$fail('validation.filter_must_be_in')->translate(['filter' => $this->key,'values' => join(', ',$this->values)]);
}
//$fail('validation.filter_not_string')->translate(['filter' => $this->key]);
}

}
Loading

0 comments on commit 79b91e2

Please sign in to comment.