From 093aa42e67ac97505209d5f99ef3d725ca895672 Mon Sep 17 00:00:00 2001 From: amazuecos Date: Thu, 28 Nov 2024 09:14:59 +0100 Subject: [PATCH 1/3] messages view --- ci4/app/Config/Routes.php | 15 ++ ci4/app/Controllers/Chat/ChatController.php | 85 ++++++++- ci4/app/Database/Seeds/MessageSeeder.php | 52 ++++++ ci4/app/Language/es/Chat.php | 14 +- ci4/app/Models/Chat/ChatMessageModel.php | 24 ++- ci4/app/Models/Chat/ChatModel.php | 124 ++++++++++++- ci4/app/Models/ChatNotification.php | 1 + ci4/app/Models/ChatUser.php | 8 + ci4/app/Models/UserModel.php | 1 - .../themes/vuexy/components/alerts/alert.php | 11 ++ .../themes/vuexy/components/chat_direct.php | 154 ++++++++++++++++ .../modals/modalAddNewChatParticipant.php | 31 ++++ .../modals/modalNewDirectMessage.php | 41 +++++ .../vuexy/form/mensajes/mensajesView.php | 66 ++++++- .../vuexy/form/mensajes/messageChat.php | 27 +++ .../js/safekat/components/alerts/alert.js | 53 ++++++ httpdocs/assets/js/safekat/components/chat.js | 170 +++++++++++++++++- .../datatables/MessagesDatatable.js | 52 ++++++ .../assets/js/safekat/components/select2.js | 3 +- .../pages/configuracion/messages/index.js | 5 + .../configuracion/messages/messagePage.js | 82 +++++++++ .../pages/messages/directMessagePage.js | 9 + .../validation/newDirectMessageValidation.js | 21 +++ 23 files changed, 1030 insertions(+), 19 deletions(-) create mode 100644 ci4/app/Database/Seeds/MessageSeeder.php create mode 100644 ci4/app/Views/themes/vuexy/components/alerts/alert.php create mode 100644 ci4/app/Views/themes/vuexy/components/chat_direct.php create mode 100644 ci4/app/Views/themes/vuexy/components/modals/modalAddNewChatParticipant.php create mode 100644 ci4/app/Views/themes/vuexy/components/modals/modalNewDirectMessage.php create mode 100644 ci4/app/Views/themes/vuexy/form/mensajes/messageChat.php create mode 100644 httpdocs/assets/js/safekat/components/alerts/alert.js create mode 100644 httpdocs/assets/js/safekat/components/datatables/MessagesDatatable.js create mode 100644 httpdocs/assets/js/safekat/pages/configuracion/messages/index.js create mode 100644 httpdocs/assets/js/safekat/pages/configuracion/messages/messagePage.js create mode 100644 httpdocs/assets/js/safekat/pages/messages/directMessagePage.js create mode 100644 httpdocs/assets/js/safekat/validation/newDirectMessageValidation.js diff --git a/ci4/app/Config/Routes.php b/ci4/app/Config/Routes.php index 44581391..1d643167 100644 --- a/ci4/app/Config/Routes.php +++ b/ci4/app/Config/Routes.php @@ -761,7 +761,22 @@ $routes->group('mensajes', ['namespace' => 'App\Controllers\Mensajeria'], functi $routes->post('datatable', 'TarifaAcabados::datatable', ['as' => 'tarifaAcabadoDT']);*/ }); }); +$routes->group('messages', ['namespace' => 'App\Controllers\Chat'], function ($routes) { + $routes->get('datatable', 'ChatController::datatable_messages', ['as' => 'getDatatableMessages']); + $routes->post('direct', 'ChatController::store_new_direct_message', ['as' => 'storeNewDirectMessage']); + +}); $routes->group('chat', ['namespace' => 'App\Controllers\Chat'], function ($routes) { + + $routes->get('direct/(:num)', 'ChatController::get_chat_direct_view/$1', ['as' => 'getChatDirectView']); + $routes->get('direct/conversation/(:num)', 'ChatController::get_chat_direct/$1', ['as' => 'getChatDirect']); + $routes->get('direct/users/select/(:num)', 'ChatController::get_chat_direct_select_users/$1', ['as' => 'getChatDirectSelectUsers']); + $routes->get('direct/users/(:num)', 'ChatController::get_chat_direct_users', ['as' => 'getChatDirectUsers']); + $routes->post('direct/users/(:num)', 'ChatController::store_chat_direct_users/$1', ['as' => 'storeChatDirectUsers']); + $routes->get('direct/messages/(:num)', 'ChatController::get_chat_direct_messages/$1', ['as' => 'getChatDirectMessages']); + $routes->post('direct/messages/(:num)', 'ChatController::store_chat_direct_message/$1', ['as' => 'storeChatDirectMessages']); + + $routes->get('departments', 'ChatController::get_chat_departments', ['as' => 'getChatDepartments']); $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']); diff --git a/ci4/app/Controllers/Chat/ChatController.php b/ci4/app/Controllers/Chat/ChatController.php index 93c5bb58..969e7713 100644 --- a/ci4/app/Controllers/Chat/ChatController.php +++ b/ci4/app/Controllers/Chat/ChatController.php @@ -11,10 +11,13 @@ use App\Models\ChatNotification; use App\Models\ChatUser; use App\Models\Clientes\ClienteModel; use App\Models\Usuarios\UserModel; +use App\Services\MessageService; use CodeIgniter\HTTP\ResponseInterface; use CodeIgniter\HTTP\RequestInterface; use CodeIgniter\Log\Logger; use Psr\Log\LoggerInterface; +use Hermawan\DataTables\DataTable; +use CodeIgniter\I18n\Time; class ChatController extends BaseController { @@ -27,7 +30,7 @@ class ChatController extends BaseController protected ChatUser $chatUserModel; protected ChatNotification $chatNotificationModel; - + protected static $viewPath = 'themes/vuexy/form/mensajes/'; public function initController( @@ -108,6 +111,16 @@ class ChatController extends BaseController $data["chat"] = $chat; return $this->response->setJSON($data); } + public function get_chat_direct_view($chat_id){ + $chat = $this->chatModel->find($chat_id); + $this->viewData['breadcrumb'] = [ + ['title' => lang("Chat.chat"), 'route' => route_to("mensajeriaView"), 'active' => false], + ['title' => $chat->title, 'route' => 'javascript:void(0);', 'active' => true] + ]; + $this->viewData["chatId"] = $chat_id; + + return view(static::$viewPath . 'messageChat', $this->viewData); + } public function get_chat(int $chat_id) { @@ -428,5 +441,75 @@ class ChatController extends BaseController return $this->response->setJSON($data); } + public function datatable_messages() + { + $query = $this->chatModel->getQueryDatatable(); + $auth_user_id = auth()->user()->id; + return DataTable::of($query) + ->edit('created_at',fn($q) => Time::createFromFormat('Y-m-d H:i:s',$q->created_at)->format("d/m/Y H:i")) + ->edit('updated_at',fn($q) => 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) => $q->id) + ->toJson(true); + } + public function store_new_direct_message() + { + $bodyData = $this->request->getPost(); + $rules = [ + "title" => "required|string", + "message" => "required|string", + "users" => "required", + ]; + if(!$this->validate($rules)){ + return $this->response->setStatusCode(400)->setJSON([ + 'message' => lang('App.global_alert_save_error'), + 'status' => 'error', + 'errors' => $this->validator->getErrors(), + ]); + } + $this->chatModel->createNewDirectChat(...$bodyData); + return $this->response->setJSON(["message" => lang("Chat.new_message_ok"),"status" => true]); + + } + public function get_chat_direct($chat_id){ + $chatData = $this->chatModel->getChatDirect($chat_id); + return $this->response->setJSON($chatData); + } + public function get_chat_direct_select_users($chat_id){ + $chat_users_id = $this->chatUserModel->getChatUserArrayId($chat_id); + + $query = $this->userModel->builder()->select( + [ + "id", + "CONCAT(first_name,' ',last_name,'(',username,')') as name" + ] + )->where("cliente_id", null) + ->where("deleted_at", null) + ->whereNotIn("id",$chat_users_id); + if ($this->request->getGet("q")) { + $query->groupStart() + ->orLike("users.username", $this->request->getGet("q")) + ->orLike("CONCAT(first_name,' ',last_name)", $this->request->getGet("q")) + ->groupEnd(); + } + + return $this->response->setJSON($query->get()->getResultObject()); + } + public function store_chat_direct_users($chat_id){ + $bodyData = $this->request->getPost(); + $chat_users = array_map(fn($q) => ["chat_id" => $chat_id,"user_id" => $q],$bodyData["users"]); + $this->chatUserModel->insertBatch($chat_users); + return $this->response->setJSON(["message" => "ok","status" => true]); + } + public function store_chat_direct_message(int $chat_id){ + $bodyData = $this->request->getPost(); + $bodyData["sender_id"] = auth()->user()->id; + $chat_message_id = $this->chatMessageModel->insert($bodyData); + $message = $this->chatMessageModel->get_chat_message($chat_message_id); + return $this->response->setJSON($message); + + + } } diff --git a/ci4/app/Database/Seeds/MessageSeeder.php b/ci4/app/Database/Seeds/MessageSeeder.php new file mode 100644 index 00000000..d8d450ca --- /dev/null +++ b/ci4/app/Database/Seeds/MessageSeeder.php @@ -0,0 +1,52 @@ + "Message Test", + "messages" => [ + [ + "sender_id" => 1, + "receiver_id" => 127, + ], + [ + "sender_id" => 127, + "receiver_id" => 1, + ] + ] + ]; + $chatModel = model(ChatModel::class); + $chatMessageModel = model(ChatMessageModel::class); + $chatNotificationModel = model(ChatNotification::class); + $userModel = model(UserModel::class); + foreach (range(1,100) as $key => $value) { + $chat_id = $chatModel->insert(["title" => $data["title"]." ".$value]); + foreach ($data["messages"] as $key => $value) { + $first_name = $userModel->find($value["receiver_id"])?->first_name; + $chat_message_id = $chatMessageModel->insert([ + "chat_id" => $chat_id, + "sender_id" => $value["sender_id"], + "receiver_id" => $value["receiver_id"], + "message" => "Hola"." ".$first_name + ]); + $chatNotificationModel->insert([ + "chat_message_id" => $chat_message_id, + "user_id" => $value["receiver_id"] + ]); + } + } + } +} diff --git a/ci4/app/Language/es/Chat.php b/ci4/app/Language/es/Chat.php index ea5eaac2..1a0efc20 100644 --- a/ci4/app/Language/es/Chat.php +++ b/ci4/app/Language/es/Chat.php @@ -10,5 +10,17 @@ return [ "new_receivers" => "Nuevos participantes", "btn_send" => "Enviar", "btn_send_update" => "Enviar" - ] + ], + "datatable_messages" => [ + "created_at" => "Fecha creación", + "updated_at" => "Fecha actualización", + "title" => "Título", + "creator" => "Creador", + "viewed" => "Leído", + + ], + "new_message_ok" => "Mensaje enviado correctamente", + "participants" => "Participantes", + "write_message_placeholder" => "Escriba aquí su mensaje..." + ]; \ No newline at end of file diff --git a/ci4/app/Models/Chat/ChatMessageModel.php b/ci4/app/Models/Chat/ChatMessageModel.php index ce3b2b0a..e0ee9a20 100644 --- a/ci4/app/Models/Chat/ChatMessageModel.php +++ b/ci4/app/Models/Chat/ChatMessageModel.php @@ -5,14 +5,15 @@ namespace App\Models\Chat; use App\Models\ChatNotification; use App\Models\Usuarios\UserModel; use CodeIgniter\Model; +use CodeIgniter\Database\BaseBuilder; class ChatMessageModel extends Model { protected $table = 'chat_messages'; protected $primaryKey = 'id'; protected $useAutoIncrement = true; - protected $returnType = 'array'; - protected $useSoftDeletes = false; + protected $returnType = 'object'; + protected $useSoftDeletes = true; protected $protectFields = true; protected $allowedFields = [ "message", @@ -29,7 +30,7 @@ class ChatMessageModel extends Model protected array $castHandlers = []; // Dates - protected $useTimestamps = false; + protected $useTimestamps = true; protected $dateFormat = 'datetime'; protected $createdField = 'created_at'; protected $updatedField = 'updated_at'; @@ -72,6 +73,23 @@ class ChatMessageModel extends Model } return $messages; } + public function get_chat_message(int $chat_message_id): object + { + $user = model(UserModel::class); + $auth_user = auth()->user(); + $message = $this->find($chat_message_id); + $message->pos = $auth_user->id == $message->sender_id ? "right" : "left"; + 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; + $message->sender_last_name = $sender_user->last_name; + } + return $message; + } public function get_chat_contact_messages(int $receiver_id): array { $conversationArray = []; diff --git a/ci4/app/Models/Chat/ChatModel.php b/ci4/app/Models/Chat/ChatModel.php index 59410d2f..d0b3b5bd 100644 --- a/ci4/app/Models/Chat/ChatModel.php +++ b/ci4/app/Models/Chat/ChatModel.php @@ -3,12 +3,13 @@ namespace App\Models\Chat; use App\Models\ChatNotification; +use App\Models\ChatUser; use App\Models\Facturas\FacturaModel; use App\Models\Pedidos\PedidoModel; use App\Models\Presupuestos\PresupuestoModel; use App\Models\Usuarios\UserModel; use CodeIgniter\Model; -use stdClass; +use CodeIgniter\Database\BaseBuilder; class ChatModel extends Model { @@ -623,5 +624,126 @@ class ChatModel extends Model return $q; } + public function getChatFirstUser(int $chat_id) : object + { + $q = $this->builder()->select(["users.id", + "CONCAT(users.first_name,' ',users.last_name) as userFullName", + ]) + ->join("chat_messages","chat_messages.chat_id = chats.id",'left') + ->join("users","users.id = chat_messages.sender_id","left") + ->where("chats.id",$chat_id) + ->where("chat_messages.deleted_at",null) + ->orderBy("chat_messages.created_at",'ASC'); + return $q->get()->getFirstRow(); + } + /** + * Check if all messages of a chat sended to an user have been viewed. + * + * @param integer $chat_id + * @param integer $user_id + * @return boolean True : All messages readed + */ + public function isMessageChatViewed(int $chat_id, int $user_id) : bool + { + $q = $this->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.id",$chat_id) + ->where("chat_notifications.user_id",$user_id) + ->where("chat_notifications.viewed",false); + $unread_messages_count = $q->countAllResults(); + if($unread_messages_count > 0){ + $result = false; + }else{ + $result = true; + } + return $result; + } + public function getQueryDatatable(): BaseBuilder + { + $query = $this->builder() + ->select([ + "chats.id", + "chats.created_at", + "chats.updated_at", + "chats.title", + ]) + ->where("chat_department_id",null) + ->where("pedido_id",null) + ->where("presupuesto_id",null) + ->where("factura_id",null) + ->where("title is NOT NULL",NULL,FALSE) + ->orderBy("created_at", "DESC"); + return $query; + } + public function createNewDirectChat(string $title,string $message,array $users) + { + $chatMessageModel = model(ChatMessageModel::class); + $chatNotificationModel = model(ChatNotification::class); + $chatUserModel = model(ChatUser::class); + $auth_user_id = auth()->user()->id; + $chat_id = $this->insert(["title" => $title]); + $chat_message_id = $chatMessageModel->insert([ + "chat_id" => $chat_id, + "sender_id" => $auth_user_id, + "receiver_id" => null, + "message" => $message + ]); + $chatUserModel->insert(["chat_id" => $chat_id,"user_id" => $auth_user_id]); + foreach ($users as $key => $user_id) { + $chatUserModel->insert(["chat_id" => $chat_id,"user_id" => $user_id]); + $chatNotificationModel->insert(["chat_message_id" => $chat_message_id,"user_id" => $user_id]); + } + } + /** + * Obtain users and messages from `chat_id` + * + * @param integer $chat_id + * @return array + * [ + * "chat" => object, + * "messages" => array , + * "users" => array + * ] + */ + public function getChatDirect(int $chat_id) : array + { + $auth_user = auth()->user()->id; + $chat = $this->find($chat_id); + $query = $this->builder()->select([ + "users.*", + ]) + ->join("chat_users","chat_users.chat_id = chats.id") + ->join("users","users.id = chat_users.user_id","left") + ->where("chats.id",$chat_id); + $users = $query->get()->getResultObject(); + $query = $this->builder()->select([ + "chat_messages.*", + "users.first_name as sender_first_name", + "users.last_name as sender_last_name", + + ]) + ->join("chat_messages","chat_messages.chat_id = chats.id","left") + ->join("users","chat_messages.sender_id = users.id","left") + ->where("chats.id",$chat_id); + + $messages = $query->get()->getResultObject(); + $validatedMessages = []; + foreach ($messages as $key => $message) { + if($auth_user == $message->sender_id){ + $message->pos = 'right'; + $validatedMessages[] = $message; + }else{ + $message->pos = 'left'; + $validatedMessages[] = $message; + } + } + $data = [ + "chat" => $chat, + "users" => $users, + "messages" => $validatedMessages + ]; + return $data; + } } diff --git a/ci4/app/Models/ChatNotification.php b/ci4/app/Models/ChatNotification.php index fdbc6e2b..85f774d2 100644 --- a/ci4/app/Models/ChatNotification.php +++ b/ci4/app/Models/ChatNotification.php @@ -47,4 +47,5 @@ class ChatNotification extends Model protected $afterFind = []; protected $beforeDelete = []; protected $afterDelete = []; + } diff --git a/ci4/app/Models/ChatUser.php b/ci4/app/Models/ChatUser.php index 9e92163c..4880c6e5 100644 --- a/ci4/app/Models/ChatUser.php +++ b/ci4/app/Models/ChatUser.php @@ -46,4 +46,12 @@ class ChatUser extends Model protected $afterFind = []; protected $beforeDelete = []; protected $afterDelete = []; + public function getChatUserArrayId(int $chat_id) : array + { + $queryResult = $this->builder() + ->select(['chat_users.user_id']) + ->where("chat_users.chat_id",$chat_id) + ->get()->getResultObject(); + return array_map(fn($q) => $q->user_id,$queryResult); + } } diff --git a/ci4/app/Models/UserModel.php b/ci4/app/Models/UserModel.php index 5507d64b..3c2fe960 100644 --- a/ci4/app/Models/UserModel.php +++ b/ci4/app/Models/UserModel.php @@ -91,5 +91,4 @@ class UserModel extends ShieldUserModel return $result === null; } - } diff --git a/ci4/app/Views/themes/vuexy/components/alerts/alert.php b/ci4/app/Views/themes/vuexy/components/alerts/alert.php new file mode 100644 index 00000000..4741e898 --- /dev/null +++ b/ci4/app/Views/themes/vuexy/components/alerts/alert.php @@ -0,0 +1,11 @@ + \ No newline at end of file diff --git a/ci4/app/Views/themes/vuexy/components/chat_direct.php b/ci4/app/Views/themes/vuexy/components/chat_direct.php new file mode 100644 index 00000000..dad29f75 --- /dev/null +++ b/ci4/app/Views/themes/vuexy/components/chat_direct.php @@ -0,0 +1,154 @@ +
+
+ +
+ + + +
+ + + +
+ + + +
+
+
+
+
+ +

+
+
+ +
+
+ +
+
+
+
+
+
+
+
+
+
+
+
+
    + + +
+
+ + +
+ + +
+
+
+
+ +
+ + +section('css') ?> + + +endSection() ?> + + + +section("additionalExternalJs") ?> + + +endSection() ?> \ No newline at end of file diff --git a/ci4/app/Views/themes/vuexy/components/modals/modalAddNewChatParticipant.php b/ci4/app/Views/themes/vuexy/components/modals/modalAddNewChatParticipant.php new file mode 100644 index 00000000..36e5c762 --- /dev/null +++ b/ci4/app/Views/themes/vuexy/components/modals/modalAddNewChatParticipant.php @@ -0,0 +1,31 @@ + + \ No newline at end of file diff --git a/ci4/app/Views/themes/vuexy/components/modals/modalNewDirectMessage.php b/ci4/app/Views/themes/vuexy/components/modals/modalNewDirectMessage.php new file mode 100644 index 00000000..b0f416c5 --- /dev/null +++ b/ci4/app/Views/themes/vuexy/components/modals/modalNewDirectMessage.php @@ -0,0 +1,41 @@ + + \ No newline at end of file diff --git a/ci4/app/Views/themes/vuexy/form/mensajes/mensajesView.php b/ci4/app/Views/themes/vuexy/form/mensajes/mensajesView.php index 594efa39..db220a0c 100644 --- a/ci4/app/Views/themes/vuexy/form/mensajes/mensajesView.php +++ b/ci4/app/Views/themes/vuexy/form/mensajes/mensajesView.php @@ -1,10 +1,68 @@ -include("themes/_commonPartialsBs/select2bs5") ?> -include("themes/_commonPartialsBs/datatables") ?> +include('themes/_commonPartialsBs/select2bs5') ?> +include('themes/_commonPartialsBs/datatables') ?> +include('themes/_commonPartialsBs/_confirm2delete') ?> extend('themes/vuexy/main/defaultlayout') ?> + section('content'); ?> -
- null]) ?> +
+
+ +
+
+

+
+ +
+ + +
+
+ +
+
+ + + + + + + + + + + + + + +
+
+ + + +
+ +
+
+ + + +endSection() ?> +section('css') ?> + + + + + +endSection() ?> +section("additionalExternalJs") ?> + + + + endSection() ?> \ No newline at end of file diff --git a/ci4/app/Views/themes/vuexy/form/mensajes/messageChat.php b/ci4/app/Views/themes/vuexy/form/mensajes/messageChat.php new file mode 100644 index 00000000..44dc5a48 --- /dev/null +++ b/ci4/app/Views/themes/vuexy/form/mensajes/messageChat.php @@ -0,0 +1,27 @@ +include('themes/_commonPartialsBs/select2bs5') ?> +include('themes/_commonPartialsBs/datatables') ?> +include('themes/_commonPartialsBs/_confirm2delete') ?> +extend('themes/vuexy/main/defaultlayout') ?> + + +section('content'); ?> + +
+ $chatId]) ?> +
+ + +endSection() ?> +section('css') ?> + + + + + +endSection() ?> +section("additionalExternalJs") ?> + + + + +endSection() ?> \ No newline at end of file diff --git a/httpdocs/assets/js/safekat/components/alerts/alert.js b/httpdocs/assets/js/safekat/components/alerts/alert.js new file mode 100644 index 00000000..ace6fde9 --- /dev/null +++ b/httpdocs/assets/js/safekat/components/alerts/alert.js @@ -0,0 +1,53 @@ + +class Alert { + constructor(domItem) { + this.item = domItem + this.headingTitle = this.item.find(".alert-heading") + this.body = this.item.find(".alert-body") + this.icon = this.item.find(".icon-alert") + this.iconSuccess = "ti-circle-check" + this.iconError = "ti-exclamation-mark" + + + + } + setIcon(iconClass){ + this.icon.removeClass(this.iconSuccess) + this.icon.removeClass(this.iconError) + this.icon.addClass(iconClass) + } + setAsError() { + this.item.removeClass("alert-success") + this.item.addClass("alert-danger") + this.setIcon(this.iconError) + + } + setAsSuccess() { + this.item.removeClass("alert-danger") + this.item.addClass("alert-success") + this.setIcon(this.iconSuccess) + } + setAsWarning() { + this.item.removeClass("alert-success") + this.item.addClass("alert-warning") + } + setAsInfo() { + this.item.removeClass("alert-*") + this.item.addClass("alert-info") + } + show() { + this.item.removeClass("d-none") + } + hide() { + this.item.addClass("d-none") + } + setHeadingTitle(title) { + this.headingTitle.text(title) + } + setContent(content) { + this.body.append(content) + } + setErrors() { } +} + +export default Alert; \ No newline at end of file diff --git a/httpdocs/assets/js/safekat/components/chat.js b/httpdocs/assets/js/safekat/components/chat.js index 79003692..844112e6 100644 --- a/httpdocs/assets/js/safekat/components/chat.js +++ b/httpdocs/assets/js/safekat/components/chat.js @@ -1,4 +1,6 @@ import Ajax from '../components/ajax.js' +import Modal from './modal.js' +import ClassSelect from './select2.js' @@ -66,12 +68,38 @@ class Chat { }); } } + initDirectMessage() { + this.chatType = "direct" + this.modalNewParticipant = new Modal(this.domItem.find("#modalAddNewChatParticipant")) + this.selectPlaceholder = { + id: '0', + text: "Seleccione un usuario" + } + this.btnDirectMessageSubmit = this.domItem.find("#send-msg-btn-direct") + this.btnDirectMessageSubmit.on("click", this._handleStoreChatDirectMessage.bind(this)) + this.selectParticipants = new ClassSelect(this.modalNewParticipant.item.find("#select-users"), `/chat/direct/users/select/${this.modelId}`, this.selectPlaceholder, true) + + this.btnAddParticipant = this.domItem.find("#btn-chat-add-participant") + this.btnAddParticipantSubmit = this.domItem.find("#btn-chat-add-participant-submit") + this.btnAddParticipantSubmit.on("click", this._handleStoreChatDirectUsers.bind(this)) + this.btnAddParticipant.on("click", () => { + this.selectParticipants.init() + this.modalNewParticipant.toggle() + }) + this.selectParticipants.item.on("change", () => { + console.log(this.selectParticipants.getVal()) + if (this.selectParticipants.getVal().length > 0) { + this.btnAddParticipantSubmit.removeClass("d-none") + } else { + this.btnAddParticipantSubmit.addClass("d-none") + } + }) + this._handleGetChatDirect() + } initGeneral() { this.chatType = "general" this._handleGetChatList() this.sendBtnMessageDepartment.on("click", this._sendMessage.bind(this)) - - } initPresupuesto() { this.chatType = "presupuesto" @@ -236,8 +264,7 @@ class Chat { ); ajax.get(); } - _getChatDepartmentMessageCount() - { + _getChatDepartmentMessageCount() { let ajax = new Ajax( `/chat/department/count/${this.chatType}/${this.chatDeparmentId}/${this.modelId}`, null, @@ -249,10 +276,10 @@ class Chat { ); ajax.get(); } - _getChatDepartmentMessageCountSuccess(data){ + _getChatDepartmentMessageCountSuccess(data) { this.domItem.find(`chat_${data.name}`).find(".messages-unread-contact").text(data.count) } - _getChatDepartmentMessageCountError(){} + _getChatDepartmentMessageCountError() { } _getChatMessage() { let ajax = new Ajax( @@ -293,7 +320,7 @@ class Chat { ${chatMessage?.user?.first_name + " " + chatMessage?.user?.last_name}
- + ${chatMessage.created_at} @@ -309,6 +336,37 @@ class Chat { this.chatHistory.append(chatItem) return chatItem } + _addChatDirectMessages(chatMessage) { + console.log(chatMessage) + let chatItem = ` +
  • +
    +
    + +
    +

    ${chatMessage?.message}

    +
    +
    +
    + + ${chatMessage?.sender_first_name + " " + chatMessage?.sender_last_name} +
    + + ${chatMessage.created_at} +
    + +
    +
    +
    + ${chatMessage?.sender_first_name.charAt(0) + chatMessage?.sender_last_name.charAt(0)} +
    +
    +
    +
  • + ` + this.chatHistory.append(chatItem) + return chatItem + } _sendMessagePressKey(e) { if (e.which == 13) { e.preventDefault(); @@ -500,6 +558,104 @@ class Chat { this.sideBar.find("#contact-list").append(contactItem) } } + _addParticipantToList(contact) { + + let contactItem = + ` +
  • + +
    + + ${contact?.first_name?.charAt(0) ?? "?" + + contact?.last_name?.charAt(0) ?? "?"} + +
    +
    +
    ${contact?.first_name ?? "" + " " + + contact?.last_name ?? ""}
    +

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

    +
    +
    +
  • + ` + + if (contact.first_name || contact.last_name) { + this.sideBar.find("#contact-list").append(contactItem) + } + } + _handleGetChatDirect() { + + const ajax = new Ajax( + `/chat/${this.chatType}/conversation/${this.modelId}`, + null, + null, + this._handleGetChatDirectSuccess.bind(this), + this._handleGetChatDirectError.bind(this) + ) + ajax.get() + } + _handleGetChatDirectSuccess(response) { + const { chat, users, messages } = response + if (users.length > 0) { + users.map(c => this._addContactToList(c)) + } + if (messages.length > 0) { + messages.map(m => this._addChatDirectMessages(m)) + } + this.domItem.find("#chat-direct-title").text(chat.title) + this.domItem.find(".chat-loader").addClass("d-none") + } + _handleGetChatDirectError(error) { } + + _handleStoreChatDirectUsers() { + const data = { "users": this.selectParticipants.getVal() } + this.domItem.find(".chat-loader").removeClass("d-none") + + const ajax = new Ajax( + `/chat/${this.chatType}/users/${this.modelId}`, + data, + null, + this._handleStoreChatDirectUsersSuccess.bind(this), + this._handleStoreChatDirectUsersError.bind(this) + ) + ajax.post() + } + _handleStoreChatDirectUsersSuccess(response) { + this.domItem.find(".chat-loader").removeClass("d-none") + this.chatHistory.empty() + this.sideBar.find("#contact-list").empty() + this.modalNewParticipant.toggle() + this._handleGetChatDirect() + this.selectParticipants.reset() + } + _handleStoreChatDirectUsersError() { + this.domItem.find(".chat-loader").removeClass("d-none") + } + _handleStoreChatDirectMessage() { + const data = { "message": this.messageInput.val(), "chat_id": this.modelId } + if (data.message) { + const ajax = new Ajax( + `/chat/${this.chatType}/messages/${this.modelId}`, + data, + null, + this._handleStoreChatDirectMessageSuccess.bind(this), + this._handleStoreChatDirectMessageError.bind(this) + ) + ajax.post() + } + } + _handleStoreChatDirectMessageSuccess(response) { + let message = response + this._addChatDirectMessages(message) + this.messageInput.val("") + } + _handleStoreChatDirectMessageError(error) { } + + + diff --git a/httpdocs/assets/js/safekat/components/datatables/MessagesDatatable.js b/httpdocs/assets/js/safekat/components/datatables/MessagesDatatable.js new file mode 100644 index 00000000..1efc7aa8 --- /dev/null +++ b/httpdocs/assets/js/safekat/components/datatables/MessagesDatatable.js @@ -0,0 +1,52 @@ +import Ajax from "../ajax.js"; + +class MessagesDatatable { + constructor(domItem) { + this.item = domItem + this.datatableItem = this.item.find("#tableMessages") + this.datatableColumns = [ + { data: 'created_at', searchable: true, sortable: true }, + { data: 'updated_at', searchable: true, sortable: true }, + { data: 'title', searchable: true, sortable: true }, + { data: 'creator', searchable: false, sortable: false }, + { data: 'viewed', searchable: false, sortable: false , + render : (d,t) => { + const iconClass = d == true ? "ti ti-sm ti-check" : "ti ti-sm ti-x" + return `` + } + }, + { + data: 'action', sortable: false, searchable: false, + render: (d, t) => { + return ` +
    + +
    + ` + } + } + ] + } + init() { + this.datatable = this.datatableItem.DataTable({ + processing: true, + 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: '/messages/datatable' + }); + + } + +} + +export default MessagesDatatable; \ 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 1670b091..1d987376 100644 --- a/httpdocs/assets/js/safekat/components/select2.js +++ b/httpdocs/assets/js/safekat/components/select2.js @@ -13,6 +13,7 @@ let ClassSelect = function (domItem, url, placeholder, allowClear = false, param placeholder: placeholder, allowClear: allowClear, dropdownParent: domItem.parent(), + language: "es", ajax: { url: () => { return this.url; @@ -47,7 +48,7 @@ let ClassSelect = function (domItem, url, placeholder, allowClear = false, param this.init = function () { if (this.item.length) { this.item = this.item.select2(this.config); - $.fn.modal.Constructor.prototype.enforceFocus = function () {}; + // $.fn.modal.Constructor.prototype.enforceFocus = function () {}; } }; this.setOption = function (id, nombre) { diff --git a/httpdocs/assets/js/safekat/pages/configuracion/messages/index.js b/httpdocs/assets/js/safekat/pages/configuracion/messages/index.js new file mode 100644 index 00000000..1cdbf75e --- /dev/null +++ b/httpdocs/assets/js/safekat/pages/configuracion/messages/index.js @@ -0,0 +1,5 @@ +import MessagePage from "./messagePage.js"; + +const messagePage = new MessagePage() + +messagePage.init() \ No newline at end of file diff --git a/httpdocs/assets/js/safekat/pages/configuracion/messages/messagePage.js b/httpdocs/assets/js/safekat/pages/configuracion/messages/messagePage.js new file mode 100644 index 00000000..5d2dbbdc --- /dev/null +++ b/httpdocs/assets/js/safekat/pages/configuracion/messages/messagePage.js @@ -0,0 +1,82 @@ +import MessagesDatatable from "../../../components/datatables/MessagesDatatable.js"; +import Modal from "../../../components/modal.js"; +import Ajax from "../../../components/ajax.js"; +import ClassSelect from "../../../components/select2.js"; +import Alert from "../../../components/alerts/alert.js"; +class MessagePage { + constructor() { + this.messageDatatable = new MessagesDatatable($("#messagesViewCard")) // mensajesView.php + this.modalNewMessage = new Modal($("#modalNewDirectMessage")) + this.btnNewMessage = $("#btn-new-message") + this.btnSubmitNewDirectMessage = this.modalNewMessage.item.find("#submit-new-direct-message") + this.formNewDirectMessage = this.modalNewMessage.item.find("#formNewDirectMessage") + this.alert = new Alert($("#alertDirectMessage")) + this.selectUsers = $("#select-users") + this.selectPlaceholder = { + id: '0', + text: "Seleccione un usuario" + } + this.selectMessageUsers = new ClassSelect(this.selectUsers, '/chat/users/internal', this.selectPlaceholder, true) + + } + init() { + this.events() + this.messageDatatable.init() + } + events() { + // Open new message when click in btn-new-message + this.btnNewMessage.on("click", this.openNewMessageModal.bind(this)) + this.btnSubmitNewDirectMessage.on("click", this.handleSubmitNewMessage.bind(this)) + + } + openNewMessageModal() { + this.formNewDirectMessage.trigger("reset") + this.selectMessageUsers.init() + this.alert.hide() + this.showForm() + this.modalNewMessage.toggle() + } + + handleSubmitNewMessage() { + this.btnNewMessage.addClass("loading") + const ajax = new Ajax("/messages/direct", + this.getNewMessageDataForm(), + null, + this.handleSubmitNewMessageSuccess.bind(this), + this.handleSubmitNewMessageError.bind(this)) + ajax.post() + } + handleSubmitNewMessageSuccess(response) { + this.btnNewMessage.removeClass("loading") + this.alert.setAsSuccess() + this.alert.setHeadingTitle(response.message) + this.alert.show() + this.hideForm() + } + handleSubmitNewMessageError(response) { + const error = response.responseJSON + this.btnNewMessage.removeClass("loading") + this.alert.show() + this.alert.setAsError() + this.alert.setHeadingTitle(error.message) + } + getNewMessageDataForm() { + return { + "title": this.formNewDirectMessage.find("#new-direct-message-title").val(), + "message": this.formNewDirectMessage.find("#new-direct-message-text").val(), + "users": this.selectMessageUsers.getVal() + } + } + hideForm() { + this.formNewDirectMessage.addClass("d-none") + this.btnSubmitNewDirectMessage.addClass("d-none") + } + showForm() { + this.formNewDirectMessage.removeClass("d-none") + this.btnSubmitNewDirectMessage.removeClass("d-none") + + } +} + + +export default MessagePage; \ No newline at end of file diff --git a/httpdocs/assets/js/safekat/pages/messages/directMessagePage.js b/httpdocs/assets/js/safekat/pages/messages/directMessagePage.js new file mode 100644 index 00000000..ef79560f --- /dev/null +++ b/httpdocs/assets/js/safekat/pages/messages/directMessagePage.js @@ -0,0 +1,9 @@ +import Chat from "../../components/chat.js"; + +$(function(){ + + const chatDirectMessage = new Chat($("#chat-direct-message")) + chatDirectMessage.init() + chatDirectMessage.initDirectMessage() +} +) diff --git a/httpdocs/assets/js/safekat/validation/newDirectMessageValidation.js b/httpdocs/assets/js/safekat/validation/newDirectMessageValidation.js new file mode 100644 index 00000000..42478e6e --- /dev/null +++ b/httpdocs/assets/js/safekat/validation/newDirectMessageValidation.js @@ -0,0 +1,21 @@ + +export const newDirectMessageValidation = +{ + fields:{ + title:{ + notEmpty:{ + message : "Título no puede estar vacío" + }, + }, + message:{ + notEmpty:{ + message : "Mensaje no puede estar vacío" + }, + }, + users:{ + notEmpty:{ + message : "Debe seleccionar al menos a un participante" + }, + } + }, +} \ No newline at end of file From c1aecb43f2afbfa1bbf3984683c181e20007f873 Mon Sep 17 00:00:00 2001 From: amazuecos Date: Thu, 28 Nov 2024 16:07:11 +0100 Subject: [PATCH 2/3] messages chat view --- ci4/app/Config/Routes.php | 3 + ci4/app/Controllers/Chat/ChatController.php | 215 +++--- ci4/app/Language/es/Chat.php | 6 +- ci4/app/Models/Chat/ChatModel.php | 629 ++++++++++-------- ci4/app/Models/ChatNotification.php | 11 + ci4/app/Models/ChatUser.php | 4 +- .../themes/vuexy/components/chat_direct.php | 19 +- .../themes/vuexy/components/chat_factura.php | 21 +- .../themes/vuexy/components/chat_general.php | 1 + .../themes/vuexy/components/chat_pedido.php | 13 +- .../vuexy/components/chat_presupuesto.php | 22 +- .../modals/modalAddNewChatParticipant.php | 15 +- .../vuexy/form/mensajes/messageChat.php | 2 +- httpdocs/assets/js/safekat/components/chat.js | 89 ++- .../js/safekat/pages/chatNotification.js | 4 + .../configuracion/messages/messagePage.js | 3 +- 16 files changed, 661 insertions(+), 396 deletions(-) diff --git a/ci4/app/Config/Routes.php b/ci4/app/Config/Routes.php index 1d643167..9e77842c 100644 --- a/ci4/app/Config/Routes.php +++ b/ci4/app/Config/Routes.php @@ -775,6 +775,7 @@ $routes->group('chat', ['namespace' => 'App\Controllers\Chat'], function ($route $routes->post('direct/users/(:num)', 'ChatController::store_chat_direct_users/$1', ['as' => 'storeChatDirectUsers']); $routes->get('direct/messages/(:num)', 'ChatController::get_chat_direct_messages/$1', ['as' => 'getChatDirectMessages']); $routes->post('direct/messages/(:num)', 'ChatController::store_chat_direct_message/$1', ['as' => 'storeChatDirectMessages']); + $routes->post('direct/messages/unread/(:num)', 'ChatController::update_chat_direct_message_unread/$1', ['as' => 'updateChatDirectMessageUnread']); $routes->get('departments', 'ChatController::get_chat_departments', ['as' => 'getChatDepartments']); @@ -794,6 +795,8 @@ $routes->group('chat', ['namespace' => 'App\Controllers\Chat'], function ($route $routes->get('contact/(:num)/messages', 'ChatController::get_chat_internal_messages/$1', ['as' => 'getChatInternalMessages']); $routes->get('notifications', 'ChatController::get_chat_cliente/$1', ['as' => 'getChatCliente']); $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']); diff --git a/ci4/app/Controllers/Chat/ChatController.php b/ci4/app/Controllers/Chat/ChatController.php index 969e7713..1712a73e 100644 --- a/ci4/app/Controllers/Chat/ChatController.php +++ b/ci4/app/Controllers/Chat/ChatController.php @@ -49,8 +49,6 @@ class ChatController extends BaseController $this->clienteModel = model(ClienteModel::class); $this->chatUserModel = model(ChatUser::class); $this->chatNotificationModel = model(ChatNotification::class); - - } public function index() {} public function get_chat_departments() @@ -89,7 +87,6 @@ class ChatController extends BaseController $data["messages"] = $this->chatMessageModel->get_chat_messages($chat->id); $this->chatMessageModel->set_chat_department_messages_as_read($chat->id); $data["count"] = count($data["messages"]); - } $data["chat"] = $chat; return $this->response->setJSON($data); @@ -111,13 +108,17 @@ class ChatController extends BaseController $data["chat"] = $chat; return $this->response->setJSON($data); } - public function get_chat_direct_view($chat_id){ + public function get_chat_direct_view($chat_id) + { $chat = $this->chatModel->find($chat_id); $this->viewData['breadcrumb'] = [ ['title' => lang("Chat.chat"), 'route' => route_to("mensajeriaView"), 'active' => false], ['title' => $chat->title, 'route' => 'javascript:void(0);', 'active' => true] ]; $this->viewData["chatId"] = $chat_id; + $auth_user = auth()->user(); + $this->chatModel->setAsViewedChatUserNotifications($chat_id, $auth_user->id); + $this->chatModel->setAsUnviewedChatUserMessages($chat_id, $auth_user->id); return view(static::$viewPath . 'messageChat', $this->viewData); } @@ -141,6 +142,12 @@ 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"]); + foreach ($chatDepartmentUsers as $user) { + if($user->id != auth()->user()->id){ + $this->chatNotificationModel->insert(["chat_message_id" => $chat_message_id,"user_id"=> $user->id]); + } + } return $this->response->setJSON($dataResponse); } public function store_chat_message_pedido() @@ -156,6 +163,12 @@ 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"]); + foreach ($chatDepartmentUsers as $user) { + if($user->id != auth()->user()->id){ + $this->chatNotificationModel->insert(["chat_message_id" => $chat_message_id,"user_id"=> $user->id]); + } + } return $this->response->setJSON($dataResponse); } public function store_chat_message_factura() @@ -171,6 +184,12 @@ 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"]); + foreach ($chatDepartmentUsers as $user) { + if($user->id != auth()->user()->id){ + $this->chatNotificationModel->insert(["chat_message_id" => $chat_message_id,"user_id"=> $user->id]); + } + } return $this->response->setJSON($dataResponse); } public function store_chat_message_single() @@ -191,7 +210,7 @@ class ChatController extends BaseController "receiver_id" => $data["receiver_id"], ] ); - $this->chatNotificationModel->insert(["chat_message_id" => $chat_message_id,"user_id" =>$data["receiver_id"]]); + $this->chatNotificationModel->insert(["chat_message_id" => $chat_message_id, "user_id" => $data["receiver_id"]]); $dataResponse = $this->chatMessageModel->find($chat_message_id); return $this->response->setJSON($dataResponse); } @@ -200,11 +219,11 @@ class ChatController extends BaseController $auth_user = auth()->user(); if ($auth_user->cliente_id) { $users = $this->chatModel->getOpenChatCliente($auth_user->id); - }else{ + } else { $users = $this->userModel->builder() - ->whereNotIn("id", [$auth_user->id]) - ->where("deleted_at", null) - ->get()->getResultObject(); + ->whereNotIn("id", [$auth_user->id]) + ->where("deleted_at", null) + ->get()->getResultObject(); } foreach ($users as $user) { $user->unreadMessages = $this->chatMessageModel->get_chat_messages_count($user->id); @@ -288,7 +307,26 @@ class ChatController extends BaseController ] )->where("cliente_id", null) ->where("deleted_at", null) - ->whereNotIn("id",[auth()->user()->id]); + ->whereNotIn("id", [auth()->user()->id]); + if ($this->request->getGet("q")) { + $query->groupStart() + ->orLike("users.username", $this->request->getGet("q")) + ->orLike("CONCAT(first_name,' ',last_name)", $this->request->getGet("q")) + ->groupEnd(); + } + + return $this->response->setJSON($query->get()->getResultObject()); + } + public function get_chat_users_all() + { + $query = $this->userModel->builder()->select( + [ + "id", + "CONCAT(first_name,' ',last_name,'(',username,')') as name" + ] + ) + ->where("deleted_at", null) + ->whereNotIn("id", [auth()->user()->id]); if ($this->request->getGet("q")) { $query->groupStart() ->orLike("users.username", $this->request->getGet("q")) @@ -310,15 +348,16 @@ class ChatController extends BaseController "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"]); + 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]); + ["chat_message_id" => $chatMessageId, "user_id" => $userId] + ); } } - return $this->response->setJSON(["message" => "Hebra creada correctamente","status" => true]); + return $this->response->setJSON(["message" => "Hebra creada correctamente", "status" => true]); } public function store_hebra_pedido() @@ -334,15 +373,16 @@ class ChatController extends BaseController "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"]); + 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]); + ["chat_message_id" => $chatMessageId, "user_id" => $userId] + ); } } - return $this->response->setJSON(["message" => "Hebra creada correctamente","status" => true]); + return $this->response->setJSON(["message" => "Hebra creada correctamente", "status" => true]); } public function store_hebra_factura() @@ -357,101 +397,105 @@ class ChatController extends BaseController "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"]); + 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]); + ["chat_message_id" => $chatMessageId, "user_id" => $userId] + ); } } - return $this->response->setJSON(["message" => "Hebra creada correctamente","status" => true]); - + return $this->response->setJSON(["message" => "Hebra creada correctamente", "status" => true]); } public function update_hebra($chat_id) { $bodyData = $this->request->getPost(); - $chatMessageId = $this->chatMessageModel->insert([ + $chatMessageId = $this->chatMessageModel->insert([ "chat_id" => $chat_id, "message" => $bodyData["message"], "sender_id" => auth()->user()->id ]); - $actualUsers = $this->chatUserModel->builder()->select("user_id")->where("chat_id",$chat_id)->get()->getResultArray(); - $actualUsersArray = array_map(fn($x) => $x["user_id"],$actualUsers); + $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]); + ["chat_message_id" => $chatMessageId, "user_id" => $user_id] + ); } - if(isset($bodyData["users"])){ + if (isset($bodyData["users"])) { foreach ($bodyData["users"] as $userId) { - if(in_array($userId,$actualUsersArray) == false){ - $chatUserData = ["user_id" => $userId,"chat_id" => $chat_id]; + if (in_array($userId, $actualUsersArray) == false) { + $chatUserData = ["user_id" => $userId, "chat_id" => $chat_id]; $this->chatUserModel->insert($chatUserData); - } $this->chatNotificationModel->insert( - ["chat_message_id" => $chatMessageId,"user_id" => $userId]); + ["chat_message_id" => $chatMessageId, "user_id" => $userId] + ); } } - return $this->response->setJSON(["message" => "Hebra actualizada correctamente","status" => true]); + return $this->response->setJSON(["message" => "Hebra actualizada correctamente", "status" => true]); } - public function get_hebra_presupuesto($presupuesto_id){ + public function get_hebra_presupuesto($presupuesto_id) + { $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(); + ->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]); + $this->chatNotificationModel->update($notification["id"], ["viewed" => true]); } return $this->response->setJSON($data); } - public function get_hebra_pedido($pedido_id){ + 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(); + ->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]); + $this->chatNotificationModel->update($notification["id"], ["viewed" => true]); } return $this->response->setJSON($data); } - public function get_hebra_factura($factura_id){ + 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(); + ->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]); + $this->chatNotificationModel->update($notification["id"], ["viewed" => true]); } return $this->response->setJSON($data); } public function datatable_messages() { - $query = $this->chatModel->getQueryDatatable(); $auth_user_id = auth()->user()->id; + $query = $this->chatModel->getQueryDatatable($auth_user_id); return DataTable::of($query) - ->edit('created_at',fn($q) => Time::createFromFormat('Y-m-d H:i:s',$q->created_at)->format("d/m/Y H:i")) - ->edit('updated_at',fn($q) => 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) => $q->id) - ->toJson(true); + ->edit('created_at', fn($q) => Time::createFromFormat('Y-m-d H:i:s', $q->created_at)->format("d/m/Y H:i")) + ->edit('updated_at', fn($q) => 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) => $q->id) + ->toJson(true); } public function store_new_direct_message() { @@ -462,7 +506,7 @@ class ChatController extends BaseController "users" => "required", ]; - if(!$this->validate($rules)){ + if (!$this->validate($rules)) { return $this->response->setStatusCode(400)->setJSON([ 'message' => lang('App.global_alert_save_error'), 'status' => 'error', @@ -470,14 +514,15 @@ class ChatController extends BaseController ]); } $this->chatModel->createNewDirectChat(...$bodyData); - return $this->response->setJSON(["message" => lang("Chat.new_message_ok"),"status" => true]); - + return $this->response->setJSON(["message" => lang("Chat.new_message_ok"), "status" => true]); } - public function get_chat_direct($chat_id){ + public function get_chat_direct($chat_id) + { $chatData = $this->chatModel->getChatDirect($chat_id); return $this->response->setJSON($chatData); } - public function get_chat_direct_select_users($chat_id){ + public function get_chat_direct_select_users($chat_id) + { $chat_users_id = $this->chatUserModel->getChatUserArrayId($chat_id); $query = $this->userModel->builder()->select( @@ -485,9 +530,9 @@ class ChatController extends BaseController "id", "CONCAT(first_name,' ',last_name,'(',username,')') as name" ] - )->where("cliente_id", null) + ) ->where("deleted_at", null) - ->whereNotIn("id",$chat_users_id); + ->whereNotIn("id", $chat_users_id); if ($this->request->getGet("q")) { $query->groupStart() ->orLike("users.username", $this->request->getGet("q")) @@ -497,19 +542,37 @@ class ChatController extends BaseController return $this->response->setJSON($query->get()->getResultObject()); } - public function store_chat_direct_users($chat_id){ + public function store_chat_direct_users($chat_id) + { $bodyData = $this->request->getPost(); - $chat_users = array_map(fn($q) => ["chat_id" => $chat_id,"user_id" => $q],$bodyData["users"]); + $chat_users = []; + foreach ($bodyData["users"] as $user_id) { + $chat_users[] = ["chat_id" => $chat_id, "user_id" => $user_id]; + if ($bodyData["notification"]) { + $this->chatModel->createNotificationsToNewChatUser($chat_id, $user_id); + } + } $this->chatUserModel->insertBatch($chat_users); - return $this->response->setJSON(["message" => "ok","status" => true]); + return $this->response->setJSON(["message" => "ok", "status" => true]); } - public function store_chat_direct_message(int $chat_id){ + public function store_chat_direct_message(int $chat_id) + { $bodyData = $this->request->getPost(); - $bodyData["sender_id"] = auth()->user()->id; + $auth_user = auth()->user(); + $bodyData["sender_id"] = $auth_user->id; $chat_message_id = $this->chatMessageModel->insert($bodyData); + $users_id = $this->chatUserModel->getChatUserArrayId($chat_id); + foreach ($users_id as $user_id) { + if ($user_id != $auth_user->id) { + $this->chatNotificationModel->insert(["chat_message_id" => $chat_message_id, "user_id" => $user_id]); + } + }; $message = $this->chatMessageModel->get_chat_message($chat_message_id); - return $this->response->setJSON($message); - - + return $this->response->setJSON($message); } + public function update_chat_direct_message_unread($chat_id){ + $this->chatModel->setAsUnviewedChatUserNotifications($chat_id,auth()->user()->id); + return $this->response->setJSON(["message" => "ok", "status" => true]); + } + } diff --git a/ci4/app/Language/es/Chat.php b/ci4/app/Language/es/Chat.php index 1a0efc20..9900a19c 100644 --- a/ci4/app/Language/es/Chat.php +++ b/ci4/app/Language/es/Chat.php @@ -21,6 +21,10 @@ return [ ], "new_message_ok" => "Mensaje enviado correctamente", "participants" => "Participantes", - "write_message_placeholder" => "Escriba aquí su mensaje..." + "new_participant" => "Añadir nuevos participantes", + "write_message_placeholder" => "Escriba aquí su mensaje...", + "add_notification" => "Notificación", + "check_as_unviewed" => "Marcar como no leídos", + "add_notification_message" => "Envía a los usuarios añadidos una notificación con los mensajes presentes en el chat." ]; \ No newline at end of file diff --git a/ci4/app/Models/Chat/ChatModel.php b/ci4/app/Models/Chat/ChatModel.php index d0b3b5bd..1862f609 100644 --- a/ci4/app/Models/Chat/ChatModel.php +++ b/ci4/app/Models/Chat/ChatModel.php @@ -81,7 +81,7 @@ class ChatModel extends Model { return $this->builder()->where("pedido_id", $pedido_id)->where("chat_department_id", $chat_department_id)->get()->getFirstRow(); } - public function getChatFactura(int $chat_department_id, int $factura_id) + public function getChatFactura(int $chat_department_id, int $factura_id) { return $this->builder()->where("factura_id", $factura_id)->where("chat_department_id", $chat_department_id)->get()->getFirstRow(); } @@ -93,15 +93,15 @@ class ChatModel extends Model "chat_department_id" => $chat_department_id ]); } - public function createChatPedido(int $chat_department_id, int $pedido_id) : int + public function createChatPedido(int $chat_department_id, int $pedido_id): int { - return $this->insert([ + return $this->insert([ "pedido_id" => $pedido_id, "chat_department_id" => $chat_department_id ]); } - public function createChatFactura(int $chat_department_id, int $factura_id) : int + public function createChatFactura(int $chat_department_id, int $factura_id): int { return $this->insert([ @@ -109,7 +109,7 @@ class ChatModel extends Model "chat_department_id" => $chat_department_id ]); } - public function createChatSingle() : int + public function createChatSingle(): int { return $this->insert(["chat_department_id" => null]); } @@ -138,82 +138,82 @@ class ChatModel extends Model return $countChatPresupuesto > 0; } - public function getChatPedidosChat() : array + public function getChatPedidosChat(): array { $query = $this->db->table("chats") - ->select([ - "chats.id as chatId", - "chats.pedido_id as pedidoId", - "chats.chat_department_id as chatDepartmentId", - "chat_departments.display as chatDisplay", - "pedidos.id as title" - ]) - ->join("chat_departments","chat_departments.id = chats.chat_department_id","left") - ->join("pedidos","pedidos.id = chats.pedido_id","left") - ->get()->getResultObject(); + ->select([ + "chats.id as chatId", + "chats.pedido_id as pedidoId", + "chats.chat_department_id as chatDepartmentId", + "chat_departments.display as chatDisplay", + "pedidos.id as title" + ]) + ->join("chat_departments", "chat_departments.id = chats.chat_department_id", "left") + ->join("pedidos", "pedidos.id = chats.pedido_id", "left") + ->get()->getResultObject(); return $query; } - - public function getChatPresupuestosChat() : array + + public function getChatPresupuestosChat(): array { $query = $this->db->table("chats") - ->select([ - "chats.id as chatId", - "chats.pedido_id as pedidoId", - "chats.chat_department_id as chatDepartmentId", - "chat_departments.display as chatDisplay", - "presupuestos.titulo as title" - ]) - ->join("chat_departments","chat_departments.id = chats.chat_department_id","left") - ->join("presupuestos","presupuestos.id = chats.pedido_id","left") - ->get()->getResultObject(); + ->select([ + "chats.id as chatId", + "chats.pedido_id as pedidoId", + "chats.chat_department_id as chatDepartmentId", + "chat_departments.display as chatDisplay", + "presupuestos.titulo as title" + ]) + ->join("chat_departments", "chat_departments.id = chats.chat_department_id", "left") + ->join("presupuestos", "presupuestos.id = chats.pedido_id", "left") + ->get()->getResultObject(); return $query; } - public function getChatFacturasChat() : array + public function getChatFacturasChat(): array { $query = $this->db->table("chats") - ->select([ - "chats.id as chatId", - "chats.pedido_id as pedidoId", - "chats.chat_department_id as chatDepartmentId", - "chat_departments.display as chatDisplay", - "facturas.numero as title" - ]) - ->join("chat_departments","chat_departments.id = chats.chat_department_id","left") - ->join("facturas","facturas.id = chats.pedido_id","left") - ->get()->getResultObject(); + ->select([ + "chats.id as chatId", + "chats.pedido_id as pedidoId", + "chats.chat_department_id as chatDepartmentId", + "chat_departments.display as chatDisplay", + "facturas.numero as title" + ]) + ->join("chat_departments", "chat_departments.id = chats.chat_department_id", "left") + ->join("facturas", "facturas.id = chats.pedido_id", "left") + ->get()->getResultObject(); return $query; } - public function getChatSingleChat() : array + public function getChatSingleChat(): array { $query = $this->db->table("chats") - ->select([ - "chats.id as chatId", - "chats.chat_department_id as chatDepartmentId", - "chat_departments.display as chatDisplay", - "facturas.numero as title" - ]) - ->join("chat_departments","chat_departments.id = chats.chat_department_id","left") - ->join("facturas","facturas.id = chats.pedido_id","left") - ->get()->getResultObject(); + ->select([ + "chats.id as chatId", + "chats.chat_department_id as chatDepartmentId", + "chat_departments.display as chatDisplay", + "facturas.numero as title" + ]) + ->join("chat_departments", "chat_departments.id = chats.chat_department_id", "left") + ->join("facturas", "facturas.id = chats.pedido_id", "left") + ->get()->getResultObject(); return $query; } - public function getClienteChatPedidos(array $pedidos) : array + public function getClienteChatPedidos(array $pedidos): array { $q = $this->db->table("chats") - ->select([ - "chats.id as chatId", - "chats.pedido_id as pedidoId", - "chats.chat_department_id as chatDepartmentId", - "chat_departments.display as chatDisplay", - "pedidos.id as title" - ]) - ->join("chat_departments","chat_departments.id = chats.chat_department_id","left") - ->join("pedidos","pedidos.id = chats.pedido_id","left") - ->where('chats.chat_department_id is NOT NULL', NULL, FALSE); - if(count($pedidos)>0){ - $q->whereIn("pedidos.id",$pedidos); - }else{ + ->select([ + "chats.id as chatId", + "chats.pedido_id as pedidoId", + "chats.chat_department_id as chatDepartmentId", + "chat_departments.display as chatDisplay", + "pedidos.id as title" + ]) + ->join("chat_departments", "chat_departments.id = chats.chat_department_id", "left") + ->join("pedidos", "pedidos.id = chats.pedido_id", "left") + ->where('chats.chat_department_id is NOT NULL', NULL, FALSE); + if (count($pedidos) > 0) { + $q->whereIn("pedidos.id", $pedidos); + } else { return []; } $results = $q->get()->getResultObject(); @@ -222,32 +222,32 @@ class ChatModel extends Model foreach ($results as $row) { $messages = $chatMessageModel->get_chat_messages($row->chatId); foreach ($messages as $key => $message) { - if($message->sender_id != auth()->user()->id && $message->viewed == false){ + if ($message->sender_id != auth()->user()->id && $message->viewed == false) { $count++; } } - $row->uri = "/pedidos/edit/".$row->pedidoId; - $row->unreadMessages=$count; + $row->uri = "/pedidos/edit/" . $row->pedidoId; + $row->unreadMessages = $count; } return $results; } - public function getClienteChatFacturas(array $facturas) : array + public function getClienteChatFacturas(array $facturas): array { $q = $this->db->table("chats") - ->select([ - "chats.id as chatId", - "chats.factura_id as facturaId", - "chats.chat_department_id as chatDepartmentId", - "chat_departments.display as chatDisplay", - "facturas.numero as title" - ]) - ->join("chat_departments","chat_departments.id = chats.chat_department_id","left") - ->join("facturas","facturas.id = chats.factura_id","left") - ->where('chats.chat_department_id is NOT NULL', NULL, FALSE); + ->select([ + "chats.id as chatId", + "chats.factura_id as facturaId", + "chats.chat_department_id as chatDepartmentId", + "chat_departments.display as chatDisplay", + "facturas.numero as title" + ]) + ->join("chat_departments", "chat_departments.id = chats.chat_department_id", "left") + ->join("facturas", "facturas.id = chats.factura_id", "left") + ->where('chats.chat_department_id is NOT NULL', NULL, FALSE); - if(count($facturas)>0){ - $q->whereIn("facturas.id",$facturas); - }else{ + if (count($facturas) > 0) { + $q->whereIn("facturas.id", $facturas); + } else { return []; } $results = $q->get()->getResultObject(); @@ -256,32 +256,32 @@ class ChatModel extends Model foreach ($results as $row) { $messages = $chatMessageModel->get_chat_messages($row->chatId); foreach ($messages as $key => $message) { - if($message->sender_id != auth()->user()->id && $message->viewed == false){ + if ($message->sender_id != auth()->user()->id && $message->viewed == false) { $count++; } } - $row->uri = "/facturas/edit/".$row->facturaId; - $row->unreadMessages=$count; + $row->uri = "/facturas/edit/" . $row->facturaId; + $row->unreadMessages = $count; } return $results; } - public function getClienteChatPresupuestos(array $presupuestos) : array + public function getClienteChatPresupuestos(array $presupuestos): array { $q = $this->db->table("chats") - ->select([ - "chats.id as chatId", - "chats.presupuesto_id as presupuestoId", - "chats.chat_department_id as chatDepartmentId", - "chat_departments.display as chatDisplay", - "presupuestos.titulo as title" - ]) - ->join("chat_departments","chat_departments.id = chats.chat_department_id","left") - ->join("presupuestos","presupuestos.id = chats.presupuesto_id","left") - ->where('chats.chat_department_id is NOT NULL', NULL, FALSE); + ->select([ + "chats.id as chatId", + "chats.presupuesto_id as presupuestoId", + "chats.chat_department_id as chatDepartmentId", + "chat_departments.display as chatDisplay", + "presupuestos.titulo as title" + ]) + ->join("chat_departments", "chat_departments.id = chats.chat_department_id", "left") + ->join("presupuestos", "presupuestos.id = chats.presupuesto_id", "left") + ->where('chats.chat_department_id is NOT NULL', NULL, FALSE); - if(count($presupuestos)>0){ - $q->whereIn("presupuestos.id",$presupuestos); - }else{ + if (count($presupuestos) > 0) { + $q->whereIn("presupuestos.id", $presupuestos); + } else { return []; } $results = $q->get()->getResultObject(); @@ -289,15 +289,15 @@ class ChatModel extends Model $count = 0; foreach ($results as $row) { $messages = $chatMessageModel->get_chat_messages($row->chatId); - foreach ($messages as $key => $message ) { - if($message->sender_id != auth()->user()->id && $message->viewed == false){ + foreach ($messages as $key => $message) { + if ($message->sender_id != auth()->user()->id && $message->viewed == false) { $count++; } } - $row->uri = "/presupuestos/presupuestocliente/edit/".$row->presupuestoId; - $row->unreadMessages=$count; + $row->uri = "/presupuestos/presupuestocliente/edit/" . $row->presupuestoId; + $row->unreadMessages = $count; } - + return $results; } public function getChatDepartmentNotifications() @@ -309,54 +309,55 @@ class ChatModel extends Model $pedidoModel = model(PedidoModel::class); $q = $this->db->table("chats") - ->select([ - "chats.id as chatId", - "chats.pedido_id as pedidoId", - "chats.presupuesto_id as presupuestoId", - "chats.factura_id as facturaId", - "chats.chat_department_id as chatDepartmentId", - "chat_departments.display as chatDisplay", - ]) - ->join("chat_departments","chat_departments.id = chats.chat_department_id","left") - ->join("chat_department_users","chat_department_users.chat_department_id = chats.chat_department_id","left") - ->where("chat_department_users.user_id",auth()->user()->id); + ->select([ + "chats.id as chatId", + "chats.pedido_id as pedidoId", + "chats.presupuesto_id as presupuestoId", + "chats.factura_id as facturaId", + "chats.chat_department_id as chatDepartmentId", + "chat_departments.display as chatDisplay", + ]) + ->join("chat_departments", "chat_departments.id = chats.chat_department_id", "left") + ->join("chat_department_users", "chat_department_users.chat_department_id = chats.chat_department_id", "left") + ->where("chat_department_users.user_id", auth()->user()->id); $rows = $q->get()->getResultObject(); - - + + $auth_user = auth()->user(); foreach ($rows as $row) { $messages = $chatMessageModel->get_chat_messages($row->chatId); $count = 0; $chatDeparmentUsers = $chatDeparmentModel->getChatDepartmentUsers($row->chatDepartmentId); - $chatDeparmentUsersId = array_map(fn($x) => $x->id,$chatDeparmentUsers); + $chatDeparmentUsersId = array_map(fn($x) => $x->id, $chatDeparmentUsers); foreach ($messages as $m) { - if($m->viewed == false && $m->sender_id != auth()->user()->id && in_array($m->sender_id,$chatDeparmentUsersId) == false) + if ($m->viewed == false && $m->sender_id != auth()->user()->id && in_array($m->sender_id, $chatDeparmentUsersId) == false) $count++; } - if($row->presupuestoId){ + if ($row->presupuestoId) { $row->model = $presupuestoModel->find($row->presupuestoId); - $row->uri = "/presupuestoadmin/edit/".$row->presupuestoId; + if($auth_user->cliente_id){ + $row->uri = "/presupuestocliente/edit/" . $row->presupuestoId; + }else{ + $row->uri = "/presupuestoadmin/edit/" . $row->presupuestoId; + + } $row->title = $row->presupuestoId; $row->avatar = "PRE"; $row->unreadMessages = $count; - } - elseif($row->pedidoId){ + } elseif ($row->pedidoId) { $row->model = $pedidoModel->find($row->pedidoId); - $row->uri = "/pedidos/edit/".$row->pedidoId; + $row->uri = "/pedidos/edit/" . $row->pedidoId; $row->title = $row->pedidoId; $row->avatar = "P"; $row->unreadMessages = $count; - - } - elseif($row->facturaId){ + } elseif ($row->facturaId) { $row->model = $facturaModel->find($row->facturaId); - $row->uri = "/facturas/edit/".$row->facturaId; + $row->uri = "/facturas/edit/" . $row->facturaId; $row->avatar = "F"; $row->title = $row->facturaId; $row->unreadMessages = $count; } } return $rows; - } public function getChatInternalNotifications() { @@ -367,42 +368,45 @@ class ChatModel extends Model $chatNotificationModel = model(ChatNotification::class); $q = $this->db->table("chats") - ->select([ - "chats.id as chatId", - "chats.pedido_id as pedidoId", - "chats.presupuesto_id as presupuestoId", - "chats.factura_id as facturaId", - "chats.title as chatDisplay", - ]) - ->join("chat_messages","chat_messages.chat_id = chats.id","left") - ->join("chat_notifications","chat_notifications.chat_message_id = chat_messages.id","left") - ->where("chat_notifications.user_id",auth()->user()->id) - ->where("chat_notifications.viewed",false); + ->select([ + "chats.id as chatId", + "chats.pedido_id as pedidoId", + "chats.presupuesto_id as presupuestoId", + "chats.factura_id as facturaId", + "chats.title as chatDisplay", + ]) + ->join("chat_messages", "chat_messages.chat_id = chats.id", "left") + ->join("chat_notifications", "chat_notifications.chat_message_id = chat_messages.id", "left") + ->where("chat_notifications.user_id", auth()->user()->id) + ->where("chat_notifications.viewed", false); + $auth_user = auth()->user(); $rows = $q->get()->getResultObject(); $rows_new = []; foreach ($rows as $row) { $row->unreadMessages = 0; - if($row->presupuestoId){ + if ($row->presupuestoId) { $row->model = $presupuestoModel->find($row->presupuestoId); - $row->uri = "/presupuestoadmin/edit/".$row->presupuestoId; + if($auth_user->cliente_id){ + $row->uri = "/presupuestocliente/edit/" . $row->presupuestoId; + }else{ + $row->uri = "/presupuestoadmin/edit/" . $row->presupuestoId; + + } $row->title = $row->presupuestoId; + $row->chatDisplay = $row->model->titulo; $row->avatar = "PRE"; $row->unreadMessages = $this->countUnreadMessagePresupuesto($row->presupuestoId); $rows_new[] = $row; - } - elseif($row->pedidoId){ + } elseif ($row->pedidoId) { $row->model = $pedidoModel->find($row->pedidoId); - $row->uri = "/pedidos/edit/".$row->pedidoId; + $row->uri = "/pedidos/edit/" . $row->pedidoId; $row->title = $row->pedidoId; $row->avatar = "P"; $row->unreadMessages = $this->countUnreadMessagePedido($row->pedidoId); $rows_new[] = $row; - - - } - elseif($row->facturaId){ + } elseif ($row->facturaId) { $row->model = $facturaModel->find($row->facturaId); - $row->uri = "/facturas/edit/".$row->facturaId; + $row->uri = "/facturas/edit/" . $row->facturaId; $row->avatar = "F"; $row->title = $row->facturaId; $row->unreadMessages = $this->countUnreadMessageFactura($row->facturaId); @@ -411,39 +415,40 @@ class ChatModel extends Model } return $rows_new; } - public function getChatDirectMessageNotifications(){ + public function getChatDirectMessageNotifications() + { $chatMessageModel = model(ChatMessageModel::class); $chatNotificationModel = model(ChatNotification::class); $q = $this->db->table("chats") - ->select([ - "chats.id as chatId", - "chats.title as chatDisplay", - "COUNT(chat_notifications.user_id) as unreadMessages" - ]) - ->join("chat_messages","chat_messages.chat_id = chats.id","left") - ->join("chat_notifications","chat_notifications.chat_message_id = chat_messages.id","left") - ->where("chats.presupuesto_id",null) - ->where("chats.chat_department_id",null) - ->where("chats.pedido_id",null) - ->where("chats.factura_id",null) - ->where("chat_notifications.viewed",false) - ->where("chat_notifications.user_id",auth()->user()->id); + ->select([ + "chats.id as chatId", + "chats.title as chatDisplay", + "COUNT(chat_notifications.user_id) as unreadMessages" + ]) + ->join("chat_messages", "chat_messages.chat_id = chats.id", "left") + ->join("chat_notifications", "chat_notifications.chat_message_id = chat_messages.id", "left") + ->where("chats.presupuesto_id", null) + ->where("chats.chat_department_id", null) + ->where("chats.pedido_id", null) + ->where("chats.factura_id", null) + ->where("chat_notifications.viewed", false) + ->where("chat_notifications.user_id", auth()->user()->id); $rows = $q->get()->getResultObject(); $rows_new = []; foreach ($rows as $row) { - if($row->chatId){ + if ($row->chatId) { $row->model = []; - $row->uri = "/mensajes/internos"; + $row->uri = "/chat/direct/".$row->chatId; $row->avatar = "MD"; $row->title = "MD"; - $row->chatDisplay = $this->getSenderIdFromChatMessage($row->chatId)?->username ?? "Unknown"; + // $row->chatDisplay = $this->getSenderIdFromChatMessage($row->chatId)?->username ?? "Unknown"; $rows_new[] = $row; } } return $rows_new; } - public function getChatInternalHebraPresupuesto(int $chat_id,int $presupuesto_id) : array + public function getChatInternalHebraPresupuesto(int $chat_id, int $presupuesto_id): array { $data = []; @@ -454,17 +459,18 @@ class ChatModel extends Model "chat_messages.created_at", "CONCAT(users.first_name,' ',users.last_name) as senderFullName", ]) - ->join("chat_messages","chat_messages.chat_id = chats.id","left") - ->join("users","users.id = chat_messages.sender_id","left") - ->where("chats.id",$chat_id) - ->where("chats.presupuesto_id",$presupuesto_id); + ->join("chat_messages", "chat_messages.chat_id = chats.id", "left") + ->join("users", "users.id = chat_messages.sender_id", "left") + ->where("chats.id", $chat_id) + ->where("chats.presupuesto_id", $presupuesto_id); $data["chatId"] = $chat_id; $data["messages"] = $query->get()->getResultObject(); $data["chatTitle"] = $this->find($chat_id)->title; $data["users"] = $this->getChatUsers($chat_id); return $data; } - public function getChatInternalHebraPedido($chat_id,$pedido_id){ + public function getChatInternalHebraPedido($chat_id, $pedido_id) + { $data = []; $query = $this->builder()->select([ "chats.id as chatId", @@ -473,17 +479,18 @@ class ChatModel extends Model "chat_messages.created_at", "CONCAT(users.first_name,' ',users.last_name) as senderFullName", ]) - ->join("chat_messages","chat_messages.chat_id = chats.id","left") - ->join("users","users.id = chat_messages.sender_id","left") - ->where("chats.id",$chat_id) - ->where("chats.pedido_id",$pedido_id); + ->join("chat_messages", "chat_messages.chat_id = chats.id", "left") + ->join("users", "users.id = chat_messages.sender_id", "left") + ->where("chats.id", $chat_id) + ->where("chats.pedido_id", $pedido_id); $data["chatId"] = $chat_id; $data["messages"] = $query->get()->getResultObject(); $data["chatTitle"] = $this->find($chat_id)->title; $data["users"] = $this->getChatUsers($chat_id); return $data; } - public function getChatInternalHebraFactura($chat_id,$factura_id){ + public function getChatInternalHebraFactura($chat_id, $factura_id) + { $data = []; $query = $this->builder()->select([ "chats.id as chatId", @@ -492,10 +499,10 @@ class ChatModel extends Model "chat_messages.created_at", "CONCAT(users.first_name,' ',users.last_name) as senderFullName", ]) - ->join("chat_messages","chat_messages.chat_id = chats.id","left") - ->join("users","users.id = chat_messages.sender_id","left") - ->where("chats.id",$chat_id) - ->where("chats.factura_id",$factura_id); + ->join("chat_messages", "chat_messages.chat_id = chats.id", "left") + ->join("users", "users.id = chat_messages.sender_id", "left") + ->where("chats.id", $chat_id) + ->where("chats.factura_id", $factura_id); $data["chatId"] = $chat_id; $data["messages"] = $query->get()->getResultObject(); $data["chatTitle"] = $this->find($chat_id)->title; @@ -508,132 +515,131 @@ class ChatModel extends Model "users.username", "CONCAT(users.first_name,' ',users.last_name) as userFullName", ]) - ->join("chat_users","chat_users.chat_id = chats.id") - ->join("users","users.id = chat_users.user_id","left") - ->where("chats.id",$chat_id); + ->join("chat_users", "chat_users.chat_id = chats.id") + ->join("users", "users.id = chat_users.user_id", "left") + ->where("chats.id", $chat_id); return $query->get()->getResultObject(); } - public function getPresupuestoHebras($presupuesto_id) : array + public function getPresupuestoHebras($presupuesto_id): array { $data = []; $chats = $this->builder()->select("chats.id as chatId") - ->where("chats.chat_department_id",null) - ->where("chats.presupuesto_id",$presupuesto_id)->get()->getResultObject(); + ->where("chats.chat_department_id", null) + ->where("chats.presupuesto_id", $presupuesto_id)->get()->getResultObject(); foreach ($chats as $chat) { - $data[$chat->chatId] = $this->getChatInternalHebraPresupuesto($chat->chatId,$presupuesto_id); - } + $data[$chat->chatId] = $this->getChatInternalHebraPresupuesto($chat->chatId, $presupuesto_id); + } return $data; } - public function getPedidoHebras($pedido_id) : array + public function getPedidoHebras($pedido_id): array { $data = []; $chats = $this->builder()->select("chats.id as chatId") - ->where("chats.chat_department_id",null) - ->where("chats.pedido_id",$pedido_id)->get()->getResultObject(); + ->where("chats.chat_department_id", null) + ->where("chats.pedido_id", $pedido_id)->get()->getResultObject(); foreach ($chats as $chat) { - $data[$chat->chatId] = $this->getChatInternalHebraPedido($chat->chatId,$pedido_id); - } + $data[$chat->chatId] = $this->getChatInternalHebraPedido($chat->chatId, $pedido_id); + } return $data; } - public function getFacturaHebras($factura_id) : array + public function getFacturaHebras($factura_id): array { $data = []; $chats = $this->builder()->select("chats.id as chatId") - ->where("chats.chat_department_id",null) - ->where("chats.factura_id",$factura_id)->get()->getResultObject(); + ->where("chats.chat_department_id", null) + ->where("chats.factura_id", $factura_id)->get()->getResultObject(); foreach ($chats as $chat) { - $data[$chat->chatId] = $this->getChatInternalHebraFactura($chat->chatId,$factura_id); - } + $data[$chat->chatId] = $this->getChatInternalHebraFactura($chat->chatId, $factura_id); + } return $data; } - public function countUnreadMessagePresupuesto($presupuesto_id) : int|string + public function countUnreadMessagePresupuesto($presupuesto_id): int|string { return $this->builder()->select() - ->join("chat_messages","chat_messages.chat_id = chats.id","left") - ->join("chat_notifications","chat_notifications.chat_message_id = chat_messages.id","left") - ->where("chats.presupuesto_id",$presupuesto_id) - ->where("chat_notifications.viewed",false) - ->where("chat_notifications.user_id",auth()->user()->id) - ->countAllResults(); + ->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.viewed", false) + ->where("chat_notifications.user_id", auth()->user()->id) + ->countAllResults(); } - public function countUnreadMessagePedido($pedido_id) : int|string + public function countUnreadMessagePedido($pedido_id): int|string { return $this->builder()->select() - ->join("chat_messages","chat_messages.chat_id = chats.id","left") - ->join("chat_notifications","chat_notifications.chat_message_id = chat_messages.id","left") - ->where("chats.pedido_id",$pedido_id) - ->where("chat_notifications.viewed",false) - ->where("chat_notifications.user_id",auth()->user()->id) - ->countAllResults(); + ->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.viewed", false) + ->where("chat_notifications.user_id", auth()->user()->id) + ->countAllResults(); } - public function countUnreadMessageFactura($factura_id) : int|string + public function countUnreadMessageFactura($factura_id): int|string { return $this->builder()->select() - ->join("chat_messages","chat_messages.chat_id = chats.id","left") - ->join("chat_notifications","chat_notifications.chat_message_id = chat_messages.id","left") - ->where("chats.factura_id",$factura_id) - ->where("chat_notifications.viewed",false) - ->where("chat_notifications.user_id",auth()->user()->id)->countAllResults(); + ->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.viewed", false) + ->where("chat_notifications.user_id", auth()->user()->id)->countAllResults(); } - public function countUnreadMessageDirectos(int $chat_id) : int|string + public function countUnreadMessageDirectos(int $chat_id): int|string { return $this->builder()->select() - ->join("chat_messages","chat_messages.chat_id = chats.id","left") - ->join("chat_notifications","chat_notifications.chat_message_id = chat_messages.id","left") - ->where("chats.presupuesto_id",null) - ->where("chats.pedido_id",null) - ->where("chats.factura_id",null) - ->where("chats.chat_department_id",null) - ->where("chat_messages.chat_id",$chat_id) - ->where("chat_notifications.viewed",false) - ->where("chat_notifications.user_id",auth()->user()->id)->countAllResults(); + ->join("chat_messages", "chat_messages.chat_id = chats.id", "left") + ->join("chat_notifications", "chat_notifications.chat_message_id = chat_messages.id", "left") + ->where("chats.presupuesto_id", null) + ->where("chats.pedido_id", null) + ->where("chats.factura_id", null) + ->where("chats.chat_department_id", null) + ->where("chat_messages.chat_id", $chat_id) + ->where("chat_notifications.viewed", false) + ->where("chat_notifications.user_id", auth()->user()->id)->countAllResults(); } public function getSenderIdFromChatMessage(int $chat_id) { $first_message = $this->builder()->select() - ->join("chat_messages","chat_messages.chat_id = chats.id","left") - ->where("chats.presupuesto_id",null) - ->where("chats.pedido_id",null) - ->where("chats.factura_id",null) - ->where("chats.id",$chat_id) - ->where("chat_messages.receiver_id",auth()->user()->id)->get()->getFirstRow(); + ->join("chat_messages", "chat_messages.chat_id = chats.id", "left") + ->where("chats.presupuesto_id", null) + ->where("chats.pedido_id", null) + ->where("chats.factura_id", null) + ->where("chats.id", $chat_id) + ->where("chat_messages.receiver_id", auth()->user()->id)->get()->getFirstRow(); $userModel = model(UserModel::class); return $userModel->find($first_message->sender_id); } - public function getOpenChatCliente(int $user_id) : array + public function getOpenChatCliente(int $user_id): array { $q = $this->builder()->distinct()->select([ "users.*" ]) - ->join("chat_messages","chat_messages.chat_id = chats.id","left") - ->join("users","users.id = chat_messages.sender_id","left") - ->where("chat_messages.receiver_id",$user_id); + ->join("chat_messages", "chat_messages.chat_id = chats.id", "left") + ->join("users", "users.id = chat_messages.sender_id", "left") + ->where("chat_messages.receiver_id", $user_id); return $q->get()->getResultObject(); - } - public function getChatDepartmentMessagesCount(int $chat_id,int $chat_department_id) : int + public function getChatDepartmentMessagesCount(int $chat_id, int $chat_department_id): int { $q = $this->builder()->select([ "chat_messages.id" ]) - ->join("chat_messages","chat_messages.chat_id = chats.id",'left') - ->where("chats.chat_department_id",$chat_department_id) - ->where("chats.id",$chat_id) - ->countAllResults(); + ->join("chat_messages", "chat_messages.chat_id = chats.id", 'left') + ->where("chats.chat_department_id", $chat_department_id) + ->where("chats.id", $chat_id) + ->countAllResults(); return $q; - } - public function getChatFirstUser(int $chat_id) : object + public function getChatFirstUser(int $chat_id): object { - $q = $this->builder()->select(["users.id", - "CONCAT(users.first_name,' ',users.last_name) as userFullName", + $q = $this->builder()->select([ + "users.id", + "CONCAT(users.first_name,' ',users.last_name) as userFullName", ]) - ->join("chat_messages","chat_messages.chat_id = chats.id",'left') - ->join("users","users.id = chat_messages.sender_id","left") - ->where("chats.id",$chat_id) - ->where("chat_messages.deleted_at",null) - ->orderBy("chat_messages.created_at",'ASC'); + ->join("chat_messages", "chat_messages.chat_id = chats.id", 'left') + ->join("users", "users.id = chat_messages.sender_id", "left") + ->where("chats.id", $chat_id) + ->where("chat_messages.deleted_at", null) + ->orderBy("chat_messages.created_at", 'ASC'); return $q->get()->getFirstRow(); } /** @@ -643,24 +649,24 @@ 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_id, int $user_id): bool { $q = $this->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.id",$chat_id) - ->where("chat_notifications.user_id",$user_id) - ->where("chat_notifications.viewed",false); + ->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_notifications.viewed", false); $unread_messages_count = $q->countAllResults(); - if($unread_messages_count > 0){ + if ($unread_messages_count > 0) { $result = false; - }else{ + } else { $result = true; } return $result; } - public function getQueryDatatable(): BaseBuilder + public function getQueryDatatable(int $user_id): BaseBuilder { $query = $this->builder() ->select([ @@ -669,15 +675,17 @@ class ChatModel extends Model "chats.updated_at", "chats.title", ]) - ->where("chat_department_id",null) - ->where("pedido_id",null) - ->where("presupuesto_id",null) - ->where("factura_id",null) - ->where("title is NOT NULL",NULL,FALSE) + ->join("chat_users","chat_users.chat_id = chats.id","left") + ->where("chat_department_id", null) + ->where("pedido_id", null) + ->where("presupuesto_id", null) + ->where("factura_id", null) + ->where("title is NOT NULL", NULL, FALSE) + ->where("chat_users.user_id",$user_id) ->orderBy("created_at", "DESC"); return $query; } - public function createNewDirectChat(string $title,string $message,array $users) + public function createNewDirectChat(string $title, string $message, array $users) { $chatMessageModel = model(ChatMessageModel::class); $chatNotificationModel = model(ChatNotification::class); @@ -690,10 +698,10 @@ class ChatModel extends Model "receiver_id" => null, "message" => $message ]); - $chatUserModel->insert(["chat_id" => $chat_id,"user_id" => $auth_user_id]); + $chatUserModel->insert(["chat_id" => $chat_id, "user_id" => $auth_user_id]); foreach ($users as $key => $user_id) { - $chatUserModel->insert(["chat_id" => $chat_id,"user_id" => $user_id]); - $chatNotificationModel->insert(["chat_message_id" => $chat_message_id,"user_id" => $user_id]); + $chatUserModel->insert(["chat_id" => $chat_id, "user_id" => $user_id]); + $chatNotificationModel->insert(["chat_message_id" => $chat_message_id, "user_id" => $user_id]); } } /** @@ -707,16 +715,17 @@ class ChatModel extends Model * "users" => array * ] */ - public function getChatDirect(int $chat_id) : array + public function getChatDirect(int $chat_id): array { $auth_user = auth()->user()->id; $chat = $this->find($chat_id); + $chatNotificationModel = model(ChatNotification::class); $query = $this->builder()->select([ "users.*", ]) - ->join("chat_users","chat_users.chat_id = chats.id") - ->join("users","users.id = chat_users.user_id","left") - ->where("chats.id",$chat_id); + ->join("chat_users", "chat_users.chat_id = chats.id") + ->join("users", "users.id = chat_users.user_id", "left") + ->where("chats.id", $chat_id); $users = $query->get()->getResultObject(); $query = $this->builder()->select([ "chat_messages.*", @@ -724,17 +733,18 @@ class ChatModel extends Model "users.last_name as sender_last_name", ]) - ->join("chat_messages","chat_messages.chat_id = chats.id","left") - ->join("users","chat_messages.sender_id = users.id","left") - ->where("chats.id",$chat_id); + ->join("chat_messages", "chat_messages.chat_id = chats.id", "left") + ->join("users", "chat_messages.sender_id = users.id", "left") + ->where("chats.id", $chat_id); $messages = $query->get()->getResultObject(); $validatedMessages = []; foreach ($messages as $key => $message) { - if($auth_user == $message->sender_id){ + $message->viewed = $chatNotificationModel->isChatMessageViewed($message->id); + if ($auth_user == $message->sender_id) { $message->pos = 'right'; $validatedMessages[] = $message; - }else{ + } else { $message->pos = 'left'; $validatedMessages[] = $message; } @@ -746,4 +756,63 @@ class ChatModel extends Model ]; return $data; } + public function setAsViewedChatUserNotifications(int $chat_id, int $user_id) + { + $query = $this->builder() + ->select("chat_messages.id") + ->join('chat_messages', 'chat_messages.chat_id = chats.id', 'left') + ->where('chat_messages.chat_id', $chat_id) + ->get()->getResultObject(); + $chat_messages_ids = array_map(fn($q) => $q->id, $query); + + $this->db->table("chat_notifications") + ->where("user_id", $user_id) + ->whereIn("chat_message_id", $chat_messages_ids) + ->update(["viewed" => true]); + + } + public function setAsViewedChatUserMessages(int $chat_id, int $user_id) + { + $this->db->table("chat_messages") + ->where('chat_id', $chat_id) + ->where('sender_id !=', $user_id) + ->update(["viewed" => true]); + + } + public function setAsUnviewedChatUserNotifications(int $chat_id, int $user_id) + { + $query = $this->builder() + ->select("chat_messages.id") + ->join('chat_messages', 'chat_messages.chat_id = chats.id', 'left') + ->where('chat_messages.chat_id', $chat_id) + ->get()->getResultObject(); + $chat_messages_ids = array_map(fn($q) => $q->id, $query); + + $this->db->table("chat_notifications") + ->where("user_id", $user_id) + ->whereIn("chat_message_id", $chat_messages_ids) + ->update(["viewed" => false]); + } + + public function setAsUnviewedChatUserMessages(int $chat_id, int $user_id) + { + $this->db->table("chat_messages") + ->where('chat_id', $chat_id) + ->where('sender_id !=', $user_id) + ->update(["viewed" => false]); + + } + public function createNotificationsToNewChatUser($chat_id,$user_id) + { + $query = $this->builder() + ->select("chat_messages.id") + ->join('chat_messages', 'chat_messages.chat_id = chats.id', 'left') + ->where('chat_messages.chat_id', $chat_id) + ->get()->getResultObject(); + $chat_notifications = array_map(fn($q) => ["chat_message_id" => $q->id,"user_id" => $user_id], $query); + $chatNotificationModel = model(ChatNotification::class); + $chatNotificationModel->insertBatch($chat_notifications); + + + } } diff --git a/ci4/app/Models/ChatNotification.php b/ci4/app/Models/ChatNotification.php index 85f774d2..007f26c5 100644 --- a/ci4/app/Models/ChatNotification.php +++ b/ci4/app/Models/ChatNotification.php @@ -48,4 +48,15 @@ class ChatNotification extends Model protected $beforeDelete = []; protected $afterDelete = []; + public function isChatMessageViewed(int $chat_message_id) : bool + { + $status = false; + $count = $this->where("chat_message_id",$chat_message_id)->where("viewed",false)->countAllResults(); + if($count>0){ + $status = false; + }else{ + $status = true; + } + return $status; + } } diff --git a/ci4/app/Models/ChatUser.php b/ci4/app/Models/ChatUser.php index 4880c6e5..f51f989f 100644 --- a/ci4/app/Models/ChatUser.php +++ b/ci4/app/Models/ChatUser.php @@ -10,7 +10,7 @@ class ChatUser extends Model protected $primaryKey = 'id'; protected $useAutoIncrement = true; protected $returnType = 'array'; - protected $useSoftDeletes = false; + protected $useSoftDeletes = true; protected $protectFields = true; protected $allowedFields = [ "user_id", @@ -24,7 +24,7 @@ class ChatUser extends Model protected array $castHandlers = []; // Dates - protected $useTimestamps = false; + protected $useTimestamps = true; protected $dateFormat = 'datetime'; protected $createdField = 'created_at'; protected $updatedField = 'updated_at'; diff --git a/ci4/app/Views/themes/vuexy/components/chat_direct.php b/ci4/app/Views/themes/vuexy/components/chat_direct.php index dad29f75..8a33235f 100644 --- a/ci4/app/Views/themes/vuexy/components/chat_direct.php +++ b/ci4/app/Views/themes/vuexy/components/chat_direct.php @@ -1,4 +1,4 @@ -
    +
    @@ -11,9 +11,11 @@
    diff --git a/ci4/app/Views/themes/vuexy/components/chat_factura.php b/ci4/app/Views/themes/vuexy/components/chat_factura.php index 797d8aa0..b7b23601 100644 --- a/ci4/app/Views/themes/vuexy/components/chat_factura.php +++ b/ci4/app/Views/themes/vuexy/components/chat_factura.php @@ -1,4 +1,4 @@ -
    +
    @@ -30,6 +30,15 @@
      +
      +
      +
      +
      +
      +
      +
      +
      +
    • No Chats Found
    • @@ -76,6 +85,15 @@
    +
    +
    +
    +
    +
    +
    +
    +
    +
      @@ -112,6 +130,7 @@
    section('css') ?> + endSection() ?> diff --git a/ci4/app/Views/themes/vuexy/components/chat_general.php b/ci4/app/Views/themes/vuexy/components/chat_general.php index b35914ce..26f403b8 100644 --- a/ci4/app/Views/themes/vuexy/components/chat_general.php +++ b/ci4/app/Views/themes/vuexy/components/chat_general.php @@ -137,6 +137,7 @@
    section('css') ?> + endSection() ?> diff --git a/ci4/app/Views/themes/vuexy/components/chat_pedido.php b/ci4/app/Views/themes/vuexy/components/chat_pedido.php index 03768365..8f6c3f89 100644 --- a/ci4/app/Views/themes/vuexy/components/chat_pedido.php +++ b/ci4/app/Views/themes/vuexy/components/chat_pedido.php @@ -1,4 +1,4 @@ -
    +
    @@ -31,6 +31,7 @@
      +
    • No Chats Found
    • @@ -76,6 +77,15 @@
    +
    +
    +
    +
    +
    +
    +
    +
    +
      @@ -113,6 +123,7 @@ section('css') ?> + endSection() ?> diff --git a/ci4/app/Views/themes/vuexy/components/chat_presupuesto.php b/ci4/app/Views/themes/vuexy/components/chat_presupuesto.php index 5a9bb075..0645bb2a 100644 --- a/ci4/app/Views/themes/vuexy/components/chat_presupuesto.php +++ b/ci4/app/Views/themes/vuexy/components/chat_presupuesto.php @@ -1,4 +1,4 @@ -
      +
      @@ -30,6 +30,15 @@
        +
        +
        +
        +
        +
        +
        +
        +
        +
      • No Chats Found
      • @@ -76,9 +85,17 @@
      +
      +
      +
      +
      +
      +
      +
      +
      +
        -
      @@ -112,6 +129,7 @@
      section('css') ?> + endSection() ?> diff --git a/ci4/app/Views/themes/vuexy/components/modals/modalAddNewChatParticipant.php b/ci4/app/Views/themes/vuexy/components/modals/modalAddNewChatParticipant.php index 36e5c762..e2f5e080 100644 --- a/ci4/app/Views/themes/vuexy/components/modals/modalAddNewChatParticipant.php +++ b/ci4/app/Views/themes/vuexy/components/modals/modalAddNewChatParticipant.php @@ -13,13 +13,24 @@
      -
      +
      +
      +
      + +
      -
      +
      - ${row.totalMessages ?? 0} + ${row.totalMessages ?? 0} ` @@ -282,6 +290,8 @@ class Chat { _getChatDepartmentMessageCountError() { } _getChatMessage() { + + this.domItem.find(".chat-loader").removeClass("d-none") let ajax = new Ajax( `/chat/department/${this.chatType}/${this.chatDeparmentId}/${this.modelId}`, null, @@ -294,6 +304,7 @@ class Chat { ajax.get(); } _getChatMessageSuccess(data) { + this.domItem.find(".chat-loader").addClass("d-none") this.chatHistory.empty() this._setBtnDeparment() if (data.messages) { @@ -315,8 +326,8 @@ class Chat {

      ${chatMessage?.message}

      -
      -
      +
      +
      ${chatMessage?.user?.first_name + " " + chatMessage?.user?.last_name}
      @@ -337,7 +348,6 @@ class Chat { return chatItem } _addChatDirectMessages(chatMessage) { - console.log(chatMessage) let chatItem = `
    • @@ -346,8 +356,8 @@ class Chat {

      ${chatMessage?.message}

      -
      -
      +
      +
      ${chatMessage?.sender_first_name + " " + chatMessage?.sender_last_name}
      @@ -549,7 +559,7 @@ class Chat {

      ${contact.unreadMessages ? `${contact.unreadMessages}` : ""} + class="badge badge-center rounded-pill bg-secondary messages-unread-contact">${contact.unreadMessages}` : ""}
    • ` @@ -559,11 +569,10 @@ class Chat { } } _addParticipantToList(contact) { - let contactItem = ` -
    • - +
    • ` @@ -587,7 +596,6 @@ class Chat { } } _handleGetChatDirect() { - const ajax = new Ajax( `/chat/${this.chatType}/conversation/${this.modelId}`, null, @@ -597,10 +605,11 @@ class Chat { ) ajax.get() } + _handleGetChatDirectSuccess(response) { const { chat, users, messages } = response if (users.length > 0) { - users.map(c => this._addContactToList(c)) + users.map(c => this._addParticipantToList(c)) } if (messages.length > 0) { messages.map(m => this._addChatDirectMessages(m)) @@ -609,9 +618,29 @@ class Chat { this.domItem.find(".chat-loader").addClass("d-none") } _handleGetChatDirectError(error) { } + _handleReloadChatDirectMessages() { + const ajax = new Ajax( + `/chat/${this.chatType}/conversation/${this.modelId}`, + null, + null, + this._handleReloadChatDirectMessagesSuccess.bind(this), + this._handleReloadChatDirectMessagesError.bind(this) + ) + ajax.get() + } + _handleReloadChatDirectMessagesSuccess(response) { + const { chat, users, messages } = response + this.chatHistory.empty() + if (messages.length > 0) { + messages.map(m => this._addChatDirectMessages(m)) + } + this.domItem.find("#chat-direct-title").text(chat.title) + this.domItem.find(".chat-loader").addClass("d-none") + } + _handleReloadChatDirectMessagesError(error) { } _handleStoreChatDirectUsers() { - const data = { "users": this.selectParticipants.getVal() } + const data = { "users": this.selectParticipants.getVal() ,"notification" : this.checkboxNotificationMessage.prop("checked")} this.domItem.find(".chat-loader").removeClass("d-none") const ajax = new Ajax( @@ -648,12 +677,34 @@ class Chat { } } _handleStoreChatDirectMessageSuccess(response) { - let message = response - this._addChatDirectMessages(message) - this.messageInput.val("") + try { + let message = response + this._addChatDirectMessages(message) + this.messageInput.val("") + } catch (error) { + + } finally { + this.scrollbarChatHistory.update() + this.chatHistoryBody[0].scrollTop = this.scrollbarChatHistory.containerHeight + } + } _handleStoreChatDirectMessageError(error) { } + _handleUpdateChatMessagesUnread() { + const ajax = new Ajax( + `/chat/${this.chatType}/messages/unread/${this.modelId}`, + null, + null, + this._handleUpdateChatMessagesUnreadSuccess.bind(this), + this._handleUpdateChatMessagesUnreadError.bind(this) + ) + ajax.post() + } + _handleUpdateChatMessagesUnreadSuccess(){ + this._handleReloadChatDirectMessages(); + } + _handleUpdateChatMessagesUnreadError(){} @@ -693,7 +744,7 @@ export const showNotificationMessages = (dom) => {
      [${e.title}] ${e.chatDisplay}
      - ${numberOfMessages} + ${numberOfMessages} ` diff --git a/httpdocs/assets/js/safekat/pages/chatNotification.js b/httpdocs/assets/js/safekat/pages/chatNotification.js index f13d8591..5a9de17f 100644 --- a/httpdocs/assets/js/safekat/pages/chatNotification.js +++ b/httpdocs/assets/js/safekat/pages/chatNotification.js @@ -1,6 +1,10 @@ import {showNotificationMessages} from "../components/chat.js"; showNotificationMessages($("#chat-notification-list")) + +setInterval(() => { + showNotificationMessages($("#chat-notification-list")) +},10000) $("#message-notification-dropdown").on("click",(e) => { showNotificationMessages($("#chat-notification-list")) }) \ No newline at end of file diff --git a/httpdocs/assets/js/safekat/pages/configuracion/messages/messagePage.js b/httpdocs/assets/js/safekat/pages/configuracion/messages/messagePage.js index 5d2dbbdc..9c6399b1 100644 --- a/httpdocs/assets/js/safekat/pages/configuracion/messages/messagePage.js +++ b/httpdocs/assets/js/safekat/pages/configuracion/messages/messagePage.js @@ -16,7 +16,7 @@ class MessagePage { id: '0', text: "Seleccione un usuario" } - this.selectMessageUsers = new ClassSelect(this.selectUsers, '/chat/users/internal', this.selectPlaceholder, true) + this.selectMessageUsers = new ClassSelect(this.selectUsers, '/chat/users/all', this.selectPlaceholder, true) } init() { @@ -52,6 +52,7 @@ class MessagePage { this.alert.setHeadingTitle(response.message) this.alert.show() this.hideForm() + this.messageDatatable.datatable.ajax.reload() } handleSubmitNewMessageError(response) { const error = response.responseJSON From 2e767889ef88dd36d03ad5640fd0247666af690f Mon Sep 17 00:00:00 2001 From: amazuecos Date: Fri, 29 Nov 2024 22:05:50 +0100 Subject: [PATCH 3/3] message chat section --- ci4/app/Config/Routes.php | 11 ++ ci4/app/Controllers/Chat/ChatController.php | 146 ++++++++++++++++-- ci4/app/Language/es/Chat.php | 6 +- ci4/app/Models/Chat/ChatDeparmentModel.php | 19 ++- ci4/app/Models/Chat/ChatModel.php | 105 ++++++++++++- ci4/app/Services/MessageService.php | 14 ++ .../themes/vuexy/components/chat_factura.php | 12 +- .../themes/vuexy/components/chat_pedido.php | 4 +- .../vuexy/components/chat_presupuesto.php | 14 +- .../modals/modalNewDirectMessage.php | 8 +- .../components/tables/messages_table.php | 15 ++ .../vuexy/form/mensajes/mensajesView.php | 65 ++++---- .../form/mensajes/messageChatFactura.php | 30 ++++ .../form/mensajes/messageChatInternal.php | 28 ++++ .../vuexy/form/mensajes/messageChatPedido.php | 27 ++++ .../form/mensajes/messageChatPresupuesto.php | 27 ++++ .../Views/themes/vuexy/main/defaultlayout.php | 12 -- httpdocs/assets/js/safekat/components/chat.js | 7 +- .../datatables/MessagesDatatable.js | 73 +++++++-- .../configuracion/messages/messagePage.js | 51 +++++- .../pages/messages/facturaMessagePage.js | 9 ++ .../pages/messages/internalMessagePage.js | 10 ++ .../pages/messages/pedidoMessagePage.js | 9 ++ .../pages/messages/presupuestoMessagePage.js | 18 +++ 24 files changed, 615 insertions(+), 105 deletions(-) create mode 100644 ci4/app/Services/MessageService.php create mode 100644 ci4/app/Views/themes/vuexy/components/tables/messages_table.php create mode 100644 ci4/app/Views/themes/vuexy/form/mensajes/messageChatFactura.php create mode 100644 ci4/app/Views/themes/vuexy/form/mensajes/messageChatInternal.php create mode 100644 ci4/app/Views/themes/vuexy/form/mensajes/messageChatPedido.php create mode 100644 ci4/app/Views/themes/vuexy/form/mensajes/messageChatPresupuesto.php create mode 100644 httpdocs/assets/js/safekat/pages/messages/facturaMessagePage.js create mode 100644 httpdocs/assets/js/safekat/pages/messages/internalMessagePage.js create mode 100644 httpdocs/assets/js/safekat/pages/messages/pedidoMessagePage.js create mode 100644 httpdocs/assets/js/safekat/pages/messages/presupuestoMessagePage.js diff --git a/ci4/app/Config/Routes.php b/ci4/app/Config/Routes.php index 9e77842c..f3ff7612 100644 --- a/ci4/app/Config/Routes.php +++ b/ci4/app/Config/Routes.php @@ -763,12 +763,22 @@ $routes->group('mensajes', ['namespace' => 'App\Controllers\Mensajeria'], functi }); $routes->group('messages', ['namespace' => 'App\Controllers\Chat'], function ($routes) { $routes->get('datatable', 'ChatController::datatable_messages', ['as' => 'getDatatableMessages']); + $routes->get('datatable/presupuesto', 'ChatController::datatable_presupuesto_messages', ['as' => 'getDatatablePresupuestoMessages']); + $routes->get('datatable/pedido', 'ChatController::datatable_pedido_messages', ['as' => 'getDatatablePedidoMessages']); + $routes->get('datatable/factura', 'ChatController::datatable_factura_messages', ['as' => 'getDatatableFacturaMessages']); + $routes->post('direct', 'ChatController::store_new_direct_message', ['as' => 'storeNewDirectMessage']); + $routes->post('direct/client', 'ChatController::store_new_direct_message_client', ['as' => 'storeNewDirectMessageClient']); + }); $routes->group('chat', ['namespace' => 'App\Controllers\Chat'], function ($routes) { $routes->get('direct/(:num)', 'ChatController::get_chat_direct_view/$1', ['as' => 'getChatDirectView']); + $routes->get('presupuesto/(:num)', 'ChatController::get_chat_presupuesto_view/$1', ['as' => 'getChatPresupuestoView']); + $routes->get('pedido/(:num)', 'ChatController::get_chat_pedido_view/$1', ['as' => 'getChatPedidoView']); + $routes->get('factura/(:num)', 'ChatController::get_chat_factura_view/$1', ['as' => 'getChatFacturaView']); + $routes->get('direct/conversation/(:num)', 'ChatController::get_chat_direct/$1', ['as' => 'getChatDirect']); $routes->get('direct/users/select/(:num)', 'ChatController::get_chat_direct_select_users/$1', ['as' => 'getChatDirectSelectUsers']); $routes->get('direct/users/(:num)', 'ChatController::get_chat_direct_users', ['as' => 'getChatDirectUsers']); @@ -779,6 +789,7 @@ $routes->group('chat', ['namespace' => 'App\Controllers\Chat'], function ($route $routes->get('departments', 'ChatController::get_chat_departments', ['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']); $routes->get('department/factura/(:num)/(:num)', 'ChatController::get_chat_factura/$1/$2', ['as' => 'getChatFactura']); diff --git a/ci4/app/Controllers/Chat/ChatController.php b/ci4/app/Controllers/Chat/ChatController.php index 1712a73e..3526b6da 100644 --- a/ci4/app/Controllers/Chat/ChatController.php +++ b/ci4/app/Controllers/Chat/ChatController.php @@ -29,7 +29,7 @@ class ChatController extends BaseController protected ClienteModel $clienteModel; protected ChatUser $chatUserModel; protected ChatNotification $chatNotificationModel; - + protected array $viewData; protected static $viewPath = 'themes/vuexy/form/mensajes/'; @@ -57,6 +57,10 @@ class ChatController extends BaseController $data = $this->chatDeparmentModel->getChatDepartments(); return $this->response->setJSON($data); } + public function get_chat_department_select(){ + $query = $this->chatDeparmentModel->getChatDepartmentSelect($this->request->getGet("q")); + return $this->response->setJSON($query->get()->getResultObject()); + } public function get_chat_presupuesto(int $chat_department_id, int $presupuesto_id) { @@ -122,6 +126,62 @@ class ChatController extends BaseController return view(static::$viewPath . 'messageChat', $this->viewData); } + public function get_chat_presupuesto_view($chat_id) + { + $chat = $this->chatModel->find($chat_id); + $this->viewData['breadcrumb'] = [ + ['title' => lang("Chat.chat"), 'route' => route_to("mensajeriaView"), 'active' => false], + ['title' => $chat->title, 'route' => 'javascript:void(0);', 'active' => true] + ]; + $this->viewData["modelId"] = $chat->presupuesto_id; + $this->viewData["type"] = "presupuesto"; + $auth_user = auth()->user(); + $this->chatModel->setAsViewedChatUserNotifications($chat_id, $auth_user->id); + $this->chatModel->setAsUnviewedChatUserMessages($chat_id, $auth_user->id); + + if($chat->chat_department_id){ + return view(static::$viewPath . 'messageChatPresupuesto', $this->viewData); + }else{ + return view(static::$viewPath . 'messageChatInternal', $this->viewData); + } + } + public function get_chat_pedido_view($chat_id) + { + $chat = $this->chatModel->find($chat_id); + $this->viewData['breadcrumb'] = [ + ['title' => lang("Chat.chat"), 'route' => route_to("mensajeriaView"), 'active' => false], + ['title' => $chat->title, 'route' => 'javascript:void(0);', 'active' => true] + ]; + $this->viewData["modelId"] = $chat->pedido_id; + $this->viewData["type"] = "pedido"; + $auth_user = auth()->user(); + $this->chatModel->setAsViewedChatUserNotifications($chat_id, $auth_user->id); + $this->chatModel->setAsUnviewedChatUserMessages($chat_id, $auth_user->id); + if($chat->chat_department_id ){ + return view(static::$viewPath . 'messageChatPedido', $this->viewData); + }else{ + return view(static::$viewPath . 'messageChatInternal', $this->viewData); + } + } + public function get_chat_factura_view($chat_id) + { + $chat = $this->chatModel->find($chat_id); + $this->viewData['breadcrumb'] = [ + ['title' => lang("Chat.chat"), 'route' => route_to("mensajeriaView"), 'active' => false], + ['title' => $chat->title, 'route' => 'javascript:void(0);', 'active' => true] + ]; + $this->viewData["modelId"] = $chat->factura_id; + $this->viewData["type"] = "factura"; + $auth_user = auth()->user(); + $this->chatModel->setAsViewedChatUserNotifications($chat_id, $auth_user->id); + $this->chatModel->setAsUnviewedChatUserMessages($chat_id, $auth_user->id); + + if($chat->chat_department_id){ + return view(static::$viewPath . 'messageChatFactura', $this->viewData); + }else{ + return view(static::$viewPath . 'messageChatInternal', $this->viewData); + } + } public function get_chat(int $chat_id) { @@ -144,8 +204,8 @@ class ChatController extends BaseController $dataResponse = $this->chatMessageModel->find($chat_message_id); $chatDepartmentUsers = $this->chatDeparmentModel->getChatDepartmentUsers($data["chat_department_id"]); foreach ($chatDepartmentUsers as $user) { - if($user->id != auth()->user()->id){ - $this->chatNotificationModel->insert(["chat_message_id" => $chat_message_id,"user_id"=> $user->id]); + if ($user->id != auth()->user()->id) { + $this->chatNotificationModel->insert(["chat_message_id" => $chat_message_id, "user_id" => $user->id]); } } return $this->response->setJSON($dataResponse); @@ -165,8 +225,8 @@ class ChatController extends BaseController $dataResponse = $this->chatMessageModel->find($chat_message_id); $chatDepartmentUsers = $this->chatDeparmentModel->getChatDepartmentUsers($data["chat_department_id"]); foreach ($chatDepartmentUsers as $user) { - if($user->id != auth()->user()->id){ - $this->chatNotificationModel->insert(["chat_message_id" => $chat_message_id,"user_id"=> $user->id]); + if ($user->id != auth()->user()->id) { + $this->chatNotificationModel->insert(["chat_message_id" => $chat_message_id, "user_id" => $user->id]); } } return $this->response->setJSON($dataResponse); @@ -186,8 +246,8 @@ class ChatController extends BaseController $dataResponse = $this->chatMessageModel->find($chat_message_id); $chatDepartmentUsers = $this->chatDeparmentModel->getChatDepartmentUsers($data["chat_department_id"]); foreach ($chatDepartmentUsers as $user) { - if($user->id != auth()->user()->id){ - $this->chatNotificationModel->insert(["chat_message_id" => $chat_message_id,"user_id"=> $user->id]); + if ($user->id != auth()->user()->id) { + $this->chatNotificationModel->insert(["chat_message_id" => $chat_message_id, "user_id" => $user->id]); } } return $this->response->setJSON($dataResponse); @@ -338,6 +398,7 @@ class ChatController extends BaseController } public function store_hebra_presupuesto() { + $auth_user = auth()->user(); $bodyData = $this->request->getPost(); $chat_id = $this->chatModel->insert([ "presupuesto_id" => $bodyData["modelId"], @@ -346,9 +407,10 @@ class ChatController extends BaseController $chatMessageId = $this->chatMessageModel->insert([ "chat_id" => $chat_id, "message" => $bodyData["message"], - "sender_id" => auth()->user()->id + "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) { @@ -494,7 +556,45 @@ class ChatController extends BaseController ->edit('updated_at', fn($q) => 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) => $q->id) + ->add("action", fn($q) => ["type" => "direct","modelId" => $q->id]) + ->toJson(true); + } + public function datatable_presupuesto_messages() + { + $auth_user_id = auth()->user()->id; + $query = $this->chatModel->getQueryDatatableMessagePresupuesto($auth_user_id); + 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]) + ->toJson(true); + } + public function datatable_pedido_messages() + { + $auth_user_id = auth()->user()->id; + $query = $this->chatModel->getQueryDatatableMessagePedido($auth_user_id); + 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]) + + ->toJson(true); + } + public function datatable_factura_messages() + { + $auth_user_id = auth()->user()->id; + $query = $this->chatModel->getQueryDatatableMessageFactura($auth_user_id); + 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]) + ->toJson(true); } public function store_new_direct_message() @@ -516,6 +616,28 @@ class ChatController extends BaseController $this->chatModel->createNewDirectChat(...$bodyData); return $this->response->setJSON(["message" => lang("Chat.new_message_ok"), "status" => true]); } + public function store_new_direct_message_client() + { + $bodyData = $this->request->getPost(); + $rules = [ + "title" => "required|string", + "message" => "required|string", + "chat_department_id" => "required", + + ]; + if (!$this->validate($rules)) { + return $this->response->setStatusCode(400)->setJSON([ + 'message' => lang('App.global_alert_save_error'), + 'status' => 'error', + 'errors' => $this->validator->getErrors(), + ]); + } + $users = $this->chatDeparmentModel->getChatDepartmentUsers($bodyData["chat_department_id"]); + $bodyData["users"] = array_map(fn($q) => $q->id,$users); + dd(1); + $this->chatModel->createNewDirectChat(...$bodyData); + return $this->response->setJSON(["message" => lang("Chat.new_message_ok"), "status" => true]); + } public function get_chat_direct($chat_id) { $chatData = $this->chatModel->getChatDirect($chat_id); @@ -570,9 +692,9 @@ class ChatController extends BaseController $message = $this->chatMessageModel->get_chat_message($chat_message_id); return $this->response->setJSON($message); } - public function update_chat_direct_message_unread($chat_id){ - $this->chatModel->setAsUnviewedChatUserNotifications($chat_id,auth()->user()->id); + public function update_chat_direct_message_unread($chat_id) + { + $this->chatModel->setAsUnviewedChatUserNotifications($chat_id, auth()->user()->id); return $this->response->setJSON(["message" => "ok", "status" => true]); } - } diff --git a/ci4/app/Language/es/Chat.php b/ci4/app/Language/es/Chat.php index 9900a19c..1aca873e 100644 --- a/ci4/app/Language/es/Chat.php +++ b/ci4/app/Language/es/Chat.php @@ -3,6 +3,7 @@ return [ "chat" => "Mensajería", "messages" => "Mensajes", + "message" => "Mensaje", "modal" => [ "new_hebra" => "Nuevo hilo", "title" => "Título", @@ -21,10 +22,11 @@ return [ ], "new_message_ok" => "Mensaje enviado correctamente", "participants" => "Participantes", + "choose_department" => "Elige un departamento", "new_participant" => "Añadir nuevos participantes", "write_message_placeholder" => "Escriba aquí su mensaje...", "add_notification" => "Notificación", "check_as_unviewed" => "Marcar como no leídos", - "add_notification_message" => "Envía a los usuarios añadidos una notificación con los mensajes presentes en el chat." - + "add_notification_message" => "Envía a los usuarios añadidos una notificación con los mensajes presentes en el chat.", + "chat_title_presupuesto" => 'Presupuesto[{title,string,0}][{id}]' ]; \ No newline at end of file diff --git a/ci4/app/Models/Chat/ChatDeparmentModel.php b/ci4/app/Models/Chat/ChatDeparmentModel.php index 8f60babe..1681f814 100644 --- a/ci4/app/Models/Chat/ChatDeparmentModel.php +++ b/ci4/app/Models/Chat/ChatDeparmentModel.php @@ -10,7 +10,7 @@ class ChatDeparmentModel extends Model protected $table = 'chat_departments'; protected $primaryKey = 'id'; protected $useAutoIncrement = true; - protected $returnType = 'array'; + protected $returnType = 'object'; protected $useSoftDeletes = false; protected $protectFields = true; protected $allowedFields = [ @@ -126,4 +126,21 @@ class ChatDeparmentModel extends Model ->get()->getResultObject(); return $result; } + public function getDisplay(int $chat_deparment_id) : string + { + return $this->find($chat_deparment_id)->display; + } + public function getChatDepartmentSelect(string $query = null) + { + $q = $this->builder()->select([ + "id", + "display as name", + "description" + ]); + if($query){ + $q->orLike("display",$query) + ->orLike("name",$query); + } + return $q; + } } diff --git a/ci4/app/Models/Chat/ChatModel.php b/ci4/app/Models/Chat/ChatModel.php index 1862f609..78628011 100644 --- a/ci4/app/Models/Chat/ChatModel.php +++ b/ci4/app/Models/Chat/ChatModel.php @@ -88,7 +88,11 @@ class ChatModel extends Model public function createChatPresupuesto(int $chat_department_id, int $presupuesto_id): int { + $model = model(PresupuestoModel::class); + $chatDeparmentModel = model(ChatDeparmentModel::class); + $presupuesto = $model->find($presupuesto_id); return $this->insert([ + "title" => $presupuesto->titulo."[".$chatDeparmentModel->getDisplay($chat_department_id)."]", "presupuesto_id" => $presupuesto_id, "chat_department_id" => $chat_department_id ]); @@ -96,7 +100,11 @@ class ChatModel extends Model public function createChatPedido(int $chat_department_id, int $pedido_id): int { + $model = model(PedidoModel::class); + $chatDeparmentModel = model(ChatDeparmentModel::class); + $pedido = $model->getPedidoClientePresupuesto($pedido_id); return $this->insert([ + "title" => "Pedido ".$pedido->titulo."[".$chatDeparmentModel->getDisplay($chat_department_id)."]", "pedido_id" => $pedido_id, "chat_department_id" => $chat_department_id ]); @@ -104,7 +112,12 @@ class ChatModel extends Model public function createChatFactura(int $chat_department_id, int $factura_id): int { + + $model = model(FacturaModel::class); + $chatDeparmentModel = model(ChatDeparmentModel::class); + $factura = $model->find($factura_id); return $this->insert([ + "title" => "Factura ".$factura->numero."[".$chatDeparmentModel->getDisplay($chat_department_id)."]", "factura_id" => $factura_id, "chat_department_id" => $chat_department_id ]); @@ -370,6 +383,7 @@ class ChatModel extends Model $q = $this->db->table("chats") ->select([ "chats.id as chatId", + "chats.chat_department_id as chatDepartmentId", "chats.pedido_id as pedidoId", "chats.presupuesto_id as presupuestoId", "chats.factura_id as facturaId", @@ -390,10 +404,13 @@ class ChatModel extends Model $row->uri = "/presupuestocliente/edit/" . $row->presupuestoId; }else{ $row->uri = "/presupuestoadmin/edit/" . $row->presupuestoId; - } $row->title = $row->presupuestoId; - $row->chatDisplay = $row->model->titulo; + if($row->chatDepartmentId){ + $row->chatDisplay = $row->model->titulo; + }else{ + $row->chatDisplay .="[INTERNAL]"; + } $row->avatar = "PRE"; $row->unreadMessages = $this->countUnreadMessagePresupuesto($row->presupuestoId); $rows_new[] = $row; @@ -401,6 +418,9 @@ class ChatModel extends Model $row->model = $pedidoModel->find($row->pedidoId); $row->uri = "/pedidos/edit/" . $row->pedidoId; $row->title = $row->pedidoId; + if($row->chatDepartmentId){ + $row->chatDisplay .= "[INTERNAL]"; + } $row->avatar = "P"; $row->unreadMessages = $this->countUnreadMessagePedido($row->pedidoId); $rows_new[] = $row; @@ -408,6 +428,9 @@ class ChatModel extends Model $row->model = $facturaModel->find($row->facturaId); $row->uri = "/facturas/edit/" . $row->facturaId; $row->avatar = "F"; + if($row->chatDepartmentId){ + $row->chatDisplay .= "[INTERNAL]"; + } $row->title = $row->facturaId; $row->unreadMessages = $this->countUnreadMessageFactura($row->facturaId); $rows_new[] = $row; @@ -465,7 +488,8 @@ class ChatModel extends Model ->where("chats.presupuesto_id", $presupuesto_id); $data["chatId"] = $chat_id; $data["messages"] = $query->get()->getResultObject(); - $data["chatTitle"] = $this->find($chat_id)->title; + $data["chatTitle"] = "Presupuesto"."[".$presupuesto_id."] - "; + $data["chatTitle"].= $this->find($chat_id)->title; $data["users"] = $this->getChatUsers($chat_id); return $data; } @@ -485,7 +509,8 @@ class ChatModel extends Model ->where("chats.pedido_id", $pedido_id); $data["chatId"] = $chat_id; $data["messages"] = $query->get()->getResultObject(); - $data["chatTitle"] = $this->find($chat_id)->title; + $data["chatTitle"] = "Pedido"."[".$pedido_id."] - "; + $data["chatTitle"].= $this->find($chat_id)->title; $data["users"] = $this->getChatUsers($chat_id); return $data; } @@ -505,7 +530,8 @@ class ChatModel extends Model ->where("chats.factura_id", $factura_id); $data["chatId"] = $chat_id; $data["messages"] = $query->get()->getResultObject(); - $data["chatTitle"] = $this->find($chat_id)->title; + $data["chatTitle"] = "Factura"."[".$factura_id."] - "; + $data["chatTitle"].= $this->find($chat_id)->title; $data["users"] = $this->getChatUsers($chat_id); return $data; } @@ -680,9 +706,73 @@ class ChatModel extends Model ->where("pedido_id", null) ->where("presupuesto_id", null) ->where("factura_id", null) - ->where("title is NOT NULL", NULL, FALSE) ->where("chat_users.user_id",$user_id) - ->orderBy("created_at", "DESC"); + ->orderBy("created_at", "DESC") + ->groupBy("chats.id"); + + return $query; + } + public function getQueryDatatableMessagePresupuesto(int $user_id): BaseBuilder + { + $query = $this->builder() + ->select([ + "chats.id", + "chats.created_at", + "chats.updated_at", + "chats.title", + ]) + ->join("chat_users","chats.id = chat_users.chat_id","left") + ->join("presupuestos","presupuestos.id = chats.presupuesto_id",'left') + ->where("presupuesto_id is NOT NULL", NULL, FALSE) + ->groupBy("chats.id"); + if(auth()->user()->inGroup("admin") == false){ + $query->where('presupuestos.cliente_id',auth()->user()->cliente_id) + ->where("chat_department_id is NOT NULL",NULL,FALSE); + } + $query->orderBy("created_at", "DESC"); + return $query; + } + public function getQueryDatatableMessagePedido(int $user_id): BaseBuilder + { + $query = $this->builder() + ->select([ + "chats.id", + "chats.created_at", + "chats.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("presupuestos","presupuestos.id = pedidos_linea.presupuesto_id",'left') + ->where("chats.pedido_id is NOT NULL", NULL, FALSE) + ->groupBy("chats.id"); + if(auth()->user()->inGroup("admin") == false){ + $query->where('presupuestos.cliente_id',auth()->user()->cliente_id) + ->where("chat_department_id is NOT NULL",NULL,FALSE); + } + $query->orderBy("created_at", "DESC"); + return $query; + } + public function getQueryDatatableMessageFactura(int $user_id): BaseBuilder + { + $query = $this->builder() + ->select([ + "chats.id", + "chats.created_at", + "chats.updated_at", + "chats.title", + ]) + ->join("chat_users","chat_users.chat_id = chats.id","left") + ->join("facturas","facturas.id = chats.factura_id","left") + ->where("chats.factura_id is NOT NULL", NULL, FALSE) + ->groupBy("chats.id"); + 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); + } + } + $query->orderBy("created_at", "DESC"); return $query; } public function createNewDirectChat(string $title, string $message, array $users) @@ -704,6 +794,7 @@ class ChatModel extends Model $chatNotificationModel->insert(["chat_message_id" => $chat_message_id, "user_id" => $user_id]); } } + /** * Obtain users and messages from `chat_id` * diff --git a/ci4/app/Services/MessageService.php b/ci4/app/Services/MessageService.php new file mode 100644 index 00000000..8202257d --- /dev/null +++ b/ci4/app/Services/MessageService.php @@ -0,0 +1,14 @@ +
        -
        -
        -
        -
        -
        -
        -
        +
        -
      • -
        No Chats Found
        -
      • +
      diff --git a/ci4/app/Views/themes/vuexy/components/chat_pedido.php b/ci4/app/Views/themes/vuexy/components/chat_pedido.php index 8f6c3f89..64cb9c3c 100644 --- a/ci4/app/Views/themes/vuexy/components/chat_pedido.php +++ b/ci4/app/Views/themes/vuexy/components/chat_pedido.php @@ -32,9 +32,7 @@
        -
      • -
        No Chats Found
        -
      • +
      diff --git a/ci4/app/Views/themes/vuexy/components/chat_presupuesto.php b/ci4/app/Views/themes/vuexy/components/chat_presupuesto.php index 0645bb2a..76c30928 100644 --- a/ci4/app/Views/themes/vuexy/components/chat_presupuesto.php +++ b/ci4/app/Views/themes/vuexy/components/chat_presupuesto.php @@ -30,18 +30,8 @@
        -
        -
        -
        -
        -
        -
        -
        -
        -
        -
      • -
        No Chats Found
        -
      • + +
      diff --git a/ci4/app/Views/themes/vuexy/components/modals/modalNewDirectMessage.php b/ci4/app/Views/themes/vuexy/components/modals/modalNewDirectMessage.php index b0f416c5..87709867 100644 --- a/ci4/app/Views/themes/vuexy/components/modals/modalNewDirectMessage.php +++ b/ci4/app/Views/themes/vuexy/components/modals/modalNewDirectMessage.php @@ -28,13 +28,19 @@
      + +
    diff --git a/ci4/app/Views/themes/vuexy/components/tables/messages_table.php b/ci4/app/Views/themes/vuexy/components/tables/messages_table.php new file mode 100644 index 00000000..22456941 --- /dev/null +++ b/ci4/app/Views/themes/vuexy/components/tables/messages_table.php @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + +
    \ No newline at end of file diff --git a/ci4/app/Views/themes/vuexy/form/mensajes/mensajesView.php b/ci4/app/Views/themes/vuexy/form/mensajes/mensajesView.php index db220a0c..2288d375 100644 --- a/ci4/app/Views/themes/vuexy/form/mensajes/mensajesView.php +++ b/ci4/app/Views/themes/vuexy/form/mensajes/mensajesView.php @@ -8,43 +8,48 @@
    + - +
    -
    diff --git a/ci4/app/Views/themes/vuexy/form/mensajes/messageChatFactura.php b/ci4/app/Views/themes/vuexy/form/mensajes/messageChatFactura.php new file mode 100644 index 00000000..ff05265c --- /dev/null +++ b/ci4/app/Views/themes/vuexy/form/mensajes/messageChatFactura.php @@ -0,0 +1,30 @@ +include('themes/_commonPartialsBs/select2bs5') ?> +include('themes/_commonPartialsBs/datatables') ?> +include('themes/_commonPartialsBs/_confirm2delete') ?> +extend('themes/vuexy/main/defaultlayout') ?> + + +section('content'); ?> + +
    + + + $modelId]) ?> + +
    + + +endSection() ?> +section('css') ?> + + + + + +endSection() ?> +section("additionalExternalJs") ?> + + + + +endSection() ?> \ No newline at end of file diff --git a/ci4/app/Views/themes/vuexy/form/mensajes/messageChatInternal.php b/ci4/app/Views/themes/vuexy/form/mensajes/messageChatInternal.php new file mode 100644 index 00000000..0152bb79 --- /dev/null +++ b/ci4/app/Views/themes/vuexy/form/mensajes/messageChatInternal.php @@ -0,0 +1,28 @@ +include('themes/_commonPartialsBs/select2bs5') ?> +include('themes/_commonPartialsBs/datatables') ?> +include('themes/_commonPartialsBs/_confirm2delete') ?> +extend('themes/vuexy/main/defaultlayout') ?> + + +section('content'); ?> + +
    + $modelId, "type" => $type]) ?> +
    + + +endSection() ?> +section('css') ?> + + + + + +endSection() ?> +section("additionalExternalJs") ?> + + + + + +endSection() ?> diff --git a/ci4/app/Views/themes/vuexy/form/mensajes/messageChatPedido.php b/ci4/app/Views/themes/vuexy/form/mensajes/messageChatPedido.php new file mode 100644 index 00000000..db0e52d1 --- /dev/null +++ b/ci4/app/Views/themes/vuexy/form/mensajes/messageChatPedido.php @@ -0,0 +1,27 @@ +include('themes/_commonPartialsBs/select2bs5') ?> +include('themes/_commonPartialsBs/datatables') ?> +include('themes/_commonPartialsBs/_confirm2delete') ?> +extend('themes/vuexy/main/defaultlayout') ?> + + +section('content'); ?> + +
    + $modelId]) ?> +
    + + +endSection() ?> +section('css') ?> + + + + + +endSection() ?> +section("additionalExternalJs") ?> + + + + +endSection() ?> \ No newline at end of file diff --git a/ci4/app/Views/themes/vuexy/form/mensajes/messageChatPresupuesto.php b/ci4/app/Views/themes/vuexy/form/mensajes/messageChatPresupuesto.php new file mode 100644 index 00000000..8eda11d4 --- /dev/null +++ b/ci4/app/Views/themes/vuexy/form/mensajes/messageChatPresupuesto.php @@ -0,0 +1,27 @@ +include('themes/_commonPartialsBs/select2bs5') ?> +include('themes/_commonPartialsBs/datatables') ?> +include('themes/_commonPartialsBs/_confirm2delete') ?> +extend('themes/vuexy/main/defaultlayout') ?> + + +section('content'); ?> + +
    + $modelId]) ?> +
    + + +endSection() ?> +section('css') ?> + + + + + +endSection() ?> +section("additionalExternalJs") ?> + + + + +endSection() ?> \ No newline at end of file diff --git a/ci4/app/Views/themes/vuexy/main/defaultlayout.php b/ci4/app/Views/themes/vuexy/main/defaultlayout.php index fb1927cd..40358745 100644 --- a/ci4/app/Views/themes/vuexy/main/defaultlayout.php +++ b/ci4/app/Views/themes/vuexy/main/defaultlayout.php @@ -147,18 +147,6 @@ $picture = "/assets/img/default-user.png"; - -