Files
firefly-iii/app/Transformers/V2/AccountTransformer.php

367 lines
15 KiB
PHP
Raw Normal View History

2022-06-25 14:23:52 +02:00
<?php
2022-10-16 19:29:53 +02:00
2022-06-25 14:23:52 +02:00
/*
* AccountTransformer.php
* Copyright (c) 2022 james@firefly-iii.org
*
* 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/>.
*/
2022-10-16 19:29:53 +02:00
declare(strict_types=1);
2022-06-25 14:23:52 +02:00
namespace FireflyIII\Transformers\V2;
2022-07-21 16:41:28 +02:00
use Carbon\Carbon;
use FireflyIII\Exceptions\FireflyException;
2022-06-25 14:23:52 +02:00
use FireflyIII\Models\Account;
2023-08-27 07:45:09 +02:00
use FireflyIII\Models\AccountType;
2022-07-21 16:41:28 +02:00
use FireflyIII\Models\TransactionCurrency;
2024-04-20 16:18:41 +02:00
use FireflyIII\Repositories\UserGroups\Account\AccountRepositoryInterface;
2023-10-28 14:59:16 +02:00
use FireflyIII\Repositories\UserGroups\Currency\CurrencyRepositoryInterface;
2022-07-17 08:51:53 +02:00
use Illuminate\Support\Collection;
2024-04-20 16:18:41 +02:00
use Illuminate\Support\Facades\Log;
2022-06-25 14:23:52 +02:00
/**
* Class AccountTransformer
*/
class AccountTransformer extends AbstractTransformer
{
2023-08-11 06:04:03 +02:00
private array $accountMeta;
2023-08-27 07:45:09 +02:00
private array $accountTypes;
2024-04-20 16:18:41 +02:00
private array $balanceDifferences;
2023-08-11 06:04:03 +02:00
private array $convertedBalances;
private array $currencies;
private TransactionCurrency $default;
2024-03-16 23:06:16 +01:00
private array $lastActivity;
2022-12-29 19:42:40 +01:00
/**
2024-04-20 16:18:41 +02:00
* This method collects meta-data for one or all accounts in the transformer's collection.
2022-12-29 19:42:40 +01:00
*/
public function collectMetaData(Collection $objects): Collection
2022-12-29 19:42:40 +01:00
{
2024-04-20 16:18:41 +02:00
$this->currencies = [];
$this->accountMeta = [];
$this->accountTypes = [];
$this->lastActivity = [];
$this->convertedBalances = [];
$this->balanceDifferences = [];
// get balances of all accounts
$this->getMetaBalances($objects);
// get default currency:
$this->getDefaultCurrency();
// collect currency and other meta-data:
$this->collectAccountMetaData($objects);
2023-10-28 14:59:16 +02:00
2023-08-27 07:45:09 +02:00
// get account types:
2024-04-20 16:18:41 +02:00
$this->collectAccountTypes($objects);
2023-12-20 19:35:52 +01:00
2024-04-20 16:18:41 +02:00
// get last activity:
$this->getLastActivity($objects);
2024-04-20 16:18:41 +02:00
// TODO add balance difference
if (null !== $this->parameters->get('start') && null !== $this->parameters->get('end')) {
$this->getBalanceDifference($objects, $this->parameters->get('start'), $this->parameters->get('end'));
2024-03-13 06:50:08 +01:00
}
2024-04-20 16:18:41 +02:00
return $this->sortAccounts($objects);
2024-03-09 19:46:16 +01:00
2022-12-29 19:42:40 +01:00
}
2022-07-21 16:41:28 +02:00
private function getDate(): Carbon
{
$date = today(config('app.timezone'));
if (null !== $this->parameters->get('date')) {
$date = $this->parameters->get('date');
}
return $date;
}
2022-06-25 14:23:52 +02:00
/**
* Transform the account.
*/
public function transform(Account $account): array
{
2024-04-20 16:18:41 +02:00
$id = $account->id;
2022-07-21 16:41:28 +02:00
2023-08-27 07:45:09 +02:00
// various meta
2024-04-20 16:18:41 +02:00
$accountRole = $this->accountMeta[$id]['account_role'] ?? null;
$accountType = $this->accountTypes[$id];
$order = $account->order;
2023-08-27 07:45:09 +02:00
2022-07-21 16:41:28 +02:00
// no currency? use default
2024-04-20 16:18:41 +02:00
$currency = $this->default;
if (array_key_exists($id, $this->accountMeta) && 0 !== (int) ($this->accountMeta[$id]['currency_id'] ?? 0)) {
$currency = $this->currencies[(int) $this->accountMeta[$id]['currency_id']];
2022-07-21 16:41:28 +02:00
}
2023-08-11 06:04:03 +02:00
// amounts and calculation.
2024-04-20 16:18:41 +02:00
$balance = $this->balances[$id]['balance'] ?? null;
2023-08-11 06:04:03 +02:00
$nativeBalance = $this->convertedBalances[$id]['native_balance'] ?? null;
2022-06-25 14:23:52 +02:00
2023-08-27 07:45:09 +02:00
// no order for some accounts:
if (!in_array(strtolower($accountType), ['liability', 'liabilities', 'asset'], true)) {
$order = null;
}
2024-04-20 16:18:41 +02:00
// balance difference
$diffStart = null;
$diffEnd = null;
$balanceDiff = null;
$nativeBalanceDiff = null;
if (null !== $this->parameters->get('start') && null !== $this->parameters->get('end')) {
$diffStart = $this->parameters->get('start')->toAtomString();
$diffEnd = $this->parameters->get('end')->toAtomString();
$balanceDiff = $this->balanceDifferences[$id]['balance'] ?? null;
$nativeBalanceDiff = $this->balanceDifferences[$id]['native_balance'] ?? null;
}
2022-06-25 14:23:52 +02:00
return [
2024-04-20 16:18:41 +02:00
'id' => (string) $account->id,
'created_at' => $account->created_at->toAtomString(),
'updated_at' => $account->updated_at->toAtomString(),
'active' => $account->active,
'order' => $order,
'name' => $account->name,
'iban' => '' === (string) $account->iban ? null : $account->iban,
'account_number' => $this->accountMeta[$id]['account_number'] ?? null,
'type' => strtolower($accountType),
'account_role' => $accountRole,
'currency_id' => (string) $currency->id,
'currency_code' => $currency->code,
'currency_symbol' => $currency->symbol,
'currency_decimal_places' => $currency->decimal_places,
'native_currency_id' => (string) $this->default->id,
'native_currency_code' => $this->default->code,
'native_currency_symbol' => $this->default->symbol,
2023-11-26 12:24:37 +01:00
'native_currency_decimal_places' => $this->default->decimal_places,
2023-08-11 06:04:03 +02:00
// balance:
'current_balance' => $balance,
'native_current_balance' => $nativeBalance,
2023-12-29 19:59:19 +01:00
'current_balance_date' => $this->getDate()->endOfDay()->toAtomString(),
2023-08-11 06:04:03 +02:00
2024-04-20 16:18:41 +02:00
// balance difference
'balance_difference' => $balanceDiff,
'native_balance_difference' => $nativeBalanceDiff,
'balance_difference_start' => $diffStart,
'balance_difference_end' => $diffEnd,
2023-08-11 06:04:03 +02:00
// more meta
2024-03-13 06:50:08 +01:00
'last_activity' => array_key_exists($id, $this->lastActivity) ? $this->lastActivity[$id]->toAtomString() : null,
2023-08-11 06:04:03 +02:00
2022-07-21 16:41:28 +02:00
// 'notes' => $this->repository->getNoteText($account),
// 'monthly_payment_date' => $monthlyPaymentDate,
// 'credit_card_type' => $creditCardType,
// 'account_number' => $this->repository->getMetaValue($account, 'account_number'),
// 'bic' => $this->repository->getMetaValue($account, 'BIC'),
// 'virtual_balance' => number_format((float) $account->virtual_balance, $decimalPlaces, '.', ''),
// 'opening_balance' => $openingBalance,
// 'opening_balance_date' => $openingBalanceDate,
// 'liability_type' => $liabilityType,
// 'liability_direction' => $liabilityDirection,
// 'interest' => $interest,
// 'interest_period' => $interestPeriod,
// 'current_debt' => $this->repository->getMetaValue($account, 'current_debt'),
// 'include_net_worth' => $includeNetWorth,
// 'longitude' => $longitude,
// 'latitude' => $latitude,
// 'zoom_level' => $zoomLevel,
'links' => [
2022-06-25 14:23:52 +02:00
[
'rel' => 'self',
2024-04-20 16:18:41 +02:00
'uri' => '/accounts/' . $account->id,
2022-06-25 14:23:52 +02:00
],
],
];
}
2024-04-20 16:18:41 +02:00
private function getMetaBalances(Collection $accounts): void
{
try {
$this->convertedBalances = app('steam')->balancesByAccountsConverted($accounts, $this->getDate());
} catch (FireflyException $e) {
Log::error($e->getMessage());
}
}
private function getDefaultCurrency(): void
{
$this->default = app('amount')->getDefaultCurrency();
}
private function collectAccountMetaData(Collection $accounts): void
{
/** @var CurrencyRepositoryInterface $repository */
$repository = app(CurrencyRepositoryInterface::class);
/** @var AccountRepositoryInterface $accountRepository */
$accountRepository = app(AccountRepositoryInterface::class);
$metaFields = $accountRepository->getMetaValues($accounts, ['currency_id', 'account_role', 'account_number']);
$currencyIds = $metaFields->where('name', 'currency_id')->pluck('data')->toArray();
$currencies = $repository->getByIds($currencyIds);
foreach ($currencies as $currency) {
$id = $currency->id;
$this->currencies[$id] = $currency;
}
foreach ($metaFields as $entry) {
$id = $entry->account_id;
$this->accountMeta[$id][$entry->name] = $entry->data;
}
}
private function collectAccountTypes(Collection $accounts): void
{
/** @var AccountRepositoryInterface $accountRepository */
$accountRepository = app(AccountRepositoryInterface::class);
$accountTypes = $accountRepository->getAccountTypes($accounts);
/** @var AccountType $row */
foreach ($accountTypes as $row) {
$this->accountTypes[$row->id] = (string) config(sprintf('firefly.shortNamesByFullName.%s', $row->type));
}
}
private function getLastActivity(Collection $accounts): void
{
/** @var AccountRepositoryInterface $accountRepository */
$accountRepository = app(AccountRepositoryInterface::class);
$lastActivity = $accountRepository->getLastActivity($accounts);
foreach ($lastActivity as $row) {
$this->lastActivity[(int) $row['account_id']] = Carbon::parse($row['date_max'], config('app.timezone'));
}
}
private function sortAccounts(Collection $accounts): Collection
{
/** @var null|array $sort */
$sort = $this->parameters->get('sort');
if (null === $sort || 0 === count($sort)) {
return $accounts;
}
/**
* @var string $column
* @var string $direction
*/
foreach ($sort as $column => $direction) {
// account_number + iban
if ('iban' === $column) {
$accounts = $this->sortByIban($accounts, $direction);
}
if ('balance' === $column) {
$accounts = $this->sortByBalance($accounts, $direction);
}
if ('last_activity' === $column) {
$accounts = $this->sortByLastActivity($accounts, $direction);
}
if ('balance_difference' === $column) {
$accounts = $this->sortByBalanceDifference($accounts, $direction);
}
}
return $accounts;
}
private function sortByIban(Collection $accounts, string $direction): Collection
{
$meta = $this->accountMeta;
return $accounts->sort(function (Account $left, Account $right) use ($meta, $direction) {
$leftIban = trim(sprintf('%s%s', $left->iban, $meta[$left->id]['account_number'] ?? ''));
$rightIban = trim(sprintf('%s%s', $right->iban, $meta[$right->id]['account_number'] ?? ''));
if ('asc' === $direction) {
return strcasecmp($leftIban, $rightIban);
}
return strcasecmp($rightIban, $leftIban);
});
}
private function sortByBalance(Collection $accounts, string $direction): Collection
{
$balances = $this->convertedBalances;
return $accounts->sort(function (Account $left, Account $right) use ($balances, $direction) {
$leftBalance = (float) ($balances[$left->id]['native_balance'] ?? 0);
$rightBalance = (float) ($balances[$right->id]['native_balance'] ?? 0);
if ('asc' === $direction) {
return $leftBalance <=> $rightBalance;
}
return $rightBalance <=> $leftBalance;
});
}
private function sortByLastActivity(Collection $accounts, string $direction): Collection
{
$dates = $this->lastActivity;
return $accounts->sort(function (Account $left, Account $right) use ($dates, $direction) {
$leftDate = $dates[$left->id] ?? Carbon::create(1900, 1, 1, 0, 0, 0);
$rightDate = $dates[$right->id] ?? Carbon::create(1900, 1, 1, 0, 0, 0);
if ('asc' === $direction) {
return $leftDate->gt($rightDate) ? 1 : -1;
}
return $rightDate->gt($leftDate) ? 1 : -1;
});
}
private function getBalanceDifference(Collection $accounts, Carbon $start, Carbon $end): void
{
// collect balances, start and end for both native and converted.
// yes the b is usually used for boolean by idiots but here it's for balance.
$bStart = [];
$bEnd = [];
try {
$bStart = app('steam')->balancesByAccountsConverted($accounts, $start);
$bEnd = app('steam')->balancesByAccountsConverted($accounts, $end);
} catch (FireflyException $e) {
Log::error($e->getMessage());
}
/** @var Account $account */
foreach ($accounts as $account) {
$id = $account->id;
if (array_key_exists($id, $bStart) && array_key_exists($id, $bEnd)) {
$this->balanceDifferences[$id] = [
'balance' => bcsub($bEnd[$id]['balance'], $bStart[$id]['balance']),
'native_balance' => bcsub($bEnd[$id]['native_balance'], $bStart[$id]['native_balance']),
];
}
}
}
private function sortByBalanceDifference(Collection $accounts, string $direction): Collection {
$balances = $this->balanceDifferences;
return $accounts->sort(function (Account $left, Account $right) use ($balances, $direction) {
$leftBalance = (float) ($balances[$left->id]['native_balance'] ?? 0);
$rightBalance = (float) ($balances[$right->id]['native_balance'] ?? 0);
if ('asc' === $direction) {
return $leftBalance <=> $rightBalance;
}
return $rightBalance <=> $leftBalance;
});
}
2022-06-25 14:23:52 +02:00
}