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

SyncWithCompanyDefaults.php 2.4KB

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