chat.blade.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. @php
  2. /** @var \Illuminate\Support\Collection|\Illuminate\Database\Eloquent\Collection $messages */
  3. $messages = $messages ?? collect();
  4. $users = $users ?? collect();
  5. $responsibleUserIds = array_map('intval', $responsibleUserIds ?? []);
  6. $managerUserId = isset($managerUserId) ? (int) $managerUserId : null;
  7. $brigadierUserId = isset($brigadierUserId) ? (int) $brigadierUserId : null;
  8. $currentUserId = (int) auth()->id();
  9. $contextKey = $contextKey ?? 'chat';
  10. $title = $title ?? 'Чат';
  11. $submitLabel = $submitLabel ?? 'Отправить';
  12. $canSendNotifications = hasPermission('chat_messages.notify');
  13. $canDeleteMessages = hasAnyPermission(['orders.chat.delete', 'reclamations.chat.delete']) && !empty($action);
  14. $notificationValue = old('notification_type', \App\Models\ChatMessage::NOTIFICATION_NONE);
  15. $notificationEnabled = $canSendNotifications && $notificationValue !== \App\Models\ChatMessage::NOTIFICATION_NONE;
  16. $showAllUsers = $notificationValue === \App\Models\ChatMessage::NOTIFICATION_ALL;
  17. $selectedTargetUserIds = collect(old('target_user_ids', []))
  18. ->map(static fn ($id) => (int) $id)
  19. ->filter()
  20. ->unique()
  21. ->values()
  22. ->all();
  23. $sortedUsers = $users->sortBy('name');
  24. @endphp
  25. <div class="chat-block mt-3" data-chat-block data-context-key="{{ $contextKey }}">
  26. <hr>
  27. <h5>{{ $title }}</h5>
  28. <div class="chat-card">
  29. <div class="chat-messages-wrap">
  30. <div class="chat-messages" data-chat-messages>
  31. @forelse($messages as $message)
  32. <div class="chat-message">
  33. <div class="chat-message-header">
  34. <div>
  35. <strong>{{ $message->user?->name ?? 'Пользователь' }}</strong>
  36. @if($message->notification_type === \App\Models\ChatMessage::NOTIFICATION_USER && $message->targetUser)
  37. <span class="text-muted">для {{ $message->targetUser->name }}</span>
  38. @elseif(in_array($message->notification_type, [\App\Models\ChatMessage::NOTIFICATION_RESPONSIBLES, \App\Models\ChatMessage::NOTIFICATION_ALL], true))
  39. <span class="badge text-bg-light border">Уведомления: {{ $message->notifiedUsers->pluck('name')->join(', ') ?: 'получатели' }}</span>
  40. @endif
  41. </div>
  42. <div class="d-flex align-items-center gap-2">
  43. <small class="text-muted">{{ $message->created_at?->format('d.m.Y H:i') }}</small>
  44. @if($canDeleteMessages)
  45. <form action="{{ $action }}" method="post" class="d-inline">
  46. @csrf
  47. <input type="hidden" name="delete_message" value="1">
  48. <input type="hidden" name="chat_message_id" value="{{ $message->id }}">
  49. <i class="bi bi-x-circle-fill fs-6 text-danger cursor-pointer"
  50. onclick="customConfirm('Удалить сообщение?', function () { this.closest('form').submit(); }.bind(this), 'Подтверждение удаления')"
  51. title="Удалить"></i>
  52. </form>
  53. @endif
  54. </div>
  55. </div>
  56. @if(!empty($message->message))
  57. <div class="chat-message-text">{{ $message->message }}</div>
  58. @endif
  59. @if($message->files->isNotEmpty())
  60. <div class="chat-message-files">
  61. @foreach($message->files as $file)
  62. @if(\Illuminate\Support\Str::startsWith((string) $file->mime_type, 'image/'))
  63. <a href="{{ $file->link }}" target="_blank" data-toggle="lightbox" data-gallery="chat-{{ $contextKey }}" data-size="fullscreen">
  64. <img src="{{ $file->link }}" alt="{{ $file->original_name }}" class="img-thumbnail">
  65. </a>
  66. @else
  67. <a href="{{ $file->link }}" target="_blank" class="btn btn-sm btn-outline-secondary">
  68. <i class="bi bi-paperclip"></i> {{ $file->original_name }}
  69. </a>
  70. @endif
  71. @endforeach
  72. </div>
  73. @endif
  74. </div>
  75. @empty
  76. <div class="text-muted px-1">Сообщений пока нет.</div>
  77. @endforelse
  78. </div>
  79. <button type="button" class="btn btn-primary btn-sm chat-scroll-bottom d-none" data-chat-scroll-bottom>
  80. <i class="bi bi-arrow-down"></i>
  81. </button>
  82. </div>
  83. </div>
  84. <form action="{{ $action }}" method="post" enctype="multipart/form-data" class="mt-3" data-chat-form>
  85. @csrf
  86. {{-- Уведомления: свитч + саммари --}}
  87. @if($canSendNotifications)
  88. <div class="d-flex align-items-center gap-3 mb-2">
  89. <div class="form-check form-switch mb-0">
  90. <input
  91. class="form-check-input"
  92. type="checkbox"
  93. role="switch"
  94. id="chat-notify-toggle-{{ $contextKey }}"
  95. data-chat-notify-toggle
  96. @checked($notificationEnabled)
  97. >
  98. <label class="form-check-label small" for="chat-notify-toggle-{{ $contextKey }}">
  99. <i class="bi bi-bell"></i> Уведомить
  100. </label>
  101. </div>
  102. <div class="small text-muted {{ $notificationEnabled ? '' : 'd-none' }}" data-chat-recipient-summary-wrap>
  103. <a href="#" class="text-decoration-none" data-chat-open-recipient-modal data-bs-toggle="modal" data-bs-target="#chatRecipientsModal-{{ $contextKey }}">
  104. <span data-chat-recipient-summary>Получатели не выбраны</span>
  105. <i class="bi bi-pencil-square ms-1"></i>
  106. </a>
  107. </div>
  108. </div>
  109. {{-- Скрытый select для notification_type (значение управляется JS) --}}
  110. <input type="hidden" name="notification_type" value="{{ $notificationValue }}" data-chat-notification-type>
  111. @else
  112. <input type="hidden" name="notification_type" value="{{ \App\Models\ChatMessage::NOTIFICATION_NONE }}">
  113. @endif
  114. {{-- Строка ввода: textarea + иконка файла + кнопка отправить --}}
  115. <div class="d-flex align-items-center gap-2">
  116. <div class="flex-grow-1">
  117. <textarea
  118. class="form-control"
  119. id="chat-message-{{ $contextKey }}"
  120. name="message"
  121. rows="2"
  122. placeholder="Введите сообщение"
  123. >{{ old('message') }}</textarea>
  124. </div>
  125. <input class="d-none" id="chat-attachments-{{ $contextKey }}" type="file" name="attachments[]" multiple data-chat-file-input>
  126. <button type="button" class="btn btn-outline-secondary position-relative d-flex align-items-center justify-content-center" style="width: 38px; height: 38px; padding: 0;" title="Прикрепить файл" data-chat-attach-btn>
  127. <i class="bi bi-paperclip"></i>
  128. <span class="d-none position-absolute top-0 start-100 translate-middle badge rounded-pill bg-primary" style="font-size: .65em;" data-chat-file-count></span>
  129. </button>
  130. <button class="btn btn-primary d-flex align-items-center justify-content-center" style="width: 38px; height: 38px; padding: 0;" type="submit" title="{{ $submitLabel }}">
  131. <i class="bi bi-send"></i>
  132. </button>
  133. </div>
  134. <div data-chat-hidden-targets>
  135. @foreach($selectedTargetUserIds as $selectedTargetUserId)
  136. <input type="hidden" name="target_user_ids[]" value="{{ $selectedTargetUserId }}">
  137. @endforeach
  138. </div>
  139. </form>
  140. @if($canSendNotifications)
  141. <div class="modal fade" id="chatRecipientsModal-{{ $contextKey }}" tabindex="-1" aria-labelledby="chatRecipientsModalLabel-{{ $contextKey }}" aria-hidden="true">
  142. <div class="modal-dialog modal-dialog-scrollable">
  143. <div class="modal-content">
  144. <div class="modal-header">
  145. <h1 class="modal-title fs-5" id="chatRecipientsModalLabel-{{ $contextKey }}">Получатели уведомления</h1>
  146. <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Закрыть"></button>
  147. </div>
  148. <div class="modal-body" data-chat-recipient-modal-body>
  149. {{-- Свитч: показать всех пользователей --}}
  150. <div class="d-flex justify-content-between align-items-center mb-3">
  151. <div class="form-check form-switch mb-0">
  152. <input
  153. class="form-check-input"
  154. type="checkbox"
  155. role="switch"
  156. id="chat-show-all-toggle-{{ $contextKey }}"
  157. data-chat-show-all-toggle
  158. @checked($showAllUsers)
  159. >
  160. <label class="form-check-label" for="chat-show-all-toggle-{{ $contextKey }}">
  161. Показать всех
  162. </label>
  163. </div>
  164. <div class="d-flex gap-2">
  165. <button type="button" class="btn btn-sm btn-outline-primary" data-chat-check-visible>Выбрать всех</button>
  166. <button type="button" class="btn btn-sm btn-outline-secondary" data-chat-uncheck-visible>Снять всех</button>
  167. </div>
  168. </div>
  169. <div class="chat-recipient-list">
  170. @foreach($sortedUsers as $userId => $userData)
  171. @php
  172. $userRole = $userData['role'] ?? '';
  173. $isManagerOfEntity = $managerUserId && (int) $userId === $managerUserId;
  174. $isBrigadierOfEntity = $brigadierUserId && (int) $userId === $brigadierUserId;
  175. $roleLabel = $userRole ? roleName($userRole) : '';
  176. $displayLabel = $userData['name'];
  177. if ($roleLabel) {
  178. $displayLabel .= ' (' . $roleLabel . ')';
  179. }
  180. if ($isManagerOfEntity) {
  181. $displayLabel .= ' — менеджер площадки';
  182. }
  183. if ($isBrigadierOfEntity) {
  184. $displayLabel .= ' — бригадир площадки';
  185. }
  186. $isSelf = (int) $userId === $currentUserId;
  187. @endphp
  188. <label class="form-check mb-2 chat-recipient-item"
  189. data-chat-recipient-item
  190. data-user-id="{{ $userId }}"
  191. data-user-name="{{ $displayLabel }}"
  192. data-chat-responsible="{{ in_array((int) $userId, $responsibleUserIds, true) ? '1' : '0' }}"
  193. data-chat-self="{{ $isSelf ? '1' : '0' }}">
  194. <input
  195. class="form-check-input"
  196. type="checkbox"
  197. value="{{ $userId }}"
  198. data-chat-recipient-checkbox
  199. @disabled($isSelf)
  200. @checked(!$isSelf && in_array((int) $userId, $selectedTargetUserIds, true))
  201. >
  202. <span class="form-check-label {{ $isSelf ? 'text-muted' : '' }}">{{ $displayLabel }}@if($isSelf) (вы)@endif</span>
  203. </label>
  204. @endforeach
  205. </div>
  206. </div>
  207. <div class="modal-footer">
  208. <button type="button" class="btn btn-outline-secondary btn-sm" data-bs-dismiss="modal">Закрыть</button>
  209. <button type="button" class="btn btn-primary btn-sm" data-chat-apply-recipients data-bs-dismiss="modal">Применить</button>
  210. </div>
  211. </div>
  212. </div>
  213. </div>
  214. @endif
  215. </div>
  216. @once
  217. @push('scripts')
  218. <script type="module">
  219. function initChatBlock(block) {
  220. const messages = block.querySelector('[data-chat-messages]');
  221. const scrollButton = block.querySelector('[data-chat-scroll-bottom]');
  222. const form = block.querySelector('[data-chat-form]');
  223. const notifyToggle = block.querySelector('[data-chat-notify-toggle]');
  224. const notificationType = block.querySelector('[data-chat-notification-type]');
  225. const showAllToggle = block.querySelector('[data-chat-show-all-toggle]');
  226. const summaryWrap = block.querySelector('[data-chat-recipient-summary-wrap]');
  227. const summary = block.querySelector('[data-chat-recipient-summary]');
  228. const hiddenTargets = block.querySelector('[data-chat-hidden-targets]');
  229. const modal = block.querySelector('.modal');
  230. const fileInput = block.querySelector('[data-chat-file-input]');
  231. const attachBtn = block.querySelector('[data-chat-attach-btn]');
  232. const fileCount = block.querySelector('[data-chat-file-count]');
  233. // --- Файлы ---
  234. if (attachBtn && fileInput) {
  235. attachBtn.addEventListener('click', () => fileInput.click());
  236. fileInput.addEventListener('change', () => {
  237. const count = fileInput.files?.length || 0;
  238. if (fileCount) {
  239. fileCount.textContent = String(count);
  240. fileCount.classList.toggle('d-none', count === 0);
  241. }
  242. });
  243. }
  244. // --- Скролл ---
  245. const scrollToBottom = (force = false) => {
  246. if (!messages) return;
  247. const isNearBottom = messages.scrollHeight - messages.scrollTop - messages.clientHeight < 48;
  248. if (force || isNearBottom) {
  249. messages.scrollTop = messages.scrollHeight;
  250. }
  251. };
  252. const syncScrollButton = () => {
  253. if (!messages || !scrollButton) return;
  254. const shouldShow = messages.scrollHeight - messages.scrollTop - messages.clientHeight > 80;
  255. scrollButton.classList.toggle('d-none', !shouldShow);
  256. };
  257. // --- Получатели ---
  258. const getSelectedIds = () => Array.from(hiddenTargets.querySelectorAll('input[name="target_user_ids[]"]'))
  259. .map((input) => Number(input.value))
  260. .filter((value) => value > 0);
  261. const setSelectedIds = (ids) => {
  262. hiddenTargets.innerHTML = '';
  263. ids.forEach((id) => {
  264. const input = document.createElement('input');
  265. input.type = 'hidden';
  266. input.name = 'target_user_ids[]';
  267. input.value = String(id);
  268. hiddenTargets.appendChild(input);
  269. });
  270. };
  271. const visibleRecipientItems = () => Array.from(block.querySelectorAll('[data-chat-recipient-item]'))
  272. .filter((item) => !item.hidden);
  273. const syncRecipientSummary = () => {
  274. if (!summary) return;
  275. if (!notifyToggle || !notifyToggle.checked) {
  276. summary.textContent = 'Уведомления выключены';
  277. return;
  278. }
  279. const selectedIds = getSelectedIds();
  280. if (!selectedIds.length) {
  281. summary.textContent = 'Получатели не выбраны';
  282. return;
  283. }
  284. const names = selectedIds
  285. .map((id) => block.querySelector('[data-chat-recipient-item][data-user-id="' + id + '"]'))
  286. .filter(Boolean)
  287. .map((item) => item.dataset.userName);
  288. summary.textContent = 'Получатели: ' + names.join(', ');
  289. };
  290. const syncNotificationType = () => {
  291. if (!notificationType) return;
  292. if (!notifyToggle || !notifyToggle.checked) {
  293. notificationType.value = 'none';
  294. } else if (showAllToggle && showAllToggle.checked) {
  295. notificationType.value = 'all';
  296. } else {
  297. notificationType.value = 'responsibles';
  298. }
  299. };
  300. const applyRecipientFilter = (preserveSelection = true) => {
  301. if (!modal) return;
  302. const isAll = showAllToggle && showAllToggle.checked;
  303. const recipientItems = Array.from(block.querySelectorAll('[data-chat-recipient-item]'));
  304. const selectedIds = new Set(getSelectedIds());
  305. recipientItems.forEach((item) => {
  306. const isSelf = item.dataset.chatSelf === '1';
  307. const isResponsible = item.dataset.chatResponsible === '1';
  308. const visible = isAll || isResponsible;
  309. const checkbox = item.querySelector('[data-chat-recipient-checkbox]');
  310. item.hidden = !visible;
  311. checkbox.disabled = !visible || isSelf;
  312. checkbox.checked = checkbox.checked && !isSelf;
  313. if (!visible || isSelf) {
  314. checkbox.checked = false;
  315. }
  316. });
  317. if (!preserveSelection) {
  318. recipientItems.forEach((item) => {
  319. const checkbox = item.querySelector('[data-chat-recipient-checkbox]');
  320. if (!checkbox.disabled) {
  321. checkbox.checked = true;
  322. }
  323. });
  324. } else {
  325. recipientItems.forEach((item) => {
  326. const checkbox = item.querySelector('[data-chat-recipient-checkbox]');
  327. checkbox.checked = !checkbox.disabled && selectedIds.has(Number(item.dataset.userId));
  328. });
  329. const hasVisibleSelected = recipientItems.some((item) => {
  330. const checkbox = item.querySelector('[data-chat-recipient-checkbox]');
  331. return !checkbox.disabled && checkbox.checked;
  332. });
  333. if (!hasVisibleSelected) {
  334. recipientItems.forEach((item) => {
  335. const checkbox = item.querySelector('[data-chat-recipient-checkbox]');
  336. if (!checkbox.disabled) {
  337. checkbox.checked = true;
  338. }
  339. });
  340. }
  341. }
  342. };
  343. const commitRecipientSelection = () => {
  344. if (!notifyToggle || !notifyToggle.checked) {
  345. setSelectedIds([]);
  346. syncNotificationType();
  347. syncRecipientSummary();
  348. return;
  349. }
  350. const ids = visibleRecipientItems()
  351. .map((item) => item.querySelector('[data-chat-recipient-checkbox]'))
  352. .filter((checkbox) => checkbox && checkbox.checked)
  353. .map((checkbox) => Number(checkbox.value))
  354. .filter((value) => value > 0);
  355. setSelectedIds(ids);
  356. syncNotificationType();
  357. syncRecipientSummary();
  358. };
  359. // --- Инициализация скролла ---
  360. if (messages) {
  361. requestAnimationFrame(() => { scrollToBottom(true); syncScrollButton(); });
  362. setTimeout(() => { scrollToBottom(true); syncScrollButton(); }, 150);
  363. messages.addEventListener('scroll', syncScrollButton);
  364. }
  365. if (scrollButton) {
  366. scrollButton.addEventListener('click', () => scrollToBottom(true));
  367. }
  368. // --- Свитч уведомлений ---
  369. if (notifyToggle) {
  370. notifyToggle.addEventListener('change', () => {
  371. const enabled = notifyToggle.checked;
  372. if (summaryWrap) {
  373. summaryWrap.classList.toggle('d-none', !enabled);
  374. }
  375. if (!enabled) {
  376. setSelectedIds([]);
  377. syncNotificationType();
  378. syncRecipientSummary();
  379. return;
  380. }
  381. // Включили — сразу открываем модалку с ответственными
  382. applyRecipientFilter(false);
  383. commitRecipientSelection();
  384. if (modal) {
  385. bootstrap.Modal.getOrCreateInstance(modal).show();
  386. }
  387. });
  388. }
  389. // --- Свитч "Показать всех" в модалке ---
  390. if (showAllToggle) {
  391. showAllToggle.addEventListener('change', () => {
  392. applyRecipientFilter(false);
  393. syncNotificationType();
  394. });
  395. }
  396. // --- Открытие модалки вручную ---
  397. block.querySelector('[data-chat-open-recipient-modal]')?.addEventListener('click', () => {
  398. applyRecipientFilter(true);
  399. });
  400. // --- Выбрать/снять всех ---
  401. block.querySelector('[data-chat-check-visible]')?.addEventListener('click', () => {
  402. visibleRecipientItems().forEach((item) => {
  403. const checkbox = item.querySelector('[data-chat-recipient-checkbox]');
  404. if (checkbox) checkbox.checked = true;
  405. });
  406. });
  407. block.querySelector('[data-chat-uncheck-visible]')?.addEventListener('click', () => {
  408. visibleRecipientItems().forEach((item) => {
  409. const checkbox = item.querySelector('[data-chat-recipient-checkbox]');
  410. if (checkbox) checkbox.checked = false;
  411. });
  412. });
  413. // --- Применить / закрыть модалку ---
  414. block.querySelector('[data-chat-apply-recipients]')?.addEventListener('click', commitRecipientSelection);
  415. modal?.addEventListener('hidden.bs.modal', () => {
  416. if (notifyToggle && notifyToggle.checked) {
  417. commitRecipientSelection();
  418. }
  419. });
  420. // --- Сабмит формы ---
  421. form?.addEventListener('submit', () => {
  422. if (notifyToggle && notifyToggle.checked) {
  423. commitRecipientSelection();
  424. }
  425. });
  426. // --- Начальное состояние ---
  427. applyRecipientFilter(true);
  428. if (notifyToggle && notifyToggle.checked) {
  429. commitRecipientSelection();
  430. } else {
  431. syncNotificationType();
  432. syncRecipientSummary();
  433. }
  434. }
  435. document.querySelectorAll('[data-chat-block]').forEach(initChatBlock);
  436. </script>
  437. @endpush
  438. @endonce