Merge branch 'refactor/messages-view' into feat/ordenes-trabajo

This commit is contained in:
amazuecos
2024-11-30 17:10:26 +01:00
156 changed files with 6538 additions and 2643 deletions

View File

@ -11,10 +11,13 @@ use App\Models\ChatNotification;
use App\Models\ChatUser;
use App\Models\Clientes\ClienteModel;
use App\Models\Usuarios\UserModel;
use App\Services\MessageService;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\Log\Logger;
use Psr\Log\LoggerInterface;
use Hermawan\DataTables\DataTable;
use CodeIgniter\I18n\Time;
class ChatController extends BaseController
{
@ -26,8 +29,8 @@ class ChatController extends BaseController
protected ClienteModel $clienteModel;
protected ChatUser $chatUserModel;
protected ChatNotification $chatNotificationModel;
protected array $viewData;
protected static $viewPath = 'themes/vuexy/form/mensajes/';
public function initController(
@ -46,8 +49,6 @@ class ChatController extends BaseController
$this->clienteModel = model(ClienteModel::class);
$this->chatUserModel = model(ChatUser::class);
$this->chatNotificationModel = model(ChatNotification::class);
}
public function index() {}
public function get_chat_departments()
@ -56,6 +57,10 @@ class ChatController extends BaseController
$data = $this->chatDeparmentModel->getChatDepartments();
return $this->response->setJSON($data);
}
public function get_chat_department_select(){
$query = $this->chatDeparmentModel->getChatDepartmentSelect($this->request->getGet("q"));
return $this->response->setJSON($query->get()->getResultObject());
}
public function get_chat_presupuesto(int $chat_department_id, int $presupuesto_id)
{
@ -86,7 +91,6 @@ class ChatController extends BaseController
$data["messages"] = $this->chatMessageModel->get_chat_messages($chat->id);
$this->chatMessageModel->set_chat_department_messages_as_read($chat->id);
$data["count"] = count($data["messages"]);
}
$data["chat"] = $chat;
return $this->response->setJSON($data);
@ -108,6 +112,76 @@ class ChatController extends BaseController
$data["chat"] = $chat;
return $this->response->setJSON($data);
}
public function get_chat_direct_view($chat_id)
{
$chat = $this->chatModel->find($chat_id);
$this->viewData['breadcrumb'] = [
['title' => lang("Chat.chat"), 'route' => route_to("mensajeriaView"), 'active' => false],
['title' => $chat->title, 'route' => 'javascript:void(0);', 'active' => true]
];
$this->viewData["chatId"] = $chat_id;
$auth_user = auth()->user();
$this->chatModel->setAsViewedChatUserNotifications($chat_id, $auth_user->id);
$this->chatModel->setAsUnviewedChatUserMessages($chat_id, $auth_user->id);
return view(static::$viewPath . 'messageChat', $this->viewData);
}
public function get_chat_presupuesto_view($chat_id)
{
$chat = $this->chatModel->find($chat_id);
$this->viewData['breadcrumb'] = [
['title' => lang("Chat.chat"), 'route' => route_to("mensajeriaView"), 'active' => false],
['title' => $chat->title, 'route' => 'javascript:void(0);', 'active' => true]
];
$this->viewData["modelId"] = $chat->presupuesto_id;
$this->viewData["type"] = "presupuesto";
$auth_user = auth()->user();
$this->chatModel->setAsViewedChatUserNotifications($chat_id, $auth_user->id);
$this->chatModel->setAsUnviewedChatUserMessages($chat_id, $auth_user->id);
if($chat->chat_department_id){
return view(static::$viewPath . 'messageChatPresupuesto', $this->viewData);
}else{
return view(static::$viewPath . 'messageChatInternal', $this->viewData);
}
}
public function get_chat_pedido_view($chat_id)
{
$chat = $this->chatModel->find($chat_id);
$this->viewData['breadcrumb'] = [
['title' => lang("Chat.chat"), 'route' => route_to("mensajeriaView"), 'active' => false],
['title' => $chat->title, 'route' => 'javascript:void(0);', 'active' => true]
];
$this->viewData["modelId"] = $chat->pedido_id;
$this->viewData["type"] = "pedido";
$auth_user = auth()->user();
$this->chatModel->setAsViewedChatUserNotifications($chat_id, $auth_user->id);
$this->chatModel->setAsUnviewedChatUserMessages($chat_id, $auth_user->id);
if($chat->chat_department_id ){
return view(static::$viewPath . 'messageChatPedido', $this->viewData);
}else{
return view(static::$viewPath . 'messageChatInternal', $this->viewData);
}
}
public function get_chat_factura_view($chat_id)
{
$chat = $this->chatModel->find($chat_id);
$this->viewData['breadcrumb'] = [
['title' => lang("Chat.chat"), 'route' => route_to("mensajeriaView"), 'active' => false],
['title' => $chat->title, 'route' => 'javascript:void(0);', 'active' => true]
];
$this->viewData["modelId"] = $chat->factura_id;
$this->viewData["type"] = "factura";
$auth_user = auth()->user();
$this->chatModel->setAsViewedChatUserNotifications($chat_id, $auth_user->id);
$this->chatModel->setAsUnviewedChatUserMessages($chat_id, $auth_user->id);
if($chat->chat_department_id){
return view(static::$viewPath . 'messageChatFactura', $this->viewData);
}else{
return view(static::$viewPath . 'messageChatInternal', $this->viewData);
}
}
public function get_chat(int $chat_id)
{
@ -128,6 +202,12 @@ class ChatController extends BaseController
}
$chat_message_id = $this->chatMessageModel->insert(["chat_id" => $chatId, "sender_id" => auth()->user()->id, "message" => $data["message"]]);
$dataResponse = $this->chatMessageModel->find($chat_message_id);
$chatDepartmentUsers = $this->chatDeparmentModel->getChatDepartmentUsers($data["chat_department_id"]);
foreach ($chatDepartmentUsers as $user) {
if ($user->id != auth()->user()->id) {
$this->chatNotificationModel->insert(["chat_message_id" => $chat_message_id, "user_id" => $user->id]);
}
}
return $this->response->setJSON($dataResponse);
}
public function store_chat_message_pedido()
@ -143,6 +223,12 @@ class ChatController extends BaseController
}
$chat_message_id = $this->chatMessageModel->insert(["chat_id" => $chatId, "sender_id" => auth()->user()->id, "message" => $data["message"]]);
$dataResponse = $this->chatMessageModel->find($chat_message_id);
$chatDepartmentUsers = $this->chatDeparmentModel->getChatDepartmentUsers($data["chat_department_id"]);
foreach ($chatDepartmentUsers as $user) {
if ($user->id != auth()->user()->id) {
$this->chatNotificationModel->insert(["chat_message_id" => $chat_message_id, "user_id" => $user->id]);
}
}
return $this->response->setJSON($dataResponse);
}
public function store_chat_message_factura()
@ -158,6 +244,12 @@ class ChatController extends BaseController
}
$chat_message_id = $this->chatMessageModel->insert(["chat_id" => $chatId, "sender_id" => auth()->user()->id, "message" => $data["message"]]);
$dataResponse = $this->chatMessageModel->find($chat_message_id);
$chatDepartmentUsers = $this->chatDeparmentModel->getChatDepartmentUsers($data["chat_department_id"]);
foreach ($chatDepartmentUsers as $user) {
if ($user->id != auth()->user()->id) {
$this->chatNotificationModel->insert(["chat_message_id" => $chat_message_id, "user_id" => $user->id]);
}
}
return $this->response->setJSON($dataResponse);
}
public function store_chat_message_single()
@ -175,44 +267,46 @@ class ChatController extends BaseController
"chat_id" => $chatId,
"sender_id" => auth()->user()->id,
"message" => $data["message"],
"receiver_id" => $data["receiver_id"]
"receiver_id" => $data["receiver_id"],
]
);
$this->chatNotificationModel->insert(["chat_message_id" => $chat_message_id, "user_id" => $data["receiver_id"]]);
$dataResponse = $this->chatMessageModel->find($chat_message_id);
return $this->response->setJSON($dataResponse);
}
public function get_chat_internal_contacts()
{
if (auth()->user()->cliente_id) {
return $this->response->setJSON([]);
$auth_user = auth()->user();
if ($auth_user->cliente_id) {
$users = $this->chatModel->getOpenChatCliente($auth_user->id);
} else {
$users = $this->userModel->builder()
->whereNotIn("id", [$auth_user->id])
->where("deleted_at", null)
->get()->getResultObject();
}
$users = $this->userModel->builder()
->where("cliente_id", null)
->whereNotIn("id", [auth()->user()->id])
->where("deleted_at", null)
->get()->getResultObject();
foreach ($users as $user) {
$user->unreadMessages = $this->chatMessageModel->get_chat_unread_messages_count($user->id);
$user->unreadMessages = $this->chatMessageModel->get_chat_messages_count($user->id);
}
usort($users, fn($a, $b) => $a->unreadMessages < $b->unreadMessages);
return $this->response->setJSON($users);
}
public function get_chat_internal_contact(int $user_id)
{
if (auth()->user()->cliente_id) {
return $this->response->setJSON([]);
}
$auth_user = auth()->user();
// if ($auth_user->cliente_id) {
// return $this->response->setJSON([]);
// }
$users = $this->userModel->builder()
->where("cliente_id", null)
->where("deleted_at", null)
->where("id", $user_id)
->get()->getFirstRow();
$this->chatMessageModel->set_chat_messages_as_read($user_id);
return $this->response->setJSON($users);
}
public function get_chat_internal_messages(int $user_id)
{
$conversation = $this->chatMessageModel->get_chat_contact_messages($user_id);
return $this->response->setJSON($conversation);
}
public function get_chat_cliente()
@ -223,6 +317,8 @@ class ChatController extends BaseController
$data = $this->clienteModel->getClienteDataPresupuestoPedidoFactura($cliente_id);
$response["totalMessages"] = 0;
$response["chatFacturas"] = $this->chatModel->getClienteChatFacturas($data["facturas"]);
$mensajes_directos = $this->chatModel->getChatDirectMessageNotifications();
foreach ($response["chatFacturas"] as $key => $value) {
$response["totalMessages"] += $value->unreadMessages;
}
@ -230,6 +326,10 @@ class ChatController extends BaseController
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;
@ -238,9 +338,13 @@ class ChatController extends BaseController
} 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;
@ -263,7 +367,26 @@ class ChatController extends BaseController
]
)->where("cliente_id", null)
->where("deleted_at", null)
->whereNotIn("id",[auth()->user()->id]);
->whereNotIn("id", [auth()->user()->id]);
if ($this->request->getGet("q")) {
$query->groupStart()
->orLike("users.username", $this->request->getGet("q"))
->orLike("CONCAT(first_name,' ',last_name)", $this->request->getGet("q"))
->groupEnd();
}
return $this->response->setJSON($query->get()->getResultObject());
}
public function get_chat_users_all()
{
$query = $this->userModel->builder()->select(
[
"id",
"CONCAT(first_name,' ',last_name,'(',username,')') as name"
]
)
->where("deleted_at", null)
->whereNotIn("id", [auth()->user()->id]);
if ($this->request->getGet("q")) {
$query->groupStart()
->orLike("users.username", $this->request->getGet("q"))
@ -275,6 +398,7 @@ class ChatController extends BaseController
}
public function store_hebra_presupuesto()
{
$auth_user = auth()->user();
$bodyData = $this->request->getPost();
$chat_id = $this->chatModel->insert([
"presupuesto_id" => $bodyData["modelId"],
@ -283,17 +407,19 @@ class ChatController extends BaseController
$chatMessageId = $this->chatMessageModel->insert([
"chat_id" => $chat_id,
"message" => $bodyData["message"],
"sender_id" => auth()->user()->id
"sender_id" => $auth_user->id
]);
if(isset($bodyData["users"])){
$chatUserData = array_map(fn($x) => ["user_id" => $x,"chat_id" => $chat_id],$bodyData["users"]);
if (isset($bodyData["users"])) {
$bodyData["users"][] = $auth_user->id;
$chatUserData = array_map(fn($x) => ["user_id" => $x, "chat_id" => $chat_id], $bodyData["users"]);
$this->chatUserModel->insertBatch($chatUserData);
foreach ($bodyData["users"] as $userId) {
$this->chatNotificationModel->insert(
["chat_message_id" => $chatMessageId,"user_id" => $userId]);
["chat_message_id" => $chatMessageId, "user_id" => $userId]
);
}
}
return $this->response->setJSON(["message" => "Hebra creada correctamente","status" => true]);
return $this->response->setJSON(["message" => "Hebra creada correctamente", "status" => true]);
}
public function store_hebra_pedido()
@ -309,15 +435,16 @@ class ChatController extends BaseController
"message" => $bodyData["message"],
"sender_id" => auth()->user()->id
]);
if(isset($bodyData["users"])){
$chatUserData = array_map(fn($x) => ["user_id" => $x,"chat_id" => $chat_id],$bodyData["users"]);
if (isset($bodyData["users"])) {
$chatUserData = array_map(fn($x) => ["user_id" => $x, "chat_id" => $chat_id], $bodyData["users"]);
$this->chatUserModel->insertBatch($chatUserData);
foreach ($bodyData["users"] as $userId) {
$this->chatNotificationModel->insert(
["chat_message_id" => $chatMessageId,"user_id" => $userId]);
["chat_message_id" => $chatMessageId, "user_id" => $userId]
);
}
}
return $this->response->setJSON(["message" => "Hebra creada correctamente","status" => true]);
return $this->response->setJSON(["message" => "Hebra creada correctamente", "status" => true]);
}
public function store_hebra_factura()
@ -332,89 +459,242 @@ class ChatController extends BaseController
"message" => $bodyData["message"],
"sender_id" => auth()->user()->id
]);
if(isset($bodyData["users"])){
$chatUserData = array_map(fn($x) => ["user_id" => $x,"chat_id" => $chat_id],$bodyData["users"]);
if (isset($bodyData["users"])) {
$chatUserData = array_map(fn($x) => ["user_id" => $x, "chat_id" => $chat_id], $bodyData["users"]);
$this->chatUserModel->insertBatch($chatUserData);
foreach ($bodyData["users"] as $userId) {
$this->chatNotificationModel->insert(
["chat_message_id" => $chatMessageId,"user_id" => $userId]);
["chat_message_id" => $chatMessageId, "user_id" => $userId]
);
}
}
return $this->response->setJSON(["message" => "Hebra creada correctamente","status" => true]);
return $this->response->setJSON(["message" => "Hebra creada correctamente", "status" => true]);
}
public function update_hebra($chat_id)
{
$bodyData = $this->request->getPost();
$chatMessageId = $this->chatMessageModel->insert([
$chatMessageId = $this->chatMessageModel->insert([
"chat_id" => $chat_id,
"message" => $bodyData["message"],
"sender_id" => auth()->user()->id
]);
$actualUsers = $this->chatUserModel->builder()->select("user_id")->where("chat_id",$chat_id)->get()->getResultArray();
$actualUsersArray = array_map(fn($x) => $x["user_id"],$actualUsers);
$actualUsers = $this->chatUserModel->builder()->select("user_id")->where("chat_id", $chat_id)->get()->getResultArray();
$actualUsersArray = array_map(fn($x) => $x["user_id"], $actualUsers);
foreach ($actualUsersArray as $key => $user_id) {
$this->chatNotificationModel->insert(
["chat_message_id" => $chatMessageId,"user_id" => $user_id]);
["chat_message_id" => $chatMessageId, "user_id" => $user_id]
);
}
if(isset($bodyData["users"])){
if (isset($bodyData["users"])) {
foreach ($bodyData["users"] as $userId) {
if(in_array($userId,$actualUsersArray) == false){
$chatUserData = ["user_id" => $userId,"chat_id" => $chat_id];
if (in_array($userId, $actualUsersArray) == false) {
$chatUserData = ["user_id" => $userId, "chat_id" => $chat_id];
$this->chatUserModel->insert($chatUserData);
}
$this->chatNotificationModel->insert(
["chat_message_id" => $chatMessageId,"user_id" => $userId]);
["chat_message_id" => $chatMessageId, "user_id" => $userId]
);
}
}
return $this->response->setJSON(["message" => "Hebra actualizada correctamente","status" => true]);
return $this->response->setJSON(["message" => "Hebra actualizada correctamente", "status" => true]);
}
public function get_hebra_presupuesto($presupuesto_id){
public function get_hebra_presupuesto($presupuesto_id)
{
$data = $this->chatModel->getPresupuestoHebras($presupuesto_id);
$notifications = $this->chatModel->builder()->select([
"chat_notifications.id"
])
->join("chat_messages","chat_messages.chat_id = chats.id","left")
->join("chat_notifications","chat_notifications.chat_message_id = chat_messages.id","left")
->where("chats.presupuesto_id",$presupuesto_id)
->where("chat_notifications.user_id",auth()->user()->id)
->get()->getResultArray();
->join("chat_messages", "chat_messages.chat_id = chats.id", "left")
->join("chat_notifications", "chat_notifications.chat_message_id = chat_messages.id", "left")
->where("chats.presupuesto_id", $presupuesto_id)
->where("chat_notifications.user_id", auth()->user()->id)
->get()->getResultArray();
foreach ($notifications as $notification) {
$this->chatNotificationModel->update($notification["id"],["viewed" => true]);
$this->chatNotificationModel->update($notification["id"], ["viewed" => true]);
}
return $this->response->setJSON($data);
}
public function get_hebra_pedido($pedido_id){
public function get_hebra_pedido($pedido_id)
{
$data = $this->chatModel->getPedidoHebras($pedido_id);
$notifications = $this->chatModel->builder()->select([
"chat_notifications.id"
])
->join("chat_messages","chat_messages.chat_id = chats.id","left")
->join("chat_notifications","chat_notifications.chat_message_id = chat_messages.id","left")
->where("chats.pedido_id",$pedido_id)
->where("chat_notifications.user_id",auth()->user()->id)
->get()->getResultArray();
->join("chat_messages", "chat_messages.chat_id = chats.id", "left")
->join("chat_notifications", "chat_notifications.chat_message_id = chat_messages.id", "left")
->where("chats.pedido_id", $pedido_id)
->where("chat_notifications.user_id", auth()->user()->id)
->get()->getResultArray();
foreach ($notifications as $notification) {
$this->chatNotificationModel->update($notification["id"],["viewed" => true]);
$this->chatNotificationModel->update($notification["id"], ["viewed" => true]);
}
return $this->response->setJSON($data);
}
public function get_hebra_factura($factura_id){
public function get_hebra_factura($factura_id)
{
$data = $this->chatModel->getFacturaHebras($factura_id);
$notifications = $this->chatModel->builder()->select([
"chat_notifications.id"
])
->join("chat_messages","chat_messages.chat_id = chats.id","left")
->join("chat_notifications","chat_notifications.chat_message_id = chat_messages.id","left")
->where("chats.factura_id",$factura_id)
->where("chat_notifications.user_id",auth()->user()->id)
->get()->getResultArray();
->join("chat_messages", "chat_messages.chat_id = chats.id", "left")
->join("chat_notifications", "chat_notifications.chat_message_id = chat_messages.id", "left")
->where("chats.factura_id", $factura_id)
->where("chat_notifications.user_id", auth()->user()->id)
->get()->getResultArray();
foreach ($notifications as $notification) {
$this->chatNotificationModel->update($notification["id"],["viewed" => true]);
$this->chatNotificationModel->update($notification["id"], ["viewed" => true]);
}
return $this->response->setJSON($data);
}
public function datatable_messages()
{
$auth_user_id = auth()->user()->id;
$query = $this->chatModel->getQueryDatatable($auth_user_id);
return DataTable::of($query)
->edit('created_at', fn($q) => Time::createFromFormat('Y-m-d H:i:s', $q->created_at)->format("d/m/Y H:i"))
->edit('updated_at', fn($q) => Time::createFromFormat('Y-m-d H:i:s', $q->updated_at)->format("d/m/Y H:i"))
->add("creator", fn($q) => $this->chatModel->getChatFirstUser($q->id)->userFullName)
->add("viewed", fn($q) => $this->chatModel->isMessageChatViewed($q->id, $auth_user_id))
->add("action", fn($q) => ["type" => "direct","modelId" => $q->id])
->toJson(true);
}
public function datatable_presupuesto_messages()
{
$auth_user_id = auth()->user()->id;
$query = $this->chatModel->getQueryDatatableMessagePresupuesto($auth_user_id);
return DataTable::of($query)
->edit('created_at', fn($q) => $q->created_at ? Time::createFromFormat('Y-m-d H:i:s', $q->created_at)->format("d/m/Y H:i") : "")
->edit('updated_at', fn($q) => $q->updated_at ? Time::createFromFormat('Y-m-d H:i:s', $q->updated_at)->format("d/m/Y H:i") : "")
->add("creator", fn($q) => $this->chatModel->getChatFirstUser($q->id)->userFullName)
->add("viewed", fn($q) => $this->chatModel->isMessageChatViewed($q->id, $auth_user_id))
->add("action", fn($q) => ["type" => "presupuesto","modelId" => $q->id])
->toJson(true);
}
public function datatable_pedido_messages()
{
$auth_user_id = auth()->user()->id;
$query = $this->chatModel->getQueryDatatableMessagePedido($auth_user_id);
return DataTable::of($query)
->edit('created_at', fn($q) => $q->created_at ? Time::createFromFormat('Y-m-d H:i:s', $q->created_at)->format("d/m/Y H:i") : "")
->edit('updated_at', fn($q) => $q->updated_at ? Time::createFromFormat('Y-m-d H:i:s', $q->updated_at)->format("d/m/Y H:i") : "")
->add("creator", fn($q) => $this->chatModel->getChatFirstUser($q->id)->userFullName)
->add("viewed", fn($q) => $this->chatModel->isMessageChatViewed($q->id, $auth_user_id))
->add("action", fn($q) => ["type" => "pedido","modelId" => $q->id])
->toJson(true);
}
public function datatable_factura_messages()
{
$auth_user_id = auth()->user()->id;
$query = $this->chatModel->getQueryDatatableMessageFactura($auth_user_id);
return DataTable::of($query)
->edit('created_at', fn($q) => $q->created_at ? Time::createFromFormat('Y-m-d H:i:s', $q->created_at)->format("d/m/Y H:i") : "")
->edit('updated_at', fn($q) => $q->updated_at ? Time::createFromFormat('Y-m-d H:i:s', $q->updated_at)->format("d/m/Y H:i") : "")
->add("creator", fn($q) => $this->chatModel->getChatFirstUser($q->id)->userFullName)
->add("viewed", fn($q) => $this->chatModel->isMessageChatViewed($q->id, $auth_user_id))
->add("action", fn($q) => ["type" => "factura","modelId" => $q->id])
->toJson(true);
}
public function store_new_direct_message()
{
$bodyData = $this->request->getPost();
$rules = [
"title" => "required|string",
"message" => "required|string",
"users" => "required",
];
if (!$this->validate($rules)) {
return $this->response->setStatusCode(400)->setJSON([
'message' => lang('App.global_alert_save_error'),
'status' => 'error',
'errors' => $this->validator->getErrors(),
]);
}
$this->chatModel->createNewDirectChat(...$bodyData);
return $this->response->setJSON(["message" => lang("Chat.new_message_ok"), "status" => true]);
}
public function store_new_direct_message_client()
{
$bodyData = $this->request->getPost();
$rules = [
"title" => "required|string",
"message" => "required|string",
"chat_department_id" => "required",
];
if (!$this->validate($rules)) {
return $this->response->setStatusCode(400)->setJSON([
'message' => lang('App.global_alert_save_error'),
'status' => 'error',
'errors' => $this->validator->getErrors(),
]);
}
$users = $this->chatDeparmentModel->getChatDepartmentUsers($bodyData["chat_department_id"]);
$bodyData["users"] = array_map(fn($q) => $q->id,$users);
dd(1);
$this->chatModel->createNewDirectChat(...$bodyData);
return $this->response->setJSON(["message" => lang("Chat.new_message_ok"), "status" => true]);
}
public function get_chat_direct($chat_id)
{
$chatData = $this->chatModel->getChatDirect($chat_id);
return $this->response->setJSON($chatData);
}
public function get_chat_direct_select_users($chat_id)
{
$chat_users_id = $this->chatUserModel->getChatUserArrayId($chat_id);
$query = $this->userModel->builder()->select(
[
"id",
"CONCAT(first_name,' ',last_name,'(',username,')') as name"
]
)
->where("deleted_at", null)
->whereNotIn("id", $chat_users_id);
if ($this->request->getGet("q")) {
$query->groupStart()
->orLike("users.username", $this->request->getGet("q"))
->orLike("CONCAT(first_name,' ',last_name)", $this->request->getGet("q"))
->groupEnd();
}
return $this->response->setJSON($query->get()->getResultObject());
}
public function store_chat_direct_users($chat_id)
{
$bodyData = $this->request->getPost();
$chat_users = [];
foreach ($bodyData["users"] as $user_id) {
$chat_users[] = ["chat_id" => $chat_id, "user_id" => $user_id];
if ($bodyData["notification"]) {
$this->chatModel->createNotificationsToNewChatUser($chat_id, $user_id);
}
}
$this->chatUserModel->insertBatch($chat_users);
return $this->response->setJSON(["message" => "ok", "status" => true]);
}
public function store_chat_direct_message(int $chat_id)
{
$bodyData = $this->request->getPost();
$auth_user = auth()->user();
$bodyData["sender_id"] = $auth_user->id;
$chat_message_id = $this->chatMessageModel->insert($bodyData);
$users_id = $this->chatUserModel->getChatUserArrayId($chat_id);
foreach ($users_id as $user_id) {
if ($user_id != $auth_user->id) {
$this->chatNotificationModel->insert(["chat_message_id" => $chat_message_id, "user_id" => $user_id]);
}
};
$message = $this->chatMessageModel->get_chat_message($chat_message_id);
return $this->response->setJSON($message);
}
public function update_chat_direct_message_unread($chat_id)
{
$this->chatModel->setAsUnviewedChatUserNotifications($chat_id, auth()->user()->id);
return $this->response->setJSON(["message" => "ok", "status" => true]);
}
}

View File

@ -234,6 +234,10 @@ class Clientedirecciones extends \App\Controllers\BaseResourceController
try {
$model = model('App\Models\Presupuestos\PresupuestoDireccionesModel');
$resourceData = $model->getDireccion($id);
if(count($resourceData) > 0){
$resourceData[0]->direccionId = $id;
}
$response = (object)[
'error' => false,
'data' => $resourceData

View File

@ -271,6 +271,27 @@ class Comunidadesautonomas extends \App\Controllers\BaseResourceController
}
}
public function menuItems2()
{
if ($this->request->isAJAX()) {
$query = $this->model->builder()->select(
[
"id",
"nombre as name"
]
)->orderBy("nombre", "asc");
if ($this->request->getGet("q")) {
$query->groupStart()
->orLike("lg_comunidades_autonomas.nombre", $this->request->getGet("q"))
->groupEnd();
}
return $this->response->setJSON($query->get()->getResultObject());
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
protected function getPaisListItems($selId = null)
{

View File

@ -230,25 +230,19 @@ class FormasPago extends \App\Controllers\BaseResourceController
public function menuItems()
{
if ($this->request->isAJAX()) {
$searchStr = goSanitize($this->request->getPost('searchTerm'))[0];
$reqId = goSanitize($this->request->getPost('id'))[0];
$reqText = goSanitize($this->request->getPost('text'))[0];
$onlyActiveOnes = false;
$columns2select = [$reqId ?? 'id', $reqText ?? 'nombre'];
$onlyActiveOnes = false;
$menu = $this->model->getSelect2MenuItems($columns2select, $columns2select[1], $onlyActiveOnes, $searchStr);
$nonItem = new \stdClass;
$nonItem->id = '';
$nonItem->text = '- ' . lang('Basic.global.None') . ' -';
array_unshift($menu, $nonItem);
$query = $this->model->builder()->select(
[
"id",
"nombre as name"
]
)->orderBy("nombre", "asc");
if ($this->request->getGet("q")) {
$query->groupStart()
->orLike("formas_pago.nombre", $this->request->getGet("q"))
->groupEnd();
}
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
$data = [
'menu' => $menu,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
return $this->response->setJSON($query->get()->getResultObject());
} else {
return $this->failUnauthorized('Invalid request', 403);
}

View File

@ -269,4 +269,25 @@ class Paises extends \App\Controllers\BaseResourceController
}
}
public function menuItems2()
{
if ($this->request->isAJAX()) {
$query = $this->model->builder()->select(
[
"id",
"nombre as name"
]
)->orderBy("nombre", "asc");
if ($this->request->getGet("q")) {
$query->groupStart()
->orLike("lg_paises.nombre", $this->request->getGet("q"))
->groupEnd();
}
return $this->response->setJSON($query->get()->getResultObject());
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
}

View File

@ -156,8 +156,13 @@ class Papelesgenericos extends \App\Controllers\BaseResourceController
if ($this->request->getPost('show_in_client') == null) {
$sanitizedData['show_in_client'] = false;
}
if ($this->request->getPost('show_in_client_special') == null) {
$sanitizedData['show_in_client_special'] = false;
}
if($sanitizedData['show_in_client_special']){
$sanitizedData['show_in_client'] = true;
}
$noException = true;
if ($successfulResult = $this->canValidate()) : // if ($successfulResult = $this->validate($this->formValidationRules) ) :
@ -288,4 +293,52 @@ class Papelesgenericos extends \App\Controllers\BaseResourceController
return $this->failUnauthorized('Invalid request', 403);
}
}
public function getPapelCliente()
{
if ($this->request->isAJAX()) {
$tipo = goSanitize($this->request->getGet('tipo'))[0];
$selected_papel = goSanitize($this->request->getGet('papel'))[0] ?? null;
$cubierta = goSanitize($this->request->getGet('cubierta'))[0] ?? 0;
$tapa_dura = goSanitize($this->request->getGet('tapa_dura'))[0] ?? null;
$menu = $this->model->getPapelCliente($tipo, $cubierta, $selected_papel, $tapa_dura, false);
$menu2 = $this->model->getPapelCliente($tipo, $cubierta, $selected_papel, $tapa_dura, true);
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
$data = [
'papeles' => $menu,
'papeles_especiales' => $menu2,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function selectPapelEspecial()
{
if ($this->request->isAJAX()) {
$tipo = goSanitize($this->request->getGet('tipo'))[0];
$cubierta = goSanitize($this->request->getGet('cubierta'))[0] ?? 0;
$items = $this->model->getPapelCliente($tipo, $cubierta, null, true);
$items = array_map(function ($item) {
return [
'id' => $item->id,
'name' => $item->nombre
];
}, $items);
return $this->response->setJSON($items);
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
}

View File

@ -175,7 +175,7 @@ class Papelesimpresion extends \App\Controllers\BaseResourceController
if ($this->request->getPost()) :
$nullIfEmpty = true; // !(phpversion() >= '8.1');
$nullIfEmpty = false; // !(phpversion() >= '8.1');
$postData = $this->request->getPost();
@ -188,6 +188,9 @@ class Papelesimpresion extends \App\Controllers\BaseResourceController
if ($this->request->getPost('defecto') == null) {
$sanitizedData['defecto'] = false;
}
if ($this->request->getPost('interior') == null) {
$sanitizedData['interior'] = false;
}
if ($this->request->getPost('bn') == null) {
$sanitizedData['bn'] = false;
}
@ -197,6 +200,9 @@ class Papelesimpresion extends \App\Controllers\BaseResourceController
if ($this->request->getPost('cubierta') == null) {
$sanitizedData['cubierta'] = false;
}
if ($this->request->getPost('use_for_tapa_dura') == null) {
$sanitizedData['use_for_tapa_dura'] = false;
}
if ($this->request->getPost('sobrecubierta') == null) {
$sanitizedData['sobrecubierta'] = false;
}
@ -209,6 +215,12 @@ class Papelesimpresion extends \App\Controllers\BaseResourceController
if ($this->request->getPost('inkjet') == null) {
$sanitizedData['inkjet'] = false;
}
if ($this->request->getPost('isActivo') == null) {
$sanitizedData['isActivo'] = false;
}
if ($this->request->getPost('use_in_client') == null) {
$sanitizedData['use_in_client'] = false;
}
// Hay que asegurarse de que se quitan los consumos de tintas de rotativa
// en caso de que se haya deseleccionado la opción rotativa

View File

@ -271,6 +271,27 @@ class Provincias extends \App\Controllers\BaseResourceController
}
}
public function menuItems2()
{
if ($this->request->isAJAX()) {
$query = $this->model->builder()->select(
[
"id",
"nombre as name"
]
)->orderBy("nombre", "asc");
if ($this->request->getGet("q")) {
$query->groupStart()
->orLike("lg_provincias.nombre", $this->request->getGet("q"))
->groupEnd();
}
return $this->response->setJSON($query->get()->getResultObject());
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
protected function getPaisListItems($selId = null)
{

View File

@ -20,7 +20,6 @@ class Users extends \App\Controllers\GoBaseController
private ChatDeparmentUserModel $chat_department_user_model;
use \CodeIgniter\API\ResponseTrait;
protected static $primaryModelName = 'App\Models\UserModel';
@ -62,7 +61,7 @@ class Users extends \App\Controllers\GoBaseController
$this->viewData['usingClientSideDataTable'] = true;
$this->viewData['pageSubTitle'] = lang('Basic.global.ManageAllRecords', [lang('Users.user')]);
$this->viewData['user_model'] = $this->user_model;
$this->viewData['userList2'] = auth()->getProvider()->findAll();
$this->viewData['userList2'] = auth()->getProvider()->findAll();
parent::index();
}
@ -77,17 +76,17 @@ class Users extends \App\Controllers\GoBaseController
// Obtener contraseña nueva si se ha introducido en texto plano
if (empty($postData['new_pwd'])) {
$postData['password'] = 'Safekat2024'; // Contraseña por defecto
}else{
} else {
$postData['password'] = $postData['new_pwd'];
}
// Obtener los grupos a los que pertenece
$currentGroups = $postData['group'] ?? [];
$chatDepartments = $postData['chatDepartments'] ?? [];
unset($postData['group']);
unset($postData['chatDepartments']);
// Generar el nombre de usuario
$postData['username'] = strstr($postData['email'], '@', true);
// Marcar el username como NULL
$sanitizedData = $this->sanitized($postData, true);
$noException = true;
@ -99,33 +98,43 @@ class Users extends \App\Controllers\GoBaseController
if ($this->canValidate()) :
try {
$user = new User([
'username' => $sanitizedData['username'],
'first_name' => $sanitizedData['first_name'],
'last_name' => $sanitizedData['last_name'],
'email' => $sanitizedData['email'],
'password' => $sanitizedData['password'],
'status' => $sanitizedData['status'] ?? 0,
'active' => $sanitizedData['active'] ?? 0,
]);
$users->save($user);
$successfulResult = true; // Hacked
} catch (\Exception $e) {
$noException = false;
//$this->dealWithException($e);
if (strpos($e->getMessage(), 'correo duplicado') !== false) {
$this->viewData['errorMessage'] = "El correo electrónico ya está registrado en el sistema";
// The Email is unique
if ($this->user_model->isEmailUnique($sanitizedData['email'])) {
// Crear el usuario si pasa la validación
$user = new \CodeIgniter\Shield\Entities\User([
'username' => null, // If you don't have a username, be sure to set the value to null anyway, so that it passes CodeIgniter's empty data check
'first_name' => $sanitizedData['first_name'],
'last_name' => $sanitizedData['last_name'],
'cliente_id' => $sanitizedData['cliente_id'],
'comments' => $sanitizedData['comments'],
'email' => $sanitizedData['email'],
'password' => $sanitizedData['password'],
'status' => $sanitizedData['status'] ?? 0,
'active' => $sanitizedData['active'] ?? 0,
]);
// Add the user to the system
$users->save($user);
$successfulResult = true; // Hacked
} // Email is not unique!
else {
$this->viewData['errorMessage'] = "El correo '". $sanitizedData['email'] ."' ya está registrado en el sistema";
$this->session->setFlashdata('formErrors', $this->model->errors());
$successfulResult = false; // Hacked
}
} catch (\Exception $e) {
$noException = false;
$this->viewData['errorMessage'] = $e->getMessage();
}
else:
$this->viewData['errorMessage'] = lang('Basic.global.formErr1', [mb_strtolower(lang('Users.user'))]);
$this->session->setFlashdata('formErrors', $this->model->errors());
endif;
$thenRedirect = true; // Change this to false if you want your user to stay on the form after submission
endif;
if ($noException && $successfulResult) :
$id = $users->getInsertID();
@ -137,12 +146,11 @@ class Users extends \App\Controllers\GoBaseController
];
$this->group_user_model->insert($group_user_data);
}
$this->chat_department_user_model->where("user_id",$id)->delete();
foreach($chatDepartments as $chatDepartment)
{
$this->chat_department_user_model->where("user_id", $id)->delete();
foreach ($chatDepartments as $chatDepartment) {
$this->chat_department_user_model->insert([
"user_id" => $id,
"chat_department_id" => $this->chat_department_model->where("name",$chatDepartment)->first()["id"]
"chat_department_id" => $this->chat_department_model->where("name", $chatDepartment)->first()["id"]
]);
}
@ -199,7 +207,6 @@ class Users extends \App\Controllers\GoBaseController
unset($postData['group']);
unset($postData['chatDepartments']);
// Obtener contraseña nueva si se ha introducido en texto plano
// Obtener contraseña nueva si se ha introducido en texto plano
if (!empty($postData['new_pwd'])) {
$postData['password'] = $postData['new_pwd'];
@ -254,12 +261,11 @@ class Users extends \App\Controllers\GoBaseController
];
$this->group_user_model->insert($group_user_data);
}
$this->chat_department_user_model->where("user_id",$id)->delete();
foreach($chatDepartments as $chatDepartment)
{
$this->chat_department_user_model->where("user_id", $id)->delete();
foreach ($chatDepartments as $chatDepartment) {
$this->chat_department_user_model->insert([
"user_id" => $id,
"chat_department_id" => $this->chat_department_model->where("name",$chatDepartment)->first()["id"]
"chat_department_id" => $this->chat_department_model->where("name", $chatDepartment)->first()["id"]
]);
}
$id = $user->id ?? $id;
@ -284,7 +290,7 @@ class Users extends \App\Controllers\GoBaseController
$this->viewData['formAction'] = route_to('updateUser', $id);
$this->viewData['selectedGroups'] = $this->group_model->getUsersRoles($requestedId);
$this->viewData['groups'] = $this->group_model->select('keyword, title')->findAll();
$this->viewData['chatDepartments'] = $this->chat_department_model->select(["display","name","id as chatDepartmentId"])->findAll();
$this->viewData['chatDepartments'] = $this->chat_department_model->select(["display", "name", "id as chatDepartmentId"])->findAll();
$this->viewData['chatDepartmentUser'] = $this->chat_department_user_model->getChatDepartmentUser($user->id);
$this->viewData['boxTitle'] = lang('Basic.global.edit2') . ' ' . lang('Users.user') . ' ' . lang('Basic.global.edit3');
@ -308,7 +314,7 @@ class Users extends \App\Controllers\GoBaseController
endif;
$users = auth()->getProvider();
$users->delete($user->id);
$users->delete($user->id, true);
$message = "Usuario eliminado correctamente";
return $this->redirect2listView('successMessage', $message);
@ -372,13 +378,7 @@ class Users extends \App\Controllers\GoBaseController
if ($this->request->isAJAX()) {
$comerciales = $this->model->getComerciales();
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
$data = [
'menu' => $comerciales,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
return $this->respond($comerciales);
} else {
return $this->failUnauthorized('Invalid request', 403);
}

View File

@ -14,10 +14,10 @@ class Js_loader extends BaseController
function comparadorCosidoTapaBlanda_js()
function comparadorPresupuestoAdmin_js()
{
$this->response->setHeader('Content-Type', 'text/javascript');
return view('themes/vuexy/form/presupuestos/cosidotapablanda/comparador.js');
return view('themes/vuexy/form/presupuestos/admin/comparador.js');
}
@ -37,49 +37,49 @@ class Js_loader extends BaseController
function datosLibro_js()
{
$this->response->setHeader('Content-Type', 'text/javascript');
return view('themes/vuexy/form/presupuestos/cosidotapablanda/_datosLibroItems.js');
return view('themes/vuexy/form/presupuestos/admin/_datosLibroItems.js');
}
function previsualizador_js()
{
$this->response->setHeader('Content-Type', 'text/javascript');
return view('themes/vuexy/form/presupuestos/cosidotapablanda/previews.js');
return view('themes/vuexy/form/presupuestos/admin/previews.js');
}
function lineasPresupuesto_js()
{
$this->response->setHeader('Content-Type', 'text/javascript');
return view('themes/vuexy/form/presupuestos/cosidotapablanda/_lineasPresupuestoItems.js');
return view('themes/vuexy/form/presupuestos/admin/_lineasPresupuestoItems.js');
}
function tiradasAlternativas_js()
{
$this->response->setHeader('Content-Type', 'text/javascript');
return view('themes/vuexy/form/presupuestos/cosidotapablanda/_tiradasAlternativasItems.js');
return view('themes/vuexy/form/presupuestos/admin/_tiradasAlternativasItems.js');
}
function datosServicios_js()
{
$this->response->setHeader('Content-Type', 'text/javascript');
return view('themes/vuexy/form/presupuestos/cosidotapablanda/_datosServiciosItems.js');
return view('themes/vuexy/form/presupuestos/admin/_datosServiciosItems.js');
}
function datosEnvios_js()
{
$this->response->setHeader('Content-Type', 'text/javascript');
return view('themes/vuexy/form/presupuestos/cosidotapablanda/_datosEnvios.js');
return view('themes/vuexy/form/presupuestos/admin/_datosEnvios.js');
}
function resumenPresupuestos_js()
{
$this->response->setHeader('Content-Type', 'text/javascript');
return view('themes/vuexy/form/presupuestos/cosidotapablanda/_resumenPresupuestos.js');
return view('themes/vuexy/form/presupuestos/admin/_resumenPresupuestos.js');
}
function presupuestos_js()
{
$this->response->setHeader('Content-Type', 'text/javascript');
return view('themes/vuexy/form/presupuestos/cosidotapablanda/_presupuestos.js');
return view('themes/vuexy/form/presupuestos/admin/_presupuestos.js');
}
function presupuestoCliente_js()

View File

@ -56,8 +56,13 @@ class PrintPresupuestos extends BaseController
$options->set('isRemoteEnabled', true);
$dompdf = new \Dompdf\Dompdf($options);
// Contenido HTML del documento
$dompdf->loadHtml(view(getenv('theme.path').'pdfs/presupuesto', $data));
// Metodo que funciona en el docker
$css = file_get_contents(getenv('theme.path'). 'css/pdf.presupuesto.css');
$html = view(getenv('theme.path') . 'pdfs/presupuesto', $data);
$html = "<style>$css</style>" . $html;
$dompdf->loadHtml($html);
//$dompdf->loadHtml(view(getenv('theme.path') . 'pdfs/presupuesto', $data));
// Establecer el tamaño del papel
$dompdf->setPaper('A4', 'portrait');

View File

@ -19,22 +19,22 @@ use App\Models\Presupuestos\PresupuestoServiciosExtraModel;
use App\Services\PresupuestoService;
use Exception;
class Cosidotapablanda extends \App\Controllers\BaseResourceController
class Presupuestoadmin extends \App\Controllers\BaseResourceController
{
protected $modelName = "PresupuestoModel";
protected $format = 'json';
protected static $singularObjectName = 'Cosido Tapa Blanda';
protected static $singularObjectNameCc = 'Cosidotapablanda';
protected static $pluralObjectName = 'Cosidos Tapa Blanda';
protected static $pluralObjectNameCc = 'cosidosTapaBlanda';
protected static $singularObjectName = 'Presupuesto Admin';
protected static $singularObjectNameCc = 'Presupuestoadmin';
protected static $pluralObjectName = 'Presupuestos Admin';
protected static $pluralObjectNameCc = 'PresupuestosAdmin';
protected static $controllerSlug = 'cosidotapablanda';
protected static $controllerSlug = 'presupuestoadmin';
protected static $viewPath = 'themes/vuexy/form/presupuestos/cosidotapablanda/';
protected static $viewPath = 'themes/vuexy/form/presupuestos/admin/';
protected $indexRoute = 'cosidotapablandaList';
protected $indexRoute = 'presupuestoadminList';
@ -71,7 +71,7 @@ class Cosidotapablanda extends \App\Controllers\BaseResourceController
$viewData = array_merge($this->viewData, $viewData); // merge any possible values from the parent controller class
return view(static::$viewPath . 'viewCosidotapablandaList', $viewData);
return view(static::$viewPath . 'viewPresupuestoAdminList', $viewData);
}
@ -126,7 +126,7 @@ class Cosidotapablanda extends \App\Controllers\BaseResourceController
if ($thenRedirect) :
if (!empty($this->indexRoute)) :
//return redirect()->to(route_to( $this->indexRoute ) )->with('sweet-success', $message);
return redirect()->to(site_url('presupuestos/cosidotapablanda/edit/' . $id))->with('sweet-success', $message);
return redirect()->to(site_url('presupuestoadmin/edit/' . $id))->with('sweet-success', $message);
else :
return $this->redirect2listView('sweet-success', $message);
endif;
@ -151,7 +151,7 @@ class Cosidotapablanda extends \App\Controllers\BaseResourceController
$this->viewData['POD'] = $this->getPOD();
$this->viewData['formAction'] = route_to('createCosidotapablanda', $tipo_impresion_id);
$this->viewData['formAction'] = route_to('createPresupuestoAdmin', $tipo_impresion_id);
$this->viewData = array_merge($this->viewData, $this->getStringsFromTipoImpresion($tipo_impresion_id));
@ -387,7 +387,7 @@ class Cosidotapablanda extends \App\Controllers\BaseResourceController
$this->viewData = array_merge($this->viewData, $this->getStringsFromTipoImpresion($presupuestoEntity->tipo_impresion_id));
$this->viewData['formAction'] = route_to('updateCosidotapablanda', $id);
$this->viewData['formAction'] = route_to('updatePresupuestoAdmin', $id);
// Si se ha llamado a esta funcion porque se ha duplicado el presupuesto
// se actualiza la bbdd para que sólo ejecute algunas funciones una vez
@ -840,7 +840,7 @@ class Cosidotapablanda extends \App\Controllers\BaseResourceController
// Breadcrumbs
$viewData['breadcrumb'] = [
['title' => lang("App.menu_presupuestos"), 'route' => "javascript:void(0);", 'active' => false],
['title' => $breadcrumbTitle, 'route' => site_url('presupuestos/cosidotapablanda/list/' . $tipo_impresion_id), 'active' => true]
['title' => $breadcrumbTitle, 'route' => site_url('presupuestoadmin/list/' . $tipo_impresion_id), 'active' => true]
];
return $viewData;

View File

@ -296,7 +296,6 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
$faja = $reqData['faja'] ?? [];
$excluirRotativa = $reqData['excluirRotativa'] ?? 0;
$excluirRotativa = intval($excluirRotativa);
$ivaReducido = intval($reqData['ivaReducido']) ?? 0;
$direcciones = $reqData['direcciones'] ?? [];
@ -304,12 +303,12 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
$lomoRedondo = $cubierta['lomoRedondo'] ?? 0;
if ($papelInteriorDiferente) {
$papel['negro'] = $modelPapelGenerico->getIdFromCode($interior['papelInterior']['negro']);
$papel['color'] = $modelPapelGenerico->getIdFromCode($interior['papelInterior']['color']);
$papel['negro'] = $modelPapelGenerico->where('id', $interior['papelInterior']['negro'])->first()->toArray();
$papel['color'] = $modelPapelGenerico->where('id', $interior['papelInterior']['color'])->first()->toArray();
$gramaje['negro'] = intval($interior['gramajeInterior']['negro']);
$gramaje['color'] = intval($interior['gramajeInterior']['color']);
} else {
$papel = $modelPapelGenerico->getIdFromCode($interior['papelInterior']);
$papel = $modelPapelGenerico->where('id', $interior['papelInterior'])->first()->toArray();
$gramaje = intval($interior['gramajeInterior']);
}
// Interior
@ -325,10 +324,10 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
// Cubierta
$cubierta = [
'papel_generico_cubierta' => $modelPapelGenerico->getIdFromCode($cubierta['papelCubierta']),
'papel_generico_cubierta' => $modelPapelGenerico->where('id', $cubierta['papelCubierta'])->first()->toArray(),
'gramajeCubierta' => intval($cubierta['gramajeCubierta']),
'carasCubierta' => intval($cubierta['carasImpresion'] ?? 0),
'solapasCubierta' => intval($cubierta['solapas'] ?? 0),
'solapasCubierta' => intval($cubierta['solapas'] ?? 0) == 1 ? intval($cubierta['tamanioSolapas']) : 0,
'acabadosCubierta' => $cubierta['acabados'] ?? 0,
'lomoRedondo' => $lomoRedondo,
];
@ -396,14 +395,16 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
for ($i = 0; $i < count($tirada); $i++) {
$coste_envio = 0.0;
$primer_envio = false;
foreach ($direcciones as $direccion) {
$coste_direccion = $this->getCosteEnvio(
$direccion['id'],
$return_data['peso'][$i],
$direccion['unidades'],
!$primer_envio ? intval($tirada[$i]) : $direccion['unidades'],
$direccion['entregaPalets'] == 'true' ? 1 : 0
)[0];
$primer_envio = true;
if (!property_exists($coste_direccion, 'coste')) {
@ -463,13 +464,101 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
return $this->respond($return_data);
} catch (Exception $e) {
return $this->failServerError($e->getMessage());
return $this->failServerError($e->getMessage() . ' - ' . $e->getFile() . ' - ' . $e->getLine());
}
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function calcularMaxSolapas()
{
if ($this->request->isAJAX()) {
$reqData = $this->request->getPost();
$modelPapelGenerico = new PapelGenericoModel();
$POD = model('App\Models\Configuracion\ConfiguracionSistemaModel')->getPOD();
$cliente_id = $reqData['clienteId'] ?? -1;
$tirada = $reqData['tirada'] ?? 0;
$tamanio = $reqData['tamanio'];
$paginas = $reqData['paginas'] ?? 0;
$paginas_color = $reqData['paginasColor'] ?? 0;
$papelInteriorDiferente = intval($reqData['papelInteriorDiferente']) ?? null;
$excluirRotativa = $reqData['excluirRotativa'] ?? 0;
$excluirRotativa = intval($excluirRotativa);
$tipo = $reqData['tipo'];
$tipoCubierta = 'blanda'; // solapas sólo tapa blanda y sobre cubierta
$isColor = intval($reqData['isColor']) ?? 0;
$isHq = intval($reqData['isHq']) ?? 0;
$tipo_impresion_id = $this->getTipoImpresion($tipo, $tipoCubierta);
$is_cosido = (new TipoPresupuestoModel())->get_isCosido($tipo_impresion_id);
$interior = $reqData['interior'] ?? [];
if ($papelInteriorDiferente) {
$papel['negro'] = $modelPapelGenerico->where('id', $interior['papelInterior']['negro'])->first()->toArray();
$papel['color'] = $modelPapelGenerico->where('id', $interior['papelInterior']['color'])->first()->toArray();
$gramaje['negro'] = intval($interior['gramajeInterior']['negro']);
$gramaje['color'] = intval($interior['gramajeInterior']['color']);
} else {
$papel = $modelPapelGenerico->where('id', $interior['papelInterior'])->first()->toArray();
$gramaje = intval($interior['gramajeInterior']);
}
$datosPedido = (object) array(
'paginas' => $paginas,
'tirada' => $tirada[0],
'merma' => $tirada[0] > $POD ? $this->calcular_merma($tirada[0], $POD) : 0,
'ancho' => intval($tamanio['ancho']) ?? 100000,
'alto' => intval($tamanio['alto']) ?? 100000,
'isCosido' => $is_cosido,
'a_favor_fibra' => 1,
);
$input_data = array(
'uso' => 'interior',
'tipo_impresion_id' => $tipo_impresion_id,
'datosPedido' => $datosPedido,
'papel_generico' => $papel,
'gramaje' => $gramaje,
'isColor' => $isColor,
'isHq' => $isHq,
'cliente_id' => $cliente_id,
'paginas_color' => $paginas_color,
'excluirRotativa' => $excluirRotativa,
'papelInteriorDiferente' => $papelInteriorDiferente
);
$interior = PresupuestoClienteService::obtenerInterior($input_data);
if ($interior == null) {
return $this->failServerError('Error al calcular el interior');
}
$anchoTotal = $interior[0]['mano'];
// le añadimos 2*ancho libro
$anchoTotal += 2 * $datosPedido->ancho;
// le añadimos los dobleces de las solapas
$anchoTotal += 6;
// le añadimos la sangre
$anchoTotal += PresupuestoService::SANGRE_FORMAS;
// 863 es el ancho máximo permitido por las máquinas
$maxSolapa = (865 - floor($anchoTotal)) / 2;
$maxSolapa = min($maxSolapa, 0.75 * $datosPedido->ancho);
return $this->respond($maxSolapa);
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function getDireccionesCliente()
{
if ($this->request->isAJAX()) {
@ -487,6 +576,7 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
'menu' => $data,
$csrfTokenName => $newTokenHash
]);
} else {
return $this->failUnauthorized('Invalid request', 403);
}
@ -652,6 +742,11 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
$isHq = intval($reqData['isHq']) ?? 0;
$prototipo = intval($reqData['prototipo']) ?? 0;
$ferro = intval($reqData['ferro']) ?? 0;
$ferroDigital = intval($reqData['ferroDigital']) ?? 0;
$marcapaginas = intval($reqData['marcapaginas']) ?? 0;
$retractilado = intval($reqData['retractilado']) ?? 0;
$retractilado5 = intval($reqData['retractilado5']) ?? 0;
$interior = $reqData['interior'] ?? [];
$cubierta = $reqData['cubierta'] ?? [];
@ -667,12 +762,12 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
$tipo_impresion_id = $this->getTipoImpresion($tipo, $cubierta['tipoCubierta']);
if ($papelInteriorDiferente) {
$papel['negro'] = $modelPapelGenerico->getIdFromCode($interior['papelInterior']['negro']);
$papel['color'] = $modelPapelGenerico->getIdFromCode($interior['papelInterior']['color']);
$papel['negro'] = $modelPapelGenerico->where('id', $interior['papelInterior']['negro'])->first()->toArray();
$papel['color'] = $modelPapelGenerico->where('id', $interior['papelInterior']['color'])->first()->toArray();
$gramaje['negro'] = intval($interior['gramajeInterior']['negro']);
$gramaje['color'] = intval($interior['gramajeInterior']['color']);
} else {
$papel = $modelPapelGenerico->getIdFromCode($interior['papelInterior']);
$papel = $modelPapelGenerico->where('id', $interior['papelInterior'])->first()->toArray();
$gramaje = intval($interior['gramajeInterior']);
}
// Interior
@ -690,10 +785,10 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
// Cubierta
$cubierta = [
'papel_generico_cubierta' => $modelPapelGenerico->getIdFromCode($cubierta['papelCubierta']),
'papel_generico_cubierta' => $modelPapelGenerico->where('id', $cubierta['papelCubierta'])->first()->toArray(),
'gramajeCubierta' => intval($cubierta['gramajeCubierta']),
'carasCubierta' => intval($cubierta['carasImpresion'] ?? 0),
'solapasCubierta' => intval($cubierta['solapas'] ?? 0),
'solapasCubierta' => intval($cubierta['solapas'] ?? 0) == 1 ? intval($cubierta['tamanioSolapas']) : 0,
'acabadosCubierta' => $cubierta['acabados'] ?? 0,
'lomoRedondo' => $cubierta['lomoRedondo'] ?? 0,
'cabezada' => $cubierta['cabezada'] ?? 'WHI',
@ -855,6 +950,11 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
}
$datos_presupuesto['prototipo'] = $prototipo;
$datos_presupuesto['ferro'] = $ferro;
$datos_presupuesto['ferro_digital'] = $ferroDigital;
$datos_presupuesto['marcapaginas'] = $marcapaginas;
$datos_presupuesto['retractilado'] = $retractilado;
$datos_presupuesto['retractilado5'] = $retractilado5;
$id = $model_presupuesto->insertarPresupuestoCliente(
$id,
@ -902,6 +1002,9 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
} else if ($servicio->tarifa_id == 62) {
// Servicios manipulado
$this->guardarServicio($id, $servicio, 'manipulado');
} else if ($servicio->tarifa_id == 73) {
// Servicios manipulado
$this->guardarServicio($id, $servicio, 'manipulado');
}
}
@ -968,6 +1071,11 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
$data['datosGenerales']['tipo'] = $this->getTipoLibro($presupuesto->tipo_impresion_id ?? null);
$data['datosGenerales']['prototipo'] = $presupuesto->prototipo;
$data['datosGenerales']['ferro'] = $presupuesto->ferro;
$data['datosGenerales']['ferroDigital'] = $presupuesto->ferro_digital;
$data['datosGenerales']['marcapaginas'] = $presupuesto->marcapaginas;
$data['datosGenerales']['retractilado'] = $presupuesto->retractilado;
$data['datosGenerales']['retractilado5'] = $presupuesto->retractilado5;
$datos_papel = $this->obtenerDatosPapel($presupuesto->id);
$data['interior'] = $datos_papel['interior'] ? $datos_papel['interior'] : [];
@ -997,6 +1105,9 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
$data['sobrecubierta']['solapas'] = $presupuesto->solapas_sobrecubierta ? 1 : 0;
$data['sobrecubierta']['solapas_ancho'] = $presupuesto->solapas_ancho_sobrecubierta;
$data['sobrecubierta']['plastificado'] = $modelAcabado->getCodeFromId($presupuesto->acabado_sobrecubierta_id);
if ($data['sobrecubierta']['plastificado'] == '') {
$data['sobrecubierta']['plastificado'] = 'NONE';
}
$data['guardas'] = array_key_exists('guardas', $datos_papel) ? $datos_papel['guardas'] : [];
@ -1272,7 +1383,7 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
$coste = 0;
$margen = 0;
if ($data > 0) {
if (count($data) > 0) {
$peso_envio = round(floatval($peso * $unidades / 1000.0)); // peso libro * unidades y se pasa a kilogramos
$tarifas_envio = $modelTarifaEnvio->getTarifaEnvio($data[0]->pais_id, $data[0]->cp, $peso_envio, $entregaPieCalle ? 'palets' : 'cajas');
for ($i = 0; $i < count($tarifas_envio); $i++) {
@ -1780,6 +1891,9 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
'solapas' => intval($solapasCubierta) > 0 ? 1 : 0,
'paginasCuadernillo' => $paginasCuadernillo,
]);
$costeServiciosDefecto = 0.0;
foreach ($servDefecto as $servicio) {
if ($servicio->total <= 0) {
@ -1813,6 +1927,14 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
}
// Servicios
/*
'retractilado' => 3,
'prototipo' => 9,
*/
$serviciosAutomaticos = [];
$servicios = [];
// se comprueba si $datos guardas es un array
if (is_array($datos_guardas)) {
if (count($datos_guardas) > 0) {
@ -1823,20 +1945,19 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
array_push($servicios, 62); // Plegado de guardas
}
}
/*
'retractilado' => 3,
'prototipo' => 9,
*/
$serviciosAutomaticos = [];
$servicios = [];
if ($datos_entrada['cubierta']['acabadosCubierta']['retractilado'] === 'true')
if ($datos_entrada['servicios']['retractilado']) // acabado
array_push($servicios, 3);
if ($datos_entrada['servicios']['prototipo'])
if ($datos_entrada['servicios']['retractilado5']) // acabado
array_push($servicios, 98);
if ($datos_entrada['servicios']['prototipo']) // extra
array_push($servicios, 9);
if ($datos_entrada['servicios']['ferro']) // extra
array_push($servicios, 30);
/*if ($datos_entrada['servicios']['ferroDigital'])
array_push($servicios, 29);*/ // Es gratis
foreach ($servicios as $servicio) {
if (intval($servicio) == 3) {
if (intval($servicio) == 3 || intval($servicio) == 98) {
// Servicios acabado
$resultado = PresupuestoCLienteService::getServiciosAcabados([
'tarifa_id' => $servicio,
@ -1851,7 +1972,7 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
$errorModel->insertError(
$datos_entrada['id'],
auth()->user()->id,
'No se puede obtener servicio con id 3',
'No se puede obtener servicio con id ' . ((string) $servicio),
$input_data
);
$return_data = [
@ -1867,8 +1988,8 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
$totalServicios += floatval($resultado[0]->total);
$margenServicios += floatval($resultado[0]->total) * floatval($resultado[0]->margen) / 100.0;
}
} else if (intval($servicio) == 9) {
// Prototipo
} else if (intval($servicio) == 9 || intval($servicio) == 30 || intval($servicio) == 29) {
// Extra
$resultado = PresupuestoCLienteService::getServiciosExtra([
'tarifa_id' => $servicio,
]);
@ -1879,7 +2000,7 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
$errorModel->insertError(
$datos_entrada['id'],
auth()->user()->id,
'No se puede obtener servicio con id 9',
'No se puede obtener servicio con id ' . ((string) $servicio),
$input_data
);
$return_data = [
@ -1899,6 +2020,45 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
}
}
// Plegado de solapas grandes
if (
(intval($solapasCubierta) > 0 && intval($cubierta['dimension_desarrollo']['ancho']) > 630) ||
(is_array($sobreCubierta) && ($sobreCubierta['solapas'] > 0 && intval($linea_sobrecubierta['dimension_desarrollo']['ancho']) > 630))
) {
// Servicios acabado
$resultado = PresupuestoCLienteService::getServiciosManipulado([
'tarifa_id' => 73,
'tirada' => $datosPedido->tirada,
'POD' => $POD,
]);
array_push($serviciosAutomaticos, $resultado[0]);
if ($resultado[0]->total <= 0) {
$errorModel = new ErrorPresupuesto();
$errorModel->insertError(
$datos_entrada['id'],
auth()->user()->id,
'No se puede obtener servicio de manupulado con id ' . ((string) $servicio),
$input_data
);
$return_data = [
'errors' => (object) ([
'status' => 1
]),
];
return $return_data;
}
$coste_servicios += floatval($resultado[0]->total);
if ($extra_info) {
$totalServicios += floatval($resultado[0]->total);
$margenServicios += floatval($resultado[0]->total) * floatval($resultado[0]->margen) / 100.0;
}
}
array_push($precio_u, round(($costeInterior + $coste_cubierta + $coste_sobrecubierta + $costeServiciosDefecto + $coste_servicios) / $tirada[$t], 4));
array_push($peso, round($peso_interior + $peso_cubierta + $peso_sobrecubierta + $peso_guardas, 2));
@ -2278,13 +2438,16 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
if ($linea->tipo == 'lp_bn' || $linea->tipo == 'lp_bnhq' || $linea->tipo == 'lp_rot_bn') {
$return_data['interior']['negro']['tipo'] = $linea->tipo == 'lp_bn' || $linea->tipo == 'lp_rot_bn' ? 'negroEstandar' : 'negroPremium';
$return_data['interior']['negro']['papel'] = $modelPapelGenerico->getCodeFromId($linea->papel_id);
$return_data['interior']['negro']['papel']['id'] = $linea->papel_id;
$return_data['interior']['negro']['gramaje'] = $linea->gramaje;
} else if ($linea->tipo == 'lp_color' || $linea->tipo == 'lp_colorhq' || $linea->tipo == 'lp_rot_color') {
$return_data['interior']['color']['tipo'] = $linea->tipo == 'lp_color' || $linea->tipo == 'lp_rot_color' ? 'colorEstandar' : 'colorPremium';
$return_data['interior']['color']['papel'] = $modelPapelGenerico->getCodeFromId($linea->papel_id);
$return_data['interior']['color']['papel']['id'] = $linea->papel_id;
$return_data['interior']['color']['gramaje'] = $linea->gramaje;
} else if ($linea->tipo == 'lp_cubierta') {
$return_data['cubierta']['papel'] = $modelPapelGenerico->getCodeFromId($linea->papel_id);
$return_data['cubierta']['papel']['id'] = $linea->papel_id;
$return_data['cubierta']['gramaje'] = $linea->gramaje;
$return_data['cubierta']['paginas'] = $linea->paginas;
} else if ($linea->tipo == 'lp_sobrecubierta') {

View File

@ -1,4 +1,5 @@
<?php namespace App\Controllers\Tarifas;
<?php
namespace App\Controllers\Tarifas;
use App\Controllers\BaseResourceController;
@ -14,10 +15,11 @@ use App\Models\Tarifas\TarifaEnvioModel;
use App\Models\Tarifas\TarifaEnvioPrecioModel;
use
DataTables\Editor,
DataTables\Editor\Field;
DataTables\Editor,
DataTables\Editor\Field;
class Tarifasenviosprecios extends \App\Controllers\BaseResourceController {
class Tarifasenviosprecios extends \App\Controllers\BaseResourceController
{
protected $modelName = TarifaEnvioPrecioModel::class;
protected $format = 'json';
@ -33,9 +35,10 @@ class Tarifasenviosprecios extends \App\Controllers\BaseResourceController {
protected $indexRoute = 'tarifaEnvioPrecioList';
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger) {
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
$this->viewData['pageTitle'] = lang('TarifasEnviosPrecios.moduleTitle');
$this->viewData['usingSweetAlert'] = true;
@ -48,66 +51,68 @@ class Tarifasenviosprecios extends \App\Controllers\BaseResourceController {
}
public function index() {
public function index()
{
$viewData = [
'currentModule' => static::$controllerSlug,
'pageSubTitle' => lang('Basic.global.ManageAllRecords', [lang('TarifasEnviosPrecios.tarifaEnvioPrecio')]),
'tarifaEnvioPrecioEntity' => new TarifaEnvioPrecioEntity(),
'usingServerSideDataTable' => true,
];
'currentModule' => static::$controllerSlug,
'pageSubTitle' => lang('Basic.global.ManageAllRecords', [lang('TarifasEnviosPrecios.tarifaEnvioPrecio')]),
'tarifaEnvioPrecioEntity' => new TarifaEnvioPrecioEntity(),
'usingServerSideDataTable' => true,
];
$viewData = array_merge($this->viewData, $viewData); // merge any possible values from the parent controller class
return view(static::$viewPath.'viewTarifaEnvioPrecioList', $viewData);
return view(static::$viewPath . 'viewTarifaEnvioPrecioList', $viewData);
}
public function add() {
public function add()
{
if ($this->request->getPost()) :
if ($this->request->getPost()):
$nullIfEmpty = true; // !(phpversion() >= '8.1');
$postData = $this->request->getPost();
$sanitizedData = $this->sanitized($postData, $nullIfEmpty);
$sanitizedData = $this->sanitized($postData, $nullIfEmpty);
$noException = true;
if ($successfulResult = $this->canValidate()) : // if ($successfulResult = $this->validate($this->formValidationRules) ) :
if ($successfulResult = $this->canValidate()): // if ($successfulResult = $this->validate($this->formValidationRules) ) :
if ($this->canValidate()) :
try {
$successfulResult = $this->model->skipValidation(true)->save($sanitizedData);
} catch (\Exception $e) {
$noException = false;
$this->dealWithException($e);
}
else:
$this->viewData['errorMessage'] = lang('Basic.global.formErr1', [mb_strtolower(lang('TarifasEnviosPrecios.tarifaEnvioPrecio'))]);
$this->session->setFlashdata('formErrors', $this->model->errors());
endif;
$thenRedirect = true; // Change this to false if you want your user to stay on the form after submission
if ($this->canValidate()):
try {
$successfulResult = $this->model->skipValidation(true)->save($sanitizedData);
} catch (\Exception $e) {
$noException = false;
$this->dealWithException($e);
}
else:
$this->viewData['errorMessage'] = lang('Basic.global.formErr1', [mb_strtolower(lang('TarifasEnviosPrecios.tarifaEnvioPrecio'))]);
$this->session->setFlashdata('formErrors', $this->model->errors());
endif;
$thenRedirect = true; // Change this to false if you want your user to stay on the form after submission
endif;
if ($noException && $successfulResult) :
if ($noException && $successfulResult):
$id = $this->model->db->insertID();
$message = lang('Basic.global.saveSuccess', [mb_strtolower(lang('TarifasEnviosPrecios.tarifaEnvioPrecio'))]).'.';
$message .= anchor( "admin/tarifasenviosprecios/{$id}/edit" , lang('Basic.global.continueEditing').'?');
$message = lang('Basic.global.saveSuccess', [mb_strtolower(lang('TarifasEnviosPrecios.tarifaEnvioPrecio'))]) . '.';
$message .= anchor("admin/tarifasenviosprecios/{$id}/edit", lang('Basic.global.continueEditing') . '?');
$message = ucfirst(str_replace("'", "\'", $message));
if ($thenRedirect) :
if (!empty($this->indexRoute)) :
return redirect()->to(route_to( $this->indexRoute ) )->with('sweet-success', $message);
if ($thenRedirect):
if (!empty($this->indexRoute)):
return redirect()->to(route_to($this->indexRoute))->with('sweet-success', $message);
else:
return $this->redirect2listView('sweet-success', $message);
endif;
@ -120,97 +125,98 @@ class Tarifasenviosprecios extends \App\Controllers\BaseResourceController {
endif; // ($requestMethod === 'post')
$this->viewData['tarifaEnvioPrecioEntity'] = isset($sanitizedData) ? new TarifaEnvioPrecioEntity($sanitizedData) : new TarifaEnvioPrecioEntity();
$this->viewData['tarifaEnvioList'] = $this->getTarifaEnvioListItems($tarifaEnvioPrecioEntity->tarifa_envio_id ?? null);
$this->viewData['proveedorList'] = $this->getProveedorListItems($tarifaEnvioPrecioEntity->proveedor_id ?? null);
$this->viewData['tipoEnvioList'] = $this->getTipoEnvioOptions();
$this->viewData['tarifaEnvioList'] = $this->getTarifaEnvioListItems($tarifaEnvioPrecioEntity->tarifa_envio_id ?? null);
$this->viewData['proveedorList'] = $this->getProveedorListItems($tarifaEnvioPrecioEntity->proveedor_id ?? null);
$this->viewData['tipoEnvioList'] = $this->getTipoEnvioOptions();
$this->viewData['formAction'] = route_to('createTarifaEnvioPrecio');
$this->viewData['boxTitle'] = lang('Basic.global.addNew').' '.lang('TarifasEnviosPrecios.moduleTitle').' '.lang('Basic.global.addNewSuffix');
$this->viewData['boxTitle'] = lang('Basic.global.addNew') . ' ' . lang('TarifasEnviosPrecios.moduleTitle') . ' ' . lang('Basic.global.addNewSuffix');
return $this->displayForm(__METHOD__);
} // end function add()
public function edit($requestedId = null) {
if ($requestedId == null) :
public function edit($requestedId = null)
{
if ($requestedId == null):
return $this->redirect2listView();
endif;
$id = filter_var($requestedId, FILTER_SANITIZE_URL);
$tarifaEnvioPrecioEntity = $this->model->find($id);
if ($tarifaEnvioPrecioEntity == false) :
if ($tarifaEnvioPrecioEntity == false):
$message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('TarifasEnviosPrecios.tarifaEnvioPrecio')), $id]);
return $this->redirect2listView('sweet-error', $message);
endif;
if ($this->request->getPost()) :
if ($this->request->getPost()):
$nullIfEmpty = true; // !(phpversion() >= '8.1');
$postData = $this->request->getPost();
$sanitizedData = $this->sanitized($postData, $nullIfEmpty);
$sanitizedData = $this->sanitized($postData, $nullIfEmpty);
$noException = true;
if ($successfulResult = $this->canValidate()) : // if ($successfulResult = $this->validate($this->formValidationRules) ) :
if ($successfulResult = $this->canValidate()): // if ($successfulResult = $this->validate($this->formValidationRules) ) :
if ($this->canValidate()) :
try {
$successfulResult = $this->model->skipValidation(true)->update($id, $sanitizedData);
} catch (\Exception $e) {
$noException = false;
$this->dealWithException($e);
}
else:
$this->viewData['warningMessage'] = lang('Basic.global.formErr1', [mb_strtolower(lang('TarifasEnviosPrecios.tarifaEnvioPrecio'))]);
$this->session->setFlashdata('formErrors', $this->model->errors());
endif;
$tarifaEnvioPrecioEntity->fill($sanitizedData);
$thenRedirect = true;
if ($this->canValidate()):
try {
$successfulResult = $this->model->skipValidation(true)->update($id, $sanitizedData);
} catch (\Exception $e) {
$noException = false;
$this->dealWithException($e);
}
else:
$this->viewData['warningMessage'] = lang('Basic.global.formErr1', [mb_strtolower(lang('TarifasEnviosPrecios.tarifaEnvioPrecio'))]);
$this->session->setFlashdata('formErrors', $this->model->errors());
endif;
$tarifaEnvioPrecioEntity->fill($sanitizedData);
$thenRedirect = true;
endif;
if ($noException && $successfulResult) :
if ($noException && $successfulResult):
$id = $tarifaEnvioPrecioEntity->id ?? $id;
$message = lang('Basic.global.updateSuccess', [mb_strtolower(lang('TarifasEnviosPrecios.tarifaEnvioPrecio'))]).'.';
$message .= anchor( "admin/tarifasenviosprecios/{$id}/edit" , lang('Basic.global.continueEditing').'?');
$message = lang('Basic.global.updateSuccess', [mb_strtolower(lang('TarifasEnviosPrecios.tarifaEnvioPrecio'))]) . '.';
$message .= anchor("admin/tarifasenviosprecios/{$id}/edit", lang('Basic.global.continueEditing') . '?');
$message = ucfirst(str_replace("'", "\'", $message));
if ($thenRedirect) :
if (!empty($this->indexRoute)) :
return redirect()->to(route_to( $this->indexRoute ) )->with('sweet-success', $message);
if ($thenRedirect):
if (!empty($this->indexRoute)):
return redirect()->to(route_to($this->indexRoute))->with('sweet-success', $message);
else:
return $this->redirect2listView('sweet-success', $message);
endif;
else:
$this->session->setFlashData('sweet-success', $message);
endif;
endif; // $noException && $successfulResult
endif; // ($requestMethod === 'post')
$this->viewData['tarifaEnvioPrecioEntity'] = $tarifaEnvioPrecioEntity;
$this->viewData['tarifaEnvioList'] = $this->getTarifaEnvioListItems($tarifaEnvioPrecioEntity->tarifa_envio_id ?? null);
$this->viewData['proveedorList'] = $this->getProveedorListItems($tarifaEnvioPrecioEntity->proveedor_id ?? null);
$this->viewData['tipoEnvioList'] = $this->getTipoEnvioOptions();
$this->viewData['tarifaEnvioList'] = $this->getTarifaEnvioListItems($tarifaEnvioPrecioEntity->tarifa_envio_id ?? null);
$this->viewData['proveedorList'] = $this->getProveedorListItems($tarifaEnvioPrecioEntity->proveedor_id ?? null);
$this->viewData['tipoEnvioList'] = $this->getTipoEnvioOptions();
$this->viewData['formAction'] = route_to('updateTarifaEnvioPrecio', $id);
$this->viewData['boxTitle'] = lang('Basic.global.edit2') . ' ' . lang('TarifasEnviosPrecios.moduleTitle') . ' ' . lang('Basic.global.edit3');
$this->viewData['formAction'] = route_to('updateTarifaEnvioPrecio', $id);
$this->viewData['boxTitle'] = lang('Basic.global.edit2').' '.lang('TarifasEnviosPrecios.moduleTitle').' '.lang('Basic.global.edit3');
return $this->displayForm(__METHOD__, $id);
} // end function edit(...)
public function datatable_editor()
{
@ -222,62 +228,101 @@ class Tarifasenviosprecios extends \App\Controllers\BaseResourceController {
$response = Editor::inst($db, 'tarifas_envios_precios')
->fields(
Field::inst('tipo_envio')
->validator('Validate::required', array(
'message' => lang('TarifasEnviosPrecios.validation.tipo_envio.required'))
),
->validator(
'Validate::required',
array(
'message' => lang('TarifasEnviosPrecios.validation.tipo_envio.required')
)
),
Field::inst('peso_min')
->getFormatter( 'Format::toDecimalChar')->setFormatter( 'Format::fromDecimalChar')
->validator('Validate::required', array(
'message' => lang('TarifasEnviosPrecios.validation.peso_min.required'))
->getFormatter('Format::toDecimalChar')->setFormatter('Format::fromDecimalChar')
->validator(
'Validate::required',
array(
'message' => lang('TarifasEnviosPrecios.validation.peso_min.required')
)
)
->validator('Validate::numeric', array(
->validator(
'Validate::numeric',
array(
"decimal" => ',',
'message' => lang('TarifasEnviosPrecios.validation.peso_min.decimal'))
'message' => lang('TarifasEnviosPrecios.validation.peso_min.decimal')
)
),
Field::inst('peso_max')
->getFormatter( 'Format::toDecimalChar')->setFormatter( 'Format::fromDecimalChar')
->validator('Validate::required', array(
'message' => lang('TarifasEnviosPrecios.validation.peso_max.required'))
->getFormatter('Format::toDecimalChar')->setFormatter('Format::fromDecimalChar')
->validator(
'Validate::required',
array(
'message' => lang('TarifasEnviosPrecios.validation.peso_max.required')
)
)
->validator('Validate::numeric', array(
->validator(
'Validate::numeric',
array(
"decimal" => ',',
'message' => lang('TarifasEnviosPrecios.validation.peso_max.decimal'))
'message' => lang('TarifasEnviosPrecios.validation.peso_max.decimal')
)
),
Field::inst('precio_min')
->getFormatter( 'Format::toDecimalChar')->setFormatter( 'Format::fromDecimalChar')
->validator('Validate::required', array(
'message' => lang('TarifasEnviosPrecios.validation.precio.required'))
->getFormatter('Format::toDecimalChar')->setFormatter('Format::fromDecimalChar')
->validator(
'Validate::required',
array(
'message' => lang('TarifasEnviosPrecios.validation.precio.required')
)
)
->validator('Validate::numeric', array(
"decimal" => ',',
'message' => lang('TarifasEnviosPrecios.validation.precio.decimal'))
->validator(
'Validate::numeric',
array(
"decimal" => ',',
'message' => lang('TarifasEnviosPrecios.validation.precio.decimal')
)
),
Field::inst('precio_max')
->getFormatter( 'Format::toDecimalChar')->setFormatter( 'Format::fromDecimalChar')
->validator('Validate::required', array(
'message' => lang('TarifasEnviosPrecios.validation.precio.required'))
->getFormatter('Format::toDecimalChar')->setFormatter('Format::fromDecimalChar')
->validator(
'Validate::required',
array(
'message' => lang('TarifasEnviosPrecios.validation.precio.required')
)
)
->validator('Validate::numeric', array(
->validator(
'Validate::numeric',
array(
"decimal" => ',',
'message' => lang('TarifasEnviosPrecios.validation.precio.decimal'))
'message' => lang('TarifasEnviosPrecios.validation.precio.decimal')
)
),
Field::inst('precio_adicional')
->getFormatter( 'Format::toDecimalChar')->setFormatter( 'Format::fromDecimalChar')
->validator('Validate::required', array(
'message' => lang('TarifasEnviosPrecios.validation.precio_adicional.required'))
->getFormatter('Format::toDecimalChar')->setFormatter('Format::fromDecimalChar')
->validator(
'Validate::required',
array(
'message' => lang('TarifasEnviosPrecios.validation.precio_adicional.required')
)
)
->validator('Validate::numeric', array(
->validator(
'Validate::numeric',
array(
"decimal" => ',',
'message' => lang('TarifasEnviosPrecios.validation.precio_adicional.decimal'))
'message' => lang('TarifasEnviosPrecios.validation.precio_adicional.decimal')
)
),
Field::inst('margen')
->getFormatter( 'Format::toDecimalChar')->setFormatter( 'Format::fromDecimalChar')
->validator('Validate::required', array(
'message' => lang('TarifasEnviosPrecios.validation.precio_adicional.required'))
->getFormatter('Format::toDecimalChar')->setFormatter('Format::fromDecimalChar')
->validator(
'Validate::required',
array(
'message' => lang('TarifasEnviosPrecios.validation.precio_adicional.required')
)
)
->validator('Validate::numeric', array(
->validator(
'Validate::numeric',
array(
"decimal" => ',',
'message' => lang('TarifasEnviosPrecios.validation.precio_adicional.decimal'))
'message' => lang('TarifasEnviosPrecios.validation.precio_adicional.decimal')
)
),
Field::inst('tarifa_envio_id'),
Field::inst('proveedor_id'),
@ -344,24 +389,35 @@ class Tarifasenviosprecios extends \App\Controllers\BaseResourceController {
}
public function datatable() {
public function datatable()
{
if ($this->request->isAJAX()) {
$reqData = $this->request->getPost();
if (!isset($reqData['draw']) || !isset($reqData['columns']) ) {
if (!isset($reqData['draw']) || !isset($reqData['columns'])) {
$errstr = 'No data available in response to this specific request.';
$response = $this->respond(Collection::datatable( [], 0, 0, $errstr ), 400, $errstr);
$response = $this->respond(Collection::datatable([], 0, 0, $errstr), 400, $errstr);
return $response;
}
$start = $reqData['start'] ?? 0;
$length = $reqData['length'] ?? 5;
$search = $reqData['search']['value'];
$requestedOrder = $reqData['order']['0']['column'] ?? 1;
$requestedOrder2 = $reqData['order']['1']['column'] ?? $requestedOrder;
$requestedOrder3 = $reqData['order']['2']['column'] ?? $requestedOrder;
$order = TarifaEnvioPrecioModel::SORTABLE[$requestedOrder > 0 ? $requestedOrder : 1];
$order2 = TarifaEnvioPrecioModel::SORTABLE[$requestedOrder2 > 0 ? $requestedOrder2 : 1];
$order3 = TarifaEnvioPrecioModel::SORTABLE[$requestedOrder3 > 0 ? $requestedOrder3 : 1];
$dir = $reqData['order']['0']['dir'] ?? 'asc';
$dir2 = $reqData['order']['0']['dir'] ?? $dir;
$dir3 = $reqData['order']['0']['dir'] ?? $dir;
$tarifa_envio_id = $reqData['tarifa_envio_id'] ?? -1;
$resourceData = $this->model->getResource($search, $tarifa_envio_id)->orderBy($order, $dir)->limit($length, $start)->get()->getResultObject();
$resourceData = $this->model->getResource($search, $tarifa_envio_id)
->orderBy($order, $dir)->orderBy($order2, $dir2)->orderBy($order3, $dir3)
->limit($length, $start)->get()->getResultObject();
return $this->respond(Collection::datatable(
$resourceData,
@ -373,15 +429,16 @@ class Tarifasenviosprecios extends \App\Controllers\BaseResourceController {
}
}
public function allItemsSelect() {
public function allItemsSelect()
{
if ($this->request->isAJAX()) {
$onlyActiveOnes = true;
$reqVal = $this->request->getPost('val') ?? 'id';
$menu = $this->model->getAllForMenu($reqVal.', tarifa_envio_id', 'tarifa_envio_id', $onlyActiveOnes, false);
$menu = $this->model->getAllForMenu($reqVal . ', tarifa_envio_id', 'tarifa_envio_id', $onlyActiveOnes, false);
$nonItem = new \stdClass;
$nonItem->id = '';
$nonItem->tarifa_envio_id = '- '.lang('Basic.global.None').' -';
array_unshift($menu , $nonItem);
$nonItem->tarifa_envio_id = '- ' . lang('Basic.global.None') . ' -';
array_unshift($menu, $nonItem);
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
@ -395,7 +452,8 @@ class Tarifasenviosprecios extends \App\Controllers\BaseResourceController {
}
}
public function menuItems() {
public function menuItems()
{
if ($this->request->isAJAX()) {
$searchStr = goSanitize($this->request->getPost('searchTerm'))[0];
$reqId = goSanitize($this->request->getPost('id'))[0];
@ -406,8 +464,8 @@ class Tarifasenviosprecios extends \App\Controllers\BaseResourceController {
$menu = $this->model->getSelect2MenuItems($columns2select, $columns2select[1], $onlyActiveOnes, $searchStr);
$nonItem = new \stdClass;
$nonItem->id = '';
$nonItem->text = '- '.lang('Basic.global.None').' -';
array_unshift($menu , $nonItem);
$nonItem->text = '- ' . lang('Basic.global.None') . ' -';
array_unshift($menu, $nonItem);
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
@ -422,42 +480,45 @@ class Tarifasenviosprecios extends \App\Controllers\BaseResourceController {
}
protected function getTarifaEnvioListItems($selId = null) {
$data = [''=>lang('Basic.global.pleaseSelectA', [mb_strtolower(lang('TarifasEnvios.tarifaEnvio'))])];
if (!empty($selId)) :
$tarifaEnvioModel = model('App\Models\Tarifas\TarifaEnvioModel');
protected function getTarifaEnvioListItems($selId = null)
{
$data = ['' => lang('Basic.global.pleaseSelectA', [mb_strtolower(lang('TarifasEnvios.tarifaEnvio'))])];
if (!empty($selId)):
$tarifaEnvioModel = model('App\Models\Tarifas\TarifaEnvioModel');
$selOption = $tarifaEnvioModel->where('id', $selId)->findColumn('id');
if (!empty($selOption)) :
if (!empty($selOption)):
$data[$selId] = $selOption[0];
endif;
endif;
return $data;
}
return $data;
}
protected function getProveedorListItems($selId = null) {
$data = [''=>lang('Basic.global.pleaseSelectA', [mb_strtolower(lang('LgProveedores.proveedor'))])];
if (!empty($selId)) :
$proveedorModel = model('App\Models\compras\ProveedorModel');
protected function getProveedorListItems($selId = null)
{
$data = ['' => lang('Basic.global.pleaseSelectA', [mb_strtolower(lang('LgProveedores.proveedor'))])];
if (!empty($selId)):
$proveedorModel = model('App\Models\compras\ProveedorModel');
$selOption = $proveedorModel->where('id', $selId)->findColumn('id');
if (!empty($selOption)) :
if (!empty($selOption)):
$data[$selId] = $selOption[0];
endif;
endif;
return $data;
}
return $data;
}
protected function getTipoEnvioOptions() {
$tipoEnvioOptions = [
'' => lang('Basic.global.pleaseSelect'),
'cajas' => 'cajas',
'palets' => 'palets',
];
return $tipoEnvioOptions;
}
protected function getTipoEnvioOptions()
{
$tipoEnvioOptions = [
'' => lang('Basic.global.pleaseSelect'),
'cajas' => 'cajas',
'palets' => 'palets',
];
return $tipoEnvioOptions;
}
}

View File

@ -0,0 +1,320 @@
<?php
namespace App\Controllers;
use App\Controllers\BaseController;
use App\Models\Configuracion\MaquinasTarifasImpresionModel;
use App\Models\Configuracion\PapelGenericoModel;
use App\Models\Configuracion\MaquinaModel;
use App\Models\Presupuestos\PresupuestoModel;
use App\Models\Usuarios\GroupModel;
use App\Models\Usuarios\PermisosModel;
use App\Services\PresupuestoService;
use CodeIgniter\Shield\Entities\User;
class Utiles extends BaseController
{
function __construct()
{
}
public function echo()
{
echo "echo";
}
public function index()
{
echo "ok";
}
public function get_tarifas_encuadernacion()
{
// Llamar al modelo
$model = model('App\Models\Tarifas\TarifaEncuadernacionModel');
// Obtener todos los resultados
$results = $model->where(['is_deleted' => 0])->findAll();
// Iterar sobre cada entidad
echo '<pre>';
foreach ($results as $result) {
// Cada $result es una instancia de una entidad
print_r($result->toArray()); // Convierte la entidad a un array para imprimir sus valores
}
echo '</pre>';
}
public function get_tarifa_encuadernacion($tarifaEncuadernacionId)
{
// Llamar a los modelos
$modelTE = model('App\Models\Tarifas\TarifaEncuadernacionModel');
$modelTELineas = model('App\Models\Tarifas\TarifaEncuadernacionLineaModel');
$modelTELineasHoras = model('App\Models\Tarifas\TarifaEncuadernacionLineaHorasModel');
$modelTETiradas = model('App\Models\Tarifas\TarifaEncuadernacionTiradaModel');
// Obtener el registro principal de tarifa_encuadernacion
$tarifas_encuadernacion = $modelTE->where([
'id' => $tarifaEncuadernacionId,
'is_deleted' => 0
])->findAll();
// Verificar si se encontró la tarifa
if (empty($tarifas_encuadernacion)) {
echo "No se encontraron datos para la tarifa de encuadernación con ID: $tarifaEncuadernacionId.";
return;
}
// Imprimir la tarifa de encuadernación principal
echo "<h3>---------------------- DATO TARIFA ENCUADERNACION ----------------------</h3>";
foreach ($tarifas_encuadernacion as $tarifa_encuadernacion) {
echo "<strong>ID Tarifa: </strong>" . $tarifa_encuadernacion->id . "<br>";
echo "<strong>Nombre: </strong>" . $tarifa_encuadernacion->nombre . "<br>";
echo "<hr>";
}
// Obtener las tiradas asociadas a esta tarifa de encuadernación
$tarifas_encuadernacion_tiradas = $modelTETiradas->where([
'tarifa_encuadernacion_id' => $tarifaEncuadernacionId,
'is_deleted' => 0
])->findAll();
// Verificar si existen tiradas para la tarifa de encuadernación
if (empty($tarifas_encuadernacion_tiradas)) {
echo "No hay tiradas asociadas a esta tarifa de encuadernación.";
return;
}
// Imprimir las tiradas asociadas
echo "<h3>---------------------- DATO TARIFA ENCUADERNACION (TIRADAS) -------------</h3>";
foreach ($tarifas_encuadernacion_tiradas as $tarifa_encuadernacion_tirada) {
echo "<strong>ID Tirada: </strong>" . $tarifa_encuadernacion_tirada->id . "<br>";
echo "<strong>Tirada Min: </strong>" . $tarifa_encuadernacion_tirada->tirada_min . "<br>";
echo "<strong>Tirada Max: </strong>" . $tarifa_encuadernacion_tirada->tirada_max . "<br>";
// Obtener las líneas asociadas a esta tirada
$tarifas_encuadernacion_lineas = $modelTELineas->where([
'tirada_encuadernacion_id' => $tarifa_encuadernacion_tirada->id,
'is_deleted' => 0
])->findAll();
// Verificar si existen líneas asociadas a la tirada
if (empty($tarifas_encuadernacion_lineas)) {
echo "No hay líneas asociadas a esta tirada de encuadernación.<br>";
} else {
// Imprimir las líneas asociadas
echo "<ul>";
foreach ($tarifas_encuadernacion_lineas as $tarifa_encuadernacion_linea) {
echo "<li><strong>ID Línea: </strong>" . $tarifa_encuadernacion_linea->id . "<br>";
}
echo "</ul>";
}
// Obtener las líneas y horas asociadas a esta tirada
$tarifas_encuadernacion_lineas_horas = $modelTELineasHoras->where([
'tirada_encuadernacion_id' => $tarifa_encuadernacion_tirada->id,
'is_deleted' => 0
])->findAll();
// Verificar si existen líneas y horas asociadas a la tirada
if (empty($tarifas_encuadernacion_lineas_horas)) {
echo "No hay líneas y horas asociadas a esta tirada de encuadernación.<br>";
} else {
// Imprimir las líneas asociadas
echo "<ul>";
foreach ($tarifas_encuadernacion_lineas_horas as $tarifas_encuadernacion_linea_hora) {
echo "<li><strong>ID Línea/Hora: </strong>" . $tarifas_encuadernacion_linea_hora->id . "<br>";
}
echo "</ul>";
}
echo "<hr>";
}
echo "<h3>---------------------- FIN DE DATO TARIFA ENCUADERNACION ----------------------</h3>";
}
public function delete_tarifa_encuadernacion($tarifaEncuadernacionId)
{
// Llamar a los modelos
$modelTE = model('App\Models\Tarifas\TarifaEncuadernacionModel');
$modelTELineas = model('App\Models\Tarifas\TarifaEncuadernacionLineaModel');
$modelTELineasHoras = model('App\Models\Tarifas\TarifaEncuadernacionLineaHorasModel');
$modelTETiradas = model('App\Models\Tarifas\TarifaEncuadernacionTiradaModel');
// Obtener el registro principal de tarifa_encuadernacion
$tarifas_encuadernacion = $modelTE->where([
'id' => $tarifaEncuadernacionId,
'is_deleted' => 0
])->findAll();
// Verificar si se encontró la tarifa
if (empty($tarifas_encuadernacion)) {
echo "No se encontró la tarifa de encuadernación con ID: $tarifaEncuadernacionId.";
return;
}
// Iniciar eliminación de datos asociados
echo "Eliminando datos asociados a la tarifa de encuadernación ID: $tarifaEncuadernacionId...<br>";
// Eliminar las tiradas asociadas a la tarifa de encuadernación
$tarifas_encuadernacion_tiradas = $modelTETiradas->where([
'tarifa_encuadernacion_id' => $tarifaEncuadernacionId,
'is_deleted' => 0
])->findAll();
if (!empty($tarifas_encuadernacion_tiradas)) {
foreach ($tarifas_encuadernacion_tiradas as $tarifa_encuadernacion_tirada) {
// Eliminar las líneas de horas asociadas a cada tirada
$tarifas_encuadernacion_lineas_horas = $modelTELineasHoras->where([
'tirada_encuadernacion_id' => $tarifa_encuadernacion_tirada->id,
'is_deleted' => 0
])->findAll();
if (!empty($tarifas_encuadernacion_lineas_horas)) {
foreach ($tarifas_encuadernacion_lineas_horas as $tarifa_encuadernacion_linea_hora) {
$modelTELineasHoras->delete($tarifa_encuadernacion_linea_hora->id); // Eliminar la línea/hora
echo "===sk >-Eliminando Línea/Hora ID: " . $tarifa_encuadernacion_linea_hora->id . "<br>";
}
}
// Eliminar las líneas asociadas a cada tirada
$tarifas_encuadernacion_lineas = $modelTELineas->where([
'tirada_encuadernacion_id' => $tarifa_encuadernacion_tirada->id,
'is_deleted' => 0
])->findAll();
if (!empty($tarifas_encuadernacion_lineas)) {
foreach ($tarifas_encuadernacion_lineas as $tarifa_encuadernacion_linea) {
$modelTELineas->delete($tarifa_encuadernacion_linea->id); // Eliminar la línea
echo "===>-Eliminando Línea ID: " . $tarifa_encuadernacion_linea->id . "<br>";
}
}
// Eliminar la tirada
$modelTETiradas->delete($tarifa_encuadernacion_tirada->id); // Eliminar la tirada
echo "=>-Eliminando Tirada ID: " . $tarifa_encuadernacion_tirada->id . "<br>";
}
}
echo " *** Proceso de eliminación completado. ***<br><br>";
}
public function clone_tarifa_encuadernacion($origenId, $destinoId)
{
// Llamar a los modelos
$modelTETiradas = model('App\Models\Tarifas\TarifaEncuadernacionTiradaModel');
$modelTELineas = model('App\Models\Tarifas\TarifaEncuadernacionLineaModel');
$modelTELineasHoras = model('App\Models\Tarifas\TarifaEncuadernacionLineaHorasModel');
// 1. Eliminar el contenido asociado de la tarifa destino
$this->delete_tarifa_encuadernacion($destinoId);
// 2. Obtener las tiradas asociadas a la tarifa origen
$tiradasOrigen = $modelTETiradas->where([
'tarifa_encuadernacion_id' => $origenId,
'is_deleted' => 0
])->findAll();
foreach ($tiradasOrigen as $tiradaOrigen) {
// Crear un nuevo registro para la tirada en la tarifa destino
$nuevaTirada = [
'tarifa_encuadernacion_id' => (int) $destinoId,
'proveedor_id' => (int) $tiradaOrigen->proveedor_id,
'importe_fijo' => (float) $tiradaOrigen->importe_fijo,
'tirada_min' => (int) $tiradaOrigen->tirada_min,
'tirada_max' => (int) $tiradaOrigen->tirada_max,
'user_created_id' => (int) auth()->id(),
'is_deleted' => 0
];
try {
$nuevaTiradaId = $modelTETiradas->insert($nuevaTirada);
if (!$nuevaTiradaId) {
throw new \Exception("Error al insertar el registro.");
}
echo "<br>==>+Tirada creada con ID: " . $nuevaTiradaId;
} catch (\Exception $e) {
echo "Error: " . $e->getMessage();
}
// 3. Clonar las líneas asociadas a esta tirada
$lineasOrigen = $modelTELineas->where([
'tirada_encuadernacion_id' => $tiradaOrigen->id,
'is_deleted' => 0
])->findAll();
foreach ($lineasOrigen as $lineaOrigen) {
$nuevaLinea = [
'tirada_encuadernacion_id' => (int) $nuevaTiradaId,
'paginas_libro_min' => (float) $lineaOrigen->paginas_libro_min,
'paginas_libro_max' => (float) $lineaOrigen->paginas_libro_max,
'dimensiones_id' => (int) $lineaOrigen->dimensiones_id,
'precio_min' => (float) $lineaOrigen->precio_min,
'precio_max' => (float) $lineaOrigen->precio_max,
'tirada_min' => (float) $lineaOrigen->tirada_min,
'tirada_max' => (float) $lineaOrigen->tirada_max,
'total_min' => (float) $lineaOrigen->total_min,
'margen' => (float) $lineaOrigen->margen,
'user_created_id' => (int) auth()->id(),
'is_deleted' => 0
];
try {
$nuevaLineaId = $modelTELineas->insert($nuevaLinea);
if (!$nuevaLineaId) {
throw new \Exception("Error al insertar el registro.");
}
echo "<br>====>+Linea creada con ID: " . $nuevaLineaId;
} catch (\Exception $e) {
echo "Error: " . $e->getMessage();
}
}
// 4. Clonar las líneas y horas asociadas a esta tirada
$lineasHorasOrigen = $modelTELineasHoras->where([
'tirada_encuadernacion_id' => $tiradaOrigen->id,
'is_deleted' => 0
])->findAll();
foreach ($lineasHorasOrigen as $lineaHoraOrigen) {
$nuevaLineaHora = [
'tirada_encuadernacion_id' => (int) $nuevaTiradaId,
'tiempo_min' => (float) $lineaHoraOrigen->tiempo_min,
'tiempo_max' => (float) $lineaHoraOrigen->tiempo_max,
'precio_hora' => (float) $lineaHoraOrigen->precio_hora,
'total_min' => (float) $lineaHoraOrigen->total_min,
'margen' => (float) $lineaHoraOrigen->margen,
'user_created_id' => (int) auth()->id(),
'is_deleted' => 0
];
try {
$nuevaLineaHoraId = $modelTELineasHoras->insert($nuevaLineaHora);
if (!$nuevaLineaHoraId) {
throw new \Exception("Error al insertar el registro.");
}
echo "<br>====>+Linea/Hora creado con ID: " . $nuevaLineaHoraId;
} catch (\Exception $e) {
echo "Error: " . $e->getMessage();
}
}
}
echo "<br> *** Proceso de clonacion completado. ***<br><br>";
}
}