Various bugfixes and code clean up.

This commit is contained in:
James Cole
2018-07-27 04:46:21 +02:00
parent 2ad8e7f343
commit 0312ba8ad7
60 changed files with 223 additions and 353 deletions

View File

@@ -63,6 +63,7 @@ class Import extends Command
{ {
Log::debug('Start start-import command'); Log::debug('Start start-import command');
$jobKey = (string)$this->argument('key'); $jobKey = (string)$this->argument('key');
/** @var ImportJob $job */
$job = ImportJob::where('key', $jobKey)->first(); $job = ImportJob::where('key', $jobKey)->first();
if (null === $job) { if (null === $job) {
$this->errorLine(sprintf('No job found with key "%s"', $jobKey)); $this->errorLine(sprintf('No job found with key "%s"', $jobKey));

View File

@@ -31,6 +31,7 @@ use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Export\Collector\AttachmentCollector; use FireflyIII\Export\Collector\AttachmentCollector;
use FireflyIII\Export\Collector\UploadCollector; use FireflyIII\Export\Collector\UploadCollector;
use FireflyIII\Export\Entry\Entry; use FireflyIII\Export\Entry\Entry;
use FireflyIII\Export\Exporter\ExporterInterface;
use FireflyIII\Helpers\Collector\JournalCollectorInterface; use FireflyIII\Helpers\Collector\JournalCollectorInterface;
use FireflyIII\Helpers\Filter\InternalTransferFilter; use FireflyIII\Helpers\Filter\InternalTransferFilter;
use FireflyIII\Models\AccountMeta; use FireflyIII\Models\AccountMeta;
@@ -220,6 +221,7 @@ class ExpandedProcessor implements ProcessorInterface
public function exportJournals(): bool public function exportJournals(): bool
{ {
$exporterClass = config('firefly.export_formats.' . $this->exportFormat); $exporterClass = config('firefly.export_formats.' . $this->exportFormat);
/** @var ExporterInterface $exporter */
$exporter = app($exporterClass); $exporter = app($exporterClass);
$exporter->setJob($this->job); $exporter->setJob($this->job);
$exporter->setEntries($this->exportEntries); $exporter->setEntries($this->exportEntries);

View File

@@ -43,7 +43,6 @@ class TransactionCurrencyFactory
*/ */
public function create(array $data): ?TransactionCurrency public function create(array $data): ?TransactionCurrency
{ {
$result = null;
try { try {
/** @var TransactionCurrency $currency */ /** @var TransactionCurrency $currency */
$result = TransactionCurrency::create( $result = TransactionCurrency::create(
@@ -55,6 +54,7 @@ class TransactionCurrencyFactory
] ]
); );
} catch (QueryException $e) { } catch (QueryException $e) {
$result = null;
Log::error(sprintf('Could not create new currency: %s', $e->getMessage())); Log::error(sprintf('Could not create new currency: %s', $e->getMessage()));
} }

View File

@@ -81,7 +81,7 @@ class VersionCheckEventHandler
$latestRelease = $this->getLatestRelease(); $latestRelease = $this->getLatestRelease();
$versionCheck = $this->versionCheck($latestRelease); $versionCheck = $this->versionCheck($latestRelease);
$resultString = $this->parseResult($latestRelease, $versionCheck); $resultString = $this->parseResult($versionCheck, $latestRelease);
if (0 !== $versionCheck && '' !== $resultString) { if (0 !== $versionCheck && '' !== $resultString) {
// flash info // flash info
session()->flash('info', $resultString); session()->flash('info', $resultString);

View File

@@ -77,11 +77,12 @@ class AttachmentHelper implements AttachmentHelperInterface
*/ */
public function getAttachmentContent(Attachment $attachment): string public function getAttachmentContent(Attachment $attachment): string
{ {
$content = '';
try { try {
$content = Crypt::decrypt($this->uploadDisk->get(sprintf('at-%d.data', $attachment->id))); $content = Crypt::decrypt($this->uploadDisk->get(sprintf('at-%d.data', $attachment->id)));
} catch (DecryptException|FileNotFoundException $e) { } catch (DecryptException|FileNotFoundException $e) {
Log::error(sprintf('Could not decrypt data of attachment #%d: %s', $attachment->id, $e->getMessage())); Log::error(sprintf('Could not decrypt data of attachment #%d: %s', $attachment->id, $e->getMessage()));
$content = '';
} }
return $content; return $content;

View File

@@ -76,7 +76,8 @@ class Help implements HelpInterface
$statusCode = $res->getStatusCode(); $statusCode = $res->getStatusCode();
$content = trim($res->getBody()->getContents()); $content = trim($res->getBody()->getContents());
} catch (GuzzleException|Exception $e) { } catch (GuzzleException|Exception $e) {
Log::error($e); Log::error($e->getMessage());
Log::error($e->getTraceAsString());
} }
Log::debug(sprintf('Status code is %d', $statusCode)); Log::debug(sprintf('Status code is %d', $statusCode));

View File

@@ -66,12 +66,12 @@ trait UpdateTrait
/** /**
* Parses the version check result in a human readable sentence. * Parses the version check result in a human readable sentence.
* *
* @param Release|null $release
* @param int $versionCheck * @param int $versionCheck
* @param Release|null $release
* *
* @return string * @return string
*/ */
public function parseResult(Release $release = null, int $versionCheck): string public function parseResult(int $versionCheck, Release $release = null): string
{ {
$current = (string)config('firefly.version'); $current = (string)config('firefly.version');
$return = ''; $return = '';

View File

@@ -144,10 +144,13 @@ class ReconcileController extends Controller
// get start and end // get start and end
if (null === $start && null === $end) { if (null === $start && null === $end) {
/** @var Carbon $start */
$start = clone session('start', app('navigation')->startOfPeriod(new Carbon, $range)); $start = clone session('start', app('navigation')->startOfPeriod(new Carbon, $range));
/** @var Carbon $end */
$end = clone session('end', app('navigation')->endOfPeriod(new Carbon, $range)); $end = clone session('end', app('navigation')->endOfPeriod(new Carbon, $range));
} }
if (null === $end) { if (null === $end) {
/** @var Carbon $end */
$end = app('navigation')->endOfPeriod($start, $range); $end = app('navigation')->endOfPeriod($start, $range);
} }

View File

@@ -90,7 +90,9 @@ class ShowController extends Controller
if (AccountType::INITIAL_BALANCE === $account->accountType->type) { if (AccountType::INITIAL_BALANCE === $account->accountType->type) {
return $this->redirectToOriginalAccount($account); return $this->redirectToOriginalAccount($account);
} }
/** @var Carbon $start */
$start = $start ?? session('start'); $start = $start ?? session('start');
/** @var Carbon $end */
$end = $end ?? session('end'); $end = $end ?? session('end');
if ($end < $start) { if ($end < $start) {
throw new FireflyException('End is after start!'); // @codeCoverageIgnore throw new FireflyException('End is after start!'); // @codeCoverageIgnore

View File

@@ -101,7 +101,7 @@ class UpdateController extends Controller
{ {
$latestRelease = $this->getLatestRelease(); $latestRelease = $this->getLatestRelease();
$versionCheck = $this->versionCheck($latestRelease); $versionCheck = $this->versionCheck($latestRelease);
$resultString = $this->parseResult($latestRelease, $versionCheck); $resultString = $this->parseResult($versionCheck, $latestRelease);
if (0 !== $versionCheck && '' !== $resultString) { if (0 !== $versionCheck && '' !== $resultString) {
// flash info // flash info

View File

@@ -22,6 +22,7 @@ declare(strict_types=1);
namespace FireflyIII\Http\Controllers; namespace FireflyIII\Http\Controllers;
use Carbon\Carbon;
use FireflyIII\Helpers\Attachments\AttachmentHelperInterface; use FireflyIII\Helpers\Attachments\AttachmentHelperInterface;
use FireflyIII\Helpers\Collector\JournalCollectorInterface; use FireflyIII\Helpers\Collector\JournalCollectorInterface;
use FireflyIII\Http\Requests\BillFormRequest; use FireflyIII\Http\Requests\BillFormRequest;
@@ -277,7 +278,9 @@ class BillController extends Controller
// add info about rules: // add info about rules:
$rules = $this->billRepository->getRulesForBill($bill); $rules = $this->billRepository->getRulesForBill($bill);
$subTitle = $bill->name; $subTitle = $bill->name;
/** @var Carbon $start */
$start = session('start'); $start = session('start');
/** @var Carbon $end */
$end = session('end'); $end = session('end');
$year = $start->year; $year = $start->year;
$page = (int)$request->get('page'); $page = (int)$request->get('page');

View File

@@ -77,6 +77,7 @@ class IndexController extends Controller
*/ */
public function index(Request $request, string $moment = null) public function index(Request $request, string $moment = null)
{ {
/** @var string $range */
$range = app('preferences')->get('viewRange', '1M')->data; $range = app('preferences')->get('viewRange', '1M')->data;
/** @var Carbon $start */ /** @var Carbon $start */
$start = session('start', new Carbon); $start = session('start', new Carbon);

View File

@@ -195,6 +195,7 @@ class ShowController extends Controller
->setBudget($budget)->setLimit($pageSize)->setPage($page)->withBudgetInformation(); ->setBudget($budget)->setLimit($pageSize)->setPage($page)->withBudgetInformation();
$transactions = $collector->getPaginatedJournals(); $transactions = $collector->getPaginatedJournals();
$transactions->setPath(route('budgets.show', [$budget->id, $budgetLimit->id])); $transactions->setPath(route('budgets.show', [$budget->id, $budgetLimit->id]));
/** @var Carbon $start */
$start = session('first', Carbon::create()->startOfYear()); $start = session('first', Carbon::create()->startOfYear());
$end = new Carbon; $end = new Carbon;
$limits = $this->getLimits($budget, $start, $end); $limits = $this->getLimits($budget, $start, $end);

View File

@@ -74,7 +74,9 @@ class AccountController extends Controller
*/ */
public function expenseAccounts(AccountRepositoryInterface $repository): JsonResponse public function expenseAccounts(AccountRepositoryInterface $repository): JsonResponse
{ {
/** @var Carbon $start */
$start = clone session('start', Carbon::now()->startOfMonth()); $start = clone session('start', Carbon::now()->startOfMonth());
/** @var Carbon $end */
$end = clone session('end', Carbon::now()->endOfMonth()); $end = clone session('end', Carbon::now()->endOfMonth());
$cache = new CacheProperties; $cache = new CacheProperties;
$cache->addProperty($start); $cache->addProperty($start);

View File

@@ -276,7 +276,7 @@ class DebugController extends Controller
{ {
$packages = []; $packages = [];
$file = \dirname(__DIR__, 3) . '/vendor/composer/installed.json'; $file = \dirname(__DIR__, 3) . '/vendor/composer/installed.json';
if (!(false === $file) && file_exists($file)) { if (file_exists($file)) {
// file exists! // file exists!
$content = file_get_contents($file); $content = file_get_contents($file);
$json = json_decode($content, true); $json = json_decode($content, true);

View File

@@ -59,6 +59,7 @@ class HelpController extends Controller
*/ */
public function show(string $route): JsonResponse public function show(string $route): JsonResponse
{ {
/** @var string $language */
$language = app('preferences')->get('language', config('firefly.default_language', 'en_US'))->data; $language = app('preferences')->get('language', config('firefly.default_language', 'en_US'))->data;
$html = $this->getHelpText($route, $language); $html = $this->getHelpText($route, $language);

View File

@@ -149,8 +149,11 @@ class JavascriptController extends Controller
private function getDateRangeConfig(): array private function getDateRangeConfig(): array
{ {
$viewRange = app('preferences')->get('viewRange', '1M')->data; $viewRange = app('preferences')->get('viewRange', '1M')->data;
/** @var Carbon $start */
$start = session('start'); $start = session('start');
/** @var Carbon $end */
$end = session('end'); $end = session('end');
/** @var Carbon $first */
$first = session('first'); $first = session('first');
$title = sprintf('%s - %s', $start->formatLocalized($this->monthAndDayFormat), $end->formatLocalized($this->monthAndDayFormat)); $title = sprintf('%s - %s', $start->formatLocalized($this->monthAndDayFormat), $end->formatLocalized($this->monthAndDayFormat));
$isCustom = true === session('is_custom_range', false); $isCustom = true === session('is_custom_range', false);

View File

@@ -54,7 +54,9 @@ class BoxController extends Controller
*/ */
public function available(BudgetRepositoryInterface $repository): JsonResponse public function available(BudgetRepositoryInterface $repository): JsonResponse
{ {
/** @var Carbon $start */
$start = session('start', Carbon::now()->startOfMonth()); $start = session('start', Carbon::now()->startOfMonth());
/** @var Carbon $end */
$end = session('end', Carbon::now()->endOfMonth()); $end = session('end', Carbon::now()->endOfMonth());
$today = new Carbon; $today = new Carbon;
$cache = new CacheProperties; $cache = new CacheProperties;
@@ -111,7 +113,9 @@ class BoxController extends Controller
public function balance(CurrencyRepositoryInterface $repository): JsonResponse public function balance(CurrencyRepositoryInterface $repository): JsonResponse
{ {
// Cache result, return cache if present. // Cache result, return cache if present.
/** @var Carbon $start */
$start = session('start', Carbon::now()->startOfMonth()); $start = session('start', Carbon::now()->startOfMonth());
/** @var Carbon $end */
$end = session('end', Carbon::now()->endOfMonth()); $end = session('end', Carbon::now()->endOfMonth());
$cache = new CacheProperties; $cache = new CacheProperties;
$cache->addProperty($start); $cache->addProperty($start);
@@ -195,7 +199,9 @@ class BoxController extends Controller
*/ */
public function bills(BillRepositoryInterface $repository): JsonResponse public function bills(BillRepositoryInterface $repository): JsonResponse
{ {
/** @var Carbon $start */
$start = session('start', Carbon::now()->startOfMonth()); $start = session('start', Carbon::now()->startOfMonth());
/** @var Carbon $end */
$end = session('end', Carbon::now()->endOfMonth()); $end = session('end', Carbon::now()->endOfMonth());
$cache = new CacheProperties; $cache = new CacheProperties;

View File

@@ -161,7 +161,7 @@ class ReconcileController extends Controller
$currencyId = (int)$this->accountRepos->getMetaValue($account, 'currency_id'); $currencyId = (int)$this->accountRepos->getMetaValue($account, 'currency_id');
$currency = $this->currencyRepos->findNull($currencyId); $currency = $this->currencyRepos->findNull($currencyId);
if (0 === $currency) { if (0 === $currencyId) {
$currency = app('amount')->getDefaultCurrency(); // @codeCoverageIgnore $currency = app('amount')->getDefaultCurrency(); // @codeCoverageIgnore
} }

View File

@@ -156,10 +156,10 @@ class RecurrenceController extends Controller
if ($date > $today || 'true' === (string)$request->get('past')) { if ($date > $today || 'true' === (string)$request->get('past')) {
$weekly = sprintf('weekly,%s', $date->dayOfWeekIso); $weekly = sprintf('weekly,%s', $date->dayOfWeekIso);
$monthly = sprintf('monthly,%s', $date->day); $monthly = sprintf('monthly,%s', $date->day);
$dayOfWeek = trans(sprintf('config.dow_%s', $date->dayOfWeekIso)); $dayOfWeek = (string)trans(sprintf('config.dow_%s', $date->dayOfWeekIso));
$ndom = sprintf('ndom,%s,%s', $date->weekOfMonth, $date->dayOfWeekIso); $ndom = sprintf('ndom,%s,%s', $date->weekOfMonth, $date->dayOfWeekIso);
$yearly = sprintf('yearly,%s', $date->format('Y-m-d')); $yearly = sprintf('yearly,%s', $date->format('Y-m-d'));
$yearlyDate = $date->formatLocalized(trans('config.month_and_day_no_year')); $yearlyDate = $date->formatLocalized((string)trans('config.month_and_day_no_year'));
$result = [ $result = [
'daily' => ['label' => (string)trans('firefly.recurring_daily'), 'selected' => 0 === strpos($preSelected, 'daily')], 'daily' => ['label' => (string)trans('firefly.recurring_daily'), 'selected' => 0 === strpos($preSelected, 'daily')],
$weekly => ['label' => (string)trans('firefly.recurring_weekly', ['weekday' => $dayOfWeek]), $weekly => ['label' => (string)trans('firefly.recurring_weekly', ['weekday' => $dayOfWeek]),

View File

@@ -95,19 +95,16 @@ class IndexController extends Controller
/** /**
* Show a single recurring transaction. * Show a single recurring transaction.
* *
* @param Request $request
* @param Recurrence $recurrence * @param Recurrence $recurrence
* *
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
* @throws FireflyException * @throws FireflyException
*/ */
public function show(Request $request, Recurrence $recurrence) public function show(Recurrence $recurrence)
{ {
$transformer = new RecurrenceTransformer(new ParameterBag); $transformer = new RecurrenceTransformer(new ParameterBag);
$array = $transformer->transform($recurrence); $array = $transformer->transform($recurrence);
$page = (int)$request->get('page'); $transactions = $this->recurring->getTransactions($recurrence);
$pageSize = (int)app('preferences')->get('listPageSize', 50)->data;
$transactions = $this->recurring->getTransactions($recurrence, $page, $pageSize);
// transform dates back to Carbon objects: // transform dates back to Carbon objects:
foreach ($array['recurrence_repetitions'] as $index => $repetition) { foreach ($array['recurrence_repetitions'] as $index => $repetition) {

View File

@@ -61,8 +61,6 @@ class Installer
return $next($request); return $next($request);
} }
// Log::debug(sprintf('URL is %s, will run installer middleware', $url));
// no tables present? // no tables present?
try { try {
DB::table('users')->count(); DB::table('users')->count();

View File

@@ -47,6 +47,7 @@ class ExportFormRequest extends Request
*/ */
public function rules(): array public function rules(): array
{ {
/** @var Carbon $sessionFirst */
$sessionFirst = clone session('first'); $sessionFirst = clone session('first');
$first = $sessionFirst->subDay()->format('Y-m-d'); $first = $sessionFirst->subDay()->format('Y-m-d');
$today = Carbon::create()->addDay()->format('Y-m-d'); $today = Carbon::create()->addDay()->format('Y-m-d');

View File

@@ -190,7 +190,7 @@ class RecurrenceFormRequest extends Request
$rules['repetitions'] = 'required|numeric|between:0,254'; $rules['repetitions'] = 'required|numeric|between:0,254';
} }
// if foreign amount, currency must be different. // if foreign amount, currency must be different.
if (0.0 !== $this->float('foreign_amount')) { if (null !== $this->float('foreign_amount')) {
$rules['foreign_currency_id'] = 'exists:transaction_currencies,id|different:transaction_currency_id'; $rules['foreign_currency_id'] = 'exists:transaction_currencies,id|different:transaction_currency_id';
} }

View File

@@ -56,11 +56,15 @@ class Request extends FormRequest
* *
* @param string $field * @param string $field
* *
* @return float * @return float|null
*/ */
public function float(string $field): float public function float(string $field): ?float
{ {
return (float)$this->get($field); $res = $this->get($field);
if(null === $res) {
return null;
}
return (float)$res;
} }
/** /**

View File

@@ -50,6 +50,7 @@ class SelectTransactionsRequest extends Request
public function rules(): array public function rules(): array
{ {
// fixed // fixed
/** @var Carbon $sessionFirst */
$sessionFirst = clone session('first'); $sessionFirst = clone session('first');
$first = $sessionFirst->subDay()->format('Y-m-d'); $first = $sessionFirst->subDay()->format('Y-m-d');
$today = Carbon::create()->addDay()->format('Y-m-d'); $today = Carbon::create()->addDay()->format('Y-m-d');

View File

@@ -113,7 +113,7 @@ class BunqJobConfiguration implements JobConfigurationInterface
Log::debug(sprintf('Now in BunqJobConfiguration::getHandler() with stage "%s"', $this->importJob->stage)); Log::debug(sprintf('Now in BunqJobConfiguration::getHandler() with stage "%s"', $this->importJob->stage));
$handler = null; $handler = null;
switch ($this->importJob->stage) { switch ($this->importJob->stage) {
case 'new'; case 'new':
$handler = app(NewBunqJobHandler::class); $handler = app(NewBunqJobHandler::class);
$handler->setImportJob($this->importJob); $handler->setImportJob($this->importJob);
break; break;

View File

@@ -101,13 +101,10 @@ class FileJobConfiguration implements JobConfigurationInterface
return 'import.file.new'; return 'import.file.new';
case 'configure-upload': case 'configure-upload':
return 'import.file.configure-upload'; return 'import.file.configure-upload';
break;
case 'roles': case 'roles':
return 'import.file.roles'; return 'import.file.roles';
break;
case 'map': case 'map':
return 'import.file.map'; return 'import.file.map';
break;
default: default:
// @codeCoverageIgnoreStart // @codeCoverageIgnoreStart
throw new FireflyException( throw new FireflyException(

View File

@@ -185,7 +185,9 @@ class ImportArrayStorage
unset($transaction['importHashV2']); unset($transaction['importHashV2']);
$json = json_encode($transaction); $json = json_encode($transaction);
if (false === $json) { if (false === $json) {
throw new FireflyException('Could not encode import array. Please see the logs.', $transaction); // @codeCoverageIgnore /** @noinspection ForgottenDebugOutputInspection */
Log::error('Could not encode import array.', print_r($transaction, true));
throw new FireflyException('Could not encode import array. Please see the logs.'); // @codeCoverageIgnore
} }
$hash = hash('sha256', $json, false); $hash = hash('sha256', $json, false);
Log::debug(sprintf('The hash is: %s', $hash)); Log::debug(sprintf('The hash is: %s', $hash));

View File

@@ -161,7 +161,7 @@ class BillRepository implements BillRepositoryInterface
$set = $set->sortBy( $set = $set->sortBy(
function (Bill $bill) { function (Bill $bill) {
$int = 1 === $bill->active ? 0 : 1; $int = $bill->active ? 0 : 1;
return $int . strtolower($bill->name); return $int . strtolower($bill->name);
} }

View File

@@ -144,11 +144,12 @@ class ExportJobRepository implements ExportJobRepositoryInterface
{ {
$disk = Storage::disk('export'); $disk = Storage::disk('export');
$file = $job->key . '.zip'; $file = $job->key . '.zip';
$content = '';
try { try {
$content = $disk->get($file); $content = $disk->get($file);
} catch (FileNotFoundException $e) { } catch (FileNotFoundException $e) {
Log::warning(sprintf('File not found: %s', $e->getMessage())); Log::warning(sprintf('File not found: %s', $e->getMessage()));
$content = '';
} }
return $content; return $content;

View File

@@ -150,12 +150,7 @@ class ImportJobRepository implements ImportJobRepositoryInterface
*/ */
public function getConfiguration(ImportJob $job): array public function getConfiguration(ImportJob $job): array
{ {
$config = $job->configuration; return $job->configuration;
if (\is_array($config)) {
return $config;
}
return [];
} }
/** /**

View File

@@ -477,7 +477,6 @@ class JournalRepository implements JournalRepositoryInterface
$value = $entry->data; $value = $entry->data;
// return when array:
if (\is_array($value)) { if (\is_array($value)) {
$return = implode(',', $value); $return = implode(',', $value);
$cache->store($return); $cache->store($return);

View File

@@ -379,7 +379,7 @@ class RecurringRepository implements RecurringRepositoryInterface
$repDate = Carbon::createFromFormat('Y-m-d', $repetition->repetition_moment); $repDate = Carbon::createFromFormat('Y-m-d', $repetition->repetition_moment);
$diffInYears = $today->diffInYears($repDate); $diffInYears = $today->diffInYears($repDate);
$repDate->addYears($diffInYears); // technically not necessary. $repDate->addYears($diffInYears); // technically not necessary.
$string = $repDate->formatLocalized(trans('config.month_and_day_no_year')); $string = $repDate->formatLocalized((string)trans('config.month_and_day_no_year'));
return (string)trans('firefly.recurring_yearly', ['date' => $string], $language); return (string)trans('firefly.recurring_yearly', ['date' => $string], $language);
} }

View File

@@ -67,18 +67,18 @@ class ValidRecurrenceRepetitionValue implements Rule
return $this->validateMonthly($value); return $this->validateMonthly($value);
} }
//ndom,3,7 // Value is like: ndom,3,7
// nth x-day of the month. // nth x-day of the month.
if (0 === strpos($value, 'ndom')) { if (0 === strpos($value, 'ndom')) {
return $this->validateNdom($value); return $this->validateNdom($value);
} }
//weekly,7 // Value is like: weekly,7
if (0 === strpos($value, 'weekly')) { if (0 === strpos($value, 'weekly')) {
return $this->validateWeekly($value); return $this->validateWeekly($value);
} }
//yearly,2018-01-01 // Value is like: yearly,2018-01-01
if (0 === strpos($value, 'yearly')) { if (0 === strpos($value, 'yearly')) {
return $this->validateYearly($value); return $this->validateYearly($value);
} }

View File

@@ -29,6 +29,7 @@ use bunq\Util\BunqEnumApiEnvironmentType;
use Exception; use Exception;
use FireflyIII\Exceptions\FireflyException; use FireflyIII\Exceptions\FireflyException;
use Log; use Log;
use Tests\Object\FakeApiContext;
/** /**
* Special class to hide away bunq's static initialisation methods. * Special class to hide away bunq's static initialisation methods.
@@ -46,10 +47,10 @@ class ApiContext
* @param string|null $proxyUrl * @param string|null $proxyUrl
* *
* @throws FireflyException * @throws FireflyException
* @return BunqApiContext * @return BunqApiContext|FakeApiContext
*/ */
public function create(BunqEnumApiEnvironmentType $environmentType, string $apiKey, string $description, array $permittedIps, string $proxyUrl = null public function create(BunqEnumApiEnvironmentType $environmentType, string $apiKey, string $description, array $permittedIps, string $proxyUrl = null
): BunqApiContext { ) {
$permittedIps = $permittedIps ?? []; $permittedIps = $permittedIps ?? [];
try { try {
$context = BunqApiContext::create($environmentType, $apiKey, $description, $permittedIps, $proxyUrl); $context = BunqApiContext::create($environmentType, $apiKey, $description, $permittedIps, $proxyUrl);

View File

@@ -41,7 +41,6 @@ class IpifyOrg implements IPRetrievalInterface
*/ */
public function getIP(): ?string public function getIP(): ?string
{ {
$result = null;
try { try {
$client = new Client; $client = new Client;
$res = $client->request('GET', 'https://api.ipify.org'); $res = $client->request('GET', 'https://api.ipify.org');

View File

@@ -28,6 +28,7 @@ use FireflyIII\Factory\BudgetFactory;
use FireflyIII\Factory\CategoryFactory; use FireflyIII\Factory\CategoryFactory;
use FireflyIII\Factory\PiggyBankFactory; use FireflyIII\Factory\PiggyBankFactory;
use FireflyIII\Factory\TransactionCurrencyFactory; use FireflyIII\Factory\TransactionCurrencyFactory;
use FireflyIII\Models\Account;
use FireflyIII\Models\AccountType; use FireflyIII\Models\AccountType;
use FireflyIII\Models\Recurrence; use FireflyIII\Models\Recurrence;
use FireflyIII\Models\RecurrenceMeta; use FireflyIII\Models\RecurrenceMeta;
@@ -44,6 +45,15 @@ use Log;
*/ */
trait RecurringTransactionTrait trait RecurringTransactionTrait
{ {
/**
* @param null|string $expectedType
* @param int|null $accountId
* @param null|string $accountName
*
* @return Account|null
*/
abstract public function findAccount(?string $expectedType, ?int $accountId, ?string $accountName): ?Account;
/** /**
* @param Recurrence $recurrence * @param Recurrence $recurrence
* @param array $repetitions * @param array $repetitions

View File

@@ -124,7 +124,6 @@ trait TransactionServiceTrait
// alternatively, return by name. Validator should catch invalid names. // alternatively, return by name. Validator should catch invalid names.
return $repository->findByName($accountName, [AccountType::ASSET]); return $repository->findByName($accountName, [AccountType::ASSET]);
break;
case AccountType::EXPENSE: case AccountType::EXPENSE:
if ($accountId > 0) { if ($accountId > 0) {
// must be able to find it based on ID. Validator should catch invalid ID's. // must be able to find it based on ID. Validator should catch invalid ID's.
@@ -140,7 +139,6 @@ trait TransactionServiceTrait
// return cash account: // return cash account:
return $repository->getCashAccount(); return $repository->getCashAccount();
break;
case AccountType::REVENUE: case AccountType::REVENUE:
if ($accountId > 0) { if ($accountId > 0) {
// must be able to find it based on ID. Validator should catch invalid ID's. // must be able to find it based on ID. Validator should catch invalid ID's.

View File

@@ -250,7 +250,7 @@ abstract class SpectreRequest
$client = new Client; $client = new Client;
$res = $client->request('POST', $fullUri, ['headers' => $headers, 'body' => $body]); $res = $client->request('POST', $fullUri, ['headers' => $headers, 'body' => $body]);
} catch (GuzzleException|Exception $e) { } catch (GuzzleException|Exception $e) {
throw new FireflyException(sprintf('Request Exception: %s', $e->getMessage())); throw new FireflyException(sprintf('Guzzle Exception: %s', $e->getMessage()));
} }
$body = $res->getBody()->getContents(); $body = $res->getBody()->getContents();
$statusCode = $res->getStatusCode(); $statusCode = $res->getStatusCode();

View File

@@ -66,22 +66,18 @@ class ImportProvider implements BinderInterface
$isDemoUser = $repository->hasRole($user, 'demo'); $isDemoUser = $repository->hasRole($user, 'demo');
$isDebug = (bool)config('app.debug'); $isDebug = (bool)config('app.debug');
foreach ($providerNames as $providerName) { foreach ($providerNames as $providerName) {
//Log::debug(sprintf('Now with provider %s', $providerName));
// only consider enabled providers // only consider enabled providers
$enabled = (bool)config(sprintf('import.enabled.%s', $providerName)); $enabled = (bool)config(sprintf('import.enabled.%s', $providerName));
$allowedForDemo = (bool)config(sprintf('import.allowed_for_demo.%s', $providerName)); $allowedForDemo = (bool)config(sprintf('import.allowed_for_demo.%s', $providerName));
$allowedForUser = (bool)config(sprintf('import.allowed_for_user.%s', $providerName)); $allowedForUser = (bool)config(sprintf('import.allowed_for_user.%s', $providerName));
if (false === $enabled) { if (false === $enabled) {
//Log::debug('Provider is not enabled. NEXT!');
continue; continue;
} }
if (true === $isDemoUser && false === $allowedForDemo) { if (true === $isDemoUser && false === $allowedForDemo) {
//Log::debug('User is demo and this provider is not allowed for demo user. NEXT!');
continue; continue;
} }
if (false === $isDemoUser && false === $allowedForUser && false === $isDebug) { if (false === $isDemoUser && false === $allowedForUser && false === $isDebug) {
//Log::debug('User is not demo and this provider is not allowed for such users. NEXT!');
continue; // @codeCoverageIgnore continue; // @codeCoverageIgnore
} }

View File

@@ -28,8 +28,11 @@ use Illuminate\Support\Facades\Facade;
/** /**
* @codeCoverageIgnore * @codeCoverageIgnore
* Class FireflyConfig. * Class FireflyConfig.
* @method ?Configuration get($name, $default = null) * @method null|Configuration get($name, $default = null)
* @method Configuration set(string $name, $value) * @method Configuration set(string $name, $value)
* @method delete(string $name)
* @method Configuration|null getFresh(string $name, $default = null)
* @method Configuration put(string $name, $value)
*/ */
class FireflyConfig extends Facade class FireflyConfig extends Facade
{ {

View File

@@ -34,7 +34,7 @@ use Illuminate\Support\Facades\Facade;
* @method Collection beginsWith(User $user, string $search) * @method Collection beginsWith(User $user, string $search)
* @method bool delete(string $name) * @method bool delete(string $name)
* @method Collection findByName(string $name) * @method Collection findByName(string $name)
* @method Preference get(string $name, $value) * @method Preference get(string $name, $value = null)
* @method array getArrayForUser(User $user, array $list) * @method array getArrayForUser(User $user, array $list)
* @method Preference|null getForUser(User $user, string $name, $default = null) * @method Preference|null getForUser(User $user, string $name, $default = null)
* @method string lastActivity() * @method string lastActivity()

View File

@@ -55,7 +55,7 @@ class FireflyConfig
* *
* @return \FireflyIII\Models\Configuration|null * @return \FireflyIII\Models\Configuration|null
*/ */
public function get(string $name, $default = null): ?Configuration public function get(string $name, $default = null): ?Configuration
{ {
$fullName = 'ff-config-' . $name; $fullName = 'ff-config-' . $name;
if (Cache::has($fullName)) { if (Cache::has($fullName)) {

View File

@@ -63,7 +63,6 @@ class ConfigureRolesHandler implements FileConfigurationInterface
{ {
/** @var array $roles */ /** @var array $roles */
$roles = $config['column-roles']; $roles = $config['column-roles'];
$count = $config['column-count'];
$assigned = 0; $assigned = 0;
// check if data actually contains amount column (foreign amount does not count) // check if data actually contains amount column (foreign amount does not count)

View File

@@ -74,7 +74,7 @@ class ReportControllerTest extends TestCase
]; ];
$uri = route('popup.general') . '?' . http_build_query($arguments); $uri = route('popup.general') . '?' . http_build_query($arguments);
$response = $this->get($uri); $response = $this->get($uri);
$response->assertStatus(500); $response->assertStatus(200);
} }
/** /**

View File

@@ -58,6 +58,8 @@ class MassControllerTest extends TestCase
{ {
$journalRepos = $this->mock(JournalRepositoryInterface::class); $journalRepos = $this->mock(JournalRepositoryInterface::class);
$journalRepos->shouldReceive('firstNull')->once()->andReturn(new TransactionJournal); $journalRepos->shouldReceive('firstNull')->once()->andReturn(new TransactionJournal);
$journalRepos->shouldReceive('getJournalSourceAccounts')->andReturn(new Collection)->once();
$journalRepos->shouldReceive('getJournalDestinationAccounts')->andReturn(new Collection)->once();
$withdrawals = TransactionJournal::where('transaction_type_id', 1)->where('user_id', $this->user()->id)->take(2)->get()->pluck('id')->toArray(); $withdrawals = TransactionJournal::where('transaction_type_id', 1)->where('user_id', $this->user()->id)->take(2)->get()->pluck('id')->toArray();

View File

@@ -845,6 +845,11 @@ class SingleControllerTest extends TestCase
$journalRepos->shouldReceive('getPiggyBankEvents')->andReturn(new Collection); $journalRepos->shouldReceive('getPiggyBankEvents')->andReturn(new Collection);
$journalRepos->shouldReceive('getMetaField')->andReturn(''); $journalRepos->shouldReceive('getMetaField')->andReturn('');
$journalRepos->shouldReceive('getJournalSourceAccounts')->andReturn(new Collection);
$journalRepos->shouldReceive('getJournalDestinationAccounts')->andReturn(new Collection);
$linkRepos->shouldReceive('get')->andReturn(new Collection); $linkRepos->shouldReceive('get')->andReturn(new Collection);
$linkRepos->shouldReceive('getLinks')->andReturn(new Collection); $linkRepos->shouldReceive('getLinks')->andReturn(new Collection);
$attRepos->shouldReceive('saveAttachmentsForModel'); $attRepos->shouldReceive('saveAttachmentsForModel');

View File

@@ -351,6 +351,9 @@ class TransactionControllerTest extends TestCase
$journalRepos->shouldReceive('getPiggyBankEvents')->andReturn(new Collection); $journalRepos->shouldReceive('getPiggyBankEvents')->andReturn(new Collection);
$journalRepos->shouldReceive('firstNull')->andReturn(new TransactionJournal); $journalRepos->shouldReceive('firstNull')->andReturn(new TransactionJournal);
$journalRepos->shouldReceive('getMetaField')->andReturn(''); $journalRepos->shouldReceive('getMetaField')->andReturn('');
$journalRepos->shouldReceive('getJournalSourceAccounts')->andReturn(new Collection);
$journalRepos->shouldReceive('getJournalDestinationAccounts')->andReturn(new Collection);
$this->be($this->user()); $this->be($this->user());
$response = $this->get(route('transactions.show', [1])); $response = $this->get(route('transactions.show', [1]));

View File

@@ -57,7 +57,6 @@ class VersionCheckEventHandlerTest extends TestCase
$repos->shouldReceive('hasRole')->andReturn(true)->once(); $repos->shouldReceive('hasRole')->andReturn(true)->once();
// report on config variables: // report on config variables:
FireflyConfig::shouldReceive('get')->withArgs(['permission_update_check', -1])->once()->andReturn($updateConfig);
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); FireflyConfig::shouldReceive('set')->withArgs(['last_update_check', Mockery::any()])->once()->andReturn($checkConfig);
@@ -91,7 +90,6 @@ class VersionCheckEventHandlerTest extends TestCase
$version = config('firefly.version'); $version = config('firefly.version');
$first = new Release(['id' => '1', 'title' => $version . '.1', 'updated' => '2017-05-01', 'content' => '']); $first = new Release(['id' => '1', 'title' => $version . '.1', 'updated' => '2017-05-01', 'content' => '']);
// report on config variables: // report on config variables:
FireflyConfig::shouldReceive('get')->withArgs(['permission_update_check', -1])->once()->andReturn($updateConfig);
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); FireflyConfig::shouldReceive('set')->withArgs(['last_update_check', Mockery::any()])->once()->andReturn($checkConfig);
@@ -139,7 +137,6 @@ class VersionCheckEventHandlerTest extends TestCase
$repos->shouldReceive('hasRole')->andReturn(true)->once(); $repos->shouldReceive('hasRole')->andReturn(true)->once();
// report on config variables: // report on config variables:
FireflyConfig::shouldReceive('get')->withArgs(['permission_update_check', -1])->once()->andReturn($updateConfig);
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); FireflyConfig::shouldReceive('set')->withArgs(['last_update_check', Mockery::any()])->once()->andReturn($checkConfig);
@@ -164,7 +161,6 @@ class VersionCheckEventHandlerTest extends TestCase
// report on config variables: // report on config variables:
FireflyConfig::shouldReceive('get')->withArgs(['permission_update_check', -1])->once()->andReturn($updateConfig);
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); FireflyConfig::shouldReceive('set')->withArgs(['last_update_check', Mockery::any()])->once()->andReturn($checkConfig);

View File

@@ -79,8 +79,8 @@ class MetaPieChartTest extends TestCase
$accountRepos = $this->mock(AccountRepositoryInterface::class); $accountRepos = $this->mock(AccountRepositoryInterface::class);
$accountRepos->shouldReceive('setUser'); $accountRepos->shouldReceive('setUser');
$accountRepos->shouldReceive('find')->withArgs([1])->andReturn($accounts[1]); $accountRepos->shouldReceive('findNull')->withArgs([1])->andReturn($accounts[1]);
$accountRepos->shouldReceive('find')->withArgs([2])->andReturn($accounts[2]); $accountRepos->shouldReceive('findNull')->withArgs([2])->andReturn($accounts[2]);
$helper = new MetaPieChart(); $helper = new MetaPieChart();
$helper->setUser($this->user()); $helper->setUser($this->user());
@@ -135,8 +135,8 @@ class MetaPieChartTest extends TestCase
$accountRepos = $this->mock(AccountRepositoryInterface::class); $accountRepos = $this->mock(AccountRepositoryInterface::class);
$accountRepos->shouldReceive('setUser'); $accountRepos->shouldReceive('setUser');
$accountRepos->shouldReceive('find')->withArgs([1])->andReturn($accounts[1]); $accountRepos->shouldReceive('findNull')->withArgs([1])->andReturn($accounts[1]);
$accountRepos->shouldReceive('find')->withArgs([2])->andReturn($accounts[2]); $accountRepos->shouldReceive('findNull')->withArgs([2])->andReturn($accounts[2]);
$helper = new MetaPieChart(); $helper = new MetaPieChart();
$helper->setCollectOtherObjects(true); $helper->setCollectOtherObjects(true);
@@ -190,8 +190,8 @@ class MetaPieChartTest extends TestCase
$accountRepos = $this->mock(AccountRepositoryInterface::class); $accountRepos = $this->mock(AccountRepositoryInterface::class);
$accountRepos->shouldReceive('setUser'); $accountRepos->shouldReceive('setUser');
$accountRepos->shouldReceive('find')->withArgs([1])->andReturn($accounts[1]); $accountRepos->shouldReceive('findNull')->withArgs([1])->andReturn($accounts[1]);
$accountRepos->shouldReceive('find')->withArgs([2])->andReturn($accounts[2]); $accountRepos->shouldReceive('findNull')->withArgs([2])->andReturn($accounts[2]);
$helper = new MetaPieChart(); $helper = new MetaPieChart();
$helper->setUser($this->user()); $helper->setUser($this->user());
@@ -245,8 +245,8 @@ class MetaPieChartTest extends TestCase
$accountRepos = $this->mock(AccountRepositoryInterface::class); $accountRepos = $this->mock(AccountRepositoryInterface::class);
$accountRepos->shouldReceive('setUser'); $accountRepos->shouldReceive('setUser');
$accountRepos->shouldReceive('find')->withArgs([1])->andReturn($accounts[1]); $accountRepos->shouldReceive('findNull')->withArgs([1])->andReturn($accounts[1]);
$accountRepos->shouldReceive('find')->withArgs([2])->andReturn($accounts[2]); $accountRepos->shouldReceive('findNull')->withArgs([2])->andReturn($accounts[2]);
$helper = new MetaPieChart(); $helper = new MetaPieChart();
$helper->setCollectOtherObjects(true); $helper->setCollectOtherObjects(true);

View File

@@ -1,75 +0,0 @@
<?php
/**
* RabobankDescriptionTest.php
* Copyright (c) 2018 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\Import\Specifics;
use FireflyIII\Import\Specifics\RabobankDescription;
use Tests\TestCase;
/**
* Class RabobankDescriptionTest
*/
class RabobankDescriptionTest extends TestCase
{
/**
* Default behaviour
* @covers \FireflyIII\Import\Specifics\RabobankDescription
*/
public function testRunBasic(): void
{
$row = ['','','','','','','','','','',''];
$parser = new RabobankDescription;
$result = $parser->run($row);
$this->assertEquals($row, $result);
}
/**
* No opposite name or iban
* @covers \FireflyIII\Import\Specifics\RabobankDescription
*/
public function testRunUseDescription(): void
{
$row = ['','','','','','','','','','','Hello'];
$parser = new RabobankDescription;
$result = $parser->run($row);
$this->assertEquals('Hello', $result[6]);
$this->assertEquals('', $result[10]);
}
/**
* Has opposite name or iban
* @covers \FireflyIII\Import\Specifics\RabobankDescription
*/
public function testRunUseFilledIn(): void
{
$row = ['','','','','','ABC','','','','',''];
$parser = new RabobankDescription;
$result = $parser->run($row);
$this->assertEquals($row, $result);
}
}

View File

@@ -25,6 +25,7 @@ namespace Tests\Unit\TransactionRules\Triggers;
use FireflyIII\Models\TransactionJournal; use FireflyIII\Models\TransactionJournal;
use FireflyIII\Repositories\Journal\JournalRepositoryInterface; use FireflyIII\Repositories\Journal\JournalRepositoryInterface;
use FireflyIII\TransactionRules\Triggers\FromAccountContains; use FireflyIII\TransactionRules\Triggers\FromAccountContains;
use Illuminate\Support\Collection;
use Tests\TestCase; use Tests\TestCase;
/** /**
@@ -38,13 +39,12 @@ class FromAccountContainsTest extends TestCase
public function testTriggered(): void public function testTriggered(): void
{ {
$repository = $this->mock(JournalRepositoryInterface::class); $repository = $this->mock(JournalRepositoryInterface::class);
$count = 0;
while ($count === 0) { /** @var TransactionJournal $journal */
$journal = TransactionJournal::inRandomOrder()->whereNull('deleted_at')->first(); $journal = $this->user()->transactionJournals()->inRandomOrder()->first();
$count = $journal->transactions()->where('amount', '<', 0)->count(); $account = $this->user()->accounts()->inRandomOrder()->first();
$transaction = $journal->transactions()->where('amount', '<', 0)->first(); $collection = new Collection([$account]);
} $repository->shouldReceive('getJournalSourceAccounts')->once()->andReturn($collection);
$account = $transaction->account;
$trigger = FromAccountContains::makeFromStrings($account->name, false); $trigger = FromAccountContains::makeFromStrings($account->name, false);
$result = $trigger->triggered($journal); $result = $trigger->triggered($journal);
@@ -57,7 +57,12 @@ class FromAccountContainsTest extends TestCase
public function testTriggeredNot(): void public function testTriggeredNot(): void
{ {
$repository = $this->mock(JournalRepositoryInterface::class); $repository = $this->mock(JournalRepositoryInterface::class);
$journal = TransactionJournal::inRandomOrder()->whereNull('deleted_at')->first();
/** @var TransactionJournal $journal */
$journal = $this->user()->transactionJournals()->inRandomOrder()->first();
$account = $this->user()->accounts()->inRandomOrder()->first();
$collection = new Collection([$account]);
$repository->shouldReceive('getJournalSourceAccounts')->once()->andReturn($collection);
$trigger = FromAccountContains::makeFromStrings('some name' . random_int(1, 234), false); $trigger = FromAccountContains::makeFromStrings('some name' . random_int(1, 234), false);
$result = $trigger->triggered($journal); $result = $trigger->triggered($journal);
@@ -70,8 +75,8 @@ class FromAccountContainsTest extends TestCase
public function testWillMatchEverythingEmpty(): void public function testWillMatchEverythingEmpty(): void
{ {
$repository = $this->mock(JournalRepositoryInterface::class); $repository = $this->mock(JournalRepositoryInterface::class);
$value = ''; $value = '';
$result = FromAccountContains::willMatchEverything($value); $result = FromAccountContains::willMatchEverything($value);
$this->assertTrue($result); $this->assertTrue($result);
} }
@@ -81,8 +86,8 @@ class FromAccountContainsTest extends TestCase
public function testWillMatchEverythingNotNull(): void public function testWillMatchEverythingNotNull(): void
{ {
$repository = $this->mock(JournalRepositoryInterface::class); $repository = $this->mock(JournalRepositoryInterface::class);
$value = 'x'; $value = 'x';
$result = FromAccountContains::willMatchEverything($value); $result = FromAccountContains::willMatchEverything($value);
$this->assertFalse($result); $this->assertFalse($result);
} }
@@ -92,8 +97,8 @@ class FromAccountContainsTest extends TestCase
public function testWillMatchEverythingNull(): void public function testWillMatchEverythingNull(): void
{ {
$repository = $this->mock(JournalRepositoryInterface::class); $repository = $this->mock(JournalRepositoryInterface::class);
$value = null; $value = null;
$result = FromAccountContains::willMatchEverything($value); $result = FromAccountContains::willMatchEverything($value);
$this->assertTrue($result); $this->assertTrue($result);
} }
} }

View File

@@ -25,6 +25,7 @@ namespace Tests\Unit\TransactionRules\Triggers;
use FireflyIII\Models\TransactionJournal; use FireflyIII\Models\TransactionJournal;
use FireflyIII\Repositories\Journal\JournalRepositoryInterface; use FireflyIII\Repositories\Journal\JournalRepositoryInterface;
use FireflyIII\TransactionRules\Triggers\FromAccountEnds; use FireflyIII\TransactionRules\Triggers\FromAccountEnds;
use Illuminate\Support\Collection;
use Tests\TestCase; use Tests\TestCase;
/** /**
@@ -38,13 +39,11 @@ class FromAccountEndsTest extends TestCase
public function testTriggered(): void public function testTriggered(): void
{ {
$repository = $this->mock(JournalRepositoryInterface::class); $repository = $this->mock(JournalRepositoryInterface::class);
$count = 0; /** @var TransactionJournal $journal */
while ($count === 0) { $journal = $this->user()->transactionJournals()->inRandomOrder()->first();
$journal = TransactionJournal::inRandomOrder()->whereNull('deleted_at')->first(); $account = $this->user()->accounts()->inRandomOrder()->first();
$count = $journal->transactions()->where('amount', '<', 0)->count(); $collection = new Collection([$account]);
$transaction = $journal->transactions()->where('amount', '<', 0)->first(); $repository->shouldReceive('getJournalSourceAccounts')->once()->andReturn($collection);
}
$account = $transaction->account;
$trigger = FromAccountEnds::makeFromStrings(substr($account->name, -3), false); $trigger = FromAccountEnds::makeFromStrings(substr($account->name, -3), false);
$result = $trigger->triggered($journal); $result = $trigger->triggered($journal);
@@ -57,13 +56,12 @@ class FromAccountEndsTest extends TestCase
public function testTriggeredLonger(): void public function testTriggeredLonger(): void
{ {
$repository = $this->mock(JournalRepositoryInterface::class); $repository = $this->mock(JournalRepositoryInterface::class);
$count = 0;
while ($count === 0) { /** @var TransactionJournal $journal */
$journal = TransactionJournal::inRandomOrder()->whereNull('deleted_at')->first(); $journal = $this->user()->transactionJournals()->inRandomOrder()->first();
$count = $journal->transactions()->where('amount', '<', 0)->count(); $account = $this->user()->accounts()->inRandomOrder()->first();
$transaction = $journal->transactions()->where('amount', '<', 0)->first(); $collection = new Collection([$account]);
} $repository->shouldReceive('getJournalSourceAccounts')->once()->andReturn($collection);
$account = $transaction->account;
$trigger = FromAccountEnds::makeFromStrings('bla-bla-bla' . $account->name, false); $trigger = FromAccountEnds::makeFromStrings('bla-bla-bla' . $account->name, false);
$result = $trigger->triggered($journal); $result = $trigger->triggered($journal);
@@ -76,7 +74,12 @@ class FromAccountEndsTest extends TestCase
public function testTriggeredNot(): void public function testTriggeredNot(): void
{ {
$repository = $this->mock(JournalRepositoryInterface::class); $repository = $this->mock(JournalRepositoryInterface::class);
$journal = TransactionJournal::inRandomOrder()->whereNull('deleted_at')->first();
/** @var TransactionJournal $journal */
$journal = $this->user()->transactionJournals()->inRandomOrder()->first();
$account = $this->user()->accounts()->inRandomOrder()->first();
$collection = new Collection([$account]);
$repository->shouldReceive('getJournalSourceAccounts')->once()->andReturn($collection);
$trigger = FromAccountEnds::makeFromStrings('some name' . random_int(1, 234), false); $trigger = FromAccountEnds::makeFromStrings('some name' . random_int(1, 234), false);
$result = $trigger->triggered($journal); $result = $trigger->triggered($journal);

View File

@@ -25,6 +25,7 @@ namespace Tests\Unit\TransactionRules\Triggers;
use FireflyIII\Models\TransactionJournal; use FireflyIII\Models\TransactionJournal;
use FireflyIII\Repositories\Journal\JournalRepositoryInterface; use FireflyIII\Repositories\Journal\JournalRepositoryInterface;
use FireflyIII\TransactionRules\Triggers\FromAccountIs; use FireflyIII\TransactionRules\Triggers\FromAccountIs;
use Illuminate\Support\Collection;
use Tests\TestCase; use Tests\TestCase;
use Log; use Log;
/** /**
@@ -38,20 +39,12 @@ class FromAccountIsTest extends TestCase
public function testTriggered(): void public function testTriggered(): void
{ {
$repository = $this->mock(JournalRepositoryInterface::class); $repository = $this->mock(JournalRepositoryInterface::class);
$loops = 0; // FINAL LOOP METHOD.
do {
/** @var TransactionJournal $journal */
$journal = $this->user()->transactionJournals()->inRandomOrder()->whereNull('deleted_at')->first();
$transaction = $journal->transactions()->where('amount', '<', 0)->first();
$account = null === $transaction ? null : $transaction->account;
$count = $journal->transactions()->count();
Log::debug(sprintf('Loop: %d, transaction count: %d, account is null: %d', $loops, $count, (int)null===$account)); /** @var TransactionJournal $journal */
$journal = $this->user()->transactionJournals()->inRandomOrder()->first();
$loops++; $account = $this->user()->accounts()->inRandomOrder()->first();
$collection = new Collection([$account]);
// do this until: account is not null, journal has two transactions, loops is below 30 $repository->shouldReceive('getJournalSourceAccounts')->once()->andReturn($collection);
} while (!(null !== $account && 2 === $count && $loops < 30));
$trigger = FromAccountIs::makeFromStrings($account->name, false); $trigger = FromAccountIs::makeFromStrings($account->name, false);
@@ -65,7 +58,12 @@ class FromAccountIsTest extends TestCase
public function testTriggeredNot(): void public function testTriggeredNot(): void
{ {
$repository = $this->mock(JournalRepositoryInterface::class); $repository = $this->mock(JournalRepositoryInterface::class);
$journal = TransactionJournal::inRandomOrder()->whereNull('deleted_at')->first();
/** @var TransactionJournal $journal */
$journal = $this->user()->transactionJournals()->inRandomOrder()->first();
$account = $this->user()->accounts()->inRandomOrder()->first();
$collection = new Collection([$account]);
$repository->shouldReceive('getJournalSourceAccounts')->once()->andReturn($collection);
$trigger = FromAccountIs::makeFromStrings('some name' . random_int(1, 234), false); $trigger = FromAccountIs::makeFromStrings('some name' . random_int(1, 234), false);
$result = $trigger->triggered($journal); $result = $trigger->triggered($journal);

View File

@@ -25,6 +25,7 @@ namespace Tests\Unit\TransactionRules\Triggers;
use FireflyIII\Models\TransactionJournal; use FireflyIII\Models\TransactionJournal;
use FireflyIII\Repositories\Journal\JournalRepositoryInterface; use FireflyIII\Repositories\Journal\JournalRepositoryInterface;
use FireflyIII\TransactionRules\Triggers\FromAccountStarts; use FireflyIII\TransactionRules\Triggers\FromAccountStarts;
use Illuminate\Support\Collection;
use Log; use Log;
use Tests\TestCase; use Tests\TestCase;
@@ -48,26 +49,12 @@ class FromAccountStartsTest extends TestCase
public function testTriggered(): void public function testTriggered(): void
{ {
$repository = $this->mock(JournalRepositoryInterface::class); $repository = $this->mock(JournalRepositoryInterface::class);
Log::debug('In testTriggered()');
$loops = 0; // FINAL LOOP METHOD.
do {
/** @var TransactionJournal $journal */
$journal = $this->user()->transactionJournals()->inRandomOrder()->whereNull('deleted_at')->first();
$transaction = $journal->transactions()->where('amount', '<', 0)->first();
$account = null === $transaction ? null : $transaction->account;
$count = $journal->transactions()->count();
$name = $account->name ?? '';
Log::debug(sprintf('Loop: %d, transaction count: %d, account is null: %d, name = "%s"', $loops, $count, (int)null === $account, $name)); /** @var TransactionJournal $journal */
$journal = $this->user()->transactionJournals()->inRandomOrder()->first();
$loops++; $account = $this->user()->accounts()->inRandomOrder()->first();
$collection = new Collection([$account]);
// do this while the following is untrue: $repository->shouldReceive('getJournalSourceAccounts')->once()->andReturn($collection);
// 1) account is not null,
// 2) journal has two transactions
// 3) loops is less than 30
// 4) $name is longer than 3
} while (!(null !== $account && 2 === $count && $loops < 30 && \strlen($name) > 3));
$trigger = FromAccountStarts::makeFromStrings(substr($account->name, 0, -3), false); $trigger = FromAccountStarts::makeFromStrings(substr($account->name, 0, -3), false);
$result = $trigger->triggered($journal); $result = $trigger->triggered($journal);
@@ -80,26 +67,12 @@ class FromAccountStartsTest extends TestCase
public function testTriggeredLonger(): void public function testTriggeredLonger(): void
{ {
$repository = $this->mock(JournalRepositoryInterface::class); $repository = $this->mock(JournalRepositoryInterface::class);
Log::debug('In testTriggeredLonger()');
$loops = 0; // FINAL LOOP METHOD.
do {
/** @var TransactionJournal $journal */
$journal = $this->user()->transactionJournals()->inRandomOrder()->whereNull('deleted_at')->first();
$transaction = $journal->transactions()->where('amount', '<', 0)->first();
$account = null === $transaction ? null : $transaction->account;
$count = $journal->transactions()->count();
$name = $account->name ?? '';
Log::debug(sprintf('Loop: %d, transaction count: %d, account is null: %d, name = "%s"', $loops, $count, (int)null === $account, $name)); /** @var TransactionJournal $journal */
$journal = $this->user()->transactionJournals()->inRandomOrder()->first();
$loops++; $account = $this->user()->accounts()->inRandomOrder()->first();
$collection = new Collection([$account]);
// do this while the following is untrue: $repository->shouldReceive('getJournalSourceAccounts')->once()->andReturn($collection);
// 1) account is not null,
// 2) journal has two transactions
// 3) loops is less than 30
// 4) $name is longer than 3
} while (!(null !== $account && 2 === $count && $loops < 30 && \strlen($name) > 3));
$trigger = FromAccountStarts::makeFromStrings('bla-bla-bla' . $account->name, false); $trigger = FromAccountStarts::makeFromStrings('bla-bla-bla' . $account->name, false);
$result = $trigger->triggered($journal); $result = $trigger->triggered($journal);
@@ -112,7 +85,12 @@ class FromAccountStartsTest extends TestCase
public function testTriggeredNot(): void public function testTriggeredNot(): void
{ {
$repository = $this->mock(JournalRepositoryInterface::class); $repository = $this->mock(JournalRepositoryInterface::class);
$journal = TransactionJournal::inRandomOrder()->whereNull('deleted_at')->first();
/** @var TransactionJournal $journal */
$journal = $this->user()->transactionJournals()->inRandomOrder()->first();
$account = $this->user()->accounts()->inRandomOrder()->first();
$collection = new Collection([$account]);
$repository->shouldReceive('getJournalSourceAccounts')->once()->andReturn($collection);
$trigger = FromAccountStarts::makeFromStrings('some name' . random_int(1, 234), false); $trigger = FromAccountStarts::makeFromStrings('some name' . random_int(1, 234), false);
$result = $trigger->triggered($journal); $result = $trigger->triggered($journal);

View File

@@ -25,6 +25,7 @@ namespace Tests\Unit\TransactionRules\Triggers;
use FireflyIII\Models\TransactionJournal; use FireflyIII\Models\TransactionJournal;
use FireflyIII\Repositories\Journal\JournalRepositoryInterface; use FireflyIII\Repositories\Journal\JournalRepositoryInterface;
use FireflyIII\TransactionRules\Triggers\ToAccountContains; use FireflyIII\TransactionRules\Triggers\ToAccountContains;
use Illuminate\Support\Collection;
use Tests\TestCase; use Tests\TestCase;
/** /**
@@ -39,14 +40,11 @@ class ToAccountContainsTest extends TestCase
{ {
$repository = $this->mock(JournalRepositoryInterface::class); $repository = $this->mock(JournalRepositoryInterface::class);
$count = 0; /** @var TransactionJournal $journal */
do { $journal = $this->user()->transactionJournals()->inRandomOrder()->first();
$journal = TransactionJournal::inRandomOrder()->whereNull('deleted_at')->first(); $account = $this->user()->accounts()->inRandomOrder()->first();
$transaction = $journal->transactions()->where('amount', '>', 0)->first(); $collection = new Collection([$account]);
$transactionCount = $journal->transactions()->count(); $repository->shouldReceive('getJournalDestinationAccounts')->once()->andReturn($collection);
$account = null === $transaction ? null : $transaction->account;
$count++;
} while ($account === null && $count < 30 && $transactionCount !== 2);
$trigger = ToAccountContains::makeFromStrings($account->name, false); $trigger = ToAccountContains::makeFromStrings($account->name, false);
@@ -60,14 +58,12 @@ class ToAccountContainsTest extends TestCase
public function testTriggeredNot(): void public function testTriggeredNot(): void
{ {
$repository = $this->mock(JournalRepositoryInterface::class); $repository = $this->mock(JournalRepositoryInterface::class);
$count = 0;
do { /** @var TransactionJournal $journal */
$journal = TransactionJournal::inRandomOrder()->whereNull('deleted_at')->first(); $journal = $this->user()->transactionJournals()->inRandomOrder()->first();
$transaction = $journal->transactions()->where('amount', '>', 0)->first(); $account = $this->user()->accounts()->inRandomOrder()->first();
$transactionCount = $journal->transactions()->count(); $collection = new Collection([$account]);
$account = null === $transaction ? null : $transaction->account; $repository->shouldReceive('getJournalDestinationAccounts')->once()->andReturn($collection);
$count++;
} while ($account === null && $count < 30 && $transactionCount !== 2);
$trigger = ToAccountContains::makeFromStrings('some name' . random_int(1, 234), false); $trigger = ToAccountContains::makeFromStrings('some name' . random_int(1, 234), false);

View File

@@ -25,6 +25,7 @@ namespace Tests\Unit\TransactionRules\Triggers;
use FireflyIII\Models\TransactionJournal; use FireflyIII\Models\TransactionJournal;
use FireflyIII\Repositories\Journal\JournalRepositoryInterface; use FireflyIII\Repositories\Journal\JournalRepositoryInterface;
use FireflyIII\TransactionRules\Triggers\ToAccountEnds; use FireflyIII\TransactionRules\Triggers\ToAccountEnds;
use Illuminate\Support\Collection;
use Log; use Log;
use Tests\TestCase; use Tests\TestCase;
@@ -39,26 +40,12 @@ class ToAccountEndsTest extends TestCase
public function testTriggered(): void public function testTriggered(): void
{ {
$repository = $this->mock(JournalRepositoryInterface::class); $repository = $this->mock(JournalRepositoryInterface::class);
$loops = 0; // FINAL LOOP METHOD.
do {
/** @var TransactionJournal $journal */
$journal = $this->user()->transactionJournals()->inRandomOrder()->whereNull('deleted_at')->first();
$transaction = $journal->transactions()->where('amount', '>', 0)->first();
$account = null === $transaction ? null : $transaction->account;
$count = $journal->transactions()->count();
$name = $account->name ?? '';
Log::debug(sprintf('Loop: %d, transaction count: %d, account is null: %d, name = "%s"', $loops, $count, (int)null === $account, $name));
$loops++;
// do this while the following is untrue:
// 1) account is not null,
// 2) journal has two transactions
// 3) loops is less than 30
// 4) $name is longer than 3
} while (!(null !== $account && 2 === $count && $loops < 30 && \strlen($name) > 3));
/** @var TransactionJournal $journal */
$journal = $this->user()->transactionJournals()->inRandomOrder()->first();
$account = $this->user()->accounts()->inRandomOrder()->first();
$collection = new Collection([$account]);
$repository->shouldReceive('getJournalDestinationAccounts')->once()->andReturn($collection);
$trigger = ToAccountEnds::makeFromStrings(substr($account->name, -3), false); $trigger = ToAccountEnds::makeFromStrings(substr($account->name, -3), false);
$result = $trigger->triggered($journal); $result = $trigger->triggered($journal);
@@ -71,25 +58,12 @@ class ToAccountEndsTest extends TestCase
public function testTriggeredLonger(): void public function testTriggeredLonger(): void
{ {
$repository = $this->mock(JournalRepositoryInterface::class); $repository = $this->mock(JournalRepositoryInterface::class);
$loops = 0; // FINAL LOOP METHOD.
do {
/** @var TransactionJournal $journal */
$journal = $this->user()->transactionJournals()->inRandomOrder()->whereNull('deleted_at')->first();
$transaction = $journal->transactions()->where('amount', '>', 0)->first();
$account = null === $transaction ? null : $transaction->account;
$count = $journal->transactions()->count();
$name = $account->name ?? '';
Log::debug(sprintf('Loop: %d, transaction count: %d, account is null: %d, name = "%s"', $loops, $count, (int)null === $account, $name)); /** @var TransactionJournal $journal */
$journal = $this->user()->transactionJournals()->inRandomOrder()->first();
$loops++; $account = $this->user()->accounts()->inRandomOrder()->first();
$collection = new Collection([$account]);
// do this while the following is untrue: $repository->shouldReceive('getJournalDestinationAccounts')->once()->andReturn($collection);
// 1) account is not null,
// 2) journal has two transactions
// 3) loops is less than 30
// 4) $name is longer than 3
} while (!(null !== $account && 2 === $count && $loops < 30 && \strlen($name) > 3));
$trigger = ToAccountEnds::makeFromStrings('bla-bla-bla' . $account->name, false); $trigger = ToAccountEnds::makeFromStrings('bla-bla-bla' . $account->name, false);
$result = $trigger->triggered($journal); $result = $trigger->triggered($journal);
@@ -102,25 +76,12 @@ class ToAccountEndsTest extends TestCase
public function testTriggeredNot(): void public function testTriggeredNot(): void
{ {
$repository = $this->mock(JournalRepositoryInterface::class); $repository = $this->mock(JournalRepositoryInterface::class);
$loops = 0; // FINAL LOOP METHOD.
do {
/** @var TransactionJournal $journal */
$journal = $this->user()->transactionJournals()->inRandomOrder()->whereNull('deleted_at')->first();
$transaction = $journal->transactions()->where('amount', '>', 0)->first();
$account = null === $transaction ? null : $transaction->account;
$count = $journal->transactions()->count();
$name = $account->name ?? '';
Log::debug(sprintf('Loop: %d, transaction count: %d, account is null: %d, name = "%s"', $loops, $count, (int)null === $account, $name)); /** @var TransactionJournal $journal */
$journal = $this->user()->transactionJournals()->inRandomOrder()->first();
$loops++; $account = $this->user()->accounts()->inRandomOrder()->first();
$collection = new Collection([$account]);
// do this while the following is untrue: $repository->shouldReceive('getJournalDestinationAccounts')->once()->andReturn($collection);
// 1) account is not null,
// 2) journal has two transactions
// 3) loops is less than 30
// 4) $name is longer than 3
} while (!(null !== $account && 2 === $count && $loops < 30 && \strlen($name) > 3));
$trigger = ToAccountEnds::makeFromStrings((string)random_int(1, 1234), false); $trigger = ToAccountEnds::makeFromStrings((string)random_int(1, 1234), false);
$result = $trigger->triggered($journal); $result = $trigger->triggered($journal);

View File

@@ -25,6 +25,7 @@ namespace Tests\Unit\TransactionRules\Triggers;
use FireflyIII\Models\TransactionJournal; use FireflyIII\Models\TransactionJournal;
use FireflyIII\Repositories\Journal\JournalRepositoryInterface; use FireflyIII\Repositories\Journal\JournalRepositoryInterface;
use FireflyIII\TransactionRules\Triggers\ToAccountIs; use FireflyIII\TransactionRules\Triggers\ToAccountIs;
use Illuminate\Support\Collection;
use Tests\TestCase; use Tests\TestCase;
use Log; use Log;
@@ -39,20 +40,12 @@ class ToAccountIsTest extends TestCase
public function testTriggered(): void public function testTriggered(): void
{ {
$repository = $this->mock(JournalRepositoryInterface::class); $repository = $this->mock(JournalRepositoryInterface::class);
$loops = 0; // FINAL LOOP METHOD.
do {
/** @var TransactionJournal $journal */
$journal = $this->user()->transactionJournals()->inRandomOrder()->whereNull('deleted_at')->first();
$transaction = $journal->transactions()->where('amount', '>', 0)->first();
$account = null === $transaction ? null : $transaction->account;
$count = $journal->transactions()->count();
Log::debug(sprintf('Loop: %d, transaction count: %d, account is null: %d', $loops, $count, (int)null===$account)); /** @var TransactionJournal $journal */
$journal = $this->user()->transactionJournals()->inRandomOrder()->first();
$loops++; $account = $this->user()->accounts()->inRandomOrder()->first();
$collection = new Collection([$account]);
// do this until: account is not null, journal has two transactions, loops is below 30 $repository->shouldReceive('getJournalDestinationAccounts')->once()->andReturn($collection);
} while (!(null !== $account && 2 === $count && $loops < 30));
@@ -67,20 +60,12 @@ class ToAccountIsTest extends TestCase
public function testTriggeredNot(): void public function testTriggeredNot(): void
{ {
$repository = $this->mock(JournalRepositoryInterface::class); $repository = $this->mock(JournalRepositoryInterface::class);
$loops = 0; // FINAL LOOP METHOD.
do {
/** @var TransactionJournal $journal */
$journal = $this->user()->transactionJournals()->inRandomOrder()->whereNull('deleted_at')->first();
$transaction = $journal->transactions()->where('amount', '>', 0)->first();
$account = null === $transaction ? null : $transaction->account;
$count = $journal->transactions()->count();
Log::debug(sprintf('Loop: %d, transaction count: %d, account is null: %d', $loops, $count, (int)null===$account)); /** @var TransactionJournal $journal */
$journal = $this->user()->transactionJournals()->inRandomOrder()->first();
$loops++; $account = $this->user()->accounts()->inRandomOrder()->first();
$collection = new Collection([$account]);
// do this until: account is not null, journal has two transactions, loops is below 30 $repository->shouldReceive('getJournalDestinationAccounts')->once()->andReturn($collection);
} while (!(null !== $account && 2 === $count && $loops < 30));
$trigger = ToAccountIs::makeFromStrings('some name' . random_int(1, 234), false); $trigger = ToAccountIs::makeFromStrings('some name' . random_int(1, 234), false);
$result = $trigger->triggered($journal); $result = $trigger->triggered($journal);

View File

@@ -25,6 +25,7 @@ namespace Tests\Unit\TransactionRules\Triggers;
use FireflyIII\Models\TransactionJournal; use FireflyIII\Models\TransactionJournal;
use FireflyIII\Repositories\Journal\JournalRepositoryInterface; use FireflyIII\Repositories\Journal\JournalRepositoryInterface;
use FireflyIII\TransactionRules\Triggers\ToAccountStarts; use FireflyIII\TransactionRules\Triggers\ToAccountStarts;
use Illuminate\Support\Collection;
use Log; use Log;
use Tests\TestCase; use Tests\TestCase;
@@ -39,22 +40,12 @@ class ToAccountStartsTest extends TestCase
public function testTriggered(): void public function testTriggered(): void
{ {
$repository = $this->mock(JournalRepositoryInterface::class); $repository = $this->mock(JournalRepositoryInterface::class);
Log::debug('Now in testTriggered');
$loops = 0; // FINAL LOOP METHOD. /** @var TransactionJournal $journal */
do { $journal = $this->user()->transactionJournals()->inRandomOrder()->first();
/** @var TransactionJournal $journal */ $account = $this->user()->accounts()->inRandomOrder()->first();
$journal = $this->user()->transactionJournals()->inRandomOrder()->whereNull('deleted_at')->first(); $collection = new Collection([$account]);
$transaction = $journal->transactions()->where('amount', '>', 0)->first(); $repository->shouldReceive('getJournalDestinationAccounts')->once()->andReturn($collection);
$account = null === $transaction ? null : $transaction->account;
$count = $journal->transactions()->count();
Log::debug(sprintf('Loop: %d, transaction count: %d, account is null: %d', $loops, $count, (int)null === $account));
$loops++;
// do this until: account is not null, journal has two transactions, loops is below 30
} while (!(null !== $account && 2 === $count && $loops < 30));
$trigger = ToAccountStarts::makeFromStrings(substr($account->name, 0, -3), false); $trigger = ToAccountStarts::makeFromStrings(substr($account->name, 0, -3), false);
@@ -68,23 +59,12 @@ class ToAccountStartsTest extends TestCase
public function testTriggeredLonger(): void public function testTriggeredLonger(): void
{ {
$repository = $this->mock(JournalRepositoryInterface::class); $repository = $this->mock(JournalRepositoryInterface::class);
Log::debug('Now in testTriggeredLonger');
/** @var TransactionJournal $journal */
$loops = 0; // FINAL LOOP METHOD. $journal = $this->user()->transactionJournals()->inRandomOrder()->first();
do { $account = $this->user()->accounts()->inRandomOrder()->first();
/** @var TransactionJournal $journal */ $collection = new Collection([$account]);
$journal = $this->user()->transactionJournals()->inRandomOrder()->whereNull('deleted_at')->first(); $repository->shouldReceive('getJournalDestinationAccounts')->once()->andReturn($collection);
$transaction = $journal->transactions()->where('amount', '>', 0)->first();
$account = null === $transaction ? null : $transaction->account;
$count = $journal->transactions()->count();
Log::debug(sprintf('Loop: %d, transaction count: %d, account is null: %d', $loops, $count, (int)null === $account));
$loops++;
// do this until: account is not null, journal has two transactions, loops is below 30
} while (!(null !== $account && 2 === $count && $loops < 30));
$trigger = ToAccountStarts::makeFromStrings('bla-bla-bla' . $account->name, false); $trigger = ToAccountStarts::makeFromStrings('bla-bla-bla' . $account->name, false);
$result = $trigger->triggered($journal); $result = $trigger->triggered($journal);
@@ -97,7 +77,12 @@ class ToAccountStartsTest extends TestCase
public function testTriggeredNot(): void public function testTriggeredNot(): void
{ {
$repository = $this->mock(JournalRepositoryInterface::class); $repository = $this->mock(JournalRepositoryInterface::class);
$journal = TransactionJournal::inRandomOrder()->whereNull('deleted_at')->first();
/** @var TransactionJournal $journal */
$journal = $this->user()->transactionJournals()->inRandomOrder()->first();
$account = $this->user()->accounts()->inRandomOrder()->first();
$collection = new Collection([$account]);
$repository->shouldReceive('getJournalDestinationAccounts')->once()->andReturn($collection);
$trigger = ToAccountStarts::makeFromStrings('some name' . random_int(1, 234), false); $trigger = ToAccountStarts::makeFromStrings('some name' . random_int(1, 234), false);
$result = $trigger->triggered($journal); $result = $trigger->triggered($journal);