Is now capable of updating transactions over the API.

This commit is contained in:
James Cole
2019-04-06 08:10:50 +02:00
parent b692cccdfb
commit c519b4d0df
36 changed files with 1840 additions and 709 deletions

View File

@@ -27,11 +27,11 @@ namespace FireflyIII\Factory;
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Models\Account;
use FireflyIII\Models\AccountType;
use FireflyIII\Models\Transaction;
use FireflyIII\Models\TransactionCurrency;
use FireflyIII\Models\TransactionJournal;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Services\Internal\Support\JournalServiceTrait;
use FireflyIII\Support\NullArrayObject;
use FireflyIII\User;
use FireflyIII\Validation\AccountValidator;
@@ -44,8 +44,8 @@ use Log;
*/
class TransactionFactory
{
/** @var AccountRepositoryInterface */
private $accountRepository;
use JournalServiceTrait;
/** @var AccountValidator */
private $accountValidator;
/** @var TransactionJournal */
@@ -113,12 +113,16 @@ class TransactionFactory
*/
public function createPair(NullArrayObject $data, TransactionCurrency $currency, ?TransactionCurrency $foreignCurrency): Collection
{
Log::debug('Going to create a pair of transactions.');
Log::debug(sprintf('Source info: ID #%d, name "%s"', $data['source_id'], $data['source_name']));
Log::debug(sprintf('Destination info: ID #%d, name "%s"', $data['destination_id'], $data['destination_name']));
// validate source and destination using a new Validator.
$this->validateAccounts($data);
// create or get source and destination accounts:
$sourceAccount = $this->getAccount('source', (int)$data['source_id'], $data['source_name']);
$destinationAccount = $this->getAccount('destination', (int)$data['destination_id'], $data['destination_name']);
$type = $this->journal->transactionType->type;
$sourceAccount = $this->getAccount($type, 'source', (int)$data['source_id'], $data['source_name']);
$destinationAccount = $this->getAccount($type, 'destination', (int)$data['destination_id'], $data['destination_name']);
$amount = $this->getAmount($data['amount']);
$foreignAmount = $this->getForeignAmount($data['foreign_amount']);
@@ -129,7 +133,7 @@ class TransactionFactory
$two->reconciled = $data['reconciled'] ?? false;
// add foreign currency info to $one and $two if necessary.
if (null !== $foreignCurrency) {
if (null !== $foreignCurrency && null !== $foreignAmount) {
$one->foreign_currency_id = $foreignCurrency->id;
$two->foreign_currency_id = $foreignCurrency->id;
$one->foreign_amount = app('steam')->negative($foreignAmount);
@@ -144,134 +148,6 @@ class TransactionFactory
}
/**
* @param string $direction
* @param int|null $accountId
* @param string|null $accountName
*
* @return Account
* @throws FireflyException
*/
public function getAccount(string $direction, ?int $accountId, ?string $accountName): Account
{
// some debug logging:
Log::debug(sprintf('Now in getAccount(%s, %d, %s)', $direction, $accountId, $accountName));
// final result:
$result = null;
// expected type of source account, in order of preference
/** @var array $array */
$array = config('firefly.expected_source_types');
$expectedTypes = $array[$direction];
unset($array);
// and now try to find it, based on the type of transaction.
$transactionType = $this->journal->transactionType->type;
$message = 'Based on the fact that the transaction is a %s, the %s account should be in: %s';
Log::debug(sprintf($message, $transactionType, $direction, implode(', ', $expectedTypes[$transactionType])));
// first attempt, find by ID.
if (null !== $accountId) {
$search = $this->accountRepository->findNull($accountId);
if (null !== $search && in_array($search->accountType->type, $expectedTypes[$transactionType], true)) {
Log::debug(
sprintf('Found "account_id" object for %s: #%d, "%s" of type %s', $direction, $search->id, $search->name, $search->accountType->type)
);
$result = $search;
}
}
// second attempt, find by name.
if (null === $result && null !== $accountName) {
Log::debug('Found nothing by account ID.');
// find by preferred type.
$source = $this->accountRepository->findByName($accountName, [$expectedTypes[$transactionType][0]]);
// or any expected type.
$source = $source ?? $this->accountRepository->findByName($accountName, $expectedTypes[$transactionType]);
if (null !== $source) {
Log::debug(sprintf('Found "account_name" object for %s: #%d, %s', $direction, $source->id, $source->name));
$result = $source;
}
}
// return cash account.
if (null === $result && null === $accountName
&& in_array(AccountType::CASH, $expectedTypes[$transactionType], true)) {
$result = $this->accountRepository->getCashAccount();
}
// return new account.
if (null === $result) {
$accountName = $accountName ?? '(no name)';
// final attempt, create it.
$preferredType = $expectedTypes[$transactionType][0];
if (AccountType::ASSET === $preferredType) {
throw new FireflyException(sprintf('TransactionFactory: Cannot create asset account with ID #%d or name "%s".', $accountId, $accountName));
}
$result = $this->accountRepository->store(
[
'account_type_id' => null,
'accountType' => $preferredType,
'name' => $accountName,
'active' => true,
'iban' => null,
]
);
}
return $result;
}
/**
* @param string $amount
*
* @return string
* @throws FireflyException
*/
public function getAmount(string $amount): string
{
if ('' === $amount) {
throw new FireflyException(sprintf('The amount cannot be an empty string: "%s"', $amount));
}
if (0 === bccomp('0', $amount)) {
throw new FireflyException(sprintf('The amount seems to be zero: "%s"', $amount));
}
return $amount;
}
/**
* @param string|null $amount
*
* @return string
*/
public function getForeignAmount(?string $amount): ?string
{
$result = null;
if (null === $amount) {
Log::debug('No foreign amount info in array. Return NULL');
return null;
}
if ('' === $amount) {
Log::debug('Foreign amount is empty string, return NULL.');
return null;
}
if (0 === bccomp('0', $amount)) {
Log::debug('Foreign amount is 0.0, return NULL.');
return null;
}
Log::debug(sprintf('Foreign amount is %s', $amount));
return $amount;
}
/**
* @param TransactionJournal $journal
@@ -298,6 +174,7 @@ class TransactionFactory
private function validateAccounts(NullArrayObject $data): void
{
$transactionType = $data['type'] ?? 'invalid';
$this->accountValidator->setUser($this->journal->user);
$this->accountValidator->setTransactionType($transactionType);
// validate source account.
@@ -309,6 +186,7 @@ class TransactionFactory
if (false === $validSource) {
throw new FireflyException($this->accountValidator->sourceError);
}
Log::debug('Source seems valid.');
// validate destination account
$destinationId = isset($data['destination_id']) ? (int)$data['destination_id'] : null;
$destinationName = $data['destination_name'] ?? null;

View File

@@ -27,7 +27,6 @@ namespace FireflyIII\Factory;
use Carbon\Carbon;
use Exception;
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Models\Note;
use FireflyIII\Models\TransactionCurrency;
use FireflyIII\Models\TransactionJournal;
use FireflyIII\Models\TransactionType;
@@ -37,6 +36,7 @@ use FireflyIII\Repositories\Category\CategoryRepositoryInterface;
use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface;
use FireflyIII\Repositories\PiggyBank\PiggyBankRepositoryInterface;
use FireflyIII\Repositories\TransactionType\TransactionTypeRepositoryInterface;
use FireflyIII\Services\Internal\Support\JournalServiceTrait;
use FireflyIII\Support\NullArrayObject;
use FireflyIII\User;
use Illuminate\Support\Collection;
@@ -47,12 +47,10 @@ use Log;
*/
class TransactionJournalFactory
{
use JournalServiceTrait;
/** @var BillRepositoryInterface */
private $billRepository;
/** @var BudgetRepositoryInterface */
private $budgetRepository;
/** @var CategoryRepositoryInterface */
private $categoryRepository;
/** @var CurrencyRepositoryInterface */
private $currencyRepository;
/** @var array */
@@ -61,8 +59,6 @@ class TransactionJournalFactory
private $piggyEventFactory;
/** @var PiggyBankRepositoryInterface */
private $piggyRepository;
/** @var TagFactory */
private $tagFactory;
/** @var TransactionFactory */
private $transactionFactory;
/** @var TransactionTypeRepositoryInterface */
@@ -88,7 +84,7 @@ class TransactionJournalFactory
'due_date', 'payment_date', 'invoice_date',
// others
'recurrence_id', 'internal_reference', 'bunq_payment_id',
'recurrence_id', 'internal_reference', 'bunq_payment_id',
'import_hash', 'import_hash_v2', 'external_id', 'original_source'];
@@ -151,6 +147,7 @@ class TransactionJournalFactory
{
$this->user = $user;
$this->currencyRepository->setUser($this->user);
$this->tagFactory->setUser($user);
$this->transactionFactory->setUser($this->user);
$this->billRepository->setUser($this->user);
$this->budgetRepository->setUser($this->user);
@@ -184,31 +181,6 @@ class TransactionJournalFactory
Log::debug('Create no piggy event');
}
/**
* Link tags to journal.
*
* @param TransactionJournal $journal
* @param array $tags
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/
public function storeTags(TransactionJournal $journal, ?array $tags): void
{
$this->tagFactory->setUser($journal->user);
$set = [];
if (!\is_array($tags)) {
return;
}
foreach ($tags as $string) {
if ('' !== $string) {
$tag = $this->tagFactory->findOrCreate($string);
if (null !== $tag) {
$set[] = $tag->id;
}
}
}
$journal->tags()->sync($set);
}
/**
* @param TransactionJournal $journal
* @param NullArrayObject $data
@@ -229,27 +201,6 @@ class TransactionJournalFactory
$factory->updateOrCreate($set);
}
/**
* @param TransactionJournal $journal
* @param string $notes
*/
protected function storeNote(TransactionJournal $journal, ?string $notes): void
{
$notes = (string)$notes;
if ('' !== $notes) {
$note = $journal->notes()->first();
if (null === $note) {
$note = new Note;
$note->noteable()->associate($journal);
}
$note->text = $notes;
$note->save();
Log::debug(sprintf('Stored notes for journal #%d', $journal->id));
return;
}
}
/**
* @param NullArrayObject $row
*
@@ -263,8 +214,9 @@ class TransactionJournalFactory
/** Get basic fields */
$type = $this->typeRepository->findTransactionType(null, $row['type']);
$carbon = $row['date'] ?? new Carbon;
$order = $row['order'] ?? 0;
$currency = $this->currencyRepository->findCurrency((int)$row['currency_id'], $row['currency_code']);
$foreignCurrency = $this->findForeignCurrency($row);
$foreignCurrency = $this->currencyRepository->findCurrencyNull($row['foreign_currency_id'], $row['foreign_currency_code']);
$bill = $this->billRepository->findBill((int)$row['bill_id'], $row['bill_name']);
$billId = TransactionType::WITHDRAWAL === $type->type && null !== $bill ? $bill->id : null;
$description = app('steam')->cleanString((string)$row['description']);
@@ -281,7 +233,7 @@ class TransactionJournalFactory
'transaction_currency_id' => $currency->id,
'description' => '' === $description ? '(empty description)' : $description,
'date' => $carbon->format('Y-m-d H:i:s'),
'order' => 0,
'order' => $order,
'tag_count' => 0,
'completed' => 0,
]
@@ -318,7 +270,7 @@ class TransactionJournalFactory
$this->storeCategory($journal, $row);
/** Set notes */
$this->storeNote($journal, $row['notes']);
$this->storeNotes($journal, $row['notes']);
/** Set piggy bank */
$this->storePiggyEvent($journal, $row);
@@ -332,22 +284,6 @@ class TransactionJournalFactory
return $journal;
}
/**
* This is a separate function because "findCurrency" will default to EUR and that may not be what we want.
*
* @param NullArrayObject $transaction
*
* @return TransactionCurrency|null
*/
private function findForeignCurrency(NullArrayObject $transaction): ?TransactionCurrency
{
if (null === $transaction['foreign_currency'] && null === $transaction['foreign_currency_id'] && null === $transaction['foreign_currency_code']) {
return null;
}
return $this->currencyRepository->findCurrency((int)$transaction['foreign_currency_id'], $transaction['foreign_currency_code']);
}
/**
* @param NullArrayObject $row
*
@@ -355,7 +291,7 @@ class TransactionJournalFactory
*/
private function hashArray(NullArrayObject $row): string
{
$row['import_hash_v2'] = null;
$row['import_hash_v2'] = null;
$row['original_source'] = null;
$json = json_encode($row);
if (false === $json) {
@@ -367,36 +303,6 @@ class TransactionJournalFactory
return $hash;
}
/**
* @param TransactionJournal $journal
* @param NullArrayObject $data
*/
private function storeBudget(TransactionJournal $journal, NullArrayObject $data): void
{
if (TransactionType::WITHDRAWAL !== $journal->transactionType->type) {
return;
}
$budget = $this->budgetRepository->findBudget($data['budget'], $data['budget_id'], $data['budget_name']);
if (null !== $budget) {
Log::debug(sprintf('Link budget #%d to journal #%d', $budget->id, $journal->id));
$journal->budgets()->sync([$budget->id]);
}
}
/**
* @param TransactionJournal $journal
* @param NullArrayObject $data
*/
private function storeCategory(TransactionJournal $journal, NullArrayObject $data): void
{
$category = $this->categoryRepository->findCategory($data['category'], $data['category_id'], $data['category_name']);
if (null !== $category) {
Log::debug(sprintf('Link category #%d to journal #%d', $category->id, $journal->id));
$journal->categories()->sync([$category->id]);
}
}
/**
* @param TransactionJournal $journal
* @param NullArrayObject $transaction

View File

@@ -53,10 +53,12 @@ class TransactionJournalMetaFactory
*/
public function updateOrCreate(array $data): ?TransactionJournalMeta
{
Log::debug('In updateOrCreate()');
$value = $data['data'];
/** @var TransactionJournalMeta $entry */
$entry = $data['journal']->transactionJournalMeta()->where('name', $data['name'])->first();
if (null === $value && null !== $entry) {
Log::debug('Value is empty, delete meta value.');
try {
$entry->delete();
} catch (Exception $e) { // @codeCoverageIgnore
@@ -67,11 +69,14 @@ class TransactionJournalMetaFactory
}
if ($data['data'] instanceof Carbon) {
Log::debug('Is a carbon object.');
$value = $data['data']->toW3cString();
}
if ('' === (string)$value) {
Log::debug('Is an empty string.');
// don't store blank strings.
if (null !== $entry) {
Log::debug('Will not store empty strings, delete meta value');
try {
$entry->delete();
} catch (Exception $e) { // @codeCoverageIgnore
@@ -83,11 +88,13 @@ class TransactionJournalMetaFactory
}
if (null === $entry) {
Log::debug('Will create new object.');
Log::debug(sprintf('Going to create new meta-data entry to store "%s".', $data['name']));
$entry = new TransactionJournalMeta();
$entry->transactionJournal()->associate($data['journal']);
$entry->name = $data['name'];
}
Log::debug('Will update value and return.');
$entry->data = $value;
$entry->save();