chat.blade.php 25 KB

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