NotificationService.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  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. $message = sprintf(
  119. '%s добавлено в график монтажей на %s, Бригадир %s.',
  120. $schedule->object_address,
  121. $date,
  122. $brigadierName,
  123. );
  124. $orderLink = $schedule->order_id
  125. ? route('order.show', ['order' => $schedule->order_id])
  126. : route('schedule.index');
  127. $messageHtml = sprintf(
  128. '<a href="%s">%s</a> добавлено в график монтажей на %s, Бригадир %s.',
  129. $orderLink,
  130. e($schedule->object_address),
  131. e($date),
  132. e($brigadierName),
  133. );
  134. $users = $this->scheduleRecipients($schedule);
  135. foreach ($users as $user) {
  136. $settings = $this->settingsForUser($user->id);
  137. if (!$settings->isSectionEnabled('schedule_settings')) {
  138. continue;
  139. }
  140. $channels = $settings->getChannelsForKey('schedule_settings', $sourceKey);
  141. if (empty($channels)) {
  142. continue;
  143. }
  144. $notification = $this->createInAppNotification(
  145. $user,
  146. UserNotification::TYPE_SCHEDULE,
  147. UserNotification::EVENT_SCHEDULE_ADDED,
  148. 'График монтажей',
  149. $message,
  150. $messageHtml,
  151. [
  152. 'schedule_id' => $schedule->id,
  153. 'source' => $schedule->source,
  154. ],
  155. );
  156. $this->dispatchDeliveryJobs($notification, [
  157. NotificationDeliveryLog::CHANNEL_BROWSER => !empty($channels['browser']),
  158. NotificationDeliveryLog::CHANNEL_PUSH => !empty($channels['push']),
  159. NotificationDeliveryLog::CHANNEL_EMAIL => !empty($channels['email']),
  160. ]);
  161. }
  162. }
  163. public function deliverChannel(int $userNotificationId, string $channel, int $attempt): void
  164. {
  165. $notification = UserNotification::query()->with('user')->find($userNotificationId);
  166. if (!$notification || !$notification->user) {
  167. return;
  168. }
  169. try {
  170. if ($channel === NotificationDeliveryLog::CHANNEL_BROWSER) {
  171. event(new SendPersistentNotificationEvent($notification->user_id, [
  172. 'id' => $notification->id,
  173. 'type' => $notification->type,
  174. 'title' => $notification->title,
  175. 'message' => $notification->message,
  176. 'message_html' => $notification->message_html,
  177. 'created_at' => $notification->created_at?->toDateTimeString(),
  178. ]));
  179. $this->createLog($notification, $channel, NotificationDeliveryLog::STATUS_SENT, $attempt, null);
  180. return;
  181. }
  182. if ($channel === NotificationDeliveryLog::CHANNEL_PUSH) {
  183. if (!$notification->user->token_fcm) {
  184. $this->createLog($notification, $channel, NotificationDeliveryLog::STATUS_SKIPPED, $attempt, 'Отсутствует token_fcm');
  185. return;
  186. }
  187. $notification->user->notify(new FireBaseNotification($notification->title, Str::limit(strip_tags($notification->message), 200)));
  188. $this->createLog($notification, $channel, NotificationDeliveryLog::STATUS_SENT, $attempt, null);
  189. return;
  190. }
  191. if ($channel === NotificationDeliveryLog::CHANNEL_EMAIL) {
  192. $email = $notification->user->notification_email;
  193. if (!$email || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
  194. $this->createLog($notification, $channel, NotificationDeliveryLog::STATUS_SKIPPED, $attempt, 'Отсутствует валидный notification_email');
  195. return;
  196. }
  197. Mail::raw($notification->message, function ($mail) use ($email, $notification) {
  198. $mail->to($email)
  199. ->subject($notification->title);
  200. });
  201. $this->createLog($notification, $channel, NotificationDeliveryLog::STATUS_SENT, $attempt, null);
  202. return;
  203. }
  204. $this->createLog($notification, $channel, NotificationDeliveryLog::STATUS_SKIPPED, $attempt, 'Неизвестный канал');
  205. } catch (\Throwable $exception) {
  206. $this->createLog($notification, $channel, NotificationDeliveryLog::STATUS_FAILED, $attempt, $exception->getMessage());
  207. throw $exception;
  208. }
  209. }
  210. public function markDeadLetter(int $userNotificationId, string $channel, int $attempt, ?string $error = null): void
  211. {
  212. $notification = UserNotification::query()->find($userNotificationId);
  213. if (!$notification) {
  214. return;
  215. }
  216. $this->createLog($notification, $channel, NotificationDeliveryLog::STATUS_DEAD_LETTER, $attempt, $error);
  217. }
  218. private function notifyOrderEvent(
  219. Order $order,
  220. string $event,
  221. string $title,
  222. string $message,
  223. string $messageHtml,
  224. string $statusName,
  225. ): void {
  226. $users = $this->orderRecipients($order);
  227. $statusId = (int) $order->order_status_id;
  228. foreach ($users as $user) {
  229. $settings = $this->settingsForUser($user->id);
  230. if (!$settings->isSectionEnabled('order_settings')) {
  231. continue;
  232. }
  233. $channels = $settings->getChannelsForKey('order_settings', $statusId);
  234. if (empty($channels)) {
  235. continue;
  236. }
  237. $notification = $this->createInAppNotification(
  238. $user,
  239. UserNotification::TYPE_PLATFORM,
  240. $event,
  241. $title,
  242. $message,
  243. $messageHtml,
  244. [
  245. 'order_id' => $order->id,
  246. 'status' => $statusName,
  247. ],
  248. );
  249. $this->dispatchDeliveryJobs($notification, [
  250. NotificationDeliveryLog::CHANNEL_BROWSER => !empty($channels['browser']),
  251. NotificationDeliveryLog::CHANNEL_PUSH => !empty($channels['push']),
  252. NotificationDeliveryLog::CHANNEL_EMAIL => !empty($channels['email']),
  253. ]);
  254. }
  255. }
  256. private function notifyReclamationEvent(
  257. Reclamation $reclamation,
  258. string $event,
  259. string $title,
  260. string $message,
  261. string $messageHtml,
  262. int $statusId,
  263. ): void {
  264. $users = $this->reclamationRecipients($reclamation);
  265. foreach ($users as $user) {
  266. $settings = $this->settingsForUser($user->id);
  267. if (!$settings->isSectionEnabled('reclamation_settings')) {
  268. continue;
  269. }
  270. $channels = $settings->getChannelsForKey('reclamation_settings', $statusId);
  271. if (empty($channels)) {
  272. continue;
  273. }
  274. $notification = $this->createInAppNotification(
  275. $user,
  276. UserNotification::TYPE_RECLAMATION,
  277. $event,
  278. $title,
  279. $message,
  280. $messageHtml,
  281. [
  282. 'reclamation_id' => $reclamation->id,
  283. 'status_id' => $statusId,
  284. ],
  285. );
  286. $this->dispatchDeliveryJobs($notification, [
  287. NotificationDeliveryLog::CHANNEL_BROWSER => !empty($channels['browser']),
  288. NotificationDeliveryLog::CHANNEL_PUSH => !empty($channels['push']),
  289. NotificationDeliveryLog::CHANNEL_EMAIL => !empty($channels['email']),
  290. ]);
  291. }
  292. }
  293. private function dispatchDeliveryJobs(UserNotification $notification, array $channels): void
  294. {
  295. foreach ($channels as $channel => $enabled) {
  296. if (!$enabled) {
  297. continue;
  298. }
  299. SendUserNotificationChannelJob::dispatch($notification->id, $channel);
  300. }
  301. }
  302. private function createInAppNotification(
  303. User $user,
  304. string $type,
  305. string $event,
  306. string $title,
  307. string $message,
  308. string $messageHtml,
  309. array $payload,
  310. ): UserNotification {
  311. $notification = UserNotification::query()->create([
  312. 'user_id' => $user->id,
  313. 'type' => $type,
  314. 'event' => $event,
  315. 'title' => $title,
  316. 'message' => $message,
  317. 'message_html' => $messageHtml,
  318. 'data' => $payload,
  319. ]);
  320. $this->createLog($notification, NotificationDeliveryLog::CHANNEL_IN_APP, NotificationDeliveryLog::STATUS_SENT, 1, null);
  321. return $notification;
  322. }
  323. private function createLog(
  324. UserNotification $notification,
  325. string $channel,
  326. string $status,
  327. int $attempt,
  328. ?string $error,
  329. ): void {
  330. NotificationDeliveryLog::query()->create([
  331. 'user_notification_id' => $notification->id,
  332. 'user_id' => $notification->user_id,
  333. 'channel' => $channel,
  334. 'status' => $status,
  335. 'attempt' => $attempt,
  336. 'message' => $notification->message,
  337. 'error' => $error,
  338. ]);
  339. }
  340. private function settingsForUser(int $userId): UserNotificationSetting
  341. {
  342. return UserNotificationSetting::query()->firstOrCreate(
  343. ['user_id' => $userId],
  344. UserNotificationSetting::defaultsForUser($userId),
  345. );
  346. }
  347. private function orderRecipients(Order $order): Collection
  348. {
  349. $query = User::query()
  350. ->whereIn('role', [Role::ADMIN, Role::ASSISTANT_HEAD, Role::WAREHOUSE_HEAD]);
  351. if ($order->user_id) {
  352. $query->orWhere('id', $order->user_id);
  353. }
  354. return $query->distinct()->get();
  355. }
  356. private function reclamationRecipients(Reclamation $reclamation): Collection
  357. {
  358. $query = User::query()
  359. ->whereIn('role', [Role::ADMIN, Role::ASSISTANT_HEAD, Role::WAREHOUSE_HEAD]);
  360. $managerId = $reclamation->order?->user_id ?: $reclamation->user_id;
  361. if ($managerId) {
  362. $query->orWhere('id', $managerId);
  363. }
  364. return $query->distinct()->get();
  365. }
  366. private function scheduleRecipients(Schedule $schedule): Collection
  367. {
  368. $query = User::query()
  369. ->whereIn('role', [Role::ADMIN, Role::ASSISTANT_HEAD, Role::WAREHOUSE_HEAD]);
  370. if ($schedule->brigadier_id) {
  371. $query->orWhere('id', $schedule->brigadier_id);
  372. }
  373. $managerId = null;
  374. if ((string)$schedule->source === 'Площадки' && $schedule->order_id) {
  375. $managerId = Order::query()
  376. ->withoutGlobalScope(\App\Models\Scopes\YearScope::class)
  377. ->where('id', $schedule->order_id)
  378. ->value('user_id');
  379. }
  380. if ((string)$schedule->source === 'Рекламации') {
  381. $reclamationId = $this->extractReclamationId((string)$schedule->address_code);
  382. if ($reclamationId) {
  383. $reclamation = Reclamation::query()
  384. ->withoutGlobalScope(\App\Models\Scopes\YearScope::class)
  385. ->with('order')
  386. ->find($reclamationId);
  387. $managerId = $reclamation?->order?->user_id ?: $reclamation?->user_id;
  388. }
  389. }
  390. if ($managerId) {
  391. $query->orWhere('id', $managerId);
  392. }
  393. return $query->distinct()->get();
  394. }
  395. private function extractReclamationId(string $addressCode): ?int
  396. {
  397. if (preg_match('/^РЕКЛ-(\d+)$/u', $addressCode, $matches)) {
  398. return (int)$matches[1];
  399. }
  400. return null;
  401. }
  402. private function sourceToSettingKey(string $source): ?string
  403. {
  404. return match ($source) {
  405. 'Площадки' => 'platform',
  406. 'Рекламации' => 'reclamation',
  407. default => null,
  408. };
  409. }
  410. }