Firefly III: a personal finances manager
PHP accountingbudgetbudgetingbudgetscash-flowcashflowcredit-carddockerexpensesfinancefinancesfinanciallinuxmoneypaycheckpersonal-financephpphp7
Factory seems to work for update and create
James Cole35d0bd19854a
diff --git a/app/Factory/AccountFactory.php b/app/Factory/AccountFactory.phpindex e618b7fd99..57ec8d2c3d 100644--- a/app/Factory/AccountFactory.php+++ b/app/Factory/AccountFactory.php@@ -23,8 +23,11 @@ declare(strict_types=1);namespace FireflyIII\Factory;+use Exception;+use FireflyIII\Exceptions\FireflyException;use FireflyIII\Models\Account;use FireflyIII\Models\AccountType;+use FireflyIII\Services\Internal\Support\AccountServiceTrait;use FireflyIII\User;/**@@ -34,17 +37,84 @@ use FireflyIII\User;*/class AccountFactory{+ use AccountServiceTrait;/** @var User */private $user;/*** @param array $data*+ * @throws FireflyException+ * @throws Exception* @return Account*/public function create(array $data): Account{- return Account::create($data);+ $type = $this->getAccountType($data['account_type_id'], $data['accountType']);+ $data['iban'] = $this->filterIban($data['iban']);+++ // account may exist already:+ $existingAccount = $this->find($data['name'], $type->type);+ if (null !== $existingAccount) {+ return $existingAccount;+ }+++ // create it:+ $databaseData+ = [+ 'user_id' => $this->user->id,+ 'account_type_id' => $type->id,+ 'name' => $data['name'],+ 'virtual_balance' => strlen(strval($data['virtualBalance'])) === 0 ? '0' : $data['virtualBalance'],+ 'active' => true === $data['active'] ? true : false,+ 'iban' => $data['iban'],+ ];++ // remove virtual balance when not an asset account:+ if ($type->type !== AccountType::ASSET) {+ $databaseData['virtual_balance'] = '0';+ }++ $newAccount = Account::create($databaseData);+ $this->updateMetadata($newAccount, $data);++ if ($this->validIBData($data)) {+ $this->updateIB($newAccount, $data);+ }+ if (!$this->validIBData($data)) {+ $this->deleteIB($newAccount);+ }+ // update note:+ if (isset($data['notes'])) {+ $this->updateNote($newAccount, $data['notes']);+ }++ return $newAccount;+ }++ /**+ * @param string $accountName+ * @param string $accountType+ *+ * @return Account|null+ * @throws Exception+ * @throws FireflyException+ */+ public function find(string $accountName, string $accountType): ?Account+ {+ $type = AccountType::whereType($accountType)->first();+ $accounts = $this->user->accounts()->where('account_type_id', $type->id)->get(['accounts.*']);++ /** @var Account $object */+ foreach ($accounts as $object) {+ if ($object->name === $accountName) {+ return $object;+ }+ }++ return null;}/**@@ -52,6 +122,8 @@ class AccountFactory* @param string $accountType** @return Account+ * @throws Exception+ * @throws FireflyException*/public function findOrCreate(string $accountName, string $accountType): Account{@@ -70,7 +142,8 @@ class AccountFactory'user_id' => $this->user->id,'name' => $accountName,'account_type_id' => $type->id,- 'virtual_balance' => '0',+ 'accountType' => null,+ 'virtualBalance' => '0','iban' => null,'active' => true,]@@ -85,4 +158,22 @@ class AccountFactory$this->user = $user;}+ /**+ * @param int|null $accountTypeId+ * @param null|string $accountType+ *+ * @return AccountType|null+ */+ protected function getAccountType(?int $accountTypeId, ?string $accountType): ?AccountType+ {+ $accountTypeId = intval($accountTypeId);+ if ($accountTypeId > 0) {+ return AccountType::find($accountTypeId);+ }+ $type = config('firefly.accountTypeByIdentifier.' . strval($accountType));++ return AccountType::whereType($type)->first();++ }+}\ No newline at end of filediff --git a/app/Http/Requests/AccountFormRequest.php b/app/Http/Requests/AccountFormRequest.phpindex efb721d45a..e10b8f2185 100644--- a/app/Http/Requests/AccountFormRequest.php+++ b/app/Http/Requests/AccountFormRequest.php@@ -47,6 +47,7 @@ class AccountFormRequest extends Request'name' => $this->string('name'),'active' => $this->boolean('active'),'accountType' => $this->string('what'),+ 'account_type_id' => 0,'currency_id' => $this->integer('currency_id'),'virtualBalance' => $this->string('virtualBalance'),'iban' => $this->string('iban'),diff --git a/app/Repositories/Account/AccountRepository.php b/app/Repositories/Account/AccountRepository.phpindex f32f79d062..ef3e3e370d 100644--- a/app/Repositories/Account/AccountRepository.php+++ b/app/Repositories/Account/AccountRepository.php@@ -25,6 +25,7 @@ namespace FireflyIII\Repositories\Account;use Carbon\Carbon;use DB;use FireflyIII\Exceptions\FireflyException;+use FireflyIII\Factory\AccountFactory;use FireflyIII\Models\Account;use FireflyIII\Models\AccountMeta;use FireflyIII\Models\AccountType;@@ -241,32 +242,15 @@ class AccountRepository implements AccountRepositoryInterface* @param array $data** @return Account- *- * @throws FireflyException*/public function store(array $data): Account{- $newAccount = $this->storeAccount($data);- $this->updateMetadata($newAccount, $data);-- if ($this->validOpeningBalanceData($data)) {- $this->updateInitialBalance($newAccount, $data);+ /** @var AccountFactory $factory */+ $factory = app(AccountFactory::class);+ $factory->setUser($this->user);+ $account = $factory->create($data);- // update note:- if (isset($data['notes'])) {- $this->updateNote($newAccount, $data['notes']);- }-- return $newAccount;- }- $this->deleteInitialBalance($newAccount);-- // update note:- if (isset($data['notes'])) {- $this->updateNote($newAccount, $data['notes']);- }-- return $newAccount;+ return $account;}/**diff --git a/app/Services/Internal/Support/AccountServiceTrait.php b/app/Services/Internal/Support/AccountServiceTrait.phpindex 3267c5a241..251f114757 100644--- a/app/Services/Internal/Support/AccountServiceTrait.php+++ b/app/Services/Internal/Support/AccountServiceTrait.php@@ -25,9 +25,11 @@ namespace FireflyIII\Services\Internal\Support;use FireflyIII\Exceptions\FireflyException;use FireflyIII\Factory\AccountFactory;+use FireflyIII\Factory\AccountMetaFactory;use FireflyIII\Factory\TransactionFactory;use FireflyIII\Factory\TransactionJournalFactory;use FireflyIII\Models\Account;+use FireflyIII\Models\AccountMeta;use FireflyIII\Models\AccountType;use FireflyIII\Models\Note;use FireflyIII\Models\Transaction;@@ -44,6 +46,13 @@ use Validator;*/trait AccountServiceTrait{+ /** @var array */+ public $validAssetFields = ['accountRole', 'accountNumber', 'currency_id', 'BIC'];+ /** @var array */+ public $validCCFields = ['accountRole', 'ccMonthlyPaymentDate', 'ccType', 'accountNumber', 'currency_id', 'BIC'];+ /** @var array */+ public $validFields = ['accountNumber', 'currency_id', 'BIC'];+/*** @param Account $account*@@ -56,7 +65,7 @@ trait AccountServiceTrait$openingBalance = $this->getIBJournal($account);// opening balance data? update it!- if (null !== $openingBalance->id) {+ if (null !== $openingBalance) {Log::debug('Opening balance journal found, delete journal.');$openingBalance->delete();@@ -216,7 +225,6 @@ trait AccountServiceTrait$factory = app(AccountFactory::class);$factory->setUser($user);-return $factory->findOrCreate($name, AccountType::INITIAL_BALANCE);}@@ -252,27 +260,6 @@ trait AccountServiceTraitreturn true;}- /**- * Verify if array contains valid data to possibly store or update the opening balance.- *- * @param array $data- *- * @return bool- */- public function validIBData(array $data): bool- {- $data['openingBalance'] = strval($data['openingBalance'] ?? '');- if (isset($data['openingBalance']) && null !== $data['openingBalance'] && strlen($data['openingBalance']) > 0- && isset($data['openingBalanceDate'])) {- Log::debug('Array has valid opening balance data.');-- return true;- }- Log::debug('Array does not have valid opening balance data.');-- return false;- }-/*** @param Account $account* @param TransactionJournal $journal@@ -282,7 +269,7 @@ trait AccountServiceTrait** @throws \Exception*/- protected function updateIBJournal(Account $account, TransactionJournal $journal, array $data): bool+ public function updateIBJournal(Account $account, TransactionJournal $journal, array $data): bool{$date = $data['openingBalanceDate'];$amount = strval($data['openingBalance']);@@ -323,13 +310,51 @@ trait AccountServiceTraitreturn true;}+ /**+ * Update meta data for account. Depends on type which fields are valid.+ *+ * @param Account $account+ * @param array $data+ */+ public function updateMetaData(Account $account, array $data)+ {+ $fields = $this->validFields;++ if ($account->accountType->type === AccountType::ASSET) {+ $fields = $this->validAssetFields;+ }+ if ($account->accountType->type === AccountType::ASSET && $data['accountRole'] === 'ccAsset') {+ $fields = $this->validCCFields;+ }+ /** @var AccountMetaFactory $factory */+ $factory = app(AccountMetaFactory::class);+ foreach ($fields as $field) {+ /** @var AccountMeta $entry */+ $entry = $account->accountMeta()->where('name', $field)->first();++ // if $data has field and $entry is null, create new one:+ if (isset($data[$field]) && null === $entry) {+ Log::debug(sprintf('Created meta-field "%s":"%s" for account #%d ("%s") ', $field, $data[$field], $account->id, $account->name));+ $factory->create(['account_id' => $account->id, 'name' => $field, 'data' => $data[$field],]);+ }++ // if $data has field and $entry is not null, update $entry:+ // let's not bother with a service.+ if (isset($data[$field]) && null !== $entry) {+ $entry->data = $data[$field];+ $entry->save();+ Log::debug(sprintf('Updated meta-field "%s":"%s" for #%d ("%s") ', $field, $data[$field], $account->id, $account->name));+ }+ }+ }+/*** @param Account $account* @param string $note** @return bool*/- protected function updateNote(Account $account, string $note): bool+ public function updateNote(Account $account, string $note): bool{if (0 === strlen($note)) {$dbNote = $account->notes()->first();@@ -349,4 +374,25 @@ trait AccountServiceTraitreturn true;}++ /**+ * Verify if array contains valid data to possibly store or update the opening balance.+ *+ * @param array $data+ *+ * @return bool+ */+ public function validIBData(array $data): bool+ {+ $data['openingBalance'] = strval($data['openingBalance'] ?? '');+ if (isset($data['openingBalance']) && null !== $data['openingBalance'] && strlen($data['openingBalance']) > 0+ && isset($data['openingBalanceDate'])) {+ Log::debug('Array has valid opening balance data.');++ return true;+ }+ Log::debug('Array does not have valid opening balance data.');++ return false;+ }}\ No newline at end of filediff --git a/app/Services/Internal/Update/AccountUpdateService.php b/app/Services/Internal/Update/AccountUpdateService.phpindex 1035cad10d..e0c1f35427 100644--- a/app/Services/Internal/Update/AccountUpdateService.php+++ b/app/Services/Internal/Update/AccountUpdateService.php@@ -39,12 +39,7 @@ class AccountUpdateService{use AccountServiceTrait;- /** @var array */- private $validAssetFields = ['accountRole', 'accountNumber', 'currency_id', 'BIC'];- /** @var array */- private $validCCFields = ['accountRole', 'ccMonthlyPaymentDate', 'ccType', 'accountNumber', 'currency_id', 'BIC'];- /** @var array */- private $validFields = ['accountNumber', 'currency_id', 'BIC'];+/*** Update account data.@@ -86,44 +81,4 @@ class AccountUpdateServicereturn $account;}-- /**- * Update meta data for account. Depends on type which fields are valid.- *- * @param Account $account- * @param array $data- */- protected function updateMetaData(Account $account, array $data)- {- $fields = $this->validFields;-- if ($account->accountType->type === AccountType::ASSET) {- $fields = $this->validAssetFields;- }- if ($account->accountType->type === AccountType::ASSET && $data['accountRole'] === 'ccAsset') {- $fields = $this->validCCFields;- }- /** @var AccountMetaFactory $factory */- $factory = app(AccountMetaFactory::class);- foreach ($fields as $field) {- /** @var AccountMeta $entry */- $entry = $account->accountMeta()->where('name', $field)->first();-- // if $data has field and $entry is null, create new one:- if (isset($data[$field]) && null === $entry) {- Log::debug(sprintf('Created meta-field "%s":"%s" for account #%d ("%s") ', $field, $data[$field], $account->id, $account->name));- $factory->create(['account_id' => $account->id, 'name' => $field, 'data' => $data[$field],]);- }-- // if $data has field and $entry is not null, update $entry:- // let's not bother with a service.- if (isset($data[$field]) && null !== $entry) {- $entry->data = $data[$field];- $entry->save();- Log::debug(sprintf('Updated meta-field "%s":"%s" for #%d ("%s") ', $field, $data[$field], $account->id, $account->name));- }- }- }--}\ No newline at end of file