message refactor

This commit is contained in:
amazuecos
2025-03-24 08:12:06 +01:00
parent 61af547135
commit c0d54e28b7
26 changed files with 994 additions and 677 deletions

View File

@ -908,7 +908,7 @@ $routes->group('chat', ['namespace' => 'App\Controllers\Chat'], function ($route
$routes->post('department', 'ChatController::store_chat_department', ['as' => 'storeChatDepartment']);
$routes->delete('department/(:num)', 'ChatController::delete_chat_department/$1', ['as' => 'deleteChatDepartment']);
$routes->post('department/update/(:num)', 'ChatController::update_chat_department/$1', ['as' => 'updateChatDepartment']);
$routes->get('departments', 'ChatController::get_chat_departments', ['as' => 'getChatDepartments']);
$routes->get('departments/(:alpha)/(:num)', 'ChatController::get_chat_departments/$1/$2', ['as' => 'getChatDepartments']);
$routes->get('departments/select', 'ChatController::get_chat_department_select', ['as' => 'getChatDepartmentSelect']);
$routes->get('department/presupuesto/(:num)/(:num)', 'ChatController::get_chat_presupuesto/$1/$2', ['as' => 'getChatPresupuesto']);
$routes->get('department/pedido/(:num)/(:num)', 'ChatController::get_chat_pedido/$1/$2', ['as' => 'getChatPedido']);
@ -928,9 +928,7 @@ $routes->group('chat', ['namespace' => 'App\Controllers\Chat'], function ($route
$routes->get('(:num)', 'ChatController::get_chat/$1', ['as' => 'getChat']);
$routes->post('message/error/presupuesto', 'ChatController::store_chat_error_message', ['as' => 'storeChatErrorMessage']);
$routes->post('message/presupuesto', 'ChatController::store_chat_message_presupuesto', ['as' => 'storeChatMessagePresupuesto']);
$routes->post('message/pedido', 'ChatController::store_chat_message_pedido', ['as' => 'storeChatMessagePedido']);
$routes->post('message/factura', 'ChatController::store_chat_message_factura', ['as' => 'storeChatMessageFactura']);
$routes->post('message/(:alpha)', 'ChatController::store_message/$1', ['as' => 'storeChatMessage']);
$routes->post('message/internal', 'ChatController::store_chat_message_single', ['as' => 'storeChatMessageSingle']);
$routes->get('contacts', 'ChatController::get_chat_internal_contacts', ['as' => 'getChatInternalContacts']);
$routes->get('contacts/(:num)', 'ChatController::get_chat_internal_contact/$1', ['as' => 'getChatInternalContact']);
@ -939,15 +937,11 @@ $routes->group('chat', ['namespace' => 'App\Controllers\Chat'], function ($route
$routes->get('users/internal', 'ChatController::get_chat_users_internal', ['as' => 'getChatUsersInternal']);
$routes->get('users/all', 'ChatController::get_chat_users_all', ['as' => 'getChatUsersAll']);
$routes->post('hebra/presupuesto', 'ChatController::store_hebra_presupuesto', ['as' => 'storeHebraPresupuesto']);
$routes->post('hebra/pedido', 'ChatController::store_hebra_pedido', ['as' => 'storeHebraPedido']);
$routes->post('hebra/factura', 'ChatController::store_hebra_factura', ['as' => 'storeHebraFactura']);
$routes->post('hebra/(:alpha)', 'ChatController::store_hebra/$1', ['as' => 'storeHebra']);
$routes->post('hebra/(:num)', 'ChatController::update_hebra/$1', ['as' => 'updateHebra']);
$routes->get('hebra/presupuesto/(:num)', "ChatController::get_hebra_presupuesto/$1", ["as" => "getHebraPresupuesto"]);
$routes->get('hebra/pedido/(:num)', "ChatController::get_hebra_pedido/$1", ["as" => "getHebraPedido"]);
$routes->get('hebra/factura/(:num)', "ChatController::get_hebra_factura/$1", ["as" => "getHebraFactura"]);
$routes->get('hebra/(:alpha)/(:num)', "ChatController::get_hebra/$1/$2", ["as" => "getHebra"]);
$routes->get('users/notifications-unviewed/(:num)','ChatController::get_notifications_not_viewed_from_chat/$1');
$routes->get('users/message/notifications-unviewed/(:num)','ChatController::get_notifications_not_viewed_from_message/$1');
});

View File

@ -2,6 +2,7 @@
namespace Config;
use App\Services\ChatService;
use App\Services\FTPService;
use App\Services\MaquinaService;
use App\Services\MessageService;
@ -53,4 +54,8 @@ class Services extends BaseService
{
return new MessageService();
}
public static function chat()
{
return new ChatService();
}
}

View File

@ -14,6 +14,7 @@ use App\Models\Facturas\FacturaModel;
use App\Models\Pedidos\PedidoModel;
use App\Models\Presupuestos\PresupuestoModel;
use App\Models\Usuarios\UserModel;
use App\Services\ChatService;
use App\Services\MessageService;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\HTTP\RequestInterface;
@ -34,7 +35,7 @@ class ChatController extends BaseController
protected ChatUser $chatUserModel;
protected ChatNotification $chatNotificationModel;
protected Validation $validation;
protected ChatService $chatService;
protected array $viewData;
protected static $viewPath = 'themes/vuexy/form/mensajes/';
@ -56,12 +57,15 @@ class ChatController extends BaseController
$this->chatUserModel = model(ChatUser::class);
$this->chatNotificationModel = model(ChatNotification::class);
$this->validation = service("validation");
$this->chatService = service("chat");
}
public function index() {}
public function get_chat_departments()
public function get_chat_departments(string $model,int $modelId)
{
$data = $this->chatDeparmentModel->getChatDepartments();
$data = $this->chatService->getChatDepartments($model,$modelId);
return $this->response->setJSON($data);
}
public function get_chat_department_select()
@ -73,6 +77,7 @@ class ChatController extends BaseController
{
$data = [
"department" => $this->chatDeparmentModel->find($chat_department_id),
"chat" => null,
"messages" => null,
"count" => 0,
@ -82,6 +87,7 @@ class ChatController extends BaseController
$data["messages"] = $this->chatMessageModel->get_chat_messages($chat->id);
$this->chatMessageModel->set_chat_department_messages_as_read($chat->id);
$this->chatModel->setAsViewedChatUserNotifications($chat->id, auth()->user()->id);
$data["count"] = count($data["messages"]);
}
$data["chat"] = $chat;
@ -91,6 +97,7 @@ class ChatController extends BaseController
{
$data = [
"department" => $this->chatDeparmentModel->find($chat_department_id),
"chat" => null,
"messages" => null,
"count" => 0,
@ -110,6 +117,7 @@ class ChatController extends BaseController
{
$data = [
"department" => $this->chatDeparmentModel->find($chat_department_id),
"chat" => null,
"messages" => null,
"count" => 0,
@ -200,115 +208,15 @@ class ChatController extends BaseController
$data = $this->chatModel->getChat($chat_id);
return $this->response->setJSON($data);
}
public function store_chat_message_presupuesto()
public function store_message($model)
{
$data = $this->request->getPost();
// $data = $this->chatModel->createChatPresupuesto();
$existChat = $this->chatModel->existChatPresupuesto($data["chat_department_id"], $data["model_id"]);
if ($existChat == false) {
$chatId = $this->chatModel->createChatPresupuesto($data["chat_department_id"], $data["model_id"]);
} else {
$chat = $this->chatModel->getChatPresupuesto($data["chat_department_id"], $data["model_id"]);
$chatId = $chat->id;
}
$chat_message_id = $this->chatMessageModel->insert(["chat_id" => $chatId, "sender_id" => auth()->user()->id, "message" => $data["message"]]);
$dataResponse = $this->chatMessageModel->find($chat_message_id);
$chatDepartmentUsers = $this->chatDeparmentModel->getChatDepartmentUsers($data["chat_department_id"]);
if (auth()->user()->inGroup('admin')) {
$cliente_in_department_count = $this->chatDeparmentUserModel->where('chat_department_id', $data["chat_department_id"])->where('user_id', $data['client'])->where('presupuesto_id', $data['model_id'])->countAllResults();
if ($cliente_in_department_count == 0) {
$this->chatDeparmentUserModel->insert(['chat_department_id' => $data["chat_department_id"], 'user_id' => $data['client'], 'presupuesto_id' => $data['model_id']]);
}
}
$chatExternalUsers = $this->chatDeparmentModel->getChatDeparmentPresupuestoUsers($data["chat_department_id"], $data["model_id"]);
$auth_user_in_department_count = $this->chatDeparmentUserModel->where('chat_department_id', $data["chat_department_id"])->where('user_id', auth()->user()->id)->countAllResults();
$chatMessageEntity = $this->chatService->storeChatMessage($data["chat_department_id"],$model,$data["model_id"],$data);
return $this->response->setJSON($chatMessageEntity);
if ($auth_user_in_department_count) {
$this->chatDeparmentUserModel->insert(['chat_department_id' => $data["chat_department_id"], 'user_id' => auth()->user()->id, 'presupuesto_id' => $data['model_id']]);
}
foreach ($chatDepartmentUsers as $user) {
if ($user->id != auth()->user()->id) {
$this->chatNotificationModel->insert(["chat_message_id" => $chat_message_id, "user_id" => $user->id]);
}
}
foreach ($chatExternalUsers as $user) {
$this->chatNotificationModel->insert(["chat_message_id" => $chat_message_id, "user_id" => $user->id]);
}
return $this->response->setJSON($dataResponse);
}
public function store_chat_message_pedido()
{
$data = $this->request->getPost();
$existChat = $this->chatModel->existChatPedido($data["chat_department_id"], $data["model_id"]);
if ($existChat == false) {
$chatId = $this->chatModel->createChatPedido($data["chat_department_id"], $data["model_id"]);
} else {
$chat = $this->chatModel->getChatPedido($data["chat_department_id"], $data["model_id"]);
$chatId = $chat->id;
}
$chat_message_id = $this->chatMessageModel->insert(["chat_id" => $chatId, "sender_id" => auth()->user()->id, "message" => $data["message"]]);
$dataResponse = $this->chatMessageModel->find($chat_message_id);
$chatDepartmentUsers = $this->chatDeparmentModel->getChatDepartmentUsers($data["chat_department_id"]);
if (auth()->user()->inGroup('admin')) {
$cliente_in_department_count = $this->chatDeparmentUserModel->where('chat_department_id', $data["chat_department_id"])->where('user_id', $data['client'])->where('pedido_id', $data['model_id'])->countAllResults();
if ($cliente_in_department_count == 0) {
$this->chatDeparmentUserModel->insert(['chat_department_id' => $data["chat_department_id"], 'user_id' => $data['client'], 'pedido_id' => $data['model_id']]);
}
}
$chatExternalUsers = $this->chatDeparmentModel->getChatDeparmentPedidoUsers($data["chat_department_id"], $data["model_id"]);
$auth_user_in_department_count = $this->chatDeparmentUserModel->where('chat_department_id', $data["chat_department_id"])->where('user_id', auth()->user()->id)->countAllResults();
if ($auth_user_in_department_count == 0) {
$this->chatDeparmentUserModel->insert(['chat_department_id' => $data["chat_department_id"], 'user_id' => auth()->user()->id, 'pedido_id' => $data['model_id']]);
}
foreach ($chatDepartmentUsers as $user) {
if ($user->id != auth()->user()->id) {
$this->chatNotificationModel->insert(["chat_message_id" => $chat_message_id, "user_id" => $user->id]);
}
}
foreach ($chatExternalUsers as $user) {
$this->chatNotificationModel->insert(["chat_message_id" => $chat_message_id, "user_id" => $user->id]);
}
return $this->response->setJSON($dataResponse);
}
public function store_chat_message_factura()
{
$data = $this->request->getPost();
$existChat = $this->chatModel->existChatPedido($data["chat_department_id"], $data["model_id"]);
if ($existChat == false) {
$chatId = $this->chatModel->createChatPedido($data["chat_department_id"], $data["model_id"]);
} else {
$chat = $this->chatModel->getChatPedido($data["chat_department_id"], $data["model_id"]);
$chatId = $chat->id;
}
$chat_message_id = $this->chatMessageModel->insert(["chat_id" => $chatId, "sender_id" => auth()->user()->id, "message" => $data["message"]]);
$dataResponse = $this->chatMessageModel->find($chat_message_id);
$chatDepartmentUsers = $this->chatDeparmentModel->getChatDepartmentUsers($data["chat_department_id"]);
if (auth()->user()->inGroup('admin')) {
$cliente_in_department_count = $this->chatDeparmentUserModel->where('chat_department_id', $data["chat_department_id"])->where('user_id', $data['client'])->where('pedido_id', $data['model_id'])->countAllResults();
if ($cliente_in_department_count == 0) {
$this->chatDeparmentUserModel->insert(['chat_department_id' => $data["chat_department_id"], 'user_id' => $data['client'], 'factura_id' => $data['model_id']]);
}
}
$chatExternalUsers = $this->chatDeparmentModel->getChatDeparmentPedidoUsers($data["chat_department_id"], $data["model_id"]);
$auth_user_in_department_count = $this->chatDeparmentUserModel->where('chat_department_id', $data["chat_department_id"])->where('user_id', auth()->user()->id)->countAllResults();
if ($auth_user_in_department_count == 0) {
$this->chatDeparmentUserModel->insert(['chat_department_id' => $data["chat_department_id"], 'user_id' => auth()->user()->id, 'pedido_id' => $data['model_id']]);
}
foreach ($chatDepartmentUsers as $user) {
if ($user->id != auth()->user()->id) {
$this->chatNotificationModel->insert(["chat_message_id" => $chat_message_id, "user_id" => $user->id]);
}
}
foreach ($chatExternalUsers as $user) {
$this->chatNotificationModel->insert(["chat_message_id" => $chat_message_id, "user_id" => $user->id]);
}
return $this->response->setJSON($dataResponse);
}
public function store_chat_message_single()
{
$data = $this->request->getPost();
@ -369,68 +277,24 @@ class ChatController extends BaseController
public function get_chat_cliente()
{
$cliente_id = auth()->user()->cliente_id;
$response = [];
if ($cliente_id) {
// $data = $this->clienteModel->getClienteDataPresupuestoPedidoFactura($cliente_id);
$response["internals"] = $this->chatModel->getChatDepartmentNotifications();
$response["totalMessages"] = 0;
$mensajes_directos = $this->chatModel->getChatDirectMessageNotifications();
// $response["chatFacturas"] = $this->chatModel->getClienteChatFacturas($data["facturas"]);
// foreach ($response["chatFacturas"] as $key => $value) {
// $response["totalMessages"] += $value->unreadMessages;
// }
// $response["chatPresupuestos"] = $this->chatModel->getClienteChatPresupuestos($data["presupuestos"]);
// foreach ($response["chatPresupuestos"] as $key => $value) {
// $response["totalMessages"] += $value->unreadMessages;
// }
foreach ($mensajes_directos as $value) {
$response["internals"][] = $value;
$response["totalMessages"] += $value->unreadMessages;
}
// $response["chatPedidos"] = $this->chatModel->getClienteChatPedidos($data["pedidos"]);
// foreach ($response["chatPedidos"] as $key => $value) {
// $response["totalMessages"] += $value->unreadMessages;
// }
// $response["data"] = $data;
$response["totalMessages"] = 0;
foreach ($response["internals"] as $key => $value) {
$response["totalMessages"] += $value->unreadMessages;
}
} else {
$response["internals"] = $this->chatModel->getChatDepartmentNotifications();
$internal_notifications = $this->chatModel->getChatInternalNotifications();
$mensajes_directos = $this->chatModel->getChatDirectMessageNotifications();
foreach ($internal_notifications as $value) {
$response["internals"][] = $value;
}
foreach ($mensajes_directos as $value) {
$response["internals"][] = $value;
}
$response["totalMessages"] = 0;
foreach ($response["internals"] as $key => $value) {
$response["totalMessages"] += $value->unreadMessages;
}
}
$response = $this->chatService->getAuthUserNotifications();
return $this->response->setJSON($response);
}
public function get_chat_department_presupuesto_users(int $chat_department_id, int $presupuesto_id)
{
$adminUsers = $this->chatDeparmentModel->getChatDepartmentUsers($chat_department_id);
$externalUsers = $this->chatDeparmentModel->getChatDeparmentPresupuestoUsers($chat_department_id, $presupuesto_id);
return $this->response->setJSON(['admin_users' => $adminUsers, 'external_users' => $externalUsers]);
$data = $this->chatDeparmentModel->find($chat_department_id)->withUsers($presupuesto_id, 'presupuesto');
return $this->response->setJSON($data);
}
public function get_chat_department_pedido_users(int $chat_department_id, $pedido_id)
{
$adminUsers = $this->chatDeparmentModel->getChatDepartmentUsers($chat_department_id);
$externalUsers = $this->chatDeparmentModel->getChatDeparmentPedidoUsers($chat_department_id, $pedido_id);
return $this->response->setJSON(['admin_users' => $adminUsers, 'external_users' => $externalUsers]);
$data = $this->chatDeparmentModel->find($chat_department_id)->withUsers($pedido_id, 'pedido');
return $this->response->setJSON($data);
}
public function get_chat_department_factura_users(int $chat_department_id, $factura_id)
{
$adminUsers = $this->chatDeparmentModel->getChatDepartmentUsers($chat_department_id);
$externalUsers = $this->chatDeparmentModel->getChatDeparmentFacturaUsers($chat_department_id, $factura_id);
return $this->response->setJSON(['admin_users' => $adminUsers, 'external_users' => $externalUsers]);
$data = $this->chatDeparmentModel->find($chat_department_id)->withUsers($factura_id, 'factura');
return $this->response->setJSON($data);
}
public function get_chat_users_internal()
{
@ -536,80 +400,14 @@ class ChatController extends BaseController
return $this->response->setJSON($query->get()->getResultObject());
}
public function store_hebra_presupuesto()
public function store_hebra(string $model)
{
$auth_user = auth()->user();
$bodyData = $this->request->getPost();
$chat_id = $this->chatModel->insert([
"presupuesto_id" => $bodyData["modelId"],
"title" => $bodyData["title"]
]);
$chatMessageId = $this->chatMessageModel->insert([
"chat_id" => $chat_id,
"message" => $bodyData["message"],
"sender_id" => $auth_user->id
]);
if (isset($bodyData["users"])) {
$bodyData["users"][] = $auth_user->id;
$chatUserData = array_map(fn($x) => ["user_id" => $x, "chat_id" => $chat_id], $bodyData["users"]);
$this->chatUserModel->insertBatch($chatUserData);
foreach ($bodyData["users"] as $userId) {
$this->chatNotificationModel->insert(
["chat_message_id" => $chatMessageId, "user_id" => $userId]
);
}
}
return $this->response->setJSON(["message" => "Hebra creada correctamente", "status" => true]);
$status = $this->chatService->storeHebra($model,$bodyData['modelId'],$bodyData);
return $this->response->setJSON(["message" => "Hebra creada correctamente", "status" => $status]);
}
public function store_hebra_pedido()
{
$bodyData = $this->request->getPost();
$chat_id = $this->chatModel->insert([
"pedido_id" => $bodyData["modelId"],
"title" => $bodyData["title"]
]);
$chatMessageId = $this->chatMessageModel->insert([
"chat_id" => $chat_id,
"message" => $bodyData["message"],
"sender_id" => auth()->user()->id
]);
if (isset($bodyData["users"])) {
$chatUserData = array_map(fn($x) => ["user_id" => $x, "chat_id" => $chat_id], $bodyData["users"]);
$this->chatUserModel->insertBatch($chatUserData);
foreach ($bodyData["users"] as $userId) {
$this->chatNotificationModel->insert(
["chat_message_id" => $chatMessageId, "user_id" => $userId]
);
}
}
return $this->response->setJSON(["message" => "Hebra creada correctamente", "status" => true]);
}
public function store_hebra_factura()
{
$bodyData = $this->request->getPost();
$chat_id = $this->chatModel->insert([
"factura_id" => $bodyData["modelId"],
"title" => $bodyData["title"]
]);
$chatMessageId = $this->chatMessageModel->insert([
"chat_id" => $chat_id,
"message" => $bodyData["message"],
"sender_id" => auth()->user()->id
]);
if (isset($bodyData["users"])) {
$chatUserData = array_map(fn($x) => ["user_id" => $x, "chat_id" => $chat_id], $bodyData["users"]);
$this->chatUserModel->insertBatch($chatUserData);
foreach ($bodyData["users"] as $userId) {
$this->chatNotificationModel->insert(
["chat_message_id" => $chatMessageId, "user_id" => $userId]
);
}
}
return $this->response->setJSON(["message" => "Hebra creada correctamente", "status" => true]);
}
public function update_hebra($chat_id)
{
$bodyData = $this->request->getPost();
@ -620,11 +418,7 @@ class ChatController extends BaseController
]);
$actualUsers = $this->chatUserModel->builder()->select("user_id")->where("chat_id", $chat_id)->get()->getResultArray();
$actualUsersArray = array_map(fn($x) => $x["user_id"], $actualUsers);
foreach ($actualUsersArray as $key => $user_id) {
$this->chatNotificationModel->insert(
["chat_message_id" => $chatMessageId, "user_id" => $user_id]
);
}
if (isset($bodyData["users"])) {
foreach ($bodyData["users"] as $userId) {
if (in_array($userId, $actualUsersArray) == false) {
@ -638,55 +432,13 @@ class ChatController extends BaseController
}
return $this->response->setJSON(["message" => "Hebra actualizada correctamente", "status" => true]);
}
public function get_hebra_presupuesto($presupuesto_id)
public function get_hebra(string $model,int $modelId)
{
$data = $this->chatModel->getPresupuestoHebras($presupuesto_id);
$notifications = $this->chatModel->builder()->select([
"chat_notifications.id"
])
->join("chat_messages", "chat_messages.chat_id = chats.id", "left")
->join("chat_notifications", "chat_notifications.chat_message_id = chat_messages.id", "left")
->where("chats.presupuesto_id", $presupuesto_id)
->where("chat_notifications.user_id", auth()->user()->id)
->get()->getResultArray();
foreach ($notifications as $notification) {
$this->chatNotificationModel->update($notification["id"], ["viewed" => true]);
}
return $this->response->setJSON($data);
}
public function get_hebra_pedido($pedido_id)
{
$data = $this->chatModel->getPedidoHebras($pedido_id);
$notifications = $this->chatModel->builder()->select([
"chat_notifications.id"
])
->join("chat_messages", "chat_messages.chat_id = chats.id", "left")
->join("chat_notifications", "chat_notifications.chat_message_id = chat_messages.id", "left")
->where("chats.pedido_id", $pedido_id)
->where("chat_notifications.user_id", auth()->user()->id)
->get()->getResultArray();
foreach ($notifications as $notification) {
$this->chatNotificationModel->update($notification["id"], ["viewed" => true]);
}
return $this->response->setJSON($data);
}
public function get_hebra_factura($factura_id)
{
$data = $this->chatModel->getFacturaHebras($factura_id);
$notifications = $this->chatModel->builder()->select([
"chat_notifications.id"
])
->join("chat_messages", "chat_messages.chat_id = chats.id", "left")
->join("chat_notifications", "chat_notifications.chat_message_id = chat_messages.id", "left")
->where("chats.factura_id", $factura_id)
->where("chat_notifications.user_id", auth()->user()->id)
->get()->getResultArray();
foreach ($notifications as $notification) {
$this->chatNotificationModel->update($notification["id"], ["viewed" => true]);
}
$data = $this->chatService->getHebras($model,$modelId);
return $this->response->setJSON($data);
}
public function datatable_messages()
{
$auth_user_id = auth()->user()->id;
@ -716,9 +468,9 @@ class ChatController extends BaseController
return DataTable::of($query)
->edit('created_at', fn($q) => $q->created_at ? Time::createFromFormat('Y-m-d H:i:s', $q->created_at)->format("d/m/Y H:i") : "")
->edit('updated_at', fn($q) => $q->updated_at ? Time::createFromFormat('Y-m-d H:i:s', $q->updated_at)->format("d/m/Y H:i") : "")
->add("creator", fn($q) => $this->chatModel->getChatFirstUser($q->id)->userFullName)
->add("viewed", fn($q) => $this->chatModel->isMessageChatViewed($q->id, $auth_user_id))
->add("action", fn($q) => ["type" => "presupuesto", "modelId" => $q->id, "isAdmin" => $isAdmin, "lang" => [
->add("viewed", fn($q) => $this->chatModel->isMessageChatViewed($q->chatMessageId))
->edit("creator",fn($q) => $q->userId == $auth_user_id ? '<span class="badge text-bg-success w-100">'.lang("App.me").'</span>' : $q->creator)
->add("action", fn($q) => ["type" => "presupuesto", "modelId" => $q->id, "isAdmin" => $isAdmin,"chatMessageId" => $q->chatMessageId, "lang" => [
"view_chat" => lang('Chat.view_chat'),
"view_by_alt_message" => lang('Chat.view_by_alt_message')
]])
@ -732,9 +484,9 @@ class ChatController extends BaseController
return DataTable::of($query)
->edit('created_at', fn($q) => $q->created_at ? Time::createFromFormat('Y-m-d H:i:s', $q->created_at)->format("d/m/Y H:i") : "")
->edit('updated_at', fn($q) => $q->updated_at ? Time::createFromFormat('Y-m-d H:i:s', $q->updated_at)->format("d/m/Y H:i") : "")
->add("creator", fn($q) => $this->chatModel->getChatFirstUser($q->id)->userFullName)
->add("viewed", fn($q) => $this->chatModel->isMessageChatViewed($q->id, $auth_user_id))
->add("action", fn($q) => ["type" => "pedido", "modelId" => $q->id, "isAdmin" => $isAdmin, "lang" => [
->edit("creator",fn($q) => $q->userId == $auth_user_id ? '<span class="badge text-bg-success w-100">'.lang("App.me").'</span>' : $q->creator)
->add("viewed", fn($q) => $this->chatModel->isMessageChatViewed($q->chatMessageId))
->add("action", fn($q) => ["type" => "pedido", "modelId" => $q->id, "isAdmin" => $isAdmin,"chatMessageId" => $q->chatMessageId, "lang" => [
"view_chat" => lang('Chat.view_chat'),
"view_by_alt_message" => lang('Chat.view_by_alt_message')
]])
@ -749,27 +501,26 @@ class ChatController extends BaseController
return DataTable::of($query)
->edit('created_at', fn($q) => $q->created_at ? Time::createFromFormat('Y-m-d H:i:s', $q->created_at)->format("d/m/Y H:i") : "")
->edit('updated_at', fn($q) => $q->updated_at ? Time::createFromFormat('Y-m-d H:i:s', $q->updated_at)->format("d/m/Y H:i") : "")
->add("creator", fn($q) => $this->chatModel->getChatFirstUser($q->id)->userFullName)
->add("viewed", fn($q) => $this->chatModel->isMessageChatViewed($q->id, $auth_user_id))
->add("action", fn($q) => ["type" => "factura", "modelId" => $q->id, "isAdmin" => $isAdmin, "lang" => [
->edit("creator",fn($q) => $q->userId == $auth_user_id ? '<span class="badge text-bg-success w-100">'.lang("App.me").'</span>' : $q->creator)
->add("viewed", fn($q) => $this->chatModel->isMessageChatViewed($q->chatMessageId))
->add("action", fn($q) => ["type" => "factura", "modelId" => $q->id, "isAdmin" => $isAdmin,"chatMessageId" => $q->chatMessageId, "lang" => [
"view_chat" => lang('Chat.view_chat'),
"view_by_alt_message" => lang('Chat.view_by_alt_message')
]])
->toJson(true);
}
public function get_notifications_not_viewed_from_chat(int $chat_id)
public function get_notifications_not_viewed_from_message(int $chat_message_id)
{
$unviewedNotifications = $this->chatModel->getUsersNotificationNotViewedFromChat($chat_id);
$viewedNotifications = $this->chatModel->getUsersNotificationViewedFromChat($chat_id);
$unviewedNotifications = $this->chatModel->getUsersNotificationNotViewedFromChat($chat_message_id);
// $viewedNotifications = $this->chatModel->getUsersNotificationViewedFromChat($chat_message_id);
return $this->response->setJSON(
[
"data" => [
"unviewedNotifications" => $unviewedNotifications,
"viewedNotifications" => $viewedNotifications
"notifications" => $unviewedNotifications,
],
"chat_id" => $chat_id
"chat_message_id" => $chat_message_id
]
);
}

View File

@ -0,0 +1,79 @@
<?php
namespace App\Entities\Chat;
use App\Models\Chat\ChatDeparmentUserModel;
use App\Models\Chat\ChatModel;
use CodeIgniter\Entity\Entity;
class ChatDepartmentEntity extends Entity
{
protected $attributes = [
"id" => null,
"name" => null,
"display" => null,
"description" => null,
"type" => null,
];
protected $casts = [
"name" => "string",
"display" => "string",
"description" => "?string",
"type" => "string",
];
/**
* Chat department users that are in department as administrador. These users belongs to department in all chats in any model associated and
* will receive notifications always
*
* @return array<ChatDepartmentEntity>
*/
public function chatDepartmentAdminUsers(){
$m = model(ChatDeparmentUserModel::class);
$chatDepartmentUsers = $m->where('chat_department_id',$this->attributes['id'])
->where('pedido_id',null)
->where('factura_id',null)
->where('presupuesto_id',null)->findAll();
return $chatDepartmentUsers;
}
/**
* Chat department users that has been associated to the department by sending a
* message and users that are not as admin of the department that has written a message.
*
* @param integer $modelFkId Id from model associated
* @param string $model Name of the model associated `['presupuesto','pedido','factura']`
* @return array<ChatDepartmentEntity>
*/
public function chatDepartmentExternalUsers(int $modelFkId,string $model = "presupuesto") : array
{
$m = model(ChatDeparmentUserModel::class);
$m->where('chat_department_id',$this->attributes['id']);
switch ($model) {
case 'presupuesto':
$m->where('presupuesto_id',$modelFkId);
break;
case 'pedido':
$m->where('pedido_id',$modelFkId);
break;
case 'factura':
$m->where('pedido_id',$modelFkId);
break;
default:
break;
}
return $m->findAll() ?? [];
}
public function withUsers(int $modelFkId,string $model = "presupuesto") : self
{
$externalUsers = $this->chatDepartmentExternalUsers($modelFkId,$model);
$this->attributes["adminUsers"] = array_map(fn(ChatDepartmentUserEntity $du) => $du->user()->withAvatar() , $this->chatDepartmentAdminUsers());
$this->attributes["externalUsers"] = array_map(fn(ChatDepartmentUserEntity $du) => $du->user()->withAvatar() , $externalUsers);
return $this;
}
}

View File

@ -0,0 +1,60 @@
<?php
namespace App\Entities\Chat;
use App\Entities\Facturas\FacturaEntity;
use App\Entities\Pedidos\PedidoEntity;
use App\Entities\Presupuestos\PresupuestoEntity;
use App\Entities\Usuarios\UserEntity;
use App\Models\Chat\ChatDeparmentModel;
use App\Models\Pedidos\PedidoModel;
use App\Models\Presupuestos\PresupuestoModel;
use App\Models\Usuarios\UserModel;
use CodeIgniter\Entity\Entity;
class ChatDepartmentUserEntity extends Entity
{
protected $attributes = [
"chat_department_id" => null,
"user_id" => null,
"pedido_id" => null,
"factura_id" => null,
"presupuesto_id" => null,
];
protected $casts = [
"chat_department_id" => "integer",
"user_id" => "integer",
"pedido_id" => "?integer",
"factura_id" => "?integer",
"presupuesto_id" => "?integer",
];
public function user() : ?UserEntity
{
$m = model(UserModel::class);
return $m->find($this->attributes['user_id']);
}
public function department() : ?ChatDepartmentEntity
{
$m = model(ChatDeparmentModel::class);
return $m->find($this->attributes['chat_department_id']);
}
public function presupuesto() : ?PresupuestoEntity
{
$m = model(PresupuestoModel::class);
return $m->find($this->attributes['presupuesto_id']);
}
public function pedido() : ?PedidoEntity
{
$m = model(PedidoModel::class);
return $m->find($this->attributes['pedido_id']);
}
public function factura() : ?FacturaEntity
{
$m = model(FacturaEntity::class);
return $m->find($this->attributes['factura_id']);
}
}

View File

@ -0,0 +1,148 @@
<?php
namespace App\Entities\Chat;
use App\Entities\Facturas\FacturaEntity;
use App\Entities\Pedidos\PedidoEntity;
use App\Entities\Presupuestos\PresupuestoEntity;
use App\Entities\Usuarios\UserEntity;
use App\Models\Chat\ChatDeparmentModel;
use App\Models\Chat\ChatMessageModel;
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\Entity\Entity;
use CodeIgniter\Model;
use stdClass;
class ChatEntity extends Entity
{
protected $attributes = [
"id" => null,
"chat_department_id" => null,
"pedido_id" => null,
"presupuesto_id" => null,
"factura_id" => null,
"title" => null
];
protected $casts = [
"chat_department_id" => "?integer",
"pedido_id" => "?integer",
"presupuesto_id" => "?integer",
"factura_id" => "?integer",
"title" => "string"
];
public function withMessages(): self
{
$auth_user = auth()->user();
$messages = $this->messages();
foreach ($messages as $key => $message) {
if ($message->sender_id == $auth_user->id) {
$message->pos = 'right';
} else {
$message->pos = 'left';
}
}
$this->attributes["messages"] = $messages;
return $this;
}
public function department(): ?ChatDepartmentEntity
{
$m = model(ChatDeparmentModel::class);
return $m->find($this->attributes['chat_department_id']);
}
public function presupuesto(): ?PresupuestoEntity
{
$m = model(PresupuestoModel::class);
return $m->find($this->attributes['presupuesto_id']);
}
public function pedido(): ?PedidoEntity
{
$m = model(PedidoModel::class);
return $m->find($this->attributes['pedido_id']);
}
public function factura(): ?FacturaEntity
{
$m = model(FacturaEntity::class);
return $m->find($this->attributes['factura_id']);
}
public function messages(): ?array
{
$m = model(ChatMessageModel::class);
$messages = $m->where('chat_id', $this->attributes["id"])->findAll();
return array_map(fn(ChatMessageEntity $m) => $m->withUser(), $messages);
}
public function withHebra(): self
{
$this->attributes["messages"] = array_map(fn(ChatMessageEntity $m) => $m->withUser(), $this->messages());
$this->attributes["internalUsers"] = array_map(fn(ChatUserEntity $u) => $u->user(), $this->internalUsers());
return $this;
}
/**
* Undocumented function
*
* @return array<ChatUserEntity>
*/
public function internalUsers(): array
{
$m = model(ChatUser::class);
return $m->where('chat_id', $this->attributes["id"])->findAll() ?? [];
}
public function getModel(): ?Model
{
$model = null;
$models = [
"presupuesto_id" => model(PresupuestoModel::class),
"pedido_id" => model(PedidoModel::class),
"factura_id" => model(FacturaModel::class)
];
$fks = [
"presupuesto_id" => $this->attributes["presupuesto_id"],
"pedido_id" => $this->attributes["pedido_id"],
"factura_id" => $this->attributes["factura_id"],
];
foreach ($fks as $key => $fk) {
if ($fk) {
$model = $models[$key];
break;
}
}
return $model;
}
public function relatedFk(): array
{
$relatedFk = null;
$relatedFkValue = null;
$fks = [
"presupuesto" => $this->attributes["presupuesto_id"],
"pedido" => $this->attributes["pedido_id"],
"factura" => $this->attributes["factura_id"],
];
foreach ($fks as $key => $fk) {
if ($fk) {
$relatedFk = $key;
$relatedFkValue = $fk;
break;
}
}
return [
"relatedModel" => $relatedFk,
"relatedFkValue" => $relatedFkValue
];
}
public function withModel() : self
{
if($this->getModel()){
$this->attributes["modelData"] = $this->getModel()->find($this->relatedFk()['relatedFkValue']);
}else{
$this->attributes["modelData"] = null;
}
return $this;
}
}

View File

@ -0,0 +1,65 @@
<?php
namespace App\Entities\Chat;
use App\Entities\Usuarios\UserEntity;
use App\Models\Chat\ChatModel;
use App\Models\ChatNotification;
use App\Models\Usuarios\UserModel;
use CodeIgniter\Entity\Entity;
use CodeIgniter\I18n\Time;
class ChatMessageEntity extends Entity
{
protected $attributes = [
"id" => null,
"message" => null,
"chat_id" => null,
"sender_id" => null,
"receiver_id" => null,
"viewed" => null,
];
protected $casts = [
"message" => "string",
"chat_id" => "integer",
"sender_id" => "?integer",
"receiver_id" => "?integer",
"viewed" => "boolean",
];
protected $dates = [];
public function chat() : ?ChatEntity
{
$m = model(ChatModel::class);
return $m->find($this->attributes['chat_id']);
}
/**
* Notifications related with this chat entity.
*
* @return array<ChatNotificationEntity>
*/
public function notifications() : array
{
$m = model(ChatNotification::class);
return $m->asArray()->where('chat_id',$this->attributes['chat_id'])->findAll() ?? [];
}
public function sentBy() : ?UserEntity
{
$m = model(UserModel::class);
return $m->find($this->attributes["sender_id"])->withAvatar();
}
public function withUser() : self
{
$this->attributes["user"] = $this->sentBy();
return $this;
}
public function getCreatedAt()
{
return Time::createFromFormat("Y-m-d H:i:s",$this->attributes['created_at'])->format('d/m/Y H:i');
}
}

View File

@ -0,0 +1,42 @@
<?php
namespace App\Entities\Chat;
use App\Entities\Usuarios\UserEntity;
use App\Models\Chat\ChatMessageModel;
use App\Models\Usuarios\UserModel;
use CodeIgniter\Entity\Entity;
use CodeIgniter\HTTP\Message;
class ChatNotificationEntity extends Entity
{
protected $attributes = [
"id" => null,
"chat_message_id" => null,
"user_id" => null,
"viewed" => null,
];
protected $casts = [
"chat_message_id" => "integer",
"user_id" => "integer",
"viewed" => "boolean",
];
public function message() : ?ChatMessageEntity
{
$m = model(ChatMessageModel::class);
return $m->find($this->attributes['chat_message_id']);
}
public function user() : ?UserEntity
{
$m = model(UserModel::class);
return $m->find($this->attributes['user_id']);
}
public function chat() : ?ChatEntity
{
return $this->message()->chat();
}
}

View File

@ -0,0 +1,36 @@
<?php
namespace App\Entities\Chat;
use App\Entities\Usuarios\UserEntity;
use App\Models\Chat\ChatModel;
use App\Models\Usuarios\UserModel;
use CodeIgniter\Entity\Entity;
class ChatUserEntity extends Entity
{
protected $attributes = [
"id" => null,
"user_id" => null,
"chat_id" => null,
];
protected $casts = [
"user_id" => "integer",
"chat_id" => "integer",
];
public function chat() : ?ChatEntity
{
$m = model(ChatModel::class);
return $m->find($this->attributes['chat_id']);
}
public function user() : ?UserEntity
{
$m = model(UserModel::class);
return $m->find($this->attributes['user_id'])->withAvatar();
}
}

View File

@ -1,6 +1,8 @@
<?php
namespace App\Entities\Usuarios;
use App\Entities\Chat\ChatNotificationEntity;
use App\Models\ChatNotification;
use CodeIgniter\Entity;
class UserEntity extends \CodeIgniter\Entity\Entity
@ -55,4 +57,20 @@ class UserEntity extends \CodeIgniter\Entity\Entity
{
return $this->getFullName();
}
public function withAvatar() : self
{
$users = auth()->getProvider();
$this->attributes["avatar"] = md5($users->findById($this->attributes['id'])->getEmail());
return $this;
}
/**
* Return an array of ChatNotificationEntities that belongs to the user
*
* @return array<ChatNotificationEntity>
*/
public function chatNotifications() : array
{
$m = model(ChatNotification::class);
return $m->where('user_id',$this->attributes['id'])->findAll() ?? [];
}
}

View File

@ -97,7 +97,10 @@ function getCurrentLanguageFlag(){
}
}
function getGravatarURL(int $size = 30)
{
return "https://gravatar.com/avatar/".md5(auth()->user()->getEmail())."?s=".$size;
}
function getAllClassFolder($folder = null){
try {
helper('filesystem');

View File

@ -826,6 +826,6 @@ return [
"menu_soporte" => "Soporte",
"menu_soporte_new_ticket" => "Crear ticket",
"menu_soporte_ticket_list" => "Mis tickets",
"me" => "Yo",
];

View File

@ -20,6 +20,7 @@ return [
"created_at" => "Fecha creación",
"updated_at" => "Fecha actualización",
"title" => "Título",
"message" => "Mensaje",
"creator" => "Creador",
"viewed" => "Leído",

View File

@ -2,6 +2,7 @@
namespace App\Models\Chat;
use App\Entities\Chat\ChatDepartmentEntity;
use App\Models\Usuarios\UserModel;
use CodeIgniter\Model;
@ -10,7 +11,7 @@ class ChatDeparmentModel extends Model
protected $table = 'chat_departments';
protected $primaryKey = 'id';
protected $useAutoIncrement = true;
protected $returnType = 'object';
protected $returnType = ChatDepartmentEntity::class;
protected $useSoftDeletes = true;
protected $protectFields = true;
protected $allowedFields = [
@ -181,4 +182,20 @@ class ChatDeparmentModel extends Model
{
return $this->select(['id','display','description'])->where('deleted_at',null);
}
public function getModelChatDepartments(string $modelFk,int $modelId) : array
{
$query = $this->builder()->select([
'chat_departments.id',
'chat_departments.name',
'chat_departments.display',
'COUNT(chat_messages.id) as countMessages'
])
->join('chats','chats.chat_department_id = chat_departments.id','left')
->join('chat_messages','chat_messages.chat_id = chats.id','left')
->where($modelFk,$modelId)
->groupBy('chat_departments.name');
return $query->get()->getResultArray() ?? [];
}
}

View File

@ -2,6 +2,7 @@
namespace App\Models\Chat;
use App\Entities\Chat\ChatDepartmentUserEntity;
use App\Models\Usuarios\UserModel;
use CodeIgniter\Model;
@ -10,7 +11,7 @@ class ChatDeparmentUserModel extends Model
protected $table = 'chat_department_users';
protected $primaryKey = 'id';
protected $useAutoIncrement = true;
protected $returnType = 'array';
protected $returnType = ChatDepartmentUserEntity::class;
protected $useSoftDeletes = true;
protected $protectFields = true;
protected $allowedFields = [

View File

@ -2,6 +2,7 @@
namespace App\Models\Chat;
use App\Entities\Chat\ChatMessageEntity;
use App\Models\ChatNotification;
use App\Models\Usuarios\UserModel;
use CodeIgniter\Model;
@ -12,7 +13,7 @@ class ChatMessageModel extends Model
protected $table = 'chat_messages';
protected $primaryKey = 'id';
protected $useAutoIncrement = true;
protected $returnType = 'object';
protected $returnType = ChatMessageEntity::class;
protected $useSoftDeletes = true;
protected $protectFields = true;
protected $allowedFields = [
@ -45,7 +46,7 @@ class ChatMessageModel extends Model
// Callbacks
protected $allowCallbacks = true;
protected $beforeInsert = [];
protected $afterInsert = [];
protected $afterInsert = ['callbackNewMessage'];
protected $beforeUpdate = [];
protected $afterUpdate = [];
protected $beforeFind = [];
@ -82,7 +83,6 @@ class ChatMessageModel extends Model
if ($auth_user->id == $message->sender_id) {
$message->sender_first_name = $auth_user->first_name;
$message->sender_last_name = $auth_user->last_name;
} else {
$sender_user = $user->find($message->sender_id);
$message->sender_first_name = $sender_user->first_name;
@ -133,10 +133,10 @@ class ChatMessageModel extends Model
->where("receiver_id", auth()->user()->id)->countAllResults();
return $messagesFromReceiver;
}
public function get_chat_department_messages_count(int $chat_id) : int
public function get_chat_department_messages_count(int $chat_id): int
{
$chatDepartmentMessagesCount = $this->builder()
->where("id",$chat_id)
->where("id", $chat_id)
->countAllResults();
return $chatDepartmentMessagesCount;
}
@ -194,4 +194,46 @@ class ChatMessageModel extends Model
return $messagesFromReceiver;
}
public function callbackNewMessage(array $data)
{
$authUser = auth()->user();
$chatNotificationModel = model(ChatNotification::class);
$chatMessageEntity = $this->find($data["id"]);
$chatEntity = $chatMessageEntity->chat();
if ($chatEntity->chat_department_id) {
$chatDepartmentEntity = $chatEntity->department();
$adminUsers = $chatDepartmentEntity->chatDepartmentAdminUsers();
$modelFk = $chatEntity->relatedFk();
$externalUsers = $chatDepartmentEntity->chatDepartmentExternalUsers($modelFk["relatedFkValue"], $modelFk["relatedModel"]);
if ($modelFk["relatedModel"] && $modelFk["relatedFkValue"]) {
foreach ($adminUsers as $user) {
if ($user->user_id != $authUser->id) {
$chatNotificationModel->insert([
"user_id" => $user->user_id,
"chat_message_id" => $data["id"]
]);
}
}
foreach ($externalUsers as $user) {
if ($user->user_id != $authUser->id) {
$chatNotificationModel->insert([
"user_id" => $user->user_id,
"chat_message_id" => $data["id"]
]);
}
}
}
}else{
foreach ($chatEntity->internalUsers() as $user) {
if ($user->user_id != $authUser->id) {
$chatNotificationModel->insert([
"user_id" => $user->user_id,
"chat_message_id" => $data["id"]
]);
}
}
}
return $data;
}
}

View File

@ -2,6 +2,7 @@
namespace App\Models\Chat;
use App\Entities\Chat\ChatEntity;
use App\Models\ChatNotification;
use App\Models\ChatUser;
use App\Models\Facturas\FacturaModel;
@ -16,7 +17,7 @@ class ChatModel extends Model
protected $table = 'chats';
protected $primaryKey = 'id';
protected $useAutoIncrement = true;
protected $returnType = 'object';
protected $returnType = ChatEntity::class;
protected $useSoftDeletes = true;
protected $protectFields = true;
protected $allowedFields = [
@ -315,12 +316,6 @@ class ChatModel extends Model
}
public function getChatDepartmentNotifications()
{
$chatDeparmentModel = model(ChatDeparmentModel::class);
$chatMessageModel = model(ChatMessageModel::class);
$presupuestoModel = model(PresupuestoModel::class);
$facturaModel = model(FacturaModel::class);
$pedidoModel = model(PedidoModel::class);
$q = $this->builder()
->select([
"chats.id as chatId",
@ -329,7 +324,7 @@ class ChatModel extends Model
"chats.presupuesto_id as presupuestoId",
"chats.factura_id as facturaId",
"chats.title as chatDisplay",
"COUNT(chat_notifications.viewed) as unreadMessages"
"COUNT(chat_notifications.id) as unreadMessages"
])
->join("chat_messages", "chat_messages.chat_id = chats.id", "left")
->join("chat_notifications", "chat_notifications.chat_message_id = chat_messages.id", "left")
@ -343,36 +338,28 @@ class ChatModel extends Model
$rows_new = [];
foreach ($rows as $row) {
if ($row->presupuestoId) {
$row->model = $presupuestoModel->find($row->presupuestoId);
// $row->model = $presupuestoModel->find($row->presupuestoId);
if ($auth_user->cliente_id) {
$row->uri = "/presupuestocliente/edit/" . $row->presupuestoId . "#accordionChatPresupuesto";
} else {
$row->uri = "/presupuestoadmin/edit/" . $row->presupuestoId . "#accordionChatPresupuesto";
}
$row->title = $row->presupuestoId;
if ($row->chatDepartmentId) {
$row->chatDisplay = $row->model->titulo;
} else {
$row->chatDisplay .= "[INTERNAL]";
}
$row->avatar = "PRE";
$rows_new[] = $row;
} elseif ($row->pedidoId) {
$row->model = $pedidoModel->find($row->pedidoId);
// $row->model = $pedidoModel->find($row->pedidoId);
$row->uri = "/pedidos/edit/" . $row->pedidoId . "#accordionChatPedido";
$row->title = $row->pedidoId;
if ($row->chatDepartmentId) {
$row->chatDisplay .= "[INTERNAL]";
}
$row->avatar = "P";
$rows_new[] = $row;
} elseif ($row->facturaId) {
$row->model = $facturaModel->find($row->facturaId);
// $row->model = $facturaModel->find($row->facturaId);
$row->uri = "/chat/factura/" . $row->facturaId . "#accordionChatFactura";
$row->avatar = "F";
if ($row->chatDepartmentId) {
$row->chatDisplay .= "[INTERNAL]";
}
$row->title = $row->facturaId;
$rows_new[] = $row;
}
@ -381,10 +368,6 @@ class ChatModel extends Model
}
public function getChatInternalNotifications()
{
$presupuestoModel = model(PresupuestoModel::class);
$facturaModel = model(FacturaModel::class);
$pedidoModel = model(PedidoModel::class);
$q = $this->builder()
->select([
"chats.id as chatId",
@ -393,52 +376,41 @@ class ChatModel extends Model
"chats.presupuesto_id as presupuestoId",
"chats.factura_id as facturaId",
"chats.title as chatDisplay",
"COUNT(chat_messages.id) as unreadMessages"
])
->join("chat_messages", "chat_messages.chat_id = chats.id", "left")
->join("chat_notifications", "chat_notifications.chat_message_id = chat_messages.id", "left")
->where("chat_notifications.user_id", auth()->user()->id)
->where("chat_notifications.viewed", false)
->where("chats.chat_department_id", null);
->where("chats.chat_department_id", null)
->groupBy('chats.id');
$auth_user = auth()->user();
$rows = $q->get()->getResultObject();
$rows_new = [];
foreach ($rows as $row) {
$row->unreadMessages = 0;
if ($row->presupuestoId) {
$row->model = $presupuestoModel->find($row->presupuestoId);
if ($auth_user->cliente_id) {
$row->uri = "/presupuestocliente/edit/" . $row->presupuestoId . "#accordionChatPresupuesto";
} else {
$row->uri = "/presupuestoadmin/edit/" . $row->presupuestoId . "#accordionChatPresupuesto";
}
$row->title = $row->presupuestoId;
if ($row->chatDepartmentId) {
$row->chatDisplay = $row->model->titulo;
} else {
$row->chatDisplay .= "[INTERNAL]";
}
$row->chatDisplay .= "[INTERNAL]";
$row->avatar = "PRE";
$row->unreadMessages = $this->countUnreadMessagePresupuesto($row->presupuestoId);
$rows_new[] = $row;
} elseif ($row->pedidoId) {
$row->model = $pedidoModel->find($row->pedidoId);
$row->uri = "/pedidos/edit/" . $row->pedidoId . "#accordionChatFactura";
$row->title = $row->pedidoId;
if ($row->chatDepartmentId) {
$row->chatDisplay .= "[INTERNAL]";
}
$row->chatDisplay .= "[INTERNAL]";
$row->avatar = "P";
$row->unreadMessages = $this->countUnreadMessagePedido($row->pedidoId);
$rows_new[] = $row;
} elseif ($row->facturaId) {
$row->model = $facturaModel->find($row->facturaId);
$row->uri = "/factura/edit/" . $row->facturaId . "#accordionChatFactura";
$row->avatar = "F";
if ($row->chatDepartmentId) {
$row->chatDisplay .= "[INTERNAL]";
}
$row->chatDisplay .= "[INTERNAL]";
$row->title = $row->facturaId;
$row->unreadMessages = $this->countUnreadMessageFactura($row->facturaId);
$rows_new[] = $row;
}
}
@ -585,7 +557,7 @@ class ChatModel extends Model
}
return $data;
}
public function countUnreadMessagePresupuesto(int $presupuesto_id,int $chat_department_id): int|string
public function countUnreadMessagePresupuesto(int $presupuesto_id): int|string
{
return $this->builder()->select()
->join("chat_messages", "chat_messages.chat_id = chats.id", "left")
@ -593,7 +565,6 @@ class ChatModel extends Model
->where("chats.presupuesto_id", $presupuesto_id)
->where("chat_notifications.viewed", false)
->where("chat_notifications.user_id", auth()->user()->id)
->where('chats.chat_department_id',$chat_department_id)
->countAllResults();
}
public function countUnreadMessagePedido($pedido_id): int|string
@ -675,6 +646,7 @@ class ChatModel extends Model
->orderBy("chat_messages.created_at", 'ASC');
return $q->get()->getFirstRow();
}
/**
* Check if all messages of a chat sent to an user have been viewed.
*
@ -682,13 +654,12 @@ class ChatModel extends Model
* @param integer $user_id
* @return boolean True : All messages readed
*/
public function isMessageChatViewed(int $chat_id, int $user_id): bool
public function isMessageChatViewed(int $chat_message_id): bool
{
$q = $this->builder()->select(["chat_notifications.id"])
$q = $this->builder()->select(["chat_notifications.id as cnId"])
->join("chat_messages", "chat_messages.chat_id = chats.id", 'left')
->join("chat_notifications", "chat_notifications.chat_message_id = chat_messages.id", 'left')
->where("chats.id", $chat_id)
// ->where("chat_notifications.user_id", $user_id)
->where("chat_messages.id", $chat_message_id)
->where("chat_notifications.viewed", false);
$unread_messages_count = $q->countAllResults();
if ($unread_messages_count > 0) {
@ -704,7 +675,7 @@ class ChatModel extends Model
* @param integer $chat_id
* @return array True : All messages readed
*/
public function getUsersNotificationNotViewedFromChat(int $chat_id): array
public function getUsersNotificationNotViewedFromChat(int $chat_message_id): array
{
$q = $this->builder()->distinct()->select(
[
@ -717,13 +688,12 @@ class ChatModel extends Model
->join("chat_messages", "chat_messages.chat_id = chats.id", 'left')
->join("chat_notifications", "chat_notifications.chat_message_id = chat_messages.id", 'left')
->join("users", "users.id = chat_notifications.user_id", 'left')
->where("chats.id", $chat_id)
->where("chat_messages.id", $chat_message_id)
->where("chat_notifications.deleted_at", null)
->where('chat_notifications.viewed',false)
->get()->getResultArray();
return $q;
}
public function getUsersNotificationViewedFromChat(int $chat_id): array
public function getUsersNotificationViewedFromChat(int $chat_message_id): array
{
$q = $this->builder()->distinct()->select(
[
@ -736,9 +706,9 @@ class ChatModel extends Model
->join("chat_messages", "chat_messages.chat_id = chats.id", 'left')
->join("chat_notifications", "chat_notifications.chat_message_id = chat_messages.id", 'left')
->join("users", "users.id = chat_notifications.user_id", 'left')
->where("chats.id", $chat_id)
->where("chat_messages.id", $chat_message_id)
->where("chat_notifications.deleted_at", null)
->where('chat_notifications.viewed',true)
->where('chat_notifications.viewed', true)
->get()->getResultArray();
return $q;
}
@ -772,78 +742,93 @@ class ChatModel extends Model
$query = $this->builder()
->select([
"chats.id",
"cm.id as chatMessageId",
"u.id as userId",
"cm.message",
"chats.created_at",
"cm.updated_at",
"chats.title",
"
(
SELECT cm2.updated_at
FROM chat_messages cm2
WHERE cm2.chat_id = chats.id
ORDER BY cm2.updated_at DESC LIMIT 1
) as updated_at",
"CONCAT(u.first_name,' ',u.last_name) as creator",
"CONCAT('[',chats.title,']',' ',presupuestos.titulo) as title",
])
->join("chat_users", "chats.id = chat_users.chat_id", "left")
->join("presupuestos", "presupuestos.id = chats.presupuesto_id", 'left')
->join("chat_messages cm", "chats.id = cm.chat_id", "left")
->where("chats.presupuesto_id is NOT NULL", NULL, FALSE)
->where("cm.updated_at = (
SELECT cm2.updated_at
FROM chat_messages cm2
WHERE cm2.chat_id = chats.id
ORDER BY cm2.updated_at DESC LIMIT 1
)");
->join("users u", "u.id = cm.sender_id", 'left')
->where("chats.presupuesto_id is NOT NULL", NULL, FALSE);
if (auth()->user()->inGroup("admin") == false) {
$query->where('presupuestos.cliente_id', auth()->user()->cliente_id)
->where("chat_department_id is NOT NULL", NULL, FALSE);
->where("chats.chat_department_id is NOT NULL", NULL, FALSE);
}
return $query;
return $query->groupBy('chatMessageId');
}
public function getQueryDatatableMessagePedido(int $user_id): BaseBuilder
{
$query = $this->builder()
->select([
"chats.id",
"cm.id as chatMessageId",
"u.id as userId",
"cm.message",
"chats.created_at",
"cm.updated_at",
"chats.title",
])
->join("chat_users", "chat_users.chat_id = chats.id", "left")
->join("pedidos_linea", "pedidos_linea.pedido_id = chats.pedido_id", 'left')
->join("chat_messages cm", "chats.id = cm.chat_id", "left")
->join("presupuestos", "presupuestos.id = pedidos_linea.presupuesto_id", 'left')
->where("chats.pedido_id is NOT NULL", NULL, FALSE)
->where("cm.updated_at = (
"
(
SELECT cm2.updated_at
FROM chat_messages cm2
WHERE cm2.chat_id = chats.id
ORDER BY cm2.updated_at DESC LIMIT 1
)");
) as updated_at",
"CONCAT(u.first_name,' ',u.last_name) as creator",
"CONCAT('[',chats.title,']',' ',presupuestos.titulo) as title",
])
->join("pedidos_linea", "pedidos_linea.pedido_id = chats.pedido_id", 'left')
->join("chat_messages cm", "chats.id = cm.chat_id", "left")
->join("users u", "u.id = cm.sender_id", 'left')
->join("presupuestos", "presupuestos.id = pedidos_linea.presupuesto_id", 'left')
->where("chats.pedido_id is NOT NULL", NULL, FALSE);
if (auth()->user()->inGroup("admin") == false) {
$query->where('presupuestos.cliente_id', auth()->user()->cliente_id)
->where("chat_department_id is NOT NULL", NULL, FALSE);
->where("chats.chat_department_id is NOT NULL", NULL, FALSE);
}
return $query;
return $query->groupBy('chatMessageId');
}
public function getQueryDatatableMessageFactura(int $user_id): BaseBuilder
{
$query = $this->builder()
->select([
"chats.id",
"cm.id as chatMessageId",
"u.id as userId",
"cm.message",
"chats.created_at",
"cm.updated_at",
"chats.title",
])
->join("chat_users", "chat_users.chat_id = chats.id", "left")
->join("chat_messages cm", "chats.id = cm.chat_id", "left")
->join("facturas", "facturas.id = chats.factura_id", "left")
->where("chats.factura_id is NOT NULL", NULL, FALSE)
->where("cm.updated_at = (
"
(
SELECT cm2.updated_at
FROM chat_messages cm2
WHERE cm2.chat_id = chats.id
ORDER BY cm2.updated_at DESC LIMIT 1
)");
) as updated_at",
"CONCAT(u.first_name,' ',u.last_name) as creator",
"chats.title",
])
->join("chat_messages cm", "chats.id = cm.chat_id", "left")
->join("users u", "u.id = cm.sender_id", 'left')
->join("facturas", "facturas.id = chats.factura_id", "left")
->where("chats.factura_id is NOT NULL", NULL, FALSE);
if (auth()->user()->inGroup("admin") == false) {
if (auth()->user()->inGroup("admin") == false) {
$query->where('facturas.cliente_id', auth()->user()->cliente_id)
->where("chat_department_id is NOT NULL", NULL, FALSE);
->where("chats.chat_department_id is NOT NULL", NULL, FALSE);
}
}
return $query;
return $query->groupBy('chatMessageId');
}
public function createNewDirectChat(string $title, string $message, array $users)
{
@ -923,12 +908,12 @@ class ChatModel extends Model
->select("chat_notifications.id as notificationId")
->join('chat_messages', 'chat_messages.chat_id = chats.id', 'left')
->join('chat_notifications', 'chat_notifications.chat_message_id = chat_messages.id', 'left')
->where('chat_notifications.user_id',$user_id)
->where('chat_notifications.user_id', $user_id)
->where('chat_messages.chat_id', $chat_id)
->get()->getResultObject();
$chat_messages_ids = array_map(fn($q) => $q->notificationId, $query);
$chatNotificationModel = model(ChatNotification::class);
if($chat_messages_ids){
if ($chat_messages_ids) {
$chatNotificationModel->setNotificationsAsViewed($chat_messages_ids);
}
}
@ -945,12 +930,12 @@ class ChatModel extends Model
->select("chat_notifications.id as notificationId")
->join('chat_messages', 'chat_messages.chat_id = chats.id', 'left')
->join('chat_notifications', 'chat_notifications.chat_message_id = chat_messages.id', 'left')
->where('chat_notifications.user_id',$user_id)
->where('chat_notifications.user_id', $user_id)
->where('chat_messages.chat_id', $chat_id)
->get()->getResultObject();
$chat_messages_ids = array_map(fn($q) => $q->notificationId, $query);
$chatNotificationModel = model(ChatNotification::class);
if($chat_messages_ids){
if ($chat_messages_ids) {
$chatNotificationModel->setNotificationsAsUnViewed($chat_messages_ids);
}
}

View File

@ -2,6 +2,7 @@
namespace App\Models;
use App\Entities\Chat\ChatNotificationEntity;
use CodeIgniter\Model;
class ChatNotification extends Model
@ -9,7 +10,7 @@ class ChatNotification extends Model
protected $table = 'chat_notifications';
protected $primaryKey = 'id';
protected $useAutoIncrement = true;
protected $returnType = 'array';
protected $returnType = ChatNotificationEntity::class;
protected $useSoftDeletes = false;
protected $protectFields = true;
protected $allowedFields = [

View File

@ -2,6 +2,7 @@
namespace App\Models;
use App\Entities\Chat\ChatUserEntity;
use CodeIgniter\Model;
class ChatUser extends Model
@ -9,7 +10,7 @@ class ChatUser extends Model
protected $table = 'chat_users';
protected $primaryKey = 'id';
protected $useAutoIncrement = true;
protected $returnType = 'array';
protected $returnType = ChatUserEntity::class;
protected $useSoftDeletes = true;
protected $protectFields = true;
protected $allowedFields = [

View File

@ -0,0 +1,176 @@
<?php
namespace App\Services;
use App\Controllers\Configuracion\ConfigVariables;
use App\Entities\Chat\ChatEntity;
use App\Entities\Chat\ChatMessageEntity;
use App\Entities\Chat\ChatNotificationEntity;
use App\Entities\Usuarios\UserEntity;
use App\Models\Chat\ChatDeparmentModel;
use App\Models\Chat\ChatDeparmentUserModel;
use App\Models\Chat\ChatMessageModel;
use App\Models\Chat\ChatModel;
use App\Models\ChatNotification;
use App\Models\ChatUser;
use App\Models\Configuracion\ConfigVariableModel;
use App\Models\Presupuestos\PresupuestoModel;
use App\Models\Usuarios\UserModel;
use CodeIgniter\Config\BaseService;
class ChatService extends BaseService
{
protected ?ChatEntity $chatEntity;
protected ChatModel $chatModel;
protected ChatMessageModel $chatMessageModel;
protected ChatUser $chatUserModel;
protected ChatNotification $chatNotificationModel;
protected PresupuestoModel $presupuestoModel;
protected ChatDeparmentModel $chatDepartmentModel;
protected ChatDeparmentUserModel $chatDepartmentUserModel;
protected ConfigVariableModel $configVariables;
protected array $modelFkMap = [
"presupuesto" => "presupuesto_id",
"pedido" => "pedido_id",
"factura" => "factura_id",
];
protected array $modelClassMap;
public function __construct()
{
$this->chatModel = model(ChatModel::class);
$this->chatMessageModel = model(ChatMessageModel::class);
$this->chatNotificationModel = model(ChatNotification::class);
$this->chatDepartmentUserModel = model(ChatDeparmentUserModel::class);
$this->chatUserModel = model(ChatUser::class);
$this->presupuestoModel = model(PresupuestoModel::class);
$this->chatDepartmentModel = model(ChatDeparmentModel::class);
$this->configVariables = model(ConfigVariableModel::class);
}
public function setChat($chatEntity): self
{
$this->chatEntity = $chatEntity;
return $this;
}
public function storeChatMessage(string $chatDepartmentId, string $model, int $modelId, array $data): ?ChatMessageEntity
{
$this->chatEntity = $this->chatModel->where('chat_department_id', $chatDepartmentId)->where($this->modelFkMap[$model], $modelId)->first();
if ($this->chatEntity == null) {
$chatId = $this->createChat($chatDepartmentId, $model, $modelId);
$this->chatEntity = $this->chatModel->find($chatId);
}
if ($data["client"]) {
$cliente_in_department = $this->chatDepartmentUserModel
->where('chat_department_id', $chatDepartmentId)
->where('user_id', $data['client'])
->where($this->modelFkMap[$model], $modelId)
->first();
if ($cliente_in_department == null) {
$this->chatDepartmentUserModel->insert(['chat_department_id' => $chatDepartmentId, 'user_id' => $data['client'], $this->modelFkMap[$model] => $modelId]);
}
}
$userAdminDepartment = $this->chatDepartmentUserModel
->where('chat_department_id', $data["chat_department_id"])
->where('user_id', auth()->user()->id)
->where("pedido_id", null)
->where("factura_id", null)
->where("presupuesto_id", null)
->first();
$userAlreadyInDepartment = $this->chatDepartmentUserModel
->where('chat_department_id', $data["chat_department_id"])
->where('user_id', auth()->user()->id)
->where($this->modelFkMap[$model], $modelId)
->first();
if ($userAdminDepartment == null && $userAlreadyInDepartment == null) {
$this->chatDepartmentUserModel->insert(['chat_department_id' => $data["chat_department_id"], $this->modelFkMap[$model] => $modelId, 'user_id' => auth()->user()->id]);
}
$chat_message_id = $this->chatMessageModel->insert(["chat_id" => $this->chatEntity->id, "sender_id" => auth()->user()->id, "message" => $data["message"]]);
$chatMessageEntity = $this->chatMessageModel->find($chat_message_id);
return $chatMessageEntity;
}
public function createChat(int $chatDepartmentId, string $model, int $modelId): bool|int|string
{
$r = false;
switch ($model) {
case 'presupuesto':
$r = $this->chatModel->createChatPresupuesto($chatDepartmentId, $modelId);
break;
case 'pedido':
$r = $this->chatModel->createChatPedido($chatDepartmentId, $modelId);
break;
case 'factura':
$r = $this->chatModel->createChatFactura($chatDepartmentId, $modelId);
break;
default:
break;
}
return $r;
}
public function getChatDepartments(string $model, int $modelId): array
{
$chatDepartments = $this->chatDepartmentModel->getModelChatDepartments($this->modelFkMap[$model], $modelId);
$departmentWithChat = array_map(fn($q) => $q["name"], $chatDepartments);
if(count($departmentWithChat) > 0){
$departmentWithoutChat = $this->chatDepartmentModel->whereNotIn('name', $departmentWithChat)->findAll();
}else{
$departmentWithoutChat = $this->chatDepartmentModel->findAll();
}
foreach ($departmentWithoutChat as $value) {
$d = [];
$d["id"] = $value->id;
$d["name"] = $value->name;
$d["display"] = $value->display;
$d["countMessages"] = "0";
$chatDepartments[] = $d;
}
return $chatDepartments;
}
public function storeHebra(string $model, int $modelId, array $data): bool
{
$auth_user = auth()->user();
$chatId = $this->chatModel->insert([$this->modelFkMap[$model] => $modelId, 'title' => $data['title']]);
if (isset($data["users"])) {
$data["users"][] = $auth_user->id;
$chatUserData = array_map(fn($x) => ["user_id" => $x, "chat_id" => $chatId], $data["users"]);
$this->chatUserModel->insertBatch($chatUserData);
}
$this->chatMessageModel->insert(
[
'chat_id' => $chatId,
'message' => $data['message'],
'sender_id' => $auth_user->id
]
);
return true;
}
public function getHebras(string $model, int $modelId): array
{
$chats = $this->chatModel->where('chat_department_id', null)
->where($this->modelFkMap[$model], $modelId)
->findAll();
foreach ($chats as $c) {
$this->chatModel->setAsViewedChatUserNotifications($c->id,auth()->user()->id);
}
$chatWithHebraData = array_map(fn(ChatEntity $c) => $c->withHebra(), $chats);
return $chatWithHebraData ?? [];
}
public function getAuthUserNotifications(): array
{
$departmentNotifications = $this->chatModel->getChatDepartmentNotifications();
$internalNotifications = $this->chatModel->getChatInternalNotifications();
$totalMessages = 0;
$countNotificiationDepartments = array_map(fn($n) => $n->unreadMessages,$departmentNotifications);
$countNotificationInternal = array_map(fn($n) => $n->unreadMessages,$internalNotifications);
$totalMessages = array_sum($countNotificiationDepartments) + array_sum($countNotificationInternal);
return [
"departmentNotifications" => $departmentNotifications,
"internalNotifications" => $internalNotifications,
"totalMessages" => $totalMessages
];
}
}

View File

@ -4,10 +4,20 @@
<th><?= lang('Chat.datatable_messages.created_at') ?></th>
<th><?= lang('Chat.datatable_messages.updated_at') ?></th>
<th><?= lang('Chat.datatable_messages.title') ?></th>
<th><?= lang('Chat.datatable_messages.message') ?></th>
<th><?= lang('Chat.datatable_messages.creator') ?></th>
<th><?= lang('Chat.datatable_messages.viewed') ?></th>
<th class="text-nowrap"><?= lang('Basic.global.Action') ?></th>
</tr>
<tr>
<th></th>
<th></th>
<th><input type="text" class="form-control datatable-message-filter" name="title"></th>
<th><input type="text" class="form-control datatable-message-filter" name="message"></th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>

View File

@ -250,7 +250,7 @@ $picture = "/assets/img/default-user.png";
<a class="nav-link dropdown-toggle hide-arrow" href="javascript:void(0);"
data-bs-toggle="dropdown">
<div class="avatar">
<img src="<?= $picture ?? '' ?>" alt class="h-auto rounded-circle" />
<img src="<?= getGravatarURL(50) ?? '' ?>" alt class="h-auto rounded-circle" />
</div>
</a>
<ul class="dropdown-menu dropdown-menu-end">
@ -259,7 +259,7 @@ $picture = "/assets/img/default-user.png";
<div class="d-flex">
<div class="flex-shrink-0 me-3">
<div class="avatar avatar">
<img src="<?= $picture ?? '' ?>" alt class="h-auto rounded-circle" />
<img src="<?= getGravatarURL() ?? '' ?>" alt class="h-auto rounded-circle" />
</div>
</div>
<div class="flex-grow-1">
@ -346,7 +346,6 @@ $picture = "/assets/img/default-user.png";
<!-- build:js assets/vendor/js/core.js -->
<script src="<?= site_url('themes/vuexy/vendor/libs/jquery/jquery.js') ?>"></script>
<script src="<?= site_url('themes/vuexy/vendor/libs/popper/popper.js') ?>"></script>
<script src="<?= site_url('themes/vuexy/vendor/libs/jquery/jquery.js') ?>"></script>
<script src="<?= site_url('themes/vuexy/vendor/js/bootstrap.js') ?>"></script>
<script src="<?= site_url('themes/vuexy/vendor/libs/flatpickr/flatpickr.js') ?>"></script>
<script src="<?= site_url('themes/vuexy/vendor/libs/perfect-scrollbar/perfect-scrollbar.js') ?>"></script>

View File

@ -138,6 +138,7 @@ class Chat {
this.messageInput.on("keypress", this._sendMessagePressKey.bind(this))
this.initSelectClient()
// setInterval(this._getChatMessage.bind(this), 10000)
@ -149,6 +150,8 @@ class Chat {
this.sendBtnMessageDepartmentClient.on("click", this._sendMessage.bind(this))
this.messageInput.on("keypress", this._sendMessagePressKey.bind(this))
this.initSelectClient()
// setInterval(this._getChatMessage.bind(this), 10000)
}
@ -159,8 +162,7 @@ class Chat {
this.sendBtnMessageDepartmentClient.on("click", this._sendMessage.bind(this))
this.messageInput.on("keypress", this._sendMessagePressKey.bind(this))
this.initSelectClient()
// setInterval(this._getChatMessage.bind(this), 10000)
}
initContacts() {
this.chatType = "internal"
@ -198,7 +200,7 @@ class Chat {
_handleGetChatList(event) {
this.domItem.find(".chat-loader").removeClass("d-none")
let ajax = new Ajax(
"/chat/departments",
`/chat/departments/${this.chatType}/${this.modelId}`,
null,
null,
this._handleGetChatListSuccess.bind(this),
@ -211,7 +213,6 @@ class Chat {
Object.values(data).map(row => {
this.chatList.append(this._getContact(row))
this.chatDeparmentId = row.id
this._getChatTotalMessages(row.name)
this.chatList.find(`#chat_${row.name}`).on("click", (event) => {
$(".chat-contact-list-item").removeClass("active")
$(event.currentTarget).parent().addClass("active")
@ -220,7 +221,6 @@ class Chat {
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._getChatMessage()
this._getChatTotalMessages(row.name)
this._getChatDeparmentUsers()
})
@ -248,8 +248,8 @@ class Chat {
ajax.get()
}
_getChatDeparmentUsersSuccess(deparmentUsers) {
deparmentUsers.admin_users.map(user => this.appendChatDepartmentUser(user))
deparmentUsers.external_users.map(user => this.appendChatDepartmentUser(user, 'warning', 'user'))
deparmentUsers.adminUsers.map(user => this.appendChatDepartmentUser(user))
deparmentUsers.externalUsers.map(user => this.appendChatDepartmentUser(user, 'warning', 'user'))
}
appendChatDepartmentUser(user, color = "primary", icon = "user") {
@ -259,10 +259,8 @@ class Chat {
<div class="d-flex align-items-center py-1"
id="chat-contact-list-item-${user.id}">
<div class="avatar-initial avatar-md px-2 py-2">
<span class="badge badge-center rounded-pill text-bg-${color}">
<i class="icon-base ti ti-xs ti-${icon}"></i>
</span>
<div class="avatar avatar-md px-2 py-2">
<img src="https://gravatar.com/avatar/${user.avatar}?s=40" class="rounded-circle"></img>
</div>
<div class="chat-contact-info flex-grow-1 ms-2">
<h6 class="chat-contact-name text-truncate m-0">${user?.first_name ?? "" + " " +
@ -292,7 +290,7 @@ class Chat {
${row.display}
</p>
</div>
<span class="badge badge-center rounded-pill bg-secondary messages-unread-contact">${row.totalMessages ?? 0}</span>
<span class="badge badge-center rounded-pill bg-secondary messages-unread-contact">${row.countMessages}</span>
</a>
</li>
`
@ -304,7 +302,7 @@ class Chat {
null,
null,
(data) => {
this.chatList.find(`#chat_${row_name} .messages-unread-contact`).text(data.count)
},
null
@ -346,6 +344,7 @@ class Chat {
_getChatMessageSuccess(data) {
this.domItem.find(".chat-loader").addClass("d-none")
this._setBtnDeparment()
this.chatList.find(`#chat_${data.department.name} .messages-unread-contact`).text(data.count ?? 0)
if (data.messages) {
data.messages.map((m) => {
this._addChatMessage(m)
@ -365,7 +364,7 @@ class Chat {
<div class="chat-message-text">
<p class="mb-0">${chatMessage?.message}</p>
</div>
<div class="text-${chatMessage?.pos == "left" ? "start" : "end"} text-muted mt-1">
<div class="text-${chatMessage?.pos == "left" ? "start" : "end"} text-muted mt-1">
<div class="text-${chatMessage?.pos == "left" ? "start" : "end"} text-muted mt-1">
<small>${chatMessage?.user?.first_name + " " + chatMessage?.user?.last_name}</small>
</div>
@ -375,8 +374,8 @@ class Chat {
</div>
<div class="user-avatar flex-shrink-0 ms-3">
<div class="avatar avatar-sm">
<span class="avatar-initial rounded-circle bg-label-primary">${chatMessage?.user?.first_name.charAt(0) + chatMessage?.user?.last_name.charAt(0)}</span>
<div class="avatar avatar-md px-2 py-2">
<img src="https://gravatar.com/avatar/${chatMessage.user.avatar}?s=40" class="rounded-circle"></img>
</div>
</div>
</div>
@ -533,8 +532,6 @@ class Chat {
}
_handleGetSingleContactMessagesSuccess(data) {
try {
if (data) {
data.map((m) => {
this._addChatMessage(m)
@ -824,106 +821,73 @@ class Chat {
}
const addInternalNotification = (e) => {
let numberOfMessages = e.unreadMessages
if (numberOfMessages > 0) {
$("#chat-notification-list").append(
`
<li class="mb-2">
<a href="${e.uri}" class="d-flex align-items-center flex-grow">
<div class="avatar d-block flex-shrink-0">
<span class="avatar-initial rounded-circle bg-label-primary">${e.avatar}</span>
</div>
<div class="chat-contact-info flex-grow-1 ms-2">
<h6 class="chat-contact-name text-truncate m-0">[${e.title}] ${e.chatDisplay}</h6>
</div>
<span class="badge badge-center rounded-pill bg-primary p-1 m-2">${numberOfMessages}</span>
</a>
</li>
`
)
}
}
const addDepartmentNotification = (e) => {
let numberOfMessages = e.unreadMessages
if (numberOfMessages > 0) {
$("#chat-notification-list").append(
`
<li class="mb-2">
<a href="${e.uri}" class="d-flex align-items-center flex-grow">
<div class="avatar d-block flex-shrink-0">
<span class="avatar-initial rounded-circle bg-label-primary">${e.avatar}</span>
</div>
<div class="chat-contact-info flex-grow-1 ms-2">
<h6 class="chat-contact-name text-truncate m-0">[${e.title}] ${e.chatDisplay}</h6>
</div>
<span class="badge badge-center rounded-pill bg-primary p-1 m-2">${numberOfMessages}</span>
</a>
</li>
`
)
}
}
export const showNotificationMessages = (dom) => {
const addNotificationsToDom = (data) =>
{
$("#chat-notification-list").empty()
if (data.totalMessages > 0) {
$("#chat-message-notification-title").addClass("d-none")
$("#chat-notification-number").removeClass("d-none")
$("#chat-notification-number").text(data.totalMessages ?? 0)
} else {
$("#chat-message-notification-title").removeClass("d-none")
$("#chat-notification-number").addClass("d-none")
$("#chat-notification-number").text(0)
}
data.departmentNotifications?.map( e => {
addDepartmentNotification(e)}
)
data.internalNotifications?.map(e => {
addInternalNotification(e)}
)
}
export const showNotificationMessages = () => {
let ajax = new Ajax(
'/chat/notifications',
null,
null,
(data) => {
dom.empty()
$("#chat-notification-number")
if (data.totalMessages > 0) {
$("#chat-message-notification-title").addClass("d-none")
$("#chat-notification-number").removeClass("d-none")
$("#chat-notification-number").text(data.totalMessages ?? 0)
} else {
$("#chat-message-notification-title").removeClass("d-none")
$("#chat-notification-number").addClass("d-none")
$("#chat-notification-number").text(0)
}
data?.internals?.map((e) => {
let numberOfMessages = e.unreadMessages
if (numberOfMessages > 0) {
dom.append(
`
<li class="mb-2">
<a href="${e.uri}" class="d-flex align-items-center flex-grow">
<div class="avatar d-block flex-shrink-0">
<span class="avatar-initial rounded-circle bg-label-primary">${e.avatar}</span>
</div>
<div class="chat-contact-info flex-grow-1 ms-2">
<h6 class="chat-contact-name text-truncate m-0">[${e.title}] ${e.chatDisplay}</h6>
</div>
<span class="badge badge-center rounded-pill bg-primary p-1 m-2">${numberOfMessages}</span>
</a>
</li>
`
)
}
})
data?.chatPresupuestos?.map((e) => {
let numberOfMessages = e.unreadMessages
if (numberOfMessages > 0) {
dom.append(
`
<li class="">
<a href="${e.uri}" class="d-flex align-items-center flex-grow">
<div class="avatar d-block flex-shrink-0">
<span class="avatar-initial rounded-circle bg-label-primary">${e.presupuestoId}</span>
</div>
<div class="chat-contact-info flex-grow-1 ms-2">
<h6 class="chat-contact-name text-truncate m-0">[${e.title}] ${e.chatDisplay}</h6>
</div>
<span class="badge badge-center rounded-pill bg-primary">${numberOfMessages}</span>
</a>
</li>
`
)
}
})
data?.chatFacturas?.map((e) => {
let numberOfMessages = e.unreadMessages
if (numberOfMessages > 0) {
dom.append(
`
<li class="">
<a href="${e.uri}" class="d-flex align-items-center flex-grow">
<div class="avatar d-block flex-shrink-0">
<span class="avatar-initial rounded-circle bg-label-primary">${e.facturaId}</span>
</div>
<div class="chat-contact-info flex-grow-1 ms-2">
<h6 class="chat-contact-name text-truncate m-0">[${e.title}] ${e.chatDisplay}</h6>
</div>
<span class="badge badge-center rounded-pill bg-primary">${numberOfMessages}</span>
</a>
</li>
`
)
}
})
data?.chatPedidos?.map((e) => {
let numberOfMessages = e.unreadMessages
if (numberOfMessages > 0) {
dom.append(
`
<li class="">
<a href="${e.uri}" class="d-flex align-items-center flex-grow">
<div class="avatar d-block flex-shrink-0">
<span class="avatar-initial rounded-circle bg-label-primary">${e.pedidoId}</span>
</div>
<div class="chat-contact-info flex-grow-1 ms-2">
<h6 class="chat-contact-name text-truncate m-0">[${e.title}] ${e.chatDisplay}</h6>
</div>
<span class="badge badge-center rounded-pill bg-primary">${numberOfMessages}</span>
</a>
</li>
`
)
}
})
},
addNotificationsToDom,
(err) => { }
)
ajax.get()
@ -931,104 +895,3 @@ export const showNotificationMessages = (dom) => {
export default Chat
// // Seleccionar elementos del DOM
// const chatContactsBody = document.querySelector('.app-chat-contacts .sidebar-body'),
// chatContactListItems = [].slice.call(
// document.querySelectorAll('.chat-contact-list-item:not(.chat-contact-list-item-title)')
// ),
// chatHistoryBody = document.querySelector('.chat-history-body'),
// chatSidebarLeftUserAbout = document.querySelector('.chat-sidebar-left-user-about'),
// messageInput = document.querySelector('.message-input'),
// searchInput = document.querySelector('.chat-search-input'),
// sendMsgBtn = document.querySelector('.send-msg-btn'); // Seleccionar el botón de envío de mensaje
// // Inicializar PerfectScrollbar
// if (chatContactsBody) {
// new PerfectScrollbar(chatContactsBody, {
// wheelPropagation: false,
// suppressScrollX: true
// });
// }
// if (chatHistoryBody) {
// new PerfectScrollbar(chatHistoryBody, {
// wheelPropagation: false,
// suppressScrollX: true
// });
// }
// // Función para desplazar el scroll al final
// function scrollToBottom() {
// if (chatHistoryBody) {
// chatHistoryBody.scrollTo(0, chatHistoryBody.scrollHeight);
// }
// }
// scrollToBottom();
// // Seleccionar chat o contacto
// // Filtrar chats
// if (searchInput) {
// searchInput.addEventListener('keyup', e => {
// const searchValue = e.currentTarget.value.toLowerCase(),
// chatListItem0 = document.querySelector('.chat-list-item-0'),
// contactListItem0 = document.querySelector('.contact-list-item-0'),
// searchChatListItems = [].slice.call(
// document.querySelectorAll('#chat-list li:not(.chat-contact-list-item-title)')
// ),
// searchContactListItems = [].slice.call(
// document.querySelectorAll('#contact-list li:not(.chat-contact-list-item-title)')
// );
// // Buscar en chats
// const chatListItemsCount = searchChatContacts(searchChatListItems, searchValue);
// // Mostrar u ocultar mensaje de "No se encontraron resultados" en chats
// if (chatListItem0) {
// chatListItem0.classList.toggle('d-none', chatListItemsCount !== 0);
// }
// // Buscar en contactos
// const contactListItemsCount = searchChatContacts(searchContactListItems, searchValue);
// // Mostrar u ocultar mensaje de "No se encontraron resultados" en contactos
// if (contactListItem0) {
// contactListItem0.classList.toggle('d-none', contactListItemsCount !== 0);
// }
// });
// }
// // Función para buscar en chats y contactos
// function searchChatContacts(searchListItems, searchValue) {
// let searchListItemsCount = 0;
// searchListItems.forEach(searchListItem => {
// const searchListItemText = searchListItem.textContent.toLowerCase();
// const matchesSearch = searchListItemText.indexOf(searchValue) !== -1;
// searchListItem.classList.toggle('d-flex', matchesSearch);
// searchListItem.classList.toggle('d-none', !matchesSearch);
// if (matchesSearch) {
// searchListItemsCount++;
// }
// });
// return searchListItemsCount;
// }
// // // Enviar mensaje
// // if (sendMsgBtn) {
// // sendMsgBtn.addEventListener('click', e => {
// // e.preventDefault();
// // if (messageInput.value) {
// // const renderMsg = document.createElement('div');
// // renderMsg.className = 'chat-message-text mt-2';
// // renderMsg.innerHTML = `<p class="mb-0">${messageInput.value}</p>`;
// // const lastChatMessageWrapper = document.querySelector('li:last-child .chat-message-wrapper');
// // if (lastChatMessageWrapper) {
// // lastChatMessageWrapper.appendChild(renderMsg);
// // }
// // messageInput.value = '';
// // scrollToBottom();
// // }
// // });
// // }

View File

@ -7,11 +7,13 @@ class MessagesDatatable {
this.datatablePresupuestoMessageItem = this.item.find("#tablePresupuestoMessages")
this.datatablePedidoMessageItem = this.item.find("#tablePedidoMessages")
this.datatableFacturaMessageItem = this.item.find("#tableFacturaMessages")
this.columnDefs = [
]
this.datatableColumns = [
{ data: 'created_at', searchable: true, sortable: true },
{ data: 'updated_at', searchable: true, sortable: true },
{ data: 'title', searchable: true, sortable: true },
{ data: 'title', name:"chats.title",searchable: true, sortable: true },
{ data: 'message', searchable: false, sortable: true },
{ data: 'creator', searchable: false, sortable: false },
{
data: 'viewed', searchable: false, sortable: true,
@ -27,10 +29,10 @@ class MessagesDatatable {
<a href="/chat/${d.type}/${d.modelId}" class="message-edit" title="${d.lang.view_chat}"><i class="ti ti-eye ti-sm mx-2"></i></a>
${d.isAdmin ?
`<div class="btn-group dropstart btn-group-sm">
<button data-id="${d.modelId}" type="button" title="${d.lang.view_by_alt_message}" class="btn btn-icon rounded-pill dropdown-toggle hide-arrow text-primary btn-notification-viewed" data-bs-toggle="dropdown">
<button data-id="${d.chatMessageId}" type="button" title="${d.lang.view_by_alt_message}" class="btn btn-icon rounded-pill dropdown-toggle hide-arrow text-primary btn-notification-viewed" data-bs-toggle="dropdown">
<i class="icon-base ti ti-messages"></i>
</button>
<ul class="dropdown-menu" id="dropdown-viewed-${d.modelId}">
<ul class="dropdown-menu" id="dropdown-viewed-${d.chatMessageId}">
</ul>
</div>` : ""
}
@ -46,13 +48,16 @@ class MessagesDatatable {
}
init() {
this.item.on('click', '.btn-notification-viewed', (event) => {
const chatId = $(event.currentTarget).data('id')
$(`#dropdown-viewed-${chatId}`).empty()
this.handleDropUp(chatId)
const chatMessageId = $(event.currentTarget).data('id')
$(`#dropdown-viewed-${chatMessageId}`).empty()
this.handleDropUp(chatMessageId)
})
this.datatable = this.datatableItem.DataTable({
processing: true,
order: [[1, 'desc']],
columnDefs : this.columnDefs,
orderCellsTop : true,
layout: {
topStart: 'pageLength',
topEnd: 'search',
@ -71,6 +76,8 @@ class MessagesDatatable {
this.datatablePresupuestoMessage = this.datatablePresupuestoMessageItem.DataTable({
processing: true,
order: [[1, 'desc']],
columnDefs : this.columnDefs,
orderCellsTop : true,
layout: {
topStart: 'pageLength',
topEnd: 'search',
@ -87,6 +94,8 @@ class MessagesDatatable {
});
this.datatablePedidoMessage = this.datatablePedidoMessageItem.DataTable({
processing: true,
orderCellsTop : true,
columnDefs : this.columnDefs,
order: [[1, 'desc']],
layout: {
topStart: 'pageLength',
@ -104,6 +113,8 @@ class MessagesDatatable {
});
this.datatableFacturaMessage = this.datatableFacturaMessageItem.DataTable({
processing: true,
orderCellsTop : true,
columnDefs : this.columnDefs,
order: [[1, 'desc']],
layout: {
topStart: 'pageLength',
@ -119,11 +130,23 @@ class MessagesDatatable {
columns: this.datatableColumns,
ajax: '/messages/datatable/factura'
});
this.datatablePresupuestoMessageItem.on("keyup", ".datatable-message-filter", (event) => {
let columnIndex = this.datatableColumns.findIndex((element) => element.data == $(event.currentTarget).attr("name"))
this.datatablePresupuestoMessage.column(columnIndex).search($(event.currentTarget).val()).draw()
})
this.datatablePedidoMessageItem.on("keyup", ".datatable-message-filter", (event) => {
let columnIndex = this.datatableColumns.findIndex((element) => element.data == $(event.currentTarget).attr("name"))
this.datatablePedidoMessage.column(columnIndex).search($(event.currentTarget).val()).draw()
})
this.datatableFacturaMessageItem.on("keyup", ".datatable-message-filter", (event) => {
let columnIndex = this.datatableColumns.findIndex((element) => element.data == $(event.currentTarget).attr("name"))
this.datatableFacturaMessage.column(columnIndex).search($(event.currentTarget).val()).draw()
})
}
handleDropUp(chatId) {
let ajax = new Ajax('/chat/users/notifications-unviewed/' + chatId,
handleDropUp(chatMessageId) {
let ajax = new Ajax('/chat/users/message/notifications-unviewed/' + chatMessageId,
null,
null,
this.handleDropUpSuccess.bind(this),
@ -133,32 +156,31 @@ class MessagesDatatable {
ajax.get();
}
handleDropUpSuccess(response) {
const chatId = response.chat_id
const unviewedNotifications = response.data.unviewedNotifications
const viewedNotifications = response.data.viewedNotifications
const chat_message_id = response.chat_message_id
const notifications = response.data.notifications
if (unviewedNotifications.length > 0) {
if (notifications.length > 0) {
unviewedNotifications.forEach(user => {
notifications.forEach(user => {
if (user.userFullName || user.userName) {
$(`#dropdown-viewed-${chatId}`)
$(`#dropdown-viewed-${chat_message_id}`)
.append(this.addDropUpItem(user))
}
});
}
if (viewedNotifications.length > 0) {
// if (viewedNotifications.length > 0) {
viewedNotifications.forEach(user => {
if (user.userFullName || user.userName) {
// viewedNotifications.forEach(user => {
// if (user.userFullName || user.userName) {
$(`#dropdown-viewed-${chatId}`)
.append(this.addDropUpItem(user))
}
// $(`#dropdown-viewed-${chat_message_id}`)
// .append(this.addDropUpItem(user))
// }
});
}
// });
// }
}
handleDropUpError() { }
addDropUpItem(user)

View File

@ -5,8 +5,8 @@ import ClassSelect from "./select2.js"
const getInitials = (name) => name.split(" ").map(e => e.charAt(0)).join("")
const hebraList = (message) => `
<div class="list-group-item list-group-item-action d-flex align-items-center cursor-pointer">
<div class="avatar avatar-sm me-2">
<span class="avatar-initial rounded-circle bg-primary" title="${message.senderFullName}">${getInitials(message.senderFullName)}</span>
<div class="avatar avatar-md px-2 py-2">
<img src="https://gravatar.com/avatar/${message.user?.avatar}?s=40" class="rounded-circle"></img>
</div>
<div class="w-100 px-4">
<div class="d-flex flex-column">
@ -18,7 +18,7 @@ const hebraList = (message) => `
${message.created_at}
</p>
<h6>
${message.senderFullName} (${message.senderUserName})
${message.user.first_name} ${message.user.last_name} (${message.user.username})
</h6>
</div>
<p class="text-start">${message.message}</p>
@ -27,12 +27,10 @@ const hebraList = (message) => `
</div>
`
const hebraUsersList = (user) => `
<div class="avatar avatar-md px-2 py-2" title="${user.first_name + " " + user.last_name}">
<img src="https://gravatar.com/avatar/${user.avatar}?s=40" class="rounded-circle"></img>
</div>`
<div class="avatar avatar-sm me-2">
<span class="avatar-initial rounded-circle bg-secondary" title="${user.userFullName}">${getInitials(user.userFullName)}</span>
</div>
`
class InternalMessages {
constructor(domItem) {
this.item = domItem
@ -53,14 +51,14 @@ class InternalMessages {
this.type = this.item.data("type")
this.chatId = null
this.selectMessageUsers = new ClassSelect(this.selectUsers, '/chat/users/internal', "Seleccione un usuario",true)
this.selectMessageUsers = new ClassSelect(this.selectUsers, '/chat/users/internal', "Seleccione un usuario", true)
}
init() {
this.selectMessageUsers.init()
this.item.on("click", ".btn-new-hebra", this.handleBtnNewHebra.bind(this))
this.item.on("click", ".btn-new-hebra-message", this.handleBtnUpdateHebra.bind(this))
this.modalNewMessage.item.on("click","#submit_new_hebra",this.handlePostNewHebra.bind(this))
this.modalNewMessage.item.on("click","#submit_update_hebra",this.handleUpdateHebra.bind(this))
this.modalNewMessage.item.on("click", "#submit_new_hebra", this.handlePostNewHebra.bind(this))
this.modalNewMessage.item.on("click", "#submit_update_hebra", this.handleUpdateHebra.bind(this))
this.handleGetInternalMessages()
}
@ -75,7 +73,7 @@ class InternalMessages {
)
ajax.get()
}
handlePostNewHebra(){
handlePostNewHebra() {
this._handleUpdateFormNewHebraValues()
let ajax = new Ajax(
`/chat/hebra/${this.type}`,
@ -87,12 +85,12 @@ class InternalMessages {
ajax.post()
}
handlePostNewHebraSuccess(data){
handlePostNewHebraSuccess(data) {
this.modalNewMessage.toggle()
this.handleGetInternalMessages()
}
handlePostNewHebraError(err){}
handleUpdateHebra(){
handlePostNewHebraError(err) { }
handleUpdateHebra() {
this._handleUpdateFormUpdateHebraValues()
let ajax = new Ajax(
`/chat/hebra/${this.chatId}`,
@ -103,11 +101,11 @@ class InternalMessages {
)
ajax.post()
}
handleUpdateNewHebraSuccess(data){
handleUpdateNewHebraSuccess(data) {
this.modalNewMessage.toggle()
this.handleGetInternalMessages()
}
handleUpdateNewHebraError(err){}
handleUpdateNewHebraError(err) { }
handleBtnNewHebra(e) {
e.preventDefault()
this.chatId = null
@ -137,34 +135,34 @@ class InternalMessages {
}
_handleUpdateFormNewHebraValues() {
this.formNewValues = {
title : this.hebraTitle.val(),
title: this.hebraTitle.val(),
users: this.selectMessageUsers.getVal(),
message: this.textAreaMessage.val(),
modelId : this.modelId
modelId: this.modelId
}
}
_handleUpdateFormUpdateHebraValues() {
this.formUpdateValues = {
users: this.selectMessageUsers.getVal(),
message: this.textAreaMessage.val(),
modelId : this.modelId
modelId: this.modelId
}
}
_handleGetInternalMessagesSuccess(data){
_handleGetInternalMessagesSuccess(data) {
Object.values(data).map((k) => {
this._addHebraDOM(k.chatId,k.chatTitle,k.messages,k.users)
this._addHebraDOM(k.id, k.title, k.messages, k.internalUsers)
})
}
_handleGetInternalMessagesError(err){}
_handleGetInternalMessagesError(err) { }
_addHebraDOM(key,chatTitle,messages,users) {
_addHebraDOM(key, chatTitle, messages, users) {
const itemHebra = $(`<div id="hebra-item-${key}"></div>`).addClass("border border-container flex-grow-0 container-p-y mt-4 p-5")
const headerHebra = $("<div></div>").addClass("d-flex justify-content-between align-items-center")
const contentHeaderHebra = $("<h4></h4>").text(`${chatTitle}`)
const btnNewHebra = $("<button></button>").attr("type", "button").addClass("btn btn-danger btn-sm btn-new-hebra")
btnNewHebra.append('<span class="ti-xs ti ti-git-branch"></span>')
btnNewHebra.append("Nuevo hilo")
headerHebra.append(contentHeaderHebra,btnNewHebra)
headerHebra.append(contentHeaderHebra, btnNewHebra)
itemHebra.append(headerHebra)
let itemMessagesHebraRow = $("<div></div>").addClass("row")
let itemMessagesHebraCol = $("<div></div>").addClass("col")

View File

@ -2,12 +2,12 @@ import { showNotificationMessages } from "../components/chat.js";
$(() => {
showNotificationMessages($("#chat-notification-list"))
showNotificationMessages()
const chatNotificationInterval = setInterval(() => {
showNotificationMessages($("#chat-notification-list"))
showNotificationMessages()
}, 10000)
$("#message-notification-dropdown").on("click", (e) => {
showNotificationMessages($("#chat-notification-list"))
showNotificationMessages()
})
$("#btn-log-out").on("click",() => {
clearInterval(chatNotificationInterval)