messages chat view

This commit is contained in:
amazuecos
2024-11-28 16:07:11 +01:00
parent 093aa42e67
commit c1aecb43f2
16 changed files with 661 additions and 396 deletions

View File

@ -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->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->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/(: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', '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('contact/(:num)/messages', 'ChatController::get_chat_internal_messages/$1', ['as' => 'getChatInternalMessages']);
$routes->get('notifications', 'ChatController::get_chat_cliente/$1', ['as' => 'getChatCliente']); $routes->get('notifications', 'ChatController::get_chat_cliente/$1', ['as' => 'getChatCliente']);
$routes->get('users/internal', 'ChatController::get_chat_users_internal', ['as' => 'getChatUsersInternal']); $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/presupuesto', 'ChatController::store_hebra_presupuesto', ['as' => 'storeHebraPresupuesto']);
$routes->post('hebra/pedido', 'ChatController::store_hebra_pedido', ['as' => 'storeHebraPedido']); $routes->post('hebra/pedido', 'ChatController::store_hebra_pedido', ['as' => 'storeHebraPedido']);
$routes->post('hebra/factura', 'ChatController::store_hebra_factura', ['as' => 'storeHebraFactura']); $routes->post('hebra/factura', 'ChatController::store_hebra_factura', ['as' => 'storeHebraFactura']);

View File

@ -49,8 +49,6 @@ class ChatController extends BaseController
$this->clienteModel = model(ClienteModel::class); $this->clienteModel = model(ClienteModel::class);
$this->chatUserModel = model(ChatUser::class); $this->chatUserModel = model(ChatUser::class);
$this->chatNotificationModel = model(ChatNotification::class); $this->chatNotificationModel = model(ChatNotification::class);
} }
public function index() {} public function index() {}
public function get_chat_departments() public function get_chat_departments()
@ -89,7 +87,6 @@ class ChatController extends BaseController
$data["messages"] = $this->chatMessageModel->get_chat_messages($chat->id); $data["messages"] = $this->chatMessageModel->get_chat_messages($chat->id);
$this->chatMessageModel->set_chat_department_messages_as_read($chat->id); $this->chatMessageModel->set_chat_department_messages_as_read($chat->id);
$data["count"] = count($data["messages"]); $data["count"] = count($data["messages"]);
} }
$data["chat"] = $chat; $data["chat"] = $chat;
return $this->response->setJSON($data); return $this->response->setJSON($data);
@ -111,13 +108,17 @@ class ChatController extends BaseController
$data["chat"] = $chat; $data["chat"] = $chat;
return $this->response->setJSON($data); 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); $chat = $this->chatModel->find($chat_id);
$this->viewData['breadcrumb'] = [ $this->viewData['breadcrumb'] = [
['title' => lang("Chat.chat"), 'route' => route_to("mensajeriaView"), 'active' => false], ['title' => lang("Chat.chat"), 'route' => route_to("mensajeriaView"), 'active' => false],
['title' => $chat->title, 'route' => 'javascript:void(0);', 'active' => true] ['title' => $chat->title, 'route' => 'javascript:void(0);', 'active' => true]
]; ];
$this->viewData["chatId"] = $chat_id; $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); 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"]]); $chat_message_id = $this->chatMessageModel->insert(["chat_id" => $chatId, "sender_id" => auth()->user()->id, "message" => $data["message"]]);
$dataResponse = $this->chatMessageModel->find($chat_message_id); $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); return $this->response->setJSON($dataResponse);
} }
public function store_chat_message_pedido() 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"]]); $chat_message_id = $this->chatMessageModel->insert(["chat_id" => $chatId, "sender_id" => auth()->user()->id, "message" => $data["message"]]);
$dataResponse = $this->chatMessageModel->find($chat_message_id); $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); return $this->response->setJSON($dataResponse);
} }
public function store_chat_message_factura() 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"]]); $chat_message_id = $this->chatMessageModel->insert(["chat_id" => $chatId, "sender_id" => auth()->user()->id, "message" => $data["message"]]);
$dataResponse = $this->chatMessageModel->find($chat_message_id); $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); return $this->response->setJSON($dataResponse);
} }
public function store_chat_message_single() public function store_chat_message_single()
@ -191,7 +210,7 @@ class ChatController extends BaseController
"receiver_id" => $data["receiver_id"], "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); $dataResponse = $this->chatMessageModel->find($chat_message_id);
return $this->response->setJSON($dataResponse); return $this->response->setJSON($dataResponse);
} }
@ -200,11 +219,11 @@ class ChatController extends BaseController
$auth_user = auth()->user(); $auth_user = auth()->user();
if ($auth_user->cliente_id) { if ($auth_user->cliente_id) {
$users = $this->chatModel->getOpenChatCliente($auth_user->id); $users = $this->chatModel->getOpenChatCliente($auth_user->id);
}else{ } else {
$users = $this->userModel->builder() $users = $this->userModel->builder()
->whereNotIn("id", [$auth_user->id]) ->whereNotIn("id", [$auth_user->id])
->where("deleted_at", null) ->where("deleted_at", null)
->get()->getResultObject(); ->get()->getResultObject();
} }
foreach ($users as $user) { foreach ($users as $user) {
$user->unreadMessages = $this->chatMessageModel->get_chat_messages_count($user->id); $user->unreadMessages = $this->chatMessageModel->get_chat_messages_count($user->id);
@ -288,7 +307,26 @@ class ChatController extends BaseController
] ]
)->where("cliente_id", null) )->where("cliente_id", null)
->where("deleted_at", 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")) { if ($this->request->getGet("q")) {
$query->groupStart() $query->groupStart()
->orLike("users.username", $this->request->getGet("q")) ->orLike("users.username", $this->request->getGet("q"))
@ -310,15 +348,16 @@ class ChatController extends BaseController
"message" => $bodyData["message"], "message" => $bodyData["message"],
"sender_id" => auth()->user()->id "sender_id" => auth()->user()->id
]); ]);
if(isset($bodyData["users"])){ if (isset($bodyData["users"])) {
$chatUserData = array_map(fn($x) => ["user_id" => $x,"chat_id" => $chat_id],$bodyData["users"]); $chatUserData = array_map(fn($x) => ["user_id" => $x, "chat_id" => $chat_id], $bodyData["users"]);
$this->chatUserModel->insertBatch($chatUserData); $this->chatUserModel->insertBatch($chatUserData);
foreach ($bodyData["users"] as $userId) { foreach ($bodyData["users"] as $userId) {
$this->chatNotificationModel->insert( $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() public function store_hebra_pedido()
@ -334,15 +373,16 @@ class ChatController extends BaseController
"message" => $bodyData["message"], "message" => $bodyData["message"],
"sender_id" => auth()->user()->id "sender_id" => auth()->user()->id
]); ]);
if(isset($bodyData["users"])){ if (isset($bodyData["users"])) {
$chatUserData = array_map(fn($x) => ["user_id" => $x,"chat_id" => $chat_id],$bodyData["users"]); $chatUserData = array_map(fn($x) => ["user_id" => $x, "chat_id" => $chat_id], $bodyData["users"]);
$this->chatUserModel->insertBatch($chatUserData); $this->chatUserModel->insertBatch($chatUserData);
foreach ($bodyData["users"] as $userId) { foreach ($bodyData["users"] as $userId) {
$this->chatNotificationModel->insert( $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() public function store_hebra_factura()
@ -357,101 +397,105 @@ class ChatController extends BaseController
"message" => $bodyData["message"], "message" => $bodyData["message"],
"sender_id" => auth()->user()->id "sender_id" => auth()->user()->id
]); ]);
if(isset($bodyData["users"])){ if (isset($bodyData["users"])) {
$chatUserData = array_map(fn($x) => ["user_id" => $x,"chat_id" => $chat_id],$bodyData["users"]); $chatUserData = array_map(fn($x) => ["user_id" => $x, "chat_id" => $chat_id], $bodyData["users"]);
$this->chatUserModel->insertBatch($chatUserData); $this->chatUserModel->insertBatch($chatUserData);
foreach ($bodyData["users"] as $userId) { foreach ($bodyData["users"] as $userId) {
$this->chatNotificationModel->insert( $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) public function update_hebra($chat_id)
{ {
$bodyData = $this->request->getPost(); $bodyData = $this->request->getPost();
$chatMessageId = $this->chatMessageModel->insert([ $chatMessageId = $this->chatMessageModel->insert([
"chat_id" => $chat_id, "chat_id" => $chat_id,
"message" => $bodyData["message"], "message" => $bodyData["message"],
"sender_id" => auth()->user()->id "sender_id" => auth()->user()->id
]); ]);
$actualUsers = $this->chatUserModel->builder()->select("user_id")->where("chat_id",$chat_id)->get()->getResultArray(); $actualUsers = $this->chatUserModel->builder()->select("user_id")->where("chat_id", $chat_id)->get()->getResultArray();
$actualUsersArray = array_map(fn($x) => $x["user_id"],$actualUsers); $actualUsersArray = array_map(fn($x) => $x["user_id"], $actualUsers);
foreach ($actualUsersArray as $key => $user_id) { foreach ($actualUsersArray as $key => $user_id) {
$this->chatNotificationModel->insert( $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) { foreach ($bodyData["users"] as $userId) {
if(in_array($userId,$actualUsersArray) == false){ if (in_array($userId, $actualUsersArray) == false) {
$chatUserData = ["user_id" => $userId,"chat_id" => $chat_id]; $chatUserData = ["user_id" => $userId, "chat_id" => $chat_id];
$this->chatUserModel->insert($chatUserData); $this->chatUserModel->insert($chatUserData);
} }
$this->chatNotificationModel->insert( $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); $data = $this->chatModel->getPresupuestoHebras($presupuesto_id);
$notifications = $this->chatModel->builder()->select([ $notifications = $this->chatModel->builder()->select([
"chat_notifications.id" "chat_notifications.id"
]) ])
->join("chat_messages","chat_messages.chat_id = chats.id","left") ->join("chat_messages", "chat_messages.chat_id = chats.id", "left")
->join("chat_notifications","chat_notifications.chat_message_id = chat_messages.id","left") ->join("chat_notifications", "chat_notifications.chat_message_id = chat_messages.id", "left")
->where("chats.presupuesto_id",$presupuesto_id) ->where("chats.presupuesto_id", $presupuesto_id)
->where("chat_notifications.user_id",auth()->user()->id) ->where("chat_notifications.user_id", auth()->user()->id)
->get()->getResultArray(); ->get()->getResultArray();
foreach ($notifications as $notification) { foreach ($notifications as $notification) {
$this->chatNotificationModel->update($notification["id"],["viewed" => true]); $this->chatNotificationModel->update($notification["id"], ["viewed" => true]);
} }
return $this->response->setJSON($data); 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); $data = $this->chatModel->getPedidoHebras($pedido_id);
$notifications = $this->chatModel->builder()->select([ $notifications = $this->chatModel->builder()->select([
"chat_notifications.id" "chat_notifications.id"
]) ])
->join("chat_messages","chat_messages.chat_id = chats.id","left") ->join("chat_messages", "chat_messages.chat_id = chats.id", "left")
->join("chat_notifications","chat_notifications.chat_message_id = chat_messages.id","left") ->join("chat_notifications", "chat_notifications.chat_message_id = chat_messages.id", "left")
->where("chats.pedido_id",$pedido_id) ->where("chats.pedido_id", $pedido_id)
->where("chat_notifications.user_id",auth()->user()->id) ->where("chat_notifications.user_id", auth()->user()->id)
->get()->getResultArray(); ->get()->getResultArray();
foreach ($notifications as $notification) { foreach ($notifications as $notification) {
$this->chatNotificationModel->update($notification["id"],["viewed" => true]); $this->chatNotificationModel->update($notification["id"], ["viewed" => true]);
} }
return $this->response->setJSON($data); 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); $data = $this->chatModel->getFacturaHebras($factura_id);
$notifications = $this->chatModel->builder()->select([ $notifications = $this->chatModel->builder()->select([
"chat_notifications.id" "chat_notifications.id"
]) ])
->join("chat_messages","chat_messages.chat_id = chats.id","left") ->join("chat_messages", "chat_messages.chat_id = chats.id", "left")
->join("chat_notifications","chat_notifications.chat_message_id = chat_messages.id","left") ->join("chat_notifications", "chat_notifications.chat_message_id = chat_messages.id", "left")
->where("chats.factura_id",$factura_id) ->where("chats.factura_id", $factura_id)
->where("chat_notifications.user_id",auth()->user()->id) ->where("chat_notifications.user_id", auth()->user()->id)
->get()->getResultArray(); ->get()->getResultArray();
foreach ($notifications as $notification) { foreach ($notifications as $notification) {
$this->chatNotificationModel->update($notification["id"],["viewed" => true]); $this->chatNotificationModel->update($notification["id"], ["viewed" => true]);
} }
return $this->response->setJSON($data); return $this->response->setJSON($data);
} }
public function datatable_messages() public function datatable_messages()
{ {
$query = $this->chatModel->getQueryDatatable();
$auth_user_id = auth()->user()->id; $auth_user_id = auth()->user()->id;
$query = $this->chatModel->getQueryDatatable($auth_user_id);
return DataTable::of($query) 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('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")) ->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("creator", fn($q) => $this->chatModel->getChatFirstUser($q->id)->userFullName)
->add("viewed", fn($q) => $this->chatModel->isMessageChatViewed($q->id,$auth_user_id)) ->add("viewed", fn($q) => $this->chatModel->isMessageChatViewed($q->id, $auth_user_id))
->add("action", fn($q) => $q->id) ->add("action", fn($q) => $q->id)
->toJson(true); ->toJson(true);
} }
public function store_new_direct_message() public function store_new_direct_message()
{ {
@ -462,7 +506,7 @@ class ChatController extends BaseController
"users" => "required", "users" => "required",
]; ];
if(!$this->validate($rules)){ if (!$this->validate($rules)) {
return $this->response->setStatusCode(400)->setJSON([ return $this->response->setStatusCode(400)->setJSON([
'message' => lang('App.global_alert_save_error'), 'message' => lang('App.global_alert_save_error'),
'status' => 'error', 'status' => 'error',
@ -470,14 +514,15 @@ class ChatController extends BaseController
]); ]);
} }
$this->chatModel->createNewDirectChat(...$bodyData); $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); $chatData = $this->chatModel->getChatDirect($chat_id);
return $this->response->setJSON($chatData); 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); $chat_users_id = $this->chatUserModel->getChatUserArrayId($chat_id);
$query = $this->userModel->builder()->select( $query = $this->userModel->builder()->select(
@ -485,9 +530,9 @@ class ChatController extends BaseController
"id", "id",
"CONCAT(first_name,' ',last_name,'(',username,')') as name" "CONCAT(first_name,' ',last_name,'(',username,')') as name"
] ]
)->where("cliente_id", null) )
->where("deleted_at", null) ->where("deleted_at", null)
->whereNotIn("id",$chat_users_id); ->whereNotIn("id", $chat_users_id);
if ($this->request->getGet("q")) { if ($this->request->getGet("q")) {
$query->groupStart() $query->groupStart()
->orLike("users.username", $this->request->getGet("q")) ->orLike("users.username", $this->request->getGet("q"))
@ -497,19 +542,37 @@ class ChatController extends BaseController
return $this->response->setJSON($query->get()->getResultObject()); 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(); $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); $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 = $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); $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); $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]);
}
} }

View File

@ -21,6 +21,10 @@ return [
], ],
"new_message_ok" => "Mensaje enviado correctamente", "new_message_ok" => "Mensaje enviado correctamente",
"participants" => "Participantes", "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."
]; ];

View File

@ -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(); 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(); 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 "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, "pedido_id" => $pedido_id,
"chat_department_id" => $chat_department_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([ return $this->insert([
@ -109,7 +109,7 @@ class ChatModel extends Model
"chat_department_id" => $chat_department_id "chat_department_id" => $chat_department_id
]); ]);
} }
public function createChatSingle() : int public function createChatSingle(): int
{ {
return $this->insert(["chat_department_id" => null]); return $this->insert(["chat_department_id" => null]);
} }
@ -138,82 +138,82 @@ class ChatModel extends Model
return $countChatPresupuesto > 0; return $countChatPresupuesto > 0;
} }
public function getChatPedidosChat() : array public function getChatPedidosChat(): array
{ {
$query = $this->db->table("chats") $query = $this->db->table("chats")
->select([ ->select([
"chats.id as chatId", "chats.id as chatId",
"chats.pedido_id as pedidoId", "chats.pedido_id as pedidoId",
"chats.chat_department_id as chatDepartmentId", "chats.chat_department_id as chatDepartmentId",
"chat_departments.display as chatDisplay", "chat_departments.display as chatDisplay",
"pedidos.id as title" "pedidos.id as title"
]) ])
->join("chat_departments","chat_departments.id = chats.chat_department_id","left") ->join("chat_departments", "chat_departments.id = chats.chat_department_id", "left")
->join("pedidos","pedidos.id = chats.pedido_id","left") ->join("pedidos", "pedidos.id = chats.pedido_id", "left")
->get()->getResultObject(); ->get()->getResultObject();
return $query; return $query;
} }
public function getChatPresupuestosChat() : array public function getChatPresupuestosChat(): array
{ {
$query = $this->db->table("chats") $query = $this->db->table("chats")
->select([ ->select([
"chats.id as chatId", "chats.id as chatId",
"chats.pedido_id as pedidoId", "chats.pedido_id as pedidoId",
"chats.chat_department_id as chatDepartmentId", "chats.chat_department_id as chatDepartmentId",
"chat_departments.display as chatDisplay", "chat_departments.display as chatDisplay",
"presupuestos.titulo as title" "presupuestos.titulo as title"
]) ])
->join("chat_departments","chat_departments.id = chats.chat_department_id","left") ->join("chat_departments", "chat_departments.id = chats.chat_department_id", "left")
->join("presupuestos","presupuestos.id = chats.pedido_id","left") ->join("presupuestos", "presupuestos.id = chats.pedido_id", "left")
->get()->getResultObject(); ->get()->getResultObject();
return $query; return $query;
} }
public function getChatFacturasChat() : array public function getChatFacturasChat(): array
{ {
$query = $this->db->table("chats") $query = $this->db->table("chats")
->select([ ->select([
"chats.id as chatId", "chats.id as chatId",
"chats.pedido_id as pedidoId", "chats.pedido_id as pedidoId",
"chats.chat_department_id as chatDepartmentId", "chats.chat_department_id as chatDepartmentId",
"chat_departments.display as chatDisplay", "chat_departments.display as chatDisplay",
"facturas.numero as title" "facturas.numero as title"
]) ])
->join("chat_departments","chat_departments.id = chats.chat_department_id","left") ->join("chat_departments", "chat_departments.id = chats.chat_department_id", "left")
->join("facturas","facturas.id = chats.pedido_id","left") ->join("facturas", "facturas.id = chats.pedido_id", "left")
->get()->getResultObject(); ->get()->getResultObject();
return $query; return $query;
} }
public function getChatSingleChat() : array public function getChatSingleChat(): array
{ {
$query = $this->db->table("chats") $query = $this->db->table("chats")
->select([ ->select([
"chats.id as chatId", "chats.id as chatId",
"chats.chat_department_id as chatDepartmentId", "chats.chat_department_id as chatDepartmentId",
"chat_departments.display as chatDisplay", "chat_departments.display as chatDisplay",
"facturas.numero as title" "facturas.numero as title"
]) ])
->join("chat_departments","chat_departments.id = chats.chat_department_id","left") ->join("chat_departments", "chat_departments.id = chats.chat_department_id", "left")
->join("facturas","facturas.id = chats.pedido_id","left") ->join("facturas", "facturas.id = chats.pedido_id", "left")
->get()->getResultObject(); ->get()->getResultObject();
return $query; return $query;
} }
public function getClienteChatPedidos(array $pedidos) : array public function getClienteChatPedidos(array $pedidos): array
{ {
$q = $this->db->table("chats") $q = $this->db->table("chats")
->select([ ->select([
"chats.id as chatId", "chats.id as chatId",
"chats.pedido_id as pedidoId", "chats.pedido_id as pedidoId",
"chats.chat_department_id as chatDepartmentId", "chats.chat_department_id as chatDepartmentId",
"chat_departments.display as chatDisplay", "chat_departments.display as chatDisplay",
"pedidos.id as title" "pedidos.id as title"
]) ])
->join("chat_departments","chat_departments.id = chats.chat_department_id","left") ->join("chat_departments", "chat_departments.id = chats.chat_department_id", "left")
->join("pedidos","pedidos.id = chats.pedido_id","left") ->join("pedidos", "pedidos.id = chats.pedido_id", "left")
->where('chats.chat_department_id is NOT NULL', NULL, FALSE); ->where('chats.chat_department_id is NOT NULL', NULL, FALSE);
if(count($pedidos)>0){ if (count($pedidos) > 0) {
$q->whereIn("pedidos.id",$pedidos); $q->whereIn("pedidos.id", $pedidos);
}else{ } else {
return []; return [];
} }
$results = $q->get()->getResultObject(); $results = $q->get()->getResultObject();
@ -222,32 +222,32 @@ class ChatModel extends Model
foreach ($results as $row) { foreach ($results as $row) {
$messages = $chatMessageModel->get_chat_messages($row->chatId); $messages = $chatMessageModel->get_chat_messages($row->chatId);
foreach ($messages as $key => $message) { 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++; $count++;
} }
} }
$row->uri = "/pedidos/edit/".$row->pedidoId; $row->uri = "/pedidos/edit/" . $row->pedidoId;
$row->unreadMessages=$count; $row->unreadMessages = $count;
} }
return $results; return $results;
} }
public function getClienteChatFacturas(array $facturas) : array public function getClienteChatFacturas(array $facturas): array
{ {
$q = $this->db->table("chats") $q = $this->db->table("chats")
->select([ ->select([
"chats.id as chatId", "chats.id as chatId",
"chats.factura_id as facturaId", "chats.factura_id as facturaId",
"chats.chat_department_id as chatDepartmentId", "chats.chat_department_id as chatDepartmentId",
"chat_departments.display as chatDisplay", "chat_departments.display as chatDisplay",
"facturas.numero as title" "facturas.numero as title"
]) ])
->join("chat_departments","chat_departments.id = chats.chat_department_id","left") ->join("chat_departments", "chat_departments.id = chats.chat_department_id", "left")
->join("facturas","facturas.id = chats.factura_id","left") ->join("facturas", "facturas.id = chats.factura_id", "left")
->where('chats.chat_department_id is NOT NULL', NULL, FALSE); ->where('chats.chat_department_id is NOT NULL', NULL, FALSE);
if(count($facturas)>0){ if (count($facturas) > 0) {
$q->whereIn("facturas.id",$facturas); $q->whereIn("facturas.id", $facturas);
}else{ } else {
return []; return [];
} }
$results = $q->get()->getResultObject(); $results = $q->get()->getResultObject();
@ -256,32 +256,32 @@ class ChatModel extends Model
foreach ($results as $row) { foreach ($results as $row) {
$messages = $chatMessageModel->get_chat_messages($row->chatId); $messages = $chatMessageModel->get_chat_messages($row->chatId);
foreach ($messages as $key => $message) { 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++; $count++;
} }
} }
$row->uri = "/facturas/edit/".$row->facturaId; $row->uri = "/facturas/edit/" . $row->facturaId;
$row->unreadMessages=$count; $row->unreadMessages = $count;
} }
return $results; return $results;
} }
public function getClienteChatPresupuestos(array $presupuestos) : array public function getClienteChatPresupuestos(array $presupuestos): array
{ {
$q = $this->db->table("chats") $q = $this->db->table("chats")
->select([ ->select([
"chats.id as chatId", "chats.id as chatId",
"chats.presupuesto_id as presupuestoId", "chats.presupuesto_id as presupuestoId",
"chats.chat_department_id as chatDepartmentId", "chats.chat_department_id as chatDepartmentId",
"chat_departments.display as chatDisplay", "chat_departments.display as chatDisplay",
"presupuestos.titulo as title" "presupuestos.titulo as title"
]) ])
->join("chat_departments","chat_departments.id = chats.chat_department_id","left") ->join("chat_departments", "chat_departments.id = chats.chat_department_id", "left")
->join("presupuestos","presupuestos.id = chats.presupuesto_id","left") ->join("presupuestos", "presupuestos.id = chats.presupuesto_id", "left")
->where('chats.chat_department_id is NOT NULL', NULL, FALSE); ->where('chats.chat_department_id is NOT NULL', NULL, FALSE);
if(count($presupuestos)>0){ if (count($presupuestos) > 0) {
$q->whereIn("presupuestos.id",$presupuestos); $q->whereIn("presupuestos.id", $presupuestos);
}else{ } else {
return []; return [];
} }
$results = $q->get()->getResultObject(); $results = $q->get()->getResultObject();
@ -289,15 +289,15 @@ class ChatModel extends Model
$count = 0; $count = 0;
foreach ($results as $row) { foreach ($results as $row) {
$messages = $chatMessageModel->get_chat_messages($row->chatId); $messages = $chatMessageModel->get_chat_messages($row->chatId);
foreach ($messages as $key => $message ) { 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++; $count++;
} }
} }
$row->uri = "/presupuestos/presupuestocliente/edit/".$row->presupuestoId; $row->uri = "/presupuestos/presupuestocliente/edit/" . $row->presupuestoId;
$row->unreadMessages=$count; $row->unreadMessages = $count;
} }
return $results; return $results;
} }
public function getChatDepartmentNotifications() public function getChatDepartmentNotifications()
@ -309,54 +309,55 @@ class ChatModel extends Model
$pedidoModel = model(PedidoModel::class); $pedidoModel = model(PedidoModel::class);
$q = $this->db->table("chats") $q = $this->db->table("chats")
->select([ ->select([
"chats.id as chatId", "chats.id as chatId",
"chats.pedido_id as pedidoId", "chats.pedido_id as pedidoId",
"chats.presupuesto_id as presupuestoId", "chats.presupuesto_id as presupuestoId",
"chats.factura_id as facturaId", "chats.factura_id as facturaId",
"chats.chat_department_id as chatDepartmentId", "chats.chat_department_id as chatDepartmentId",
"chat_departments.display as chatDisplay", "chat_departments.display as chatDisplay",
]) ])
->join("chat_departments","chat_departments.id = chats.chat_department_id","left") ->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") ->join("chat_department_users", "chat_department_users.chat_department_id = chats.chat_department_id", "left")
->where("chat_department_users.user_id",auth()->user()->id); ->where("chat_department_users.user_id", auth()->user()->id);
$rows = $q->get()->getResultObject(); $rows = $q->get()->getResultObject();
$auth_user = auth()->user();
foreach ($rows as $row) { foreach ($rows as $row) {
$messages = $chatMessageModel->get_chat_messages($row->chatId); $messages = $chatMessageModel->get_chat_messages($row->chatId);
$count = 0; $count = 0;
$chatDeparmentUsers = $chatDeparmentModel->getChatDepartmentUsers($row->chatDepartmentId); $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) { 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++; $count++;
} }
if($row->presupuestoId){ if ($row->presupuestoId) {
$row->model = $presupuestoModel->find($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->title = $row->presupuestoId;
$row->avatar = "PRE"; $row->avatar = "PRE";
$row->unreadMessages = $count; $row->unreadMessages = $count;
} } elseif ($row->pedidoId) {
elseif($row->pedidoId){
$row->model = $pedidoModel->find($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->title = $row->pedidoId;
$row->avatar = "P"; $row->avatar = "P";
$row->unreadMessages = $count; $row->unreadMessages = $count;
} elseif ($row->facturaId) {
}
elseif($row->facturaId){
$row->model = $facturaModel->find($row->facturaId); $row->model = $facturaModel->find($row->facturaId);
$row->uri = "/facturas/edit/".$row->facturaId; $row->uri = "/facturas/edit/" . $row->facturaId;
$row->avatar = "F"; $row->avatar = "F";
$row->title = $row->facturaId; $row->title = $row->facturaId;
$row->unreadMessages = $count; $row->unreadMessages = $count;
} }
} }
return $rows; return $rows;
} }
public function getChatInternalNotifications() public function getChatInternalNotifications()
{ {
@ -367,42 +368,45 @@ class ChatModel extends Model
$chatNotificationModel = model(ChatNotification::class); $chatNotificationModel = model(ChatNotification::class);
$q = $this->db->table("chats") $q = $this->db->table("chats")
->select([ ->select([
"chats.id as chatId", "chats.id as chatId",
"chats.pedido_id as pedidoId", "chats.pedido_id as pedidoId",
"chats.presupuesto_id as presupuestoId", "chats.presupuesto_id as presupuestoId",
"chats.factura_id as facturaId", "chats.factura_id as facturaId",
"chats.title as chatDisplay", "chats.title as chatDisplay",
]) ])
->join("chat_messages","chat_messages.chat_id = chats.id","left") ->join("chat_messages", "chat_messages.chat_id = chats.id", "left")
->join("chat_notifications","chat_notifications.chat_message_id = chat_messages.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.user_id", auth()->user()->id)
->where("chat_notifications.viewed",false); ->where("chat_notifications.viewed", false);
$auth_user = auth()->user();
$rows = $q->get()->getResultObject(); $rows = $q->get()->getResultObject();
$rows_new = []; $rows_new = [];
foreach ($rows as $row) { foreach ($rows as $row) {
$row->unreadMessages = 0; $row->unreadMessages = 0;
if($row->presupuestoId){ if ($row->presupuestoId) {
$row->model = $presupuestoModel->find($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->title = $row->presupuestoId;
$row->chatDisplay = $row->model->titulo;
$row->avatar = "PRE"; $row->avatar = "PRE";
$row->unreadMessages = $this->countUnreadMessagePresupuesto($row->presupuestoId); $row->unreadMessages = $this->countUnreadMessagePresupuesto($row->presupuestoId);
$rows_new[] = $row; $rows_new[] = $row;
} } elseif ($row->pedidoId) {
elseif($row->pedidoId){
$row->model = $pedidoModel->find($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->title = $row->pedidoId;
$row->avatar = "P"; $row->avatar = "P";
$row->unreadMessages = $this->countUnreadMessagePedido($row->pedidoId); $row->unreadMessages = $this->countUnreadMessagePedido($row->pedidoId);
$rows_new[] = $row; $rows_new[] = $row;
} elseif ($row->facturaId) {
}
elseif($row->facturaId){
$row->model = $facturaModel->find($row->facturaId); $row->model = $facturaModel->find($row->facturaId);
$row->uri = "/facturas/edit/".$row->facturaId; $row->uri = "/facturas/edit/" . $row->facturaId;
$row->avatar = "F"; $row->avatar = "F";
$row->title = $row->facturaId; $row->title = $row->facturaId;
$row->unreadMessages = $this->countUnreadMessageFactura($row->facturaId); $row->unreadMessages = $this->countUnreadMessageFactura($row->facturaId);
@ -411,39 +415,40 @@ class ChatModel extends Model
} }
return $rows_new; return $rows_new;
} }
public function getChatDirectMessageNotifications(){ public function getChatDirectMessageNotifications()
{
$chatMessageModel = model(ChatMessageModel::class); $chatMessageModel = model(ChatMessageModel::class);
$chatNotificationModel = model(ChatNotification::class); $chatNotificationModel = model(ChatNotification::class);
$q = $this->db->table("chats") $q = $this->db->table("chats")
->select([ ->select([
"chats.id as chatId", "chats.id as chatId",
"chats.title as chatDisplay", "chats.title as chatDisplay",
"COUNT(chat_notifications.user_id) as unreadMessages" "COUNT(chat_notifications.user_id) as unreadMessages"
]) ])
->join("chat_messages","chat_messages.chat_id = chats.id","left") ->join("chat_messages", "chat_messages.chat_id = chats.id", "left")
->join("chat_notifications","chat_notifications.chat_message_id = chat_messages.id","left") ->join("chat_notifications", "chat_notifications.chat_message_id = chat_messages.id", "left")
->where("chats.presupuesto_id",null) ->where("chats.presupuesto_id", null)
->where("chats.chat_department_id",null) ->where("chats.chat_department_id", null)
->where("chats.pedido_id",null) ->where("chats.pedido_id", null)
->where("chats.factura_id",null) ->where("chats.factura_id", null)
->where("chat_notifications.viewed",false) ->where("chat_notifications.viewed", false)
->where("chat_notifications.user_id",auth()->user()->id); ->where("chat_notifications.user_id", auth()->user()->id);
$rows = $q->get()->getResultObject(); $rows = $q->get()->getResultObject();
$rows_new = []; $rows_new = [];
foreach ($rows as $row) { foreach ($rows as $row) {
if($row->chatId){ if ($row->chatId) {
$row->model = []; $row->model = [];
$row->uri = "/mensajes/internos"; $row->uri = "/chat/direct/".$row->chatId;
$row->avatar = "MD"; $row->avatar = "MD";
$row->title = "MD"; $row->title = "MD";
$row->chatDisplay = $this->getSenderIdFromChatMessage($row->chatId)?->username ?? "Unknown"; // $row->chatDisplay = $this->getSenderIdFromChatMessage($row->chatId)?->username ?? "Unknown";
$rows_new[] = $row; $rows_new[] = $row;
} }
} }
return $rows_new; return $rows_new;
} }
public function getChatInternalHebraPresupuesto(int $chat_id,int $presupuesto_id) : array public function getChatInternalHebraPresupuesto(int $chat_id, int $presupuesto_id): array
{ {
$data = []; $data = [];
@ -454,17 +459,18 @@ class ChatModel extends Model
"chat_messages.created_at", "chat_messages.created_at",
"CONCAT(users.first_name,' ',users.last_name) as senderFullName", "CONCAT(users.first_name,' ',users.last_name) as senderFullName",
]) ])
->join("chat_messages","chat_messages.chat_id = chats.id","left") ->join("chat_messages", "chat_messages.chat_id = chats.id", "left")
->join("users","users.id = chat_messages.sender_id","left") ->join("users", "users.id = chat_messages.sender_id", "left")
->where("chats.id",$chat_id) ->where("chats.id", $chat_id)
->where("chats.presupuesto_id",$presupuesto_id); ->where("chats.presupuesto_id", $presupuesto_id);
$data["chatId"] = $chat_id; $data["chatId"] = $chat_id;
$data["messages"] = $query->get()->getResultObject(); $data["messages"] = $query->get()->getResultObject();
$data["chatTitle"] = $this->find($chat_id)->title; $data["chatTitle"] = $this->find($chat_id)->title;
$data["users"] = $this->getChatUsers($chat_id); $data["users"] = $this->getChatUsers($chat_id);
return $data; return $data;
} }
public function getChatInternalHebraPedido($chat_id,$pedido_id){ public function getChatInternalHebraPedido($chat_id, $pedido_id)
{
$data = []; $data = [];
$query = $this->builder()->select([ $query = $this->builder()->select([
"chats.id as chatId", "chats.id as chatId",
@ -473,17 +479,18 @@ class ChatModel extends Model
"chat_messages.created_at", "chat_messages.created_at",
"CONCAT(users.first_name,' ',users.last_name) as senderFullName", "CONCAT(users.first_name,' ',users.last_name) as senderFullName",
]) ])
->join("chat_messages","chat_messages.chat_id = chats.id","left") ->join("chat_messages", "chat_messages.chat_id = chats.id", "left")
->join("users","users.id = chat_messages.sender_id","left") ->join("users", "users.id = chat_messages.sender_id", "left")
->where("chats.id",$chat_id) ->where("chats.id", $chat_id)
->where("chats.pedido_id",$pedido_id); ->where("chats.pedido_id", $pedido_id);
$data["chatId"] = $chat_id; $data["chatId"] = $chat_id;
$data["messages"] = $query->get()->getResultObject(); $data["messages"] = $query->get()->getResultObject();
$data["chatTitle"] = $this->find($chat_id)->title; $data["chatTitle"] = $this->find($chat_id)->title;
$data["users"] = $this->getChatUsers($chat_id); $data["users"] = $this->getChatUsers($chat_id);
return $data; return $data;
} }
public function getChatInternalHebraFactura($chat_id,$factura_id){ public function getChatInternalHebraFactura($chat_id, $factura_id)
{
$data = []; $data = [];
$query = $this->builder()->select([ $query = $this->builder()->select([
"chats.id as chatId", "chats.id as chatId",
@ -492,10 +499,10 @@ class ChatModel extends Model
"chat_messages.created_at", "chat_messages.created_at",
"CONCAT(users.first_name,' ',users.last_name) as senderFullName", "CONCAT(users.first_name,' ',users.last_name) as senderFullName",
]) ])
->join("chat_messages","chat_messages.chat_id = chats.id","left") ->join("chat_messages", "chat_messages.chat_id = chats.id", "left")
->join("users","users.id = chat_messages.sender_id","left") ->join("users", "users.id = chat_messages.sender_id", "left")
->where("chats.id",$chat_id) ->where("chats.id", $chat_id)
->where("chats.factura_id",$factura_id); ->where("chats.factura_id", $factura_id);
$data["chatId"] = $chat_id; $data["chatId"] = $chat_id;
$data["messages"] = $query->get()->getResultObject(); $data["messages"] = $query->get()->getResultObject();
$data["chatTitle"] = $this->find($chat_id)->title; $data["chatTitle"] = $this->find($chat_id)->title;
@ -508,132 +515,131 @@ class ChatModel extends Model
"users.username", "users.username",
"CONCAT(users.first_name,' ',users.last_name) as userFullName", "CONCAT(users.first_name,' ',users.last_name) as userFullName",
]) ])
->join("chat_users","chat_users.chat_id = chats.id") ->join("chat_users", "chat_users.chat_id = chats.id")
->join("users","users.id = chat_users.user_id","left") ->join("users", "users.id = chat_users.user_id", "left")
->where("chats.id",$chat_id); ->where("chats.id", $chat_id);
return $query->get()->getResultObject(); return $query->get()->getResultObject();
} }
public function getPresupuestoHebras($presupuesto_id) : array public function getPresupuestoHebras($presupuesto_id): array
{ {
$data = []; $data = [];
$chats = $this->builder()->select("chats.id as chatId") $chats = $this->builder()->select("chats.id as chatId")
->where("chats.chat_department_id",null) ->where("chats.chat_department_id", null)
->where("chats.presupuesto_id",$presupuesto_id)->get()->getResultObject(); ->where("chats.presupuesto_id", $presupuesto_id)->get()->getResultObject();
foreach ($chats as $chat) { foreach ($chats as $chat) {
$data[$chat->chatId] = $this->getChatInternalHebraPresupuesto($chat->chatId,$presupuesto_id); $data[$chat->chatId] = $this->getChatInternalHebraPresupuesto($chat->chatId, $presupuesto_id);
} }
return $data; return $data;
} }
public function getPedidoHebras($pedido_id) : array public function getPedidoHebras($pedido_id): array
{ {
$data = []; $data = [];
$chats = $this->builder()->select("chats.id as chatId") $chats = $this->builder()->select("chats.id as chatId")
->where("chats.chat_department_id",null) ->where("chats.chat_department_id", null)
->where("chats.pedido_id",$pedido_id)->get()->getResultObject(); ->where("chats.pedido_id", $pedido_id)->get()->getResultObject();
foreach ($chats as $chat) { foreach ($chats as $chat) {
$data[$chat->chatId] = $this->getChatInternalHebraPedido($chat->chatId,$pedido_id); $data[$chat->chatId] = $this->getChatInternalHebraPedido($chat->chatId, $pedido_id);
} }
return $data; return $data;
} }
public function getFacturaHebras($factura_id) : array public function getFacturaHebras($factura_id): array
{ {
$data = []; $data = [];
$chats = $this->builder()->select("chats.id as chatId") $chats = $this->builder()->select("chats.id as chatId")
->where("chats.chat_department_id",null) ->where("chats.chat_department_id", null)
->where("chats.factura_id",$factura_id)->get()->getResultObject(); ->where("chats.factura_id", $factura_id)->get()->getResultObject();
foreach ($chats as $chat) { foreach ($chats as $chat) {
$data[$chat->chatId] = $this->getChatInternalHebraFactura($chat->chatId,$factura_id); $data[$chat->chatId] = $this->getChatInternalHebraFactura($chat->chatId, $factura_id);
} }
return $data; return $data;
} }
public function countUnreadMessagePresupuesto($presupuesto_id) : int|string public function countUnreadMessagePresupuesto($presupuesto_id): int|string
{ {
return $this->builder()->select() return $this->builder()->select()
->join("chat_messages","chat_messages.chat_id = chats.id","left") ->join("chat_messages", "chat_messages.chat_id = chats.id", "left")
->join("chat_notifications","chat_notifications.chat_message_id = chat_messages.id","left") ->join("chat_notifications", "chat_notifications.chat_message_id = chat_messages.id", "left")
->where("chats.presupuesto_id",$presupuesto_id) ->where("chats.presupuesto_id", $presupuesto_id)
->where("chat_notifications.viewed",false) ->where("chat_notifications.viewed", false)
->where("chat_notifications.user_id",auth()->user()->id) ->where("chat_notifications.user_id", auth()->user()->id)
->countAllResults(); ->countAllResults();
} }
public function countUnreadMessagePedido($pedido_id) : int|string public function countUnreadMessagePedido($pedido_id): int|string
{ {
return $this->builder()->select() return $this->builder()->select()
->join("chat_messages","chat_messages.chat_id = chats.id","left") ->join("chat_messages", "chat_messages.chat_id = chats.id", "left")
->join("chat_notifications","chat_notifications.chat_message_id = chat_messages.id","left") ->join("chat_notifications", "chat_notifications.chat_message_id = chat_messages.id", "left")
->where("chats.pedido_id",$pedido_id) ->where("chats.pedido_id", $pedido_id)
->where("chat_notifications.viewed",false) ->where("chat_notifications.viewed", false)
->where("chat_notifications.user_id",auth()->user()->id) ->where("chat_notifications.user_id", auth()->user()->id)
->countAllResults(); ->countAllResults();
} }
public function countUnreadMessageFactura($factura_id) : int|string public function countUnreadMessageFactura($factura_id): int|string
{ {
return $this->builder()->select() return $this->builder()->select()
->join("chat_messages","chat_messages.chat_id = chats.id","left") ->join("chat_messages", "chat_messages.chat_id = chats.id", "left")
->join("chat_notifications","chat_notifications.chat_message_id = chat_messages.id","left") ->join("chat_notifications", "chat_notifications.chat_message_id = chat_messages.id", "left")
->where("chats.factura_id",$factura_id) ->where("chats.factura_id", $factura_id)
->where("chat_notifications.viewed",false) ->where("chat_notifications.viewed", false)
->where("chat_notifications.user_id",auth()->user()->id)->countAllResults(); ->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() return $this->builder()->select()
->join("chat_messages","chat_messages.chat_id = chats.id","left") ->join("chat_messages", "chat_messages.chat_id = chats.id", "left")
->join("chat_notifications","chat_notifications.chat_message_id = chat_messages.id","left") ->join("chat_notifications", "chat_notifications.chat_message_id = chat_messages.id", "left")
->where("chats.presupuesto_id",null) ->where("chats.presupuesto_id", null)
->where("chats.pedido_id",null) ->where("chats.pedido_id", null)
->where("chats.factura_id",null) ->where("chats.factura_id", null)
->where("chats.chat_department_id",null) ->where("chats.chat_department_id", null)
->where("chat_messages.chat_id",$chat_id) ->where("chat_messages.chat_id", $chat_id)
->where("chat_notifications.viewed",false) ->where("chat_notifications.viewed", false)
->where("chat_notifications.user_id",auth()->user()->id)->countAllResults(); ->where("chat_notifications.user_id", auth()->user()->id)->countAllResults();
} }
public function getSenderIdFromChatMessage(int $chat_id) public function getSenderIdFromChatMessage(int $chat_id)
{ {
$first_message = $this->builder()->select() $first_message = $this->builder()->select()
->join("chat_messages","chat_messages.chat_id = chats.id","left") ->join("chat_messages", "chat_messages.chat_id = chats.id", "left")
->where("chats.presupuesto_id",null) ->where("chats.presupuesto_id", null)
->where("chats.pedido_id",null) ->where("chats.pedido_id", null)
->where("chats.factura_id",null) ->where("chats.factura_id", null)
->where("chats.id",$chat_id) ->where("chats.id", $chat_id)
->where("chat_messages.receiver_id",auth()->user()->id)->get()->getFirstRow(); ->where("chat_messages.receiver_id", auth()->user()->id)->get()->getFirstRow();
$userModel = model(UserModel::class); $userModel = model(UserModel::class);
return $userModel->find($first_message->sender_id); 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([ $q = $this->builder()->distinct()->select([
"users.*" "users.*"
]) ])
->join("chat_messages","chat_messages.chat_id = chats.id","left") ->join("chat_messages", "chat_messages.chat_id = chats.id", "left")
->join("users","users.id = chat_messages.sender_id","left") ->join("users", "users.id = chat_messages.sender_id", "left")
->where("chat_messages.receiver_id",$user_id); ->where("chat_messages.receiver_id", $user_id);
return $q->get()->getResultObject(); 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([ $q = $this->builder()->select([
"chat_messages.id" "chat_messages.id"
]) ])
->join("chat_messages","chat_messages.chat_id = chats.id",'left') ->join("chat_messages", "chat_messages.chat_id = chats.id", 'left')
->where("chats.chat_department_id",$chat_department_id) ->where("chats.chat_department_id", $chat_department_id)
->where("chats.id",$chat_id) ->where("chats.id", $chat_id)
->countAllResults(); ->countAllResults();
return $q; return $q;
} }
public function getChatFirstUser(int $chat_id) : object public function getChatFirstUser(int $chat_id): object
{ {
$q = $this->builder()->select(["users.id", $q = $this->builder()->select([
"CONCAT(users.first_name,' ',users.last_name) as userFullName", "users.id",
"CONCAT(users.first_name,' ',users.last_name) as userFullName",
]) ])
->join("chat_messages","chat_messages.chat_id = chats.id",'left') ->join("chat_messages", "chat_messages.chat_id = chats.id", 'left')
->join("users","users.id = chat_messages.sender_id","left") ->join("users", "users.id = chat_messages.sender_id", "left")
->where("chats.id",$chat_id) ->where("chats.id", $chat_id)
->where("chat_messages.deleted_at",null) ->where("chat_messages.deleted_at", null)
->orderBy("chat_messages.created_at",'ASC'); ->orderBy("chat_messages.created_at", 'ASC');
return $q->get()->getFirstRow(); return $q->get()->getFirstRow();
} }
/** /**
@ -643,24 +649,24 @@ class ChatModel extends Model
* @param integer $user_id * @param integer $user_id
* @return boolean True : All messages readed * @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"]) $q = $this->builder()->select(["chat_notifications.id"])
->join("chat_messages","chat_messages.chat_id = chats.id",'left') ->join("chat_messages", "chat_messages.chat_id = chats.id", 'left')
->join("chat_notifications","chat_notifications.chat_message_id = chat_messages.id",'left') ->join("chat_notifications", "chat_notifications.chat_message_id = chat_messages.id", 'left')
->where("chats.id",$chat_id) ->where("chats.id", $chat_id)
->where("chat_notifications.user_id",$user_id) ->where("chat_notifications.user_id", $user_id)
->where("chat_notifications.viewed",false); ->where("chat_notifications.viewed", false);
$unread_messages_count = $q->countAllResults(); $unread_messages_count = $q->countAllResults();
if($unread_messages_count > 0){ if ($unread_messages_count > 0) {
$result = false; $result = false;
}else{ } else {
$result = true; $result = true;
} }
return $result; return $result;
} }
public function getQueryDatatable(): BaseBuilder public function getQueryDatatable(int $user_id): BaseBuilder
{ {
$query = $this->builder() $query = $this->builder()
->select([ ->select([
@ -669,15 +675,17 @@ class ChatModel extends Model
"chats.updated_at", "chats.updated_at",
"chats.title", "chats.title",
]) ])
->where("chat_department_id",null) ->join("chat_users","chat_users.chat_id = chats.id","left")
->where("pedido_id",null) ->where("chat_department_id", null)
->where("presupuesto_id",null) ->where("pedido_id", null)
->where("factura_id",null) ->where("presupuesto_id", null)
->where("title is NOT NULL",NULL,FALSE) ->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");
return $query; return $query;
} }
public function createNewDirectChat(string $title,string $message,array $users) public function createNewDirectChat(string $title, string $message, array $users)
{ {
$chatMessageModel = model(ChatMessageModel::class); $chatMessageModel = model(ChatMessageModel::class);
$chatNotificationModel = model(ChatNotification::class); $chatNotificationModel = model(ChatNotification::class);
@ -690,10 +698,10 @@ class ChatModel extends Model
"receiver_id" => null, "receiver_id" => null,
"message" => $message "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) { foreach ($users as $key => $user_id) {
$chatUserModel->insert(["chat_id" => $chat_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]); $chatNotificationModel->insert(["chat_message_id" => $chat_message_id, "user_id" => $user_id]);
} }
} }
/** /**
@ -707,16 +715,17 @@ class ChatModel extends Model
* "users" => array * "users" => array
* ] * ]
*/ */
public function getChatDirect(int $chat_id) : array public function getChatDirect(int $chat_id): array
{ {
$auth_user = auth()->user()->id; $auth_user = auth()->user()->id;
$chat = $this->find($chat_id); $chat = $this->find($chat_id);
$chatNotificationModel = model(ChatNotification::class);
$query = $this->builder()->select([ $query = $this->builder()->select([
"users.*", "users.*",
]) ])
->join("chat_users","chat_users.chat_id = chats.id") ->join("chat_users", "chat_users.chat_id = chats.id")
->join("users","users.id = chat_users.user_id","left") ->join("users", "users.id = chat_users.user_id", "left")
->where("chats.id",$chat_id); ->where("chats.id", $chat_id);
$users = $query->get()->getResultObject(); $users = $query->get()->getResultObject();
$query = $this->builder()->select([ $query = $this->builder()->select([
"chat_messages.*", "chat_messages.*",
@ -724,17 +733,18 @@ class ChatModel extends Model
"users.last_name as sender_last_name", "users.last_name as sender_last_name",
]) ])
->join("chat_messages","chat_messages.chat_id = chats.id","left") ->join("chat_messages", "chat_messages.chat_id = chats.id", "left")
->join("users","chat_messages.sender_id = users.id","left") ->join("users", "chat_messages.sender_id = users.id", "left")
->where("chats.id",$chat_id); ->where("chats.id", $chat_id);
$messages = $query->get()->getResultObject(); $messages = $query->get()->getResultObject();
$validatedMessages = []; $validatedMessages = [];
foreach ($messages as $key => $message) { 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'; $message->pos = 'right';
$validatedMessages[] = $message; $validatedMessages[] = $message;
}else{ } else {
$message->pos = 'left'; $message->pos = 'left';
$validatedMessages[] = $message; $validatedMessages[] = $message;
} }
@ -746,4 +756,63 @@ class ChatModel extends Model
]; ];
return $data; 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);
}
} }

View File

@ -48,4 +48,15 @@ class ChatNotification extends Model
protected $beforeDelete = []; protected $beforeDelete = [];
protected $afterDelete = []; 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;
}
} }

View File

@ -10,7 +10,7 @@ class ChatUser extends Model
protected $primaryKey = 'id'; protected $primaryKey = 'id';
protected $useAutoIncrement = true; protected $useAutoIncrement = true;
protected $returnType = 'array'; protected $returnType = 'array';
protected $useSoftDeletes = false; protected $useSoftDeletes = true;
protected $protectFields = true; protected $protectFields = true;
protected $allowedFields = [ protected $allowedFields = [
"user_id", "user_id",
@ -24,7 +24,7 @@ class ChatUser extends Model
protected array $castHandlers = []; protected array $castHandlers = [];
// Dates // Dates
protected $useTimestamps = false; protected $useTimestamps = true;
protected $dateFormat = 'datetime'; protected $dateFormat = 'datetime';
protected $createdField = 'created_at'; protected $createdField = 'created_at';
protected $updatedField = 'updated_at'; protected $updatedField = 'updated_at';

View File

@ -1,4 +1,4 @@
<div class="container-xxl flex-grow-1 container-p-y" id="chat-direct-message" data-id="<?= $modelId ?>"> <div class="col-md-12" id="chat-direct-message" data-id="<?= $modelId ?>" data-user-id="<?= $userId ?>">
<div class="app-chat card overflow-hidden"> <div class="app-chat card overflow-hidden">
<div class="row g-0"> <div class="row g-0">
@ -11,9 +11,11 @@
<div class="sidebar-header"> <div class="sidebar-header">
<div class="d-flex align-items-center me-3 me-lg-0"> <div class="d-flex align-items-center me-3 me-lg-0">
<div class="flex-shrink-0 avatar me-3"> <?php if (auth()->user()->inGroup('admin')) { ?>
<button class="btn btn-primary btn-icon me-2" id="btn-chat-add-participant"><span class="ti ti-md ti-plus"></span></button> <div class="flex-shrink-0 avatar me-3">
</div> <button title="<?= lang("Chat.new_participant") ?>" class="btn btn-primary btn-icon me-2 rounded-circle" id="btn-chat-add-participant"><span class="ti ti-sm ti-user-plus"></span></button>
</div>
<?php } ?>
<div class="flex-grow-1 input-group input-group-merge rounded-pill"> <div class="flex-grow-1 input-group input-group-merge rounded-pill">
<span class="input-group-text" id="basic-addon-search31"> <span class="input-group-text" id="basic-addon-search31">
@ -79,7 +81,7 @@
<small class="user-status text-muted"></small> <small class="user-status text-muted"></small>
</div> </div>
</div> </div>
<!-- <div class="d-flex align-items-center"> <div class="d-flex align-items-center">
<div class="dropdown d-flex align-self-center"> <div class="dropdown d-flex align-self-center">
<button class="btn p-0" type="button" id="chat-header-actions" <button class="btn p-0" type="button" id="chat-header-actions"
data-bs-toggle="dropdown" aria-haspopup="true" data-bs-toggle="dropdown" aria-haspopup="true"
@ -88,13 +90,10 @@
</button> </button>
<div class="dropdown-menu dropdown-menu-end" <div class="dropdown-menu dropdown-menu-end"
aria-labelledby="chat-header-actions"> aria-labelledby="chat-header-actions">
<a class="dropdown-item" href="javascript:void(0);">Silenciar <a class="dropdown-item" id="update-message-unviewed" href="javascript:void(0);"><?= lang("Chat.check_as_unviewed") ?></a>
Conversacion</a>
<a class="dropdown-item" href="javascript:void(0);">Limpiar
Conversacion</a>
</div> </div>
</div> </div>
</div> --> </div>
</div> </div>
</div> </div>
<div class="chat-history-body bg-body "> <div class="chat-history-body bg-body ">

View File

@ -1,4 +1,4 @@
<div class="container-xxl flex-grow-1 container-p-y" id="chat-factura" data-id="<?= $modelId ?>"> <div class="col-md-12" id="chat-factura" data-id="<?= $modelId ?>">
<div class="app-chat card overflow-hidden"> <div class="app-chat card overflow-hidden">
<div class="row g-0"> <div class="row g-0">
@ -30,6 +30,15 @@
</div> </div>
<!-- Chats --> <!-- Chats -->
<ul class="list-unstyled chat-contact-list" id="chat-list"> <ul class="list-unstyled chat-contact-list" id="chat-list">
<div class="d-flex justify-content-center chat-loader">
<div class="sk-wave sk-primary ">
<div class="sk-wave-rect"></div>
<div class="sk-wave-rect"></div>
<div class="sk-wave-rect"></div>
<div class="sk-wave-rect"></div>
<div class="sk-wave-rect"></div>
</div>
</div>
<li class="chat-contact-list-item chat-list-item-0 d-none"> <li class="chat-contact-list-item chat-list-item-0 d-none">
<h6 class="text-muted mb-0">No Chats Found</h6> <h6 class="text-muted mb-0">No Chats Found</h6>
</li> </li>
@ -76,6 +85,15 @@
</div> </div>
</div> </div>
<div class="chat-history-body bg-body "> <div class="chat-history-body bg-body ">
<div class="d-flex justify-content-center chat-loader">
<div class="sk-wave sk-primary ">
<div class="sk-wave-rect"></div>
<div class="sk-wave-rect"></div>
<div class="sk-wave-rect"></div>
<div class="sk-wave-rect"></div>
<div class="sk-wave-rect"></div>
</div>
</div>
<ul class="list-unstyled chat-history" id="chat-conversation"> <ul class="list-unstyled chat-history" id="chat-conversation">
@ -112,6 +130,7 @@
</div> </div>
<?= $this->section('css') ?> <?= $this->section('css') ?>
<link rel="stylesheet" href="<?= site_url('themes/vuexy/vendor/libs/spinkit/spinkit.css') ?>" />
<link rel="stylesheet" href="<?= site_url('themes/vuexy/vendor/css/pages/app-chat.css') ?>"> <link rel="stylesheet" href="<?= site_url('themes/vuexy/vendor/css/pages/app-chat.css') ?>">
<?= $this->endSection() ?> <?= $this->endSection() ?>
<!-------------------------------------------------------> <!------------------------------------------------------->

View File

@ -137,6 +137,7 @@
</div> </div>
</div> </div>
<?= $this->section('css') ?> <?= $this->section('css') ?>
<link rel="stylesheet" href="<?= site_url('themes/vuexy/vendor/libs/spinkit/spinkit.css') ?>" />
<link rel="stylesheet" href="<?= site_url('themes/vuexy/vendor/css/pages/app-chat.css') ?>"> <link rel="stylesheet" href="<?= site_url('themes/vuexy/vendor/css/pages/app-chat.css') ?>">
<?= $this->endSection() ?> <?= $this->endSection() ?>
<!-------------------------------------------------------> <!------------------------------------------------------->

View File

@ -1,4 +1,4 @@
<div class="container-xxl flex-grow-1 container-p-y" id="chat-pedido" data-id="<?= $modelId ?>"> <div class="col-md-12" id="chat-pedido" data-id="<?= $modelId ?>">
<div class="app-chat card overflow-hidden"> <div class="app-chat card overflow-hidden">
<div class="row g-0"> <div class="row g-0">
@ -31,6 +31,7 @@
</div> </div>
<!-- Chats --> <!-- Chats -->
<ul class="list-unstyled chat-contact-list" id="chat-list"> <ul class="list-unstyled chat-contact-list" id="chat-list">
<li class="chat-contact-list-item chat-list-item-0 d-none"> <li class="chat-contact-list-item chat-list-item-0 d-none">
<h6 class="text-muted mb-0">No Chats Found</h6> <h6 class="text-muted mb-0">No Chats Found</h6>
</li> </li>
@ -76,6 +77,15 @@
</div> </div>
</div> </div>
<div class="chat-history-body bg-body "> <div class="chat-history-body bg-body ">
<div class="d-flex justify-content-center chat-loader">
<div class="sk-wave sk-primary ">
<div class="sk-wave-rect"></div>
<div class="sk-wave-rect"></div>
<div class="sk-wave-rect"></div>
<div class="sk-wave-rect"></div>
<div class="sk-wave-rect"></div>
</div>
</div>
<ul class="list-unstyled chat-history" id="chat-conversation"> <ul class="list-unstyled chat-history" id="chat-conversation">
@ -113,6 +123,7 @@
<?= $this->section('css') ?> <?= $this->section('css') ?>
<link rel="stylesheet" href="<?= site_url('themes/vuexy/vendor/libs/spinkit/spinkit.css') ?>" />
<link rel="stylesheet" href="<?= site_url('themes/vuexy/vendor/css/pages/app-chat.css') ?>"> <link rel="stylesheet" href="<?= site_url('themes/vuexy/vendor/css/pages/app-chat.css') ?>">
<?= $this->endSection() ?> <?= $this->endSection() ?>
<!-------------------------------------------------------> <!------------------------------------------------------->

View File

@ -1,4 +1,4 @@
<div id="chat-presupuesto" data-id="<?= $modelId ?>"> <div class="col-md-12" id="chat-presupuesto" data-id="<?= $modelId ?>">
<div class="app-chat card overflow-hidden"> <div class="app-chat card overflow-hidden">
<div class="row g-0"> <div class="row g-0">
@ -30,6 +30,15 @@
</div> </div>
<!-- Chats --> <!-- Chats -->
<ul class="list-unstyled chat-contact-list" id="chat-list"> <ul class="list-unstyled chat-contact-list" id="chat-list">
<div class="d-flex justify-content-center chat-loader">
<div class="sk-wave sk-primary ">
<div class="sk-wave-rect"></div>
<div class="sk-wave-rect"></div>
<div class="sk-wave-rect"></div>
<div class="sk-wave-rect"></div>
<div class="sk-wave-rect"></div>
</div>
</div>
<li class="chat-contact-list-item chat-list-item-0 d-none"> <li class="chat-contact-list-item chat-list-item-0 d-none">
<h6 class="text-muted mb-0">No Chats Found</h6> <h6 class="text-muted mb-0">No Chats Found</h6>
</li> </li>
@ -76,9 +85,17 @@
</div> </div>
</div> </div>
<div class="chat-history-body bg-body "> <div class="chat-history-body bg-body ">
<div class="d-flex justify-content-center chat-loader">
<div class="sk-wave sk-primary ">
<div class="sk-wave-rect"></div>
<div class="sk-wave-rect"></div>
<div class="sk-wave-rect"></div>
<div class="sk-wave-rect"></div>
<div class="sk-wave-rect"></div>
</div>
</div>
<ul class="list-unstyled chat-history" id="chat-conversation"> <ul class="list-unstyled chat-history" id="chat-conversation">
</ul> </ul>
</div> </div>
<!-- Chat message form --> <!-- Chat message form -->
@ -112,6 +129,7 @@
</div> </div>
<?= $this->section('css') ?> <?= $this->section('css') ?>
<link rel="stylesheet" href="<?= site_url('themes/vuexy/vendor/libs/spinkit/spinkit.css') ?>" />
<link rel="stylesheet" href="<?= site_url('themes/vuexy/vendor/css/pages/app-chat.css') ?>"> <link rel="stylesheet" href="<?= site_url('themes/vuexy/vendor/css/pages/app-chat.css') ?>">
<?= $this->endSection() ?> <?= $this->endSection() ?>
<!-------------------------------------------------------> <!------------------------------------------------------->

View File

@ -13,13 +13,24 @@
<form id="formNewParticipant"> <form id="formNewParticipant">
<div class="form-group"> <div class="form-group">
<div class="row"> <div class="row">
<div class="col-12 mb-0"> <div class="col-12 mb-2">
<label for="select-users" class="required form-label"><?= lang('Chat.modal.new_receivers') ?></label> <label for="select-users" class="required form-label"><?= lang('Chat.modal.new_receivers') ?></label>
<select id="select-users" name="users" class="select2 form-control" multiple required> <select id="select-users" name="users" class="select2 form-control" multiple required>
</select> </select>
</div> </div>
<div class="col-12 mb-2">
<div class="text-light small fw-medium mb-2"><?= lang("Chat.add_notification") ?></div>
<label class="switch">
<input type="checkbox" class="switch-input" name="notification" id="checkbox-notification-chat" checked />
<span class="switch-toggle-slider">
<span class="switch-on"></span>
<span class="switch-off"></span>
</span>
<span class="switch-label"><?= lang("Chat.add_notification_message") ?></span>
</label>
</div>
</div> </div>
</div>
</form> </form>
</div> </div>
<div class="modal-footer"> <div class="modal-footer">

View File

@ -7,7 +7,7 @@
<?= $this->section('content'); ?> <?= $this->section('content'); ?>
<!--Content Body--> <!--Content Body-->
<div class="row"> <div class="row">
<?= view("themes/vuexy/components/chat_direct",["modelId" => $chatId]) ?> <?= view("themes/vuexy/components/chat_direct",["modelId" => $chatId,"userId" => auth()->user()->id]) ?>
</div> </div>

View File

@ -75,9 +75,12 @@ class Chat {
id: '0', id: '0',
text: "Seleccione un usuario" text: "Seleccione un usuario"
} }
this.btnUpdateMessagesUnviewed = this.domItem.find("#update-message-unviewed")
this.btnDirectMessageSubmit = this.domItem.find("#send-msg-btn-direct") this.btnDirectMessageSubmit = this.domItem.find("#send-msg-btn-direct")
this.btnDirectMessageSubmit.on("click", this._handleStoreChatDirectMessage.bind(this)) 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.selectParticipants = new ClassSelect(this.modalNewParticipant.item.find("#select-users"), `/chat/direct/users/select/${this.modelId}`, this.selectPlaceholder, true)
this.authUserId = this.domItem.data("user-id")
this.checkboxNotificationMessage = this.modalNewParticipant.item.find("#checkbox-notification-chat")
this.btnAddParticipant = this.domItem.find("#btn-chat-add-participant") this.btnAddParticipant = this.domItem.find("#btn-chat-add-participant")
this.btnAddParticipantSubmit = this.domItem.find("#btn-chat-add-participant-submit") this.btnAddParticipantSubmit = this.domItem.find("#btn-chat-add-participant-submit")
@ -86,15 +89,17 @@ class Chat {
this.selectParticipants.init() this.selectParticipants.init()
this.modalNewParticipant.toggle() this.modalNewParticipant.toggle()
}) })
this.selectParticipants.item.on("change", () => { this.selectParticipants.item.on("change", () => {
console.log(this.selectParticipants.getVal())
if (this.selectParticipants.getVal().length > 0) { if (this.selectParticipants.getVal().length > 0) {
this.btnAddParticipantSubmit.removeClass("d-none") this.btnAddParticipantSubmit.removeClass("d-none")
} else { } else {
this.btnAddParticipantSubmit.addClass("d-none") this.btnAddParticipantSubmit.addClass("d-none")
} }
}) })
this.btnUpdateMessagesUnviewed.on("click",this._handleUpdateChatMessagesUnread.bind(this))
this._handleGetChatDirect() this._handleGetChatDirect()
setInterval(this._handleReloadChatDirectMessages.bind(this),10000)
} }
initGeneral() { initGeneral() {
this.chatType = "general" this.chatType = "general"
@ -156,6 +161,7 @@ class Chat {
* PRESUPUESTOS * PRESUPUESTOS
*=============================================**/ *=============================================**/
_handleGetChatList(event) { _handleGetChatList(event) {
this.domItem.find(".chat-loader").removeClass("d-none")
let ajax = new Ajax( let ajax = new Ajax(
"/chat/departments", "/chat/departments",
null, null,
@ -168,6 +174,7 @@ class Chat {
ajax.get(); ajax.get();
} }
_handleGetChatListSuccess(data) { _handleGetChatListSuccess(data) {
this.domItem.find(".chat-loader").addClass("d-none")
Object.values(data).map(row => { Object.values(data).map(row => {
this.chatList.append(this._getContact(row)) this.chatList.append(this._getContact(row))
this.chatDeparmentId = row.id this.chatDeparmentId = row.id
@ -175,6 +182,7 @@ class Chat {
this.chatList.find(`#chat_${row.name}`).on("click", (event) => { this.chatList.find(`#chat_${row.name}`).on("click", (event) => {
$(".chat-contact-list-item").removeClass("active") $(".chat-contact-list-item").removeClass("active")
$(event.currentTarget).parent().addClass("active") $(event.currentTarget).parent().addClass("active")
this.chatHistoryBody.empty()
this.chatDeparmentId = this.chatList.find(`#chat_${row.name}`).data("id") this.chatDeparmentId = this.chatList.find(`#chat_${row.name}`).data("id")
this.domItem.find(".chat-history-header div.chat-contact-info h6").text(row.display) this.domItem.find(".chat-history-header div.chat-contact-info h6").text(row.display)
this.domItem.find(".chat-history-header div.chat-contact-info small.user-status").text(row.display) this.domItem.find(".chat-history-header div.chat-contact-info small.user-status").text(row.display)
@ -244,7 +252,7 @@ class Chat {
${row.display} ${row.display}
</p> </p>
</div> </div>
<span class="badge badge-center rounded-pill bg-danger messages-unread-contact">${row.totalMessages ?? 0}</span> <span class="badge badge-center rounded-pill bg-secondary messages-unread-contact">${row.totalMessages ?? 0}</span>
</a> </a>
</li> </li>
` `
@ -282,6 +290,8 @@ class Chat {
_getChatDepartmentMessageCountError() { } _getChatDepartmentMessageCountError() { }
_getChatMessage() { _getChatMessage() {
this.domItem.find(".chat-loader").removeClass("d-none")
let ajax = new Ajax( let ajax = new Ajax(
`/chat/department/${this.chatType}/${this.chatDeparmentId}/${this.modelId}`, `/chat/department/${this.chatType}/${this.chatDeparmentId}/${this.modelId}`,
null, null,
@ -294,6 +304,7 @@ class Chat {
ajax.get(); ajax.get();
} }
_getChatMessageSuccess(data) { _getChatMessageSuccess(data) {
this.domItem.find(".chat-loader").addClass("d-none")
this.chatHistory.empty() this.chatHistory.empty()
this._setBtnDeparment() this._setBtnDeparment()
if (data.messages) { if (data.messages) {
@ -315,8 +326,8 @@ class Chat {
<div class="chat-message-text"> <div class="chat-message-text">
<p class="mb-0">${chatMessage?.message}</p> <p class="mb-0">${chatMessage?.message}</p>
</div> </div>
<div class="text-end text-muted mt-1"> <div class="text-${chatMessage?.pos == "left" ? "start" : "end"} text-muted mt-1">
<div class="text-start text-muted mt-1"> <div class="text-${chatMessage?.pos == "left" ? "start" : "end"} text-muted mt-1">
<i class="ti me-1"></i> <i class="ti me-1"></i>
<small>${chatMessage?.user?.first_name + " " + chatMessage?.user?.last_name}</small> <small>${chatMessage?.user?.first_name + " " + chatMessage?.user?.last_name}</small>
</div> </div>
@ -337,7 +348,6 @@ class Chat {
return chatItem return chatItem
} }
_addChatDirectMessages(chatMessage) { _addChatDirectMessages(chatMessage) {
console.log(chatMessage)
let chatItem = ` let chatItem = `
<li class="chat-message chat-message-${chatMessage.pos}"> <li class="chat-message chat-message-${chatMessage.pos}">
<div class="d-flex overflow-hidden"> <div class="d-flex overflow-hidden">
@ -346,8 +356,8 @@ class Chat {
<div class="chat-message-text"> <div class="chat-message-text">
<p class="mb-0">${chatMessage?.message}</p> <p class="mb-0">${chatMessage?.message}</p>
</div> </div>
<div class="text-end text-muted mt-1"> <div class="text-${chatMessage?.pos == "left" ? "start" : "end"} text-muted mt-1">
<div class="text-start text-muted mt-1"> <div class="text-${chatMessage?.pos == "left" ? "start" : "end"} text-muted mt-1">
<i class="ti me-1"></i> <i class="ti me-1"></i>
<small>${chatMessage?.sender_first_name + " " + chatMessage?.sender_last_name}</small> <small>${chatMessage?.sender_first_name + " " + chatMessage?.sender_last_name}</small>
</div> </div>
@ -549,7 +559,7 @@ class Chat {
</p> </p>
</div> </div>
${contact.unreadMessages ? `<span ${contact.unreadMessages ? `<span
class="badge badge-center rounded-pill bg-danger messages-unread-contact">${contact.unreadMessages}</span>` : ""} class="badge badge-center rounded-pill bg-secondary messages-unread-contact">${contact.unreadMessages}</span>` : ""}
</a> </a>
</li> </li>
` `
@ -559,11 +569,10 @@ class Chat {
} }
} }
_addParticipantToList(contact) { _addParticipantToList(contact) {
let contactItem = let contactItem =
` `
<li class="chat-contact-list-item"> <li class="chat-contact-list-item ${this.authUserId == contact.id ? "active" : ""}">
<a class="d-flex align-items-center contact-chat" data-id="${contact.id}" <div class="d-flex align-items-center contact-chat" data-id="${contact.id}"
id="chat-contact-list-item-${contact.id}"> id="chat-contact-list-item-${contact.id}">
<div class="avatar d-block flex-shrink-0"> <div class="avatar d-block flex-shrink-0">
<span class="avatar-initial rounded-circle bg-label-primary"> <span class="avatar-initial rounded-circle bg-label-primary">
@ -578,7 +587,7 @@ class Chat {
${contact?.cliente_id ? "[CLIENTE]" : ""}${contact.username} ${contact?.cliente_id ? "[CLIENTE]" : ""}${contact.username}
</p> </p>
</div> </div>
</a> </div>
</li> </li>
` `
@ -587,7 +596,6 @@ class Chat {
} }
} }
_handleGetChatDirect() { _handleGetChatDirect() {
const ajax = new Ajax( const ajax = new Ajax(
`/chat/${this.chatType}/conversation/${this.modelId}`, `/chat/${this.chatType}/conversation/${this.modelId}`,
null, null,
@ -597,10 +605,11 @@ class Chat {
) )
ajax.get() ajax.get()
} }
_handleGetChatDirectSuccess(response) { _handleGetChatDirectSuccess(response) {
const { chat, users, messages } = response const { chat, users, messages } = response
if (users.length > 0) { if (users.length > 0) {
users.map(c => this._addContactToList(c)) users.map(c => this._addParticipantToList(c))
} }
if (messages.length > 0) { if (messages.length > 0) {
messages.map(m => this._addChatDirectMessages(m)) messages.map(m => this._addChatDirectMessages(m))
@ -609,9 +618,29 @@ class Chat {
this.domItem.find(".chat-loader").addClass("d-none") this.domItem.find(".chat-loader").addClass("d-none")
} }
_handleGetChatDirectError(error) { } _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() { _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") this.domItem.find(".chat-loader").removeClass("d-none")
const ajax = new Ajax( const ajax = new Ajax(
@ -648,12 +677,34 @@ class Chat {
} }
} }
_handleStoreChatDirectMessageSuccess(response) { _handleStoreChatDirectMessageSuccess(response) {
let message = response try {
this._addChatDirectMessages(message) let message = response
this.messageInput.val("") this._addChatDirectMessages(message)
this.messageInput.val("")
} catch (error) {
} finally {
this.scrollbarChatHistory.update()
this.chatHistoryBody[0].scrollTop = this.scrollbarChatHistory.containerHeight
}
} }
_handleStoreChatDirectMessageError(error) { } _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) => {
<div class="chat-contact-info flex-grow-1 ms-2"> <div class="chat-contact-info flex-grow-1 ms-2">
<h6 class="chat-contact-name text-truncate m-0">[${e.title}] ${e.chatDisplay}</h6> <h6 class="chat-contact-name text-truncate m-0">[${e.title}] ${e.chatDisplay}</h6>
</div> </div>
<span class="badge badge-center rounded-pill bg-primary p-1">${numberOfMessages}</span> <span class="badge badge-center rounded-pill bg-primary p-1 m-2">${numberOfMessages}</span>
</a> </a>
</li> </li>
` `

View File

@ -1,6 +1,10 @@
import {showNotificationMessages} from "../components/chat.js"; import {showNotificationMessages} from "../components/chat.js";
showNotificationMessages($("#chat-notification-list")) showNotificationMessages($("#chat-notification-list"))
setInterval(() => {
showNotificationMessages($("#chat-notification-list"))
},10000)
$("#message-notification-dropdown").on("click",(e) => { $("#message-notification-dropdown").on("click",(e) => {
showNotificationMessages($("#chat-notification-list")) showNotificationMessages($("#chat-notification-list"))
}) })

View File

@ -16,7 +16,7 @@ class MessagePage {
id: '0', id: '0',
text: "Seleccione un usuario" 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() { init() {
@ -52,6 +52,7 @@ class MessagePage {
this.alert.setHeadingTitle(response.message) this.alert.setHeadingTitle(response.message)
this.alert.show() this.alert.show()
this.hideForm() this.hideForm()
this.messageDatatable.datatable.ajax.reload()
} }
handleSubmitNewMessageError(response) { handleSubmitNewMessageError(response) {
const error = response.responseJSON const error = response.responseJSON