import Ajax from '../components/ajax.js' import Modal from './modal.js' import ClassSelect from './select2.js' import { alertConfirmAction, alertConfirmationDelete, alertError, alertSuccess } from "./alerts/sweetAlert.js" class Chat { constructor(domItem) { this.domItem = domItem this.chatList = this.domItem.find("#chat-list") this.chatHistory = this.domItem.find("#chat-conversation") this.modelId = this.domItem.data("id") this.chatHistoryBody = this.domItem.find(".chat-history-body") this.sendBtnMessageDepartment = this.domItem.find("#send-msg-btn-deparment") this.sendBtnMessageDepartmentClient = this.domItem.find("#send-msg-btn-deparment-client") this.sendBtnMessageInternal = this.domItem.find("#send-msg-btn-internal") this.chatSidebarLeftUserAbout = this.domItem.find('.chat-sidebar-left-user-about'), this.messageInput = this.domItem.find(".message-input") this.sideBar = this.domItem.find(".sidebar-body") this.selectItem = this.domItem.find(".chat-search-client") this.btnExitChat = this.domItem.find(".exit-chat") this.btnSubscribeChat = this.domItem.find(".subscribe-chat") this.chatDeparmentId = undefined this.searchInput = this.domItem.find(".chat-search-input") this.headers = {} this.chatContactsBody = this.domItem.find('.app-chat-contacts .sidebar-body') this.chatContactListItems = [].slice.call( document.querySelectorAll('.chat-contact-list-item:not(.chat-contact-list-item-title)') ) } init() { if (this.searchInput.length) { this.searchInput.on('keyup', () => { const searchValue = this.searchInput.val(), chatListItem0 = this.domItem.find('.chat-list-item-0'), contactListItem0 = this.domItem.find('.contact-list-item-0'), searchChatListItems = this.domItem.find('#chat-list li:not(.chat-contact-list-item-title)'), searchContactListItems = this.domItem.find('#contact-list li:not(.chat-contact-list-item-title)'); // Buscar en chats const chatListItemsCount = this._searchChatContacts(searchChatListItems, searchValue); // Mostrar u ocultar mensaje de "No se encontraron resultados" en chats if (chatListItem0.length) { chatListItem0.toggleClass('d-none', chatListItemsCount === 0); } // Buscar en contactos const contactListItemsCount = this._searchChatContacts(searchContactListItems, searchValue); // Mostrar u ocultar mensaje de "No se encontraron resultados" en contactos if (contactListItem0.length) { contactListItem0.toggleClass('d-none', contactListItemsCount === 0); } }); } this.sendBtnMessageDepartment.addClass("d-none") this.btnExitChat.on('click', this._handleExitChatDepartment.bind(this)) this.btnSubscribeChat.on('click', this._handleSubscribeChatDepartment.bind(this)) this.sendBtnMessageInternal.addClass("d-none") if (this.chatContactsBody[0]) { this.scrollbarContacts = new PerfectScrollbar(this.chatContactsBody[0], { wheelPropagation: false, suppressScrollX: true, }); } if (this.chatHistoryBody[0]) { this.scrollbarChatHistory = new PerfectScrollbar(this.chatHistoryBody[0], { wheelPropagation: false, suppressScrollX: true, }); } } initDirectMessage() { this.chatType = "direct" this.modalNewParticipant = new Modal(this.domItem.find("#modalAddNewChatParticipant")) this.selectPlaceholder = { id: '0', text: "Seleccione un usuario" } this.btnUpdateMessagesUnviewed = this.domItem.find("#update-message-unviewed") this.btnDirectMessageSubmit = this.domItem.find("#send-msg-btn-direct") this.btnDirectMessageSubmit.on("click", this._handleStoreChatDirectMessage.bind(this)) this.messageInput.on("keypress", this._sendDirectMessagePressKey.bind(this)) this.selectParticipants = new ClassSelect(this.modalNewParticipant.item.find("#select-users"), `/chat/direct/users/select/${this.modelId}`, this.selectPlaceholder, true) this.authUserId = this.domItem.data("user-id") this.checkboxNotificationMessage = this.modalNewParticipant.item.find("#checkbox-notification-chat") this.btnAddParticipant = this.domItem.find("#btn-chat-add-participant") this.btnAddParticipantSubmit = this.domItem.find("#btn-chat-add-participant-submit") this.btnAddParticipantSubmit.on("click", this._handleStoreChatDirectUsers.bind(this)) this.btnAddParticipant.on("click", () => { this.selectParticipants.init() this.modalNewParticipant.toggle() }) this.selectParticipants.item.on("change", () => { if (this.selectParticipants.getVal().length > 0) { this.btnAddParticipantSubmit.removeClass("d-none") } else { this.btnAddParticipantSubmit.addClass("d-none") } }) this.btnUpdateMessagesUnviewed.on("click", this._handleUpdateChatMessagesUnread.bind(this)) this._handleGetChatDirect() setInterval(this._handleReloadChatDirectMessages.bind(this), 10000) } initSelectClient() { this.selectClientUser = new ClassSelect(this.selectItem, `/chat/direct/client/users/select/${this.chatType}/${this.modelId}`, "Seleccione contacto", true) this.selectClientUser.init() this.selectItem.on('change', () => { if (this.selectClientUser.getVal()) { this.sendBtnMessageDepartment.attr('disabled', null) } else { this.sendBtnMessageDepartment.attr('disabled', 'disabled') } }) } initGeneral() { this.chatType = "general" this._handleGetChatList() this.sendBtnMessageDepartment.on("click", this._sendMessage.bind(this)) this.sendBtnMessageDepartmentClient.on("click", this._sendMessage.bind(this)) } initPresupuesto() { this.chatType = "presupuesto" this._handleGetChatList() this.sendBtnMessageDepartment.on("click", this._sendMessage.bind(this)) this.sendBtnMessageDepartmentClient.on("click", this._sendMessage.bind(this)) this.messageInput.on("keypress", this._sendMessagePressKey.bind(this)) this.initSelectClient() // setInterval(this._getChatMessage.bind(this), 10000) } initPedido() { this.chatType = "pedido" this._handleGetChatList() this.sendBtnMessageDepartment.on("click", this._sendMessage.bind(this)) this.sendBtnMessageDepartmentClient.on("click", this._sendMessage.bind(this)) this.messageInput.on("keypress", this._sendMessagePressKey.bind(this)) this.initSelectClient() // setInterval(this._getChatMessage.bind(this), 10000) } initFactura() { this.chatType = "factura" this._handleGetChatList() this.sendBtnMessageDepartment.on("click", this._sendMessage.bind(this)) this.sendBtnMessageDepartmentClient.on("click", this._sendMessage.bind(this)) this.messageInput.on("keypress", this._sendMessagePressKey.bind(this)) this.initSelectClient() // setInterval(this._getChatMessage.bind(this), 10000) } initContacts() { this.chatType = "internal" } _searchChatContacts(searchListItems, searchValue) { let searchListItemsCount = 0; searchListItems.each(function () { const searchListItemText = $(this).text().toLowerCase(); const matchesSearch = searchListItemText.indexOf(searchValue) !== -1; $(this).toggleClass('d-flex', matchesSearch); $(this).toggleClass('d-none', !matchesSearch); if (matchesSearch) { searchListItemsCount++; } }); return searchListItemsCount; } _setBtnInternal() { this.sendBtnMessageInternal.removeClass("d-none") this.sendBtnMessageDepartment.addClass("d-none") } _setBtnDeparment() { this.sendBtnMessageDepartment.removeClass("d-none") this.sendBtnMessageInternal.addClass("d-none") } /**============================================ * PRESUPUESTOS *=============================================**/ _handleGetChatList(event) { this.domItem.find(".chat-loader").removeClass("d-none") let ajax = new Ajax( `/chat/departments/${this.chatType}/${this.modelId}`, null, null, this._handleGetChatListSuccess.bind(this), this._handleGetChatListError.bind(this), ); ajax.get(); } _handleGetChatListSuccess(data) { this.domItem.find(".chat-loader").addClass("d-none") Object.values(data).map(row => { this.chatList.append(this._getContact(row)) this.chatDeparmentId = row.id this.chatList.find(`#chat_${row.name}`).on("click", (event) => { $(".chat-contact-list-item").removeClass("active") $(event.currentTarget).parent().addClass("active") this.chatHistory.empty() this.chatDeparmentId = this.chatList.find(`#chat_${row.name}`).data("id") this.domItem.find(".chat-history-header div.chat-contact-info h6").text(row.display) this.domItem.find(".chat-history-header div.chat-contact-info small.user-status").text(row.display) this._getChatMessage() this._getChatDeparmentUsers() }) }) if (Object.values(data)) { const firstDepartment = Object.values(data)[0] this.chatList.find(`#chat_${firstDepartment.name}`).trigger("click"); } } _handleGetChatListError(error) { console.error(error) } _getChatDeparmentUsers() { this.domItem.find("#chat-header-users").empty() this.domItem.find("#chat-header-dropdown-users").removeClass("d-none") let ajax = new Ajax( `/chat/department/users/${this.chatType}/${this.chatDeparmentId}/${this.modelId}`, null, null, this._getChatDeparmentUsersSuccess.bind(this), this._getChatDeparmentUsersError.bind(this), ) ajax.get() } _getChatDeparmentUsersSuccess(deparmentUsers) { deparmentUsers.adminUsers.map(user => this.appendChatDepartmentUser(user)) deparmentUsers.externalUsers.map(user => this.appendChatDepartmentUser(user, 'warning', 'user')) } appendChatDepartmentUser(user, color = "primary", icon = "user") { this.domItem.find("#chat-header-users").append( `
  • ${user?.first_name ?? "" + " " + user?.last_name ?? ""}

    ${user.username}

  • ` ) } _getChatDeparmentUsersError(err) { } _getContact(row) { let chat = `
  • ${row.display.charAt(0)}
    ${row.display}

    ${row.display}

    ${row.countMessages}
  • ` return chat } _getChatTotalMessages(row_name) { let ajax = new Ajax( `/chat/department/${this.chatType}/${this.chatDeparmentId}/${this.modelId}`, null, null, (data) => { }, null ); ajax.get(); } _getChatDepartmentMessageCount() { let ajax = new Ajax( `/chat/department/count/${this.chatType}/${this.chatDeparmentId}/${this.modelId}`, null, null, this._getChatDepartmentMessageCountSuccess.bind(this), this._getChatDepartmentMessageCountError.bind(this), ); ajax.get(); } _getChatDepartmentMessageCountSuccess(data) { this.domItem.find(`chat_${data.name}`).find(".messages-unread-contact").text(data.count) } _getChatDepartmentMessageCountError() { } _getChatMessage() { this.chatHistory.empty() this.domItem.find(".chat-loader").removeClass("d-none") let ajax = new Ajax( `/chat/department/${this.chatType}/${this.chatDeparmentId}/${this.modelId}`, null, null, this._getChatMessageSuccess.bind(this), this._getChatMessageError.bind(this), ); ajax.get(); } _getChatMessageSuccess(data) { this.domItem.find(".chat-loader").addClass("d-none") this._setBtnDeparment() this.chatList.find(`#chat_${data.department.name} .messages-unread-contact`).text(data.count ?? 0) if (data.messages) { data.messages.map((m) => { this._addChatMessage(m) }) } } _getChatMessageError(err) { console.log(err) } _addChatMessage(chatMessage, pos = "left") { let chatItem = `
  • ${chatMessage?.message}

    ${chatMessage?.user?.first_name + " " + chatMessage?.user?.last_name}
    ${chatMessage.created_at}
  • ` this.chatHistory.append(chatItem) return chatItem } _addChatDirectMessages(chatMessage) { let chatItem = `
  • ${chatMessage?.message}

    ${chatMessage?.sender_first_name + " " + chatMessage?.sender_last_name}
    ${chatMessage.created_at}
    ${chatMessage?.sender_first_name.charAt(0) + chatMessage?.sender_last_name.charAt(0)}
  • ` this.chatHistory.append(chatItem) return chatItem } _sendMessagePressKey(e) { if (e.which == 13) { e.preventDefault(); this._sendMessage() } } _sendDirectMessagePressKey(e) { if (e.which == 13) { e.preventDefault(); this._handleStoreChatDirectMessage() } } _sendMessage() { let messageText = this.messageInput.val() const body = { message: messageText, chat_department_id: this.chatDeparmentId, user: this.userId, client: this.selectClientUser.getVal() ?? null, model_id: this.modelId } if (messageText) { let ajax = new Ajax( `/chat/message/${this.chatType}`, body, null, this._sendMessageSuccess.bind(this), this._sendMessageError.bind(this), ); ajax.post(); } } _sendMessageSuccess(data) { this.messageInput.val("") this._getChatMessage(this.chatDeparmentId) this._getChatDeparmentUsers() } _sendMessageError(err) { console.error(err) } _handleListContacts() { this.sideBar.find("#contact-list").removeClass("d-none") this.sendBtnMessageInternal.on("click", this._sendMessageInternal.bind(this)) this.sendBtnMessageInternal.on("keypress", this._sendMessageInternalPressKey.bind(this)) let ajax = new Ajax( "/chat/contacts", null, null, this._handleListContactsSuccess.bind(this), this._handleListContactsError.bind(this) ) ajax.get() } _handleListContactsSuccess(contacts) { try { if (contacts.length) { contacts.map((c, index) => { this._addContactToList(c) }); } else { this.sideBar.find("#contact-list").addClass("d-none") } this.sideBar.find(".contact-chat").on("click", (e) => { // $(e.currentTarget).find(".messages-unread-contact").empty() $(".contact-chat").parent().removeClass("active") $(".chat-contact-list-item").removeClass("active") this.chatHistory.empty() this.domItem.find("#chat-header-dropdown-users").addClass("d-none") let userId = $(e.currentTarget).data("id") $(e.currentTarget).parent().addClass('active') this.receiverId = userId this._handleGetSingleContact(userId) this._setBtnInternal() }) } catch (error) { } finally { this.domItem.find(`#chat-contact-list-item-${contacts[0].id}`).click() } } _handleListContactsError(err) { console.error(err) } _handleGetSingleContact(userId) { let ajax = new Ajax( `/chat/contacts/${userId}`, null, null, this._handleGetSingleContactSuccess.bind(this), this._handleGetSingleContactError.bind(this), ) ajax.get() } _handleGetSingleContactSuccess(contact) { this.domItem.find(".chat-history-header div.chat-contact-info h6").text([contact.first_name, contact.last_name].join(" ")) this.domItem.find(".chat-history-header div.chat-contact-info small.user-status").text(contact.username) let ajax = new Ajax( `/chat/contact/${contact.id}/messages`, null, null, this._handleGetSingleContactMessagesSuccess.bind(this), this._handleGetSingleContactMessagesError.bind(this) ) ajax.get() } _handleGetSingleContactMessagesSuccess(data) { try { if (data) { data.map((m) => { this._addChatMessage(m) }) } } catch (error) { } finally { // console.log(this.chatHistoryBody[0].scrollTop) this.scrollbarChatHistory.update() this.chatHistoryBody[0].scrollTop = this.scrollbarChatHistory.containerHeight } } _handleGetSingleContactMessagesError(err) { } _handleGetSingleContactError(err) { } _sendMessageInternalPressKey(e) { if (e.which == 13) { e.preventDefault(); this._sendMessageInternal() } } _sendMessageInternal() { let messageText = this.messageInput.val() const body = { message: messageText, receiver_id: this.receiverId, } if (messageText) { let ajax = new Ajax( `/chat/message/internal`, body, null, this._sendMessageInternalSuccess.bind(this), this._sendMessageInternalError.bind(this), ); ajax.post(); } } _sendMessageInternalSuccess(message) { this.messageInput.val("") this.chatHistory.empty() this._handleGetSingleContact(this.receiverId) } _sendMessageInternalError(err) { console.error(err) } _addContactToList(contact) { let contactItem = `
  • ${contact?.first_name?.charAt(0) ?? "?" + contact?.last_name?.charAt(0) ?? "?"}
    ${contact?.first_name ?? "" + " " + contact?.last_name ?? ""}

    ${contact?.cliente_id ? "[CLIENTE]" : ""}${contact.username}

    ${contact.unreadMessages ? `${contact.unreadMessages}` : ""}
  • ` if (contact.first_name || contact.last_name) { this.sideBar.find("#contact-list").append(contactItem) } } _addParticipantToList(contact) { let contactItem = `
  • ${contact?.first_name?.charAt(0) ?? "?" + contact?.last_name?.charAt(0) ?? "?"}
    ${contact?.first_name ?? "" + " " + contact?.last_name ?? ""}

    ${contact?.cliente_id ? "[CLIENTE]" : ""}${contact.username}

  • ` if (contact.first_name || contact.last_name) { this.sideBar.find("#contact-list").append(contactItem) } } _handleGetChatDirect() { const ajax = new Ajax( `/chat/${this.chatType}/conversation/${this.modelId}`, null, null, this._handleGetChatDirectSuccess.bind(this), this._handleGetChatDirectError.bind(this) ) ajax.get() } _handleGetChatDirectSuccess(response) { const { chat, users, messages } = response if (users.length > 0) { users.map(c => this._addParticipantToList(c)) } if (messages.length > 0) { messages.map(m => this._addChatDirectMessages(m)) } this.domItem.find("#chat-direct-title").text(chat.title) this.domItem.find(".chat-loader").addClass("d-none") } _handleGetChatDirectError(error) { } _handleReloadChatDirectMessages() { const ajax = new Ajax( `/chat/${this.chatType}/conversation/${this.modelId}`, null, null, this._handleReloadChatDirectMessagesSuccess.bind(this), this._handleReloadChatDirectMessagesError.bind(this) ) ajax.get() } _handleReloadChatDirectMessagesSuccess(response) { const { chat, users, messages } = response this.chatHistory.empty() if (messages.length > 0) { messages.map(m => this._addChatDirectMessages(m)) } this.domItem.find("#chat-direct-title").text(chat.title) this.domItem.find(".chat-loader").addClass("d-none") } _handleReloadChatDirectMessagesError(error) { } _handleStoreChatDirectUsers() { const data = { "users": this.selectParticipants.getVal(), "notification": this.checkboxNotificationMessage.prop("checked") } this.domItem.find(".chat-loader").removeClass("d-none") const ajax = new Ajax( `/chat/${this.chatType}/users/${this.modelId}`, data, null, this._handleStoreChatDirectUsersSuccess.bind(this), this._handleStoreChatDirectUsersError.bind(this) ) ajax.post() } _handleStoreChatDirectUsersSuccess(response) { this.domItem.find(".chat-loader").removeClass("d-none") this.chatHistory.empty() this.sideBar.find("#contact-list").empty() this.modalNewParticipant.toggle() this._handleGetChatDirect() this.selectParticipants.reset() } _handleStoreChatDirectUsersError() { this.domItem.find(".chat-loader").removeClass("d-none") } _handleStoreChatDirectMessage() { const data = { "message": this.messageInput.val(), "chat_id": this.modelId } if (data.message) { const ajax = new Ajax( `/chat/${this.chatType}/messages/${this.modelId}`, data, null, this._handleStoreChatDirectMessageSuccess.bind(this), this._handleStoreChatDirectMessageError.bind(this) ) ajax.post() } } _handleStoreChatDirectMessageSuccess(response) { try { let message = response this._addChatDirectMessages(message) this.messageInput.val("") } catch (error) { } finally { this.scrollbarChatHistory.update() this.chatHistoryBody[0].scrollTop = this.scrollbarChatHistory.containerHeight } } _handleStoreChatDirectMessageError(error) { } _handleUpdateChatMessagesUnread() { const ajax = new Ajax( `/chat/${this.chatType}/messages/unread/${this.modelId}`, null, null, this._handleUpdateChatMessagesUnreadSuccess.bind(this), this._handleUpdateChatMessagesUnreadError.bind(this) ) ajax.post() } _handleUpdateChatMessagesUnreadSuccess() { this._handleReloadChatDirectMessages(); } _handleUpdateChatMessagesUnreadError() { } _handleRequestExitChatDeparment() { const ajax = new Ajax('/chat/department/user/' + this.chatDeparmentId, { model_fk: this.chatType + "_id", model_id_fk: this.modelId }, null, (response) => { if (response.status) { alertSuccess(response.message).fire() this._getChatDeparmentUsers() } else { alertError(response.message).fire() } }, (error) => { alertError("Error") } ) ajax.delete(); } _handleRequestSubscribeChatDeparment() { const ajax = new Ajax('/chat/department/user', { chat_department_id: this.chatDeparmentId, model_fk: this.chatType + "_id", model_id_fk: this.modelId }, null, (response) => { if (response.status) { alertSuccess(response.message).fire() this._getChatDeparmentUsers() } else { alertError(response.message).fire() } }, (error) => { alertError("Error") } ) ajax.post(); } _handleExitChatDepartment() { if (this.chatDeparmentId) { alertConfirmationDelete('¿Estás seguro de salir de la conversación?').then((result) => { if (result.isConfirmed) { this._handleRequestExitChatDeparment() } }) } } _handleSubscribeChatDepartment() { if (this.chatDeparmentId) { alertConfirmAction('¿Estás seguro de subscribirte al chat?').then((result) => { if (result.isConfirmed) { this._handleRequestSubscribeChatDeparment() } }) } } } const addInternalNotification = (e) => { let numberOfMessages = e.unreadMessages if (numberOfMessages > 0) { $("#chat-notification-list").append( `
  • ${e.avatar}
    [${e.title}] ${e.chatDisplay}
    ${numberOfMessages}
  • ` ) } } const addDepartmentNotification = (e) => { let numberOfMessages = e.unreadMessages if (numberOfMessages > 0) { $("#chat-notification-list").append( `
  • ${e.avatar}
    [${e.title}] ${e.chatDisplay}
    ${numberOfMessages}
  • ` ) } } const addNotificationsToDom = (data) => { $("#chat-notification-list").empty() if (data.totalMessages > 0) { $("#chat-message-notification-title").addClass("d-none") $("#chat-notification-number").removeClass("d-none") $("#chat-notification-number").text(data.totalMessages ?? 0) } else { $("#chat-message-notification-title").removeClass("d-none") $("#chat-notification-number").addClass("d-none") $("#chat-notification-number").text(0) } data.departmentNotifications?.map( e => { addDepartmentNotification(e)} ) data.internalNotifications?.map(e => { addInternalNotification(e)} ) } export const showNotificationMessages = () => { let ajax = new Ajax( '/chat/notifications', null, null, addNotificationsToDom, (err) => { } ) ajax.get() } export default Chat