Clean up various code.

This commit is contained in:
James Cole 2023-12-22 17:28:42 +01:00
parent e8890ada7c
commit 067d160c13
No known key found for this signature in database
GPG Key ID: B49A324B7EAD6D80
33 changed files with 331 additions and 699 deletions

View File

@ -470,16 +470,16 @@
}, },
{ {
"name": "sebastian/diff", "name": "sebastian/diff",
"version": "5.0.3", "version": "5.1.0",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/sebastianbergmann/diff.git", "url": "https://github.com/sebastianbergmann/diff.git",
"reference": "912dc2fbe3e3c1e7873313cc801b100b6c68c87b" "reference": "fbf413a49e54f6b9b17e12d900ac7f6101591b7f"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/sebastianbergmann/diff/zipball/912dc2fbe3e3c1e7873313cc801b100b6c68c87b", "url": "https://api.github.com/repos/sebastianbergmann/diff/zipball/fbf413a49e54f6b9b17e12d900ac7f6101591b7f",
"reference": "912dc2fbe3e3c1e7873313cc801b100b6c68c87b", "reference": "fbf413a49e54f6b9b17e12d900ac7f6101591b7f",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
@ -492,7 +492,7 @@
"type": "library", "type": "library",
"extra": { "extra": {
"branch-alias": { "branch-alias": {
"dev-main": "5.0-dev" "dev-main": "5.1-dev"
} }
}, },
"autoload": { "autoload": {
@ -525,7 +525,7 @@
"support": { "support": {
"issues": "https://github.com/sebastianbergmann/diff/issues", "issues": "https://github.com/sebastianbergmann/diff/issues",
"security": "https://github.com/sebastianbergmann/diff/security/policy", "security": "https://github.com/sebastianbergmann/diff/security/policy",
"source": "https://github.com/sebastianbergmann/diff/tree/5.0.3" "source": "https://github.com/sebastianbergmann/diff/tree/5.1.0"
}, },
"funding": [ "funding": [
{ {
@ -533,7 +533,7 @@
"type": "github" "type": "github"
} }
], ],
"time": "2023-05-01T07:48:21+00:00" "time": "2023-12-22T10:55:06+00:00"
}, },
{ {
"name": "symfony/console", "name": "symfony/console",

View File

@ -70,8 +70,8 @@
</rule> </rule>
<rule ref="rulesets/codesize.xml/ExcessiveMethodLength"> <rule ref="rulesets/codesize.xml/ExcessiveMethodLength">
<properties> <properties>
<!-- TODO we want to be at a value of 40. But we start high, and drop the bar slowly. --> <!-- 75 seems like a nice number. Shorter isn't always feasible and there are a few exceptions already -->
<property name="minimum" value="100"/> <property name="minimum" value="75"/>
<property name="ignore-whitespace" value="true"/> <property name="ignore-whitespace" value="true"/>
</properties> </properties>
</rule> </rule>

View File

@ -146,13 +146,7 @@ class BasicController extends Controller
// collect income of user using the new group collector. // collect income of user using the new group collector.
/** @var GroupCollectorInterface $collector */ /** @var GroupCollectorInterface $collector */
$collector = app(GroupCollectorInterface::class); $collector = app(GroupCollectorInterface::class);
$collector $collector->setRange($start, $end)->setPage($this->parameters->get('page'))->setTypes([TransactionType::DEPOSIT]);
->setRange($start, $end)
// set page to retrieve
->setPage($this->parameters->get('page'))
// set types of transactions to return.
->setTypes([TransactionType::DEPOSIT])
;
$set = $collector->getExtractedJournals(); $set = $collector->getExtractedJournals();
@ -171,13 +165,7 @@ class BasicController extends Controller
// collect expenses of user using the new group collector. // collect expenses of user using the new group collector.
/** @var GroupCollectorInterface $collector */ /** @var GroupCollectorInterface $collector */
$collector = app(GroupCollectorInterface::class); $collector = app(GroupCollectorInterface::class);
$collector $collector->setRange($start, $end)->setPage($this->parameters->get('page'))->setTypes([TransactionType::WITHDRAWAL]);
->setRange($start, $end)
// set page to retrieve
->setPage($this->parameters->get('page'))
// set types of transactions to return.
->setTypes([TransactionType::WITHDRAWAL])
;
$set = $collector->getExtractedJournals(); $set = $collector->getExtractedJournals();
/** @var array $transactionJournal */ /** @var array $transactionJournal */

View File

@ -62,75 +62,15 @@ class UpdateRequest extends FormRequest
public function getAll(): array public function getAll(): array
{ {
app('log')->debug(sprintf('Now in %s', __METHOD__)); app('log')->debug(sprintf('Now in %s', __METHOD__));
$this->integerFields = [ $this->integerFields = ['order', 'currency_id', 'foreign_currency_id', 'transaction_journal_id', 'source_id', 'destination_id', 'budget_id', 'category_id', 'bill_id', 'recurrence_id'];
'order', $this->dateFields = ['date', 'interest_date', 'book_date', 'process_date', 'due_date', 'payment_date', 'invoice_date'];
'currency_id', $this->textareaFields = ['notes'];
'foreign_currency_id', // not really floats, for validation.
'transaction_journal_id', $this->floatFields = ['amount', 'foreign_amount'];
'source_id', $this->stringFields = ['type', 'currency_code', 'foreign_currency_code', 'description', 'source_name', 'source_iban', 'source_number', 'source_bic', 'destination_name', 'destination_iban', 'destination_number', 'destination_bic', 'budget_name', 'category_name', 'bill_name', 'internal_reference', 'external_id', 'bunq_payment_id', 'sepa_cc', 'sepa_ct_op', 'sepa_ct_id', 'sepa_db', 'sepa_country', 'sepa_ep', 'sepa_ci', 'sepa_batch_id', 'external_url'];
'destination_id', $this->booleanFields = ['reconciled'];
'budget_id', $this->arrayFields = ['tags'];
'category_id', $data = [];
'bill_id',
'recurrence_id',
];
$this->dateFields = [
'date',
'interest_date',
'book_date',
'process_date',
'due_date',
'payment_date',
'invoice_date',
];
$this->textareaFields = [
'notes',
];
$this->floatFields = [ // not really floats, for validation.
'amount',
'foreign_amount',
];
$this->stringFields = [
'type',
'currency_code',
'foreign_currency_code',
'description',
'source_name',
'source_iban',
'source_number',
'source_bic',
'destination_name',
'destination_iban',
'destination_number',
'destination_bic',
'budget_name',
'category_name',
'bill_name',
'internal_reference',
'external_id',
'bunq_payment_id',
'sepa_cc',
'sepa_ct_op',
'sepa_ct_id',
'sepa_db',
'sepa_country',
'sepa_ep',
'sepa_ci',
'sepa_batch_id',
'external_url',
];
$this->booleanFields = [
'reconciled',
];
$this->arrayFields = [
'tags',
];
$data = [];
if ($this->has('transactions')) { if ($this->has('transactions')) {
$data['transactions'] = $this->getTransactionData(); $data['transactions'] = $this->getTransactionData();
} }
@ -308,7 +248,7 @@ class UpdateRequest extends FormRequest
{ {
foreach ($this->integerFields as $fieldName) { foreach ($this->integerFields as $fieldName) {
if (array_key_exists($fieldName, $transaction)) { if (array_key_exists($fieldName, $transaction)) {
$current[$fieldName] = $this->integerFromValue((string)$transaction[$fieldName]); $current[$fieldName] = $this->integerFromValue((string) $transaction[$fieldName]);
} }
} }
@ -319,7 +259,7 @@ class UpdateRequest extends FormRequest
{ {
foreach ($this->stringFields as $fieldName) { foreach ($this->stringFields as $fieldName) {
if (array_key_exists($fieldName, $transaction)) { if (array_key_exists($fieldName, $transaction)) {
$current[$fieldName] = $this->clearString((string)$transaction[$fieldName]); $current[$fieldName] = $this->clearString((string) $transaction[$fieldName]);
} }
} }
@ -330,7 +270,7 @@ class UpdateRequest extends FormRequest
{ {
foreach ($this->textareaFields as $fieldName) { foreach ($this->textareaFields as $fieldName) {
if (array_key_exists($fieldName, $transaction)) { if (array_key_exists($fieldName, $transaction)) {
$current[$fieldName] = $this->clearStringKeepNewlines((string)$transaction[$fieldName]); // keep newlines $current[$fieldName] = $this->clearStringKeepNewlines((string) $transaction[$fieldName]); // keep newlines
} }
} }
@ -342,8 +282,8 @@ class UpdateRequest extends FormRequest
foreach ($this->dateFields as $fieldName) { foreach ($this->dateFields as $fieldName) {
app('log')->debug(sprintf('Now at date field %s', $fieldName)); app('log')->debug(sprintf('Now at date field %s', $fieldName));
if (array_key_exists($fieldName, $transaction)) { if (array_key_exists($fieldName, $transaction)) {
app('log')->debug(sprintf('New value: "%s"', (string)$transaction[$fieldName])); app('log')->debug(sprintf('New value: "%s"', (string) $transaction[$fieldName]));
$current[$fieldName] = $this->dateFromValue((string)$transaction[$fieldName]); $current[$fieldName] = $this->dateFromValue((string) $transaction[$fieldName]);
} }
} }
@ -354,7 +294,7 @@ class UpdateRequest extends FormRequest
{ {
foreach ($this->booleanFields as $fieldName) { foreach ($this->booleanFields as $fieldName) {
if (array_key_exists($fieldName, $transaction)) { if (array_key_exists($fieldName, $transaction)) {
$current[$fieldName] = $this->convertBoolean((string)$transaction[$fieldName]); $current[$fieldName] = $this->convertBoolean((string) $transaction[$fieldName]);
} }
} }
@ -381,7 +321,7 @@ class UpdateRequest extends FormRequest
$current[$fieldName] = sprintf('%.12f', $value); $current[$fieldName] = sprintf('%.12f', $value);
} }
if (!is_float($value)) { if (!is_float($value)) {
$current[$fieldName] = (string)$value; $current[$fieldName] = (string) $value;
} }
} }
} }

View File

@ -240,7 +240,7 @@ class BasicController extends Controller
} }
/** /**
* @throws \Exception * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/ */
private function getLeftToSpendInfo(Carbon $start, Carbon $end): array private function getLeftToSpendInfo(Carbon $start, Carbon $end): array
{ {

View File

@ -47,64 +47,7 @@ class FixPostgresSequences extends Command
return 0; return 0;
} }
$this->friendlyLine('Going to verify PostgreSQL table sequences.'); $this->friendlyLine('Going to verify PostgreSQL table sequences.');
$tablesToCheck = [ $tablesToCheck = ['2fa_tokens', 'account_meta', 'account_types', 'accounts', 'attachments', 'auto_budgets', 'available_budgets', 'bills', 'budget_limits', 'budget_transaction', 'budget_transaction_journal', 'budgets', 'categories', 'category_transaction', 'category_transaction_journal', 'configuration', 'currency_exchange_rates', 'failed_jobs', 'group_journals', 'jobs', 'journal_links', 'journal_meta', 'limit_repetitions', 'link_types', 'locations', 'migrations', 'notes', 'oauth_clients', 'oauth_personal_access_clients', 'object_groups', 'permissions', 'piggy_bank_events', 'piggy_bank_repetitions', 'piggy_banks', 'preferences', 'recurrences', 'recurrences_meta', 'recurrences_repetitions', 'recurrences_transactions', 'roles', 'rt_meta', 'rule_actions', 'rule_groups', 'rule_triggers', 'rules', 'tag_transaction_journal', 'tags', 'transaction_currencies', 'transaction_groups', 'transaction_journals', 'transaction_types', 'transactions', 'users', 'webhook_attempts', 'webhook_messages', 'webhooks'];
'2fa_tokens',
'account_meta',
'account_types',
'accounts',
'attachments',
'auto_budgets',
'available_budgets',
'bills',
'budget_limits',
'budget_transaction',
'budget_transaction_journal',
'budgets',
'categories',
'category_transaction',
'category_transaction_journal',
'configuration',
'currency_exchange_rates',
'failed_jobs',
'group_journals',
'jobs',
'journal_links',
'journal_meta',
'limit_repetitions',
'link_types',
'locations',
'migrations',
'notes',
'oauth_clients',
'oauth_personal_access_clients',
'object_groups',
'permissions',
'piggy_bank_events',
'piggy_bank_repetitions',
'piggy_banks',
'preferences',
'recurrences',
'recurrences_meta',
'recurrences_repetitions',
'recurrences_transactions',
'roles',
'rt_meta',
'rule_actions',
'rule_groups',
'rule_triggers',
'rules',
'tag_transaction_journal',
'tags',
'transaction_currencies',
'transaction_groups',
'transaction_journals',
'transaction_types',
'transactions',
'users',
'webhook_attempts',
'webhook_messages',
'webhooks',
];
foreach ($tablesToCheck as $tableToCheck) { foreach ($tablesToCheck as $tableToCheck) {
$this->friendlyLine(sprintf('Checking the next id sequence for table "%s".', $tableToCheck)); $this->friendlyLine(sprintf('Checking the next id sequence for table "%s".', $tableToCheck));

View File

@ -104,7 +104,7 @@ class MigrateToGroups extends Command
{ {
$configVar = app('fireflyconfig')->get(self::CONFIG_NAME, false); $configVar = app('fireflyconfig')->get(self::CONFIG_NAME, false);
if (null !== $configVar) { if (null !== $configVar) {
return (bool)$configVar->data; return (bool) $configVar->data;
} }
return false; return false;
@ -197,7 +197,7 @@ class MigrateToGroups extends Command
{ {
$set = $journal->transactions->filter( $set = $journal->transactions->filter(
static function (Transaction $subject) use ($transaction) { static function (Transaction $subject) use ($transaction) {
$amount = (float)$transaction->amount * -1 === (float)$subject->amount; // intentional float $amount = (float) $transaction->amount * -1 === (float) $subject->amount; // intentional float
$identifier = $transaction->identifier === $subject->identifier; $identifier = $transaction->identifier === $subject->identifier;
app('log')->debug(sprintf('Amount the same? %s', var_export($amount, true))); app('log')->debug(sprintf('Amount the same? %s', var_export($amount, true)));
app('log')->debug(sprintf('ID the same? %s', var_export($identifier, true))); app('log')->debug(sprintf('ID the same? %s', var_export($identifier, true)));
@ -209,6 +209,9 @@ class MigrateToGroups extends Command
return $set->first(); return $set->first();
} }
/**
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
private function generateTransaction(TransactionJournal $journal, Transaction $transaction): array private function generateTransaction(TransactionJournal $journal, Transaction $transaction): array
{ {
app('log')->debug(sprintf('Now going to add transaction #%d to the array.', $transaction->id)); app('log')->debug(sprintf('Now going to add transaction #%d to the array.', $transaction->id));
@ -226,31 +229,31 @@ class MigrateToGroups extends Command
return []; return [];
} }
$budgetId = $this->cliRepository->getJournalBudgetId($journal); $budgetId = $this->cliRepository->getJournalBudgetId($journal);
$categoryId = $this->cliRepository->getJournalCategoryId($journal); $categoryId = $this->cliRepository->getJournalCategoryId($journal);
$notes = $this->cliRepository->getNoteText($journal); $notes = $this->cliRepository->getNoteText($journal);
$tags = $this->cliRepository->getTags($journal); $tags = $this->cliRepository->getTags($journal);
$internalRef = $this->cliRepository->getMetaField($journal, 'internal-reference'); $internalRef = $this->cliRepository->getMetaField($journal, 'internal-reference');
$sepaCC = $this->cliRepository->getMetaField($journal, 'sepa_cc'); $sepaCC = $this->cliRepository->getMetaField($journal, 'sepa_cc');
$sepaCtOp = $this->cliRepository->getMetaField($journal, 'sepa_ct_op'); $sepaCtOp = $this->cliRepository->getMetaField($journal, 'sepa_ct_op');
$sepaCtId = $this->cliRepository->getMetaField($journal, 'sepa_ct_id'); $sepaCtId = $this->cliRepository->getMetaField($journal, 'sepa_ct_id');
$sepaDb = $this->cliRepository->getMetaField($journal, 'sepa_db'); $sepaDb = $this->cliRepository->getMetaField($journal, 'sepa_db');
$sepaCountry = $this->cliRepository->getMetaField($journal, 'sepa_country'); $sepaCountry = $this->cliRepository->getMetaField($journal, 'sepa_country');
$sepaEp = $this->cliRepository->getMetaField($journal, 'sepa_ep'); $sepaEp = $this->cliRepository->getMetaField($journal, 'sepa_ep');
$sepaCi = $this->cliRepository->getMetaField($journal, 'sepa_ci'); $sepaCi = $this->cliRepository->getMetaField($journal, 'sepa_ci');
$sepaBatchId = $this->cliRepository->getMetaField($journal, 'sepa_batch_id'); $sepaBatchId = $this->cliRepository->getMetaField($journal, 'sepa_batch_id');
$externalId = $this->cliRepository->getMetaField($journal, 'external-id'); $externalId = $this->cliRepository->getMetaField($journal, 'external-id');
$originalSource = $this->cliRepository->getMetaField($journal, 'original-source'); $originalSource = $this->cliRepository->getMetaField($journal, 'original-source');
$recurrenceId = $this->cliRepository->getMetaField($journal, 'recurrence_id'); $recurrenceId = $this->cliRepository->getMetaField($journal, 'recurrence_id');
$bunq = $this->cliRepository->getMetaField($journal, 'bunq_payment_id'); $bunq = $this->cliRepository->getMetaField($journal, 'bunq_payment_id');
$hash = $this->cliRepository->getMetaField($journal, 'import_hash'); $hash = $this->cliRepository->getMetaField($journal, 'import_hash');
$hashTwo = $this->cliRepository->getMetaField($journal, 'import_hash_v2'); $hashTwo = $this->cliRepository->getMetaField($journal, 'import_hash_v2');
$interestDate = $this->cliRepository->getMetaDate($journal, 'interest_date'); $interestDate = $this->cliRepository->getMetaDate($journal, 'interest_date');
$bookDate = $this->cliRepository->getMetaDate($journal, 'book_date'); $bookDate = $this->cliRepository->getMetaDate($journal, 'book_date');
$processDate = $this->cliRepository->getMetaDate($journal, 'process_date'); $processDate = $this->cliRepository->getMetaDate($journal, 'process_date');
$dueDate = $this->cliRepository->getMetaDate($journal, 'due_date'); $dueDate = $this->cliRepository->getMetaDate($journal, 'due_date');
$paymentDate = $this->cliRepository->getMetaDate($journal, 'payment_date'); $paymentDate = $this->cliRepository->getMetaDate($journal, 'payment_date');
$invoiceDate = $this->cliRepository->getMetaDate($journal, 'invoice_date'); $invoiceDate = $this->cliRepository->getMetaDate($journal, 'invoice_date');
// overrule journal category with transaction category. // overrule journal category with transaction category.
$budgetId = $this->getTransactionBudget($transaction, $opposingTr) ?? $budgetId; $budgetId = $this->getTransactionBudget($transaction, $opposingTr) ?? $budgetId;

View File

@ -166,7 +166,7 @@ class TransactionJournalFactory
$set = [ $set = [
'journal' => $journal, 'journal' => $journal,
'name' => $field, 'name' => $field,
'data' => (string)($data[$field] ?? ''), 'data' => (string) ($data[$field] ?? ''),
]; ];
if ($data[$field] instanceof Carbon) { if ($data[$field] instanceof Carbon) {
$data[$field]->setTimezone(config('app.timezone')); $data[$field]->setTimezone(config('app.timezone'));
@ -182,9 +182,14 @@ class TransactionJournalFactory
} }
/** /**
* TODO typeOverrule: the account validator may have another opinion on the transaction type. not sure what to do
* with this.
*
* @throws DuplicateTransactionException * @throws DuplicateTransactionException
* @throws FireflyException * @throws FireflyException
* */ *
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
private function createJournal(NullArrayObject $row): ?TransactionJournal private function createJournal(NullArrayObject $row): ?TransactionJournal
{ {
$row['import_hash_v2'] = $this->hashArray($row); $row['import_hash_v2'] = $this->hashArray($row);
@ -195,11 +200,11 @@ class TransactionJournalFactory
$type = $this->typeRepository->findTransactionType(null, $row['type']); $type = $this->typeRepository->findTransactionType(null, $row['type']);
$carbon = $row['date'] ?? today(config('app.timezone')); $carbon = $row['date'] ?? today(config('app.timezone'));
$order = $row['order'] ?? 0; $order = $row['order'] ?? 0;
$currency = $this->currencyRepository->findCurrency((int)$row['currency_id'], $row['currency_code']); $currency = $this->currencyRepository->findCurrency((int) $row['currency_id'], $row['currency_code']);
$foreignCurrency = $this->currencyRepository->findCurrencyNull($row['foreign_currency_id'], $row['foreign_currency_code']); $foreignCurrency = $this->currencyRepository->findCurrencyNull($row['foreign_currency_id'], $row['foreign_currency_code']);
$bill = $this->billRepository->findBill((int)$row['bill_id'], $row['bill_name']); $bill = $this->billRepository->findBill((int) $row['bill_id'], $row['bill_name']);
$billId = TransactionType::WITHDRAWAL === $type->type && null !== $bill ? $bill->id : null; $billId = TransactionType::WITHDRAWAL === $type->type && null !== $bill ? $bill->id : null;
$description = (string)$row['description']; $description = (string) $row['description'];
// Manipulate basic fields // Manipulate basic fields
$carbon->setTimezone(config('app.timezone')); $carbon->setTimezone(config('app.timezone'));
@ -214,9 +219,6 @@ class TransactionJournalFactory
return null; return null;
} }
// typeOverrule: the account validator may have another opinion on the transaction type.
// not sure what to do with this.
/** create or get source and destination accounts */ /** create or get source and destination accounts */
$sourceInfo = [ $sourceInfo = [
'id' => $row['source_id'], 'id' => $row['source_id'],
@ -237,9 +239,7 @@ class TransactionJournalFactory
]; ];
app('log')->debug('Source info:', $sourceInfo); app('log')->debug('Source info:', $sourceInfo);
app('log')->debug('Destination info:', $destInfo); app('log')->debug('Destination info:', $destInfo);
app('log')->debug('Now calling getAccount for the source.'); $sourceAccount = $this->getAccount($type->type, 'source', $sourceInfo);
$sourceAccount = $this->getAccount($type->type, 'source', $sourceInfo);
app('log')->debug('Now calling getAccount for the destination.');
$destinationAccount = $this->getAccount($type->type, 'destination', $destInfo); $destinationAccount = $this->getAccount($type->type, 'destination', $destInfo);
app('log')->debug('Done with getAccount(2x)'); app('log')->debug('Done with getAccount(2x)');
@ -283,17 +283,14 @@ class TransactionJournalFactory
$transactionFactory->setReconciled($row['reconciled'] ?? false); $transactionFactory->setReconciled($row['reconciled'] ?? false);
try { try {
$negative = $transactionFactory->createNegative((string)$row['amount'], (string)$row['foreign_amount']); $negative = $transactionFactory->createNegative((string) $row['amount'], (string) $row['foreign_amount']);
} catch (FireflyException $e) { } catch (FireflyException $e) {
app('log')->error('Exception creating negative transaction.'); app('log')->error(sprintf('Exception creating negative transaction: %s', $e->getMessage()));
app('log')->error($e->getMessage());
app('log')->error($e->getTraceAsString());
$this->forceDeleteOnError(new Collection([$journal])); $this->forceDeleteOnError(new Collection([$journal]));
throw new FireflyException($e->getMessage(), 0, $e); throw new FireflyException($e->getMessage(), 0, $e);
} }
// and the destination one:
/** @var TransactionFactory $transactionFactory */ /** @var TransactionFactory $transactionFactory */
$transactionFactory = app(TransactionFactory::class); $transactionFactory = app(TransactionFactory::class);
$transactionFactory->setUser($this->user); $transactionFactory->setUser($this->user);
@ -305,39 +302,21 @@ class TransactionJournalFactory
$transactionFactory->setReconciled($row['reconciled'] ?? false); $transactionFactory->setReconciled($row['reconciled'] ?? false);
try { try {
$transactionFactory->createPositive((string)$row['amount'], (string)$row['foreign_amount']); $transactionFactory->createPositive((string) $row['amount'], (string) $row['foreign_amount']);
} catch (FireflyException $e) { } catch (FireflyException $e) {
app('log')->error('Exception creating positive transaction.'); app('log')->error(sprintf('Exception creating positive transaction: %s', $e->getMessage()));
app('log')->error($e->getMessage());
app('log')->error($e->getTraceAsString());
app('log')->warning('Delete negative transaction.');
$this->forceTrDelete($negative); $this->forceTrDelete($negative);
$this->forceDeleteOnError(new Collection([$journal])); $this->forceDeleteOnError(new Collection([$journal]));
throw new FireflyException($e->getMessage(), 0, $e); throw new FireflyException($e->getMessage(), 0, $e);
} }
// verify that journal has two transactions. Otherwise, delete and cancel.
$journal->completed = true; $journal->completed = true;
$journal->save(); $journal->save();
// Link all other data to the journal.
// Link budget
$this->storeBudget($journal, $row); $this->storeBudget($journal, $row);
// Link category
$this->storeCategory($journal, $row); $this->storeCategory($journal, $row);
// Set notes
$this->storeNotes($journal, $row['notes']); $this->storeNotes($journal, $row['notes']);
// Set piggy bank
$this->storePiggyEvent($journal, $row); $this->storePiggyEvent($journal, $row);
// Set tags
$this->storeTags($journal, $row['tags']); $this->storeTags($journal, $row['tags']);
// set all meta fields
$this->storeMetaFields($journal, $row); $this->storeMetaFields($journal, $row);
return $journal; return $journal;
@ -348,7 +327,13 @@ class TransactionJournalFactory
$dataRow = $row->getArrayCopy(); $dataRow = $row->getArrayCopy();
unset($dataRow['import_hash_v2'], $dataRow['original_source']); unset($dataRow['import_hash_v2'], $dataRow['original_source']);
$json = json_encode($dataRow, JSON_THROW_ON_ERROR);
try {
$json = json_encode($dataRow, JSON_THROW_ON_ERROR);
} catch (\JsonException $e) {
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); app('log')->debug(sprintf('The hash is: %s', $hash), $dataRow);
@ -399,10 +384,10 @@ class TransactionJournalFactory
// validate source account. // validate source account.
$array = [ $array = [
'id' => null !== $data['source_id'] ? (int)$data['source_id'] : null, 'id' => null !== $data['source_id'] ? (int) $data['source_id'] : null,
'name' => null !== $data['source_name'] ? (string)$data['source_name'] : null, 'name' => null !== $data['source_name'] ? (string) $data['source_name'] : null,
'iban' => null !== $data['source_iban'] ? (string)$data['source_iban'] : null, 'iban' => null !== $data['source_iban'] ? (string) $data['source_iban'] : null,
'number' => null !== $data['source_number'] ? (string)$data['source_number'] : null, 'number' => null !== $data['source_number'] ? (string) $data['source_number'] : null,
]; ];
$validSource = $this->accountValidator->validateSource($array); $validSource = $this->accountValidator->validateSource($array);
@ -414,10 +399,10 @@ class TransactionJournalFactory
// validate destination account // validate destination account
$array = [ $array = [
'id' => null !== $data['destination_id'] ? (int)$data['destination_id'] : null, 'id' => null !== $data['destination_id'] ? (int) $data['destination_id'] : null,
'name' => null !== $data['destination_name'] ? (string)$data['destination_name'] : null, 'name' => null !== $data['destination_name'] ? (string) $data['destination_name'] : null,
'iban' => null !== $data['destination_iban'] ? (string)$data['destination_iban'] : null, 'iban' => null !== $data['destination_iban'] ? (string) $data['destination_iban'] : null,
'number' => null !== $data['destination_number'] ? (string)$data['destination_number'] : null, 'number' => null !== $data['destination_number'] ? (string) $data['destination_number'] : null,
]; ];
$validDestination = $this->accountValidator->validateDestination($array); $validDestination = $this->accountValidator->validateDestination($array);
@ -549,7 +534,7 @@ class TransactionJournalFactory
{ {
app('log')->debug('Will now store piggy event.'); app('log')->debug('Will now store piggy event.');
$piggyBank = $this->piggyRepository->findPiggyBank((int)$data['piggy_bank_id'], $data['piggy_bank_name']); $piggyBank = $this->piggyRepository->findPiggyBank((int) $data['piggy_bank_id'], $data['piggy_bank_name']);
if (null !== $piggyBank) { if (null !== $piggyBank) {
$this->piggyEventFactory->create($journal, $piggyBank); $this->piggyEventFactory->create($journal, $piggyBank);

View File

@ -56,7 +56,7 @@ class EditController extends Controller
$this->middleware( $this->middleware(
function ($request, $next) { function ($request, $next) {
app('view')->share('mainTitleIcon', 'fa-credit-card'); app('view')->share('mainTitleIcon', 'fa-credit-card');
app('view')->share('title', (string)trans('firefly.accounts')); app('view')->share('title', (string) trans('firefly.accounts'));
$this->repository = app(AccountRepositoryInterface::class); $this->repository = app(AccountRepositoryInterface::class);
$this->attachments = app(AttachmentHelperInterface::class); $this->attachments = app(AttachmentHelperInterface::class);
@ -78,7 +78,7 @@ class EditController extends Controller
} }
$objectType = config('firefly.shortNamesByFullName')[$account->accountType->type]; $objectType = config('firefly.shortNamesByFullName')[$account->accountType->type];
$subTitle = (string)trans(sprintf('firefly.edit_%s_account', $objectType), ['name' => $account->name]); $subTitle = (string) trans(sprintf('firefly.edit_%s_account', $objectType), ['name' => $account->name]);
$subTitleIcon = config(sprintf('firefly.subIconsByIdentifier.%s', $objectType)); $subTitleIcon = config(sprintf('firefly.subIconsByIdentifier.%s', $objectType));
$roles = $this->getRoles(); $roles = $this->getRoles();
$liabilityTypes = $this->getLiabilityTypes(); $liabilityTypes = $this->getLiabilityTypes();
@ -103,9 +103,9 @@ class EditController extends Controller
// interest calculation periods: // interest calculation periods:
$interestPeriods = [ $interestPeriods = [
'daily' => (string)trans('firefly.interest_calc_daily'), 'daily' => (string) trans('firefly.interest_calc_daily'),
'monthly' => (string)trans('firefly.interest_calc_monthly'), 'monthly' => (string) trans('firefly.interest_calc_monthly'),
'yearly' => (string)trans('firefly.interest_calc_yearly'), 'yearly' => (string) trans('firefly.interest_calc_yearly'),
]; ];
// put previous url in session if not redirect from store (not "return_to_edit"). // put previous url in session if not redirect from store (not "return_to_edit").
@ -114,7 +114,7 @@ class EditController extends Controller
} }
$request->session()->forget('accounts.edit.fromUpdate'); $request->session()->forget('accounts.edit.fromUpdate');
$openingBalanceAmount = (string)$repository->getOpeningBalanceAmount($account); $openingBalanceAmount = (string) $repository->getOpeningBalanceAmount($account);
if ('0' === $openingBalanceAmount) { if ('0' === $openingBalanceAmount) {
$openingBalanceAmount = ''; $openingBalanceAmount = '';
} }
@ -134,17 +134,17 @@ class EditController extends Controller
'cc_type' => $repository->getMetaValue($account, 'cc_type'), 'cc_type' => $repository->getMetaValue($account, 'cc_type'),
'cc_monthly_payment_date' => $repository->getMetaValue($account, 'cc_monthly_payment_date'), 'cc_monthly_payment_date' => $repository->getMetaValue($account, 'cc_monthly_payment_date'),
'BIC' => $repository->getMetaValue($account, 'BIC'), 'BIC' => $repository->getMetaValue($account, 'BIC'),
'opening_balance_date' => substr((string)$openingBalanceDate, 0, 10), 'opening_balance_date' => substr((string) $openingBalanceDate, 0, 10),
'liability_type_id' => $account->account_type_id, 'liability_type_id' => $account->account_type_id,
'opening_balance' => app('steam')->bcround($openingBalanceAmount, $currency->decimal_places), 'opening_balance' => app('steam')->bcround($openingBalanceAmount, $currency->decimal_places),
'liability_direction' => $this->repository->getMetaValue($account, 'liability_direction'), 'liability_direction' => $this->repository->getMetaValue($account, 'liability_direction'),
'virtual_balance' => app('steam')->bcround($virtualBalance, $currency->decimal_places), 'virtual_balance' => app('steam')->bcround($virtualBalance, $currency->decimal_places),
'currency_id' => $currency->id, 'currency_id' => $currency->id,
'include_net_worth' => $hasOldInput ? (bool)$request->old('include_net_worth') : $includeNetWorth, 'include_net_worth' => $hasOldInput ? (bool) $request->old('include_net_worth') : $includeNetWorth,
'interest' => $repository->getMetaValue($account, 'interest'), 'interest' => $repository->getMetaValue($account, 'interest'),
'interest_period' => $repository->getMetaValue($account, 'interest_period'), 'interest_period' => $repository->getMetaValue($account, 'interest_period'),
'notes' => $this->repository->getNoteText($account), 'notes' => $this->repository->getNoteText($account),
'active' => $hasOldInput ? (bool)$request->old('active') : $account->active, 'active' => $hasOldInput ? (bool) $request->old('active') : $account->active,
]; ];
if ('' === $openingBalanceAmount) { if ('' === $openingBalanceAmount) {
$preFilled['opening_balance'] = ''; $preFilled['opening_balance'] = '';
@ -152,22 +152,7 @@ class EditController extends Controller
$request->session()->flash('preFilled', $preFilled); $request->session()->flash('preFilled', $preFilled);
return view( return view('accounts.edit', compact('account', 'currency', 'subTitle', 'subTitleIcon', 'locations', 'liabilityDirections', 'objectType', 'roles', 'preFilled', 'liabilityTypes', 'interestPeriods'));
'accounts.edit',
compact(
'account',
'currency',
'subTitle',
'subTitleIcon',
'locations',
'liabilityDirections',
'objectType',
'roles',
'preFilled',
'liabilityTypes',
'interestPeriods'
)
);
} }
/** /**
@ -184,7 +169,7 @@ class EditController extends Controller
$data = $request->getAccountData(); $data = $request->getAccountData();
$this->repository->update($account, $data); $this->repository->update($account, $data);
$request->session()->flash('success', (string)trans('firefly.updated_account', ['name' => $account->name])); $request->session()->flash('success', (string) trans('firefly.updated_account', ['name' => $account->name]));
// store new attachment(s): // store new attachment(s):
/** @var null|array $files */ /** @var null|array $files */
@ -193,7 +178,7 @@ class EditController extends Controller
$this->attachments->saveAttachmentsForModel($account, $files); $this->attachments->saveAttachmentsForModel($account, $files);
} }
if (null !== $files && auth()->user()->hasRole('demo')) { if (null !== $files && auth()->user()->hasRole('demo')) {
session()->flash('info', (string)trans('firefly.no_att_demo_user')); session()->flash('info', (string) trans('firefly.no_att_demo_user'));
} }
if (count($this->attachments->getMessages()->get('attachments')) > 0) { if (count($this->attachments->getMessages()->get('attachments')) > 0) {
@ -202,7 +187,7 @@ class EditController extends Controller
// redirect // redirect
$redirect = redirect($this->getPreviousUrl('accounts.edit.url')); $redirect = redirect($this->getPreviousUrl('accounts.edit.url'));
if (1 === (int)$request->get('return_to_edit')) { if (1 === (int) $request->get('return_to_edit')) {
// set value so edit routine will not overwrite URL: // set value so edit routine will not overwrite URL:
$request->session()->put('accounts.edit.fromUpdate', true); $request->session()->put('accounts.edit.fromUpdate', true);

View File

@ -44,11 +44,8 @@ class ExpenseReportController extends Controller
use AugumentData; use AugumentData;
use TransactionCalculation; use TransactionCalculation;
/** @var AccountRepositoryInterface The account repository */ protected AccountRepositoryInterface $accountRepository;
protected $accountRepository; protected GeneratorInterface $generator;
/** @var GeneratorInterface Chart generation methods. */
protected $generator;
/** /**
* ExpenseReportController constructor. * ExpenseReportController constructor.
@ -71,7 +68,8 @@ class ExpenseReportController extends Controller
* *
* TODO this chart is not multi currency aware. * TODO this chart is not multi currency aware.
* *
* */ * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function mainChart(Collection $accounts, Collection $expense, Carbon $start, Carbon $end): JsonResponse public function mainChart(Collection $accounts, Collection $expense, Carbon $start, Carbon $end): JsonResponse
{ {
$cache = new CacheProperties(); $cache = new CacheProperties();
@ -89,9 +87,8 @@ class ExpenseReportController extends Controller
$chartData = []; $chartData = [];
$currentStart = clone $start; $currentStart = clone $start;
$combined = $this->combineAccounts($expense); $combined = $this->combineAccounts($expense);
// make "all" set: $all = new Collection();
$all = new Collection(); foreach ($combined as $combination) {
foreach ($combined as $name => $combination) {
$all = $all->merge($combination); $all = $all->merge($combination);
} }
@ -105,27 +102,27 @@ class ExpenseReportController extends Controller
/** @var Account $exp */ /** @var Account $exp */
$exp = $combination->first(); $exp = $combination->first();
$chartData[$exp->id.'-in'] = [ $chartData[$exp->id.'-in'] = [
'label' => sprintf('%s (%s)', $name, (string)trans('firefly.income')), 'label' => sprintf('%s (%s)', $name, (string) trans('firefly.income')),
'type' => 'bar', 'type' => 'bar',
'yAxisID' => 'y-axis-0', 'yAxisID' => 'y-axis-0',
'entries' => [], 'entries' => [],
]; ];
$chartData[$exp->id.'-out'] = [ $chartData[$exp->id.'-out'] = [
'label' => sprintf('%s (%s)', $name, (string)trans('firefly.expenses')), 'label' => sprintf('%s (%s)', $name, (string) trans('firefly.expenses')),
'type' => 'bar', 'type' => 'bar',
'yAxisID' => 'y-axis-0', 'yAxisID' => 'y-axis-0',
'entries' => [], 'entries' => [],
]; ];
// total in, total out: // total in, total out:
$chartData[$exp->id.'-total-in'] = [ $chartData[$exp->id.'-total-in'] = [
'label' => sprintf('%s (%s)', $name, (string)trans('firefly.sum_of_income')), 'label' => sprintf('%s (%s)', $name, (string) trans('firefly.sum_of_income')),
'type' => 'line', 'type' => 'line',
'fill' => false, 'fill' => false,
'yAxisID' => 'y-axis-1', 'yAxisID' => 'y-axis-1',
'entries' => [], 'entries' => [],
]; ];
$chartData[$exp->id.'-total-out'] = [ $chartData[$exp->id.'-total-out'] = [
'label' => sprintf('%s (%s)', $name, (string)trans('firefly.sum_of_expenses')), 'label' => sprintf('%s (%s)', $name, (string) trans('firefly.sum_of_expenses')),
'type' => 'line', 'type' => 'line',
'fill' => false, 'fill' => false,
'yAxisID' => 'y-axis-1', 'yAxisID' => 'y-axis-1',

View File

@ -45,8 +45,7 @@ class ReportController extends Controller
use BasicDataSupport; use BasicDataSupport;
use ChartGeneration; use ChartGeneration;
/** @var GeneratorInterface Chart generation methods. */ protected GeneratorInterface $generator;
protected $generator;
/** /**
* ReportController constructor. * ReportController constructor.
@ -109,7 +108,7 @@ class ReportController extends Controller
continue; continue;
} }
$currencyId = $netWorthItem['currency_id']; $currencyId = $netWorthItem['currency_id'];
$label = $current->isoFormat((string)trans('config.month_and_day_js', [], $locale)); $label = $current->isoFormat((string) trans('config.month_and_day_js', [], $locale));
if (!array_key_exists($currencyId, $chartData)) { if (!array_key_exists($currencyId, $chartData)) {
$chartData[$currencyId] = [ $chartData[$currencyId] = [
'label' => 'Net worth in '.$netWorthItem['currency_name'], 'label' => 'Net worth in '.$netWorthItem['currency_name'],
@ -133,7 +132,8 @@ class ReportController extends Controller
/** /**
* Shows income and expense, debit/credit: operations. * Shows income and expense, debit/credit: operations.
* *
* */ * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function operations(Collection $accounts, Carbon $start, Carbon $end): JsonResponse public function operations(Collection $accounts, Carbon $start, Carbon $end): JsonResponse
{ {
// chart properties for cache: // chart properties for cache:
@ -150,11 +150,8 @@ class ReportController extends Controller
$titleFormat = app('navigation')->preferredCarbonLocalizedFormat($start, $end); $titleFormat = app('navigation')->preferredCarbonLocalizedFormat($start, $end);
$preferredRange = app('navigation')->preferredRangeFormat($start, $end); $preferredRange = app('navigation')->preferredRangeFormat($start, $end);
$ids = $accounts->pluck('id')->toArray(); $ids = $accounts->pluck('id')->toArray();
$data = [];
// get journals for entire period: $chartData = [];
$data = [];
$chartData = [
];
/** @var GroupCollectorInterface $collector */ /** @var GroupCollectorInterface $collector */
$collector = app(GroupCollectorInterface::class); $collector = app(GroupCollectorInterface::class);
@ -167,13 +164,13 @@ class ReportController extends Controller
/** @var array $journal */ /** @var array $journal */
foreach ($journals as $journal) { foreach ($journals as $journal) {
$period = $journal['date']->format($format); $period = $journal['date']->format($format);
$currencyId = (int)$journal['currency_id']; $currencyId = (int) $journal['currency_id'];
$data[$currencyId] ??= [ $data[$currencyId] ??= [
'currency_id' => $currencyId, 'currency_id' => $currencyId,
'currency_symbol' => $journal['currency_symbol'], 'currency_symbol' => $journal['currency_symbol'],
'currency_code' => $journal['currency_code'], 'currency_code' => $journal['currency_code'],
'currency_name' => $journal['currency_name'], 'currency_name' => $journal['currency_name'],
'currency_decimal_places' => (int)$journal['currency_decimal_places'], 'currency_decimal_places' => (int) $journal['currency_decimal_places'],
]; ];
$data[$currencyId][$period] ??= [ $data[$currencyId][$period] ??= [
'period' => $period, 'period' => $period,
@ -186,18 +183,7 @@ class ReportController extends Controller
// deposit = incoming // deposit = incoming
// transfer or reconcile or opening balance, and these accounts are the destination. // transfer or reconcile or opening balance, and these accounts are the destination.
if ( if (TransactionType::DEPOSIT === $journal['transaction_type_type'] || ((TransactionType::TRANSFER === $journal['transaction_type_type'] || TransactionType::RECONCILIATION === $journal['transaction_type_type'] || TransactionType::OPENING_BALANCE === $journal['transaction_type_type']) && in_array($journal['destination_account_id'], $ids, true))) {
TransactionType::DEPOSIT === $journal['transaction_type_type']
|| (
(
TransactionType::TRANSFER === $journal['transaction_type_type']
|| TransactionType::RECONCILIATION === $journal['transaction_type_type']
|| TransactionType::OPENING_BALANCE === $journal['transaction_type_type']
)
&& in_array($journal['destination_account_id'], $ids, true)
)
) {
$key = 'earned'; $key = 'earned';
} }
$data[$currencyId][$period][$key] = bcadd($data[$currencyId][$period][$key], $amount); $data[$currencyId][$period][$key] = bcadd($data[$currencyId][$period][$key], $amount);
@ -207,7 +193,7 @@ class ReportController extends Controller
/** @var array $currency */ /** @var array $currency */
foreach ($data as $currency) { foreach ($data as $currency) {
$income = [ $income = [
'label' => (string)trans('firefly.box_earned_in_currency', ['currency' => $currency['currency_name']]), 'label' => (string) trans('firefly.box_earned_in_currency', ['currency' => $currency['currency_name']]),
'type' => 'bar', 'type' => 'bar',
'backgroundColor' => 'rgba(0, 141, 76, 0.5)', // green 'backgroundColor' => 'rgba(0, 141, 76, 0.5)', // green
'currency_id' => $currency['currency_id'], 'currency_id' => $currency['currency_id'],
@ -216,7 +202,7 @@ class ReportController extends Controller
'entries' => [], 'entries' => [],
]; ];
$expense = [ $expense = [
'label' => (string)trans('firefly.box_spent_in_currency', ['currency' => $currency['currency_name']]), 'label' => (string) trans('firefly.box_spent_in_currency', ['currency' => $currency['currency_name']]),
'type' => 'bar', 'type' => 'bar',
'backgroundColor' => 'rgba(219, 68, 55, 0.5)', // red 'backgroundColor' => 'rgba(219, 68, 55, 0.5)', // red
'currency_id' => $currency['currency_id'], 'currency_id' => $currency['currency_id'],

View File

@ -48,6 +48,8 @@ class BoxController extends Controller
* 0) If the user has available amount this period and has overspent: overspent box. * 0) If the user has available amount this period and has overspent: overspent box.
* 1) If the user has available amount this period and has NOT overspent: left to spend box. * 1) If the user has available amount this period and has NOT overspent: left to spend box.
* 2) if the user has no available amount set this period: spent per day * 2) if the user has no available amount set this period: spent per day
*
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/ */
public function available(): JsonResponse public function available(): JsonResponse
{ {

View File

@ -49,7 +49,7 @@ class PreferencesController extends Controller
$this->middleware( $this->middleware(
static function ($request, $next) { static function ($request, $next) {
app('view')->share('title', (string)trans('firefly.preferences')); app('view')->share('title', (string) trans('firefly.preferences'));
app('view')->share('mainTitleIcon', 'fa-gear'); app('view')->share('mainTitleIcon', 'fa-gear');
return $next($request); return $next($request);
@ -66,10 +66,8 @@ class PreferencesController extends Controller
*/ */
public function index(AccountRepositoryInterface $repository) public function index(AccountRepositoryInterface $repository)
{ {
$accounts = $repository->getAccountsByType([AccountType::DEFAULT, AccountType::ASSET, AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE]); $accounts = $repository->getAccountsByType([AccountType::DEFAULT, AccountType::ASSET, AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE]);
$isDocker = env('IS_DOCKER', false); $isDocker = env('IS_DOCKER', false);
// group accounts
$groupedAccounts = []; $groupedAccounts = [];
/** @var Account $account */ /** @var Account $account */
@ -84,7 +82,7 @@ class PreferencesController extends Controller
if ('opt_group_' === $role) { if ('opt_group_' === $role) {
$role = 'opt_group_defaultAsset'; $role = 'opt_group_defaultAsset';
} }
$groupedAccounts[(string)trans(sprintf('firefly.%s', $role))][$account->id] = $account->name; $groupedAccounts[(string) trans(sprintf('firefly.%s', $role))][$account->id] = $account->name;
} }
ksort($groupedAccounts); ksort($groupedAccounts);
@ -107,7 +105,7 @@ class PreferencesController extends Controller
if (is_array($fiscalYearStartStr)) { if (is_array($fiscalYearStartStr)) {
$fiscalYearStartStr = '01-01'; $fiscalYearStartStr = '01-01';
} }
$fiscalYearStart = sprintf('%s-%s', date('Y'), (string)$fiscalYearStartStr); $fiscalYearStart = sprintf('%s-%s', date('Y'), (string) $fiscalYearStartStr);
$tjOptionalFields = app('preferences')->get('transaction_journal_optional_fields', [])->data; $tjOptionalFields = app('preferences')->get('transaction_journal_optional_fields', [])->data;
$availableDarkModes = config('firefly.available_dark_modes'); $availableDarkModes = config('firefly.available_dark_modes');
@ -122,12 +120,12 @@ class PreferencesController extends Controller
// list of locales also has "equal" which makes it equal to whatever the language is. // list of locales also has "equal" which makes it equal to whatever the language is.
try { try {
$locales = json_decode((string)file_get_contents(resource_path(sprintf('lang/%s/locales.json', $language))), true, 512, JSON_THROW_ON_ERROR); $locales = json_decode((string) file_get_contents(resource_path(sprintf('lang/%s/locales.json', $language))), true, 512, JSON_THROW_ON_ERROR);
} catch (\JsonException $e) { } catch (\JsonException $e) {
app('log')->error($e->getMessage()); app('log')->error($e->getMessage());
$locales = []; $locales = [];
} }
$locales = ['equal' => (string)trans('firefly.equal_to_language')] + $locales; $locales = ['equal' => (string) trans('firefly.equal_to_language')] + $locales;
// an important fallback is that the frontPageAccount array gets refilled automatically // an important fallback is that the frontPageAccount array gets refilled automatically
// when it turns up empty. // when it turns up empty.
if (0 === count($frontPageAccounts)) { if (0 === count($frontPageAccounts)) {
@ -141,27 +139,7 @@ class PreferencesController extends Controller
$slackUrl = ''; $slackUrl = '';
} }
return view( return view('preferences.index', compact('language', 'groupedAccounts', 'isDocker', 'frontPageAccounts', 'languages', 'darkMode', 'availableDarkModes', 'notifications', 'slackUrl', 'locales', 'locale', 'tjOptionalFields', 'viewRange', 'customFiscalYear', 'listPageSize', 'fiscalYearStart'));
'preferences.index',
compact(
'language',
'groupedAccounts',
'isDocker',
'frontPageAccounts',
'languages',
'darkMode',
'availableDarkModes',
'notifications',
'slackUrl',
'locales',
'locale',
'tjOptionalFields',
'viewRange',
'customFiscalYear',
'listPageSize',
'fiscalYearStart'
)
);
} }
/** /**
@ -170,6 +148,8 @@ class PreferencesController extends Controller
* @return Redirector|RedirectResponse * @return Redirector|RedirectResponse
* *
* @throws FireflyException * @throws FireflyException
*
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/ */
public function postIndex(Request $request) public function postIndex(Request $request)
{ {
@ -177,7 +157,7 @@ class PreferencesController extends Controller
$frontPageAccounts = []; $frontPageAccounts = [];
if (is_array($request->get('frontPageAccounts')) && count($request->get('frontPageAccounts')) > 0) { if (is_array($request->get('frontPageAccounts')) && count($request->get('frontPageAccounts')) > 0) {
foreach ($request->get('frontPageAccounts') as $id) { foreach ($request->get('frontPageAccounts') as $id) {
$frontPageAccounts[] = (int)$id; $frontPageAccounts[] = (int) $id;
} }
app('preferences')->set('frontPageAccounts', $frontPageAccounts); app('preferences')->set('frontPageAccounts', $frontPageAccounts);
} }
@ -203,7 +183,7 @@ class PreferencesController extends Controller
// slack URL: // slack URL:
if (!auth()->user()->hasRole('demo')) { if (!auth()->user()->hasRole('demo')) {
$url = (string)$request->get('slackUrl'); $url = (string) $request->get('slackUrl');
if (UrlValidator::isValidWebhookURL($url)) { if (UrlValidator::isValidWebhookURL($url)) {
app('preferences')->set('slack_webhook_url', $url); app('preferences')->set('slack_webhook_url', $url);
} }
@ -213,8 +193,8 @@ class PreferencesController extends Controller
} }
// custom fiscal year // custom fiscal year
$customFiscalYear = 1 === (int)$request->get('customFiscalYear'); $customFiscalYear = 1 === (int) $request->get('customFiscalYear');
$string = strtotime((string)$request->get('fiscalYearStart')); $string = strtotime((string) $request->get('fiscalYearStart'));
if (false !== $string) { if (false !== $string) {
$fiscalYearStart = date('m-d', $string); $fiscalYearStart = date('m-d', $string);
app('preferences')->set('customFiscalYear', $customFiscalYear); app('preferences')->set('customFiscalYear', $customFiscalYear);
@ -223,7 +203,7 @@ class PreferencesController extends Controller
// save page size: // save page size:
app('preferences')->set('listPageSize', 50); app('preferences')->set('listPageSize', 50);
$listPageSize = (int)$request->get('listPageSize'); $listPageSize = (int) $request->get('listPageSize');
if ($listPageSize > 0 && $listPageSize < 1337) { if ($listPageSize > 0 && $listPageSize < 1337) {
app('preferences')->set('listPageSize', $listPageSize); app('preferences')->set('listPageSize', $listPageSize);
} }
@ -271,7 +251,7 @@ class PreferencesController extends Controller
app('preferences')->set('darkMode', $darkMode); app('preferences')->set('darkMode', $darkMode);
} }
session()->flash('success', (string)trans('firefly.saved_preferences')); session()->flash('success', (string) trans('firefly.saved_preferences'));
app('preferences')->mark(); app('preferences')->mark();
return redirect(route('preferences.index')); return redirect(route('preferences.index'));

View File

@ -120,6 +120,8 @@ class CreateController extends Controller
/** /**
* @return Factory|\Illuminate\Contracts\View\View * @return Factory|\Illuminate\Contracts\View\View
*
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/ */
public function createFromJournal(Request $request, TransactionJournal $journal) public function createFromJournal(Request $request, TransactionJournal $journal)
{ {

View File

@ -155,6 +155,8 @@ class CategoryController extends Controller
/** /**
* @return Factory|View * @return Factory|View
*
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/ */
public function accounts(Collection $accounts, Collection $categories, Carbon $start, Carbon $end) public function accounts(Collection $accounts, Collection $categories, Carbon $start, Carbon $end)
{ {
@ -281,8 +283,8 @@ class CategoryController extends Controller
]; ];
++$result[$key]['transactions']; ++$result[$key]['transactions'];
$result[$key]['sum'] = bcadd($journal['amount'], $result[$key]['sum']); $result[$key]['sum'] = bcadd($journal['amount'], $result[$key]['sum']);
$result[$key]['avg'] = bcdiv($result[$key]['sum'], (string)$result[$key]['transactions']); $result[$key]['avg'] = bcdiv($result[$key]['sum'], (string) $result[$key]['transactions']);
$result[$key]['avg_float'] = (float)$result[$key]['avg']; // intentional float $result[$key]['avg_float'] = (float) $result[$key]['avg']; // intentional float
} }
} }
} }
@ -331,8 +333,8 @@ class CategoryController extends Controller
]; ];
++$result[$key]['transactions']; ++$result[$key]['transactions'];
$result[$key]['sum'] = bcadd($journal['amount'], $result[$key]['sum']); $result[$key]['sum'] = bcadd($journal['amount'], $result[$key]['sum']);
$result[$key]['avg'] = bcdiv($result[$key]['sum'], (string)$result[$key]['transactions']); $result[$key]['avg'] = bcdiv($result[$key]['sum'], (string) $result[$key]['transactions']);
$result[$key]['avg_float'] = (float)$result[$key]['avg']; $result[$key]['avg_float'] = (float) $result[$key]['avg'];
} }
} }
} }
@ -355,6 +357,8 @@ class CategoryController extends Controller
/** /**
* @return Factory|View * @return Factory|View
*
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/ */
public function categories(Collection $accounts, Collection $categories, Carbon $start, Carbon $end) public function categories(Collection $accounts, Collection $categories, Carbon $start, Carbon $end)
{ {
@ -660,7 +664,7 @@ class CategoryController extends Controller
$result[] = [ $result[] = [
'description' => $journal['description'], 'description' => $journal['description'],
'transaction_group_id' => $journal['transaction_group_id'], 'transaction_group_id' => $journal['transaction_group_id'],
'amount_float' => (float)$journal['amount'], 'amount_float' => (float) $journal['amount'],
'amount' => $journal['amount'], 'amount' => $journal['amount'],
'date' => $journal['date']->isoFormat($this->monthAndDayFormat), 'date' => $journal['date']->isoFormat($this->monthAndDayFormat),
'date_sort' => $journal['date']->format('Y-m-d'), 'date_sort' => $journal['date']->format('Y-m-d'),
@ -708,7 +712,7 @@ class CategoryController extends Controller
$result[] = [ $result[] = [
'description' => $journal['description'], 'description' => $journal['description'],
'transaction_group_id' => $journal['transaction_group_id'], 'transaction_group_id' => $journal['transaction_group_id'],
'amount_float' => (float)$journal['amount'], 'amount_float' => (float) $journal['amount'],
'amount' => $journal['amount'], 'amount' => $journal['amount'],
'date' => $journal['date']->isoFormat($this->monthAndDayFormat), 'date' => $journal['date']->isoFormat($this->monthAndDayFormat),
'date_sort' => $journal['date']->format('Y-m-d'), 'date_sort' => $journal['date']->format('Y-m-d'),

View File

@ -41,11 +41,8 @@ class DoubleController extends Controller
{ {
use AugumentData; use AugumentData;
/** @var AccountRepositoryInterface The account repository */ protected AccountRepositoryInterface $accountRepository;
protected $accountRepository; private OperationsRepositoryInterface $opsRepository;
/** @var OperationsRepositoryInterface */
private $opsRepository;
/** /**
* Constructor for ExpenseController * Constructor for ExpenseController
@ -167,6 +164,8 @@ class DoubleController extends Controller
/** /**
* @return Factory|View * @return Factory|View
*
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/ */
public function operations(Collection $accounts, Collection $double, Carbon $start, Carbon $end) public function operations(Collection $accounts, Collection $double, Carbon $start, Carbon $end)
{ {

View File

@ -147,6 +147,8 @@ class TagController extends Controller
/** /**
* @return Factory|View * @return Factory|View
*
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/ */
public function accounts(Collection $accounts, Collection $tags, Carbon $start, Carbon $end) public function accounts(Collection $accounts, Collection $tags, Carbon $start, Carbon $end)
{ {
@ -273,8 +275,8 @@ class TagController extends Controller
]; ];
++$result[$key]['transactions']; ++$result[$key]['transactions'];
$result[$key]['sum'] = bcadd($journal['amount'], $result[$key]['sum']); $result[$key]['sum'] = bcadd($journal['amount'], $result[$key]['sum']);
$result[$key]['avg'] = bcdiv($result[$key]['sum'], (string)$result[$key]['transactions']); $result[$key]['avg'] = bcdiv($result[$key]['sum'], (string) $result[$key]['transactions']);
$result[$key]['avg_float'] = (float)$result[$key]['avg']; $result[$key]['avg_float'] = (float) $result[$key]['avg'];
} }
} }
} }
@ -323,8 +325,8 @@ class TagController extends Controller
]; ];
++$result[$key]['transactions']; ++$result[$key]['transactions'];
$result[$key]['sum'] = bcadd($journal['amount'], $result[$key]['sum']); $result[$key]['sum'] = bcadd($journal['amount'], $result[$key]['sum']);
$result[$key]['avg'] = bcdiv($result[$key]['sum'], (string)$result[$key]['transactions']); $result[$key]['avg'] = bcdiv($result[$key]['sum'], (string) $result[$key]['transactions']);
$result[$key]['avg_float'] = (float)$result[$key]['avg']; $result[$key]['avg_float'] = (float) $result[$key]['avg'];
} }
} }
} }
@ -347,6 +349,8 @@ class TagController extends Controller
/** /**
* @return Factory|View * @return Factory|View
*
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/ */
public function tags(Collection $accounts, Collection $tags, Carbon $start, Carbon $end) public function tags(Collection $accounts, Collection $tags, Carbon $start, Carbon $end)
{ {
@ -466,7 +470,7 @@ class TagController extends Controller
$result[] = [ $result[] = [
'description' => $journal['description'], 'description' => $journal['description'],
'transaction_group_id' => $journal['transaction_group_id'], 'transaction_group_id' => $journal['transaction_group_id'],
'amount_float' => (float)$journal['amount'], 'amount_float' => (float) $journal['amount'],
'amount' => $journal['amount'], 'amount' => $journal['amount'],
'date' => $journal['date']->isoFormat($this->monthAndDayFormat), 'date' => $journal['date']->isoFormat($this->monthAndDayFormat),
'date_sort' => $journal['date']->format('Y-m-d'), 'date_sort' => $journal['date']->format('Y-m-d'),
@ -514,7 +518,7 @@ class TagController extends Controller
$result[] = [ $result[] = [
'description' => $journal['description'], 'description' => $journal['description'],
'transaction_group_id' => $journal['transaction_group_id'], 'transaction_group_id' => $journal['transaction_group_id'],
'amount_float' => (float)$journal['amount'], // intentional float. 'amount_float' => (float) $journal['amount'], // intentional float.
'amount' => $journal['amount'], 'amount' => $journal['amount'],
'date' => $journal['date']->isoFormat($this->monthAndDayFormat), 'date' => $journal['date']->isoFormat($this->monthAndDayFormat),
'date_sort' => $journal['date']->format('Y-m-d'), 'date_sort' => $journal['date']->format('Y-m-d'),

View File

@ -47,6 +47,8 @@ class RecurrenceFormRequest extends FormRequest
* Get the data required by the controller. * Get the data required by the controller.
* *
* @throws FireflyException * @throws FireflyException
*
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/ */
public function getAll(): array public function getAll(): array
{ {
@ -270,18 +272,18 @@ class RecurrenceFormRequest extends FormRequest
$throwError = true; $throwError = true;
if ('withdrawal' === $type) { if ('withdrawal' === $type) {
$throwError = false; $throwError = false;
$sourceId = (int)$data['source_id']; $sourceId = (int) $data['source_id'];
$destinationId = (int)$data['withdrawal_destination_id']; $destinationId = (int) $data['withdrawal_destination_id'];
} }
if ('deposit' === $type) { if ('deposit' === $type) {
$throwError = false; $throwError = false;
$sourceId = (int)$data['deposit_source_id']; $sourceId = (int) $data['deposit_source_id'];
$destinationId = (int)$data['destination_id']; $destinationId = (int) $data['destination_id'];
} }
if ('transfer' === $type) { if ('transfer' === $type) {
$throwError = false; $throwError = false;
$sourceId = (int)$data['source_id']; $sourceId = (int) $data['source_id'];
$destinationId = (int)$data['destination_id']; $destinationId = (int) $data['destination_id'];
} }
if (true === $throwError) { if (true === $throwError) {
throw new FireflyException(sprintf('Cannot handle transaction type "%s"', $this->convertString('transaction_type'))); throw new FireflyException(sprintf('Cannot handle transaction type "%s"', $this->convertString('transaction_type')));
@ -292,7 +294,7 @@ class RecurrenceFormRequest extends FormRequest
// do something with result: // do something with result:
if (false === $validSource) { if (false === $validSource) {
$message = (string)trans('validation.generic_invalid_source'); $message = (string) trans('validation.generic_invalid_source');
$validator->errors()->add('source_id', $message); $validator->errors()->add('source_id', $message);
$validator->errors()->add('deposit_source_id', $message); $validator->errors()->add('deposit_source_id', $message);
@ -303,7 +305,7 @@ class RecurrenceFormRequest extends FormRequest
$validDestination = $accountValidator->validateDestination(['id' => $destinationId]); $validDestination = $accountValidator->validateDestination(['id' => $destinationId]);
// do something with result: // do something with result:
if (false === $validDestination) { if (false === $validDestination) {
$message = (string)trans('validation.generic_invalid_destination'); $message = (string) trans('validation.generic_invalid_destination');
$validator->errors()->add('destination_id', $message); $validator->errors()->add('destination_id', $message);
$validator->errors()->add('withdrawal_destination_id', $message); $validator->errors()->add('withdrawal_destination_id', $message);
} }

View File

@ -54,6 +54,8 @@ class BudgetServiceProvider extends ServiceProvider
/** /**
* Register the application services. * Register the application services.
*
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/ */
public function register(): void public function register(): void
{ {

View File

@ -181,7 +181,6 @@ class CreditRecalculateService
} }
$startOfDebt = $this->repository->getOpeningBalanceAmount($account) ?? '0'; $startOfDebt = $this->repository->getOpeningBalanceAmount($account) ?? '0';
$leftOfDebt = app('steam')->positive($startOfDebt); $leftOfDebt = app('steam')->positive($startOfDebt);
$currency = $this->repository->getAccountCurrency($account);
app('log')->debug(sprintf('Start of debt is "%s", so initial left of debt is "%s"', app('steam')->bcround($startOfDebt, 2), app('steam')->bcround($leftOfDebt, 2))); app('log')->debug(sprintf('Start of debt is "%s", so initial left of debt is "%s"', app('steam')->bcround($startOfDebt, 2), app('steam')->bcround($leftOfDebt, 2)));
/** @var AccountMetaFactory $factory */ /** @var AccountMetaFactory $factory */
@ -243,6 +242,9 @@ class CreditRecalculateService
app('log')->debug('Opening balance is valid'); app('log')->debug('Opening balance is valid');
} }
/**
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
private function processTransaction(Account $account, string $direction, Transaction $transaction, string $leftOfDebt): string private function processTransaction(Account $account, string $direction, Transaction $transaction, string $leftOfDebt): string
{ {
$journal = $transaction->transactionJournal; $journal = $transaction->transactionJournal;
@ -313,14 +315,14 @@ class CreditRecalculateService
return $result; return $result;
} }
if($isSameAccount && $isDebit && $this->isDepositOut($usedAmount, $type)) { // case 7 if ($isSameAccount && $isDebit && $this->isDepositOut($usedAmount, $type)) { // case 7
$usedAmount = app('steam')->positive($usedAmount); $usedAmount = app('steam')->positive($usedAmount);
$result = bcadd($leftOfDebt, $usedAmount); $result = bcadd($leftOfDebt, $usedAmount);
app('log')->debug(sprintf('Case 7 (deposit away from liability): %s - %s = %s', app('steam')->bcround($leftOfDebt, 2), app('steam')->bcround($usedAmount, 2), app('steam')->bcround($result, 2))); app('log')->debug(sprintf('Case 7 (deposit away from liability): %s - %s = %s', app('steam')->bcround($leftOfDebt, 2), app('steam')->bcround($usedAmount, 2), app('steam')->bcround($result, 2)));
return $result; return $result;
} }
if($isSameAccount && $isDebit && $this->isWithdrawalOut($usedAmount, $type)) { // case 8 if ($isSameAccount && $isDebit && $this->isWithdrawalOut($usedAmount, $type)) { // case 8
$usedAmount = app('steam')->positive($usedAmount); $usedAmount = app('steam')->positive($usedAmount);
$result = bcadd($leftOfDebt, $usedAmount); $result = bcadd($leftOfDebt, $usedAmount);
app('log')->debug(sprintf('Case 8 (withdrawal away from liability): %s + %s = %s', app('steam')->bcround($leftOfDebt, 2), app('steam')->bcround($usedAmount, 2), app('steam')->bcround($result, 2))); app('log')->debug(sprintf('Case 8 (withdrawal away from liability): %s + %s = %s', app('steam')->bcround($leftOfDebt, 2), app('steam')->bcround($usedAmount, 2), app('steam')->bcround($result, 2)));

View File

@ -44,6 +44,11 @@ class StandardWebhookSender implements WebhookSenderInterface
return $this->version; return $this->version;
} }
/**
* @throws \GuzzleHttp\Exception\GuzzleException
*
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function send(): void public function send(): void
{ {
// have the signature generator generate a signature. If it fails, the error thrown will // have the signature generator generate a signature. If it fails, the error thrown will

View File

@ -92,9 +92,6 @@ class Amount
return $user->currencies()->orderBy('code', 'ASC')->get(); return $user->currencies()->orderBy('code', 'ASC')->get();
} }
/**
* @throws FireflyException
*/
public function getDefaultCurrency(): TransactionCurrency public function getDefaultCurrency(): TransactionCurrency
{ {
/** @var User $user */ /** @var User $user */

View File

@ -577,39 +577,12 @@ class ExportDataGenerator
$recurringRepos->setUser($this->user); $recurringRepos->setUser($this->user);
$header = [ $header = [
// recurrence: // recurrence:
'user_id', 'user_id', 'recurrence_id', 'row_contains', 'created_at', 'updated_at', 'type', 'title', 'description', 'first_date', 'repeat_until', 'latest_date', 'repetitions', 'apply_rules', 'active',
'recurrence_id',
'row_contains',
'created_at',
'updated_at',
'type',
'title',
'description',
'first_date',
'repeat_until',
'latest_date',
'repetitions',
'apply_rules',
'active',
// repetition info: // repetition info:
'type', 'type', 'moment', 'skip', 'weekend',
'moment',
'skip',
'weekend',
// transactions + meta: // transactions + meta:
'currency_code', 'currency_code', 'foreign_currency_code', 'source_name', 'source_type', 'destination_name', 'destination_type', 'amount', 'foreign_amount', 'category', 'budget', 'piggy_bank', 'tags',
'foreign_currency_code',
'source_name',
'source_type',
'destination_name',
'destination_type',
'amount',
'foreign_amount',
'category',
'budget',
'piggy_bank',
'tags',
]; ];
$records = []; $records = [];
$recurrences = $recurringRepos->getAll(); $recurrences = $recurringRepos->getAll();
@ -618,20 +591,9 @@ class ExportDataGenerator
foreach ($recurrences as $recurrence) { foreach ($recurrences as $recurrence) {
// add recurrence: // add recurrence:
$records[] = [ $records[] = [
$this->user->id, $this->user->id, $recurrence->id,
$recurrence->id,
'recurrence', 'recurrence',
$recurrence->created_at->toAtomString(), $recurrence->created_at->toAtomString(), $recurrence->updated_at->toAtomString(), $recurrence->transactionType->type, $recurrence->title, $recurrence->description, $recurrence->first_date?->format('Y-m-d'), $recurrence->repeat_until?->format('Y-m-d'), $recurrence->latest_date?->format('Y-m-d'), $recurrence->repetitions, $recurrence->apply_rules, $recurrence->active,
$recurrence->updated_at->toAtomString(),
$recurrence->transactionType->type,
$recurrence->title,
$recurrence->description,
$recurrence->first_date?->format('Y-m-d'),
$recurrence->repeat_until?->format('Y-m-d'),
$recurrence->latest_date?->format('Y-m-d'),
$recurrence->repetitions,
$recurrence->apply_rules,
$recurrence->active,
]; ];
// add new row for each repetition // add new row for each repetition
@ -642,23 +604,10 @@ class ExportDataGenerator
$this->user->id, $this->user->id,
$recurrence->id, $recurrence->id,
'repetition', 'repetition',
null, null, null, null, null, null, null, null, null, null, null, null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
// repetition: // repetition:
$repetition->repetition_type, $repetition->repetition_type, $repetition->repetition_moment, $repetition->repetition_skip, $repetition->weekend,
$repetition->repetition_moment,
$repetition->repetition_skip,
$repetition->weekend,
]; ];
} }
@ -674,37 +623,13 @@ class ExportDataGenerator
$this->user->id, $this->user->id,
$recurrence->id, $recurrence->id,
'transaction', 'transaction',
null, null, null, null, null, null, null, null, null, null, null, null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
// repetition: // repetition:
null, null, null, null, null,
null,
null,
null,
// transaction: // transaction:
$transaction->transactionCurrency->code, $transaction->transactionCurrency->code, $transaction->foreignCurrency?->code, $transaction->sourceAccount->name, $transaction->sourceAccount->accountType->type, $transaction->destinationAccount->name, $transaction->destinationAccount->accountType->type, $transaction->amount, $transaction->foreign_amount, $categoryName, $budgetId, $piggyBankId, implode(',', $tags),
$transaction->foreignCurrency?->code,
$transaction->sourceAccount->name,
$transaction->sourceAccount->accountType->type,
$transaction->destinationAccount->name,
$transaction->destinationAccount->accountType->type,
$transaction->amount,
$transaction->foreign_amount,
$categoryName,
$budgetId,
$piggyBankId,
implode(',', $tags),
]; ];
} }
} }
@ -739,31 +664,7 @@ class ExportDataGenerator
*/ */
private function exportRules(): string private function exportRules(): string
{ {
$header = [ $header = ['user_id', 'rule_id', 'row_contains', 'created_at', 'updated_at', 'group_id', 'title', 'description', 'order', 'active', 'stop_processing', 'strict', 'trigger_type', 'trigger_value', 'trigger_order', 'trigger_active', 'trigger_stop_processing', 'action_type', 'action_value', 'action_order', 'action_active', 'action_stop_processing'];
'user_id',
'rule_id',
'row_contains',
'created_at',
'updated_at',
'group_id',
'group_name',
'title',
'description',
'order',
'active',
'stop_processing',
'strict',
'trigger_type',
'trigger_value',
'trigger_order',
'trigger_active',
'trigger_stop_processing',
'action_type',
'action_value',
'action_order',
'action_active',
'action_stop_processing',
];
$ruleRepos = app(RuleRepositoryInterface::class); $ruleRepos = app(RuleRepositoryInterface::class);
$ruleRepos->setUser($this->user); $ruleRepos->setUser($this->user);
$rules = $ruleRepos->getAll(); $rules = $ruleRepos->getAll();
@ -772,19 +673,9 @@ class ExportDataGenerator
/** @var Rule $rule */ /** @var Rule $rule */
foreach ($rules as $rule) { foreach ($rules as $rule) {
$records[] = [ $records[] = [
$this->user->id, $this->user->id, $rule->id,
$rule->id,
'rule', 'rule',
$rule->created_at->toAtomString(), $rule->created_at->toAtomString(), $rule->updated_at->toAtomString(), $rule->ruleGroup->id, $rule->ruleGroup->title, $rule->title, $rule->description, $rule->order, $rule->active, $rule->stop_processing, $rule->strict,
$rule->updated_at->toAtomString(),
$rule->ruleGroup->id,
$rule->ruleGroup->title,
$rule->title,
$rule->description,
$rule->order,
$rule->active,
$rule->stop_processing,
$rule->strict,
]; ];
/** @var RuleTrigger $trigger */ /** @var RuleTrigger $trigger */
@ -793,21 +684,8 @@ class ExportDataGenerator
$this->user->id, $this->user->id,
$rule->id, $rule->id,
'trigger', 'trigger',
null, null, null, null, null, null, null, null, null, null, null,
null, $trigger->trigger_type, $trigger->trigger_value, $trigger->order, $trigger->active, $trigger->stop_processing,
null,
null,
null,
null,
null,
null,
null,
null,
$trigger->trigger_type,
$trigger->trigger_value,
$trigger->order,
$trigger->active,
$trigger->stop_processing,
]; ];
} }
@ -817,26 +695,8 @@ class ExportDataGenerator
$this->user->id, $this->user->id,
$rule->id, $rule->id,
'action', 'action',
null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null,
null, $action->action_type, $action->action_value, $action->order, $action->active, $action->stop_processing,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
$action->action_type,
$action->action_value,
$action->order,
$action->active,
$action->stop_processing,
]; ];
} }
} }
@ -927,34 +787,7 @@ class ExportDataGenerator
private function exportTransactions(): string private function exportTransactions(): string
{ {
// TODO better place for keys? // TODO better place for keys?
$header = [ $header = ['user_id', 'group_id', 'journal_id', 'created_at', 'updated_at', 'group_title', 'type', 'amount', 'foreign_amount', 'currency_code', 'foreign_currency_code', 'description', 'date', 'source_name', 'source_iban', 'source_type', 'destination_name', 'destination_iban', 'destination_type', 'reconciled', 'category', 'budget', 'bill', 'tags', 'notes'];
'user_id',
'group_id',
'journal_id',
'created_at',
'updated_at',
'group_title',
'type',
'amount',
'foreign_amount',
'currency_code',
'foreign_currency_code',
'description',
'date',
'source_name',
'source_iban',
'source_type',
'destination_name',
'destination_iban',
'destination_type',
'reconciled',
'category',
'budget',
'bill',
'tags',
'notes',
// all optional meta fields:
];
$metaFields = config('firefly.journal_meta_fields'); $metaFields = config('firefly.journal_meta_fields');
$header = array_merge($header, $metaFields); $header = array_merge($header, $metaFields);
@ -980,65 +813,21 @@ class ExportDataGenerator
foreach ($journals as $journal) { foreach ($journals as $journal) {
$metaData = $repository->getMetaFields($journal['transaction_journal_id'], $metaFields); $metaData = $repository->getMetaFields($journal['transaction_journal_id'], $metaFields);
$records[] = [ $records[] = [
$journal['user_id'], $journal['user_id'], $journal['transaction_group_id'], $journal['transaction_journal_id'], $journal['created_at']->toAtomString(), $journal['updated_at']->toAtomString(), $journal['transaction_group_title'], $journal['transaction_type_type'], $journal['amount'], $journal['foreign_amount'], $journal['currency_code'], $journal['foreign_currency_code'], $journal['description'], $journal['date']->toAtomString(), $journal['source_account_name'], $journal['source_account_iban'], $journal['source_account_type'], $journal['destination_account_name'], $journal['destination_account_iban'], $journal['destination_account_type'], $journal['reconciled'], $journal['category_name'], $journal['budget_name'], $journal['bill_name'],
$journal['transaction_group_id'],
$journal['transaction_journal_id'],
$journal['created_at']->toAtomString(),
$journal['updated_at']->toAtomString(),
$journal['transaction_group_title'],
$journal['transaction_type_type'],
$journal['amount'],
$journal['foreign_amount'],
$journal['currency_code'],
$journal['foreign_currency_code'],
$journal['description'],
$journal['date']->toAtomString(),
$journal['source_account_name'],
$journal['source_account_iban'],
$journal['source_account_type'],
$journal['destination_account_name'],
$journal['destination_account_iban'],
$journal['destination_account_type'],
$journal['reconciled'],
$journal['category_name'],
$journal['budget_name'],
$journal['bill_name'],
$this->mergeTags($journal['tags']), $this->mergeTags($journal['tags']),
$this->clearStringKeepNewlines($journal['notes']), $this->clearStringKeepNewlines($journal['notes']),
// export also the optional fields (ALL)
// sepa // sepa
$metaData['sepa_cc'], $metaData['sepa_cc'], $metaData['sepa_ct_op'], $metaData['sepa_ct_id'], $metaData['sepa_db'], $metaData['sepa_country'], $metaData['sepa_ep'], $metaData['sepa_ci'], $metaData['sepa_batch_id'], $metaData['external_url'],
$metaData['sepa_ct_op'],
$metaData['sepa_ct_id'],
$metaData['sepa_db'],
$metaData['sepa_country'],
$metaData['sepa_ep'],
$metaData['sepa_ci'],
$metaData['sepa_batch_id'],
$metaData['external_url'],
// dates // dates
$metaData['interest_date'], $metaData['interest_date'], $metaData['book_date'], $metaData['process_date'], $metaData['due_date'], $metaData['payment_date'], $metaData['invoice_date'],
$metaData['book_date'],
$metaData['process_date'],
$metaData['due_date'],
$metaData['payment_date'],
$metaData['invoice_date'],
// others // others
$metaData['recurrence_id'], $metaData['recurrence_id'], $metaData['internal_reference'], $metaData['bunq_payment_id'], $metaData['import_hash'], $metaData['import_hash_v2'], $metaData['external_id'], $metaData['original_source'],
$metaData['internal_reference'],
$metaData['bunq_payment_id'],
$metaData['import_hash'],
$metaData['import_hash_v2'],
$metaData['external_id'],
$metaData['original_source'],
// recurring transactions // recurring transactions
$metaData['recurrence_total'], $metaData['recurrence_total'], $metaData['recurrence_count'],
$metaData['recurrence_count'],
]; ];
} }

View File

@ -84,9 +84,9 @@ trait ModelInformation
/** @var AccountType $mortgage */ /** @var AccountType $mortgage */
$mortgage = $repository->getAccountTypeByType(AccountType::MORTGAGE); $mortgage = $repository->getAccountTypeByType(AccountType::MORTGAGE);
$liabilityTypes = [ $liabilityTypes = [
$debt->id => (string)trans(sprintf('firefly.account_type_%s', AccountType::DEBT)), $debt->id => (string) trans(sprintf('firefly.account_type_%s', AccountType::DEBT)),
$loan->id => (string)trans(sprintf('firefly.account_type_%s', AccountType::LOAN)), $loan->id => (string) trans(sprintf('firefly.account_type_%s', AccountType::LOAN)),
$mortgage->id => (string)trans(sprintf('firefly.account_type_%s', AccountType::MORTGAGE)), $mortgage->id => (string) trans(sprintf('firefly.account_type_%s', AccountType::MORTGAGE)),
]; ];
asort($liabilityTypes); asort($liabilityTypes);
@ -97,7 +97,7 @@ trait ModelInformation
{ {
$roles = []; $roles = [];
foreach (config('firefly.accountRoles') as $role) { foreach (config('firefly.accountRoles') as $role) {
$roles[$role] = (string)trans(sprintf('firefly.account_role_%s', $role)); $roles[$role] = (string) trans(sprintf('firefly.account_role_%s', $role));
} }
return $roles; return $roles;
@ -115,7 +115,7 @@ trait ModelInformation
$triggers = []; $triggers = [];
foreach ($operators as $key => $operator) { foreach ($operators as $key => $operator) {
if ('user_action' !== $key && false === $operator['alias']) { if ('user_action' !== $key && false === $operator['alias']) {
$triggers[$key] = (string)trans(sprintf('firefly.rule_trigger_%s_choice', $key)); $triggers[$key] = (string) trans(sprintf('firefly.rule_trigger_%s_choice', $key));
} }
} }
asort($triggers); asort($triggers);
@ -156,6 +156,8 @@ trait ModelInformation
/** /**
* @throws FireflyException * @throws FireflyException
*
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/ */
private function getTriggersForJournal(TransactionJournal $journal): array private function getTriggersForJournal(TransactionJournal $journal): array
{ {
@ -164,7 +166,7 @@ trait ModelInformation
$triggers = []; $triggers = [];
foreach ($operators as $key => $operator) { foreach ($operators as $key => $operator) {
if ('user_action' !== $key && false === $operator['alias']) { if ('user_action' !== $key && false === $operator['alias']) {
$triggers[$key] = (string)trans(sprintf('firefly.rule_trigger_%s_choice', $key)); $triggers[$key] = (string) trans(sprintf('firefly.rule_trigger_%s_choice', $key));
} }
} }
asort($triggers); asort($triggers);

View File

@ -215,6 +215,8 @@ class Steam
/** /**
* @throws FireflyException * @throws FireflyException
*
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/ */
public function balanceInRangeConverted(Account $account, Carbon $start, Carbon $end, TransactionCurrency $native): array public function balanceInRangeConverted(Account $account, Carbon $start, Carbon $end, TransactionCurrency $native): array
{ {
@ -317,22 +319,36 @@ class Steam
} }
/** /**
* selection of transactions
* 1: all normal transactions. No foreign currency info. In $currency. Need conversion.
* 2: all normal transactions. No foreign currency info. In $native. Need NO conversion.
* 3: all normal transactions. No foreign currency info. In neither currency. Need conversion.
* Then, select everything with foreign currency info:
* 4. All transactions with foreign currency info in $native. Normal currency value is ignored. Do not need
* conversion.
* 5. All transactions with foreign currency info NOT in $native, but currency info in $currency. Need conversion.
* 6. All transactions with foreign currency info NOT in $native, and currency info NOT in $currency. Need
* conversion.
*
* Gets balance at the end of current month by default. Returns the balance converted * Gets balance at the end of current month by default. Returns the balance converted
* to the indicated currency ($native). * to the indicated currency ($native).
* *
* @throws FireflyException * @throws FireflyException
*
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/ */
public function balanceConverted(Account $account, Carbon $date, TransactionCurrency $native): string public function balanceConverted(Account $account, Carbon $date, TransactionCurrency $native): string
{ {
// app('log')->debug(sprintf('Now in balanceConverted (%s) for account #%d, converting to %s', $date->format('Y-m-d'), $account->id, $native->code)); app('log')->debug(sprintf('Now in balanceConverted (%s) for account #%d, converting to %s', $date->format('Y-m-d'), $account->id, $native->code));
$cache = new CacheProperties(); $cache = new CacheProperties();
$cache->addProperty($account->id); $cache->addProperty($account->id);
$cache->addProperty('balance'); $cache->addProperty('balance');
$cache->addProperty($date); $cache->addProperty($date);
$cache->addProperty($native->id); $cache->addProperty($native->id);
if ($cache->has()) { if ($cache->has()) {
// Log::debug('Cached!'); Log::debug('Cached!');
// return $cache->get();
return $cache->get();
} }
/** @var AccountRepositoryInterface $repository */ /** @var AccountRepositoryInterface $repository */
@ -344,20 +360,9 @@ class Steam
return $this->balance($account, $date); return $this->balance($account, $date);
} }
/**
* selection of transactions
* 1: all normal transactions. No foreign currency info. In $currency. Need conversion.
* 2: all normal transactions. No foreign currency info. In $native. Need NO conversion.
* 3: all normal transactions. No foreign currency info. In neither currency. Need conversion.
* Then, select everything with foreign currency info:
* 4. All transactions with foreign currency info in $native. Normal currency value is ignored. Do not need conversion.
* 5. All transactions with foreign currency info NOT in $native, but currency info in $currency. Need conversion.
* 6. All transactions with foreign currency info NOT in $native, and currency info NOT in $currency. Need conversion.
*/
$new = []; $new = [];
$existing = []; $existing = [];
// 1 $new[] = $account->transactions() // 1
$new[] = $account->transactions()
->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id') ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id')
->where('transaction_journals.date', '<=', $date->format('Y-m-d 23:59:59')) ->where('transaction_journals.date', '<=', $date->format('Y-m-d 23:59:59'))
->where('transactions.transaction_currency_id', $currency->id) ->where('transactions.transaction_currency_id', $currency->id)
@ -365,8 +370,7 @@ class Steam
->get(['transaction_journals.date', 'transactions.amount'])->toArray() ->get(['transaction_journals.date', 'transactions.amount'])->toArray()
; ;
app('log')->debug(sprintf('%d transaction(s) in set #1', count($new[0]))); app('log')->debug(sprintf('%d transaction(s) in set #1', count($new[0])));
// 2 $existing[] = $account->transactions() // 2
$existing[] = $account->transactions()
->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id') ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id')
->where('transaction_journals.date', '<=', $date->format('Y-m-d 23:59:59')) ->where('transaction_journals.date', '<=', $date->format('Y-m-d 23:59:59'))
->where('transactions.transaction_currency_id', $native->id) ->where('transactions.transaction_currency_id', $native->id)
@ -374,8 +378,7 @@ class Steam
->get(['transactions.amount'])->toArray() ->get(['transactions.amount'])->toArray()
; ;
app('log')->debug(sprintf('%d transaction(s) in set #2', count($existing[0]))); app('log')->debug(sprintf('%d transaction(s) in set #2', count($existing[0])));
// 3 $new[] = $account->transactions() // 3
$new[] = $account->transactions()
->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id') ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id')
->where('transaction_journals.date', '<=', $date->format('Y-m-d 23:59:59')) ->where('transaction_journals.date', '<=', $date->format('Y-m-d 23:59:59'))
->where('transactions.transaction_currency_id', '!=', $currency->id) ->where('transactions.transaction_currency_id', '!=', $currency->id)
@ -384,8 +387,7 @@ class Steam
->get(['transaction_journals.date', 'transactions.amount'])->toArray() ->get(['transaction_journals.date', 'transactions.amount'])->toArray()
; ;
app('log')->debug(sprintf('%d transactions in set #3', count($new[1]))); app('log')->debug(sprintf('%d transactions in set #3', count($new[1])));
// 4 $existing[] = $account->transactions() // 4
$existing[] = $account->transactions()
->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id') ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id')
->where('transaction_journals.date', '<=', $date->format('Y-m-d 23:59:59')) ->where('transaction_journals.date', '<=', $date->format('Y-m-d 23:59:59'))
->where('transactions.foreign_currency_id', $native->id) ->where('transactions.foreign_currency_id', $native->id)
@ -393,8 +395,7 @@ class Steam
->get(['transactions.foreign_amount'])->toArray() ->get(['transactions.foreign_amount'])->toArray()
; ;
app('log')->debug(sprintf('%d transactions in set #4', count($existing[1]))); app('log')->debug(sprintf('%d transactions in set #4', count($existing[1])));
// 5 $new[] = $account->transactions()// 5
$new[] = $account->transactions()
->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id') ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id')
->where('transaction_journals.date', '<=', $date->format('Y-m-d 23:59:59')) ->where('transaction_journals.date', '<=', $date->format('Y-m-d 23:59:59'))
->where('transactions.transaction_currency_id', $currency->id) ->where('transactions.transaction_currency_id', $currency->id)
@ -403,8 +404,7 @@ class Steam
->get(['transaction_journals.date', 'transactions.amount'])->toArray() ->get(['transaction_journals.date', 'transactions.amount'])->toArray()
; ;
app('log')->debug(sprintf('%d transactions in set #5', count($new[2]))); app('log')->debug(sprintf('%d transactions in set #5', count($new[2])));
// 6 $new[] = $account->transactions()// 6
$new[] = $account->transactions()
->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id') ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id')
->where('transaction_journals.date', '<=', $date->format('Y-m-d 23:59:59')) ->where('transaction_journals.date', '<=', $date->format('Y-m-d 23:59:59'))
->where('transactions.transaction_currency_id', '!=', $currency->id) ->where('transactions.transaction_currency_id', '!=', $currency->id)

View File

@ -49,6 +49,9 @@ class ConvertToTransfer implements ActionInterface
$this->action = $action; $this->action = $action;
} }
/**
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function actOnArray(array $journal): bool public function actOnArray(array $journal): bool
{ {
// make object from array (so the data is fresh). // make object from array (so the data is fresh).
@ -162,7 +165,7 @@ class ConvertToTransfer implements ActionInterface
return ''; return '';
} }
return (string)$journal->transactions()->where('amount', '<', 0)->first()?->account?->accountType?->type; return (string) $journal->transactions()->where('amount', '<', 0)->first()?->account?->accountType?->type;
} }
private function getDestinationType(int $journalId): string private function getDestinationType(int $journalId): string
@ -175,7 +178,7 @@ class ConvertToTransfer implements ActionInterface
return ''; return '';
} }
return (string)$journal->transactions()->where('amount', '>', 0)->first()?->account?->accountType?->type; return (string) $journal->transactions()->where('amount', '>', 0)->first()?->account?->accountType?->type;
} }
/** /**

View File

@ -51,24 +51,23 @@ class BillTransformer extends AbstractTransformer
/** /**
* Transform the bill. * Transform the bill.
*
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/ */
public function transform(Bill $bill): array public function transform(Bill $bill): array
{ {
$paidData = $this->paidData($bill); $paidData = $this->paidData($bill);
$lastPaidDate = $this->getLastPaidDate($paidData); $lastPaidDate = $this->getLastPaidDate($paidData);
$start = $this->parameters->get('start') ?? today()->subYears(10);
// both params can be NULL, so just in case they are, add some wide margins: $end = $this->parameters->get('end') ?? today()->addYears(10);
$start = $this->parameters->get('start') ?? today()->subYears(10); $payDates = $this->calculator->getPayDates($start, $end, $bill->date, $bill->repeat_freq, $bill->skip, $lastPaidDate);
$end = $this->parameters->get('end') ?? today()->addYears(10); $currency = $bill->transactionCurrency;
$payDates = $this->calculator->getPayDates($start, $end, $bill->date, $bill->repeat_freq, $bill->skip, $lastPaidDate); $notes = $this->repository->getNoteText($bill);
$currency = $bill->transactionCurrency; $notes = '' === $notes ? null : $notes;
$notes = $this->repository->getNoteText($bill);
$notes = '' === $notes ? null : $notes;
$this->repository->setUser($bill->user);
$objectGroupId = null; $objectGroupId = null;
$objectGroupOrder = null; $objectGroupOrder = null;
$objectGroupTitle = null; $objectGroupTitle = null;
$this->repository->setUser($bill->user);
/** @var null|ObjectGroup $objectGroup */ /** @var null|ObjectGroup $objectGroup */
$objectGroup = $bill->objectGroups->first(); $objectGroup = $bill->objectGroups->first();
@ -138,7 +137,7 @@ class BillTransformer extends AbstractTransformer
'id' => $bill->id, 'id' => $bill->id,
'created_at' => $bill->created_at->toAtomString(), 'created_at' => $bill->created_at->toAtomString(),
'updated_at' => $bill->updated_at->toAtomString(), 'updated_at' => $bill->updated_at->toAtomString(),
'currency_id' => (string)$bill->transaction_currency_id, 'currency_id' => (string) $bill->transaction_currency_id,
'currency_code' => $currency->code, 'currency_code' => $currency->code,
'currency_symbol' => $currency->symbol, 'currency_symbol' => $currency->symbol,
'currency_decimal_places' => $currency->decimal_places, 'currency_decimal_places' => $currency->decimal_places,
@ -153,7 +152,7 @@ class BillTransformer extends AbstractTransformer
'active' => $bill->active, 'active' => $bill->active,
'order' => $bill->order, 'order' => $bill->order,
'notes' => $notes, 'notes' => $notes,
'object_group_id' => null !== $objectGroupId ? (string)$objectGroupId : null, 'object_group_id' => null !== $objectGroupId ? (string) $objectGroupId : null,
'object_group_order' => $objectGroupOrder, 'object_group_order' => $objectGroupOrder,
'object_group_title' => $objectGroupTitle, 'object_group_title' => $objectGroupTitle,
@ -207,8 +206,8 @@ class BillTransformer extends AbstractTransformer
$result = []; $result = [];
foreach ($set as $entry) { foreach ($set as $entry) {
$result[] = [ $result[] = [
'transaction_group_id' => (string)$entry->transaction_group_id, 'transaction_group_id' => (string) $entry->transaction_group_id,
'transaction_journal_id' => (string)$entry->id, 'transaction_journal_id' => (string) $entry->id,
'date' => $entry->date->format('Y-m-d'), 'date' => $entry->date->format('Y-m-d'),
'date_object' => $entry->date, 'date_object' => $entry->date,
]; ];

View File

@ -80,10 +80,10 @@ class TransactionGroupTransformer extends AbstractTransformer
$first = new NullArrayObject(reset($group['transactions'])); $first = new NullArrayObject(reset($group['transactions']));
return [ return [
'id' => (int)$first['transaction_group_id'], 'id' => (int) $first['transaction_group_id'],
'created_at' => $first['created_at']->toAtomString(), 'created_at' => $first['created_at']->toAtomString(),
'updated_at' => $first['updated_at']->toAtomString(), 'updated_at' => $first['updated_at']->toAtomString(),
'user' => (string)$data['user_id'], 'user' => (string) $data['user_id'],
'group_title' => $data['title'], 'group_title' => $data['title'],
'transactions' => $this->transformTransactions($data), 'transactions' => $this->transformTransactions($data),
'links' => [ 'links' => [
@ -138,25 +138,28 @@ class TransactionGroupTransformer extends AbstractTransformer
return $result; return $result;
} }
/**
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
private function transformTransaction(array $transaction): array private function transformTransaction(array $transaction): array
{ {
$row = new NullArrayObject($transaction); $row = new NullArrayObject($transaction);
// amount: // amount:
$amount = app('steam')->positive((string)($row['amount'] ?? '0')); $amount = app('steam')->positive((string) ($row['amount'] ?? '0'));
$foreignAmount = null; $foreignAmount = null;
if (null !== $row['foreign_amount'] && '' !== $row['foreign_amount'] && 0 !== bccomp('0', $row['foreign_amount'])) { if (null !== $row['foreign_amount'] && '' !== $row['foreign_amount'] && 0 !== bccomp('0', $row['foreign_amount'])) {
$foreignAmount = app('steam')->positive($row['foreign_amount']); $foreignAmount = app('steam')->positive($row['foreign_amount']);
} }
$metaFieldData = $this->groupRepos->getMetaFields((int)$row['transaction_journal_id'], $this->metaFields); $metaFieldData = $this->groupRepos->getMetaFields((int) $row['transaction_journal_id'], $this->metaFields);
$metaDateData = $this->groupRepos->getMetaDateFields((int)$row['transaction_journal_id'], $this->metaDateFields); $metaDateData = $this->groupRepos->getMetaDateFields((int) $row['transaction_journal_id'], $this->metaDateFields);
$type = $this->stringFromArray($transaction, 'transaction_type_type', TransactionType::WITHDRAWAL); $type = $this->stringFromArray($transaction, 'transaction_type_type', TransactionType::WITHDRAWAL);
$longitude = null; $longitude = null;
$latitude = null; $latitude = null;
$zoomLevel = null; $zoomLevel = null;
$location = $this->getLocationById((int)$row['transaction_journal_id']); $location = $this->getLocationById((int) $row['transaction_journal_id']);
if (null !== $location) { if (null !== $location) {
$longitude = $location->longitude; $longitude = $location->longitude;
$latitude = $location->latitude; $latitude = $location->latitude;
@ -164,17 +167,17 @@ class TransactionGroupTransformer extends AbstractTransformer
} }
return [ return [
'user' => (string)$row['user_id'], 'user' => (string) $row['user_id'],
'transaction_journal_id' => (string)$row['transaction_journal_id'], 'transaction_journal_id' => (string) $row['transaction_journal_id'],
'type' => strtolower($type), 'type' => strtolower($type),
'date' => $row['date']->toAtomString(), 'date' => $row['date']->toAtomString(),
'order' => $row['order'], 'order' => $row['order'],
'currency_id' => (string)$row['currency_id'], 'currency_id' => (string) $row['currency_id'],
'currency_code' => $row['currency_code'], 'currency_code' => $row['currency_code'],
'currency_name' => $row['currency_name'], 'currency_name' => $row['currency_name'],
'currency_symbol' => $row['currency_symbol'], 'currency_symbol' => $row['currency_symbol'],
'currency_decimal_places' => (int)$row['currency_decimal_places'], 'currency_decimal_places' => (int) $row['currency_decimal_places'],
'foreign_currency_id' => $this->stringFromArray($transaction, 'foreign_currency_id', null), 'foreign_currency_id' => $this->stringFromArray($transaction, 'foreign_currency_id', null),
'foreign_currency_code' => $row['foreign_currency_code'], 'foreign_currency_code' => $row['foreign_currency_code'],
@ -186,12 +189,12 @@ class TransactionGroupTransformer extends AbstractTransformer
'description' => $row['description'], 'description' => $row['description'],
'source_id' => (string)$row['source_account_id'], 'source_id' => (string) $row['source_account_id'],
'source_name' => $row['source_account_name'], 'source_name' => $row['source_account_name'],
'source_iban' => $row['source_account_iban'], 'source_iban' => $row['source_account_iban'],
'source_type' => $row['source_account_type'], 'source_type' => $row['source_account_type'],
'destination_id' => (string)$row['destination_account_id'], 'destination_id' => (string) $row['destination_account_id'],
'destination_name' => $row['destination_account_name'], 'destination_name' => $row['destination_account_name'],
'destination_iban' => $row['destination_account_iban'], 'destination_iban' => $row['destination_account_iban'],
'destination_type' => $row['destination_account_type'], 'destination_type' => $row['destination_account_type'],
@ -206,8 +209,8 @@ class TransactionGroupTransformer extends AbstractTransformer
'bill_name' => $row['bill_name'], 'bill_name' => $row['bill_name'],
'reconciled' => $row['reconciled'], 'reconciled' => $row['reconciled'],
'notes' => $this->groupRepos->getNoteText((int)$row['transaction_journal_id']), 'notes' => $this->groupRepos->getNoteText((int) $row['transaction_journal_id']),
'tags' => $this->groupRepos->getTags((int)$row['transaction_journal_id']), 'tags' => $this->groupRepos->getTags((int) $row['transaction_journal_id']),
'internal_reference' => $metaFieldData['internal_reference'], 'internal_reference' => $metaFieldData['internal_reference'],
'external_id' => $metaFieldData['external_id'], 'external_id' => $metaFieldData['external_id'],
@ -240,7 +243,7 @@ class TransactionGroupTransformer extends AbstractTransformer
'latitude' => $latitude, 'latitude' => $latitude,
'zoom_level' => $zoomLevel, 'zoom_level' => $zoomLevel,
'has_attachments' => $this->hasAttachments((int)$row['transaction_journal_id']), 'has_attachments' => $this->hasAttachments((int) $row['transaction_journal_id']),
]; ];
} }
@ -257,7 +260,7 @@ class TransactionGroupTransformer extends AbstractTransformer
return $default; return $default;
} }
return (string)$array[$key]; return (string) $array[$key];
} }
if (null !== $default) { if (null !== $default) {
@ -280,7 +283,7 @@ class TransactionGroupTransformer extends AbstractTransformer
private function integerFromArray(array $array, string $key): ?int private function integerFromArray(array $array, string $key): ?int
{ {
if (array_key_exists($key, $array)) { if (array_key_exists($key, $array)) {
return (int)$array[$key]; return (int) $array[$key];
} }
return null; return null;
@ -317,6 +320,8 @@ class TransactionGroupTransformer extends AbstractTransformer
/** /**
* @throws FireflyException * @throws FireflyException
*
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/ */
private function transformJournal(TransactionJournal $journal): array private function transformJournal(TransactionJournal $journal): array
{ {
@ -429,7 +434,7 @@ class TransactionGroupTransformer extends AbstractTransformer
{ {
$result = $journal->transactions->first( $result = $journal->transactions->first(
static function (Transaction $transaction) { static function (Transaction $transaction) {
return (float)$transaction->amount < 0; // lame but it works. return (float) $transaction->amount < 0; // lame but it works.
} }
); );
if (null === $result) { if (null === $result) {
@ -446,7 +451,7 @@ class TransactionGroupTransformer extends AbstractTransformer
{ {
$result = $journal->transactions->first( $result = $journal->transactions->first(
static function (Transaction $transaction) { static function (Transaction $transaction) {
return (float)$transaction->amount > 0; // lame but it works return (float) $transaction->amount > 0; // lame but it works
} }
); );
if (null === $result) { if (null === $result) {
@ -550,7 +555,7 @@ class TransactionGroupTransformer extends AbstractTransformer
if (null === $bill) { if (null === $bill) {
return $array; return $array;
} }
$array['id'] = (string)$bill->id; $array['id'] = (string) $bill->id;
$array['name'] = $bill->name; $array['name'] = $bill->name;
return $array; return $array;

View File

@ -47,6 +47,11 @@ class BillTransformer extends AbstractTransformer
private array $notes; private array $notes;
private array $paidDates; private array $paidDates;
/**
* @throws \FireflyIII\Exceptions\FireflyException
*
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function collectMetaData(Collection $objects): void public function collectMetaData(Collection $objects): void
{ {
$currencies = []; $currencies = [];
@ -55,7 +60,6 @@ class BillTransformer extends AbstractTransformer
$this->groups = []; $this->groups = [];
$this->paidDates = []; $this->paidDates = [];
// start with currencies:
/** @var Bill $object */ /** @var Bill $object */
foreach ($objects as $object) { foreach ($objects as $object) {
$id = $object->transaction_currency_id; $id = $object->transaction_currency_id;
@ -63,9 +67,7 @@ class BillTransformer extends AbstractTransformer
$currencies[$id] ??= TransactionCurrency::find($id); $currencies[$id] ??= TransactionCurrency::find($id);
} }
$this->currencies = $currencies; $this->currencies = $currencies;
$notes = Note::whereNoteableType(Bill::class)->whereIn('noteable_id', array_keys($bills))->get();
// continue with notes
$notes = Note::whereNoteableType(Bill::class)->whereIn('noteable_id', array_keys($bills))->get();
/** @var Note $note */ /** @var Note $note */
foreach ($notes as $note) { foreach ($notes as $note) {
@ -81,8 +83,8 @@ class BillTransformer extends AbstractTransformer
/** @var ObjectGroup $entry */ /** @var ObjectGroup $entry */
foreach ($set as $entry) { foreach ($set as $entry) {
$billId = (int)$entry->object_groupable_id; $billId = (int) $entry->object_groupable_id;
$id = (int)$entry->object_group_id; $id = (int) $entry->object_group_id;
$order = $entry->order; $order = $entry->order;
$this->groups[$billId] = [ $this->groups[$billId] = [
'object_group_id' => $id, 'object_group_id' => $id,
@ -103,11 +105,10 @@ class BillTransformer extends AbstractTransformer
$journalIds = $journals->pluck('id')->toArray(); $journalIds = $journals->pluck('id')->toArray();
// grab transactions for amount: // grab transactions for amount:
$set = Transaction::whereIn('transaction_journal_id', $journalIds) $set = Transaction::whereIn('transaction_journal_id', $journalIds)
->where('transactions.amount', '<', 0) ->where('transactions.amount', '<', 0)
->get(['transactions.id', 'transactions.transaction_journal_id', 'transactions.amount', 'transactions.foreign_amount', 'transactions.transaction_currency_id', 'transactions.foreign_currency_id']) ->get(['transactions.id', 'transactions.transaction_journal_id', 'transactions.amount', 'transactions.foreign_amount', 'transactions.transaction_currency_id', 'transactions.foreign_currency_id'])
; ;
// convert to array for easy finding:
$transactions = []; $transactions = [];
/** @var Transaction $transaction */ /** @var Transaction $transaction */
@ -120,8 +121,8 @@ class BillTransformer extends AbstractTransformer
foreach ($journals as $journal) { foreach ($journals as $journal) {
app('log')->debug(sprintf('Processing journal #%d', $journal->id)); app('log')->debug(sprintf('Processing journal #%d', $journal->id));
$transaction = $transactions[$journal->id] ?? []; $transaction = $transactions[$journal->id] ?? [];
$billId = (int)$journal->bill_id; $billId = (int) $journal->bill_id;
$currencyId = (int)($transaction['transaction_currency_id'] ?? 0); $currencyId = (int) ($transaction['transaction_currency_id'] ?? 0);
$currencies[$currencyId] ??= TransactionCurrency::find($currencyId); $currencies[$currencyId] ??= TransactionCurrency::find($currencyId);
// foreign currency // foreign currency
@ -133,7 +134,7 @@ class BillTransformer extends AbstractTransformer
app('log')->debug('Foreign currency is NULL'); app('log')->debug('Foreign currency is NULL');
if (null !== $transaction['foreign_currency_id']) { if (null !== $transaction['foreign_currency_id']) {
app('log')->debug(sprintf('Foreign currency is #%d', $transaction['foreign_currency_id'])); app('log')->debug(sprintf('Foreign currency is #%d', $transaction['foreign_currency_id']));
$foreignCurrencyId = (int)$transaction['foreign_currency_id']; $foreignCurrencyId = (int) $transaction['foreign_currency_id'];
$currencies[$foreignCurrencyId] ??= TransactionCurrency::find($foreignCurrencyId); $currencies[$foreignCurrencyId] ??= TransactionCurrency::find($foreignCurrencyId);
$foreignCurrencyCode = $currencies[$foreignCurrencyId]->code; $foreignCurrencyCode = $currencies[$foreignCurrencyId]->code;
$foreignCurrencyName = $currencies[$foreignCurrencyId]->name; $foreignCurrencyName = $currencies[$foreignCurrencyId]->name;
@ -142,8 +143,8 @@ class BillTransformer extends AbstractTransformer
} }
$this->paidDates[$billId][] = [ $this->paidDates[$billId][] = [
'transaction_group_id' => (string)$journal->id, 'transaction_group_id' => (string) $journal->id,
'transaction_journal_id' => (string)$journal->transaction_group_id, 'transaction_journal_id' => (string) $journal->transaction_group_id,
'date' => $journal->date->toAtomString(), 'date' => $journal->date->toAtomString(),
'currency_id' => $currencies[$currencyId]->id, 'currency_id' => $currencies[$currencyId]->id,
'currency_code' => $currencies[$currencyId]->code, 'currency_code' => $currencies[$currencyId]->code,
@ -162,7 +163,7 @@ class BillTransformer extends AbstractTransformer
'amount' => $transaction['amount'], 'amount' => $transaction['amount'],
'foreign_amount' => $transaction['foreign_amount'], 'foreign_amount' => $transaction['foreign_amount'],
'native_amount' => $this->converter->convert($currencies[$currencyId], $this->default, $journal->date, $transaction['amount']), 'native_amount' => $this->converter->convert($currencies[$currencyId], $this->default, $journal->date, $transaction['amount']),
'foreign_native_amount' => '' === (string)$transaction['foreign_amount'] ? null : $this->converter->convert( 'foreign_native_amount' => '' === (string) $transaction['foreign_amount'] ? null : $this->converter->convert(
$currencies[$foreignCurrencyId], $currencies[$foreignCurrencyId],
$this->default, $this->default,
$journal->date, $journal->date,
@ -203,7 +204,7 @@ class BillTransformer extends AbstractTransformer
'amount_max' => app('steam')->bcround($bill->amount_max, $currency->decimal_places), 'amount_max' => app('steam')->bcround($bill->amount_max, $currency->decimal_places),
'native_amount_min' => $this->converter->convert($currency, $this->default, $date, $bill->amount_min), 'native_amount_min' => $this->converter->convert($currency, $this->default, $date, $bill->amount_min),
'native_amount_max' => $this->converter->convert($currency, $this->default, $date, $bill->amount_max), 'native_amount_max' => $this->converter->convert($currency, $this->default, $date, $bill->amount_max),
'currency_id' => (string)$bill->transaction_currency_id, 'currency_id' => (string) $bill->transaction_currency_id,
'currency_code' => $currency->code, 'currency_code' => $currency->code,
'currency_name' => $currency->name, 'currency_name' => $currency->name,
'currency_symbol' => $currency->symbol, 'currency_symbol' => $currency->symbol,

View File

@ -57,13 +57,13 @@ class TransactionGroupTransformer extends AbstractTransformer
/** @var array $object */ /** @var array $object */
foreach ($objects as $object) { foreach ($objects as $object) {
foreach ($object['sums'] as $sum) { foreach ($object['sums'] as $sum) {
$id = (int)$sum['currency_id']; $id = (int) $sum['currency_id'];
$currencies[$id] ??= TransactionCurrency::find($sum['currency_id']); $currencies[$id] ??= TransactionCurrency::find($sum['currency_id']);
} }
/** @var array $transaction */ /** @var array $transaction */
foreach ($object['transactions'] as $transaction) { foreach ($object['transactions'] as $transaction) {
$id = (int)$transaction['transaction_journal_id']; $id = (int) $transaction['transaction_journal_id'];
$journals[$id] = []; $journals[$id] = [];
} }
} }
@ -97,7 +97,7 @@ class TransactionGroupTransformer extends AbstractTransformer
/** @var \stdClass $tag */ /** @var \stdClass $tag */
foreach ($tags as $tag) { foreach ($tags as $tag) {
$id = (int)$tag->transaction_journal_id; $id = (int) $tag->transaction_journal_id;
$this->tags[$id][] = $tag->tag; $this->tags[$id][] = $tag->tag;
} }
@ -110,11 +110,11 @@ class TransactionGroupTransformer extends AbstractTransformer
$first = reset($group['transactions']); $first = reset($group['transactions']);
return [ return [
'id' => (string)$group['id'], 'id' => (string) $group['id'],
'created_at' => $first['created_at']->toAtomString(), 'created_at' => $first['created_at']->toAtomString(),
'updated_at' => $first['updated_at']->toAtomString(), 'updated_at' => $first['updated_at']->toAtomString(),
'user' => (string)$first['user_id'], 'user' => (string) $first['user_id'],
'user_group' => (string)$first['user_group_id'], 'user_group' => (string) $first['user_group_id'],
'group_title' => $group['title'] ?? null, 'group_title' => $group['title'] ?? null,
'transactions' => $this->transformTransactions($group['transactions'] ?? []), 'transactions' => $this->transformTransactions($group['transactions'] ?? []),
'links' => [ 'links' => [
@ -140,33 +140,35 @@ class TransactionGroupTransformer extends AbstractTransformer
/** /**
* @throws FireflyException * @throws FireflyException
*
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/ */
private function transformTransaction(array $transaction): array private function transformTransaction(array $transaction): array
{ {
$transaction = new NullArrayObject($transaction); $transaction = new NullArrayObject($transaction);
$type = $this->stringFromArray($transaction, 'transaction_type_type', TransactionType::WITHDRAWAL); $type = $this->stringFromArray($transaction, 'transaction_type_type', TransactionType::WITHDRAWAL);
$journalId = (int)$transaction['transaction_journal_id']; $journalId = (int) $transaction['transaction_journal_id'];
$meta = new NullArrayObject($this->meta[$journalId] ?? []); $meta = new NullArrayObject($this->meta[$journalId] ?? []);
/** /**
* Convert and use amount: * Convert and use amount:
*/ */
$amount = app('steam')->positive((string)($transaction['amount'] ?? '0')); $amount = app('steam')->positive((string) ($transaction['amount'] ?? '0'));
$currencyId = (int)$transaction['currency_id']; $currencyId = (int) $transaction['currency_id'];
$nativeAmount = $this->converter->convert($this->default, $this->currencies[$currencyId], $transaction['date'], $amount); $nativeAmount = $this->converter->convert($this->default, $this->currencies[$currencyId], $transaction['date'], $amount);
$foreignAmount = null; $foreignAmount = null;
$nativeForeignAmount = null; $nativeForeignAmount = null;
if (null !== $transaction['foreign_amount']) { if (null !== $transaction['foreign_amount']) {
$foreignCurrencyId = (int)$transaction['foreign_currency_id']; $foreignCurrencyId = (int) $transaction['foreign_currency_id'];
$foreignAmount = app('steam')->positive($transaction['foreign_amount']); $foreignAmount = app('steam')->positive($transaction['foreign_amount']);
$nativeForeignAmount = $this->converter->convert($this->default, $this->currencies[$foreignCurrencyId], $transaction['date'], $foreignAmount); $nativeForeignAmount = $this->converter->convert($this->default, $this->currencies[$foreignCurrencyId], $transaction['date'], $foreignAmount);
} }
$this->converter->summarize(); $this->converter->summarize();
return [ return [
'user' => (string)$transaction['user_id'], 'user' => (string) $transaction['user_id'],
'user_group' => (string)$transaction['user_group_id'], 'user_group' => (string) $transaction['user_group_id'],
'transaction_journal_id' => (string)$transaction['transaction_journal_id'], 'transaction_journal_id' => (string) $transaction['transaction_journal_id'],
'type' => strtolower($type), 'type' => strtolower($type),
'date' => $transaction['date']->toAtomString(), 'date' => $transaction['date']->toAtomString(),
'order' => $transaction['order'], 'order' => $transaction['order'],
@ -174,14 +176,14 @@ class TransactionGroupTransformer extends AbstractTransformer
'native_amount' => $nativeAmount, 'native_amount' => $nativeAmount,
'foreign_amount' => $foreignAmount, 'foreign_amount' => $foreignAmount,
'native_foreign_amount' => $nativeForeignAmount, 'native_foreign_amount' => $nativeForeignAmount,
'currency_id' => (string)$transaction['currency_id'], 'currency_id' => (string) $transaction['currency_id'],
'currency_code' => $transaction['currency_code'], 'currency_code' => $transaction['currency_code'],
'currency_name' => $transaction['currency_name'], 'currency_name' => $transaction['currency_name'],
'currency_symbol' => $transaction['currency_symbol'], 'currency_symbol' => $transaction['currency_symbol'],
'currency_decimal_places' => (int)$transaction['currency_decimal_places'], 'currency_decimal_places' => (int) $transaction['currency_decimal_places'],
// converted to native currency // converted to native currency
'native_currency_id' => (string)$this->default->id, 'native_currency_id' => (string) $this->default->id,
'native_currency_code' => $this->default->code, 'native_currency_code' => $this->default->code,
'native_currency_name' => $this->default->name, 'native_currency_name' => $this->default->name,
'native_currency_symbol' => $this->default->symbol, 'native_currency_symbol' => $this->default->symbol,
@ -196,11 +198,11 @@ class TransactionGroupTransformer extends AbstractTransformer
// foreign converted to native: // foreign converted to native:
'description' => $transaction['description'], 'description' => $transaction['description'],
'source_id' => (string)$transaction['source_account_id'], 'source_id' => (string) $transaction['source_account_id'],
'source_name' => $transaction['source_account_name'], 'source_name' => $transaction['source_account_name'],
'source_iban' => $transaction['source_account_iban'], 'source_iban' => $transaction['source_account_iban'],
'source_type' => $transaction['source_account_type'], 'source_type' => $transaction['source_account_type'],
'destination_id' => (string)$transaction['destination_account_id'], 'destination_id' => (string) $transaction['destination_account_id'],
'destination_name' => $transaction['destination_account_name'], 'destination_name' => $transaction['destination_account_name'],
'destination_iban' => $transaction['destination_account_iban'], 'destination_iban' => $transaction['destination_account_iban'],
'destination_type' => $transaction['destination_account_type'], 'destination_type' => $transaction['destination_account_type'],
@ -265,7 +267,7 @@ class TransactionGroupTransformer extends AbstractTransformer
return $default; return $default;
} }
if (null !== $array[$key]) { if (null !== $array[$key]) {
return (string)$array[$key]; return (string) $array[$key];
} }
if (null !== $default) { if (null !== $default) {

View File

@ -115,6 +115,7 @@ class FireflyValidator extends Validator
/** /**
* @SuppressWarnings(PHPMD.UnusedFormalParameter) * @SuppressWarnings(PHPMD.UnusedFormalParameter)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/ */
public function validateIban(mixed $attribute, mixed $value): bool public function validateIban(mixed $attribute, mixed $value): bool
{ {

View File

@ -386,6 +386,9 @@ class CreateMainTables extends Migration
} }
} }
/**
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
private function createRuleTables(): void private function createRuleTables(): void
{ {
if (!Schema::hasTable('rule_groups')) { if (!Schema::hasTable('rule_groups')) {

View File

@ -107,6 +107,7 @@ class UserGroups extends Migration
* Run the migrations. * Run the migrations.
* *
* @SuppressWarnings(PHPMD.ShortMethodName) * @SuppressWarnings(PHPMD.ShortMethodName)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/ */
public function up(): void public function up(): void
{ {