merge from main

This commit is contained in:
amazuecos
2024-12-15 19:49:33 +01:00
65 changed files with 2009 additions and 4007 deletions

View File

@ -113,6 +113,7 @@ $routes->group('users', ['namespace' => 'App\Controllers\Configuracion'], functi
$routes->get('delete/(:num)', 'Users::delete/$1', ['as' => 'deleteUser']);
$routes->post('allmenuitems', 'Users::allItemsSelect', ['as' => 'select2ItemsOfUsers']);
$routes->post('menuitems', 'Users::menuItems', ['as' => 'menuItemsOfUsers']);
$routes->post('datatable', 'Users::datatable', ['as' => 'datatableOfUsers']);
$routes->get('getMenuComerciales', 'Users::getMenuComerciales', ['as' => 'menuItemsComerciales']);
});
$routes->resource('users', ['namespace' => 'App\Controllers\Configuracion', 'controller' => 'Users', 'except' => 'show,new,create,update']);
@ -263,6 +264,8 @@ $routes->resource('papelesimpresionmargenes', ['namespace' => 'App\Controllers\C
$routes->group('maquinas', ['namespace' => 'App\Controllers\Configuracion'], function ($routes) {
$routes->get('', 'Maquinas::index', ['as' => 'maquinaList']);
$routes->get('add', 'Maquinas::add', ['as' => 'newMaquina']);
$routes->get('edit/(:num)', 'Maquinas::edit/$1');
$routes->get('delete/(:num)', 'Maquinas::delete/$1');
$routes->post('add', 'Maquinas::add', ['as' => 'createMaquina']);
$routes->post('create', 'Maquinas::create', ['as' => 'ajaxCreateMaquina']);
$routes->put('update/(:num)', 'Maquinas::update/$1', ['as' => 'ajaxUpdateMaquina']);
@ -428,11 +431,15 @@ $routes->resource('clienteplantillaprecios', ['namespace' => 'App\Controllers\Cl
$routes->group('clienteplantillaprecioslineas', ['namespace' => 'App\Controllers\Clientes'], function ($routes) {
$routes->post('datatable', 'Clienteplantillaprecioslineas::datatable', ['as' => 'dataTableOfClientesplantillaprecioslineas']);
$routes->post('datatable_editor', 'Clienteplantillaprecioslineas::datatable_editor', ['as' => 'editorOfClienteplantillaprecioslineas']);
$routes->post('getrows', 'Clienteplantillaprecioslineas::getStoredRows', ['as' => 'getStoredRowsOfClienteplantillaprecioslineas']);
});
$routes->resource('clienteplantillaprecioslineas', ['namespace' => 'App\Controllers\Clientes', 'controller' => 'clienteplantillaprecioslineas', 'except' => 'show,new,create,update']);
$routes->group('clienteusuarios', ['namespace' => 'App\Controllers\Clientes'], function ($routes) {
$routes->post('datatable', 'Clienteusuarios::datatable', ['as' => 'dataTableOfClienteUsuarios']);
$routes->post('adduser', 'Clienteusuarios::addUserToClient');
$routes->get('delete/(:num)', 'Clienteusuarios::removeClienteFromUser/$1');
$routes->get('getusers', 'Clienteusuarios::getAvailableUsers');
});
@ -607,6 +614,7 @@ $routes->group('serviciosacabados', ['namespace' => 'App\Controllers\Presupuesto
$routes->post('datatable', 'Presupuestoacabados::datatable', ['as' => 'dataTableOfPresupuestoAcabados']);
$routes->post('menuitems', 'Presupuestoacabados::menuItems', ['as' => 'menuItemsOfPresupuestoAcabados']);
$routes->post('edit/(:num)', 'Presupuestoacabados::edit/$1', ['as' => 'updatePresupuestoacabados']);
$routes->get('getacabados', 'Presupuestoacabados::getAcabados');
});
$routes->group('serviciosencuadernaciones', ['namespace' => 'App\Controllers\Presupuestos'], function ($routes) {
@ -799,6 +807,11 @@ $routes->group('chat', ['namespace' => 'App\Controllers\Chat'], function ($route
$routes->get('direct/conversation/(:num)', 'ChatController::get_chat_direct/$1', ['as' => 'getChatDirect']);
$routes->get('direct/users/select/(:num)', 'ChatController::get_chat_direct_select_users/$1', ['as' => 'getChatDirectSelectUsers']);
$routes->get('direct/client/users/select/presupuesto/(:num)', 'ChatController::get_presupuesto_client_users/$1/$2', ['as' => 'getPresupuestoClientUsers']);
$routes->get('direct/client/users/select/pedido/(:num)', 'ChatController::get_pedido_client_users/$1/$2', ['as' => 'getPedidoClientUsers']);
$routes->get('direct/client/users/select/factura/(:num)', 'ChatController::get_factura_client_users/$1/$2', ['as' => 'getFacturaClientUsers']);
$routes->get('direct/users/(:num)', 'ChatController::get_chat_direct_users', ['as' => 'getChatDirectUsers']);
$routes->post('direct/users/(:num)', 'ChatController::store_chat_direct_users/$1', ['as' => 'storeChatDirectUsers']);
$routes->get('direct/messages/(:num)', 'ChatController::get_chat_direct_messages/$1', ['as' => 'getChatDirectMessages']);

View File

@ -10,6 +10,9 @@ use App\Models\Chat\ChatModel;
use App\Models\ChatNotification;
use App\Models\ChatUser;
use App\Models\Clientes\ClienteModel;
use App\Models\Facturas\FacturaModel;
use App\Models\Pedidos\PedidoModel;
use App\Models\Presupuestos\PresupuestoModel;
use App\Models\Usuarios\UserModel;
use App\Services\MessageService;
use CodeIgniter\HTTP\ResponseInterface;
@ -396,6 +399,72 @@ class ChatController extends BaseController
return $this->response->setJSON($query->get()->getResultObject());
}
public function get_presupuesto_client_users(int $presupuesto_id)
{
$pm = model(PresupuestoModel::class);
$p = $pm->find($presupuesto_id);
$query = $this->userModel->builder()->select(
[
"id",
"CONCAT(first_name,' ',last_name,'(',username,')') as name"
]
)
->where("deleted_at", null)
->whereNotIn("id", [auth()->user()->id])
->where("cliente_id",$p->cliente_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_pedido_client_users(int $pedido_id)
{
$pm = model(PedidoModel::class);
$p = $pm->find($pedido_id);
$query = $this->userModel->builder()->select(
[
"id",
"CONCAT(first_name,' ',last_name,'(',username,')') as name"
]
)
->where("deleted_at", null)
->whereNotIn("id", [auth()->user()->id])
->where("cliente_id",$p->cliente()->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_factura_client_users(int $factura_id)
{
$fm = model(FacturaModel::class);
$f = $fm->find($factura_id);
$query = $this->userModel->builder()->select(
[
"id",
"CONCAT(first_name,' ',last_name,'(',username,')') as name"
]
)
->where("deleted_at", null)
->whereNotIn("id", [auth()->user()->id])
->where("cliente_id",$f->cliente_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_hebra_presupuesto()
{
$auth_user = auth()->user();

View File

@ -250,11 +250,20 @@ class Cliente extends \App\Controllers\BaseResourceController
$start = $reqData['start'] ?? 0;
$length = $reqData['length'] ?? 5;
$search = $reqData['search']['value'];
$requestedOrder = $reqData['order']['0']['column'] ?? 1;
$order = ClienteModel::SORTABLE[$requestedOrder > 0 ? $requestedOrder : 1];
$dir = $reqData['order']['0']['dir'] ?? 'asc';
$searchValues = get_filter_datatables_columns($reqData);
$requestedOrder = $reqData['order'] ?? [];
$resourceData = $this->model->getResource($search)->orderBy($order, $dir)->limit($length, $start)->get()->getResultObject();
$resourceData = $this->model->getResource($searchValues);
foreach ($requestedOrder as $order) {
$column = $order['column'] ?? 0;
$dir = $order['dir'] ?? 'asc';
$orderColumn = ClienteModel::SORTABLE[$column] ?? null;
if ($orderColumn) {
$resourceData->orderBy($orderColumn, $dir);
}
}
$resourceData = $resourceData->limit($length, $start)->get()->getResultObject();
foreach ($resourceData as $item) :
if (isset($item->direccion) && strlen($item->direccion) > 100) :
$item->direccion = character_limiter($item->direccion, 100);
@ -273,7 +282,7 @@ class Cliente extends \App\Controllers\BaseResourceController
return $this->respond(Collection::datatable(
$resourceData,
$this->model->getResource()->countAllResults(),
$this->model->getResource($search)->countAllResults()
$this->model->getResource($searchValues)->countAllResults()
));
} else {
return $this->failUnauthorized('Invalid request', 403);

View File

@ -120,6 +120,26 @@ class Clienteplantillaprecioslineas extends \App\Controllers\BaseResourceControl
}
}
public function getStoredRows()
{
if ($this->request->isAJAX()) {
$reqData = $this->request->getPost();
$plantilla_id = $reqData['plantilla_id'] ?? 0;
$resourceData = $this->model->getResource([], $plantilla_id);
$resourceData = $resourceData->get()->getResultObject();
return $this->respond(Collection::datatable(
$resourceData,
$this->model->getResource([], $plantilla_id)->countAllResults(),
$this->model->getResource([], $plantilla_id)->countAllResults()
));
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function datatable_editor() {
if ($this->request->isAJAX()) {
@ -178,26 +198,6 @@ class Clienteplantillaprecioslineas extends \App\Controllers\BaseResourceControl
),
)
->validator(function ($editor, $action, $data) {
if ($action === Editor::ACTION_CREATE || $action === Editor::ACTION_EDIT) {
foreach ($data['data'] as $pkey => $values) {
// Si no se quiere borrar...
if ($data['data'][$pkey]['is_deleted'] != 1) {
$process_data['tiempo_min'] = $data['data'][$pkey]['tiempo_min'];
$process_data['tiempo_max'] = $data['data'][$pkey]['tiempo_max'];
$process_data['tipo'] = $data['data'][$pkey]['tipo'];
$process_data['tipo_maquina'] = $data['data'][$pkey]['tipo_maquina'];
$process_data['tipo_impresion'] = $data['data'][$pkey]['tipo_impresion'];
$response = $this->model->checkIntervals($process_data, $pkey, $data['data'][$pkey]['plantilla_id']);
// No se pueden duplicar valores al crear o al editar
if (!empty($response)) {
return $response;
}
}
}
}
})
->on('preCreate', function ($editor, &$values) {
$datetime = (new \CodeIgniter\I18n\Time("now"));
$editor

View File

@ -1,4 +1,5 @@
<?php namespace App\Controllers\Clientes;
<?php
namespace App\Controllers\Clientes;
use App\Controllers\BaseResourceController;
@ -40,6 +41,59 @@ class Clienteusuarios extends \App\Controllers\BaseResourceController
parent::initController($request, $response, $logger);
}
public function removeClienteFromUser($user_id)
{
if ($this->request->isAJAX()) {
if (intval($user_id) > 0) {
$this->model->removeClienteFromUser($user_id);
return $this->respond(['status' => 'success', 'msg' => 'Usuario eliminado correctamente']);
}
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function addUserToClient(){
if ($this->request->isAJAX()) {
$user_id = $this->request->getPost("user_id");
$cliente_id = $this->request->getPost("cliente_id");
if (intval($user_id) > 0 && intval($cliente_id) > 0) {
$this->model->addUserToClient($user_id, $cliente_id);
return $this->respond(['status' => 'success', 'msg' => 'Usuario añadido correctamente']);
}
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function getAvailableUsers()
{
if ($this->request->isAJAX()) {
$query = $this->model->builder()->select(
[
"id",
"CONCAT(first_name, ' ', last_name) as name"
]
)
->where("deleted_at", null)
->where("cliente_id", null);
if ($this->request->getGet("q")) {
$column = "CONCAT(first_name, ' ', last_name)";
$value = $this->request->getGet("q");
$query->groupStart()
->where("LOWER(CONVERT($column USING utf8)) COLLATE utf8_general_ci LIKE", "%" . strtolower($value) . "%")
->groupEnd();
}
$items = $query->get()->getResultObject();
return $this->response->setJSON($items);
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function datatable()
@ -53,14 +107,19 @@ class Clienteusuarios extends \App\Controllers\BaseResourceController
}
$start = $reqData['start'] ?? 0;
$length = $reqData['length'] ?? 5;
$search = $reqData['search']['value'];
$requestedOrder = $reqData['order']['0']['column'] ?? 1;
$order = ClienteUsuariosModel::SORTABLE[$requestedOrder >= 0 ? $requestedOrder : 1];
$dir = $reqData['order']['0']['dir'] ?? 'asc';
$requestedOrder = $reqData['order'] ?? [];
$id_C = $reqData['id_cliente'] ?? -1;
$resourceData = $this->model->getResource("", $id_C)->orderBy($order, $dir)->limit($length, $start)->get()->getResultObject();
$resourceData = $this->model->getResource("", $id_C);
foreach ($requestedOrder as $order) {
$column = $order['column'] ?? 0;
$dir = $order['dir'] ?? 'asc';
$orderColumn = ClienteUsuariosModel::SORTABLE[$column] ?? null;
if ($orderColumn) {
$resourceData->orderBy($orderColumn, $dir);
}
}
$resourceData = $resourceData->limit($length, $start)->get()->getResultObject();
return $this->respond(Collection::datatable(
$resourceData,

View File

@ -1,4 +1,5 @@
<?php namespace App\Controllers\Configuracion;
<?php
namespace App\Controllers\Configuracion;
use App\Controllers\BaseResourceController;
@ -65,14 +66,50 @@ class Maquinas extends \App\Controllers\BaseResourceController
return view(static::$viewPath . 'viewMaquinaList', $viewData);
}
public function delete($id = null)
{
// Sanitizar el ID
$id = filter_var($id, FILTER_SANITIZE_URL);
// Validar que el ID es válido
if (empty($id) || !is_numeric($id)) {
return $this->respond(['status' => 'error', 'msg' => 'ID no válida']);
}
// Buscar la máquina en la base de datos
$maquina = $this->model->find($id);
if (!$maquina) {
$message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Maquinas.maquina')), $id]);
return $this->respond(['status' => 'error', 'msg' => 'ID no válida']);
}
// Verificar que el usuario está autenticado
if (!auth()->user()) {
return $this->respond(['status' => 'error', 'msg' => 'Usuario no autenticado']);
}
// Preparar los datos para actualizar
$data = [
'id' => $id,
'is_deleted' => 1,
'deleted_at' => date('Y-m-d H:i:s'),
'user_updated_id' => auth()->user()->id,
];
// Guardar los cambios
if (!$this->model->save($data)) {
return $this->respond(['status' => 'error', 'msg' => 'Error al eliminar']);
}
// Retornar éxito
$message = lang('Basic.global.deleteSuccess', [lang('Basic.global.record')]) . '.';
return $this->respond(['status' => 'error', 'msg' => $message]);
}
public function add()
{
if ($this->request->getPost()) :
if ($this->request->getPost()):
$nullIfEmpty = true; // !(phpversion() >= '8.1');
@ -84,10 +121,10 @@ class Maquinas extends \App\Controllers\BaseResourceController
$sanitizedData['user_created_id'] = auth()->user()->id;
$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()) :
if ($this->canValidate()):
try {
$successfulResult = $this->model->skipValidation(true)->save($sanitizedData);
} catch (\Exception $e) {
@ -101,14 +138,14 @@ class Maquinas extends \App\Controllers\BaseResourceController
$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', [lang('Basic.global.record')]) . '.';
if ($thenRedirect) :
if (!empty($this->indexRoute)) :
if ($thenRedirect):
if (!empty($this->indexRoute)):
//return redirect()->to(route_to($this->indexRoute))->with('sweet-success', $message);
return redirect()->to(site_url('configuracion/maquinas/edit/' . $id))->with('sweet-success', $message);
else:
@ -138,20 +175,20 @@ class Maquinas extends \App\Controllers\BaseResourceController
{
if ($requestedId == null) :
if ($requestedId == null):
return $this->redirect2listView();
endif;
$id = filter_var($requestedId, FILTER_SANITIZE_URL);
$maquina = $this->model->find($id);
if ($maquina == false) :
if ($maquina == false):
$message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Maquinas.maquina')), $id]);
return $this->redirect2listView('sweet-error', $message);
endif;
if ($this->request->getPost()) :
if ($this->request->getPost()):
$nullIfEmpty = true; // !(phpversion() >= '8.1');
@ -171,17 +208,19 @@ class Maquinas extends \App\Controllers\BaseResourceController
// JJO
$sanitizedData['user_updated_id'] = auth()->user()->id;
$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()) :
if ($this->canValidate()):
//JJO: comprobar alto y ancho impresion < alto y ancho
if ($sanitizedData['alto'] < $sanitizedData['alto_impresion']) {
$successfulResult = false;
$this->viewData['errorMessage'] = lang('Maquinas.validation.alto_menor_alto_impresion');;
$this->viewData['errorMessage'] = lang('Maquinas.validation.alto_menor_alto_impresion');
;
$this->session->setFlashdata('formErrors', $this->model->errors());
} else if ($sanitizedData['ancho'] < $sanitizedData['ancho_impresion']) {
$successfulResult = false;
$this->viewData['errorMessage'] = lang('Maquinas.validation.ancho_menor_ancho_impresion');;
$this->viewData['errorMessage'] = lang('Maquinas.validation.ancho_menor_ancho_impresion');
;
$this->session->setFlashdata('formErrors', $this->model->errors());
} else {
try {
@ -202,12 +241,12 @@ class Maquinas extends \App\Controllers\BaseResourceController
$thenRedirect = false;
endif;
if ($noException && $successfulResult) :
if ($noException && $successfulResult):
$id = $maquina->id ?? $id;
$message = lang('Basic.global.updateSuccess', [lang('Basic.global.record')]) . '.';
if ($thenRedirect) :
if (!empty($this->indexRoute)) :
if ($thenRedirect):
if (!empty($this->indexRoute)):
return redirect()->to(route_to($this->indexRoute))->with('sweet-success', $message);
else:
return $this->redirect2listView('sweet-success', $message);
@ -243,22 +282,24 @@ class Maquinas extends \App\Controllers\BaseResourceController
}
$start = $reqData['start'] ?? 0;
$length = $reqData['length'] ?? 5;
$search = $reqData['search']['value'];
$requestedOrder = $reqData['order']['0']['column'] ?? 1;
$order = MaquinaModel::SORTABLE[$requestedOrder >= 0 ? $requestedOrder : 1];
$dir = $reqData['order']['0']['dir'] ?? 'asc';
$searchValues = get_filter_datatables_columns($reqData);
$requestedOrder = $reqData['order'] ?? [];
$resourceData = $this->model->getResource($search)->orderBy($order, $dir)->limit($length, $start)->get()->getResultObject();
foreach ($resourceData as $item) :
if (isset($item->observaciones) && strlen($item->observaciones) > 100) :
$item->observaciones = character_limiter($item->observaciones, 100);
endif;
endforeach;
$resourceData = $this->model->getResource($searchValues);
foreach ($requestedOrder as $order) {
$column = $order['column'] ?? 0;
$dir = $order['dir'] ?? 'asc';
$orderColumn = MaquinaModel::SORTABLE[$column] ?? null;
if ($orderColumn) {
$resourceData->orderBy($orderColumn, $dir);
}
}
$resourceData = $resourceData->limit($length, $start)->get()->getResultObject();
return $this->respond(Collection::datatable(
$resourceData,
$this->model->getResource()->countAllResults(),
$this->model->getResource($search)->countAllResults()
$this->model->getResource([])->countAllResults(),
$this->model->getResource($searchValues)->countAllResults()
));
} else {
return $this->failUnauthorized('Invalid request', 403);
@ -319,11 +360,11 @@ class Maquinas extends \App\Controllers\BaseResourceController
protected function getMaquinaListItems($selId = null)
{
$data = ['' => lang('Basic.global.pleaseSelectA', [mb_strtolower(lang('Maquinas.maquina'))])];
if (!empty($selId)) :
if (!empty($selId)):
$maquinaModel = model('App\Models\Configuracion\MaquinaModel');
$selOption = $maquinaModel->where('id', $selId)->findColumn('nombre');
if (!empty($selOption)) :
if (!empty($selOption)):
$data[$selId] = $selOption[0];
endif;
endif;

View File

@ -7,6 +7,8 @@ use App\Models\Usuarios\GroupModel;
use App\Models\UserModel;
use App\Models\Usuarios\GroupsUsersModel;
use App\Models\Collection;
use CodeIgniter\Shield\Entities\User;
use function PHPUnit\Framework\isNull;
@ -22,7 +24,8 @@ class Users extends \App\Controllers\GoBaseController
use \CodeIgniter\API\ResponseTrait;
protected static $primaryModelName = 'App\Models\UserModel';
protected static $primaryModelName = UserModel::class;
protected $modelName = ClientePlantillaPreciosLineasModel::class;
protected static $singularObjectNameCc = 'user';
protected static $singularObjectName = 'User';
@ -58,10 +61,8 @@ class Users extends \App\Controllers\GoBaseController
public function index()
{
$this->viewData['usingClientSideDataTable'] = true;
$this->viewData['usingServerSideDataTable'] = true;
$this->viewData['pageSubTitle'] = lang('Basic.global.ManageAllRecords', [lang('Users.user')]);
$this->viewData['user_model'] = $this->user_model;
$this->viewData['userList2'] = auth()->getProvider()->findAll();
parent::index();
}
@ -313,8 +314,10 @@ class Users extends \App\Controllers\GoBaseController
return $this->redirect2listView('errorMessage', $message);
endif;
$this->chat_department_user_model->where("user_id", $id)->delete();
$users = auth()->getProvider();
$users->delete($user->id, true);
$users->delete($user->id);
$message = "Usuario eliminado correctamente";
return $this->redirect2listView('successMessage', $message);
@ -373,6 +376,43 @@ class Users extends \App\Controllers\GoBaseController
}
}
public function datatable(){
if($this->request->isAJAX()){
$reqData = $this->request->getPost();
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);
return $response;
}
$start = $reqData['start'] ?? 0;
$length = $reqData['length'] ?? 5;
$searchValues = get_filter_datatables_columns($reqData);
$requestedOrder = $reqData['order'] ?? [];
$resourceData = $this->model->getResource($searchValues);
foreach ($requestedOrder as $order) {
$column = $order['column'] ?? 0;
$dir = $order['dir'] ?? 'asc';
$orderColumn = UserModel::SORTABLE[$column] ?? null;
if ($orderColumn) {
$resourceData->orderBy($orderColumn, $dir);
}
}
$resourceData = $resourceData->limit($length, $start)->get()->getResultObject();
return $this->respond(Collection::datatable(
$resourceData,
$this->model->getResource([])->countAllResults(),
$this->model->getResource($searchValues)->countAllResults()
));
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function getMenuComerciales()
{
if ($this->request->isAJAX()) {

View File

@ -1,4 +1,5 @@
<?php namespace App\Controllers\Presupuestos;
<?php
namespace App\Controllers\Presupuestos;
use App\Controllers\BaseResourceController;
@ -9,7 +10,7 @@ use App\Models\Collection;
use App\Models\Presupuestos\PresupuestoAcabadosModel;
class Presupuestoacabados extends \App\Controllers\BaseResourceController
{
@ -37,19 +38,18 @@ class Presupuestoacabados extends \App\Controllers\BaseResourceController
public function edit($requestedId = null)
{
if ($requestedId == null) :
if ($requestedId == null):
return;
endif;
$postData = $this->request->getJSON();
if(count($postData->datos)>0){
if (count($postData->datos) > 0) {
$this->model->deleteServiciosNotInArray($requestedId, $postData->datos);
}
else{
} else {
$this->model->deleteAllServicios($requestedId);
}
if(count($postData->datos)>0){
if (count($postData->datos) > 0) {
$this->model->updateTarifas($requestedId, $postData->datos);
}
@ -58,14 +58,14 @@ class Presupuestoacabados extends \App\Controllers\BaseResourceController
$data = [
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
}
public function update($requestedId = null)
{
if ($requestedId == null) :
if ($requestedId == null):
return;
endif;
@ -75,20 +75,20 @@ class Presupuestoacabados extends \App\Controllers\BaseResourceController
$POD = $postData->POD ?? 0;
$result = [];
if(count($tarifas)>0){
foreach ($tarifas as $tarifa){
if (count($tarifas) > 0) {
foreach ($tarifas as $tarifa) {
$values = $this->model->getPrecioTarifa($tarifa, $tirada, $POD);
array_push($result, $values);
}
}
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
$data = [
'lines' => $result,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
}
@ -101,7 +101,7 @@ class Presupuestoacabados extends \App\Controllers\BaseResourceController
$tirada = $reqData['tirada'] ?? 0;
$proveedor_id = $reqData['proveedor_id'] ?? -1;
$POD = $reqData['POD'] ?? 0;
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
@ -119,17 +119,59 @@ class Presupuestoacabados extends \App\Controllers\BaseResourceController
}
}
public function getAcabados()
{
if ($this->request->isAJAX()) {
$cubierta = $this->request->getGet("cubierta") ?? 0;
$sobrecubierta = $this->request->getGet("sobrecubierta") ?? 0;
$model = model('App\Models\Tarifas\Acabados\TarifaAcabadoModel');
$query = $model->builder()->select(
[
"id",
"nombre as name"
]
)
->where("lg_tarifa_acabado.is_deleted", 0)
->where("lg_tarifa_acabado.mostrar_en_presupuesto", 1);
if($cubierta == 1){
$query->where("lg_tarifa_acabado.acabado_cubierta", 1);
}
else if ($sobrecubierta == 1){
$query->where("lg_tarifa_acabado.acabado_sobrecubierta", 1);
}
if ($this->request->getGet("q")) {
$query->groupStart()
->orLike("lg_tarifa_acabado.nombre", $this->request->getGet("q"))
->groupEnd();
}
$items = $query->get()->getResultObject();
// add a custom item at the beginning
$customItem = new \stdClass;
$customItem->id = 0;
$customItem->name = "Ninguno";
array_unshift($items, $customItem);
return $this->response->setJSON($items);
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function menuItems()
{
if ($this->request->isAJAX()) {
$reqData = $this->request->getPost();
try{
try {
$tarifa_id = $reqData['tarifa_id'] ?? -1;
$tirada = $reqData['tirada'] ?? 0;
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
@ -140,17 +182,15 @@ class Presupuestoacabados extends \App\Controllers\BaseResourceController
$csrfTokenName => $newTokenHash
];
}
catch(Exception $e){
} catch (Exception $e) {
$data = [
'error' => $e,
$csrfTokenName => $newTokenHash
];
}
finally{
} finally {
return $this->respond($data);
}
} else {
return $this->failUnauthorized('Invalid request', 403);
}

View File

@ -22,6 +22,7 @@ use App\Services\PresupuestoClienteService;
use App\Services\PresupuestoService;
use Exception;
use stdClass;
use function PHPUnit\Framework\containsOnly;
@ -328,7 +329,7 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
'gramajeCubierta' => intval($cubierta['gramajeCubierta']),
'carasCubierta' => intval($cubierta['carasImpresion'] ?? 0),
'solapasCubierta' => intval($cubierta['solapas'] ?? 0) == 1 ? intval($cubierta['tamanioSolapas']) : 0,
'acabadosCubierta' => $cubierta['acabados'] ?? 0,
'acabado' => $cubierta['acabado'] ?? 0,
'lomoRedondo' => $lomoRedondo,
];
@ -338,7 +339,7 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
'papel' => $modelPapelGenerico->getIdFromCode($sobrecubierta['papel']),
'gramaje' => intval($sobrecubierta['gramaje']),
'solapas' => intval($sobrecubierta['solapas'] ?? 0),
'acabados' => $sobrecubierta['plastificado'] ?? 0,
'acabado' => $sobrecubierta['acabado'] ?? 0,
];
} else
$sobrecubierta = false;
@ -718,6 +719,8 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
$reqData = $this->request->getPost();
$POD = model('App\Models\Configuracion\ConfiguracionSistemaModel')->getPOD();
$id = $reqData['id'] ?? 0;
$id = intval($id);
@ -794,7 +797,7 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
'gramajeCubierta' => intval($cubierta['gramajeCubierta']),
'carasCubierta' => intval($cubierta['carasImpresion'] ?? 0),
'solapasCubierta' => intval($cubierta['solapas'] ?? 0) == 1 ? intval($cubierta['tamanioSolapas']) : 0,
'acabadosCubierta' => $cubierta['acabados'] ?? 0,
'acabado' => $cubierta['acabado'] ?? 0,
'lomoRedondo' => $cubierta['lomoRedondo'] ?? 0,
'cabezada' => $cubierta['cabezada'] ?? 'WHI',
];
@ -805,7 +808,7 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
'papel' => $modelPapelGenerico->getIdFromCode($sobrecubierta['papel']),
'gramaje' => intval($sobrecubierta['gramaje']),
'solapas' => intval($sobrecubierta['solapas'] ?? 0),
'acabados' => $sobrecubierta['plastificado'] ?? 0,
'acabado' => $sobrecubierta['acabado'] ?? 0,
];
} else
$sobrecubierta = false;
@ -933,33 +936,13 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
$borrar_antes = true;
}
if ($datos_presupuesto['sobrecubierta']) {
$acabado_id = $this->obtenerTarifasAcabado(['plastificado' => $datos_presupuesto['sobrecubierta']['acabados']]);
if (count($acabado_id) > 0) {
$datos_presupuesto['sobrecubierta']['acabados'] = $acabado_id[0];
}
}
$acabado_id = $this->obtenerTarifasAcabado($datos_presupuesto['cubierta']['acabadosCubierta']);
if (count($acabado_id) > 0) {
if (array_key_exists('plastificado', $acabado_id)) {
$datos_presupuesto['cubierta']['acabadosCubierta']['plastificado'] = $acabado_id['plastificado'];
}
if (array_key_exists('barniz', $acabado_id)) {
$datos_presupuesto['cubierta']['acabadosCubierta']['barniz'] = $acabado_id['barniz'];
}
if (array_key_exists('estampado', $acabado_id)) {
$datos_presupuesto['cubierta']['acabadosCubierta']['estampado'] = $acabado_id['estampado'];
}
} else {
$datos_presupuesto['cubierta']['acabadosCubierta']['id'] = 0;
}
$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;
$datos_presupuesto['entrega_taller'] = $reqData['entrega_taller'] ?? 0;
$id = $model_presupuesto->insertarPresupuestoCliente(
$id,
@ -991,6 +974,29 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
$this->guardarLineaPresupuesto($id, $resultado_presupuesto['info']['guardas']);
// Servicios
if ($sobrecubierta) {
if (intval($sobrecubierta['acabado']) > 0) {
$model = model('App\Models\Presupuestos\PresupuestoAcabadosModel');
$servicio = $model->getPrecioTarifa(intval($sobrecubierta['acabado']), intval($selected_tirada), -1, $POD);
if (count($servicio) > 0) {
if ($servicio[0]->total > 0) {
$this->guardarServicio($id, $servicio[0], 'acabado', false, true);
}
}
}
}
if (intval($cubierta['acabado']) > 0) {
$model = model('App\Models\Presupuestos\PresupuestoAcabadosModel');
$servicio = $model->getPrecioTarifa(intval($cubierta['acabado']), intval($selected_tirada), -1, $POD);
if (count($servicio) > 0) {
if ($servicio[0]->total > 0) {
$this->guardarServicio($id, $servicio[0], 'acabado', true, false);
}
}
}
foreach ($resultado_presupuesto['info']['serviciosDefecto'] as $servicio) {
$this->guardarServicio($id, $servicio, 'encuadernacion');
}
@ -1092,26 +1098,22 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
$data['cubierta']['solapas_ancho'] = $presupuesto->solapas_ancho;
$data['cubierta']['cabezada'] = $presupuesto->cabezada;
$modelAcabado = model("App\Models\Tarifas\Acabados\TarifaAcabadoModel");
$data['cubierta']['plastificado'] = $modelAcabado->getCodeFromId($presupuesto->acabado_cubierta_id);
if ($data['cubierta']['plastificado'] == '') {
$data['cubierta']['plastificado'] = 'NONE';
}
$data['cubierta']['barniz'] = $modelAcabado->getCodeFromId($presupuesto->barniz_cubierta_id);
if ($data['cubierta']['barniz'] == '') {
$data['cubierta']['barniz'] = 'NONE';
}
$data['cubierta']['estampado'] = $modelAcabado->getCodeFromId($presupuesto->estampado_cubierta_id);
if ($data['cubierta']['estampado'] == '') {
$data['cubierta']['estampado'] = 'NONE';
$data['cubierta']['acabado']['id'] = $presupuesto->acabado_cubierta_id;
if ($presupuesto->acabado_cubierta_id == 0) {
$data['cubierta']['acabado']['text'] = "Ninguno";
} else {
$data['cubierta']['acabado']['text'] = $modelAcabado->find($presupuesto->acabado_cubierta_id)->nombre;
}
$data['cubierta']['retractilado'] = $presupuesto->retractilado ? 1 : 0;
$data['sobrecubierta'] = array_key_exists('sobrecubierta', $datos_papel) ? $datos_papel['sobrecubierta'] : [];
$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['sobrecubierta']['acabado']['id'] = $presupuesto->acabado_sobrecubierta_id;
if ($presupuesto->acabado_sobrecubierta_id == 0) {
$data['sobrecubierta']['acabado']['text'] = "Ninguno";
} else {
$data['sobrecubierta']['acabado']['text'] = $modelAcabado->find($presupuesto->acabado_sobrecubierta_id)->nombre;
}
$data['guardas'] = array_key_exists('guardas', $datos_papel) ? $datos_papel['guardas'] : [];
@ -1122,7 +1124,12 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
[$data['datosGenerales']['paginasNegro'], $data['datosGenerales']['paginasColor']] =
$this->getPaginas($lineas);
$data['direcciones'] = $this->obtenerDireccionesEnvio($id, $presupuesto->cliente_id);
if (intval($presupuesto->envios_recoge_cliente) == 1) {
$data['direcciones']['entrega_taller'] = 1;
} else {
$data['direcciones']['entrega_taller'] = 0;
$data['direcciones'] = $this->obtenerDireccionesEnvio($id, $presupuesto->cliente_id);
}
if (intval($presupuesto->estado_id) == 2) {
$data['resumen']['base'] = $presupuesto->total_aceptado;
@ -1311,7 +1318,7 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
}
protected function guardarServicio($presupuestoId, $servicio, $tipo)
protected function guardarServicio($presupuestoId, $servicio, $tipo, $cubierta = false, $sobrecubierta = false)
{
if ($tipo == 'encuadernacion') {
@ -1349,9 +1356,12 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
$data = [
'presupuesto_id' => $presupuestoId,
'tarifa_acabado_id' => $servicio->tarifa_id,
'precio_total' => $servicio->total,
'precio_unidad' => $servicio->precio_unidad,
'precio_total' => round($servicio->total, 2),
'precio_unidad' => round($servicio->precio_unidad, 2),
'margen' => $servicio->margen,
'proveedor_id' => $servicio->proveedor_id,
'cubierta' => $cubierta,
'sobrecubierta' => $sobrecubierta,
];
$model->insert($data);
} else if ($tipo == 'manipulado') {
@ -1460,7 +1470,6 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
$gramajeCubierta = $datos_entrada['cubierta']['gramajeCubierta'];
$carasCubierta = $datos_entrada['cubierta']['carasCubierta'];
$solapasCubierta = $datos_entrada['cubierta']['solapasCubierta'];
$acabadosCubierta = $datos_entrada['cubierta']['acabadosCubierta'] ?? [];
$lomoRedondo = $datos_entrada['cubierta']['lomoRedondo'];
// Sobrecubierta
@ -1698,20 +1707,18 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
];
return $return_data;
}
// Acabados Cubierta
$tarifaAcabadoCubierta = $this->obtenerTarifasAcabado($acabadosCubierta);
$acabadoCubierta = [];
foreach ($tarifaAcabadoCubierta as $tarifa) {
if ($tarifa == 0)
continue;
// Acabado Cubierta
if (intval($datos_entrada['cubierta']['acabado']) != 0) {
$model = model('App\Models\Presupuestos\PresupuestoAcabadosModel');
$acabadoCubierta = $model->getPrecioTarifa($tarifa, $datosPedido->tirada, -1, $POD);
$acabadoCubierta = $model->getPrecioTarifa(intval($datos_entrada['cubierta']['acabado']), $datosPedido->tirada, -1, $POD);
if (count($acabadoCubierta) > 0) {
if ($acabadoCubierta[0]->total <= 0) {
$input_data['tarifas_acabado_cubierta'] = $tarifaAcabadoCubierta;
$input_data['tarifas_acabado_cubierta'] = intval($datos_entrada['cubierta']['acabado']);
$errorModel = new ErrorPresupuesto();
$errorModel->insertError(
$datos_entrada['id'],
@ -1785,21 +1792,17 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
}
$lomo_sobrecubierta = $lomo + floatval($linea_sobrecubierta['mano']);
$tarifaAcabadoSobrecubierta = $this->obtenerTarifasAcabado(['plastificado' => $sobreCubierta['acabados']]);
$acabadoSobrecubierta = [];
foreach ($tarifaAcabadoSobrecubierta as $tarifa) {
// Acabado sobrecubierta
if (intval($datos_entrada['sobrecubierta']['acabado']) != 0) {
// NONE
if ($tarifaAcabadoSobrecubierta[0] == 0)
continue;
$model = model('App\Models\Presupuestos\PresupuestoAcabadosModel');
$acabadoSobrecubierta = $model->getPrecioTarifa($tarifa, $datosPedido->tirada, -1, $POD);
$acabadoSobrecubierta = $model->getPrecioTarifa(intval($datos_entrada['sobrecubierta']['acabado']), $datosPedido->tirada, -1, $POD);
if (count($acabadoSobrecubierta) > 0) {
if ($acabadoSobrecubierta[0]->total <= 0) {
$input_data['tarifas_acabado_sobrecubierta'] = $tarifaAcabadoSobrecubierta;
$input_data['tarifas_acabado_sobrecubierta'] = intval($datos_entrada['sobrecubierta']['acabado']);
$errorModel = new ErrorPresupuesto();
$errorModel->insertError(
$datos_entrada['id'],
@ -2250,22 +2253,6 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
return $data;
}
protected function getAcabadosCubierta()
{
$model = model('App\Models\Tarifas\Acabados\TarifaAcabadoModel');
$data = $model->getServiciosAcabadoCubierta();
array_unshift($data, (object) ['id' => '', 'label' => lang('Basic.global.None')]);
return $data;
}
protected function getAcabadosSobrecubierta()
{
$model = model('App\Models\Tarifas\Acabados\TarifaAcabadoModel');
$data = $model->getServiciosAcabadoSobrecubierta();
array_unshift($data, (object) ['id' => '', 'label' => lang('Basic.global.None')]);
return $data;
}
protected function getClienteListItems($selId = null)
{
$data = ['' => lang('Basic.global.pleaseSelectA', [mb_strtolower(lang('Clientes.cliente'))])];
@ -2403,7 +2390,6 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
{
$model = model('App\Models\Presupuestos\PresupuestoDireccionesModel');
$model_direcciones = model('App\Models\Clientes\ClienteDireccionesModel');
$model_pais = model('App\Models\Configuracion\PaisModel');
$direcciones = $model->where('presupuesto_id', $id)->findAll();
$result = [];
@ -2447,16 +2433,16 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
foreach ($data as $linea) {
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'] = $modelPapelGenerico->getNombre($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'] = $modelPapelGenerico->getNombre($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'] = $modelPapelGenerico->getNombre($linea->papel_id);
$return_data['cubierta']['papel']['id'] = $linea->papel_id;
$return_data['cubierta']['gramaje'] = $linea->gramaje;
$return_data['cubierta']['paginas'] = $linea->paginas;
@ -2590,10 +2576,7 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
if ($value != 'NONE') {
$data = $model->where('code', $value)->first();
$data = $data->id;
array_push($tarifas, [$acabado => $data]);
} else {
array_push($tarifas, 0);
$tarifas[$acabado] = $data->id;
}
}

View File

@ -0,0 +1,36 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class RemoveEstampadoBarnizado extends Migration
{
public function up()
{
$this->forge->dropColumn('presupuestos', 'barniz_cubierta_id');
$this->forge->dropColumn('presupuestos', 'estampado_cubierta_id');
}
public function down()
{
$fields = [
'barniz_cubierta_id' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => true,
'null' => false,
'default' => 0,
],
'estampado_cubierta_id' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => true,
'null' => false,
'default' => 0,
],
];
$this->forge->addColumn('presupuestos', $fields);
}
}

View File

@ -4,6 +4,8 @@ namespace App\Entities\Pedidos;
use App\Entities\Presupuestos\PresupuestoEntity;
use App\Entities\Produccion\OrdenTrabajoEntity;
use App\Models\OrdenTrabajo\OrdenTrabajoModel;
use App\Entities\Clientes\ClienteEntity;
use App\Models\Clientes\ClienteModel;
use App\Models\Pedidos\PedidoLineaModel;
use App\Models\Presupuestos\PresupuestoModel;
use CodeIgniter\Entity;
@ -63,4 +65,14 @@ class PedidoEntity extends \CodeIgniter\Entity\Entity
return $m->where("pedido_id",$this->attributes["id"])->first();
}
public function cliente() : ?ClienteEntity
{
$m = model(ClienteModel::class);
$pl = model(PedidoLineaModel::class);
$pm = model(PresupuestoModel::class);
$pedido_linea = $pl->where('pedido_id',$this->attributes["id"])->first();
$pre = $pm->find($pedido_linea->presupuesto_id);
return $m->find($pre->cliente_id);
}
}

View File

@ -67,6 +67,7 @@ return [
'papelFormatoPersonalizado' => 'Tamaño personalizado',
'papelFormatoAncho' => 'Ancho',
'papelFormatoAlto' => 'Alto',
'acabado' => 'Acabado',
'acabadosExteriores' => 'Acabados exteriores',
'acabadoCubierta' => 'Acabado Cubierta',
'acabadoSobrecubierta' => 'Acabado Sobrecubierta',

View File

@ -3,6 +3,7 @@
return [
'add' => 'Añadir',
'address' => 'Dirección',
'blocked' => 'Bloqueado',
'non_blocked' => 'No bloqueado',
@ -38,6 +39,7 @@ return [
'user' => 'Usuario',
'userList' => 'Lista de usuarios',
'users' => 'Usuarios',
'usersAvailables' => 'Usuarios disponibles',
'zipCode' => 'Código postal',
'admin' => 'Administrador',
@ -52,6 +54,8 @@ return [
'editor' => 'Editor',
'beta' => 'Beta',
'cliente' => 'Cliente',
'errors' => [
'cliente_sin_clienteID' => 'El usuario debe de tener un cliente asignado cuando se usa algún rol de cliente.',
],

View File

@ -11,7 +11,7 @@ class ChatDeparmentUserModel extends Model
protected $primaryKey = 'id';
protected $useAutoIncrement = true;
protected $returnType = 'array';
protected $useSoftDeletes = false;
protected $useSoftDeletes = true;
protected $protectFields = true;
protected $allowedFields = [
"chat_department_id",

View File

@ -14,13 +14,14 @@ class ClienteModel extends \App\Models\BaseModel
protected $useAutoIncrement = true;
const SORTABLE = [
0 => "t1.nombre",
1 => "t1.alias",
2 => "t1.cif",
3 => "t1.email",
4 => "t1.comercial_id",
5 => "t1.forma_pago_id",
6 => "t1.vencimiento",
0 => "t1.id",
1 => "t1.nombre",
2 => "t1.alias",
3 => "t1.cif",
4 => "t1.email",
5 => "t1.comercial_id",
6 => "t1.forma_pago_id",
7 => "t1.vencimiento",
];
protected $allowedFields = [
@ -63,7 +64,7 @@ class ClienteModel extends \App\Models\BaseModel
];
protected $returnType = "App\Entities\Clientes\ClienteEntity";
protected $deletedField = 'deleted_at';
protected $deletedField = 'deleted_at';
public static $labelField = "nombre";
@ -245,7 +246,7 @@ class ClienteModel extends \App\Models\BaseModel
"required" => "Clientes.validation.vencimiento.required",
],
];
public function findAllWithAllRelations(string $selcols = "*", int $limit = null, int $offset = 0)
public function findAllWithAllRelations($selcols = "*", int $limit = null, int $offset = 0)
{
$sql =
"SELECT t1." .
@ -279,35 +280,30 @@ class ClienteModel extends \App\Models\BaseModel
*
* @return \CodeIgniter\Database\BaseBuilder
*/
public function getResource(string $search = "")
public function getResource($search = [])
{
$builder = $this->db
->table($this->table . " t1")
->select(
"t1.id AS id, t1.nombre AS nombre, t1.alias AS alias, t1.cif AS cif, t1.email AS email, t1.vencimiento AS vencimiento, t5.first_name AS comercial, t7.nombre AS forma_pago_id"
)
->where("is_deleted", 0);;
->where("is_deleted", 0);
;
$builder->join("users t5", "t1.comercial_id = t5.id", "left");
$builder->join("formas_pago t7", "t1.forma_pago_id = t7.id", "left");
return empty($search)
? $builder
: $builder
->groupStart()
->like("t1.nombre", $search)
->orLike("t1.alias", $search)
->orLike("t1.cif", $search)
->orLike("t1.email", $search)
->orLike("t1.soporte_id", $search)
->orLike("t1.forma_pago_id", $search)
->orLike("t1.vencimiento", $search)
->orLike("t5.id", $search)
->orLike("t5.first_name", $search)
->orLike("t5.last_name", $search)
->orLike("t7.id", $search)
->orLike("t7.nombre", $search)
->groupEnd();
if (empty($search))
return $builder;
else {
$builder->groupStart();
foreach ($search as $col_search) {
$column = self::SORTABLE[$col_search[0]];
$value = $col_search[2];
$builder->where("LOWER(CONVERT($column USING utf8)) COLLATE utf8_general_ci LIKE", "%" . strtolower($value) . "%");
}
$builder->groupEnd();
return $builder;
}
}
/*
@ -353,7 +349,7 @@ class ClienteModel extends \App\Models\BaseModel
->join("pedidos", "pedidos.id = pedidos_linea.pedido_id", "left")
->join("facturas_pedidos_lineas", "facturas_pedidos_lineas.pedido_linea_id = pedidos_linea.id", "left")
->where("t1.id", $cliente_id);
$data = $query->get()->getResultObject();
$data = $query->get()->getResultObject();
$facturas = [];
$presupuestos = [];
$pedidos = [];

View File

@ -160,7 +160,7 @@ class ClientePlantillaPreciosLineasModel extends \App\Models\BaseModel
else {
$builder->groupStart();
foreach ($search as $col_search) {
if ($col_search[1] > 0 && $col_search[0] < 4)
if ($col_search[0] > 0 && $col_search[0] < 4)
$builder->where(self::SORTABLE[$col_search[0]], $col_search[2]);
else
$builder->like(self::SORTABLE[$col_search[0]], $col_search[2]);

View File

@ -16,9 +16,10 @@ class ClienteUsuariosModel extends ShieldUserModel
protected $useAutoIncrement = true;
const SORTABLE = [
0 => "t1.first_name",
1 => "t1.last_name",
2 => "t2.secret",
0 => "t1.id",
1 => "t1.first_name",
2 => "t1.last_name",
3 => "t2.secret",
];
protected $allowedFields = ["id", "first_name", "last_name", "email"];
@ -83,6 +84,19 @@ class ClienteUsuariosModel extends ShieldUserModel
return $result;
}
public function removeClienteFromUser($user_id = -1){
$this->db->table($this->table)->where('id', $user_id)->update(['cliente_id' => null]);
}
public function addUserToClient($user_id = -1, $cliente_id = -1){
if($user_id < 1 || $cliente_id < 1){
return;
}
$this->db->table($this->table)->where('id', $user_id)->update(['cliente_id' => $cliente_id]);
}
/**
* Get resource data.
*
@ -100,15 +114,8 @@ class ClienteUsuariosModel extends ShieldUserModel
);
$builder->join("auth_identities t2", "t1.id = t2.user_id", "left");
$builder->where('t1.id', $cliente_id);
$builder->where('t1.cliente_id', $cliente_id);
return empty($search)
? $builder
: $builder
->groupStart()
->like("t1.first_name", $search)
->orLike("t1.last_name", $search)
->orLike("t2.secret", $search)
->groupEnd();
return $builder;
}
}

View File

@ -14,22 +14,13 @@ class MaquinaModel extends \App\Models\BaseModel
protected $useAutoIncrement = true;
const SORTABLE = [
//1 => "t1.id",
0 => "t1.nombre",
0 => "t1.id",
1 => "t2.nombre",
2 => "t1.tipo",
3 => "t1.velocidad",
4 => "t1.duracion_jornada",
5 => "t1.ancho",
6 => "t1.alto",
7 => "t1.ancho_impresion",
8 => "t1.alto_impresion",
9 => "t1.orden_planning",
10 => "t1.min",
11 => "t1.max",
];
3 => "t1.ancho_impresion",
4 => "t1.alto_impresion",
5 => "t1.min",
6 => "t1.max", ];
protected $allowedFields = [
"nombre",
@ -295,7 +286,7 @@ class MaquinaModel extends \App\Models\BaseModel
*
* @return \CodeIgniter\Database\BaseBuilder
*/
public function getResource(string $search = "")
public function getResource($search = [])
{
$builder = $this->db
->table($this->table . " t1")
@ -313,56 +304,18 @@ class MaquinaModel extends \App\Models\BaseModel
//JJO
$builder->where("t1.is_deleted", 0);
return empty($search)
? $builder
: $builder
->groupStart()
->like("t1.id", $search)
->orLike("t1.nombre", $search)
->orLike("t1.tipo", $search)
->orLike("t1.velocidad", $search)
->orLike("t1.ancho", $search)
->orLike("t1.alto", $search)
->orLike("t1.ancho_impresion", $search)
->orLike("t1.alto_impresion", $search)
->orLike("t1.alto_click", $search)
->orLike("t1.min", $search)
->orLike("t1.max", $search)
->orLike("t1.duracion_jornada", $search)
->orLike("t1.orden_planning", $search)
->orLike("t1.precio_tinta_negro", $search)
->orLike("t1.precio_tinta_color", $search)
->orLike("t1.velocidad_corte", $search)
->orLike("t1.precio_hora_corte", $search)
->orLike("t1.metrosxminuto", $search)
->orLike("t1.forzar_num_formas_horizontales_cubierta", $search)
->orLike("t1.forzar_num_formas_verticales_cubierta", $search)
->orLike("t1.observaciones", $search)
->orLike("t2.id", $search)
->orLike("t1.id", $search)
->orLike("t1.nombre", $search)
->orLike("t1.tipo", $search)
->orLike("t1.velocidad", $search)
->orLike("t1.ancho", $search)
->orLike("t1.alto", $search)
->orLike("t1.ancho_impresion", $search)
->orLike("t1.alto_impresion", $search)
->orLike("t1.alto_click", $search)
->orLike("t1.padre_id", $search)
->orLike("t1.min", $search)
->orLike("t1.max", $search)
->orLike("t1.duracion_jornada", $search)
->orLike("t1.orden_planning", $search)
->orLike("t1.precio_tinta_negro", $search)
->orLike("t1.precio_tinta_color", $search)
->orLike("t1.velocidad_corte", $search)
->orLike("t1.precio_hora_corte", $search)
->orLike("t1.metrosxminuto", $search)
->orLike("t1.forzar_num_formas_horizontales_cubierta", $search)
->orLike("t1.forzar_num_formas_verticales_cubierta", $search)
->orLike("t1.observaciones", $search)
->orLike("t2.nombre", $search)
->groupEnd();
if (empty($search))
return $builder;
else {
$builder->groupStart();
foreach ($search as $col_search) {
$column = self::SORTABLE[$col_search[0]];
$value = $col_search[2];
$builder->where("LOWER(CONVERT($column USING utf8)) COLLATE utf8_general_ci LIKE", "%" . strtolower($value) . "%");
}
$builder->groupEnd();
return $builder;
}
}
public function getMaquinaImpresionForPresupuesto($is_rotativa, $tarifa_tipo, $uso_tarifa , $tirada, $papel_impresion_id = -1)

View File

@ -94,6 +94,20 @@ class PapelGenericoModel extends \App\Models\BaseModel
return $data;
}
public function getNombre($id = 0)
{
$builder = $this->db
->table($this->table . " t1")
->select(
"t1.nombre AS nombre"
)
->where("t1.id", $id)
->where("t1.is_deleted", 0);
$data = $builder->get()->getFirstRow();
// se convierte a de stdClass a array
$data = json_decode(json_encode($data), true);
return $data;
}
/**
* Get resource data.

View File

@ -132,7 +132,7 @@ class BuscadorModel extends \App\Models\BaseModel
t6.estado AS estado"
);
$builder->join("clientes t2", "t1.cliente_id = t2.id", "left");
$builder->join("users t3", "t1.user_update_id = t3.id", "left");
$builder->join("users t3", "t2.comercial_id = t3.id", "left");
$builder->join("lg_paises t5", "t1.pais_id = t5.id", "left");
$builder->join("presupuesto_estados t6", "t1.estado_id = t6.id", "left");
$builder->join("tipos_presupuestos t7", "t1.tipo_impresion_id = t7.id", "left");

View File

@ -434,6 +434,8 @@ class PresupuestoModel extends \App\Models\BaseModel
'merma_cubierta' => $extra_info['merma'],
'paginasCuadernillo' => $data['paginasCuadernillo'],
'recoger_en_taller' => $data['entrega_taller'],
'comp_pos_paginas_color' => $data['interior']['pos_paginas_color'],
'paginas_color_consecutivas' => $data['interior']['paginas_color_consecutivas'],
'papel_interior_diferente' => $data['interior']['papelInteriorDiferente'],
@ -443,10 +445,8 @@ class PresupuestoModel extends \App\Models\BaseModel
'comparador_json_data' => $this->generateJson($data),
'acabado_cubierta_id' => $data['cubierta']['acabadosCubierta']['plastificado'],
'barniz_cubierta_id' => $data['cubierta']['acabadosCubierta']['barniz'],
'estampado_cubierta_id' => $data['cubierta']['acabadosCubierta']['estampado'],
'acabado_sobrecubierta_id' => !$data['sobrecubierta'] ? 0 : $data['sobrecubierta']['acabados'],
'acabado_cubierta_id' => $data['cubierta']['acabado'],
'acabado_sobrecubierta_id' => !$data['sobrecubierta'] ? 0 : $data['sobrecubierta']['acabado'],
'comp_tipo_impresion' => $data['isHq'] ? ($data['isColor'] ? 'colorhq' : 'negrohq') : ($data['isColor'] ? 'color' : 'negro'),

View File

@ -25,6 +25,15 @@ class UserModel extends ShieldUserModel
];
}
const SORTABLE = [
0 => "t1.id",
1 => "t1.first_name",
2 => "t1.last_name",
3 => "t2.secret",
4 => "t3.nombre",
5 => "t1.last_active",
];
protected $returnType = UsersEntity::class;
protected $useSoftDeletes = true;
@ -36,6 +45,7 @@ class UserModel extends ShieldUserModel
protected $validationRules = [
"first_name" => "required|trim|max_length[150]",
"last_name" => "required|trim|max_length[150]",
"email" => "required|valid_email|max_length[150]",
'new_pwd' => 'permit_empty|min_length[8]',
'new_pwd_confirm' => 'permit_empty|required_with[new_pwd]|matches[new_pwd]',
"comments" => "permit_empty|trim|max_length[512]"
@ -59,9 +69,42 @@ class UserModel extends ShieldUserModel
'comments' => [
"max_length" => "Users.validation.last_name.max_length",
],
'email' => [
"required" => "Users.validation.email.required",
"valid_email" => "Users.validation.email.valid_email",
"max_length" => "Users.validation.email.max_length"
]
];
public function getResource($search = [])
{
$builder = $this->db
->table($this->table . " t1")
->select(
"t1.id as id, t1.first_name AS first_name, t1.last_name AS last_name,
t2.secret AS email, t1.last_active AS last_active, t3.nombre AS cliente"
);
$builder->join("auth_identities t2", "t1.id = t2.user_id", "left");
$builder->join("clientes t3", "t1.cliente_id = t3.id", "left");
$builder->where('t1.deleted_at', null)->groupBy("t1.id");
if (empty($search))
return $builder;
else {
$builder->groupStart();
foreach ($search as $col_search) {
$column = self::SORTABLE[$col_search[0]];
$value = $col_search[2];
$builder->where("LOWER(CONVERT($column USING utf8)) COLLATE utf8_general_ci LIKE", "%" . strtolower($value) . "%");
}
$builder->groupEnd();
return $builder;
}
}
public function getComerciales()
{

View File

@ -1,4 +1,9 @@
<div class="col-md-12" id="chat-factura" data-id="<?= $modelId ?>">
<?php if (auth()->user()->inGroup('admin')) { ?>
<div class="d-flex justify-content-start align-items-start gap-2 mb-3">
<button class="btn btn-primary btn-md" id="direct-message-cliente"><i class="ti ti-xs ti-message"></i> Mensaje directo a cliente</button>
</div>
<?php } ?>
<div class="app-chat card overflow-hidden">
<div class="row g-0">
@ -119,6 +124,8 @@
<div class="app-overlay"></div>
</div>
</div>
<?= view("themes/vuexy/components/modals/modalNewDirectMessageClient", ["modelId" => $modelId]) ?>
</div>
<?= $this->section('css') ?>

View File

@ -1,5 +1,9 @@
<div class="col-md-12" id="chat-pedido" data-id="<?= $modelId ?>">
<?php if (auth()->user()->inGroup('admin')) { ?>
<div class="d-flex justify-content-start align-items-start gap-2 mb-3">
<button class="btn btn-primary btn-md" id="direct-message-cliente"><i class="ti ti-xs ti-message"></i> Mensaje directo a cliente</button>
</div>
<?php } ?>
<div class="app-chat card overflow-hidden">
<div class="row g-0">
@ -117,6 +121,8 @@
<div class="app-overlay"></div>
</div>
</div>
<?= view("themes/vuexy/components/modals/modalNewDirectMessageClient", ["modelId" => $modelId]) ?>
</div>

View File

@ -1,7 +1,11 @@
<div class="col-md-12" id="chat-presupuesto" data-id="<?= $modelId ?>">
<div class="app-chat card overflow-hidden">
<?php if (auth()->user()->inGroup('admin')) { ?>
<div class="d-flex justify-content-start align-items-start gap-2 mb-3">
<button class="btn btn-primary btn-md" id="direct-message-cliente"><i class="ti ti-xs ti-message"></i> Mensaje directo a cliente</button>
</div>
<?php } ?>
<div class="app-chat card overflow-hidden border">
<div class="row g-0">
<!-- Chat & Contacts -->
<div class="col app-chat-contacts app-sidebar flex-grow-0 overflow-hidden border-end"
id="app-chat-contacts">
@ -30,8 +34,8 @@
</div>
<!-- Chats -->
<ul class="list-unstyled chat-contact-list" id="chat-list">
<!-- CHAT LIST -->
</ul>
@ -116,6 +120,7 @@
<div class="app-overlay"></div>
</div>
</div>
<?= view("themes/vuexy/components/modals/modalNewDirectMessageClient", ["modelId" => $modelId]) ?>
</div>
<?= $this->section('css') ?>

View File

@ -0,0 +1,47 @@
<!-- Modal -->
<div class="modal fade" id="modalNewDirectMessageClient" tabindex="-1" aria-hidden="true" data-id=<?= $modelId ?>>
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel1"><?= lang('Chat.modal.new_message') ?></h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<div class="col-12 mb-0">
<?= view("themes/vuexy/components/alerts/alert", ["id" => "alertDirectMessage"]) ?>
</div>
<form id="new-direct-message-form">
<div class="form-group">
<div class="row">
<div class="col-12 mb-0">
<label for="new-direct-message-title" class="form-label"><?= lang('Chat.modal.title') ?></label>
<input type="input" rows="4" cols="10" id="new-direct-message-cliente-title" name="title" placeholder="Escriba un título" name="title" class="form-control" required />
</div>
<div class="col-12 mb-0">
<label for="description" class="required form-label"><?= lang('Chat.modal.new_message') ?></label>
<textarea type="input" rows="4" cols="10" id="new-direct-message-cliente-text" name="message" placeholder="Escribe el mensaje ..." name="message" class="form-control" required></textarea>
</div>
<div class="col-12 mb-0">
<label for="select-clients" class="required form-label"><?= lang('Chat.modal.new_receivers') ?></label>
<select id="select-clients" name="clientes" class="form-control" multiple required>
<option value="0"></option>
</select>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-label-secondary" data-bs-dismiss="modal"><?= lang('App.global_come_back') ?></button>
<?php if (auth()->user()->inGroup('admin')) { ?>
<button type="button" id="submit-new-direct-message-client" class="btn btn-primary"><?= lang('Chat.modal.btn_send') ?></button>
<?php } ?>
</div>
</div>
</div>
</div>

View File

@ -654,6 +654,24 @@
</div>
<div class="tab-pane fade" id="usuarios" role="tabpanel">
<div class="row align-items-end">
<div class="col-md-12 col-lg-4 px-4">
<div>
<label id="label_usuario" for="usuarios" class="form-label">
<?= lang('Users.usersAvailables') ?>
</label>
<select id="usuariosDisponibles" name="usuarios_disponibles" class="form-control select2bs2" style="width: 100%;">
</select>
</div>
</div>
<div class="col-md-12 col-lg-4 px-4">
<button id="addUserToClient" type="button" class="btn btn-secondary waves-effect waves-light float-start"><?= lang("Users.add")?></button>
</div>
</div>
<table id="tableOfClienteUsuarios" class="table table-striped table-hover" style="width: 100%;">
<thead>
<tr>
@ -1104,67 +1122,6 @@ function delete_direccion_envio(dataId){
<?=$this->endSection() ?>
<?= $this->section("additionalInlineJs") ?>
/****************************************
Contactos
*****************************************/
const lastColNrCU = $('#tableOfClienteUsuarios').find("tr:first th").length - 1;
var theTableCU = $('#tableOfClienteUsuarios').DataTable( {
serverSide: true,
processing: true,
autoWidth: true,
responsive: true,
lengthMenu: [ 5, 10, 25],
order: [[ 0, "asc" ], [ 1, "asc" ]],
pageLength: 10,
lengthChange: true,
searching: false,
paging: true,
info: false,
dom: '<"mt-4"><"float-end"B><"float-start"l><t><"mt-4 mb-3"p>',
ajax : $.fn.dataTable.pipeline( {
url: '<?= route_to('dataTableOfClienteUsuarios') ?>',
data: {
//id_cliente: id,
id_cliente: 1,
},
method: 'POST',
headers: {'X-Requested-With': 'XMLHttpRequest'},
async: true,
}),
columns: [
{ 'data': 'id' },
{ 'data': 'nombre' },
{ 'data': 'apellidos' },
{ 'data': 'email' },
{
data: actionBtns,
className: 'row-edit dt-center'
}
],
columnDefs: [
{
orderable: false,
searchable: false,
targets: [lastColNrCU]
},
{
"orderData": [ 0, 1 ],
"targets": 0
},
],
language: {
url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json"
}
} );
<?=$this->endSection() ?>
<?=$this->section('css') ?>
<link rel="stylesheet" href="<?= site_url('themes/vuexy/css/datatables-editor/editor.bootstrap5.min.css') ?>">

View File

@ -1,35 +1,35 @@
<?= $this->include('themes/_commonPartialsBs/select2bs5') ?>
<?= $this->include('themes/_commonPartialsBs/datatables') ?>
<?= $this->include('themes/_commonPartialsBs/_confirm2delete') ?>
<?= $this->extend('themes/vuexy/main/defaultlayout') ?>
<?= $this->section('content'); ?>
<?= $this->section('content'); ?>
<div class="row">
<div class="col-md-12">
<div class="card card-info">
<div class="card-header">
<h3 class="card-title"><?=lang('Clientes.clienteList') ?></h3>
<?=anchor(route_to('clienteAdd'), lang('Basic.global.addNew').' '.lang('Clientes.cliente'), ['class'=>'btn btn-primary float-end']); ?>
</div><!--//.card-header -->
<h3 class="card-title"><?= lang('Clientes.clienteList') ?></h3>
<?= anchor(route_to('clienteAdd'), lang('Basic.global.addNew') . ' ' . lang('Clientes.cliente'), ['class' => 'btn btn-primary float-end']); ?>
</div><!--//.card-header -->
<div class="card-body">
<?= view('themes/_commonPartialsBs/_alertBoxes'); ?>
<table id="tableOfClientes" class="table table-striped table-hover" style="width: 100%;">
<thead>
<tr>
<th><?= lang('Clientes.nombre') ?></th>
<th><?= lang('Clientes.alias') ?></th>
<th><?= lang('Clientes.cif') ?></th>
<th><?= lang('Clientes.email') ?></th>
<th><?= lang('Users.comercial') ?></th>
<th><?= lang('FormasPago.formaDePago') ?></th>
<th><?= lang('Clientes.vencimiento') ?></th>
<th class="text-nowrap"><?= lang('Basic.global.Action') ?></th>
</tr>
</thead>
<tbody>
<?= view('themes/_commonPartialsBs/_alertBoxes'); ?>
<table id="tableOfClientes" class="table table-striped table-hover" style="width: 100%;">
<thead>
<tr>
<th>ID</th>
<th><?= lang('Clientes.nombre') ?></th>
<th><?= lang('Clientes.alias') ?></th>
<th><?= lang('Clientes.cif') ?></th>
<th><?= lang('Clientes.email') ?></th>
<th><?= lang('Users.comercial') ?></th>
<th><?= lang('FormasPago.formaDePago') ?></th>
<th><?= lang('Clientes.vencimiento') ?></th>
<th class="text-nowrap noFilter" style="min-width: 80px;"><?= lang('Basic.global.Action') ?></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</tbody>
</table>
</div><!--//.card-body -->
<div class="card-footer">
</div><!--//.card-footer -->
@ -37,111 +37,28 @@
</div><!--//.col -->
</div><!--//.row -->
<?=$this->endSection() ?>
<?= $this->endSection() ?>
<?=$this->section('additionalInlineJs') ?>
const lastColNr = $('#tableOfClientes').find("tr:first th").length - 1;
const actionBtns = function(data) {
return `
<td class="text-right py-0 align-middle">
<div class="btn-group btn-group-sm">
<a href="javascript:void(0);"><i class="ti ti-pencil ti-sm btn-edit mx-2" data-id="${data.id}"></i></a>
<a href="javascript:void(0);"><i class="ti ti-trash ti-sm btn-delete mx-2" data-id="${data.id}" data-bs-toggle="modal" data-bs-target="#confirm2delete"></i></a>
</div>
</td>`;
};
theTable = $('#tableOfClientes').DataTable({
processing: true,
serverSide: true,
autoWidth: true,
responsive: true,
scrollX: true,
lengthMenu: [ 5, 10, 25, 50, 75, 100, 250, 500, 1000, 2500 ],
pageLength: 10,
lengthChange: true,
"dom": 'lfBrtip',
"buttons": [
'copy', 'csv', 'excel', 'print', {
extend: 'pdfHtml5',
orientation: 'landscape',
pageSize: 'A4'
}
],
stateSave: true,
order: [[0, 'asc']],
language: {
url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json"
},
ajax : $.fn.dataTable.pipeline( {
url: '<?= route_to('clienteDT') ?>',
method: 'POST',
headers: {'X-Requested-With': 'XMLHttpRequest'},
async: true,
}),
columnDefs: [
{
orderable: false,
searchable: false,
targets: [lastColNr]
}
],
columns : [
{ 'data': 'nombre' },
{ 'data': 'alias' },
{ 'data': 'cif' },
{ 'data': 'email' },
{ 'data': 'comercial' },
{ 'data': 'forma_pago_id' },
{ 'data': 'vencimiento' },
{ 'data': actionBtns }
]
});
$(document).on('click', '.btn-edit', function(e) {
window.location.href = `/clientes/cliente/edit/${$(this).attr('data-id')}`;
});
$(document).on('click', '.btn-delete', function(e) {
$(".btn-remove").attr('data-id', $(this).attr('data-id'));
});
$(document).on('click', '.btn-remove', function(e) {
const dataId = $(this).attr('data-id');
const row = $(this).closest('tr');
if ($.isNumeric(dataId)) {
$.ajax({
url: `/clientes/cliente/delete/${dataId}`,
method: 'GET',
}).done((data, textStatus, jqXHR) => {
$('#confirm2delete').modal('toggle');
theTable.clearPipeline();
theTable.row($(row)).invalidate().draw();
popSuccessAlert(data.msg ?? jqXHR.statusText);
}).fail((jqXHR, textStatus, errorThrown) => {
popErrorAlert(jqXHR.responseJSON.messages.error)
})
}
});
<?=$this->endSection() ?>
<?=$this->section('css') ?>
<link rel="stylesheet" href="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/buttons/buttons.bootstrap5.min.css") ?>">
<?=$this->endSection() ?>
<?= $this->section('css') ?>
<link rel="stylesheet"
href="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/buttons/buttons.bootstrap5.min.css") ?>">
<?= $this->endSection() ?>
<?= $this->section('additionalExternalJs') ?>
<script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/buttons/dataTables.buttons.min.js") ?>"></script>
<script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/buttons/buttons.bootstrap5.min.js") ?>"></script>
<script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/buttons/buttons.html5.min.js") ?>"></script>
<script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/buttons/buttons.print.min.js") ?>"></script>
<script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/jszip/jszip.min.js") ?>"></script>
<script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/pdfmake/pdfmake.min.js") ?>" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/pdfmake/vfs_fonts.js") ?>"></script>
<?=$this->endSection() ?>
<script
src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/buttons/dataTables.buttons.min.js") ?>"></script>
<script
src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/buttons/buttons.bootstrap5.min.js") ?>"></script>
<script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/buttons/buttons.html5.min.js") ?>"></script>
<script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/buttons/buttons.print.min.js") ?>"></script>
<script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/jszip/jszip.min.js") ?>"></script>
<script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/pdfmake/pdfmake.min.js") ?>"
crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/buttons/buttons.colVis.min.js") ?>"></script>
<script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/pdfmake/vfs_fonts.js") ?>"></script>
<script type="module" src="<?= site_url('assets/js/safekat/pages/cliente/clienteList.js') ?>"></script>
<?= $this->endSection() ?>

View File

@ -18,13 +18,14 @@
<table id="tableOfMaquinas" class="table table-striped table-hover" style="width: 100%;">
<thead>
<tr>
<th style="max-width: 50px;">ID</th>
<th><?= lang('Maquinas.nombre') ?></th>
<th><?= lang('Maquinas.tipo') ?></th>
<th><?= lang('Maquinas.anchoImpresion') ?></th>
<th><?= lang('Maquinas.altoImpresion') ?></th>
<th><?= lang('Maquinas.min') ?></th>
<th><?= lang('Maquinas.max') ?></th>
<th class="text-nowrap"><?= lang('Basic.global.Action') ?></th>
<th class="text-nowrap noFilter" style="min-width:80px;"><?= lang('Basic.global.Action') ?></th>
</tr>
</thead>
<tbody>
@ -42,102 +43,6 @@
<?=$this->endSection() ?>
<?=$this->section('additionalInlineJs') ?>
const lastColNr = $('#tableOfMaquinas').find("tr:first th").length - 1;
const actionBtns = function(data) {
return `
<td class="text-right py-0 align-middle">
<div class="btn-group btn-group-sm">
<a href="javascript:void(0);"><i class="ti ti-pencil ti-sm btn-edit mx-2" data-id="${data.id}"></i></a>
<a href="javascript:void(0);"><i class="ti ti-trash ti-sm btn-delete mx-2" data-id="${data.id}" data-bs-toggle="modal" data-bs-target="#confirm2delete"></i></a>
</div>
</td>`;
};
theTable = $('#tableOfMaquinas').DataTable({
processing: true,
serverSide: true,
autoWidth: true,
responsive: true,
scrollX: true,
lengthMenu: [ 5, 10, 25, 50, 75, 100, 250, 500, 1000, 2500 ],
pageLength: 10,
lengthChange: true,
"dom": 'lfBrtip',
"buttons": [
'copy', 'csv', 'excel', 'print', {
extend: 'pdfHtml5',
orientation: 'landscape',
pageSize: 'A4'
}
],
stateSave: true,
order: [[0, 'asc']],
language: {
url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json"
},
ajax : $.fn.dataTable.pipeline( {
url: '<?= route_to('dataTableOfMaquinas') ?>',
method: 'POST',
headers: {'X-Requested-With': 'XMLHttpRequest'},
async: true,
}),
columnDefs: [
{
orderable: false,
searchable: false,
targets: [lastColNr]
}
],
columns : [
{ 'data': 'nombre' },
{ 'data': 'tipo' },
{ 'data': 'ancho_impresion' },
{ 'data': 'alto_impresion' },
{ 'data': 'min' },
{ 'data': 'max' },
{ 'data': actionBtns }
]
});
theTable.on( 'draw.dt', function () {
const boolCols = [];
for (let coln of boolCols) {
theTable.column(coln, { page: 'current' }).nodes().each( function (cell, i) {
cell.innerHTML = cell.innerHTML == '1' ? '<i class="text-success bi bi-check-lg"></i>' : '';
});
}
});
$(document).on('click', '.btn-edit', function(e) {
window.location.href = `/configuracion/maquinas/edit/${$(this).attr('data-id')}`;
});
$(document).on('click', '.btn-delete', function(e) {
$(".btn-remove").attr('data-id', $(this).attr('data-id'));
});
$(document).on('click', '.btn-remove', function(e) {
const dataId = $(this).attr('data-id');
const row = $(this).closest('tr');
if ($.isNumeric(dataId)) {
$.ajax({
url: `/configuracion/maquinas/delete/${dataId}`,
method: 'GET',
}).done((data, textStatus, jqXHR) => {
$('#confirm2delete').modal('toggle');
theTable.clearPipeline();
theTable.row($(row)).invalidate().draw();
popSuccessAlert(data.msg ?? jqXHR.statusText);
}).fail((jqXHR, textStatus, errorThrown) => {
popErrorAlert(jqXHR.responseJSON.messages.error)
})
}
});
<?=$this->endSection() ?>
<?=$this->section('css') ?>
<link rel="stylesheet" href="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/buttons/buttons.bootstrap5.min.css") ?>">
<?=$this->endSection() ?>
@ -151,5 +56,7 @@
<script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/jszip/jszip.min.js") ?>"></script>
<script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/pdfmake/pdfmake.min.js") ?>" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/pdfmake/vfs_fonts.js") ?>"></script>
<script type="module" src="<?= site_url('assets/js/safekat/pages/maquinas/maquinasList.js') ?>"></script>
<?=$this->endSection() ?>

View File

@ -1,94 +0,0 @@
<div class="col-12 pb-2">
<input hidden readonly style="background: #E8E8E8;" id="id" name="id" maxLength="12" class="form-control" value="<?= old('id', $presupuestoEntity->id) ?>">
<div class="row g-2">
<div class="col-sm-6 mb-3">
<label for="titulo" class="form-label">
<?=lang('Presupuestos.titulo') ?>*
</label>
<input type="text" id="titulo" name="titulo" maxLength="300" class="form-control" value="<?=old('titulo', $presupuestoEntity->titulo) ?>">
</div><!--//.mb-3 -->
<div class="col-sm-6 mb-3">
<label for="autor" class="form-label">
<?=lang('Presupuestos.autor') ?>
</label>
<input type="text" id="autor" name="autor" maxLength="150" class="form-control" value="<?=old('autor', $presupuestoEntity->autor) ?>">
</div><!--//.mb-3 -->
<div class="col-sm-6 mb-3">
<label for="coleccion" class="form-label">
<?=lang('Presupuestos.coleccion') ?>
</label>
<input type="text" id="coleccion" name="coleccion" maxLength="255" class="form-control" value="<?=old('coleccion', $presupuestoEntity->coleccion) ?>">
</div><!--//.mb-3 -->
<div class="col-sm-6 mb-3">
<label for="numeroEdicion" class="form-label">
<?=lang('Presupuestos.numeroEdicion') ?>
</label>
<input type="text" id="numeroEdicion" name="numero_edicion" maxLength="50" class="form-control" value="<?=old('numero_edicion', $presupuestoEntity->numero_edicion) ?>">
</div><!--//.mb-3 -->
<div class="col-sm-6 mb-3">
<label for="numeroEdicion" class="form-label">
<?=lang('Presupuestos.numeroEdicion') ?>
</label>
<input type="text" id="numeroEdicion" name="numero_edicion" maxLength="50" class="form-control" value="<?=old('numero_edicion', $presupuestoEntity->numero_edicion) ?>">
</div>
<div class="col-sm-6 mb-3">
<label for="isbn" class="form-label">
<?=lang('Presupuestos.isbn') ?>
</label>
<input type="text" id="isbn" name="isbn" maxLength="50" class="form-control" value="<?=old('isbn', $presupuestoEntity->isbn) ?>">
</div>
<div class="col-sm-6 mb-3">
<label for="paisId" class="form-label">
<?=lang('Presupuestos.paisId') ?>*
</label>
<select id="paisId" name="pais_id" class="form-control select2bs" style="width: 100%;" >
<?php foreach ($datosPresupuesto->paisList as $item) : ?>
<option value="<?=$item->id ?>"<?=$item->id==$presupuestoEntity->pais_id ? ' selected':'' ?>>
<?=$item->nombre ?>
</option>
<?php endforeach; ?>
</select>
</div>
<hr> <!-- Separador -->
<div class="col-sm-6 mb-3">
<label for="clienteId" class="form-label">
<?= lang('Presupuestos.clienteId') ?>*
</label>
<select id="clienteId" name="clienteId" class="form-control select2bs2" style="width: 100%;">
<?php if (isset($datosPresupuesto->clienteList) && is_array($datosPresupuesto->clienteList) && !empty($datosPresupuesto->clienteList)) :
foreach ($datosPresupuesto->clienteList as $k => $v) : ?>
<option value="<?= $k ?>" <?= $k == $presupuestoEntity->cliente_id ? ' selected' : '' ?>>
<?= $v ?>
</option>
<?php endforeach;
endif; ?>
</select>
</div>
<div class="col-sm-6 mb-3">
<label for="referenciaCliente" class="form-label">
<?=lang('Presupuestos.referenciaCliente') ?>
</label>
<input type="text" id="referenciaCliente" name="referencia_cliente" maxLength="100" class="form-control" value="<?=old('referencia_cliente', $presupuestoEntity->referencia_cliente) ?>">
</div>
</div>
</div><!--//.col -->

View File

@ -1,48 +0,0 @@
<div class="col-12 pb-2">
<div id="containerTiradasEnvios" class="row mb-3">
</div>
<div class="row mb-3">
<div class="col-sm-4 mb-3">
<label for="direcciones" class="form-label">Mis direcciones</label>
<select id="direcciones" name="direcciones" class="form-control select2bs2" style="width: 100%;"></select>
</div>
<div class="col-sm-2 mb-3">
<label for="unidadesEnvio" class="form-label">
Unidades
</label>
<input type="number" class="form-control" id="unidadesEnvio" name="unidadesEnvio" maxLength="8" step="1" class="form-control">
</div><!--//.mb-3 -->
<div class="col-sm-2 mb-3 mt-auto mb-0">
<button id="insertarDireccion" type="button" class="btn btn-secondary waves-effect waves-light">Insertar</button>
</div>
<div id="errorDirecciones" class="fv-plugins-message-container invalid-feedback" style="display: none;">
</div>
</div>
<div class="row mb-3">
<div class="col-sm-4 mb-3">
<div class="form-check form-switch mb-2">
<input class="form-check-input" type="checkbox" id="entregaPieCalle" name="entregaPieCalle" value="1">
<label class="form-check-label" for="add_entregaPieCalle"><?= lang('PresupuestosDirecciones.entregaPieCalle') ?></label>
</div>
</div>
</div>
<div id="divDirecciones" class="col-12 pb-2">
</div>
</div>
<?= $this->section("additionalInlineJs") ?>
window.direcciones = <?= json_encode($presupuestoEntity->direcciones_envio) ?>;
window.direcciones_sel_tirada = <?= json_encode($presupuestoEntity->selected_tirada) ?>;
window.routes_direcciones = {
direcciones: "<?= route_to('getDirecciones') ?>",
getDatos: "<?= route_to('getDatosDireccion') ?>",
nuevaDireccion: "<?= route_to('nuevaDireccion') ?>",
}
<?= $this->endSection() ?>

View File

@ -1,665 +0,0 @@
<div class="col-12 pb-2">
<input hidden readonly style="background: #E8E8E8;" id="id" name="id" maxLength="12" class="form-control" value="<?= old('id', $presupuestoEntity->id) ?>">
<div class="row g-2">
<h3 id="tituloDisenioLibro">Fresado</h3>
<div class="row">
<div class="col-sm-12 mb-3">
<label for="titulo" class="form-label">
<?= lang('Presupuestos.titulo') ?>*
</label>
<input type="text" id="titulo" name="titulo" maxLength="300" class="form-control" value="<?= old('titulo', $presupuestoEntity->titulo) ?>">
</div><!--//.mb-3 -->
</div>
<div class="row">
<div class="col-sm-6 mb-3" <?= $clienteId != 0 && !(auth()->user()->inGroup('admin') || auth()->user()->inGroup('beta')) ?' style="display:none;"':''?>>
<label for="clienteId" class="form-label">
<?= lang('Presupuestos.clienteId') ?>*
</label>
<select id="clienteId" name="clienteId" class="form-control select2bs2" style="width: 100%;">
<?php if (isset($datosPresupuesto->clienteList) && is_array($datosPresupuesto->clienteList) && !empty($datosPresupuesto->clienteList)) :
foreach ($datosPresupuesto->clienteList as $k => $v) : ?>
<option value="<?= $k ?>" <?= $k == $clienteId ? ' selected' : '' ?>>
<?= $v ?>
</option>
<?php endforeach;
endif; ?>
</select>
</div>
<div class="col-sm-6 mb-3">
<label for="referenciaCliente" class="form-label">
<?php if($clienteId == 0): ?>
<?= lang('Presupuestos.referenciaCliente') ?>
<?php else: ?>
<?= lang('Presupuestos.referenciaCliente2') ?>
<?php endif; ?>
</label>
<input type="text" id="referenciaCliente" name="referencia_cliente" maxLength="100" class="form-control" value="<?= old('referencia_cliente', $presupuestoEntity->referencia_cliente) ?>">
</div>
</div>
<div id="tapaDiv" class="row mt-3">
<div class="col-sm-3 mb-md-0 mb-2" id="tapaBlandaDiv">
<div id="tapaBlandaInnerDiv" class="form-check custom-option custom-option-tapa custom-option-basic
<?php echo ($datosPresupuesto->tapa == 'blanda' ? ' checked"': '"'); ?> >
<label class="form-check-label custom-option-content" for="tapaBlanda">
<input name="tapaBlanda" class="form-check-input elementos-libro calcular-presupuesto" type="radio" value="" id="tapaBlanda"
<?php echo ($datosPresupuesto->tapa == 'blanda' ? ' checked=""': ''); ?> >
<span class="custom-option-header">
<span class="h6 mb-0">Tapa blanda</span>
</span>
</label>
</div>
</div>
<div id="tapaDuraDiv" class="col-sm-3 mb-md-0 mb-2">
<div class="form-check custom-option custom-option-tapa custom-option-basic
<?php echo ($datosPresupuesto->tapa == 'dura' ? ' checked"': '"'); ?> >
<label class="form-check-label custom-option-content" for="tapaDura">
<input name="tapaDura" class="form-check-input elementos-libro calcular-presupuesto" type="radio" value="" id="tapaDura"
<?php echo ($datosPresupuesto->tapa == 'dura' ? ' checked=""': ''); ?> >
<span class="custom-option-header">
<span class="h6 mb-0">Tapa Dura</span>
</span>
</label>
</div>
</div>
</div> <!--//.row -->
<div class="divider divider-dark text-start mb-1">
<div class="divider-text">
<h5>Datos presupuesto</h5>
</div>
</div>
<div class="row">
<div id="errorTiradas" class="fv-plugins-message-container invalid-feedback" style="display: none;">
<div>No puede mezclar tiradas mayores de 30 unidades con tiradas menores de 30 unidades</div>
</div>
<div class="row">
<div class="col-sm-3 mb-3">
<label for="tirada" class="form-label">
<?= lang('Presupuestos.tirada') ?> 1
</label>
<input type="number" class="calcular-presupuesto" id="tirada" name="tirada" maxLength="8" step="1" class="form-control" value="<?= old(0, $presupuestoEntity->tirada) ?>">
</div><!--//.mb-3 -->
<div class="col-sm-3 mb-3">
<label for="tirada2" class="form-label">
<?= lang('Presupuestos.tirada') ?> 2
</label>
<input type="number" class="calcular-presupuesto" id="tirada2" name="tirada2" maxLength="8" step="1" class="form-control" value="<?= old(0, $presupuestoEntity->tirada2) ?>">
</div><!--//.mb-3 -->
<div class="col-sm-3 mb-3">
<label for="tirada3" class="form-label">
<?= lang('Presupuestos.tirada') ?> 3
</label>
<input type="number" class="calcular-presupuesto" id="tirada3" name="tirada3" maxLength="8" step="1" class="form-control" value="<?= old(0, $presupuestoEntity->tirada3) ?>">
</div><!--//.mb-3 -->
<div class="col-sm-3 mb-3">
<label for="tirada4" class="form-label">
<?= lang('Presupuestos.tirada') ?> 4
</label>
<input type="number" class="calcular-presupuesto" id="tirada4" name="tirada4" maxLength="8" step="1" class="form-control" value="<?= old(0, $presupuestoEntity->tirada4) ?>">
</div><!--//.mb-3 -->
</div> <!--//.row -->
</div> <!--//.row -->
<div class="row">
<div class="col-sm-3 mb-3">
<label for="paginas" class="form-label">
<?= lang('Presupuestos.paginas') ?>
</label>
<input type="number" class="calcular-presupuesto" id="paginas" name="paginas" maxLength="8" step="1" class="form-control" value="<?= old(0, $presupuestoEntity->paginas) ?>">
</div><!--//.mb-3 -->
<div id="div_pagCuadernillo" class="col-sm-3 mb-3">
<label for="paginas_por_cuadernillo" class="form-label">
<?= lang('Presupuestos.paginasCuadernillo') ?>
</label>
<select id="paginasCuadernillo" name="paginas_por_cuadernillo" class="calcular-presupuesto form-control select2bs2" style="width: 100%;">
<?php if (isset($datosPresupuesto->paginasCuadernillo) && is_array($datosPresupuesto->paginasCuadernillo) && !empty($datosPresupuesto->paginasCuadernillo)) :
foreach ($datosPresupuesto->paginasCuadernillo as $value) : ?>
<option value="<?= $value ?>" <?= $value == $presupuestoEntity->paginas_por_cuadernillo ? ' selected' : '' ?>>
<?= $value ?>
</option>
<?php endforeach;
endif; ?>
</select>
</div><!--//.mb-3 -->
</div> <!--//.row -->
<div class="row">
<div id="tamanioLibroDiv" class="col-sm-3 mb-3" <?= $presupuestoEntity->papel_formato_personalizado == false ? '' : 'style="display: none"'; ?>>
<label id="label_papelFormatoId" for="papelFormatoId" class="form-label">
Tamaño Libro*
</label>
<select id="papelFormatoId" name="papel_formato_id" tabindex="3" class="form-control select2bs2 calcular-presupuesto" style="width: 100%;">
<?php if (isset($datosPresupuesto->papelFormatoList) && is_array($datosPresupuesto->papelFormatoList) && !empty($datosPresupuesto->papelFormatoList)) :
foreach ($datosPresupuesto->papelFormatoList as $formato) : ?>
<option value="<?= $formato->id ?>" <?= $formato->id == $presupuestoEntity->papel_formato_id ? ' selected' : '' ?>>
<?= $formato->tamanio ?>
</option>
<?php endforeach;
endif; ?>
</select>
</div>
<div id="anchoLibroDiv" class="col-sm-3 mb-3" <?= $presupuestoEntity->papel_formato_personalizado == true ? '' : 'style="display: none"'; ?>>
<div class="mb-1">
<label class="form-label" for="papelFormatoAncho">Ancho Libro</label>
<input type="number" id="papelFormatoAncho" name="papel_formato_ancho" maxLength="8" step="1" class="form-control formato_libro calcular-presupuesto" value="<?= old('papel_formato_ancho', $presupuestoEntity->papel_formato_ancho) ?>">
</div><!--//.mb-3 -->
</div><!--//.col -->
<div id="altoLibroDiv" class="col-sm-3 mb-3" <?= $presupuestoEntity->papel_formato_personalizado == true ? '' : 'style="display: none"'; ?>>
<div class="mb-1">
<label class="form-label" for="papelFormatoAlto">Alto Libro</label>
<input type="number" id="papelFormatoAlto" name="papel_formato_alto" maxLength="8" step="1" class="form-control formato_libro calcular-presupuesto" value="<?= old('papel_formato_alto', $presupuestoEntity->papel_formato_alto) ?>">
</div><!--//.mb-3 -->
</div><!--//.col -->
<div class="col-sm-3 mb-3 d-flex align-items-end">
<div class="form-check form-switch mb-2">
<input class="form-check-input" type="checkbox" id="papelFormatoPersonalizado" name="papel_formato_personalizado" value="1" <?= $presupuestoEntity->papel_formato_personalizado == true ? 'checked' : ''; ?>>
<label class="form-check-label" for="papelFormatoPersonalizado"><?= lang('Presupuestos.papelFormatoPersonalizado') ?></label>
</div>
</div>
</div> <!--//.row -->
<div class="divider divider-dark text-start mb-1">
<div class="divider-text">
<h5>Interior</h5>
</div>
</div>
<div id="errorInterior" class="fv-plugins-message-container invalid-feedback" style="display: none;">
<div>No existe combinación con las opciones seleccionadas. Pruebe con otro papel/gramaje</div>
</div>
<h6> Color del interior </h6>
<div class="row-color">
<!-- Fila 1 -->
<div class="row mb-2">
<!-- Imagen 1 (Color Negro) -->
<div class="col-sm-4 offset-sm-1 d-flex flex-column align-items-center justify-content-center">
<div id="colorNegroDiv" class="form-check change-tipo-impresion custom-option-color custom-option custom-option-image custom-option-image-radio">
<label class="form-check-label custom-option-content" for="colorNegro">
<span class="custom-option-body">
<img style="height:150px;width:240px" src="<?= site_url('assets/img/bn.png') ?>" alt="">
</span>
</label>
<input name="colorNegro" class="form-check-input calcular-presupuesto" type="radio" value="colorNegro" id="colorNegro"
<?php echo ($datosPresupuesto->color_impresion == 'negro' ? ' checked=""': ''); ?> >
</div>
<!-- Texto alineado debajo de la imagen -->
<div>
<h6 class="mt-2 text-center">Blanco y Negro Estándar</h6>
</div>
</div>
<!-- Imagen 2 (Color Negro HQ) -->
<div class="col-sm-4 d-flex flex-column align-items-center justify-content-center">
<div id="colorNegroHqDiv" class="form-check change-tipo-impresion custom-option-color custom-option custom-option-image custom-option-image-radio">
<label class="form-check-label custom-option-content" for="colorNegroHq">
<span class="custom-option-body">
<img style="height:150px;width:240px" src="<?= site_url('assets/img/bn_hq.png') ?>" alt="">
</span>
</label>
<input name="colorNegroHq" class="form-check-input calcular-presupuesto" type="radio" value="colorNegroHq" id="colorNegroHq"
<?php echo ($datosPresupuesto->color_impresion == 'negroHq' ? ' checked=""': ''); ?> >
</div>
<!-- Texto alineado debajo de la imagen -->
<div>
<h6 class="mt-2 text-center">Blanco y Negro Premium</h6>
</div>
</div>
</div> <!-- //.row -->
<!-- Fila 2 -->
<div class="row mb-2">
<!-- Imagen 3 (Color) -->
<div class="col-sm-4 offset-sm-1 d-flex flex-column align-items-center justify-content-center">
<div id="colorColorDiv" class="form-check change-tipo-impresion custom-option-color custom-option custom-option-image custom-option-image-radio">
<label class="form-check-label custom-option-content" for="colorColor">
<span class="custom-option-body">
<img style="height:150px;width:240px" src="<?= site_url('assets/img/color.png') ?>" alt="">
</span>
</label>
<input name="colorColor" class="form-check-input calcular-presupuesto" type="radio" value="colorColor" id="colorColor"
<?php echo ($datosPresupuesto->color_impresion == 'color' ? ' checked=""': ''); ?> >
</div>
<!-- Texto alineado debajo de la imagen -->
<div>
<h6 class="mt-2 text-center">Color Estándar</h6>
</div>
</div>
<!-- Imagen 4 (Color HQ) -->
<div class="col-sm-4 d-flex flex-column align-items-center justify-content-center">
<div id="colorColorHqDiv" class="form-check change-tipo-impresion custom-option-color custom-option custom-option-image custom-option-image-radio">
<label class="form-check-label custom-option-content" for="colorColorHq">
<span class="custom-option-body">
<img style="height:150px;width:240px" src="<?= site_url('assets/img/color_hq.png') ?>" alt="">
</span>
</label>
<input name="colorColorHq" class="form-check-input calcular-presupuesto" type="radio" value="colorColorHq" id="colorColorHq"
<?php echo ($datosPresupuesto->color_impresion == 'colorHq' ? ' checked=""': ''); ?> >
</div>
<!-- Texto alineado debajo de la imagen -->
<div>
<h6 class="mt-2 text-center">Color Premium</h6>
</div>
</div>
</div> <!-- //.row -->
</div> <!-- //.row-color -->
<div id="pagColorDiv" class="row">
<div class="col-sm-3 mb-3">
<label for="paginasColor" class="form-label">
Páginas a color
</label>
<input type="number" class="calcular-presupuesto" id="paginasColor" name="paginasColor" maxLength="8" step="1" class="form-control" value="<?= old(0, $presupuestoEntity->paginasColor) ?>">
</div><!--//.mb-3 -->
</div>
<h6> Papel </h6>
<div class="row">
<div class="col-sm-4 mb-md-0 mb-2">
<label for="papelInterior" class="form-label">Tipo de papel</label>
<select id="papelInterior" name="papelInterior" class="form-control select2bs2 calcular-presupuesto" style="width: 100%;"></select>
</div>
<div class="col-sm-2 mb-md-0 mb-2">
<label for="gramajeInterior" class="form-label">Gramaje (g/m2)</label>
<select id="gramajeInterior" name="gramajeInterior" class="form-control select2bs2 calcular-presupuesto" style="width: 100%;">
</select>
</div>
</div>
<h6> Opciones extra </h6>
<div class="row" <?= $clienteId != 0 ?' style="display:none;"':' '?>>
<div class="col-sm-3 mb-3 d-flex align-items-end">
<div class="form-check form-switch mb-2">
<input class="form-check-input calcular-presupuesto" type="checkbox" id="excluirRotativa" name="excluir_rotativa" value="0" <?= $presupuestoEntity->excluir_rotativa == true ? 'checked' : ''; ?>>
<label class="form-check-label" for="excluirRotativa">Excluir rotativa</label>
</div>
</div>
</div>
<!--SECCION DE CUBIERTA -->
<div class="divider divider-dark text-start mb-1">
<div class="divider-text">
<h5>Cubierta</h5>
</div>
</div>
<div id="errorCubierta" class="fv-plugins-message-container invalid-feedback" style="display: none;">
<div>No existe combinación con las opciones seleccionadas. Pruebe con otro papel/gramaje</div>
</div>
<h6> Papel </h6>
<div class="row">
<div class="col-sm-4 mb-md-0 mb-2">
<label for="papelCubierta" class="form-label">Tipo de papel</label>
<select id="papelCubierta" name="papelCubierta" class="form-control select2bs2 calcular-presupuesto" style="width: 100%;">
<?php if (isset($datosPresupuesto->papelCubierta) && is_array($datosPresupuesto->papelCubierta) && !empty($datosPresupuesto->papelCubierta)) :
foreach ($datosPresupuesto->papelCubierta as $k => $v) : ?>
<option value="<?= $v->id ?>">
<?= $v->nombre ?>
</option>
<?php endforeach;
endif; ?>
</select>
</div>
<div class="col-sm-2 mb-md-0 mb-2">
<label for="gramajeCubierta" class="form-label">Gramaje (g/m2)</label>
<select id="gramajeCubierta" name="gramajeCubierta" class="form-control select2bs2 calcular-presupuesto" style="width: 100%;">
</select>
</div>
</div>
<div class="row">
<div class="col-sm-4 mb-md-0 mb-2">
<label for="carasCubierta" class="form-label">Caras impresas cubierta</label>
<select id="carasCubierta" name="carasCubierta" class="form-control select2bs2 calcular-presupuesto" style="width: 100%;">
<option value="2" <?php echo $presupuestoEntity->paginas_cubierta==2?'selected':''?> >
<p><?= lang('Presupuestos.unaCara') ?></p>
</option>
<option value="4" <?php echo $presupuestoEntity->paginas_cubierta==4?'selected':''?>>
<p><?= lang('Presupuestos.dosCaras') ?></p>
</option>
</select>
</div>
</div>
<h6 class='solapas-cubierta'> Opciones extra </h6>
<div class="row solapas-cubierta">
<div class="col-sm-3 mb-md-0 mb-2 d-flex align-items-end">
<div class="form-check form-switch mb-2">
<input class="form-check-input" type="checkbox" id="solapasCubierta" name="solapasCubierta" value="0" <?= $presupuestoEntity->solapas == true ? 'checked' : ''; ?>>
<label class="form-check-label" for="solapasCubierta">Solapas cubierta</label>
</div>
</div>
<div id="tamanioSolapasCubierta" class="col-sm-3 mb-md-0 mb-2" <?= $presupuestoEntity->solapas == true ? '' : 'style="display: none;"'; ?>>
<label for="anchoSolapasCubierta" class="form-label">Tamaño</label>
<input type="number" id="anchoSolapasCubierta" name="anchoSolapasCubierta" maxLength="8" step="1" class="form-control calcular-presupuesto" value="<?= old(0, $presupuestoEntity->solapas_ancho) ?>">
</div>
</div>
<div class="row">
<div class="col-sm-4 mb-md-0 mb-2">
<label for="acabadosCubierta" class="form-label">Acabados cubierta</label>
<select id="acabadosCubierta" name="acabadosCubierta" class="form-control select2bs2 calcular-presupuesto" style="width: 100%;">
<?php if (isset($datosPresupuesto->acabadosCubierta) && is_array($datosPresupuesto->acabadosCubierta) && !empty($datosPresupuesto->acabadosCubierta)) :
foreach ($datosPresupuesto->acabadosCubierta as $acabado) : ?>
<option value="<?= $acabado->id ?>" <?= $acabado->id == $presupuestoEntity->acabado_cubierta_id ? ' selected' : '' ?>>
<?= $acabado->label ?>
</option>
<?php endforeach;
endif; ?>
</select>
</div>
</div>
<!--SECCION DE SOBRECUBIERTA -->
<div class="divider divider-dark text-start mb-1 sobrecubierta">
<div class="divider-text">
<h5>Sobrecubierta</h5>
</div>
</div>
<div id="errorSobrecubierta" class="fv-plugins-message-container invalid-feedback" style="display: none;">
<div>No existe combinación con las opciones seleccionadas. Pruebe con otro papel/gramaje</div>
</div>
<div class="row sobrecubierta">
<div class="col-sm-3 mb-md-0 mb-2 d-flex align-items-end">
<div class="form-check form-switch mb-2">
<input class="form-check-input" type="checkbox" id="enableSobrecubierta" name="enableSobrecubierta" value="0"
<?php if (isset($presupuestoEntity->papel_sobrecubierta) && $presupuestoEntity->papel_sobrecubierta>0) :
echo 'checked';
endif; ?>
>
<label class="form-check-label" for="enableSobrecubierta">Añadir sobrecubierta</label>
</div>
</div>
</div>
<h6 class="sobrecubierta enable-sobrecubierta"
<?php if (isset($presupuestoEntity->papel_sobrecubierta) && $presupuestoEntity->papel_sobrecubierta>0) :
echo '';
else:
echo 'style="display: none;"';
endif; ?>
> Papel </h6>
<div class="row sobrecubierta enable-sobrecubierta">
<div class="col-sm-4 mb-md-0 mb-2">
<label for="papelSobrecubierta" class="form-label">Tipo de papel</label>
<select id="papelSobrecubierta" name="papelSobrecubierta" class="form-control select2bs2 calcular-presupuesto input-sobrecubierta" style="width: 100%;">
<?php if (isset($datosPresupuesto->papelSobrecubierta) && is_array($datosPresupuesto->papelSobrecubierta) && !empty($datosPresupuesto->papelSobrecubierta)) :
foreach ($datosPresupuesto->papelSobrecubierta as $k => $v) : ?>
<option value="<?= $v->id ?>">
<?= $v->nombre ?>
</option>
<?php endforeach;
endif; ?>
</select>
</div>
<div class="col-sm-2 mb-md-0 mb-2">
<label for="gramajeSobrecubierta" class="form-label">Gramaje (g/m2)</label>
<select id="gramajeSobrecubierta" name="gramajeSobrecubierta" class="form-control select2bs2 calcular-presupuesto input-sobrecubierta" style="width: 100%;">
</select>
</div>
</div>
<h6 class="sobrecubierta enable-sobrecubierta"
<?php if (isset($presupuestoEntity->papel_sobrecubierta) && $presupuestoEntity->papel_sobrecubierta>0) :
echo '';
else:
echo 'style="display: none;"';
endif; ?>
> Opciones extra </h6>
<div class="row sobrecubierta enable-sobrecubierta"
<?php if (isset($presupuestoEntity->papel_sobrecubierta) && $presupuestoEntity->papel_sobrecubierta>0) :
echo '';
else:
echo 'style="display: none;"';
endif; ?>
>
<div id="tamanioSolapasSobrecubierta" class="col-sm-3 mb-md-0 mb-2"">
<label for="anchoSolapasSobrecubierta" class="form-label">Tamaño solapas</label>
<input type="number" id="anchoSolapasSobrecubierta" name="anchoSolapasSobrecubierta" maxLength="8" step="1" class="form-control input-sobrecubierta calcular-presupuesto" value="<?= old(0, $presupuestoEntity->solapas_ancho_sobrecubierta) ?>">
</div>
</div>
<div class="row sobrecubierta enable-sobrecubierta"
<?php if (isset($presupuestoEntity->papel_sobrecubierta) && $presupuestoEntity->papel_sobrecubierta>0) :
echo '';
else:
echo 'style="display: none;"';
endif; ?>
>
<div class="col-sm-4 mb-md-0 mb-2">
<label for="acabadosSobrecubierta" class="form-label">Acabados sobrecubierta</label>
<select id="acabadosSobrecubierta" name="acabadosSobrecubierta" class="form-control select2bs2 calcular-presupuesto" style="width: 100%;">
<?php if (isset($datosPresupuesto->acabadosSobrecubierta) && is_array($datosPresupuesto->acabadosSobrecubierta) && !empty($datosPresupuesto->acabadosSobrecubierta)) :
foreach ($datosPresupuesto->acabadosSobrecubierta as $acabado) : ?>
<option value="<?= $acabado->id ?>" <?= $acabado->id == $presupuestoEntity->acabado_sobrecubierta_id ? ' selected' : '' ?>>
<?= $acabado->label ?>
</option>
<?php endforeach;
endif; ?>
</select>
</div>
</div>
<!--SECCION DE GUARDAS -->
<div class="divider divider-dark text-start mb-1 guardas">
<div class="divider-text">
<h5>Guardas</h5>
</div>
</div>
<div id="errorGuardas" class="fv-plugins-message-container invalid-feedback" style="display: none;">
<div>No existe combinación con las opciones seleccionadas. Pruebe con otro papel/gramaje</div>
</div>
<div id="divGuardas" class="row guardas">
<div class="col-sm-4 mb-md-0 mb-2">
<label for="impresionGuardas" class="form-label">Impresión de guardas</label>
<select id="impresionGuardas" name="impresionGuardas" class="form-control select2bs2 comp_guardas_items calcular-presupuesto" style="width: 100%;">
<option value="0"
<?php echo ((!isset($presupuestoEntity->paginas_guardas) || $presupuestoEntity->paginas_guardas==0) ? 'selected' : ''); ?>
>
<p><?= lang('Presupuestos.sinImpresion') ?></p>
</option>
<option value="4"
<?php echo ($presupuestoEntity->paginas_guardas==4 ? 'selected' : ''); ?>
>
<p><?= lang('Presupuestos.unaCara') ?></p>
</option>
<option value="8"
<?php echo ($presupuestoEntity->paginas_guardas==8 ? 'selected' : ''); ?>
>
<p><?= lang('Presupuestos.dosCaras') ?></p>
</option>
</select>
</div>
</div>
<div class="row guardas">
<div class="col-sm-4 mb-md-0 mb-2">
<label for="papelGuardas" class="form-label">Tipo de papel</label>
<select id="papelGuardas" name="papelGuardas" class="form-control select2bs2 calcular-presupuesto" style="width: 100%;">
<?php if (isset($datosPresupuesto->papelGuardas) && is_array($datosPresupuesto->papelGuardas) && !empty($datosPresupuesto->papelGuardas)) :
foreach ($datosPresupuesto->papelGuardas as $k => $v) : ?>
<option value="<?= $v->id ?>" <?php echo ($v->id==$presupuestoEntity->papel_guardas?'selected':'');?> >
<?= $v->nombre ?>
</option>
<?php endforeach;
endif; ?>
</select>
</div>
</div>
<!--SECCION DE SERVICIOS EXTRA -->
<div class="divider divider-dark text-start mb-1">
<div class="divider-text">
<h5>Servicios Extra</h5>
</div>
</div>
<div class="row">
<div class="col-md-12 col-lg-3 px-4">
<div class="mb-3">
<div class="form-check">
<label for="retractilado" class="form-check-label">
<input type="checkbox" id="retractilado" name="retractilado" serv_id="3" value="1" class="form-check-input servicio-extra calcular-presupuesto" <?= $presupuestoEntity->retractilado == true ? 'checked' : ''; ?>>
<?= lang('Presupuestos.retractilado') ?>
</label>
</div><!--//.form-check -->
</div><!--//.mb-3 -->
</div><!--//.col -->
<div class="col-md-12 col-lg-3 px-4">
<div class="mb-3">
<div class="form-check">
<label for="retractilado5" class="form-check-label">
<input type="checkbox" id="retractilado5" name="retractilado_5" serv_id="5" value="1" class="form-check-input servicio-extra calcular-presupuesto" <?= $presupuestoEntity->retractilado5 == true ? 'checked' : ''; ?>>
<?= lang('Presupuestos.retractilado5') ?>
</label>
</div><!--//.form-check -->
</div><!--//.mb-3 -->
</div><!--//.col -->
<div class="col-md-12 col-lg-3 px-4">
<div class="mb-3">
<div class="form-check">
<label for="fajaColor" class="form-check-label">
<input type="checkbox" id="fajaColor" name="faja_color" value="1" serv_id="16" class="form-check-input servicio-extra calcular-presupuesto" <?= $presupuestoEntity->faja_color == true ? 'checked' : ''; ?>>
<?= lang('Presupuestos.fajaColor') ?>
</label>
</div><!--//.form-check -->
</div><!--//.mb-3 -->
</div><!--//.col -->
<div class="col-md-12 col-lg-3 px-4">
<div class="mb-3">
<div class="form-check">
<label for="prototipo" class="form-check-label">
<input type="checkbox" id="prototipo" name="prototipo" value="1" serv_id="9" class="form-check-input servicio-extra calcular-presupuesto" <?= $presupuestoEntity->prototipo == true ? 'checked' : ''; ?>>
<?= lang('Presupuestos.prototipo') ?>
</label>
</div><!--//.form-check -->
</div><!--//.mb-3 -->
<div class="mb-3">
</div><!--//.mb-3 -->
</div><!--//.col -->
<div class="col-md-12 col-lg-3 px-4">
<div class="mb-3">
<div class="form-check">
<label for="ferro" class="form-check-label">
<input type="checkbox" id="ferro" name="ferro" value="1" serv_id="24" class="form-check-input servicio-extra calcular-presupuesto" <?= $presupuestoEntity->ferro == true ? 'checked' : ''; ?>>
<?= lang('Presupuestos.ferro') ?>
</label>
</div><!--//.form-check -->
</div><!--//.mb-3 -->
</div><!--//.col -->
</div><!--//.row -->
<!--SECCION DE OTRAS OPCIONES -->
<div class="divider divider-dark text-start mb-1">
<div class="divider-text">
<h5>Otras opciones</h5>
</div>
</div>
<div class="row">
<div class="col-sm-2 mb-md-0 mb-2">
<label for="ivaReducido" class="form-label">I.V.A. reducido</label>
<select id="ivaReducido" name="ivaReducido" class="form-control select2bs2 calcular-presupuesto" style="width: 100%;">
<option value="1" <?= $presupuestoEntity->iva_reducido == 1? 'selected':''?> >
<p><?= lang('SI') ?></p>
</option>
<option value="0" <?= $presupuestoEntity->iva_reducido == 0? 'selected':''?> >
<p><?= lang('NO') ?></p>
</option>
</select>
</div>
<p class="mt-2">Se verificará que el pedido cumpla con los requisitos establecidos en el Artículo 91 de la Ley 37/1992, sobre inserción de publicidad, antes de proceder con su producción, lo que garantiza la aplicación del IVA reducido del 4%.</p>
</div>
</div><!--//.col -->
</div>
<?= $this->section("additionalInlineJs") ?>
window.datosDisenioLibro = {
papel_interior: <?php echo $presupuestoEntity->papel_interior ? $presupuestoEntity->papel_interior : 'null'; ?>,
gramaje_interior: <?php echo $presupuestoEntity->gramaje_interior ? $presupuestoEntity->gramaje_interior : 'null'; ?>,
papel_cubierta: <?php echo $presupuestoEntity->papel_cubierta ? $presupuestoEntity->papel_cubierta : 'null'; ?>,
gramaje_cubierta: <?php echo $presupuestoEntity->gramaje_cubierta ? $presupuestoEntity->gramaje_cubierta : 'null'; ?>,
papel_sobrecubierta: <?php echo $presupuestoEntity->papel_sobrecubierta ? $presupuestoEntity->papel_sobrecubierta : 'null'; ?>,
gramaje_sobrecubierta: <?php echo $presupuestoEntity->gramaje_sobrecubierta ? $presupuestoEntity->gramaje_sobrecubierta : 'null'; ?>,
}
window.routes_disenio_libro = {
obtenerGramaje: "<?= route_to('obtenerGramaje') ?>",
presupuestoCliente: "<?= route_to('presupuestoCliente') ?>",
}
<?= $this->endSection() ?>

View File

@ -1,316 +0,0 @@
<div class="col-12 pb-2">
<div class="row mb-3">
<?php if($presupuestoEntity->estado_id==2): ?>
<h2>PRESUPUESTO ACEPTADO</h2>
<input type="hidden" id="lomo_cubierta" value=<?php echo $presupuestoEntity->lomo_cubierta ?>>
<br>
<?php endif; ?>
<h3>Resumen</h3>
<div class="col-sm-6">
<h5 class="mb-1">Libro</h5>
<p class="mb-0"><small id="tipoLibro"><?php echo (isset($presupuestoEntity->resumen->titulo)?$presupuestoEntity->resumen->titulo:'') ?></small></p>
<p class="mb-0"><small id="resumenTamanio">Tamaño: <?php echo (isset($presupuestoEntity->resumen->tamanio)?$presupuestoEntity->resumen->tamanio:'') ?></small></p>
<p class="mb-0"><small id="resumenPaginas">Número de páginas: <?php echo $presupuestoEntity->paginas ?></small></p>
<p class="mb-0"><small id="resumenTirada">Tirada: <?php echo $presupuestoEntity->tirada ?></small></p>
<p class="mb-0"><small id="resumenPrototipo">Prototipo: <?php echo ($presupuestoEntity->prototipo?'SI':'NO') ?></small></p>
<p class="mb-3"><small id="resumenFerro">Ferro: <?php echo ($presupuestoEntity->ferro?'SI':'NO') ?></small></p>
<h5 class="mb-1">Interior</h5>
<p class="mb-0"><small id="tipoImpresion">Impresion:
<?php echo (isset($presupuestoEntity->resumen->tipo_impresion)?$presupuestoEntity->resumen->tipo_impresion:'') ?>
</small></p>
<p id="pResumenPaginasColor" class="mb-0" <?php echo ($presupuestoEntity->paginasColor==0?'style="display:none"':'')?>>
<small id="resumenPaginasColor">Páginas a color: <?php echo $presupuestoEntity->paginasColor?></small></p>
<p class="mb-3"><small id="resumenPapelInterior">Papel:
<?php echo (isset($presupuestoEntity->papel_interior_nombre)?$presupuestoEntity->papel_interior_nombre:'') ?>
<?php echo (isset($presupuestoEntity->gramaje_interior)?$presupuestoEntity->gramaje_interior:'') ?>gr/m²</small></p>
<h5 class="mb-1">Cubierta</h5>
<p class="mb-0"><small id="resumenPapelCubierta">Papel:
<?php echo (isset($presupuestoEntity->papel_cubierta_nombre)?$presupuestoEntity->papel_cubierta_nombre:''); ?>
<?php echo (isset($presupuestoEntity->gramaje_cubierta)?$presupuestoEntity->gramaje_cubierta:''); ?>gr/m²</small></p>
<p class="mb-0"><small id="resumenCarasCubierta">Impresión: <?php echo ($presupuestoEntity->paginas_cubierta==2?"1 cara":"2 caras");?></small></p>
<?php if($presupuestoEntity->solapas_ancho>0 || $presupuestoEntity->estado_id==1): ?>
<p class="mb-0"><small id="resumenSolapasCubierta">Solapas: <?php echo $presupuestoEntity->solapas_ancho;?>mm</small></p>
<?php endif; ?>
<?php if($presupuestoEntity->acabado_cubierta_id>0 || $presupuestoEntity->estado_id==1): ?>
<p class="mb-3"><small id="resumenAcabadoCubierta">Acabado:
<?php if (isset($datosPresupuesto->acabadosCubierta) && is_array($datosPresupuesto->acabadosCubierta) && !empty($datosPresupuesto->acabadosCubierta)) :
foreach ($datosPresupuesto->acabadosCubierta as $acabado) :
if ($acabado->id == $presupuestoEntity->acabado_cubierta_id):
echo $acabado->label;
endif;
endforeach;
endif; ?>
</small></p>
<?php endif; ?>
<?php if($presupuestoEntity->papel_sobrecubierta || $presupuestoEntity->estado_id==1): ?>
<h5 class="mb-1 resumen-sobrecubierta">Sobrecubierta</h5>
<p class="mb-0 resumen-sobrecubierta"><small id="resumenPapelSobrecubierta">Papel:
<?php echo (isset($presupuestoEntity->papel_sobrecubierta_nombre)?$presupuestoEntity->papel_sobrecubierta_nombre:'') ?>
<?php echo (isset($presupuestoEntity->gramaje_sobrecubierta)?$presupuestoEntity->gramaje_sobrecubierta:'') ?>gr/m²</small></p>
<?php if($presupuestoEntity->solapas_ancho_sobrecubierta>0 || $presupuestoEntity->estado_id==1): ?>
<p class="mb-0 resumen-sobrecubierta"><small id="resumenSolapasCubierta">Ancho solapas: <?php echo $presupuestoEntity->solapas_ancho_sobrecubierta;?>mm</small></p>
<?php endif; ?>
<p class="mb-3 resumen-sobrecubierta"><small id="resumenAcabadoSobrecubierta">Acabado:
<?php if (isset($datosPresupuesto->acabadosSobrecubierta) && is_array($datosPresupuesto->acabadosSobrecubierta) && !empty($datosPresupuesto->acabadosSobrecubierta)) :
foreach ($datosPresupuesto->acabadosSobrecubierta as $acabado) :
if ($acabado->id == $presupuestoEntity->acabado_sobrecubierta_id):
echo $acabado->label;
endif;
endforeach;
endif; ?>
</small></p>
<?php endif; ?>
<?php if($presupuestoEntity->papel_guardas || $presupuestoEntity->estado_id==1): ?>
<h5 class="mb-1 resumen-guardas">Guardas</h5>
<p class="mb-0 resumen-guardas"><small id="resumenGuardasPapel">Papel:
<?php echo (isset($presupuestoEntity->papel_guardas_nombre)?$presupuestoEntity->papel_guardas_nombre:''); ?>
170gr/m²</small></p>
<p class="mb-3 resumen-guardas"><small id="resumenGuardasCaras">Impresión:
<?php if(!isset($presupuestoEntity->paginas_guardas) || $presupuestoEntity->paginas_guardas==0):
echo "Sin impresion";
elseif($presupuestoEntity->paginas_guardas==4):
echo "1 cara";
else:
echo "2 caras";
endif; ?></small></p>
<?php endif; ?>
<?php if($presupuestoEntity->retractiladol || $presupuestoEntity->retractilado5 || $presupuestoEntity->faja_color || $presupuestoEntity->estado_id==1): ?>
<h5 class="mb-1 resumen-extras">Extras</h5>
<?php endif; ?>
<?php if($presupuestoEntity->retractiladol): ?>
<p class="mb-0 resumen-extras" id="resumenRetractilado1"><small>Retractilado individual</small></p>
<?php elseif ($presupuestoEntity->retractilado5): ?>
<p class="mb-0 resumen-extras" id="resumenRetractilado5"><small>Retractilado de 5</small></p>
<?php elseif ($presupuestoEntity->faja_color): ?>
<p class="mb-0 resumen-extras" id="resumenFajaColor"><small>Imprimir faja a color</small></p>
<?php endif; ?>
</div>
<div class="col-sm-6">
<?php if($presupuestoEntity->estado_id==2):
$total = $presupuestoEntity->total_aceptado;
$iva = $presupuestoEntity->iva_reducido?1.04:1.21;
$total *= $iva;
$total_unidad = $presupuestoEntity->total_precio_unidad * $iva;;
echo '<h4 id="resumenTotalIVA" class="mb-1">Total: ' . round($total, 2) . '€</h4>';
echo '<h6 id="resumenPrecioU" class="mb-0">' . round($total_unidad, 4) . '€/ud</h6>'
?>
<?php else: ?>
<h4 id="resumenTotalIVA" class="mb-1">Total: 100€</h4>
<h6 id="resumenPrecioU" class="mb-0">10.4€/ud</h6>
<?php endif; ?>
<div id="shape-container">
<div id="thumbnail_ec_shape" style="width:350px;height:300px;margin:2.5% auto;"></div>
<div class="d-flex justify-content-center">
<button type="button" id="pv_details" class="btn btn-primary align-content-center"
data-bs-toggle="modal" data-bs-target="#pv_ec_modal">
Previsualizar detalles de cubierta
</button>
</div>
</div>
</div>
</div>
<?php if($presupuestoEntity->estado_id==2):
echo '<div class="row mb-3">';
echo '<h3>Direcciones de envío</h3>';
echo '<div class="col-sm-6">';
if(isset($presupuestoEntity->direcciones_envio)):
foreach ($presupuestoEntity->direcciones_envio as $direccion):
echo '<div class="row mb-3">';
echo '<div class="col-sm-5 form-check custom-option custom-option-basic checked">';
echo '<label class="form-check-label custom-option-content">';
echo '<span class="custom-option-header mb-2">';
echo '<h6 class="fw-semibold mb-0">' . $direccion['att'] . '</h6>';
echo '<span class="badge bg-label-primary">' . $direccion['cantidad'] . ' unidades</span>';
echo '</span>';
echo '<span class="custom-option-body">';
echo '<small>' . $direccion['direccion'] . '</small><br>';
echo '<small>' . $direccion['cp'] . '</small><br>';
echo '<small>' . $direccion['municipio'] .', ' . $direccion['pais'] . '</small><br>';
echo '<small>' . $direccion['telefono'] . '</small><br>';
echo '<small>' . $direccion['email'] . '</small><br>';
if($direccion['entregaPieCalle'] == 1){
echo '<small><i>Envío en palets</i></small><br>';
}
echo '<hr class="my-2">';
echo '</span>';
echo '</label>';
echo '</div>';
echo '</div>';
endforeach;
endif;
echo '</div>';
echo '</div>';
endif; ?>
<?php if($presupuestoEntity->estado_id==2): ?>
<div class="row mb-3">
<h3>Ficheros</h3>
<div class="col-12">
<div class="dropzone needsclick" id="dropzone-multi" >
<div class="dz-message needsclick">
Arrastre aquí los ficheros o haga click
</div>
<div class="fallback">
<input name="file" type="file" />
</div>
</div>
</div>
<button id="submit-all" class="btn mt-3 btn-primary btn-submit waves-effect waves-light ml-2">
<span class="align-middle d-sm-inline-block d-none me-sm-1">Actualizar ficheros</span>
<i class="ti ti-upload ti-xs"></i>
</button>
</div>
<?php endif; ?>
</div>
<!-- Modal -->
<div class="modal fade" id="pv_ec_modal" tabindex="-1">
<div class="modal-dialog modal-xl modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Esquema de cubierta</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close">
</button>
</div>
<div class="modal-body" >
<div id="pv_ec_shape" style="width:850px;height:600px;margin:2.5% auto;"></div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cerrar</button>
</div>
</div>
</div>
</div>
<?= $this->section("additionalInlineJs") ?>
window.estado = <?= $presupuestoEntity->estado_id ?? 1?>;
window.tirada = <?= $presupuestoEntity->selected_tirada ?? 0?>;
window.total = <?= $presupuestoEntity->total_aceptado ?? 0?>;
window.total_unidad = <?= $presupuestoEntity->total_precio_unidad ?? 0 ?>;
window.routes_resumen = {
guardarPresupuesto: "<?= route_to('guardarPresupuesto') ?>",
duplicarPresupuesto: "<?= route_to('duplicarPresupuesto') ?>",
}
<?php if ($presupuestoEntity->estado_id===2): ?>
previewEsquemaCubierta(true);
const previewTemplate = `<div class="dz-preview dz-file-preview">
<div class="dz-details">
<div class="dz-thumbnail">
<!---<img data-dz-thumbnail>
<span class="dz-nopreview">No preview</span> --->
<div class="dz-success-mark"></div>
<div class="dz-error-mark"></div>
<div class="dz-error-message"><span data-dz-errormessage></span></div>
<div class="progress">
<div class="progress-bar progress-bar-primary" role="progressbar" aria-valuemin="0" aria-valuemax="100" data-dz-uploadprogress></div>
</div>
</div>
<div class="dz-filename" data-dz-name></div>
<div class="dz-size" data-dz-size></div>
</div>
</div>`;
Dropzone.autoDiscover = false;
var dropzoneMulti = new Dropzone('#dropzone-multi', {
url: "<?= site_url('presupuestos/presupuestocliente/upload_files') ?>",
addRemoveLinks: true,
previewTemplate: previewTemplate,
paramName: "file",
uploadMultiple: true,
parallelUploads: 4, // Ajusta este número al máximo número de archivos que esperas subir a la vez
maxFiles: 5, // Ajusta este número al máximo número de archivos que esperas subir a la vez
autoProcessQueue: true,
dictRemoveFile: "Eliminar",
acceptedFiles: 'image/*, application/pdf',
maxFilesize: 5e+7, // Bytes
init: function() {
thisDropzone = this;
$('#loader').show();
$.ajax({
url: "<?= site_url('presupuestos/presupuestocliente/get_files') ?>",
type: 'POST',
data: { presupuesto_id: <?= $presupuestoEntity->id ?> },
}).done(function(response) {
if(response == null || response == ""){
return;
}
values = JSON.parse(response);
for(var i = 0; i < values.length; i++){
var mockFile = { name: values[i].name, size: values[i].size, hash: values[i].hash};
thisDropzone.files.push(mockFile); // add to files array
thisDropzone.emit("addedfile", mockFile);
thisDropzone.emit("thumbnail", mockFile, window.location.host + "/sistema/intranet/presupuestos/"+values[i].hash);
thisDropzone.emit("complete", mockFile);
thisDropzone.options.success.call(thisDropzone, mockFile);
};
}).always(function() {
$('#loader').hide();
});
this.on("addedfile", function (file) {
if(file.hash){
var viewButton = Dropzone.createElement("<span class='dz-remove'>Ver</span>");
file.previewElement.appendChild(viewButton);
// Listen to the view button click event
viewButton.addEventListener("click", function (e) {
window.open(window.location.protocol + "//" + window.location.host + "/sistema/intranet/presupuestos/"+file.hash, '_blank');
});
}
});
}
});
$('#presupuesto-cliente-form').submit(function(e){
e.preventDefault();
var files = dropzoneMulti.files;
$('#loader').show();
var formData = new FormData();
var oldFiles = [];
var counter = 0;
for (var i = 0; i < files.length; i++) {
if(files[i].upload){
var file = files[i];
formData.append('file[' + counter + ']', file);
counter += 1;
}
else{
oldFiles.push(files[i].name);
}
}
formData.append('oldFiles', JSON.stringify(oldFiles));
formData.append('presupuesto_id', <?= $presupuestoEntity->id ?>);
$.ajax({
url: "<?= site_url('presupuestos/presupuestocliente/upload_files') ?>",
type: 'POST',
data: formData,
processData: false, // Indicar a jQuery que no procese los datos
contentType: false // Indicar a jQuery que no establezca el tipo de contenido
}).done(function(response) {
// Aquí puedes manejar la respuesta del servidor
}).always(function() {
$('#loader').hide();
})
return false;
});
<?php endif; ?>
<?= $this->endSection() ?>

View File

@ -1,122 +0,0 @@
<div class="col-12 pb-2">
<div class="tipo_libro">
<input type="hidden" id="lomo_cubierta" value=<?php echo $presupuestoEntity->lomo_cubierta ?>>
<div class="row row-cols-3 mb-6 d-flex justify-content-center d-flex justify-content-center">
<div class="container col-md-4 mb-6 d-flex justify-content-center" style="margin-bottom: 40px;">
<div>
<div style="max-width:200px;max-height:200px;padding-right:0px" id="cosidoDiv"
class="form-check custom-option-tipo custom-option custom-option-image custom-option-image-radio
<?php
if($datosPresupuesto->tipo_libro == 'cosido' || $datosPresupuesto->tipo_libro == ''){
echo ' checked"';
}
else
{
echo '"';
}
?>
>
<label style="max-width:200px;max-height:200px;" class="form-check-label custom-option-content"
for="tipoCosido">
<span class="custom-option-body">
<img style="max-width:200px;max-height:200px;"
src="<?= site_url("assets/img/libro_cosido.png") ?>" alt="radioImg">
</span>
</label>
<input name="cosido" class="form-check-input elementos-libro calcular-presupuesto" type="radio" value="tipoCosido"
id="tipoCosido"
<?php
if($datosPresupuesto->tipo_libro == 'cosido' || $datosPresupuesto->tipo_libro == ''){
echo 'checked=""';
}
?>
>
</div>
<h4 class="text-center">Rústica cosido</h4>
</div>
</div>
<div class="container col-md-4 mb-6 d-flex justify-content-center" style="margin-bottom: 40px;">
<div>
<div style="max-width:200px;max-height:200px;padding-right:0px" id="fresadoDiv"
class="form-check custom-option-tipo custom-option custom-option-image custom-option-image-radio
<?php echo ($datosPresupuesto->tipo_libro == 'fresado' ? ' checked"': '"'); ?> >
<label style="max-width:200px;max-height:200px;" class="form-check-label custom-option-content"
for="tipoFresado">
<span class="custom-option-body">
<img style="max-width:200px;max-height:200px;"
src="<?= site_url("assets/img/libro_fresado.png") ?>" alt="radioImg2">
</span>
</label>
<input name="fresado" class="form-check-input elementos-libro calcular-presupuesto" type="radio" value="tipoFresado"
id="tipoFresado" <?php echo (($datosPresupuesto->tipo_libro)=='fresado'? 'checked=""':''); ?> >
</div>
<h4 class="text-center">Rústica fresado</h4>
</div>
</div>
<div class="container col-md-4 mb-6 d-flex justify-content-center" style="margin-bottom: 40px;">
<div>
<div style="max-width:200px;max-height:200px;padding-right:0px" id="grapadoDiv"
class="form-check custom-option-tipo custom-option custom-option-image custom-option-image-radio
<?php echo ($datosPresupuesto->tipo_libro == 'grapado' ? ' checked"': '"'); ?> >
<label style="max-width:200px;max-height:200px;" class="form-check-label custom-option-content"
for="tipoGrapado">
<span class="custom-option-body">
<img style="max-width:200px;max-height:200px;"
src="<?= site_url("assets/img/libro_grapado.png") ?>" alt="radioImg3">
</span>
</label>
<input name="grapado" class="form-check-input elementos-libro calcular-presupuesto" type="radio" value="tipoGrapado"
id="tipoGrapado" <?php echo (($datosPresupuesto->tipo_libro)=='grapado'? 'checked=""':''); ?> >
</div>
<h4 class="text-center">Cosido con grapas</h4>
</div>
</div>
</div>
<div class="row row-cols-3 d-flex justify-content-center d-flex justify-content-center">
<div class="col-md-4 mb-6 d-flex justify-content-center">
<div>
<div style="max-width:200px;max-height:200px;padding-right:0px" id="espiralDiv"
class="form-check custom-option-tipo custom-option custom-option-image custom-option-image-radio
<?php echo ($datosPresupuesto->tipo_libro == 'espiral' ? ' checked"': '"'); ?> >
<label style="max-width:200px;max-height:200px;" class="form-check-label custom-option-content"
for="tipoEspiral">
<span class="custom-option-body">
<img style="max-width:200px;max-height:200px;"
src="<?= site_url("assets/img/libro_espiral.png") ?>" alt="radioImg4">
</span>
</label>
<input name="espiral" class="form-check-input elementos-libro calcular-presupuesto" type="radio" value="tipoEspiral"
id="tipoEspiral" <?php echo (($datosPresupuesto->tipo_libro)=='espiral'? 'checked=""':''); ?> >
</div>
<h4 class="text-center">Espiral</h4>
</div>
</div>
<div class="col-md-4 mb-6 d-flex justify-content-center" >
<div>
<div style="max-width:200px;max-height:200px;padding-right:0px" id="wireoDiv"
class="form-check custom-option-tipo custom-option custom-option-image custom-option-image-radio
<?php echo ($datosPresupuesto->tipo_libro == 'wireo' ? ' checked"': '"'); ?> >
<label style="max-width:200px;max-height:200px;" class="form-check-label custom-option-content"
for="tipoWireO">
<span class="custom-option-body">
<img style="max-width:200px;max-height:200px;"
src="<?= site_url("assets/img/libro_wire-o.png") ?>" alt="radioImg5">
</span>
</label>
<input name="wireo" class="form-check-input elementos-libro calcular-presupuesto" type="radio" value="tipoWireO"
id="tipoWireO" <?php echo (($datosPresupuesto->tipo_libro)=='wireo'? 'checked=""':''); ?> >
</div>
<h4 class="text-center">Wire-o</h4>
</div>
</div>
</div>
</div>
</div>

View File

@ -1,387 +0,0 @@
function initDirecciones() {
data = {
id: $('#clienteId').val()
},
data = Object.assign(data, window.token_ajax);
$('#errorDirecciones').hide();
$.ajax({
url: window.routes_direcciones.direcciones,
type: 'POST',
data: data,
success: function(response) {
$("#direcciones").empty();
$.each(response.menu, function(index, value) {
$("#direcciones").append('<option value="' + value.id + '">' + value.text + '</option>');
});
$("#direcciones").val('');
},
error: function() {
$("#direcciones").empty();
},
});
}
function initTiradasDirecciones() {
const _this = this
let sel_index = 1;
$('#containerTiradasEnvios').empty();
for (i = 1; i <= 4; i++) {
let id = "tiradaPrecio" + i;
if ($('#' + id).length > 0) {
let tirada_id = "ud_tiradaPrecio" + i;
let total_id = "tot_tiradaPrecio" + i;
let precio_u_id = "pu_tiradaPrecio" + i;
let peso = $('#' + id).attr('peso');
let html = '';
html += '<div class="col-sm-3">';
html += '<div id=div-env_' + id + ' class="form-check custom-option custom-option-basic custom-option-tiradasDirecciones">';
html += '<label class="form-check-label custom-option-content" for="tiradaEnvios' + i + '">';
html += '<input name=env_"' + id + '" peso="' + peso + '" class="form-check-input" type="radio" value="" id="env_' + id + '"></input>';
html += '<span class="custom-option-header">';
html += '<span id="tiradaDireccionesValue' + i + '" class="h6 mb-0">' + $('#' + tirada_id).text().split(' ')[0] + '</span>';
html += '<span class="text-muted">' + $('#' + total_id).text() + '</span>';
html += '</span>';
html += '<span class="custom-option-body">';
html += '<small>' + $('#' + precio_u_id).text() + '</small>';
html += '</span>';
html += '</label>';
html += '</div>';
html += '</div>';
$('#containerTiradasEnvios').append(html);
if(parseInt($('#' + tirada_id).text().split(' ')[0]) == window.direcciones_sel_tirada){
sel_index = i;
}
$('#' + id).hide();
}
}
$(('#env_tiradaPrecio' + sel_index)).trigger('click');
cargarDirecciones();
const tiradasDireccionesList = [].slice.call(document.querySelectorAll('.custom-option-tiradasDirecciones .form-check-input'))
tiradasDireccionesList.map(function (customOptionEL) {
// Update custom options check on page load
_this.updateTiradasDireccionesCheck(customOptionEL)
// Update custom options check on click
customOptionEL.addEventListener('click', e => {
_this.updateTiradasDireccionesCheck(customOptionEL)
})
})
}
function cargarDirecciones(){
$('#loader').show();
$('#divDirecciones').empty();
if(window.direcciones == null){
$('#loader').hide();
return;
}
for(let i=0; i<window.direcciones.length; i++){
const tipo = window.direcciones[i].entregaPieCalle == 1?'palets':'cajas';
let html = '';
html += '<div id="envioId' + window.direcciones[i].direccion_id + '" t="' + tipo + '" p= ' +window.direcciones[i].precio + ' class="row mb-3">';
html += '<div class="col-sm-5 form-check custom-option custom-option-basic checked">';
html += '<label class="form-check-label custom-option-content" for="customRadioAddress1">';
html += '<span class="custom-option-header mb-2">';
html += '<h6 class="fw-semibold mb-0">' + window.direcciones[i].att + '</h6>';
html += '<span class="badge bg-label-primary">' + window.direcciones[i].cantidad + ' unidades</span>';
html += '</span>';
html += '<span class="custom-option-body">';
html += '<small>' + window.direcciones[i].direccion + '</small><br>';
html += '<small>' + window.direcciones[i].cp + '</small><br>';
html += '<small>' + window.direcciones[i].municipio +', ' + window.direcciones[i].pais + '</small><br>';
html += '<small>' + window.direcciones[i].telefono + '</small><br>';
html += '<small>' + window.direcciones[i].email + '</small><br>';
if(tipo == 'palets'){
html += '<small><i>Envío en palets</i></small><br>';
}
html += '<hr class="my-2">';
html += '<span class="d-flex">';
html += '<a class="eliminar-direccion" href="javascript:void(0)">Eliminar</a>';
html += '</span>';
html += '</span>';
html += '</label>';
html += '</div>';
html += '</div>';
$('#divDirecciones').append(html);
$('#errorDirecciones').hide();
$('#loader').hide();
}
}
function updateTiradasDireccionesCheck(el) {
if (el.checked) {
// If custom option element is radio, remove checked from the siblings (closest `.row`)
if (el.type === 'radio') {
const customRadioOptionList = [].slice.call(el.closest('.row').querySelectorAll('.custom-option-tiradasDirecciones'))
customRadioOptionList.map(function (customRadioOptionEL) {
customRadioOptionEL.closest('.custom-option-tiradasDirecciones').classList.remove('checked')
let id_temp = customRadioOptionEL.id.split('-')[1];
$('#' + id_temp).prop('checked', false);
})
}
const element = el.closest('.custom-option-tiradasDirecciones');
element.classList.add('checked');
let id = element.id.split('-')[1];
$('#' + id).prop('checked', true);
} else {
el.closest('.custom-option-tiradasDirecciones').classList.remove('checked')
}
}
function obtenerUnidadesEnvio(){
const elements = $('#divDirecciones').find('.row.mb-3');
let total = 0;
if(elements.length > 0) {
for (let index=0; index<elements.length; index++){
let unidades_direcciones = parseInt($(elements[index]).find('div label span span').text().split(' ')[0]);
total += unidades_direcciones;
};
}
return total;
}
$('#insertarDireccion').on('click', function() {
if( $('#direcciones').val() > 0 ) {
let unidades = $('#unidadesEnvio').val();
if(unidades == '' || isNaN(unidades) || parseInt(unidades) <= 0){
return false;
}
unidades = parseInt(unidades);
const seleccion = $('.custom-option-tiradasDirecciones.checked');
if(seleccion.length == 0) {
return false;
}
const element_tirada =($(seleccion[0]).find('label input')[0]);
const number = element_tirada.id.match(/\d+$/);
if (number.length == 0) {
return false;
}
let tirada = parseInt($('#tiradaDireccionesValue' + number[0]).text());
let total = obtenerUnidadesEnvio();
if($('#prototipo').is(':checked')) {
tirada += 1;
}
if(total + unidades <= tirada) {
data = {
id: $('#direcciones').val(),
peso: $('#env_tiradaPrecio' + number[0]).attr('peso'),
unidades: unidades,
entregaPieCalle: $('#entregaPieCalle').is(':checked')?1:0,
},
data = Object.assign(data, window.token_ajax)
$('#loader').show();
$.ajax({
url: window.routes_direcciones.getDatos,
type: 'POST',
data: data,
success: function(response) {
if(response.data.length > 0) {
let html = '';
html += '<div id="envioId' + response.data[0].id + '" t="' +response.data[0].tipo + '" p= ' +response.data[0].coste + ' class="row mb-3">';
html += '<div class="col-sm-5 form-check custom-option custom-option-basic checked">';
html += '<label class="form-check-label custom-option-content" for="customRadioAddress1">';
html += '<span class="custom-option-header mb-2">';
html += '<h6 class="fw-semibold mb-0">' + response.data[0].att + '</h6>';
html += '<span class="badge bg-label-primary">' + unidades + ' unidades</span>';
html += '</span>';
html += '<span class="custom-option-body">';
html += '<small>' + response.data[0].direccion + '</small><br>';
html += '<small>' + response.data[0].cp + '</small><br>';
html += '<small>' + response.data[0].municipio +', ' + response.data[0].pais + '</small><br>';
html += '<small>' + response.data[0].telefono + '</small><br>';
html += '<small>' + response.data[0].email + '</small><br>';
if(response.data[0].tipo == 'palets'){
html += '<small><i>Envío en palets</i></small><br>';
}
html += '<hr class="my-2">';
html += '<span class="d-flex">';
html += '<a class="eliminar-direccion" href="javascript:void(0)">Eliminar</a>';
html += '</span>';
html += '</span>';
html += '</label>';
html += '</div>';
html += '</div>';
$('#divDirecciones').append(html);
$('#errorDirecciones').hide();
$('#loader').hide();
}
},
error: function() {
$("#direcciones").empty();
$('#loader').hide();
},
});
}
else{
$('#errorDirecciones').text('El número de unidades supera la tirada seleccionada.');
$('#errorDirecciones').show();
}
}
return false;
})
$(document).on('click', '.eliminar-direccion', function(e) {
$(this).closest('.row.mb-3').remove();
const seleccion = $('.custom-option-tiradasDirecciones.checked');
if(seleccion.length == 0) {
return false;
}
const element_tirada =($(seleccion[0]).find('label input')[0]);
const number = element_tirada.id.match(/\d+$/);
if (number.length == 0) {
return false;
}
let tirada = parseInt($('#tiradaDireccionesValue' + number[0]).text());
const elements = $('#divDirecciones').find('.row.mb-3');
let total = 0;
if(elements.length > 0) {
for (let index=0; index<elements.length; index++){
let unidades_direcciones = parseInt($(elements[index]).find('div label span span').text().split(' ')[0]);
total += unidades_direcciones;
};
}
if(total <= tirada) {
$('#errorDirecciones').hide();
}
return false;
});
$('#direcciones').on('change', function() {
if( $('#direcciones').val() == 0 ) {
$("#addressForm").attr('action','create')
var $newAddDialog = $("#addressForm")
$newAddDialog.modal('show')
$newAddDialog.on('hidden.bs.modal', function (e) {
$('#direcciones').val('');
});
}
})
function saveAdd_callback(){
if($('#addressForm').attr('action')=='create'){
let data = {
cliente_id: $('#clienteId').val(),
alias: $('#add_alias').val(),
att: $('#add_att').val(),
email: $('#add_email').val(),
direccion: $('#add_direccion').val(),
pais_id: $("#add_pais_id option:selected").val(),
municipio: $('#add_municipio').val(),
provincia: $('#add_provincia').val(),
cp: $('#add_cp').val(),
telefono: $('#add_telefono').val(),
}
data = Object.assign(data, window.token_ajax)
$.ajax({
url: window.routes_direcciones.nuevaDireccion,
type: 'POST',
data: data,
success: function(response) {
$("#direcciones").empty();
$.each(response.data, function(index, value) {
$("#direcciones").append('<option value="' + value.id + '">' + value.text + '</option>');
});
$("#direcciones").val('');
$('#addressForm').modal('hide');
},
error: function() {
$('#addressForm').modal('hide');
},
});
}
}
function validarEnvio(){
const seleccion = $('.custom-option-tiradasDirecciones.checked');
if(seleccion.length == 0) {
return false;
}
const element_tirada =($(seleccion[0]).find('label input')[0]);
const number = element_tirada.id.match(/\d+$/);
if (number.length == 0) {
return false;
}
let tirada = parseInt($('#tiradaDireccionesValue' + number[0]).text());
let total = obtenerUnidadesEnvio();
if($('#prototipo').is(':checked')) {
tirada += 1;
}
if(total != tirada){
return false;
}
return true;
}
function getDireccionesEnvio(){
const elements = $('#divDirecciones').find('.row.mb-3');
let direcciones = [];
if(elements.length > 0) {
for (let index=0; index<elements.length; index++){
const unidades = parseInt($(elements[index]).find('div label span span').text().split(' ')[0]);
const id = $(elements[index]).attr('id').replace('envioId', '');
const tipo = $(elements[index]).attr('t');
direcciones.push({
unidades: unidades,
id: id,
tipo: tipo,
})
};
}
return direcciones;
}

View File

@ -1,789 +0,0 @@
$('#papelFormatoPersonalizado').on('change', function () {
if ($(this).is(":checked")) {
$('#tamanioLibroDiv').hide();
$('#anchoLibroDiv').show();
$('#altoLibroDiv').show();
$('#papelFormatoId').val('').trigger('change');
} else {
$('#tamanioLibroDiv').show();
$('#anchoLibroDiv').hide();
$('#altoLibroDiv').hide();
}
});
// Init custom option check
function initTapaCheck() {
const _this = this
const tapaOptionList = [].slice.call(document.querySelectorAll('.custom-option-tapa .form-check-input'))
tapaOptionList.map(function (customOptionEL) {
// Update custom options check on page load
_this.updateTapaCheck(customOptionEL)
// Update custom options check on click
customOptionEL.addEventListener('click', e => {
_this.updateTapaCheck(customOptionEL)
})
})
}
function updateTapaCheck(el) {
if (el.checked) {
// If custom option element is radio, remove checked from the siblings (closest `.row`)
if (el.type === 'radio') {
const customRadioOptionList = [].slice.call(el.closest('.row').querySelectorAll('.custom-option-tapa'))
customRadioOptionList.map(function (customRadioOptionEL) {
customRadioOptionEL.closest('.custom-option-tapa').classList.remove('checked')
})
}
el.closest('.custom-option-tapa').classList.add('checked')
if (el.closest('.custom-option-tapa').id == 'tapaBlandaInnerDiv') {
$('#tapaBlanda').prop('checked', true);
$('#tapaDura').prop('checked', false);
}
else {
$('#tapaBlanda').prop('checked', false);
$('#tapaDura').prop('checked', true);
}
} else {
el.closest('.custom-option-tapa').classList.remove('checked')
}
}
function initColorCheck() {
const _this = this
const custopOptionList = [].slice.call(document.querySelectorAll('.custom-option-color .form-check-input'))
custopOptionList.map(function (customOptionEL) {
// Update custom options check on page load
_this.updateColorCheck(customOptionEL)
// Update custom options check on click
customOptionEL.addEventListener('click', e => {
_this.updateColorCheck(customOptionEL)
})
})
}
function updateColorCheck(el) {
if (el.checked) {
// If custom option element is radio, remove checked from the siblings (closest `.row`)
if (el.type === 'radio') {
const customRadioOptionList = [].slice.call(el.closest('.row-color').querySelectorAll('.custom-option-color'))
customRadioOptionList.map(function (customRadioOptionEL) {
customRadioOptionEL.closest('.custom-option-color').classList.remove('checked')
})
}
el.closest('.custom-option-color').classList.add('checked')
if (el.closest('.custom-option-color').id == 'colorNegroDiv') {
$('#colorNegro').prop('checked', true);
$('#colorNegroHq').prop('checked', false);
$('#colorColor').prop('checked', false);
$('#colorColorHq').prop('checked', false);
}
else if (el.closest('.custom-option-color').id == 'colorNegroHqDiv') {
$('#colorNegro').prop('checked', false);
$('#colorNegroHq').prop('checked', true);
$('#colorColor').prop('checked', false);
$('#colorColorHq').prop('checked', false);
}
else if (el.closest('.custom-option-color').id == 'colorColorDiv') {
$('#colorNegro').prop('checked', false);
$('#colorNegroHq').prop('checked', false);
$('#colorColor').prop('checked', true);
$('#colorColorHq').prop('checked', false);
}
else {
$('#colorNegro').prop('checked', false);
$('#colorNegroHq').prop('checked', false);
$('#colorColor').prop('checked', false);
$('#colorColorHq').prop('checked', true);
}
} else {
el.closest('.custom-option-color').classList.remove('checked')
}
}
$('#enableSobrecubierta').on('change', function () {
if ($(this).is(":checked")) {
$('.enable-sobrecubierta').show();
} else {
$('#gramajeSobrecubierta').val('').trigger('change');
$('#paperSobrecubierta').val('').trigger('change');
$('#acabadosSobrecubierta').val('').trigger('change');
$('#tamanioSolapasSobrecubierta').val();
$('.enable-sobrecubierta').hide();
}
});
function initDisenioLibro() {
initTapaCheck();
initColorCheck();
$('.elementos-libro').trigger('change');
$('.change-tipo-impresion').trigger('change');
$('#papelInterior').trigger('change');
$('#papelInterior').val(window.datosDisenioLibro.papel_interior);
$('#gramajeInterior').append($('<option>', {
value: window.datosDisenioLibro.gramaje_interior,
text: window.datosDisenioLibro.gramaje_interior
}));
$('#gramajeInterior').val(window.datosDisenioLibro.gramaje_interior);
$('#papelCubierta').val('').trigger('change');
$('#papelCubierta').val(window.datosDisenioLibro.papel_cubierta);
$('#gramajeCubierta').append($('<option>', {
value: window.datosDisenioLibro.gramaje_cubierta,
text: window.datosDisenioLibro.gramaje_cubierta
}));
$('#gramajeCubierta').val(window.datosDisenioLibro.gramaje_cubierta);
$('#papelSobrecubierta').val('').trigger('change');
$('#papelSobrecubierta').val(window.datosDisenioLibro.papel_sobrecubierta);
$('#gramajeSobrecubierta').append($('<option>', {
value: window.datosDisenioLibro.gramaje_sobrecubierta,
text: window.datosDisenioLibro.gramaje_sobrecubierta
}));
$('#gramajeSobrecubierta').val(window.datosDisenioLibro.gramaje_sobrecubierta);
$('#enableSobrecubierta').trigger('change');
}
$('.change-tipo-impresion').on('change', function () {
let isColor = false;
if($('#colorColorDiv').hasClass('checked') || $('#colorColorHqDiv').hasClass('checked'))
isColor = true;
let isHq = false;
if($('#colorNegroDiv').hasClass('checked') || $('#colorColorHqDiv').hasClass('checked'))
isHq = true;
//si es color hay que mostrar el numero de paginas a color
if (isColor) {
$('#pagColorDiv').show();
if($('#paginasColor').val() == '')
$('#paginasColor').val('0');
}
else {
$('#pagColorDiv').hide();
$('#paginasColor').val('0');
}
var data = [];
if (!isColor && !isHq) {
data = window.datosPresupuesto.papelInteriorNegro;
}
else if (!isColor && isHq) {
data = window.datosPresupuesto.papelInteriorNegroHq;
}
else if (isColor && !isHq) {
data = window.datosPresupuesto.papelInteriorColor;
}
else if (isColor && isHq) {
data = window.datosPresupuesto.papelInteriorColorHq;
}
var dropdown = $("#papelInterior");
dropdown.empty();
$.each(data, function () {
dropdown.append($("<option />").val(this.id).text(this.nombre));
});
//Se quita la seleccion del dropdown
dropdown.val('').trigger('change');
$('#gramajeInterior').val('').trigger('change');
});
$('#tirada').on('change', function () {
const valInterior = $('#gramajeInterior option:selected').val();
const valCubierta = $('#gramajeCubierta option:selected').val();
const valSobrecubierta = $('#gramajeSobrecubierta option:selected').val();
$('#papelInterior').trigger('change');
$('#papelCubierta').trigger('change');
$('#papelSobrecubierta').trigger('change');
});
$('#papelInterior').on('change', function () {
let isColor = false;
if($('#colorColorDiv').hasClass('checked') || $('#colorColorHqDiv').hasClass('checked'))
isColor = true;
let isHq = false;
if($('#colorNegroDiv').hasClass('checked') || $('#colorColorHqDiv').hasClass('checked'))
isHq = true;
if ($('#papelInterior option:selected').val() != undefined) {
var uso = 'bn';
if (!isColor && !isHq) {
uso = 'bn';
}
else if (!isColor && isHq) {
uso = 'bnhq';
}
else if (isColor && !isHq) {
uso = 'color';
}
else if (isColor && isHq) {
uso = 'colorhq';
}
datos = {
tirada: $('#tirada').val(),
merma: 0,
uso: uso,
papel: $('#papelInterior option:selected').text()
};
datos = Object.assign(datos, window.token_ajax)
const valInterior = $('#gramajeInterior option:selected').val();
$.ajax({
url: window.routes_disenio_libro.obtenerGramaje,
type: 'POST',
data: datos,
success: function (response) {
if(response.menu){
$('#gramajeInterior').empty();
$(response.menu).each(function (index, element) {
$('#gramajeInterior').append($("<option />").val(element.id).text(element.text));
});
}
if (valInterior != undefined && valInterior != '')
$('#gramajeInterior option[value=' + valInterior + ']').prop('selected', true).trigger('change');
else
$('#gramajeInterior').val('').trigger('change');
}
});
}
});
$('#papelCubierta').on('change', function () {
let isColor = true;
let isHq = true;
if ($('#papelCubierta option:selected').val() != undefined) {
var uso = 'cubierta';
datos = {
tirada: $('#tirada').val(),
merma: 0,
uso: uso,
papel: $('#papelCubierta option:selected').text().trim()
};
datos = Object.assign(datos, window.token_ajax)
const valCubierta = $('#gramajeCubierta option:selected').val();
$.ajax({
url: window.routes_disenio_libro.obtenerGramaje,
type: 'POST',
data: datos,
success: function (response) {
$('#gramajeCubierta').empty();
$(response.menu).each(function (index, element) {
$('#gramajeCubierta').append($("<option />").val(element.id).text(element.text));
});
if (valCubierta != undefined && valCubierta != '')
$('#gramajeCubierta option[value=' + valCubierta + ']').prop('selected', true).trigger('change');
else
$('#gramajeCubierta').val('').trigger('change');
}
});
}
});
$('#papelSobrecubierta').on('change', function () {
let isColor = true;
let isHq = true;
if ($('#papelSobrecubierta option:selected').val() != undefined) {
var uso = 'sobrecubierta';
datos = {
tirada: $('#tirada').val(),
merma: 0,
uso: uso,
papel: $('#papelSobrecubierta option:selected').text().trim()
};
datos = Object.assign(datos, window.token_ajax)
const valSobrecubierta = $('#gramajeSobrecubierta option:selected').val();
$.ajax({
url: window.routes_disenio_libro.obtenerGramaje,
type: 'POST',
data: datos,
success: function (response) {
$('#gramajeSobrecubierta').empty();
$(response.menu).each(function (index, element) {
$('#gramajeSobrecubierta').append($("<option />").val(element.id).text(element.text));
});
if (valSobrecubierta != undefined)
$('#gramajeSobrecubierta option[value=' + valSobrecubierta + ']').prop('selected', true).trigger('change');
else
$('#gramajeSobrecubierta').val('').trigger('change');
}
});
}
});
$('#solapasCubierta').on('change', function () {
if ($(this).is(":checked")) {
$('#tamanioSolapasCubierta').show();
} else {
$('#tamanioSolapasCubierta').hide();
}
});
// Funcion que comprueba que están rellenos todos los datos necesarios para calcular el presupuesto
function checkValues() {
const tirada = $('#tirada').val();
const paginas = $('#paginas').val();
const papelInterior = $('#papelInterior option:selected').val();
const gramajeInterior = $('#gramajeInterior option:selected').text();
const papelCubierta = $('#papelCubierta option:selected').val();
const gramajeCubierta = $('#gramajeCubierta option:selected').text();
const papelFormatoAlto = $('#papelFormatoAlto').val();
const papelFormatoAncho = $('#papelFormatoAncho').val();
const clienteId = $('#clienteId').val();
if (paginas == '' || isNaN(paginas) || parseInt(paginas) <= 0) {
return false;
}
if(parseInt(paginas)%2!=0){
$('#paginas').val(parseInt(paginas)+1).trigger('change');
return false;
}
if(clienteId == '' || isNaN(clienteId) || parseInt(clienteId) <= 0){
return false;
}
if (tirada == '' || isNaN(tirada) || parseInt(tirada) <= 0) {
return false;
}
if (papelInterior == '' || gramajeInterior == '') {
return false;
}
if (papelCubierta == '' || gramajeCubierta == '') {
return false;
}
if ($('#papelFormatoId').val() == null && !$('#papelFormatoPersonalizado').is(':checked')){
return false;
}
if($('#papelFormatoPersonalizado').is(':checked')){
if(papelFormatoAncho == '' || parseInt(papelFormatoAncho) <= 0 ||
papelFormatoAlto == '' || parseInt(papelFormatoAlto) <= 0){
return false;
}
}
return true;
}
function getTiradas() {
let tiradas = [];
tiradas.push(parseInt($('#tirada').val()));
if ($('#tirada2').val().length > 0 && parseInt($('#tirada2').val()) > 0)
tiradas.push(parseInt($('#tirada2').val()));
if ($('#tirada3').val().length > 0 && parseInt($('#tirada3').val()) > 0)
tiradas.push(parseInt($('#tirada3').val()));
if ($('#tirada4').val().length > 0 && parseInt($('#tirada4').val()) > 0)
tiradas.push(parseInt($('#tirada4').val()));
return tiradas;
}
function getDimensionLibro() {
var ancho = 0;
var alto = 0;
if ($('#papelFormatoId option:selected').length > 0) {
var selectedText = $('#papelFormatoId option:selected').text();
if (selectedText.length > 0) {
ancho = parseFloat(selectedText.trim().split(" x ")[0]);
alto = parseFloat(selectedText.trim().split(" x ")[1]);
}
else if (document.getElementById('papelFormatoPersonalizado').checked) {
ancho = parseFloat(document.getElementById('papelFormatoAncho').value);
alto = parseFloat(document.getElementById('papelFormatoAlto').value);
}
}
else if (document.getElementById('papelFormatoPersonalizado').checked) {
ancho = parseFloat(document.getElementById('papelFormatoAncho').value);
alto = parseFloat(document.getElementById('papelFormatoAlto').value);
}
return {
ancho: ancho,
alto: alto
}
}
$('#retractilado').on('change', function () {
if ($(this).is(':checked')) {
if ($('#retractilado5').is(':checked'))
$('#retractilado5').prop('checked', false);
}
});
$('#retractilado5').on('change', function () {
if ($(this).is(':checked')) {
if ($('#retractilado').is(':checked'))
$('#retractilado').prop('checked', false);
}
});
$('.elementos-libro').on('change', function () {
// Libro cosido
if ($('#cosidoDiv').hasClass('checked')) {
$('#tituloDisenioLibro').text("Rústica cosido");
if ($('#tapaBlandaInnerDiv').hasClass('checked')) {
// Cosido tapa blanda
$('.guardas').hide();
$('.solapas-cubierta').show();
$('.sobrecubierta').show();
$('#enableSobrecubierta').trigger('change');
}
else {
// Cosido tapa dura
$('.guardas').show();
numCarasGuardas(2);
$('.solapas-cubierta').hide();
$('.sobrecubierta').show();
$('#enableSobrecubierta').trigger('change');
}
}
// Libro fresado
else if ($('#fresadoDiv').hasClass('checked')) {
$('#tituloDisenioLibro').text("Rústica fresado");
if ($('#tapaBlandaInnerDiv').hasClass('checked')) {
// fresado tapa blanda
$('.guardas').hide();
$('.solapas-cubierta').show();
$('.sobrecubierta').show();
$('#enableSobrecubierta').trigger('change');
}
else {
// fresado tapa dura
$('.guardas').show();
numCarasGuardas(2);
$('.solapas-cubierta').hide();
$('.sobrecubierta').show();
$('#enableSobrecubierta').trigger('change');
}
}
// Libro grapado
else if ($('#grapadoDiv').hasClass('checked')) {
$('#tituloDisenioLibro').text("Cosido con grapas");
if ($('#tapaBlandaInnerDiv').hasClass('checked')) {
// grapado tapa blanda
$('.guardas').hide();
$('.solapas-cubierta').show();
$('.sobrecubierta').hide();
$('#enableSobrecubierta').prop('checked', false);
}
}
// Libro wire-o
else if ($('#wireoDiv').hasClass('checked')) {
$('#tituloDisenioLibro').text("Wire-O");
if ($('#tapaBlandaInnerDiv').hasClass('checked')) {
// wire-o tapa blanda
$('.guardas').hide();
$('.solapas-cubierta').show();
$('.sobrecubierta').hide();
$('#enableSobrecubierta').prop('checked', false);
}
else {
// wire-o tapa dura
$('.guardas').show();
numCarasGuardas(1);
$('.solapas-cubierta').hide();
$('.sobrecubierta').hide();
$('#enableSobrecubierta').prop('checked', false);
}
}
// Libro espiral
else if ($('#espiralDiv').hasClass('checked')) {
$('#tituloDisenioLibro').text("Espiral");
if ($('#tapaBlandaInnerDiv').hasClass('checked')) {
// espiral tapa blanda
$('.guardas').hide();
$('.solapas-cubierta').show();
$('.sobrecubierta').hide();
$('#enableSobrecubierta').prop('checked', false);
}
else {
// espiral tapa dura
$('.espiral').show();
numCarasGuardas(1);
$('.solapas-cubierta').hide();
$('.sobrecubierta').hide();
$('#enableSobrecubierta').prop('checked', false);
}
}
});
function numCarasGuardas(numCaras) {
if (numCaras == 1) {
$("#impresionGuardas option[value='8']").remove();
}
else {
if ($("#impresionGuardas option[value='8']").length == 0)
$("#impresionGuardas").append('<option value="8">' + window.Presupuestos.dosCaras + '</option>');
}
}
$('.calcular-presupuesto').on('change', function () {
// se obtiene el id del elemento que ha disparado el evento
if($(this).hasClass('input-sobrecubierta')){
if($('#papelSobrecubierta option:selected').val() == '' || $('#gramajeSobrecubierta option:selected').val() == ''){
return;
}
}
calcularPresupuesto();
});
function comprobarTiradasPOD(){
const tiradas = getTiradas();
//Comprobar que todos los elementos del array tiradas estan por encima de 30 o por debajo
const tiradasPOD = tiradas.every(tirada => tirada <= 30);
const tiradasNoPOD = tiradas.every(tirada => tirada > 30);
if (tiradasPOD == !tiradasNoPOD) {
return true;
}
return false;
}
$('#clienteId').on('select2:change', function () {
calcularPresupuesto();
});
async function calcularPresupuesto() {
let isColor = false;
if($('#colorColorDiv').hasClass('checked') || $('#colorColorHqDiv').hasClass('checked'))
isColor = true;
let isHq = false;
if($('#colorNegroHqDiv').hasClass('checked') || $('#colorColorHqDiv').hasClass('checked'))
isHq = true;
if(!comprobarTiradasPOD()){
$('#errorTiradas').show();
return;
}
$('#errorTiradas').hide();
// se obtiene la propiedad serv_id de los checkboxes seleccionados de la clase .servicio-extra
if (!checkValues()) {
return;
}
let servicios = [];
$('.servicio-extra:checked').each(function () {
servicios.push($(this).attr('serv_id'));
})
let datos = {
tamanio: getDimensionLibro(),
tirada: getTiradas(),
paginas: $('#paginas').val(),
paginasColor: $('#paginasColor').val(),
tipo: $('.custom-option-tipo.checked').attr('id').replace('Div', ''),
tapa: $('#tapaDura').is(':checked') ? 'dura' : 'blanda',
isColor: isColor ? 1 : 0,
isHq: isHq ? 1 : 0,
papelInterior: $('#papelInterior option:selected').val(),
papelInteriorNombre: $('#papelInterior option:selected').text().trim(),
gramajeInterior: $('#gramajeInterior option:selected').text(),
excluirRotativa: $('#excluirRotativa').is(':checked')? 1 : 0,
papelCubierta: $('#papelCubierta option:selected').val(),
papelCubiertaNombre: $('#papelCubierta option:selected').text().trim(),
gramajeCubierta: $('#gramajeCubierta option:selected').text(),
carasCubierta: $('#carasCubierta').val(),
acabadoCubierta: $('#acabadosCubierta').val(),
clienteId: $('#clienteId').val(),
servicios: servicios,
}
// Si es cosido, se añade el número de páginas del cuadernillo
if ($('#cosidoDiv').hasClass('checked')) {
datos.paginasCuadernillo = $('#paginasCuadernillo').val();
}
// Si hay solapas de cubierta
if ($('#solapasCubierta').is(':checked')) {
datos.solapasCubierta = $('#anchoSolapasCubierta').val()
}
// Si hay sobrecubierta
if ($('#enableSobrecubierta').is(':checked')) {
if($('#papelSobrecubierta option:selected').val()>0 && $('#gramajeSobrecubierta option:selected').val()>0){
datos.sobrecubierta = {
papel: $('#papelSobrecubierta option:selected').val(),
papel_nombre: $('#papelSobrecubierta option:selected').text().trim(),
gramaje: $('#gramajeSobrecubierta option:selected').text(),
acabado: $('#acabadosSobrecubierta').val()
}
datos.sobrecubierta.solapas = $('#anchoSolapasSobrecubierta').val()
}
}
if ($('#divGuardas').is(':visible')) {
datos.guardas = {
papel: $('#papelGuardas option:selected').val(),
papel_nombre: $('#papelGuardas option:selected').text().trim(),
gramaje: 170,
caras: $('#impresionGuardas option:selected').val()
}
}
datos = Object.assign(datos, window.token_ajax)
$('.divTiradasPrecio').empty();
$('#loader').show();
$.ajax({
url: window.routes_disenio_libro.presupuestoCliente,
type: 'POST',
data: datos,
success: function (response) {
error = false;
$('#errorGeneral').hide();
try{
if(response.errors.interior.length > 0){
$('#errorInterior').show();
error = true;
}
else
$('#errorInterior').hide();
if(response.errors.cubierta.length > 0){
$('#errorCubierta').show();
error = true;
}
else
$('#errorCubierta').hide();
if(response.errors.sobrecubierta.length > 0){
$('#errorSobrecubierta').show();
error = true;
}
else
$('#errorSobrecubierta').hide();
if(response.errors.guardas.length > 0){
$('#errorGuardas').show();
error = true;
}
else
$('#errorGuardas').hide();
if(response.errors.servicios.length > 0 || response.errors.serviciosDefecto.length > 0){
error = true;
$('#errorGeneral').show();
}
else{
$('#errorGeneral').hide();
}
}
catch(error){
}
//For debug only
//console.log(response);
$('#loader').hide();
$('.divTiradasPrecio').empty();
if(!error){
$('#lomo_cubierta').val(response.info.lomo_cubierta);
$('#precios').show();
if(response.tiradas){
for (i = 0; i < response.tiradas.length; i++) {
const total = (parseFloat(response.precio_u[i]) * parseInt(response.tiradas[i])).toFixed(2) ;
const label = "tiradaPrecio" + parseInt(i+1);
let html = '';
html += '<div id="' + label + '" peso="' +response.peso[i]+ '" class="list-group" >';
html += '<a href="javascript:void(0);" class="list-group-item list-group-item-action">';
html += '<div class="li-wrapper d-flex justify-content-start align-items-center" >';
html += '<div class="list-content">';
html += '<h7 id="ud_' + label + '" class="mb-1">' + (response.tiradas[i] + ' ud.') + '</h7>';
html += '<h6 id="tot_' + label + '" class="mb-1">' + ('Total: ' + total + '€') + '</h6>';
html += '<h7 id="pu_' + label + '" class="mb-1">' + (response.precio_u[i] + '€/ud') + '</h7>';
html += '</div>';
html += '</div>'
html += '</a>';
html += '</div>';
$('.divTiradasPrecio').append(html);
}
}
if($('#resumen-libro').hasClass('active')) {
initDirecciones();
initTiradasDirecciones();
generarResumen();
previewEsquemaCubierta(true);
}
}
},
error: function (error) {
$('#loader').hide();
$('.divTiradasPrecio').empty();
}
});
}

View File

@ -13,7 +13,15 @@
<div id="containerTiradasEnvios" class="row mb-3 justify-content-center">
</div>
<div class="row mb-3 justify-content-center">
<div class="row justify-content-center">
<div class="col-md-12 col-lg-4 px-4 py-2">
<input class="form-check-input" type="checkbox" id="recogerEnTaller" name="recoger_en_taller" value="1">
<label class="form-check-label"
for="recoger_en_taller"><?= lang('Presupuestos.recogerEnTaller') ?></label>
</div>
</div>
<div class="row mb-3 justify-content-center div-direcciones">
<div class="col-sm-4 mb-3">
<label for="direcciones" class="form-label">Mis direcciones</label>
@ -36,7 +44,7 @@
</div>
<div class="row mb-3 justify-content-center">
<div class="row mb-3 justify-content-center div-direcciones">
<div class="col-sm-4 mb-3">
<div class="form-check form-switch mb-2">
<input class="form-check-input" type="checkbox" id="entregaPieCalle" name="entregaPieCalle"
@ -47,16 +55,16 @@
</div>
</div>
<div class="row mb-3 justify-content-center">
<div class="row mb-3 justify-content-center div-direcciones">
<div class="col-sm-2 mb-3 mt-auto mb-0">
<button id="nuevaDireccion" type="button"
class="btn btn-secondary waves-effect waves-light">Nueva Dirección</button>
<button id="nuevaDireccion" type="button" class="btn btn-secondary waves-effect waves-light">Nueva
Dirección</button>
</div>
</div>
<div id="divErrorEnvios" name="div_error_envios" class="col-sm-10 mb-3 justify-content-center"></div>
<div id="divDirecciones" class="calcular-presupuesto col-sm-12 d-flex flex-column align-items-center">
<div id="divDirecciones" class="calcular-presupuesto col-sm-12 d-flex flex-column align-items-center div-direcciones">
</div>
</div>

View File

@ -171,46 +171,12 @@
<div class="row justify-content-center">
<div class="col-sm-3">
<label for="plastificado" class="form-label">
<?= lang('Presupuestos.plastificado') ?>
</label>
<select class="form-select select2bs2 calcular-presupuesto" id="plastificado" name="plastificado">
<option value="NONE"><?= lang('Presupuestos.sinPlastificar') ?></option>
<option value="BRIL"><?= lang('Presupuestos.brillo') ?></option>
<option value="MATE"><?= lang('Presupuestos.mate') ?></option>
<option value="ANTI"><?= lang('Presupuestos.antirrayado') ?></option>
<option value="SAND"><?= lang('Presupuestos.rugoso') ?></option>
</select>
</div>
<div class="col-sm-3">
<label for="barniz" class="form-label">
<?= lang('Presupuestos.barniz') ?>
</label>
<select class="form-select select2bs2 calcular-presupuesto" id="barniz" name="barniz">
<option value="NONE"> - </option>
<option value="R2D"><?= lang('Presupuestos.relieve2D') ?></option>
<option value="R3D"><?= lang('Presupuestos.relieve3D') ?></option>
</select>
<div class="form-text">
<?= lang('Presupuestos.barnizDescription') ?>
</div>
</div>
<div class="col-sm-3">
<label for="estampado" class="form-label">
<?= lang('Presupuestos.estampado') ?>
</label>
<select class="form-select select2bs2 calcular-presupuesto" id="estampado" name="estampado">
<option value="NONE"> - </option>
<option value="GOLD"><?= lang('Presupuestos.oro') ?></option>
<option value="SILV"><?= lang('Presupuestos.plata') ?></option>
<option value="COPP"><?= lang('Presupuestos.cobre') ?></option>
<option value="BRON"><?= lang('Presupuestos.bronce') ?></option>
<div class="col-sm-6">
<select class="form-select select2bs2 calcular-presupuesto" id="acabadoCubierta" name="acabado_cubierta">
</select>
</div>
<div id="retractilado"
class="calcular-presupuesto d-flex flex-column align-items-center justify-content-center solapas-cubierta imagen-selector image-container">
<img class="image-presupuesto" src="<?= site_url("assets/img/presupuestoCliente/retractilado.png") ?>"
@ -230,11 +196,11 @@
<h3 class="mb-1 fw-bold"> Extras </h3>
</div><!--//.mb-3 -->
<div class="row col-sm-12 mb-3 justify-content-center">
<div class="row col-sm-12 mb-3 justify-content-center align-items-top">
<div class="row justify-content-center">
<div class="row col-sm-3 mb-3 d-flex flex-column align-items-center sobrecubierta-items">
<div class="row col-sm-2 mb-3 d-flex flex-column align-items-center sobrecubierta-items">
<div class="form-check form-switch mb-2">
<input class="calcular-presupuesto form-check-input" type="checkbox" id="addSobrecubierta"
name="add_sobrecubierta" value="1">
@ -266,20 +232,14 @@
</div>
</div>
<div class="col-sm-3 config-sobrecubierta d-none sobrecubierta-items">
<div class="col-sm-4 config-sobrecubierta d-none sobrecubierta-items">
<label for="plastificadoSobrecubierta" class="form-label">
<?= lang('Presupuestos.plastificadoSobrecubierta') ?>
<?= lang('Presupuestos.acabado') ?>
</label>
<select class="form-select select2bs2 calcular-presupuesto" id="plastificadoSobrecubierta"
name="plastificado_sobrecubierta">
<option value="NONE">Sin plastificar </option>
<option value="BRIL"><?= lang('Presupuestos.brillo') ?></option>
<option value="MATE"><?= lang('Presupuestos.mate') ?></option>
<option value="ANTI"><?= lang('Presupuestos.antirrayado') ?></option>
<select class="form-select select2bs2 calcular-presupuesto" id="acabadoSobrecubierta"
name="acabado_sobrecubierta">
</select>
</div>
</div>
</div>
<div class="row col-sm-12 mb-0 justify-content-center d-none">

View File

@ -1,4 +1,4 @@
<div id="loader" class="modal modal-transparent" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
<div id="loader" class="modal modal-transparent" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" inert>
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-body">

View File

@ -1,356 +0,0 @@
/**
* Cliente presupuesto Wizard
*/
'use strict';
(function () {
// Init custom option check
//window.Helpers.initCustomOptionCheck();
// Vertical Wizard
// --------------------------------------------------------------------
const clientePresupuestoWizard = document.querySelector('#wizard-presupuesto-cliente');
if (typeof clientePresupuestoWizard !== undefined && clientePresupuestoWizard !== null ) {
// Wizard form
const clientePresupuestoWizardForm = clientePresupuestoWizard.querySelector('#presupuesto-cliente-form');
// Wizard steps
const clientePresupuestoWizardFormStep2 = clientePresupuestoWizardForm.querySelector('#tipo-libro');
const clientePresupuestoWizardFormStep3 = clientePresupuestoWizardForm.querySelector('#disenio-libro');
const clientePresupuestoWizardFormStep4 = clientePresupuestoWizardForm.querySelector('#direcciones-libro');
const clientePresupuestoWizardFormStep5 = clientePresupuestoWizardForm.querySelector('#resumen-libro');
// Wizard next prev button
const clientePresupuestoWizardNext = [].slice.call(clientePresupuestoWizardForm.querySelectorAll('.btn-next'));
const clientePresupuestoWizardPrev = [].slice.call(clientePresupuestoWizardForm.querySelectorAll('.btn-prev'));
let FormValidation2;
let FormValidation3;
let FormValidation4;
let FormValidation5;
let validationStepper = new Stepper(clientePresupuestoWizard, {
linear: true
});
if(clientePresupuestoWizardFormStep2 != null) {
// select2 (clienteId)
const clienteId = $('#clienteId');
clienteId.on('change.select2', function () {
// Revalidate the clienteId field when an option is chosen
FormValidation2.revalidateField('clienteId');
});
// Deal Details
FormValidation2 = FormValidation.formValidation(clientePresupuestoWizardFormStep2, {
fields: {
},
plugins: {
trigger: new FormValidation.plugins.Trigger(),
bootstrap5: new FormValidation.plugins.Bootstrap5({
// Use this for enabling/changing valid/invalid class
// eleInvalidClass: '',
eleValidClass: '',
rowSelector: '.col-sm-3'
}),
autoFocus: new FormValidation.plugins.AutoFocus(),
submitButton: new FormValidation.plugins.SubmitButton()
}
}).on('core.form.valid', function () {
// Jump to the next step when all fields in the current step are valid
validationStepper.next();
});
// Deal Usage
FormValidation3 = FormValidation.formValidation(clientePresupuestoWizardFormStep3, {
fields: {
titulo: {
validators: {
notEmpty: {
message: window.Presupuestos.validation.requerido_short
},
}
},
clienteId: {
validators: {
callback: {
message: window.Presupuestos.validation.cliente,
callback: function (input) {
// Get the selected options
const options = $("#clienteId").select2('data');
const hasValidOption = options.some(option => parseInt(option.id) > 0);
return options !== null && options.length > 0 && hasValidOption;
},
}
}
},
tirada: {
validators: {
callback: {
message: window.Presupuestos.validation.integer_greatherThan_0,
callback: function (input) {
const value = $("#tirada").val();
return value.length > 0 && Number.isInteger(parseInt(value)) && parseInt(value) > 0;
},
}
}
},
paginas: {
validators: {
callback: {
message: window.Presupuestos.validation.integer_greatherThan_0,
callback: function (input) {
const value = $("#paginas").val();
return value.length > 0 && Number.isInteger(parseInt(value)) && parseInt(value) > 0;
},
}
}
},
paginasColor: {
validators: {
callback: {
message: window.Presupuestos.validation.integer_greatherThan_0,
callback: function (input) {
if ($('#pagColorDiv').is(':hidden'))
return true;
else {
const value = $("#paginasColor").val();
return value.length > 0 && Number.isInteger(parseInt(value)) && parseInt(value) > 0;
}
},
}
}
},
gramajeInterior: {
validators: {
callback: {
callback: function (input) {
const value = $("#tirada").val();
if ($('#gramajeInterior option:selected').text().length == 0) {
if(value.length > 0 && Number.isInteger(parseInt(value)) && parseInt(value) > 0){
return {
valid: false,
message: window.Presupuestos.validation.sin_gramaje,
}
}
return {
valid: value.length > 0 && Number.isInteger(parseInt(value)) && parseInt(value) > 0,
message: window.Presupuestos.validation.tirada_no_valida,
}
}
return true;
},
},
}
},
gramajeCubierta: {
validators: {
callback: {
message: window.Presupuestos.validation.tirada_no_valida,
callback: function (input) {
const value = $("#tirada").val();
if ($('#gramajeCubierta option:selected').text().length == 0) {
return value.length > 0 && Number.isInteger(parseInt(value)) && parseInt(value) > 0;
}
return true;
},
},
callback: {
message: window.Presupuestos.validation.sin_gramaje,
callback: function (input) {
if ($('#gramajeCubierta option:selected').text().length == 0) {
return false;
}
return true;
},
}
}
},
gramajeSobrecubierta: {
validators: {
callback: {
message: window.Presupuestos.validation.tirada_no_valida,
callback: function (input) {
const value = $("#tirada").val();
if ($('#gramajeSobrecubierta option:selected').text().length == 0) {
return value.length > 0 && Number.isInteger(parseInt(value)) && parseInt(value) > 0;
}
return true;
},
}
}
},
},
plugins: {
trigger: new FormValidation.plugins.Trigger(),
bootstrap5: new FormValidation.plugins.Bootstrap5({
// Use this for enabling/changing valid/invalid class
// eleInvalidClass: '',
eleValidClass: '',
rowSelector: function (field, ele) {
// field is the field name
// ele is the field element
switch (field) {
case 'gramajeInterior':
case 'gramajeCubierta':
case 'gramajeSobrecubierta':
return '.col-sm-2';
case 'titulo':
return '.col-sm-12';
case 'clienteId':
return '.col-sm-6';
default:
return '.col-sm-3';
}
}
}),
autoFocus: new FormValidation.plugins.AutoFocus(),
submitButton: new FormValidation.plugins.SubmitButton()
}
}).on('core.form.valid', function () {
if($('#tiradaPrecio1').length > 0) {
validationStepper.next();
initDirecciones();
initTiradasDirecciones();
}
});
const tirada = $('#tirada');
tirada.on('change', function () {
// Revalidate the clienteId field when an option is chosen
FormValidation2.revalidateField('gramajeInterior');
FormValidation2.revalidateField('gramajeCubierta');
FormValidation2.revalidateField('gramajeSobrecubierta');
});
// Direcciones
FormValidation4 = FormValidation.formValidation(clientePresupuestoWizardFormStep4, {
fields: {
},
plugins: {
trigger: new FormValidation.plugins.Trigger(),
bootstrap5: new FormValidation.plugins.Bootstrap5({
// Use this for enabling/changing valid/invalid class
// eleInvalidClass: '',
eleValidClass: '',
rowSelector: '.col-md-12'
}),
autoFocus: new FormValidation.plugins.AutoFocus(),
submitButton: new FormValidation.plugins.SubmitButton()
}
}).on('core.form.valid', function () {
if(validarEnvio()){
generarResumen();
validationStepper.next();
}
else{
let text = "El número de unidades enviadas no coincie con la tirada seleccionada.";
if($('#prototipo').is(':checked')) {
text += "<br>(Tenga en cuenta que se ha seleccionado la opción de prototipo)";
}
$('#errorDirecciones').text(text);
$('#errorDirecciones').show();
}
});
}
// Deal Usage
FormValidation5 = FormValidation.formValidation(clientePresupuestoWizardFormStep5, {
fields: {
// * Validate the fields here based on your requirements
},
plugins: {
trigger: new FormValidation.plugins.Trigger(),
bootstrap5: new FormValidation.plugins.Bootstrap5({
// Use this for enabling/changing valid/invalid class
// eleInvalidClass: '',
eleValidClass: '',
rowSelector: '.col-md-12'
}),
autoFocus: new FormValidation.plugins.AutoFocus(),
submitButton: new FormValidation.plugins.SubmitButton()
}
}).on('core.form.valid', function () {
// You can submit the form
// clientePresupuestoWizardForm.submit()
// or send the form data to server via an Ajax request
// To make the demo simple, I just placed an alert
//alert('Submitted..!!');
});
clientePresupuestoWizardNext.forEach(item => {
item.addEventListener('click', event => {
// When click the Next button, we will validate the current step
switch (validationStepper._currentIndex) {
case 0:
FormValidation2.validate();
break;
case 1:
FormValidation3.validate();
break;
case 2:
FormValidation4.validate();
break;
case 3:
FormValidation5.validate();
break;
default:
validationStepper.next();
break;
}
});
});
clientePresupuestoWizardPrev.forEach(item => {
item.addEventListener('click', event => {
switch (validationStepper._currentIndex) {
case 4:
validationStepper.previous();
break;
case 3:
validationStepper.previous();
break;
case 2:
for (let i = 0; i < 4; i++) {
let id = "tiradaPrecio" + i;
if ($('#' + id).length > 0) {
$('#' + id).show();
}
}
validationStepper.previous();
break;
case 1:
validationStepper.previous();
break;
case 0:
window.location.href = document.location.origin + '/presupuestocliente/list';
default:
break;
}
});
});
var url = $(location).attr('href'); // Obtener URL actual
if (url.includes('/edit/')) { // Comprobar si la URL contiene 'edit'
validationStepper.to(4);
}
}
})();

View File

@ -1,311 +0,0 @@
function generarResumen(){
$('#tipoLibro').text($('#tituloDisenioLibro').text() + ' tapa ' + (($('#tapaBlandaInnerDiv').hasClass('checked'))?'blanda':'dura'));
$('#resumenTamanio').text('Dimensiones: ' + getDimensionLibro().ancho + 'x' + getDimensionLibro().alto + 'mm');
$('#resumenPaginas').text('Páginas: '+ $('#paginas').val() + ' páginas');
const seleccion = $('.custom-option-tiradasDirecciones.checked');
let tirada = 0;
if(seleccion.length != 0) {
const element_tirada =($(seleccion[0]).find('label input')[0]);
const number = element_tirada.id.match(/\d+$/);
if (number.length != 0) {
tirada = parseInt($('#tiradaDireccionesValue' + number[0]).text());
}
}
$('#resumenTirada').text('Tirada: '+ tirada + ' unidades');
$('#resumenPrototipo').text('Prototipo: ' + (($('#prototipo').is(':checked'))?'Sí':'No'));
$('#resumenFerro').text('Ferro: ' + (($('#ferro').is(':checked'))?'Sí':'No'));
$('#tipoImpresion').text('Impresión: ' +
($('#colorNegroDiv').hasClass('checked')?'Negro estándar':
$('#colorNegroHqDiv').hasClass('checked')?'Negro premium':
$('#colorColorDiv').hasClass('checked')?'Color estándar':'Color premium'));
if($('#colorNegroDiv').hasClass('checked') || $('#colorNegroHqDiv').hasClass('checked')){
$('#pResumenPaginasColor').hide();
}
else{
$('#pResumenPaginasColor').show();
$('#resumenPaginasColor').text($('#paginasColor').val());
}
$('#resumenPapelInterior').text($('#papelInterior option:selected').text().trim() + ' ' +
$('#gramajeInterior option:selected').text() + 'gr/m²');
let papelCubierta = $('#papelCubierta option:selected').text().trim() + ' ' +
$('#gramajeCubierta option:selected').text();
papelCubierta += 'gr/m²';
$('#resumenPapelCubierta').text(papelCubierta);
$('#resumenCarasCubierta').text('Impresión: ' + $('#carasCubierta option:selected').text())
$('#resumenAcabadoCubierta').text('Acabado: ' + $('#acabadosCubierta option:selected').text())
if ($('#solapasCubierta').is(':checked')) {
$('#resumenSolapasCubierta').text('Solapas: ' + $('#anchoSolapasCubierta').val())
}
else{
$('#resumenSolapasCubierta').text('Solapas: No')
}
if ($('#enableSobrecubierta').is(':checked')) {
$(".resumen-sobrecubierta").show();
$('#resumenPapelCubierta').text($('#papelSobrecubierta option:selected').text().trim() + ' ' +
$('#gramajeSobrecubierta option:selected').text() + 'gr/m²');
$('#resumenAcabadoSobrecubierta').text('Acabado: ' + $('#acabadosSobrecubierta option:selected').text())
$('#resumenSolapasSobrecubierta').text('Solapas: ' + $('#anchoSolapasSobrecubierta').val())
}
else{
$(".resumen-sobrecubierta").hide();
}
if ($('#divGuardas').css('display') != 'none') {
$(".resumen-guardas").show();
$('#resumenGuardasPapel').text($('#papelGuardas option:selected').text().trim() + ' ' + '170gr/m²');
$('#resumenGuardasCaras').text('Impresión: ' + $('#impresionGuardas option:selected').text())
}
else{
$(".resumen-guardas").hide();
}
if($('#retractilado').is(':checked') || $('#retractilado5').is(':checked') || $('#fajaColor').is(':checked')){
$('.resumen-extras').show();
$('#retractilado').is(':checked')?$('#resumenRetractilado1').show():$('#resumenRetractilado1').hide();
$('#retractilado5').is(':checked')?$('#resumenRetractilado5').show():$('#resumenRetractilado5').hide();
$('#fajaColor').is(':checked')?$('#resumenFajaColor').show():$('#resumenFajaColor').hide();
}
else{
$('.resumen-extras').hide();
}
for (i = 1; i <= 4; i++) {
let id = "tiradaPrecio" + i;
if ($('#' + id).length > 0) {
const envio = getTotalEnvio();
let tirada_id = "ud_tiradaPrecio" + i;
if(parseInt($('#' + tirada_id).text().replace(' ud.', '')) != tirada){
continue;
}
let total_id = "tot_tiradaPrecio" + i;
let total = parseFloat($('#' + total_id).text().replace('€', '').replace('Total: ', '')) + envio;
let total_iva = 0.0;
if($('#ivaReducido').val() == '1'){
total_iva = total * 1.04;
}
else{
total_iva = total * 1.21;
}
const precio_u = total_iva/tirada;
$('#resumenTotalIVA').text('Total (I.V.A. ' + (($('#ivaReducido').val() == '1')?'4':'21') + '%): ' + total_iva.toFixed(2) + '€');
$('#resumenPrecioU').text(precio_u.toFixed(4) + '€/ud');
}
}
}
function getTotalEnvio(){
const elements = $('#divDirecciones').find('.row.mb-3');
let total = 0.0;
if(elements.length > 0) {
for (let index=0; index<elements.length; index++){
let precio_envio = parseFloat($(elements[index]).attr('p'));
total += precio_envio;
};
}
return total;
}
$('#btnSave').on('click', function() {
finalizarPresupuesto(false);
});
$('#btnConfirm').on('click', function() {
finalizarPresupuesto(true);
});
$('#btnDuplicar').on('click', function() {
const paths = window.location.pathname.split("/").filter(path => path !== "");
let id=0;
if(paths.length > 0 && paths[paths.length - 2] == 'edit'){
id=paths[paths.length - 1];
}
datos = {
id: id,
}
datos = Object.assign(datos, window.token_ajax)
$('#loader').show();
$.ajax({
url: window.routes_resumen.duplicarPresupuesto,
type: 'POST',
data: datos,
success: function(response) {
if(Object.keys(response).length > 0) {
if(response.success){
$('#loader').hide();
window.location.href = document.location.origin + '/presupuestos/presupuestocliente/edit/' + response.id;
}
}
$('#loader').hide();
},
error: function() {
$('#loader').hide();
},
});
});
$('#btnBack').on('click', function() {
window.location.href = document.location.origin + '/presupuestocliente/list';
});
function finalizarPresupuesto(confirmar){
let isColor = false;
if($('#colorColorDiv').hasClass('checked') || $('#colorColorHqDiv').hasClass('checked'))
isColor = true;
let isHq = false;
if($('#colorNegroDiv').hasClass('checked') || $('#colorColorHqDiv').hasClass('checked'))
isHq = true;
const paths = window.location.pathname.split("/").filter(path => path !== "");
let id=0;
if(paths.length > 0 && paths[paths.length - 2] == 'edit'){
id=paths[paths.length - 1];
}
let servicios = [];
$('.servicio-extra:checked').each(function () {
servicios.push($(this).attr('serv_id'));
})
let datos_libro = {
tamanio: getDimensionLibro(),
tirada: getTiradas(),
paginas: $('#paginas').val(),
paginasColor: $('#paginasColor').val(),
tipo: $('.custom-option-tipo.checked').attr('id').replace('Div', ''),
tapa: $('#tapaDura').is(':checked') ? 'dura' : 'blanda',
isColor: isColor,
isHq: isHq,
papelInterior: $('#papelInterior option:selected').val(),
papelInteriorNombre: $('#papelInterior option:selected').text().trim(),
gramajeInterior: $('#gramajeInterior option:selected').text(),
excluirRotativa: $('#excluirRotativa').is(':checked')? 1 : 0,
papelCubierta: $('#papelCubierta option:selected').val(),
papelCubiertaNombre: $('#papelCubierta option:selected').text().trim(),
gramajeCubierta: $('#gramajeCubierta option:selected').text(),
carasCubierta: $('#carasCubierta').val(),
acabadoCubierta: $('#acabadosCubierta').val(),
clienteId: $('#clienteId').val(),
servicios: servicios,
};
// Si es cosido, se añade el número de páginas del cuadernillo
if ($('#cosidoDiv').hasClass('checked')) {
datos_libro.paginasCuadernillo = $('#paginasCuadernillo').val();
}
// Si hay solapas de cubierta
if ($('#solapasCubierta').is(':checked')) {
datos_libro.solapasCubierta = $('#anchoSolapasCubierta').val()
}
// Si hay sobrecubierta
if ($('#enableSobrecubierta').is(':checked')) {
if($('#papelSobrecubierta option:selected').val()>0 && $('#gramajeSobrecubierta option:selected').val()>0){
datos_libro.sobrecubierta = {
papel: $('#papelSobrecubierta option:selected').val(),
papel_nombre: $('#papelSobrecubierta option:selected').text().trim(),
gramaje: $('#gramajeSobrecubierta option:selected').text(),
acabado: $('#acabadosSobrecubierta').val()
}
datos_libro.sobrecubierta.solapas = $('#anchoSolapasSobrecubierta').val()
}
}
if ($('#divGuardas').css('display') != 'none') {
datos_libro.guardas = {
papel: $('#papelGuardas option:selected').val(),
papel_nombre: $('#papelGuardas option:selected').text().trim(),
gramaje: 170,
caras: $('#impresionGuardas option:selected').val()
}
}
let datos_cabecera = {
titulo: $('#titulo').val(),
referenciaCliente: $('#referenciaCliente').val(),
}
const seleccion = $('.custom-option-tiradasDirecciones.checked');
let tirada = 0;
let peso_libro = 0;
if(seleccion.length != 0) {
const element_tirada =($(seleccion[0]).find('label input')[0]);
const number = element_tirada.id.match(/\d+$/);
if (number.length != 0) {
tirada = parseInt($('#tiradaDireccionesValue' + number[0]).text());
peso_libro = ($(seleccion[0])).find('label input').attr('peso');
}
}
let direcciones = getDireccionesEnvio();
datos = {
id: id,
datos_libro : datos_libro,
datos_cabecera: datos_cabecera,
direcciones: direcciones,
tirada: tirada,
peso: peso_libro,
iva_reducido: $('#ivaReducido').val()==1?1:0,
confirmar: confirmar?1:0,
},
datos = Object.assign(datos, window.token_ajax)
$('#loader').show();
$.ajax({
url: window.routes_resumen.guardarPresupuesto,
type: 'POST',
data: datos,
success: function(response) {
if(Object.keys(response).length > 0) {
if(response.status > 0){
if(confirmar || window.location.href.includes("add"))
window.location.href = response.url + '/' + response.status;
}
}
$('#loader').hide();
},
error: function() {
$('#loader').hide();
},
});
}

View File

@ -1,58 +0,0 @@
// Init custom option check
function initTipoLibroCheck()
{
const _this = this
const custopOptionList = [].slice.call(document.querySelectorAll('.custom-option-tipo .form-check-input'))
custopOptionList.map(function (customOptionEL) {
// Update custom options check on page load
_this.updateTipoLibroCheck(customOptionEL)
// Update custom options check on click
customOptionEL.addEventListener('click', e => {
_this.updateTipoLibroCheck(customOptionEL)
})
})
}
function updateTipoLibroCheck(el)
{
if (el.checked) {
// If custom option element is radio, remove checked from the siblings (closest `.row`)
if (el.type === 'radio') {
const customRadioOptionList = [].slice.call(el.closest('.tipo_libro').querySelectorAll('.custom-option-tipo'))
customRadioOptionList.map(function (customRadioOptionEL) {
customRadioOptionEL.closest('.custom-option-tipo').classList.remove('checked')
})
}
el.closest('.custom-option-tipo').classList.add('checked')
if(el.closest('.custom-option-tipo').id == 'grapadoDiv') {
$('#tapaDuraDiv').hide();
$('#tapaBlanda').prop('checked', true);
}
else {
$('#tapaDuraDiv').show();
}
if(el.closest('.custom-option-tipo').id == 'cosidoDiv') {
$('#div_pagCuadernillo').show();
}
else {
$('#div_pagCuadernillo').hide();
}
} else {
el.closest('.custom-option-tipo').classList.remove('checked')
}
}
initTipoLibroCheck();
function getUpdatePapelInterior() {
var impresionInterior = $('input[name="impresionInterior"]:checked').val();
if(impresionInterior == 'color') {
$('#colorInteriorDiv').show();
}
else {
$('#colorInteriorDiv').hide();
}
}

View File

@ -1,5 +1,6 @@
<?= $this->include('themes/_commonPartialsBs/datatables') ?>
<?=$this->include('themes/_commonPartialsBs/datatables') ?>
<?= $this->extend('themes/vuexy/main/defaultlayout') ?>
<?= $this->section('content'); ?>
<div class="row">
<div class="col-md-12">
@ -16,36 +17,16 @@
style="width: 100%;">
<thead>
<tr>
<th>ID</th>
<th><?= lang('Users.firstName') ?></th>
<th><?= lang('Users.lastName') ?></th>
<th><?= lang('Users.email') ?></th>
<th><?= lang('Users.lastAccess') ?></th>
<th class="text-nowrap"><?= lang('Basic.global.Action') ?></th>
<th><?= lang('Users.cliente') ?></th>
<th class="noFilter"><?= lang('Users.lastAccess') ?></th>
<th class="noFilter text-nowrap"><?= lang('Basic.global.Action') ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($userList2 as $item) : ?>
<tr>
<td class="align-middle">
<?= empty($item->first_name) || strlen($item->first_name) < 51 ? esc($item->first_name) : character_limiter(esc($item->first_name), 50) ?>
</td>
<td class="align-middle">
<?= empty($item->last_name) || strlen($item->last_name) < 51 ? esc($item->last_name) : character_limiter(esc($item->last_name), 50) ?>
</td>
<td class="align-middle">
<?= empty(auth()->getProvider()->findById($item->id)->email) ? "" : character_limiter(esc(auth()->getProvider()->findById($item->id)->email), 50) ?>
</td>
<td class="align-middle text-nowrap">
<?= empty($item->last_active) ? '' : date('d/m/Y H:m:s', strtotime($item->last_active)) ?>
</td>
<td class="align-middle text-center text-nowrap">
<?= anchor(route_to('editUser', $item->id), "<i class='ti ti-pencil ti-sm mx-2'></i>", ['class' => 'text-body', 'data-id' => $item->id,]); ?>
<?= anchor('#confirm2delete', "<i class='ti ti-trash ti-sm mx-2'></i>", ['class' => 'text-body', 'data-href' => route_to('deleteUser', $item->id), 'data-bs-toggle' => 'modal', 'data-bs-target' => '#confirm2delete']); ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div><!--//.card-body -->
@ -56,4 +37,24 @@
</div><!--//.col -->
</div><!--//.row -->
<?= $this->endSection() ?>
<?= $this->endSection() ?>
<?=$this->section('css') ?>
<link rel="stylesheet" href="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/buttons/buttons.bootstrap5.min.css") ?>">
<?=$this->endSection() ?>
<?= $this->section('additionalExternalJs') ?>
<script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/buttons/dataTables.buttons.min.js") ?>"></script>
<script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/buttons/buttons.bootstrap5.min.js") ?>"></script>
<script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/buttons/buttons.html5.min.js") ?>"></script>
<script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/buttons/buttons.print.min.js") ?>"></script>
<script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/jszip/jszip.min.js") ?>"></script>
<script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/pdfmake/pdfmake.min.js") ?>" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/pdfmake/vfs_fonts.js") ?>"></script>
<script type="module" src="<?= site_url('assets/js/safekat/pages/users/list.js') ?>"></script>
<?=$this->endSection() ?>

View File

@ -7,6 +7,8 @@ class Alert {
this.icon = this.item.find(".icon-alert")
this.iconSuccess = "ti-circle-check"
this.iconError = "ti-exclamation-mark"
this.iconInfo = "ti-question-mark"
@ -14,6 +16,7 @@ class Alert {
setIcon(iconClass){
this.icon.removeClass(this.iconSuccess)
this.icon.removeClass(this.iconError)
this.icon.removeClass(this.iconInfo)
this.icon.addClass(iconClass)
}
setAsError() {
@ -24,16 +27,25 @@ class Alert {
}
setAsSuccess() {
this.item.removeClass("alert-danger")
this.item.removeClass("alert-warning")
this.item.removeClass("alert-info")
this.item.addClass("alert-success")
this.setIcon(this.iconSuccess)
}
setAsWarning() {
this.item.removeClass("alert-success")
this.item.removeClass("alert-danger")
this.item.removeClass("alert-info")
this.item.addClass("alert-warning")
this.setIcon(this.iconError)
}
setAsInfo() {
this.item.removeClass("alert-*")
this.item.removeClass("alert-success")
this.item.removeClass("alert-danger")
this.item.addClass("alert-warning")
this.item.addClass("alert-info")
this.setIcon(this.iconInfo)
}
show() {
this.item.removeClass("d-none")
@ -48,6 +60,16 @@ class Alert {
this.body.append(content)
}
setErrors() { }
reset(){
this.item.removeClass("alert-success")
this.item.removeClass("alert-danger")
this.item.removeClass("alert-warning")
this.item.removeClass("alert-info")
this.item.setContent("")
this.item.setHeadingTitle("")
this.item.hide()
}
}
export default Alert;

View File

@ -7,8 +7,10 @@ class ModalYesNo {
this.btnCancelId = alias !== "" ? `btnCancelModal-${alias}` : 'btnCancelModal';
this.btnConfirmId = alias !== "" ? `btnYesModal-${alias}` : 'btnYesModal';
this.callback = () => {};
this.modalHtml = `
<div class="modal fade" id="${this.modalId}" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="${this.modalId}Label" aria-hidden="true">
<div class="modal modalYesNo fade" id="${this.modalId}" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="${this.modalId}Label" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
@ -30,13 +32,22 @@ class ModalYesNo {
init() {
const self = this;
// Insertar el modal en el body del documento si no existe
if (!document.getElementById(this.modalId)) {
document.body.insertAdjacentHTML('beforeend', this.modalHtml);
}
document.getElementById(this.btnCancelId).addEventListener('click', () => {
const modal = new bootstrap.Modal(document.getElementById(this.modalId));
modal.hide();
$('#' + this.btnCancelId).on('click', () => {
$('#' + self.modalId).modal('hide');
});
$('#' + this.btnConfirmId).on('click', () => {
self.callback(); // Llamar al callback que el usuario haya proporcionado
$('#' + self.modalId).modal('hide');
});
}
@ -47,21 +58,15 @@ class ModalYesNo {
// Método para mostrar el modal
show(callback) {
// Mostrar el modal usando Bootstrap
const modal = new bootstrap.Modal(document.getElementById(this.modalId));
modal.show();
this.callback = callback;
// Configurar el evento de confirmación de eliminación
document.getElementById(this.btnConfirmId).addEventListener('click', () => {
callback(); // Llamar al callback que el usuario haya proporcionado
modal.hide(); // Cerrar el modal
});
// Mostrar el modal usando Bootstrap
$('#' + this.modalId).modal('show');
}
// Método para ocultar el modal si es necesario
hide() {
const modal = new bootstrap.Modal(document.getElementById(this.modalId));
modal.hide();
$('#' + this.modalId).modal('hide');
}
}

View File

@ -0,0 +1,85 @@
import Ajax from "../ajax.js";
import Modal from "../modal.js"
import ClassSelect from "../select2.js";
import Alert from "../alerts/alert.js";
class ModalDirectMessageClient {
constructor(model="presupuesto",domItem = null) {
this.item = domItem
this.modal = new Modal(domItem)
this.alert = new Alert(this.item.find("#alertDirectMessage"))
this.modelId = this.item.data("id");
this.selectItem = this.item.find("#select-clients")
this.model = model
this.selectClientUser = new ClassSelect(this.selectItem,`/chat/direct/client/users/select/${this.model}/${this.modelId}`,"Seleccione contacto",true)
this.messageInput = this.item.find("#new-direct-message-cliente-text")
this.title = this.item.find("#new-direct-message-cliente-title")
this.btnSubmitMessage = this.item.find("#submit-new-direct-message-client")
}
init() {
this.selectClientUser.init()
this.modal.item.on("hidden.bs.modal",this.reset_close.bind(this))
this.modal.item.on("shown.bs.modal",this.reset_show.bind(this))
this.btnSubmitMessage.on("click",this._handleStoreChatDirectMessage.bind(this))
}
reset(){
this.messageInput.val("")
this.title.val("")
this.selectClientUser.reset();
}
reset_close(){
this.messageInput.val("")
this.title.val("")
this.selectClientUser.reset();
this.alert.hide()
this.alert.setHeadingTitle("")
this.alert.setContent("")
this.alert.setAsSuccess()
}
reset_show(){
this.messageInput.val("")
this.title.val("")
this.selectClientUser.reset();
this.alert.hide()
this.alert.setHeadingTitle("")
this.alert.setContent("")
this.alert.setAsSuccess()
}
_handleStoreChatDirectMessage() {
const data = { "message": this.messageInput.val(), "title": this.title.val() , "users" : this.selectClientUser.getVal() }
if (data.message) {
const ajax = new Ajax(
`/messages/direct`,
data,
null,
this._handleStoreNewDirectMessageSuccess.bind(this),
this._handleStoreNewDirectMessageError.bind(this)
)
ajax.post()
}else{
this.alert.show()
this.alert.setAsWarning()
this.alert.setHeadingTitle("Tienes que añadir un mensaje")
}
}
_handleStoreNewDirectMessageSuccess(response) {
try {
this.alert.setAsSuccess()
this.alert.setHeadingTitle(response.message)
this.alert.setContent(response.message)
this.alert.show()
} catch (error) {
} finally {
this.reset()
}
}
_handleStoreNewDirectMessageError(error){
this.alert.setHeadingTitle(error.message)
this.alert.setAsError()
this.alert.setContent(JSON.stringify(error.errors))
this.alert.show()
}
}
export default ModalDirectMessageClient

View File

@ -93,7 +93,7 @@ let Table = function (
autoWidth: true,
responsive: true,
scrollX: true,
stateSave: true,
stateSave: false,
lengthMenu: [5, 10, 25, 50, 75, 100, 250, 500, 1000, 2500],
order: order,
orderCellsTop: true,

View File

@ -4,7 +4,7 @@ class tarjetaDireccion {
this.container = container;
this.id = id;
this.direccionId = direccion.direccionId;
this.direccionId = direccion.id;
this.card = this.#generateHTML(id, direccion);
this.deleteBtn = this.card.find('.direccion-eliminar');
this.editBtn = this.card.find('.direccion-editar');

View File

@ -1,5 +1,6 @@
import Chat from '../components/chat.js'
import InternalMessages from "../components/internalMessagesSection.js"
import ModalDirectMessageClient from '../components/modals/modalDirectMessageClient.js'
$(document).ready(() => {
let chat = new Chat($("#chat-factura"))
@ -9,5 +10,9 @@ $(document).ready(() => {
let internalMessages = new InternalMessages($("#internal_messages_chat"))
internalMessages.init()
}
let modalDirectMessageClient = new ModalDirectMessageClient("factura", $("#modalNewDirectMessageClient"))
modalDirectMessageClient.init()
$("#direct-message-cliente").on("click",() => {
modalDirectMessageClient.modal.show()
})
})

View File

@ -1,5 +1,6 @@
import Chat from '../components/chat.js'
import InternalMessages from "../components/internalMessagesSection.js"
import ModalDirectMessageClient from '../components/modals/modalDirectMessageClient.js'
$(document).ready(() => {
let chat = new Chat($("#chat-pedido"))
@ -9,5 +10,10 @@ $(document).ready(() => {
let internalMessages = new InternalMessages($("#internal_messages_chat"))
internalMessages.init()
}
let modalDirectMessageClient = new ModalDirectMessageClient("pedido", $("#modalNewDirectMessageClient"))
modalDirectMessageClient.init()
$("#direct-message-cliente").on("click",() => {
modalDirectMessageClient.modal.show()
})
})

View File

@ -1,13 +1,18 @@
import Chat from '../components/chat.js'
import InternalMessages from "../components/internalMessagesSection.js"
$(document).ready(() => {
import ModalDirectMessageClient from '../components/modals/modalDirectMessageClient.js'
$(function () {
let chat = new Chat($("#chat-presupuesto"))
chat.init()
chat.initPresupuesto()
if($("#internal_messages_chat").length > 0){
let internalMessages = new InternalMessages($("#internal_messages_chat"))
internalMessages.init()
if ($("#internal_messages_chat").length > 0) {
let internalMessages = new InternalMessages($("#internal_messages_chat"))
internalMessages.init()
let modalDirectMessageClient = new ModalDirectMessageClient("presupuesto", $("#modalNewDirectMessageClient"))
modalDirectMessageClient.init()
$("#direct-message-cliente").on("click",() => {
modalDirectMessageClient.modal.show()
})
}
})

View File

@ -1,5 +1,7 @@
import ClassSelect from '../../components/select2.js';
import tarifasClienteView from './tarifasCliente.js';
import ClienteUsuarios from './clienteUsuarios.js';
import Ajax from '../../components/ajax.js';
class Cliente {
@ -15,6 +17,8 @@ class Cliente {
this.provincia = new ClassSelect($("#provinciaId"), '/provincias/menuitems2', "Seleccione una provincia", {[this.csrf_token]: this.csrf_hash});
this.comunidadAutonoma = new ClassSelect($("#comunidadAutonomaId"), '/comunidades-autonomas/menuitems2', "Seleccione una comunidad autónoma", {[this.csrf_token]: this.csrf_hash});
this.clienteUsuarios = new ClienteUsuarios($('#usuarios'));
}
init() {
@ -32,6 +36,7 @@ class Cliente {
this.comunidadAutonoma.init();
this.tarifas.init();
this.clienteUsuarios.init();
$(document).keypress(function (e) {
var key = e.which;

View File

@ -0,0 +1,162 @@
import Table from '../../components/table.js';
import ConfirmDeleteModal from '../../components/ConfirmDeleteModal.js';
import Ajax from '../../components/ajax.js';
import { getToken } from '../../common/common.js';
class ClienteList {
constructor() {
this.domItem = $('.card-body');
this.csrf_token = getToken();
this.csrf_hash = $('#mainContainer').find('input[name="' + this.csrf_token + '"]').val();
this.tableClientes = null;
this.deleteModal = null;
}
init() {
const self = this;
this.headerSearcher();
this.deleteModal = new ConfirmDeleteModal('plantillasTarifasCliente');
this.deleteModal.init();
this.#initTable();
// Editar en linea la fila
this.tableClientes.table.on('click', '.btn-edit-' + this.tableClientes.getAlias(), function (e) {
const dataId = $(this).attr('data-id');
if (!Number.isNaN(Number(dataId))) {
window.location.href = '/clientes/cliente/edit/' + dataId;
}
});
// Eliminar la fila
this.tableClientes.table.on('click', '.btn-delete-' + this.tableClientes.getAlias(), function (e) {
const row = $(this).closest('tr')[0]._DT_RowIndex;
const dataId = $(this).attr('data-id');
self.deleteModal.setData($(this).attr('data-id'));
self.deleteModal.show(() => {
if (!Number.isNaN(Number(self.deleteModal.getData()))) {
new Ajax(
'/clientes/cliente/delete/' + dataId,
{
},
{},
(data, textStatus, jqXHR) => {
self.tableClientes.table.clearPipeline();
self.tableClientes.table.row($(row)).invalidate().draw();
popSuccessAlert(data.msg ?? jqXHR.statusText);
},
(error) => {
console.log(error);
}
).get();
self.deleteModal.hide();
}
});
});
}
#initTable() {
const self = this;
const columns = [
{ 'data': 'id' },
{ 'data': 'nombre' },
{ 'data': 'alias' },
{ 'data': 'cif' },
{ 'data': 'email' },
{ 'data': 'comercial' },
{ 'data': 'forma_pago_id' },
{ 'data': 'vencimiento' },
];
const actions = ['edit', 'delete'];
this.tableClientes = new Table(
$('#tableOfClientes'),
'clienteList',
'/clientes/cliente/datatable',
columns,
[]
);
this.tableClientes.init({
actions: actions,
colVisibility: true,
buttonsExport: true,
});
this.tableClientes.table.on('init.dt', function () {
self.tableClientes.table.page.len(50).draw();
});
}
headerSearcher() {
const self = this;
$('#tableOfClientes thead tr').clone(false).appendTo('#tableOfClientes thead');
$('#tableOfClientes thead tr:eq(1) th').each(function (i) {
if (!$(this).hasClass("noFilter")) {
let min_width = 100;
if(i == 0){
min_width = 50;
}
$(this).html(`<input type="text" class="form-control " style="min-width:${min_width}px;max-width:500px;font-size:0.8rem !important;" />`);
$('input', this).on('change clear', function () {
if (self.tableClientes.table.column(i).search() !== this.value) {
self.tableClientes.table
.column(i)
.search(this.value)
.draw();
}
});
}
else {
$(this).html('<span></span>');
}
});
}
}
document.addEventListener('DOMContentLoaded', function () {
const locale = document.querySelector('meta[name="locale"]').getAttribute('content');
new Ajax('/translate/getTranslation', { locale: locale, translationFile: ['Clientes', 'FormasPago', 'Users'] }, {},
function (translations) {
window.language = JSON.parse(translations);
new ClienteList().init();
},
function (error) {
console.log("Error getting translations:", error);
}
).post();
});

View File

@ -0,0 +1,115 @@
import Table from '../../components/table.js';
import ConfirmDeleteModal from '../../components/ConfirmDeleteModal.js';
import Ajax from '../../components/ajax.js';
import ClassSelect from '../../components/select2.js';
class ClienteUsuarios {
constructor(domItem) {
this.domItem = domItem;
this.table = null;
this.deleteModal = null;
this.usersSelect = new ClassSelect($('#usuariosDisponibles'), '/clienteusuarios/getusers', "");
this.userAdd = this.domItem.find('#addUserToClient');
this.clienteId = window.location.href.split("/").pop();
}
init() {
const self = this;
this.#initTable();
this.usersSelect.init();
this.deleteModal = new ConfirmDeleteModal('clienteUsuarios');
this.deleteModal.init();
// Eliminar la fila
this.table.table.on('click', '.btn-delete-' + this.table.getAlias(), function (e) {
const row = $(this).closest('tr')[0]._DT_RowIndex;
const dataId = $(this).attr('data-id');
self.deleteModal.setData($(this).attr('data-id'));
self.deleteModal.show(() => {
if (!Number.isNaN(Number(self.deleteModal.getData()))) {
new Ajax(
'/clienteusuarios/delete/' + dataId,
{
},
{},
(data, textStatus, jqXHR) => {
self.table.table.clearPipeline();
self.table.table.row($(row)).invalidate().draw();
popSuccessAlert(data.msg ?? jqXHR.statusText);
},
(error) => {
console.log(error);
}
).get();
self.deleteModal.hide();
}
});
});
this.userAdd.on('click', function (e) {
e.preventDefault();
const userId = self.usersSelect.getVal();
if (userId != "") {
new Ajax(
'/clienteusuarios/adduser',
{
cliente_id: self.clienteId,
user_id: userId,
},
{},
(data, textStatus, jqXHR) => {
self.table.table.clearPipeline();
self.table.table.draw();
popSuccessAlert(data.msg ?? jqXHR.statusText);
},
(error) => {
console.log(error);
}
).post();
}
});
}
#initTable() {
const columns = [
{ 'data': 'id' },
{ 'data': 'nombre' },
{ 'data': 'apellidos' },
{ 'data': 'email' },
];
const actions = ['delete'];
this.table = new Table(
$('#tableOfClienteUsuarios'),
'clienteUsuarios',
'/clienteusuarios/datatable',
columns,
[{ name: 'id_cliente', value: this.clienteId },]
);
this.table.init({
actions: actions,
colVisibility: false,
buttonsExport: false,
});
}
}
export default ClienteUsuarios;

View File

@ -49,7 +49,7 @@ class tarifasClienteView {
this.#initTable();
this.selectorPlantilla.init();
this.#getPlantillaPrecios();
this.convertToTemplateBtn.on('click', function () {
@ -188,15 +188,17 @@ class tarifasClienteView {
this.editorTarifas.editor.on('postEdit', function (e, json, data, action) {
self.#borrarPlantillaTarifa(self.clienteId);
self.selectorPlantilla.offChange();
self.selectorPlantilla.empty();
self.selectorPlantilla.setOption(0, 'Personalizado');
self.selectorPlantilla.onChange(self.#changePlantilla.bind(this));
self.selectorPlantilla.onChange(self.#changePlantilla.bind(self));
})
this.editorTarifas.editor.on('postCreate', function (e, json, data, action) {
self.#borrarPlantillaTarifa(self.clienteId);
self.selectorPlantilla.offChange();
self.selectorPlantilla.empty();
self.selectorPlantilla.setOption(0, 'Personalizado');
self.selectorPlantilla.onChange(self.#changePlantilla.bind(this));
self.selectorPlantilla.onChange(self.#changePlantilla.bind(self));
})
this.editorTarifas.editor.on('postCancel', function (e, json, data) {
@ -246,7 +248,9 @@ class tarifasClienteView {
},
{},
(data) => {
this.selectorPlantilla.offChange();
if (data !== null && typeof data === 'object') {
if (data.hasOwnProperty('id') && data.id != null)
this.selectorPlantilla.setOption(data.id, data.nombre);
else {
@ -254,6 +258,7 @@ class tarifasClienteView {
}
}
else {
this.selectorPlantilla.setOption(0, 'Personalizado');
}
this.selectorPlantilla.onChange(this.#changePlantilla.bind(this));
@ -268,6 +273,7 @@ class tarifasClienteView {
#changePlantilla() {
const self = this;
const data = $('#plantillas').select2('data');
if (data.length > 0) {
if (data[0].id == 0) {
@ -280,12 +286,14 @@ class tarifasClienteView {
const id = data[0].id;
if(id == 0)
id = -1;
new Ajax(
'/clienteprecios/changeplantilla',
{
'cliente_id': self.clienteId,
'plantilla_id': id,
[this.csrf_token]: this.csrf_hash
[self.csrf_token]: self.csrf_hash
},
{},
() => {

View File

@ -0,0 +1,185 @@
import Table from '../../components/table.js';
import ConfirmDeleteModal from '../../components/ConfirmDeleteModal.js';
import Ajax from '../../components/ajax.js';
import { getToken } from '../../common/common.js';
class MaquinasList {
constructor() {
this.domItem = $('.card-body');
this.csrf_token = getToken();
this.csrf_hash = $('#mainContainer').find('input[name="' + this.csrf_token + '"]').val();
this.tableMaquinas = null;
this.deleteModal = null;
}
init() {
const self = this;
this.headerSearcher();
this.deleteModal = new ConfirmDeleteModal('maquinas');
this.deleteModal.init();
this.#initTable();
// Editar en linea la fila
this.tableMaquinas.table.on('click', '.btn-edit-' + this.tableMaquinas.getAlias(), function (e) {
const dataId = $(this).attr('data-id');
if (!Number.isNaN(Number(dataId))) {
window.location.href = '/maquinas/edit/' + dataId;
}
});
// Eliminar la fila
this.tableMaquinas.table.on('click', '.btn-delete-' + this.tableMaquinas.getAlias(), function (e) {
const row = $(this).closest('tr')[0]._DT_RowIndex;
const dataId = $(this).attr('data-id');
self.deleteModal.setData($(this).attr('data-id'));
self.deleteModal.show(() => {
if (!Number.isNaN(Number(self.deleteModal.getData()))) {
new Ajax(
'/maquinas/delete/' + dataId,
{
},
{},
(data, textStatus, jqXHR) => {
self.tableMaquinas.table.clearPipeline();
self.tableMaquinas.table.row($(row)).invalidate().draw();
popSuccessAlert(data.msg ?? jqXHR.statusText);
},
(error) => {
console.log(error);
}
).get();
self.deleteModal.hide();
}
});
});
}
#initTable() {
const self = this;
const columns = [
{ 'data': 'id' },
{ 'data': 'nombre' },
{ 'data': 'tipo' },
{ 'data': 'ancho_impresion' },
{ 'data': 'alto_impresion' },
{ 'data': 'min' },
{ 'data': 'max' }
];
const actions = ['edit', 'delete'];
this.tableMaquinas = new Table(
$('#tableOfMaquinas'),
'maquinasList',
'/maquinas/datatable',
columns,
[]
);
this.tableMaquinas.init({
actions: actions,
colVisibility: false,
buttonsExport: true,
});
this.tableMaquinas.table.on('init.dt', function () {
self.tableMaquinas.table.page.len(50).draw();
});
}
headerSearcher() {
const self = this;
$('#tableOfMaquinas thead tr').clone(false).appendTo('#tableOfMaquinas thead');
$('#tableOfMaquinas thead tr:eq(1) th').each(function (i) {
if (!$(this).hasClass("noFilter")) {
let min_width = 100;
if (i == 0) {
min_width = 50;
}
if (i == 2) {
// Agregar un selector en la segunda columna
$(this).html('<select class="form-control" style="min-width:100px;max-width:120px;font-size:0.8rem !important;"></select>');
// Agregar opciones al selector
var selector = $('select', this);
selector.append('<option value="">Todos</option>'); // Opción vacía
selector.append('<option value="acabado">Acabado</option>');
selector.append('<option value="manipulado">Manupulado</option>');
selector.append('<option value="impresion">Impresión</option>');
selector.on('change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
self.tableMaquinas.table.column(i).search(val).draw();
});
}
else {
$(this).html(`<input type="text" class="form-control " style="min-width:${min_width}px;max-width:500px;font-size:0.8rem !important;" />`);
$('input', this).on('change clear', function () {
if (self.tableMaquinas.table.column(i).search() !== this.value) {
self.tableMaquinas.table
.column(i)
.search(this.value)
.draw();
}
});
}
}
else {
$(this).html('<span></span>');
}
});
}
}
document.addEventListener('DOMContentLoaded', function () {
const locale = document.querySelector('meta[name="locale"]').getAttribute('content');
new Ajax('/translate/getTranslation', { locale: locale, translationFile: ['Maquinas'] }, {},
function (translations) {
window.language = JSON.parse(translations);
new MaquinasList().init();
},
function (error) {
console.log("Error getting translations:", error);
}
).post();
});

View File

@ -23,6 +23,11 @@ class PlantillasTarifasClienteForm {
this.localEditor = null;
this.ajaxEditor = null;
this.rows = [];
this.rowsDeleted = [];
this.rowsEdited = [];
this.rowsCreated = [];
}
init() {
@ -42,6 +47,20 @@ class PlantillasTarifasClienteForm {
this.#initTable();
new Ajax(
'/clienteplantillaprecioslineas/getrows',
{
[this.csrf_token]: this.csrf_hash,
plantilla_id: this.plantillaId
},
{},
(response) => {
self.rows = response.data;
},
(error) => {
console.log(error);
}
).post();
// Editar en linea la fila
this.tablePlantilla.table.on('click', 'tbody span.edit', function (e) {
@ -62,10 +81,38 @@ class PlantillasTarifasClienteForm {
);
});
this.tablePlantilla.table.on('draw.dt', function (e) {
self.tablePlantilla.table.rows().every(function (rowIdx, tableLoop, rowLoop) {
var row = this.data();
if (self.rowsDeleted.includes(row.id)) {
$('#' + row.id).css('background-color', '#ffcccc');
$('#' + row.id).addClass('row-deleted');
$('#' + row.id).find('span.edit').addClass('d-none');
$('#' + row.id).find('.btn-delete-' + self.tablePlantilla.getAlias()).addClass('d-none');
}
else if (self.rowsEdited.includes(row.id)) {
$('#' + row.id).css('background-color', '#E9DEAC');
$('#' + row.id).addClass('row-edited');
}
else if (row.id === '') {
self.tablePlantilla.table.row(rowIdx).nodes().to$().addClass('row-created');
self.tablePlantilla.table.row(rowIdx).nodes().to$().css('background-color', '#C9E2C7');
}
});
});
this.tablePlantilla.table.on('click', '.btn-delete-' + this.tablePlantilla.getAlias(), function (e) {
self.tablePlantilla.table.settings()[0].oFeatures.bServerSide = false;
if ($(this).closest('tr').hasClass('row-created')) {
$(this).closest('tr').remove();
}
const row = $(this).attr('data-id');
self.btnApply.removeClass('d-none');
self.btnUndo.removeClass('d-none');
@ -76,6 +123,9 @@ class PlantillasTarifasClienteForm {
// find closest span.edit
$('#' + row).find('span.edit').addClass('d-none');
$('#' + row).find('.btn-delete-' + self.tablePlantilla.getAlias()).addClass('d-none');
if (self.rowsDeleted.indexOf(row) == -1)
self.rowsDeleted.push(row);
});
this.btnApply.on('click', function (e) {
@ -121,7 +171,7 @@ class PlantillasTarifasClienteForm {
{
name: "id",
type: "readonly",
def: new Date().toISOString().slice(0, 19).replace('T', ' ')
def: ''
}, {
name: "tipo",
type: "select",
@ -192,6 +242,10 @@ class PlantillasTarifasClienteForm {
const row = self.tablePlantilla.table.row('#' + json.data[0].id);
if (row.length) {
self.rowsCreated.push(row);
}
let rowNode = row.node();
$(rowNode).addClass('row-created');
@ -209,6 +263,9 @@ class PlantillasTarifasClienteForm {
let rowNode = row.node();
// Añadir una clase usando jQuery
if (!$(rowNode).hasClass('row-created')) {
$(rowNode).addClass('row-edited');
@ -234,6 +291,15 @@ class PlantillasTarifasClienteForm {
self.btnApply.removeClass('d-none');
self.btnUndo.removeClass('d-none');
// modificar la fila en rows que tenga el mismo id
let index = self.rows.findIndex(r => r.id == data.id);
if (index != -1) {
self.rows[index] = data;
}
if (self.rowsEdited.indexOf(row.id) == -1)
self.rowsEdited.push(row.id);
}
});
@ -251,12 +317,8 @@ class PlantillasTarifasClienteForm {
const self = this;
const deletedRows = self.tablePlantilla.table.rows('.row-deleted').data().toArray();
const editedRows = self.tablePlantilla.table.rows('.row-edited').data().toArray();
const createdRows = self.tablePlantilla.table.rows('.row-created').data().toArray();
if (editedRows.length != 0) {
let error = self.#checkInterval(editedRows);
if (this.rowsEdited.length != 0) {
let error = self.#checkInterval(self.rowsEdited);
if (error) {
if (error == 1) {
popErrorAlert('Hay filas EDITADAS con el tiempo mínimo mayor que el tiempo máximo');
@ -268,8 +330,8 @@ class PlantillasTarifasClienteForm {
}
}
if (createdRows.length != 0) {
let error = self.#checkInterval(editedRows);
if (this.rowsCreated.length != 0) {
let error = self.#checkInterval(self.rowsCreated.map(row => row.data()));
if (error) {
if (error == 1) {
popErrorAlert('Hay filas CREADAS con el tiempo mínimo mayor que el tiempo máximo');
@ -281,9 +343,9 @@ class PlantillasTarifasClienteForm {
}
}
if (deletedRows.length != 0) {
if (this.rowsDeleted.length != 0) {
let rowIds = deletedRows.map(row => '#' + row.id);
let rowIds = self.rowsDeleted.map(row => '#' + row);
// Iterar sobre cada fila y actualizar los campos necesarios
self.ajaxEditor.editor
@ -297,13 +359,15 @@ class PlantillasTarifasClienteForm {
if (editedRows.length != 0) {
if (this.rowsEdited.length != 0) {
let rowIds = editedRows.map(row => '#' + row.id);
let rowIds = this.rowsEdited.map(row => '#' + this.tablePlantilla.table.row(row).data().id);
let updatedFields = {};
// Iterar sobre las filas editadas y construir el objeto actualizado
editedRows.forEach(row => {
this.rowsEdited.forEach(row2Edit => {
const row = this.tablePlantilla.table.row(row2Edit).data();
updatedFields['tipo'] = updatedFields['tipo'] || {};
updatedFields['tipo'][row.id] = row.tipo;
@ -332,13 +396,13 @@ class PlantillasTarifasClienteForm {
}
if (createdRows.length != 0) {
if (this.rowsCreated.length != 0) {
let updatedFields = {};
let count = 0;
// Iterar sobre las filas editadas y construir el objeto actualizado
createdRows.forEach(row => {
this.rowsCreated.forEach(row => {
updatedFields['id'] = updatedFields['id'] || {};
updatedFields['id'][row.id] = count;
@ -370,48 +434,68 @@ class PlantillasTarifasClienteForm {
count++;
});
self.ajaxEditor.editor.create(createdRows.length, false).multiSet(updatedFields)
self.ajaxEditor.editor.create(self.rowsCreated.length, false).multiSet(updatedFields)
.submit()
}
if (deletedRows.length != 0 || editedRows.length != 0 || createdRows.length != 0) {
new Ajax(
'/clienteprecios/update',
{
[self.csrf_token]: self.csrf_hash,
plantilla_id: self.plantillaId
},
{},
() => {
window.location.reload();
},
(error) => {
console.log(error);
}
).post();
new Ajax(
'/clienteprecios/update',
{
[self.csrf_token]: self.csrf_hash,
plantilla_id: self.plantillaId
},
{},
() => {
self.tablePlantilla.table.settings()[0].oFeatures.bServerSide = true;
}
new Ajax(
'/clienteplantillaprecioslineas/getrows',
{
[self.csrf_token]: self.csrf_hash,
plantilla_id: self.plantillaId
},
{},
(response) => {
self.rows = response.data;
self.rowsDeleted = [];
self.rowsEdited = [];
self.rowsCreated = [];
self.tablePlantilla.table.clearPipeline();
self.tablePlantilla.table.draw(true);
},
(error) => {
console.log(error);
}).post();
},
(error) => {
console.log(error);
}
).post();
}
#checkInterval(rows) {
// obtener todas las filas de la tabla que no tengan la clase row-deleted
let rowsNotDeletedDT = this.tablePlantilla.table.rows(':not(.row-deleted)').nodes().toArray();
for (let row of rowsNotDeletedDT) {
let rowData = this.tablePlantilla.table.row(row).data();
for (let rowEdited of rows) {
if (rowEdited.tiempo_min > rowEdited.tiempo_max) {
for (let row of this.rows) {
let rowData = this.tablePlantilla.table.row(row).data();
for (let row2Check of rows) {
let checkRow = this.tablePlantilla.table.row(row2Check).data();
if (checkRow.tiempo_min > checkRow.tiempo_max) {
return 1;
}
if (rowData.tipo == rowEdited.tipo && rowData.tipo_maquina == rowEdited.tipo_maquina && rowData.tipo_impresion == rowEdited.tipo_impresion) {
if (checkRow.id == rowData.id) continue;
if (rowData.tipo == checkRow.tipo && rowData.tipo_maquina == checkRow.tipo_maquina && rowData.tipo_impresion == checkRow.tipo_impresion) {
// check overlapping intervals
if (rowEdited.tiempo_min >= rowData.tiempo_min || rowEdited.tiempo_min <= rowData.tiempo_max) {
if (Math.max(checkRow.tiempo_max, rowData.tiempo_max) - Math.min(checkRow.tiempo_min, rowData.tiempo_min)
<= Math.min(checkRow.tiempo_max - checkRow.tiempo_min) + Math.min(rowData.tiempo_max - rowData.tiempo_min))
return 2;
}
}
}
}
@ -518,12 +602,38 @@ class PlantillasTarifasClienteForm {
selector.append('<option value="sobrecubierta">Sobrecubierta</option>');
selector.on('change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
self.tablePlantilla.table.column(i).search(val).draw();
if (!self.tablePlantilla.table.settings()[0].oFeatures.bServerSide) {
var val = $(this).val(); // El valor seleccionado
var searchVal = "";
// Determinar el texto renderizado que debe buscarse
if (val === "interior") {
searchVal = window.language.ClientePrecios.interior;
} else if (val === "cubierta") {
searchVal = window.language.ClientePrecios.cubierta;
} else if (val === "sobrecubierta") {
searchVal = window.language.ClientePrecios.sobrecubierta;
}
const allRows = [...self.rows, ...self.rowsCreated.map(row => row.data())];
// Actualizar los datos de la tabla
self.tablePlantilla.table.clear().rows.add(allRows).draw();
// Aplicar el filtro sobre los valores renderizados
self.tablePlantilla.table.column(i).search(searchVal ? '^' + searchVal + '$' : '', true, false).draw();
}
else {
// Aplicar el filtro sobre los valores renderizados
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
self.tablePlantilla.table.column(i).search(val).draw();
}
});
}
else if (i == 2) {
@ -537,10 +647,35 @@ class PlantillasTarifasClienteForm {
selector.append('<option value="inkjet">Inkjet</option>');
selector.on('change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
self.tablePlantilla.table.column(i).search(val).draw();
if (!self.tablePlantilla.table.settings()[0].oFeatures.bServerSide) {
var val = $(this).val(); // El valor seleccionado
var searchVal = "";
// Determinar el texto renderizado que debe buscarse
if (val === "toner") {
searchVal = window.language.ClientePrecios.toner;
} else if (val === "inkjet") {
searchVal = window.language.ClientePrecios.inkjet;
}
const allRows = [...self.rows, ...self.rowsCreated.map(row => row.data())];
// Actualizar los datos de la tabla
self.tablePlantilla.table.clear().rows.add(allRows).draw();
// Aplicar el filtro sobre los valores renderizados
self.tablePlantilla.table.column(i).search(val).draw();
}
else {
// Aplicar el filtro sobre los valores renderizados
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
self.tablePlantilla.table.column(i).search(val).draw();
}
});
}
@ -557,17 +692,52 @@ class PlantillasTarifasClienteForm {
selector.append('<option value="colorhq">' + window.language.ClientePrecios.colorhq + '</option>');
selector.on('change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
self.tablePlantilla.table.column(i).search(val).draw();
if (!self.tablePlantilla.table.settings()[0].oFeatures.bServerSide) {
var val = $(this).val(); // El valor seleccionado
var searchVal = "";
// Determinar el texto renderizado que debe buscarse
if (val === "negro") {
searchVal = window.language.ClientePrecios.negro;
} else if (val === "negrohq") {
searchVal = window.language.ClientePrecios.negrohq;
} else if (val === "color") {
searchVal = window.language.ClientePrecios.color;
} else if (val === "colorhq") {
searchVal = window.language.ClientePrecios.colorhq;
}
const allRows = [...self.rows, ...self.rowsCreated.map(row => row.data())];
// Actualizar los datos de la tabla
self.tablePlantilla.table.clear().rows.add(allRows).draw();
self.tablePlantilla.table.column(i).search(searchVal ? '^' + searchVal + '$' : '', true, false).draw();
}
else {
// Aplicar el filtro sobre los valores renderizados
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
self.tablePlantilla.table.column(i).search(val).draw();
}
});
}
else {
$(this).html('<input type="text" class="form-control " style="min-width:100px;max-width:120px;font-size:0.8rem !important;" />');
$('input', this).on('change clear', function () {
if (self.tablePlantilla.table.column(i).search() !== this.value) {
if (!self.tablePlantilla.table.settings()[0].oFeatures.bServerSide) {
const allRows = [...self.rows, ...self.rowsCreated.map(row => row.data())];
// Actualizar los datos de la tabla
self.tablePlantilla.table.clear().rows.add(allRows).draw();
}
self.tablePlantilla.table
.column(i)
.search(this.value)

View File

@ -14,6 +14,8 @@ class Direcciones {
this.validatorStepper = validatorStepper;
this.allowNext = true;
this.recogidaTaller = this.domItem.find('#recogerEnTaller');
this.unidadesAdd = this.domItem.find('#unidadesEnvio');
this.btnAdd = this.domItem.find('#insertarDireccion');
this.btnNew = this.domItem.find('#nuevaDireccion');
@ -39,6 +41,20 @@ class Direcciones {
$("#clienteId").on('change', this.handleChangeCliente.bind(this));
this.recogidaTaller.on('change', () => {
if (this.recogidaTaller.is(':checked')) {
this.divDirecciones.empty();
this.direcciones = [];
$('.div-direcciones').addClass('d-none');
}
else{
$('.div-direcciones').removeClass('d-none');
}
});
this.direccionesCliente.init();
this.btnAdd.on('click', this.#insertDireccion.bind(this));
this.btnNew.on('click', this.#nuevaDireccion.bind(this));
@ -70,44 +86,52 @@ class Direcciones {
});
}, 0);
setTimeout(function () {
$(`#containerTiradasEnvios .tirada-envio input[tirada="${datosGenerales.tirada}"]`).trigger('click');
}, 0);
if (datos.entrega_taller == 1) {
this.recogidaTaller.prop('checked', true);
}
else {
this.recogidaTaller.prop('checked', false);
setTimeout(function () {
$(`#containerTiradasEnvios .tirada-envio input[tirada="${datosGenerales.tirada}"]`).trigger('click');
}, 0);
for (let i = 0; i < datos.length; i++) {
for (let i = 0; i < datos.length; i++) {
let id = datos[i].id;
let unidades = datos[i].unidades;
let entregaPalets = datos[i].palets;
let divId = "dirEnvio-1";
let direccionesActuales = this.divDirecciones.find('.direccion-cliente');
if (direccionesActuales.length > 0) {
// the the lass item
let last = direccionesActuales[direccionesActuales.length - 1];
divId = "dirEnvio-" + (parseInt(last.id.split('-')[1]) + 1);
let id = datos[i].id;
let unidades = datos[i].unidades;
let entregaPalets = datos[i].palets;
let divId = "dirEnvio-1";
let direccionesActuales = this.divDirecciones.find('.direccion-cliente');
if (direccionesActuales.length > 0) {
// the the lass item
let last = direccionesActuales[direccionesActuales.length - 1];
divId = "dirEnvio-" + (parseInt(last.id.split('-')[1]) + 1);
}
if (id == null || id <= 0 || id == undefined)
return;
if (unidades == null || unidades <= 0 || unidades == undefined)
return;
let peticion = new Ajax('/misdirecciones/getDireccionPresupuesto/' + id, {}, {},
(response) => {
let tarjeta = new tarjetaDireccion(this.divDirecciones, divId, response.data[0]);
tarjeta.setUnidades(unidades);
tarjeta.setEntregaPalets(entregaPalets);
tarjeta.card.find('.direccion-editar').on('click', this.#editUnits.bind(self));
tarjeta.card.find('.direccion-eliminar').on('click', this.#deleteDireccion.bind(self));
this.divDirecciones.append(tarjeta.card);
this.direcciones.push(tarjeta);
},
() => {
console.error('Error getting address');
});
peticion.get();
}
if (id == null || id <= 0 || id == undefined)
return;
if (unidades == null || unidades <= 0 || unidades == undefined)
return;
let peticion = new Ajax('/misdirecciones/getDireccionPresupuesto/' + id, {}, {},
(response) => {
let tarjeta = new tarjetaDireccion(this.divDirecciones, divId, response.data[0]);
tarjeta.setUnidades(unidades);
tarjeta.setEntregaPalets(entregaPalets);
tarjeta.card.find('.direccion-editar').on('click', this.#editUnits.bind(self));
tarjeta.card.find('.direccion-eliminar').on('click', this.#deleteDireccion.bind(self));
this.divDirecciones.append(tarjeta.card);
this.direcciones.push(tarjeta);
},
() => {
console.error('Error getting address');
});
peticion.get();
}
} catch (e) {
console.error(e);

View File

@ -62,15 +62,13 @@ class DisenioCubierta {
this.divPapelCubierta = this.domItem.find("#divPapelCubierta");
this.divGramajeCubierta = this.domItem.find("#divGramajeCubierta");
this.cubiertaPlastificado = this.domItem.find("#plastificado");
this.cubiertaBarniz = this.domItem.find("#barniz");
this.cubiertaEstampado = this.domItem.find("#estampado");
this.acabadoCubierta = this.domItem.find("#acabadoCubierta");
this.cubiertaRetractilado = this.domItem.find("#retractilado");
this.configuracionSobrecubierta = this.domItem.find(".config-sobrecubierta");
this.sobrecubierta = this.domItem.find("#addSobrecubierta");
this.papelSobrecubierta = this.domItem.find("#papelSobrecubierta");
this.plastificadoSobrecubierta = this.domItem.find("#plastificadoSobrecubierta");
this.acabadoSobrecubierta = this.domItem.find("#acabadoSobrecubierta");
this.configuracionFaja = this.domItem.find(".config-faja");
this.faja = this.domItem.find("#addFaja");
@ -94,6 +92,26 @@ class DisenioCubierta {
this.rl_tamanio_sobrecubierta = $('#rl_tamanio_sobrecubierta');
this.rl_acabado_sobrecubierta = $("#rl_acabado_sobrecubierta");
this.acabadoCubierta = new ClassSelect($("#acabadoCubierta"),
'/serviciosacabados/getacabados',
'',
false,
{
[this.csrf_token]: this.csrf_hash,
"cubierta": 1
}
);
this.acabadoSobrecubierta = new ClassSelect($("#acabadoSobrecubierta"),
'/serviciosacabados/getacabados',
'',
false,
{
[this.csrf_token]: this.csrf_hash,
"sobrecubierta": 1
}
);
this.initValidation();
// Creamos un nuevo observador que detecta cambios en los atributos
@ -116,6 +134,10 @@ class DisenioCubierta {
this.gramaje = null;
this.cargando = true;
this.presupuestoConfirmado = false;
this.papelForResumen = "";
this.gramajeForResumen = "";
}
@ -124,6 +146,9 @@ class DisenioCubierta {
const self = this;
this.papelEspecial.init();
this.acabadoCubierta.init();
this.acabadoSobrecubierta.init();
$('#papelEspecialCubiertaSel').on("change", this.#handlePapelCubiertaEspecial.bind(this));
// Eventos
@ -195,9 +220,8 @@ class DisenioCubierta {
$(`#divGramajeCubierta .gramaje-cubierta input[data-value="${datosCubierta.gramaje}"]`).trigger('click');
}, 0);
this.cubiertaPlastificado.val(datosCubierta.plastificado).trigger('change');
this.cubiertaBarniz.val(datosCubierta.barniz).trigger('change');
this.cubiertaEstampado.val(datosCubierta.estampado).trigger('change');
this.acabadoCubierta.setOption(datosCubierta.acabado.id, datosCubierta.acabado.text);
if (datosCubierta.retractilado) {
setTimeout(() => {
this.cubiertaRetractilado.trigger('click');
@ -208,7 +232,7 @@ class DisenioCubierta {
this.sobrecubierta.trigger('click');
this.papelSobrecubierta.val(datosSobrecubierta.papel.code + "_" + datosSobrecubierta.gramaje).trigger('change');
this.solapasSobrecubierta.val(datosSobrecubierta.solapas_ancho);
this.plastificadoSobrecubierta.val(datosSobrecubierta.plastificado).trigger('change');
this.acabadoSobrecubierta.setOption(datosSobrecubierta.acabado.id, datosSobrecubierta.acabado.text);
}
}
@ -390,7 +414,7 @@ class DisenioCubierta {
if (papel != null && gramaje != null) {
this.rl_papel_cubierta.text(papel + " " + gramaje + " gr");
this.rl_acabado_cubierta.text(this.domItem.find("#plastificado").children("option:selected").text());
this.rl_acabado_cubierta.text("Acabado: " + this.acabadoCubierta.getText());
this.rl_papel_cubierta.removeClass('d-none');
this.rl_acabado_cubierta.removeClass('d-none');
@ -433,10 +457,7 @@ class DisenioCubierta {
const sobrecubierta = this.getSobrecubierta(true);
this.rl_papel_sobrecubierta.text(sobrecubierta.papel + " " + sobrecubierta.gramaje + " gr")
this.rl_tamanio_sobrecubierta.text("Solapas: " + sobrecubierta.solapas + " mm")
let acabado_text = sobrecubierta.plastificado;
if (acabado_text.includes("Sin plastificar"))
acabado_text = "Sin plastificar";
this.rl_acabado_sobrecubierta.text(acabado_text);
this.rl_acabado_sobrecubierta.text("Acabado: " + this.acabadoSobrecubierta.getText());
}
}
else {
@ -470,6 +491,9 @@ class DisenioCubierta {
getPapel(forResumen = false) {
try {
if (this.presupuestoConfirmado)
return this.papelForResumen;
let checkedPapel = $('.custom-selector-papel-cubierta input[type="radio"]:checked');
if (this.papelCubierta != null && checkedPapel != null && checkedPapel.length > 0) {
if (forResumen) {
@ -506,9 +530,12 @@ class DisenioCubierta {
try {
if (checkedGramaje.length == 0)
return null;
return checkedGramaje[0].id.split('_')[1];
if (this.presupuestoConfirmado)
return this.gramajeForResumen;
if (checkedGramaje.length == 0)
return null;
return checkedGramaje[0].id.split('_')[1];
} catch (e) {
return null;
}
@ -516,25 +543,14 @@ class DisenioCubierta {
getAcabados(forResumen = false) {
try {
let acabados = {};
let acabado;
if (forResumen) {
acabados = 'Plastificado ' + this.domItem.find("#plastificado").children("option:selected").text();
if (this.domItem.find("#barniz").children("option:selected").val() != 'NONE')
acabados += ", Barniz UVI " + this.domItem.find("#barniz").children("option:selected").text();
if (this.domItem.find("#estampado").children("option:selected").val() != 'NONE')
acabados += ", Estampado " + this.domItem.find("#estampado").children("option:selected").text();
if (this.domItem.find("#retractilado").hasClass('selected')) {
acabados += ", Retractilado ";
}
return acabados;
acabado = this.acabadoCubierta.getText();
}
else {
acabados.plastificado = this.domItem.find("#plastificado ").children("option:selected").val();
acabados.barniz = this.domItem.find("#barniz").children("option:selected").val();
acabados.estampado = this.domItem.find("#estampado").children("option:selected").val();
acabados.retractilado = this.domItem.find("#retractilado").hasClass('selected') ? 'RETR' : 'NONE';
acabado = this.acabadoCubierta.getVal();
}
return acabados;
return acabado;
} catch (e) {
return null;
}
@ -599,7 +615,7 @@ class DisenioCubierta {
sobrecubierta.papel = papel.split(' ')[0] + ' ' + papel.split(' ')[1];
sobrecubierta.gramaje = papel.split(' ')[2];
sobrecubierta.solapas = this.domItem.find("#solapasSobrecubierta").val();
sobrecubierta.plastificado = 'Plastificado ' + this.domItem.find("#plastificadoSobrecubierta").children("option:selected").text();
sobrecubierta.acabado = this.acabadoSobrecubierta.getText();
return sobrecubierta;
}
else {
@ -608,7 +624,7 @@ class DisenioCubierta {
sobrecubierta.papel = papel.split('_')[0];
sobrecubierta.gramaje = papel.split('_')[1];
sobrecubierta.solapas = this.domItem.find("#solapasSobrecubierta").val();
sobrecubierta.plastificado = this.domItem.find("#plastificadoSobrecubierta").children("option:selected").val();
sobrecubierta.acabado = this.acabadoSobrecubierta.getVal();
return sobrecubierta;
}
}
@ -867,20 +883,20 @@ class DisenioCubierta {
const element = $(event.target);
const papel = element[0].id.split('_')[1];
this.papelCubierta = papel;
$('#' + papel).prop('checked', true);
if (element[0].id == 'papelEspecialCubierta') {
if(!this.cargando)
if (!this.cargando)
this.gramaje = null;
this.divGramajeCubierta.empty();
this.divPapelEspecial.removeClass("d-none");
$('#papelEspecialCubiertaSel').off("change");
this.papelEspecial.empty();
$('#papelEspecialCubiertaSel').on("change", this.#handlePapelCubiertaEspecial.bind(this));
}

View File

@ -79,9 +79,13 @@ class DisenioInterior {
this.cargando = true;
this.presupuestoConfirmado = false;
this.papelNegroForResumen = "";
this.gramajeNegroForResumen = "";
this.papelColorForResumen = "";
this.gramajeColorForResumen = "";
this.initValidation();
}
@ -350,7 +354,7 @@ class DisenioInterior {
this.gramaje = datos.negro.gramaje;
}
}
if(datos.paginasColorConsecutivas)
if (datos.paginasColorConsecutivas)
this.updatePapeles();
else
this.updatePapeles('negro');
@ -666,6 +670,21 @@ class DisenioInterior {
getPapel(forResumen = false) {
try {
if (this.presupuestoConfirmado) {
if (this.papelColorForResumen.length > 0 && this.papelNegroForResumen.length > 0)
return {
negro: this.papelNegroForResumen,
color: this.papelColorForResumen
}
else if (this.papelColorForResumen.length > 0) {
return this.papelColorForResumen;
}
else {
return this.papelNegroForResumen;
}
}
let checkedPapel = $('.custom-selector-papel input[type="radio"]:checked');
if (this.papelInterior != null && checkedPapel != null && checkedPapel.length > 0) {
@ -748,6 +767,22 @@ class DisenioInterior {
getGramaje() {
try {
if (this.presupuestoConfirmado) {
if (this.gramajeColorForResumen.length > 0 && this.gramajeNegroForResumen.length > 0)
return {
negro: this.gramajeNegroForResumen,
color: this.gramajeColorForResumen
}
else if (this.gramajeColorForResumen.length > 0) {
return this.gramajeColorForResumen;
}
else {
return this.gramajeNegroForResumen;
}
}
let checkedGramaje = $('.custom-selector-gramaje input[type="radio"]:checked');
if (this.interiorColor.filter('.d-none').length == 0) {
@ -830,14 +865,14 @@ class DisenioInterior {
const element = $(event.target);
const papel = element[0].id.split('_')[1];
this.papelInterior = papel;
$('#' + papel).prop('checked', true);
let tipo = this.getTipoImpresion();
if (element[0].id == 'papelEspecialInterior') {
if(!this.cargando)
if (!this.cargando)
this.gramaje = null;
this.divGramajeInterior.empty();
this.divPapelEspecialInterior.removeClass("d-none");

View File

@ -45,7 +45,7 @@ class PresupuestoCliente {
this.datos = {};
this.ajax_calcular = new Ajax('/presupuestocliente/calcular',
this.datos,
{},
{},
this.#procesarPresupuesto.bind(this),
() => { $('#loader').modal('hide'); });
@ -71,6 +71,7 @@ class PresupuestoCliente {
this.disenioInterior.init();
this.disenioCubierta.init();
this.direcciones.init();
if (window.location.href.includes("edit")) {
this.resumen.init(window.location.href.split("/").pop());
}
@ -156,7 +157,7 @@ class PresupuestoCliente {
return !(noPOD && siPOD);
}
calcularSolapas(){
calcularSolapas() {
/* Solapas Max */
this.#getDatos(false, true);
@ -174,7 +175,7 @@ class PresupuestoCliente {
this.disenioCubierta.textoSolapasCubierta.text("Entre 60 y " + response + " mm");
this.disenioCubierta.textoSolapasSobrecubierta.text("Entre 60 y " + response + " mm");
},
() => { }
() => { }
).post();
}
}
@ -187,7 +188,7 @@ class PresupuestoCliente {
return;
}
if (this.calcularPresupuesto) {
if (event.target.id === 'divDirecciones') {
@ -414,13 +415,17 @@ class PresupuestoCliente {
#confirmPresupuesto() {
let total_unidades = 0;
this.direcciones.direcciones.forEach(element => {
total_unidades += parseInt(element.tirada.val());
});
if (!this.direcciones.recogidaTaller.is(':checked')) {
if (total_unidades != parseInt(this.direcciones.getSelectedTirada())) {
popErrorAlert("No se puede confirmar el presupuesto. La suma de las unidades enviadas no coincide con la tirada seleccionada.");
return;
this.direcciones.direcciones.forEach(element => {
total_unidades += parseInt(element.getUnidades());
});
if (total_unidades != parseInt(this.direcciones.getSelectedTirada())) {
popErrorAlert("No se puede confirmar el presupuesto. La suma de las unidades enviadas no coincide con la tirada seleccionada.");
return;
}
}
this.#solicitudGuardarPresupuesto(true);
@ -588,17 +593,11 @@ class PresupuestoCliente {
if (datos_to_check.posPaginasColor == "" || datos_to_check.posPaginasColor == null) {
delete datos_to_check.posPaginasColor;
}
if (datos_to_check.cubierta.acabados.barniz == undefined) {
delete datos_to_check.cubierta.acabados.barniz;
if (datos_to_check.cubierta.acabado == 0) {
delete datos_to_check.cubierta.acabado;
}
if (datos_to_check.cubierta.acabados.plastificado == undefined) {
delete datos_to_check.cubierta.acabados.plastificado;
}
if (datos_to_check.cubierta.acabados.estampado == undefined) {
delete datos_to_check.cubierta.acabados.estampado;
}
if (datos_to_check.sobrecubierta.plastificado == undefined) {
delete datos_to_check.sobrecubierta.plastificado;
if (datos_to_check.sobrecubierta.acabado == 0) {
delete datos_to_check.sobrecubierta.acabado;
}
return datos_to_check;
@ -650,7 +649,7 @@ class PresupuestoCliente {
papelCubierta: this.disenioCubierta.getPapel(),
gramajeCubierta: this.disenioCubierta.getGramaje(),
cabezada: this.disenioCubierta.getCabezada(),
acabados: this.disenioCubierta.getAcabados(),
acabado: this.disenioCubierta.getAcabados(),
carasImpresion: this.disenioCubierta.carasCubierta.val(),
};
@ -691,13 +690,16 @@ class PresupuestoCliente {
this.datos.cubierta.solapas = 0;
}
if (this.direcciones.direcciones.length > 0) {
this.datos.direcciones = [];
for (let i = 0; i < this.direcciones.direcciones.length; i++) {
this.datos.direcciones.push(this.direcciones.direcciones[i].getFormData());
};
}
this.datos.entrega_taller = this.direcciones.recogidaTaller.is(':checked') ? 1 : 0;
if (!this.direcciones.recogidaTaller.is(':checked')) {
if (this.direcciones.direcciones.length > 0) {
this.datos.direcciones = [];
for (let i = 0; i < this.direcciones.direcciones.length; i++) {
this.datos.direcciones.push(this.direcciones.direcciones[i].getFormData());
};
}
}
if (save) {
this.datos.datosCabecera = {
titulo: this.datosGenerales.titulo.val(),
@ -717,6 +719,8 @@ class PresupuestoCliente {
#cargarPresupuesto() {
const self = this;
$('#loader').modal('show');
let id = window.location.href.split("/").pop()
new Ajax('/presupuestocliente/cargar/' + id,
@ -726,18 +730,18 @@ class PresupuestoCliente {
if (response.status === 1) {
this.lc.val(parseFloat(response.data.lc).toFixed(2));
this.lsc.val(parseFloat(response.data.lsc).toFixed(2));
self.lc.val(parseFloat(response.data.lc).toFixed(2));
self.lsc.val(parseFloat(response.data.lsc).toFixed(2));
this.calcularPresupuesto = false;
self.calcularPresupuesto = false;
this.datosGenerales.cargarDatos(response.data.datosGenerales);
this.direcciones.handleChangeCliente();
self.datosGenerales.cargarDatos(response.data.datosGenerales);
self.direcciones.handleChangeCliente();
this.direcciones.cargarDatos(response.data.direcciones, response.data.datosGenerales);
self.direcciones.cargarDatos(response.data.direcciones, response.data.datosGenerales);
this.disenioInterior.cargarDatos(response.data.interior, response.data.datosGenerales.papelInteriorDiferente);
this.disenioCubierta.cargarDatos(response.data.cubierta, response.data.guardas, response.data.sobrecubierta);
self.disenioInterior.cargarDatos(response.data.interior, response.data.datosGenerales.papelInteriorDiferente);
self.disenioCubierta.cargarDatos(response.data.cubierta, response.data.guardas, response.data.sobrecubierta);
setTimeout(() => {
@ -746,14 +750,28 @@ class PresupuestoCliente {
if (response.data.state != 2) {
this.calcularPresupuesto = true;
this.checkForm({ target: { id: 'tirada' } });
self.calcularPresupuesto = true;
self.checkForm({ target: { id: 'tirada' } });
}
else {
self.disenioInterior.presupuestoConfirmado = true;
if (response.data.interior.negro) {
self.disenioInterior.papelNegroForResumen = response.data.interior.negro.papel.nombre;
self.disenioInterior.gramajeNegroForResumen = response.data.interior.negro.gramaje;
}
if (response.data.interior.color) {
self.disenioInterior.papelColorForResumen = response.data.interior.color.nombre;
self.disenioInterior.gramajeColorForResumen = response.data.interior.color.gramaje;
}
self.disenioCubierta.presupuestoConfirmado = true;
self.disenioCubierta.papelForResumen = response.data.cubierta.papel.nombre;
self.disenioCubierta.gramajeForResumen = response.data.cubierta.gramaje;
$('#menu_resumen_button').trigger('click');
setTimeout(() => {
this.resumen.init_dropzone();
this.resumen.generate_total(response.data.resumen.base, response.data.resumen.precio_unidad);
self.resumen.init_dropzone();
self.resumen.generate_total(response.data.resumen.base, response.data.resumen.precio_unidad);
}, 0);
}
}, 0);

View File

@ -1,4 +1,4 @@
import previewFormas from "../preview.js";
import previewFormas from "../../components/preview.js";
import { capitalizeFirstLetter } from "../../common/common.js";
class Resumen {
@ -290,7 +290,7 @@ class Resumen {
this.papelSobrecubierta.text(sobrecubierta.papel);
this.gramajeSobrecubierta.text(sobrecubierta.gramaje);
this.solapasSobrecubierta.text(sobrecubierta.solapas);
this.plastificadoSobrecubierta.text(sobrecubierta.plastificado);
this.plastificadoSobrecubierta.text(sobrecubierta.acabado);
}
else {
this.divSobrecubierta.addClass('d-none');

View File

@ -31,6 +31,9 @@ class tarjetaTiradasPrecio {
class: 'list-content'
});
const formattedPrecio = precio.toString().replace('.', ',');
const formattedPrecioUnidad = precio_unidad.toString().replace('.', ',');
$listContent.append($('<h7>', {
id: 'ud_' + id,
class: 'mb-1 tarjeta-tiradas-precios-tirada',
@ -40,13 +43,13 @@ class tarjetaTiradasPrecio {
$listContent.append($('<h6>', {
id: 'tot_' + id,
class: 'mb-1 tarjeta-tiradas-precios-precio',
text: 'Total: ' + precio + '€'
text: 'Total: ' + formattedPrecio + '€'
}).attr('data', precio));
$listContent.append($('<h7>', {
id: 'pu_' + id,
class: 'mb-1 tarjeta-tiradas-precios-precio-unidad',
text: precio_unidad + '€/ud'
text: formattedPrecioUnidad + '€/ud'
}).attr('data', precio_unidad));
$liWrapper.append($listContent);

View File

@ -0,0 +1,144 @@
import Table from '../../components/table.js';
import ConfirmDeleteModal from '../../components/ConfirmDeleteModal.js';
import Ajax from '../../components/ajax.js';
import { getToken } from '../../common/common.js';
class UserList {
constructor() {
this.domItem = $('.card-body');
this.csrf_token = getToken();
this.csrf_hash = $('#mainContainer').find('input[name="' + this.csrf_token + '"]').val();
this.tableUsers = null;
this.deleteModal = null;
}
init() {
const self = this;
this.headerSearcher();
this.deleteModal = new ConfirmDeleteModal('plantillasTarifasCliente');
this.deleteModal.init();
this.#initTable();
// Editar en linea la fila
this.tableUsers.table.on('click', '.btn-edit-' + this.tableUsers.getAlias(), function (e) {
const dataId = $(this).attr('data-id');
if (!Number.isNaN(Number(dataId))) {
window.location.href = '/users/edit/' + dataId;
}
});
// Eliminar la fila
this.tableUsers.table.on('click', '.btn-delete-' + this.tableUsers.getAlias(), function (e) {
const row = $(this).closest('tr')[0]._DT_RowIndex;
const dataId = $(this).attr('data-id');
self.deleteModal.setData($(this).attr('data-id'));
self.deleteModal.show(() => {
if (!Number.isNaN(Number(self.deleteModal.getData()))) {
new Ajax(
'/users/delete/' + dataId,
{
},
{},
(data, textStatus, jqXHR) => {
self.tableUsers.table.clearPipeline();
self.tableUsers.table.row($(row)).invalidate().draw();
popSuccessAlert(data.msg ?? jqXHR.statusText);
},
(error) => {
console.log(error);
}
).get();
self.deleteModal.hide();
}
});
});
}
#initTable() {
const self = this;
const columns = [
{ 'data': 'id' },
{ 'data': 'first_name' },
{ 'data': 'last_name' },
{ 'data': 'email' },
{ 'data': 'cliente' },
{ 'data': 'last_active' },
];
const actions = ['edit', 'delete'];
this.tableUsers = new Table(
$('#tableOfUsers'),
'users',
'/users/datatable',
columns,
[]
);
this.tableUsers.init({
actions: actions,
colVisibility: false,
buttonsExport: true,
});
this.tableUsers.table.on('init.dt', function () {
self.tableUsers.table.page.len(50).draw();
});
}
headerSearcher() {
const self = this;
$('#tableOfUsers thead tr').clone(false).appendTo('#tableOfUsers thead');
$('#tableOfUsers thead tr:eq(1) th').each(function (i) {
if (!$(this).hasClass("noFilter")) {
$(this).html('<input type="text" class="form-control " style="min-width:100px;max-width:500px;font-size:0.8rem !important;" />');
$('input', this).on('change clear', function () {
if (self.tableUsers.table.column(i).search() !== this.value) {
self.tableUsers.table
.column(i)
.search(this.value)
.draw();
}
});
}
else {
$(this).html('<span></span>');
}
});
}
}
document.addEventListener('DOMContentLoaded', function () {
new UserList().init();
});