diff --git a/ci4/app/Controllers/Chat/ChatController.php b/ci4/app/Controllers/Chat/ChatController.php index cad8ad6b..93c5bb58 100644 --- a/ci4/app/Controllers/Chat/ChatController.php +++ b/ci4/app/Controllers/Chat/ChatController.php @@ -175,44 +175,46 @@ class ChatController extends BaseController "chat_id" => $chatId, "sender_id" => auth()->user()->id, "message" => $data["message"], - "receiver_id" => $data["receiver_id"] + "receiver_id" => $data["receiver_id"], ] ); + $this->chatNotificationModel->insert(["chat_message_id" => $chat_message_id,"user_id" =>$data["receiver_id"]]); $dataResponse = $this->chatMessageModel->find($chat_message_id); return $this->response->setJSON($dataResponse); } public function get_chat_internal_contacts() { - if (auth()->user()->cliente_id) { - return $this->response->setJSON([]); - } - $users = $this->userModel->builder() - ->where("cliente_id", null) - ->whereNotIn("id", [auth()->user()->id]) + $auth_user = auth()->user(); + if ($auth_user->cliente_id) { + $users = $this->chatModel->getOpenChatCliente($auth_user->id); + }else{ + $users = $this->userModel->builder() + ->whereNotIn("id", [$auth_user->id]) ->where("deleted_at", null) ->get()->getResultObject(); + } foreach ($users as $user) { - $user->unreadMessages = $this->chatMessageModel->get_chat_unread_messages_count($user->id); + $user->unreadMessages = $this->chatMessageModel->get_chat_messages_count($user->id); } usort($users, fn($a, $b) => $a->unreadMessages < $b->unreadMessages); return $this->response->setJSON($users); } public function get_chat_internal_contact(int $user_id) { - if (auth()->user()->cliente_id) { - return $this->response->setJSON([]); - } + $auth_user = auth()->user(); + // if ($auth_user->cliente_id) { + // return $this->response->setJSON([]); + // } $users = $this->userModel->builder() - ->where("cliente_id", null) ->where("deleted_at", null) ->where("id", $user_id) ->get()->getFirstRow(); - $this->chatMessageModel->set_chat_messages_as_read($user_id); return $this->response->setJSON($users); } public function get_chat_internal_messages(int $user_id) { $conversation = $this->chatMessageModel->get_chat_contact_messages($user_id); + return $this->response->setJSON($conversation); } public function get_chat_cliente() @@ -223,6 +225,8 @@ class ChatController extends BaseController $data = $this->clienteModel->getClienteDataPresupuestoPedidoFactura($cliente_id); $response["totalMessages"] = 0; $response["chatFacturas"] = $this->chatModel->getClienteChatFacturas($data["facturas"]); + $mensajes_directos = $this->chatModel->getChatDirectMessageNotifications(); + foreach ($response["chatFacturas"] as $key => $value) { $response["totalMessages"] += $value->unreadMessages; } @@ -230,6 +234,10 @@ class ChatController extends BaseController foreach ($response["chatPresupuestos"] as $key => $value) { $response["totalMessages"] += $value->unreadMessages; } + foreach ($mensajes_directos as $value) { + $response["internals"][] = $value; + $response["totalMessages"] += $value->unreadMessages; + } $response["chatPedidos"] = $this->chatModel->getClienteChatPedidos($data["pedidos"]); foreach ($response["chatPedidos"] as $key => $value) { $response["totalMessages"] += $value->unreadMessages; @@ -238,9 +246,13 @@ class ChatController extends BaseController } else { $response["internals"] = $this->chatModel->getChatDepartmentNotifications(); $internal_notifications = $this->chatModel->getChatInternalNotifications(); + $mensajes_directos = $this->chatModel->getChatDirectMessageNotifications(); foreach ($internal_notifications as $value) { $response["internals"][] = $value; } + foreach ($mensajes_directos as $value) { + $response["internals"][] = $value; + } $response["totalMessages"] = 0; foreach ($response["internals"] as $key => $value) { $response["totalMessages"] += $value->unreadMessages; diff --git a/ci4/app/Language/es/Chat.php b/ci4/app/Language/es/Chat.php index 3bc975c8..ea5eaac2 100644 --- a/ci4/app/Language/es/Chat.php +++ b/ci4/app/Language/es/Chat.php @@ -4,7 +4,7 @@ return [ "chat" => "Mensajería", "messages" => "Mensajes", "modal" => [ - "new_hebra" => "Nueva hebra", + "new_hebra" => "Nuevo hilo", "title" => "Título", "new_message" => "Nuevo mensaje", "new_receivers" => "Nuevos participantes", diff --git a/ci4/app/Models/Chat/ChatDeparmentModel.php b/ci4/app/Models/Chat/ChatDeparmentModel.php index e51f29ce..51af2f67 100644 --- a/ci4/app/Models/Chat/ChatDeparmentModel.php +++ b/ci4/app/Models/Chat/ChatDeparmentModel.php @@ -55,7 +55,7 @@ class ChatDeparmentModel extends Model $userModel = model(UserModel::class); $chatMessageModel = model(ChatMessageModel::class); - $query = $this->db->table('chat_departments') + $query = $this->builder() ->select( [ @@ -82,23 +82,30 @@ class ChatDeparmentModel extends Model "left" ) ->where("chat_departments.type", $type); - if (auth()->user()->cliente_id == null) { - $query->where("chat_department_users.user_id", auth()->user()->id); - } + + // if (auth()->user()->cliente_id == null) { + // $query->where("chat_department_users.user_id", auth()->user()->id); + // } $results = $query->get()->getResultArray(); // Create the desired structure $departments = []; - foreach ($results as $row) { $departmentName = $row['name']; + $totalMessages = 0; // If the department is not yet added to the array, initialize it if (!isset($departments[$departmentName])) { + if($row['chatId']){ + $data["messages"] = $chatMessageModel->get_chat_messages($row['chatId']); + $totalMessages = count($data["messages"]); + + } $departments[$departmentName] = [ 'id' => $row['id'], 'name' => $row['name'], 'display' => $row['display'], + 'totalMessages' => $totalMessages, 'users' => [] // Initialize users as an empty array ]; } diff --git a/ci4/app/Models/Chat/ChatMessageModel.php b/ci4/app/Models/Chat/ChatMessageModel.php index f87c1243..ce3b2b0a 100644 --- a/ci4/app/Models/Chat/ChatMessageModel.php +++ b/ci4/app/Models/Chat/ChatMessageModel.php @@ -2,6 +2,7 @@ namespace App\Models\Chat; +use App\Models\ChatNotification; use App\Models\Usuarios\UserModel; use CodeIgniter\Model; @@ -75,7 +76,9 @@ class ChatMessageModel extends Model { $conversationArray = []; $userModel = model(UserModel::class); + $chatNotificationModel = model(ChatNotification::class); $receiverUser = $userModel->find($receiver_id); + $chat_id = null; $messagesFromClient = $this->builder() ->where("sender_id", auth()->user()->id) ->where("receiver_id", $receiverUser->id) @@ -95,7 +98,9 @@ class ChatMessageModel extends Model $conversationArray[] = $message; } $dates = array(); + foreach ($conversationArray as $key => $row) { + $chatNotificationModel->builder()->set("viewed", true)->where("chat_message_id", $row->id)->where("user_id", auth()->user()->id)->update(); $dates[$key] = strtotime($row->created_at); } array_multisort($dates, SORT_ASC, $conversationArray); @@ -110,11 +115,32 @@ class ChatMessageModel extends Model ->where("receiver_id", auth()->user()->id)->countAllResults(); return $messagesFromReceiver; } + public function get_chat_department_messages_count(int $chat_id) : int + { + $chatDepartmentMessagesCount = $this->builder() + ->where("id",$chat_id) + ->countAllResults(); + return $chatDepartmentMessagesCount; + } + public function get_chat_messages_count(int $sender_id): int + { + $messagesFromReceiver = $this->builder() + ->groupStart() + ->where("sender_id", $sender_id) + ->where("receiver_id", auth()->user()->id) + ->orGroupStart() + ->where("receiver_id", $sender_id) + ->where("sender_id", auth()->user()->id) + ->groupEnd() + ->groupEnd() + ->countAllResults(); + return $messagesFromReceiver; + } public function set_chat_messages_as_read(int $sender_id): int { $messagesFromReceiver = $this->builder() ->set("viewed", true) - ->where("sender_id", $sender_id) + ->where("user_id", $sender_id) ->where("receiver_id", auth()->user()->id)->update(); return $messagesFromReceiver; } @@ -122,23 +148,32 @@ class ChatMessageModel extends Model { $chatDepartmentModel = model(ChatDeparmentModel::class); $chatModel = model(ChatModel::class); - - if(auth()->user()->cliente_id){ + $messagesFromReceiver = 0; + $auth_user = auth()->user(); + $chat_department_id = $chatModel->find($chat_id)->chat_department_id; + $users_in_chat = array_map(fn($x) => $x->id, $chatDepartmentModel->getChatDepartmentUsers($chat_department_id)); + if (auth()->user()->cliente_id) { + // Si el usuario es cliente, marca como leídos todos los mensajes exceptos los suyos $messagesFromReceiver = $this->builder() - ->set("viewed", true) - ->where("chat_id", $chat_id) - ->whereNotIn("sender_id", [auth()->user()->id])->update(); - }else{ - $chat_department_id = $chatModel->find($chat_id)->chat_department_id; - $users_in_chat = array_map(fn($x) => $x->id, $chatDepartmentModel->getChatDepartmentUsers($chat_department_id)); - $messagesFromReceiver = $this->builder() - ->set("viewed", true) - ->where("chat_id", $chat_id) - ->whereNotIn("sender_id", $users_in_chat) - ->update(); + ->set("viewed", true) + ->where("chat_id", $chat_id) + ->whereNotIn("sender_id", [$auth_user->id])->update(); + } else { + // Si el usuario no es cliente y está dentro de los usuarios de departamento + // marca como leido todos los mensajes, excepto los mensajes de los usuarios + // de dentro del departamento + if (in_array($auth_user->id, $users_in_chat) == true) { + // if (($key = array_search($auth_user->id, $users_in_chat)) !== false) { + // unset($users_in_chat[$key]); + // } + $messagesFromReceiver = $this->builder() + ->set("viewed", true) + ->where("chat_id", $chat_id) + ->whereNotIn("sender_id", $users_in_chat) + ->update(); + } } - + return $messagesFromReceiver; } - } diff --git a/ci4/app/Models/Chat/ChatModel.php b/ci4/app/Models/Chat/ChatModel.php index 29367da0..d296be7e 100644 --- a/ci4/app/Models/Chat/ChatModel.php +++ b/ci4/app/Models/Chat/ChatModel.php @@ -16,7 +16,7 @@ class ChatModel extends Model protected $primaryKey = 'id'; protected $useAutoIncrement = true; protected $returnType = 'object'; - protected $useSoftDeletes = false; + protected $useSoftDeletes = true; protected $protectFields = true; protected $allowedFields = [ "pedido_id", @@ -33,7 +33,7 @@ class ChatModel extends Model protected array $castHandlers = []; // Dates - protected $useTimestamps = false; + protected $useTimestamps = true; protected $dateFormat = 'datetime'; protected $createdField = 'created_at'; protected $updatedField = 'updated_at'; @@ -313,7 +313,6 @@ class ChatModel extends Model "chats.pedido_id as pedidoId", "chats.presupuesto_id as presupuestoId", "chats.factura_id as facturaId", - "chats.presupuesto_id as presupuestoId", "chats.chat_department_id as chatDepartmentId", "chat_departments.display as chatDisplay", ]) @@ -372,22 +371,23 @@ class ChatModel extends Model "chats.pedido_id as pedidoId", "chats.presupuesto_id as presupuestoId", "chats.factura_id as facturaId", - "chats.presupuesto_id as presupuestoId", - "chats.title as chatDisplay" + "chats.title as chatDisplay", ]) ->join("chat_messages","chat_messages.chat_id = chats.id","left") ->join("chat_notifications","chat_notifications.chat_message_id = chat_messages.id","left") ->where("chat_notifications.user_id",auth()->user()->id) ->where("chat_notifications.viewed",false); $rows = $q->get()->getResultObject(); - + $rows_new = []; foreach ($rows as $row) { + $row->unreadMessages = 0; if($row->presupuestoId){ $row->model = $presupuestoModel->find($row->presupuestoId); $row->uri = "/presupuestos/cosidotapablanda/edit/".$row->presupuestoId; $row->title = $row->presupuestoId; $row->avatar = "PRE"; $row->unreadMessages = $this->countUnreadMessagePresupuesto($row->presupuestoId); + $rows_new[] = $row; } elseif($row->pedidoId){ $row->model = $pedidoModel->find($row->pedidoId); @@ -395,6 +395,7 @@ class ChatModel extends Model $row->title = $row->pedidoId; $row->avatar = "P"; $row->unreadMessages = $this->countUnreadMessagePedido($row->pedidoId); + $rows_new[] = $row; } @@ -404,10 +405,42 @@ class ChatModel extends Model $row->avatar = "F"; $row->title = $row->facturaId; $row->unreadMessages = $this->countUnreadMessageFactura($row->facturaId); - + $rows_new[] = $row; } } - return $rows; + return $rows_new; + } + public function getChatDirectMessageNotifications(){ + $chatMessageModel = model(ChatMessageModel::class); + $chatNotificationModel = model(ChatNotification::class); + + $q = $this->db->table("chats") + ->select([ + "chats.id as chatId", + "chats.title as chatDisplay", + "COUNT(chat_notifications.user_id) as unreadMessages" + ]) + ->join("chat_messages","chat_messages.chat_id = chats.id","left") + ->join("chat_notifications","chat_notifications.chat_message_id = chat_messages.id","left") + ->where("chats.presupuesto_id",null) + ->where("chats.chat_department_id",null) + ->where("chats.pedido_id",null) + ->where("chats.factura_id",null) + ->where("chat_notifications.viewed",false) + ->where("chat_notifications.user_id",auth()->user()->id); + $rows = $q->get()->getResultObject(); + $rows_new = []; + foreach ($rows as $row) { + if($row->chatId){ + $row->model = []; + $row->uri = "/mensajes/internos"; + $row->avatar = "MD"; + $row->title = "MD"; + $row->chatDisplay = $this->getSenderIdFromChatMessage($row->chatId)?->username ?? "Unknown"; + $rows_new[] = $row; + } + } + return $rows_new; } public function getChatInternalHebraPresupuesto(int $chat_id,int $presupuesto_id) : array { @@ -541,4 +574,42 @@ class ChatModel extends Model ->where("chat_notifications.viewed",false) ->where("chat_notifications.user_id",auth()->user()->id)->countAllResults(); } + public function countUnreadMessageDirectos(int $chat_id) : int|string + { + return $this->builder()->select() + ->join("chat_messages","chat_messages.chat_id = chats.id","left") + ->join("chat_notifications","chat_notifications.chat_message_id = chat_messages.id","left") + ->where("chats.presupuesto_id",null) + ->where("chats.pedido_id",null) + ->where("chats.factura_id",null) + ->where("chats.chat_department_id",null) + ->where("chat_messages.chat_id",$chat_id) + ->where("chat_notifications.viewed",false) + ->where("chat_notifications.user_id",auth()->user()->id)->countAllResults(); + } + public function getSenderIdFromChatMessage(int $chat_id) + { + $first_message = $this->builder()->select() + ->join("chat_messages","chat_messages.chat_id = chats.id","left") + ->where("chats.presupuesto_id",null) + ->where("chats.pedido_id",null) + ->where("chats.factura_id",null) + ->where("chats.id",$chat_id) + ->where("chat_messages.receiver_id",auth()->user()->id)->get()->getFirstRow(); + $userModel = model(UserModel::class); + return $userModel->find($first_message->sender_id); + } + public function getOpenChatCliente(int $user_id) : array + { + $q = $this->builder()->distinct()->select([ + "users.*" + ]) + ->join("chat_messages","chat_messages.chat_id = chats.id","left") + ->join("users","users.id = chat_messages.sender_id","left") + ->where("chat_messages.receiver_id",$user_id); + + return $q->get()->getResultObject(); + + } + } diff --git a/ci4/app/Views/themes/vuexy/components/chat_general.php b/ci4/app/Views/themes/vuexy/components/chat_general.php index af8ff7ef..b35914ce 100644 --- a/ci4/app/Views/themes/vuexy/components/chat_general.php +++ b/ci4/app/Views/themes/vuexy/components/chat_general.php @@ -37,14 +37,11 @@
@@ -75,9 +73,8 @@ class="avatar-initial rounded-circle bg-label-primary">P
-
Departamento Producción
- Consulta sobre el presupuesto - P001 +
+
@@ -87,13 +84,13 @@ aria-expanded="false"> - +
--> diff --git a/ci4/app/Views/themes/vuexy/main/menus/clientes_menu.php b/ci4/app/Views/themes/vuexy/main/menus/clientes_menu.php index 71e53116..59ee8395 100644 --- a/ci4/app/Views/themes/vuexy/main/menus/clientes_menu.php +++ b/ci4/app/Views/themes/vuexy/main/menus/clientes_menu.php @@ -1,11 +1,12 @@ user()->inGroup('cliente-admin') || auth()->user()->inGroup('cliente-editor')) { if (auth()->user()->can('perfil.edit') || auth()->user()->can('direcciones.menu')) { - ?> +?> + - user()->can('clientes.menu') || - auth()->user()->can('plantilla-tarifa.menu')) { - ?> + if ( + auth()->user()->can('clientes.menu') || + auth()->user()->can('plantilla-tarifa.menu') + ) { + ?> + - - - - +?> \ No newline at end of file diff --git a/ci4/app/Views/themes/vuexy/main/menus/mensajes_menu.php b/ci4/app/Views/themes/vuexy/main/menus/mensajes_menu.php index 44913967..7faa33da 100644 --- a/ci4/app/Views/themes/vuexy/main/menus/mensajes_menu.php +++ b/ci4/app/Views/themes/vuexy/main/menus/mensajes_menu.php @@ -2,7 +2,7 @@ /** * MENU MENSAJES */ -if (auth()->user()->inGroup('beta')) { +if (auth()->user()->inGroup('beta') || auth()->user()->inGroup('cliente-editor')) { ?> ` @@ -226,7 +226,7 @@ class Chat { `/chat/department/${this.chatType}/${this.chatDeparmentId}/${this.modelId}`, null, null, - (data)=> { + (data) => { this.chatList.find(`#chat_${row_name} .messages-unread-contact`).text(data.count) }, null @@ -290,12 +290,12 @@ class Chat { this.chatHistory.append(chatItem) return chatItem } - _sendMessagePressKey(e){ - if ( e.which == 13 ) { + _sendMessagePressKey(e) { + if (e.which == 13) { e.preventDefault(); this._sendMessage() } - + } _sendMessage() { @@ -341,26 +341,35 @@ class Chat { } _handleListContactsSuccess(contacts) { - if (contacts.length) { - console.log(contacts) - contacts.map((c) => { - this._addContactToList(c) - }); - } else { - this.sideBar.find("#contact-list").addClass("d-none") + 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() + } - 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() - }) } _handleListContactsError(err) { console.error(err) @@ -389,10 +398,20 @@ class Chat { ajax.get() } _handleGetSingleContactMessagesSuccess(data) { - if (data) { - data.map((m) => { - this._addChatMessage(m) - }) + 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) { } @@ -400,8 +419,8 @@ class Chat { _handleGetSingleContactError(err) { } - _sendMessageInternalPressKey(e){ - if ( e.which == 13 ) { + _sendMessageInternalPressKey(e) { + if (e.which == 13) { e.preventDefault(); this._sendMessageInternal() } @@ -449,11 +468,11 @@ class Chat {
${contact?.first_name ?? "" + " " + contact?.last_name ?? ""}

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

${contact.unreadMessages ? `${contact.unreadMessages}` : ""} + class="badge badge-center rounded-pill bg-danger messages-unread-contact">${contact.unreadMessages}` : ""} ` @@ -479,18 +498,18 @@ export const showNotificationMessages = (dom) => { (data) => { dom.empty() $("#chat-notification-number") - if(data.totalMessages > 0){ + if (data.totalMessages > 0) { $("#chat-notification-number").removeClass("d-none") $("#chat-notification-number").text(data.totalMessages ?? 0) - }else{ + } else { $("#chat-notification-number").addClass("d-none") $("#chat-notification-number").text(0) } data?.internals?.map((e) => { let numberOfMessages = e.unreadMessages - if(numberOfMessages > 0){ - dom.append( - ` + if (numberOfMessages > 0) { + dom.append( + `
  • @@ -503,14 +522,14 @@ export const showNotificationMessages = (dom) => {
  • ` - ) - } + ) + } }) data?.chatPresupuestos?.map((e) => { let numberOfMessages = e.unreadMessages - if(numberOfMessages > 0){ - dom.append( - ` + if (numberOfMessages > 0) { + dom.append( + `
  • @@ -523,14 +542,14 @@ export const showNotificationMessages = (dom) => {
  • ` - ) - } + ) + } }) data?.chatFacturas?.map((e) => { let numberOfMessages = e.unreadMessages - if(numberOfMessages > 0){ - dom.append( - ` + if (numberOfMessages > 0) { + dom.append( + `
  • @@ -543,14 +562,14 @@ export const showNotificationMessages = (dom) => {
  • ` - ) - } + ) + } }) data?.chatPedidos?.map((e) => { let numberOfMessages = e.unreadMessages - if(numberOfMessages > 0){ - dom.append( - ` + if (numberOfMessages > 0) { + dom.append( + `
  • @@ -563,8 +582,8 @@ export const showNotificationMessages = (dom) => {
  • ` - ) - } + ) + } }) }, diff --git a/httpdocs/assets/js/safekat/components/internalMessagesSection.js b/httpdocs/assets/js/safekat/components/internalMessagesSection.js index 6adcee0c..751678a0 100644 --- a/httpdocs/assets/js/safekat/components/internalMessagesSection.js +++ b/httpdocs/assets/js/safekat/components/internalMessagesSection.js @@ -111,7 +111,7 @@ class InternalMessages { handleBtnNewHebra(e) { e.preventDefault() this.chatId = null - this.modalNewMessage.item.find(".modal-title").text("Nueva hebra") + this.modalNewMessage.item.find(".modal-title").text("Nuevo hilo") this.selectMessageUsers.reset() this.textAreaMessage.val("") this.hebraTitle.val("") @@ -163,7 +163,7 @@ class InternalMessages { const contentHeaderHebra = $("

    ").text(`${chatTitle}`) const btnNewHebra = $("").attr("type", "button").addClass("btn btn-danger btn-sm btn-new-hebra") btnNewHebra.append('') - btnNewHebra.append("Nueva hebra") + btnNewHebra.append("Nuevo hilo") headerHebra.append(contentHeaderHebra,btnNewHebra) itemHebra.append(headerHebra) let itemMessagesHebraRow = $("
    ").addClass("row")