Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

AccountObserver.php 1.8KB

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