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

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