chat.blade.php 21 KB

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