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.

SyncWithCompanyDefaults.php 2.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. namespace App\Listeners;
  3. use App\Enums\{CategoryType, DiscountType, TaxType};
  4. use App\Events\CompanyDefaultEvent;
  5. use App\Models\Setting\CompanyDefault;
  6. use Illuminate\Support\Facades\DB;
  7. class SyncWithCompanyDefaults
  8. {
  9. /**
  10. * Create the event listener.
  11. */
  12. public function __construct()
  13. {
  14. //
  15. }
  16. /**
  17. * Handle the event.
  18. */
  19. public function handle(CompanyDefaultEvent $event): void
  20. {
  21. DB::transaction(function () use ($event) {
  22. $this->syncWithCompanyDefaults($event);
  23. }, 5);
  24. }
  25. private function syncWithCompanyDefaults($event): void
  26. {
  27. $model = $event->model;
  28. if (! $model->getAttribute('enabled') || ! auth()->check() || ! auth()->user()->currentCompany) {
  29. return;
  30. }
  31. $companyId = auth()->user()->currentCompany->id;
  32. if (! $companyId) {
  33. return;
  34. }
  35. $this->updateCompanyDefaults($model, $companyId);
  36. }
  37. private function updateCompanyDefaults($model, $companyId): void
  38. {
  39. $modelName = class_basename($model);
  40. $type = $model->getAttribute('type');
  41. $default = CompanyDefault::firstOrNew([
  42. 'company_id' => $companyId,
  43. ]);
  44. match ($modelName) {
  45. 'Discount' => $this->handleDiscount($default, $type, $model->getKey()),
  46. 'Tax' => $this->handleTax($default, $type, $model->getKey()),
  47. 'Category' => $this->handleCategory($default, $type, $model->getKey()),
  48. 'Currency' => $default->currency_code = $model->getAttribute('code'),
  49. 'Account' => $default->account_id = $model->getKey(),
  50. default => null,
  51. };
  52. $default->save();
  53. }
  54. private function handleDiscount($default, $type, $key): void
  55. {
  56. match (true) {
  57. $type === DiscountType::Sales => $default->sales_discount_id = $key,
  58. $type === DiscountType::Purchase => $default->purchase_discount_id = $key,
  59. };
  60. }
  61. private function handleTax($default, $type, $key): void
  62. {
  63. match (true) {
  64. $type === TaxType::Sales => $default->sales_tax_id = $key,
  65. $type === TaxType::Purchase => $default->purchase_tax_id = $key,
  66. };
  67. }
  68. private function handleCategory($default, $type, $key): void
  69. {
  70. match (true) {
  71. $type === CategoryType::Income => $default->income_category_id = $key,
  72. $type === CategoryType::Expense => $default->expense_category_id = $key,
  73. };
  74. }
  75. }