UserNotificationSetting.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. namespace App\Models;
  3. use Illuminate\Database\Eloquent\Factories\HasFactory;
  4. use Illuminate\Database\Eloquent\Model;
  5. use Illuminate\Database\Eloquent\Relations\BelongsTo;
  6. class UserNotificationSetting extends Model
  7. {
  8. use HasFactory;
  9. protected $fillable = [
  10. 'user_id',
  11. 'order_settings',
  12. 'reclamation_settings',
  13. 'schedule_settings',
  14. ];
  15. protected function casts(): array
  16. {
  17. return [
  18. 'order_settings' => 'array',
  19. 'reclamation_settings' => 'array',
  20. 'schedule_settings' => 'array',
  21. ];
  22. }
  23. public function user(): BelongsTo
  24. {
  25. return $this->belongsTo(User::class);
  26. }
  27. public static function defaultsForUser(int $userId): array
  28. {
  29. return [
  30. 'user_id' => $userId,
  31. 'order_settings' => [],
  32. 'reclamation_settings' => [],
  33. 'schedule_settings' => [],
  34. ];
  35. }
  36. /**
  37. * Проверяет, включены ли уведомления хотя бы для одного статуса/источника в секции.
  38. * Секция считается активной если есть хотя бы один true-канал.
  39. */
  40. public function isSectionEnabled(string $settingsKey): bool
  41. {
  42. $settings = $this->{$settingsKey};
  43. if (!is_array($settings) || empty($settings)) {
  44. return false;
  45. }
  46. foreach ($settings as $channels) {
  47. if (is_array($channels) && array_filter($channels)) {
  48. return true;
  49. }
  50. }
  51. return false;
  52. }
  53. /**
  54. * Возвращает включённые каналы для конкретного статуса/источника.
  55. * @return array<string, bool> ['browser' => true, 'push' => false, 'email' => true]
  56. */
  57. public function getChannelsForKey(string $settingsKey, int|string $key): array
  58. {
  59. $settings = $this->{$settingsKey};
  60. if (!is_array($settings) || !isset($settings[$key])) {
  61. return [];
  62. }
  63. return array_filter($settings[$key]);
  64. }
  65. /**
  66. * Проверяет, включён ли хотя бы один канал для конкретного статуса/источника.
  67. */
  68. public function hasEnabledChannelForKey(string $settingsKey, int|string $key): bool
  69. {
  70. return !empty($this->getChannelsForKey($settingsKey, $key));
  71. }
  72. }