Code cleanup that (hopefully) matches style CI

This commit is contained in:
James Cole
2020-03-17 14:57:04 +01:00
parent b0c9fc0792
commit bd2f064eeb
30 changed files with 318 additions and 298 deletions

View File

@@ -55,7 +55,7 @@ class RequestedReportOnJournals
public function __construct(int $userId, Collection $groups) public function __construct(int $userId, Collection $groups)
{ {
Log::debug('In event RequestedReportOnJournals.'); Log::debug('In event RequestedReportOnJournals.');
$this->userId = $userId; $this->userId = $userId;
$this->groups = $groups; $this->groups = $groups;
} }

View File

@@ -20,6 +20,7 @@
*/ */
namespace FireflyIII\Exceptions; namespace FireflyIII\Exceptions;
use Exception; use Exception;
/** /**
@@ -27,5 +28,4 @@ use Exception;
*/ */
class DuplicateTransactionException extends Exception class DuplicateTransactionException extends Exception
{ {
}
}

View File

@@ -28,6 +28,7 @@ use Exception;
/** /**
* Class FireflyException. * Class FireflyException.
*
* @codeCoverageIgnore * @codeCoverageIgnore
*/ */
class FireflyException extends Exception class FireflyException extends Exception

View File

@@ -33,8 +33,11 @@ use FireflyIII\Models\TransactionJournal;
use FireflyIII\Models\TransactionType; use FireflyIII\Models\TransactionType;
use FireflyIII\User; use FireflyIII\User;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler; use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Routing\Redirector;
use Log; use Log;
use Symfony\Component\HttpFoundation\Response;
/** /**
* Class GracefulNotFoundHandler * Class GracefulNotFoundHandler
@@ -134,7 +137,7 @@ class GracefulNotFoundHandler extends ExceptionHandler
* @param Request $request * @param Request $request
* @param Exception $exception * @param Exception $exception
* *
* @return \Illuminate\Http\Response|\Symfony\Component\HttpFoundation\Response * @return \Illuminate\Http\Response|Response
*/ */
private function handleAccount($request, Exception $exception) private function handleAccount($request, Exception $exception)
{ {
@@ -142,7 +145,7 @@ class GracefulNotFoundHandler extends ExceptionHandler
/** @var User $user */ /** @var User $user */
$user = auth()->user(); $user = auth()->user();
$route = $request->route(); $route = $request->route();
$accountId = (int)$route->parameter('account'); $accountId = (int) $route->parameter('account');
/** @var Account $account */ /** @var Account $account */
$account = $user->accounts()->with(['accountType'])->withTrashed()->find($accountId); $account = $user->accounts()->with(['accountType'])->withTrashed()->find($accountId);
if (null === $account) { if (null === $account) {
@@ -163,7 +166,7 @@ class GracefulNotFoundHandler extends ExceptionHandler
/** @var User $user */ /** @var User $user */
$user = auth()->user(); $user = auth()->user();
$route = $request->route(); $route = $request->route();
$attachmentId = (int)$route->parameter('attachment'); $attachmentId = (int) $route->parameter('attachment');
/** @var Attachment $attachment */ /** @var Attachment $attachment */
$attachment = $user->attachments()->withTrashed()->find($attachmentId); $attachment = $user->attachments()->withTrashed()->find($attachmentId);
if (null === $attachment) { if (null === $attachment) {
@@ -199,7 +202,7 @@ class GracefulNotFoundHandler extends ExceptionHandler
* @param $request * @param $request
* @param Exception $exception * @param Exception $exception
* *
* @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\Response|\Illuminate\Routing\Redirector|\Symfony\Component\HttpFoundation\Response * @return RedirectResponse|\Illuminate\Http\Response|Redirector|Response
*/ */
private function handleGroup($request, Exception $exception) private function handleGroup($request, Exception $exception)
{ {
@@ -207,7 +210,7 @@ class GracefulNotFoundHandler extends ExceptionHandler
/** @var User $user */ /** @var User $user */
$user = auth()->user(); $user = auth()->user();
$route = $request->route(); $route = $request->route();
$groupId = (int)$route->parameter('transactionGroup'); $groupId = (int) $route->parameter('transactionGroup');
/** @var TransactionGroup $group */ /** @var TransactionGroup $group */
$group = $user->transactionGroups()->withTrashed()->find($groupId); $group = $user->transactionGroups()->withTrashed()->find($groupId);

View File

@@ -82,15 +82,17 @@ class Handler extends ExceptionHandler
'line' => $exception->getLine(), 'line' => $exception->getLine(),
'file' => $exception->getFile(), 'file' => $exception->getFile(),
'trace' => $exception->getTrace(), 'trace' => $exception->getTrace(),
], 500 ],
500
); );
} }
return response()->json(['message' => 'Internal Firefly III Exception. See log files.', 'exception' => get_class($exception)], 500); return response()->json(['message' => 'Internal Firefly III Exception. See log files.', 'exception' => get_class($exception)], 500);
} }
if($exception instanceof NotFoundHttpException) { if ($exception instanceof NotFoundHttpException) {
$handler = app(GracefulNotFoundHandler::class); $handler = app(GracefulNotFoundHandler::class);
return $handler->render($request, $exception); return $handler->render($request, $exception);
} }
@@ -113,13 +115,12 @@ class Handler extends ExceptionHandler
* *
* @param Exception $exception * @param Exception $exception
* *
* @throws Exception
* @return mixed|void * @return mixed|void
* *
* @throws Exception
*/ */
public function report(Exception $exception) public function report(Exception $exception)
{ {
$doMailError = config('firefly.send_error_message'); $doMailError = config('firefly.send_error_message');
// if the user wants us to mail: // if the user wants us to mail:
if (true === $doMailError if (true === $doMailError
@@ -149,7 +150,7 @@ class Handler extends ExceptionHandler
// create job that will mail. // create job that will mail.
$ipAddress = Request::ip() ?? '0.0.0.0'; $ipAddress = Request::ip() ?? '0.0.0.0';
$job = new MailError($userData, (string)config('firefly.site_owner'), $ipAddress, $data); $job = new MailError($userData, (string) config('firefly.site_owner'), $ipAddress, $data);
dispatch($job); dispatch($job);
} }

View File

@@ -28,6 +28,7 @@ use Exception;
/** /**
* Class NotImplementedException. * Class NotImplementedException.
*
* @codeCoverageIgnore * @codeCoverageIgnore
*/ */
class NotImplementedException extends Exception class NotImplementedException extends Exception

View File

@@ -28,6 +28,7 @@ use Exception;
/** /**
* Class ValidationExceptions. * Class ValidationExceptions.
*
* @codeCoverageIgnore * @codeCoverageIgnore
*/ */
class ValidationException extends Exception class ValidationException extends Exception

View File

@@ -27,7 +27,6 @@ namespace FireflyIII\Factory;
use FireflyIII\Exceptions\FireflyException; use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Models\Account; use FireflyIII\Models\Account;
use FireflyIII\Models\AccountType; use FireflyIII\Models\AccountType;
use FireflyIII\Models\Location;
use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Services\Internal\Support\AccountServiceTrait; use FireflyIII\Services\Internal\Support\AccountServiceTrait;
use FireflyIII\Services\Internal\Support\LocationServiceTrait; use FireflyIII\Services\Internal\Support\LocationServiceTrait;
@@ -45,18 +44,16 @@ class AccountFactory
/** @var AccountRepositoryInterface */ /** @var AccountRepositoryInterface */
protected $accountRepository; protected $accountRepository;
/** @var User */
private $user;
/** @var array */
private $canHaveVirtual;
/** @var array */ /** @var array */
protected $validAssetFields = ['account_role', 'account_number', 'currency_id', 'BIC', 'include_net_worth']; protected $validAssetFields = ['account_role', 'account_number', 'currency_id', 'BIC', 'include_net_worth'];
/** @var array */ /** @var array */
protected $validCCFields = ['account_role', 'cc_monthly_payment_date', 'cc_type', 'account_number', 'currency_id', 'BIC', 'include_net_worth']; protected $validCCFields = ['account_role', 'cc_monthly_payment_date', 'cc_type', 'account_number', 'currency_id', 'BIC', 'include_net_worth'];
/** @var array */ /** @var array */
protected $validFields = ['account_number', 'currency_id', 'BIC', 'interest', 'interest_period', 'include_net_worth']; protected $validFields = ['account_number', 'currency_id', 'BIC', 'interest', 'interest_period', 'include_net_worth'];
/** @var array */
private $canHaveVirtual;
/** @var User */
private $user;
/** /**
* AccountFactory constructor. * AccountFactory constructor.
@@ -75,8 +72,8 @@ class AccountFactory
/** /**
* @param array $data * @param array $data
* *
* @return Account
* @throws FireflyException * @throws FireflyException
* @return Account
*/ */
public function create(array $data): Account public function create(array $data): Account
{ {
@@ -106,7 +103,7 @@ class AccountFactory
'iban' => $data['iban'], 'iban' => $data['iban'],
]; ];
$currency = $this->getCurrency((int)($data['currency_id'] ?? null), (string)($data['currency_code'] ?? null)); $currency = $this->getCurrency((int) ($data['currency_id'] ?? null), (string) ($data['currency_code'] ?? null));
unset($data['currency_code']); unset($data['currency_code']);
$data['currency_id'] = $currency->id; $data['currency_id'] = $currency->id;
@@ -159,8 +156,8 @@ class AccountFactory
* @param string $accountName * @param string $accountName
* @param string $accountType * @param string $accountType
* *
* @return Account
* @throws FireflyException * @throws FireflyException
* @return Account
*/ */
public function findOrCreate(string $accountName, string $accountType): Account public function findOrCreate(string $accountName, string $accountType): Account
{ {
@@ -197,7 +194,7 @@ class AccountFactory
} }
/** /**
* @param int|null $accountTypeId * @param int|null $accountTypeId
* @param null|string $accountType * @param null|string $accountType
* *
* @return AccountType|null * @return AccountType|null
@@ -205,7 +202,7 @@ class AccountFactory
*/ */
protected function getAccountType(?int $accountTypeId, ?string $accountType): ?AccountType protected function getAccountType(?int $accountTypeId, ?string $accountType): ?AccountType
{ {
$accountTypeId = (int)$accountTypeId; $accountTypeId = (int) $accountTypeId;
$result = null; $result = null;
if ($accountTypeId > 0) { if ($accountTypeId > 0) {
$result = AccountType::find($accountTypeId); $result = AccountType::find($accountTypeId);

View File

@@ -36,6 +36,7 @@ class AccountMetaFactory
{ {
/** /**
* Constructor. * Constructor.
*
* @codeCoverageIgnore * @codeCoverageIgnore
*/ */
public function __construct() public function __construct()

View File

@@ -41,6 +41,7 @@ class AttachmentFactory
/** /**
* Constructor. * Constructor.
*
* @codeCoverageIgnore * @codeCoverageIgnore
*/ */
public function __construct() public function __construct()
@@ -53,8 +54,8 @@ class AttachmentFactory
/** /**
* @param array $data * @param array $data
* *
* @return Attachment|null
* @throws FireflyException * @throws FireflyException
* @return Attachment|null
*/ */
public function create(array $data): ?Attachment public function create(array $data): ?Attachment
{ {
@@ -64,7 +65,7 @@ class AttachmentFactory
// get journal instead of transaction. // get journal instead of transaction.
if (Transaction::class === $model) { if (Transaction::class === $model) {
/** @var Transaction $transaction */ /** @var Transaction $transaction */
$transaction = $this->user->transactions()->find((int)$data['model_id']); $transaction = $this->user->transactions()->find((int) $data['model_id']);
if (null === $transaction) { if (null === $transaction) {
throw new FireflyException('Unexpectedly could not find transaction'); // @codeCoverageIgnore throw new FireflyException('Unexpectedly could not find transaction'); // @codeCoverageIgnore
} }
@@ -87,7 +88,7 @@ class AttachmentFactory
'uploaded' => 0, 'uploaded' => 0,
] ]
); );
$notes = (string)($data['notes'] ?? ''); $notes = (string) ($data['notes'] ?? '');
if ('' !== $notes) { if ('' !== $notes) {
$note = new Note; $note = new Note;
$note->noteable()->associate($attachment); $note->noteable()->associate($attachment);

View File

@@ -44,6 +44,7 @@ class BillFactory
/** /**
* Constructor. * Constructor.
*
* @codeCoverageIgnore * @codeCoverageIgnore
*/ */
public function __construct() public function __construct()
@@ -56,15 +57,15 @@ class BillFactory
/** /**
* @param array $data * @param array $data
* *
* @return Bill|null
* @throws FireflyException * @throws FireflyException
* @return Bill|null
*/ */
public function create(array $data): ?Bill public function create(array $data): ?Bill
{ {
/** @var TransactionCurrencyFactory $factory */ /** @var TransactionCurrencyFactory $factory */
$factory = app(TransactionCurrencyFactory::class); $factory = app(TransactionCurrencyFactory::class);
/** @var TransactionCurrency $currency */ /** @var TransactionCurrency $currency */
$currency = $factory->find((int)($data['currency_id'] ?? null), (string)($data['currency_code'] ?? null)); $currency = $factory->find((int) ($data['currency_id'] ?? null), (string) ($data['currency_code'] ?? null));
if (null === $currency) { if (null === $currency) {
$currency = app('amount')->getDefaultCurrencyByUser($this->user); $currency = app('amount')->getDefaultCurrencyByUser($this->user);
@@ -86,7 +87,7 @@ class BillFactory
'active' => $data['active'] ?? true, 'active' => $data['active'] ?? true,
] ]
); );
} catch(QueryException $e) { } catch (QueryException $e) {
Log::error($e->getMessage()); Log::error($e->getMessage());
Log::error($e->getTraceAsString()); Log::error($e->getTraceAsString());
throw new FireflyException('400000: Could not store bill.'); throw new FireflyException('400000: Could not store bill.');
@@ -100,15 +101,15 @@ class BillFactory
} }
/** /**
* @param int|null $billId * @param int|null $billId
* @param null|string $billName * @param null|string $billName
* *
* @return Bill|null * @return Bill|null
*/ */
public function find(?int $billId, ?string $billName): ?Bill public function find(?int $billId, ?string $billName): ?Bill
{ {
$billId = (int)$billId; $billId = (int) $billId;
$billName = (string)$billName; $billName = (string) $billName;
$bill = null; $bill = null;
// first find by ID: // first find by ID:
if ($billId > 0) { if ($billId > 0) {

View File

@@ -38,6 +38,7 @@ class BudgetFactory
/** /**
* Constructor. * Constructor.
*
* @codeCoverageIgnore * @codeCoverageIgnore
*/ */
public function __construct() public function __construct()
@@ -56,8 +57,8 @@ class BudgetFactory
*/ */
public function find(?int $budgetId, ?string $budgetName): ?Budget public function find(?int $budgetId, ?string $budgetName): ?Budget
{ {
$budgetId = (int)$budgetId; $budgetId = (int) $budgetId;
$budgetName = (string)$budgetName; $budgetName = (string) $budgetName;
if (0 === $budgetId && '' === $budgetName) { if (0 === $budgetId && '' === $budgetName) {
return null; return null;

View File

@@ -40,6 +40,7 @@ class CategoryFactory
/** /**
* Constructor. * Constructor.
*
* @codeCoverageIgnore * @codeCoverageIgnore
*/ */
public function __construct() public function __construct()
@@ -63,13 +64,13 @@ class CategoryFactory
* @param int|null $categoryId * @param int|null $categoryId
* @param null|string $categoryName * @param null|string $categoryName
* *
* @return Category|null
* @throws FireflyException * @throws FireflyException
* @return Category|null
*/ */
public function findOrCreate(?int $categoryId, ?string $categoryName): ?Category public function findOrCreate(?int $categoryId, ?string $categoryName): ?Category
{ {
$categoryId = (int)$categoryId; $categoryId = (int) $categoryId;
$categoryName = (string)$categoryName; $categoryName = (string) $categoryName;
Log::debug(sprintf('Going to find category with ID %d and name "%s"', $categoryId, $categoryName)); Log::debug(sprintf('Going to find category with ID %d and name "%s"', $categoryId, $categoryName));

View File

@@ -39,6 +39,7 @@ class PiggyBankEventFactory
{ {
/** /**
* Constructor. * Constructor.
*
* @codeCoverageIgnore * @codeCoverageIgnore
*/ */
public function __construct() public function __construct()
@@ -60,6 +61,7 @@ class PiggyBankEventFactory
Log::debug(sprintf('Now in PiggyBankEventCreate for a %s', $journal->transactionType->type)); Log::debug(sprintf('Now in PiggyBankEventCreate for a %s', $journal->transactionType->type));
if (null === $piggyBank) { if (null === $piggyBank) {
Log::debug('Piggy bank is null'); Log::debug('Piggy bank is null');
return null; return null;
} }

View File

@@ -38,6 +38,7 @@ class PiggyBankFactory
/** /**
* Constructor. * Constructor.
*
* @codeCoverageIgnore * @codeCoverageIgnore
*/ */
public function __construct() public function __construct()
@@ -56,8 +57,8 @@ class PiggyBankFactory
*/ */
public function find(?int $piggyBankId, ?string $piggyBankName): ?PiggyBank public function find(?int $piggyBankId, ?string $piggyBankName): ?PiggyBank
{ {
$piggyBankId = (int)$piggyBankId; $piggyBankId = (int) $piggyBankId;
$piggyBankName = (string)$piggyBankName; $piggyBankName = (string) $piggyBankName;
if ('' === $piggyBankName && 0 === $piggyBankId) { if ('' === $piggyBankName && 0 === $piggyBankId) {
return null; return null;
} }

View File

@@ -39,16 +39,16 @@ use Log;
*/ */
class RecurrenceFactory class RecurrenceFactory
{ {
/** @var User */
private $user;
/** @var MessageBag */ /** @var MessageBag */
private $errors; private $errors;
/** @var User */
private $user;
use TransactionTypeTrait, RecurringTransactionTrait; use TransactionTypeTrait, RecurringTransactionTrait;
/** /**
* Constructor. * Constructor.
*
* @codeCoverageIgnore * @codeCoverageIgnore
*/ */
public function __construct() public function __construct()
@@ -62,8 +62,8 @@ class RecurrenceFactory
/** /**
* @param array $data * @param array $data
* *
* @return Recurrence
* @throws FireflyException * @throws FireflyException
* @return Recurrence
*/ */
public function create(array $data): Recurrence public function create(array $data): Recurrence
{ {
@@ -79,7 +79,7 @@ class RecurrenceFactory
/** @var Carbon $firstDate */ /** @var Carbon $firstDate */
$firstDate = $data['recurrence']['first_date']; $firstDate = $data['recurrence']['first_date'];
$repetitions = (int)$data['recurrence']['repetitions']; $repetitions = (int) $data['recurrence']['repetitions'];
$recurrence = new Recurrence( $recurrence = new Recurrence(
[ [
'user_id' => $this->user->id, 'user_id' => $this->user->id,

View File

@@ -42,6 +42,7 @@ class TagFactory
/** /**
* Constructor. * Constructor.
*
* @codeCoverageIgnore * @codeCoverageIgnore
*/ */
public function __construct() public function __construct()
@@ -58,9 +59,9 @@ class TagFactory
*/ */
public function create(array $data): ?Tag public function create(array $data): ?Tag
{ {
$zoomLevel = 0 === (int)$data['zoom_level'] ? null : (int)$data['zoom_level']; $zoomLevel = 0 === (int) $data['zoom_level'] ? null : (int) $data['zoom_level'];
$latitude = 0.0 === (float)$data['latitude'] ? null : (float)$data['latitude']; $latitude = 0.0 === (float) $data['latitude'] ? null : (float) $data['latitude'];
$longitude = 0.0 === (float)$data['longitude'] ? null : (float)$data['longitude']; $longitude = 0.0 === (float) $data['longitude'] ? null : (float) $data['longitude'];
$array = [ $array = [
'user_id' => $this->user->id, 'user_id' => $this->user->id,
'tag' => trim($data['tag']), 'tag' => trim($data['tag']),

View File

@@ -52,8 +52,8 @@ class TransactionCurrencyFactory
/** /**
* @param array $data * @param array $data
* *
* @return TransactionCurrency
* @throws FireflyException * @throws FireflyException
* @return TransactionCurrency
*/ */
public function create(array $data): TransactionCurrency public function create(array $data): TransactionCurrency
{ {
@@ -86,8 +86,8 @@ class TransactionCurrencyFactory
*/ */
public function find(?int $currencyId, ?string $currencyCode): ?TransactionCurrency public function find(?int $currencyId, ?string $currencyCode): ?TransactionCurrency
{ {
$currencyCode = (string)$currencyCode; $currencyCode = (string) $currencyCode;
$currencyId = (int)$currencyId; $currencyId = (int) $currencyId;
if ('' === $currencyCode && 0 === $currencyId) { if ('' === $currencyCode && 0 === $currencyId) {
Log::debug('Cannot find anything on empty currency code and empty currency ID!'); Log::debug('Cannot find anything on empty currency code and empty currency ID!');

View File

@@ -24,7 +24,6 @@ declare(strict_types=1);
namespace FireflyIII\Factory; namespace FireflyIII\Factory;
use FireflyIII\Exceptions\FireflyException; use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Models\Account; use FireflyIII\Models\Account;
use FireflyIII\Models\Transaction; use FireflyIII\Models\Transaction;
@@ -39,21 +38,22 @@ use Log;
*/ */
class TransactionFactory class TransactionFactory
{ {
/** @var TransactionJournal */
private $journal;
/** @var Account */ /** @var Account */
private $account; private $account;
/** @var TransactionCurrency */ /** @var TransactionCurrency */
private $currency; private $currency;
/** @var TransactionCurrency */ /** @var TransactionCurrency */
private $foreignCurrency; private $foreignCurrency;
/** @var User */ /** @var TransactionJournal */
private $user; private $journal;
/** @var bool */ /** @var bool */
private $reconciled; private $reconciled;
/** @var User */
private $user;
/** /**
* Constructor. * Constructor.
*
* @codeCoverageIgnore * @codeCoverageIgnore
*/ */
public function __construct() public function __construct()
@@ -64,50 +64,14 @@ class TransactionFactory
$this->reconciled = false; $this->reconciled = false;
} }
/**
* @param bool $reconciled
* @codeCoverageIgnore
*/
public function setReconciled(bool $reconciled): void
{
$this->reconciled = $reconciled;
}
/**
* @param Account $account
* @codeCoverageIgnore
*/
public function setAccount(Account $account): void
{
$this->account = $account;
}
/**
* @param TransactionCurrency $currency
* @codeCoverageIgnore
*/
public function setCurrency(TransactionCurrency $currency): void
{
$this->currency = $currency;
}
/**
* @param TransactionCurrency $foreignCurrency |null
* @codeCoverageIgnore
*/
public function setForeignCurrency(?TransactionCurrency $foreignCurrency): void
{
$this->foreignCurrency = $foreignCurrency;
}
/** /**
* Create transaction with negative amount (for source accounts). * Create transaction with negative amount (for source accounts).
* *
* @param string $amount * @param string $amount
* @param string|null $foreignAmount * @param string|null $foreignAmount
* *
* @return Transaction
* @throws FireflyException * @throws FireflyException
* @return Transaction
*/ */
public function createNegative(string $amount, ?string $foreignAmount): Transaction public function createNegative(string $amount, ?string $foreignAmount): Transaction
{ {
@@ -127,8 +91,8 @@ class TransactionFactory
* @param string $amount * @param string $amount
* @param string|null $foreignAmount * @param string|null $foreignAmount
* *
* @return Transaction
* @throws FireflyException * @throws FireflyException
* @return Transaction
*/ */
public function createPositive(string $amount, ?string $foreignAmount): Transaction public function createPositive(string $amount, ?string $foreignAmount): Transaction
{ {
@@ -138,12 +102,43 @@ class TransactionFactory
if (null !== $foreignAmount) { if (null !== $foreignAmount) {
$foreignAmount = app('steam')->positive($foreignAmount); $foreignAmount = app('steam')->positive($foreignAmount);
} }
return $this->create(app('steam')->positive($amount), $foreignAmount); return $this->create(app('steam')->positive($amount), $foreignAmount);
} }
/**
* @param Account $account
*
* @codeCoverageIgnore
*/
public function setAccount(Account $account): void
{
$this->account = $account;
}
/**
* @param TransactionCurrency $currency
*
* @codeCoverageIgnore
*/
public function setCurrency(TransactionCurrency $currency): void
{
$this->currency = $currency;
}
/**
* @param TransactionCurrency $foreignCurrency |null
*
* @codeCoverageIgnore
*/
public function setForeignCurrency(?TransactionCurrency $foreignCurrency): void
{
$this->foreignCurrency = $foreignCurrency;
}
/** /**
* @param TransactionJournal $journal * @param TransactionJournal $journal
*
* @codeCoverageIgnore * @codeCoverageIgnore
*/ */
public function setJournal(TransactionJournal $journal): void public function setJournal(TransactionJournal $journal): void
@@ -151,8 +146,19 @@ class TransactionFactory
$this->journal = $journal; $this->journal = $journal;
} }
/**
* @param bool $reconciled
*
* @codeCoverageIgnore
*/
public function setReconciled(bool $reconciled): void
{
$this->reconciled = $reconciled;
}
/** /**
* @param User $user * @param User $user
*
* @codeCoverageIgnore * @codeCoverageIgnore
*/ */
public function setUser(User $user): void public function setUser(User $user): void
@@ -164,8 +170,8 @@ class TransactionFactory
* @param string $amount * @param string $amount
* @param string|null $foreignAmount * @param string|null $foreignAmount
* *
* @return Transaction
* @throws FireflyException * @throws FireflyException
* @return Transaction
*/ */
private function create(string $amount, ?string $foreignAmount): Transaction private function create(string $amount, ?string $foreignAmount): Transaction
{ {
@@ -200,7 +206,11 @@ class TransactionFactory
if (null !== $result) { if (null !== $result) {
Log::debug( Log::debug(
sprintf( sprintf(
'Created transaction #%d (%s %s, account %s), part of journal #%d', $result->id, $this->currency->code, $amount, $this->account->name, 'Created transaction #%d (%s %s, account %s), part of journal #%d',
$result->id,
$this->currency->code,
$amount,
$this->account->name,
$this->journal->id $this->journal->id
) )
); );
@@ -209,7 +219,6 @@ class TransactionFactory
if (null !== $this->foreignCurrency && null !== $foreignAmount && $this->foreignCurrency->id !== $this->currency->id && '' !== $foreignAmount) { if (null !== $this->foreignCurrency && null !== $foreignAmount && $this->foreignCurrency->id !== $this->currency->id && '' !== $foreignAmount) {
$result->foreign_currency_id = $this->foreignCurrency->id; $result->foreign_currency_id = $this->foreignCurrency->id;
$result->foreign_amount = $foreignAmount; $result->foreign_amount = $foreignAmount;
} }
$result->save(); $result->save();
} }

View File

@@ -24,7 +24,6 @@ declare(strict_types=1);
namespace FireflyIII\Factory; namespace FireflyIII\Factory;
use FireflyIII\Exceptions\DuplicateTransactionException; use FireflyIII\Exceptions\DuplicateTransactionException;
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Models\TransactionGroup; use FireflyIII\Models\TransactionGroup;
use FireflyIII\User; use FireflyIII\User;
use Log; use Log;
@@ -54,8 +53,8 @@ class TransactionGroupFactory
* *
* @param array $data * @param array $data
* *
* @return TransactionGroup
* @throws DuplicateTransactionException * @throws DuplicateTransactionException
* @return TransactionGroup
*/ */
public function create(array $data): TransactionGroup public function create(array $data): TransactionGroup
{ {
@@ -63,12 +62,12 @@ class TransactionGroupFactory
$this->journalFactory->setErrorOnHash($data['error_if_duplicate_hash'] ?? false); $this->journalFactory->setErrorOnHash($data['error_if_duplicate_hash'] ?? false);
try { try {
$collection = $this->journalFactory->create($data); $collection = $this->journalFactory->create($data);
} catch(DuplicateTransactionException $e) { } catch (DuplicateTransactionException $e) {
Log::warning('GroupFactory::create() caught journalFactory::create() with a duplicate!'); Log::warning('GroupFactory::create() caught journalFactory::create() with a duplicate!');
throw new DuplicateTransactionException($e->getMessage()); throw new DuplicateTransactionException($e->getMessage());
} }
$title = $data['group_title'] ?? null; $title = $data['group_title'] ?? null;
$title = '' === $title ? null : $title; $title = '' === $title ? null : $title;
if (null !== $title) { if (null !== $title) {
$title = substr($title, 0, 1000); $title = substr($title, 0, 1000);

View File

@@ -64,6 +64,8 @@ class TransactionJournalFactory
private $billRepository; private $billRepository;
/** @var CurrencyRepositoryInterface */ /** @var CurrencyRepositoryInterface */
private $currencyRepository; private $currencyRepository;
/** @var bool */
private $errorOnHash;
/** @var array */ /** @var array */
private $fields; private $fields;
/** @var PiggyBankEventFactory */ /** @var PiggyBankEventFactory */
@@ -76,8 +78,6 @@ class TransactionJournalFactory
private $typeRepository; private $typeRepository;
/** @var User The user */ /** @var User The user */
private $user; private $user;
/** @var bool */
private $errorOnHash;
/** /**
* Constructor. * Constructor.
@@ -125,9 +125,9 @@ class TransactionJournalFactory
* *
* @param array $data * @param array $data
* *
* @return Collection
* @throws DuplicateTransactionException * @throws DuplicateTransactionException
* @throws FireflyException * @throws FireflyException
* @return Collection
*/ */
public function create(array $data): Collection public function create(array $data): Collection
{ {
@@ -171,6 +171,17 @@ class TransactionJournalFactory
return $collection; return $collection;
} }
/**
* @param bool $errorOnHash
*/
public function setErrorOnHash(bool $errorOnHash): void
{
$this->errorOnHash = $errorOnHash;
if (true === $errorOnHash) {
Log::info('Will trigger duplication alert for this journal.');
}
}
/** /**
* Set the user. * Set the user.
* *
@@ -199,7 +210,7 @@ class TransactionJournalFactory
$set = [ $set = [
'journal' => $journal, 'journal' => $journal,
'name' => $field, 'name' => $field,
'data' => (string)($data[$field] ?? ''), 'data' => (string) ($data[$field] ?? ''),
]; ];
Log::debug(sprintf('Going to store meta-field "%s", with value "%s".', $set['name'], $set['data'])); Log::debug(sprintf('Going to store meta-field "%s", with value "%s".', $set['name'], $set['data']));
@@ -212,9 +223,9 @@ class TransactionJournalFactory
/** /**
* @param NullArrayObject $row * @param NullArrayObject $row
* *
* @return TransactionJournal|null
* @throws FireflyException * @throws FireflyException
* @throws DuplicateTransactionException * @throws DuplicateTransactionException
* @return TransactionJournal|null
*/ */
private function createJournal(NullArrayObject $row): ?TransactionJournal private function createJournal(NullArrayObject $row): ?TransactionJournal
{ {
@@ -226,11 +237,11 @@ class TransactionJournalFactory
$type = $this->typeRepository->findTransactionType(null, $row['type']); $type = $this->typeRepository->findTransactionType(null, $row['type']);
$carbon = $row['date'] ?? new Carbon; $carbon = $row['date'] ?? new Carbon;
$order = $row['order'] ?? 0; $order = $row['order'] ?? 0;
$currency = $this->currencyRepository->findCurrency((int)$row['currency_id'], $row['currency_code']); $currency = $this->currencyRepository->findCurrency((int) $row['currency_id'], $row['currency_code']);
$foreignCurrency = $this->currencyRepository->findCurrencyNull($row['foreign_currency_id'], $row['foreign_currency_code']); $foreignCurrency = $this->currencyRepository->findCurrencyNull($row['foreign_currency_id'], $row['foreign_currency_code']);
$bill = $this->billRepository->findBill((int)$row['bill_id'], $row['bill_name']); $bill = $this->billRepository->findBill((int) $row['bill_id'], $row['bill_name']);
$billId = TransactionType::WITHDRAWAL === $type->type && null !== $bill ? $bill->id : null; $billId = TransactionType::WITHDRAWAL === $type->type && null !== $bill ? $bill->id : null;
$description = app('steam')->cleanString((string)$row['description']); $description = app('steam')->cleanString((string) $row['description']);
/** Manipulate basic fields */ /** Manipulate basic fields */
$carbon->setTimezone(config('app.timezone')); $carbon->setTimezone(config('app.timezone'));
@@ -249,7 +260,7 @@ class TransactionJournalFactory
} }
/** create or get source and destination accounts */ /** create or get source and destination accounts */
$sourceInfo = [ $sourceInfo = [
'id' => (int)$row['source_id'], 'id' => (int) $row['source_id'],
'name' => $row['source_name'], 'name' => $row['source_name'],
'iban' => $row['source_iban'], 'iban' => $row['source_iban'],
'number' => $row['source_number'], 'number' => $row['source_number'],
@@ -257,7 +268,7 @@ class TransactionJournalFactory
]; ];
$destInfo = [ $destInfo = [
'id' => (int)$row['destination_id'], 'id' => (int) $row['destination_id'],
'name' => $row['destination_name'], 'name' => $row['destination_name'],
'iban' => $row['destination_iban'], 'iban' => $row['destination_iban'],
'number' => $row['destination_number'], 'number' => $row['destination_number'],
@@ -325,7 +336,7 @@ class TransactionJournalFactory
'transaction_type_id' => $type->id, 'transaction_type_id' => $type->id,
'bill_id' => $billId, 'bill_id' => $billId,
'transaction_currency_id' => $currency->id, 'transaction_currency_id' => $currency->id,
'description' => substr($description,0,1000), 'description' => substr($description, 0, 1000),
'date' => $carbon->format('Y-m-d H:i:s'), 'date' => $carbon->format('Y-m-d H:i:s'),
'order' => $order, 'order' => $order,
'tag_count' => 0, 'tag_count' => 0,
@@ -344,7 +355,7 @@ class TransactionJournalFactory
$transactionFactory->setForeignCurrency($sourceForeignCurrency); $transactionFactory->setForeignCurrency($sourceForeignCurrency);
$transactionFactory->setReconciled($row['reconciled'] ?? false); $transactionFactory->setReconciled($row['reconciled'] ?? false);
try { try {
$negative = $transactionFactory->createNegative((string)$row['amount'], (string)$row['foreign_amount']); $negative = $transactionFactory->createNegative((string) $row['amount'], (string) $row['foreign_amount']);
} catch (FireflyException $e) { } catch (FireflyException $e) {
Log::error('Exception creating negative transaction.'); Log::error('Exception creating negative transaction.');
Log::error($e->getMessage()); Log::error($e->getMessage());
@@ -363,7 +374,7 @@ class TransactionJournalFactory
$transactionFactory->setForeignCurrency($destForeignCurrency); $transactionFactory->setForeignCurrency($destForeignCurrency);
$transactionFactory->setReconciled($row['reconciled'] ?? false); $transactionFactory->setReconciled($row['reconciled'] ?? false);
try { try {
$transactionFactory->createPositive((string)$row['amount'], (string)$row['foreign_amount']); $transactionFactory->createPositive((string) $row['amount'], (string) $row['foreign_amount']);
} catch (FireflyException $e) { } catch (FireflyException $e) {
Log::error('Exception creating positive transaction.'); Log::error('Exception creating positive transaction.');
Log::error($e->getMessage()); Log::error($e->getMessage());
@@ -506,7 +517,7 @@ class TransactionJournalFactory
$json = json_encode($dataRow); $json = json_encode($dataRow);
if (false === $json) { if (false === $json) {
// @codeCoverageIgnoreStart // @codeCoverageIgnoreStart
$json = json_encode((string)microtime()); $json = json_encode((string) microtime());
Log::error(sprintf('Could not hash the original row! %s', json_last_error_msg()), $dataRow); Log::error(sprintf('Could not hash the original row! %s', json_last_error_msg()), $dataRow);
// @codeCoverageIgnoreEnd // @codeCoverageIgnoreEnd
} }
@@ -542,7 +553,7 @@ class TransactionJournalFactory
return; return;
} }
$piggyBank = $this->piggyRepository->findPiggyBank((int)$data['piggy_bank_id'], $data['piggy_bank_name']); $piggyBank = $this->piggyRepository->findPiggyBank((int) $data['piggy_bank_id'], $data['piggy_bank_name']);
if (null !== $piggyBank) { if (null !== $piggyBank) {
$this->piggyEventFactory->create($journal, $piggyBank); $this->piggyEventFactory->create($journal, $piggyBank);
@@ -565,7 +576,7 @@ class TransactionJournalFactory
$this->accountValidator->setTransactionType($transactionType); $this->accountValidator->setTransactionType($transactionType);
// validate source account. // validate source account.
$sourceId = isset($data['source_id']) ? (int)$data['source_id'] : null; $sourceId = isset($data['source_id']) ? (int) $data['source_id'] : null;
$sourceName = $data['source_name'] ?? null; $sourceName = $data['source_name'] ?? null;
$validSource = $this->accountValidator->validateSource($sourceId, $sourceName); $validSource = $this->accountValidator->validateSource($sourceId, $sourceName);
@@ -575,7 +586,7 @@ class TransactionJournalFactory
} }
Log::debug('Source seems valid.'); Log::debug('Source seems valid.');
// validate destination account // validate destination account
$destinationId = isset($data['destination_id']) ? (int)$data['destination_id'] : null; $destinationId = isset($data['destination_id']) ? (int) $data['destination_id'] : null;
$destinationName = $data['destination_name'] ?? null; $destinationName = $data['destination_name'] ?? null;
$validDestination = $this->accountValidator->validateDestination($destinationId, $destinationName); $validDestination = $this->accountValidator->validateDestination($destinationId, $destinationName);
// do something with result: // do something with result:
@@ -584,16 +595,5 @@ class TransactionJournalFactory
} }
} }
/**
* @param bool $errorOnHash
*/
public function setErrorOnHash(bool $errorOnHash): void
{
$this->errorOnHash = $errorOnHash;
if (true === $errorOnHash) {
Log::info('Will trigger duplication alert for this journal.');
}
}
} }

View File

@@ -36,6 +36,7 @@ class TransactionJournalMetaFactory
{ {
/** /**
* Constructor. * Constructor.
*
* @codeCoverageIgnore * @codeCoverageIgnore
*/ */
public function __construct() public function __construct()
@@ -71,7 +72,7 @@ class TransactionJournalMetaFactory
Log::debug('Is a carbon object.'); Log::debug('Is a carbon object.');
$value = $data['data']->toW3cString(); $value = $data['data']->toW3cString();
} }
if ('' === (string)$value) { if ('' === (string) $value) {
Log::debug('Is an empty string.'); Log::debug('Is an empty string.');
// don't store blank strings. // don't store blank strings.
if (null !== $entry) { if (null !== $entry) {

View File

@@ -35,6 +35,7 @@ class TransactionTypeFactory
{ {
/** /**
* Constructor. * Constructor.
*
* @codeCoverageIgnore * @codeCoverageIgnore
*/ */
public function __construct() public function __construct()

View File

@@ -63,7 +63,7 @@ class ChartJsGenerator implements GeneratorInterface
$amounts = array_column($data, 'amount'); $amounts = array_column($data, 'amount');
$next = next($amounts); $next = next($amounts);
$sortFlag = SORT_ASC; $sortFlag = SORT_ASC;
if (!is_bool($next) && 1 === bccomp((string)$next, '0')) { if (!is_bool($next) && 1 === bccomp((string) $next, '0')) {
$sortFlag = SORT_DESC; $sortFlag = SORT_DESC;
} }
array_multisort($amounts, $sortFlag, $data); array_multisort($amounts, $sortFlag, $data);
@@ -72,7 +72,7 @@ class ChartJsGenerator implements GeneratorInterface
$index = 0; $index = 0;
foreach ($data as $key => $valueArray) { foreach ($data as $key => $valueArray) {
// make larger than 0 // make larger than 0
$chartData['datasets'][0]['data'][] = (float)app('steam')->positive((string)$valueArray['amount']); $chartData['datasets'][0]['data'][] = (float) app('steam')->positive((string) $valueArray['amount']);
$chartData['datasets'][0]['backgroundColor'][] = ChartColour::getColour($index); $chartData['datasets'][0]['backgroundColor'][] = ChartColour::getColour($index);
$chartData['datasets'][0]['currency_symbol'][] = $valueArray['currency_symbol']; $chartData['datasets'][0]['currency_symbol'][] = $valueArray['currency_symbol'];
$chartData['labels'][] = $key; $chartData['labels'][] = $key;
@@ -178,7 +178,7 @@ class ChartJsGenerator implements GeneratorInterface
// different sort when values are positive and when they're negative. // different sort when values are positive and when they're negative.
asort($data); asort($data);
$next = next($data); $next = next($data);
if (!is_bool($next) && 1 === bccomp((string)$next, '0')) { if (!is_bool($next) && 1 === bccomp((string) $next, '0')) {
// next is positive, sort other way around. // next is positive, sort other way around.
arsort($data); arsort($data);
} }
@@ -187,7 +187,7 @@ class ChartJsGenerator implements GeneratorInterface
$index = 0; $index = 0;
foreach ($data as $key => $value) { foreach ($data as $key => $value) {
// make larger than 0 // make larger than 0
$chartData['datasets'][0]['data'][] = (float)app('steam')->positive((string)$value); $chartData['datasets'][0]['data'][] = (float) app('steam')->positive((string) $value);
$chartData['datasets'][0]['backgroundColor'][] = ChartColour::getColour($index); $chartData['datasets'][0]['backgroundColor'][] = ChartColour::getColour($index);
$chartData['labels'][] = $key; $chartData['labels'][] = $key;

View File

@@ -52,14 +52,14 @@ class MonthReportGenerator implements ReportGeneratorInterface
public function generate(): string public function generate(): string
{ {
$accountIds = implode(',', $this->accounts->pluck('id')->toArray()); $accountIds = implode(',', $this->accounts->pluck('id')->toArray());
$doubleIds = implode(',', $this->expense->pluck('id')->toArray()); $doubleIds = implode(',', $this->expense->pluck('id')->toArray());
$reportType = 'account'; $reportType = 'account';
$preferredPeriod = $this->preferredPeriod(); $preferredPeriod = $this->preferredPeriod();
try { try {
$result = view('reports.double.report', compact('accountIds', 'reportType', 'doubleIds', 'preferredPeriod')) $result = view('reports.double.report', compact('accountIds', 'reportType', 'doubleIds', 'preferredPeriod'))
->with('start', $this->start)->with('end', $this->end) ->with('start', $this->start)->with('end', $this->end)
->with('doubles', $this->expense) ->with('doubles', $this->expense)
->render(); ->render();
} catch (Throwable $e) { } catch (Throwable $e) {
Log::error(sprintf('Cannot render reports.double.report: %s', $e->getMessage())); Log::error(sprintf('Cannot render reports.double.report: %s', $e->getMessage()));
$result = sprintf('Could not render report view: %s', $e->getMessage()); $result = sprintf('Could not render report view: %s', $e->getMessage());

View File

@@ -51,9 +51,9 @@ class MonthReportGenerator implements ReportGeneratorInterface
/** /**
* Generates the report. * Generates the report.
* *
* @return string
* @throws FireflyException * @throws FireflyException
* @codeCoverageIgnore * @codeCoverageIgnore
* @return string
*/ */
public function generate(): string public function generate(): string
{ {
@@ -100,9 +100,9 @@ class MonthReportGenerator implements ReportGeneratorInterface
* @param Account $account * @param Account $account
* @param Carbon $date * @param Carbon $date
* *
* @throws FireflyException
* @return array * @return array
* *
* @throws FireflyException
*/ */
public function getAuditReport(Account $account, Carbon $date): array public function getAuditReport(Account $account, Carbon $date): array
{ {
@@ -117,7 +117,7 @@ class MonthReportGenerator implements ReportGeneratorInterface
/** @var GroupCollectorInterface $collector */ /** @var GroupCollectorInterface $collector */
$collector = app(GroupCollectorInterface::class); $collector = app(GroupCollectorInterface::class);
$collector->setAccounts(new Collection([$account]))->setRange($this->start, $this->end)->withAccountInformation() $collector->setAccounts(new Collection([$account]))->setRange($this->start, $this->end)->withAccountInformation()
->withBudgetInformation()->withCategoryInformation()->withBillInformation(); ->withBudgetInformation()->withCategoryInformation()->withBillInformation();
$journals = $collector->getExtractedJournals(); $journals = $collector->getExtractedJournals();
$journals = array_reverse($journals, true); $journals = array_reverse($journals, true);
$dayBeforeBalance = app('steam')->balance($account, $date); $dayBeforeBalance = app('steam')->balance($account, $date);
@@ -159,9 +159,9 @@ class MonthReportGenerator implements ReportGeneratorInterface
'journals' => $journals, 'journals' => $journals,
'currency' => $currency, 'currency' => $currency,
'exists' => count($journals) > 0, 'exists' => count($journals) > 0,
'end' => $this->end->formatLocalized((string)trans('config.month_and_day')), 'end' => $this->end->formatLocalized((string) trans('config.month_and_day')),
'endBalance' => app('steam')->balance($account, $this->end), 'endBalance' => app('steam')->balance($account, $this->end),
'dayBefore' => $date->formatLocalized((string)trans('config.month_and_day')), 'dayBefore' => $date->formatLocalized((string) trans('config.month_and_day')),
'dayBeforeBalance' => $dayBeforeBalance, 'dayBeforeBalance' => $dayBeforeBalance,
]; ];

View File

@@ -76,7 +76,7 @@ class MonthReportGenerator implements ReportGeneratorInterface
// render! // render!
try { try {
return view('reports.category.month', compact('accountIds', 'categoryIds', 'reportType',)) return view('reports.category.month', compact('accountIds', 'categoryIds', 'reportType', ))
->with('start', $this->start)->with('end', $this->end) ->with('start', $this->start)->with('end', $this->end)
->with('categories', $this->categories) ->with('categories', $this->categories)
->with('accounts', $this->accounts) ->with('accounts', $this->accounts)

View File

@@ -39,9 +39,9 @@ class ReportGeneratorFactory
* @param Carbon $start * @param Carbon $start
* @param Carbon $end * @param Carbon $end
* *
* @throws FireflyException
* @return ReportGeneratorInterface * @return ReportGeneratorInterface
* *
* @throws FireflyException
*/ */
public static function reportGenerator(string $type, Carbon $start, Carbon $end): ReportGeneratorInterface public static function reportGenerator(string $type, Carbon $start, Carbon $end): ReportGeneratorInterface
{ {

View File

@@ -76,7 +76,8 @@ class MonthReportGenerator implements ReportGeneratorInterface
// render! // render!
try { try {
$result = view( $result = view(
'reports.tag.month', compact('accountIds', 'reportType', 'tagIds') 'reports.tag.month',
compact('accountIds', 'reportType', 'tagIds')
)->with('start', $this->start)->with('end', $this->end)->with('tags', $this->tags)->with('accounts', $this->accounts)->render(); )->with('start', $this->start)->with('end', $this->end)->with('tags', $this->tags)->with('accounts', $this->accounts)->render();
} catch (Throwable $e) { } catch (Throwable $e) {
Log::error(sprintf('Cannot render reports.tag.month: %s', $e->getMessage())); Log::error(sprintf('Cannot render reports.tag.month: %s', $e->getMessage()));
@@ -177,6 +178,4 @@ class MonthReportGenerator implements ReportGeneratorInterface
return $this; return $this;
} }
} }

View File

@@ -58,10 +58,12 @@ class GroupCollector implements GroupCollectorInterface
private $hasBudgetInformation; private $hasBudgetInformation;
/** @var bool Will be true if query result contains category info. */ /** @var bool Will be true if query result contains category info. */
private $hasCatInformation; private $hasCatInformation;
/** @var bool Will be true of the query has the tag info tables joined. */
private $hasJoinedTagTables;
/** @var bool Will be true for attachments */ /** @var bool Will be true for attachments */
private $hasJoinedAttTables; private $hasJoinedAttTables;
/** @var bool Will be true of the query has the tag info tables joined. */
private $hasJoinedTagTables;
/** @var array */
private $integerFields;
/** @var int The maximum number of results. */ /** @var int The maximum number of results. */
private $limit; private $limit;
/** @var int The page to return. */ /** @var int The page to return. */
@@ -72,8 +74,6 @@ class GroupCollector implements GroupCollectorInterface
private $total; private $total;
/** @var User The user object. */ /** @var User The user object. */
private $user; private $user;
/** @var array */
private $integerFields;
/** /**
* Group collector constructor. * Group collector constructor.
@@ -210,7 +210,6 @@ class GroupCollector implements GroupCollectorInterface
*/ */
public function dumpQuery(): void public function dumpQuery(): void
{ {
echo $this->query->toSql(); echo $this->query->toSql();
echo '<pre>'; echo '<pre>';
print_r($this->query->getBindings()); print_r($this->query->getBindings());
@@ -304,7 +303,6 @@ class GroupCollector implements GroupCollectorInterface
} }
return $collection; return $collection;
} }
/** /**
@@ -331,7 +329,7 @@ class GroupCollector implements GroupCollectorInterface
$sum = '0'; $sum = '0';
/** @var array $journal */ /** @var array $journal */
foreach ($journals as $journal) { foreach ($journals as $journal) {
$amount = (string)$journal['amount']; $amount = (string) $journal['amount'];
$sum = bcadd($sum, $amount); $sum = bcadd($sum, $amount);
} }
@@ -510,6 +508,24 @@ class GroupCollector implements GroupCollectorInterface
return $this; return $this;
} }
/**
* Collect transactions created on a specific date.
*
* @param Carbon $date
*
* @return GroupCollectorInterface
*/
public function setCreatedAt(Carbon $date): GroupCollectorInterface
{
$after = $date->format('Y-m-d 00:00:00');
$before = $date->format('Y-m-d 23:59:59');
$this->query->where('transaction_journals.created_at', '>=', $after);
$this->query->where('transaction_journals.created_at', '<=', $before);
Log::debug(sprintf('GroupCollector created_at is now after %s (inclusive)', $after));
return $this;
}
/** /**
* Limit results to a specific currency, either foreign or normal one. * Limit results to a specific currency, either foreign or normal one.
* *
@@ -742,6 +758,24 @@ class GroupCollector implements GroupCollectorInterface
return $this; return $this;
} }
/**
* Collect transactions updated on a specific date.
*
* @param Carbon $date
*
* @return GroupCollectorInterface
*/
public function setUpdatedAt(Carbon $date): GroupCollectorInterface
{
$after = $date->format('Y-m-d 00:00:00');
$before = $date->format('Y-m-d 23:59:59');
$this->query->where('transaction_journals.updated_at', '>=', $after);
$this->query->where('transaction_journals.updated_at', '<=', $before);
Log::debug(sprintf('GroupCollector created_at is now after %s (inclusive)', $after));
return $this;
}
/** /**
* Set the user object and start the query. * Set the user object and start the query.
* *
@@ -757,6 +791,43 @@ class GroupCollector implements GroupCollectorInterface
return $this; return $this;
} }
/**
* Either account can be set, but NOT both. This effectively excludes internal transfers.
*
* @param Collection $accounts
*
* @return GroupCollectorInterface
*/
public function setXorAccounts(Collection $accounts): GroupCollectorInterface
{
if ($accounts->count() > 0) {
$accountIds = $accounts->pluck('id')->toArray();
$this->query->where(
static function (EloquentBuilder $q1) use ($accountIds) {
// sourceAccount is in the set, and destination is NOT.
$q1->where(
static function (EloquentBuilder $q2) use ($accountIds) {
$q2->whereIn('source.account_id', $accountIds);
$q2->whereNotIn('destination.account_id', $accountIds);
}
);
// destination is in the set, and source is NOT
$q1->orWhere(
static function (EloquentBuilder $q3) use ($accountIds) {
$q3->whereNotIn('source.account_id', $accountIds);
$q3->whereIn('destination.account_id', $accountIds);
}
);
}
);
app('log')->debug(sprintf('GroupCollector: setXorAccounts: %s', implode(', ', $accountIds)));
}
return $this;
}
/** /**
* Automatically include all stuff required to make API calls work. * Automatically include all stuff required to make API calls work.
* *
@@ -810,6 +881,17 @@ class GroupCollector implements GroupCollectorInterface
return $this; return $this;
} }
/**
* @inheritDoc
*/
public function withAttachmentInformation(): GroupCollectorInterface
{
$this->fields[] = 'attachments.id as attachment_id';
$this->joinAttachmentTables();
return $this;
}
/** /**
* Will include bill name + ID, if any. * Will include bill name + ID, if any.
* *
@@ -933,25 +1015,12 @@ class GroupCollector implements GroupCollectorInterface
private function convertToInteger(array $array): array private function convertToInteger(array $array): array
{ {
foreach ($this->integerFields as $field) { foreach ($this->integerFields as $field) {
$array[$field] = isset($array[$field]) ? (int)$array[$field] : null; $array[$field] = isset($array[$field]) ? (int) $array[$field] : null;
} }
return $array; return $array;
} }
/**
* Join table to get tag information.
*/
private function joinTagTables(): void
{
if (false === $this->hasJoinedTagTables) {
// join some extra tables:
$this->hasJoinedTagTables = true;
$this->query->leftJoin('tag_transaction_journal', 'tag_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id');
$this->query->leftJoin('tags', 'tag_transaction_journal.tag_id', '=', 'tags.id');
}
}
/** /**
* Join table to get attachment information. * Join table to get attachment information.
*/ */
@@ -971,33 +1040,16 @@ class GroupCollector implements GroupCollectorInterface
} }
/** /**
* @param array $existingJournal * Join table to get tag information.
* @param TransactionJournal $newJournal
*
* @return array
*/ */
private function mergeTags(array $existingJournal, TransactionJournal $newJournal): array private function joinTagTables(): void
{ {
$newArray = $newJournal->toArray(); if (false === $this->hasJoinedTagTables) {
if (isset($newArray['tag_id'])) { // assume the other fields are present as well. // join some extra tables:
$tagId = (int)$newJournal['tag_id']; $this->hasJoinedTagTables = true;
$this->query->leftJoin('tag_transaction_journal', 'tag_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id');
$tagDate = null; $this->query->leftJoin('tags', 'tag_transaction_journal.tag_id', '=', 'tags.id');
try {
$tagDate = Carbon::parse($newArray['tag_date']);
} catch (InvalidDateException $e) {
Log::debug(sprintf('Could not parse date: %s', $e->getMessage()));
}
$existingJournal['tags'][$tagId] = [
'id' => (int)$newArray['tag_id'],
'name' => $newArray['tag_name'],
'date' => $tagDate,
'description' => $newArray['tag_description'],
];
} }
return $existingJournal;
} }
/** /**
@@ -1010,7 +1062,7 @@ class GroupCollector implements GroupCollectorInterface
{ {
$newArray = $newJournal->toArray(); $newArray = $newJournal->toArray();
if (isset($newArray['attachment_id'])) { if (isset($newArray['attachment_id'])) {
$attachmentId = (int)$newJournal['tag_id']; $attachmentId = (int) $newJournal['tag_id'];
$existingJournal['attachments'][$attachmentId] = [ $existingJournal['attachments'][$attachmentId] = [
'id' => $attachmentId, 'id' => $attachmentId,
]; ];
@@ -1019,6 +1071,35 @@ class GroupCollector implements GroupCollectorInterface
return $existingJournal; return $existingJournal;
} }
/**
* @param array $existingJournal
* @param TransactionJournal $newJournal
*
* @return array
*/
private function mergeTags(array $existingJournal, TransactionJournal $newJournal): array
{
$newArray = $newJournal->toArray();
if (isset($newArray['tag_id'])) { // assume the other fields are present as well.
$tagId = (int) $newJournal['tag_id'];
$tagDate = null;
try {
$tagDate = Carbon::parse($newArray['tag_date']);
} catch (InvalidDateException $e) {
Log::debug(sprintf('Could not parse date: %s', $e->getMessage()));
}
$existingJournal['tags'][$tagId] = [
'id' => (int) $newArray['tag_id'],
'name' => $newArray['tag_name'],
'date' => $tagDate,
'description' => $newArray['tag_description'],
];
}
return $existingJournal;
}
/** /**
* @param Collection $collection * @param Collection $collection
@@ -1036,21 +1117,21 @@ class GroupCollector implements GroupCollectorInterface
// make new array // make new array
$parsedGroup = $this->parseAugmentedJournal($augumentedJournal); $parsedGroup = $this->parseAugmentedJournal($augumentedJournal);
$groupArray = [ $groupArray = [
'id' => (int)$augumentedJournal->transaction_group_id, 'id' => (int) $augumentedJournal->transaction_group_id,
'user_id' => (int)$augumentedJournal->user_id, 'user_id' => (int) $augumentedJournal->user_id,
'title' => $augumentedJournal->transaction_group_title, 'title' => $augumentedJournal->transaction_group_title,
'transaction_type' => $parsedGroup['transaction_type_type'], 'transaction_type' => $parsedGroup['transaction_type_type'],
'count' => 1, 'count' => 1,
'sums' => [], 'sums' => [],
'transactions' => [], 'transactions' => [],
]; ];
$journalId = (int)$augumentedJournal->transaction_journal_id; $journalId = (int) $augumentedJournal->transaction_journal_id;
$groupArray['transactions'][$journalId] = $parsedGroup; $groupArray['transactions'][$journalId] = $parsedGroup;
$groups[$groupId] = $groupArray; $groups[$groupId] = $groupArray;
continue; continue;
} }
// or parse the rest. // or parse the rest.
$journalId = (int)$augumentedJournal->transaction_journal_id; $journalId = (int) $augumentedJournal->transaction_journal_id;
$groups[$groupId]['count']++; $groups[$groupId]['count']++;
if (isset($groups[$groupId]['transactions'][$journalId])) { if (isset($groups[$groupId]['transactions'][$journalId])) {
@@ -1063,8 +1144,6 @@ class GroupCollector implements GroupCollectorInterface
// create second, third, fourth split: // create second, third, fourth split:
$groups[$groupId]['transactions'][$journalId] = $this->parseAugmentedJournal($augumentedJournal); $groups[$groupId]['transactions'][$journalId] = $this->parseAugmentedJournal($augumentedJournal);
} }
} }
$groups = $this->parseSums($groups); $groups = $this->parseSums($groups);
@@ -1093,9 +1172,9 @@ class GroupCollector implements GroupCollectorInterface
// convert values to integers: // convert values to integers:
$result = $this->convertToInteger($result); $result = $this->convertToInteger($result);
$result['reconciled'] = 1 === (int)$result['reconciled']; $result['reconciled'] = 1 === (int) $result['reconciled'];
if (isset($augumentedJournal['tag_id'])) { // assume the other fields are present as well. if (isset($augumentedJournal['tag_id'])) { // assume the other fields are present as well.
$tagId = (int)$augumentedJournal['tag_id']; $tagId = (int) $augumentedJournal['tag_id'];
$tagDate = null; $tagDate = null;
try { try {
$tagDate = Carbon::parse($augumentedJournal['tag_date']); $tagDate = Carbon::parse($augumentedJournal['tag_date']);
@@ -1104,7 +1183,7 @@ class GroupCollector implements GroupCollectorInterface
} }
$result['tags'][$tagId] = [ $result['tags'][$tagId] = [
'id' => (int)$result['tag_id'], 'id' => (int) $result['tag_id'],
'name' => $result['tag_name'], 'name' => $result['tag_name'],
'date' => $tagDate, 'date' => $tagDate,
'description' => $result['tag_description'], 'description' => $result['tag_description'],
@@ -1113,7 +1192,7 @@ class GroupCollector implements GroupCollectorInterface
// also merge attachments: // also merge attachments:
if (isset($augumentedJournal['attachment_id'])) { if (isset($augumentedJournal['attachment_id'])) {
$attachmentId = (int)$augumentedJournal['attachment_id']; $attachmentId = (int) $augumentedJournal['attachment_id'];
$result['attachments'][$attachmentId] = [ $result['attachments'][$attachmentId] = [
'id' => $attachmentId, 'id' => $attachmentId,
]; ];
@@ -1136,7 +1215,7 @@ class GroupCollector implements GroupCollectorInterface
foreach ($groups as $groudId => $group) { foreach ($groups as $groudId => $group) {
/** @var array $transaction */ /** @var array $transaction */
foreach ($group['transactions'] as $transaction) { foreach ($group['transactions'] as $transaction) {
$currencyId = (int)$transaction['currency_id']; $currencyId = (int) $transaction['currency_id'];
// set default: // set default:
if (!isset($groups[$groudId]['sums'][$currencyId])) { if (!isset($groups[$groudId]['sums'][$currencyId])) {
@@ -1149,7 +1228,7 @@ class GroupCollector implements GroupCollectorInterface
$groups[$groudId]['sums'][$currencyId]['amount'] = bcadd($groups[$groudId]['sums'][$currencyId]['amount'], $transaction['amount'] ?? '0'); $groups[$groudId]['sums'][$currencyId]['amount'] = bcadd($groups[$groudId]['sums'][$currencyId]['amount'], $transaction['amount'] ?? '0');
if (null !== $transaction['foreign_amount'] && null !== $transaction['foreign_currency_id']) { if (null !== $transaction['foreign_amount'] && null !== $transaction['foreign_currency_id']) {
$currencyId = (int)$transaction['foreign_currency_id']; $currencyId = (int) $transaction['foreign_currency_id'];
// set default: // set default:
if (!isset($groups[$groudId]['sums'][$currencyId])) { if (!isset($groups[$groudId]['sums'][$currencyId])) {
@@ -1160,7 +1239,8 @@ class GroupCollector implements GroupCollectorInterface
$groups[$groudId]['sums'][$currencyId]['amount'] = '0'; $groups[$groudId]['sums'][$currencyId]['amount'] = '0';
} }
$groups[$groudId]['sums'][$currencyId]['amount'] = bcadd( $groups[$groudId]['sums'][$currencyId]['amount'] = bcadd(
$groups[$groudId]['sums'][$currencyId]['amount'], $transaction['foreign_amount'] ?? '0' $groups[$groudId]['sums'][$currencyId]['amount'],
$transaction['foreign_amount'] ?? '0'
); );
} }
} }
@@ -1183,17 +1263,19 @@ class GroupCollector implements GroupCollectorInterface
// join source transaction. // join source transaction.
->leftJoin( ->leftJoin(
'transactions as source', function (JoinClause $join) { 'transactions as source',
$join->on('source.transaction_journal_id', '=', 'transaction_journals.id') function (JoinClause $join) {
$join->on('source.transaction_journal_id', '=', 'transaction_journals.id')
->where('source.amount', '<', 0); ->where('source.amount', '<', 0);
} }
) )
// join destination transaction // join destination transaction
->leftJoin( ->leftJoin(
'transactions as destination', function (JoinClause $join) { 'transactions as destination',
$join->on('destination.transaction_journal_id', '=', 'transaction_journals.id') function (JoinClause $join) {
$join->on('destination.transaction_journal_id', '=', 'transaction_journals.id')
->where('destination.amount', '>', 0); ->where('destination.amount', '>', 0);
} }
) )
// left join transaction type. // left join transaction type.
->leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id') ->leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id')
@@ -1209,88 +1291,4 @@ class GroupCollector implements GroupCollectorInterface
->orderBy('transaction_journals.description', 'DESC') ->orderBy('transaction_journals.description', 'DESC')
->orderBy('source.amount', 'DESC'); ->orderBy('source.amount', 'DESC');
} }
/**
* Either account can be set, but NOT both. This effectively excludes internal transfers.
*
* @param Collection $accounts
*
* @return GroupCollectorInterface
*/
public function setXorAccounts(Collection $accounts): GroupCollectorInterface
{
if ($accounts->count() > 0) {
$accountIds = $accounts->pluck('id')->toArray();
$this->query->where(
static function (EloquentBuilder $q1) use ($accountIds) {
// sourceAccount is in the set, and destination is NOT.
$q1->where(
static function (EloquentBuilder $q2) use ($accountIds) {
$q2->whereIn('source.account_id', $accountIds);
$q2->whereNotIn('destination.account_id', $accountIds);
}
);
// destination is in the set, and source is NOT
$q1->orWhere(
static function (EloquentBuilder $q3) use ($accountIds) {
$q3->whereNotIn('source.account_id', $accountIds);
$q3->whereIn('destination.account_id', $accountIds);
}
);
}
);
app('log')->debug(sprintf('GroupCollector: setXorAccounts: %s', implode(', ', $accountIds)));
}
return $this;
}
/**
* Collect transactions created on a specific date.
*
* @param Carbon $date
*
* @return GroupCollectorInterface
*/
public function setCreatedAt(Carbon $date): GroupCollectorInterface
{
$after = $date->format('Y-m-d 00:00:00');
$before = $date->format('Y-m-d 23:59:59');
$this->query->where('transaction_journals.created_at', '>=', $after);
$this->query->where('transaction_journals.created_at', '<=', $before);
Log::debug(sprintf('GroupCollector created_at is now after %s (inclusive)', $after));
return $this;
}
/**
* Collect transactions updated on a specific date.
*
* @param Carbon $date
*
* @return GroupCollectorInterface
*/
public function setUpdatedAt(Carbon $date): GroupCollectorInterface
{
$after = $date->format('Y-m-d 00:00:00');
$before = $date->format('Y-m-d 23:59:59');
$this->query->where('transaction_journals.updated_at', '>=', $after);
$this->query->where('transaction_journals.updated_at', '<=', $before);
Log::debug(sprintf('GroupCollector created_at is now after %s (inclusive)', $after));
return $this;
}
/**
* @inheritDoc
*/
public function withAttachmentInformation(): GroupCollectorInterface
{
$this->fields[] = 'attachments.id as attachment_id';
$this->joinAttachmentTables();
return $this;
}
} }