NotificationService.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  1. <?php
  2. namespace App\Services;
  3. use App\Events\SendPersistentNotificationEvent;
  4. use App\Helpers\DateHelper;
  5. use App\Jobs\SendUserNotificationChannelJob;
  6. use App\Models\NotificationDeliveryLog;
  7. use App\Models\Order;
  8. use App\Models\Reclamation;
  9. use App\Models\Role;
  10. use App\Models\Schedule;
  11. use App\Models\User;
  12. use App\Models\UserNotification;
  13. use App\Models\UserNotificationSetting;
  14. use App\Notifications\FireBaseNotification;
  15. use Illuminate\Database\Eloquent\Collection;
  16. use Illuminate\Support\Facades\Mail;
  17. use Illuminate\Support\Str;
  18. class NotificationService
  19. {
  20. public function notifyOrderCreated(Order $order): void
  21. {
  22. $statusName = $order->orderStatus?->name ?? (Order::STATUS_NAMES[$order->order_status_id] ?? '-');
  23. $this->notifyOrderEvent(
  24. $order,
  25. UserNotification::EVENT_CREATED,
  26. 'Площадки',
  27. sprintf('Добавлена новая площадка %s', $order->object_address),
  28. sprintf(
  29. 'Добавлена новая площадка <a href="%s">%s</a>.',
  30. route('order.show', ['order' => $order->id]),
  31. e($order->object_address)
  32. ),
  33. $statusName,
  34. );
  35. }
  36. public function notifyOrderStatusChanged(Order $order): void
  37. {
  38. $statusName = $order->orderStatus?->name ?? (Order::STATUS_NAMES[$order->order_status_id] ?? '-');
  39. $this->notifyOrderEvent(
  40. $order,
  41. UserNotification::EVENT_STATUS_CHANGED,
  42. 'Площадки',
  43. sprintf('Статус площадки %s изменен на %s', $order->object_address, $statusName),
  44. sprintf(
  45. 'Статус площадки <a href="%s">%s</a> изменен на %s.',
  46. route('order.show', ['order' => $order->id]),
  47. e($order->object_address),
  48. e($statusName)
  49. ),
  50. $statusName,
  51. );
  52. }
  53. public function notifyReclamationCreated(Reclamation $reclamation): void
  54. {
  55. $order = $reclamation->order;
  56. if (!$order) {
  57. return;
  58. }
  59. $message = sprintf(
  60. 'Добавлена новая рекламация по адресу %s #%d',
  61. $order->object_address,
  62. $reclamation->id,
  63. );
  64. $messageHtml = sprintf(
  65. 'Добавлена новая рекламация по адресу <a href="%s">%s</a> <a href="%s">#%d</a>.',
  66. route('order.show', ['order' => $order->id]),
  67. e($order->object_address),
  68. route('reclamations.show', ['reclamation' => $reclamation->id]),
  69. $reclamation->id,
  70. );
  71. $this->notifyReclamationEvent(
  72. $reclamation,
  73. UserNotification::EVENT_CREATED,
  74. 'Рекламации',
  75. $message,
  76. $messageHtml,
  77. (int)$reclamation->status_id,
  78. );
  79. }
  80. public function notifyReclamationStatusChanged(Reclamation $reclamation): void
  81. {
  82. $order = $reclamation->order;
  83. if (!$order) {
  84. return;
  85. }
  86. $statusName = $reclamation->status?->name ?? (Reclamation::STATUS_NAMES[$reclamation->status_id] ?? '-');
  87. $message = sprintf(
  88. 'Статус рекламации %s #%d изменен на %s',
  89. $order->object_address,
  90. $reclamation->id,
  91. $statusName,
  92. );
  93. $messageHtml = sprintf(
  94. 'Статус рекламации по адресу <a href="%s">%s</a> <a href="%s">#%d</a> изменен на %s.',
  95. route('order.show', ['order' => $order->id]),
  96. e($order->object_address),
  97. route('reclamations.show', ['reclamation' => $reclamation->id]),
  98. $reclamation->id,
  99. e($statusName),
  100. );
  101. $this->notifyReclamationEvent(
  102. $reclamation,
  103. UserNotification::EVENT_STATUS_CHANGED,
  104. 'Рекламации',
  105. $message,
  106. $messageHtml,
  107. (int)$reclamation->status_id,
  108. );
  109. }
  110. public function notifyScheduleAdded(Schedule $schedule): void
  111. {
  112. $sourceKey = $this->sourceToSettingKey((string)$schedule->source);
  113. if (!$sourceKey) {
  114. return;
  115. }
  116. $brigadierName = $schedule->brigadier?->name ?? '-';
  117. $date = DateHelper::getHumanDate((string)$schedule->installation_date, true);
  118. if ((string)$schedule->source === 'Рекламации') {
  119. $reclamationId = $this->extractReclamationId((string)$schedule->address_code);
  120. $message = sprintf(
  121. 'Рекламация №%s по адресу %s добавлена в график на %s, Бригадир %s.',
  122. $reclamationId ?? '—',
  123. $schedule->object_address,
  124. $date,
  125. $brigadierName,
  126. );
  127. $reclamationLink = $reclamationId
  128. ? route('reclamations.show', ['reclamation' => $reclamationId])
  129. : route('schedule.index');
  130. $orderLink = $schedule->order_id
  131. ? route('order.show', ['order' => $schedule->order_id])
  132. : null;
  133. $addressHtml = $orderLink
  134. ? sprintf('<a href="%s">%s</a>', $orderLink, e($schedule->object_address))
  135. : e($schedule->object_address);
  136. $messageHtml = sprintf(
  137. '<a href="%s">Рекламация №%s</a> по адресу %s добавлена в график на %s, Бригадир %s.',
  138. $reclamationLink,
  139. $reclamationId ?? '—',
  140. $addressHtml,
  141. e($date),
  142. e($brigadierName),
  143. );
  144. } else {
  145. $message = sprintf(
  146. '%s добавлено в график монтажей на %s, Бригадир %s.',
  147. $schedule->object_address,
  148. $date,
  149. $brigadierName,
  150. );
  151. $orderLink = $schedule->order_id
  152. ? route('order.show', ['order' => $schedule->order_id])
  153. : route('schedule.index');
  154. $messageHtml = sprintf(
  155. '<a href="%s">%s</a> добавлено в график монтажей на %s, Бригадир %s.',
  156. $orderLink,
  157. e($schedule->object_address),
  158. e($date),
  159. e($brigadierName),
  160. );
  161. }
  162. $users = $this->scheduleRecipients($schedule);
  163. foreach ($users as $user) {
  164. $settings = $this->settingsForUser($user->id);
  165. if (!$settings->isSectionEnabled('schedule_settings')) {
  166. continue;
  167. }
  168. $channels = $settings->getChannelsForKey('schedule_settings', $sourceKey);
  169. if (empty($channels)) {
  170. continue;
  171. }
  172. $notification = $this->createInAppNotification(
  173. $user,
  174. UserNotification::TYPE_SCHEDULE,
  175. UserNotification::EVENT_SCHEDULE_ADDED,
  176. 'График монтажей',
  177. $message,
  178. $messageHtml,
  179. [
  180. 'schedule_id' => $schedule->id,
  181. 'source' => $schedule->source,
  182. ],
  183. );
  184. $this->dispatchDeliveryJobs($notification, [
  185. NotificationDeliveryLog::CHANNEL_BROWSER => !empty($channels['browser']),
  186. NotificationDeliveryLog::CHANNEL_PUSH => !empty($channels['push']),
  187. NotificationDeliveryLog::CHANNEL_EMAIL => !empty($channels['email']),
  188. ]);
  189. }
  190. }
  191. public function deliverChannel(int $userNotificationId, string $channel, int $attempt): void
  192. {
  193. $notification = UserNotification::query()->with('user')->find($userNotificationId);
  194. if (!$notification || !$notification->user) {
  195. return;
  196. }
  197. try {
  198. if ($channel === NotificationDeliveryLog::CHANNEL_BROWSER) {
  199. event(new SendPersistentNotificationEvent($notification->user_id, [
  200. 'id' => $notification->id,
  201. 'type' => $notification->type,
  202. 'title' => $notification->title,
  203. 'message' => $notification->message,
  204. 'message_html' => $notification->message_html,
  205. 'created_at' => $notification->created_at?->toDateTimeString(),
  206. ]));
  207. $this->createLog($notification, $channel, NotificationDeliveryLog::STATUS_SENT, $attempt, null);
  208. return;
  209. }
  210. if ($channel === NotificationDeliveryLog::CHANNEL_PUSH) {
  211. if (!$notification->user->token_fcm) {
  212. $this->createLog($notification, $channel, NotificationDeliveryLog::STATUS_SKIPPED, $attempt, 'Отсутствует token_fcm');
  213. return;
  214. }
  215. $notification->user->notify(new FireBaseNotification($notification->title, Str::limit(strip_tags($notification->message), 200)));
  216. $this->createLog($notification, $channel, NotificationDeliveryLog::STATUS_SENT, $attempt, null);
  217. return;
  218. }
  219. if ($channel === NotificationDeliveryLog::CHANNEL_EMAIL) {
  220. $email = $notification->user->notification_email;
  221. if (!$email || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
  222. $this->createLog($notification, $channel, NotificationDeliveryLog::STATUS_SKIPPED, $attempt, 'Отсутствует валидный notification_email');
  223. return;
  224. }
  225. Mail::html($notification->message_html, function ($message) use ($email, $notification) {
  226. $message->to($email)
  227. ->subject($notification->title);
  228. });
  229. $this->createLog($notification, $channel, NotificationDeliveryLog::STATUS_SENT, $attempt, null);
  230. return;
  231. }
  232. $this->createLog($notification, $channel, NotificationDeliveryLog::STATUS_SKIPPED, $attempt, 'Неизвестный канал');
  233. } catch (\Throwable $exception) {
  234. $this->createLog($notification, $channel, NotificationDeliveryLog::STATUS_FAILED, $attempt, $exception->getMessage());
  235. throw $exception;
  236. }
  237. }
  238. public function markDeadLetter(int $userNotificationId, string $channel, int $attempt, ?string $error = null): void
  239. {
  240. $notification = UserNotification::query()->find($userNotificationId);
  241. if (!$notification) {
  242. return;
  243. }
  244. $this->createLog($notification, $channel, NotificationDeliveryLog::STATUS_DEAD_LETTER, $attempt, $error);
  245. }
  246. private function notifyOrderEvent(
  247. Order $order,
  248. string $event,
  249. string $title,
  250. string $message,
  251. string $messageHtml,
  252. string $statusName,
  253. ): void {
  254. $users = $this->orderRecipients($order);
  255. $statusId = (int) $order->order_status_id;
  256. foreach ($users as $user) {
  257. $settings = $this->settingsForUser($user->id);
  258. if (!$settings->isSectionEnabled('order_settings')) {
  259. continue;
  260. }
  261. $channels = $settings->getChannelsForKey('order_settings', $statusId);
  262. if (empty($channels)) {
  263. continue;
  264. }
  265. $notification = $this->createInAppNotification(
  266. $user,
  267. UserNotification::TYPE_PLATFORM,
  268. $event,
  269. $title,
  270. $message,
  271. $messageHtml,
  272. [
  273. 'order_id' => $order->id,
  274. 'status' => $statusName,
  275. ],
  276. );
  277. $this->dispatchDeliveryJobs($notification, [
  278. NotificationDeliveryLog::CHANNEL_BROWSER => !empty($channels['browser']),
  279. NotificationDeliveryLog::CHANNEL_PUSH => !empty($channels['push']),
  280. NotificationDeliveryLog::CHANNEL_EMAIL => !empty($channels['email']),
  281. ]);
  282. }
  283. }
  284. private function notifyReclamationEvent(
  285. Reclamation $reclamation,
  286. string $event,
  287. string $title,
  288. string $message,
  289. string $messageHtml,
  290. int $statusId,
  291. ): void {
  292. $users = $this->reclamationRecipients($reclamation);
  293. foreach ($users as $user) {
  294. $settings = $this->settingsForUser($user->id);
  295. if (!$settings->isSectionEnabled('reclamation_settings')) {
  296. continue;
  297. }
  298. $channels = $settings->getChannelsForKey('reclamation_settings', $statusId);
  299. if (empty($channels)) {
  300. continue;
  301. }
  302. $notification = $this->createInAppNotification(
  303. $user,
  304. UserNotification::TYPE_RECLAMATION,
  305. $event,
  306. $title,
  307. $message,
  308. $messageHtml,
  309. [
  310. 'reclamation_id' => $reclamation->id,
  311. 'status_id' => $statusId,
  312. ],
  313. );
  314. $this->dispatchDeliveryJobs($notification, [
  315. NotificationDeliveryLog::CHANNEL_BROWSER => !empty($channels['browser']),
  316. NotificationDeliveryLog::CHANNEL_PUSH => !empty($channels['push']),
  317. NotificationDeliveryLog::CHANNEL_EMAIL => !empty($channels['email']),
  318. ]);
  319. }
  320. }
  321. private function dispatchDeliveryJobs(UserNotification $notification, array $channels): void
  322. {
  323. foreach ($channels as $channel => $enabled) {
  324. if (!$enabled) {
  325. continue;
  326. }
  327. SendUserNotificationChannelJob::dispatch($notification->id, $channel);
  328. }
  329. }
  330. private function createInAppNotification(
  331. User $user,
  332. string $type,
  333. string $event,
  334. string $title,
  335. string $message,
  336. string $messageHtml,
  337. array $payload,
  338. ): UserNotification {
  339. $notification = UserNotification::query()->create([
  340. 'user_id' => $user->id,
  341. 'type' => $type,
  342. 'event' => $event,
  343. 'title' => $title,
  344. 'message' => $message,
  345. 'message_html' => $messageHtml,
  346. 'data' => $payload,
  347. ]);
  348. $this->createLog($notification, NotificationDeliveryLog::CHANNEL_IN_APP, NotificationDeliveryLog::STATUS_SENT, 1, null);
  349. return $notification;
  350. }
  351. private function createLog(
  352. UserNotification $notification,
  353. string $channel,
  354. string $status,
  355. int $attempt,
  356. ?string $error,
  357. ): void {
  358. NotificationDeliveryLog::query()->create([
  359. 'user_notification_id' => $notification->id,
  360. 'user_id' => $notification->user_id,
  361. 'channel' => $channel,
  362. 'status' => $status,
  363. 'attempt' => $attempt,
  364. 'message' => $notification->message,
  365. 'error' => $error,
  366. ]);
  367. }
  368. private function settingsForUser(int $userId): UserNotificationSetting
  369. {
  370. return UserNotificationSetting::query()->firstOrCreate(
  371. ['user_id' => $userId],
  372. UserNotificationSetting::defaultsForUser($userId),
  373. );
  374. }
  375. private function orderRecipients(Order $order): Collection
  376. {
  377. $query = User::query()
  378. ->whereIn('role', [Role::ADMIN, Role::ASSISTANT_HEAD, Role::WAREHOUSE_HEAD]);
  379. if ($order->user_id) {
  380. $query->orWhere('id', $order->user_id);
  381. }
  382. return $query->distinct()->get();
  383. }
  384. private function reclamationRecipients(Reclamation $reclamation): Collection
  385. {
  386. $query = User::query()
  387. ->whereIn('role', [Role::ADMIN, Role::ASSISTANT_HEAD, Role::WAREHOUSE_HEAD]);
  388. $managerId = $reclamation->user_id;
  389. if ($managerId) {
  390. $query->orWhere('id', $managerId);
  391. }
  392. return $query->distinct()->get();
  393. }
  394. private function scheduleRecipients(Schedule $schedule): Collection
  395. {
  396. $query = User::query()
  397. ->whereIn('role', [Role::ADMIN, Role::ASSISTANT_HEAD, Role::WAREHOUSE_HEAD]);
  398. if ($schedule->brigadier_id) {
  399. $query->orWhere('id', $schedule->brigadier_id);
  400. }
  401. $managerId = null;
  402. if ((string)$schedule->source === 'Площадки' && $schedule->order_id) {
  403. $managerId = Order::query()
  404. ->withoutGlobalScope(\App\Models\Scopes\YearScope::class)
  405. ->where('id', $schedule->order_id)
  406. ->value('user_id');
  407. }
  408. if ((string)$schedule->source === 'Рекламации') {
  409. $reclamationId = $this->extractReclamationId((string)$schedule->address_code);
  410. if ($reclamationId) {
  411. $reclamation = Reclamation::query()
  412. ->withoutGlobalScope(\App\Models\Scopes\YearScope::class)
  413. ->with('order')
  414. ->find($reclamationId);
  415. $managerId = $reclamation?->order?->user_id ?: $reclamation?->user_id;
  416. }
  417. }
  418. if ($managerId) {
  419. $query->orWhere('id', $managerId);
  420. }
  421. return $query->distinct()->get();
  422. }
  423. private function extractReclamationId(string $addressCode): ?int
  424. {
  425. if (preg_match('/^РЕКЛ-(\d+)$/u', $addressCode, $matches)) {
  426. return (int)$matches[1];
  427. }
  428. return null;
  429. }
  430. private function sourceToSettingKey(string $source): ?string
  431. {
  432. return match ($source) {
  433. 'Площадки' => 'platform',
  434. 'Рекламации' => 'reclamation',
  435. default => null,
  436. };
  437. }
  438. }