chat.blade.php 26 KB

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