firefly-iii/app/Validation/TransactionValidation.php

568 lines
22 KiB
PHP
Raw Normal View History

2018-07-05 11:02:02 -05:00
<?php
/**
* TransactionValidation.php
2020-02-16 06:58:22 -06:00
* Copyright (c) 2019 james@firefly-iii.org
2018-07-05 11:02:02 -05:00
*
* This file is part of Firefly III (https://github.com/firefly-iii).
2018-07-05 11:02:02 -05:00
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
2018-07-05 11:02:02 -05:00
*
* This program is distributed in the hope that it will be useful,
2018-07-05 11:02:02 -05:00
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
2018-07-05 11:02:02 -05:00
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
2018-07-05 11:02:02 -05:00
*/
declare(strict_types=1);
namespace FireflyIII\Validation;
2019-06-02 09:33:25 -05:00
use FireflyIII\Models\Transaction;
use FireflyIII\Models\TransactionGroup;
2019-06-04 13:42:11 -05:00
use FireflyIII\Models\TransactionJournal;
2018-07-05 11:02:02 -05:00
use Illuminate\Validation\Validator;
2019-06-07 23:19:21 -05:00
use Log;
2018-07-05 11:02:02 -05:00
/**
* Trait TransactionValidation
*/
trait TransactionValidation
{
2018-07-05 11:02:02 -05:00
/**
* Validates the given account information. Switches on given transaction type.
*
* @param Validator $validator
*/
public function validateAccountInformation(Validator $validator): void
{
2020-02-22 04:05:16 -06:00
Log::debug('Now in validateAccountInformation()');
$transactions = $this->getTransactionsArray($validator);
$data = $validator->getData();
2019-06-07 23:19:21 -05:00
$transactionType = $data['type'] ?? 'invalid';
2020-02-05 13:37:23 -06:00
/** @var AccountValidator $accountValidator */
$accountValidator = app(AccountValidator::class);
2018-07-05 11:02:02 -05:00
2019-06-07 23:19:21 -05:00
Log::debug(sprintf('Going to loop %d transaction(s)', count($transactions)));
foreach ($transactions as $index => $transaction) {
$transactionType = $transaction['type'] ?? $transactionType;
$accountValidator->setTransactionType($transactionType);
// validate source account.
$sourceId = isset($transaction['source_id']) ? (int)$transaction['source_id'] : null;
$sourceName = $transaction['source_name'] ?? null;
$validSource = $accountValidator->validateSource($sourceId, $sourceName);
2018-07-05 11:02:02 -05:00
// do something with result:
if (false === $validSource) {
$validator->errors()->add(sprintf('transactions.%d.source_id', $index), $accountValidator->sourceError);
$validator->errors()->add(sprintf('transactions.%d.source_name', $index), $accountValidator->sourceError);
2018-07-05 11:02:02 -05:00
return;
2018-07-05 11:02:02 -05:00
}
// validate destination account
$destinationId = isset($transaction['destination_id']) ? (int)$transaction['destination_id'] : null;
$destinationName = $transaction['destination_name'] ?? null;
$validDestination = $accountValidator->validateDestination($destinationId, $destinationName);
// do something with result:
if (false === $validDestination) {
$validator->errors()->add(sprintf('transactions.%d.destination_id', $index), $accountValidator->destError);
$validator->errors()->add(sprintf('transactions.%d.destination_name', $index), $accountValidator->destError);
return;
2018-07-05 11:02:02 -05:00
}
}
}
/**
* Validates the given account information. Switches on given transaction type.
*
* @param Validator $validator
*/
public function validateAccountInformationUpdate(Validator $validator): void
{
2020-02-22 04:05:16 -06:00
Log::debug('Now in validateAccountInformationUpdate()');
$transactions = $this->getTransactionsArray($validator);
2020-02-05 13:37:23 -06:00
/** @var AccountValidator $accountValidator */
$accountValidator = app(AccountValidator::class);
foreach ($transactions as $index => $transaction) {
2019-08-27 00:28:39 -05:00
$originalType = $this->getOriginalType((int)($transaction['transaction_journal_id'] ?? 0));
2019-09-23 09:33:27 -05:00
$originalData = $this->getOriginalData((int)($transaction['transaction_journal_id'] ?? 0));
$transactionType = $transaction['type'] ?? $originalType;
$accountValidator->setTransactionType($transactionType);
2019-12-22 00:50:21 -06:00
// if no account types are given, just skip the check.
if (!isset($transaction['source_id'])
&& !isset($transaction['source_name'])
&& !isset($transaction['destination_id'])
&& !isset($transaction['destination_name'])) {
continue;
}
// validate source account.
$sourceId = isset($transaction['source_id']) ? (int)$transaction['source_id'] : $originalData['source_id'];
$sourceName = $transaction['source_name'] ?? $originalData['source_name'];
$validSource = $accountValidator->validateSource($sourceId, $sourceName);
// do something with result:
if (false === $validSource) {
$validator->errors()->add(sprintf('transactions.%d.source_id', $index), $accountValidator->sourceError);
$validator->errors()->add(sprintf('transactions.%d.source_name', $index), $accountValidator->sourceError);
continue;
}
// validate destination account
$destinationId = isset($transaction['destination_id']) ? (int)$transaction['destination_id'] : $originalData['destination_id'];
$destinationName = $transaction['destination_name'] ?? $originalData['destination_name'];
$validDestination = $accountValidator->validateDestination($destinationId, $destinationName);
// do something with result:
if (false === $validDestination) {
$validator->errors()->add(sprintf('transactions.%d.destination_id', $index), $accountValidator->destError);
$validator->errors()->add(sprintf('transactions.%d.destination_name', $index), $accountValidator->destError);
continue;
}
}
}
2018-07-05 11:02:02 -05:00
/**
* Adds an error to the "description" field when the user has submitted no descriptions and no
* journal description.
*
* @param Validator $validator
*/
public function validateDescriptions(Validator $validator): void
{
2020-02-22 04:05:16 -06:00
Log::debug('Now in validateDescriptions()');
$transactions = $this->getTransactionsArray($validator);
$validDescriptions = 0;
2020-02-22 04:05:16 -06:00
foreach ($transactions as $transaction) {
2019-01-01 11:03:24 -06:00
if ('' !== (string)($transaction['description'] ?? null)) {
2018-07-05 11:02:02 -05:00
$validDescriptions++;
}
}
// no valid descriptions?
if (0 === $validDescriptions) {
$validator->errors()->add(
'transactions.0.description', (string)trans('validation.filled', ['attribute' => (string)trans('validation.attributes.description')])
);
2018-07-05 11:02:02 -05:00
}
}
/**
* If the transactions contain foreign amounts, there must also be foreign currency information.
*
* @param Validator $validator
*/
public function validateForeignCurrencyInformation(Validator $validator): void
{
2020-02-22 04:05:16 -06:00
Log::debug('Now in validateForeignCurrencyInformation()');
$transactions = $this->getTransactionsArray($validator);
2020-02-05 13:37:23 -06:00
2018-07-05 11:02:02 -05:00
foreach ($transactions as $index => $transaction) {
2019-04-16 09:20:46 -05:00
// if foreign amount is present, then the currency must be as well.
if (isset($transaction['foreign_amount']) && !(isset($transaction['foreign_currency_id']) || isset($transaction['foreign_currency_code']))
&& 0 !== bccomp('0', $transaction['foreign_amount'])
) {
2018-07-05 11:02:02 -05:00
$validator->errors()->add(
'transactions.' . $index . '.foreign_amount',
2018-07-15 02:38:49 -05:00
(string)trans('validation.require_currency_info')
2018-07-05 11:02:02 -05:00
);
}
2019-04-16 09:20:46 -05:00
// if the currency is present, then the amount must be present as well.
if ((isset($transaction['foreign_currency_id']) || isset($transaction['foreign_currency_code'])) && !isset($transaction['foreign_amount'])) {
$validator->errors()->add(
'transactions.' . $index . '.foreign_amount',
(string)trans('validation.require_currency_amount')
);
}
2018-07-05 11:02:02 -05:00
}
}
/**
* @param Validator $validator
*/
public function validateGroupDescription(Validator $validator): void
2018-07-05 11:02:02 -05:00
{
2020-02-22 04:05:16 -06:00
Log::debug('Now in validateGroupDescription()');
$data = $validator->getData();
$transactions = $this->getTransactionsArray($validator);
2020-02-05 13:37:23 -06:00
$groupTitle = $data['group_title'] ?? '';
if ('' === $groupTitle && count($transactions) > 1) {
$validator->errors()->add('group_title', (string)trans('validation.group_title_mandatory'));
2018-07-05 11:02:02 -05:00
}
}
/**
* Adds an error to the validator when there are no transactions in the array of data.
*
* @param Validator $validator
*/
public function validateOneRecurrenceTransaction(Validator $validator): void
2018-07-05 11:02:02 -05:00
{
2020-02-22 04:05:16 -06:00
Log::debug('Now in validateOneRecurrenceTransaction()');
$transactions = $this->getTransactionsArray($validator);
2020-02-05 13:37:23 -06:00
2018-07-05 11:02:02 -05:00
// need at least one transaction
if (0 === count($transactions)) {
$validator->errors()->add('transactions', (string)trans('validation.at_least_one_transaction'));
2018-07-05 11:02:02 -05:00
}
}
2019-06-09 01:26:23 -05:00
/**
* Adds an error to the validator when there are no transactions in the array of data.
*
* @param Validator $validator
*/
public function validateOneRecurrenceTransactionUpdate(Validator $validator): void
2019-06-09 01:26:23 -05:00
{
2020-02-22 04:05:16 -06:00
Log::debug('Now in validateOneRecurrenceTransactionUpdate()');
$transactions = $this->getTransactionsArray($validator);
2019-06-09 01:26:23 -05:00
// need at least one transaction
if (0 === count($transactions)) {
$validator->errors()->add('transactions', (string)trans('validation.at_least_one_transaction'));
2019-06-09 01:26:23 -05:00
}
}
/**
* Adds an error to the validator when there are no transactions in the array of data.
*
* @param Validator $validator
*/
public function validateOneTransaction(Validator $validator): void
{
2020-02-22 04:05:16 -06:00
Log::debug('Now in validateOneTransaction()');
$transactions = $this->getTransactionsArray($validator);
// need at least one transaction
if (0 === count($transactions)) {
$validator->errors()->add('transactions.0.description', (string)trans('validation.at_least_one_transaction'));
2020-02-22 04:05:16 -06:00
Log::debug('Added error: at_least_one_transaction.');
return;
}
2020-02-22 04:05:16 -06:00
Log::debug('Added NO errors.');
}
2018-07-05 11:02:02 -05:00
/**
* All types of splits must be equal.
2018-07-05 11:02:02 -05:00
*
* @param Validator $validator
*/
public function validateTransactionTypes(Validator $validator): void
2018-07-05 11:02:02 -05:00
{
2020-02-22 04:05:16 -06:00
Log::debug('Now in validateTransactionTypes()');
$transactions = $this->getTransactionsArray($validator);
2020-02-05 13:37:23 -06:00
$types = [];
2018-07-05 11:02:02 -05:00
foreach ($transactions as $index => $transaction) {
$types[] = $transaction['type'] ?? 'invalid';
2018-07-05 11:02:02 -05:00
}
$unique = array_unique($types);
if (count($unique) > 1) {
$validator->errors()->add('transactions.0.type', (string)trans('validation.transaction_types_equal'));
2018-07-05 11:02:02 -05:00
return;
2018-07-05 11:02:02 -05:00
}
$first = $unique[0] ?? 'invalid';
if ('invalid' === $first) {
$validator->errors()->add('transactions.0.type', (string)trans('validation.invalid_transaction_type'));
2019-06-04 13:42:11 -05:00
2018-07-05 11:02:02 -05:00
}
}
/**
* All types of splits must be equal.
*
* @param Validator $validator
*/
public function validateTransactionTypesForUpdate(Validator $validator): void
{
2020-02-22 04:05:16 -06:00
Log::debug('Now in validateTransactionTypesForUpdate()');
$transactions = $this->getTransactionsArray($validator);
$types = [];
foreach ($transactions as $index => $transaction) {
2019-06-04 13:42:11 -05:00
$originalType = $this->getOriginalType((int)($transaction['transaction_journal_id'] ?? 0));
// if type is not set, fall back to the type of the journal, if one is given.
$types[] = $transaction['type'] ?? $originalType;
}
$unique = array_unique($types);
if (count($unique) > 1) {
$validator->errors()->add('transactions.0.type', (string)trans('validation.transaction_types_equal'));
return;
}
}
2019-06-04 13:42:11 -05:00
/**
* @param array $array
2019-06-04 13:42:11 -05:00
*
* @return bool
2019-06-04 13:42:11 -05:00
*/
private function arrayEqual(array $array): bool
2019-06-04 13:42:11 -05:00
{
return 1 === count(array_unique($array));
}
2019-06-04 13:42:11 -05:00
/**
* @param int $journalId
*
* @return array
*/
private function getOriginalData(int $journalId): array
{
$return = [
'source_id' => 0,
'source_name' => '',
'destination_id' => 0,
'destination_name' => '',
];
if (0 === $journalId) {
return $return;
}
/** @var Transaction $source */
$source = Transaction::where('transaction_journal_id', $journalId)->where('amount', '<', 0)->with(['account'])->first();
if (null !== $source) {
$return['source_id'] = $source->account_id;
$return['source_name'] = $source->account->name;
}
/** @var Transaction $destination */
$destination = Transaction::where('transaction_journal_id', $journalId)->where('amount', '>', 0)->with(['account'])->first();
if (null !== $source) {
$return['destination_id'] = $destination->account_id;
$return['destination_name'] = $destination->account->name;
}
2019-06-04 13:42:11 -05:00
return $return;
}
2019-06-04 13:42:11 -05:00
/**
* @param int $journalId
*
* @return string
*/
private function getOriginalType(int $journalId): string
{
if (0 === $journalId) {
return 'invalid';
2019-06-04 13:42:11 -05:00
}
/** @var TransactionJournal $journal */
$journal = TransactionJournal::with(['transactionType'])->find($journalId);
if (null !== $journal) {
return strtolower($journal->transactionType->type);
}
return 'invalid';
2019-06-04 13:42:11 -05:00
}
/**
* @param Validator $validator
*
* @return array
*/
private function getTransactionsArray(Validator $validator): array
{
$data = $validator->getData();
$transactions = $data['transactions'] ?? [];
if (!is_countable($transactions)) {
Log::error(sprintf('Transactions array is not countable, because its a %s', gettype($transactions)));
return [];
}
// a superfluous check but you never know.
if (!is_array($transactions)) {
Log::error(sprintf('Transactions array is not an array, because its a %s', gettype($transactions)));
return [];
}
return $transactions;
}
2019-04-06 04:08:46 -05:00
/**
* @param Validator $validator
*/
private function validateEqualAccounts(Validator $validator): void
{
2020-02-22 04:05:16 -06:00
Log::debug('Now in validateEqualAccounts()');
2019-04-06 04:08:46 -05:00
$data = $validator->getData();
$transactions = $data['transactions'] ?? [];
2020-02-05 13:37:23 -06:00
2020-02-14 06:14:06 -06:00
if (!is_countable($transactions)) {
2020-02-05 13:37:23 -06:00
$validator->errors()->add(
'transactions.0.description', (string)trans('validation.filled', ['attribute' => (string)trans('validation.attributes.description')])
);
return;
}
2019-04-06 04:08:46 -05:00
// needs to be split
if (count($transactions) < 2) {
return;
}
$type = $transactions[0]['type'] ?? 'withdrawal';
$sources = [];
$dests = [];
foreach ($transactions as $transaction) {
$sources[] = sprintf('%d-%s', $transaction['source_id'] ?? 0, $transaction['source_name'] ?? '');
$dests[] = sprintf('%d-%s', $transaction['destination_id'] ?? 0, $transaction['destination_name'] ?? '');
}
$sources = array_unique($sources);
$dests = array_unique($dests);
switch ($type) {
case 'withdrawal':
if (count($sources) > 1) {
$validator->errors()->add('transactions.0.source_id', (string)trans('validation.all_accounts_equal'));
}
break;
case 'deposit':
if (count($dests) > 1) {
$validator->errors()->add('transactions.0.destination_id', (string)trans('validation.all_accounts_equal'));
}
break;
case'transfer':
if (count($sources) > 1 || count($dests) > 1) {
$validator->errors()->add('transactions.0.source_id', (string)trans('validation.all_accounts_equal'));
$validator->errors()->add('transactions.0.destination_id', (string)trans('validation.all_accounts_equal'));
}
break;
}
}
/**
* @param Validator $validator
2019-04-06 04:08:46 -05:00
* @param TransactionGroup $transactionGroup
*/
private function validateEqualAccountsForUpdate(Validator $validator, TransactionGroup $transactionGroup): void
{
2020-02-22 04:05:16 -06:00
Log::debug('Now in validateEqualAccountsForUpdate()');
2019-04-06 04:08:46 -05:00
$data = $validator->getData();
$transactions = $data['transactions'] ?? [];
2020-02-05 13:37:23 -06:00
2020-02-14 06:14:06 -06:00
if (!is_countable($transactions)) {
2020-02-05 13:37:23 -06:00
$validator->errors()->add(
'transactions.0.description', (string)trans('validation.filled', ['attribute' => (string)trans('validation.attributes.description')])
);
return;
}
2019-04-06 04:08:46 -05:00
// needs to be split
if (count($transactions) < 2) {
return;
}
2019-06-02 09:33:25 -05:00
$type = $transactions[0]['type'] ?? strtolower($transactionGroup->transactionJournals()->first()->transactionType->type);
// compare source ID's, destination ID's, source names and destination names.
// I think I can get away with one combination being equal, as long as the rest
// of the code picks up on this as well.
// either way all fields must be blank or all equal
// but if ID's are equal don't bother with the names.
$fields = ['source_id', 'destination_id', 'source_name', 'destination_name'];
$comparison = [];
foreach ($fields as $field) {
$comparison[$field] = [];
/** @var array $transaction */
foreach ($transactions as $transaction) {
// source or destination may be omitted. If this is the case, use the original source / destination name + ID.
$originalData = $this->getOriginalData((int)($transaction['transaction_journal_id'] ?? 0));
// get field.
$comparison[$field][] = $transaction[$field] ?? $originalData[$field];
}
2019-04-06 04:08:46 -05:00
}
2019-06-02 09:33:25 -05:00
// TODO not the best way to loop this.
2019-04-06 04:08:46 -05:00
switch ($type) {
case 'withdrawal':
2019-06-02 09:33:25 -05:00
if ($this->arrayEqual($comparison['source_id'])) {
// source ID's are equal, return void.
return;
}
if ($this->arrayEqual($comparison['source_name'])) {
// source names are equal, return void.
return;
2019-04-06 04:08:46 -05:00
}
2019-06-02 09:33:25 -05:00
// add error:
$validator->errors()->add('transactions.0.source_id', (string)trans('validation.all_accounts_equal'));
2019-04-06 04:08:46 -05:00
break;
case 'deposit':
2019-06-02 09:33:25 -05:00
if ($this->arrayEqual($comparison['destination_id'])) {
// destination ID's are equal, return void.
return;
}
if ($this->arrayEqual($comparison['destination_name'])) {
// destination names are equal, return void.
return;
2019-04-06 04:08:46 -05:00
}
2019-06-02 09:33:25 -05:00
// add error:
$validator->errors()->add('transactions.0.destination_id', (string)trans('validation.all_accounts_equal'));
2019-04-06 04:08:46 -05:00
break;
2019-06-02 09:33:25 -05:00
case 'transfer':
if ($this->arrayEqual($comparison['source_id'])) {
// source ID's are equal, return void.
return;
}
if ($this->arrayEqual($comparison['source_name'])) {
// source names are equal, return void.
return;
}
if ($this->arrayEqual($comparison['destination_id'])) {
// destination ID's are equal, return void.
return;
}
if ($this->arrayEqual($comparison['destination_name'])) {
// destination names are equal, return void.
return;
2019-04-06 04:08:46 -05:00
}
2019-06-02 09:33:25 -05:00
// add error:
$validator->errors()->add('transactions.0.source_id', (string)trans('validation.all_accounts_equal'));
$validator->errors()->add('transactions.0.destination_id', (string)trans('validation.all_accounts_equal'));
2019-04-06 04:08:46 -05:00
break;
}
}
/**
* @param Validator $validator
* @param TransactionGroup $transactionGroup
*/
private function validateJournalIds(Validator $validator, TransactionGroup $transactionGroup): void
{
2020-02-22 04:05:16 -06:00
Log::debug('Now in validateJournalIds()');
$data = $validator->getData();
$transactions = $data['transactions'] ?? [];
2020-02-05 13:37:23 -06:00
2020-02-14 06:14:06 -06:00
if (!is_countable($transactions)) {
2020-02-05 13:37:23 -06:00
$validator->errors()->add(
'transactions.0.description', (string)trans('validation.filled', ['attribute' => (string)trans('validation.attributes.description')])
);
return;
}
if (count($transactions) < 2) {
return;
}
foreach ($transactions as $index => $transaction) {
2019-04-16 09:20:46 -05:00
$journalId = $transaction['transaction_journal_id'] ?? null;
$journalId = null === $journalId ? null : (int)$journalId;
$count = $transactionGroup->transactionJournals()->where('id', $journalId)->count();
2019-04-16 09:20:46 -05:00
if (null === $journalId || (null !== $journalId && 0 !== $journalId && 0 === $count)) {
$validator->errors()->add(sprintf('transactions.%d.source_name', $index), (string)trans('validation.need_id_in_edit'));
}
}
}
}