diff --git a/ci4/app/Config/Routes.php b/ci4/app/Config/Routes.php index 2ce703a0..a8339e44 100644 --- a/ci4/app/Config/Routes.php +++ b/ci4/app/Config/Routes.php @@ -761,9 +761,36 @@ $routes->group('mensajes', ['namespace' => 'App\Controllers\Mensajeria'], functi $routes->get('delete/(:num)', 'TarifaAcabados::delete/$1', ['as' => 'tarifaAcabadoDelete']); $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->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']); + $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']); + $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']); @@ -780,6 +807,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 93c5bb58..3526b6da 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 { @@ -26,8 +29,8 @@ class ChatController extends BaseController protected ClienteModel $clienteModel; protected ChatUser $chatUserModel; protected ChatNotification $chatNotificationModel; - - + protected array $viewData; + protected static $viewPath = 'themes/vuexy/form/mensajes/'; public function initController( @@ -46,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() @@ -56,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) { @@ -86,7 +91,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); @@ -108,6 +112,76 @@ 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; + $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); + } + 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) { @@ -128,6 +202,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() @@ -143,6 +223,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() @@ -158,6 +244,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() @@ -178,7 +270,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); } @@ -187,11 +279,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); @@ -275,7 +367,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")) @@ -287,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"], @@ -295,17 +407,19 @@ 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"])){ - $chatUserData = array_map(fn($x) => ["user_id" => $x,"chat_id" => $chat_id],$bodyData["users"]); + if (isset($bodyData["users"])) { + $bodyData["users"][] = $auth_user->id; + $chatUserData = array_map(fn($x) => ["user_id" => $x, "chat_id" => $chat_id], $bodyData["users"]); $this->chatUserModel->insertBatch($chatUserData); foreach ($bodyData["users"] as $userId) { $this->chatNotificationModel->insert( - ["chat_message_id" => $chatMessageId,"user_id" => $userId]); + ["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() @@ -321,15 +435,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() @@ -344,89 +459,242 @@ 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() + { + $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) => ["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() + { + $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 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); + 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("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 = []; + 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]); + } + public function store_chat_direct_message(int $chat_id) + { + $bodyData = $this->request->getPost(); + $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); + } + 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/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..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", @@ -10,5 +11,22 @@ 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", + "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.", + "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/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..78628011 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 { @@ -80,35 +81,48 @@ 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(); } 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 ]); } - 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([ + $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 ]); } - public function createChatFactura(int $chat_department_id, int $factura_id) : int + 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 ]); } - public function createChatSingle() : int + public function createChatSingle(): int { return $this->insert(["chat_department_id" => null]); } @@ -137,82 +151,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(); @@ -221,32 +235,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(); @@ -255,32 +269,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(); @@ -288,15 +302,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() @@ -308,54 +322,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() { @@ -366,43 +381,56 @@ 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.chat_department_id as chatDepartmentId", + "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; + if($row->chatDepartmentId){ + $row->chatDisplay = $row->model->titulo; + }else{ + $row->chatDisplay .="[INTERNAL]"; + } $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; + if($row->chatDepartmentId){ + $row->chatDisplay .= "[INTERNAL]"; + } $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"; + if($row->chatDepartmentId){ + $row->chatDisplay .= "[INTERNAL]"; + } $row->title = $row->facturaId; $row->unreadMessages = $this->countUnreadMessageFactura($row->facturaId); $rows_new[] = $row; @@ -410,39 +438,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 = []; @@ -453,17 +482,19 @@ 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["chatTitle"] = "Presupuesto"."[".$presupuesto_id."] - "; + $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", @@ -472,17 +503,19 @@ 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["chatTitle"] = "Pedido"."[".$pedido_id."] - "; + $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", @@ -491,13 +524,14 @@ 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; + $data["chatTitle"] = "Factura"."[".$factura_id."] - "; + $data["chatTitle"].= $this->find($chat_id)->title; $data["users"] = $this->getChatUsers($chat_id); return $data; } @@ -507,121 +541,369 @@ 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 + { + $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(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") + ->where("chat_department_id", null) + ->where("pedido_id", null) + ->where("presupuesto_id", null) + ->where("factura_id", null) + ->where("chat_users.user_id",$user_id) + ->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) + { + $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); + $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); + $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) { + $message->viewed = $chatNotificationModel->isChatMessageViewed($message->id); + 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; + } + 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 fdbc6e2b..007f26c5 100644 --- a/ci4/app/Models/ChatNotification.php +++ b/ci4/app/Models/ChatNotification.php @@ -47,4 +47,16 @@ class ChatNotification extends Model protected $afterFind = []; 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 9e92163c..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'; @@ -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/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 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..8a33235f --- /dev/null +++ b/ci4/app/Views/themes/vuexy/components/chat_direct.php @@ -0,0 +1,153 @@ +
+
+ +
+ + + +
+ + + +
+ + + +
+
+
+
+
+ +

+
+
+ +
+
+
+ +
+
+
+
+
+
+
+
+
+
+
+
+
+
    + + +
+
+ + +
+ + +
+
+
+
+ +
+ + +section('css') ?> + + +endSection() ?> + + + +section("additionalExternalJs") ?> + + +endSection() ?> \ No newline at end of file diff --git a/ci4/app/Views/themes/vuexy/components/chat_factura.php b/ci4/app/Views/themes/vuexy/components/chat_factura.php index 797d8aa0..f3e13cdf 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,9 +30,10 @@
    -
  • -
    No Chats Found
    -
  • +
    + +
    +
@@ -76,6 +77,15 @@
+
+
+
+
+
+
+
+
+
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..64cb9c3c 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,9 +31,8 @@
    -
  • -
    No Chats Found
    -
  • + +
@@ -76,6 +75,15 @@
+
+
+
+
+
+
+
+
+