NotificationService.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810
  1. <?php
  2. namespace App\Services;
  3. use App\Enums\ProductionOrderNotificationEvent;
  4. use App\Events\SendPersistentNotificationEvent;
  5. use App\Helpers\DateHelper;
  6. use App\Jobs\SendUserNotificationChannelJob;
  7. use App\Models\ChatMessage;
  8. use App\Models\NotificationDeliveryLog;
  9. use App\Models\Order;
  10. use App\Models\ProductionOrder;
  11. use App\Models\ProductionOrderDelivery;
  12. use App\Models\ProductionOrderInstallation;
  13. use App\Models\Reclamation;
  14. use App\Models\Schedule;
  15. use App\Models\User;
  16. use App\Models\UserNotification;
  17. use App\Models\UserNotificationSetting;
  18. use App\Notifications\FireBaseNotification;
  19. use Illuminate\Database\Eloquent\Collection;
  20. use Illuminate\Support\Facades\Mail;
  21. use Illuminate\Support\Str;
  22. class NotificationService
  23. {
  24. public function notifyProductionOrderEvent(
  25. ProductionOrder $order,
  26. ProductionOrderNotificationEvent $event,
  27. ?User $author = null,
  28. ?ProductionOrderDelivery $delivery = null,
  29. ?ProductionOrderInstallation $installation = null,
  30. ): void {
  31. $order->loadMissing(['manager', 'deliveries.driver', 'installations.brigadier']);
  32. $authorSuffix = $author ? sprintf(' Изменил %s.', $author->name) : '';
  33. $authorSuffixHtml = $author ? sprintf(' Изменил %s.', e($author->name)) : '';
  34. $url = route('schedule.orders.show', $order);
  35. $label = 'заказ №'.$order->order_number;
  36. $htmlLabel = sprintf('<a href="%s">заказ №%s</a>', $url, e($order->order_number));
  37. [$message, $messageHtml] = match ($event) {
  38. ProductionOrderNotificationEvent::Created => [
  39. sprintf('Создан %s, %s.', $label, $order->object_address).$authorSuffix,
  40. sprintf('Создан %s, %s.', $htmlLabel, e($order->object_address)).$authorSuffixHtml,
  41. ],
  42. ProductionOrderNotificationEvent::StatusChanged => [
  43. sprintf('Статус %s изменён на «%s».', $label, $order->statusLabel()).$authorSuffix,
  44. sprintf('Статус %s изменён на «%s».', $htmlLabel, e($order->statusLabel())).$authorSuffixHtml,
  45. ],
  46. ProductionOrderNotificationEvent::DeliveryAdded => [
  47. sprintf(
  48. 'Для %s добавлена доставка на %s, водитель %s.',
  49. $label,
  50. $delivery?->delivery_date?->format('d.m.Y') ?? '—',
  51. $delivery?->driver?->name ?? '—',
  52. ).$authorSuffix,
  53. sprintf(
  54. 'Для %s добавлена доставка на %s, водитель %s.',
  55. $htmlLabel,
  56. e($delivery?->delivery_date?->format('d.m.Y') ?? '—'),
  57. e($delivery?->driver?->name ?? '—'),
  58. ).$authorSuffixHtml,
  59. ],
  60. ProductionOrderNotificationEvent::InstallationAdded => [
  61. sprintf(
  62. 'Для %s добавлен монтаж на %s, бригадир %s.',
  63. $label,
  64. $installation?->installation_date?->format('d.m.Y') ?? '—',
  65. $installation?->brigadier?->name ?? '—',
  66. ).$authorSuffix,
  67. sprintf(
  68. 'Для %s добавлен монтаж на %s, бригадир %s.',
  69. $htmlLabel,
  70. e($installation?->installation_date?->format('d.m.Y') ?? '—'),
  71. e($installation?->brigadier?->name ?? '—'),
  72. ).$authorSuffixHtml,
  73. ],
  74. ProductionOrderNotificationEvent::ReclamationAdded => [
  75. sprintf('Для %s добавлена рекламация.', $label).$authorSuffix,
  76. sprintf('Для %s добавлена рекламация.', $htmlLabel).$authorSuffixHtml,
  77. ],
  78. };
  79. foreach ($this->productionOrderRecipients($order) as $user) {
  80. $settings = $this->settingsForUser($user->id);
  81. $channels = $settings->getChannelsForKey('production_order_settings', $event->value);
  82. if ($channels === []) {
  83. continue;
  84. }
  85. $notification = $this->createInAppNotification(
  86. $user,
  87. UserNotification::TYPE_PRODUCTION_ORDER,
  88. $event->value,
  89. 'График заказов',
  90. $message,
  91. $messageHtml,
  92. [
  93. 'production_order_id' => $order->id,
  94. 'delivery_id' => $delivery?->id,
  95. 'installation_id' => $installation?->id,
  96. ],
  97. );
  98. $this->dispatchDeliveryJobs($notification, [
  99. NotificationDeliveryLog::CHANNEL_BROWSER => ! empty($channels['browser']),
  100. NotificationDeliveryLog::CHANNEL_PUSH => ! empty($channels['push']),
  101. NotificationDeliveryLog::CHANNEL_EMAIL => ! empty($channels['email']),
  102. ]);
  103. }
  104. }
  105. public function notifyChatMessage(ChatMessage $chatMessage, array $recipientIds = [], bool $forceBrowserNotification = false): void
  106. {
  107. $chatMessage->loadMissing([
  108. 'user',
  109. 'targetUser',
  110. 'order.user',
  111. 'order.brigadier',
  112. 'reclamation.order',
  113. 'reclamation.user',
  114. 'reclamation.brigadier',
  115. ]);
  116. $type = $chatMessage->order_id ? UserNotification::TYPE_PLATFORM : UserNotification::TYPE_RECLAMATION;
  117. $sourceKey = $chatMessage->order_id ? 'platform' : 'reclamation';
  118. $title = $chatMessage->order_id ? 'Чат площадки' : 'Чат рекламации';
  119. [$message, $messageHtml, $payload] = $this->buildChatNotificationContent($chatMessage, $type);
  120. foreach ($this->chatRecipients($chatMessage, $recipientIds) as $user) {
  121. $settings = $this->settingsForUser($user->id);
  122. if (!$forceBrowserNotification && !$settings->isSectionEnabled('chat_settings')) {
  123. continue;
  124. }
  125. $channels = $settings->getChannelsForKey('chat_settings', $sourceKey);
  126. if (!$forceBrowserNotification && empty($channels)) {
  127. continue;
  128. }
  129. $notification = $this->createInAppNotification(
  130. $user,
  131. $type,
  132. UserNotification::EVENT_CHAT_MESSAGE,
  133. $title,
  134. $message,
  135. $messageHtml,
  136. $payload,
  137. );
  138. $this->dispatchDeliveryJobs($notification, [
  139. NotificationDeliveryLog::CHANNEL_BROWSER => $forceBrowserNotification || !empty($channels['browser']),
  140. NotificationDeliveryLog::CHANNEL_PUSH => !empty($channels['push']),
  141. NotificationDeliveryLog::CHANNEL_EMAIL => !empty($channels['email']),
  142. ]);
  143. }
  144. }
  145. public function notifyOrderCreated(Order $order, ?User $author = null): void
  146. {
  147. $statusName = $order->orderStatus?->name ?? (Order::STATUS_NAMES[$order->order_status_id] ?? '-');
  148. $authorSuffix = $author ? sprintf(' Изменил %s.', $author->name) : '';
  149. $authorSuffixHtml = $author ? sprintf(' Изменил %s.', e($author->name)) : '';
  150. $this->notifyOrderEvent(
  151. $order,
  152. UserNotification::EVENT_CREATED,
  153. 'Площадки',
  154. sprintf('Добавлена новая площадка %s.', $order->object_address) . $authorSuffix,
  155. sprintf(
  156. 'Добавлена новая площадка <a href="%s">%s</a>.',
  157. route('order.show', ['order' => $order->id, 'sync_year' => 1]),
  158. e($order->object_address)
  159. ) . $authorSuffixHtml,
  160. $statusName,
  161. );
  162. }
  163. public function notifyOrderStatusChanged(Order $order, ?User $author = null): void
  164. {
  165. $statusName = $order->orderStatus?->name ?? (Order::STATUS_NAMES[$order->order_status_id] ?? '-');
  166. $authorSuffix = $author ? sprintf(' Изменил %s.', $author->name) : '';
  167. $authorSuffixHtml = $author ? sprintf(' Изменил %s.', e($author->name)) : '';
  168. $this->notifyOrderEvent(
  169. $order,
  170. UserNotification::EVENT_STATUS_CHANGED,
  171. 'Площадки',
  172. sprintf('Статус площадки %s изменен на %s.', $order->object_address, $statusName) . $authorSuffix,
  173. sprintf(
  174. 'Статус площадки <a href="%s">%s</a> изменен на %s.',
  175. route('order.show', ['order' => $order->id, 'sync_year' => 1]),
  176. e($order->object_address),
  177. e($statusName)
  178. ) . $authorSuffixHtml,
  179. $statusName,
  180. );
  181. }
  182. public function notifyReclamationCreated(Reclamation $reclamation, ?User $author = null): void
  183. {
  184. $order = $reclamation->order;
  185. if (!$order) {
  186. return;
  187. }
  188. $authorSuffix = $author ? sprintf(' Изменил %s.', $author->name) : '';
  189. $authorSuffixHtml = $author ? sprintf(' Изменил %s.', e($author->name)) : '';
  190. $message = sprintf(
  191. 'Добавлена новая рекламация по адресу %s #%d.',
  192. $order->object_address,
  193. $reclamation->id,
  194. ) . $authorSuffix;
  195. $messageHtml = sprintf(
  196. 'Добавлена новая рекламация по адресу <a href="%s">%s</a> <a href="%s">#%d</a>.',
  197. route('order.show', ['order' => $order->id, 'sync_year' => 1]),
  198. e($order->object_address),
  199. route('reclamations.show', ['reclamation' => $reclamation->id]),
  200. $reclamation->id,
  201. ) . $authorSuffixHtml;
  202. $this->notifyReclamationEvent(
  203. $reclamation,
  204. UserNotification::EVENT_CREATED,
  205. 'Рекламации',
  206. $message,
  207. $messageHtml,
  208. (int)$reclamation->status_id,
  209. );
  210. }
  211. public function notifyReclamationStatusChanged(Reclamation $reclamation, ?User $author = null): void
  212. {
  213. $order = $reclamation->order;
  214. if (!$order) {
  215. return;
  216. }
  217. $statusName = $reclamation->status?->name ?? (Reclamation::STATUS_NAMES[$reclamation->status_id] ?? '-');
  218. $authorSuffix = $author ? sprintf(' Изменил %s.', $author->name) : '';
  219. $authorSuffixHtml = $author ? sprintf(' Изменил %s.', e($author->name)) : '';
  220. $message = sprintf(
  221. 'Статус рекламации %s #%d изменен на %s.',
  222. $order->object_address,
  223. $reclamation->id,
  224. $statusName,
  225. ) . $authorSuffix;
  226. $messageHtml = sprintf(
  227. 'Статус рекламации по адресу <a href="%s">%s</a> <a href="%s">#%d</a> изменен на %s.',
  228. route('order.show', ['order' => $order->id, 'sync_year' => 1]),
  229. e($order->object_address),
  230. route('reclamations.show', ['reclamation' => $reclamation->id]),
  231. $reclamation->id,
  232. e($statusName),
  233. ) . $authorSuffixHtml;
  234. $this->notifyReclamationEvent(
  235. $reclamation,
  236. UserNotification::EVENT_STATUS_CHANGED,
  237. 'Рекламации',
  238. $message,
  239. $messageHtml,
  240. (int)$reclamation->status_id,
  241. );
  242. }
  243. public function notifyScheduleAdded(Schedule $schedule, ?User $author = null): void
  244. {
  245. $sourceKey = $this->sourceToSettingKey((string)$schedule->source);
  246. if (!$sourceKey) {
  247. return;
  248. }
  249. $brigadierName = $schedule->brigadier?->name ?? '-';
  250. $date = DateHelper::getHumanDate((string)$schedule->installation_date, true);
  251. $authorSuffix = $author ? sprintf(' Изменил %s.', $author->name) : '';
  252. $authorSuffixHtml = $author ? sprintf(' Изменил %s.', e($author->name)) : '';
  253. if ((string)$schedule->source === 'Рекламации') {
  254. $reclamationId = $this->extractReclamationId((string)$schedule->address_code);
  255. $message = sprintf(
  256. 'Рекламация №%s по адресу %s добавлена в график на %s, Бригадир %s.',
  257. $reclamationId ?? '—',
  258. $schedule->object_address,
  259. $date,
  260. $brigadierName,
  261. ) . $authorSuffix;
  262. $reclamationLink = $reclamationId
  263. ? route('reclamations.show', ['reclamation' => $reclamationId])
  264. : route('schedule.index');
  265. $orderLink = $schedule->order_id
  266. ? route('order.show', ['order' => $schedule->order_id, 'sync_year' => 1])
  267. : null;
  268. $addressHtml = $orderLink
  269. ? sprintf('<a href="%s">%s</a>', $orderLink, e($schedule->object_address))
  270. : e($schedule->object_address);
  271. $messageHtml = sprintf(
  272. '<a href="%s">Рекламация №%s</a> по адресу %s добавлена в график на %s, Бригадир %s.',
  273. $reclamationLink,
  274. $reclamationId ?? '—',
  275. $addressHtml,
  276. e($date),
  277. e($brigadierName),
  278. ) . $authorSuffixHtml;
  279. } else {
  280. $message = sprintf(
  281. '%s добавлено в график монтажей на %s, Бригадир %s.',
  282. $schedule->object_address,
  283. $date,
  284. $brigadierName,
  285. ) . $authorSuffix;
  286. $orderLink = $schedule->order_id
  287. ? route('order.show', ['order' => $schedule->order_id, 'sync_year' => 1])
  288. : route('schedule.index');
  289. $messageHtml = sprintf(
  290. '<a href="%s">%s</a> добавлено в график монтажей на %s, Бригадир %s.',
  291. $orderLink,
  292. e($schedule->object_address),
  293. e($date),
  294. e($brigadierName),
  295. ) . $authorSuffixHtml;
  296. }
  297. $users = $this->scheduleRecipients($schedule);
  298. foreach ($users as $user) {
  299. $settings = $this->settingsForUser($user->id);
  300. if (!$settings->isSectionEnabled('schedule_settings')) {
  301. continue;
  302. }
  303. $channels = $settings->getChannelsForKey('schedule_settings', $sourceKey);
  304. if (empty($channels)) {
  305. continue;
  306. }
  307. $notification = $this->createInAppNotification(
  308. $user,
  309. UserNotification::TYPE_SCHEDULE,
  310. UserNotification::EVENT_SCHEDULE_ADDED,
  311. 'График монтажей',
  312. $message,
  313. $messageHtml,
  314. [
  315. 'schedule_id' => $schedule->id,
  316. 'source' => $schedule->source,
  317. ],
  318. );
  319. $this->dispatchDeliveryJobs($notification, [
  320. NotificationDeliveryLog::CHANNEL_BROWSER => !empty($channels['browser']),
  321. NotificationDeliveryLog::CHANNEL_PUSH => !empty($channels['push']),
  322. NotificationDeliveryLog::CHANNEL_EMAIL => !empty($channels['email']),
  323. ]);
  324. }
  325. }
  326. public function deliverChannel(int $userNotificationId, string $channel, int $attempt): void
  327. {
  328. $notification = UserNotification::query()->with('user')->find($userNotificationId);
  329. if (!$notification || !$notification->user) {
  330. return;
  331. }
  332. try {
  333. if ($channel === NotificationDeliveryLog::CHANNEL_BROWSER) {
  334. event(new SendPersistentNotificationEvent($notification->user_id, [
  335. 'id' => $notification->id,
  336. 'type' => $notification->type,
  337. 'title' => $notification->title,
  338. 'message' => $notification->message,
  339. 'message_html' => $notification->message_html,
  340. 'created_at' => $notification->created_at?->toDateTimeString(),
  341. ]));
  342. $this->createLog($notification, $channel, NotificationDeliveryLog::STATUS_SENT, $attempt, null);
  343. return;
  344. }
  345. if ($channel === NotificationDeliveryLog::CHANNEL_PUSH) {
  346. if (!$notification->user->token_fcm) {
  347. $this->createLog($notification, $channel, NotificationDeliveryLog::STATUS_SKIPPED, $attempt, 'Отсутствует token_fcm');
  348. return;
  349. }
  350. $notification->user->notify(new FireBaseNotification($notification->title, Str::limit(strip_tags($notification->message), 200)));
  351. $this->createLog($notification, $channel, NotificationDeliveryLog::STATUS_SENT, $attempt, null);
  352. return;
  353. }
  354. if ($channel === NotificationDeliveryLog::CHANNEL_EMAIL) {
  355. $email = $notification->user->notification_email;
  356. if (!$email || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
  357. $this->createLog($notification, $channel, NotificationDeliveryLog::STATUS_SKIPPED, $attempt, 'Отсутствует валидный notification_email');
  358. return;
  359. }
  360. Mail::html($notification->message_html, function ($message) use ($email, $notification) {
  361. $message->to($email)
  362. ->subject($notification->title);
  363. });
  364. $this->createLog($notification, $channel, NotificationDeliveryLog::STATUS_SENT, $attempt, null);
  365. return;
  366. }
  367. $this->createLog($notification, $channel, NotificationDeliveryLog::STATUS_SKIPPED, $attempt, 'Неизвестный канал');
  368. } catch (\Throwable $exception) {
  369. $this->createLog($notification, $channel, NotificationDeliveryLog::STATUS_FAILED, $attempt, $exception->getMessage());
  370. throw $exception;
  371. }
  372. }
  373. public function markDeadLetter(int $userNotificationId, string $channel, int $attempt, ?string $error = null): void
  374. {
  375. $notification = UserNotification::query()->find($userNotificationId);
  376. if (!$notification) {
  377. return;
  378. }
  379. $this->createLog($notification, $channel, NotificationDeliveryLog::STATUS_DEAD_LETTER, $attempt, $error);
  380. }
  381. private function notifyOrderEvent(
  382. Order $order,
  383. string $event,
  384. string $title,
  385. string $message,
  386. string $messageHtml,
  387. string $statusName,
  388. ): void {
  389. $users = $this->orderRecipients($order);
  390. $statusId = (int) $order->order_status_id;
  391. foreach ($users as $user) {
  392. $settings = $this->settingsForUser($user->id);
  393. if (!$settings->isSectionEnabled('order_settings')) {
  394. continue;
  395. }
  396. $channels = $settings->getChannelsForKey('order_settings', $statusId);
  397. if (empty($channels)) {
  398. continue;
  399. }
  400. $notification = $this->createInAppNotification(
  401. $user,
  402. UserNotification::TYPE_PLATFORM,
  403. $event,
  404. $title,
  405. $message,
  406. $messageHtml,
  407. [
  408. 'order_id' => $order->id,
  409. 'status' => $statusName,
  410. ],
  411. );
  412. $this->dispatchDeliveryJobs($notification, [
  413. NotificationDeliveryLog::CHANNEL_BROWSER => !empty($channels['browser']),
  414. NotificationDeliveryLog::CHANNEL_PUSH => !empty($channels['push']),
  415. NotificationDeliveryLog::CHANNEL_EMAIL => !empty($channels['email']),
  416. ]);
  417. }
  418. }
  419. private function notifyReclamationEvent(
  420. Reclamation $reclamation,
  421. string $event,
  422. string $title,
  423. string $message,
  424. string $messageHtml,
  425. int $statusId,
  426. ): void {
  427. $users = $this->reclamationRecipients($reclamation);
  428. foreach ($users as $user) {
  429. $settings = $this->settingsForUser($user->id);
  430. if (!$settings->isSectionEnabled('reclamation_settings')) {
  431. continue;
  432. }
  433. $channels = $settings->getChannelsForKey('reclamation_settings', $statusId);
  434. if (empty($channels)) {
  435. continue;
  436. }
  437. $notification = $this->createInAppNotification(
  438. $user,
  439. UserNotification::TYPE_RECLAMATION,
  440. $event,
  441. $title,
  442. $message,
  443. $messageHtml,
  444. [
  445. 'reclamation_id' => $reclamation->id,
  446. 'status_id' => $statusId,
  447. ],
  448. );
  449. $this->dispatchDeliveryJobs($notification, [
  450. NotificationDeliveryLog::CHANNEL_BROWSER => !empty($channels['browser']),
  451. NotificationDeliveryLog::CHANNEL_PUSH => !empty($channels['push']),
  452. NotificationDeliveryLog::CHANNEL_EMAIL => !empty($channels['email']),
  453. ]);
  454. }
  455. }
  456. private function dispatchDeliveryJobs(UserNotification $notification, array $channels): void
  457. {
  458. foreach ($channels as $channel => $enabled) {
  459. if (!$enabled) {
  460. continue;
  461. }
  462. SendUserNotificationChannelJob::dispatch($notification->id, $channel);
  463. }
  464. }
  465. private function createInAppNotification(
  466. User $user,
  467. string $type,
  468. string $event,
  469. string $title,
  470. string $message,
  471. string $messageHtml,
  472. array $payload,
  473. ): UserNotification {
  474. $notification = UserNotification::query()->create([
  475. 'user_id' => $user->id,
  476. 'type' => $type,
  477. 'event' => $event,
  478. 'title' => $title,
  479. 'message' => $message,
  480. 'message_html' => $messageHtml,
  481. 'data' => $payload,
  482. ]);
  483. $this->createLog($notification, NotificationDeliveryLog::CHANNEL_IN_APP, NotificationDeliveryLog::STATUS_SENT, 1, null);
  484. return $notification;
  485. }
  486. private function createLog(
  487. UserNotification $notification,
  488. string $channel,
  489. string $status,
  490. int $attempt,
  491. ?string $error,
  492. ): void {
  493. NotificationDeliveryLog::query()->create([
  494. 'user_notification_id' => $notification->id,
  495. 'user_id' => $notification->user_id,
  496. 'channel' => $channel,
  497. 'status' => $status,
  498. 'attempt' => $attempt,
  499. 'message' => $notification->message,
  500. 'error' => $error,
  501. ]);
  502. }
  503. private function settingsForUser(int $userId): UserNotificationSetting
  504. {
  505. return UserNotificationSetting::query()->firstOrCreate(
  506. ['user_id' => $userId],
  507. UserNotificationSetting::defaultsForUser($userId),
  508. );
  509. }
  510. private function orderRecipients(Order $order): Collection
  511. {
  512. $query = User::query()
  513. ->withAnyPermission(['orders.scope.admin', 'orders.scope.warehouse_head']);
  514. if ($order->user_id) {
  515. $query->orWhere('id', $order->user_id);
  516. }
  517. return $query->distinct()->get();
  518. }
  519. private function productionOrderRecipients(ProductionOrder $order): Collection
  520. {
  521. $ids = collect([$order->manager_id])
  522. ->merge($order->deliveries->pluck('driver_id'))
  523. ->merge($order->installations->pluck('brigadier_id'))
  524. ->filter()
  525. ->map(static fn ($id): int => (int) $id)
  526. ->unique()
  527. ->values();
  528. return User::query()->whereKey($ids)->get();
  529. }
  530. private function reclamationRecipients(Reclamation $reclamation): Collection
  531. {
  532. $query = User::query()
  533. ->withAnyPermission(['reclamations.scope.admin', 'reclamations.scope.warehouse_head']);
  534. $managerId = $reclamation->user_id;
  535. if ($managerId) {
  536. $query->orWhere('id', $managerId);
  537. }
  538. return $query->distinct()->get();
  539. }
  540. private function scheduleRecipients(Schedule $schedule): Collection
  541. {
  542. $query = User::query()
  543. ->withAnyPermission(['schedule.scope.admin', 'orders.scope.warehouse_head', 'reclamations.scope.warehouse_head']);
  544. if ($schedule->brigadier_id) {
  545. $query->orWhere('id', $schedule->brigadier_id);
  546. }
  547. $managerId = null;
  548. if ((string)$schedule->source === 'Площадки' && $schedule->order_id) {
  549. $managerId = Order::query()
  550. ->withoutGlobalScope(\App\Models\Scopes\YearScope::class)
  551. ->where('id', $schedule->order_id)
  552. ->value('user_id');
  553. }
  554. if ((string)$schedule->source === 'Рекламации') {
  555. $reclamationId = $this->extractReclamationId((string)$schedule->address_code);
  556. if ($reclamationId) {
  557. $reclamation = Reclamation::query()
  558. ->withoutGlobalScope(\App\Models\Scopes\YearScope::class)
  559. ->with('order')
  560. ->find($reclamationId);
  561. $managerId = $reclamation?->order?->user_id ?: $reclamation?->user_id;
  562. }
  563. }
  564. if ($managerId) {
  565. $query->orWhere('id', $managerId);
  566. }
  567. return $query->distinct()->get();
  568. }
  569. private function extractReclamationId(string $addressCode): ?int
  570. {
  571. if (preg_match('/^РЕКЛ-(\d+)$/u', $addressCode, $matches)) {
  572. return (int)$matches[1];
  573. }
  574. return null;
  575. }
  576. private function sourceToSettingKey(string $source): ?string
  577. {
  578. return match ($source) {
  579. 'Площадки' => 'platform',
  580. 'Рекламации' => 'reclamation',
  581. default => null,
  582. };
  583. }
  584. private function chatRecipients(ChatMessage $chatMessage, array $recipientIds = []): Collection
  585. {
  586. $recipientIds = array_values(array_unique(array_map(static fn ($id) => (int) $id, $recipientIds)));
  587. $recipientIds = array_values(array_diff($recipientIds, [(int) $chatMessage->user_id]));
  588. if (!empty($recipientIds)) {
  589. return User::query()
  590. ->whereIn('id', $recipientIds)
  591. ->get();
  592. }
  593. if ($chatMessage->notification_type === ChatMessage::NOTIFICATION_USER) {
  594. if (!$chatMessage->target_user_id || (int) $chatMessage->target_user_id === (int) $chatMessage->user_id) {
  595. return new Collection();
  596. }
  597. return User::query()
  598. ->where('id', $chatMessage->target_user_id)
  599. ->get();
  600. }
  601. if (!in_array($chatMessage->notification_type, [
  602. ChatMessage::NOTIFICATION_ALL,
  603. ChatMessage::NOTIFICATION_RESPONSIBLES,
  604. ], true)) {
  605. return new Collection();
  606. }
  607. $recipientIds = [];
  608. if ($chatMessage->order) {
  609. $recipientIds = $chatMessage->notification_type === ChatMessage::NOTIFICATION_ALL
  610. ? $this->allChatRecipientIds()
  611. : $this->chatResponsibleRecipientIdsForOrder($chatMessage->order);
  612. }
  613. if ($chatMessage->reclamation) {
  614. $recipientIds = $chatMessage->notification_type === ChatMessage::NOTIFICATION_ALL
  615. ? $this->allChatRecipientIds()
  616. : $this->chatResponsibleRecipientIdsForReclamation($chatMessage->reclamation);
  617. }
  618. $recipientIds = array_values(array_unique(array_filter($recipientIds)));
  619. $recipientIds = array_values(array_diff($recipientIds, [(int) $chatMessage->user_id]));
  620. if (empty($recipientIds)) {
  621. return new Collection();
  622. }
  623. return User::query()
  624. ->whereIn('id', $recipientIds)
  625. ->get();
  626. }
  627. private function allChatRecipientIds(): array
  628. {
  629. return User::query()
  630. ->pluck('id')
  631. ->map(static fn ($id) => (int) $id)
  632. ->all();
  633. }
  634. private function chatResponsibleRecipientIdsForOrder(Order $order): array
  635. {
  636. $adminIds = User::query()
  637. ->withPermission('orders.scope.admin')
  638. ->pluck('id')
  639. ->map(static fn ($id) => (int) $id)
  640. ->all();
  641. return array_merge($adminIds, [
  642. $order->user_id ? (int) $order->user_id : null,
  643. $order->brigadier_id ? (int) $order->brigadier_id : null,
  644. ]);
  645. }
  646. private function chatResponsibleRecipientIdsForReclamation(Reclamation $reclamation): array
  647. {
  648. $adminIds = User::query()
  649. ->withPermission('reclamations.scope.admin')
  650. ->pluck('id')
  651. ->map(static fn ($id) => (int) $id)
  652. ->all();
  653. return array_merge($adminIds, [
  654. $reclamation->user_id ? (int) $reclamation->user_id : null,
  655. $reclamation->brigadier_id ? (int) $reclamation->brigadier_id : null,
  656. ]);
  657. }
  658. private function buildChatNotificationContent(ChatMessage $chatMessage, string $type): array
  659. {
  660. $senderName = $chatMessage->user?->name ?? 'Пользователь';
  661. $text = trim((string) $chatMessage->message);
  662. $text = $text !== '' ? Str::limit($text, 200) : 'Вложение';
  663. if ($type === UserNotification::TYPE_PLATFORM) {
  664. $order = $chatMessage->order;
  665. $address = $order?->object_address ?? '-';
  666. $orderUrl = $order ? route('order.show', ['order' => $order->id, 'sync_year' => 1]) : route('order.index');
  667. $message = sprintf('Новое сообщение в чате площадки %s от %s: %s', $address, $senderName, $text);
  668. $messageHtml = sprintf(
  669. 'Новое сообщение в <a href="%s">чате площадки %s</a> от %s: %s',
  670. $orderUrl,
  671. e($address),
  672. e($senderName),
  673. e($text)
  674. );
  675. return [$message, $messageHtml, [
  676. 'chat_message_id' => $chatMessage->id,
  677. 'order_id' => $order?->id,
  678. ]];
  679. }
  680. $reclamation = $chatMessage->reclamation;
  681. $address = $reclamation?->order?->object_address ?? '-';
  682. $reclamationUrl = $reclamation
  683. ? route('reclamations.show', ['reclamation' => $reclamation->id, 'sync_year' => 1])
  684. : route('reclamations.index');
  685. $reclamationNumber = $reclamation?->id ? ('#' . $reclamation->id) : '#-';
  686. $message = sprintf('Новое сообщение в чате рекламации %s по адресу %s от %s: %s', $reclamationNumber, $address, $senderName, $text);
  687. $messageHtml = sprintf(
  688. 'Новое сообщение в <a href="%s">чате рекламации %s</a> по адресу %s от %s: %s',
  689. $reclamationUrl,
  690. e($reclamationNumber),
  691. e($address),
  692. e($senderName),
  693. e($text)
  694. );
  695. return [$message, $messageHtml, [
  696. 'chat_message_id' => $chatMessage->id,
  697. 'reclamation_id' => $reclamation?->id,
  698. ]];
  699. }
  700. }