You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

AccountObserver.php 1.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <?php
  2. namespace App\Observers;
  3. use App\Enums\Accounting\AccountCategory;
  4. use App\Enums\Accounting\AccountType;
  5. use App\Models\Accounting\Account;
  6. use App\Models\Accounting\AccountSubtype;
  7. use App\Utilities\Accounting\AccountCode;
  8. class AccountObserver
  9. {
  10. public function creating(Account $account): void
  11. {
  12. $this->setCategoryAndType($account, true);
  13. }
  14. public function updating(Account $account): void
  15. {
  16. if ($account->isDirty('subtype_id')) {
  17. $this->setCategoryAndType($account, false);
  18. }
  19. }
  20. private function setCategoryAndType(Account $account, bool $isCreating): void
  21. {
  22. $subtype = $account->subtype_id ? AccountSubtype::find($account->subtype_id) : null;
  23. if ($subtype) {
  24. $account->category = $subtype->category;
  25. $account->type = $subtype->type;
  26. } elseif ($isCreating) {
  27. $account->category = AccountCategory::Asset;
  28. $account->type = AccountType::CurrentAsset;
  29. }
  30. }
  31. private function setFieldsForBankAccount(Account $account): void
  32. {
  33. $generatedAccountCode = AccountCode::generate($account->subtype);
  34. $account->code = $generatedAccountCode;
  35. }
  36. /**
  37. * Handle the Account "created" event.
  38. */
  39. public function created(Account $account): void
  40. {
  41. if ($account->bankAccount && $account->code === null) {
  42. $this->setFieldsForBankAccount($account);
  43. $account->save();
  44. }
  45. }
  46. }