Some generic code refactoring.

This commit is contained in:
James Cole
2019-06-21 19:10:02 +02:00
parent fb1af395f9
commit 2d3d7f7720
67 changed files with 920 additions and 603 deletions

View File

@@ -32,6 +32,7 @@ class ChartJsGenerator implements GeneratorInterface
{ {
/** /**
* Constructor. * Constructor.
* @codeCoverageIgnore
*/ */
public function __construct() public function __construct()
{ {

View File

@@ -83,71 +83,13 @@ class MonthReportGenerator implements ReportGeneratorInterface
->render(); ->render();
} catch (Throwable $e) { } catch (Throwable $e) {
Log::error(sprintf('Cannot render reports.audit.report: %s', $e->getMessage())); Log::error(sprintf('Cannot render reports.audit.report: %s', $e->getMessage()));
$result = 'Could not render report view.'; Log::error($e->getTraceAsString());
$result = sprintf('Could not render report view: %s', $e->getMessage());
} }
return $result; return $result;
} }
/**
* Get the audit report.
*
* @param Account $account
* @param Carbon $date
*
* @return array
*
* @SuppressWarnings(PHPMD.ExcessiveMethodLength) // not that long
* @throws FireflyException
*/
public function getAuditReport(Account $account, Carbon $date): array
{
/** @var CurrencyRepositoryInterface $currencyRepos */
$currencyRepos = app(CurrencyRepositoryInterface::class);
/** @var AccountRepositoryInterface $accountRepository */
$accountRepository = app(AccountRepositoryInterface::class);
$accountRepository->setUser($account->user);
/** @var GroupCollectorInterface $collector */
$collector = app(GroupCollectorInterface::class);
$collector->setAccounts(new Collection([$account]))->setRange($this->start, $this->end)
->withAccountInformation();
$journals = $collector->getExtractedJournals();
$dayBeforeBalance = app('steam')->balance($account, $date);
$startBalance = $dayBeforeBalance;
$currency = $currencyRepos->findNull((int)$accountRepository->getMetaValue($account, 'currency_id'));
if (null === $currency) {
throw new FireflyException('Unexpected NULL value in account currency preference.');
}
foreach ($journals as $index => $journal) {
$journals[$index]['balance_before'] = $startBalance;
$transactionAmount = $journal['amount'];
if ($currency->id === $journal['foreign_currency_id']) {
$transactionAmount = $journal['foreign_amount'];
}
$newBalance = bcadd($startBalance, $transactionAmount);
$journals[$index]['balance_after'] = $newBalance;
$startBalance = $newBalance;
}
$return = [
'journals' => $journals,
'exists' => count($journals) > 0,
'end' => $this->end->formatLocalized((string)trans('config.month_and_day')),
'endBalance' => app('steam')->balance($account, $this->end),
'dayBefore' => $date->formatLocalized((string)trans('config.month_and_day')),
'dayBeforeBalance' => $dayBeforeBalance,
];
return $return;
}
/** /**
* Account collection setter. * Account collection setter.
* *
@@ -214,6 +156,7 @@ class MonthReportGenerator implements ReportGeneratorInterface
*/ */
public function setExpense(Collection $expense): ReportGeneratorInterface public function setExpense(Collection $expense): ReportGeneratorInterface
{ {
// doesn't use expense collection.
return $this; return $this;
} }
@@ -244,4 +187,62 @@ class MonthReportGenerator implements ReportGeneratorInterface
{ {
return $this; return $this;
} }
/**
* Get the audit report.
*
* @param Account $account
* @param Carbon $date
*
* @return array
*
* @throws FireflyException
*/
public function getAuditReport(Account $account, Carbon $date): array
{
/** @var CurrencyRepositoryInterface $currencyRepos */
$currencyRepos = app(CurrencyRepositoryInterface::class);
/** @var AccountRepositoryInterface $accountRepository */
$accountRepository = app(AccountRepositoryInterface::class);
$accountRepository->setUser($account->user);
/** @var GroupCollectorInterface $collector */
$collector = app(GroupCollectorInterface::class);
$collector->setAccounts(new Collection([$account]))->setRange($this->start, $this->end)
->withAccountInformation();
$journals = $collector->getExtractedJournals();
$dayBeforeBalance = app('steam')->balance($account, $date);
$startBalance = $dayBeforeBalance;
$currency = $currencyRepos->findNull((int)$accountRepository->getMetaValue($account, 'currency_id'));
if (null === $currency) {
throw new FireflyException('Unexpected NULL value in account currency preference.'); // @codeCoverageIgnore
}
foreach ($journals as $index => $journal) {
$journals[$index]['balance_before'] = $startBalance;
$transactionAmount = $journal['amount'];
if ($currency->id === $journal['foreign_currency_id']) {
$transactionAmount = $journal['foreign_amount'];
}
$newBalance = bcadd($startBalance, $transactionAmount);
$journals[$index]['balance_after'] = $newBalance;
$startBalance = $newBalance;
}
$return = [
'journals' => $journals,
'exists' => count($journals) > 0,
'end' => $this->end->formatLocalized((string)trans('config.month_and_day')),
'endBalance' => app('steam')->balance($account, $this->end),
'dayBefore' => $date->formatLocalized((string)trans('config.month_and_day')),
'dayBeforeBalance' => $dayBeforeBalance,
];
return $return;
}
} }

View File

@@ -43,7 +43,6 @@ use Mail;
* This class responds to any events that have anything to do with the User object. * This class responds to any events that have anything to do with the User object.
* *
* The method name reflects what is being done. This is in the present tense. * The method name reflects what is being done. This is in the present tense.
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/ */
class UserEventHandler class UserEventHandler
{ {

View File

@@ -56,6 +56,7 @@ class AttachmentHelper implements AttachmentHelperInterface
/** /**
* AttachmentHelper constructor. * AttachmentHelper constructor.
* @codeCoverageIgnore
*/ */
public function __construct() public function __construct()
{ {
@@ -98,7 +99,7 @@ class AttachmentHelper implements AttachmentHelperInterface
* Returns the file path relative to upload disk for an attachment, * Returns the file path relative to upload disk for an attachment,
* *
* @param Attachment $attachment * @param Attachment $attachment
* * @codeCoverageIgnore
* @return string * @return string
*/ */
public function getAttachmentLocation(Attachment $attachment): string public function getAttachmentLocation(Attachment $attachment): string
@@ -108,7 +109,7 @@ class AttachmentHelper implements AttachmentHelperInterface
/** /**
* Get all attachments. * Get all attachments.
* * @codeCoverageIgnore
* @return Collection * @return Collection
*/ */
public function getAttachments(): Collection public function getAttachments(): Collection
@@ -120,6 +121,7 @@ class AttachmentHelper implements AttachmentHelperInterface
* Get all errors. * Get all errors.
* *
* @return MessageBag * @return MessageBag
* @codeCoverageIgnore
*/ */
public function getErrors(): MessageBag public function getErrors(): MessageBag
{ {
@@ -130,13 +132,13 @@ class AttachmentHelper implements AttachmentHelperInterface
* Get all messages. * Get all messages.
* *
* @return MessageBag * @return MessageBag
* @codeCoverageIgnore
*/ */
public function getMessages(): MessageBag public function getMessages(): MessageBag
{ {
return $this->messages; return $this->messages;
} }
/** @noinspection MultipleReturnStatementsInspection */
/** /**
* Uploads a file as a string. * Uploads a file as a string.
* *
@@ -160,7 +162,7 @@ class AttachmentHelper implements AttachmentHelperInterface
$finfo = finfo_open(FILEINFO_MIME_TYPE); $finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $path); $mime = finfo_file($finfo, $path);
$allowedMime = config('firefly.allowedMimes'); $allowedMime = config('firefly.allowedMimes');
if (!\in_array($mime, $allowedMime, true)) { if (!in_array($mime, $allowedMime, true)) {
Log::error(sprintf('Mime type %s is not allowed for API file upload.', $mime)); Log::error(sprintf('Mime type %s is not allowed for API file upload.', $mime));
return false; return false;
@@ -307,7 +309,7 @@ class AttachmentHelper implements AttachmentHelperInterface
Log::debug('Valid mimes are', $this->allowedMimes); Log::debug('Valid mimes are', $this->allowedMimes);
$result = true; $result = true;
if (!\in_array($mime, $this->allowedMimes, true)) { if (!in_array($mime, $this->allowedMimes, true)) {
$msg = (string)trans('validation.file_invalid_mime', ['name' => $name, 'mime' => $mime]); $msg = (string)trans('validation.file_invalid_mime', ['name' => $name, 'mime' => $mime]);
$this->errors->add('attachments', $msg); $this->errors->add('attachments', $msg);
Log::error($msg); Log::error($msg);

View File

@@ -163,9 +163,6 @@ class MetaPieChart implements MetaPieChartInterface
$collector->setBudgets($this->budgets); $collector->setBudgets($this->budgets);
$collector->setCategories($this->categories); $collector->setCategories($this->categories);
$collector->withCategoryInformation();
$collector->withBudgetInformation();
// @codeCoverageIgnoreStart // @codeCoverageIgnoreStart
if ($this->tags->count() > 0) { if ($this->tags->count() > 0) {
$collector->setTags($this->tags); $collector->setTags($this->tags);

View File

@@ -42,6 +42,7 @@ use Log;
/** /**
* Class GroupCollector * Class GroupCollector
* @codeCoverageIgnore
*/ */
class GroupCollector implements GroupCollectorInterface class GroupCollector implements GroupCollectorInterface
{ {
@@ -50,7 +51,7 @@ class GroupCollector implements GroupCollectorInterface
/** @var array The standard fields to select. */ /** @var array The standard fields to select. */
private $fields; private $fields;
/** @var bool Will be set to true if query result contains account information. (see function withAccountInformation). */ /** @var bool Will be set to true if query result contains account information. (see function withAccountInformation). */
private $hasAccountInformation; private $hasAccountInfo;
/** @var bool Will be true if query result includes bill information. */ /** @var bool Will be true if query result includes bill information. */
private $hasBillInformation; private $hasBillInformation;
/** @var bool Will be true if query result contains budget info. */ /** @var bool Will be true if query result contains budget info. */
@@ -78,11 +79,11 @@ class GroupCollector implements GroupCollectorInterface
if ('testing' === config('app.env')) { if ('testing' === config('app.env')) {
app('log')->warning(sprintf('%s should not be instantiated in the TEST environment!', get_class($this))); app('log')->warning(sprintf('%s should not be instantiated in the TEST environment!', get_class($this)));
} }
$this->hasAccountInformation = false; $this->hasAccountInfo = false;
$this->hasCatInformation = false; $this->hasCatInformation = false;
$this->hasBudgetInformation = false; $this->hasBudgetInformation = false;
$this->hasBillInformation = false; $this->hasBillInformation = false;
$this->hasJoinedTagTables = false; $this->hasJoinedTagTables = false;
$this->total = 0; $this->total = 0;
$this->limit = 50; $this->limit = 50;
@@ -174,7 +175,7 @@ class GroupCollector implements GroupCollectorInterface
if ($accounts->count() > 0) { if ($accounts->count() > 0) {
$accountIds = $accounts->pluck('id')->toArray(); $accountIds = $accounts->pluck('id')->toArray();
$this->query->where( $this->query->where(
function (EloquentBuilder $query) use ($accountIds) { static function (EloquentBuilder $query) use ($accountIds) {
$query->whereIn('source.account_id', $accountIds); $query->whereIn('source.account_id', $accountIds);
$query->orWhereIn('destination.account_id', $accountIds); $query->orWhereIn('destination.account_id', $accountIds);
} }
@@ -482,7 +483,7 @@ class GroupCollector implements GroupCollectorInterface
*/ */
public function withAccountInformation(): GroupCollectorInterface public function withAccountInformation(): GroupCollectorInterface
{ {
if (false === $this->hasAccountInformation) { if (false === $this->hasAccountInfo) {
// join source account table // join source account table
$this->query->leftJoin('accounts as source_account', 'source_account.id', '=', 'source.account_id'); $this->query->leftJoin('accounts as source_account', 'source_account.id', '=', 'source.account_id');
// join source account type table // join source account type table
@@ -503,7 +504,7 @@ class GroupCollector implements GroupCollectorInterface
$this->fields[] = 'dest_account_type.type as destination_account_type'; $this->fields[] = 'dest_account_type.type as destination_account_type';
$this->hasAccountInformation = true; $this->hasAccountInfo = true;
} }
return $this; return $this;
@@ -777,7 +778,6 @@ class GroupCollector implements GroupCollectorInterface
* @param Collection $collection * @param Collection $collection
* *
* @return Collection * @return Collection
* @throws Exception
*/ */
private function parseArray(Collection $collection): Collection private function parseArray(Collection $collection): Collection
{ {
@@ -823,15 +823,18 @@ class GroupCollector implements GroupCollectorInterface
* @param TransactionGroup $augmentedGroup * @param TransactionGroup $augmentedGroup
* *
* @return array * @return array
* @throws Exception
*/ */
private function parseAugmentedGroup(TransactionGroup $augmentedGroup): array private function parseAugmentedGroup(TransactionGroup $augmentedGroup): array
{ {
$result = $augmentedGroup->toArray(); $result = $augmentedGroup->toArray();
$result['tags'] = []; $result['tags'] = [];
$result['date'] = new Carbon($result['date']); try {
$result['created_at'] = new Carbon($result['created_at']); $result['date'] = new Carbon($result['date']);
$result['updated_at'] = new Carbon($result['updated_at']); $result['created_at'] = new Carbon($result['created_at']);
$result['updated_at'] = new Carbon($result['updated_at']);
} catch (Exception $e) {
Log::error($e->getMessage());
}
$result['reconciled'] = 1 === (int)$result['reconciled']; $result['reconciled'] = 1 === (int)$result['reconciled'];
if (isset($augmentedGroup['tag_id'])) { // assume the other fields are present as well. if (isset($augmentedGroup['tag_id'])) { // assume the other fields are present as well.
$tagId = (int)$augmentedGroup['tag_id']; $tagId = (int)$augmentedGroup['tag_id'];

View File

@@ -25,12 +25,14 @@ namespace FireflyIII\Helpers\Collector;
use Carbon\Carbon; use Carbon\Carbon;
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Models\Transaction; use FireflyIII\Models\Transaction;
use FireflyIII\User; use FireflyIII\User;
use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\Relations\HasMany;
/** /**
* Class GroupSumCollector * Class GroupSumCollector
* @codeCoverageIgnore
*/ */
class GroupSumCollector implements GroupSumCollectorInterface class GroupSumCollector implements GroupSumCollectorInterface
{ {
@@ -48,6 +50,7 @@ class GroupSumCollector implements GroupSumCollectorInterface
*/ */
public function __construct() public function __construct()
{ {
throw new FireflyException('I dont work. dont use me');
$this->hasJoinedTypeTable = false; $this->hasJoinedTypeTable = false;
$this->fields = [ $this->fields = [
'transactions.amount', 'transactions.amount',
@@ -158,6 +161,21 @@ class GroupSumCollector implements GroupSumCollectorInterface
return $this; return $this;
} }
/**
* @param Carbon $start
* @param Carbon $end
*
* @return GroupSumCollectorInterface
*/
public function setRange(Carbon $start, Carbon $end): GroupSumCollectorInterface
{
$this->query
->where('transaction_journals.date', '>=', $start->format('Y-m-d H:i:s'))
->where('transaction_journals.date', '<=', $end->format('Y-m-d H:i:s'));
return $this;
}
private function joinTypeTable(): void private function joinTypeTable(): void
{ {
$this->hasJoinedTypeTable = true; $this->hasJoinedTypeTable = true;
@@ -178,18 +196,4 @@ class GroupSumCollector implements GroupSumCollectorInterface
->whereNull('transactions.deleted_at') ->whereNull('transactions.deleted_at')
->where('transactions.amount', '>', 0); ->where('transactions.amount', '>', 0);
} }
/**
* @param Carbon $start
* @param Carbon $end
*
* @return GroupSumCollectorInterface
*/
public function setRange(Carbon $start, Carbon $end): GroupSumCollectorInterface
{
$this->query
->where('transaction_journals.date','>=',$start->format('Y-m-d H:i:s'))
->where('transaction_journals.date','<=',$end->format('Y-m-d H:i:s'));
return $this;
}
} }

View File

@@ -28,6 +28,7 @@ use FireflyIII\User;
/** /**
* Interface GroupSumCollectorInterface * Interface GroupSumCollectorInterface
* @codeCoverageIgnore
*/ */
interface GroupSumCollectorInterface interface GroupSumCollectorInterface
{ {

View File

@@ -1,7 +1,7 @@
<?php <?php
/** /**
* FiscalHelper.php * FiscalHelper.php
* Copyright (c) 2017 thegrumpydictator@gmail.com * Copyright (c) 2019 thegrumpydictator@gmail.com
* *
* This file is part of Firefly III. * This file is part of Firefly III.
* *
@@ -20,7 +20,7 @@
*/ */
declare(strict_types=1); declare(strict_types=1);
namespace FireflyIII\Helpers; namespace FireflyIII\Helpers\Fiscal;
use Carbon\Carbon; use Carbon\Carbon;
use Log; use Log;

View File

@@ -1,7 +1,7 @@
<?php <?php
/** /**
* FiscalHelperInterface.php * FiscalHelperInterface.php
* Copyright (c) 2017 thegrumpydictator@gmail.com * Copyright (c) 2019 thegrumpydictator@gmail.com
* *
* This file is part of Firefly III. * This file is part of Firefly III.
* *
@@ -20,7 +20,7 @@
*/ */
declare(strict_types=1); declare(strict_types=1);
namespace FireflyIII\Helpers; namespace FireflyIII\Helpers\Fiscal;
use Carbon\Carbon; use Carbon\Carbon;

View File

@@ -37,7 +37,7 @@ class Help implements HelpInterface
/** @var string The cache key */ /** @var string The cache key */
public const CACHEKEY = 'help_%s_%s'; public const CACHEKEY = 'help_%s_%s';
/** @var string The user agent. */ /** @var string The user agent. */
protected $userAgent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36'; protected $userAgent = 'Firefly III v%s';
/** /**
* Constructor. * Constructor.
@@ -47,6 +47,7 @@ class Help implements HelpInterface
if ('testing' === config('app.env')) { if ('testing' === config('app.env')) {
Log::warning(sprintf('%s should not be instantiated in the TEST environment!', get_class($this))); Log::warning(sprintf('%s should not be instantiated in the TEST environment!', get_class($this)));
} }
$this->userAgent = sprintf($this->userAgent, config('firefly.version'));
} }
/** /**

View File

@@ -26,7 +26,7 @@ use Carbon\Carbon;
use FireflyIII\Helpers\Collection\Bill as BillCollection; use FireflyIII\Helpers\Collection\Bill as BillCollection;
use FireflyIII\Helpers\Collection\BillLine; use FireflyIII\Helpers\Collection\BillLine;
use FireflyIII\Helpers\Collector\GroupCollectorInterface; use FireflyIII\Helpers\Collector\GroupCollectorInterface;
use FireflyIII\Helpers\FiscalHelperInterface; use FireflyIII\Helpers\Fiscal\FiscalHelperInterface;
use FireflyIII\Models\Bill; use FireflyIII\Models\Bill;
use FireflyIII\Repositories\Bill\BillRepositoryInterface; use FireflyIII\Repositories\Bill\BillRepositoryInterface;
use FireflyIII\Repositories\Budget\BudgetRepositoryInterface; use FireflyIII\Repositories\Budget\BudgetRepositoryInterface;

View File

@@ -123,10 +123,12 @@ trait UpdateTrait
$return = (string)trans('firefly.update_newer_version_alert', ['your_version' => $current, 'new_version' => $release->getTitle()]); $return = (string)trans('firefly.update_newer_version_alert', ['your_version' => $current, 'new_version' => $release->getTitle()]);
} }
// @codeCoverageIgnoreStart
if (false === $triggered) { if (false === $triggered) {
Log::debug('No option was triggered.'); Log::debug('No option was triggered.');
$return = (string)trans('firefly.update_check_error'); $return = (string)trans('firefly.update_check_error');
} }
// @codeCoverageIgnoreEnd
return $return; return $return;
} }

View File

@@ -213,7 +213,7 @@ class DebugController extends Controller
/** @var Route $route */ /** @var Route $route */
foreach ($set as $route) { foreach ($set as $route) {
$name = (string)$route->getName(); $name = (string)$route->getName();
if (\in_array('GET', $route->methods(), true)) { if (in_array('GET', $route->methods(), true)) {
$found = false; $found = false;
foreach ($ignore as $string) { foreach ($ignore as $string) {
if (!(false === stripos($name, $string))) { if (!(false === stripos($name, $string))) {

View File

@@ -75,7 +75,7 @@ class JobConfigurationController extends Controller
{ {
Log::debug('Now in JobConfigurationController::index()'); Log::debug('Now in JobConfigurationController::index()');
$allowed = ['has_prereq', 'need_job_config']; $allowed = ['has_prereq', 'need_job_config'];
if (null !== $importJob && !\in_array($importJob->status, $allowed, true)) { if (null !== $importJob && !in_array($importJob->status, $allowed, true)) {
Log::error(sprintf('Job has state "%s", but we only accept %s', $importJob->status, json_encode($allowed))); Log::error(sprintf('Job has state "%s", but we only accept %s', $importJob->status, json_encode($allowed)));
session()->flash('error', (string)trans('import.bad_job_status', ['status' => $importJob->status])); session()->flash('error', (string)trans('import.bad_job_status', ['status' => $importJob->status]));
@@ -126,7 +126,7 @@ class JobConfigurationController extends Controller
{ {
// catch impossible status: // catch impossible status:
$allowed = ['has_prereq', 'need_job_config']; $allowed = ['has_prereq', 'need_job_config'];
if (null !== $importJob && !\in_array($importJob->status, $allowed, true)) { if (null !== $importJob && !in_array($importJob->status, $allowed, true)) {
session()->flash('error', (string)trans('import.bad_job_status', ['status' => $importJob->status])); session()->flash('error', (string)trans('import.bad_job_status', ['status' => $importJob->status]));
return redirect(route('import.index')); return redirect(route('import.index'));

View File

@@ -139,7 +139,7 @@ class JobStatusController extends Controller
// catch impossible status: // catch impossible status:
$allowed = ['ready_to_run', 'need_job_config']; $allowed = ['ready_to_run', 'need_job_config'];
if (null !== $importJob && !\in_array($importJob->status, $allowed, true)) { if (null !== $importJob && !in_array($importJob->status, $allowed, true)) {
Log::error(sprintf('Job is not ready. Status should be in array, but is %s', $importJob->status), $allowed); Log::error(sprintf('Job is not ready. Status should be in array, but is %s', $importJob->status), $allowed);
$this->repository->setStatus($importJob, 'error'); $this->repository->setStatus($importJob, 'error');
@@ -202,7 +202,7 @@ class JobStatusController extends Controller
Log::info('Now in JobStatusController::store'); Log::info('Now in JobStatusController::store');
// catch impossible status: // catch impossible status:
$allowed = ['provider_finished', 'storing_data']; $allowed = ['provider_finished', 'storing_data'];
if (null !== $importJob && !\in_array($importJob->status, $allowed, true)) { if (null !== $importJob && !in_array($importJob->status, $allowed, true)) {
Log::error(sprintf('Job is not ready. Status should be in array, but is %s', $importJob->status), $allowed); Log::error(sprintf('Job is not ready. Status should be in array, but is %s', $importJob->status), $allowed);
return response()->json( return response()->json(

View File

@@ -74,7 +74,7 @@ class PrerequisitesController extends Controller
{ {
// catch impossible status: // catch impossible status:
$allowed = ['new']; $allowed = ['new'];
if (null !== $importJob && !\in_array($importJob->status, $allowed, true)) { if (null !== $importJob && !in_array($importJob->status, $allowed, true)) {
Log::error(sprintf('Job has state "%s" but this Prerequisites::index() only accepts %s', $importJob->status, json_encode($allowed))); Log::error(sprintf('Job has state "%s" but this Prerequisites::index() only accepts %s', $importJob->status, json_encode($allowed)));
session()->flash('error', (string)trans('import.bad_job_status', ['status' => $importJob->status])); session()->flash('error', (string)trans('import.bad_job_status', ['status' => $importJob->status]));
@@ -127,7 +127,7 @@ class PrerequisitesController extends Controller
// catch impossible status: // catch impossible status:
$allowed = ['new']; $allowed = ['new'];
if (null !== $importJob && !\in_array($importJob->status, $allowed, true)) { if (null !== $importJob && !in_array($importJob->status, $allowed, true)) {
Log::error(sprintf('Job has state "%s" but this Prerequisites::post() only accepts %s', $importJob->status, json_encode($allowed))); Log::error(sprintf('Job has state "%s" but this Prerequisites::post() only accepts %s', $importJob->status, json_encode($allowed)));
session()->flash('error', (string)trans('import.bad_job_status', ['status' => $importJob->status])); session()->flash('error', (string)trans('import.bad_job_status', ['status' => $importJob->status]));

View File

@@ -24,7 +24,6 @@ namespace FireflyIII\Http\Requests;
use FireflyIII\Models\Account; use FireflyIII\Models\Account;
use FireflyIII\Rules\UniqueIban; use FireflyIII\Rules\UniqueIban;
use FireflyIII\Rules\ZeroOrMore;
/** /**
* Class AccountFormRequest. * Class AccountFormRequest.
@@ -55,15 +54,15 @@ class AccountFormRequest extends Request
'account_type' => $this->string('what'), 'account_type' => $this->string('what'),
'account_type_id' => 0, 'account_type_id' => 0,
'currency_id' => $this->integer('currency_id'), 'currency_id' => $this->integer('currency_id'),
'virtual_balance' => $this->string('virtualBalance'), 'virtual_balance' => $this->string('virtual_balance'),
'iban' => $this->string('iban'), 'iban' => $this->string('iban'),
'BIC' => $this->string('BIC'), 'BIC' => $this->string('BIC'),
'account_number' => $this->string('accountNumber'), 'account_number' => $this->string('account_number'),
'account_role' => $this->string('accountRole'), 'account_role' => $this->string('account_role'),
'opening_balance' => $this->string('openingBalance'), 'opening_balance' => $this->string('opening_balance'),
'opening_balance_date' => $this->date('openingBalanceDate'), 'opening_balance_date' => $this->date('opening_balance_date'),
'cc_type' => $this->string('ccType'), 'cc_type' => $this->string('cc_type'),
'cc_monthly_payment_date' => $this->string('ccMonthlyPaymentDate'), 'cc_monthly_payment_date' => $this->string('cc_monthly_payment_date'),
'notes' => $this->string('notes'), 'notes' => $this->string('notes'),
'interest' => $this->string('interest'), 'interest' => $this->string('interest'),
'interest_period' => $this->string('interest_period'), 'interest_period' => $this->string('interest_period'),
@@ -107,14 +106,14 @@ class AccountFormRequest extends Request
'ccType' => 'in:' . $ccPaymentTypes, 'ccType' => 'in:' . $ccPaymentTypes,
'cc_monthly_payment_date' => 'date', 'cc_monthly_payment_date' => 'date',
'amount_currency_id_opening_balance' => 'exists:transaction_currencies,id', 'amount_currency_id_opening_balance' => 'exists:transaction_currencies,id',
'amount_currency_id_virtua_balance' => 'exists:transaction_currencies,id', 'amount_currency_id_virtual_balance' => 'exists:transaction_currencies,id',
'what' => 'in:' . $types, 'what' => 'in:' . $types,
'interest_period' => 'in:daily,monthly,yearly', 'interest_period' => 'in:daily,monthly,yearly',
]; ];
// TODO verify if this will work. // TODO verify if this will work.
if ('liabilities' === $this->get('what')) { if ('liabilities' === $this->get('what')) {
$rules['opening_balance'] = ['numeric', 'required', new ZeroOrMore]; $rules['opening_balance'] = ['numeric', 'required'];
$rules['opening_balance_date'] = 'date|required'; $rules['opening_balance_date'] = 'date|required';
} }

View File

@@ -251,7 +251,7 @@ class RecurrenceFormRequest extends Request
} }
//monthly,17 //monthly,17
//ndom,3,7 //ndom,3,7
if (\in_array(substr($value, 0, 6), ['yearly', 'weekly'])) { if (in_array(substr($value, 0, 6), ['yearly', 'weekly'])) {
$return['type'] = substr($value, 0, 6); $return['type'] = substr($value, 0, 6);
$return['moment'] = substr($value, 7); $return['moment'] = substr($value, 7);
} }

View File

@@ -50,7 +50,7 @@ class BankDebitCredit implements ConverterInterface
'Af', // ING (NL). 'Af', // ING (NL).
'Debet', // Triodos (NL) 'Debet', // Triodos (NL)
]; ];
if (\in_array(trim($value), $negative, true)) { if (in_array(trim($value), $negative, true)) {
return -1; return -1;
} }

View File

@@ -57,7 +57,7 @@ class AssetAccountIbans implements MapperInterface
$name = $account->iban . ' (' . $account->name . ')'; $name = $account->iban . ' (' . $account->name . ')';
// is a liability? // is a liability?
if (\in_array($account->accountType->type, [AccountType::LOAN, AccountType::DEBT, AccountType::CREDITCARD, AccountType::MORTGAGE], true)) { if (in_array($account->accountType->type, [AccountType::LOAN, AccountType::DEBT, AccountType::CREDITCARD, AccountType::MORTGAGE], true)) {
$name = $name . ' (' . strtolower(trans('import.import_liability_select')) . ')'; $name = $name . ' (' . strtolower(trans('import.import_liability_select')) . ')';
} }
@@ -66,7 +66,7 @@ class AssetAccountIbans implements MapperInterface
if ('' === $iban) { if ('' === $iban) {
$name = $account->name; $name = $account->name;
// is a liability? // is a liability?
if (\in_array($account->accountType->type, [AccountType::LOAN, AccountType::DEBT, AccountType::CREDITCARD, AccountType::MORTGAGE], true)) { if (in_array($account->accountType->type, [AccountType::LOAN, AccountType::DEBT, AccountType::CREDITCARD, AccountType::MORTGAGE], true)) {
$name = $name . ' (' . strtolower(trans('import.import_liability_select')) . ')'; $name = $name . ' (' . strtolower(trans('import.import_liability_select')) . ')';
} }
$list[$accountId] = $name; $list[$accountId] = $name;

View File

@@ -55,7 +55,7 @@ class AssetAccounts implements MapperInterface
} }
// is a liability? // is a liability?
if (\in_array($account->accountType->type, [AccountType::LOAN, AccountType::DEBT, AccountType::CREDITCARD, AccountType::MORTGAGE], true)) { if (in_array($account->accountType->type, [AccountType::LOAN, AccountType::DEBT, AccountType::CREDITCARD, AccountType::MORTGAGE], true)) {
$name = trans('import.import_liability_select') . ': ' . $name; $name = trans('import.import_liability_select') . ': ' . $name;
} }

View File

@@ -59,7 +59,7 @@ class OpposingAccountIbans implements MapperInterface
$name = $account->iban . ' (' . $account->name . ')'; $name = $account->iban . ' (' . $account->name . ')';
// is a liability? // is a liability?
if (\in_array($account->accountType->type, [AccountType::LOAN, AccountType::DEBT, AccountType::CREDITCARD, AccountType::MORTGAGE], true)) { if (in_array($account->accountType->type, [AccountType::LOAN, AccountType::DEBT, AccountType::CREDITCARD, AccountType::MORTGAGE], true)) {
$name = $name . ' (' . strtolower(trans('import.import_liability_select')) . ')'; $name = $name . ' (' . strtolower(trans('import.import_liability_select')) . ')';
} }
@@ -69,7 +69,7 @@ class OpposingAccountIbans implements MapperInterface
if ('' === $iban) { if ('' === $iban) {
$name = $account->name; $name = $account->name;
// is a liability? // is a liability?
if (\in_array($account->accountType->type, [AccountType::LOAN, AccountType::DEBT, AccountType::CREDITCARD, AccountType::MORTGAGE], true)) { if (in_array($account->accountType->type, [AccountType::LOAN, AccountType::DEBT, AccountType::CREDITCARD, AccountType::MORTGAGE], true)) {
$name = $name . ' (' . strtolower(trans('import.import_liability_select')) . ')'; $name = $name . ' (' . strtolower(trans('import.import_liability_select')) . ')';
} }
$list[$accountId] = $name; $list[$accountId] = $name;

View File

@@ -59,7 +59,7 @@ class OpposingAccounts implements MapperInterface
$name .= ' (' . $iban . ')'; $name .= ' (' . $iban . ')';
} }
// is a liability? // is a liability?
if (\in_array($account->accountType->type, [AccountType::LOAN, AccountType::DEBT, AccountType::CREDITCARD, AccountType::MORTGAGE], true)) { if (in_array($account->accountType->type, [AccountType::LOAN, AccountType::DEBT, AccountType::CREDITCARD, AccountType::MORTGAGE], true)) {
$name = trans('import.import_liability_select') . ': ' . $name; $name = trans('import.import_liability_select') . ': ' . $name;
} }
$list[$accountId] = $name; $list[$accountId] = $name;

View File

@@ -52,7 +52,7 @@ class BunqRoutine implements RoutineInterface
{ {
Log::info(sprintf('Now in BunqRoutine::run() with status "%s" and stage "%s".', $this->importJob->status, $this->importJob->stage)); Log::info(sprintf('Now in BunqRoutine::run() with status "%s" and stage "%s".', $this->importJob->status, $this->importJob->stage));
$valid = ['ready_to_run']; // should be only ready_to_run $valid = ['ready_to_run']; // should be only ready_to_run
if (\in_array($this->importJob->status, $valid, true)) { if (in_array($this->importJob->status, $valid, true)) {
switch ($this->importJob->stage) { switch ($this->importJob->stage) {
default: default:
throw new FireflyException(sprintf('BunqRoutine cannot handle stage "%s".', $this->importJob->stage)); // @codeCoverageIgnore throw new FireflyException(sprintf('BunqRoutine cannot handle stage "%s".', $this->importJob->stage)); // @codeCoverageIgnore

View File

@@ -52,7 +52,7 @@ class FinTSRoutine implements RoutineInterface
{ {
Log::debug(sprintf('Now in FinTSRoutine::run() with status "%s" and stage "%s".', $this->importJob->status, $this->importJob->stage)); Log::debug(sprintf('Now in FinTSRoutine::run() with status "%s" and stage "%s".', $this->importJob->status, $this->importJob->stage));
$valid = ['ready_to_run']; // should be only ready_to_run $valid = ['ready_to_run']; // should be only ready_to_run
if (\in_array($this->importJob->status, $valid, true)) { if (in_array($this->importJob->status, $valid, true)) {
switch ($this->importJob->stage) { switch ($this->importJob->stage) {
default: default:
throw new FireflyException(sprintf('FinTSRoutine cannot handle stage "%s".', $this->importJob->stage)); // @codeCoverageIgnore throw new FireflyException(sprintf('FinTSRoutine cannot handle stage "%s".', $this->importJob->stage)); // @codeCoverageIgnore

View File

@@ -56,7 +56,7 @@ class SpectreRoutine implements RoutineInterface
{ {
Log::debug(sprintf('Now in SpectreRoutine::run() with status "%s" and stage "%s".', $this->importJob->status, $this->importJob->stage)); Log::debug(sprintf('Now in SpectreRoutine::run() with status "%s" and stage "%s".', $this->importJob->status, $this->importJob->stage));
$valid = ['ready_to_run']; // should be only ready_to_run $valid = ['ready_to_run']; // should be only ready_to_run
if (\in_array($this->importJob->status, $valid, true)) { if (in_array($this->importJob->status, $valid, true)) {
switch ($this->importJob->stage) { switch ($this->importJob->stage) {
default: default:
throw new FireflyException(sprintf('SpectreRoutine cannot handle stage "%s".', $this->importJob->stage)); // @codeCoverageIgnore throw new FireflyException(sprintf('SpectreRoutine cannot handle stage "%s".', $this->importJob->stage)); // @codeCoverageIgnore

View File

@@ -54,7 +54,7 @@ class YnabRoutine implements RoutineInterface
{ {
Log::debug(sprintf('Now in YNAB routine::run() with status "%s" and stage "%s".', $this->importJob->status, $this->importJob->stage)); Log::debug(sprintf('Now in YNAB routine::run() with status "%s" and stage "%s".', $this->importJob->status, $this->importJob->stage));
$valid = ['ready_to_run']; // should be only ready_to_run $valid = ['ready_to_run']; // should be only ready_to_run
if (\in_array($this->importJob->status, $valid, true)) { if (in_array($this->importJob->status, $valid, true)) {
// get access token from YNAB // get access token from YNAB
if ('get_access_token' === $this->importJob->stage) { if ('get_access_token' === $this->importJob->stage) {

View File

@@ -29,8 +29,8 @@ use FireflyIII\Helpers\Attachments\AttachmentHelper;
use FireflyIII\Helpers\Attachments\AttachmentHelperInterface; use FireflyIII\Helpers\Attachments\AttachmentHelperInterface;
use FireflyIII\Helpers\Chart\MetaPieChart; use FireflyIII\Helpers\Chart\MetaPieChart;
use FireflyIII\Helpers\Chart\MetaPieChartInterface; use FireflyIII\Helpers\Chart\MetaPieChartInterface;
use FireflyIII\Helpers\FiscalHelper; use FireflyIII\Helpers\Fiscal\FiscalHelper;
use FireflyIII\Helpers\FiscalHelperInterface; use FireflyIII\Helpers\Fiscal\FiscalHelperInterface;
use FireflyIII\Helpers\Help\Help; use FireflyIII\Helpers\Help\Help;
use FireflyIII\Helpers\Help\HelpInterface; use FireflyIII\Helpers\Help\HelpInterface;
use FireflyIII\Helpers\Report\BalanceReportHelper; use FireflyIII\Helpers\Report\BalanceReportHelper;

View File

@@ -24,8 +24,6 @@ namespace FireflyIII\Providers;
use FireflyIII\Helpers\Collector\GroupCollector; use FireflyIII\Helpers\Collector\GroupCollector;
use FireflyIII\Helpers\Collector\GroupCollectorInterface; use FireflyIII\Helpers\Collector\GroupCollectorInterface;
use FireflyIII\Helpers\Collector\GroupSumCollector;
use FireflyIII\Helpers\Collector\GroupSumCollectorInterface;
use FireflyIII\Repositories\Journal\JournalRepository; use FireflyIII\Repositories\Journal\JournalRepository;
use FireflyIII\Repositories\Journal\JournalRepositoryInterface; use FireflyIII\Repositories\Journal\JournalRepositoryInterface;
use FireflyIII\Repositories\TransactionGroup\TransactionGroupRepository; use FireflyIII\Repositories\TransactionGroup\TransactionGroupRepository;
@@ -54,7 +52,6 @@ class JournalServiceProvider extends ServiceProvider
$this->registerRepository(); $this->registerRepository();
$this->registerGroupRepository(); $this->registerGroupRepository();
$this->registerGroupCollector(); $this->registerGroupCollector();
$this->registerSumCollector();
} }
/** /**
@@ -113,23 +110,4 @@ class JournalServiceProvider extends ServiceProvider
} }
); );
} }
/**
* Register sum collector.
*/
private function registerSumCollector(): void
{
$this->app->bind(
GroupSumCollectorInterface::class,
function (Application $app) {
/** @var GroupSumCollector $collector */
$collector = app(GroupSumCollector::class);
if ($app->auth->check()) {
$collector->setUser(auth()->user());
}
return $collector;
}
);
}
} }

View File

@@ -461,7 +461,7 @@ class AccountRepository implements AccountRepositoryInterface
*/ */
public function isLiability(Account $account): bool public function isLiability(Account $account): bool
{ {
return \in_array($account->accountType->type, [AccountType::CREDITCARD, AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE], true); return in_array($account->accountType->type, [AccountType::CREDITCARD, AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE], true);
} }
/** /**

View File

@@ -305,7 +305,7 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface
Log::debug(sprintf('Will add/remove %f to piggy bank #%d ("%s")', $amount, $piggyBank->id, $piggyBank->name)); Log::debug(sprintf('Will add/remove %f to piggy bank #%d ("%s")', $amount, $piggyBank->id, $piggyBank->name));
// if piggy account matches source account, the amount is positive // if piggy account matches source account, the amount is positive
if (\in_array($piggyBank->account_id, $sources, true)) { if (in_array($piggyBank->account_id, $sources, true)) {
$amount = bcmul($amount, '-1'); $amount = bcmul($amount, '-1');
Log::debug(sprintf('Account #%d is the source, so will remove amount from piggy bank.', $piggyBank->account_id)); Log::debug(sprintf('Account #%d is the source, so will remove amount from piggy bank.', $piggyBank->account_id));
} }

View File

@@ -59,7 +59,7 @@ class ValidRecurrenceRepetitionType implements Rule
} }
//monthly,17 //monthly,17
//ndom,3,7 //ndom,3,7
if (\in_array(substr($value, 0, 6), ['yearly', 'weekly'])) { if (in_array(substr($value, 0, 6), ['yearly', 'weekly'])) {
return true; return true;
} }
if (0 === strpos($value, 'monthly')) { if (0 === strpos($value, 'monthly')) {

View File

@@ -66,10 +66,10 @@ class RecurrenceUpdateService
if (isset($data['recurrence']['repetition_end'])) { if (isset($data['recurrence']['repetition_end'])) {
if (\in_array($data['recurrence']['repetition_end'], ['forever', 'until_date'])) { if (in_array($data['recurrence']['repetition_end'], ['forever', 'until_date'])) {
$recurrence->repetitions = 0; $recurrence->repetitions = 0;
} }
if (\in_array($data['recurrence']['repetition_end'], ['forever', 'times'])) { if (in_array($data['recurrence']['repetition_end'], ['forever', 'times'])) {
$recurrence->repeat_until = null; $recurrence->repeat_until = null;
} }
} }

View File

@@ -55,7 +55,7 @@ class BudgetList implements BinderInterface
->get(); ->get();
// add empty budget if applicable. // add empty budget if applicable.
if (\in_array(0, $list, true)) { if (in_array(0, $list, true)) {
$collection->push(new Budget); $collection->push(new Budget);
} }

View File

@@ -54,7 +54,7 @@ class CategoryList implements BinderInterface
->get(); ->get();
// add empty category if applicable. // add empty category if applicable.
if (\in_array(0, $list, true)) { if (in_array(0, $list, true)) {
$collection->push(new Category); $collection->push(new Category);
} }

View File

@@ -43,7 +43,7 @@ class ConfigurationName implements BinderInterface
public static function routeBinder(string $value, Route $route): string public static function routeBinder(string $value, Route $route): string
{ {
$accepted = ['is_demo_site', 'permission_update_check', 'single_user_mode']; $accepted = ['is_demo_site', 'permission_update_check', 'single_user_mode'];
if (\in_array($value, $accepted, true)) { if (in_array($value, $accepted, true)) {
return $value; return $value;
} }
throw new NotFoundHttpException; throw new NotFoundHttpException;

View File

@@ -24,7 +24,7 @@ namespace FireflyIII\Support\Binder;
use Carbon\Carbon; use Carbon\Carbon;
use Exception; use Exception;
use FireflyIII\Helpers\FiscalHelperInterface; use FireflyIII\Helpers\Fiscal\FiscalHelperInterface;
use Illuminate\Routing\Route; use Illuminate\Routing\Route;
use Log; use Log;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

View File

@@ -93,7 +93,7 @@ class ImportProvider implements BinderInterface
public static function routeBinder(string $value, Route $route): string public static function routeBinder(string $value, Route $route): string
{ {
$providers = array_keys(self::getProviders()); $providers = array_keys(self::getProviders());
if (\in_array($value, $providers, true)) { if (in_array($value, $providers, true)) {
return $value; return $value;
} }
throw new NotFoundHttpException; throw new NotFoundHttpException;

View File

@@ -57,10 +57,10 @@ class TagList implements BinderInterface
$collection = $allTags->filter( $collection = $allTags->filter(
function (Tag $tag) use ($list) { function (Tag $tag) use ($list) {
if (\in_array(strtolower($tag->tag), $list, true)) { if (in_array(strtolower($tag->tag), $list, true)) {
return true; return true;
} }
if (\in_array((string)$tag->id, $list, true)) { if (in_array((string)$tag->id, $list, true)) {
return true; return true;
} }

View File

@@ -119,11 +119,11 @@ class ExpandedForm
$currencyId = (int)$repository->getMetaValue($account, 'currency_id'); $currencyId = (int)$repository->getMetaValue($account, 'currency_id');
$currency = $currencyRepos->findNull($currencyId); $currency = $currencyRepos->findNull($currencyId);
$role = $repository->getMetaValue($account, 'accountRole'); $role = $repository->getMetaValue($account, 'accountRole');
if ('' === $role && !\in_array($account->accountType->type, $liabilityTypes, true)) { if ('' === $role && !in_array($account->accountType->type, $liabilityTypes, true)) {
$role = 'no_account_type'; // @codeCoverageIgnore $role = 'no_account_type'; // @codeCoverageIgnore
} }
if (\in_array($account->accountType->type, $liabilityTypes, true)) { if (in_array($account->accountType->type, $liabilityTypes, true)) {
$role = 'l_' . $account->accountType->type; // @codeCoverageIgnore $role = 'l_' . $account->accountType->type; // @codeCoverageIgnore
} }
@@ -508,7 +508,7 @@ class ExpandedForm
$role = 'no_account_type'; // @codeCoverageIgnore $role = 'no_account_type'; // @codeCoverageIgnore
} }
if (\in_array($account->accountType->type, $liabilityTypes, true)) { if (in_array($account->accountType->type, $liabilityTypes, true)) {
$role = 'l_' . $account->accountType->type; // @codeCoverageIgnore $role = 'l_' . $account->accountType->type; // @codeCoverageIgnore
} }

View File

@@ -220,7 +220,7 @@ trait GetConfigurationData
}, $forbidden }, $forbidden
); );
foreach ($list as $entry) { foreach ($list as $entry) {
if (\in_array($entry, $trimmed, true)) { if (in_array($entry, $trimmed, true)) {
Log::error('Method "%s" is FORBIDDEN, so the console command cannot be executed.'); Log::error('Method "%s" is FORBIDDEN, so the console command cannot be executed.');
return true; return true;

View File

@@ -474,6 +474,12 @@ trait PeriodOverview
$sumCollector = app(GroupSumCollectorInterface::class); $sumCollector = app(GroupSumCollectorInterface::class);
$sumCollector->setTypes($types)->setRange($currentDate['start'], $currentDate['end']); $sumCollector->setTypes($types)->setRange($currentDate['start'], $currentDate['end']);
$amounts = $sumCollector->getSum(); $amounts = $sumCollector->getSum();
/** @var GroupCollectorInterface $collector */
$collector = app(GroupCollectorInterface::class);
$collector->setTypes($types)->setRange($currentDate['start'], $currentDate['end']);
$amounts = $collector->getSum();
$spent = []; $spent = [];
$earned = []; $earned = [];
$transferred = []; $transferred = [];

View File

@@ -60,7 +60,7 @@ trait RenderPartialViews
$set = new Collection; $set = new Collection;
$names = $revenue->pluck('name')->toArray(); $names = $revenue->pluck('name')->toArray();
foreach ($expense as $exp) { foreach ($expense as $exp) {
if (\in_array($exp->name, $names, true)) { if (in_array($exp->name, $names, true)) {
$set->push($exp); $set->push($exp);
} }
} }

View File

@@ -103,7 +103,7 @@ trait UserNavigation
/** @var Transaction $transaction */ /** @var Transaction $transaction */
foreach ($transactions as $transaction) { foreach ($transactions as $transaction) {
$account = $transaction->account; $account = $transaction->account;
if (\in_array($account->accountType->type, $valid, true)) { if (in_array($account->accountType->type, $valid, true)) {
return redirect(route('accounts.show', [$account->id])); return redirect(route('accounts.show', [$account->id]));
} }
} }

View File

@@ -67,7 +67,7 @@ class ConfigureMappingHandler implements FileConfigurationInterface
$specifics = $config['specifics'] ?? []; $specifics = $config['specifics'] ?? [];
$names = array_keys($specifics); $names = array_keys($specifics);
foreach ($names as $name) { foreach ($names as $name) {
if (!\in_array($name, $validSpecifics, true)) { if (!in_array($name, $validSpecifics, true)) {
continue; continue;
} }
$class = config(sprintf('csv.import_specifics.%s', $name)); $class = config(sprintf('csv.import_specifics.%s', $name));
@@ -331,7 +331,7 @@ class ConfigureMappingHandler implements FileConfigurationInterface
{ {
/** @var array $validColumns */ /** @var array $validColumns */
$validColumns = array_keys(config('csv.import_roles')); $validColumns = array_keys(config('csv.import_roles'));
if (!\in_array($name, $validColumns, true)) { if (!in_array($name, $validColumns, true)) {
$name = '_ignore'; $name = '_ignore';
} }

View File

@@ -74,7 +74,7 @@ class ConfigureRolesHandler implements FileConfigurationInterface
if ('_ignore' !== $role) { if ('_ignore' !== $role) {
++$assigned; ++$assigned;
} }
if (\in_array($role, ['amount', 'amount_credit', 'amount_debit', 'amount_negated'])) { if (in_array($role, ['amount', 'amount_credit', 'amount_debit', 'amount_negated'])) {
$hasAmount = true; $hasAmount = true;
} }
if ('foreign-currency-code' === $role) { if ('foreign-currency-code' === $role) {
@@ -372,7 +372,7 @@ class ConfigureRolesHandler implements FileConfigurationInterface
$specifics = $config['specifics'] ?? []; $specifics = $config['specifics'] ?? [];
$names = array_keys($specifics); $names = array_keys($specifics);
foreach ($names as $name) { foreach ($names as $name) {
if (!\in_array($name, $validSpecifics, true)) { if (!in_array($name, $validSpecifics, true)) {
continue; continue;
} }
/** @var SpecificInterface $specific */ /** @var SpecificInterface $specific */

View File

@@ -211,7 +211,7 @@ class ImportTransaction
$meta = ['sepa_ct_id', 'sepa_ct_op', 'sepa_db', 'sepa_cc', 'sepa_country', 'sepa_batch_id', 'sepa_ep', 'sepa_ci', 'internal_reference', 'date_interest', $meta = ['sepa_ct_id', 'sepa_ct_op', 'sepa_db', 'sepa_cc', 'sepa_country', 'sepa_batch_id', 'sepa_ep', 'sepa_ci', 'internal_reference', 'date_interest',
'date_invoice', 'date_book', 'date_payment', 'date_process', 'date_due', 'original_source']; 'date_invoice', 'date_book', 'date_payment', 'date_process', 'date_due', 'original_source'];
Log::debug(sprintf('Now going to check role "%s".', $role)); Log::debug(sprintf('Now going to check role "%s".', $role));
if (\in_array($role, $meta, true)) { if (in_array($role, $meta, true)) {
Log::debug(sprintf('Role "%s" is in allowed meta roles, so store its value "%s".', $role, $columnValue->getValue())); Log::debug(sprintf('Role "%s" is in allowed meta roles, so store its value "%s".', $role, $columnValue->getValue()));
$this->meta[$role] = $columnValue->getValue(); $this->meta[$role] = $columnValue->getValue();

View File

@@ -93,7 +93,7 @@ class LineReader
$names = array_keys($specifics); $names = array_keys($specifics);
$toApply = []; $toApply = [];
foreach ($names as $name) { foreach ($names as $name) {
if (!\in_array($name, $validSpecifics, true)) { if (!in_array($name, $validSpecifics, true)) {
continue; continue;
} }
$class = config(sprintf('csv.import_specifics.%s', $name)); $class = config(sprintf('csv.import_specifics.%s', $name));

View File

@@ -233,7 +233,7 @@ class StageImportDataHandler
if (null === $account) { if (null === $account) {
throw new FireflyException(sprintf('Cannot find Firefly III asset account with ID #%d. Job must stop now.', $accountId)); // @codeCoverageIgnore throw new FireflyException(sprintf('Cannot find Firefly III asset account with ID #%d. Job must stop now.', $accountId)); // @codeCoverageIgnore
} }
if (!\in_array($account->accountType->type, [AccountType::ASSET, AccountType::LOAN, AccountType::MORTGAGE, AccountType::DEBT], true)) { if (!in_array($account->accountType->type, [AccountType::ASSET, AccountType::LOAN, AccountType::MORTGAGE, AccountType::DEBT], true)) {
throw new FireflyException( throw new FireflyException(
sprintf('Account with ID #%d is not an asset/loan/mortgage/debt account. Job must stop now.', $accountId) sprintf('Account with ID #%d is not an asset/loan/mortgage/debt account. Job must stop now.', $accountId)
); // @codeCoverageIgnore ); // @codeCoverageIgnore

View File

@@ -24,7 +24,7 @@ namespace FireflyIII\Support;
use Carbon\Carbon; use Carbon\Carbon;
use FireflyIII\Exceptions\FireflyException; use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Helpers\FiscalHelperInterface; use FireflyIII\Helpers\Fiscal\FiscalHelperInterface;
use Log; use Log;
/** /**
@@ -90,7 +90,7 @@ class Navigation
$months = ['1M', 'month', 'monthly']; $months = ['1M', 'month', 'monthly'];
$difference = $date->month - $theDate->month; $difference = $date->month - $theDate->month;
if (2 === $difference && $date->day > 0 && \in_array($repeatFreq, $months, true)) { if (2 === $difference && $date->day > 0 && in_array($repeatFreq, $months, true)) {
$date->subDays($date->day); $date->subDays($date->day);
} }
@@ -227,7 +227,7 @@ class Navigation
if (isset($modifierMap[$repeatFreq])) { if (isset($modifierMap[$repeatFreq])) {
$currentEnd->$function($modifierMap[$repeatFreq]); $currentEnd->$function($modifierMap[$repeatFreq]);
if (\in_array($repeatFreq, $subDay, true)) { if (in_array($repeatFreq, $subDay, true)) {
$currentEnd->subDay(); $currentEnd->subDay();
} }
$currentEnd->endOfDay(); $currentEnd->endOfDay();
@@ -236,7 +236,7 @@ class Navigation
} }
$currentEnd->$function(); $currentEnd->$function();
$currentEnd->endOfDay(); $currentEnd->endOfDay();
if (\in_array($repeatFreq, $subDay, true)) { if (in_array($repeatFreq, $subDay, true)) {
$currentEnd->subDay(); $currentEnd->subDay();
} }

View File

@@ -139,7 +139,7 @@ class Search implements SearchInterface
if (2 === count($parts) && '' !== trim((string)$parts[1]) && '' !== trim((string)$parts[0])) { if (2 === count($parts) && '' !== trim((string)$parts[1]) && '' !== trim((string)$parts[0])) {
$type = trim((string)$parts[0]); $type = trim((string)$parts[0]);
$value = trim((string)$parts[1]); $value = trim((string)$parts[1]);
if (\in_array($type, $this->validModifiers, true)) { if (in_array($type, $this->validModifiers, true)) {
// filter for valid type // filter for valid type
$this->modifiers->push(['type' => $type, 'value' => $value]); $this->modifiers->push(['type' => $type, 'value' => $value]);
} }

View File

@@ -124,7 +124,7 @@ class General extends Twig_Extension
return new Twig_SimpleFunction( return new Twig_SimpleFunction(
'activeRouteStrict', 'activeRouteStrict',
function (): string { function (): string {
$args = \func_get_args(); $args = func_get_args();
$route = $args[0]; // name of the route. $route = $args[0]; // name of the route.
if (Route::getCurrentRoute()->getName() === $route) { if (Route::getCurrentRoute()->getName() === $route) {

View File

@@ -24,6 +24,7 @@ namespace FireflyIII\TransactionRules\Engine;
use FireflyIII\Exceptions\FireflyException; use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Models\Rule; use FireflyIII\Models\Rule;
use FireflyIII\Models\RuleGroup; use FireflyIII\Models\RuleGroup;
use FireflyIII\Models\RuleTrigger;
use FireflyIII\Models\TransactionJournal; use FireflyIII\Models\TransactionJournal;
use FireflyIII\Repositories\RuleGroup\RuleGroupRepository; use FireflyIII\Repositories\RuleGroup\RuleGroupRepository;
use FireflyIII\TransactionRules\Processor; use FireflyIII\TransactionRules\Processor;
@@ -40,20 +41,23 @@ use Log;
*/ */
class RuleEngine class RuleEngine
{ {
/** @var int */
public const TRIGGER_STORE = 1;
/** @var int */
public const TRIGGER_UPDATE = 2;
/** @var Collection */ /** @var Collection */
private $ruleGroups; private $ruleGroups;
/** @var array */ /** @var array */
private $rulesToApply; private $rulesToApply;
/** @var bool */ /** @var bool */
private $allRules; private $allRules;
/** @var User */ /** @var User */
private $user; private $user;
/** @var RuleGroupRepository */ /** @var RuleGroupRepository */
private $ruleGroupRepository; private $ruleGroupRepository;
/** @var int */
private $triggerMode;
/** /**
* RuleEngine constructor. * RuleEngine constructor.
@@ -65,6 +69,15 @@ class RuleEngine
$this->rulesToApply = []; $this->rulesToApply = [];
$this->allRules = false; $this->allRules = false;
$this->ruleGroupRepository = app(RuleGroupRepository::class); $this->ruleGroupRepository = app(RuleGroupRepository::class);
$this->triggerMode = self::TRIGGER_STORE;
}
/**
* @param int $triggerMode
*/
public function setTriggerMode(int $triggerMode): void
{
$this->triggerMode = $triggerMode;
} }
/** /**
@@ -204,7 +217,13 @@ class RuleEngine
*/ */
private function includeRule(Rule $rule): bool private function includeRule(Rule $rule): bool
{ {
return $this->allRules || in_array($rule->id, $this->rulesToApply, true); /** @var RuleTrigger $trigger */
$trigger = $rule->ruleTriggers()->where('trigger_type', 'user_action')->first();
$validTrigger = ('store-journal' === $trigger->trigger_value && self::TRIGGER_STORE === $this->triggerMode) ||
('update-journal' === $trigger->trigger_value && self::TRIGGER_UPDATE === $this->triggerMode);
return $validTrigger && ($this->allRules || in_array($rule->id, $this->rulesToApply, true));
} }
} }

View File

@@ -229,7 +229,7 @@ class AccountTransformer extends AbstractTransformer
{ {
$openingBalance = null; $openingBalance = null;
$openingBalanceDate = null; $openingBalanceDate = null;
if (\in_array($accountType, ['asset', 'liabilities'], true)) { if (in_array($accountType, ['asset', 'liabilities'], true)) {
$amount = $this->repository->getOpeningBalanceAmount($account); $amount = $this->repository->getOpeningBalanceAmount($account);
$openingBalance = null === $amount ? null : round($amount, $decimalPlaces); $openingBalance = null === $amount ? null : round($amount, $decimalPlaces);
$openingBalanceDate = $this->repository->getOpeningBalanceDate($account); $openingBalanceDate = $this->repository->getOpeningBalanceDate($account);

View File

@@ -327,7 +327,7 @@ class FireflyValidator extends Validator
// these trigger types need a numerical check: // these trigger types need a numerical check:
$numerical = ['amount_less', 'amount_more', 'amount_exactly']; $numerical = ['amount_less', 'amount_more', 'amount_exactly'];
if (\in_array($triggerType, $numerical, true)) { if (in_array($triggerType, $numerical, true)) {
return is_numeric($value); return is_numeric($value);
} }
@@ -335,7 +335,7 @@ class FireflyValidator extends Validator
$length = ['from_account_starts', 'from_account_ends', 'from_account_is', 'from_account_contains', 'to_account_starts', 'to_account_ends', $length = ['from_account_starts', 'from_account_ends', 'from_account_is', 'from_account_contains', 'to_account_starts', 'to_account_ends',
'to_account_is', 'to_account_contains', 'description_starts', 'description_ends', 'description_contains', 'description_is', 'category_is', 'to_account_is', 'to_account_contains', 'description_starts', 'description_ends', 'description_contains', 'description_is', 'category_is',
'budget_is', 'tag_is', 'currency_is', 'notes_contain', 'notes_start', 'notes_end', 'notes_are',]; 'budget_is', 'tag_is', 'currency_is', 'notes_contain', 'notes_start', 'notes_end', 'notes_are',];
if (\in_array($triggerType, $length, true)) { if (in_array($triggerType, $length, true)) {
return '' !== $value; return '' !== $value;
} }

View File

@@ -131,8 +131,6 @@ abstract class TestCase extends BaseTestCase
*/ */
public function emptyUser(): User public function emptyUser(): User
{ {
throw new FireflyException('emptyUser()-method is obsolete.');
return User::find(2); return User::find(2);
} }

View File

@@ -91,6 +91,7 @@ class ApplyRulesTest extends TestCase
$ruleEngine->shouldReceive('setUser')->atLeast()->once(); $ruleEngine->shouldReceive('setUser')->atLeast()->once();
$ruleEngine->shouldReceive('setRulesToApply')->atLeast()->once(); $ruleEngine->shouldReceive('setRulesToApply')->atLeast()->once();
$ruleEngine->shouldReceive('processJournalArray')->times(3); $ruleEngine->shouldReceive('processJournalArray')->times(3);
$ruleEngine->shouldReceive('setTriggerMode')->atLeast()->once()->withArgs([RuleEngine::TRIGGER_STORE]);
$parameters = [ $parameters = [
'--user=1', '--user=1',
@@ -149,6 +150,7 @@ class ApplyRulesTest extends TestCase
$ruleEngine->shouldReceive('setUser')->atLeast()->once(); $ruleEngine->shouldReceive('setUser')->atLeast()->once();
$ruleEngine->shouldReceive('setRulesToApply')->atLeast()->once(); $ruleEngine->shouldReceive('setRulesToApply')->atLeast()->once();
$ruleEngine->shouldReceive('processJournalArray')->times(3); $ruleEngine->shouldReceive('processJournalArray')->times(3);
$ruleEngine->shouldReceive('setTriggerMode')->atLeast()->once()->withArgs([RuleEngine::TRIGGER_STORE]);
$parameters = [ $parameters = [
'--user=1', '--user=1',
@@ -205,6 +207,7 @@ class ApplyRulesTest extends TestCase
$ruleEngine->shouldReceive('setUser')->atLeast()->once(); $ruleEngine->shouldReceive('setUser')->atLeast()->once();
$ruleEngine->shouldReceive('setRulesToApply')->atLeast()->once(); $ruleEngine->shouldReceive('setRulesToApply')->atLeast()->once();
$ruleEngine->shouldReceive('processJournalArray')->times(3); $ruleEngine->shouldReceive('processJournalArray')->times(3);
$ruleEngine->shouldReceive('setTriggerMode')->atLeast()->once()->withArgs([RuleEngine::TRIGGER_STORE]);
$parameters = [ $parameters = [
'--user=1', '--user=1',
@@ -269,6 +272,7 @@ class ApplyRulesTest extends TestCase
$ruleEngine->shouldReceive('setUser')->atLeast()->once(); $ruleEngine->shouldReceive('setUser')->atLeast()->once();
$ruleEngine->shouldReceive('setRulesToApply')->atLeast()->once(); $ruleEngine->shouldReceive('setRulesToApply')->atLeast()->once();
$ruleEngine->shouldReceive('processJournalArray')->times(3); $ruleEngine->shouldReceive('processJournalArray')->times(3);
$ruleEngine->shouldReceive('setTriggerMode')->atLeast()->once()->withArgs([RuleEngine::TRIGGER_STORE]);
$parameters = [ $parameters = [
'--user=1', '--user=1',
@@ -330,6 +334,7 @@ class ApplyRulesTest extends TestCase
$ruleEngine->shouldReceive('setUser')->atLeast()->once(); $ruleEngine->shouldReceive('setUser')->atLeast()->once();
$ruleEngine->shouldReceive('setRulesToApply')->atLeast()->once(); $ruleEngine->shouldReceive('setRulesToApply')->atLeast()->once();
$ruleEngine->shouldReceive('processJournalArray')->times(3); $ruleEngine->shouldReceive('processJournalArray')->times(3);
$ruleEngine->shouldReceive('setTriggerMode')->atLeast()->once()->withArgs([RuleEngine::TRIGGER_STORE]);
$parameters = [ $parameters = [
'--user=1', '--user=1',
@@ -366,6 +371,7 @@ class ApplyRulesTest extends TestCase
$ruleRepos->shouldReceive('setUser')->atLeast()->once(); $ruleRepos->shouldReceive('setUser')->atLeast()->once();
$ruleGroupRepos->shouldReceive('setUser')->atLeast()->once(); $ruleGroupRepos->shouldReceive('setUser')->atLeast()->once();
$parameters = [ $parameters = [
'--user=1', '--user=1',
'--token=token', '--token=token',

View File

@@ -297,7 +297,14 @@ class TransferCurrenciesCorrectionsTest extends TestCase
$euro = $this->getEuro(); $euro = $this->getEuro();
$dollar = $this->getDollar(); $dollar = $this->getDollar();
// make sure that source and destination have the right currencies beforehand
$source = $transfer->transactions()->where('amount', '<', 0)->first(); $source = $transfer->transactions()->where('amount', '<', 0)->first();
$source->transaction_currency_id = $euro->id;
$source->save();
$dest= $transfer->transactions()->where('amount', '>', 0)->first();
$dest->transaction_currency_id = $dollar->id;
$dest->save();
// mock calls: // mock calls:
$journalRepos->shouldReceive('getAllJournals') $journalRepos->shouldReceive('getAllJournals')
@@ -325,7 +332,7 @@ class TransferCurrenciesCorrectionsTest extends TestCase
FireflyConfig::shouldReceive('set')->withArgs(['4780_transfer_currencies', true]); FireflyConfig::shouldReceive('set')->withArgs(['4780_transfer_currencies', true]);
$this->artisan('firefly-iii:transfer-currencies') $this->artisan('firefly-iii:transfer-currencies')
->expectsOutput('Verified currency information of 2 transfer(s).') ->expectsOutput('Verified currency information of 1 transfer(s).')
->assertExitCode(0); ->assertExitCode(0);
// source and destination transaction should be corrected: // source and destination transaction should be corrected:

View File

@@ -78,7 +78,7 @@ class ChartJsGeneratorTest extends TestCase
/** @var ChartJsGenerator $generator */ /** @var ChartJsGenerator $generator */
$generator = new ChartJsGenerator(); $generator = app(ChartJsGenerator::class);
$result = $generator->multiSet($data); $result = $generator->multiSet($data);
$this->assertEquals('one', $result['labels'][0]); $this->assertEquals('one', $result['labels'][0]);
@@ -105,7 +105,7 @@ class ChartJsGeneratorTest extends TestCase
]; ];
/** @var ChartJsGenerator $generator */ /** @var ChartJsGenerator $generator */
$generator = new ChartJsGenerator(); $generator = app(ChartJsGenerator::class);
$result = $generator->multiCurrencyPieChart($data); $result = $generator->multiCurrencyPieChart($data);
$this->assertEquals('three', $result['labels'][0]); $this->assertEquals('three', $result['labels'][0]);
@@ -126,7 +126,7 @@ class ChartJsGeneratorTest extends TestCase
]; ];
/** @var ChartJsGenerator $generator */ /** @var ChartJsGenerator $generator */
$generator = new ChartJsGenerator(); $generator = app(ChartJsGenerator::class);
$result = $generator->multiCurrencyPieChart($data); $result = $generator->multiCurrencyPieChart($data);
$this->assertEquals('three', $result['labels'][0]); $this->assertEquals('three', $result['labels'][0]);
@@ -147,7 +147,7 @@ class ChartJsGeneratorTest extends TestCase
]; ];
/** @var ChartJsGenerator $generator */ /** @var ChartJsGenerator $generator */
$generator = new ChartJsGenerator(); $generator = app(ChartJsGenerator::class);
$result = $generator->pieChart($data); $result = $generator->pieChart($data);
$this->assertEquals('three', $result['labels'][0]); $this->assertEquals('three', $result['labels'][0]);
@@ -168,7 +168,7 @@ class ChartJsGeneratorTest extends TestCase
]; ];
/** @var ChartJsGenerator $generator */ /** @var ChartJsGenerator $generator */
$generator = new ChartJsGenerator(); $generator = app(ChartJsGenerator::class);
$result = $generator->pieChart($data); $result = $generator->pieChart($data);
$this->assertEquals('three', $result['labels'][0]); $this->assertEquals('three', $result['labels'][0]);
@@ -188,7 +188,7 @@ class ChartJsGeneratorTest extends TestCase
]; ];
/** @var ChartJsGenerator $generator */ /** @var ChartJsGenerator $generator */
$generator = new ChartJsGenerator(); $generator = app(ChartJsGenerator::class);
$result = $generator->singleSet('Some label', $data); $result = $generator->singleSet('Some label', $data);
$this->assertEquals('one', $result['labels'][0]); $this->assertEquals('one', $result['labels'][0]);

View File

@@ -27,9 +27,7 @@ namespace Tests\Unit\Generator\Report\Audit;
use Carbon\Carbon; use Carbon\Carbon;
use FireflyIII\Exceptions\FireflyException; use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Generator\Report\Audit\MonthReportGenerator; use FireflyIII\Generator\Report\Audit\MonthReportGenerator;
use FireflyIII\Helpers\Collector\TransactionCollectorInterface; use FireflyIII\Helpers\Collector\GroupCollectorInterface;
use FireflyIII\Models\Account;
use FireflyIII\Models\TransactionCurrency;
use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface; use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface;
use Illuminate\Support\Collection; use Illuminate\Support\Collection;
@@ -56,187 +54,209 @@ class MonthReportGeneratorTest extends TestCase
/** /**
* @covers \FireflyIII\Generator\Report\Audit\MonthReportGenerator * @covers \FireflyIII\Generator\Report\Audit\MonthReportGenerator
*/ */
public function testBasic(): void public function testGetAuditReport(): void
{ {
$this->markTestIncomplete('Needs to be rewritten for v4.8.0'); $asset = $this->getRandomAsset();
$date = new Carbon;
$start = Carbon::now()->startOfMonth();
$end = Carbon::now()->endOfMonth();
$collection = new Collection([$asset]);
$euro = $this->getEuro();
$dollar = $this->getDollar();
$return = [
[
'description' => 'Hello',
'amount' => '10',
'foreign_currency_id' => null,
'currency_id' => $euro->id,
'source_id' => $asset->id,
'source_name' => $asset->name,
],
[
'description' => 'Hello2',
'amount' => '10',
'foreign_amount' => '10',
'foreign_currency_id' => $euro->id,
'currency_id' => $dollar->id,
'source_id' => $asset->id,
'source_name' => $asset->name,
],
];
/** @var MonthReportGenerator $generator */
$generator = app(MonthReportGenerator::class);
return;
/** @var Account $account */
$account = $this->user()->accounts()->where('account_type_id', 3)->first();
$date = new Carbon;
$start = Carbon::now()->startOfMonth();
$end = Carbon::now()->endOfMonth();
$generator = new MonthReportGenerator();
$generator->setStartDate($start); $generator->setStartDate($start);
$generator->setEndDate($end); $generator->setEndDate($end);
$generator->setAccounts($collection);
$collection = new Collection;
// mock stuff // mock stuff
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class); $currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class); $accountRepos = $this->mock(AccountRepositoryInterface::class);
$collector = $this->mock(TransactionCollectorInterface::class); $collector = $this->mock(GroupCollectorInterface::class);
// mock calls
Steam::shouldReceive('balance')->times(2)->andReturn('100'); Steam::shouldReceive('balance')->times(2)->andReturn('100');
// mock calls:
$accountRepos->shouldReceive('setUser')->once(); $accountRepos->shouldReceive('setUser')->once();
$accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'currency_id'])->andReturn('1')->once(); $accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'currency_id'])->andReturn('1')->once();
$currencyRepos->shouldReceive('findNull')->withArgs([1])->andReturn(TransactionCurrency::first())->once(); // mock collector:
$collector->shouldReceive('setAccounts')->atLeast()->once()->andReturnSelf();
$collector->shouldReceive('setAccounts')->andReturnSelf(); $collector->shouldReceive('setRange')->atLeast()->once()->andReturnSelf();
$collector->shouldReceive('setRange')->andReturnSelf(); $collector->shouldReceive('withAccountInformation')->atLeast()->once()->andReturnSelf();
$collector->shouldReceive('getTransactions')->andReturn($collection); $collector->shouldReceive('getExtractedJournals')->atLeast()->once()->andReturn($return);
$currencyRepos->shouldReceive('findNull')->withArgs([1])->andReturn($euro)->once();
try { try {
$result = $generator->getAuditReport($account, $date); $result = $generator->getAuditReport($asset, $date);
} catch (FireflyException $e) {
$this->assertTrue(false, $e->getMessage());
}
$this->assertFalse($result['exists']);
$this->assertEquals('100', $result['endBalance']);
}
/**
* @covers \FireflyIII\Generator\Report\Audit\MonthReportGenerator
*/
public function testBasicNoCurrency(): void
{
$this->markTestIncomplete('Needs to be rewritten for v4.8.0');
return;
/** @var Account $account */
$account = $this->user()->accounts()->where('account_type_id', 3)->first();
$date = new Carbon;
$start = Carbon::now()->startOfMonth();
$end = Carbon::now()->endOfMonth();
$generator = new MonthReportGenerator();
$generator->setStartDate($start);
$generator->setEndDate($end);
$collection = new Collection;
// mock stuff
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$collector = $this->mock(TransactionCollectorInterface::class);
Steam::shouldReceive('balance')->times(1)->andReturn('100');
// mock calls:
$accountRepos->shouldReceive('setUser')->once();
$accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'currency_id'])->andReturn('1')->once();
$currencyRepos->shouldReceive('findNull')->withArgs([1])->andReturn(null)->once();
$collector->shouldReceive('setAccounts')->andReturnSelf();
$collector->shouldReceive('setRange')->andReturnSelf();
$collector->shouldReceive('getTransactions')->andReturn($collection);
try {
$generator->getAuditReport($account, $date);
} catch (FireflyException $e) {
$this->assertEquals('Unexpected NULL value in account currency preference.', $e->getMessage());
}
}
/**
* @covers \FireflyIII\Generator\Report\Audit\MonthReportGenerator
*/
public function testBasicWithForeign(): void
{
$this->markTestIncomplete('Needs to be rewritten for v4.8.0');
return;
/** @var Account $account */
$account = $this->user()->accounts()->where('account_type_id', 3)->first();
$date = new Carbon;
$start = Carbon::now()->startOfMonth();
$end = Carbon::now()->endOfMonth();
$generator = new MonthReportGenerator();
$generator->setStartDate($start);
$generator->setEndDate($end);
$collection = new Collection;
$transaction = $this->user()->transactions()->first();
$transaction->transaction_amount = '30';
$transaction->foreign_currency_id = 1;
$transaction->transaction_foreign_amount = '30';
$collection->push($transaction);
// mock stuff
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$collector = $this->mock(TransactionCollectorInterface::class);
Steam::shouldReceive('balance')->times(2)->andReturn('100');
// mock calls:
$accountRepos->shouldReceive('setUser')->once();
$accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'currency_id'])->andReturn('1')->once();
$currencyRepos->shouldReceive('findNull')->withArgs([1])->andReturn(TransactionCurrency::first())->once();
$collector->shouldReceive('setAccounts')->andReturnSelf();
$collector->shouldReceive('setRange')->andReturnSelf();
$collector->shouldReceive('getTransactions')->andReturn($collection);
try {
$result = $generator->getAuditReport($account, $date);
} catch (FireflyException $e) {
$this->assertTrue(false, $e->getMessage());
}
$this->assertTrue($result['exists']);
$this->assertEquals('100', $result['endBalance']);
}
/**
* @covers \FireflyIII\Generator\Report\Audit\MonthReportGenerator
*/
public function testBasicWithTransactions(): void
{
$this->markTestIncomplete('Needs to be rewritten for v4.8.0');
return;
/** @var Account $account */
$account = $this->user()->accounts()->where('account_type_id', 3)->first();
$date = new Carbon;
$start = Carbon::now()->startOfMonth();
$end = Carbon::now()->endOfMonth();
$generator = new MonthReportGenerator();
$generator->setStartDate($start);
$generator->setEndDate($end);
$collection = new Collection;
$transaction = $this->user()->transactions()->first();
$transaction->transaction_amount = '30';
$collection->push($transaction);
// mock stuff
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$collector = $this->mock(TransactionCollectorInterface::class);
Steam::shouldReceive('balance')->times(2)->andReturn('100');
// mock calls:
$accountRepos->shouldReceive('setUser')->once();
$accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'currency_id'])->andReturn('1')->once();
$currencyRepos->shouldReceive('findNull')->withArgs([1])->andReturn(TransactionCurrency::first())->once();
$collector->shouldReceive('setAccounts')->andReturnSelf();
$collector->shouldReceive('setRange')->andReturnSelf();
$collector->shouldReceive('getTransactions')->andReturn($collection);
try {
$result = $generator->getAuditReport($account, $date);
} catch (FireflyException $e) { } catch (FireflyException $e) {
$this->assertTrue(false, $e->getMessage()); $this->assertTrue(false, $e->getMessage());
} }
$this->assertTrue($result['exists']); $this->assertTrue($result['exists']);
$this->assertEquals('100', $result['endBalance']); $this->assertEquals('100', $result['endBalance']);
} }
//
// /**
// * @covers \FireflyIII\Generator\Report\Audit\MonthReportGenerator
// */
// public function testBasicNoCurrency(): void
// {
// $this->markTestIncomplete('Needs to be rewritten for v4.8.0');
//
// return;
// /** @var Account $account */
// $account = $this->user()->accounts()->where('account_type_id', 3)->first();
// $date = new Carbon;
// $start = Carbon::now()->startOfMonth();
// $end = Carbon::now()->endOfMonth();
// $generator = new MonthReportGenerator();
// $generator->setStartDate($start);
// $generator->setEndDate($end);
//
// $collection = new Collection;
//
// // mock stuff
// $currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
// $accountRepos = $this->mock(AccountRepositoryInterface::class);
// $collector = $this->mock(TransactionCollectorInterface::class);
// Steam::shouldReceive('balance')->times(1)->andReturn('100');
//
// // mock calls:
// $accountRepos->shouldReceive('setUser')->once();
// $accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'currency_id'])->andReturn('1')->once();
//
// $currencyRepos->shouldReceive('findNull')->withArgs([1])->andReturn(null)->once();
//
// $collector->shouldReceive('setAccounts')->andReturnSelf();
// $collector->shouldReceive('setRange')->andReturnSelf();
// $collector->shouldReceive('getTransactions')->andReturn($collection);
//
//
// try {
// $generator->getAuditReport($account, $date);
// } catch (FireflyException $e) {
// $this->assertEquals('Unexpected NULL value in account currency preference.', $e->getMessage());
// }
// }
//
// /**
// * @covers \FireflyIII\Generator\Report\Audit\MonthReportGenerator
// */
// public function testBasicWithForeign(): void
// {
// $this->markTestIncomplete('Needs to be rewritten for v4.8.0');
//
// return;
// /** @var Account $account */
// $account = $this->user()->accounts()->where('account_type_id', 3)->first();
// $date = new Carbon;
// $start = Carbon::now()->startOfMonth();
// $end = Carbon::now()->endOfMonth();
// $generator = new MonthReportGenerator();
// $generator->setStartDate($start);
// $generator->setEndDate($end);
//
// $collection = new Collection;
// $transaction = $this->user()->transactions()->first();
// $transaction->transaction_amount = '30';
// $transaction->foreign_currency_id = 1;
// $transaction->transaction_foreign_amount = '30';
// $collection->push($transaction);
//
// // mock stuff
// $currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
// $accountRepos = $this->mock(AccountRepositoryInterface::class);
// $collector = $this->mock(TransactionCollectorInterface::class);
// Steam::shouldReceive('balance')->times(2)->andReturn('100');
//
// // mock calls:
// $accountRepos->shouldReceive('setUser')->once();
// $accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'currency_id'])->andReturn('1')->once();
//
// $currencyRepos->shouldReceive('findNull')->withArgs([1])->andReturn(TransactionCurrency::first())->once();
//
// $collector->shouldReceive('setAccounts')->andReturnSelf();
// $collector->shouldReceive('setRange')->andReturnSelf();
// $collector->shouldReceive('getTransactions')->andReturn($collection);
//
//
// try {
// $result = $generator->getAuditReport($account, $date);
// } catch (FireflyException $e) {
// $this->assertTrue(false, $e->getMessage());
// }
// $this->assertTrue($result['exists']);
// $this->assertEquals('100', $result['endBalance']);
// }
//
// /**
// * @covers \FireflyIII\Generator\Report\Audit\MonthReportGenerator
// */
// public function testBasicWithTransactions(): void
// {
// $this->markTestIncomplete('Needs to be rewritten for v4.8.0');
//
// return;
// /** @var Account $account */
// $account = $this->user()->accounts()->where('account_type_id', 3)->first();
// $date = new Carbon;
// $start = Carbon::now()->startOfMonth();
// $end = Carbon::now()->endOfMonth();
// $generator = new MonthReportGenerator();
// $generator->setStartDate($start);
// $generator->setEndDate($end);
//
// $collection = new Collection;
// $transaction = $this->user()->transactions()->first();
// $transaction->transaction_amount = '30';
// $collection->push($transaction);
//
// // mock stuff
// $currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
// $accountRepos = $this->mock(AccountRepositoryInterface::class);
// $collector = $this->mock(TransactionCollectorInterface::class);
// Steam::shouldReceive('balance')->times(2)->andReturn('100');
//
// // mock calls:
// $accountRepos->shouldReceive('setUser')->once();
// $accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'currency_id'])->andReturn('1')->once();
//
// $currencyRepos->shouldReceive('findNull')->withArgs([1])->andReturn(TransactionCurrency::first())->once();
//
// $collector->shouldReceive('setAccounts')->andReturnSelf();
// $collector->shouldReceive('setRange')->andReturnSelf();
// $collector->shouldReceive('getTransactions')->andReturn($collection);
//
//
// try {
// $result = $generator->getAuditReport($account, $date);
// } catch (FireflyException $e) {
// $this->assertTrue(false, $e->getMessage());
// }
// $this->assertTrue($result['exists']);
// $this->assertEquals('100', $result['endBalance']);
// }
} }

View File

@@ -0,0 +1,80 @@
<?php
/**
* StoredGroupEventHandlerTest.php
* Copyright (c) 2019 thegrumpydictator@gmail.com
*
* This file is part of Firefly III.
*
* Firefly III is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Firefly III 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Firefly III. If not, see <http://www.gnu.org/licenses/>.
*/
declare(strict_types=1);
namespace Tests\Unit\Handlers\Events;
use FireflyIII\Events\StoredTransactionGroup;
use FireflyIII\Handlers\Events\StoredGroupEventHandler;
use FireflyIII\TransactionRules\Engine\RuleEngine;
use Log;
use Tests\TestCase;
/**
*
* Class StoredGroupEventHandlerTest
*/
class StoredGroupEventHandlerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Handlers\Events\StoredGroupEventHandler
*/
public function testProcessRules(): void
{
$group = $this->getRandomWithdrawalGroup();
$ruleEngine = $this->mock(RuleEngine::class);
$ruleEngine->shouldReceive('setUser')->atLeast()->once();
$ruleEngine->shouldReceive('setAllRules')->atLeast()->once()->withArgs([true]);
$ruleEngine->shouldReceive('setTriggerMode')->atLeast()->once()->withArgs([RuleEngine::TRIGGER_STORE]);
$ruleEngine->shouldReceive('processTransactionJournal')->atLeast()->once();
$event = new StoredTransactionGroup($group, true);
$handler = new StoredGroupEventHandler;
$handler->processRules($event);
}
/**
* @covers \FireflyIII\Handlers\Events\StoredGroupEventHandler
*/
public function testNoProcessRules(): void
{
$group = $this->getRandomWithdrawalGroup();
$this->mock(RuleEngine::class);
$event = new StoredTransactionGroup($group, false);
$handler = new StoredGroupEventHandler;
$handler->processRules($event);
$this->assertTrue(true);
}
}

View File

@@ -1,6 +1,6 @@
<?php <?php
/** /**
* UpdatedJournalEventHandlerTest.php * UpdatedGroupEventHandlerTest.php
* Copyright (c) 2018 thegrumpydictator@gmail.com * Copyright (c) 2018 thegrumpydictator@gmail.com
* *
* This file is part of Firefly III. * This file is part of Firefly III.
@@ -23,9 +23,7 @@ declare(strict_types=1);
namespace Tests\Unit\Handlers\Events; namespace Tests\Unit\Handlers\Events;
use FireflyIII\Events\StoredTransactionGroup;
use FireflyIII\Events\UpdatedTransactionGroup; use FireflyIII\Events\UpdatedTransactionGroup;
use FireflyIII\Handlers\Events\StoredGroupEventHandler;
use FireflyIII\Handlers\Events\UpdatedGroupEventHandler; use FireflyIII\Handlers\Events\UpdatedGroupEventHandler;
use FireflyIII\TransactionRules\Engine\RuleEngine; use FireflyIII\TransactionRules\Engine\RuleEngine;
use Log; use Log;
@@ -34,7 +32,7 @@ use Tests\TestCase;
/** /**
* Class UpdatedJournalEventHandlerTest * Class UpdatedJournalEventHandlerTest
*/ */
class UpdatedJournalEventHandlerTest extends TestCase class UpdatedGroupEventHandlerTest extends TestCase
{ {
/** /**
* *
@@ -56,7 +54,7 @@ class UpdatedJournalEventHandlerTest extends TestCase
$ruleEngine->shouldReceive('setUser')->atLeast()->once(); $ruleEngine->shouldReceive('setUser')->atLeast()->once();
$ruleEngine->shouldReceive('setAllRules')->atLeast()->once()->withArgs([true]); $ruleEngine->shouldReceive('setAllRules')->atLeast()->once()->withArgs([true]);
$ruleEngine->shouldReceive('setTriggerMode')->atLeast()->once()->withArgs([RuleEngine::TRIGGER_STORE]); $ruleEngine->shouldReceive('setTriggerMode')->atLeast()->once()->withArgs([RuleEngine::TRIGGER_UPDATE]);
$ruleEngine->shouldReceive('processTransactionJournal')->atLeast()->once(); $ruleEngine->shouldReceive('processTransactionJournal')->atLeast()->once();
$event = new UpdatedTransactionGroup($group); $event = new UpdatedTransactionGroup($group);

View File

@@ -54,6 +54,7 @@ class VersionCheckEventHandlerTest extends TestCase
/** /**
* @covers \FireflyIII\Events\RequestedVersionCheckStatus * @covers \FireflyIII\Events\RequestedVersionCheckStatus
* @covers \FireflyIII\Handlers\Events\VersionCheckEventHandler * @covers \FireflyIII\Handlers\Events\VersionCheckEventHandler
* @covers \FireflyIII\Helpers\Update\UpdateTrait
*/ */
public function testCheckForUpdatesError(): void public function testCheckForUpdatesError(): void
{ {
@@ -84,6 +85,7 @@ class VersionCheckEventHandlerTest extends TestCase
/** /**
* @covers \FireflyIII\Events\RequestedVersionCheckStatus * @covers \FireflyIII\Events\RequestedVersionCheckStatus
* @covers \FireflyIII\Handlers\Events\VersionCheckEventHandler * @covers \FireflyIII\Handlers\Events\VersionCheckEventHandler
* @covers \FireflyIII\Helpers\Update\UpdateTrait
*/ */
public function testCheckForUpdatesNewer(): void public function testCheckForUpdatesNewer(): void
{ {
@@ -117,6 +119,40 @@ class VersionCheckEventHandlerTest extends TestCase
/** /**
* @covers \FireflyIII\Events\RequestedVersionCheckStatus * @covers \FireflyIII\Events\RequestedVersionCheckStatus
* @covers \FireflyIII\Handlers\Events\VersionCheckEventHandler * @covers \FireflyIII\Handlers\Events\VersionCheckEventHandler
* @covers \FireflyIII\Helpers\Update\UpdateTrait
*/
public function testCheckForUpdatesSameVersion(): void
{
$updateConfig = new Configuration;
$updateConfig->data = 1;
$checkConfig = new Configuration;
$checkConfig->data = time() - 604800;
$event = new RequestedVersionCheckStatus($this->user());
$request = $this->mock(UpdateRequest::class);
$repos = $this->mock(UserRepositoryInterface::class);
$repos->shouldReceive('hasRole')->andReturn(true)->once();
// is newer than default return:
$version = config('firefly.version');
$first = new Release(['id' => '1', 'title' => $version, 'updated' => '2017-05-01', 'content' => '']);
// report on config variables:
FireflyConfig::shouldReceive('get')->withArgs(['last_update_check', Mockery::any()])->once()->andReturn($checkConfig);
FireflyConfig::shouldReceive('set')->withArgs(['last_update_check', Mockery::any()])->once()->andReturn($checkConfig);
// request thing:
$request->shouldReceive('call')->once();
$request->shouldReceive('getReleases')->once()->andReturn([$first]);
$handler = new VersionCheckEventHandler;
$handler->checkForUpdates($event);
}
/**
* @covers \FireflyIII\Events\RequestedVersionCheckStatus
* @covers \FireflyIII\Handlers\Events\VersionCheckEventHandler
* @covers \FireflyIII\Helpers\Update\UpdateTrait
*/ */
public function testCheckForUpdatesNoAdmin(): void public function testCheckForUpdatesNoAdmin(): void
{ {
@@ -135,7 +171,9 @@ class VersionCheckEventHandlerTest extends TestCase
} }
/** /**
* * @covers \FireflyIII\Events\RequestedVersionCheckStatus
* @covers \FireflyIII\Handlers\Events\VersionCheckEventHandler
* @covers \FireflyIII\Helpers\Update\UpdateTrait
*/ */
public function testCheckForUpdatesNoPermission(): void public function testCheckForUpdatesNoPermission(): void
{ {
@@ -160,6 +198,7 @@ class VersionCheckEventHandlerTest extends TestCase
/** /**
* @covers \FireflyIII\Events\RequestedVersionCheckStatus * @covers \FireflyIII\Events\RequestedVersionCheckStatus
* @covers \FireflyIII\Handlers\Events\VersionCheckEventHandler * @covers \FireflyIII\Handlers\Events\VersionCheckEventHandler
* @covers \FireflyIII\Helpers\Update\UpdateTrait
*/ */
public function testCheckForUpdatesSandstorm(): void public function testCheckForUpdatesSandstorm(): void
{ {
@@ -169,11 +208,13 @@ class VersionCheckEventHandlerTest extends TestCase
$handler = new VersionCheckEventHandler; $handler = new VersionCheckEventHandler;
$handler->checkForUpdates($event); $handler->checkForUpdates($event);
putenv('SANDSTORM=0'); putenv('SANDSTORM=0');
$this->assertTrue(true);
} }
/** /**
* @covers \FireflyIII\Events\RequestedVersionCheckStatus * @covers \FireflyIII\Events\RequestedVersionCheckStatus
* @covers \FireflyIII\Handlers\Events\VersionCheckEventHandler * @covers \FireflyIII\Handlers\Events\VersionCheckEventHandler
* @covers \FireflyIII\Helpers\Update\UpdateTrait
*/ */
public function testCheckForUpdatesTooRecent(): void public function testCheckForUpdatesTooRecent(): void
{ {
@@ -190,7 +231,6 @@ class VersionCheckEventHandlerTest extends TestCase
// report on config variables: // report on config variables:
FireflyConfig::shouldReceive('get')->withArgs(['last_update_check', Mockery::any()])->once()->andReturn($checkConfig); FireflyConfig::shouldReceive('get')->withArgs(['last_update_check', Mockery::any()])->once()->andReturn($checkConfig);
//FireflyConfig::shouldReceive('set')->withArgs(['last_update_check', Mockery::any()])->once()->andReturn($checkConfig);
$handler = new VersionCheckEventHandler; $handler = new VersionCheckEventHandler;
$handler->checkForUpdates($event); $handler->checkForUpdates($event);

View File

@@ -49,17 +49,6 @@ class AttachmentHelperTest extends TestCase
Log::info(sprintf('Now in %s.', get_class($this))); Log::info(sprintf('Now in %s.', get_class($this)));
} }
/**
* @covers \FireflyIII\Helpers\Attachments\AttachmentHelper
*/
public function testGetAttachmentLocation(): void
{
$attachment = Attachment::first();
$helper = new AttachmentHelper;
$path = $path = sprintf('%sat-%d.data', DIRECTORY_SEPARATOR, (int)$attachment->id);
$this->assertEquals($helper->getAttachmentLocation($attachment), $path);
}
/** /**
* Test invalid mime thing * Test invalid mime thing
* *

View File

@@ -24,16 +24,9 @@ namespace Tests\Unit\Helpers\Chart;
use Carbon\Carbon; use Carbon\Carbon;
use FireflyIII\Helpers\Chart\MetaPieChart; use FireflyIII\Helpers\Chart\MetaPieChart;
use FireflyIII\Helpers\Collector\TransactionCollectorInterface; use FireflyIII\Helpers\Collector\GroupCollectorInterface;
use FireflyIII\Helpers\Filter\NegativeAmountFilter;
use FireflyIII\Helpers\Filter\OpposingAccountFilter;
use FireflyIII\Helpers\Filter\PositiveAmountFilter;
use FireflyIII\Helpers\Filter\TransferFilter;
use FireflyIII\Models\Account;
use FireflyIII\Models\Transaction;
use FireflyIII\Models\TransactionType; use FireflyIII\Models\TransactionType;
use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use Illuminate\Support\Collection;
use Log; use Log;
use Tests\TestCase; use Tests\TestCase;
@@ -60,42 +53,48 @@ class MetaPieChartTest extends TestCase
*/ */
public function testGenerateExpenseAccount(): void public function testGenerateExpenseAccount(): void
{ {
$this->markTestIncomplete('Needs to be rewritten for v4.8.0'); $som = (new Carbon())->startOfMonth();
$eom = (new Carbon())->endOfMonth();
return; $one = $this->getRandomAsset();
$som = (new Carbon())->startOfMonth(); $two = $this->getRandomAsset($one->id);
$eom = (new Carbon())->endOfMonth(); $array = [
$collection = $this->fakeTransactions(); [
$accounts = [ 'destination_account_id' => $one->id,
1 => factory(Account::class)->make(), 'budget_id' => 1,
2 => factory(Account::class)->make(), 'category_id' => 1,
'amount' => '10',
],
[
'destination_account_id' => $two->id,
'budget_id' => 2,
'category_id' => 2,
'amount' => '10',
],
]; ];
$collector = $this->mock(GroupCollectorInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
// mock collector so the correct set of journals is returned: // mock collector so the correct set of journals is returned:
// then verify the results. // then verify the results.
$collector = $this->mock(TransactionCollectorInterface::class);
$collector->shouldReceive('addFilter')->withArgs([PositiveAmountFilter::class])->andReturnSelf()->once();
$collector->shouldReceive('removeFilter')->withArgs([NegativeAmountFilter::class])->andReturnSelf()->once();
$collector->shouldReceive('addFilter')->withArgs([NegativeAmountFilter::class])->andReturnSelf()->once();
$collector->shouldReceive('addFilter')->withArgs([OpposingAccountFilter::class])->andReturnSelf()->once();
$collector->shouldReceive('setUser')->andReturnSelf()->once(); $collector->shouldReceive('setUser')->andReturnSelf()->once();
$collector->shouldReceive('setAccounts')->andReturnSelf()->once(); $collector->shouldReceive('setAccounts')->andReturnSelf()->once();
$collector->shouldReceive('setRange')->andReturnSelf()->once(); $collector->shouldReceive('setRange')->andReturnSelf()->once();
$collector->shouldReceive('setBudgets')->andReturnSelf()->once(); $collector->shouldReceive('setBudgets')->andReturnSelf()->once();
$collector->shouldReceive('setCategories')->andReturnSelf()->once(); $collector->shouldReceive('setCategories')->andReturnSelf()->once();
$collector->shouldReceive('setTypes')->withArgs([[TransactionType::WITHDRAWAL, TransactionType::TRANSFER]])->andReturnSelf()->once(); $collector->shouldReceive('setTypes')->withArgs([[TransactionType::WITHDRAWAL, TransactionType::TRANSFER]])->andReturnSelf()->once();
$collector->shouldReceive('withOpposingAccount')->andReturnSelf()->once(); $collector->shouldReceive('getExtractedJournals')->andReturn($array)->atLeast()->once();
$collector->shouldReceive('getTransactions')->andReturn($collection); $collector->shouldReceive('withAccountInformation')->andReturnSelf()->once();
// mock all repositories: // mock all repositories:
$accountRepos = $this->mock(AccountRepositoryInterface::class); $accountRepos->shouldReceive('setUser')->atLeast()->once();
$accountRepos->shouldReceive('findNull')->withArgs([$one->id])->andReturn($one)->atLeast()->once();
$accountRepos->shouldReceive('findNull')->withArgs([$two->id])->andReturn($two)->atLeast()->once();
$accountRepos->shouldReceive('setUser'); /** @var MetaPieChart $helper */
$accountRepos->shouldReceive('findNull')->withArgs([1])->andReturn($accounts[1]); $helper = app(MetaPieChart::class);
$accountRepos->shouldReceive('findNull')->withArgs([2])->andReturn($accounts[2]);
$helper = new MetaPieChart();
$helper->setUser($this->user()); $helper->setUser($this->user());
$helper->setStart($som); $helper->setStart($som);
$helper->setEnd($eom); $helper->setEnd($eom);
@@ -103,10 +102,11 @@ class MetaPieChartTest extends TestCase
// since the set is pretty basic the result is easy to validate: // since the set is pretty basic the result is easy to validate:
$keys = array_keys($chart); $keys = array_keys($chart);
$this->assertEquals($keys[0], $accounts[1]->name); $this->assertContains($keys[0], [$one->name, $two->name]);
$this->assertEquals($keys[1], $accounts[2]->name); $this->assertContains($keys[1], [$one->name, $two->name]);
$this->assertSame(0, bccomp('1000', $chart[$accounts[1]->name]));
$this->assertSame(0, bccomp('1000', $chart[$accounts[2]->name])); $this->assertEquals('10.000000000000', $chart[$one->name]);
$this->assertEquals('10.000000000000', $chart[$two->name]);
$this->assertTrue(true); $this->assertTrue(true);
} }
@@ -114,105 +114,186 @@ class MetaPieChartTest extends TestCase
/** /**
* @covers \FireflyIII\Helpers\Chart\MetaPieChart * @covers \FireflyIII\Helpers\Chart\MetaPieChart
*/ */
public function testGenerateExpenseAccountWithOthers(): void public function testGenerateExpenseAccountOthers(): void
{ {
$this->markTestIncomplete('Needs to be rewritten for v4.8.0'); $som = (new Carbon())->startOfMonth();
$eom = (new Carbon())->endOfMonth();
return; $one = $this->getRandomAsset();
$som = (new Carbon())->startOfMonth(); $two = $this->getRandomAsset($one->id);
$eom = (new Carbon())->endOfMonth(); $array = [
$collection = $this->fakeTransactions(); [
$others = $this->fakeOthers(); 'destination_account_id' => $one->id,
$accounts = [ 'budget_id' => 1,
1 => factory(Account::class)->make(), 'category_id' => 1,
2 => factory(Account::class)->make(), 'amount' => '10',
],
[
'destination_account_id' => $two->id,
'budget_id' => 2,
'category_id' => 2,
'amount' => '10',
],
]; ];
$collector = $this->mock(GroupCollectorInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
// mock collector so the correct set of journals is returned: // mock collector so the correct set of journals is returned:
// then verify the results. // then verify the results.
$collector = $this->mock(TransactionCollectorInterface::class);
$collector->shouldReceive('addFilter')->withArgs([NegativeAmountFilter::class])->andReturnSelf()->once();
$collector->shouldReceive('addFilter')->withArgs([PositiveAmountFilter::class])->andReturnSelf()->once();
$collector->shouldReceive('addFilter')->withArgs([OpposingAccountFilter::class])->andReturnSelf()->once();
$collector->shouldReceive('removeFilter')->withArgs([NegativeAmountFilter::class])->andReturnSelf()->once();
$collector->shouldReceive('setUser')->andReturnSelf()->twice(); $collector->shouldReceive('setUser')->andReturnSelf()->twice();
$collector->shouldReceive('setAccounts')->andReturnSelf()->twice(); $collector->shouldReceive('setAccounts')->andReturnSelf()->twice();
$collector->shouldReceive('setRange')->andReturnSelf()->twice(); $collector->shouldReceive('setRange')->andReturnSelf()->twice();
$collector->shouldReceive('setBudgets')->andReturnSelf()->once(); $collector->shouldReceive('setBudgets')->andReturnSelf()->once();
$collector->shouldReceive('setCategories')->andReturnSelf()->once(); $collector->shouldReceive('setCategories')->andReturnSelf()->once();
$collector->shouldReceive('setTypes')->withArgs([[TransactionType::WITHDRAWAL, TransactionType::TRANSFER]])->andReturnSelf()->once();
$collector->shouldReceive('withOpposingAccount')->andReturnSelf()->once();
$collector->shouldReceive('getTransactions')->andReturn($collection)->once();
$collector->shouldReceive('setTypes')->withArgs([[TransactionType::WITHDRAWAL, TransactionType::TRANSFER]])->andReturnSelf()->once();
$collector->shouldReceive('getExtractedJournals')->andReturn($array)->atLeast()->once();
$collector->shouldReceive('withAccountInformation')->andReturnSelf()->once();
// also collect others:
$collector->shouldReceive('setTypes')->withArgs([[TransactionType::WITHDRAWAL]])->andReturnSelf()->once(); $collector->shouldReceive('setTypes')->withArgs([[TransactionType::WITHDRAWAL]])->andReturnSelf()->once();
$collector->shouldReceive('getTransactions')->andReturn($others)->once(); $collector->shouldReceive('getSum')->atLeast()->once()->andReturn('100');
// mock all repositories: // mock all repositories:
$accountRepos = $this->mock(AccountRepositoryInterface::class); $accountRepos->shouldReceive('setUser')->atLeast()->once();
$accountRepos->shouldReceive('findNull')->withArgs([$one->id])->andReturn($one)->atLeast()->once();
$accountRepos->shouldReceive('findNull')->withArgs([$two->id])->andReturn($two)->atLeast()->once();
$accountRepos->shouldReceive('setUser'); /** @var MetaPieChart $helper */
$accountRepos->shouldReceive('findNull')->withArgs([1])->andReturn($accounts[1]); $helper = app(MetaPieChart::class);
$accountRepos->shouldReceive('findNull')->withArgs([2])->andReturn($accounts[2]);
$helper = new MetaPieChart();
$helper->setCollectOtherObjects(true);
$helper->setUser($this->user()); $helper->setUser($this->user());
$helper->setStart($som); $helper->setStart($som);
$helper->setEnd($eom); $helper->setEnd($eom);
$helper->setCollectOtherObjects(true);
$chart = $helper->generate('expense', 'account'); $chart = $helper->generate('expense', 'account');
// since the set is pretty basic the result is easy to validate: // since the set is pretty basic the result is easy to validate:
$keys = array_keys($chart); $keys = array_keys($chart);
$this->assertEquals($keys[0], $accounts[1]->name); $this->assertContains($keys[0], [$one->name, $two->name]);
$this->assertEquals($keys[1], $accounts[2]->name); $this->assertContains($keys[1], [$one->name, $two->name]);
$this->assertSame(0, bccomp('1000', $chart[$accounts[1]->name]));
$this->assertSame(0, bccomp('1000', $chart[$accounts[2]->name])); $this->assertEquals('10.000000000000', $chart[$one->name]);
$this->assertSame(0, bccomp('-5000', $chart['Everything else'])); $this->assertEquals('10.000000000000', $chart[$two->name]);
$this->assertTrue(true); $this->assertTrue(true);
} }
/**
* @covers \FireflyIII\Helpers\Chart\MetaPieChart
*/
public function testGenerateIncomeAccountOthers(): void
{
$som = (new Carbon())->startOfMonth();
$eom = (new Carbon())->endOfMonth();
$one = $this->getRandomAsset();
$two = $this->getRandomAsset($one->id);
$array = [
[
'destination_account_id' => $one->id,
'budget_id' => 1,
'category_id' => 1,
'amount' => '10',
],
[
'destination_account_id' => $two->id,
'budget_id' => 2,
'category_id' => 2,
'amount' => '10',
],
];
$collector = $this->mock(GroupCollectorInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
// mock collector so the correct set of journals is returned:
// then verify the results.
$collector->shouldReceive('setUser')->andReturnSelf()->twice();
$collector->shouldReceive('setAccounts')->andReturnSelf()->twice();
$collector->shouldReceive('setRange')->andReturnSelf()->twice();
$collector->shouldReceive('setBudgets')->andReturnSelf()->once();
$collector->shouldReceive('setCategories')->andReturnSelf()->once();
$collector->shouldReceive('setTypes')->withArgs([[TransactionType::DEPOSIT, TransactionType::TRANSFER]])->andReturnSelf()->once();
$collector->shouldReceive('getExtractedJournals')->andReturn($array)->atLeast()->once();
$collector->shouldReceive('withAccountInformation')->andReturnSelf()->once();
// also collect others:
$collector->shouldReceive('setTypes')->withArgs([[TransactionType::DEPOSIT]])->andReturnSelf()->once();
$collector->shouldReceive('getSum')->atLeast()->once()->andReturn('100');
// mock all repositories:
$accountRepos->shouldReceive('setUser')->atLeast()->once();
$accountRepos->shouldReceive('findNull')->withArgs([$one->id])->andReturn($one)->atLeast()->once();
$accountRepos->shouldReceive('findNull')->withArgs([$two->id])->andReturn($two)->atLeast()->once();
/** @var MetaPieChart $helper */
$helper = app(MetaPieChart::class);
$helper->setUser($this->user());
$helper->setStart($som);
$helper->setEnd($eom);
$helper->setCollectOtherObjects(true);
$chart = $helper->generate('income', 'account');
// since the set is pretty basic the result is easy to validate:
$keys = array_keys($chart);
$this->assertContains($keys[0], [$one->name, $two->name]);
$this->assertContains($keys[1], [$one->name, $two->name]);
$this->assertEquals('10.000000000000', $chart[$one->name]);
$this->assertEquals('10.000000000000', $chart[$two->name]);
$this->assertTrue(true);
}
/** /**
* @covers \FireflyIII\Helpers\Chart\MetaPieChart * @covers \FireflyIII\Helpers\Chart\MetaPieChart
*/ */
public function testGenerateIncomeAccount(): void public function testGenerateIncomeAccount(): void
{ {
$this->markTestIncomplete('Needs to be rewritten for v4.8.0'); $som = (new Carbon())->startOfMonth();
$eom = (new Carbon())->endOfMonth();
return; $one = $this->getRandomAsset();
$som = (new Carbon())->startOfMonth(); $two = $this->getRandomAsset($one->id);
$eom = (new Carbon())->endOfMonth(); $array = [
$collection = $this->fakeTransactions(); [
$accounts = [ 'destination_account_id' => $one->id,
1 => factory(Account::class)->make(), 'budget_id' => 1,
2 => factory(Account::class)->make(), 'category_id' => 1,
'amount' => '10',
],
[
'destination_account_id' => $two->id,
'budget_id' => 2,
'category_id' => 2,
'amount' => '10',
],
]; ];
$collector = $this->mock(GroupCollectorInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
// mock collector so the correct set of journals is returned: // mock collector so the correct set of journals is returned:
// then verify the results. // then verify the results.
$collector = $this->mock(TransactionCollectorInterface::class);
$collector->shouldReceive('addFilter')->withArgs([NegativeAmountFilter::class])->andReturnSelf()->once();
$collector->shouldReceive('addFilter')->withArgs([OpposingAccountFilter::class])->andReturnSelf()->once();
$collector->shouldReceive('removeFilter')->withArgs([TransferFilter::class])->andReturnSelf()->once();
$collector->shouldReceive('setUser')->andReturnSelf()->once(); $collector->shouldReceive('setUser')->andReturnSelf()->once();
$collector->shouldReceive('setAccounts')->andReturnSelf()->once(); $collector->shouldReceive('setAccounts')->andReturnSelf()->once();
$collector->shouldReceive('setRange')->andReturnSelf()->once(); $collector->shouldReceive('setRange')->andReturnSelf()->once();
$collector->shouldReceive('setBudgets')->andReturnSelf()->once(); $collector->shouldReceive('setBudgets')->andReturnSelf()->once();
$collector->shouldReceive('setCategories')->andReturnSelf()->once(); $collector->shouldReceive('setCategories')->andReturnSelf()->once();
$collector->shouldReceive('setTypes')->withArgs([[TransactionType::DEPOSIT, TransactionType::TRANSFER]])->andReturnSelf()->once(); $collector->shouldReceive('setTypes')->withArgs([[TransactionType::DEPOSIT, TransactionType::TRANSFER]])->andReturnSelf()->once();
$collector->shouldReceive('withOpposingAccount')->andReturnSelf()->once(); $collector->shouldReceive('getExtractedJournals')->andReturn($array)->atLeast()->once();
$collector->shouldReceive('getTransactions')->andReturn($collection); $collector->shouldReceive('withAccountInformation')->andReturnSelf()->once();
// mock all repositories: // mock all repositories:
$accountRepos = $this->mock(AccountRepositoryInterface::class); $accountRepos->shouldReceive('setUser')->atLeast()->once();
$accountRepos->shouldReceive('findNull')->withArgs([$one->id])->andReturn($one)->atLeast()->once();
$accountRepos->shouldReceive('findNull')->withArgs([$two->id])->andReturn($two)->atLeast()->once();
$accountRepos->shouldReceive('setUser'); /** @var MetaPieChart $helper */
$accountRepos->shouldReceive('findNull')->withArgs([1])->andReturn($accounts[1]); $helper = app(MetaPieChart::class);
$accountRepos->shouldReceive('findNull')->withArgs([2])->andReturn($accounts[2]);
$helper = new MetaPieChart();
$helper->setUser($this->user()); $helper->setUser($this->user());
$helper->setStart($som); $helper->setStart($som);
$helper->setEnd($eom); $helper->setEnd($eom);
@@ -220,129 +301,214 @@ class MetaPieChartTest extends TestCase
// since the set is pretty basic the result is easy to validate: // since the set is pretty basic the result is easy to validate:
$keys = array_keys($chart); $keys = array_keys($chart);
$this->assertEquals($keys[0], $accounts[1]->name); $this->assertContains($keys[0], [$one->name, $two->name]);
$this->assertEquals($keys[1], $accounts[2]->name); $this->assertContains($keys[1], [$one->name, $two->name]);
$this->assertSame(0, bccomp('1000', $chart[$accounts[1]->name]));
$this->assertSame(0, bccomp('1000', $chart[$accounts[2]->name])); $this->assertEquals('10.000000000000', $chart[$one->name]);
$this->assertEquals('10.000000000000', $chart[$two->name]);
$this->assertTrue(true); $this->assertTrue(true);
} }
/**
* @covers \FireflyIII\Helpers\Chart\MetaPieChart
*/
public function testGenerateIncomeAccountWithOthers(): void
{
$this->markTestIncomplete('Needs to be rewritten for v4.8.0');
return; // /**
$som = (new Carbon())->startOfMonth(); // * @covers \FireflyIII\Helpers\Chart\MetaPieChart
$eom = (new Carbon())->endOfMonth(); // */
$collection = $this->fakeTransactions(); // public function testGenerateExpenseAccountWithOthers(): void
$others = $this->fakeOthers(); // {
$accounts = [ // $this->markTestIncomplete('Needs to be rewritten for v4.8.0');
1 => factory(Account::class)->make(), //
2 => factory(Account::class)->make(), // return;
]; // $som = (new Carbon())->startOfMonth();
// $eom = (new Carbon())->endOfMonth();
// $collection = $this->fakeTransactions();
// $others = $this->fakeOthers();
// $accounts = [
// 1 => factory(Account::class)->make(),
// 2 => factory(Account::class)->make(),
// ];
//
// // mock collector so the correct set of journals is returned:
// // then verify the results.
// $collector = $this->mock(TransactionCollectorInterface::class);
// $collector->shouldReceive('addFilter')->withArgs([NegativeAmountFilter::class])->andReturnSelf()->once();
// $collector->shouldReceive('addFilter')->withArgs([PositiveAmountFilter::class])->andReturnSelf()->once();
// $collector->shouldReceive('addFilter')->withArgs([OpposingAccountFilter::class])->andReturnSelf()->once();
// $collector->shouldReceive('removeFilter')->withArgs([NegativeAmountFilter::class])->andReturnSelf()->once();
// $collector->shouldReceive('setUser')->andReturnSelf()->twice();
// $collector->shouldReceive('setAccounts')->andReturnSelf()->twice();
// $collector->shouldReceive('setRange')->andReturnSelf()->twice();
// $collector->shouldReceive('setBudgets')->andReturnSelf()->once();
// $collector->shouldReceive('setCategories')->andReturnSelf()->once();
// $collector->shouldReceive('setTypes')->withArgs([[TransactionType::WITHDRAWAL, TransactionType::TRANSFER]])->andReturnSelf()->once();
// $collector->shouldReceive('withOpposingAccount')->andReturnSelf()->once();
// $collector->shouldReceive('getTransactions')->andReturn($collection)->once();
//
// $collector->shouldReceive('setTypes')->withArgs([[TransactionType::WITHDRAWAL]])->andReturnSelf()->once();
// $collector->shouldReceive('getTransactions')->andReturn($others)->once();
//
// // mock all repositories:
// $accountRepos = $this->mock(AccountRepositoryInterface::class);
//
// $accountRepos->shouldReceive('setUser');
// $accountRepos->shouldReceive('findNull')->withArgs([1])->andReturn($accounts[1]);
// $accountRepos->shouldReceive('findNull')->withArgs([2])->andReturn($accounts[2]);
//
// $helper = new MetaPieChart();
// $helper->setCollectOtherObjects(true);
// $helper->setUser($this->user());
// $helper->setStart($som);
// $helper->setEnd($eom);
// $chart = $helper->generate('expense', 'account');
//
// // since the set is pretty basic the result is easy to validate:
// $keys = array_keys($chart);
// $this->assertEquals($keys[0], $accounts[1]->name);
// $this->assertEquals($keys[1], $accounts[2]->name);
// $this->assertSame(0, bccomp('1000', $chart[$accounts[1]->name]));
// $this->assertSame(0, bccomp('1000', $chart[$accounts[2]->name]));
// $this->assertSame(0, bccomp('-5000', $chart['Everything else']));
//
// $this->assertTrue(true);
// }
//
//
// /**
// * @covers \FireflyIII\Helpers\Chart\MetaPieChart
// */
// public function testGenerateIncomeAccount(): void
// {
// $this->markTestIncomplete('Needs to be rewritten for v4.8.0');
//
// return;
// $som = (new Carbon())->startOfMonth();
// $eom = (new Carbon())->endOfMonth();
// $collection = $this->fakeTransactions();
// $accounts = [
// 1 => factory(Account::class)->make(),
// 2 => factory(Account::class)->make(),
// ];
//
// // mock collector so the correct set of journals is returned:
// // then verify the results.
// $collector = $this->mock(TransactionCollectorInterface::class);
//
// $collector->shouldReceive('addFilter')->withArgs([NegativeAmountFilter::class])->andReturnSelf()->once();
// $collector->shouldReceive('addFilter')->withArgs([OpposingAccountFilter::class])->andReturnSelf()->once();
// $collector->shouldReceive('removeFilter')->withArgs([TransferFilter::class])->andReturnSelf()->once();
// $collector->shouldReceive('setUser')->andReturnSelf()->once();
// $collector->shouldReceive('setAccounts')->andReturnSelf()->once();
// $collector->shouldReceive('setRange')->andReturnSelf()->once();
// $collector->shouldReceive('setBudgets')->andReturnSelf()->once();
// $collector->shouldReceive('setCategories')->andReturnSelf()->once();
// $collector->shouldReceive('setTypes')->withArgs([[TransactionType::DEPOSIT, TransactionType::TRANSFER]])->andReturnSelf()->once();
// $collector->shouldReceive('withOpposingAccount')->andReturnSelf()->once();
// $collector->shouldReceive('getTransactions')->andReturn($collection);
//
// // mock all repositories:
// $accountRepos = $this->mock(AccountRepositoryInterface::class);
//
// $accountRepos->shouldReceive('setUser');
// $accountRepos->shouldReceive('findNull')->withArgs([1])->andReturn($accounts[1]);
// $accountRepos->shouldReceive('findNull')->withArgs([2])->andReturn($accounts[2]);
//
// $helper = new MetaPieChart();
// $helper->setUser($this->user());
// $helper->setStart($som);
// $helper->setEnd($eom);
// $chart = $helper->generate('income', 'account');
//
// // since the set is pretty basic the result is easy to validate:
// $keys = array_keys($chart);
// $this->assertEquals($keys[0], $accounts[1]->name);
// $this->assertEquals($keys[1], $accounts[2]->name);
// $this->assertSame(0, bccomp('1000', $chart[$accounts[1]->name]));
// $this->assertSame(0, bccomp('1000', $chart[$accounts[2]->name]));
//
// $this->assertTrue(true);
// }
//
// /**
// * @covers \FireflyIII\Helpers\Chart\MetaPieChart
// */
// public function testGenerateIncomeAccountWithOthers(): void
// {
// $this->markTestIncomplete('Needs to be rewritten for v4.8.0');
//
// return;
// $som = (new Carbon())->startOfMonth();
// $eom = (new Carbon())->endOfMonth();
// $collection = $this->fakeTransactions();
// $others = $this->fakeOthers();
// $accounts = [
// 1 => factory(Account::class)->make(),
// 2 => factory(Account::class)->make(),
// ];
//
// // mock collector so the correct set of journals is returned:
// // then verify the results.
// $collector = $this->mock(TransactionCollectorInterface::class);
// $collector->shouldReceive('addFilter')->withArgs([NegativeAmountFilter::class])->andReturnSelf()->once();
// $collector->shouldReceive('addFilter')->withArgs([OpposingAccountFilter::class])->andReturnSelf()->once();
// $collector->shouldReceive('removeFilter')->withArgs([TransferFilter::class])->andReturnSelf()->once();
// $collector->shouldReceive('setUser')->andReturnSelf()->twice();
// $collector->shouldReceive('setAccounts')->andReturnSelf()->twice();
// $collector->shouldReceive('setRange')->andReturnSelf()->twice();
// $collector->shouldReceive('setBudgets')->andReturnSelf()->once();
// $collector->shouldReceive('setCategories')->andReturnSelf()->once();
// $collector->shouldReceive('setTypes')->withArgs([[TransactionType::DEPOSIT, TransactionType::TRANSFER]])->andReturnSelf()->once();
// $collector->shouldReceive('withOpposingAccount')->andReturnSelf()->once();
// $collector->shouldReceive('getTransactions')->andReturn($collection)->once();
//
// $collector->shouldReceive('setTypes')->withArgs([[TransactionType::DEPOSIT]])->andReturnSelf()->once();
// $collector->shouldReceive('getTransactions')->andReturn($others)->once();
//
// // mock all repositories:
// $accountRepos = $this->mock(AccountRepositoryInterface::class);
//
// $accountRepos->shouldReceive('setUser');
// $accountRepos->shouldReceive('findNull')->withArgs([1])->andReturn($accounts[1]);
// $accountRepos->shouldReceive('findNull')->withArgs([2])->andReturn($accounts[2]);
//
// $helper = new MetaPieChart();
// $helper->setCollectOtherObjects(true);
// $helper->setUser($this->user());
// $helper->setStart($som);
// $helper->setEnd($eom);
// $chart = $helper->generate('income', 'account');
//
// // since the set is pretty basic the result is easy to validate:
// $keys = array_keys($chart);
// $this->assertEquals($keys[0], $accounts[1]->name);
// $this->assertEquals($keys[1], $accounts[2]->name);
// $this->assertSame(0, bccomp('1000', $chart[$accounts[1]->name]));
// $this->assertSame(0, bccomp('1000', $chart[$accounts[2]->name]));
// $this->assertSame(0, bccomp('1000', $chart['Everything else']));
//
// $this->assertTrue(true);
// }
//
// /**
// * @return Collection
// */
// private function fakeOthers(): Collection
// {
// $set = new Collection;
//
// for ($i = 0; $i < 30; ++$i) {
// $transaction = new Transaction;
//
// // basic fields.
// $transaction->opposing_account_id = 3;
// $transaction->transaction_journal_budget_id = 3;
// $transaction->transaction_budget_id = 3;
// $transaction->transaction_journal_category_id = 3;
// $transaction->transaction_category_id = 3;
// $transaction->transaction_amount = '100';
// $set->push($transaction);
// }
//
// return $set;
// }
// mock collector so the correct set of journals is returned:
// then verify the results.
$collector = $this->mock(TransactionCollectorInterface::class);
$collector->shouldReceive('addFilter')->withArgs([NegativeAmountFilter::class])->andReturnSelf()->once();
$collector->shouldReceive('addFilter')->withArgs([OpposingAccountFilter::class])->andReturnSelf()->once();
$collector->shouldReceive('removeFilter')->withArgs([TransferFilter::class])->andReturnSelf()->once();
$collector->shouldReceive('setUser')->andReturnSelf()->twice();
$collector->shouldReceive('setAccounts')->andReturnSelf()->twice();
$collector->shouldReceive('setRange')->andReturnSelf()->twice();
$collector->shouldReceive('setBudgets')->andReturnSelf()->once();
$collector->shouldReceive('setCategories')->andReturnSelf()->once();
$collector->shouldReceive('setTypes')->withArgs([[TransactionType::DEPOSIT, TransactionType::TRANSFER]])->andReturnSelf()->once();
$collector->shouldReceive('withOpposingAccount')->andReturnSelf()->once();
$collector->shouldReceive('getTransactions')->andReturn($collection)->once();
$collector->shouldReceive('setTypes')->withArgs([[TransactionType::DEPOSIT]])->andReturnSelf()->once();
$collector->shouldReceive('getTransactions')->andReturn($others)->once();
// mock all repositories:
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$accountRepos->shouldReceive('setUser');
$accountRepos->shouldReceive('findNull')->withArgs([1])->andReturn($accounts[1]);
$accountRepos->shouldReceive('findNull')->withArgs([2])->andReturn($accounts[2]);
$helper = new MetaPieChart();
$helper->setCollectOtherObjects(true);
$helper->setUser($this->user());
$helper->setStart($som);
$helper->setEnd($eom);
$chart = $helper->generate('income', 'account');
// since the set is pretty basic the result is easy to validate:
$keys = array_keys($chart);
$this->assertEquals($keys[0], $accounts[1]->name);
$this->assertEquals($keys[1], $accounts[2]->name);
$this->assertSame(0, bccomp('1000', $chart[$accounts[1]->name]));
$this->assertSame(0, bccomp('1000', $chart[$accounts[2]->name]));
$this->assertSame(0, bccomp('1000', $chart['Everything else']));
$this->assertTrue(true);
}
/**
* @return Collection
*/
private function fakeOthers(): Collection
{
$set = new Collection;
for ($i = 0; $i < 30; ++$i) {
$transaction = new Transaction;
// basic fields.
$transaction->opposing_account_id = 3;
$transaction->transaction_journal_budget_id = 3;
$transaction->transaction_budget_id = 3;
$transaction->transaction_journal_category_id = 3;
$transaction->transaction_category_id = 3;
$transaction->transaction_amount = '100';
$set->push($transaction);
}
return $set;
}
/**
* @return Collection
*/
private function fakeTransactions(): Collection
{
$set = new Collection;
for ($i = 0; $i < 10; ++$i) {
$transaction = new Transaction;
// basic fields.
$transaction->opposing_account_id = 1;
$transaction->transaction_journal_budget_id = 1;
$transaction->transaction_budget_id = 1;
$transaction->transaction_journal_category_id = 1;
$transaction->transaction_category_id = 1;
$transaction->transaction_amount = '100';
$set->push($transaction);
}
for ($i = 0; $i < 10; ++$i) {
$transaction = new Transaction;
// basic fields.
$transaction->opposing_account_id = 2;
$transaction->transaction_journal_budget_id = 2;
$transaction->transaction_budget_id = 2;
$transaction->transaction_journal_category_id = 2;
$transaction->transaction_category_id = 2;
$transaction->transaction_amount = '100';
$set->push($transaction);
}
return $set;
}
} }

View File

@@ -1,7 +1,7 @@
<?php <?php
/** /**
* FiscalHelperTest.php * FiscalHelperTest.php
* Copyright (c) 2018 thegrumpydictator@gmail.com * Copyright (c) 2019 thegrumpydictator@gmail.com
* *
* This file is part of Firefly III. * This file is part of Firefly III.
* *
@@ -21,11 +21,11 @@
declare(strict_types=1); declare(strict_types=1);
namespace Tests\Unit\Helpers; namespace Tests\Unit\Helpers\Fiscal;
use Carbon\Carbon; use Carbon\Carbon;
use FireflyIII\Helpers\FiscalHelper; use FireflyIII\Helpers\Fiscal\FiscalHelper;
use FireflyIII\Models\Preference; use FireflyIII\Models\Preference;
use Log; use Log;
use Preferences; use Preferences;
@@ -53,7 +53,7 @@ class FiscalHelperTest extends TestCase
* *
* Fiscal year ends next year on Mar 31. * Fiscal year ends next year on Mar 31.
* *
* @covers \FireflyIII\Helpers\FiscalHelper * @covers \FireflyIII\Helpers\Fiscal\FiscalHelper
*/ */
public function testEndOfFiscalYear(): void public function testEndOfFiscalYear(): void
{ {
@@ -79,7 +79,7 @@ class FiscalHelperTest extends TestCase
* *
* Fiscal year ends next year on Dec 31. * Fiscal year ends next year on Dec 31.
* *
* @covers \FireflyIII\Helpers\FiscalHelper * @covers \FireflyIII\Helpers\Fiscal\FiscalHelper
*/ */
public function testEndOfFiscalYearNoPref(): void public function testEndOfFiscalYearNoPref(): void
{ {
@@ -101,7 +101,7 @@ class FiscalHelperTest extends TestCase
* *
* Fiscal year starts in current year. * Fiscal year starts in current year.
* *
* @covers \FireflyIII\Helpers\FiscalHelper * @covers \FireflyIII\Helpers\Fiscal\FiscalHelper
*/ */
public function testStartOfFiscalYear(): void public function testStartOfFiscalYear(): void
{ {
@@ -127,7 +127,7 @@ class FiscalHelperTest extends TestCase
* *
* Fiscal year starts Jan 1st. * Fiscal year starts Jan 1st.
* *
* @covers \FireflyIII\Helpers\FiscalHelper * @covers \FireflyIII\Helpers\Fiscal\FiscalHelper
*/ */
public function testStartOfFiscalYearNoPref(): void public function testStartOfFiscalYearNoPref(): void
{ {
@@ -149,7 +149,7 @@ class FiscalHelperTest extends TestCase
* *
* Fiscal year starts in previous year. * Fiscal year starts in previous year.
* *
* @covers \FireflyIII\Helpers\FiscalHelper * @covers \FireflyIII\Helpers\Fiscal\FiscalHelper
*/ */
public function testStartOfFiscalYearPrev(): void public function testStartOfFiscalYearPrev(): void
{ {