chat.blade.php 26 KB

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