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>