From 55157d23aaecb412efe2d75cf89dc871c0fa894a Mon Sep 17 00:00:00 2001 From: amazuecos Date: Sun, 16 Mar 2025 23:13:03 +0100 Subject: [PATCH 1/7] message client department --- ci4/app/Config/Routes.php | 3 + ci4/app/Controllers/Chat/ChatController.php | 92 ++++++++++++++---- ci4/app/Language/en/Chat.php | 45 +++++++++ ci4/app/Language/es/Chat.php | 11 ++- .../themes/vuexy/components/chat_factura.php | 43 +++++---- .../themes/vuexy/components/chat_pedido.php | 44 +++++---- .../vuexy/components/chat_presupuesto.php | 42 +++++---- .../safekat/components/alerts/sweetAlert.js | 26 ++--- httpdocs/assets/js/safekat/components/chat.js | 94 ++++++++++++++++++- 9 files changed, 318 insertions(+), 82 deletions(-) create mode 100644 ci4/app/Language/en/Chat.php diff --git a/ci4/app/Config/Routes.php b/ci4/app/Config/Routes.php index b4f6144b..bbd2c1e0 100644 --- a/ci4/app/Config/Routes.php +++ b/ci4/app/Config/Routes.php @@ -898,6 +898,9 @@ $routes->group('chat', ['namespace' => 'App\Controllers\Chat'], function ($route $routes->get('department/pedido/(:num)/(:num)', 'ChatController::get_chat_pedido/$1/$2', ['as' => 'getChatPedido']); $routes->get('department/factura/(:num)/(:num)', 'ChatController::get_chat_factura/$1/$2', ['as' => 'getChatFactura']); $routes->get('department/(:num)/users', 'ChatController::get_chat_department_users/$1', ['as' => 'getChatDepartmentUsers']); + $routes->post('department/user', 'ChatController::subscribe_to_chat_deparment/$1', ['as' => 'subscribeToChatDepartment']); + $routes->delete('department/user/(:num)', 'ChatController::delete_user_from_department/$1', ['as' => 'deleteUserFromDepartment']); + $routes->get('(:num)', 'ChatController::get_chat/$1', ['as' => 'getChat']); $routes->post('message/error/presupuesto', 'ChatController::store_chat_error_message', ['as' => 'storeChatErrorMessage']); diff --git a/ci4/app/Controllers/Chat/ChatController.php b/ci4/app/Controllers/Chat/ChatController.php index 872235f4..4a2e97c2 100644 --- a/ci4/app/Controllers/Chat/ChatController.php +++ b/ci4/app/Controllers/Chat/ChatController.php @@ -207,6 +207,17 @@ class ChatController extends BaseController $chat_message_id = $this->chatMessageModel->insert(["chat_id" => $chatId, "sender_id" => auth()->user()->id, "message" => $data["message"]]); $dataResponse = $this->chatMessageModel->find($chat_message_id); $chatDepartmentUsers = $this->chatDeparmentModel->getChatDepartmentUsers($data["chat_department_id"]); + $this->chatNotificationModel->insert(["chat_message_id" => $chat_message_id, "user_id" => $data['client']]); + $cliente_in_department_count = $this->chatDeparmentUserModel->where('chat_department_id',$data["chat_department_id"])->where('user_id',$data['client'])->countAllResults(); + $auth_user_in_department_count = $this->chatDeparmentUserModel->where('chat_department_id',$data["chat_department_id"])->where('user_id',auth()->user()->id)->countAllResults(); + if($cliente_in_department_count == 0){ + $this->chatDeparmentUserModel->insert(['chat_department_id' => $data["chat_department_id"],'user_id' => $data['client']]); + } + if($auth_user_in_department_count){ + $this->chatDeparmentUserModel->insert(['chat_department_id' => $data["chat_department_id"],'user_id' => auth()->user()->id]); + + } + foreach ($chatDepartmentUsers as $user) { if ($user->id != auth()->user()->id) { $this->chatNotificationModel->insert(["chat_message_id" => $chat_message_id, "user_id" => $user->id]); @@ -228,6 +239,16 @@ class ChatController extends BaseController $chat_message_id = $this->chatMessageModel->insert(["chat_id" => $chatId, "sender_id" => auth()->user()->id, "message" => $data["message"]]); $dataResponse = $this->chatMessageModel->find($chat_message_id); $chatDepartmentUsers = $this->chatDeparmentModel->getChatDepartmentUsers($data["chat_department_id"]); + $this->chatNotificationModel->insert(["chat_message_id" => $chat_message_id, "user_id" => $data['client']]); + $cliente_in_department_count = $this->chatDeparmentUserModel->where('chat_department_id',$data["chat_department_id"])->where('user_id',$data['client'])->countAllResults(); + $auth_user_in_department_count = $this->chatDeparmentUserModel->where('chat_department_id',$data["chat_department_id"])->where('user_id',auth()->user()->id)->countAllResults(); + if($cliente_in_department_count == 0){ + $this->chatDeparmentUserModel->insert(['chat_department_id' => $data["chat_department_id"],'user_id' => $data['client']]); + } + if($auth_user_in_department_count){ + $this->chatDeparmentUserModel->insert(['chat_department_id' => $data["chat_department_id"],'user_id' => auth()->user()->id]); + + } foreach ($chatDepartmentUsers as $user) { if ($user->id != auth()->user()->id) { $this->chatNotificationModel->insert(["chat_message_id" => $chat_message_id, "user_id" => $user->id]); @@ -249,6 +270,16 @@ class ChatController extends BaseController $chat_message_id = $this->chatMessageModel->insert(["chat_id" => $chatId, "sender_id" => auth()->user()->id, "message" => $data["message"]]); $dataResponse = $this->chatMessageModel->find($chat_message_id); $chatDepartmentUsers = $this->chatDeparmentModel->getChatDepartmentUsers($data["chat_department_id"]); + $this->chatNotificationModel->insert(["chat_message_id" => $chat_message_id, "user_id" => $data['client']]); + $cliente_in_department_count = $this->chatDeparmentUserModel->where('chat_department_id',$data["chat_department_id"])->where('user_id',$data['client'])->countAllResults(); + $auth_user_in_department_count = $this->chatDeparmentUserModel->where('chat_department_id',$data["chat_department_id"])->where('user_id',auth()->user()->id)->countAllResults(); + if($cliente_in_department_count == 0){ + $this->chatDeparmentUserModel->insert(['chat_department_id' => $data["chat_department_id"],'user_id' => $data['client']]); + } + if($auth_user_in_department_count){ + $this->chatDeparmentUserModel->insert(['chat_department_id' => $data["chat_department_id"],'user_id' => auth()->user()->id]); + + } foreach ($chatDepartmentUsers as $user) { if ($user->id != auth()->user()->id) { $this->chatNotificationModel->insert(["chat_message_id" => $chat_message_id, "user_id" => $user->id]); @@ -319,26 +350,30 @@ class ChatController extends BaseController $response = []; if ($cliente_id) { $data = $this->clienteModel->getClienteDataPresupuestoPedidoFactura($cliente_id); + $response["internals"] = $this->chatModel->getChatDepartmentNotifications(); $response["totalMessages"] = 0; - $response["chatFacturas"] = $this->chatModel->getClienteChatFacturas($data["facturas"]); $mensajes_directos = $this->chatModel->getChatDirectMessageNotifications(); - - foreach ($response["chatFacturas"] as $key => $value) { + // $response["chatFacturas"] = $this->chatModel->getClienteChatFacturas($data["facturas"]); + // foreach ($response["chatFacturas"] as $key => $value) { + // $response["totalMessages"] += $value->unreadMessages; + // } + // $response["chatPresupuestos"] = $this->chatModel->getClienteChatPresupuestos($data["presupuestos"]); + // 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; + // } + // $response["data"] = $data; + $response["totalMessages"] = 0; + foreach ($response["internals"] as $key => $value) { $response["totalMessages"] += $value->unreadMessages; } - $response["chatPresupuestos"] = $this->chatModel->getClienteChatPresupuestos($data["presupuestos"]); - 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; - } - $response["data"] = $data; } else { $response["internals"] = $this->chatModel->getChatDepartmentNotifications(); $internal_notifications = $this->chatModel->getChatInternalNotifications(); @@ -800,4 +835,29 @@ class ChatController extends BaseController $r = $messageService->createErrorMessagePresupuesto("Error", $bodyData['presupuesto_id']); return $this->response->setJSON(["message" => "ok", "data" => $r]); } + public function delete_user_from_department($chat_department_id) + { + $user_id = auth()->user()->id; + $chatDepartmentUserEntity = $this->chatDeparmentUserModel->where('chat_department_id',$chat_department_id)->where('user_id',$user_id); + if($chatDepartmentUserEntity->countAllResults() > 0) + { + $deleted = $this->chatDeparmentUserModel->where('chat_department_id',$chat_department_id)->where('user_id',$user_id)->delete(); + return $this->response->setJSON(["message" => lang('Chat.exit_chat_ok'), "status" => true]); + }else{ + return $this->response->setJSON(["message" => lang('Chat.exit_chat_wrong'),"status" => false]); + } + } + public function subscribe_to_chat_deparment() + { + $data = $this->request->getPost(); + $user_id = auth()->user()->id; + $chatDepartmentUserEntity = $this->chatDeparmentUserModel->where('chat_department_id',$data['chat_department_id'])->where('user_id',$user_id); + if($chatDepartmentUserEntity->countAllResults() > 0) + { + return $this->response->setJSON(["message" => lang('Chat.subscribe_chat_wrong'),"status" => false]); + }else{ + $this->chatDeparmentUserModel->insert(["chat_department_id" => $data["chat_department_id"],"user_id" => $user_id]); + return $this->response->setJSON(["message" => lang('Chat.subscribe_chat_ok'), "status" => true]); + } + } } diff --git a/ci4/app/Language/en/Chat.php b/ci4/app/Language/en/Chat.php new file mode 100644 index 00000000..bb9c813c --- /dev/null +++ b/ci4/app/Language/en/Chat.php @@ -0,0 +1,45 @@ + "Messages", + "messages" => "Messages", + "message" => "Message", + "messages_internal" => "Internal messages", + "message_internal" => "Internal message", + "messages_client" => "Client messages", + "message_client" => "Client message", + "modal" => [ + "new_hebra" => "New thread", + "title" => "Title", + "new_message" => "New message", + "new_receivers" => "New participants", + "btn_send" => "Send", + "btn_send_update" => "Send" + ], + "datatable_messages" => [ + "created_at" => "Created at", + "updated_at" => "Updated at", + "title" => "Title", + "creator" => "Created by", + "viewed" => "Viewed", + + ], + "new_message_ok" => "Message sent successfully", + "participants" => "Participants", + "choose_department" => "Choose a deparment", + "new_participant" => "Add new participants", + "write_message_placeholder" => "Type your message here ...", + "add_notification" => "Notification", + "check_as_unviewed" => "Check as not viewed", + "add_notification_message" => "Add users present in this chat a notification", + "chat_title_presupuesto" => 'Presupuesto[{title,string,0}][{id}]', + "no_messages_notification" => 'There is no messages', + "view_chat" => 'See chat', + "view_by_alt_message" => 'Show users that has or not viewed the messages', + "exit_chat" => 'Exit chat', + "subscribe_chat" => 'Subscribe to chat', + "exit_chat_ok" => "You have exit chat successfully. Notifications on this chat will no longer be received", + "exit_chat_wrong" => "You can't exit the chat because you don't belong to it.", + "subscribe_chat_ok" => "You've subscribed to chat successfully. Now on you'll receive notifications.", + "subscribe_chat_wrong" => "You already belong to this chat.", +]; \ No newline at end of file diff --git a/ci4/app/Language/es/Chat.php b/ci4/app/Language/es/Chat.php index e9f32692..3488f38b 100644 --- a/ci4/app/Language/es/Chat.php +++ b/ci4/app/Language/es/Chat.php @@ -35,5 +35,14 @@ return [ "chat_title_presupuesto" => 'Presupuesto[{title,string,0}][{id}]', "no_messages_notification" => 'No hay mensajes que revisar por el momento', "view_chat" => 'Ver chat', - "view_by_alt_message" => 'Muestra los usuarios que han leído o no los mensajes' + "view_by_alt_message" => 'Muestra los usuarios que han leído o no los mensajes', + "exit_chat" => 'Salir conversación', + "subscribe_chat" => 'Subscribirse al chat', + "exit_chat_ok" => "Ha salido de la conversación correctamente. No recibirá más notificaciones a no ser que sea añadido de nuevo.", + "exit_chat_wrong" => "No puede salir de la conversación porque no pertenece a ella.", + "subscribe_chat_ok" => "Te has subscrito al chat correctamente. Ahora recibirás notificaciones cuando lleguen mensajes.", + "subscribe_chat_wrong" => "Ya perteneces a este chat.", + + + ]; \ No newline at end of file diff --git a/ci4/app/Views/themes/vuexy/components/chat_factura.php b/ci4/app/Views/themes/vuexy/components/chat_factura.php index be1ebf0b..0a50c300 100644 --- a/ci4/app/Views/themes/vuexy/components/chat_factura.php +++ b/ci4/app/Views/themes/vuexy/components/chat_factura.php @@ -1,9 +1,5 @@
-user()->inGroup('admin')) { ?> -
- -
- +
@@ -30,12 +26,17 @@

- ${chatMessage?.user?.first_name + " " + chatMessage?.user?.last_name}
- + ${chatMessage.created_at}
@@ -426,7 +436,7 @@ class Chat { message: messageText, chat_department_id: this.chatDeparmentId, user: this.userId, - client: this.selectClientUser.getVal(), + client: this.selectClientUser.getVal() ?? null, model_id: this.modelId } if (messageText) { @@ -745,7 +755,7 @@ class Chat { _handleRequestExitChatDeparment() { const ajax = new Ajax('/chat/department/user/' + this.chatDeparmentId, { - model_fk: this.chatType, + model_fk: this.chatType + "_id", model_id_fk: this.modelId }, null, @@ -768,7 +778,7 @@ class Chat { const ajax = new Ajax('/chat/department/user', { chat_department_id: this.chatDeparmentId, - model_fk: this.chatType, + model_fk: this.chatType + "_id", model_id_fk: this.modelId }, null, diff --git a/httpdocs/assets/js/safekat/components/datatables/ChatDepartmentDatatable.js b/httpdocs/assets/js/safekat/components/datatables/ChatDepartmentDatatable.js new file mode 100644 index 00000000..3b33a0c2 --- /dev/null +++ b/httpdocs/assets/js/safekat/components/datatables/ChatDepartmentDatatable.js @@ -0,0 +1,160 @@ +import Ajax from "../ajax.js"; +import { alertConfirmationDelete, alertSuccess, alertError, alertConfirmAction } from '../alerts/sweetAlert.js' +export class ChatDepartmentDatatable { + constructor(domItem) { + this.item = domItem + this.chatDepartmentDisplay = $("#chat-department-display") + this.btnStoreChatDepartment = $("#btn-add-new-chat-department") + + this.datatableColumns = [ + { data: 'id', searchable: false, sortable: true }, + { data: 'display', searchable: true, sortable: true }, + { data: 'description', searchable: true, sortable: true }, + { + data: 'action', searchable: false, sortable: false, + render: (d, t) => { + return `
+ + +
` + } + } + ] + } + init() { + this.btnStoreChatDepartment.on('click', this.storeNewChatDepartment.bind(this)) + this.item.on('click', '.chat-department-delete', this.deleteChatDepartment.bind(this)) + + this.datatable = this.item.DataTable({ + processing: true, + order: [[0, 'asc']], + layout: { + topStart: 'pageLength', + topEnd: 'search', + bottomStart: 'info', + bottomEnd: 'paging' + }, + serverSide: true, + pageLength: 10, + language: { + url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json" + }, + columns: this.datatableColumns, + ajax: '/chat/department/datatable' + }); + } + deleteChatDepartment(event) { + const ajax = new Ajax( + `/chat/department/${$(event.currentTarget).data("id")}`, + null, + null, + this.deleteChatDepartmentSuccess.bind(this), + this.deleteChatDepartmentError.bind(this) + ) + alertConfirmationDelete().then(result => { + if (result.isConfirmed) { + ajax.delete() + } + }) + } + deleteChatDepartmentSuccess(response) { + this.datatable.ajax.reload() + alertSuccess(response.message).fire() + } + deleteChatDepartmentError(response) { + alertError(response.message).fire() + } + storeNewChatDepartment() { + this.btnStoreChatDepartment.attr("disabled") + const ajax = new Ajax("/chat/department", { + display: this.chatDepartmentDisplay.val() + }, + null, + this.storeNewChatDepartmentSuccess.bind(this), + this.storeNewChatDepartmentError.bind(this) + ) + if (this.chatDepartmentDisplay.val()) { + alertConfirmAction().then(result => { + if (result.isConfirmed) { + ajax.post() + } + }) + } else { + this.btnStoreChatDepartment.removeAttr("disabled") + } + } + storeNewChatDepartmentSuccess(response) { + this.datatable.ajax.reload() + alertSuccess(response.message).fire() + } + storeNewChatDepartmentError(response) { + console.log(response) + alertError(response.message).fire() + } + +} +export class ChatDepartmentUserDatatable { + constructor(domItem) { + this.item = domItem + this.datatableColumns = [ + { data: 'userFullName', searchable: true, sortable: true }, + { data: 'username', searchable: true, sortable: true }, + { + data: 'action', searchable: false, sortable: false, + render: (d, t) => { + return `
+ +
` + } + } + ] + } + init() { + this.actions() + this.datatable = this.item.DataTable({ + processing: true, + order: [[0, 'desc']], + layout: { + topStart: 'pageLength', + topEnd: 'search', + bottomStart: 'info', + bottomEnd: 'paging' + }, + serverSide: true, + pageLength: 10, + language: { + url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json" + }, + columns: this.datatableColumns, + ajax: '/chat/department/users/datatable/' + this.item.data('id') + }); + } + actions() { + this.item.on("click", ".chat-department-user-delete", this.deleteRow.bind(this)) + } + deleteRow(event) { + const ajax = new Ajax(`/chat/department/admin/user/${this.item.data('id')}/${$(event.currentTarget).data("id")}`, + null, + null, + this.deleteRowSuccess.bind(this), + this.deleteRowError.bind(this), + ) + alertConfirmationDelete().then(result => { + if (result.isConfirmed) { + ajax.delete() + } + }) + } + deleteRowSuccess(response) { + this.datatable.ajax.reload(); + alertSuccess(response.message).fire() + } + deleteRowError(response) { + alertError(response?.message).fire() + } + + +} + + + diff --git a/httpdocs/assets/js/safekat/components/datatables/MessagesDatatable.js b/httpdocs/assets/js/safekat/components/datatables/MessagesDatatable.js index c27f70ef..d46d76a6 100644 --- a/httpdocs/assets/js/safekat/components/datatables/MessagesDatatable.js +++ b/httpdocs/assets/js/safekat/components/datatables/MessagesDatatable.js @@ -134,33 +134,49 @@ class MessagesDatatable { } handleDropUpSuccess(response) { const chatId = response.chat_id - const users = response.data - if (users.length > 0) { + const unviewedNotifications = response.data.unviewedNotifications + const viewedNotifications = response.data.viewedNotifications - users.forEach(user => { - const viewed = (user.notification_count - user.viewed_count) == 0 + if (unviewedNotifications.length > 0) { + + unviewedNotifications.forEach(user => { if (user.userFullName || user.userName) { $(`#dropdown-viewed-${chatId}`) - .append(` -
  • - - ${user.userFullName ?? user.userName} - - - - -
  • - `) + .append(this.addDropUpItem(user)) } }); - } else { - $(`#dropdown-viewed-${chatId}`).append(`
  • Visto
  • `) } + if (viewedNotifications.length > 0) { + + viewedNotifications.forEach(user => { + if (user.userFullName || user.userName) { + + $(`#dropdown-viewed-${chatId}`) + .append(this.addDropUpItem(user)) + } + + }); + } } handleDropUpError() { } - + addDropUpItem(user) + { + return ` +
  • + + ${user.userFullName ?? user.userName} + + + + +
  • `; + } } diff --git a/httpdocs/assets/js/safekat/components/forms/chatDepartmentForm.js b/httpdocs/assets/js/safekat/components/forms/chatDepartmentForm.js new file mode 100644 index 00000000..16d66d30 --- /dev/null +++ b/httpdocs/assets/js/safekat/components/forms/chatDepartmentForm.js @@ -0,0 +1,91 @@ +import ClassSelect from "../select2.js" +import { ChatDepartmentUserDatatable } from '../datatables/ChatDepartmentDatatable.js' +import Ajax from "../ajax.js" +import { alertConfirmAction, alertError, alertSuccess } from "../alerts/sweetAlert.js" + +class ChatDepartmentForm { + constructor(domItem) { + this.item = domItem + this.chatDepartmentId = this.item.data("id") + this.btnAddUserToDepartment = this.item.find("#add-user-admin-chat-department") + this.btnUpdate = this.item.find("#btn-chat-department-update") + this.chatDepartmentUsersDatatable = new ChatDepartmentUserDatatable($("#tableChatDepartmentUsers")) + this.seletChatDepartmentUserItem = this.item.find("#selectChatDepartmentUser") + this.seletChatDepartmentUser = new ClassSelect( + this.seletChatDepartmentUserItem, + `/chat/department/users/select/add/${this.chatDepartmentId}` + ) + } + init() { + this.seletChatDepartmentUser.init() + this.chatDepartmentUsersDatatable.init() + this.btnAddUserToDepartment.on('click', this._handleUserToDepartment.bind(this)) + this.btnUpdate.on("click", this._handleUpdateDepartment.bind(this)) + } + getFormData() { + return { + display: this.item.find("#chat-department-display").val(), + description: this.item.find("#chat-department-description").val() + } + } + updateFormData(data) { + this.item.find("#chat-department-display").val(data.display) + this.item.find("#chat-department-description").val(data.description) + } + _handleUserToDepartment() { + this.btnAddUserToDepartment.attr("disabled", "disabled") + const ajax = new Ajax("/chat/department/subscribe/admin/user", + { + user_id: this.seletChatDepartmentUser.getVal(), + chat_department_id: this.chatDepartmentId + }, + null, + this._handleUserToDepartmentSuccess.bind(this), + this._handleUserToDepartmentError.bind(this) + ) + if (this.seletChatDepartmentUser.getVal()) { + ajax.post(); + } else { + this.btnAddUserToDepartment.removeAttr("disabled") + } + } + _handleUserToDepartmentSuccess(response) { + this.btnAddUserToDepartment.removeAttr("disabled") + this.chatDepartmentUsersDatatable.datatable.ajax.reload() + alertSuccess(response.message).fire() + this.seletChatDepartmentUser.reset() + } + _handleUserToDepartmentError(response) { + alertError(response.message ?? "").fire() + this.btnAddUserToDepartment.removeAttr("disabled") + + } + _handleUpdateDepartment() { + this.btnUpdate.attr("disabled") + const ajax = new Ajax("/chat/department/update/" + this.chatDepartmentId, + this.getFormData(), + null, + this._handleUserToDepartmentSuccess.bind(this), + this._handleUserToDepartmentError.bind(this) + ) + if (this.getFormData()) { + ajax.post(); + } else { + this.btnUpdate.removeAttr("disabled") + } + } + __handleUpdateDepartmentSuccess(response) { + this.btnUpdate.removeAttr("disabled") + alertSuccess(response.message).fire() + this.updateFormData(response.data) + } + _handleUpdateDepartmentError(response) { + this.btnUpdate.removeAttr("disabled") + alertError(response.message ?? "").fire() + } + + + +} + +export default ChatDepartmentForm \ No newline at end of file diff --git a/httpdocs/assets/js/safekat/components/select2.js b/httpdocs/assets/js/safekat/components/select2.js index c7fdfa51..c6199c56 100644 --- a/httpdocs/assets/js/safekat/components/select2.js +++ b/httpdocs/assets/js/safekat/components/select2.js @@ -5,97 +5,96 @@ * @param {String} placeholder */ let ClassSelect = function (domItem, url, placeholder, allowClear = false, params = {}, dropdownParent = "", hideSearch = false) { - this.url = url; - this.item = domItem; - this.params = params; - this.dropdownParent = dropdownParent; - this.hideSearch = hideSearch; + this.url = url; + this.item = domItem; + this.params = params; + this.dropdownParent = dropdownParent; + this.hideSearch = hideSearch; - this.config = { - placeholder: placeholder, - allowClear: allowClear, - dropdownParent: dropdownParent!=""?dropdownParent:domItem.parent(), - language: "es", - ajax: { - url: () => { - return this.url; - }, - data: (params) => { - let q = $.trim(params.term); - let d = { - q: q, - page: params.page || 1, - }; - - for (let key in this.params) { - d[key] = this.params[key]; - } - - return d; - }, - processResults: function (data) { - return { - results: $.map(data, function (obj) { - return { - id: obj.id, - text: obj.nombre ?? obj.name, - desc: obj.description, - }; - }), - }; - }, - cache: true, + this.config = { + placeholder: placeholder, + allowClear: allowClear, + dropdownParent: dropdownParent != "" ? dropdownParent : domItem.parent(), + language: "es", + ajax: { + url: () => { + return this.url; }, - }; - this.init = function () { - if (this.item.length) { + data: (params) => { + let q = $.trim(params.term); + let d = { + q: q, + page: params.page || 1, + }; - if(this.hideSearch){ - this.config.minimumResultsForSearch = -1; + for (let key in this.params) { + d[key] = this.params[key]; } - this.item = this.item.select2(this.config); - // $.fn.modal.Constructor.prototype.enforceFocus = function () {}; - } - }; - this.setOption = function (id, nombre) { - var newOption = new Option(nombre , id, false, false); - this.item.append(newOption); - this.item.val(id).trigger("change"); - }; - this.reset = function () { - this.item.val(null).trigger("change"); - }; - this.setParams = function(params){ - this.params = params; - }; - this.getVal = function () { - return this.item.val(); - }; - this.setVal = function (val) { - return this.item.val(val).trigger("change"); - }; - this.empty = function () { - return this.item.empty().trigger("change"); - }; - this.readOnly = function () { - this.item.enable(false); - }; - this.enable = () => { - this.item.enable(true); - }; - this.fixWithScroll = function () {}; - this.getText = () => { - return this.item.find(":selected").text(); - }; - this.onChange = function(callback) { - this.item.on('change', callback); - }; - this.offChange = function() { - this.item.off('change'); - }; - + return d; + }, + processResults: function (data) { + return { + results: $.map(data, function (obj) { + return { + id: obj.id, + text: obj.nombre ?? obj.name, + desc: obj.description, + }; + }), + }; + }, + cache: true, + }, }; - + this.init = function () { + if (this.item.length) { + + if (this.hideSearch) { + this.config.minimumResultsForSearch = -1; + } + + this.item = this.item.select2(this.config); + // $.fn.modal.Constructor.prototype.enforceFocus = function () {}; + } + }; + this.setOption = function (id, nombre) { + var newOption = new Option(nombre, id, false, false); + this.item.append(newOption); + this.item.val(id).trigger("change"); + }; + this.reset = function () { + this.item.val(null).trigger("change"); + }; + this.setParams = function (params) { + this.params = params; + }; + this.getVal = function () { + return this.item.val(); + }; + this.setVal = function (val) { + return this.item.val(val).trigger("change"); + }; + this.empty = function () { + return this.item.empty().trigger("change"); + }; + this.readOnly = function () { + this.item.enable(false); + }; + this.enable = () => { + this.item.enable(true); + }; + this.fixWithScroll = function () { }; + this.getText = () => { + return this.item.find(":selected").text(); + }; + this.onChange = function (callback) { + this.item.on('change', callback); + }; + this.offChange = function () { + this.item.off('change'); + }; + +}; + export default ClassSelect; - \ No newline at end of file diff --git a/httpdocs/assets/js/safekat/pages/configuracion/messages/configView.js b/httpdocs/assets/js/safekat/pages/configuracion/messages/configView.js new file mode 100644 index 00000000..5c17e5b2 --- /dev/null +++ b/httpdocs/assets/js/safekat/pages/configuracion/messages/configView.js @@ -0,0 +1,13 @@ + +import Ajax from '../../../components/ajax.js' +import { ChatDepartmentDatatable } from '../../../components/datatables/ChatDepartmentDatatable.js' + + + + + +$(() => { + const chatDepartmentDatatable = new ChatDepartmentDatatable($("#tableChatDepartments")) + chatDepartmentDatatable.init() +}) + diff --git a/httpdocs/assets/js/safekat/pages/configuracion/messages/editChatDepartmentView.js b/httpdocs/assets/js/safekat/pages/configuracion/messages/editChatDepartmentView.js new file mode 100644 index 00000000..94b36ab8 --- /dev/null +++ b/httpdocs/assets/js/safekat/pages/configuracion/messages/editChatDepartmentView.js @@ -0,0 +1,8 @@ + +import ChatDepartmentForm from '../../../components/forms/chatDepartmentForm.js' + +$(() => { + + const chatDepartmentForm = new ChatDepartmentForm($("#chatDepartmentForm")) + chatDepartmentForm.init() +}) \ No newline at end of file From c0d54e28b7cd86d2a570ca592a2aec81175f8883 Mon Sep 17 00:00:00 2001 From: amazuecos Date: Mon, 24 Mar 2025 08:12:06 +0100 Subject: [PATCH 6/7] message refactor --- ci4/app/Config/Routes.php | 16 +- ci4/app/Config/Services.php | 5 + ci4/app/Controllers/Chat/ChatController.php | 333 +++--------------- .../Entities/Chat/ChatDepartmentEntity.php | 79 +++++ .../Chat/ChatDepartmentUserEntity.php | 60 ++++ ci4/app/Entities/Chat/ChatEntity.php | 148 ++++++++ ci4/app/Entities/Chat/ChatMessageEntity.php | 65 ++++ .../Entities/Chat/ChatNotificationEntity.php | 42 +++ ci4/app/Entities/Chat/ChatUserEntity.php | 36 ++ ci4/app/Entities/Usuarios/UserEntity.php | 18 + ci4/app/Helpers/general_helper.php | 5 +- ci4/app/Language/es/App.php | 2 +- ci4/app/Language/es/Chat.php | 1 + ci4/app/Models/Chat/ChatDeparmentModel.php | 19 +- .../Models/Chat/ChatDeparmentUserModel.php | 3 +- ci4/app/Models/Chat/ChatMessageModel.php | 52 ++- ci4/app/Models/Chat/ChatModel.php | 177 +++++----- ci4/app/Models/ChatNotification.php | 3 +- ci4/app/Models/ChatUser.php | 3 +- ci4/app/Services/ChatService.php | 176 +++++++++ .../components/tables/messages_table.php | 10 + .../Views/themes/vuexy/main/defaultlayout.php | 5 +- httpdocs/assets/js/safekat/components/chat.js | 291 ++++----------- .../datatables/MessagesDatatable.js | 68 ++-- .../components/internalMessagesSection.js | 48 ++- .../js/safekat/pages/chatNotification.js | 6 +- 26 files changed, 994 insertions(+), 677 deletions(-) create mode 100644 ci4/app/Entities/Chat/ChatDepartmentEntity.php create mode 100644 ci4/app/Entities/Chat/ChatDepartmentUserEntity.php create mode 100644 ci4/app/Entities/Chat/ChatEntity.php create mode 100644 ci4/app/Entities/Chat/ChatMessageEntity.php create mode 100644 ci4/app/Entities/Chat/ChatNotificationEntity.php create mode 100644 ci4/app/Entities/Chat/ChatUserEntity.php create mode 100644 ci4/app/Services/ChatService.php diff --git a/ci4/app/Config/Routes.php b/ci4/app/Config/Routes.php index 8ac4ad83..b40d287a 100644 --- a/ci4/app/Config/Routes.php +++ b/ci4/app/Config/Routes.php @@ -908,7 +908,7 @@ $routes->group('chat', ['namespace' => 'App\Controllers\Chat'], function ($route $routes->post('department', 'ChatController::store_chat_department', ['as' => 'storeChatDepartment']); $routes->delete('department/(:num)', 'ChatController::delete_chat_department/$1', ['as' => 'deleteChatDepartment']); $routes->post('department/update/(:num)', 'ChatController::update_chat_department/$1', ['as' => 'updateChatDepartment']); - $routes->get('departments', 'ChatController::get_chat_departments', ['as' => 'getChatDepartments']); + $routes->get('departments/(:alpha)/(:num)', 'ChatController::get_chat_departments/$1/$2', ['as' => 'getChatDepartments']); $routes->get('departments/select', 'ChatController::get_chat_department_select', ['as' => 'getChatDepartmentSelect']); $routes->get('department/presupuesto/(:num)/(:num)', 'ChatController::get_chat_presupuesto/$1/$2', ['as' => 'getChatPresupuesto']); $routes->get('department/pedido/(:num)/(:num)', 'ChatController::get_chat_pedido/$1/$2', ['as' => 'getChatPedido']); @@ -928,9 +928,7 @@ $routes->group('chat', ['namespace' => 'App\Controllers\Chat'], function ($route $routes->get('(:num)', 'ChatController::get_chat/$1', ['as' => 'getChat']); $routes->post('message/error/presupuesto', 'ChatController::store_chat_error_message', ['as' => 'storeChatErrorMessage']); - $routes->post('message/presupuesto', 'ChatController::store_chat_message_presupuesto', ['as' => 'storeChatMessagePresupuesto']); - $routes->post('message/pedido', 'ChatController::store_chat_message_pedido', ['as' => 'storeChatMessagePedido']); - $routes->post('message/factura', 'ChatController::store_chat_message_factura', ['as' => 'storeChatMessageFactura']); + $routes->post('message/(:alpha)', 'ChatController::store_message/$1', ['as' => 'storeChatMessage']); $routes->post('message/internal', 'ChatController::store_chat_message_single', ['as' => 'storeChatMessageSingle']); $routes->get('contacts', 'ChatController::get_chat_internal_contacts', ['as' => 'getChatInternalContacts']); $routes->get('contacts/(:num)', 'ChatController::get_chat_internal_contact/$1', ['as' => 'getChatInternalContact']); @@ -939,15 +937,11 @@ $routes->group('chat', ['namespace' => 'App\Controllers\Chat'], function ($route $routes->get('users/internal', 'ChatController::get_chat_users_internal', ['as' => 'getChatUsersInternal']); $routes->get('users/all', 'ChatController::get_chat_users_all', ['as' => 'getChatUsersAll']); - $routes->post('hebra/presupuesto', 'ChatController::store_hebra_presupuesto', ['as' => 'storeHebraPresupuesto']); - $routes->post('hebra/pedido', 'ChatController::store_hebra_pedido', ['as' => 'storeHebraPedido']); - $routes->post('hebra/factura', 'ChatController::store_hebra_factura', ['as' => 'storeHebraFactura']); + $routes->post('hebra/(:alpha)', 'ChatController::store_hebra/$1', ['as' => 'storeHebra']); $routes->post('hebra/(:num)', 'ChatController::update_hebra/$1', ['as' => 'updateHebra']); - $routes->get('hebra/presupuesto/(:num)', "ChatController::get_hebra_presupuesto/$1", ["as" => "getHebraPresupuesto"]); - $routes->get('hebra/pedido/(:num)', "ChatController::get_hebra_pedido/$1", ["as" => "getHebraPedido"]); - $routes->get('hebra/factura/(:num)', "ChatController::get_hebra_factura/$1", ["as" => "getHebraFactura"]); + $routes->get('hebra/(:alpha)/(:num)', "ChatController::get_hebra/$1/$2", ["as" => "getHebra"]); - $routes->get('users/notifications-unviewed/(:num)','ChatController::get_notifications_not_viewed_from_chat/$1'); + $routes->get('users/message/notifications-unviewed/(:num)','ChatController::get_notifications_not_viewed_from_message/$1'); }); diff --git a/ci4/app/Config/Services.php b/ci4/app/Config/Services.php index 33330fa1..9309734f 100755 --- a/ci4/app/Config/Services.php +++ b/ci4/app/Config/Services.php @@ -2,6 +2,7 @@ namespace Config; +use App\Services\ChatService; use App\Services\FTPService; use App\Services\MaquinaService; use App\Services\MessageService; @@ -53,4 +54,8 @@ class Services extends BaseService { return new MessageService(); } + public static function chat() + { + return new ChatService(); + } } diff --git a/ci4/app/Controllers/Chat/ChatController.php b/ci4/app/Controllers/Chat/ChatController.php index 840785ce..b54ec909 100644 --- a/ci4/app/Controllers/Chat/ChatController.php +++ b/ci4/app/Controllers/Chat/ChatController.php @@ -14,6 +14,7 @@ use App\Models\Facturas\FacturaModel; use App\Models\Pedidos\PedidoModel; use App\Models\Presupuestos\PresupuestoModel; use App\Models\Usuarios\UserModel; +use App\Services\ChatService; use App\Services\MessageService; use CodeIgniter\HTTP\ResponseInterface; use CodeIgniter\HTTP\RequestInterface; @@ -34,7 +35,7 @@ class ChatController extends BaseController protected ChatUser $chatUserModel; protected ChatNotification $chatNotificationModel; protected Validation $validation; - + protected ChatService $chatService; protected array $viewData; protected static $viewPath = 'themes/vuexy/form/mensajes/'; @@ -56,12 +57,15 @@ class ChatController extends BaseController $this->chatUserModel = model(ChatUser::class); $this->chatNotificationModel = model(ChatNotification::class); $this->validation = service("validation"); + $this->chatService = service("chat"); + } public function index() {} - public function get_chat_departments() + public function get_chat_departments(string $model,int $modelId) { - $data = $this->chatDeparmentModel->getChatDepartments(); + $data = $this->chatService->getChatDepartments($model,$modelId); + return $this->response->setJSON($data); } public function get_chat_department_select() @@ -73,6 +77,7 @@ class ChatController extends BaseController { $data = [ + "department" => $this->chatDeparmentModel->find($chat_department_id), "chat" => null, "messages" => null, "count" => 0, @@ -82,6 +87,7 @@ class ChatController extends BaseController $data["messages"] = $this->chatMessageModel->get_chat_messages($chat->id); $this->chatMessageModel->set_chat_department_messages_as_read($chat->id); $this->chatModel->setAsViewedChatUserNotifications($chat->id, auth()->user()->id); + $data["count"] = count($data["messages"]); } $data["chat"] = $chat; @@ -91,6 +97,7 @@ class ChatController extends BaseController { $data = [ + "department" => $this->chatDeparmentModel->find($chat_department_id), "chat" => null, "messages" => null, "count" => 0, @@ -110,6 +117,7 @@ class ChatController extends BaseController { $data = [ + "department" => $this->chatDeparmentModel->find($chat_department_id), "chat" => null, "messages" => null, "count" => 0, @@ -200,115 +208,15 @@ class ChatController extends BaseController $data = $this->chatModel->getChat($chat_id); return $this->response->setJSON($data); } - public function store_chat_message_presupuesto() + public function store_message($model) { $data = $this->request->getPost(); - // $data = $this->chatModel->createChatPresupuesto(); - $existChat = $this->chatModel->existChatPresupuesto($data["chat_department_id"], $data["model_id"]); - if ($existChat == false) { - $chatId = $this->chatModel->createChatPresupuesto($data["chat_department_id"], $data["model_id"]); - } else { - $chat = $this->chatModel->getChatPresupuesto($data["chat_department_id"], $data["model_id"]); - $chatId = $chat->id; - } - $chat_message_id = $this->chatMessageModel->insert(["chat_id" => $chatId, "sender_id" => auth()->user()->id, "message" => $data["message"]]); - $dataResponse = $this->chatMessageModel->find($chat_message_id); - $chatDepartmentUsers = $this->chatDeparmentModel->getChatDepartmentUsers($data["chat_department_id"]); - if (auth()->user()->inGroup('admin')) { - $cliente_in_department_count = $this->chatDeparmentUserModel->where('chat_department_id', $data["chat_department_id"])->where('user_id', $data['client'])->where('presupuesto_id', $data['model_id'])->countAllResults(); - if ($cliente_in_department_count == 0) { - $this->chatDeparmentUserModel->insert(['chat_department_id' => $data["chat_department_id"], 'user_id' => $data['client'], 'presupuesto_id' => $data['model_id']]); - } - } - $chatExternalUsers = $this->chatDeparmentModel->getChatDeparmentPresupuestoUsers($data["chat_department_id"], $data["model_id"]); - $auth_user_in_department_count = $this->chatDeparmentUserModel->where('chat_department_id', $data["chat_department_id"])->where('user_id', auth()->user()->id)->countAllResults(); + $chatMessageEntity = $this->chatService->storeChatMessage($data["chat_department_id"],$model,$data["model_id"],$data); + return $this->response->setJSON($chatMessageEntity); - if ($auth_user_in_department_count) { - $this->chatDeparmentUserModel->insert(['chat_department_id' => $data["chat_department_id"], 'user_id' => auth()->user()->id, 'presupuesto_id' => $data['model_id']]); - } - - foreach ($chatDepartmentUsers as $user) { - if ($user->id != auth()->user()->id) { - $this->chatNotificationModel->insert(["chat_message_id" => $chat_message_id, "user_id" => $user->id]); - } - } - foreach ($chatExternalUsers as $user) { - $this->chatNotificationModel->insert(["chat_message_id" => $chat_message_id, "user_id" => $user->id]); - } - return $this->response->setJSON($dataResponse); } - public function store_chat_message_pedido() - { - $data = $this->request->getPost(); - $existChat = $this->chatModel->existChatPedido($data["chat_department_id"], $data["model_id"]); - if ($existChat == false) { - $chatId = $this->chatModel->createChatPedido($data["chat_department_id"], $data["model_id"]); - } else { - $chat = $this->chatModel->getChatPedido($data["chat_department_id"], $data["model_id"]); - $chatId = $chat->id; - } - $chat_message_id = $this->chatMessageModel->insert(["chat_id" => $chatId, "sender_id" => auth()->user()->id, "message" => $data["message"]]); - $dataResponse = $this->chatMessageModel->find($chat_message_id); - $chatDepartmentUsers = $this->chatDeparmentModel->getChatDepartmentUsers($data["chat_department_id"]); - if (auth()->user()->inGroup('admin')) { - $cliente_in_department_count = $this->chatDeparmentUserModel->where('chat_department_id', $data["chat_department_id"])->where('user_id', $data['client'])->where('pedido_id', $data['model_id'])->countAllResults(); - if ($cliente_in_department_count == 0) { - $this->chatDeparmentUserModel->insert(['chat_department_id' => $data["chat_department_id"], 'user_id' => $data['client'], 'pedido_id' => $data['model_id']]); - } - } - $chatExternalUsers = $this->chatDeparmentModel->getChatDeparmentPedidoUsers($data["chat_department_id"], $data["model_id"]); - $auth_user_in_department_count = $this->chatDeparmentUserModel->where('chat_department_id', $data["chat_department_id"])->where('user_id', auth()->user()->id)->countAllResults(); - if ($auth_user_in_department_count == 0) { - $this->chatDeparmentUserModel->insert(['chat_department_id' => $data["chat_department_id"], 'user_id' => auth()->user()->id, 'pedido_id' => $data['model_id']]); - } - - foreach ($chatDepartmentUsers as $user) { - if ($user->id != auth()->user()->id) { - $this->chatNotificationModel->insert(["chat_message_id" => $chat_message_id, "user_id" => $user->id]); - } - } - foreach ($chatExternalUsers as $user) { - $this->chatNotificationModel->insert(["chat_message_id" => $chat_message_id, "user_id" => $user->id]); - } - return $this->response->setJSON($dataResponse); - } - public function store_chat_message_factura() - { - $data = $this->request->getPost(); - $existChat = $this->chatModel->existChatPedido($data["chat_department_id"], $data["model_id"]); - if ($existChat == false) { - $chatId = $this->chatModel->createChatPedido($data["chat_department_id"], $data["model_id"]); - } else { - $chat = $this->chatModel->getChatPedido($data["chat_department_id"], $data["model_id"]); - $chatId = $chat->id; - } - $chat_message_id = $this->chatMessageModel->insert(["chat_id" => $chatId, "sender_id" => auth()->user()->id, "message" => $data["message"]]); - $dataResponse = $this->chatMessageModel->find($chat_message_id); - $chatDepartmentUsers = $this->chatDeparmentModel->getChatDepartmentUsers($data["chat_department_id"]); - if (auth()->user()->inGroup('admin')) { - $cliente_in_department_count = $this->chatDeparmentUserModel->where('chat_department_id', $data["chat_department_id"])->where('user_id', $data['client'])->where('pedido_id', $data['model_id'])->countAllResults(); - if ($cliente_in_department_count == 0) { - $this->chatDeparmentUserModel->insert(['chat_department_id' => $data["chat_department_id"], 'user_id' => $data['client'], 'factura_id' => $data['model_id']]); - } - } - $chatExternalUsers = $this->chatDeparmentModel->getChatDeparmentPedidoUsers($data["chat_department_id"], $data["model_id"]); - $auth_user_in_department_count = $this->chatDeparmentUserModel->where('chat_department_id', $data["chat_department_id"])->where('user_id', auth()->user()->id)->countAllResults(); - if ($auth_user_in_department_count == 0) { - $this->chatDeparmentUserModel->insert(['chat_department_id' => $data["chat_department_id"], 'user_id' => auth()->user()->id, 'pedido_id' => $data['model_id']]); - } - - foreach ($chatDepartmentUsers as $user) { - if ($user->id != auth()->user()->id) { - $this->chatNotificationModel->insert(["chat_message_id" => $chat_message_id, "user_id" => $user->id]); - } - } - foreach ($chatExternalUsers as $user) { - $this->chatNotificationModel->insert(["chat_message_id" => $chat_message_id, "user_id" => $user->id]); - } - return $this->response->setJSON($dataResponse); - } public function store_chat_message_single() { $data = $this->request->getPost(); @@ -369,68 +277,24 @@ class ChatController extends BaseController public function get_chat_cliente() { $cliente_id = auth()->user()->cliente_id; - $response = []; - if ($cliente_id) { - // $data = $this->clienteModel->getClienteDataPresupuestoPedidoFactura($cliente_id); - $response["internals"] = $this->chatModel->getChatDepartmentNotifications(); - $response["totalMessages"] = 0; - $mensajes_directos = $this->chatModel->getChatDirectMessageNotifications(); - // $response["chatFacturas"] = $this->chatModel->getClienteChatFacturas($data["facturas"]); - // foreach ($response["chatFacturas"] as $key => $value) { - // $response["totalMessages"] += $value->unreadMessages; - // } - // $response["chatPresupuestos"] = $this->chatModel->getClienteChatPresupuestos($data["presupuestos"]); - // 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; - // } - // $response["data"] = $data; - $response["totalMessages"] = 0; - foreach ($response["internals"] as $key => $value) { - $response["totalMessages"] += $value->unreadMessages; - } - } 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; - } - } + $response = $this->chatService->getAuthUserNotifications(); return $this->response->setJSON($response); } public function get_chat_department_presupuesto_users(int $chat_department_id, int $presupuesto_id) { - $adminUsers = $this->chatDeparmentModel->getChatDepartmentUsers($chat_department_id); - $externalUsers = $this->chatDeparmentModel->getChatDeparmentPresupuestoUsers($chat_department_id, $presupuesto_id); - return $this->response->setJSON(['admin_users' => $adminUsers, 'external_users' => $externalUsers]); + $data = $this->chatDeparmentModel->find($chat_department_id)->withUsers($presupuesto_id, 'presupuesto'); + return $this->response->setJSON($data); } public function get_chat_department_pedido_users(int $chat_department_id, $pedido_id) { - $adminUsers = $this->chatDeparmentModel->getChatDepartmentUsers($chat_department_id); - $externalUsers = $this->chatDeparmentModel->getChatDeparmentPedidoUsers($chat_department_id, $pedido_id); - return $this->response->setJSON(['admin_users' => $adminUsers, 'external_users' => $externalUsers]); + $data = $this->chatDeparmentModel->find($chat_department_id)->withUsers($pedido_id, 'pedido'); + return $this->response->setJSON($data); } public function get_chat_department_factura_users(int $chat_department_id, $factura_id) { - $adminUsers = $this->chatDeparmentModel->getChatDepartmentUsers($chat_department_id); - $externalUsers = $this->chatDeparmentModel->getChatDeparmentFacturaUsers($chat_department_id, $factura_id); - return $this->response->setJSON(['admin_users' => $adminUsers, 'external_users' => $externalUsers]); + $data = $this->chatDeparmentModel->find($chat_department_id)->withUsers($factura_id, 'factura'); + return $this->response->setJSON($data); } public function get_chat_users_internal() { @@ -536,80 +400,14 @@ class ChatController extends BaseController return $this->response->setJSON($query->get()->getResultObject()); } - public function store_hebra_presupuesto() + public function store_hebra(string $model) { $auth_user = auth()->user(); $bodyData = $this->request->getPost(); - $chat_id = $this->chatModel->insert([ - "presupuesto_id" => $bodyData["modelId"], - "title" => $bodyData["title"] - ]); - $chatMessageId = $this->chatMessageModel->insert([ - "chat_id" => $chat_id, - "message" => $bodyData["message"], - "sender_id" => $auth_user->id - ]); - if (isset($bodyData["users"])) { - $bodyData["users"][] = $auth_user->id; - $chatUserData = array_map(fn($x) => ["user_id" => $x, "chat_id" => $chat_id], $bodyData["users"]); - $this->chatUserModel->insertBatch($chatUserData); - foreach ($bodyData["users"] as $userId) { - $this->chatNotificationModel->insert( - ["chat_message_id" => $chatMessageId, "user_id" => $userId] - ); - } - } - return $this->response->setJSON(["message" => "Hebra creada correctamente", "status" => true]); + $status = $this->chatService->storeHebra($model,$bodyData['modelId'],$bodyData); + return $this->response->setJSON(["message" => "Hebra creada correctamente", "status" => $status]); } - public function store_hebra_pedido() - { - $bodyData = $this->request->getPost(); - $chat_id = $this->chatModel->insert([ - "pedido_id" => $bodyData["modelId"], - "title" => $bodyData["title"] - - ]); - $chatMessageId = $this->chatMessageModel->insert([ - "chat_id" => $chat_id, - "message" => $bodyData["message"], - "sender_id" => auth()->user()->id - ]); - if (isset($bodyData["users"])) { - $chatUserData = array_map(fn($x) => ["user_id" => $x, "chat_id" => $chat_id], $bodyData["users"]); - $this->chatUserModel->insertBatch($chatUserData); - foreach ($bodyData["users"] as $userId) { - $this->chatNotificationModel->insert( - ["chat_message_id" => $chatMessageId, "user_id" => $userId] - ); - } - } - return $this->response->setJSON(["message" => "Hebra creada correctamente", "status" => true]); - } - - public function store_hebra_factura() - { - $bodyData = $this->request->getPost(); - $chat_id = $this->chatModel->insert([ - "factura_id" => $bodyData["modelId"], - "title" => $bodyData["title"] - ]); - $chatMessageId = $this->chatMessageModel->insert([ - "chat_id" => $chat_id, - "message" => $bodyData["message"], - "sender_id" => auth()->user()->id - ]); - if (isset($bodyData["users"])) { - $chatUserData = array_map(fn($x) => ["user_id" => $x, "chat_id" => $chat_id], $bodyData["users"]); - $this->chatUserModel->insertBatch($chatUserData); - foreach ($bodyData["users"] as $userId) { - $this->chatNotificationModel->insert( - ["chat_message_id" => $chatMessageId, "user_id" => $userId] - ); - } - } - return $this->response->setJSON(["message" => "Hebra creada correctamente", "status" => true]); - } public function update_hebra($chat_id) { $bodyData = $this->request->getPost(); @@ -620,11 +418,7 @@ class ChatController extends BaseController ]); $actualUsers = $this->chatUserModel->builder()->select("user_id")->where("chat_id", $chat_id)->get()->getResultArray(); $actualUsersArray = array_map(fn($x) => $x["user_id"], $actualUsers); - foreach ($actualUsersArray as $key => $user_id) { - $this->chatNotificationModel->insert( - ["chat_message_id" => $chatMessageId, "user_id" => $user_id] - ); - } + if (isset($bodyData["users"])) { foreach ($bodyData["users"] as $userId) { if (in_array($userId, $actualUsersArray) == false) { @@ -638,55 +432,13 @@ class ChatController extends BaseController } return $this->response->setJSON(["message" => "Hebra actualizada correctamente", "status" => true]); } - public function get_hebra_presupuesto($presupuesto_id) + public function get_hebra(string $model,int $modelId) { - $data = $this->chatModel->getPresupuestoHebras($presupuesto_id); - $notifications = $this->chatModel->builder()->select([ - "chat_notifications.id" - ]) - ->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", $presupuesto_id) - ->where("chat_notifications.user_id", auth()->user()->id) - ->get()->getResultArray(); - foreach ($notifications as $notification) { - $this->chatNotificationModel->update($notification["id"], ["viewed" => true]); - } - return $this->response->setJSON($data); - } - public function get_hebra_pedido($pedido_id) - { - $data = $this->chatModel->getPedidoHebras($pedido_id); - $notifications = $this->chatModel->builder()->select([ - "chat_notifications.id" - ]) - ->join("chat_messages", "chat_messages.chat_id = chats.id", "left") - ->join("chat_notifications", "chat_notifications.chat_message_id = chat_messages.id", "left") - ->where("chats.pedido_id", $pedido_id) - ->where("chat_notifications.user_id", auth()->user()->id) - ->get()->getResultArray(); - foreach ($notifications as $notification) { - $this->chatNotificationModel->update($notification["id"], ["viewed" => true]); - } - return $this->response->setJSON($data); - } - public function get_hebra_factura($factura_id) - { - $data = $this->chatModel->getFacturaHebras($factura_id); - $notifications = $this->chatModel->builder()->select([ - "chat_notifications.id" - ]) - ->join("chat_messages", "chat_messages.chat_id = chats.id", "left") - ->join("chat_notifications", "chat_notifications.chat_message_id = chat_messages.id", "left") - ->where("chats.factura_id", $factura_id) - ->where("chat_notifications.user_id", auth()->user()->id) - ->get()->getResultArray(); - foreach ($notifications as $notification) { - $this->chatNotificationModel->update($notification["id"], ["viewed" => true]); - } + $data = $this->chatService->getHebras($model,$modelId); return $this->response->setJSON($data); } + public function datatable_messages() { $auth_user_id = auth()->user()->id; @@ -716,9 +468,9 @@ class ChatController extends BaseController return DataTable::of($query) ->edit('created_at', fn($q) => $q->created_at ? Time::createFromFormat('Y-m-d H:i:s', $q->created_at)->format("d/m/Y H:i") : "") ->edit('updated_at', fn($q) => $q->updated_at ? Time::createFromFormat('Y-m-d H:i:s', $q->updated_at)->format("d/m/Y H:i") : "") - ->add("creator", fn($q) => $this->chatModel->getChatFirstUser($q->id)->userFullName) - ->add("viewed", fn($q) => $this->chatModel->isMessageChatViewed($q->id, $auth_user_id)) - ->add("action", fn($q) => ["type" => "presupuesto", "modelId" => $q->id, "isAdmin" => $isAdmin, "lang" => [ + ->add("viewed", fn($q) => $this->chatModel->isMessageChatViewed($q->chatMessageId)) + ->edit("creator",fn($q) => $q->userId == $auth_user_id ? ''.lang("App.me").'' : $q->creator) + ->add("action", fn($q) => ["type" => "presupuesto", "modelId" => $q->id, "isAdmin" => $isAdmin,"chatMessageId" => $q->chatMessageId, "lang" => [ "view_chat" => lang('Chat.view_chat'), "view_by_alt_message" => lang('Chat.view_by_alt_message') ]]) @@ -732,9 +484,9 @@ class ChatController extends BaseController return DataTable::of($query) ->edit('created_at', fn($q) => $q->created_at ? Time::createFromFormat('Y-m-d H:i:s', $q->created_at)->format("d/m/Y H:i") : "") ->edit('updated_at', fn($q) => $q->updated_at ? Time::createFromFormat('Y-m-d H:i:s', $q->updated_at)->format("d/m/Y H:i") : "") - ->add("creator", fn($q) => $this->chatModel->getChatFirstUser($q->id)->userFullName) - ->add("viewed", fn($q) => $this->chatModel->isMessageChatViewed($q->id, $auth_user_id)) - ->add("action", fn($q) => ["type" => "pedido", "modelId" => $q->id, "isAdmin" => $isAdmin, "lang" => [ + ->edit("creator",fn($q) => $q->userId == $auth_user_id ? ''.lang("App.me").'' : $q->creator) + ->add("viewed", fn($q) => $this->chatModel->isMessageChatViewed($q->chatMessageId)) + ->add("action", fn($q) => ["type" => "pedido", "modelId" => $q->id, "isAdmin" => $isAdmin,"chatMessageId" => $q->chatMessageId, "lang" => [ "view_chat" => lang('Chat.view_chat'), "view_by_alt_message" => lang('Chat.view_by_alt_message') ]]) @@ -749,27 +501,26 @@ class ChatController extends BaseController return DataTable::of($query) ->edit('created_at', fn($q) => $q->created_at ? Time::createFromFormat('Y-m-d H:i:s', $q->created_at)->format("d/m/Y H:i") : "") ->edit('updated_at', fn($q) => $q->updated_at ? Time::createFromFormat('Y-m-d H:i:s', $q->updated_at)->format("d/m/Y H:i") : "") - ->add("creator", fn($q) => $this->chatModel->getChatFirstUser($q->id)->userFullName) - ->add("viewed", fn($q) => $this->chatModel->isMessageChatViewed($q->id, $auth_user_id)) - ->add("action", fn($q) => ["type" => "factura", "modelId" => $q->id, "isAdmin" => $isAdmin, "lang" => [ + ->edit("creator",fn($q) => $q->userId == $auth_user_id ? ''.lang("App.me").'' : $q->creator) + ->add("viewed", fn($q) => $this->chatModel->isMessageChatViewed($q->chatMessageId)) + ->add("action", fn($q) => ["type" => "factura", "modelId" => $q->id, "isAdmin" => $isAdmin,"chatMessageId" => $q->chatMessageId, "lang" => [ "view_chat" => lang('Chat.view_chat'), "view_by_alt_message" => lang('Chat.view_by_alt_message') ]]) ->toJson(true); } - public function get_notifications_not_viewed_from_chat(int $chat_id) + public function get_notifications_not_viewed_from_message(int $chat_message_id) { - $unviewedNotifications = $this->chatModel->getUsersNotificationNotViewedFromChat($chat_id); - $viewedNotifications = $this->chatModel->getUsersNotificationViewedFromChat($chat_id); + $unviewedNotifications = $this->chatModel->getUsersNotificationNotViewedFromChat($chat_message_id); + // $viewedNotifications = $this->chatModel->getUsersNotificationViewedFromChat($chat_message_id); return $this->response->setJSON( [ "data" => [ - "unviewedNotifications" => $unviewedNotifications, - "viewedNotifications" => $viewedNotifications + "notifications" => $unviewedNotifications, ], - "chat_id" => $chat_id + "chat_message_id" => $chat_message_id ] ); } diff --git a/ci4/app/Entities/Chat/ChatDepartmentEntity.php b/ci4/app/Entities/Chat/ChatDepartmentEntity.php new file mode 100644 index 00000000..5017c310 --- /dev/null +++ b/ci4/app/Entities/Chat/ChatDepartmentEntity.php @@ -0,0 +1,79 @@ + null, + "name" => null, + "display" => null, + "description" => null, + "type" => null, + ]; + + + protected $casts = [ + "name" => "string", + "display" => "string", + "description" => "?string", + "type" => "string", + ]; + + /** + * Chat department users that are in department as administrador. These users belongs to department in all chats in any model associated and + * will receive notifications always + * + * @return array + */ + public function chatDepartmentAdminUsers(){ + $m = model(ChatDeparmentUserModel::class); + $chatDepartmentUsers = $m->where('chat_department_id',$this->attributes['id']) + ->where('pedido_id',null) + ->where('factura_id',null) + ->where('presupuesto_id',null)->findAll(); + return $chatDepartmentUsers; + } + /** + * Chat department users that has been associated to the department by sending a + * message and users that are not as admin of the department that has written a message. + * + * @param integer $modelFkId Id from model associated + * @param string $model Name of the model associated `['presupuesto','pedido','factura']` + * @return array + */ + public function chatDepartmentExternalUsers(int $modelFkId,string $model = "presupuesto") : array + { + $m = model(ChatDeparmentUserModel::class); + $m->where('chat_department_id',$this->attributes['id']); + + switch ($model) { + case 'presupuesto': + $m->where('presupuesto_id',$modelFkId); + break; + case 'pedido': + $m->where('pedido_id',$modelFkId); + break; + case 'factura': + $m->where('pedido_id',$modelFkId); + break; + default: + break; + } + return $m->findAll() ?? []; + + } + public function withUsers(int $modelFkId,string $model = "presupuesto") : self + { + $externalUsers = $this->chatDepartmentExternalUsers($modelFkId,$model); + $this->attributes["adminUsers"] = array_map(fn(ChatDepartmentUserEntity $du) => $du->user()->withAvatar() , $this->chatDepartmentAdminUsers()); + $this->attributes["externalUsers"] = array_map(fn(ChatDepartmentUserEntity $du) => $du->user()->withAvatar() , $externalUsers); + return $this; + } + +} diff --git a/ci4/app/Entities/Chat/ChatDepartmentUserEntity.php b/ci4/app/Entities/Chat/ChatDepartmentUserEntity.php new file mode 100644 index 00000000..c261f568 --- /dev/null +++ b/ci4/app/Entities/Chat/ChatDepartmentUserEntity.php @@ -0,0 +1,60 @@ + null, + "user_id" => null, + "pedido_id" => null, + "factura_id" => null, + "presupuesto_id" => null, + ]; + + + protected $casts = [ + "chat_department_id" => "integer", + "user_id" => "integer", + "pedido_id" => "?integer", + "factura_id" => "?integer", + "presupuesto_id" => "?integer", + ]; + + public function user() : ?UserEntity + { + $m = model(UserModel::class); + return $m->find($this->attributes['user_id']); + } + public function department() : ?ChatDepartmentEntity + { + $m = model(ChatDeparmentModel::class); + return $m->find($this->attributes['chat_department_id']); + } + public function presupuesto() : ?PresupuestoEntity + { + $m = model(PresupuestoModel::class); + return $m->find($this->attributes['presupuesto_id']); + } + public function pedido() : ?PedidoEntity + { + $m = model(PedidoModel::class); + return $m->find($this->attributes['pedido_id']); + } + public function factura() : ?FacturaEntity + { + $m = model(FacturaEntity::class); + return $m->find($this->attributes['factura_id']); + } + +} diff --git a/ci4/app/Entities/Chat/ChatEntity.php b/ci4/app/Entities/Chat/ChatEntity.php new file mode 100644 index 00000000..1669f3cd --- /dev/null +++ b/ci4/app/Entities/Chat/ChatEntity.php @@ -0,0 +1,148 @@ + null, + "chat_department_id" => null, + "pedido_id" => null, + "presupuesto_id" => null, + "factura_id" => null, + "title" => null + ]; + + + protected $casts = [ + "chat_department_id" => "?integer", + "pedido_id" => "?integer", + "presupuesto_id" => "?integer", + "factura_id" => "?integer", + "title" => "string" + ]; + + public function withMessages(): self + { + $auth_user = auth()->user(); + $messages = $this->messages(); + foreach ($messages as $key => $message) { + if ($message->sender_id == $auth_user->id) { + $message->pos = 'right'; + } else { + $message->pos = 'left'; + } + } + $this->attributes["messages"] = $messages; + return $this; + } + public function department(): ?ChatDepartmentEntity + { + $m = model(ChatDeparmentModel::class); + return $m->find($this->attributes['chat_department_id']); + } + public function presupuesto(): ?PresupuestoEntity + { + $m = model(PresupuestoModel::class); + return $m->find($this->attributes['presupuesto_id']); + } + public function pedido(): ?PedidoEntity + { + $m = model(PedidoModel::class); + return $m->find($this->attributes['pedido_id']); + } + public function factura(): ?FacturaEntity + { + $m = model(FacturaEntity::class); + return $m->find($this->attributes['factura_id']); + } + public function messages(): ?array + { + $m = model(ChatMessageModel::class); + + $messages = $m->where('chat_id', $this->attributes["id"])->findAll(); + return array_map(fn(ChatMessageEntity $m) => $m->withUser(), $messages); + } + public function withHebra(): self + { + $this->attributes["messages"] = array_map(fn(ChatMessageEntity $m) => $m->withUser(), $this->messages()); + $this->attributes["internalUsers"] = array_map(fn(ChatUserEntity $u) => $u->user(), $this->internalUsers()); + return $this; + } + /** + * Undocumented function + * + * @return array + */ + public function internalUsers(): array + { + $m = model(ChatUser::class); + return $m->where('chat_id', $this->attributes["id"])->findAll() ?? []; + } + public function getModel(): ?Model + { + $model = null; + $models = [ + "presupuesto_id" => model(PresupuestoModel::class), + "pedido_id" => model(PedidoModel::class), + "factura_id" => model(FacturaModel::class) + ]; + $fks = [ + "presupuesto_id" => $this->attributes["presupuesto_id"], + "pedido_id" => $this->attributes["pedido_id"], + "factura_id" => $this->attributes["factura_id"], + ]; + foreach ($fks as $key => $fk) { + if ($fk) { + $model = $models[$key]; + break; + } + } + return $model; + } + public function relatedFk(): array + { + $relatedFk = null; + $relatedFkValue = null; + $fks = [ + "presupuesto" => $this->attributes["presupuesto_id"], + "pedido" => $this->attributes["pedido_id"], + "factura" => $this->attributes["factura_id"], + ]; + foreach ($fks as $key => $fk) { + if ($fk) { + $relatedFk = $key; + $relatedFkValue = $fk; + break; + } + } + return [ + "relatedModel" => $relatedFk, + "relatedFkValue" => $relatedFkValue + ]; + } + public function withModel() : self + { + if($this->getModel()){ + $this->attributes["modelData"] = $this->getModel()->find($this->relatedFk()['relatedFkValue']); + }else{ + $this->attributes["modelData"] = null; + } + return $this; + } +} diff --git a/ci4/app/Entities/Chat/ChatMessageEntity.php b/ci4/app/Entities/Chat/ChatMessageEntity.php new file mode 100644 index 00000000..2771a9c4 --- /dev/null +++ b/ci4/app/Entities/Chat/ChatMessageEntity.php @@ -0,0 +1,65 @@ + null, + "message" => null, + "chat_id" => null, + "sender_id" => null, + "receiver_id" => null, + "viewed" => null, + ]; + + + protected $casts = [ + "message" => "string", + "chat_id" => "integer", + "sender_id" => "?integer", + "receiver_id" => "?integer", + "viewed" => "boolean", + ]; + protected $dates = []; + + public function chat() : ?ChatEntity + { + $m = model(ChatModel::class); + return $m->find($this->attributes['chat_id']); + + } + /** + * Notifications related with this chat entity. + * + * @return array + */ + public function notifications() : array + { + $m = model(ChatNotification::class); + return $m->asArray()->where('chat_id',$this->attributes['chat_id'])->findAll() ?? []; + } + public function sentBy() : ?UserEntity + { + $m = model(UserModel::class); + return $m->find($this->attributes["sender_id"])->withAvatar(); + + } + public function withUser() : self + { + $this->attributes["user"] = $this->sentBy(); + return $this; + } + public function getCreatedAt() + { + return Time::createFromFormat("Y-m-d H:i:s",$this->attributes['created_at'])->format('d/m/Y H:i'); + + } +} diff --git a/ci4/app/Entities/Chat/ChatNotificationEntity.php b/ci4/app/Entities/Chat/ChatNotificationEntity.php new file mode 100644 index 00000000..07828a1c --- /dev/null +++ b/ci4/app/Entities/Chat/ChatNotificationEntity.php @@ -0,0 +1,42 @@ + null, + "chat_message_id" => null, + "user_id" => null, + "viewed" => null, + ]; + + + protected $casts = [ + "chat_message_id" => "integer", + "user_id" => "integer", + "viewed" => "boolean", + ]; + + public function message() : ?ChatMessageEntity + { + $m = model(ChatMessageModel::class); + return $m->find($this->attributes['chat_message_id']); + } + public function user() : ?UserEntity + { + $m = model(UserModel::class); + return $m->find($this->attributes['user_id']); + } + public function chat() : ?ChatEntity + { + return $this->message()->chat(); + } + +} diff --git a/ci4/app/Entities/Chat/ChatUserEntity.php b/ci4/app/Entities/Chat/ChatUserEntity.php new file mode 100644 index 00000000..9f485cb5 --- /dev/null +++ b/ci4/app/Entities/Chat/ChatUserEntity.php @@ -0,0 +1,36 @@ + null, + "user_id" => null, + "chat_id" => null, + ]; + + + protected $casts = [ + "user_id" => "integer", + "chat_id" => "integer", + ]; + + public function chat() : ?ChatEntity + { + $m = model(ChatModel::class); + return $m->find($this->attributes['chat_id']); + + } + public function user() : ?UserEntity + { + $m = model(UserModel::class); + return $m->find($this->attributes['user_id'])->withAvatar(); + } + +} diff --git a/ci4/app/Entities/Usuarios/UserEntity.php b/ci4/app/Entities/Usuarios/UserEntity.php index 34206cad..a6410e2f 100755 --- a/ci4/app/Entities/Usuarios/UserEntity.php +++ b/ci4/app/Entities/Usuarios/UserEntity.php @@ -1,6 +1,8 @@ getFullName(); } + public function withAvatar() : self + { + $users = auth()->getProvider(); + $this->attributes["avatar"] = md5($users->findById($this->attributes['id'])->getEmail()); + return $this; + } + /** + * Return an array of ChatNotificationEntities that belongs to the user + * + * @return array + */ + public function chatNotifications() : array + { + $m = model(ChatNotification::class); + return $m->where('user_id',$this->attributes['id'])->findAll() ?? []; + } } diff --git a/ci4/app/Helpers/general_helper.php b/ci4/app/Helpers/general_helper.php index e0578134..0736e7aa 100644 --- a/ci4/app/Helpers/general_helper.php +++ b/ci4/app/Helpers/general_helper.php @@ -97,7 +97,10 @@ function getCurrentLanguageFlag(){ } } - +function getGravatarURL(int $size = 30) +{ + return "https://gravatar.com/avatar/".md5(auth()->user()->getEmail())."?s=".$size; +} function getAllClassFolder($folder = null){ try { helper('filesystem'); diff --git a/ci4/app/Language/es/App.php b/ci4/app/Language/es/App.php index 095247ad..eac95b5e 100755 --- a/ci4/app/Language/es/App.php +++ b/ci4/app/Language/es/App.php @@ -826,6 +826,6 @@ return [ "menu_soporte" => "Soporte", "menu_soporte_new_ticket" => "Crear ticket", "menu_soporte_ticket_list" => "Mis tickets", - + "me" => "Yo", ]; \ No newline at end of file diff --git a/ci4/app/Language/es/Chat.php b/ci4/app/Language/es/Chat.php index 300a3974..b1ba0e4e 100644 --- a/ci4/app/Language/es/Chat.php +++ b/ci4/app/Language/es/Chat.php @@ -20,6 +20,7 @@ return [ "created_at" => "Fecha creación", "updated_at" => "Fecha actualización", "title" => "Título", + "message" => "Mensaje", "creator" => "Creador", "viewed" => "Leído", diff --git a/ci4/app/Models/Chat/ChatDeparmentModel.php b/ci4/app/Models/Chat/ChatDeparmentModel.php index ec3a857a..c5d81c87 100644 --- a/ci4/app/Models/Chat/ChatDeparmentModel.php +++ b/ci4/app/Models/Chat/ChatDeparmentModel.php @@ -2,6 +2,7 @@ namespace App\Models\Chat; +use App\Entities\Chat\ChatDepartmentEntity; use App\Models\Usuarios\UserModel; use CodeIgniter\Model; @@ -10,7 +11,7 @@ class ChatDeparmentModel extends Model protected $table = 'chat_departments'; protected $primaryKey = 'id'; protected $useAutoIncrement = true; - protected $returnType = 'object'; + protected $returnType = ChatDepartmentEntity::class; protected $useSoftDeletes = true; protected $protectFields = true; protected $allowedFields = [ @@ -181,4 +182,20 @@ class ChatDeparmentModel extends Model { return $this->select(['id','display','description'])->where('deleted_at',null); } + + public function getModelChatDepartments(string $modelFk,int $modelId) : array + { + $query = $this->builder()->select([ + 'chat_departments.id', + 'chat_departments.name', + 'chat_departments.display', + 'COUNT(chat_messages.id) as countMessages' + ]) + ->join('chats','chats.chat_department_id = chat_departments.id','left') + ->join('chat_messages','chat_messages.chat_id = chats.id','left') + ->where($modelFk,$modelId) + ->groupBy('chat_departments.name'); + return $query->get()->getResultArray() ?? []; + + } } diff --git a/ci4/app/Models/Chat/ChatDeparmentUserModel.php b/ci4/app/Models/Chat/ChatDeparmentUserModel.php index 7726e5d9..1afdca85 100644 --- a/ci4/app/Models/Chat/ChatDeparmentUserModel.php +++ b/ci4/app/Models/Chat/ChatDeparmentUserModel.php @@ -2,6 +2,7 @@ namespace App\Models\Chat; +use App\Entities\Chat\ChatDepartmentUserEntity; use App\Models\Usuarios\UserModel; use CodeIgniter\Model; @@ -10,7 +11,7 @@ class ChatDeparmentUserModel extends Model protected $table = 'chat_department_users'; protected $primaryKey = 'id'; protected $useAutoIncrement = true; - protected $returnType = 'array'; + protected $returnType = ChatDepartmentUserEntity::class; protected $useSoftDeletes = true; protected $protectFields = true; protected $allowedFields = [ diff --git a/ci4/app/Models/Chat/ChatMessageModel.php b/ci4/app/Models/Chat/ChatMessageModel.php index e0ee9a20..5fb01241 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\Entities\Chat\ChatMessageEntity; use App\Models\ChatNotification; use App\Models\Usuarios\UserModel; use CodeIgniter\Model; @@ -12,7 +13,7 @@ class ChatMessageModel extends Model protected $table = 'chat_messages'; protected $primaryKey = 'id'; protected $useAutoIncrement = true; - protected $returnType = 'object'; + protected $returnType = ChatMessageEntity::class; protected $useSoftDeletes = true; protected $protectFields = true; protected $allowedFields = [ @@ -45,7 +46,7 @@ class ChatMessageModel extends Model // Callbacks protected $allowCallbacks = true; protected $beforeInsert = []; - protected $afterInsert = []; + protected $afterInsert = ['callbackNewMessage']; protected $beforeUpdate = []; protected $afterUpdate = []; protected $beforeFind = []; @@ -82,7 +83,6 @@ class ChatMessageModel extends Model if ($auth_user->id == $message->sender_id) { $message->sender_first_name = $auth_user->first_name; $message->sender_last_name = $auth_user->last_name; - } else { $sender_user = $user->find($message->sender_id); $message->sender_first_name = $sender_user->first_name; @@ -133,10 +133,10 @@ class ChatMessageModel extends Model ->where("receiver_id", auth()->user()->id)->countAllResults(); return $messagesFromReceiver; } - public function get_chat_department_messages_count(int $chat_id) : int + public function get_chat_department_messages_count(int $chat_id): int { $chatDepartmentMessagesCount = $this->builder() - ->where("id",$chat_id) + ->where("id", $chat_id) ->countAllResults(); return $chatDepartmentMessagesCount; } @@ -194,4 +194,46 @@ class ChatMessageModel extends Model return $messagesFromReceiver; } + public function callbackNewMessage(array $data) + { + $authUser = auth()->user(); + $chatNotificationModel = model(ChatNotification::class); + $chatMessageEntity = $this->find($data["id"]); + $chatEntity = $chatMessageEntity->chat(); + if ($chatEntity->chat_department_id) { + $chatDepartmentEntity = $chatEntity->department(); + $adminUsers = $chatDepartmentEntity->chatDepartmentAdminUsers(); + $modelFk = $chatEntity->relatedFk(); + $externalUsers = $chatDepartmentEntity->chatDepartmentExternalUsers($modelFk["relatedFkValue"], $modelFk["relatedModel"]); + if ($modelFk["relatedModel"] && $modelFk["relatedFkValue"]) { + + foreach ($adminUsers as $user) { + if ($user->user_id != $authUser->id) { + $chatNotificationModel->insert([ + "user_id" => $user->user_id, + "chat_message_id" => $data["id"] + ]); + } + } + foreach ($externalUsers as $user) { + if ($user->user_id != $authUser->id) { + $chatNotificationModel->insert([ + "user_id" => $user->user_id, + "chat_message_id" => $data["id"] + ]); + } + } + } + }else{ + foreach ($chatEntity->internalUsers() as $user) { + if ($user->user_id != $authUser->id) { + $chatNotificationModel->insert([ + "user_id" => $user->user_id, + "chat_message_id" => $data["id"] + ]); + } + } + } + return $data; + } } diff --git a/ci4/app/Models/Chat/ChatModel.php b/ci4/app/Models/Chat/ChatModel.php index 70db1dca..3106560f 100644 --- a/ci4/app/Models/Chat/ChatModel.php +++ b/ci4/app/Models/Chat/ChatModel.php @@ -2,6 +2,7 @@ namespace App\Models\Chat; +use App\Entities\Chat\ChatEntity; use App\Models\ChatNotification; use App\Models\ChatUser; use App\Models\Facturas\FacturaModel; @@ -16,7 +17,7 @@ class ChatModel extends Model protected $table = 'chats'; protected $primaryKey = 'id'; protected $useAutoIncrement = true; - protected $returnType = 'object'; + protected $returnType = ChatEntity::class; protected $useSoftDeletes = true; protected $protectFields = true; protected $allowedFields = [ @@ -315,12 +316,6 @@ class ChatModel extends Model } public function getChatDepartmentNotifications() { - $chatDeparmentModel = model(ChatDeparmentModel::class); - $chatMessageModel = model(ChatMessageModel::class); - $presupuestoModel = model(PresupuestoModel::class); - $facturaModel = model(FacturaModel::class); - $pedidoModel = model(PedidoModel::class); - $q = $this->builder() ->select([ "chats.id as chatId", @@ -329,7 +324,7 @@ class ChatModel extends Model "chats.presupuesto_id as presupuestoId", "chats.factura_id as facturaId", "chats.title as chatDisplay", - "COUNT(chat_notifications.viewed) as unreadMessages" + "COUNT(chat_notifications.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") @@ -343,36 +338,28 @@ class ChatModel extends Model $rows_new = []; foreach ($rows as $row) { if ($row->presupuestoId) { - $row->model = $presupuestoModel->find($row->presupuestoId); + // $row->model = $presupuestoModel->find($row->presupuestoId); if ($auth_user->cliente_id) { $row->uri = "/presupuestocliente/edit/" . $row->presupuestoId . "#accordionChatPresupuesto"; } else { $row->uri = "/presupuestoadmin/edit/" . $row->presupuestoId . "#accordionChatPresupuesto"; } $row->title = $row->presupuestoId; - if ($row->chatDepartmentId) { - $row->chatDisplay = $row->model->titulo; - } else { - $row->chatDisplay .= "[INTERNAL]"; - } + $row->avatar = "PRE"; $rows_new[] = $row; } elseif ($row->pedidoId) { - $row->model = $pedidoModel->find($row->pedidoId); + // $row->model = $pedidoModel->find($row->pedidoId); $row->uri = "/pedidos/edit/" . $row->pedidoId . "#accordionChatPedido"; $row->title = $row->pedidoId; - if ($row->chatDepartmentId) { - $row->chatDisplay .= "[INTERNAL]"; - } + $row->avatar = "P"; $rows_new[] = $row; } elseif ($row->facturaId) { - $row->model = $facturaModel->find($row->facturaId); + // $row->model = $facturaModel->find($row->facturaId); $row->uri = "/chat/factura/" . $row->facturaId . "#accordionChatFactura"; $row->avatar = "F"; - if ($row->chatDepartmentId) { - $row->chatDisplay .= "[INTERNAL]"; - } + $row->title = $row->facturaId; $rows_new[] = $row; } @@ -381,10 +368,6 @@ class ChatModel extends Model } public function getChatInternalNotifications() { - $presupuestoModel = model(PresupuestoModel::class); - $facturaModel = model(FacturaModel::class); - $pedidoModel = model(PedidoModel::class); - $q = $this->builder() ->select([ "chats.id as chatId", @@ -393,52 +376,41 @@ class ChatModel extends Model "chats.presupuesto_id as presupuestoId", "chats.factura_id as facturaId", "chats.title as chatDisplay", + "COUNT(chat_messages.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("chat_notifications.user_id", auth()->user()->id) ->where("chat_notifications.viewed", false) - ->where("chats.chat_department_id", null); + ->where("chats.chat_department_id", null) + ->groupBy('chats.id'); + $auth_user = auth()->user(); $rows = $q->get()->getResultObject(); $rows_new = []; foreach ($rows as $row) { - $row->unreadMessages = 0; if ($row->presupuestoId) { - $row->model = $presupuestoModel->find($row->presupuestoId); if ($auth_user->cliente_id) { $row->uri = "/presupuestocliente/edit/" . $row->presupuestoId . "#accordionChatPresupuesto"; } else { $row->uri = "/presupuestoadmin/edit/" . $row->presupuestoId . "#accordionChatPresupuesto"; } $row->title = $row->presupuestoId; - if ($row->chatDepartmentId) { - $row->chatDisplay = $row->model->titulo; - } else { - $row->chatDisplay .= "[INTERNAL]"; - } + $row->chatDisplay .= "[INTERNAL]"; $row->avatar = "PRE"; - $row->unreadMessages = $this->countUnreadMessagePresupuesto($row->presupuestoId); $rows_new[] = $row; } elseif ($row->pedidoId) { - $row->model = $pedidoModel->find($row->pedidoId); $row->uri = "/pedidos/edit/" . $row->pedidoId . "#accordionChatFactura"; $row->title = $row->pedidoId; - if ($row->chatDepartmentId) { - $row->chatDisplay .= "[INTERNAL]"; - } + $row->chatDisplay .= "[INTERNAL]"; $row->avatar = "P"; - $row->unreadMessages = $this->countUnreadMessagePedido($row->pedidoId); $rows_new[] = $row; } elseif ($row->facturaId) { - $row->model = $facturaModel->find($row->facturaId); $row->uri = "/factura/edit/" . $row->facturaId . "#accordionChatFactura"; $row->avatar = "F"; - if ($row->chatDepartmentId) { - $row->chatDisplay .= "[INTERNAL]"; - } + $row->chatDisplay .= "[INTERNAL]"; $row->title = $row->facturaId; - $row->unreadMessages = $this->countUnreadMessageFactura($row->facturaId); $rows_new[] = $row; } } @@ -585,7 +557,7 @@ class ChatModel extends Model } return $data; } - public function countUnreadMessagePresupuesto(int $presupuesto_id,int $chat_department_id): int|string + public function countUnreadMessagePresupuesto(int $presupuesto_id): int|string { return $this->builder()->select() ->join("chat_messages", "chat_messages.chat_id = chats.id", "left") @@ -593,7 +565,6 @@ class ChatModel extends Model ->where("chats.presupuesto_id", $presupuesto_id) ->where("chat_notifications.viewed", false) ->where("chat_notifications.user_id", auth()->user()->id) - ->where('chats.chat_department_id',$chat_department_id) ->countAllResults(); } public function countUnreadMessagePedido($pedido_id): int|string @@ -675,6 +646,7 @@ class ChatModel extends Model ->orderBy("chat_messages.created_at", 'ASC'); return $q->get()->getFirstRow(); } + /** * Check if all messages of a chat sent to an user have been viewed. * @@ -682,13 +654,12 @@ class ChatModel extends Model * @param integer $user_id * @return boolean True : All messages readed */ - public function isMessageChatViewed(int $chat_id, int $user_id): bool + public function isMessageChatViewed(int $chat_message_id): bool { - $q = $this->builder()->select(["chat_notifications.id"]) + $q = $this->builder()->select(["chat_notifications.id as cnId"]) ->join("chat_messages", "chat_messages.chat_id = chats.id", 'left') ->join("chat_notifications", "chat_notifications.chat_message_id = chat_messages.id", 'left') - ->where("chats.id", $chat_id) - // ->where("chat_notifications.user_id", $user_id) + ->where("chat_messages.id", $chat_message_id) ->where("chat_notifications.viewed", false); $unread_messages_count = $q->countAllResults(); if ($unread_messages_count > 0) { @@ -704,7 +675,7 @@ class ChatModel extends Model * @param integer $chat_id * @return array True : All messages readed */ - public function getUsersNotificationNotViewedFromChat(int $chat_id): array + public function getUsersNotificationNotViewedFromChat(int $chat_message_id): array { $q = $this->builder()->distinct()->select( [ @@ -717,13 +688,12 @@ class ChatModel extends Model ->join("chat_messages", "chat_messages.chat_id = chats.id", 'left') ->join("chat_notifications", "chat_notifications.chat_message_id = chat_messages.id", 'left') ->join("users", "users.id = chat_notifications.user_id", 'left') - ->where("chats.id", $chat_id) + ->where("chat_messages.id", $chat_message_id) ->where("chat_notifications.deleted_at", null) - ->where('chat_notifications.viewed',false) ->get()->getResultArray(); return $q; } - public function getUsersNotificationViewedFromChat(int $chat_id): array + public function getUsersNotificationViewedFromChat(int $chat_message_id): array { $q = $this->builder()->distinct()->select( [ @@ -736,9 +706,9 @@ class ChatModel extends Model ->join("chat_messages", "chat_messages.chat_id = chats.id", 'left') ->join("chat_notifications", "chat_notifications.chat_message_id = chat_messages.id", 'left') ->join("users", "users.id = chat_notifications.user_id", 'left') - ->where("chats.id", $chat_id) + ->where("chat_messages.id", $chat_message_id) ->where("chat_notifications.deleted_at", null) - ->where('chat_notifications.viewed',true) + ->where('chat_notifications.viewed', true) ->get()->getResultArray(); return $q; } @@ -772,78 +742,93 @@ class ChatModel extends Model $query = $this->builder() ->select([ "chats.id", + "cm.id as chatMessageId", + "u.id as userId", + "cm.message", "chats.created_at", - "cm.updated_at", - "chats.title", + " + ( + SELECT cm2.updated_at + FROM chat_messages cm2 + WHERE cm2.chat_id = chats.id + ORDER BY cm2.updated_at DESC LIMIT 1 + ) as updated_at", + "CONCAT(u.first_name,' ',u.last_name) as creator", + "CONCAT('[',chats.title,']',' ',presupuestos.titulo) as title", ]) - ->join("chat_users", "chats.id = chat_users.chat_id", "left") ->join("presupuestos", "presupuestos.id = chats.presupuesto_id", 'left') ->join("chat_messages cm", "chats.id = cm.chat_id", "left") - ->where("chats.presupuesto_id is NOT NULL", NULL, FALSE) - ->where("cm.updated_at = ( - SELECT cm2.updated_at - FROM chat_messages cm2 - WHERE cm2.chat_id = chats.id - ORDER BY cm2.updated_at DESC LIMIT 1 - )"); + ->join("users u", "u.id = cm.sender_id", 'left') + ->where("chats.presupuesto_id is NOT NULL", NULL, FALSE); + if (auth()->user()->inGroup("admin") == false) { $query->where('presupuestos.cliente_id', auth()->user()->cliente_id) - ->where("chat_department_id is NOT NULL", NULL, FALSE); + ->where("chats.chat_department_id is NOT NULL", NULL, FALSE); } - return $query; + return $query->groupBy('chatMessageId'); } public function getQueryDatatableMessagePedido(int $user_id): BaseBuilder { $query = $this->builder() ->select([ "chats.id", + "cm.id as chatMessageId", + "u.id as userId", + "cm.message", "chats.created_at", - "cm.updated_at", - "chats.title", - ]) - ->join("chat_users", "chat_users.chat_id = chats.id", "left") - ->join("pedidos_linea", "pedidos_linea.pedido_id = chats.pedido_id", 'left') - ->join("chat_messages cm", "chats.id = cm.chat_id", "left") - ->join("presupuestos", "presupuestos.id = pedidos_linea.presupuesto_id", 'left') - ->where("chats.pedido_id is NOT NULL", NULL, FALSE) - ->where("cm.updated_at = ( + " + ( SELECT cm2.updated_at FROM chat_messages cm2 WHERE cm2.chat_id = chats.id ORDER BY cm2.updated_at DESC LIMIT 1 - )"); + ) as updated_at", + "CONCAT(u.first_name,' ',u.last_name) as creator", + "CONCAT('[',chats.title,']',' ',presupuestos.titulo) as title", + ]) + ->join("pedidos_linea", "pedidos_linea.pedido_id = chats.pedido_id", 'left') + ->join("chat_messages cm", "chats.id = cm.chat_id", "left") + ->join("users u", "u.id = cm.sender_id", 'left') + ->join("presupuestos", "presupuestos.id = pedidos_linea.presupuesto_id", 'left') + ->where("chats.pedido_id is NOT NULL", NULL, FALSE); + if (auth()->user()->inGroup("admin") == false) { $query->where('presupuestos.cliente_id', auth()->user()->cliente_id) - ->where("chat_department_id is NOT NULL", NULL, FALSE); + ->where("chats.chat_department_id is NOT NULL", NULL, FALSE); } - return $query; + return $query->groupBy('chatMessageId'); } public function getQueryDatatableMessageFactura(int $user_id): BaseBuilder { $query = $this->builder() ->select([ "chats.id", + "cm.id as chatMessageId", + "u.id as userId", + "cm.message", "chats.created_at", - "cm.updated_at", - "chats.title", - ]) - ->join("chat_users", "chat_users.chat_id = chats.id", "left") - ->join("chat_messages cm", "chats.id = cm.chat_id", "left") - ->join("facturas", "facturas.id = chats.factura_id", "left") - ->where("chats.factura_id is NOT NULL", NULL, FALSE) - ->where("cm.updated_at = ( + " + ( SELECT cm2.updated_at FROM chat_messages cm2 WHERE cm2.chat_id = chats.id ORDER BY cm2.updated_at DESC LIMIT 1 - )"); + ) as updated_at", + "CONCAT(u.first_name,' ',u.last_name) as creator", + "chats.title", + ]) + ->join("chat_messages cm", "chats.id = cm.chat_id", "left") + ->join("users u", "u.id = cm.sender_id", 'left') + ->join("facturas", "facturas.id = chats.factura_id", "left") + ->where("chats.factura_id is NOT NULL", NULL, FALSE); + if (auth()->user()->inGroup("admin") == false) { if (auth()->user()->inGroup("admin") == false) { $query->where('facturas.cliente_id', auth()->user()->cliente_id) - ->where("chat_department_id is NOT NULL", NULL, FALSE); + ->where("chats.chat_department_id is NOT NULL", NULL, FALSE); } } - return $query; + return $query->groupBy('chatMessageId'); } public function createNewDirectChat(string $title, string $message, array $users) { @@ -923,12 +908,12 @@ class ChatModel extends Model ->select("chat_notifications.id as notificationId") ->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',$user_id) + ->where('chat_notifications.user_id', $user_id) ->where('chat_messages.chat_id', $chat_id) ->get()->getResultObject(); $chat_messages_ids = array_map(fn($q) => $q->notificationId, $query); $chatNotificationModel = model(ChatNotification::class); - if($chat_messages_ids){ + if ($chat_messages_ids) { $chatNotificationModel->setNotificationsAsViewed($chat_messages_ids); } } @@ -945,12 +930,12 @@ class ChatModel extends Model ->select("chat_notifications.id as notificationId") ->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',$user_id) + ->where('chat_notifications.user_id', $user_id) ->where('chat_messages.chat_id', $chat_id) ->get()->getResultObject(); $chat_messages_ids = array_map(fn($q) => $q->notificationId, $query); $chatNotificationModel = model(ChatNotification::class); - if($chat_messages_ids){ + if ($chat_messages_ids) { $chatNotificationModel->setNotificationsAsUnViewed($chat_messages_ids); } } diff --git a/ci4/app/Models/ChatNotification.php b/ci4/app/Models/ChatNotification.php index 7d8824d4..aa1e0a28 100644 --- a/ci4/app/Models/ChatNotification.php +++ b/ci4/app/Models/ChatNotification.php @@ -2,6 +2,7 @@ namespace App\Models; +use App\Entities\Chat\ChatNotificationEntity; use CodeIgniter\Model; class ChatNotification extends Model @@ -9,7 +10,7 @@ class ChatNotification extends Model protected $table = 'chat_notifications'; protected $primaryKey = 'id'; protected $useAutoIncrement = true; - protected $returnType = 'array'; + protected $returnType = ChatNotificationEntity::class; protected $useSoftDeletes = false; protected $protectFields = true; protected $allowedFields = [ diff --git a/ci4/app/Models/ChatUser.php b/ci4/app/Models/ChatUser.php index f51f989f..b6355a53 100644 --- a/ci4/app/Models/ChatUser.php +++ b/ci4/app/Models/ChatUser.php @@ -2,6 +2,7 @@ namespace App\Models; +use App\Entities\Chat\ChatUserEntity; use CodeIgniter\Model; class ChatUser extends Model @@ -9,7 +10,7 @@ class ChatUser extends Model protected $table = 'chat_users'; protected $primaryKey = 'id'; protected $useAutoIncrement = true; - protected $returnType = 'array'; + protected $returnType = ChatUserEntity::class; protected $useSoftDeletes = true; protected $protectFields = true; protected $allowedFields = [ diff --git a/ci4/app/Services/ChatService.php b/ci4/app/Services/ChatService.php new file mode 100644 index 00000000..66277625 --- /dev/null +++ b/ci4/app/Services/ChatService.php @@ -0,0 +1,176 @@ + "presupuesto_id", + "pedido" => "pedido_id", + "factura" => "factura_id", + ]; + protected array $modelClassMap; + public function __construct() + { + $this->chatModel = model(ChatModel::class); + $this->chatMessageModel = model(ChatMessageModel::class); + $this->chatNotificationModel = model(ChatNotification::class); + $this->chatDepartmentUserModel = model(ChatDeparmentUserModel::class); + $this->chatUserModel = model(ChatUser::class); + $this->presupuestoModel = model(PresupuestoModel::class); + $this->chatDepartmentModel = model(ChatDeparmentModel::class); + $this->configVariables = model(ConfigVariableModel::class); + } + public function setChat($chatEntity): self + { + $this->chatEntity = $chatEntity; + return $this; + } + public function storeChatMessage(string $chatDepartmentId, string $model, int $modelId, array $data): ?ChatMessageEntity + { + $this->chatEntity = $this->chatModel->where('chat_department_id', $chatDepartmentId)->where($this->modelFkMap[$model], $modelId)->first(); + if ($this->chatEntity == null) { + $chatId = $this->createChat($chatDepartmentId, $model, $modelId); + $this->chatEntity = $this->chatModel->find($chatId); + } + if ($data["client"]) { + $cliente_in_department = $this->chatDepartmentUserModel + ->where('chat_department_id', $chatDepartmentId) + ->where('user_id', $data['client']) + ->where($this->modelFkMap[$model], $modelId) + ->first(); + if ($cliente_in_department == null) { + $this->chatDepartmentUserModel->insert(['chat_department_id' => $chatDepartmentId, 'user_id' => $data['client'], $this->modelFkMap[$model] => $modelId]); + } + } + $userAdminDepartment = $this->chatDepartmentUserModel + ->where('chat_department_id', $data["chat_department_id"]) + ->where('user_id', auth()->user()->id) + ->where("pedido_id", null) + ->where("factura_id", null) + ->where("presupuesto_id", null) + ->first(); + $userAlreadyInDepartment = $this->chatDepartmentUserModel + ->where('chat_department_id', $data["chat_department_id"]) + ->where('user_id', auth()->user()->id) + ->where($this->modelFkMap[$model], $modelId) + ->first(); + if ($userAdminDepartment == null && $userAlreadyInDepartment == null) { + $this->chatDepartmentUserModel->insert(['chat_department_id' => $data["chat_department_id"], $this->modelFkMap[$model] => $modelId, 'user_id' => auth()->user()->id]); + } + $chat_message_id = $this->chatMessageModel->insert(["chat_id" => $this->chatEntity->id, "sender_id" => auth()->user()->id, "message" => $data["message"]]); + $chatMessageEntity = $this->chatMessageModel->find($chat_message_id); + return $chatMessageEntity; + } + public function createChat(int $chatDepartmentId, string $model, int $modelId): bool|int|string + { + $r = false; + switch ($model) { + case 'presupuesto': + $r = $this->chatModel->createChatPresupuesto($chatDepartmentId, $modelId); + break; + case 'pedido': + $r = $this->chatModel->createChatPedido($chatDepartmentId, $modelId); + break; + case 'factura': + $r = $this->chatModel->createChatFactura($chatDepartmentId, $modelId); + break; + default: + break; + } + return $r; + } + + public function getChatDepartments(string $model, int $modelId): array + { + $chatDepartments = $this->chatDepartmentModel->getModelChatDepartments($this->modelFkMap[$model], $modelId); + $departmentWithChat = array_map(fn($q) => $q["name"], $chatDepartments); + if(count($departmentWithChat) > 0){ + $departmentWithoutChat = $this->chatDepartmentModel->whereNotIn('name', $departmentWithChat)->findAll(); + }else{ + $departmentWithoutChat = $this->chatDepartmentModel->findAll(); + } + foreach ($departmentWithoutChat as $value) { + $d = []; + $d["id"] = $value->id; + $d["name"] = $value->name; + $d["display"] = $value->display; + $d["countMessages"] = "0"; + $chatDepartments[] = $d; + } + return $chatDepartments; + } + + public function storeHebra(string $model, int $modelId, array $data): bool + { + $auth_user = auth()->user(); + $chatId = $this->chatModel->insert([$this->modelFkMap[$model] => $modelId, 'title' => $data['title']]); + + if (isset($data["users"])) { + $data["users"][] = $auth_user->id; + $chatUserData = array_map(fn($x) => ["user_id" => $x, "chat_id" => $chatId], $data["users"]); + $this->chatUserModel->insertBatch($chatUserData); + } + $this->chatMessageModel->insert( + [ + 'chat_id' => $chatId, + 'message' => $data['message'], + 'sender_id' => $auth_user->id + ] + ); + return true; + } + public function getHebras(string $model, int $modelId): array + { + $chats = $this->chatModel->where('chat_department_id', null) + ->where($this->modelFkMap[$model], $modelId) + ->findAll(); + foreach ($chats as $c) { + $this->chatModel->setAsViewedChatUserNotifications($c->id,auth()->user()->id); + } + $chatWithHebraData = array_map(fn(ChatEntity $c) => $c->withHebra(), $chats); + return $chatWithHebraData ?? []; + } + public function getAuthUserNotifications(): array + { + $departmentNotifications = $this->chatModel->getChatDepartmentNotifications(); + $internalNotifications = $this->chatModel->getChatInternalNotifications(); + $totalMessages = 0; + $countNotificiationDepartments = array_map(fn($n) => $n->unreadMessages,$departmentNotifications); + $countNotificationInternal = array_map(fn($n) => $n->unreadMessages,$internalNotifications); + $totalMessages = array_sum($countNotificiationDepartments) + array_sum($countNotificationInternal); + + return [ + "departmentNotifications" => $departmentNotifications, + "internalNotifications" => $internalNotifications, + "totalMessages" => $totalMessages + ]; + } +} diff --git a/ci4/app/Views/themes/vuexy/components/tables/messages_table.php b/ci4/app/Views/themes/vuexy/components/tables/messages_table.php index 22456941..17316fda 100644 --- a/ci4/app/Views/themes/vuexy/components/tables/messages_table.php +++ b/ci4/app/Views/themes/vuexy/components/tables/messages_table.php @@ -4,10 +4,20 @@ + + + + + + + + + + diff --git a/ci4/app/Views/themes/vuexy/main/defaultlayout.php b/ci4/app/Views/themes/vuexy/main/defaultlayout.php index adc7e9e1..63230311 100644 --- a/ci4/app/Views/themes/vuexy/main/defaultlayout.php +++ b/ci4/app/Views/themes/vuexy/main/defaultlayout.php @@ -250,7 +250,7 @@ $picture = "/assets/img/default-user.png";
    - +