Small code cleanup

This commit is contained in:
James Cole 2024-01-04 07:44:52 +01:00
parent ff98f3cc3e
commit 8be27a2201
No known key found for this signature in database
GPG Key ID: B49A324B7EAD6D80
17 changed files with 1860 additions and 1874 deletions

View File

@ -226,21 +226,22 @@
},
{
"name": "friendsofphp/php-cs-fixer",
"version": "v3.45.0",
"version": "v3.46.0",
"source": {
"type": "git",
"url": "https://github.com/PHP-CS-Fixer/PHP-CS-Fixer.git",
"reference": "c0daa33cb2533cd73f48dde1c70c2afa3e7953b5"
"reference": "be6831c9af1740470d2a773119b9273f8ac1c3d2"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/PHP-CS-Fixer/PHP-CS-Fixer/zipball/c0daa33cb2533cd73f48dde1c70c2afa3e7953b5",
"reference": "c0daa33cb2533cd73f48dde1c70c2afa3e7953b5",
"url": "https://api.github.com/repos/PHP-CS-Fixer/PHP-CS-Fixer/zipball/be6831c9af1740470d2a773119b9273f8ac1c3d2",
"reference": "be6831c9af1740470d2a773119b9273f8ac1c3d2",
"shasum": ""
},
"require": {
"composer/semver": "^3.4",
"composer/xdebug-handler": "^3.0.3",
"ext-filter": "*",
"ext-json": "*",
"ext-tokenizer": "*",
"php": "^7.4 || ^8.0",
@ -304,7 +305,7 @@
],
"support": {
"issues": "https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/issues",
"source": "https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/tree/v3.45.0"
"source": "https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/tree/v3.46.0"
},
"funding": [
{
@ -312,7 +313,7 @@
"type": "github"
}
],
"time": "2023-12-30T02:07:07+00:00"
"time": "2024-01-03T21:38:46+00:00"
},
{
"name": "psr/container",

View File

@ -59,9 +59,7 @@ class MoveTransactionsRequest extends FormRequest
/**
* Configure the validator instance with special rules for after the basic validation rules.
*
* @param validator $validator
* TODO this is duplicate
* TODO this is duplicate.
*/
public function withValidator(Validator $validator): void
{
@ -78,15 +76,15 @@ class MoveTransactionsRequest extends FormRequest
private function validateMove(Validator $validator): void
{
$data = $validator->getData();
$repository = app(AccountRepositoryInterface::class);
$data = $validator->getData();
$repository = app(AccountRepositoryInterface::class);
$repository->setUser(auth()->user());
$original = $repository->find((int)$data['original_account']);
$destination = $repository->find((int)$data['destination_account']);
$original = $repository->find((int) $data['original_account']);
$destination = $repository->find((int) $data['destination_account']);
// not the same type:
if ($original->accountType->type !== $destination->accountType->type) {
$validator->errors()->add('title', (string)trans('validation.same_account_type'));
$validator->errors()->add('title', (string) trans('validation.same_account_type'));
return;
}
@ -96,7 +94,7 @@ class MoveTransactionsRequest extends FormRequest
// check different scenario's.
if (null === $originalCurrency xor null === $destinationCurrency) {
$validator->errors()->add('title', (string)trans('validation.same_account_currency'));
$validator->errors()->add('title', (string) trans('validation.same_account_currency'));
return;
}
@ -105,7 +103,7 @@ class MoveTransactionsRequest extends FormRequest
return;
}
if ($originalCurrency->code !== $destinationCurrency->code) {
$validator->errors()->add('title', (string)trans('validation.same_account_currency'));
$validator->errors()->add('title', (string) trans('validation.same_account_currency'));
}
}
}

View File

@ -70,9 +70,7 @@ class UpdateRequest extends FormRequest
/**
* Configure the validator instance with special rules for after the basic validation rules.
*
* @param Validator $validator
* TODO duplicate code
* TODO duplicate code.
*/
public function withValidator(Validator $validator): void
{
@ -84,7 +82,7 @@ class UpdateRequest extends FormRequest
$start = new Carbon($data['start']);
$end = new Carbon($data['end']);
if ($end->isBefore($start)) {
$validator->errors()->add('end', (string)trans('validation.date_after'));
$validator->errors()->add('end', (string) trans('validation.date_after'));
}
}
}

View File

@ -65,7 +65,7 @@ class BudgetController extends Controller
$this->opsRepository = app(OperationsRepositoryInterface::class);
$this->currency = app('amount')->getDefaultCurrency();
$userGroup = $this->validateUserGroup($request);
$userGroup = $this->validateUserGroup($request);
if (null !== $userGroup) {
$this->repository->setUserGroup($userGroup);
$this->opsRepository->setUserGroup($userGroup);
@ -77,21 +77,18 @@ class BudgetController extends Controller
}
/**
* @param DateRequest $request
*
* TODO see autocomplete/accountcontroller
*
* @throws FireflyException
* TODO see autocomplete/accountcontroller.
*/
public function dashboard(DateRequest $request): JsonResponse
{
$params = $request->getAll();
$params = $request->getAll();
/** @var Carbon $start */
$start = $params['start'];
$start = $params['start'];
/** @var Carbon $end */
$end = $params['end'];
$end = $params['end'];
// code from FrontpageChartGenerator, but not in separate class
$budgets = $this->repository->getActiveBudgets();
@ -212,14 +209,14 @@ class BudgetController extends Controller
'overspent' => '0',
'native_overspent' => '0',
];
$currentBudgetArray = $block['budgets'][$budgetId];
$currentBudgetArray = $block['budgets'][$budgetId];
// var_dump($return);
/** @var array $journal */
foreach ($currentBudgetArray['transaction_journals'] as $journal) {
// convert the amount to the native currency.
$rate = $converter->getCurrencyRate($this->currencies[$currencyId], $this->currency, $journal['date']);
$convertedAmount = bcmul($journal['amount'], $rate);
$rate = $converter->getCurrencyRate($this->currencies[$currencyId], $this->currency, $journal['date']);
$convertedAmount = bcmul($journal['amount'], $rate);
if ($journal['foreign_currency_id'] === $this->currency->id) {
$convertedAmount = $journal['foreign_amount'];
}
@ -262,7 +259,7 @@ class BudgetController extends Controller
private function processLimit(Budget $budget, BudgetLimit $limit): array
{
Log::debug(sprintf('Created new ExchangeRateConverter in %s', __METHOD__));
$end = clone $limit->end_date;
$end = clone $limit->end_date;
$end->endOfDay();
$spent = $this->opsRepository->listExpenses($limit->start_date, $end, null, new Collection([$budget]));
$limitCurrencyId = $limit->transaction_currency_id;
@ -280,7 +277,7 @@ class BudgetController extends Controller
$filtered[$currencyId] = $entry;
}
}
$result = $this->processExpenses($budget->id, $filtered, $limit->start_date, $end);
$result = $this->processExpenses($budget->id, $filtered, $limit->start_date, $end);
if (1 === count($result)) {
$compare = bccomp($limit->amount, app('steam')->positive($result[$limitCurrencyId]['spent']));
if (1 === $compare) {

View File

@ -91,85 +91,84 @@ class StoreRequest extends FormRequest
return [
// basic fields for group:
'group_title' => 'between:1,1000|nullable',
'error_if_duplicate_hash' => [new IsBoolean()],
'apply_rules' => [new IsBoolean()],
'group_title' => 'between:1,1000|nullable',
'error_if_duplicate_hash' => [new IsBoolean()],
'apply_rules' => [new IsBoolean()],
// transaction rules (in array for splits):
'transactions.*.type' => 'required|in:withdrawal,deposit,transfer,opening-balance,reconciliation',
'transactions.*.date' => ['required', new IsDateOrTime()],
'transactions.*.order' => 'numeric|min:0',
'transactions.*.type' => 'required|in:withdrawal,deposit,transfer,opening-balance,reconciliation',
'transactions.*.date' => ['required', new IsDateOrTime()],
'transactions.*.order' => 'numeric|min:0',
// currency info
'transactions.*.currency_id' => 'numeric|exists:transaction_currencies,id|nullable',
'transactions.*.currency_code' => 'min:3|max:51|exists:transaction_currencies,code|nullable',
'transactions.*.foreign_currency_id' => 'numeric|exists:transaction_currencies,id|nullable',
'transactions.*.foreign_currency_code' => 'min:3|max:51|exists:transaction_currencies,code|nullable',
'transactions.*.currency_id' => 'numeric|exists:transaction_currencies,id|nullable',
'transactions.*.currency_code' => 'min:3|max:51|exists:transaction_currencies,code|nullable',
'transactions.*.foreign_currency_id' => 'numeric|exists:transaction_currencies,id|nullable',
'transactions.*.foreign_currency_code' => 'min:3|max:51|exists:transaction_currencies,code|nullable',
// amount
'transactions.*.amount' => ['required', new IsValidPositiveAmount()],
'transactions.*.foreign_amount' => ['nullable', new IsValidPositiveAmount()],
// description
'transactions.*.description' => 'nullable|between:1,1000',
'transactions.*.description' => 'nullable|between:1,1000',
// source of transaction
'transactions.*.source_id' => ['numeric', 'nullable', new BelongsUserGroup($userGroup)],
'transactions.*.source_name' => 'between:1,255|nullable',
'transactions.*.source_iban' => 'between:1,255|nullable|iban',
'transactions.*.source_number' => 'between:1,255|nullable',
'transactions.*.source_bic' => 'between:1,255|nullable|bic',
'transactions.*.source_id' => ['numeric', 'nullable', new BelongsUserGroup($userGroup)],
'transactions.*.source_name' => 'between:1,255|nullable',
'transactions.*.source_iban' => 'between:1,255|nullable|iban',
'transactions.*.source_number' => 'between:1,255|nullable',
'transactions.*.source_bic' => 'between:1,255|nullable|bic',
// destination of transaction
'transactions.*.destination_id' => ['numeric', 'nullable', new BelongsUserGroup($userGroup)],
'transactions.*.destination_name' => 'between:1,255|nullable',
'transactions.*.destination_iban' => 'between:1,255|nullable|iban',
'transactions.*.destination_number' => 'between:1,255|nullable',
'transactions.*.destination_bic' => 'between:1,255|nullable|bic',
'transactions.*.destination_id' => ['numeric', 'nullable', new BelongsUserGroup($userGroup)],
'transactions.*.destination_name' => 'between:1,255|nullable',
'transactions.*.destination_iban' => 'between:1,255|nullable|iban',
'transactions.*.destination_number' => 'between:1,255|nullable',
'transactions.*.destination_bic' => 'between:1,255|nullable|bic',
// budget, category, bill and piggy
'transactions.*.budget_id' => ['mustExist:budgets,id', new BelongsUserGroup($userGroup)],
'transactions.*.budget_name' => ['between:1,255', 'nullable', new BelongsUserGroup($userGroup)],
'transactions.*.category_id' => ['mustExist:categories,id', new BelongsUserGroup($userGroup), 'nullable'],
'transactions.*.category_name' => 'between:1,255|nullable',
'transactions.*.bill_id' => ['numeric', 'nullable', 'mustExist:bills,id', new BelongsUserGroup($userGroup)],
'transactions.*.bill_name' => ['between:1,255', 'nullable', new BelongsUserGroup($userGroup)],
'transactions.*.piggy_bank_id' => ['numeric', 'nullable', 'mustExist:piggy_banks,id', new BelongsUserGroup($userGroup)],
'transactions.*.piggy_bank_name' => ['between:1,255', 'nullable', new BelongsUserGroup($userGroup)],
'transactions.*.budget_id' => ['mustExist:budgets,id', new BelongsUserGroup($userGroup)],
'transactions.*.budget_name' => ['between:1,255', 'nullable', new BelongsUserGroup($userGroup)],
'transactions.*.category_id' => ['mustExist:categories,id', new BelongsUserGroup($userGroup), 'nullable'],
'transactions.*.category_name' => 'between:1,255|nullable',
'transactions.*.bill_id' => ['numeric', 'nullable', 'mustExist:bills,id', new BelongsUserGroup($userGroup)],
'transactions.*.bill_name' => ['between:1,255', 'nullable', new BelongsUserGroup($userGroup)],
'transactions.*.piggy_bank_id' => ['numeric', 'nullable', 'mustExist:piggy_banks,id', new BelongsUserGroup($userGroup)],
'transactions.*.piggy_bank_name' => ['between:1,255', 'nullable', new BelongsUserGroup($userGroup)],
// other interesting fields
'transactions.*.reconciled' => [new IsBoolean()],
'transactions.*.notes' => 'min:1|max:50000|nullable',
'transactions.*.tags' => 'between:0,1024',
'transactions.*.tags*' => 'between:0,1024',
'transactions.*.reconciled' => [new IsBoolean()],
'transactions.*.notes' => 'min:1|max:50000|nullable',
'transactions.*.tags' => 'between:0,1024',
'transactions.*.tags*' => 'between:0,1024',
// meta info fields
'transactions.*.internal_reference' => 'min:1|max:255|nullable',
'transactions.*.external_id' => 'min:1|max:255|nullable',
'transactions.*.recurrence_id' => 'min:1|max:255|nullable',
'transactions.*.bunq_payment_id' => 'min:1|max:255|nullable',
'transactions.*.external_url' => 'min:1|max:255|nullable|url',
'transactions.*.internal_reference' => 'min:1|max:255|nullable',
'transactions.*.external_id' => 'min:1|max:255|nullable',
'transactions.*.recurrence_id' => 'min:1|max:255|nullable',
'transactions.*.bunq_payment_id' => 'min:1|max:255|nullable',
'transactions.*.external_url' => 'min:1|max:255|nullable|url',
// SEPA fields:
'transactions.*.sepa_cc' => 'min:1|max:255|nullable',
'transactions.*.sepa_ct_op' => 'min:1|max:255|nullable',
'transactions.*.sepa_ct_id' => 'min:1|max:255|nullable',
'transactions.*.sepa_db' => 'min:1|max:255|nullable',
'transactions.*.sepa_country' => 'min:1|max:255|nullable',
'transactions.*.sepa_ep' => 'min:1|max:255|nullable',
'transactions.*.sepa_ci' => 'min:1|max:255|nullable',
'transactions.*.sepa_batch_id' => 'min:1|max:255|nullable',
'transactions.*.sepa_cc' => 'min:1|max:255|nullable',
'transactions.*.sepa_ct_op' => 'min:1|max:255|nullable',
'transactions.*.sepa_ct_id' => 'min:1|max:255|nullable',
'transactions.*.sepa_db' => 'min:1|max:255|nullable',
'transactions.*.sepa_country' => 'min:1|max:255|nullable',
'transactions.*.sepa_ep' => 'min:1|max:255|nullable',
'transactions.*.sepa_ci' => 'min:1|max:255|nullable',
'transactions.*.sepa_batch_id' => 'min:1|max:255|nullable',
// dates
'transactions.*.interest_date' => 'date|nullable',
'transactions.*.book_date' => 'date|nullable',
'transactions.*.process_date' => 'date|nullable',
'transactions.*.due_date' => 'date|nullable',
'transactions.*.payment_date' => 'date|nullable',
'transactions.*.invoice_date' => 'date|nullable',
'transactions.*.interest_date' => 'date|nullable',
'transactions.*.book_date' => 'date|nullable',
'transactions.*.process_date' => 'date|nullable',
'transactions.*.due_date' => 'date|nullable',
'transactions.*.payment_date' => 'date|nullable',
'transactions.*.invoice_date' => 'date|nullable',
// TODO include location and ability to process it.
];
}
@ -226,7 +225,7 @@ class StoreRequest extends FormRequest
*/
foreach ($this->get('transactions') as $transaction) {
$object = new NullArrayObject($transaction);
$result= [
$result = [
'type' => $this->clearString($object['type']),
'date' => $this->dateFromValue($object['date']),
'order' => $this->integerFromValue((string)$object['order']),
@ -304,7 +303,7 @@ class StoreRequest extends FormRequest
'payment_date' => $this->dateFromValue($object['payment_date']),
'invoice_date' => $this->dateFromValue($object['invoice_date']),
];
$result = $this->addFromromTransactionStore($transaction, $result);
$result = $this->addFromromTransactionStore($transaction, $result);
$return[] = $result;
}

View File

@ -97,7 +97,7 @@ class TransactionJournalFactory
{
app('log')->debug('Now in TransactionJournalFactory::create()');
// convert to special object.
$dataObject = new NullArrayObject($data);
$dataObject = new NullArrayObject($data);
app('log')->debug('Start of TransactionJournalFactory::create()');
$collection = new Collection();
@ -164,7 +164,7 @@ class TransactionJournalFactory
protected function storeMeta(TransactionJournal $journal, NullArrayObject $data, string $field): void
{
$set = [
$set = [
'journal' => $journal,
'name' => $field,
'data' => (string) ($data[$field] ?? ''),
@ -198,14 +198,14 @@ class TransactionJournalFactory
$this->errorIfDuplicate($row['import_hash_v2']);
/** Some basic fields */
$type = $this->typeRepository->findTransactionType(null, $row['type']);
$carbon = $row['date'] ?? today(config('app.timezone'));
$order = $row['order'] ?? 0;
$currency = $this->currencyRepository->findCurrency((int) $row['currency_id'], $row['currency_code']);
$foreignCurrency = $this->currencyRepository->findCurrencyNull($row['foreign_currency_id'], $row['foreign_currency_code']);
$bill = $this->billRepository->findBill((int) $row['bill_id'], $row['bill_name']);
$billId = TransactionType::WITHDRAWAL === $type->type && null !== $bill ? $bill->id : null;
$description = (string) $row['description'];
$type = $this->typeRepository->findTransactionType(null, $row['type']);
$carbon = $row['date'] ?? today(config('app.timezone'));
$order = $row['order'] ?? 0;
$currency = $this->currencyRepository->findCurrency((int) $row['currency_id'], $row['currency_code']);
$foreignCurrency = $this->currencyRepository->findCurrencyNull($row['foreign_currency_id'], $row['foreign_currency_code']);
$bill = $this->billRepository->findBill((int) $row['bill_id'], $row['bill_name']);
$billId = TransactionType::WITHDRAWAL === $type->type && null !== $bill ? $bill->id : null;
$description = (string) $row['description'];
// Manipulate basic fields
$carbon->setTimezone(config('app.timezone'));
@ -221,7 +221,7 @@ class TransactionJournalFactory
}
/** create or get source and destination accounts */
$sourceInfo = [
$sourceInfo = [
'id' => $row['source_id'],
'name' => $row['source_name'],
'iban' => $row['source_iban'],
@ -230,7 +230,7 @@ class TransactionJournalFactory
'currency_id' => $currency->id,
];
$destInfo = [
$destInfo = [
'id' => $row['destination_id'],
'name' => $row['destination_name'],
'iban' => $row['destination_iban'],
@ -240,8 +240,8 @@ class TransactionJournalFactory
];
app('log')->debug('Source info:', $sourceInfo);
app('log')->debug('Destination info:', $destInfo);
$sourceAccount = $this->getAccount($type->type, 'source', $sourceInfo);
$destinationAccount = $this->getAccount($type->type, 'destination', $destInfo);
$sourceAccount = $this->getAccount($type->type, 'source', $sourceInfo);
$destinationAccount = $this->getAccount($type->type, 'destination', $destInfo);
app('log')->debug('Done with getAccount(2x)');
// this is the moment for a reconciliation sanity check (again).
@ -249,15 +249,15 @@ class TransactionJournalFactory
[$sourceAccount, $destinationAccount] = $this->reconciliationSanityCheck($sourceAccount, $destinationAccount);
}
$currency = $this->getCurrencyByAccount($type->type, $currency, $sourceAccount, $destinationAccount);
$foreignCurrency = $this->compareCurrencies($currency, $foreignCurrency);
$foreignCurrency = $this->getForeignByAccount($type->type, $foreignCurrency, $destinationAccount);
$description = $this->getDescription($description);
$currency = $this->getCurrencyByAccount($type->type, $currency, $sourceAccount, $destinationAccount);
$foreignCurrency = $this->compareCurrencies($currency, $foreignCurrency);
$foreignCurrency = $this->getForeignByAccount($type->type, $foreignCurrency, $destinationAccount);
$description = $this->getDescription($description);
app('log')->debug(sprintf('Date: %s (%s)', $carbon->toW3cString(), $carbon->getTimezone()->getName()));
/** Create a basic journal. */
$journal = TransactionJournal::create(
$journal = TransactionJournal::create(
[
'user_id' => $this->user->id,
'user_group_id' => $this->user->user_group_id,
@ -274,7 +274,7 @@ class TransactionJournalFactory
app('log')->debug(sprintf('Created new journal #%d: "%s"', $journal->id, $journal->description));
/** Create two transactions. */
$transactionFactory = app(TransactionFactory::class);
$transactionFactory = app(TransactionFactory::class);
$transactionFactory->setUser($this->user);
$transactionFactory->setJournal($journal);
$transactionFactory->setAccount($sourceAccount);
@ -293,7 +293,7 @@ class TransactionJournalFactory
}
/** @var TransactionFactory $transactionFactory */
$transactionFactory = app(TransactionFactory::class);
$transactionFactory = app(TransactionFactory::class);
$transactionFactory->setUser($this->user);
$transactionFactory->setJournal($journal);
$transactionFactory->setAccount($destinationAccount);
@ -311,7 +311,7 @@ class TransactionJournalFactory
throw new FireflyException($e->getMessage(), 0, $e);
}
$journal->completed = true;
$journal->completed = true;
$journal->save();
$this->storeBudget($journal, $row);
$this->storeCategory($journal, $row);
@ -348,7 +348,7 @@ class TransactionJournalFactory
app('log')->error(sprintf('Could not encode dataRow: %s', $e->getMessage()));
$json = microtime();
}
$hash = hash('sha256', $json);
$hash = hash('sha256', $json);
app('log')->debug(sprintf('The hash is: %s', $hash), $dataRow);
return $hash;
@ -369,12 +369,13 @@ class TransactionJournalFactory
/** @var null|TransactionJournalMeta $result */
$result = TransactionJournalMeta::withTrashed()
->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'journal_meta.transaction_journal_id')
->whereNotNull('transaction_journals.id')
->where('transaction_journals.user_id', $this->user->id)
->where('data', json_encode($hash, JSON_THROW_ON_ERROR))
->with(['transactionJournal', 'transactionJournal.transactionGroup'])
->first(['journal_meta.*']);
->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'journal_meta.transaction_journal_id')
->whereNotNull('transaction_journals.id')
->where('transaction_journals.user_id', $this->user->id)
->where('data', json_encode($hash, JSON_THROW_ON_ERROR))
->with(['transactionJournal', 'transactionJournal.transactionGroup'])
->first(['journal_meta.*'])
;
if (null !== $result) {
app('log')->warning(sprintf('Found a duplicate in errorIfDuplicate because hash %s is not unique!', $hash));
$journal = $result->transactionJournal()->withTrashed()->first();
@ -391,18 +392,18 @@ class TransactionJournalFactory
private function validateAccounts(NullArrayObject $data): void
{
app('log')->debug(sprintf('Now in %s', __METHOD__));
$transactionType = $data['type'] ?? 'invalid';
$transactionType = $data['type'] ?? 'invalid';
$this->accountValidator->setUser($this->user);
$this->accountValidator->setTransactionType($transactionType);
// validate source account.
$array = [
$array = [
'id' => null !== $data['source_id'] ? (int) $data['source_id'] : null,
'name' => null !== $data['source_name'] ? (string) $data['source_name'] : null,
'iban' => null !== $data['source_iban'] ? (string) $data['source_iban'] : null,
'number' => null !== $data['source_number'] ? (string) $data['source_number'] : null,
];
$validSource = $this->accountValidator->validateSource($array);
$validSource = $this->accountValidator->validateSource($array);
// do something with result:
if (false === $validSource) {
@ -411,7 +412,7 @@ class TransactionJournalFactory
app('log')->debug('Source seems valid.');
// validate destination account
$array = [
$array = [
'id' => null !== $data['destination_id'] ? (int) $data['destination_id'] : null,
'name' => null !== $data['destination_name'] ? (string) $data['destination_name'] : null,
'iban' => null !== $data['destination_iban'] ? (string) $data['destination_iban'] : null,
@ -479,7 +480,7 @@ class TransactionJournalFactory
// return user's default:
return app('amount')->getDefaultCurrencyByUserGroup($this->user->userGroup);
}
$result = $preference ?? $currency;
$result = $preference ?? $currency;
app('log')->debug(sprintf('Currency is now #%d (%s) because of account #%d (%s)', $result->id, $result->code, $account->id, $account->name));
return $result;

View File

@ -74,8 +74,8 @@ class CreateController extends Controller
app('preferences')->mark();
$title = $newGroup->title ?? $newGroup->transactionJournals->first()->description;
$link = route('transactions.show', [$newGroup->id]);
$title = $newGroup->title ?? $newGroup->transactionJournals->first()->description;
$link = route('transactions.show', [$newGroup->id]);
session()->flash('success', trans('firefly.stored_journal', ['description' => $title]));
session()->flash('success_url', $link);
@ -101,8 +101,8 @@ class CreateController extends Controller
{
app('preferences')->mark();
$sourceId = (int) request()->get('source');
$destinationId = (int) request()->get('destination');
$sourceId = (int) request()->get('source');
$destinationId = (int) request()->get('destination');
/** @var AccountRepositoryInterface $accountRepository */
$accountRepository = app(AccountRepositoryInterface::class);
@ -119,7 +119,7 @@ class CreateController extends Controller
$search = sprintf('?%s', $parts['query'] ?? '');
$previousUrl = str_replace($search, '', $previousUrl);
// not really a fan of this, but meh.
$optionalDateFields = [
$optionalDateFields = [
'interest_date' => $optionalFields['interest_date'],
'book_date' => $optionalFields['book_date'],
'process_date' => $optionalFields['process_date'],
@ -127,10 +127,10 @@ class CreateController extends Controller
'payment_date' => $optionalFields['payment_date'],
'invoice_date' => $optionalFields['invoice_date'],
];
// var_dump($optionalFields);
// exit;
$optionalFields['external_url'] = $optionalFields['external_url'] ?? false;
$optionalFields['location'] = $optionalFields['location'] ?? false;
// var_dump($optionalFields);
// exit;
$optionalFields['external_url'] ??= false;
$optionalFields['location'] ??= false;
session()->put('preFilled', $preFilled);
return view(

View File

@ -72,8 +72,7 @@ class AccountRepository implements AccountRepositoryInterface
/** @var Account $account */
foreach ($accounts as $account) {
$byName = $this->user->accounts()->where('name', $account->name)
->where('id', '!=', $account->id)->first()
;
->where('id', '!=', $account->id)->first();
if (null !== $byName) {
$result->push($account);
$result->push($byName);
@ -82,8 +81,7 @@ class AccountRepository implements AccountRepositoryInterface
}
if (null !== $account->iban) {
$byIban = $this->user->accounts()->where('iban', $account->iban)
->where('id', '!=', $account->id)->first()
;
->where('id', '!=', $account->id)->first();
if (null !== $byIban) {
$result->push($account);
$result->push($byIban);
@ -109,8 +107,7 @@ class AccountRepository implements AccountRepositoryInterface
$q1->where('account_meta.name', '=', 'account_number');
$q1->where('account_meta.data', '=', $json);
}
)
;
);
if (0 !== count($types)) {
$dbQuery->leftJoin('account_types', 'accounts.account_type_id', '=', 'account_types.id');
@ -136,7 +133,7 @@ class AccountRepository implements AccountRepositoryInterface
public function findByName(string $name, array $types): ?Account
{
$query = $this->user->accounts();
$query = $this->user->accounts();
if (0 !== count($types)) {
$query->leftJoin('account_types', 'accounts.account_type_id', '=', 'account_types.id');
@ -203,7 +200,7 @@ class AccountRepository implements AccountRepositoryInterface
public function getAttachments(Account $account): Collection
{
$set = $account->attachments()->get();
$set = $account->attachments()->get();
/** @var \Storage $disk */
$disk = \Storage::disk('upload');
@ -225,7 +222,7 @@ class AccountRepository implements AccountRepositoryInterface
public function getCashAccount(): Account
{
/** @var AccountType $type */
$type = AccountType::where('type', AccountType::CASH)->first();
$type = AccountType::where('type', AccountType::CASH)->first();
/** @var AccountFactory $factory */
$factory = app(AccountFactory::class);
@ -234,7 +231,7 @@ class AccountRepository implements AccountRepositoryInterface
return $factory->findOrCreate('Cash account', $type->type);
}
public function setUser(null|Authenticatable|User $user): void
public function setUser(null | Authenticatable | User $user): void
{
if ($user instanceof User) {
$this->user = $user;
@ -244,10 +241,9 @@ class AccountRepository implements AccountRepositoryInterface
public function getCreditTransactionGroup(Account $account): ?TransactionGroup
{
$journal = TransactionJournal::leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id')
->where('transactions.account_id', $account->id)
->transactionTypes([TransactionType::LIABILITY_CREDIT])
->first(['transaction_journals.*'])
;
->where('transactions.account_id', $account->id)
->transactionTypes([TransactionType::LIABILITY_CREDIT])
->first(['transaction_journals.*']);
return $journal?->transactionGroup;
}
@ -291,11 +287,10 @@ class AccountRepository implements AccountRepositoryInterface
*/
public function getOpeningBalanceAmount(Account $account): ?string
{
$journal = TransactionJournal::leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id')
->where('transactions.account_id', $account->id)
->transactionTypes([TransactionType::OPENING_BALANCE, TransactionType::LIABILITY_CREDIT])
->first(['transaction_journals.*'])
;
$journal = TransactionJournal::leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id')
->where('transactions.account_id', $account->id)
->transactionTypes([TransactionType::OPENING_BALANCE, TransactionType::LIABILITY_CREDIT])
->first(['transaction_journals.*']);
if (null === $journal) {
return null;
}
@ -313,10 +308,9 @@ class AccountRepository implements AccountRepositoryInterface
public function getOpeningBalanceDate(Account $account): ?string
{
return TransactionJournal::leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id')
->where('transactions.account_id', $account->id)
->transactionTypes([TransactionType::OPENING_BALANCE, TransactionType::LIABILITY_CREDIT])
->first(['transaction_journals.*'])?->date->format('Y-m-d H:i:s')
;
->where('transactions.account_id', $account->id)
->transactionTypes([TransactionType::OPENING_BALANCE, TransactionType::LIABILITY_CREDIT])
->first(['transaction_journals.*'])?->date->format('Y-m-d H:i:s');
}
public function getOpeningBalanceGroup(Account $account): ?TransactionGroup
@ -326,13 +320,19 @@ class AccountRepository implements AccountRepositoryInterface
return $journal?->transactionGroup;
}
/**
*
*
* @param Account $account
*
* @return TransactionJournal|null
*/
public function getOpeningBalance(Account $account): ?TransactionJournal
{
return TransactionJournal::leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id')
->where('transactions.account_id', $account->id)
->transactionTypes([TransactionType::OPENING_BALANCE])
->first(['transaction_journals.*'])
;
->where('transactions.account_id', $account->id)
->transactionTypes([TransactionType::OPENING_BALANCE])
->first(['transaction_journals.*']);
}
public function getPiggyBanks(Account $account): Collection
@ -352,19 +352,18 @@ class AccountRepository implements AccountRepositoryInterface
$name = trans('firefly.reconciliation_account_name', ['name' => $account->name, 'currency' => $currency->code]);
/** @var AccountType $type */
$type = AccountType::where('type', AccountType::RECONCILIATION)->first();
$type = AccountType::where('type', AccountType::RECONCILIATION)->first();
/** @var null|Account $current */
$current = $this->user->accounts()->where('account_type_id', $type->id)
->where('name', $name)
->first()
;
$current = $this->user->accounts()->where('account_type_id', $type->id)
->where('name', $name)
->first();
if (null !== $current) {
return $current;
}
$data = [
$data = [
'account_type_id' => null,
'account_type_name' => AccountType::RECONCILIATION,
'active' => true,
@ -374,7 +373,7 @@ class AccountRepository implements AccountRepositoryInterface
];
/** @var AccountFactory $factory */
$factory = app(AccountFactory::class);
$factory = app(AccountFactory::class);
$factory->setUser($account->user);
return $factory->create($data);
@ -382,14 +381,14 @@ class AccountRepository implements AccountRepositoryInterface
public function getAccountCurrency(Account $account): ?TransactionCurrency
{
$type = $account->accountType->type;
$list = config('firefly.valid_currency_account_types');
$type = $account->accountType->type;
$list = config('firefly.valid_currency_account_types');
// return null if not in this list.
if (!in_array($type, $list, true)) {
return null;
}
$currencyId = (int)$this->getMetaValue($account, 'currency_id');
$currencyId = (int) $this->getMetaValue($account, 'currency_id');
if ($currencyId > 0) {
return TransactionCurrency::find($currencyId);
}
@ -411,7 +410,7 @@ class AccountRepository implements AccountRepositoryInterface
return null;
}
if (1 === $result->count()) {
return (string)$result->first()->data;
return (string) $result->first()->data;
}
return null;
@ -432,8 +431,8 @@ class AccountRepository implements AccountRepositoryInterface
$info = $account->transactions()->get(['transaction_currency_id', 'foreign_currency_id'])->toArray();
$currencyIds = [];
foreach ($info as $entry) {
$currencyIds[] = (int)$entry['transaction_currency_id'];
$currencyIds[] = (int)$entry['foreign_currency_id'];
$currencyIds[] = (int) $entry['transaction_currency_id'];
$currencyIds[] = (int) $entry['foreign_currency_id'];
}
$currencyIds = array_unique($currencyIds);
@ -447,7 +446,7 @@ class AccountRepository implements AccountRepositoryInterface
public function maxOrder(string $type): int
{
$sets = [
$sets = [
AccountType::ASSET => [AccountType::DEFAULT, AccountType::ASSET],
AccountType::EXPENSE => [AccountType::EXPENSE, AccountType::BENEFICIARY],
AccountType::REVENUE => [AccountType::REVENUE],
@ -456,14 +455,14 @@ class AccountRepository implements AccountRepositoryInterface
AccountType::MORTGAGE => [AccountType::LOAN, AccountType::DEBT, AccountType::CREDITCARD, AccountType::MORTGAGE],
];
if (array_key_exists(ucfirst($type), $sets)) {
$order = (int)$this->getAccountsByType($sets[ucfirst($type)])->max('order');
$order = (int) $this->getAccountsByType($sets[ucfirst($type)])->max('order');
app('log')->debug(sprintf('Return max order of "%s" set: %d', $type, $order));
return $order;
}
$specials = [AccountType::CASH, AccountType::INITIAL_BALANCE, AccountType::IMPORT, AccountType::RECONCILIATION];
$order = (int)$this->getAccountsByType($specials)->max('order');
$order = (int) $this->getAccountsByType($specials)->max('order');
app('log')->debug(sprintf('Return max order of "%s" set (specials!): %d', $type, $order));
return $order;
@ -512,13 +511,12 @@ class AccountRepository implements AccountRepositoryInterface
{
/** @var null|TransactionJournal $first */
$first = $account->transactions()
->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id')
->orderBy('transaction_journals.date', 'ASC')
->orderBy('transaction_journals.order', 'DESC')
->where('transaction_journals.user_id', $this->user->id)
->orderBy('transaction_journals.id', 'ASC')
->first(['transaction_journals.id'])
;
->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id')
->orderBy('transaction_journals.date', 'ASC')
->orderBy('transaction_journals.order', 'DESC')
->where('transaction_journals.user_id', $this->user->id)
->orderBy('transaction_journals.id', 'ASC')
->first(['transaction_journals.id']);
if (null !== $first) {
return TransactionJournal::find($first->id);
}
@ -544,7 +542,7 @@ class AccountRepository implements AccountRepositoryInterface
continue;
}
if ($index !== (int)$account->order) {
if ($index !== (int) $account->order) {
app('log')->debug(sprintf('Account #%d ("%s"): order should %d be but is %d.', $account->id, $account->name, $index, $account->order));
$account->order = $index;
$account->save();
@ -557,12 +555,11 @@ class AccountRepository implements AccountRepositoryInterface
public function searchAccount(string $query, array $types, int $limit): Collection
{
$dbQuery = $this->user->accounts()
->where('active', true)
->orderBy('accounts.order', 'ASC')
->orderBy('accounts.account_type_id', 'ASC')
->orderBy('accounts.name', 'ASC')
->with(['accountType'])
;
->where('active', true)
->orderBy('accounts.order', 'ASC')
->orderBy('accounts.account_type_id', 'ASC')
->orderBy('accounts.name', 'ASC')
->with(['accountType']);
if ('' !== $query) {
// split query on spaces just in case:
$parts = explode(' ', $query);
@ -582,13 +579,12 @@ class AccountRepository implements AccountRepositoryInterface
public function searchAccountNr(string $query, array $types, int $limit): Collection
{
$dbQuery = $this->user->accounts()->distinct()
->leftJoin('account_meta', 'accounts.id', '=', 'account_meta.account_id')
->where('accounts.active', true)
->orderBy('accounts.order', 'ASC')
->orderBy('accounts.account_type_id', 'ASC')
->orderBy('accounts.name', 'ASC')
->with(['accountType', 'accountMeta'])
;
->leftJoin('account_meta', 'accounts.id', '=', 'account_meta.account_id')
->where('accounts.active', true)
->orderBy('accounts.order', 'ASC')
->orderBy('accounts.account_type_id', 'ASC')
->orderBy('accounts.name', 'ASC')
->with(['accountType', 'accountMeta']);
if ('' !== $query) {
// split query on spaces just in case:
$parts = explode(' ', $query);

View File

@ -273,10 +273,6 @@ class CurrencyRepository implements CurrencyRepositoryInterface
return TransactionCurrency::where('code', $currencyCode)->first();
}
/**
* @param TransactionCurrency $currency
* Enables a currency
*/
public function enable(TransactionCurrency $currency): void
{
$this->userGroup->currencies()->syncWithoutDetaching([$currency->id]);

View File

@ -216,10 +216,9 @@ class Preferences
}
/**
* @param null $default
* TODO remove me.
*
* @return null|preference
* TODO remove me
* @param null $default
*
* @throws FireflyException
*/

View File

@ -65,6 +65,23 @@ trait AppendsLocationData
*/
abstract public function boolean($key = null, $default = false);
public function addFromromTransactionStore(array $information, array $return): array
{
$return['store_location'] = false;
if (true === $information['store_location']) {
$long = array_key_exists('longitude', $information) ? $information['longitude'] : null;
$lat = array_key_exists('latitude', $information) ? $information['latitude'] : null;
if (null !== $long && null !== $lat && $this->validLongitude($long) && $this->validLatitude($lat)) {
$return['store_location'] = true;
$return['longitude'] = $information['longitude'];
$return['latitude'] = $information['latitude'];
$return['zoom_level'] = $information['zoom_level'];
}
}
return $return;
}
/**
* Read the submitted Request data and add new or updated Location data to the array.
*/
@ -78,12 +95,12 @@ trait AppendsLocationData
$data['latitude'] = null;
$data['zoom_level'] = null;
$longitudeKey = $this->getLocationKey($prefix, 'longitude');
$latitudeKey = $this->getLocationKey($prefix, 'latitude');
$zoomLevelKey = $this->getLocationKey($prefix, 'zoom_level');
$isValidPOST = $this->isValidPost($prefix);
$isValidPUT = $this->isValidPUT($prefix);
$isValidEmptyPUT = $this->isValidEmptyPUT($prefix);
$longitudeKey = $this->getLocationKey($prefix, 'longitude');
$latitudeKey = $this->getLocationKey($prefix, 'latitude');
$zoomLevelKey = $this->getLocationKey($prefix, 'zoom_level');
$isValidPOST = $this->isValidPost($prefix);
$isValidPUT = $this->isValidPUT($prefix);
$isValidEmptyPUT = $this->isValidEmptyPUT($prefix);
// for a POST (store), all fields must be present and not NULL.
if ($isValidPOST) {
@ -119,37 +136,17 @@ trait AppendsLocationData
return $data;
}
/**
* @param array $information
* @param array $return
*
* @return array
*/
public function addFromromTransactionStore(array $information, array $return): array
{
$return['store_location'] = false;
if (true === $information['store_location']) {
$long = array_key_exists('longitude', $information) ? $information['longitude'] : null;
$lat = array_key_exists('latitude', $information) ? $information['latitude'] : null;
if (null !== $long && null !== $lat && $this->validLongitude($long) && $this->validLatitude($lat)) {
$return['store_location'] = true;
$return['longitude'] = $information['longitude'];
$return['latitude'] = $information['latitude'];
$return['zoom_level'] = $information['zoom_level'];
}
}
return $return;
}
private function validLongitude(string $longitude): bool
{
$number = (float) $longitude;
return $number >= -180 && $number <= 180;
}
private function validLatitude(string $latitude): bool
{
$number = (float) $latitude;
return $number >= -90 && $number <= 90;
}
@ -247,9 +244,9 @@ trait AppendsLocationData
$zoomLevelKey = $this->getLocationKey($prefix, 'zoom_level');
return (
null === $this->get($longitudeKey)
&& null === $this->get($latitudeKey)
&& null === $this->get($zoomLevelKey))
null === $this->get($longitudeKey)
&& null === $this->get($latitudeKey)
&& null === $this->get($zoomLevelKey))
&& (
'PUT' === $this->method()
|| ('POST' === $this->method() && $this->routeIs('*.update'))

View File

@ -81,8 +81,7 @@ class AmountFormat extends AbstractExtension
/**
* Will format the amount by the currency related to the given account.
*
* @return twigFunction
* TODO remove me when layout v1 is deprecated
* TODO Remove me when v2 hits.
*/
protected function formatAmountByAccount(): TwigFunction
{

View File

@ -346,8 +346,9 @@ class General extends AbstractExtension
}
/**
* @return twigFunction
* TODO remove me when layout v1 is deprecated
* TODO Remove me when v2 hits.
*
* @return TwigFunction
*/
protected function getMetaField(): TwigFunction
{

View File

@ -199,9 +199,12 @@ class AccountTransformer extends AbstractTransformer
}
/**
* @return array
*
* TODO refactor call to get~OpeningBalanceAmount / Date because it is a lot of queries
*
* @param Account $account
* @param string $accountType
*
* @return array
*/
private function getOpeningBalance(Account $account, string $accountType): array
{

View File

@ -53,13 +53,13 @@ class TransactionGroupTransformer extends AbstractTransformer
public function collectMetaData(Collection $objects): void
{
$currencies = [];
$journals = [];
$currencies = [];
$journals = [];
/** @var array $object */
foreach ($objects as $object) {
foreach ($object['sums'] as $sum) {
$id = (int) $sum['currency_id'];
$id = (int) $sum['currency_id'];
$currencies[$id] ??= TransactionCurrency::find($sum['currency_id']);
}
@ -73,7 +73,7 @@ class TransactionGroupTransformer extends AbstractTransformer
$this->default = app('amount')->getDefaultCurrency();
// grab meta for all journals:
$meta = TransactionJournalMeta::whereIn('transaction_journal_id', array_keys($journals))->get();
$meta = TransactionJournalMeta::whereIn('transaction_journal_id', array_keys($journals))->get();
/** @var TransactionJournalMeta $entry */
foreach ($meta as $entry) {
@ -82,7 +82,7 @@ class TransactionGroupTransformer extends AbstractTransformer
}
// grab all notes for all journals:
$notes = Note::whereNoteableType(TransactionJournal::class)->whereIn('noteable_id', array_keys($journals))->get();
$notes = Note::whereNoteableType(TransactionJournal::class)->whereIn('noteable_id', array_keys($journals))->get();
/** @var Note $note */
foreach ($notes as $note) {
@ -91,7 +91,7 @@ class TransactionGroupTransformer extends AbstractTransformer
}
// grab all locations for all journals:
$locations = Location::whereLocatableType(TransactionJournal::class)->whereIn('locatable_id', array_keys($journals))->get();
$locations = Location::whereLocatableType(TransactionJournal::class)->whereIn('locatable_id', array_keys($journals))->get();
/** @var Location $location */
foreach ($locations as $location) {
@ -100,10 +100,11 @@ class TransactionGroupTransformer extends AbstractTransformer
}
// grab all tags for all journals:
$tags = DB::table('tag_transaction_journal')
->leftJoin('tags', 'tags.id', 'tag_transaction_journal.tag_id')
->whereIn('tag_transaction_journal.transaction_journal_id', array_keys($journals))
->get(['tag_transaction_journal.transaction_journal_id', 'tags.tag']);
$tags = DB::table('tag_transaction_journal')
->leftJoin('tags', 'tags.id', 'tag_transaction_journal.tag_id')
->whereIn('tag_transaction_journal.transaction_journal_id', array_keys($journals))
->get(['tag_transaction_journal.transaction_journal_id', 'tags.tag'])
;
/** @var \stdClass $tag */
foreach ($tags as $tag) {
@ -113,7 +114,7 @@ class TransactionGroupTransformer extends AbstractTransformer
// create converter
Log::debug(sprintf('Created new ExchangeRateConverter in %s', __METHOD__));
$this->converter = new ExchangeRateConverter();
$this->converter = new ExchangeRateConverter();
}
public function transform(array $group): array
@ -156,10 +157,10 @@ class TransactionGroupTransformer extends AbstractTransformer
*/
private function transformTransaction(array $transaction): array
{
$transaction = new NullArrayObject($transaction);
$type = $this->stringFromArray($transaction, 'transaction_type_type', TransactionType::WITHDRAWAL);
$journalId = (int) $transaction['transaction_journal_id'];
$meta = new NullArrayObject($this->meta[$journalId] ?? []);
$transaction = new NullArrayObject($transaction);
$type = $this->stringFromArray($transaction, 'transaction_type_type', TransactionType::WITHDRAWAL);
$journalId = (int) $transaction['transaction_journal_id'];
$meta = new NullArrayObject($this->meta[$journalId] ?? []);
/**
* Convert and use amount:
@ -176,9 +177,9 @@ class TransactionGroupTransformer extends AbstractTransformer
}
$this->converter->summarize();
$longitude = null;
$latitude = null;
$zoomLevel = null;
$longitude = null;
$latitude = null;
$zoomLevel = null;
if (array_key_exists($journalId, $this->locations)) {
/** @var Location $location */
$location = $this->locations[$journalId];

View File

@ -62,7 +62,7 @@ trait CurrencyValidation
}
// if foreign amount is present, then the currency must be as well.
if (!(array_key_exists('foreign_currency_id', $transaction) || array_key_exists('foreign_currency_code', $transaction)) && 0 !== bccomp('0', $transaction['foreign_amount'])) {
$validator->errors()->add('transactions.' . $index . '.foreign_amount', (string) trans('validation.require_currency_info'));
$validator->errors()->add('transactions.'.$index.'.foreign_amount', (string) trans('validation.require_currency_info'));
}
// if the currency is present, then the amount must be present as well.
if ((array_key_exists('foreign_currency_id', $transaction) || array_key_exists('foreign_currency_code', $transaction))
@ -71,7 +71,7 @@ trait CurrencyValidation
$transaction
)) {
$validator->errors()->add(
'transactions.' . $index . '.foreign_amount',
'transactions.'.$index.'.foreign_amount',
(string) trans('validation.require_currency_amount')
);
}

File diff suppressed because it is too large Load Diff