Code for 4.8.0

This commit is contained in:
James Cole
2019-03-05 17:26:49 +01:00
parent 6e12f434ad
commit e4fb223f77
45 changed files with 1416 additions and 206 deletions

View File

@@ -59,22 +59,9 @@ class TransactionFactory
* @param array $data
*
* @return Transaction
* @throws FireflyException
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/
public function create(array $data): ?Transaction
{
Log::debug('Start of TransactionFactory::create()');
$currencyId = $data['currency_id'] ?? null;
$currencyId = isset($data['currency']) ? $data['currency']->id : $currencyId;
if ('' === $data['amount']) {
Log::error('Empty string in data.', $data);
throw new FireflyException('Amount is an empty string, which Firefly III cannot handle. Apologies.');
}
if (null === $currencyId) {
$currency = app('amount')->getDefaultCurrencyByUser($data['account']->user);
$currencyId = $currency->id;
}
$data['foreign_amount'] = '' === (string)$data['foreign_amount'] ? null : $data['foreign_amount'];
Log::debug(sprintf('Create transaction for account #%d ("%s") with amount %s', $data['account']->id, $data['account']->name, $data['amount']));
@@ -84,11 +71,11 @@ class TransactionFactory
'account_id' => $data['account']->id,
'transaction_journal_id' => $data['transaction_journal']->id,
'description' => $data['description'],
'transaction_currency_id' => $currencyId,
'transaction_currency_id' => $data['currency']->id,
'amount' => $data['amount'],
'foreign_amount' => $data['foreign_amount'],
'foreign_currency_id' => null,
'identifier' => $data['identifier'],
'foreign_currency_id' => $data['foreign_currency'] ? $data['foreign_currency']->id : null,
'identifier' => 0,
]
);
}
@@ -107,24 +94,13 @@ class TransactionFactory
*/
public function createPair(TransactionJournal $journal, array $data): Collection
{
Log::debug('Start of TransactionFactory::createPair()', $data);
// all this data is the same for both transactions:
Log::debug('Searching for currency info.');
$defaultCurrency = app('amount')->getDefaultCurrencyByUser($this->user);
$currency = $this->findCurrency($data['currency_id'], $data['currency_code']);
$currency = $currency ?? $defaultCurrency;
// enable currency:
if (false === $currency->enabled) {
$currency->enabled = true;
$currency->save();
}
Log::debug('Start of TransactionFactory::createPair()' );
// type of source account and destination account depends on journal type:
$sourceType = $this->accountType($journal, 'source');
$destinationType = $this->accountType($journal, 'destination');
Log::debug(sprintf('Journal is a %s.', $journal->transactionType->type));
Log::debug(sprintf('Expect source account to be of type "%s"', $sourceType));
Log::debug(sprintf('Expect source destination to be of type "%s"', $destinationType));
@@ -149,11 +125,11 @@ class TransactionFactory
'description' => $data['description'],
'amount' => app('steam')->negative((string)$data['amount']),
'foreign_amount' => null,
'currency' => $currency,
'currency' => $data['currency'],
'foreign_currency' => $data['foreign_currency'],
'account' => $sourceAccount,
'transaction_journal' => $journal,
'reconciled' => $data['reconciled'],
'identifier' => $data['identifier'],
]
);
$dest = $this->create(
@@ -161,44 +137,23 @@ class TransactionFactory
'description' => $data['description'],
'amount' => app('steam')->positive((string)$data['amount']),
'foreign_amount' => null,
'currency' => $currency,
'currency' => $data['currency'],
'foreign_currency' => $data['foreign_currency'],
'account' => $destinationAccount,
'transaction_journal' => $journal,
'reconciled' => $data['reconciled'],
'identifier' => $data['identifier'],
]
);
if (null === $source || null === $dest) {
throw new FireflyException('Could not create transactions.'); // @codeCoverageIgnore
}
// set foreign currency
Log::debug('Trying to find foreign currency information.');
$foreign = $this->findCurrency($data['foreign_currency_id'], $data['foreign_currency_code']);
$this->setForeignCurrency($source, $foreign);
$this->setForeignCurrency($dest, $foreign);
// set foreign amount:
if (null !== $data['foreign_amount']) {
$this->setForeignAmount($source, app('steam')->negative((string)$data['foreign_amount']));
$this->setForeignAmount($dest, app('steam')->positive((string)$data['foreign_amount']));
}
// set budget:
if ($journal->transactionType->type !== TransactionType::WITHDRAWAL) {
$data['budget_id'] = null;
$data['budget_name'] = null;
}
$budget = $this->findBudget($data['budget_id'], $data['budget_name']);
$this->setBudget($source, $budget);
$this->setBudget($dest, $budget);
// set category
$category = $this->findCategory($data['category_id'], $data['category_name']);
$this->setCategory($source, $category);
$this->setCategory($dest, $category);
return new Collection([$source, $dest]);
}
@@ -231,8 +186,6 @@ class TransactionFactory
&& !\in_array($destinationType, $list, true)) {
throw new FireflyException(sprintf('At least one of the accounts must be an asset account (%s, %s).', $sourceType, $destinationType));
}
// either of these must be asset or default account.
}

View File

@@ -24,12 +24,14 @@ declare(strict_types=1);
namespace FireflyIII\Factory;
use Carbon\Carbon;
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Models\TransactionCurrency;
use FireflyIII\Models\TransactionGroup;
use FireflyIII\Models\TransactionJournal;
use FireflyIII\Services\Internal\Support\JournalServiceTrait;
use FireflyIII\Services\Internal\Support\TransactionTypeTrait;
use FireflyIII\User;
use Illuminate\Support\Collection;
use Log;
/**
@@ -37,6 +39,7 @@ use Log;
*/
class TransactionJournalFactory
{
private $fields;
/** @var User The user */
private $user;
@@ -47,6 +50,9 @@ class TransactionJournalFactory
*/
public function __construct()
{
$this->fields = ['sepa-cc', 'sepa-ct-op', 'sepa-ct-id', 'sepa-db', 'sepa-country', 'sepa-ep', 'sepa-ci', 'interest_date', 'book_date', 'process_date',
'due_date', 'recurrence_id', 'payment_date', 'invoice_date', 'internal_reference', 'bunq_payment_id', 'importHash', 'importHashV2',
'external_id', 'sepa-batch-id', 'original-source'];
if ('testing' === config('app.env')) {
Log::warning(sprintf('%s should not be instantiated in the TEST environment!', \get_class($this)));
}
@@ -57,85 +63,116 @@ class TransactionJournalFactory
*
* @param array $data
*
* @return TransactionJournal
* @return Collection
* @throws FireflyException
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function create(array $data): TransactionJournal
public function create(array $data): Collection
{
Log::debug('Start of TransactionJournalFactory::create()');
// store basic journal first.
$type = $this->findTransactionType($data['type']);
$defaultCurrency = app('amount')->getDefaultCurrencyByUser($this->user);
Log::debug(sprintf('Going to store a %s', $type->type));
$factory = app(TransactionFactory::class);
$journals = new Collection;
$carbon = $data['date'];
$type = $this->findTransactionType($data['type']);
$description = app('steam')->cleanString($data['description']);
$description = str_replace(["\n", "\t", "\r"], "\x20", $description);
/** @var Carbon $carbon */
$carbon = $data['date'];
$carbon->setTimezone(config('app.timezone'));
$journal = TransactionJournal::create(
[
'user_id' => $data['user'],
'transaction_type_id' => $type->id,
'bill_id' => null,
'transaction_currency_id' => $defaultCurrency->id,
'description' => $description,
'date' => $carbon->format('Y-m-d H:i:s'),
'order' => 0,
'tag_count' => 0,
'completed' => 0,
]
);
if (isset($data['transactions'][0]['amount']) && '' === $data['transactions'][0]['amount']) {
Log::error('Empty amount in data', $data);
}
// store basic transactions:
/** @var TransactionFactory $factory */
$factory = app(TransactionFactory::class);
$factory->setUser($this->user);
$totalAmount = '0';
Log::debug(sprintf('Found %d transactions in array.', \count($data['transactions'])));
/** @var array $trData */
foreach ($data['transactions'] as $index => $trData) {
Log::debug(sprintf('Now storing transaction %d of %d', $index + 1, \count($data['transactions'])));
$factory->createPair($journal, $trData);
$totalAmount = bcadd($totalAmount, (string)($trData['amount'] ?? '0'));
Log::debug(sprintf('New journal(group): %s with description "%s"', $type->type, $description));
// loop each transaction.
/**
* @var int $index
* @var array $transactionData
*/
foreach ($data['transactions'] as $index => $transactionData) {
Log::debug(sprintf('Now at journal #%d from %d', $index + 1, count($data['transactions'])));
// catch to stop empty amounts:
if ('' === (string)$transactionData['amount'] || 0.0 === (float)$transactionData['amount']) {
continue;
}
// currency & foreign currency
$transactionData['currency'] = $this->getCurrency($data, $index);
$transactionData['foreign_currency'] = $this->getForeignCurrency($data, $index);
// store basic journal first.
$journal = TransactionJournal::create(
[
'user_id' => $data['user'],
'transaction_type_id' => $type->id,
'bill_id' => null,
'transaction_currency_id' => $transactionData['currency']->id,
'description' => $description,
'date' => $carbon->format('Y-m-d H:i:s'),
'order' => 0,
'tag_count' => 0,
'completed' => 0,
]
);
Log::debug(sprintf('Stored journal under ID #%d', $journal->id));
// store transactions for this journal:
$factory->createPair($journal, $transactionData);
// save journal:
$journal->completed = true;
$journal->save();
// // link bill TODO
// $this->connectBill($journal, $data);
//
// // link piggy bank (if transfer) TODO
// $this->connectPiggyBank($journal, $data);
//
// // link tags: TODO
// $this->connectTags($journal, $transactionData);
//
// // store note: TODO
// $this->storeNote($journal, $transactionData['notes']);
//
// if ($journal->transactionType->type !== TransactionType::WITHDRAWAL) {
// $transactionData['budget_id'] = null;
// $transactionData['budget_name'] = null;
// }
// // save budget TODO
// $budget = $this->findBudget($data['budget_id'], $data['budget_name']);
// $this->setBudget($journal, $budget);
//
// // set category TODO
// $category = $this->findCategory($data['category_id'], $data['category_name']);
// $this->setCategory($journal, $category);
//
// // store meta data TODO
// foreach ($this->fields as $field) {
// $this->storeMeta($journal, $data, $field);
// }
// add to array
$journals->push($journal);
}
$journal->completed = true;
$journal->save();
// link bill:
$this->connectBill($journal, $data);
// create group if necessary
if ($journals->count() > 1) {
$group = new TransactionGroup;
$group->user()->associate($this->user);
$group->title = $description;
$group->save();
$group->transactionJournals()->saveMany($journals);
// link piggy bank (if transfer)
$this->connectPiggyBank($journal, $data);
// link tags:
$this->connectTags($journal, $data);
// store note:
$this->storeNote($journal, (string)$data['notes']);
// store date meta fields (if present):
$fields = ['sepa-cc', 'sepa-ct-op', 'sepa-ct-id', 'sepa-db', 'sepa-country', 'sepa-ep', 'sepa-ci', 'interest_date', 'book_date', 'process_date',
'due_date', 'recurrence_id', 'payment_date', 'invoice_date', 'internal_reference', 'bunq_payment_id', 'importHash', 'importHashV2',
'external_id', 'sepa-batch-id', 'original-source'];
foreach ($fields as $field) {
$this->storeMeta($journal, $data, $field);
Log::debug(sprintf('More than one journal, created group #%d.', $group->id));
}
Log::debug('End of TransactionJournalFactory::create()');
// invalidate cache.
app('preferences')->mark();
return $journal;
return $journals;
}
/**
* Set the user.
*
@@ -166,4 +203,126 @@ class TransactionJournalFactory
}
}
/**
* @param array $data
* @param int $index
*
* @return TransactionCurrency
*/
private function getCurrency(array $data, int $index): TransactionCurrency
{
// first check the transaction row itself.
$row = $data['transactions'][$index];
$currency = null;
// check currency object:
if (null === $currency && isset($row['currency']) && $row['currency'] instanceof TransactionCurrency) {
$currency = $row['currency'];
}
// check currency ID:
if (null === $currency && isset($row['currency_id']) && (int)$row['currency_id'] > 0) {
$currencyId = (int)$row['currency_id'];
$currency = TransactionCurrency::find($currencyId);
}
// check currency code
if (null === $currency && isset($row['currency_code']) && 3 === \strlen($row['currency_code'])) {
$currency = TransactionCurrency::whereCode($row['currency_code'])->first();
}
// continue with journal itself.
// check currency object:
if (null === $currency && isset($data['currency']) && $data['currency'] instanceof TransactionCurrency) {
$currency = $data['currency'];
}
// check currency ID:
if (null === $currency && isset($data['currency_id']) && (int)$data['currency_id'] > 0) {
$currencyId = (int)$data['currency_id'];
$currency = TransactionCurrency::find($currencyId);
}
// check currency code
if (null === $currency && isset($data['currency_code']) && 3 === \strlen($data['currency_code'])) {
$currency = TransactionCurrency::whereCode($data['currency_code'])->first();
}
if (null === $currency) {
// return user's default currency:
$currency = app('amount')->getDefaultCurrencyByUser($this->user);
}
// enable currency:
if (false === $currency->enabled) {
$currency->enabled = true;
$currency->save();
}
Log::debug(sprintf('Journal currency will be #%d (%s)', $currency->id, $currency->code));
return $currency;
}
/**
* @param array $data
* @param int $index
*
* @return TransactionCurrency|null
*/
private function getForeignCurrency(array $data, int $index): ?TransactionCurrency
{
// first check the transaction row itself.
$row = $data['transactions'][$index];
$currency = null;
// check currency object:
if (null === $currency && isset($row['foreign_currency']) && $row['foreign_currency'] instanceof TransactionCurrency) {
$currency = $row['foreign_currency'];
}
// check currency ID:
if (null === $currency && isset($row['foreign_currency_id']) && (int)$row['foreign_currency_id'] > 0) {
$currencyId = (int)$row['foreign_currency_id'];
$currency = TransactionCurrency::find($currencyId);
}
// check currency code
if (null === $currency && isset($row['foreign_currency_code']) && 3 === \strlen($row['foreign_currency_code'])) {
$currency = TransactionCurrency::whereCode($row['foreign_currency_code'])->first();
}
// continue with journal itself.
// check currency object:
if (null === $currency && isset($data['foreign_currency']) && $data['foreign_currency'] instanceof TransactionCurrency) {
$currency = $data['foreign_currency'];
}
// check currency ID:
if (null === $currency && isset($data['foreign_currency_id']) && (int)$data['foreign_currency_id'] > 0) {
$currencyId = (int)$data['foreign_currency_id'];
$currency = TransactionCurrency::find($currencyId);
}
// check currency code
if (null === $currency && isset($data['foreign_currency_code']) && 3 === \strlen($data['foreign_currency_code'])) {
$currency = TransactionCurrency::whereCode($data['foreign_currency_code'])->first();
}
// enable currency:
if (null !== $currency && false === $currency->enabled) {
$currency->enabled = true;
$currency->save();
}
if (null !== $currency) {
Log::debug(sprintf('Journal foreign currency will be #%d (%s)', $currency->id, $currency->code));
}
if (null === $currency) {
Log::debug('Journal foreign currency will be NULL');
}
return $currency;
}
}