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

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

2
.gitignore vendored
View File

@ -1,4 +1,4 @@
ci4/.env ci4/.env
.vscode/ .vscode/
xdebug.log *xdebug*.log*

15
.idea/codeception.xml generated Normal file
View File

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Codeception">
<option name="configurations">
<list>
<Configuration>
<option name="path" value="$PROJECT_DIR$/tests" />
</Configuration>
<Configuration>
<option name="path" value="$PROJECT_DIR$/ci4/tests" />
</Configuration>
</list>
</option>
</component>
</project>

7
.idea/php.xml generated
View File

@ -55,6 +55,13 @@
<path value="$PROJECT_DIR$/ci4/vendor/codeigniter4/shield" /> <path value="$PROJECT_DIR$/ci4/vendor/codeigniter4/shield" />
<path value="$PROJECT_DIR$/ci4/vendor/codeigniter4/settings" /> <path value="$PROJECT_DIR$/ci4/vendor/codeigniter4/settings" />
<path value="$PROJECT_DIR$/ci4/vendor/codeigniter4/framework" /> <path value="$PROJECT_DIR$/ci4/vendor/codeigniter4/framework" />
<path value="$PROJECT_DIR$/ci4/vendor/nicolab/php-ftp-client" />
<path value="$PROJECT_DIR$/ci4/vendor/hermawan/codeigniter4-datatables" />
<path value="$PROJECT_DIR$/ci4/vendor/firebase/php-jwt" />
<path value="$PROJECT_DIR$/ci4/vendor/greenlion/php-sql-parser" />
<path value="$PROJECT_DIR$/ci4/vendor/paragonie/random_compat" />
<path value="$PROJECT_DIR$/ci4/vendor/paragonie/constant_time_encoding" />
<path value="$PROJECT_DIR$/ci4/vendor/phpseclib/phpseclib" />
</include_path> </include_path>
</component> </component>
<component name="PhpProjectSharedConfiguration" php_language_level="8.2"> <component name="PhpProjectSharedConfiguration" php_language_level="8.2">

16
.idea/phpspec.xml generated Normal file
View File

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="PHPSpec">
<suites>
<PhpSpecSuiteConfiguration>
<option name="myPath" value="$PROJECT_DIR$" />
</PhpSpecSuiteConfiguration>
<PhpSpecSuiteConfiguration>
<option name="myPath" value="$PROJECT_DIR$/ci4" />
</PhpSpecSuiteConfiguration>
<PhpSpecSuiteConfiguration>
<option name="myPath" value="$PROJECT_DIR$/ci4" />
</PhpSpecSuiteConfiguration>
</suites>
</component>
</project>

7
.idea/safekat.iml generated
View File

@ -7,6 +7,13 @@
<sourceFolder url="file://$MODULE_DIR$/ci4/app/ThirdParty/DatatablesEditor/" isTestSource="false" packagePrefix="DataTables\" /> <sourceFolder url="file://$MODULE_DIR$/ci4/app/ThirdParty/DatatablesEditor/" isTestSource="false" packagePrefix="DataTables\" />
<sourceFolder url="file://$MODULE_DIR$/ci4/tests" isTestSource="true" /> <sourceFolder url="file://$MODULE_DIR$/ci4/tests" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/ci4/tests/_support" isTestSource="true" packagePrefix="Tests\Support\" /> <sourceFolder url="file://$MODULE_DIR$/ci4/tests/_support" isTestSource="true" packagePrefix="Tests\Support\" />
<excludeFolder url="file://$MODULE_DIR$/ci4/vendor/firebase/php-jwt" />
<excludeFolder url="file://$MODULE_DIR$/ci4/vendor/greenlion/php-sql-parser" />
<excludeFolder url="file://$MODULE_DIR$/ci4/vendor/hermawan/codeigniter4-datatables" />
<excludeFolder url="file://$MODULE_DIR$/ci4/vendor/nicolab/php-ftp-client" />
<excludeFolder url="file://$MODULE_DIR$/ci4/vendor/paragonie/constant_time_encoding" />
<excludeFolder url="file://$MODULE_DIR$/ci4/vendor/paragonie/random_compat" />
<excludeFolder url="file://$MODULE_DIR$/ci4/vendor/phpseclib/phpseclib" />
</content> </content>
<orderEntry type="inheritedJdk" /> <orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" /> <orderEntry type="sourceFolder" forTests="false" />

View File

@ -77,14 +77,7 @@ $routes->group('configuracion', ['namespace' => 'App\Controllers\Configuracion']
$routes->post('menuitemsFacturas', 'SeriesFacturas::menuItemsFacturas', ['as' => 'menuItemsOfSeriesFacturas']); $routes->post('menuitemsFacturas', 'SeriesFacturas::menuItemsFacturas', ['as' => 'menuItemsOfSeriesFacturas']);
}); });
/* Formas de Pago */
$routes->group('formas-pago', ['namespace' => 'App\Controllers\Configuracion'], function ($routes) {
$routes->get('', 'FormasPago::index', ['as' => 'formasPagoList']);
$routes->match(['get', 'post'], 'add', 'FormasPago::add', ['as' => 'formasPagoAdd']);
$routes->match(['get', 'post'], 'edit/(:num)', 'FormasPago::edit/$1', ['as' => 'formasPagoEdit']);
$routes->get('delete/(:num)', 'FormasPago::delete/$1', ['as' => 'formasPagoDelete']);
$routes->post('datatable', 'FormasPago::datatable', ['as' => 'formasPagoDT']);
});
$routes->group("variables", ["namespace" => 'App\Controllers\Configuracion'], function ($routes) { $routes->group("variables", ["namespace" => 'App\Controllers\Configuracion'], function ($routes) {
$routes->get('', 'ConfigVariables::index', ['as' => 'variablesIndex']); $routes->get('', 'ConfigVariables::index', ['as' => 'variablesIndex']);
$routes->get('find/(:num)', 'ConfigVariables::get/$1', ['as' => 'variablesFind']); $routes->get('find/(:num)', 'ConfigVariables::get/$1', ['as' => 'variablesFind']);
@ -104,7 +97,6 @@ $routes->group('configuracion', ['namespace' => 'App\Controllers\Configuracion']
$routes->group('users', ['namespace' => 'App\Controllers\Configuracion'], function ($routes) { $routes->group('users', ['namespace' => 'App\Controllers\Configuracion'], function ($routes) {
$routes->get('', 'Users::index', ['as' => 'userList']); $routes->get('', 'Users::index', ['as' => 'userList']);
$routes->get('index', 'Users::index', ['as' => 'userIndex']);
$routes->get('list', 'Users::index', ['as' => 'userList2']); $routes->get('list', 'Users::index', ['as' => 'userList2']);
$routes->get('add', 'Users::add', ['as' => 'newUser']); $routes->get('add', 'Users::add', ['as' => 'newUser']);
$routes->post('add', 'Users::add', ['as' => 'createUser']); $routes->post('add', 'Users::add', ['as' => 'createUser']);
@ -113,8 +105,10 @@ $routes->group('users', ['namespace' => 'App\Controllers\Configuracion'], functi
$routes->get('delete/(:num)', 'Users::delete/$1', ['as' => 'deleteUser']); $routes->get('delete/(:num)', 'Users::delete/$1', ['as' => 'deleteUser']);
$routes->post('allmenuitems', 'Users::allItemsSelect', ['as' => 'select2ItemsOfUsers']); $routes->post('allmenuitems', 'Users::allItemsSelect', ['as' => 'select2ItemsOfUsers']);
$routes->post('menuitems', 'Users::menuItems', ['as' => 'menuItemsOfUsers']); $routes->post('menuitems', 'Users::menuItems', ['as' => 'menuItemsOfUsers']);
$routes->post('getMenuComerciales', 'Users::getMenuComerciales', ['as' => 'menuItemsComerciales']); $routes->get('getMenuComerciales', 'Users::getMenuComerciales', ['as' => 'menuItemsComerciales']);
}); });
$routes->resource('users', ['namespace' => 'App\Controllers\Configuracion', 'controller' => 'Users', 'except' => 'show,new,create,update']);
$routes->group('group', ['namespace' => 'App\Controllers\Configuracion'], function ($routes) { $routes->group('group', ['namespace' => 'App\Controllers\Configuracion'], function ($routes) {
$routes->get('', 'Group::index', ['as' => 'userGroupList']); $routes->get('', 'Group::index', ['as' => 'userGroupList']);
@ -221,6 +215,8 @@ $routes->group('papelesgenericos', ['namespace' => 'App\Controllers\Configuracio
$routes->post('datatable', 'Papelesgenericos::datatable', ['as' => 'dataTableOfPapelesGenericos']); $routes->post('datatable', 'Papelesgenericos::datatable', ['as' => 'dataTableOfPapelesGenericos']);
$routes->post('allmenuitems', 'Papelesgenericos::allItemsSelect', ['as' => 'select2ItemsOfPapelesGenericos']); $routes->post('allmenuitems', 'Papelesgenericos::allItemsSelect', ['as' => 'select2ItemsOfPapelesGenericos']);
$routes->post('menuitems', 'Papelesgenericos::menuItems', ['as' => 'menuItemsOfPapelesGenericos']); $routes->post('menuitems', 'Papelesgenericos::menuItems', ['as' => 'menuItemsOfPapelesGenericos']);
$routes->get('getpapelcliente', 'Papelesgenericos::getPapelCliente', ['as' => 'getPapelCliente']);
$routes->get('selectpapelespecial', 'Papelesgenericos::selectPapelEspecial', ['as' => 'selectPapelEspecial']);
}); });
$routes->resource('papelesgenericos', ['namespace' => 'App\Controllers\Configuracion', 'controller' => 'Papelesgenericos', 'except' => 'show,new,create,update']); $routes->resource('papelesgenericos', ['namespace' => 'App\Controllers\Configuracion', 'controller' => 'Papelesgenericos', 'except' => 'show,new,create,update']);
@ -332,10 +328,22 @@ $routes->group('comunidades-autonomas', ['namespace' => 'App\Controllers\Configu
$routes->post('datatable', 'Comunidadesautonomas::datatable', ['as' => 'dataTableOfComunidadesAutonomas']); $routes->post('datatable', 'Comunidadesautonomas::datatable', ['as' => 'dataTableOfComunidadesAutonomas']);
$routes->post('allmenuitems', 'Comunidadesautonomas::allItemsSelect', ['as' => 'select2ItemsOfComunidadesAutonomas']); $routes->post('allmenuitems', 'Comunidadesautonomas::allItemsSelect', ['as' => 'select2ItemsOfComunidadesAutonomas']);
$routes->post('menuitems', 'Comunidadesautonomas::menuItems', ['as' => 'menuItemsOfComunidadesAutonomas']); $routes->post('menuitems', 'Comunidadesautonomas::menuItems', ['as' => 'menuItemsOfComunidadesAutonomas']);
$routes->get('menuitems2', 'Comunidadesautonomas::menuItems2', ['as' => 'menuItemsOfComunidadesAutonomas2']);
}); });
$routes->resource('comunidades-autonomas', ['namespace' => 'App\Controllers\Configuracion', 'controller' => 'Comunidadesautonomas', 'except' => 'show,new,create,update']); $routes->resource('comunidades-autonomas', ['namespace' => 'App\Controllers\Configuracion', 'controller' => 'Comunidadesautonomas', 'except' => 'show,new,create,update']);
$routes->group('formas-pago', ['namespace' => 'App\Controllers\Configuracion'], function ($routes) {
$routes->get('', 'FormasPago::index', ['as' => 'formasPagoList']);
$routes->match(['get', 'post'], 'add', 'FormasPago::add', ['as' => 'formasPagoAdd']);
$routes->match(['get', 'post'], 'edit/(:num)', 'FormasPago::edit/$1', ['as' => 'formasPagoEdit']);
$routes->get('delete/(:num)', 'FormasPago::delete/$1', ['as' => 'formasPagoDelete']);
$routes->post('datatable', 'FormasPago::datatable', ['as' => 'formasPagoDT']);
$routes->get('menuitems', 'FormasPago::menuItems', ['as' => 'menuItemsOfFormasDePagos']);
});
$routes->resource('formas-pago', ['namespace' => 'App\Controllers\Configuracion', 'controller' => 'FormasPago', 'except' => 'show,new,create,update']);
$routes->group('paises', ['namespace' => 'App\Controllers\Configuracion'], function ($routes) { $routes->group('paises', ['namespace' => 'App\Controllers\Configuracion'], function ($routes) {
$routes->get('', 'Paises::index', ['as' => 'paisList']); $routes->get('', 'Paises::index', ['as' => 'paisList']);
$routes->get('add', 'Paises::add', ['as' => 'newPais']); $routes->get('add', 'Paises::add', ['as' => 'newPais']);
@ -346,6 +354,7 @@ $routes->group('paises', ['namespace' => 'App\Controllers\Configuracion'], funct
$routes->post('datatable', 'Paises::datatable', ['as' => 'dataTableOfPaises']); $routes->post('datatable', 'Paises::datatable', ['as' => 'dataTableOfPaises']);
$routes->post('allmenuitems', 'Paises::allItemsSelect', ['as' => 'select2ItemsOfPaises']); $routes->post('allmenuitems', 'Paises::allItemsSelect', ['as' => 'select2ItemsOfPaises']);
$routes->post('menuitems', 'Paises::menuItems', ['as' => 'menuItemsOfPaises']); $routes->post('menuitems', 'Paises::menuItems', ['as' => 'menuItemsOfPaises']);
$routes->get('menuitems2', 'Paises::menuItems2', ['as' => 'menuItemsOfPaises2']);
}); });
$routes->resource('paises', ['namespace' => 'App\Controllers\Configuracion', 'controller' => 'Paises', 'except' => 'show,new,create,update']); $routes->resource('paises', ['namespace' => 'App\Controllers\Configuracion', 'controller' => 'Paises', 'except' => 'show,new,create,update']);
@ -360,6 +369,7 @@ $routes->group('provincias', ['namespace' => 'App\Controllers\Configuracion'], f
$routes->post('datatable', 'Provincias::datatable', ['as' => 'dataTableOfProvincias']); $routes->post('datatable', 'Provincias::datatable', ['as' => 'dataTableOfProvincias']);
$routes->post('allmenuitems', 'Provincias::allItemsSelect', ['as' => 'select2ItemsOfProvincias']); $routes->post('allmenuitems', 'Provincias::allItemsSelect', ['as' => 'select2ItemsOfProvincias']);
$routes->post('menuitems', 'Provincias::menuItems', ['as' => 'menuItemsOfProvincias']); $routes->post('menuitems', 'Provincias::menuItems', ['as' => 'menuItemsOfProvincias']);
$routes->get('menuitems2', 'Provincias::menuItems2', ['as' => 'menuItemsOfProvincias2']);
}); });
$routes->resource('provincias', ['namespace' => 'App\Controllers\Configuracion', 'controller' => 'Provincias', 'except' => 'show,new,create,update']); $routes->resource('provincias', ['namespace' => 'App\Controllers\Configuracion', 'controller' => 'Provincias', 'except' => 'show,new,create,update']);
@ -420,18 +430,6 @@ $routes->group('misdirecciones', ['namespace' => 'App\Controllers\Clientes'], fu
}); });
$routes->group('formas-pagos', ['namespace' => 'App\Controllers\Configuracion'], function ($routes) {
$routes->get('', 'Formaspagos::index', ['as' => 'formaDePagoList']);
$routes->get('add', 'Formaspagos::add', ['as' => 'newFormaDePago']);
$routes->post('add', 'Formaspagos::add', ['as' => 'createFormaDePago']);
$routes->post('create', 'Formaspagos::create', ['as' => 'ajaxCreateFormaDePago']);
$routes->put('(:num)/update', 'Formaspagos::update/$1', ['as' => 'ajaxUpdateFormaDePago']);
$routes->post('(:num)/edit', 'Formaspagos::edit/$1', ['as' => 'updateFormaDePago']);
$routes->post('datatable', 'Formaspagos::datatable', ['as' => 'dataTableOfFormasDePagos']);
$routes->post('allmenuitems', 'Formaspagos::allItemsSelect', ['as' => 'select2ItemsOfFormasDePagos']);
$routes->post('menuitems', 'Formaspagos::menuItems', ['as' => 'menuItemsOfFormasDePagos']);
});
$routes->resource('formas-pagos', ['namespace' => 'App\Controllers\Configuracion', 'controller' => 'Formaspagos', 'except' => 'show,new,create,update']);
$routes->group('tarifasencuadernacion', ['namespace' => 'App\Controllers\Tarifas'], function ($routes) { $routes->group('tarifasencuadernacion', ['namespace' => 'App\Controllers\Tarifas'], function ($routes) {
$routes->get('', 'Tarifasencuadernacion::index', ['as' => 'tarifaEncuadernacionList']); $routes->get('', 'Tarifasencuadernacion::index', ['as' => 'tarifaEncuadernacionList']);
@ -556,20 +554,20 @@ $routes->group('clientedirecciones', ['namespace' => 'App\Controllers\Clientes']
$routes->resource('clientedirecciones', ['namespace' => 'App\Controllers\Clientes', 'controller' => 'Clientedirecciones', 'except' => 'show,new,create,update']); $routes->resource('clientedirecciones', ['namespace' => 'App\Controllers\Clientes', 'controller' => 'Clientedirecciones', 'except' => 'show,new,create,update']);
$routes->group('cosidotapablanda', ['namespace' => 'App\Controllers\Presupuestos'], function ($routes) { $routes->group('presupuestoadmin', ['namespace' => 'App\Controllers\Presupuestos'], function ($routes) {
$routes->get('list/(:num)', 'Cosidotapablanda::list/$1', ['as' => 'cosidotapablandaList']); // HOMOGENIZAR CON ARGS DINAMICOS!!! $routes->get('list/(:num)', 'Presupuestoadmin::list/$1', ['as' => 'presupuestoAdminList']); // HOMOGENIZAR CON ARGS DINAMICOS!!!
$routes->get('add/(:num)', 'Cosidotapablanda::add/$1', ['as' => 'newCosidotapablanda']); $routes->get('add/(:num)', 'Presupuestoadmin::add/$1', ['as' => 'newPresupuestoAdmin']);
$routes->get('edit/(:any)', 'Cosidotapablanda::edit/$1', ['as' => 'editarPresupuesto']); $routes->get('edit/(:any)', 'Presupuestoadmin::edit/$1', ['as' => 'editarPresupuestoAdmin']);
$routes->post('add/(:num)', 'Cosidotapablanda::add/$1', ['as' => 'createCosidotapablanda']); $routes->post('add/(:num)', 'Presupuestoadmin::add/$1', ['as' => 'createPresupuestoAdmin']);
$routes->post('create', 'Cosidotapablanda::create', ['as' => 'ajaxCreateCosidotapablanda']); $routes->post('create', 'Presupuestoadmin::create', ['as' => 'ajaxCreatePresupuestoAdmin']);
$routes->put('(:num)/update', 'Cosidotapablanda::update/$1', ['as' => 'ajaxUpdateCosidotapablanda']); $routes->put('(:num)/update', 'Presupuestoadmin::update/$1', ['as' => 'ajaxUpdatePresupuestoAdmin']);
$routes->post('edit/(:num)', 'Cosidotapablanda::edit/$1', ['as' => 'updateCosidotapablanda']); $routes->post('edit/(:num)', 'Presupuestoadmin::edit/$1', ['as' => 'updatePresupuestoAdmin']);
$routes->post('datatable', 'Cosidotapablanda::datatable', ['as' => 'dataTableOfCosidotapablanda']); $routes->post('datatable', 'Presupuestoadmin::datatable', ['as' => 'dataTableOfPresupuestoAdmin']);
$routes->post('datatable_2', 'Cosidotapablanda::datatable_2', ['as' => 'updateDataOfCosidotapablanda']); $routes->post('datatable_2', 'Presupuestoadmin::datatable_2', ['as' => 'updateDataOfPresupuestoAdmin']);
$routes->post('allmenuitems', 'Cosidotapablanda::allItemsSelect', ['as' => 'select2ItemsOfCosidotapablanda']); $routes->post('allmenuitems', 'Presupuestoadmin::allItemsSelect', ['as' => 'select2ItemsOfPresupuestoAdmin']);
$routes->post('menuitems', 'Cosidotapablanda::menuItems', ['as' => 'menuItemsOfCosidotapablanda']); $routes->post('menuitems', 'Presupuestoadmin::menuItems', ['as' => 'menuItemsOfPresupuestoAdmin']);
}); });
$routes->resource('cosidotapablanda', ['namespace' => 'App\Controllers\Presupuestos', 'controller' => 'Cosidotapablanda', 'except' => 'show,new,create,update']); $routes->resource('presupuestoadmin', ['namespace' => 'App\Controllers\Presupuestos', 'controller' => 'Presupuestoadmin', 'except' => 'show,new,create,update']);
$routes->group('presupuestocliente', ['namespace' => 'App\Controllers\Presupuestos'], function ($routes) { $routes->group('presupuestocliente', ['namespace' => 'App\Controllers\Presupuestos'], function ($routes) {
$routes->get('list', 'Presupuestocliente::list', ['as' => 'listaPresupuestos']); $routes->get('list', 'Presupuestocliente::list', ['as' => 'listaPresupuestos']);
@ -586,6 +584,7 @@ $routes->group('presupuestocliente', ['namespace' => 'App\Controllers\Presupuest
$routes->get('cargar/(:num)', 'Presupuestocliente::cargar/$1', ['as' => 'cargarPresupuesto']); $routes->get('cargar/(:num)', 'Presupuestocliente::cargar/$1', ['as' => 'cargarPresupuesto']);
$routes->post('duplicarPresupuesto', 'Presupuestocliente::duplicarPresupuesto', ['as' => 'duplicarPresupuesto']); $routes->post('duplicarPresupuesto', 'Presupuestocliente::duplicarPresupuesto', ['as' => 'duplicarPresupuesto']);
$routes->post('calcular', 'Presupuestocliente::calcular', ['as' => 'calcularPresupuesto']); $routes->post('calcular', 'Presupuestocliente::calcular', ['as' => 'calcularPresupuesto']);
$routes->post('calcularsolapas', 'Presupuestocliente::calcularMaxSolapas', ['as' => 'calcularSolapas']);
}); });
$routes->resource('presupuestocliente', ['namespace' => 'App\Controllers\Presupuestos', 'controller' => 'Presupuestocliente', 'except' => 'show,new,create,update']); $routes->resource('presupuestocliente', ['namespace' => 'App\Controllers\Presupuestos', 'controller' => 'Presupuestocliente', 'except' => 'show,new,create,update']);
@ -762,9 +761,36 @@ $routes->group('mensajes', ['namespace' => 'App\Controllers\Mensajeria'], functi
$routes->get('delete/(:num)', 'TarifaAcabados::delete/$1', ['as' => 'tarifaAcabadoDelete']); $routes->get('delete/(:num)', 'TarifaAcabados::delete/$1', ['as' => 'tarifaAcabadoDelete']);
$routes->post('datatable', 'TarifaAcabados::datatable', ['as' => 'tarifaAcabadoDT']);*/ $routes->post('datatable', 'TarifaAcabados::datatable', ['as' => 'tarifaAcabadoDT']);*/
}); });
});
$routes->group('messages', ['namespace' => 'App\Controllers\Chat'], function ($routes) {
$routes->get('datatable', 'ChatController::datatable_messages', ['as' => 'getDatatableMessages']);
$routes->get('datatable/presupuesto', 'ChatController::datatable_presupuesto_messages', ['as' => 'getDatatablePresupuestoMessages']);
$routes->get('datatable/pedido', 'ChatController::datatable_pedido_messages', ['as' => 'getDatatablePedidoMessages']);
$routes->get('datatable/factura', 'ChatController::datatable_factura_messages', ['as' => 'getDatatableFacturaMessages']);
$routes->post('direct', 'ChatController::store_new_direct_message', ['as' => 'storeNewDirectMessage']);
$routes->post('direct/client', 'ChatController::store_new_direct_message_client', ['as' => 'storeNewDirectMessageClient']);
}); });
$routes->group('chat', ['namespace' => 'App\Controllers\Chat'], function ($routes) { $routes->group('chat', ['namespace' => 'App\Controllers\Chat'], function ($routes) {
$routes->get('direct/(:num)', 'ChatController::get_chat_direct_view/$1', ['as' => 'getChatDirectView']);
$routes->get('presupuesto/(:num)', 'ChatController::get_chat_presupuesto_view/$1', ['as' => 'getChatPresupuestoView']);
$routes->get('pedido/(:num)', 'ChatController::get_chat_pedido_view/$1', ['as' => 'getChatPedidoView']);
$routes->get('factura/(:num)', 'ChatController::get_chat_factura_view/$1', ['as' => 'getChatFacturaView']);
$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/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']);
$routes->post('direct/messages/(:num)', 'ChatController::store_chat_direct_message/$1', ['as' => 'storeChatDirectMessages']);
$routes->post('direct/messages/unread/(:num)', 'ChatController::update_chat_direct_message_unread/$1', ['as' => 'updateChatDirectMessageUnread']);
$routes->get('departments', 'ChatController::get_chat_departments', ['as' => 'getChatDepartments']); $routes->get('departments', 'ChatController::get_chat_departments', ['as' => 'getChatDepartments']);
$routes->get('departments/select', 'ChatController::get_chat_department_select', ['as' => 'getChatDepartmentSelect']);
$routes->get('department/presupuesto/(:num)/(:num)', 'ChatController::get_chat_presupuesto/$1/$2', ['as' => 'getChatPresupuesto']); $routes->get('department/presupuesto/(:num)/(:num)', 'ChatController::get_chat_presupuesto/$1/$2', ['as' => 'getChatPresupuesto']);
$routes->get('department/pedido/(:num)/(:num)', 'ChatController::get_chat_pedido/$1/$2', ['as' => 'getChatPedido']); $routes->get('department/pedido/(:num)/(:num)', 'ChatController::get_chat_pedido/$1/$2', ['as' => 'getChatPedido']);
$routes->get('department/factura/(:num)/(:num)', 'ChatController::get_chat_factura/$1/$2', ['as' => 'getChatFactura']); $routes->get('department/factura/(:num)/(:num)', 'ChatController::get_chat_factura/$1/$2', ['as' => 'getChatFactura']);
@ -781,6 +807,8 @@ $routes->group('chat', ['namespace' => 'App\Controllers\Chat'], function ($route
$routes->get('contact/(:num)/messages', 'ChatController::get_chat_internal_messages/$1', ['as' => 'getChatInternalMessages']); $routes->get('contact/(:num)/messages', 'ChatController::get_chat_internal_messages/$1', ['as' => 'getChatInternalMessages']);
$routes->get('notifications', 'ChatController::get_chat_cliente/$1', ['as' => 'getChatCliente']); $routes->get('notifications', 'ChatController::get_chat_cliente/$1', ['as' => 'getChatCliente']);
$routes->get('users/internal', 'ChatController::get_chat_users_internal', ['as' => 'getChatUsersInternal']); $routes->get('users/internal', 'ChatController::get_chat_users_internal', ['as' => 'getChatUsersInternal']);
$routes->get('users/all', 'ChatController::get_chat_users_all', ['as' => 'getChatUsersAll']);
$routes->post('hebra/presupuesto', 'ChatController::store_hebra_presupuesto', ['as' => 'storeHebraPresupuesto']); $routes->post('hebra/presupuesto', 'ChatController::store_hebra_presupuesto', ['as' => 'storeHebraPresupuesto']);
$routes->post('hebra/pedido', 'ChatController::store_hebra_pedido', ['as' => 'storeHebraPedido']); $routes->post('hebra/pedido', 'ChatController::store_hebra_pedido', ['as' => 'storeHebraPedido']);
$routes->post('hebra/factura', 'ChatController::store_hebra_factura', ['as' => 'storeHebraFactura']); $routes->post('hebra/factura', 'ChatController::store_hebra_factura', ['as' => 'storeHebraFactura']);

View File

@ -34,7 +34,7 @@ class Validation extends BaseConfig
* @var array<string, string> * @var array<string, string>
*/ */
public array $templates = [ public array $templates = [
'list' => 'CodeIgniter\Validation\Views\list', 'list' => 'CodeIgniter\Validation\Views\list',
'single' => 'CodeIgniter\Validation\Views\single', 'single' => 'CodeIgniter\Validation\Views\single',
'bootstrap_style' => 'themes/_commonPartialsBs/_form_validation_errors', 'bootstrap_style' => 'themes/_commonPartialsBs/_form_validation_errors',
]; ];
@ -42,4 +42,6 @@ class Validation extends BaseConfig
// -------------------------------------------------------------------- // --------------------------------------------------------------------
// Rules // Rules
// -------------------------------------------------------------------- // --------------------------------------------------------------------
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,27 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class CheckWebClientesPapeles extends Migration
{
public function up()
{
$fields = [
'show_in_client' => [
'type' => 'TINYINT',
'constraint' => 1,
'null' => false,
'default' => 0,
],
];
$this->forge->addColumn('lg_papel_impresion', $fields);
}
public function down()
{
$this->forge->dropColumn('lg_papel_impresion', 'show_in_client');
}
}

View File

@ -0,0 +1,37 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class ModifyNullableComercialSoporte extends Migration
{
public function up()
{
$this->forge->modifyColumn('clientes', [
'comercial_id' => [
'type' => 'int(10) unsigned',
'null' => true, // Permitir valores NULL
],
'soporte_id' => [
'type' => 'int(10) unsigned',
'null' => true, // Permitir valores NULL
],
]);
}
public function down()
{
$this->forge->modifyColumn('clientes', [
'comercial_id' => [
'type' => 'int(10) unsigned',
'null' => false,
],
'soporte_id' => [
'type' => 'int(10) unsigned',
'null' => false,
],
]);
}
}

View File

@ -0,0 +1,40 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class TicksPapeles extends Migration
{
public function up()
{
$fields = [
'show_in_client_special' => [
'type' => 'TINYINT',
'constraint' => 1,
'null' => false,
'default' => 0,
],
];
$this->forge->addColumn('lg_papel_generico', $fields);
$fields = [
'show_in_client_special' => [
'type' => 'TINYINT',
'constraint' => 1,
'null' => false,
'default' => 0,
],
];
$this->forge->addColumn('lg_papel_impresion', $fields);
}
public function down()
{
$this->forge->dropColumn('lg_papel_generico', 'show_in_client_special');
$this->forge->dropColumn('lg_papel_impresion', 'show_in_client_special');
}
}

View File

@ -0,0 +1,46 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class CambiarTicksPapelImpresion extends Migration
{
public function up()
{
$fields = [
'use_in_client' => [
'type' => 'TINYINT',
'constraint' => 1,
'null' => false,
'default' => 0,
],
];
$this->forge->addColumn('lg_papel_impresion', $fields);
$this->forge->dropColumn('lg_papel_impresion', 'show_in_client');
$this->forge->dropColumn('lg_papel_impresion', 'show_in_client_special');
}
public function down()
{
$fields = [
'show_in_client_special' => [
'type' => 'TINYINT',
'constraint' => 1,
'null' => false,
'default' => 0,
],
'show_in_client' => [
'type' => 'TINYINT',
'constraint' => 1,
'null' => false,
'default' => 0,
],
];
$this->forge->addColumn('lg_papel_impresion', $fields);
$this->forge->dropColumn('lg_papel_impresion', 'use_in_client');
}
}

View File

@ -0,0 +1,26 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class AddTickInteriorPapelImpresion extends Migration
{
public function up()
{
$fields = [
'interior' => [
'type' => 'TINYINT',
'constraint' => 1,
'null' => false,
'default' => 0,
],
];
$this->forge->addColumn('lg_papel_impresion', $fields);
}
public function down()
{
$this->forge->dropColumn('lg_papel_impresion', 'interior');
}
}

View File

@ -0,0 +1,27 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class AddTickTapaDuraPapelImp extends Migration
{
public function up()
{
$fields = [
'use_for_tapa_dura' => [
'type' => 'TINYINT',
'constraint' => 1,
'null' => false,
'default' => 0,
],
];
$this->forge->addColumn('lg_papel_impresion', $fields);
}
public function down()
{
$this->forge->dropColumn('lg_papel_impresion', 'use_for_tapa_dura');
}
}

View File

@ -0,0 +1,52 @@
<?php
namespace App\Database\Seeds;
use App\Models\Chat\ChatDeparmentModel;
use App\Models\Chat\ChatDeparmentUserModel;
use App\Models\Chat\ChatMessageModel;
use App\Models\Chat\ChatModel;
use App\Models\ChatNotification;
use CodeIgniter\Database\Seeder;
use App\Models\Usuarios\UserModel;
class MessageSeeder extends Seeder
{
public function run()
{
$data = [
"title" => "Message Test",
"messages" => [
[
"sender_id" => 1,
"receiver_id" => 127,
],
[
"sender_id" => 127,
"receiver_id" => 1,
]
]
];
$chatModel = model(ChatModel::class);
$chatMessageModel = model(ChatMessageModel::class);
$chatNotificationModel = model(ChatNotification::class);
$userModel = model(UserModel::class);
foreach (range(1,100) as $key => $value) {
$chat_id = $chatModel->insert(["title" => $data["title"]." ".$value]);
foreach ($data["messages"] as $key => $value) {
$first_name = $userModel->find($value["receiver_id"])?->first_name;
$chat_message_id = $chatMessageModel->insert([
"chat_id" => $chat_id,
"sender_id" => $value["sender_id"],
"receiver_id" => $value["receiver_id"],
"message" => "Hola"." ".$first_name
]);
$chatNotificationModel->insert([
"chat_message_id" => $chat_message_id,
"user_id" => $value["receiver_id"]
]);
}
}
}
}

View File

@ -10,13 +10,15 @@ class PapelGenerico extends \CodeIgniter\Entity\Entity
"nombre" => null, "nombre" => null,
"code" => null, "code" => null,
"code_ot" => null, "code_ot" => null,
"show_in_client" => true, "show_in_client" => false,
"show_in_client_special" => false,
"is_deleted" => 0, "is_deleted" => 0,
"created_at" => null, "created_at" => null,
"updated_at" => null, "updated_at" => null,
]; ];
protected $casts = [ protected $casts = [
"show_in_client" => "boolean", "show_in_client" => "boolean",
"show_in_client_special" => "boolean",
"is_deleted" => "int", "is_deleted" => "int",
]; ];
} }

View File

@ -15,6 +15,7 @@ class PapelImpresion extends \CodeIgniter\Entity\Entity
"espesor" => 0.0, "espesor" => 0.0,
"gramaje" => null, "gramaje" => null,
"precio_tonelada" => null, "precio_tonelada" => null,
"interior" => true,
"bn" => true, "bn" => true,
"color" => true, "color" => true,
"cubierta" => false, "cubierta" => false,
@ -22,6 +23,9 @@ class PapelImpresion extends \CodeIgniter\Entity\Entity
"guardas" => false, "guardas" => false,
"inkjet" => false, "inkjet" => false,
"rotativa" => false, "rotativa" => false,
"isActivo" => true,
"use_in_client" => false,
"use_for_tapa_dura" => false,
"is_deleted" => 0, "is_deleted" => 0,
"created_at" => null, "created_at" => null,
"updated_at" => null, "updated_at" => null,
@ -33,12 +37,16 @@ class PapelImpresion extends \CodeIgniter\Entity\Entity
"espesor" => "float", "espesor" => "float",
"gramaje" => "float", "gramaje" => "float",
"precio_tonelada" => "float", "precio_tonelada" => "float",
"interior" => "boolean",
"bn" => "boolean", "bn" => "boolean",
"color" => "boolean", "color" => "boolean",
"cubierta" => "boolean", "cubierta" => "boolean",
"sobrecubierta" => "boolean", "sobrecubierta" => "boolean",
"guardas" => "boolean", "guardas" => "boolean",
"rotativa" => "boolean", "rotativa" => "boolean",
"isActivo" => "boolean",
"use_in_client" => "boolean",
"use_for_tapa_dura" => "boolean",
"is_deleted" => "int", "is_deleted" => "int",
]; ];
} }

View File

@ -6,7 +6,7 @@ return [
'moduleTitleCosidoTB' => 'Budget for Softcover Stitched Book', 'moduleTitleCosidoTB' => 'Budget for Softcover Stitched Book',
'moduleTitleFresadoTB' => 'Budget for Softcover Milling Book', 'moduleTitleFresadoTB' => 'Budget for Softcover Milling Book',
'presupuestoCosidotapablandaList' => 'List of budgets for Softcover Stitched Books', 'presupuestoPresupuestoAdminList' => 'List of budgets for Softcover Stitched Books',
'presupuestoFresadotapablandaList' => 'List of budgets for Milling Stitched Books', 'presupuestoFresadotapablandaList' => 'List of budgets for Milling Stitched Books',
'presupuesto' => 'Budget', 'presupuesto' => 'Budget',
@ -51,7 +51,7 @@ return [
'merma' => 'Weakening', 'merma' => 'Weakening',
'mermacubierta' => 'Cover weakening', 'mermacubierta' => 'Cover weakening',
'tipoImpresion' => 'Printing type', 'tipoImpresion' => 'Printing type',
'papelesComparadorCosidoTapaBlanda' => 'Interior and cover papers', 'papelesComparadorPresupuestoAdmin' => 'Interior and cover papers',
'posicionPagColor' => 'Color pages position', 'posicionPagColor' => 'Color pages position',
'colorPageInstructions' => 'Enter the position of the color pages within the book. E.g., 3,5,7 or 4-10,20,155.', 'colorPageInstructions' => 'Enter the position of the color pages within the book. E.g., 3,5,7 or 4-10,20,155.',
'numeroPaginas' => 'Nº Pages', 'numeroPaginas' => 'Nº Pages',

View File

@ -15,7 +15,7 @@ return [
'createdAt' => 'Created At', 'createdAt' => 'Created At',
'dateBirth' => 'Date Birth', 'dateBirth' => 'Date Birth',
'email' => 'Email', 'email' => 'Email',
'emailConfirmed' => 'Email Confirmed', 'emailConfirmed' => 'Email Confirmed',
'firstName' => 'First Name', 'firstName' => 'First Name',
'group' => 'Group', 'group' => 'Group',
'idUser' => 'ID User', 'idUser' => 'ID User',

View File

@ -3,12 +3,30 @@
return [ return [
"chat" => "Mensajería", "chat" => "Mensajería",
"messages" => "Mensajes", "messages" => "Mensajes",
"message" => "Mensaje",
"modal" => [ "modal" => [
"new_hebra" => "Nueva hebra", "new_hebra" => "Nuevo hilo",
"title" => "Título", "title" => "Título",
"new_message" => "Nuevo mensaje", "new_message" => "Nuevo mensaje",
"new_receivers" => "Nuevos participantes", "new_receivers" => "Nuevos participantes",
"btn_send" => "Enviar", "btn_send" => "Enviar",
"btn_send_update" => "Enviar" "btn_send_update" => "Enviar"
] ],
"datatable_messages" => [
"created_at" => "Fecha creación",
"updated_at" => "Fecha actualización",
"title" => "Título",
"creator" => "Creador",
"viewed" => "Leído",
],
"new_message_ok" => "Mensaje enviado correctamente",
"participants" => "Participantes",
"choose_department" => "Elige un departamento",
"new_participant" => "Añadir nuevos participantes",
"write_message_placeholder" => "Escriba aquí su mensaje...",
"add_notification" => "Notificación",
"check_as_unviewed" => "Marcar como no leídos",
"add_notification_message" => "Envía a los usuarios añadidos una notificación con los mensajes presentes en el chat.",
"chat_title_presupuesto" => 'Presupuesto[{title,string,0}][{id}]'
]; ];

View File

@ -16,6 +16,7 @@ return [
'papelGenericoList' => 'Lista Papeles Genéricos', 'papelGenericoList' => 'Lista Papeles Genéricos',
'papelesGenericos' => 'Papeles Genéricos', 'papelesGenericos' => 'Papeles Genéricos',
'showInClient' => 'Mostrar en cliente', 'showInClient' => 'Mostrar en cliente',
'showInClientSpecial' => 'Papel especial cliente',
'updatedAt' => 'Actualizado el', 'updatedAt' => 'Actualizado el',
'form_acordion_title' => 'Propiedades Papel Genérico', 'form_acordion_title' => 'Propiedades Papel Genérico',

View File

@ -5,10 +5,12 @@
return [ return [
'alto' => 'Alto', 'alto' => 'Alto',
'ancho' => 'Ancho', 'ancho' => 'Ancho',
'interior' => 'Interior',
'bn' => 'B/N', 'bn' => 'B/N',
'color' => 'Color', 'color' => 'Color',
'createdAt' => 'Creado en', 'createdAt' => 'Creado en',
'cubierta' => 'Cubierta', 'cubierta' => 'Cubierta',
'use_for_tapa_dura' => 'Papel tapa dura',
'sobrecubierta' => 'Sobrecubierta', 'sobrecubierta' => 'Sobrecubierta',
'guardas' => 'Guardas', 'guardas' => 'Guardas',
'defecto' => 'Por defecto', 'defecto' => 'Por defecto',
@ -35,6 +37,7 @@ return [
'rotativa' => 'Rotativa', 'rotativa' => 'Rotativa',
'updatedAt' => 'Actualizado en', 'updatedAt' => 'Actualizado en',
'activo' => 'Activo?', 'activo' => 'Activo?',
'useInClient' => 'Usar en presup. cliente',
'userUpdateId' => 'ID usuario actualización', 'userUpdateId' => 'ID usuario actualización',
'consumo_tintas_rotativas' => 'Consumo tintas', 'consumo_tintas_rotativas' => 'Consumo tintas',

View File

@ -17,7 +17,7 @@ return [
'presupuestoFresadotapaduraList' => 'Lista presupuestos Libros Fresado Tapa Dura', 'presupuestoFresadotapaduraList' => 'Lista presupuestos Libros Fresado Tapa Dura',
'presupuestoFresadotapablandaList' => 'Lista presupuestos Libros Fresado Tapa Blanda', 'presupuestoFresadotapablandaList' => 'Lista presupuestos Libros Fresado Tapa Blanda',
'presupuestoCosidotapaduraList' => 'Lista presupuestos Libros Cosido Tapa Dura', 'presupuestoCosidotapaduraList' => 'Lista presupuestos Libros Cosido Tapa Dura',
'presupuestoCosidotapablandaList' => 'Lista presupuestos Libros Cosido Tapa Blanda', 'presupuestoPresupuestoAdminList' => 'Lista presupuestos Libros Cosido Tapa Blanda',
'presupuesto' => 'Presupuesto', 'presupuesto' => 'Presupuesto',
'presupuestos' => 'Presupuestos', 'presupuestos' => 'Presupuestos',
@ -80,7 +80,7 @@ return [
'merma' => 'Merma', 'merma' => 'Merma',
'mermacubierta' => 'Merma cubierta', 'mermacubierta' => 'Merma cubierta',
'tipoImpresion' => 'Tipo de impresión', 'tipoImpresion' => 'Tipo de impresión',
'papelesComparadorCosidoTapaBlanda' => 'Papeles interior y cubierta', 'papelesComparadorPresupuestoAdmin' => 'Papeles interior y cubierta',
'posicionPagColor' => 'Posición páginas a color', 'posicionPagColor' => 'Posición páginas a color',
'papelDiferente' => 'Papel color y negro diferente', 'papelDiferente' => 'Papel color y negro diferente',
'paginasColorConsecutivas' => 'Páginas color consecutivas', 'paginasColorConsecutivas' => 'Páginas color consecutivas',
@ -256,6 +256,7 @@ return [
// Placeholders // Placeholders
'formatoLibro' => "Formato libro", 'formatoLibro' => "Formato libro",
'selectCliente' => "Seleccione cliente", 'selectCliente' => "Seleccione cliente",
'selectPapel' => "Seleccione papel",
// Preview // Preview

View File

@ -19,6 +19,7 @@ return [
'adminRolTooltip' => 'Permitir acceso completo al sistema', 'adminRolTooltip' => 'Permitir acceso completo al sistema',
// System permissions // System permissions
'viewPermission' => 'Visualizar',
'createPermission' => 'Crear', 'createPermission' => 'Crear',
'editPermission' => 'Editar', 'editPermission' => 'Editar',
'deletePermission' => 'Eliminar', 'deletePermission' => 'Eliminar',
@ -30,6 +31,10 @@ return [
'direccionesSection' => 'Direcciones', 'direccionesSection' => 'Direcciones',
'presupuestoSection' => 'Presupuestos', 'presupuestoSection' => 'Presupuestos',
'presupuestoClienteSection' => 'Presupuestos', 'presupuestoClienteSection' => 'Presupuestos',
'pedidosActivosSection' => 'Activos',
'pedidosFinalizadosSection' => 'Finalizados',
'pedidosCanceladosSection' => 'Cancelados',
'pedidosTodosSection' => 'Todos',
'tarifaPreimpresionSection' => 'Tarifas de preimpresión', 'tarifaPreimpresionSection' => 'Tarifas de preimpresión',
'tarifaManipuladoSection' => 'Tarifas de manipulado', 'tarifaManipuladoSection' => 'Tarifas de manipulado',
'tarifaAcabadoSection' => 'Tarifas de acabado', 'tarifaAcabadoSection' => 'Tarifas de acabado',

View File

@ -10,7 +10,7 @@ class ChatDeparmentModel extends Model
protected $table = 'chat_departments'; protected $table = 'chat_departments';
protected $primaryKey = 'id'; protected $primaryKey = 'id';
protected $useAutoIncrement = true; protected $useAutoIncrement = true;
protected $returnType = 'array'; protected $returnType = 'object';
protected $useSoftDeletes = false; protected $useSoftDeletes = false;
protected $protectFields = true; protected $protectFields = true;
protected $allowedFields = [ protected $allowedFields = [
@ -53,9 +53,9 @@ class ChatDeparmentModel extends Model
public function getChatDepartments(string $type = "general"): array public function getChatDepartments(string $type = "general"): array
{ {
$userModel = model(UserModel::class); $userModel = model(UserModel::class);
$chatMessageModel = model(ChatMessageModel::class); $chatModel = model(ChatModel::class);
$query = $this->db->table('chat_departments') $query = $this->builder()
->select( ->select(
[ [
@ -63,7 +63,6 @@ class ChatDeparmentModel extends Model
'chat_departments.name', 'chat_departments.name',
'chat_departments.display', 'chat_departments.display',
'chat_department_users.user_id', 'chat_department_users.user_id',
'chats.id as chatId',
] ]
) )
->join( ->join(
@ -71,30 +70,26 @@ class ChatDeparmentModel extends Model
"chat_department_users.chat_department_id = chat_departments.id", "chat_department_users.chat_department_id = chat_departments.id",
'left' 'left'
) )
->join("chats", "chats.chat_department_id = chat_departments.id", "left")
->join( ->join(
"users", "users",
"chat_department_users.user_id = users.id", "chat_department_users.user_id = users.id",
'left' 'left'
)->join(
"chat_messages",
"chat_messages.chat_id = chats.id",
"left"
) )
->where("chat_departments.type", $type); ->where("chat_departments.type", $type);
if (auth()->user()->cliente_id == null) {
$query->where("chat_department_users.user_id", auth()->user()->id);
} // if (auth()->user()->cliente_id == null) {
// $query->where("chat_department_users.user_id", auth()->user()->id);
// }
$results = $query->get()->getResultArray(); $results = $query->get()->getResultArray();
// Create the desired structure // Create the desired structure
$departments = []; $departments = [];
foreach ($results as $row) { foreach ($results as $row) {
$departmentName = $row['name']; $departmentName = $row['name'];
// If the department is not yet added to the array, initialize it // If the department is not yet added to the array, initialize it
if (!isset($departments[$departmentName])) { if (!isset($departments[$departmentName])) {
$departments[$departmentName] = [ $departments[$departmentName] = [
'id' => $row['id'], 'id' => $row['id'],
'name' => $row['name'], 'name' => $row['name'],
@ -131,4 +126,21 @@ class ChatDeparmentModel extends Model
->get()->getResultObject(); ->get()->getResultObject();
return $result; return $result;
} }
public function getDisplay(int $chat_deparment_id) : string
{
return $this->find($chat_deparment_id)->display;
}
public function getChatDepartmentSelect(string $query = null)
{
$q = $this->builder()->select([
"id",
"display as name",
"description"
]);
if($query){
$q->orLike("display",$query)
->orLike("name",$query);
}
return $q;
}
} }

View File

@ -2,16 +2,18 @@
namespace App\Models\Chat; namespace App\Models\Chat;
use App\Models\ChatNotification;
use App\Models\Usuarios\UserModel; use App\Models\Usuarios\UserModel;
use CodeIgniter\Model; use CodeIgniter\Model;
use CodeIgniter\Database\BaseBuilder;
class ChatMessageModel extends Model class ChatMessageModel extends Model
{ {
protected $table = 'chat_messages'; protected $table = 'chat_messages';
protected $primaryKey = 'id'; protected $primaryKey = 'id';
protected $useAutoIncrement = true; protected $useAutoIncrement = true;
protected $returnType = 'array'; protected $returnType = 'object';
protected $useSoftDeletes = false; protected $useSoftDeletes = true;
protected $protectFields = true; protected $protectFields = true;
protected $allowedFields = [ protected $allowedFields = [
"message", "message",
@ -28,7 +30,7 @@ class ChatMessageModel extends Model
protected array $castHandlers = []; protected array $castHandlers = [];
// Dates // Dates
protected $useTimestamps = false; protected $useTimestamps = true;
protected $dateFormat = 'datetime'; protected $dateFormat = 'datetime';
protected $createdField = 'created_at'; protected $createdField = 'created_at';
protected $updatedField = 'updated_at'; protected $updatedField = 'updated_at';
@ -71,11 +73,30 @@ class ChatMessageModel extends Model
} }
return $messages; return $messages;
} }
public function get_chat_message(int $chat_message_id): object
{
$user = model(UserModel::class);
$auth_user = auth()->user();
$message = $this->find($chat_message_id);
$message->pos = $auth_user->id == $message->sender_id ? "right" : "left";
if ($auth_user->id == $message->sender_id) {
$message->sender_first_name = $auth_user->first_name;
$message->sender_last_name = $auth_user->last_name;
} else {
$sender_user = $user->find($message->sender_id);
$message->sender_first_name = $sender_user->first_name;
$message->sender_last_name = $sender_user->last_name;
}
return $message;
}
public function get_chat_contact_messages(int $receiver_id): array public function get_chat_contact_messages(int $receiver_id): array
{ {
$conversationArray = []; $conversationArray = [];
$userModel = model(UserModel::class); $userModel = model(UserModel::class);
$chatNotificationModel = model(ChatNotification::class);
$receiverUser = $userModel->find($receiver_id); $receiverUser = $userModel->find($receiver_id);
$chat_id = null;
$messagesFromClient = $this->builder() $messagesFromClient = $this->builder()
->where("sender_id", auth()->user()->id) ->where("sender_id", auth()->user()->id)
->where("receiver_id", $receiverUser->id) ->where("receiver_id", $receiverUser->id)
@ -95,7 +116,9 @@ class ChatMessageModel extends Model
$conversationArray[] = $message; $conversationArray[] = $message;
} }
$dates = array(); $dates = array();
foreach ($conversationArray as $key => $row) { foreach ($conversationArray as $key => $row) {
$chatNotificationModel->builder()->set("viewed", true)->where("chat_message_id", $row->id)->where("user_id", auth()->user()->id)->update();
$dates[$key] = strtotime($row->created_at); $dates[$key] = strtotime($row->created_at);
} }
array_multisort($dates, SORT_ASC, $conversationArray); array_multisort($dates, SORT_ASC, $conversationArray);
@ -110,11 +133,32 @@ class ChatMessageModel extends Model
->where("receiver_id", auth()->user()->id)->countAllResults(); ->where("receiver_id", auth()->user()->id)->countAllResults();
return $messagesFromReceiver; return $messagesFromReceiver;
} }
public function get_chat_department_messages_count(int $chat_id) : int
{
$chatDepartmentMessagesCount = $this->builder()
->where("id",$chat_id)
->countAllResults();
return $chatDepartmentMessagesCount;
}
public function get_chat_messages_count(int $sender_id): int
{
$messagesFromReceiver = $this->builder()
->groupStart()
->where("sender_id", $sender_id)
->where("receiver_id", auth()->user()->id)
->orGroupStart()
->where("receiver_id", $sender_id)
->where("sender_id", auth()->user()->id)
->groupEnd()
->groupEnd()
->countAllResults();
return $messagesFromReceiver;
}
public function set_chat_messages_as_read(int $sender_id): int public function set_chat_messages_as_read(int $sender_id): int
{ {
$messagesFromReceiver = $this->builder() $messagesFromReceiver = $this->builder()
->set("viewed", true) ->set("viewed", true)
->where("sender_id", $sender_id) ->where("user_id", $sender_id)
->where("receiver_id", auth()->user()->id)->update(); ->where("receiver_id", auth()->user()->id)->update();
return $messagesFromReceiver; return $messagesFromReceiver;
} }
@ -122,23 +166,32 @@ class ChatMessageModel extends Model
{ {
$chatDepartmentModel = model(ChatDeparmentModel::class); $chatDepartmentModel = model(ChatDeparmentModel::class);
$chatModel = model(ChatModel::class); $chatModel = model(ChatModel::class);
$messagesFromReceiver = 0;
if(auth()->user()->cliente_id){ $auth_user = auth()->user();
$chat_department_id = $chatModel->find($chat_id)->chat_department_id;
$users_in_chat = array_map(fn($x) => $x->id, $chatDepartmentModel->getChatDepartmentUsers($chat_department_id));
if (auth()->user()->cliente_id) {
// Si el usuario es cliente, marca como leídos todos los mensajes exceptos los suyos
$messagesFromReceiver = $this->builder() $messagesFromReceiver = $this->builder()
->set("viewed", true) ->set("viewed", true)
->where("chat_id", $chat_id) ->where("chat_id", $chat_id)
->whereNotIn("sender_id", [auth()->user()->id])->update(); ->whereNotIn("sender_id", [$auth_user->id])->update();
}else{ } else {
$chat_department_id = $chatModel->find($chat_id)->chat_department_id; // Si el usuario no es cliente y está dentro de los usuarios de departamento
$users_in_chat = array_map(fn($x) => $x->id, $chatDepartmentModel->getChatDepartmentUsers($chat_department_id)); // marca como leido todos los mensajes, excepto los mensajes de los usuarios
$messagesFromReceiver = $this->builder() // de dentro del departamento
->set("viewed", true) if (in_array($auth_user->id, $users_in_chat) == true) {
->where("chat_id", $chat_id) // if (($key = array_search($auth_user->id, $users_in_chat)) !== false) {
->whereNotIn("sender_id", $users_in_chat) // unset($users_in_chat[$key]);
->update(); // }
$messagesFromReceiver = $this->builder()
->set("viewed", true)
->where("chat_id", $chat_id)
->whereNotIn("sender_id", $users_in_chat)
->update();
}
} }
return $messagesFromReceiver; return $messagesFromReceiver;
} }
} }

File diff suppressed because it is too large Load Diff

View File

@ -47,4 +47,16 @@ class ChatNotification extends Model
protected $afterFind = []; protected $afterFind = [];
protected $beforeDelete = []; protected $beforeDelete = [];
protected $afterDelete = []; protected $afterDelete = [];
public function isChatMessageViewed(int $chat_message_id) : bool
{
$status = false;
$count = $this->where("chat_message_id",$chat_message_id)->where("viewed",false)->countAllResults();
if($count>0){
$status = false;
}else{
$status = true;
}
return $status;
}
} }

View File

@ -10,7 +10,7 @@ class ChatUser extends Model
protected $primaryKey = 'id'; protected $primaryKey = 'id';
protected $useAutoIncrement = true; protected $useAutoIncrement = true;
protected $returnType = 'array'; protected $returnType = 'array';
protected $useSoftDeletes = false; protected $useSoftDeletes = true;
protected $protectFields = true; protected $protectFields = true;
protected $allowedFields = [ protected $allowedFields = [
"user_id", "user_id",
@ -24,7 +24,7 @@ class ChatUser extends Model
protected array $castHandlers = []; protected array $castHandlers = [];
// Dates // Dates
protected $useTimestamps = false; protected $useTimestamps = true;
protected $dateFormat = 'datetime'; protected $dateFormat = 'datetime';
protected $createdField = 'created_at'; protected $createdField = 'created_at';
protected $updatedField = 'updated_at'; protected $updatedField = 'updated_at';
@ -46,4 +46,12 @@ class ChatUser extends Model
protected $afterFind = []; protected $afterFind = [];
protected $beforeDelete = []; protected $beforeDelete = [];
protected $afterDelete = []; protected $afterDelete = [];
public function getChatUserArrayId(int $chat_id) : array
{
$queryResult = $this->builder()
->select(['chat_users.user_id'])
->where("chat_users.chat_id",$chat_id)
->get()->getResultObject();
return array_map(fn($q) => $q->user_id,$queryResult);
}
} }

View File

@ -19,9 +19,10 @@ class PapelGenericoModel extends \App\Models\BaseModel
1 => "t1.code", 1 => "t1.code",
2 => "t1.code_ot", 2 => "t1.code_ot",
3 => "t1.show_in_client", 3 => "t1.show_in_client",
4 => "t1.show_in_client_special",
]; ];
protected $allowedFields = ["nombre", "code", "code_ot", "show_in_client", "deleted_at", "is_deleted"]; protected $allowedFields = ["nombre", "code", "code_ot", "show_in_client", "show_in_client_special", "deleted_at", "is_deleted"];
protected $returnType = "App\Entities\Configuracion\PapelGenerico"; protected $returnType = "App\Entities\Configuracion\PapelGenerico";
protected $useTimestamps = true; protected $useTimestamps = true;
@ -62,7 +63,8 @@ class PapelGenericoModel extends \App\Models\BaseModel
]; ];
public function getIdFromCode(string $code=""){ public function getIdFromCode(string $code = "")
{
$builder = $this->db $builder = $this->db
->table($this->table . " t1") ->table($this->table . " t1")
->select( ->select(
@ -77,7 +79,8 @@ class PapelGenericoModel extends \App\Models\BaseModel
} }
public function getCodeFromId($id=0){ public function getCodeFromId($id = 0)
{
$builder = $this->db $builder = $this->db
->table($this->table . " t1") ->table($this->table . " t1")
->select( ->select(
@ -104,23 +107,24 @@ class PapelGenericoModel extends \App\Models\BaseModel
$builder = $this->db $builder = $this->db
->table($this->table . " t1") ->table($this->table . " t1")
->select( ->select(
"t1.id AS id, t1.nombre AS nombre, t1.code AS code, t1.code_ot AS code_ot, t1.show_in_client AS show_in_client" "t1.id AS id, t1.nombre AS nombre, t1.code AS code, t1.code_ot AS code_ot,
t1.show_in_client AS show_in_client, t1.show_in_client_special AS show_in_client_special"
) )
->where("is_deleted", 0); ->where("is_deleted", 0);
return empty($search) return empty($search)
? $builder ? $builder
: $builder : $builder
->groupStart() ->groupStart()
->like("t1.id", $search) ->like("t1.id", $search)
->orLike("t1.nombre", $search) ->orLike("t1.nombre", $search)
->orLike("t1.code", $search) ->orLike("t1.code", $search)
->orLike("t1.code_ot", $search) ->orLike("t1.code_ot", $search)
->orLike("t1.id", $search) ->orLike("t1.id", $search)
->orLike("t1.nombre", $search) ->orLike("t1.nombre", $search)
->orLike("t1.code", $search) ->orLike("t1.code", $search)
->orLike("t1.code_ot", $search) ->orLike("t1.code_ot", $search)
->groupEnd(); ->groupEnd();
} }
@ -128,9 +132,9 @@ class PapelGenericoModel extends \App\Models\BaseModel
{ {
/* /*
1.-> Tipo impresion 1.-> Tipo impresion
2.-> Maquina 2.-> Maquina
3.-> Papeles impresion asociados a esa maquina 3.-> Papeles impresion asociados a esa maquina
4.-> papeles genericos que aparecen en esos papeles impresion 4.-> papeles genericos que aparecen en esos papeles impresion
*/ */
$builder = $this->db $builder = $this->db
->table($this->table . " t1") ->table($this->table . " t1")
@ -153,48 +157,48 @@ class PapelGenericoModel extends \App\Models\BaseModel
->where("t5.is_deleted", 0) ->where("t5.is_deleted", 0)
->where("t5.tipo", $tipo); ->where("t5.tipo", $tipo);
if($is_cubierta==true){ if ($is_cubierta == true) {
$builder->where("t2.cubierta", 1);
$builder->where("t5.uso", 'cubierta');
}
if($is_sobrecubierta==true){
$builder->where("t2.sobrecubierta", 1);
$builder->where("t5.uso", 'sobrecubierta');
}
if($is_cubierta==false && $is_sobrecubierta==false){ $builder->where("t2.cubierta", 1);
$builder->where("t5.uso", 'interior'); $builder->where("t5.uso", 'cubierta');
} }
if($is_guardas==true){ if ($is_sobrecubierta == true) {
$builder->where("t2.guardas", 1); $builder->where("t2.sobrecubierta", 1);
} $builder->where("t5.uso", 'sobrecubierta');
}
if($rotativa==true){ if ($is_cubierta == false && $is_sobrecubierta == false) {
$builder->where("t2.rotativa", 1); $builder->where("t5.uso", 'interior');
} }
if($mostrar_cliente!=null){ if ($is_guardas == true) {
$builder->where("t1.show_in_client", $mostrar_cliente); $builder->where("t2.guardas", 1);
} }
if ($rotativa == true) {
$builder->where("t2.rotativa", 1);
}
if ($mostrar_cliente != null) {
$builder->where("t1.show_in_client", $mostrar_cliente);
}
$data = $builder->orderBy("t1.nombre", "asc")->get()->getResultObject(); $data = $builder->orderBy("t1.nombre", "asc")->get()->getResultObject();
//var_dump($this->db->getLastQuery()); //var_dump($this->db->getLastQuery());
return $data; return $data;
} }
public function getGramajeComparador(string $papel_generico_nombre="", $uso="", $ejemplares=0) public function getGramajeComparador(string $papel_generico_nombre = "", $uso = "", $ejemplares = 0)
{ {
if($uso == 'cubierta' || $uso == 'sobrecubierta') if ($uso == 'cubierta' || $uso == 'sobrecubierta')
$tipo = 'colorhq'; $tipo = 'colorhq';
else else
$tipo=$uso; // color y colorhq valen para los dos $tipo = $uso; // color y colorhq valen para los dos
if($uso == 'bn') if ($uso == 'bn')
$tipo="negro"; $tipo = "negro";
if($uso == 'bnhq') if ($uso == 'bnhq')
$tipo="negrohq"; $tipo = "negrohq";
$builder = $this->db $builder = $this->db
->table($this->table . " t1") ->table($this->table . " t1")
@ -205,7 +209,7 @@ class PapelGenericoModel extends \App\Models\BaseModel
->join("lg_maquina_papel_impresion t3", "t3.papel_impresion_id = t2.id", "left") ->join("lg_maquina_papel_impresion t3", "t3.papel_impresion_id = t2.id", "left")
->join("lg_maquinas t4", "t3.maquina_id = t4.id", "left") ->join("lg_maquinas t4", "t3.maquina_id = t4.id", "left")
->join("lg_maquinas_tarifas_impresion t5", "t5.maquina_id = t4.id", "left") ->join("lg_maquinas_tarifas_impresion t5", "t5.maquina_id = t4.id", "left")
->where("t1.is_deleted", 0) ->where("t1.is_deleted", 0)
->where("t2.is_deleted", 0) ->where("t2.is_deleted", 0)
->where("t2.isActivo", 1) ->where("t2.isActivo", 1)
@ -214,44 +218,43 @@ class PapelGenericoModel extends \App\Models\BaseModel
->where("t4.tipo", "impresion") ->where("t4.tipo", "impresion")
->where("t5.tipo", $tipo) ->where("t5.tipo", $tipo)
->where("t1.nombre", $papel_generico_nombre); ->where("t1.nombre", $papel_generico_nombre);
$uso_tarifa = 'interior';
if($uso == 'bn' || $uso == 'bnhq') $uso_tarifa = 'interior';
$builder->where("t2.bn", 1);
else if ($uso == 'color' || $uso == 'colorhq')
$builder->where("t2.color", 1);
else if ($uso == 'cubierta'){
$uso_tarifa = 'cubierta';
$builder->where("t2.cubierta", 1);
}
else if ($uso == 'sobrecubierta'){
$uso_tarifa = 'sobrecubierta';
$builder->where("t2.sobrecubierta", 1);
}
$builder->where("t5.uso", $uso_tarifa); if ($uso == 'bn' || $uso == 'bnhq')
$builder->where("t2.bn", 1);
else if ($uso == 'color' || $uso == 'colorhq')
$builder->where("t2.color", 1);
else if ($uso == 'cubierta') {
$uso_tarifa = 'cubierta';
$builder->where("t2.cubierta", 1);
} else if ($uso == 'sobrecubierta') {
$uso_tarifa = 'sobrecubierta';
$builder->where("t2.sobrecubierta", 1);
}
$builder->where("t4.min <=", $ejemplares); $builder->where("t5.uso", $uso_tarifa);
$builder->where("t4.max >=", $ejemplares);
$builder->where("t4.min <=", $ejemplares);
$values = $builder->orderBy("t2.gramaje", "asc")->get()->getResultObject(); $builder->where("t4.max >=", $ejemplares);
$id = 1;
foreach ($values as $value){ $values = $builder->orderBy("t2.gramaje", "asc")->get()->getResultObject();
$value->id = $id; $id = 1;
$id++; foreach ($values as $value) {
} $value->id = $id;
$values_array = array_map( function( $value ) { $id++;
return $value->text; }
}, $values ); $values_array = array_map(function ($value) {
$unique_values = array_unique($values_array); return $value->text;
return array_values(array_intersect_key($values, $unique_values)); }, $values);
$unique_values = array_unique($values_array);
return array_values(array_intersect_key($values, $unique_values));
} }
//tipo: negro, negrohq, color, colorhq //tipo: negro, negrohq, color, colorhq
//uso: interior, rotativa, cubierta, sobrecubierta //uso: interior, rotativa, cubierta, sobrecubierta
public function getGramajeLineasPresupuesto($papel_generico_id=0, $tipo="", $uso="") public function getGramajeLineasPresupuesto($papel_generico_id = 0, $tipo = "", $uso = "")
{ {
$builder = $this->db $builder = $this->db
->table($this->table . " t1") ->table($this->table . " t1")
@ -262,7 +265,7 @@ class PapelGenericoModel extends \App\Models\BaseModel
->join("lg_maquina_papel_impresion t3", "t3.papel_impresion_id = t2.id", "left") ->join("lg_maquina_papel_impresion t3", "t3.papel_impresion_id = t2.id", "left")
->join("lg_maquinas t4", "t3.maquina_id = t4.id", "left") ->join("lg_maquinas t4", "t3.maquina_id = t4.id", "left")
->join("lg_maquinas_tarifas_impresion t5", "t5.maquina_id = t4.id", "left") ->join("lg_maquinas_tarifas_impresion t5", "t5.maquina_id = t4.id", "left")
->where("t1.is_deleted", 0) ->where("t1.is_deleted", 0)
->where("t2.is_deleted", 0) ->where("t2.is_deleted", 0)
->where("t2.isActivo", 1) ->where("t2.isActivo", 1)
@ -272,42 +275,142 @@ class PapelGenericoModel extends \App\Models\BaseModel
->where("t5.tipo", $tipo) ->where("t5.tipo", $tipo)
->where("t1.id", $papel_generico_id); ->where("t1.id", $papel_generico_id);
$uso_tarifa = 'interior'; $uso_tarifa = 'interior';
if ($uso == 'cubierta'){ if ($uso == 'cubierta') {
$uso_tarifa = 'cubierta'; $uso_tarifa = 'cubierta';
$builder->where("t2.cubierta", 1); $builder->where("t2.cubierta", 1);
} } else if ($uso == 'sobrecubierta') {
else if ($uso == 'sobrecubierta'){ $uso_tarifa = 'sobrecubierta';
$uso_tarifa = 'sobrecubierta'; $builder->where("t2.sobrecubierta", 1);
$builder->where("t2.sobrecubierta", 1); } else {
} if ($tipo == 'negro' || $tipo == 'negrohq')
else{ $builder->where("t2.bn", 1);
if($tipo == 'negro' || $tipo == 'negrohq') else if ($tipo == 'color' || $tipo == 'colorhq')
$builder->where("t2.bn", 1); $builder->where("t2.color", 1);
else if ($tipo == 'color' || $tipo == 'colorhq') }
$builder->where("t2.color", 1);
}
if($uso=='rotativa')
$builder->where("t2.rotativa", 1);
else
$builder->where("t2.rotativa", 0);
$builder->where("t5.uso", $uso_tarifa); if ($uso == 'rotativa')
$builder->where("t2.rotativa", 1);
else
$values = $builder->orderBy("t2.gramaje", "asc")->get()->getResultObject(); $builder->where("t2.rotativa", 0);
$id = 1;
foreach ($values as $value){ $builder->where("t5.uso", $uso_tarifa);
$value->id = $id;
$id++;
} $values = $builder->orderBy("t2.gramaje", "asc")->get()->getResultObject();
$values_array = array_map( function( $value ) { $id = 1;
return $value->text; foreach ($values as $value) {
}, $values ); $value->id = $id;
$unique_values = array_unique($values_array); $id++;
return array_values(array_intersect_key($values, $unique_values)); }
$values_array = array_map(function ($value) {
return $value->text;
}, $values);
$unique_values = array_unique($values_array);
return array_values(array_intersect_key($values, $unique_values));
} }
public function getPapelCliente($tipo, $is_cubierta = false, $selected_papel_id = null, $tapa_dura = null, $papel_especial = false)
{
/*
1.-> Tipo impresion
2.-> Maquina
3.-> Papeles impresion asociados a esa maquina
4.-> papeles genericos que aparecen en esos papeles impresion
*/
if ($selected_papel_id != null) {
$builder = $this->db
->table($this->table . " t1")
->select(
"t2.gramaje as gramaje",
// for debug, t2.nombre AS nombre_papel_impresion, t4.nombre AS maquina_nombre, t5.uso AS tarifa_uso, t5.tipo AS tarifa_tipo"
)
->join("lg_papel_impresion t2", "t2.papel_generico_id = t1.id", "inner")
->join("lg_maquina_papel_impresion t3", "t3.papel_impresion_id = t2.id", "inner")
->join("lg_maquinas t4", "t3.maquina_id = t4.id", "inner")
->join("lg_maquinas_tarifas_impresion t5", "t5.maquina_id = t4.id", "inner")
->where("t1.id", $selected_papel_id)
->where("t1.is_deleted", 0)
->where("t1.show_in_client", 1)
->where("t2.is_deleted", 0)
->where("t2.isActivo", 1)
->where("t2.use_in_client", 1)
->where("t3.active", 1)
->where("t4.is_deleted", 0)
->where("t4.tipo", "impresion")
->where("t5.is_deleted", 0)
->where("t5.tipo", $tipo)
->distinct('t2.gramaje');
} else {
$builder = $this->db
->table($this->table . " t1")
->select(
"t1.id as id, t1.nombre AS nombre",
// for debug, t2.nombre AS nombre_papel_impresion, t4.nombre AS maquina_nombre, t5.uso AS tarifa_uso, t5.tipo AS tarifa_tipo"
)
->join("lg_papel_impresion t2", "t2.papel_generico_id = t1.id", "inner")
->join("lg_maquina_papel_impresion t3", "t3.papel_impresion_id = t2.id", "inner")
->join("lg_maquinas t4", "t3.maquina_id = t4.id", "inner")
->join("lg_maquinas_tarifas_impresion t5", "t5.maquina_id = t4.id", "inner")
->where("t1.is_deleted", 0)
->where("t1.show_in_client", 1)
->where("t2.is_deleted", 0)
->where("t2.isActivo", 1)
->where("t2.use_in_client", 1)
->where("t3.active", 1)
->where("t4.is_deleted", 0)
->where("t4.tipo", "impresion")
->where("t5.is_deleted", 0)
->where("t5.tipo", $tipo)
->distinct('t1.id');
}
// Validación adicional para asegurar que t1.id esté presente en las combinaciones con t3.active = 1
$builder->whereIn("t1.id", function ($subQuery) {
$subQuery->select("t1_inner.id")
->from("lg_papel_generico t1_inner")
->join("lg_papel_impresion t2_inner", "t2_inner.papel_generico_id = t1_inner.id", "inner")
->join("lg_maquina_papel_impresion t3_inner", "t3_inner.papel_impresion_id = t2_inner.id", "inner")
->where("t3_inner.active", 1);
});
if ($is_cubierta == true) {
$builder->where("t2.cubierta", 1);
$builder->where("t5.uso", 'cubierta');
if($tapa_dura == true){
$builder->where("t2.use_for_tapa_dura", 1);
}
} else {
$builder->where("t2.interior", 1);
$builder->where("t5.uso", 'interior');
if ($tipo == 'negro' || $tipo == 'negrohq')
$builder->where("t2.bn", 1);
else if ($tipo == 'color' || $tipo == 'colorhq')
$builder->where("t2.color", 1);
}
if ($papel_especial == true) {
$builder->where("t1.show_in_client_special", 1);
}
else{
$builder->where("t1.show_in_client_special", 0);
}
if ($tipo == 'colorhq' || $tipo == 'negrohq') {
$builder->where("t2.rotativa", 0);
}
if ($selected_papel_id != null)
$data = $builder->orderBy("t2.gramaje", "asc")->get()->getResultObject();
else
$data = $builder->orderBy("t1.nombre", "asc")->get()->getResultObject();
//$query = $this->db->getLastQuery();
return $data;
}
} }

View File

@ -16,14 +16,17 @@ class PapelImpresionModel extends \App\Models\BaseModel
0 => "t1.nombre", 0 => "t1.nombre",
1 => "t2.nombre", 1 => "t2.nombre",
2 => "t1.gramaje", 2 => "t1.gramaje",
3 => "t1.bn", 3 => "t1.interior",
4 => "t1.color", 4 => "t1.bn",
5 => "t1.cubierta", 5 => "t1.color",
6 => "t1.sobrecubierta", 6 => "t1.cubierta",
7 => "t1.guardas", 7 => "t1.use_for_tapa_dura",
8 => "t1.inkjet", 8 => "t1.sobrecubierta",
9 => "t1.rotativa", 9 => "t1.guardas",
10 => "t1.isActivo" 10 => "t1.inkjet",
11 => "t1.rotativa",
12 => "t1.isActivo",
13 => "t1.use_in_client",
]; ];
@ -36,6 +39,7 @@ class PapelImpresionModel extends \App\Models\BaseModel
"espesor", "espesor",
"gramaje", "gramaje",
"precio_tonelada", "precio_tonelada",
"interior",
"bn", "bn",
"color", "color",
"cubierta", "cubierta",
@ -44,6 +48,8 @@ class PapelImpresionModel extends \App\Models\BaseModel
"inkjet", "inkjet",
"rotativa", "rotativa",
"isActivo", "isActivo",
"use_in_client",
"use_for_tapa_dura",
"deleted_at", "deleted_at",
"is_deleted", "is_deleted",
"user_updated_id", "user_updated_id",
@ -141,23 +147,25 @@ class PapelImpresionModel extends \App\Models\BaseModel
* *
* @return \CodeIgniter\Database\BaseBuilder * @return \CodeIgniter\Database\BaseBuilder
*/ */
public function getResource(string $search = "", $generico_id=-1) public function getResource(string $search = "", $generico_id = -1)
{ {
$builder = $this->db $builder = $this->db
->table($this->table . " t1") ->table($this->table . " t1")
->select( ->select(
"t1.id AS id, t1.nombre AS nombre, t1.defecto AS defecto, t1.referencia AS referencia, t1.mano AS mano, "t1.id AS id, t1.nombre AS nombre, t1.defecto AS defecto, t1.referencia AS referencia, t1.mano AS mano,
t1.espesor AS espesor, t1.gramaje AS gramaje, t1.precio_tonelada AS precio_tonelada, t1.espesor AS espesor, t1.gramaje AS gramaje, t1.interior AS interior, t1.precio_tonelada AS precio_tonelada,
t1.bn AS bn, t1.color AS color, t1.cubierta AS cubierta, t1.sobrecubierta AS sobrecubierta, t1.guardas AS guardas, t1.bn AS bn, t1.color AS color, t1.cubierta AS cubierta, t1.use_for_tapa_dura AS use_for_tapa_dura,
t1.sobrecubierta AS sobrecubierta, t1.guardas AS guardas,
t1.inkjet AS inkjet, t1.rotativa AS rotativa, t1.inkjet AS inkjet, t1.rotativa AS rotativa,
t1.isActivo AS isActivo, t2.nombre AS papel_generico_id" t1.isActivo AS isActivo, t2.nombre AS papel_generico_id,
t1.use_in_client AS use_in_client"
); );
$builder->join("lg_papel_generico t2", "t1.papel_generico_id = t2.id", "left"); $builder->join("lg_papel_generico t2", "t1.papel_generico_id = t2.id", "left");
$builder->where("t1.is_deleted", 0); $builder->where("t1.is_deleted", 0);
$builder->where("t1.isActivo", 1); $builder->where("t1.isActivo", 1);
if($generico_id>0){ if ($generico_id > 0) {
$builder->where("t1.papel_generico_id", $generico_id); $builder->where("t1.papel_generico_id", $generico_id);
} }
return empty($search) return empty($search)
@ -177,29 +185,29 @@ class PapelImpresionModel extends \App\Models\BaseModel
$builder = $this->db $builder = $this->db
->table($this->table . " t1") ->table($this->table . " t1")
->select( ->select(
"'".$maquina_id."'". " as maquina_id, t1.id AS papel_impresion_id, '0' as active" "'" . $maquina_id . "'" . " as maquina_id, t1.id AS papel_impresion_id, '0' as active"
); );
$builder->where("t1.is_deleted", 0); $builder->where("t1.is_deleted", 0);
$builder->where("t1.isActivo", 1); $builder->where("t1.isActivo", 1);
$isFirst = true; $isFirst = true;
$where_str = ""; $where_str = "";
//Si hay tarifas... //Si hay tarifas...
if (!empty($tarifas)){ if (!empty($tarifas)) {
foreach ($tarifas as $tarifa){ foreach ($tarifas as $tarifa) {
if (!$isFirst) if (!$isFirst)
$where_str .= ' OR '; $where_str .= ' OR ';
else{ else {
$isFirst = false; $isFirst = false;
} }
if ($tarifa->uso == 'cubierta') if ($tarifa->uso == 'cubierta')
$where_str .= "`t1`.`cubierta`=1"; $where_str .= "`t1`.`cubierta`=1";
else if ($tarifa->uso == 'sobrecubierta') else if ($tarifa->uso == 'sobrecubierta')
$where_str .= "`t1`.`sobrecubierta`=1"; $where_str .= "`t1`.`sobrecubierta`=1";
else{ else {
if ($tarifa->tipo == 'negro' || $tarifa->tipo == 'negrohq') if ($tarifa->tipo == 'negro' || $tarifa->tipo == 'negrohq')
$where_str .= "`t1`.`bn`=1 "; $where_str .= "`t1`.`bn`=1 ";
else else
$where_str .= "`t1`.`color`=1 "; $where_str .= "`t1`.`color`=1 ";
} }
@ -207,11 +215,11 @@ class PapelImpresionModel extends \App\Models\BaseModel
$builder->where($where_str); $builder->where($where_str);
} }
// si no hay tarifas no hay que devolver nada // si no hay tarifas no hay que devolver nada
else{ else {
// Se pone una condicion que no se puede dar // Se pone una condicion que no se puede dar
$builder->where("t1.bn", 2); $builder->where("t1.bn", 2);
} }
return $builder; return $builder;
} }
@ -224,43 +232,45 @@ class PapelImpresionModel extends \App\Models\BaseModel
* *
* @return [type] * @return [type]
*/ */
public function getIdPapelesImpresionForPresupuesto($papel_generico_id = null, $gramaje = null, $options=[]){ public function getIdPapelesImpresionForPresupuesto($papel_generico_id = null, $gramaje = null, $options = [])
{
$bn = array_key_exists('bn', $options) ? $options['bn'] : null; $bn = array_key_exists('bn', $options) ? $options['bn'] : null;
$color = array_key_exists('color', $options)? $options['color'] : null; $color = array_key_exists('color', $options) ? $options['color'] : null;
$cubierta = array_key_exists('cubierta', $options)? $options['cubierta'] : null; $cubierta = array_key_exists('cubierta', $options) ? $options['cubierta'] : null;
$sobrecubierta = array_key_exists('sobrecubierta', $options)? $options['sobrecubierta'] : null; $sobrecubierta = array_key_exists('sobrecubierta', $options) ? $options['sobrecubierta'] : null;
$guardas = array_key_exists('guardas', $options)? $options['guardas'] : null; $guardas = array_key_exists('guardas', $options) ? $options['guardas'] : null;
$rotativa = array_key_exists('rotativa', $options)? $options['rotativa'] : null; $rotativa = array_key_exists('rotativa', $options) ? $options['rotativa'] : null;
$builder = $this->db $builder = $this->db
->table($this->table . " t1") ->table($this->table . " t1")
->distinct("t1.id") ->distinct("t1.id")
->select( ->select(
"t1.id AS id, t1.nombre AS nombre, t1.papel_generico_id AS papel_generico_id, "t1.id AS id, t1.nombre AS nombre, t1.papel_generico_id AS papel_generico_id,
t1.gramaje as gramaje, t1.espesor AS espesor, t1.precio_tonelada AS precio_tonelada, t1.rotativa AS rotativa"); t1.gramaje as gramaje, t1.espesor AS espesor, t1.precio_tonelada AS precio_tonelada, t1.rotativa AS rotativa"
);
$builder->where("t1.is_deleted", 0); $builder->where("t1.is_deleted", 0);
$builder->where("t1.isActivo", 1); $builder->where("t1.isActivo", 1);
$builder->where("t1.papel_generico_id", $papel_generico_id); $builder->where("t1.papel_generico_id", $papel_generico_id);
$builder->where("t1.gramaje", $gramaje); $builder->where("t1.gramaje", $gramaje);
if(!is_null($bn)){ if (!is_null($bn)) {
$builder->where("t1.bn", $bn); $builder->where("t1.bn", $bn);
} }
if(!is_null($color)){ if (!is_null($color)) {
$builder->where("t1.color", $color); $builder->where("t1.color", $color);
} }
if(!is_null($cubierta)){ if (!is_null($cubierta)) {
$builder->where("t1.cubierta", $cubierta); $builder->where("t1.cubierta", $cubierta);
} }
if(!is_null($sobrecubierta)){ if (!is_null($sobrecubierta)) {
$builder->where("t1.sobrecubierta", $sobrecubierta); $builder->where("t1.sobrecubierta", $sobrecubierta);
} }
if(!is_null($guardas)){ if (!is_null($guardas)) {
$builder->where("t1.guardas", $guardas); $builder->where("t1.guardas", $guardas);
} }
if(!is_null($rotativa)){ if (!is_null($rotativa)) {
$builder->where("t1.rotativa", $rotativa); $builder->where("t1.rotativa", $rotativa);
} }
@ -269,7 +279,8 @@ class PapelImpresionModel extends \App\Models\BaseModel
//tipo: negro, negrohq, color, colorhq //tipo: negro, negrohq, color, colorhq
//uso: interior, rotativa, cubierta, sobrecubierta //uso: interior, rotativa, cubierta, sobrecubierta
public function getPapelesImpresionForMenu($papel_generico = null, $gramaje = null, $tipo = null, $uso=""){ public function getPapelesImpresionForMenu($papel_generico = null, $gramaje = null, $tipo = null, $uso = "")
{
$builder = $this->db $builder = $this->db
->table($this->table . " t1") ->table($this->table . " t1")
->distinct("t1.id") ->distinct("t1.id")
@ -278,8 +289,9 @@ class PapelImpresionModel extends \App\Models\BaseModel
->join("lg_maquinas t4", "t3.maquina_id = t4.id", "left") ->join("lg_maquinas t4", "t3.maquina_id = t4.id", "left")
->join("lg_maquinas_tarifas_impresion t5", "t4.id = t5.maquina_id", "left") ->join("lg_maquinas_tarifas_impresion t5", "t4.id = t5.maquina_id", "left")
->select( ->select(
"t1.id AS id, t1.nombre AS text"); "t1.id AS id, t1.nombre AS text"
);
$builder->where("t1.is_deleted", 0); $builder->where("t1.is_deleted", 0);
$builder->where("t1.isActivo", 1); $builder->where("t1.isActivo", 1);
$builder->where("t2.is_deleted", 0); $builder->where("t2.is_deleted", 0);
@ -288,7 +300,7 @@ class PapelImpresionModel extends \App\Models\BaseModel
$builder->where("t4.tipo", 'impresion'); $builder->where("t4.tipo", 'impresion');
$builder->where("t5.is_deleted", 0); $builder->where("t5.is_deleted", 0);
$builder->where("t5.tipo", $tipo); $builder->where("t5.tipo", $tipo);
$builder->where("t2.id", $papel_generico); $builder->where("t2.id", $papel_generico);
$builder->where("t1.gramaje", $gramaje); $builder->where("t1.gramaje", $gramaje);
@ -298,32 +310,35 @@ class PapelImpresionModel extends \App\Models\BaseModel
$builder->where("t1.sobrecubierta", 1); $builder->where("t1.sobrecubierta", 1);
else if ($uso == 'guardas') else if ($uso == 'guardas')
$builder->where("t1.guardas", 1); $builder->where("t1.guardas", 1);
else{ else {
if($tipo == 'negro' || $tipo == 'negrohq') if ($tipo == 'negro' || $tipo == 'negrohq')
$builder->where("t1.bn", 1); $builder->where("t1.bn", 1);
else if ($tipo == 'color' || $tipo == 'colorhq') else if ($tipo == 'color' || $tipo == 'colorhq')
$builder->where("t1.color", 1); $builder->where("t1.color", 1);
} }
if($uso=='rotativa') if ($uso == 'rotativa')
$builder->where("t1.rotativa", 1); $builder->where("t1.rotativa", 1);
else else
$builder->where("t1.rotativa", 0); $builder->where("t1.rotativa", 0);
return $builder->orderBy("t1.id", "asc")->get()->getResultObject(); return $builder->orderBy("t1.id", "asc")->get()->getResultObject();
} }
public function getNombre($id){ public function getNombre($id)
{
$builder = $this->db $builder = $this->db
->table($this->table . " t1") ->table($this->table . " t1")
->select( ->select(
"t1.nombre AS text"); "t1.nombre AS text"
);
$builder->where("t1.id", $id); $builder->where("t1.id", $id);
return $builder->orderBy("t1.id", "asc")->get()->getResultObject(); return $builder->orderBy("t1.id", "asc")->get()->getResultObject();
} }
public function getPapelGenericoCode($papel_id = 0){ public function getPapelGenericoCode($papel_id = 0)
{
$builder = $this->db $builder = $this->db
->table($this->table . " t1") ->table($this->table . " t1")
->select("t2.code AS code") ->select("t2.code AS code")
@ -332,12 +347,13 @@ class PapelImpresionModel extends \App\Models\BaseModel
->where("t1.is_deleted", 0) ->where("t1.is_deleted", 0)
->where("t1.isActivo", 1) ->where("t1.isActivo", 1)
->where("t2.is_deleted", 0); ->where("t2.is_deleted", 0);
$result = $builder->get()->getResultObject(); $result = $builder->get()->getResultObject();
if(count($result) > 0){ if (count($result) > 0) {
return $result[0]->code; return $result[0]->code;
} } else
else
return ""; return "";
} }
} }

View File

@ -73,7 +73,7 @@ class PresupuestoEncuadernacionesModel extends \App\Models\BaseModel
$result_array = []; $result_array = [];
foreach($tarifa_value as $tarifa_proveedor){ foreach($tarifa_value as $tarifa_proveedor){
$precio_total = floatval(1.0* $tarifa_proveedor->precio_hora* $tiempo) * (1+$tarifa_value[0]->margen/100.0); $precio_total = floatval(1.0* $tarifa_proveedor->precio_hora* $tiempo) * (1+$tarifa_value[0]->margen/100.0);
if (!$POD){ if ($tirada>=$POD){
$precio_total += floatval($tarifa_proveedor->tarifa_importe_fijo); $precio_total += floatval($tarifa_proveedor->tarifa_importe_fijo);
} }
@ -248,7 +248,7 @@ class PresupuestoEncuadernacionesModel extends \App\Models\BaseModel
return []; return [];
} }
public function getPrecioTarifaHoras($tarifa_encuadernacion_id, $paginas, $tirada, $proveedor_id, $POD, $paginas_cuadernillo = null){ public function getPrecioTarifaHoras($tarifa_encuadernacion_id, $paginas, $tirada, $proveedor_id, $POD, $paginas_cuadernillo = 32){
$modelTarifa = model('App\Models\Tarifas\TarifaEncuadernacionModel'); $modelTarifa = model('App\Models\Tarifas\TarifaEncuadernacionModel');
@ -265,7 +265,7 @@ class PresupuestoEncuadernacionesModel extends \App\Models\BaseModel
$ret_array = []; $ret_array = [];
foreach($tarifa_value as $tarifa_proveedor){ foreach($tarifa_value as $tarifa_proveedor){
$precio_total = floatval(1.0* $tarifa_proveedor->precio_hora* $tiempo) * (1+$tarifa_value[0]->margen/100.0); $precio_total = floatval(1.0* $tarifa_proveedor->precio_hora* $tiempo) * (1+$tarifa_value[0]->margen/100.0);
if (!$POD){ if ($tirada>=$POD){
$precio_total += floatval($tarifa_proveedor->tarifa_importe_fijo); $precio_total += floatval($tarifa_proveedor->tarifa_importe_fijo);
} }

View File

@ -404,11 +404,13 @@ class PresupuestoModel extends \App\Models\BaseModel
'cliente_id' => $data['clienteId'], 'cliente_id' => $data['clienteId'],
'tipo_impresion_id' => $data['tipo_impresion_id'], 'tipo_impresion_id' => $data['tipo_impresion_id'],
'pais_id' => 1, 'pais_id' => 1,
'retractilado' => in_array("RETR", $data['cubierta']['acabadosCubierta']) ? 1 : 0, 'retractilado' => $data['retractilado'] ? 1 : 0,
'retractilado5' => in_array(5, $data['servicios']) ? 1 : 0, 'retractilado5' => $data['retractilado5'] ? 1 : 0,
'guardas' => in_array(62, $data['servicios']) ? 1 : 0, 'guardas' => in_array(62, $data['servicios']) ? 1 : 0,
'faja_color' => in_array(16, $data['servicios']) ? 1 : 0, 'faja_color' => in_array(16, $data['servicios']) ? 1 : 0,
'ferro' => in_array(24, $data['servicios']) ? 1 : 0, 'ferro' => $data['ferro'] ? 1 : 0,
'ferro_digital' => $data['ferro_digital'] ? 1 : 0,
'marcapaginas' => $data['marcapaginas'] ? 1 : 0,
'prototipo' => $data['prototipo'] ? 1 : 0, 'prototipo' => $data['prototipo'] ? 1 : 0,
'papel_formato_id' => is_null($papel_formato_id) ? 0 : $papel_formato_id->id, 'papel_formato_id' => is_null($papel_formato_id) ? 0 : $papel_formato_id->id,
'papel_formato_personalizado' => !$papel_formato_id ? 1 : 0, 'papel_formato_personalizado' => !$papel_formato_id ? 1 : 0,
@ -424,7 +426,7 @@ class PresupuestoModel extends \App\Models\BaseModel
'solapas' => $data['cubierta']['solapasCubierta'] == 0 ? 0 : 1, 'solapas' => $data['cubierta']['solapasCubierta'] == 0 ? 0 : 1,
'lomo_redondo' => $data['cubierta']['lomoRedondo'] == 0 ? 0 : 1, 'lomo_redondo' => $data['cubierta']['lomoRedondo'] == 0 ? 0 : 1,
'cabezada' => $data['cubierta']['cabezada'] == 0 ? 0 : 1, 'cabezada' => $data['cubierta']['cabezada'] == 0 ? 0 : 1,
'solapas_ancho' => $data['cubierta']['solapasCubierta'] == 0 ? $data['cubierta']['solapasCubierta'] : 0, 'solapas_ancho' => $data['cubierta']['solapasCubierta'] > 0 ? $data['cubierta']['solapasCubierta'] : 0,
'solapas_sobrecubierta' => !$data['sobrecubierta'] ? 0 : 1, 'solapas_sobrecubierta' => !$data['sobrecubierta'] ? 0 : 1,
'solapas_ancho_sobrecubierta' => !$data['sobrecubierta'] ? 0 : $data['sobrecubierta']['solapas'], 'solapas_ancho_sobrecubierta' => !$data['sobrecubierta'] ? 0 : $data['sobrecubierta']['solapas'],
'cosido' => $is_cosido, 'cosido' => $is_cosido,

View File

@ -79,6 +79,7 @@ class TipoPresupuestoServiciosDefectoModel extends \App\Models\BaseModel
$where = "(t1.solapas IS NULL OR t1.solapas='" . $solapas . "')"; $where = "(t1.solapas IS NULL OR t1.solapas='" . $solapas . "')";
$builder->where($where); $builder->where($where);
$builder->where("t1.is_deleted", 0);
$builder->where("t2.is_deleted", 0); $builder->where("t2.is_deleted", 0);
$builder->select("t1.tarifa_id AS tarifa_id, t2.nombre AS tarifa_nombre"); $builder->select("t1.tarifa_id AS tarifa_id, t2.nombre AS tarifa_nombre");

View File

@ -30,7 +30,6 @@ class UserModel extends ShieldUserModel
protected $updatedField = 'updated_at'; protected $updatedField = 'updated_at';
protected $deletedField = 'deleted_at'; protected $deletedField = 'deleted_at';
protected $validationRules = [ protected $validationRules = [
"first_name" => "required|trim|max_length[150]", "first_name" => "required|trim|max_length[150]",
"last_name" => "required|trim|max_length[150]", "last_name" => "required|trim|max_length[150]",
@ -66,7 +65,7 @@ class UserModel extends ShieldUserModel
$builder = $this->db $builder = $this->db
->table("users" . " t1") ->table("users" . " t1")
->select( ->select(
"t1.id AS id, CONCAT(t1.first_name, ' ', t1.last_name) AS text" "t1.id AS id, CONCAT(t1.first_name, ' ', t1.last_name) AS name"
); );
$builder->where('t1.deleted_at', null); $builder->where('t1.deleted_at', null);
@ -77,5 +76,19 @@ class UserModel extends ShieldUserModel
} }
// Método para comprobar si el email ya está registrado
public function isEmailUnique($email)
{
$builder = $this->db
->table("auth_identities t1") // La tabla correcta
->select("t1.secret AS email")
->where('secret', $email);
// Obtener resultados
$result = $builder->get()->getRow();
// Devuelve true si no se encuentra el correo (es único), false en caso contrario
return $result === null;
}
} }

View File

@ -20,6 +20,7 @@ class UserModel extends \App\Models\BaseModel
protected $allowedFields = [ protected $allowedFields = [
"username", "username",
"email",
"first_name", "first_name",
"last_name", "last_name",
"client_id", "client_id",

View File

@ -0,0 +1,14 @@
<?php
namespace App\Services;
use App\Models\Presupuestos\PresupuestoModel;
use CodeIgniter\Config\BaseService;
class MessageService extends BaseService
{
public static function get_chat_title_from_presupuesto(int $presuesto_id,?string $department_name = null) : string
{
}
}

View File

@ -25,19 +25,19 @@ class PresupuestoClienteService extends BaseService
$total_plana = -1; $total_plana = -1;
$hay_plana = false; $hay_plana = false;
if ($data['isColor']) { if ($data['isColor']) {
if ($data['datosPedido']->paginas == $data['paginas_color']){ if (count($plana) > 0) {
if(count($plana[1]) > 2) if ($data['datosPedido']->paginas == $data['paginas_color']) {
$total_plana += floatval($plana[1]['total_impresion']); if (count($plana[1]) > 2)
else $total_plana += floatval($plana[1]['total_impresion']);
return -1; else
} return -1;
} else {
elseif (count($plana) > 0) { if (count($plana[0]) > 2 && count($plana[1]) > 2) {
if (count($plana[0]) > 2 && count($plana[1]) > 2) { $total_plana = 0.0;
$total_plana = 0.0; foreach ($plana as $linea) {
foreach ($plana as $linea) { if (count($linea) > 0)
if (count($linea) > 0) $total_plana += floatval($linea['total_impresion']);
$total_plana += floatval($linea['total_impresion']); }
} }
} }
} }
@ -416,6 +416,17 @@ class PresupuestoClienteService extends BaseService
return $values; return $values;
} }
public static function getServiciosManipuladoDefault($data)
{
$tirada = $data['tirada'] ?? -1;
$anchoDesarrollo = $data['anchoDesarrollo'] ?? -1;
/*$model = model('App\Models\Presupuestos\PresupuestoEncuadernacionesModel');
$values = $model->initPresupuesto($tipo_impresion_id, $solapas, $tirada, $paginas, $ancho, $alto, $POD, $paginasCuadernillo);*/
//return $values;
}
public static function getServiciosManipulado($data) public static function getServiciosManipulado($data)
{ {

View File

@ -1479,7 +1479,7 @@ class PresupuestoService extends BaseService
// con el mismo proveedor // con el mismo proveedor
else { else {
if ($tarifaModel->isTarifaPorHoras($servicio->tarifa_encuadernado_id)) { if ($tarifaModel->isTarifaPorHoras($servicio->tarifa_encuadernado_id)) {
$paginas_cuadernillo = $servicio->paginas_por_cuadernillo ?? null; $paginas_cuadernillo = $servicio->paginas_por_cuadernillo ?? 32;
$nueva_tarifa = $model->getPrecioTarifaHoras( $nueva_tarifa = $model->getPrecioTarifaHoras(
$servicio->tarifa_encuadernado_id, $servicio->tarifa_encuadernado_id,
$input_data['paginas'], $input_data['paginas'],
@ -1815,6 +1815,12 @@ class PresupuestoService extends BaseService
} }
} }
if ($uso == 'cubierta' || $uso == 'sobrecubierta') {
$linea['fields']['dimension_desarrollo']['ancho'] = $datosPedido->anchoExteriores;
$linea['fields']['dimension_desarrollo']['alto'] = $datosPedido->altoExteriores;
}
if (!array_key_exists('tipo_linea', $linea['fields'])) { if (!array_key_exists('tipo_linea', $linea['fields'])) {
if ($isColor) { if ($isColor) {
if ($isHq) if ($isHq)

View File

@ -0,0 +1,11 @@
<div class="alert alert-success d-flex align-items-baseline d-none" role="alert" id="<?= $id ?>">
<span class="alert-icon alert-icon-lg text-primary me-2">
<i class="ti ti-sm icon-alert"></i>
</span>
<div class="d-flex flex-column ps-1">
<h5 class="alert-heading mb-2"></h5>
<div class="alert-body">
</div>
</div>
</div>

View File

@ -0,0 +1,153 @@
<div class="col-md-12" id="chat-direct-message" data-id="<?= $modelId ?>" data-user-id="<?= $userId ?>">
<div class="app-chat card overflow-hidden">
<div class="row g-0">
<!-- Chat & Contacts -->
<div class="col app-chat-contacts app-sidebar flex-grow-0 overflow-hidden border-end"
id="app-chat-contacts">
<div class="sidebar-header">
<div class="d-flex align-items-center me-3 me-lg-0">
<?php if (auth()->user()->inGroup('admin')) { ?>
<div class="flex-shrink-0 avatar me-3">
<button title="<?= lang("Chat.new_participant") ?>" class="btn btn-primary btn-icon me-2 rounded-circle" id="btn-chat-add-participant"><span class="ti ti-sm ti-user-plus"></span></button>
</div>
<?php } ?>
<div class="flex-grow-1 input-group input-group-merge rounded-pill">
<span class="input-group-text" id="basic-addon-search31">
<i class="ti ti-search"></i>
</span>
<input type="text" class="form-control chat-search-input"
placeholder="Buscar..." aria-label="Buscar..."
aria-describedby="basic-addon-search31" />
</div>
</div>
<!-- <i class="ti ti-x cursor-pointer d-lg-none d-block position-absolute mt-2 me-1 top-0 end-0"
data-overlay data-bs-toggle="sidebar" data-target="#app-chat-contacts"></i> -->
</div>
<div class="sidebar-body">
<!-- CLIENTES -->
<ul class="list-unstyled chat-contact-list mb-0">
<li class="chat-contact-list-item chat-contact-list-item-title">
<h5 class="text-primary mb-0"><?= lang("Chat.participants") ?></h5>
</li>
</ul>
<ul class="list-unstyled chat-contact-list mb-0" id="contact-list">
<div class="d-flex justify-content-center chat-loader">
<div class="sk-wave sk-primary ">
<div class="sk-wave-rect"></div>
<div class="sk-wave-rect"></div>
<div class="sk-wave-rect"></div>
<div class="sk-wave-rect"></div>
<div class="sk-wave-rect"></div>
</div>
</div>
<!-- <li class="chat-contact-list-item">
<a class="d-flex align-items-center">
<div class="avatar d-block flex-shrink-0">
<span class="avatar-initial rounded-circle bg-label-primary">JJ</span>
</div>
<div class="chat-contact-info flex-grow-1 ms-2">
<h6 class="chat-contact-name text-truncate m-0">Jaime Jimenez</h6>
</div>
</a>
</li> -->
</ul>
</div>
</div>
<!-- /Chat contacts -->
<!-- Chat History -->
<div class="col app-chat-history bg-body">
<div class="chat-history-wrapper ">
<div class="chat-history-header border-bottom">
<div class="d-flex justify-content-between align-items-center">
<div class="d-flex overflow-hidden align-items-center">
<i class="ti ti-menu-2 ti-sm cursor-pointer d-lg-none d-block me-2"
data-bs-toggle="sidebar" data-overlay
data-target="#app-chat-contacts"></i>
<h5 class="text-primary mb-0" id="chat-direct-title"><br></h5>
<div class="chat-contact-info flex-grow-1 ms-2">
<h6 class="m-0"></h6>
<small class="user-status text-muted"></small>
</div>
</div>
<div class="d-flex align-items-center">
<div class="dropdown d-flex align-self-center">
<button class="btn p-0" type="button" id="chat-header-actions"
data-bs-toggle="dropdown" aria-haspopup="true"
aria-expanded="false">
<i class="ti ti-dots-vertical"></i>
</button>
<div class="dropdown-menu dropdown-menu-end"
aria-labelledby="chat-header-actions">
<a class="dropdown-item" id="update-message-unviewed" href="javascript:void(0);"><?= lang("Chat.check_as_unviewed") ?></a>
</div>
</div>
</div>
</div>
</div>
<div class="chat-history-body bg-body ">
<div class="d-flex justify-content-center chat-loader">
<div class="sk-wave sk-primary ">
<div class="sk-wave-rect"></div>
<div class="sk-wave-rect"></div>
<div class="sk-wave-rect"></div>
<div class="sk-wave-rect"></div>
<div class="sk-wave-rect"></div>
</div>
</div>
<ul class="list-unstyled chat-history" id="chat-conversation">
</ul>
</div>
<!-- Chat message form -->
<div class="chat-history-footer shadow-sm">
<div
class="form-send-message d-flex justify-content-between align-items-center">
<input class="form-control message-input border-0 me-3 shadow-none"
placeholder="<?= lang("Chat.write_message_placeholder") ?>" />
<div class="message-actions d-flex align-items-center">
<div class="message-actions d-flex align-items-center">
<a class="btn btn-primary d-flex send-msg-btn" style="color:white"
id="send-msg-btn-direct">
<i class="ti ti-send me-md-1 me-0"></i>
<span class="align-middle d-md-inline-block"><?= lang("Chat.modal.btn_send") ?></span>
</a>
</div>
</div>
</div>
</div>
</div>
<!-- /Chat History -->
<div class="app-overlay"></div>
</div>
</div>
</div>
<?= view("themes/vuexy/components/modals/modalAddNewChatParticipant") ?>
</div>
<?= $this->section('css') ?>
<link rel="stylesheet" href="<?= site_url('themes/vuexy/vendor/libs/spinkit/spinkit.css') ?>" />
<link rel="stylesheet" href="<?= site_url('themes/vuexy/vendor/css/pages/app-chat.css') ?>">
<?= $this->endSection() ?>
<!------------------------------------------------------->
<!-- Código JS logica -->
<!------------------------------------------------------->
<?= $this->section("additionalExternalJs") ?>
<script type="module" src="<?= site_url('assets/js/safekat/pages/messages/directMessagePage.js') ?>"></script>
<script src="<?= site_url('themes/vuexy/vendor/libs/perfect-scrollbar/perfect-scrollbar.js') ?>"></script>
<?= $this->endSection() ?>

View File

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

View File

@ -37,14 +37,11 @@
<hr class="container-m-nx m-0" /> <hr class="container-m-nx m-0" />
<div class="sidebar-body"> <div class="sidebar-body">
<!-- Contacts --> <!-- CLIENTES -->
<ul class="list-unstyled chat-contact-list mb-0" id="contact-list"> <ul class="list-unstyled chat-contact-list mb-0" id="contact-list">
<li class="chat-contact-list-item chat-contact-list-item-title"> <li class="chat-contact-list-item chat-contact-list-item-title">
<h5 class="text-primary mb-0">Contactos</h5> <h5 class="text-primary mb-0">Contactos</h5>
</li> </li>
<li class="chat-contact-list-item contact-list-item-0 ">
<h6 class="text-muted mb-0">No Contacts Found</h6>
</li>
<!-- <li class="chat-contact-list-item"> <!-- <li class="chat-contact-list-item">
<a class="d-flex align-items-center"> <a class="d-flex align-items-center">
<div class="avatar d-block flex-shrink-0"> <div class="avatar d-block flex-shrink-0">
@ -57,6 +54,7 @@
</li> --> </li> -->
</ul> </ul>
</div> </div>
</div> </div>
<!-- /Chat contacts --> <!-- /Chat contacts -->
@ -75,9 +73,8 @@
class="avatar-initial rounded-circle bg-label-primary">P</span> class="avatar-initial rounded-circle bg-label-primary">P</span>
</div> </div>
<div class="chat-contact-info flex-grow-1 ms-2"> <div class="chat-contact-info flex-grow-1 ms-2">
<h6 class="m-0">Departamento Producción</h6> <h6 class="m-0"></h6>
<small class="user-status text-muted">Consulta sobre el presupuesto <small class="user-status text-muted"></small>
P001</small>
</div> </div>
</div> </div>
<div class="d-flex align-items-center"> <div class="d-flex align-items-center">
@ -87,13 +84,13 @@
aria-expanded="false"> aria-expanded="false">
<i class="ti ti-dots-vertical"></i> <i class="ti ti-dots-vertical"></i>
</button> </button>
<div class="dropdown-menu dropdown-menu-end" <!-- <div class="dropdown-menu dropdown-menu-end"
aria-labelledby="chat-header-actions"> aria-labelledby="chat-header-actions">
<a class="dropdown-item" href="javascript:void(0);">Silenciar <a class="dropdown-item" href="javascript:void(0);">Silenciar
Conversacion</a> Conversacion</a>
<a class="dropdown-item" href="javascript:void(0);">Limpiar <a class="dropdown-item" href="javascript:void(0);">Limpiar
Conversacion</a> Conversacion</a>
</div> </div> -->
</div> </div>
</div> </div>
</div> </div>
@ -140,6 +137,7 @@
</div> </div>
</div> </div>
<?= $this->section('css') ?> <?= $this->section('css') ?>
<link rel="stylesheet" href="<?= site_url('themes/vuexy/vendor/libs/spinkit/spinkit.css') ?>" />
<link rel="stylesheet" href="<?= site_url('themes/vuexy/vendor/css/pages/app-chat.css') ?>"> <link rel="stylesheet" href="<?= site_url('themes/vuexy/vendor/css/pages/app-chat.css') ?>">
<?= $this->endSection() ?> <?= $this->endSection() ?>
<!-------------------------------------------------------> <!------------------------------------------------------->

View File

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

View File

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

View File

@ -0,0 +1,42 @@
<!-- Modal -->
<div class="modal fade" id="modalAddNewChatParticipant" tabindex="-1" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel1"><?= lang('Chat.modal.new_receivers') ?></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" => "alertNewParticipant"]) ?>
</div>
<form id="formNewParticipant">
<div class="form-group">
<div class="row">
<div class="col-12 mb-2">
<label for="select-users" class="required form-label"><?= lang('Chat.modal.new_receivers') ?></label>
<select id="select-users" name="users" class="select2 form-control" multiple required>
</select>
</div>
<div class="col-12 mb-2">
<div class="text-light small fw-medium mb-2"><?= lang("Chat.add_notification") ?></div>
<label class="switch">
<input type="checkbox" class="switch-input" name="notification" id="checkbox-notification-chat" checked />
<span class="switch-toggle-slider">
<span class="switch-on"></span>
<span class="switch-off"></span>
</span>
<span class="switch-label"><?= lang("Chat.add_notification_message") ?></span>
</label>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-label-secondary" data-bs-dismiss="modal"><?= lang('App.global_come_back') ?></button>
<button type="button" id="btn-chat-add-participant-submit" class="btn btn-primary d-none"><?= lang('App.global_save') ?></button>
</div>
</div>
</div>
</div>

View File

@ -0,0 +1,47 @@
<!-- Modal -->
<div class="modal fade" id="modalNewDirectMessage" tabindex="-1" aria-hidden="true">
<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="formNewDirectMessage">
<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-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-text" name="message" placeholder="Escribe el mensaje ..." name="message" class="form-control" required></textarea>
</div>
<div class="col-12 mb-0">
<label for="select-users" class="required form-label"><?= lang('Chat.modal.new_receivers') ?></label>
<select id="select-users" name="users" 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" class="btn btn-primary"><?= lang('Chat.modal.btn_send') ?></button>
<?php } ?>
</div>
</div>
</div>
</div>

View File

@ -0,0 +1,15 @@
<table id="<?= $id ?>" class="table table-striped table-hover" style="width: 100%;">
<thead>
<tr>
<th><?= lang('Chat.datatable_messages.created_at') ?></th>
<th><?= lang('Chat.datatable_messages.updated_at') ?></th>
<th><?= lang('Chat.datatable_messages.title') ?></th>
<th><?= lang('Chat.datatable_messages.creator') ?></th>
<th><?= lang('Chat.datatable_messages.viewed') ?></th>
<th class="text-nowrap"><?= lang('Basic.global.Action') ?></th>
</tr>
</thead>
<tbody>
</tbody>
</table>

View File

@ -158,11 +158,6 @@
<?= lang('Clientes.paisId') ?> <?= lang('Clientes.paisId') ?>
</label> </label>
<select id="paisId" name="pais_id" class="form-control select2bs" style="width: 100%;" > <select id="paisId" name="pais_id" class="form-control select2bs" style="width: 100%;" >
<?php foreach ($paisList as $item) : ?>
<option value="<?=$item->id ?>"<?=$item->id==$clienteEntity->pais_id ? ' selected':'' ?>>
<?=$item->nombre ?>
</option>
<?php endforeach; ?>
</select> </select>
</div> </div>

View File

@ -34,201 +34,6 @@
<?= $this->endSection() ?> <?= $this->endSection() ?>
<?= $this->section("additionalInlineJs") ?>
$(document).keypress(function (e) {
var key = e.which;
if(key == 13) // the enter key code
{ e.preventDefault()
if($('#addressForm').hasClass('show')){
$("#saveAdd").click();
}
else if ($('#convert2Template').hasClass('show')){
$("#saveTemplate").click();
}
else{
$('#saveForm').click();
}
}
});
$('#soporteId').select2({
allowClear: false,
ajax: {
url: '<?= route_to("menuItemsComerciales") ?>',
type: 'post',
dataType: 'json',
data: function (params) {
return {
id: 'id_user',
text: 'first_name',
searchTerm: params.term,
<?= csrf_token() ?? "token" ?> : <?= csrf_token() ?>v
};
},
delay: 60,
processResults: function (response) {
yeniden(response.<?= csrf_token() ?>);
return {
results: response.menu
};
},
cache: true
}
});
$('#formaPagoId').select2({
allowClear: false,
ajax: {
url: '<?= route_to("menuItemsOfFormasDePagos") ?>',
type: 'post',
dataType: 'json',
data: function (params) {
return {
id: 'id',
text: 'nombre',
searchTerm: params.term,
<?= csrf_token() ?? "token" ?> : <?= csrf_token() ?>v
};
},
delay: 60,
processResults: function (response) {
yeniden(response.<?= csrf_token() ?>);
return {
results: response.menu
};
},
cache: true
}
});
$('#paisId').select2({
allowClear: false,
ajax: {
url: '<?= route_to("menuItemsOfPaises") ?>',
type: 'post',
dataType: 'json',
data: function (params) {
return {
id: 'id',
text: 'nombre',
searchTerm: params.term,
<?= csrf_token() ?? "token" ?> : <?= csrf_token() ?>v
};
},
delay: 60,
processResults: function (response) {
yeniden(response.<?= csrf_token() ?>);
return {
results: response.menu
};
},
cache: true
}
});
$('#provinciaId').select2({
allowClear: false,
ajax: {
url: '<?= route_to("menuItemsOfProvincias") ?>',
type: 'post',
dataType: 'json',
data: function (params) {
return {
id: 'id',
text: 'nombre',
searchTerm: params.term,
<?= csrf_token() ?? "token" ?> : <?= csrf_token() ?>v
};
},
delay: 60,
processResults: function (response) {
yeniden(response.<?= csrf_token() ?>);
return {
results: response.menu
};
},
cache: true
}
});
$('#comunidadAutonomaId').select2({
allowClear: false,
ajax: {
url: '<?= route_to("menuItemsOfComunidadesAutonomas") ?>',
type: 'post',
dataType: 'json',
data: function (params) {
return {
id: 'id',
text: 'nombre',
searchTerm: params.term,
<?= csrf_token() ?? "token" ?> : <?= csrf_token() ?>v
};
},
delay: 60,
processResults: function (response) {
yeniden(response.<?= csrf_token() ?>);
return {
results: response.menu
};
},
cache: true
}
});
$('#comercialId').select2({
allowClear: false,
ajax: {
url: '<?= route_to("menuItemsComerciales") ?>',
type: 'post',
dataType: 'json',
data: function (params) {
return {
id: 'id',
text: 'text',
searchTerm: params.term,
<?= csrf_token() ?? "token" ?> : <?= csrf_token() ?>v
};
},
delay: 60,
processResults: function (response) {
yeniden(response.<?= csrf_token() ?>);
return {
results: response.menu
};
},
cache: true
}
});
<?= $this->endSection() ?>
<?=$this->section('css') ?> <?=$this->section('css') ?>
<link rel="stylesheet" href="<?= site_url('themes/vuexy/css/datatables-editor/editor.dataTables.min.css') ?>"> <link rel="stylesheet" href="<?= site_url('themes/vuexy/css/datatables-editor/editor.dataTables.min.css') ?>">
<link rel="stylesheet" href="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/buttons/buttons.bootstrap5.min.css") ?>"> <link rel="stylesheet" href="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/buttons/buttons.bootstrap5.min.css") ?>">
@ -236,3 +41,7 @@
<link rel="stylesheet" href="<?= site_url('themes/vuexy/css/safekat.css') ?>"> <link rel="stylesheet" href="<?= site_url('themes/vuexy/css/safekat.css') ?>">
<?=$this->endSection() ?> <?=$this->endSection() ?>
<?= $this->section("additionalExternalJs") ?>
<script type="module" src="<?= site_url('assets/js/safekat/pages/cliente/cliente.js?'. 'token' . '='. (csrf_token() ?? "token")) ?>"></script>
<?= $this->endSection() ?>

View File

@ -278,14 +278,26 @@
language: { language: {
url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json" url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json"
}, },
buttons: [ { buttons: [
className: 'btn btn-primary me-sm-3 me-1', {
extend: "createInline", extend: 'collection',
editor: editor, text: 'Exportar',
formOptions: { buttons:[
submitTrigger: -1, 'copy', 'csv', 'excel', 'print', {
submitHtml: '<a href="javascript:void(0);"><i class="ti ti-device-floppy"></i></a>' extend: 'pdfHtml5',
} orientation: 'landscape',
pageSize: 'A4'
}
]
},
{
className: 'btn btn-primary me-sm-3 me-1',
extend: "createInline",
editor: editor,
formOptions: {
submitTrigger: -1,
submitHtml: '<a href="javascript:void(0);"><i class="ti ti-device-floppy"></i></a>'
}
} ] } ]
} ); } );

View File

@ -1,36 +1,55 @@
<div class="row"> <div class="row">
<div class="col-md-12 col-lg-12 px-4"> <div class="col-md-12 col-lg-12 px-4">
<div class="mb-3"> <div class="mb-3">
<label for="nombre" class="form-label"> <label for="nombre" class="form-label">
<?=lang('PapelGenerico.nombre') ?>* <?= lang('PapelGenerico.nombre') ?>*
</label> </label>
<input type="text" id="nombre" name="nombre" required maxLength="255" class="form-control" value="<?=old('nombre', $papelGenerico->nombre) ?>"> <input type="text" id="nombre" name="nombre" required maxLength="255" class="form-control"
</div><!--//.mb-3 --> value="<?= old('nombre', $papelGenerico->nombre) ?>">
</div><!--//.mb-3 -->
<div class="mb-3"> <div class="mb-3">
<label for="code" class="form-label"> <label for="code" class="form-label">
<?=lang('PapelGenerico.code') ?> <?= lang('PapelGenerico.code') ?>
</label> </label>
<input type="text" id="code" name="code" maxLength="5" class="form-control" value="<?=old('code', $papelGenerico->code) ?>"> <input type="text" id="code" name="code" maxLength="5" class="form-control"
</div><!--//.mb-3 --> value="<?= old('code', $papelGenerico->code) ?>">
</div><!--//.mb-3 -->
<div class="mb-3"> <div class="mb-3">
<label for="codeOt" class="form-label"> <label for="codeOt" class="form-label">
<?=lang('PapelGenerico.codeOt') ?> <?= lang('PapelGenerico.codeOt') ?>
</label> </label>
<input type="text" id="codeOt" name="code_ot" maxLength="5" class="form-control" value="<?=old('code_ot', $papelGenerico->code_ot) ?>"> <input type="text" id="codeOt" name="code_ot" maxLength="5" class="form-control"
</div><!--//.mb-3 --> value="<?= old('code_ot', $papelGenerico->code_ot) ?>">
</div><!--//.mb-3 -->
<div class="mb-3"> <div class="mb-3">
<div class="form-check"> <div class="form-check">
<label for="showInClient" class="form-check-label"> <label for="showInClient" class="form-check-label">
<input type="checkbox" id="showInClient" name="show_in_client" value="1" class="form-check-input"<?=$papelGenerico->show_in_client== true ? 'checked' : ''; ?>> <?= lang('PapelGenerico.showInClient') ?>
<?=lang('PapelGenerico.showInClient') ?> </label>
</label> <input type="checkbox" id="showInClient" name="show_in_client" value="1" class="form-check-input"
</div><!--//.form-check --> <?= $papelGenerico->show_in_client_special == true ? 'disabled' : ''; ?>
</div><!--//.mb-3 --> <?= $papelGenerico->show_in_client == true ? 'checked' : ''; ?>>
</div><!--//.col --> </div><!--//.form-check -->
</div><!--//.mb-3 -->
</div><!-- //.row --> <div class="mb-3">
<div class="form-check">
<label for="showInClientSpecial" class="form-check-label">
<?= lang('PapelGenerico.showInClientSpecial') ?>
</label>
<input type="checkbox" id="showInClientSpecial" name="show_in_client_special" value="1"
class="form-check-input" <?= $papelGenerico->show_in_client_special == true ? 'checked' : ''; ?>>
</div><!--//.form-check -->
</div><!--//.mb-3 -->
</div><!--//.col -->
</div><!-- //.row -->

View File

@ -1,165 +1,213 @@
<div class="row"> <div class="row">
<div class="col-md-12 col-lg-6 px-4"> <div class="col-md-12 col-lg-6 px-4">
<div class="mb-3"> <div class="mb-3">
<label for="nombre" class="form-label"> <label for="nombre" class="form-label">
<?= lang('PapelImpresion.nombre') ?>* <?= lang('PapelImpresion.nombre') ?>*
</label> </label>
<input type="text" id="nombre" name="nombre" required maxLength="255" class="form-control" value="<?= old('nombre', $papelImpresion->nombre) ?>"> <input type="text" id="nombre" name="nombre" required maxLength="255" class="form-control"
</div><!--//.mb-3 --> value="<?= old('nombre', $papelImpresion->nombre) ?>">
</div><!--//.mb-3 -->
<div class="mb-3"> <div class="mb-3">
<label for="referencia" class="form-label"> <label for="referencia" class="form-label">
<?= lang('PapelImpresion.referencia') ?> <?= lang('PapelImpresion.referencia') ?>
</label> </label>
<input type="text" id="referencia" name="referencia" maxLength="13" class="form-control" value="<?= old('referencia', $papelImpresion->referencia) ?>"> <input type="text" id="referencia" name="referencia" maxLength="13" class="form-control"
</div><!--//.mb-3 --> value="<?= old('referencia', $papelImpresion->referencia) ?>">
</div><!--//.mb-3 -->
<div class="mb-3"> <div class="mb-3">
<label for="mano" class="form-label"> <label for="mano" class="form-label">
<?= lang('PapelImpresion.mano') ?>* <?= lang('PapelImpresion.mano') ?>*
</label> </label>
<input type="number" id="mano" name="mano" required maxLength="8" step="0.01" class="form-control" value="<?= old('mano', $papelImpresion->mano) ?>"> <input type="number" id="mano" name="mano" required maxLength="8" step="0.01" class="form-control"
</div><!--//.mb-3 --> value="<?= old('mano', $papelImpresion->mano) ?>">
</div><!--//.mb-3 -->
<div class="mb-3"> <div class="mb-3">
<label for="precioTonelada" class="form-label"> <label for="precioTonelada" class="form-label">
<?= lang('PapelImpresion.precioTonelada') ?>* <?= lang('PapelImpresion.precioTonelada') ?>*
</label> </label>
<input type="number" id="precioTonelada" name="precio_tonelada" required maxLength="31" step="0.01" class="form-control" value="<?= old('precio_tonelada', $papelImpresion->precio_tonelada) ?>"> <input type="number" id="precioTonelada" name="precio_tonelada" required maxLength="31" step="0.01"
</div><!--//.mb-3 --> class="form-control" value="<?= old('precio_tonelada', $papelImpresion->precio_tonelada) ?>">
</div><!--//.mb-3 -->
</div><!--//.col --> </div><!--//.col -->
<div class="col-md-12 col-lg-6 px-4"> <div class="col-md-12 col-lg-6 px-4">
<div class="mb-3"> <div class="mb-3">
<label for="papelGenericoId" class="form-label"> <label for="papelGenericoId" class="form-label">
<?= lang('PapelImpresion.papelGenericoId') ?>* <?= lang('PapelImpresion.papelGenericoId') ?>*
</label> </label>
<select id="papelGenericoId" name="papel_generico_id" required class="form-control select2" style="width: 100%;"> <select id="papelGenericoId" name="papel_generico_id" required class="form-control select2"
style="width: 100%;">
<?php if (isset($papelGenericoList) && is_array($papelGenericoList) && !empty($papelGenericoList)) : <?php if (isset($papelGenericoList) && is_array($papelGenericoList) && !empty($papelGenericoList)):
foreach ($papelGenericoList as $k => $v) : ?> foreach ($papelGenericoList as $k => $v): ?>
<option value="<?= $k ?>" <?= $k == $papelImpresion->papel_generico_id ? ' selected' : '' ?>> <option value="<?= $k ?>" <?= $k == $papelImpresion->papel_generico_id ? ' selected' : '' ?>>
<?= $v ?> <?= $v ?>
</option> </option>
<?php endforeach; <?php endforeach;
endif; ?> endif; ?>
</select> </select>
</div><!--//.mb-3 --> </div><!--//.mb-3 -->
<div class="mb-3"> <div class="mb-3">
<label for="gramaje" class="form-label"> <label for="gramaje" class="form-label">
<?= lang('PapelImpresion.gramaje') ?>* <?= lang('PapelImpresion.gramaje') ?>*
</label> </label>
<input type="number" id="gramaje" name="gramaje" required maxLength="31" step="0.01" class="form-control" value="<?= old('gramaje', $papelImpresion->gramaje) ?>"> <input type="number" id="gramaje" name="gramaje" required maxLength="31" step="0.01" class="form-control"
</div><!--//.mb-3 --> value="<?= old('gramaje', $papelImpresion->gramaje) ?>">
</div><!--//.mb-3 -->
<div class="mb-3"> <div class="mb-3">
<label for="espesor" class="form-label"> <label for="espesor" class="form-label">
<?= lang('PapelImpresion.espesor') ?>* <?= lang('PapelImpresion.espesor') ?>*
</label> </label>
<input type="number" id="espesor" name="espesor" required placeholder="0.00" maxLength="8" step="0.01" class="form-control" value="<?= old('espesor', $papelImpresion->espesor) ?>"> <input type="number" id="espesor" name="espesor" required placeholder="0.00" maxLength="8" step="0.01"
</div><!--//.mb-3 --> class="form-control" value="<?= old('espesor', $papelImpresion->espesor) ?>">
</div><!--//.mb-3 -->
</div><!--//.col --> </div><!--//.col -->
</div><!-- //.row --> </div><!-- //.row -->
<div class="row"> <div class="row">
<div class="col-md-12 col-lg-6 px-4"> <div class="col-md-12 col-lg-6 px-4">
<div class="mb-3"> <div class="mb-3">
<div class="form-check"> <div class="form-check">
<label for="bn" class="form-check-label"> <label for="bn" class="form-check-label">
<input type="checkbox" id="bn" name="bn" value="1" class="form-check-input" <?= $papelImpresion->bn == true ? 'checked' : ''; ?>> <input type="checkbox" id="bn" name="bn" value="1" class="form-check-input"
<?= lang('PapelImpresion.bn') ?> <?= $papelImpresion->bn == true ? 'checked' : ''; ?>>
</label> <?= lang('PapelImpresion.bn') ?>
</div><!--//.form-check --> </label>
</div><!--//.mb-3 --> </div><!--//.form-check -->
</div><!--//.mb-3 -->
<div class="mb-3"> <div class="mb-3">
<div class="form-check"> <div class="form-check">
<label for="cubierta" class="form-check-label"> <label for="interior" class="form-check-label">
<input type="checkbox" id="cubierta" name="cubierta" value="1" class="form-check-input" <?= $papelImpresion->cubierta == true ? 'checked' : ''; ?>> <input type="checkbox" id="interior" name="interior" value="1" class="form-check-input"
<?= lang('PapelImpresion.cubierta') ?> <?= $papelImpresion->interior == true ? 'checked' : ''; ?>>
</label> <?= lang('PapelImpresion.interior') ?>
</div><!--//.form-check --> </label>
</div><!--//.mb-3 --> </div><!--//.form-check -->
</div><!--//.mb-3 -->
<div class="mb-3"> <div class="mb-3">
<div class="form-check"> <div class="form-check">
<label for="guardas" class="form-check-label"> <label for="use_for_tapa_dura" class="form-check-label">
<input type="checkbox" id="guardas" name="guardas" value="1" class="form-check-input" <?= $papelImpresion->guardas == true ? 'checked' : ''; ?>> <input <?= $papelImpresion->cubierta? ' ' : 'disabled ' ?> type="checkbox" id="useForTapaDura" name="use_for_tapa_dura" value="1" class="form-check-input"
<?= lang('PapelImpresion.guardas') ?> <?= $papelImpresion->use_for_tapa_dura == true ? 'checked' : ''; ?>>
</label> <?= lang('PapelImpresion.use_for_tapa_dura') ?>
</div><!--//.form-check --> </label>
</div><!--//.mb-3 --> </div><!--//.form-check -->
</div><!--//.mb-3 -->
<div class="mb-3"> <div class="mb-3">
<div class="form-check"> <div class="form-check">
<label for="rotativa" class="form-check-label"> <label for="guardas" class="form-check-label">
<input type="checkbox" id="rotativa" name="rotativa" value="1" class="form-check-input" <?= $papelImpresion->rotativa == true ? 'checked' : ''; ?>> <input type="checkbox" id="guardas" name="guardas" value="1" class="form-check-input"
<?= lang('PapelImpresion.rotativa') ?> <?= $papelImpresion->guardas == true ? 'checked' : ''; ?>>
</label> <?= lang('PapelImpresion.guardas') ?>
</div><!--//.form-check --> </label>
</div><!--//.mb-3 --> </div><!--//.form-check -->
</div><!--//.mb-3 -->
<div class="mb-3"> <div class="mb-3">
<div class="form-check"> <div class="form-check">
<label for="isActivo" class="form-check-label"> <label for="rotativa" class="form-check-label">
<input type="checkbox" id="isActivo" name="isActivo" value="1" class="form-check-input" <?= $papelImpresion->isActivo == true ? 'checked' : ''; ?>> <input type="checkbox" id="rotativa" name="rotativa" value="1" class="form-check-input"
<?= lang('PapelImpresion.activo') ?> <?= $papelImpresion->rotativa == true ? 'checked' : ''; ?>>
</label> <?= lang('PapelImpresion.rotativa') ?>
</div><!--//.form-check --> </label>
</div><!--//.mb-3 --> </div><!--//.form-check -->
</div><!--//.col --> </div><!--//.mb-3 -->
<div class="col-md-12 col-lg-6 px-4"> <div class="mb-3">
<div class="mb-3"> <div class="form-check">
<div class="form-check">
<label for="color" class="form-check-label"> <label for="isActivo" class="form-check-label">
<input type="checkbox" id="color" name="color" value="1" class="form-check-input" <?= $papelImpresion->color == true ? 'checked' : ''; ?>> <input type="checkbox" id="isActivo" name="isActivo" value="1" class="form-check-input"
<?= lang('PapelImpresion.color') ?> <?= $papelImpresion->isActivo == true ? 'checked' : ''; ?>>
</label> <?= lang('PapelImpresion.activo') ?>
</div><!--//.form-check --> </label>
</div><!--//.mb-3 --> </div><!--//.form-check -->
</div><!--//.mb-3 -->
<div class="mb-3"> <div class="mb-3">
<div class="form-check"> <div class="form-check">
<label for="useInClient" class="form-check-label">
<?= lang('PapelImpresion.useInClient') ?>
</label>
<input type="checkbox" id="useInClient" name="use_in_client" value="1" class="form-check-input"
<?= $papelImpresion->use_in_client == true ? 'checked' : ''; ?>>
</div><!--//.form-check -->
</div><!--//.mb-3 -->
</div><!--//.col -->
<label for="sobrecubierta" class="form-check-label"> <div class="col-md-12 col-lg-6 px-4">
<input type="checkbox" id="sobrecubierta" name="sobrecubierta" value="1" class="form-check-input" <?= $papelImpresion->sobrecubierta == true ? 'checked' : ''; ?>> <div class="mb-3">
<?= lang('PapelImpresion.sobrecubierta') ?> <div class="form-check">
</label>
</div><!--//.form-check -->
</div><!--//.mb-3 -->
<div class="mb-3"> <label for="color" class="form-check-label">
<div class="form-check"> <input type="checkbox" id="color" name="color" value="1" class="form-check-input"
<?= $papelImpresion->color == true ? 'checked' : ''; ?>>
<?= lang('PapelImpresion.color') ?>
</label>
</div><!--//.form-check -->
</div><!--//.mb-3 -->
<label for="inkjet" class="form-check-label"> <div class="mb-3">
<input type="checkbox" id="inkjet" name="inkjet" value="1" class="form-check-input" <?= $papelImpresion->inkjet == true ? 'checked' : ''; ?>> <div class="form-check">
<?= lang('PapelImpresion.inkjet') ?>
</label>
</div><!--//.form-check -->
</div><!--//.mb-3 -->
<div class="mb-3"> <label for="cubierta" class="form-check-label">
<div class="form-check"> <input type="checkbox" id="cubierta" name="cubierta" value="1" class="form-check-input"
<?= $papelImpresion->cubierta == true ? 'checked' : ''; ?>>
<?= lang('PapelImpresion.cubierta') ?>
</label>
</div><!--//.form-check -->
</div><!--//.mb-3 -->
<div class="mb-3">
<div class="form-check">
<label for="defecto" class="form-check-label"> <label for="sobrecubierta" class="form-check-label">
<input type="checkbox" id="defecto" name="defecto" value="1" class="form-check-input" <?= $papelImpresion->defecto == true ? 'checked' : ''; ?>> <input type="checkbox" id="sobrecubierta" name="sobrecubierta" value="1" class="form-check-input"
<?= lang('PapelImpresion.defecto') ?> <?= $papelImpresion->sobrecubierta == true ? 'checked' : ''; ?>>
</label> <?= lang('PapelImpresion.sobrecubierta') ?>
</div><!--//.form-check --> </label>
</div><!--//.mb-3 --> </div><!--//.form-check -->
</div><!--//.col --> </div><!--//.mb-3 -->
</div><!-- //.row -->
<div class="mb-3">
<div class="form-check">
<label for="inkjet" class="form-check-label">
<input type="checkbox" id="inkjet" name="inkjet" value="1" class="form-check-input"
<?= $papelImpresion->inkjet == true ? 'checked' : ''; ?>>
<?= lang('PapelImpresion.inkjet') ?>
</label>
</div><!--//.form-check -->
</div><!--//.mb-3 -->
<div class="mb-3">
<div class="form-check">
<label for="defecto" class="form-check-label">
<input type="checkbox" id="defecto" name="defecto" value="1" class="form-check-input"
<?= $papelImpresion->defecto == true ? 'checked' : ''; ?>>
<?= lang('PapelImpresion.defecto') ?>
</label>
</div><!--//.form-check -->
</div><!--//.mb-3 -->
</div><!--//.col -->
</div><!-- //.row -->

View File

@ -134,6 +134,16 @@
window.location.href = `/configuracion/papelesimpresion/edit/${$(this).attr('data-id')}`; window.location.href = `/configuracion/papelesimpresion/edit/${$(this).attr('data-id')}`;
}); });
$('#showInClientSpecial').on('change', function() {
if($(this).is(':checked')) {
$('#showInClient').prop('disabled', true);
$('#showInClient').prop('checked', true);
}
else{
$('#showInClient').prop('disabled', false);
}
});
<?=$this->endSection() ?> <?=$this->endSection() ?>

View File

@ -20,6 +20,7 @@
<th><?= lang('PapelGenerico.code') ?></th> <th><?= lang('PapelGenerico.code') ?></th>
<th><?= lang('PapelGenerico.codeOt') ?></th> <th><?= lang('PapelGenerico.codeOt') ?></th>
<th><?= lang('PapelGenerico.showInClient') ?></th> <th><?= lang('PapelGenerico.showInClient') ?></th>
<th><?= lang('PapelGenerico.showInClientSpecial') ?></th>
<th class="text-nowrap"><?= lang('Basic.global.Action') ?></th> <th class="text-nowrap"><?= lang('Basic.global.Action') ?></th>
</tr> </tr>
</thead> </thead>
@ -90,13 +91,14 @@
{ 'data': 'code' }, { 'data': 'code' },
{ 'data': 'code_ot' }, { 'data': 'code_ot' },
{ 'data': 'show_in_client' }, { 'data': 'show_in_client' },
{ 'data': 'show_in_client_special' },
{ 'data': actionBtns } { 'data': actionBtns }
] ]
}); });
theTable.on( 'draw.dt', function () { theTable.on( 'draw.dt', function () {
const boolCols = [3]; const boolCols = [3, 4];
for (let coln of boolCols) { for (let coln of boolCols) {
theTable.column(coln, { page: 'current' }).nodes().each( function (cell, i) { theTable.column(coln, { page: 'current' }).nodes().each( function (cell, i) {
cell.innerHTML = cell.innerHTML == '1' ? '<i class="ti ti-check"></i>' : ''; cell.innerHTML = cell.innerHTML == '1' ? '<i class="ti ti-check"></i>' : '';

View File

@ -403,6 +403,16 @@
`; `;
}; };
$('#cubierta').on('change', function() {
if($(this).is(':checked')) {
$('#useForTapaDura').prop('disabled', false);
$('#useForTapaDura').prop('checked', false);
}
else{
$('#useForTapaDura').prop('disabled', true);
}
});
// Etiquetas para las tipologias // Etiquetas para las tipologias
const tipoTypes = [ const tipoTypes = [
@ -757,7 +767,7 @@
} }
}) })
<?= $this->endSection() ?> <?= $this->endSection() ?>
<?php endif; ?> <?php endif; ?>

View File

@ -21,14 +21,17 @@
<th><?= lang('PapelImpresion.nombre') ?></th> <th><?= lang('PapelImpresion.nombre') ?></th>
<th><?= lang('PapelGenerico.papelGenerico') ?></th> <th><?= lang('PapelGenerico.papelGenerico') ?></th>
<th><?= lang('PapelImpresion.gramaje') ?></th> <th><?= lang('PapelImpresion.gramaje') ?></th>
<th><?= lang('PapelImpresion.interior') ?></th>
<th><?= lang('PapelImpresion.bn') ?></th> <th><?= lang('PapelImpresion.bn') ?></th>
<th><?= lang('PapelImpresion.color') ?></th> <th><?= lang('PapelImpresion.color') ?></th>
<th><?= lang('PapelImpresion.cubierta') ?></th> <th><?= lang('PapelImpresion.cubierta') ?></th>
<th><?= lang('PapelImpresion.use_for_tapa_dura') ?></th>
<th><?= lang('PapelImpresion.sobrecubierta') ?></th> <th><?= lang('PapelImpresion.sobrecubierta') ?></th>
<th><?= lang('PapelImpresion.guardas') ?></th> <th><?= lang('PapelImpresion.guardas') ?></th>
<th><?= lang('PapelImpresion.inkjet') ?></th> <th><?= lang('PapelImpresion.inkjet') ?></th>
<th><?= lang('PapelImpresion.rotativa') ?></th> <th><?= lang('PapelImpresion.rotativa') ?></th>
<th><?= lang('PapelImpresion.activo') ?></th> <th><?= lang('PapelImpresion.activo') ?></th>
<th><?= lang('PapelImpresion.useInClient') ?></th>
<th class="text-nowrap"><?= lang('Basic.global.Action') ?></th> <th class="text-nowrap"><?= lang('Basic.global.Action') ?></th>
</tr> </tr>
</thead> </thead>
@ -98,21 +101,24 @@
{ 'data': 'nombre' }, { 'data': 'nombre' },
{ 'data': 'papel_generico_id' }, { 'data': 'papel_generico_id' },
{ 'data': 'gramaje' }, { 'data': 'gramaje' },
{ 'data': 'interior' },
{ 'data': 'bn' }, { 'data': 'bn' },
{ 'data': 'color' }, { 'data': 'color' },
{ 'data': 'cubierta' }, { 'data': 'cubierta' },
{ 'data': 'use_for_tapa_dura'},
{ 'data': 'sobrecubierta' }, { 'data': 'sobrecubierta' },
{ 'data': 'guardas' }, { 'data': 'guardas' },
{ 'data': 'inkjet' }, { 'data': 'inkjet' },
{ 'data': 'rotativa' }, { 'data': 'rotativa' },
{ 'data': 'isActivo' }, { 'data': 'isActivo' },
{ 'data': 'use_in_client' },
{ 'data': actionBtns } { 'data': actionBtns }
] ]
}); });
theTable.on( 'draw.dt', function () { theTable.on( 'draw.dt', function () {
const boolCols = [3, 4, 5, 6, 7, 8, 9, 10]; const boolCols = [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
for (let coln of boolCols) { for (let coln of boolCols) {
theTable.column(coln, { page: 'current' }).nodes().each( function (cell, i) { theTable.column(coln, { page: 'current' }).nodes().each( function (cell, i) {
cell.innerHTML = cell.innerHTML == '1' ? '<i class="ti ti-check"></i>' : ''; cell.innerHTML = cell.innerHTML == '1' ? '<i class="ti ti-check"></i>' : '';

View File

@ -1,10 +1,73 @@
<?= $this->include("themes/_commonPartialsBs/select2bs5") ?> <?= $this->include('themes/_commonPartialsBs/select2bs5') ?>
<?= $this->include("themes/_commonPartialsBs/datatables") ?> <?= $this->include('themes/_commonPartialsBs/datatables') ?>
<?= $this->include('themes/_commonPartialsBs/_confirm2delete') ?>
<?= $this->extend('themes/vuexy/main/defaultlayout') ?> <?= $this->extend('themes/vuexy/main/defaultlayout') ?>
<?= $this->section('content'); ?> <?= $this->section('content'); ?>
<!--Content Body--> <!--Content Body-->
<div class="container-xxl flex-grow-1 container-p-y"> <div class="row">
<?= view("themes/vuexy/components/chat_general", data: ["modelId" => null]) ?> <div class="col-md-12">
<div class="nav-tabs-shadow nav-align-top">
<ul class="nav nav-tabs" role="tablist">
<li class="nav-item">
<button type="button" class="nav-link active" role="tab" id="navs-top-align-directos-tab" data-bs-toggle="tab" data-bs-target="#navs-top-align-directos">Directos</button>
</li>
<li class="nav-item">
<button type="button" class="nav-link" role="tab" id="navs-top-align-presupuestos-tab" data-bs-toggle="tab" data-bs-target="#navs-top-align-presupuestos">Presupuestos</button>
</li>
<li class="nav-item">
<button type="button" class="nav-link" role="tab" id="navs-top-align-pedidos-tab" data-bs-toggle="tab" data-bs-target="#navs-top-align-pedidos">Pedidos</button>
</li>
<li class="nav-item">
<button type="button" class="nav-link" role="tab" id="navs-top-align-facturas-tab" data-bs-toggle="tab" data-bs-target="#navs-top-align-facturas">Facturas</button>
</li>
</ul>
<div class="tab-content" id="message-datatables-container">
<div class="tab-pane fade show active" id="navs-top-align-directos">
<?php if (auth()->user()->inGroup('admin')) { ?>
<div class="row">
<div class="col-md-12 d-flex justify-content-start">
<button class="btn btn-primary" id="btn-new-message"><span class="ti ti-md ti-plus"></span>Nuevo mensaje</button>
</div>
</div>
<?php } ?>
<?= view("themes/vuexy/components/tables/messages_table", ["id" => "tableMessages"]) ?>
</div>
<div class="tab-pane fade show" id="navs-top-align-presupuestos">
<?= view("themes/vuexy/components/tables/messages_table", ["id" => "tablePresupuestoMessages"]) ?>
</div>
<div class="tab-pane fade show" id="navs-top-align-pedidos">
<?= view("themes/vuexy/components/tables/messages_table", ["id" => "tablePedidoMessages"]) ?>
</div>
<div class="tab-pane fade show" id="navs-top-align-facturas">
<?= view("themes/vuexy/components/tables/messages_table", ["id" => "tableFacturaMessages"]) ?>
</div>
</div>
<!--//.card -->
</div>
</div>
<!--//.col -->
</div> </div>
<?= view("themes/vuexy/components/modals/modalNewDirectMessage") ?>
<?= $this->endSection() ?>
<?= $this->section('css') ?>
<link rel="stylesheet" href="<?= site_url('themes/vuexy/vendor/libs/formvalidation/dist/css/formValidation.min.css') ?>" />
<link rel="stylesheet" href="<?= site_url('themes/vuexy/vendor/css/pages/app-chat.css') ?>">
<?= $this->endSection() ?>
<?= $this->section("additionalExternalJs") ?>
<script src="<?= site_url("themes/vuexy/vendor/libs/formvalidation/dist/js/FormValidation.js") ?>"></script>
<script src="<?= site_url("themes/vuexy/vendor/libs/formvalidation/dist/js/plugins/Bootstrap5.min.js") ?>"></script>
<script src="<?= site_url("themes/vuexy/vendor/libs/formvalidation/dist/js/plugins/AutoFocus.min.js") ?>"></script>
<script type="module" src="<?= site_url('assets/js/safekat/pages/configuracion/messages/index.js') ?>">
</script>
<?= $this->endSection() ?> <?= $this->endSection() ?>

View File

@ -0,0 +1,27 @@
<?= $this->include('themes/_commonPartialsBs/select2bs5') ?>
<?= $this->include('themes/_commonPartialsBs/datatables') ?>
<?= $this->include('themes/_commonPartialsBs/_confirm2delete') ?>
<?= $this->extend('themes/vuexy/main/defaultlayout') ?>
<?= $this->section('content'); ?>
<!--Content Body-->
<div class="row">
<?= view("themes/vuexy/components/chat_direct",["modelId" => $chatId,"userId" => auth()->user()->id]) ?>
</div>
<?= $this->endSection() ?>
<?= $this->section('css') ?>
<link rel="stylesheet" href="<?= site_url('themes/vuexy/vendor/libs/formvalidation/dist/css/formValidation.min.css') ?>" />
<link rel="stylesheet" href="<?= site_url('themes/vuexy/vendor/css/pages/app-chat.css') ?>">
<?= $this->endSection() ?>
<?= $this->section("additionalExternalJs") ?>
<script src="<?= site_url("themes/vuexy/vendor/libs/formvalidation/dist/js/FormValidation.js") ?>"></script>
<script src="<?= site_url("themes/vuexy/vendor/libs/formvalidation/dist/js/plugins/Bootstrap5.min.js") ?>"></script>
<script src="<?= site_url("themes/vuexy/vendor/libs/formvalidation/dist/js/plugins/AutoFocus.min.js") ?>"></script>
</script>
<?= $this->endSection() ?>

View File

@ -0,0 +1,30 @@
<?= $this->include('themes/_commonPartialsBs/select2bs5') ?>
<?= $this->include('themes/_commonPartialsBs/datatables') ?>
<?= $this->include('themes/_commonPartialsBs/_confirm2delete') ?>
<?= $this->extend('themes/vuexy/main/defaultlayout') ?>
<?= $this->section('content'); ?>
<!--Content Body-->
<div class="row">
<?= view("themes/vuexy/components/chat_factura",["modelId" => $modelId]) ?>
</div>
<?= $this->endSection() ?>
<?= $this->section('css') ?>
<link rel="stylesheet" href="<?= site_url('themes/vuexy/vendor/libs/formvalidation/dist/css/formValidation.min.css') ?>" />
<link rel="stylesheet" href="<?= site_url('themes/vuexy/vendor/css/pages/app-chat.css') ?>">
<?= $this->endSection() ?>
<?= $this->section("additionalExternalJs") ?>
<script src="<?= site_url("themes/vuexy/vendor/libs/formvalidation/dist/js/FormValidation.js") ?>"></script>
<script src="<?= site_url("themes/vuexy/vendor/libs/formvalidation/dist/js/plugins/Bootstrap5.min.js") ?>"></script>
<script src="<?= site_url("themes/vuexy/vendor/libs/formvalidation/dist/js/plugins/AutoFocus.min.js") ?>"></script>
</script>
<?= $this->endSection() ?>

View File

@ -0,0 +1,28 @@
<?= $this->include('themes/_commonPartialsBs/select2bs5') ?>
<?= $this->include('themes/_commonPartialsBs/datatables') ?>
<?= $this->include('themes/_commonPartialsBs/_confirm2delete') ?>
<?= $this->extend('themes/vuexy/main/defaultlayout') ?>
<?= $this->section('content'); ?>
<!--Content Body-->
<div class="row">
<?= view("themes/vuexy/components/internal_messages", data: ["modelId" => $modelId, "type" => $type]) ?>
</div>
<?= $this->endSection() ?>
<?= $this->section('css') ?>
<link rel="stylesheet" href="<?= site_url('themes/vuexy/vendor/libs/formvalidation/dist/css/formValidation.min.css') ?>" />
<link rel="stylesheet" href="<?= site_url('themes/vuexy/vendor/css/pages/app-chat.css') ?>">
<?= $this->endSection() ?>
<?= $this->section("additionalExternalJs") ?>
<script type="module" src="<?= site_url("assets/js/safekat/pages/messages/internalMessagePage.js") ?>"></script>
<script src="<?= site_url("themes/vuexy/vendor/libs/formvalidation/dist/js/FormValidation.js") ?>"></script>
<script src="<?= site_url("themes/vuexy/vendor/libs/formvalidation/dist/js/plugins/Bootstrap5.min.js") ?>"></script>
<script src="<?= site_url("themes/vuexy/vendor/libs/formvalidation/dist/js/plugins/AutoFocus.min.js") ?>"></script>
</script>
<?= $this->endSection() ?>

View File

@ -0,0 +1,27 @@
<?= $this->include('themes/_commonPartialsBs/select2bs5') ?>
<?= $this->include('themes/_commonPartialsBs/datatables') ?>
<?= $this->include('themes/_commonPartialsBs/_confirm2delete') ?>
<?= $this->extend('themes/vuexy/main/defaultlayout') ?>
<?= $this->section('content'); ?>
<!--Content Body-->
<div class="row">
<?= view("themes/vuexy/components/chat_pedido",["modelId" => $modelId]) ?>
</div>
<?= $this->endSection() ?>
<?= $this->section('css') ?>
<link rel="stylesheet" href="<?= site_url('themes/vuexy/vendor/libs/formvalidation/dist/css/formValidation.min.css') ?>" />
<link rel="stylesheet" href="<?= site_url('themes/vuexy/vendor/css/pages/app-chat.css') ?>">
<?= $this->endSection() ?>
<?= $this->section("additionalExternalJs") ?>
<script src="<?= site_url("themes/vuexy/vendor/libs/formvalidation/dist/js/FormValidation.js") ?>"></script>
<script src="<?= site_url("themes/vuexy/vendor/libs/formvalidation/dist/js/plugins/Bootstrap5.min.js") ?>"></script>
<script src="<?= site_url("themes/vuexy/vendor/libs/formvalidation/dist/js/plugins/AutoFocus.min.js") ?>"></script>
</script>
<?= $this->endSection() ?>

View File

@ -0,0 +1,27 @@
<?= $this->include('themes/_commonPartialsBs/select2bs5') ?>
<?= $this->include('themes/_commonPartialsBs/datatables') ?>
<?= $this->include('themes/_commonPartialsBs/_confirm2delete') ?>
<?= $this->extend('themes/vuexy/main/defaultlayout') ?>
<?= $this->section('content'); ?>
<!--Content Body-->
<div class="row">
<?= view("themes/vuexy/components/chat_presupuesto", ["modelId" => $modelId]) ?>
</div>
<?= $this->endSection() ?>
<?= $this->section('css') ?>
<link rel="stylesheet" href="<?= site_url('themes/vuexy/vendor/libs/formvalidation/dist/css/formValidation.min.css') ?>" />
<link rel="stylesheet" href="<?= site_url('themes/vuexy/vendor/css/pages/app-chat.css') ?>">
<?= $this->endSection() ?>
<?= $this->section("additionalExternalJs") ?>
<script src="<?= site_url("themes/vuexy/vendor/libs/formvalidation/dist/js/FormValidation.js") ?>"></script>
<script src="<?= site_url("themes/vuexy/vendor/libs/formvalidation/dist/js/plugins/Bootstrap5.min.js") ?>"></script>
<script src="<?= site_url("themes/vuexy/vendor/libs/formvalidation/dist/js/plugins/AutoFocus.min.js") ?>"></script>
</script>
<?= $this->endSection() ?>

View File

@ -125,7 +125,7 @@ var tableOfLineasPedido = new DataTable('#tableOfLineasPedido',{
$(document).on('click', '.btn-view', function(e) { $(document).on('click', '.btn-view', function(e) {
<?php if (auth()->user()->inGroup('admin') || auth()->user()->inGroup('beta')): ?> <?php if (auth()->user()->inGroup('admin') || auth()->user()->inGroup('beta')): ?>
var url = '<?= route_to('editarPresupuesto', ':id') ?>'; var url = '<?= route_to('editarPresupuestoAdmin', ':id') ?>';
<?php else: ?> <?php else: ?>
var url = '<?= route_to('editarPresupuestoCliente2', ':id') ?>'; var url = '<?= route_to('editarPresupuestoCliente2', ':id') ?>';
<?php endif; ?> <?php endif; ?>

View File

@ -9,7 +9,7 @@
<div id="accordionEnviosTip" class="accordion-collapse collapse show" data-bs-parent="#accordionEnvios"> <div id="accordionEnviosTip" class="accordion-collapse collapse show" data-bs-parent="#accordionEnvios">
<div class="accordion-body"> <div class="accordion-body">
<div id='alert-envios'></div> <div id='alert-envios'></div>
<?= view("themes/vuexy/form/presupuestos/cosidotapablanda/_presupuestoDireccionesForm") ?> <?= view("themes/vuexy/form/presupuestos/admin/_presupuestoDireccionesForm") ?>
<div id='rowTable' class='row'> <div id='rowTable' class='row'>
<table id="tableOfDireccionesEnvio" class="table dt-responsive dataTable px-2 update-resumen-presupuesto" style="width: 95%;"> <table id="tableOfDireccionesEnvio" class="table dt-responsive dataTable px-2 update-resumen-presupuesto" style="width: 95%;">
<thead> <thead>

View File

@ -45,7 +45,7 @@
<div class="divider divider-dark text-start mb-1"> <div class="divider divider-dark text-start mb-1">
<div class="divider-text"> <div class="divider-text">
<h5><?= lang("Presupuestos.papelesComparadorCosidoTapaBlanda") ?></h5> <h5><?= lang("Presupuestos.papelesComparadorPresupuestoAdmin") ?></h5>
</div> </div>
</div> </div>
@ -587,7 +587,7 @@
allowClear: false, allowClear: false,
minimumResultsForSearch: Infinity, minimumResultsForSearch: Infinity,
ajax: { ajax: {
url: '<?= route_to("menuItemsOfCosidotapablanda") ?>', url: '<?= route_to("menuItemsOfPresupuestoAdmin") ?>',
type: 'post', type: 'post',
dataType: 'json', dataType: 'json',
@ -620,7 +620,7 @@
allowClear: false, allowClear: false,
minimumResultsForSearch: Infinity, minimumResultsForSearch: Infinity,
ajax: { ajax: {
url: '<?= route_to("menuItemsOfCosidotapablanda") ?>', url: '<?= route_to("menuItemsOfPresupuestoAdmin") ?>',
type: 'post', type: 'post',
dataType: 'json', dataType: 'json',
@ -658,7 +658,7 @@
allowClear: false, allowClear: false,
minimumResultsForSearch: Infinity, minimumResultsForSearch: Infinity,
ajax: { ajax: {
url: '<?= route_to("menuItemsOfCosidotapablanda") ?>', url: '<?= route_to("menuItemsOfPresupuestoAdmin") ?>',
type: 'post', type: 'post',
dataType: 'json', dataType: 'json',
@ -687,7 +687,7 @@
allowClear: false, allowClear: false,
minimumResultsForSearch: Infinity, minimumResultsForSearch: Infinity,
ajax: { ajax: {
url: '<?= route_to("menuItemsOfCosidotapablanda") ?>', url: '<?= route_to("menuItemsOfPresupuestoAdmin") ?>',
type: 'post', type: 'post',
data: function (params) { data: function (params) {
@ -1104,7 +1104,7 @@
$.ajax({ $.ajax({
type: "POST", type: "POST",
url: "/cosidotapablanda/datatable", url: "/presupuestoadmin/datatable",
data: datos, data: datos,
success: function (data) { success: function (data) {
@ -1173,7 +1173,7 @@
$.ajax({ $.ajax({
type: "POST", type: "POST",
url: "/cosidotapablanda/datatable", url: "/presupuestoadmin/datatable",
data: datos, data: datos,
success: function (data) { success: function (data) {
@ -1252,7 +1252,7 @@
$.ajax({ $.ajax({
type: "POST", type: "POST",
url: "/cosidotapablanda/datatable", url: "/presupuestoadmin/datatable",
data: datos, data: datos,
success: function (data) { success: function (data) {
@ -1331,7 +1331,7 @@
$.ajax({ $.ajax({
type: "POST", type: "POST",
url: "/cosidotapablanda/datatable", url: "/presupuestoadmin/datatable",
data: datos, data: datos,
success: function (data) { success: function (data) {
@ -1412,7 +1412,7 @@
$.ajax({ $.ajax({
type: "POST", type: "POST",
url: "/cosidotapablanda/datatable", url: "/presupuestoadmin/datatable",
data: datos, data: datos,
success: function (data) { success: function (data) {
@ -1609,7 +1609,7 @@
allowClear: false, allowClear: false,
minimumResultsForSearch: Infinity, minimumResultsForSearch: Infinity,
ajax: { ajax: {
url: '<?= route_to("menuItemsOfCosidotapablanda") ?>', url: '<?= route_to("menuItemsOfPresupuestoAdmin") ?>',
type: 'post', type: 'post',
dataType: 'json', dataType: 'json',
@ -1653,7 +1653,7 @@
allowClear: false, allowClear: false,
minimumResultsForSearch: Infinity, minimumResultsForSearch: Infinity,
ajax: { ajax: {
url: '<?= route_to("menuItemsOfCosidotapablanda") ?>', url: '<?= route_to("menuItemsOfPresupuestoAdmin") ?>',
type: 'post', type: 'post',
dataType: 'json', dataType: 'json',
@ -1699,7 +1699,7 @@
allowClear: false, allowClear: false,
minimumResultsForSearch: Infinity, minimumResultsForSearch: Infinity,
ajax: { ajax: {
url: '<?= route_to("menuItemsOfCosidotapablanda") ?>', url: '<?= route_to("menuItemsOfPresupuestoAdmin") ?>',
type: 'post', type: 'post',
dataType: 'json', dataType: 'json',
@ -1745,7 +1745,7 @@
allowClear: false, allowClear: false,
minimumResultsForSearch: Infinity, minimumResultsForSearch: Infinity,
ajax: { ajax: {
url: '<?= route_to("menuItemsOfCosidotapablanda") ?>', url: '<?= route_to("menuItemsOfPresupuestoAdmin") ?>',
type: 'post', type: 'post',
dataType: 'json', dataType: 'json',
@ -1787,7 +1787,7 @@
allowClear: false, allowClear: false,
minimumResultsForSearch: Infinity, minimumResultsForSearch: Infinity,
ajax: { ajax: {
url: '<?= route_to("menuItemsOfCosidotapablanda") ?>', url: '<?= route_to("menuItemsOfPresupuestoAdmin") ?>',
type: 'post', type: 'post',
dataType: 'json', dataType: 'json',
@ -1834,7 +1834,7 @@
allowClear: false, allowClear: false,
minimumResultsForSearch: Infinity, minimumResultsForSearch: Infinity,
ajax: { ajax: {
url: '<?= route_to("menuItemsOfCosidotapablanda") ?>', url: '<?= route_to("menuItemsOfPresupuestoAdmin") ?>',
type: 'post', type: 'post',
dataType: 'json', dataType: 'json',

View File

@ -777,7 +777,7 @@ function convertirTiempo(horas){
// se convierte a formato hh:mm:ss // se convierte a formato hh:mm:ss
const h = Math.floor(seconds / 3600); const h = Math.floor(seconds / 3600);
const minutos = Math.floor((seconds % 3600) / 60); const minutos = Math.floor((seconds % 3600) / 60);
const segundos = seconds % 60; const segundos = Math.round(seconds % 60, 0);
return h + ':' + minutos + ':' + segundos; return h + ':' + minutos + ':' + segundos;
} }
else{ else{

View File

@ -318,6 +318,8 @@
init_servicio_extra() init_servicio_extra()
/* ELIMINADO PARA COMPROBAR EL MAXIMO DE SOLAPAS DESDE EL BACKEND
PENDIENTE
$('.solapas_cubierta').on('change', function(){ $('.solapas_cubierta').on('change', function(){
const ancho_libro = getDimensionLibro().ancho; const ancho_libro = getDimensionLibro().ancho;
@ -337,6 +339,7 @@
} }
$('#compGramajeCubierta').trigger('change') $('#compGramajeCubierta').trigger('change')
}) })
@ -360,5 +363,7 @@
$('#compGramajeSobrecubierta').trigger('change') $('#compGramajeSobrecubierta').trigger('change')
}) })
*/
<?= $this->endSection() ?> <?= $this->endSection() ?>

View File

@ -275,7 +275,7 @@ async function fill_bbdd_from_lp(presupuesto_id){
await $.ajax({ await $.ajax({
type: 'post', type: 'post',
url: window.routes_lp.updateDataOfCosidotapablanda, url: window.routes_lp.updateDataOfPresupuestoAdmin,
data: datos, data: datos,
dataType: 'json', dataType: 'json',
@ -1528,7 +1528,7 @@ async function set_lp_bn_gramaje(mantenerSeleccion = false){
await $.ajax({ await $.ajax({
type: 'post', type: 'post',
url: window.routes_lp.menuItemsOfCosidotapablanda, url: window.routes_lp.menuItemsOfPresupuestoAdmin,
beforeSend: function() { beforeSend: function() {
$('#lp_bn_gramaje').empty() $('#lp_bn_gramaje').empty()
}, },
@ -1568,7 +1568,7 @@ async function set_lp_bn_papelImpresion(){
await $.ajax({ await $.ajax({
type: 'post', type: 'post',
url: window.routes_lp.menuItemsOfCosidotapablanda, url: window.routes_lp.menuItemsOfPresupuestoAdmin,
beforeSend: function() { beforeSend: function() {
$('#lp_bn_papelImpresion').empty() $('#lp_bn_papelImpresion').empty()
$('#lp_bn_maquina').empty() $('#lp_bn_maquina').empty()
@ -1604,7 +1604,7 @@ async function set_lp_bn_maquina(){
await $.ajax({ await $.ajax({
type: 'post', type: 'post',
url: window.routes_lp.menuItemsOfCosidotapablanda, url: window.routes_lp.menuItemsOfPresupuestoAdmin,
beforeSend: function() { beforeSend: function() {
$('#lp_bn_maquina').empty() $('#lp_bn_maquina').empty()
clear_lp_bn(false) clear_lp_bn(false)
@ -1676,7 +1676,7 @@ async function calcularPresupuesto_bn(input_data={}, updatedTipologias = false){
await $.ajax({ await $.ajax({
type: "POST", type: "POST",
url: "/cosidotapablanda/datatable", url: "/presupuestoadmin/datatable",
data: datos, data: datos,
success: function (data) { success: function (data) {
@ -1903,7 +1903,7 @@ async function set_lp_color_gramaje(mantenerSeleccion = false){
await $.ajax({ await $.ajax({
type: 'post', type: 'post',
url: window.routes_lp.menuItemsOfCosidotapablanda, url: window.routes_lp.menuItemsOfPresupuestoAdmin,
beforeSend: function() { beforeSend: function() {
$('#lp_color_gramaje').empty() $('#lp_color_gramaje').empty()
}, },
@ -1941,7 +1941,7 @@ async function set_lp_color_papelImpresion(){
await $.ajax({ await $.ajax({
type: 'post', type: 'post',
url: window.routes_lp.menuItemsOfCosidotapablanda, url: window.routes_lp.menuItemsOfPresupuestoAdmin,
beforeSend: function() { beforeSend: function() {
$('#lp_color_papelImpresion').empty() $('#lp_color_papelImpresion').empty()
$('#lp_color_maquina').empty() $('#lp_color_maquina').empty()
@ -1977,7 +1977,7 @@ async function set_lp_color_maquina(){
await $.ajax({ await $.ajax({
type: 'post', type: 'post',
url: window.routes_lp.menuItemsOfCosidotapablanda, url: window.routes_lp.menuItemsOfPresupuestoAdmin,
beforeSend: function() { beforeSend: function() {
$('#lp_color_maquina').empty() $('#lp_color_maquina').empty()
clear_lp_color(false) clear_lp_color(false)
@ -2048,7 +2048,7 @@ async function calcularPresupuesto_color(input_data={}, updatedTipologias = fals
await $.ajax({ await $.ajax({
type: "POST", type: "POST",
url: "/cosidotapablanda/datatable", url: "/presupuestoadmin/datatable",
data: datos, data: datos,
success: function (data) { success: function (data) {
@ -2269,7 +2269,7 @@ async function set_lp_bnhq_gramaje(mantenerSeleccion = false){
await $.ajax({ await $.ajax({
type: 'post', type: 'post',
url: window.routes_lp.menuItemsOfCosidotapablanda, url: window.routes_lp.menuItemsOfPresupuestoAdmin,
beforeSend: function() { beforeSend: function() {
$('#lp_bnhq_gramaje').empty() $('#lp_bnhq_gramaje').empty()
}, },
@ -2307,7 +2307,7 @@ async function set_lp_bnhq_papelImpresion(){
await $.ajax({ await $.ajax({
type: 'post', type: 'post',
url: window.routes_lp.menuItemsOfCosidotapablanda, url: window.routes_lp.menuItemsOfPresupuestoAdmin,
beforeSend: function() { beforeSend: function() {
$('#lp_bnhq_papelImpresion').empty() $('#lp_bnhq_papelImpresion').empty()
$('#lp_bnhq_maquina').empty() $('#lp_bnhq_maquina').empty()
@ -2343,7 +2343,7 @@ async function set_lp_bnhq_maquina(){
await $.ajax({ await $.ajax({
type: 'post', type: 'post',
url: window.routes_lp.menuItemsOfCosidotapablanda, url: window.routes_lp.menuItemsOfPresupuestoAdmin,
beforeSend: function() { beforeSend: function() {
$('#lp_bnhq_maquina').empty() $('#lp_bnhq_maquina').empty()
clear_lp_bnhq(false) clear_lp_bnhq(false)
@ -2484,7 +2484,7 @@ async function calcularPresupuesto_bnhq(input_data={}, updatedTipologias = false
await $.ajax({ await $.ajax({
type: "POST", type: "POST",
url: "/cosidotapablanda/datatable", url: "/presupuestoadmin/datatable",
data: datos, data: datos,
success: function (data) { success: function (data) {
@ -2633,7 +2633,7 @@ async function set_lp_colorhq_gramaje(mantenerSeleccion = false){
await $.ajax({ await $.ajax({
type: 'post', type: 'post',
url: window.routes_lp.menuItemsOfCosidotapablanda, url: window.routes_lp.menuItemsOfPresupuestoAdmin,
beforeSend: function() { beforeSend: function() {
$('#lp_colorhq_gramaje').empty() $('#lp_colorhq_gramaje').empty()
}, },
@ -2671,7 +2671,7 @@ async function set_lp_colorhq_papelImpresion(){
await $.ajax({ await $.ajax({
type: 'post', type: 'post',
url: window.routes_lp.menuItemsOfCosidotapablanda, url: window.routes_lp.menuItemsOfPresupuestoAdmin,
beforeSend: function() { beforeSend: function() {
$('#lp_colorhq_papelImpresion').empty() $('#lp_colorhq_papelImpresion').empty()
$('#lp_colorhq_maquina').empty() $('#lp_colorhq_maquina').empty()
@ -2707,7 +2707,7 @@ async function set_lp_colorhq_maquina(){
await $.ajax({ await $.ajax({
type: 'post', type: 'post',
url: window.routes_lp.menuItemsOfCosidotapablanda, url: window.routes_lp.menuItemsOfPresupuestoAdmin,
beforeSend: function() { beforeSend: function() {
$('#lp_colorhq_maquina').empty() $('#lp_colorhq_maquina').empty()
clear_lp_colorhq(false) clear_lp_colorhq(false)
@ -2854,7 +2854,7 @@ async function calcularPresupuesto_colorhq(input_data={}, updatedTipologias = fa
await $.ajax({ await $.ajax({
type: "POST", type: "POST",
url: "/cosidotapablanda/datatable", url: "/presupuestoadmin/datatable",
data: datos, data: datos,
success: function (data) { success: function (data) {
@ -3004,7 +3004,7 @@ async function set_lp_rot_bn_gramaje(mantenerSeleccion = false){
await $.ajax({ await $.ajax({
type: 'post', type: 'post',
url: window.routes_lp.menuItemsOfCosidotapablanda, url: window.routes_lp.menuItemsOfPresupuestoAdmin,
beforeSend: function() { beforeSend: function() {
$('#lp_rot_bn_gramaje').empty() $('#lp_rot_bn_gramaje').empty()
}, },
@ -3042,7 +3042,7 @@ async function set_lp_rot_bn_papelImpresion(){
await $.ajax({ await $.ajax({
type: 'post', type: 'post',
url: window.routes_lp.menuItemsOfCosidotapablanda, url: window.routes_lp.menuItemsOfPresupuestoAdmin,
beforeSend: function() { beforeSend: function() {
$('#lp_rot_bn_papelImpresion').empty() $('#lp_rot_bn_papelImpresion').empty()
$('#lp_rot_bn_maquina').empty() $('#lp_rot_bn_maquina').empty()
@ -3077,7 +3077,7 @@ async function set_lp_rot_bn_maquina(){
await $.ajax({ await $.ajax({
type: 'post', type: 'post',
url: window.routes_lp.menuItemsOfCosidotapablanda, url: window.routes_lp.menuItemsOfPresupuestoAdmin,
beforeSend: function() { beforeSend: function() {
$('#lp_rot_bn_maquina').empty() $('#lp_rot_bn_maquina').empty()
clear_lp_rot_bn(false) clear_lp_rot_bn(false)
@ -3192,7 +3192,7 @@ async function calcularPresupuesto_rot_bn(fromComparador=false, updatedTipologia
await $.ajax({ await $.ajax({
type: "POST", type: "POST",
url: "/cosidotapablanda/datatable", url: "/presupuestoadmin/datatable",
data: datos, data: datos,
success: function (data) { success: function (data) {
@ -3376,7 +3376,7 @@ async function set_lp_rot_color_gramaje(mantenerSeleccion = false){
await $.ajax({ await $.ajax({
type: 'post', type: 'post',
url: window.routes_lp.menuItemsOfCosidotapablanda, url: window.routes_lp.menuItemsOfPresupuestoAdmin,
beforeSend: function() { beforeSend: function() {
$('#lp_rot_color_gramaje').empty() $('#lp_rot_color_gramaje').empty()
}, },
@ -3414,7 +3414,7 @@ async function set_lp_rot_color_papelImpresion(){
await $.ajax({ await $.ajax({
type: 'post', type: 'post',
url: window.routes_lp.menuItemsOfCosidotapablanda, url: window.routes_lp.menuItemsOfPresupuestoAdmin,
beforeSend: function() { beforeSend: function() {
$('#lp_rot_color_papelImpresion').empty() $('#lp_rot_color_papelImpresion').empty()
$('#lp_rot_color_maquina').empty() $('#lp_rot_color_maquina').empty()
@ -3450,7 +3450,7 @@ async function set_lp_rot_color_maquina(){
await $.ajax({ await $.ajax({
type: 'post', type: 'post',
url: window.routes_lp.menuItemsOfCosidotapablanda, url: window.routes_lp.menuItemsOfPresupuestoAdmin,
beforeSend: function() { beforeSend: function() {
$('#lp_rot_color_maquina').empty() $('#lp_rot_color_maquina').empty()
clear_lp_rot_color(false) clear_lp_rot_color(false)
@ -3571,7 +3571,7 @@ async function calcularPresupuesto_rot_color(fromComparador=false, updatedTipolo
await $.ajax({ await $.ajax({
type: "POST", type: "POST",
url: "/cosidotapablanda/datatable", url: "/presupuestoadmin/datatable",
data: datos, data: datos,
success: function (data) { success: function (data) {
@ -3753,7 +3753,7 @@ async function set_lp_cubierta_gramaje(mantenerSeleccion = false){
await $.ajax({ await $.ajax({
type: 'post', type: 'post',
url: window.routes_lp.menuItemsOfCosidotapablanda, url: window.routes_lp.menuItemsOfPresupuestoAdmin,
beforeSend: function() { beforeSend: function() {
$('#lp_cubierta_gramaje').empty() $('#lp_cubierta_gramaje').empty()
}, },
@ -3792,7 +3792,7 @@ async function set_lp_cubierta_papelImpresion(){
await $.ajax({ await $.ajax({
type: 'post', type: 'post',
url: window.routes_lp.menuItemsOfCosidotapablanda, url: window.routes_lp.menuItemsOfPresupuestoAdmin,
beforeSend: function() { beforeSend: function() {
$('#lp_cubierta_papelImpresion').empty() $('#lp_cubierta_papelImpresion').empty()
$('#lp_cubierta_maquina').empty() $('#lp_cubierta_maquina').empty()
@ -3829,7 +3829,7 @@ async function set_lp_cubierta_maquina(){
await $.ajax({ await $.ajax({
type: 'post', type: 'post',
url: window.routes_lp.menuItemsOfCosidotapablanda, url: window.routes_lp.menuItemsOfPresupuestoAdmin,
beforeSend: function() { beforeSend: function() {
$('#lp_cubierta_maquina').empty() $('#lp_cubierta_maquina').empty()
clear_lp_cubierta(false) clear_lp_cubierta(false)
@ -3919,7 +3919,7 @@ async function calcularPresupuesto_cubierta(fromComparador=false, input_data={})
await $.ajax({ await $.ajax({
type: "POST", type: "POST",
url: "/cosidotapablanda/datatable", url: "/presupuestoadmin/datatable",
data: datos, data: datos,
success: function (data) { success: function (data) {
@ -4066,7 +4066,7 @@ async function set_lp_sobrecubierta_gramaje(mantenerSeleccion = false){
await $.ajax({ await $.ajax({
type: 'post', type: 'post',
url: window.routes_lp.menuItemsOfCosidotapablanda, url: window.routes_lp.menuItemsOfPresupuestoAdmin,
beforeSend: function() { beforeSend: function() {
$('#lp_sobrecubierta_gramaje').empty() $('#lp_sobrecubierta_gramaje').empty()
}, },
@ -4105,7 +4105,7 @@ async function set_lp_sobrecubierta_papelImpresion(){
await $.ajax({ await $.ajax({
type: 'post', type: 'post',
url: window.routes_lp.menuItemsOfCosidotapablanda, url: window.routes_lp.menuItemsOfPresupuestoAdmin,
beforeSend: function() { beforeSend: function() {
$('#lp_sobrecubierta_papelImpresion').empty() $('#lp_sobrecubierta_papelImpresion').empty()
$('#lp_sobrecubierta_maquina').empty() $('#lp_sobrecubierta_maquina').empty()
@ -4142,7 +4142,7 @@ async function set_lp_sobrecubierta_maquina(){
await $.ajax({ await $.ajax({
type: 'post', type: 'post',
url: window.routes_lp.menuItemsOfCosidotapablanda, url: window.routes_lp.menuItemsOfPresupuestoAdmin,
beforeSend: function() { beforeSend: function() {
$('#lp_sobrecubierta_maquina').empty() $('#lp_sobrecubierta_maquina').empty()
clear_lp_sobrecubierta(false) clear_lp_sobrecubierta(false)
@ -4215,7 +4215,7 @@ async function calcularPresupuesto_sobrecubierta(fromComparador=false, input_dat
await $.ajax({ await $.ajax({
type: "POST", type: "POST",
url: "/cosidotapablanda/datatable", url: "/presupuestoadmin/datatable",
data: datos, data: datos,
success: function (data) { success: function (data) {
@ -4436,7 +4436,7 @@ async function calcularPresupuesto_guardas(fromComparador=false, input_data={}){
await $.ajax({ await $.ajax({
type: "POST", type: "POST",
url: "/cosidotapablanda/datatable", url: "/presupuestoadmin/datatable",
data: datos, data: datos,
success: function (data) { success: function (data) {
@ -4609,7 +4609,7 @@ async function set_lp_guardas_maquina(){
await $.ajax({ await $.ajax({
type: 'post', type: 'post',
url: window.routes_lp.menuItemsOfCosidotapablanda, url: window.routes_lp.menuItemsOfPresupuestoAdmin,
beforeSend: function() { beforeSend: function() {
$('#lp_guardas_maquina').empty() $('#lp_guardas_maquina').empty()
clear_lp_guardas(false) clear_lp_guardas(false)
@ -4640,7 +4640,7 @@ async function set_lp_guardas_papelImpresion(){
await $.ajax({ await $.ajax({
type: 'post', type: 'post',
url: window.routes_lp.menuItemsOfCosidotapablanda, url: window.routes_lp.menuItemsOfPresupuestoAdmin,
beforeSend: function() { beforeSend: function() {
$('#lp_guardas_papelImpresion').empty() $('#lp_guardas_papelImpresion').empty()
$('#lp_guardas_maquina').empty() $('#lp_guardas_maquina').empty()

View File

@ -90,8 +90,8 @@ window.papelGenericoRotativaColorList = <?php echo json_encode($papelGenericoRot
window.lineasPresupuestoList = <?php echo json_encode($lineasPresupuesto); ?>; window.lineasPresupuestoList = <?php echo json_encode($lineasPresupuesto); ?>;
window.routes_lp = { window.routes_lp = {
menuItemsOfCosidotapablanda: '<?= route_to("menuItemsOfCosidotapablanda") ?>', menuItemsOfPresupuestoAdmin: '<?= route_to("menuItemsOfPresupuestoAdmin") ?>',
updateDataOfCosidotapablanda: '<?= route_to("updateDataOfCosidotapablanda") ?>', updateDataOfPresupuestoAdmin: '<?= route_to("updateDataOfPresupuestoAdmin") ?>',
} }

View File

@ -10,7 +10,7 @@
<div class="card card-info"> <div class="card card-info">
<div class="card-header"> <div class="card-header">
<h3 class="card-title"><?= $pageTitle ?></h3> <h3 class="card-title"><?= $pageTitle ?></h3>
<?=anchor(route_to('newCosidotapablanda', $tipo_impresion_id), lang('Basic.global.addNew').' '.lang('Presupuestos.presupuesto'), ['class'=>'btn btn-primary ']); ?> <?=anchor(route_to('newPresupuestoAdmin', $tipo_impresion_id), lang('Basic.global.addNew').' '.lang('Presupuestos.presupuesto'), ['class'=>'btn btn-primary ']); ?>
</div><!--//.card-header --> </div><!--//.card-header -->
<div class="card-body"> <div class="card-body">
<?= view('themes/_commonPartialsBs/_alertBoxes'); ?> <?= view('themes/_commonPartialsBs/_alertBoxes'); ?>
@ -164,7 +164,7 @@ theTable = $('#tableOfPresupuestos').DataTable({
url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json" url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json"
}, },
ajax : $.fn.dataTable.pipeline( { ajax : $.fn.dataTable.pipeline( {
url: '<?= route_to('dataTableOfCosidotapablanda') ?>', url: '<?= route_to('dataTableOfPresupuestoAdmin') ?>',
data: function (d) { data: function (d) {
d.tipo_impresion_id = '<?php echo $tipo_impresion_id; ?>'; d.tipo_impresion_id = '<?php echo $tipo_impresion_id; ?>';
}, },
@ -231,7 +231,7 @@ theTable.on( 'draw.dt', function () {
$(document).on('click', '.btn-edit', function(e) { $(document).on('click', '.btn-edit', function(e) {
window.location.href = `/presupuestos/cosidotapablanda/edit/${$(this).attr('data-id')}/`; window.location.href = `/presupuestoadmin/edit/${$(this).attr('data-id')}/`;
}); });
@ -245,7 +245,7 @@ $(document).on('click', '.btn-remove', function(e) {
const row = $(this).closest('tr'); const row = $(this).closest('tr');
if ($.isNumeric(dataId)) { if ($.isNumeric(dataId)) {
$.ajax({ $.ajax({
url: `/presupuestos/cosidotapablanda/delete/${dataId}`, url: `/presupuestoadmin/delete/${dataId}`,
method: 'GET', method: 'GET',
}).done((data, textStatus, jqXHR) => { }).done((data, textStatus, jqXHR) => {
$('#confirm2delete').modal('toggle'); $('#confirm2delete').modal('toggle');

Some files were not shown because too many files have changed in this diff Show More