您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

SyncWithCompanyDefaults.php 2.5KB

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