diff --git a/ci4/app/Config/Routes.php b/ci4/app/Config/Routes.php index 9e90e035..529ce510 100755 --- a/ci4/app/Config/Routes.php +++ b/ci4/app/Config/Routes.php @@ -534,11 +534,11 @@ $routes->group('cosidotapablanda', ['namespace' => 'App\Controllers\Presupuestos $routes->resource('cosidotapablanda', ['namespace' => 'App\Controllers\Presupuestos', 'controller' => 'Cosidotapablanda', 'except' => 'show,new,create,update']); $routes->group('presupuestocliente', ['namespace' => 'App\Controllers\Presupuestos'], function ($routes) { - $routes->get('list/(:num)', 'Presupuestocliente::list/$1', ['as' => 'listarPresupuestoCliente']); // HOMOGENIZAR CON ARGS DINAMICOS!!! + $routes->get('list', 'Presupuestocliente::list', ['as' => 'listaPresupuestos']); + $routes->post('datatable', 'Presupuestocliente::datatable', ['as' => 'datatableOfPresupuestos']); $routes->get('add', 'Presupuestocliente::add', ['as' => 'nuevoPresupuestoCliente']); $routes->post('add', 'Presupuestocliente::add', ['as' => 'crearPresupuestoCliente']); $routes->post('edit/(:num)', 'Presupuestocliente::edit/$1', ['as' => 'editarPresupuestoCliente']); - $routes->post('datatable', 'Cosidotapablanda::datatable', ['as' => 'tablaPresupuestosCliente']); $routes->post('getgramaje', 'Presupuestocliente::getGramaje', ['as' => 'obtenerGramaje']); $routes->post('presupuesto', 'Presupuestocliente::presupuesto', ['as' => 'presupuestoCliente']); $routes->post('getDireccionesCliente', 'Presupuestocliente::getDireccionesCliente', ['as' => 'getDirecciones']); diff --git a/ci4/app/Controllers/Presupuestos/Buscador.php b/ci4/app/Controllers/Presupuestos/Buscador.php index ef261dea..30b7b53e 100644 --- a/ci4/app/Controllers/Presupuestos/Buscador.php +++ b/ci4/app/Controllers/Presupuestos/Buscador.php @@ -97,11 +97,11 @@ class Buscador extends \App\Controllers\BaseResourceController $order1 = PresupuestoModel::SORTABLE[$requestedOrder1 >= 0 ? $requestedOrder1 : 0]; $dir1 = $reqData['order']['0']['dir'] ?? 'asc'; $requestedOrder2 = $reqData['order']['1']['column'] ?? 0; - $order2 = PresupuestoModel::SORTABLE[$requestedOrder2 >= 0 ? $requestedOrder1 : 0]; - $dir2 = $reqData['order']['0']['dir'] ?? 'asc'; + $order2 = PresupuestoModel::SORTABLE[$requestedOrder2 >= 0 ? $requestedOrder2 : 0]; + $dir2 = $reqData['order']['1']['dir'] ?? 'asc'; $requestedOrder3 = $reqData['order']['2']['column'] ?? 0; - $order3 = PresupuestoModel::SORTABLE[$requestedOrder3 >= 0 ? $requestedOrder1 : 0]; - $dir3 = $reqData['order']['0']['dir'] ?? 'asc'; + $order3 = PresupuestoModel::SORTABLE[$requestedOrder3 >= 0 ? $requestedOrder3 : 0]; + $dir3 = $reqData['order']['2']['dir'] ?? 'asc'; $searchValues = get_filter_datatables_columns($reqData); diff --git a/ci4/app/Controllers/Presupuestos/Presupuestocliente.php b/ci4/app/Controllers/Presupuestos/Presupuestocliente.php index 1d200354..4f434328 100755 --- a/ci4/app/Controllers/Presupuestos/Presupuestocliente.php +++ b/ci4/app/Controllers/Presupuestos/Presupuestocliente.php @@ -15,6 +15,7 @@ use App\Models\Presupuestos\PresupuestoModel; use App\Models\Presupuestos\PresupuestoPreimpresionesModel; use App\Models\Presupuestos\PresupuestoServiciosExtraModel; use App\Services\PresupuestoClienteService; +use App\Services\PresupuestoService; use Exception; use function PHPUnit\Framework\containsOnly; @@ -33,7 +34,7 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController protected static $viewPath = 'themes/vuexy/form/presupuestos/cliente/'; - protected $indexRoute = 'cosidotapablandaList'; + protected $indexRoute = 'listaPresupuestos'; @@ -54,90 +55,30 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController } - public function list($tipo_impresion_id = 4) + public function list() { $viewData = [ 'currentModule' => static::$controllerSlug, 'pageSubTitle' => lang('Basic.global.ManageAllRecords', [lang('Presupuestos.presupuesto')]), 'presupuestoEntity' => new PresupuestoEntity(), 'usingServerSideDataTable' => true, - 'tipo_impresion_id' => $tipo_impresion_id + 'pageTitle' => lang('Presupuestos.presupuestos'), ]; - $viewData = array_merge($viewData, $this->getStringsFromTipoImpresion($tipo_impresion_id)); - $viewData = array_merge($this->viewData, $viewData); // merge any possible values from the parent controller class + if (auth()->user()->inGroup('cliente-admin') || auth()->user()->inGroup('cliente-editor')) { + $clienteId = 999; // Fijo hasta desarollar clientes usuarios + } else { + $clienteId = 0; + } - - return view(static::$viewPath . 'viewCosidotapablandaList', $viewData); + $viewData['clienteId'] = $clienteId; + return view(static::$viewPath . 'viewPresupuestoList', $viewData); } public function add() { - - // JJO - $session = session(); - - $requestMethod = $this->request->getMethod(); - - if ($requestMethod === 'post') : - - $nullIfEmpty = true; // !(phpversion() >= '8.1'); - - $postData = $this->request->getPost(); - - $sanitizedData = $this->sanitized($postData, $nullIfEmpty); - - // JJO - $sanitizedData['user_created_id'] = $session->id_user; - - if (!isset($sanitizedData['papel_formato_id']) || $sanitizedData['papel_formato_id'] == null) { - $sanitizedData['papel_formato_id'] = 0; - } - - if (!isset($sanitizedData['is_duplicado']) || $sanitizedData['is_duplicado'] == null) { - $sanitizedData['is_duplicado'] = 0; - } - - $noException = true; - if ($successfulResult = $this->canValidate($this->model->validationRulesAdd, $this->model->validationMessagesAdd)) : // if ($successfulResult = $this->validate($this->formValidationRules) ) : - - if ($this->canValidate($this->model->validationRulesAdd, $this->model->validationMessagesAdd)) : - try { - $successfulResult = $this->model->skipValidation(true)->save($sanitizedData); - } catch (\Exception $e) { - $noException = false; - $this->dealWithException($e); - } - else : - $this->viewData['errorMessage'] = lang('Basic.global.formErr1', [mb_strtolower(lang('Presupuestos.presupuesto'))]); - $this->session->setFlashdata('formErrors', $this->model->errors()); - endif; - - $thenRedirect = true; // Change this to false if you want your user to stay on the form after submission - endif; - if ($noException && $successfulResult) : - - $id = $this->model->db->insertID(); - - $message = lang('Basic.global.saveSuccess', [lang('Basic.global.record')]) . '.'; - - if ($thenRedirect) : - if (!empty($this->indexRoute)) : - //return redirect()->to(route_to( $this->indexRoute ) )->with('sweet-success', $message); - return redirect()->to(site_url('presupuestos/cliente/edit/' . $id))->with('sweet-success', $message); - else : - return $this->redirect2listView('sweet-success', $message); - endif; - else : - $this->session->setFlashData('sweet-success', $message); - endif; - - endif; // $noException && $successfulResult - - endif; // ($requestMethod === 'post') - // Se obtiene el cliente ID a partir del usuario de la sesion $clienteId = 999; // Fijo hasta desarollar clientes usuarios @@ -194,218 +135,52 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController $requestMethod = $this->request->getMethod(); - if ($requestMethod === 'post') : + $datosPresupuesto = (object)array(); + $datosPresupuesto->POD = model('App\Models\Configuracion\ConfiguracionSistemaModel')->getPOD(); + $datosPresupuesto->paisList = model('App\Models\Configuracion\PaisModel')->getAllForMenu('id, nombre', 'nombre', true); + $datosPresupuesto->papelFormatoList = $this->getPapelFormatoListItems($presupuestoEntity->papel_formato_id ?? null); - $nullIfEmpty = true; // !(phpversion() >= '8.1'); + $datosPresupuesto->papelInteriorNegro = model('App\Models\Configuracion\PapelGenericoModel')->getPapelForComparador('negro', false, false, false, false, true); + $datosPresupuesto->papelInteriorNegroHq = model('App\Models\Configuracion\PapelGenericoModel')->getPapelForComparador('negrohq', false, false, false, false, true); + $datosPresupuesto->papelInteriorColor = model('App\Models\Configuracion\PapelGenericoModel')->getPapelForComparador('color', false, false, false, false, true); + $datosPresupuesto->papelInteriorColorHq = model('App\Models\Configuracion\PapelGenericoModel')->getPapelForComparador('colorhq', false, false, false, false, true); - $postData = $this->request->getPost(); + $datosPresupuesto->papelCubierta = model('App\Models\Configuracion\PapelGenericoModel')->getPapelForComparador('colorhq', true, false, false, false, true); + $datosPresupuesto->papelSobrecubierta = model('App\Models\Configuracion\PapelGenericoModel')->getPapelForComparador('colorhq', false, true, false, false, true); + $datosPresupuesto->papelGuardas = model('App\Models\Configuracion\PapelGenericoModel')->getPapelForComparador('colorhq', false, false, false, true, false); - $postData['updated_at'] = gmdate('Y-m-d H:m:s', time()); + $datosPresupuesto->acabadosCubierta = $this->getAcabadosCubierta(); + $datosPresupuesto->acabadosSobrecubierta = $this->getAcabadosSobrecubierta(); - $sanitizedData = $this->sanitized($postData, $nullIfEmpty); - - // JJO - $sanitizedData['user_updated_id'] = $session->id_user; - - if ($this->request->getPost('is_duplicado') == null) { - $sanitizedData['is_duplicado'] = 0; - } - - if ($this->request->getPost('retractilado') == null) { - $sanitizedData['retractilado'] = false; - } - if ($this->request->getPost('retractilado5') == null) { - $sanitizedData['retractilado5'] = false; - } - if ($this->request->getPost('ferro') == null) { - $sanitizedData['ferro'] = false; - } - if ($this->request->getPost('ferro_digital') == null) { - $sanitizedData['ferro_digital'] = false; - } - if ($this->request->getPost('prototipo') == null) { - $sanitizedData['prototipo'] = false; - } - if ($this->request->getPost('marcapaginas') == null) { - $sanitizedData['marcapaginas'] = false; - } - if ($this->request->getPost('faja_color') == null) { - $sanitizedData['faja_color'] = false; - } - if ($this->request->getPost('papel_formato_personalizado') == null) { - $sanitizedData['papel_formato_personalizado'] = false; - } - - if ($this->request->getPost('papel_formato_id') == null) { - $sanitizedData['papel_formato_id'] = 0; - } - - if ($this->request->getPost('solapas') == null) { - $sanitizedData['solapas'] = 0; - } - if ($this->request->getPost('solapas_sobrecubierta') == null) { - $sanitizedData['solapas_sobrecubierta'] = 0; - } - - $noException = true; - if ( - $sanitizedData['papel_formato_id'] == null && $sanitizedData['papel_formato_ancho'] == null - && $sanitizedData['papel_formato_alto'] == null - ) { - if ($this->request->isAJAX()) { - $newTokenHash = csrf_hash(); - $csrfTokenName = csrf_token(); - $data = [ - 'errorMensaje' => lang('Presupuestos.errores.formato_papel'), - $csrfTokenName => $newTokenHash - ]; - return $this->respond($data); - } else { - $this->session->setFlashData('errorMessage', lang('Presupuestos.errores.formato_papel')); - } - $successfulResult = false; - } else { - - 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('Presupuestos.presupuesto'))]); - $this->session->setFlashdata('formErrors', $this->model->errors()); - - endif; - - $presupuestoEntity->fill($sanitizedData); - - $thenRedirect = false; - endif; - } - - if ($noException && $successfulResult) : - $id = $presupuestoEntity->id ?? $id; - $message = lang('Basic.global.updateSuccess', [mb_strtolower(lang('Presupuestos.presupuesto'))]) . '.'; - - if ($thenRedirect) : - if (!empty($this->indexRoute)) : - return redirect()->to(route_to($this->indexRoute))->with('sweet-success', $message); - else : - if ($this->request->isAJAX()) { - $newTokenHash = csrf_hash(); - $csrfTokenName = csrf_token(); - $data = [ - 'mensaje' => $message, - $csrfTokenName => $newTokenHash - ]; - return $this->respond($data); - } else { - return $this->redirect2listView('sweet-success', $message); - } - - endif; - else : - if ($this->request->isAJAX()) { - $newTokenHash = csrf_hash(); - $csrfTokenName = csrf_token(); - $data = [ - 'mensaje' => $message, - $csrfTokenName => $newTokenHash - ]; - return $this->respond($data); - } else { - $this->session->setFlashData('sweet-success', $message); - } - endif; - - endif; // $noException && $successfulResult - endif; // ($requestMethod === 'post') - - /* - $this->viewData['presupuestoId'] = $id; - $this->viewData['presupuestoEntity'] = $presupuestoEntity; - $this->viewData['isCosido'] = (new TipoPresupuestoModel())->get_isCosido($presupuestoEntity->tipo_impresion_id); - $this->viewData['isTapaDura'] = (new TipoPresupuestoModel())->get_isTapaDura($presupuestoEntity->tipo_impresion_id); - - if (!is_null($presupuestoEntity->comparador_json_data)) - $this->viewData['comp_data'] = json_decode($presupuestoEntity->comparador_json_data); - else - $this->viewData['comp_data'] = ""; - - $this->viewData['clienteList'] = $this->getClienteListItems($presupuestoEntity->cliente_id ?? null); - $this->viewData['paisList'] = $this->getPaisListItems(); - $this->viewData['ccaaList'] = $this->getCcaaListItems(); - - $this->viewData['clienteList'] = $this->getClienteListItems($presupuestoEntity->cliente_id ?? null); - $this->viewData['incReiList'] = array('incidencia' => lang('Presupuestos.incidencia'), 'reimpresion' => lang('Presupuestos.reimpresion'), 'sin_cargo' => lang('Presupuestos.sinCargo')); - $this->viewData['papelFormatoList'] = $this->getPapelFormatoListItems($presupuestoEntity->papel_formato_id ?? null); - $this->viewData['papelGenericoNegroList'] = $this->getPapelGenericoNegro(); - $this->viewData['papelGenericoNegroHQList'] = $this->getPapelGenericoNegroHQ(); - $this->viewData['papelGenericoColorList'] = $this->getPapelGenericoColor(); - $this->viewData['papelGenericoColorHQList'] = $this->getPapelGenericoColorHQ(); - $this->viewData['papelGenericoCubiertaList'] = $this->getPapelGenericoCubierta(); - $this->viewData['papelGenericoGuardasList'] = $this->getPapelGenericoGuardas(); - $this->viewData['papelGenericoSobrecubiertaList'] = $this->getPapelGenericoSobreCubierta(); - $this->viewData['papelGenericoRotativaNegroList'] = $this->getPapelGenericoRotativaNegro(); - $this->viewData['papelGenericoRotativaColorList'] = $this->getPapelGenericoRotativaColor(); - - // Acabados exteriores - $this->viewData['acabadosCubierta'] = $this->getAcabadosCubierta(); - $this->viewData['acabadosSobrecubierta'] = $this->getAcabadosSobrecubierta(); - - // Lineas Presupuesto - [$cambios_lineas, $this->viewData['lineasPresupuesto']] = $this->getLineasPresupuesto($presupuestoEntity); - $this->viewData['presupuestoEntity']->cambios_lineas=$cambios_lineas; - - // Servicios - $this->viewData['serviciosPreimpresion'] = $this->getServiciosPreimpresion(); - $this->viewData['serviciosEncuadernacion'] = $this->getServiciosEncuadernacion(); - $this->viewData['serviciosManipulado'] = $this->getServiciosManipulado(); - $this->viewData['serviciosAcabado'] = $this->getServiciosAcabado(); - $this->viewData['serviciosExtra'] = $this->getServiciosExtra(); - - [$cambios_en_servicios, $servicios] = $this->getLineasServicios($presupuestoEntity); - $this->viewData['presupuestoEntity']->cambios_servicios=$cambios_en_servicios; - - $this->viewData['serviciosEncuadernacionList'] = $servicios->serviciosEncuadernacion; - $this->viewData['serviciosAcabadosList'] = $servicios->serviciosAcabado; - $this->viewData['serviciosManipuladoList'] = $servicios->serviciosManipulado; - $this->viewData['serviciosPreimpresionList'] = $servicios->serviciosPreimpresion; - $this->viewData['serviciosExtraList'] = $servicios->serviciosExtra; - - // Direciones presupuesto - [$cambios_en_direcciones, $this->viewData['direccionesList']] = $this->getLineasDirecciones($presupuestoEntity); - $this->viewData['presupuestoEntity']->cambios_direcciones=$cambios_en_direcciones; - - $this->viewData['POD'] = $this->getPOD(); - - $this->viewData['serviciosAutomaticos'] = [ - 'retractilado' => 3, - 'retractilado5' => 5, - 'ferro' => 24, - 'prototipo' => 9, - 'fajaColor' => 16, - 'plegadoGuardas' => 62, - ]; - - $this->viewData['tipo_impresion_id'] = $presupuestoEntity->tipo_impresion_id; // Cosido tapa blanda JJO - - $this->viewData = array_merge($this->viewData, $this->getStringsFromTipoImpresion($presupuestoEntity->tipo_impresion_id)); + $datosPresupuesto->clienteList = $this->getClienteListItems($presupuestoEntity->cliente_id ?? null); $this->viewData['formAction'] = route_to('updateCosidotapablanda', $id); + $this->viewData['paisList'] = $this->getPaisListItems(); + + $this->viewData['presupuestoEntity'] = $presupuestoEntity; + $this->viewData['datosPresupuesto'] = $datosPresupuesto; + + + $cambios_lineas = $this->getLineasPresupuesto($presupuestoEntity)[0]; + $this->viewData['updated']->cambios_lineas=$cambios_lineas; + + $cambios_en_servicios = $this->getLineasServicios($presupuestoEntity)[0]; + $this->viewData['updated']->cambios_servicios=$cambios_en_servicios; + + $cambios_en_direcciones = $this->getLineasDirecciones($presupuestoEntity)[0]; + $this->viewData['updated']->cambios_direcciones=$cambios_en_direcciones; + + // 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 if($presupuestoEntity->is_duplicado){ $this->model->removeIsDuplicado($presupuestoEntity->id); } + $this->viewData['boxTitle'] = lang('Basic.global.edit2') . ' ' . $this->viewData['pageTitle'] . ' ' . lang('Basic.global.edit3'); -*/ + return $this->displayForm(__METHOD__, $id); } // end function edit(...) @@ -517,83 +292,37 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController if ($this->request->isAJAX()) { $reqData = $this->request->getPost(); - $type = $reqData['type'] ?? null; + $clienteId = $reqData['clienteId'] ?? 0; - if (is_null($type)) { - if (!isset($reqData['draw']) || !isset($reqData['columns'])) { - $errstr = 'No data available in response to this specific request.'; - $response = $this->respond(Collection::datatable([], 0, 0, $errstr), 400, $errstr); - return $response; - } - $search = $reqData['search']['value']; + if (!isset($reqData['draw']) || !isset($reqData['columns'])) { + $errstr = 'No data available in response to this specific request.'; + $response = $this->respond(Collection::datatable([], 0, 0, $errstr), 400, $errstr); + return $response; } + $search = $reqData['search']['value']; + $start = $reqData['start'] ?? 0; $length = $reqData['length'] ?? 5; $requestedOrder1 = $reqData['order']['0']['column'] ?? 0; - $order1 = PresupuestoModel::SORTABLE[$requestedOrder1 >= 0 ? $requestedOrder1 : 0]; + $order1 = PresupuestoModel::SORTABLE_CLIENTE[$requestedOrder1 >= 0 ? $requestedOrder1 : 0]; $dir1 = $reqData['order']['0']['dir'] ?? 'asc'; - $requestedOrder2 = $reqData['order']['1']['column'] ?? 0; - $order2 = PresupuestoModel::SORTABLE[$requestedOrder2 >= 0 ? $requestedOrder1 : 0]; - $dir2 = $reqData['order']['0']['dir'] ?? 'asc'; - $requestedOrder3 = $reqData['order']['2']['column'] ?? 0; - $order3 = PresupuestoModel::SORTABLE[$requestedOrder3 >= 0 ? $requestedOrder1 : 0]; - $dir3 = $reqData['order']['0']['dir'] ?? 'asc'; - - // por defecto, se deja cosido tapa blanda por ahora JJO - $tipo_impresion_id = $reqData['tipo_impresion_id'] ?? 4; - - + $requestedOrder2 = $reqData['order']['1']['column'] ?? $requestedOrder1; + $order2 = PresupuestoModel::SORTABLE_CLIENTE[$requestedOrder2 >= 0 ? $requestedOrder2 : 0]; + $dir2 = $reqData['order']['1']['dir'] ?? 'asc'; + $requestedOrder3 = $reqData['order']['2']['column'] ?? $requestedOrder1; + $order3 = PresupuestoModel::SORTABLE_CLIENTE[$requestedOrder3 >= 0 ? $requestedOrder3 : 0]; + $dir3 = $reqData['order']['2']['dir'] ?? 'asc'; $searchValues = get_filter_datatables_columns($reqData); - $resourceData = $this->model->getResource($searchValues, $tipo_impresion_id)->orderBy($order1, $dir1)->orderBy($order2, $dir2) + $resourceData = $this->model->getListaPresupuestosCliente($searchValues, $clienteId)->orderBy($order1, $dir1)->orderBy($order2, $dir2) ->orderBy($order3, $dir3)->limit($length, $start)->get()->getResultObject(); - foreach ($resourceData as $item) : - if (isset($item->comentarios_pdf) && strlen($item->comentarios_pdf) > 100) : - $item->comentarios_pdf = character_limiter($item->comentarios_pdf, 100); - endif; - if (isset($item->causa_cancelacion) && strlen($item->causa_cancelacion) > 100) : - $item->causa_cancelacion = character_limiter($item->causa_cancelacion, 100); - endif; - if (isset($item->comentarios_cliente) && strlen($item->comentarios_cliente) > 100) : - $item->comentarios_cliente = character_limiter($item->comentarios_cliente, 100); - endif; - if (isset($item->comentarios_safekat) && strlen($item->comentarios_safekat) > 100) : - $item->comentarios_safekat = character_limiter($item->comentarios_safekat, 100); - endif; - if (isset($item->comentarios_tarifa) && strlen($item->comentarios_tarifa) > 100) : - $item->comentarios_tarifa = character_limiter($item->comentarios_tarifa, 100); - endif; - if (isset($item->comentarios_produccion) && strlen($item->comentarios_produccion) > 100) : - $item->comentarios_produccion = character_limiter($item->comentarios_produccion, 100); - endif; - if (isset($item->tirada_alternativa_json_data) && strlen($item->tirada_alternativa_json_data) > 100) : - $item->tirada_alternativa_json_data = character_limiter($item->tirada_alternativa_json_data, 100); - endif; - if (isset($item->titulo) && strlen($item->titulo) > 100) : - $item->titulo = character_limiter($item->titulo, 100); - endif; - if (isset($item->paginas_color_posicion) && strlen($item->paginas_color_posicion) > 100) : - $item->paginas_color_posicion = character_limiter($item->paginas_color_posicion, 100); - endif; - if (isset($item->aprobado_json_data) && strlen($item->aprobado_json_data) > 100) : - $item->aprobado_json_data = character_limiter($item->aprobado_json_data, 100); - endif; - if (isset($item->comparador_json_data) && strlen($item->comparador_json_data) > 100) : - $item->comparador_json_data = character_limiter($item->comparador_json_data, 100); - endif; - if (isset($item->ws_externo_json_data) && strlen($item->ws_externo_json_data) > 100) : - $item->ws_externo_json_data = character_limiter($item->ws_externo_json_data, 100); - endif; - endforeach; - - return $this->respond(Collection::datatable( $resourceData, - $this->model->getResource("", $tipo_impresion_id)->countAllResults(), - $this->model->getResource($search, $tipo_impresion_id)->countAllResults() + $this->model->getListaPresupuestosCliente("", $clienteId)->countAllResults(), + $this->model->getListaPresupuestosCliente($search, $clienteId)->countAllResults() )); } else { return $this->failUnauthorized('Invalid request', 403); @@ -601,6 +330,7 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController } + public function presupuesto() { if ($this->request->isAJAX()) { @@ -773,6 +503,8 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController $newTokenHash = csrf_hash(); $csrfTokenName = csrf_token(); + $confirmar = $reqData['confirmar'] ?? 0; + $datosCabecera = $reqData['datos_cabecera'] ?? []; $tirada = $reqData['datos_libro']['tirada'] ?? 0; @@ -812,7 +544,7 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController $servicios = $reqData['datos_libro']['servicios'] ?? []; $iva_reducido = $reqData['iva_reducido']; - + $datos_presupuesto = array( 'tirada' => $tirada, 'tamanio' => $tamanio, @@ -840,9 +572,9 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController 'servicios' => $servicios, ); - $resultado_presupuesto = $this->calcular_presupuesto($datos_presupuesto , $selected_tirada, true); - - if(isset($resultado_presupuesto['errors'])){ + $resultado_presupuesto = $this->calcular_presupuesto($datos_presupuesto, $selected_tirada, true); + + if (isset($resultado_presupuesto['errors'])) { $errors = $resultado_presupuesto['errors']; foreach ($errors as $error) { if (!empty($error)) { @@ -852,51 +584,54 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController ]); } } - } - else if(isset($resultado_presupuesto['exception'])){ + } else if (isset($resultado_presupuesto['exception'])) { return $this->respond([ 'error' => $resultado_presupuesto['exception'], $csrfTokenName => $newTokenHash ]); } - - for ($i=0; $icalcular_coste_envio( - $direccion['id'], $peso_libro, $unidades_calculo, $direccion['tipo']=='cajas'?0:1); - if(count($coste_envio)> 0){ + $direccion['id'], + $peso_libro, + $unidades_calculo, + $direccion['tipo'] == 'cajas' ? 0 : 1 + ); + if (count($coste_envio) > 0) { $coste = floatval($coste_envio[0]->coste); - $margen = ($coste * floatval($coste_envio[0]->margen))/100.0; + $margen = ($coste * floatval($coste_envio[0]->margen)) / 100.0; $coste -= $margen; $resultado_presupuesto['info']['totales'][$i]['coste_envio'] += $coste; $resultado_presupuesto['info']['totales'][$i]['margen_envio'] += $margen; } - } + } } $model_presupuesto = new PresupuestoModel(); $tiradas_alternativas = []; $resumen_totales = []; - for ($i=0; $i $tirada[$i], 'coste_impresion' => round($coste_total, 2), @@ -905,57 +640,65 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController 'total_pedido' => $total_pedido, 'precio_unidad' => $precio_u, )); - } - else{ + } else { $resumen_totales = $resultado_presupuesto['info']['totales'][$i]; } } - - $id = $model_presupuesto->insertarPresupuestoCliente( - $selected_tirada, $datos_presupuesto, $datosCabecera, $resultado_presupuesto['info'], - $resumen_totales, $iva_reducido, $tiradas_alternativas); - - // Lineas Presupuesto - foreach ($resultado_presupuesto['info']['interior'] as $linea){ - if(count($linea) > 0) + $id = $model_presupuesto->insertarPresupuestoCliente( + $selected_tirada, + $datos_presupuesto, + $datosCabecera, + $resultado_presupuesto['info'], + $resumen_totales, + $iva_reducido, + $tiradas_alternativas + ); + + // Lineas Presupuesto + foreach ($resultado_presupuesto['info']['interior'] as $linea) { + + if (count($linea) > 0) $this->guardarLineaPresupuesto($id, $linea); } - if(count($resultado_presupuesto['info']['cubierta']) > 0) + if (count($resultado_presupuesto['info']['cubierta']) > 0) $this->guardarLineaPresupuesto($id, $resultado_presupuesto['info']['cubierta']); - if(count($resultado_presupuesto['info']['sobrecubierta']) > 0) + if (count($resultado_presupuesto['info']['sobrecubierta']) > 0) $this->guardarLineaPresupuesto($id, $resultado_presupuesto['info']['sobrecubierta']); - if(count($resultado_presupuesto['info']['guardas']) > 0) + if (count($resultado_presupuesto['info']['guardas']) > 0) $this->guardarLineaPresupuesto($id, $resultado_presupuesto['info']['guardas']); - + // Servicios - foreach ($resultado_presupuesto['info']['serviciosDefecto'] as $servicio){ + foreach ($resultado_presupuesto['info']['serviciosDefecto'] as $servicio) { $this->guardarServicio($id, $servicio, 'encuadernacion'); } - foreach ($resultado_presupuesto['info']['servicios_automaticos'] as $servicio){ + foreach ($resultado_presupuesto['info']['servicios_automaticos'] as $servicio) { if ($servicio->tarifa_id == 3 || $servicio->tarifa_id == 5 || $servicio->tarifa_id == 16) { // Servicios acabado $this->guardarServicio($id, $servicio, 'acabado'); - } else if ($servicio->tarifa_id == 24 || $servicio->tarifa_id == 9) { // Servicios extra $this->guardarServicio($id, $servicio, 'extra'); - } else if ($servicio->tarifa_id == 62) { // Servicios manipulado $this->guardarServicio($id, $servicio, 'manipulado'); } } - - foreach ($reqData['direcciones'] as $direccion){ + + foreach ($reqData['direcciones'] as $direccion) { $this->guardarLineaEnvio($id, $direccion, $peso_libro); } - + + if($confirmar == 1){ + $model_presupuesto->confirmarPresupuesto($id); + } + return $this->respond([ - 'value' => $id, + 'status' => $id, + 'url' => site_url('presupuestocliente/list'), + 'message' => lang('Basic.global.saveSuccess', [lang('Basic.global.record')]), $csrfTokenName => $newTokenHash ]); - } else { return $this->failUnauthorized('Invalid request', 403); } @@ -967,27 +710,29 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController * Funciones auxiliares * **********************/ - protected function guardarLineaPresupuesto($presupuestoId, $linea){ + protected function guardarLineaPresupuesto($presupuestoId, $linea) + { $model = new PresupuestoLineaModel(); $model->insertLPFromBackend($presupuestoId, $linea); } - protected function guardarLineaEnvio($presupuestoId, $direccion, $peso_libro){ - + protected function guardarLineaEnvio($presupuestoId, $direccion, $peso_libro) + { + $unidades = intval($direccion['unidades']); $peso_envio = $peso_libro * $unidades / 1000.0; - - $data = $this->calcular_coste_envio($direccion['id'], $peso_libro, $direccion['unidades'], $direccion['tipo']=='cajas'?0:1); - if(count($data)>0){ - + + $data = $this->calcular_coste_envio($direccion['id'], $peso_libro, $direccion['unidades'], $direccion['tipo'] == 'cajas' ? 0 : 1); + if (count($data) > 0) { + $data[0]->presupuesto_id = $presupuestoId; $data[0]->tarifa_id = $data[0]->id; unset($data[0]->id); $data[0]->precio = $data[0]->coste; unset($data[0]->coste); - $data[0]->entregaPieCalle = $direccion['tipo']=='cajas'?0:1; + $data[0]->entregaPieCalle = $direccion['tipo'] == 'cajas' ? 0 : 1; unset($data[0]->tipo); $data[0]->peso = $peso_envio; $data[0]->cantidad = $unidades; @@ -998,11 +743,12 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController } - protected function guardarServicio($presupuestoId, $servicio, $tipo){ + protected function guardarServicio($presupuestoId, $servicio, $tipo) + { - if($tipo == 'encuadernacion'){ + if ($tipo == 'encuadernacion') { $model = new PresupuestoEncuadernacionesModel(); - + $data = [ 'presupuesto_id' => $presupuestoId, 'tarifa_encuadernado_id' => $servicio->tarifa_id, @@ -1013,10 +759,9 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController 'margen' => $servicio->margen, ]; $model->insert($data); - } - else if($tipo == 'extra'){ + } else if ($tipo == 'extra') { $model = new PresupuestoServiciosExtraModel(); - + $data = [ 'presupuesto_id' => $presupuestoId, 'tarifa_extra_id' => $servicio->tarifa_id, @@ -1025,10 +770,9 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController 'margen' => $servicio->margen, ]; $model->insert($data); - } - else if($tipo == 'acabado'){ + } else if ($tipo == 'acabado') { $model = new PresupuestoAcabadosModel(); - + $data = [ 'presupuesto_id' => $presupuestoId, 'tarifa_acabado_id' => $servicio->tarifa_id, @@ -1037,10 +781,9 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController 'margen' => $servicio->margen, ]; $model->insert($data); - } - else if($tipo == 'manipulado'){ + } else if ($tipo == 'manipulado') { $model = new PresupuestoManipuladosModel(); - + $data = [ 'presupuesto_id' => $presupuestoId, 'tarifa_manipulado_id' => $servicio->tarifa_id, @@ -1053,7 +796,8 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController } - protected function calcular_coste_envio($direccionId, $peso, $unidades, $entregaPieCalle){ + protected function calcular_coste_envio($direccionId, $peso, $unidades, $entregaPieCalle) + { $model = model('App\Models\Clientes\ClienteDireccionesModel'); $data = $model->getDireccion($direccionId); @@ -1095,16 +839,16 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController $data[0]->proveedor = $tarifas_envio[0]->proveedor; $data[0]->proveedor_id = $tarifas_envio[0]->proveedor_id; } - + return $data; } - protected function calcular_presupuesto($datos_entrada , $selected_tirada, $extra_info =false) + protected function calcular_presupuesto($datos_entrada, $selected_tirada, $extra_info = false) { try { $return_data = []; - if($extra_info){ + if ($extra_info) { $info = [ 'merma' => 0, 'lomo_cubierta' => 0.0, @@ -1112,7 +856,7 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController 'user_id' => auth()->user()->id, ]; } - + $tirada = $datos_entrada['tirada']; $tamanio = $datos_entrada['tamanio']; $tipo_impresion_id = $datos_entrada['tipo_impresion_id']; @@ -1156,14 +900,14 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController $precio_u = []; $peso = []; - if($extra_info) + if ($extra_info) $totales = []; $lomo = 0.0; for ($t = 0; $t < count($tirada); $t++) { // Inicialización para los totalizadores - if($extra_info){ + if ($extra_info) { $totalPapel = 0.0; $margenPapel = 0.0; $totalImpresion = 0.0; @@ -1171,7 +915,7 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController $sumForFactor = 0.0; $sumForFactorPonderado = 0.0; - + $totalServicios = 0.0; $margenServicios = 0.0; } @@ -1187,7 +931,7 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController 'alto' => intval($tamanio['alto']) ?? 100000, 'isCosido' => $is_cosido, ); - if($extra_info){ + if ($extra_info) { $info['merma'] = $datosPedido->merma; } @@ -1213,9 +957,15 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController $costeInterior += floatval($linea['total_impresion']); $peso_interior += floatval($linea['peso']); $lomo += floatval($linea['mano']); - if($extra_info){ - $this->calcular_coste_linea($linea, - $totalPapel, $margenPapel, $sumForFactor, $totalImpresion, $margenImpresion); + if ($extra_info) { + $this->calcular_coste_linea( + $linea, + $totalPapel, + $margenPapel, + $sumForFactor, + $totalImpresion, + $margenImpresion + ); } } } @@ -1234,15 +984,15 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController } } $input_data['datosPedido']->merma = $this->calcular_merma($tirada[$t], $POD, $num_formas); - if($extra_info){ + if ($extra_info) { $info['merma'] = max($info['merma'], $input_data['datosPedido']->merma); } $interior = PresupuestoClienteService::obtenerInterior($input_data); - + $costeInterior = 0.0; $peso_interior = 0.0; $lomo = 0; - if($extra_info){ + if ($extra_info) { $totalPapel = 0.0; $margenPapel = 0.0; $sumForFactor = 0.0; @@ -1254,14 +1004,20 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController $costeInterior += floatval($linea['total_impresion']); $peso_interior += floatval($linea['peso']); $lomo += floatval($linea['mano']); - if($extra_info){ - - $this->calcular_coste_linea($linea, - $totalPapel, $margenPapel, $sumForFactor, $totalImpresion, $margenImpresion); + if ($extra_info) { + + $this->calcular_coste_linea( + $linea, + $totalPapel, + $margenPapel, + $sumForFactor, + $totalImpresion, + $margenImpresion + ); } } } - } + } if ($costeInterior <= 0) $error->interior = lang('Presupuestos.errores.noInterior'); @@ -1288,10 +1044,16 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController $coste_cubierta += floatval($cubierta['total_impresion']); $peso_cubierta += floatval($cubierta['peso']); $lomo += floatval($cubierta['mano']); - if($extra_info){ - - $this->calcular_coste_linea($linea, - $totalPapel, $margenPapel, $sumForFactor, $totalImpresion, $margenImpresion); + if ($extra_info) { + + $this->calcular_coste_linea( + $linea, + $totalPapel, + $margenPapel, + $sumForFactor, + $totalImpresion, + $margenImpresion + ); } } if ($coste_cubierta <= 0) @@ -1339,10 +1101,16 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController if (count($linea_sobrecubierta) > 0) { $coste_sobrecubierta += floatval($linea_sobrecubierta['total_impresion']); $peso_sobrecubierta += floatval($linea_sobrecubierta['peso']); - if($extra_info){ - - $this->calcular_coste_linea($linea, - $totalPapel, $margenPapel, $sumForFactor, $totalImpresion, $margenImpresion); + if ($extra_info) { + + $this->calcular_coste_linea( + $linea, + $totalPapel, + $margenPapel, + $sumForFactor, + $totalImpresion, + $margenImpresion + ); } } if ($coste_sobrecubierta <= 0) @@ -1402,10 +1170,16 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController if (count($guardas) > 0) { $coste_guardas += floatval($guardas['total_impresion']); $peso_guardas += floatval($guardas['peso']); - if($extra_info){ - - $this->calcular_coste_linea($linea, - $totalPapel, $margenPapel, $sumForFactor, $totalImpresion, $margenImpresion); + if ($extra_info) { + + $this->calcular_coste_linea( + $linea, + $totalPapel, + $margenPapel, + $sumForFactor, + $totalImpresion, + $margenImpresion + ); } } if ($coste_guardas <= 0) @@ -1414,12 +1188,12 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController $error->guardas = ""; } - if($extra_info){ + if ($extra_info) { $totalPapel -= $margenPapel; $totalImpresion -= $margenImpresion; - $porcentajeMargenPapel = is_numeric($margenPapel/($totalPapel)*100.0)? $margenPapel/($totalPapel)*100.0 : 0; - $porcentajeMargenImpresion = is_numeric($margenImpresion/($totalImpresion)*100.0) ? $margenImpresion/($totalImpresion)*100.0 : 0; + $porcentajeMargenPapel = is_numeric($margenPapel / ($totalPapel) * 100.0) ? $margenPapel / ($totalPapel) * 100.0 : 0; + $porcentajeMargenImpresion = is_numeric($margenImpresion / ($totalImpresion) * 100.0) ? $margenImpresion / ($totalImpresion) * 100.0 : 0; } // Servicios defecto @@ -1438,13 +1212,13 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController $error->serviciosDefecto = lang('Presupuestos.errores.errorPresupuesto'); $costeServiciosDefecto += floatval($servicio->total); - if($extra_info){ + if ($extra_info) { $totalServicios += floatval($servicio->total); - $margenServicios += floatval($servicio->total)*floatval($servicio->margen)/100.0; + $margenServicios += floatval($servicio->total) * floatval($servicio->margen) / 100.0; } } - if($extra_info){ + if ($extra_info) { $sumForFactorPonderado = $sumForFactor; } @@ -1475,9 +1249,9 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController $error->servicios = lang('Presupuestos.errores.errorPresupuesto'); $coste_servicios += floatval($resultado[0]->total); - if($extra_info){ + if ($extra_info) { $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) == 24 || intval($servicio) == 9) { // Servicios preimpresion @@ -1489,9 +1263,9 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController $error->servicios = lang('Presupuestos.errores.errorPresupuesto'); $coste_servicios += floatval($resultado[0]->precio); - if($extra_info){ + if ($extra_info) { $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) == 62) { // Servicios manipulado @@ -1505,9 +1279,9 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController $error->servicios = lang('Presupuestos.errores.errorPresupuesto'); $coste_servicios += floatval($resultado[0]->total); - if($extra_info){ + if ($extra_info) { $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; } } } @@ -1519,19 +1293,19 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController break; } - if($extra_info){ + if ($extra_info) { $totalServicios -= $margenServicios; - $porcentajeMargenServicios = $margenServicios/($margenServicios+$totalServicios)*100; + $porcentajeMargenServicios = $margenServicios / ($margenServicios + $totalServicios) * 100; $sumForFactorPonderado += $totalServicios; } - if($extra_info){ + if ($extra_info) { array_push($totales, array( 'totalPapel' => $totalPapel, 'margenPapel' => $margenPapel, 'totalImpresion' => $totalImpresion, 'margenImpresion' => $margenImpresion, - + 'sumForFactor' => $sumForFactor, 'sumForFactorPonderado' => $sumForFactorPonderado, @@ -1540,10 +1314,11 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController 'porcentajeMargenPapel' => $porcentajeMargenPapel, 'porcentajeMargenImpresion' => $porcentajeMargenImpresion, - 'porcentajeMargenServicios' => $porcentajeMargenServicios)); + 'porcentajeMargenServicios' => $porcentajeMargenServicios + )); } - if($extra_info && $tirada[$t] == $selected_tirada){ + if ($extra_info && $tirada[$t] == $selected_tirada) { $info['lomo_cubierta'] = $lomo; $info['lomo_sobrecubierta'] = $lomo_sobrecubierta; @@ -1569,20 +1344,20 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController 'peso' => $peso, ]; - if($extra_info){ + if ($extra_info) { $return_data['info']['totales'] = $totales; } - - return $return_data; + return $return_data; } catch (Exception $e) { return ['exception' => $e->getMessage()]; } } - protected function calcular_coste_linea($linea, &$totalPapel, &$margenPapel, &$sumForFactor, &$totalImpresion, &$margenImpresion){ - if(count($linea) == 0) + protected function calcular_coste_linea($linea, &$totalPapel, &$margenPapel, &$sumForFactor, &$totalImpresion, &$margenImpresion) + { + if (count($linea) == 0) return; $totalPapel += $linea['precio_pedido']; $margenPapel += $linea['margen_papel_pedido']; @@ -1593,7 +1368,7 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController $totalImpresion += $linea['precio_click_pedido']; $sumForFactor += $linea['precio_click_pedido']; - if($linea['tipo_maquina'] == 'inkjet'){ + if ($linea['tipo_maquina'] == 'inkjet') { $totalImpresion += $linea['precio_tinta']; $totalImpresion += $linea['total_corte']; $sumForFactor += $linea['total_corte']; @@ -1601,7 +1376,6 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController $margenImpresion += $linea['margen_impresion_horas']; $margenImpresion += $linea['margen_click_pedido']; $sumForFactor -= $linea['margen_click_pedido']; - } protected function calcular_lomo($lineas, $lomo_inicial) @@ -1722,4 +1496,60 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController return $data; } + + protected function getLineasPresupuesto($presupuestoEntity){ + $lineas = (new PresupuestoLineaModel())->getLineasPresupuesto($presupuestoEntity->id); + + $input_data = []; + $input_data['presupuesto'] = $presupuestoEntity; + + return PresupuestoService::checkLineasPresupuesto($input_data, $lineas); + } + + protected function getLineasServicios($presupuestoEntity){ + + $serviciosPresupuesto = (object)array(); + + $serviciosPresupuesto->serviciosAcabado = (new PresupuestoAcabadosModel())->getResource($presupuestoEntity->id)->get()->getResultObject(); + $serviciosPresupuesto->serviciosPreimpresion = (new PresupuestoPreimpresionesModel())->getResource($presupuestoEntity->id)->get()->getResultObject(); + $serviciosPresupuesto->serviciosEncuadernacion = (new PresupuestoEncuadernacionesModel())->getResource($presupuestoEntity->id)->get()->getResultObject(); + $serviciosPresupuesto->serviciosManipulado = (new PresupuestoManipuladosModel())->getResource($presupuestoEntity->id)->get()->getResultObject(); + $serviciosPresupuesto->serviciosExtra = (new PresupuestoServiciosExtraModel())->getResource($presupuestoEntity->id)->get()->getResultObject(); + + $input_data = []; + $input_data['presupuesto_id'] = $presupuestoEntity->id; + $input_data['tipo_impresion_id'] = $presupuestoEntity->tipo_impresion_id; + $input_data['tirada'] = $presupuestoEntity->tirada; + $input_data['POD'] = $this->getPOD(); + $input_data['paginas'] = $presupuestoEntity->paginas; + $input_data['is_duplicado'] = $presupuestoEntity->is_duplicado; + + if($presupuestoEntity->papel_formato_personalizado){ + $input_data['ancho'] = $presupuestoEntity->ancho; + $input_data['alto'] = $presupuestoEntity->alto; + } + else{ + $model = model("App\Models\Configuracion\PapelFormatoModel"); + $papel = $model->find($presupuestoEntity->papel_formato_id); + if($papel){ + $input_data['ancho'] = $papel->ancho; + $input_data['alto'] = $papel->alto; + } + else{ + $input_data['ancho'] = 0; + $input_data['alto'] = 0; + } + } + + return PresupuestoService::checkLineasServicios($input_data, $serviciosPresupuesto); + } + + protected function getLineasDirecciones($presupuestoEntity){ + + $model = model('App\Models\Presupuestos\PresupuestoDireccionesModel'); + $direccionesEnvio = $model->where('presupuesto_id', $presupuestoEntity->id)->findAll(); + + return PresupuestoService::checkLineasEnvios($direccionesEnvio); + } + } diff --git a/ci4/app/Language/es/Presupuestos.php b/ci4/app/Language/es/Presupuestos.php index 6c92c66a..96b1646b 100755 --- a/ci4/app/Language/es/Presupuestos.php +++ b/ci4/app/Language/es/Presupuestos.php @@ -19,6 +19,7 @@ return [ 'presupuestoCosidotapaduraList' => 'Lista presupuestos Libros Cosido Tapa Dura', 'presupuestoCosidotapablandaList' => 'Lista presupuestos Libros Cosido Tapa Blanda', 'presupuesto' => 'Presupuesto', + 'presupuestos' => 'Presupuestos', 'libroCosidoTapaBlanda' => "Cosido Tapa Blanda", 'libroCosidoTapaDura' => "Cosido Tapa Dura", diff --git a/ci4/app/Models/Presupuestos/PresupuestoModel.php b/ci4/app/Models/Presupuestos/PresupuestoModel.php index e523fbbe..0cc6e398 100755 --- a/ci4/app/Models/Presupuestos/PresupuestoModel.php +++ b/ci4/app/Models/Presupuestos/PresupuestoModel.php @@ -30,6 +30,20 @@ class PresupuestoModel extends \App\Models\BaseModel 10 => "t6.estado", ]; + const SORTABLE_CLIENTE = [ + 0 => "t1.id", + 1 => "t1.created_at", + 2 => "t7.codigo", + 3 => "t2.nombre", + 4 => "t3.first_name", + 5 => "t1.titulo", + 6 => "t5.nombre", + 8 => "t1.paginas", + 9 => "t1.tirada", + 10 => "t1.total_presupuesto", + 11 => "t6.estado", + ]; + protected $allowedFields = [ "cliente_id", "user_created_id", @@ -313,6 +327,55 @@ class PresupuestoModel extends \App\Models\BaseModel return $builder; } + function getListaPresupuestosCliente($search = [] , $clienteId){ + + $builder = $this->db + ->table($this->table . " t1") + ->select( + "t1.id AS id, t1.created_at AS fecha, t7.codigo as codigo, t2.nombre AS cliente, + CONCAT(t3.first_name, ' ', t3.last_name) AS comercial, t1.titulo AS titulo, + t5.nombre AS pais, t1.inc_rei AS inc_rei, t1.paginas AS paginas, t1.tirada AS tirada, + t1.total_presupuesto AS total_presupuesto, t1.total_presupuesto AS total_presupuesto, + t6.estado AS estado" + ); + $builder->join("clientes t2", "t1.cliente_id = t2.id", "left"); + $builder->join("users t3", "t1.user_update_id = t3.id", "left"); + $builder->join("lg_paises t5", "t1.pais_id = t5.id", "left"); + $builder->join("presupuesto_estados t6", "t1.estado_id = t6.id", "left"); + $builder->join("tipos_presupuestos t7", "t1.tipo_impresion_id = t7.id", "left"); + + if($clienteId != 0) + $builder->where("t1.cliente_id", $clienteId); + + $builder->where("t1.is_deleted", 0); + + if (empty($search)) + return $builder; + else { + $builder->groupStart(); + foreach ($search as $col_search) { + if ($col_search[0] != 1) + $builder->like(self::SORTABLE_CLIENTE[$col_search[0]], $col_search[2]); + else { + $dates = explode(" ", $col_search[2]); + $builder->where(self::SORTABLE_CLIENTE[$col_search[0]] . ">=", $dates[0]); + $builder->where(self::SORTABLE_CLIENTE[$col_search[0]] . "<=", $dates[1]); + } + } + $builder->groupEnd(); + return $builder; + } + } + + function confirmarPresupuesto($presupuesto_id) + { + $this->db + ->table($this->table . " t1") + ->where('t1.id', $presupuesto_id) + ->set('t1.estado', 2) + ->update(); + } + function insertarPresupuestoCliente($tirada, $data, $data_cabecera, $extra_info, $resumen_totales, $iva_reducido, $tiradas_alternativas) { @@ -389,7 +452,8 @@ class PresupuestoModel extends \App\Models\BaseModel 'total_descuentoPercent' => 0, 'total_precio_unidad' => round(($totalCostes + $totalMargenes)/$tirada, 4), - 'total_presupuesto' => round($totalCostes + $totalMargenes, 2), + 'total_presupuesto' => round($totalCostes + $totalMargenes, 2), + 'total_aceptado' => round($totalCostes + $totalMargenes, 2), 'total_factor' => round(($totalCostes + $totalMargenes-$resumen_totales['coste_envio']-$resumen_totales['margen_envio'])/$resumen_totales['sumForFactor'], 2), 'total_factor_ponderado' => round(($totalCostes + $totalMargenes-$resumen_totales['coste_envio']-$resumen_totales['margen_envio'])/$resumen_totales['sumForFactorPonderado'], 2), @@ -463,4 +527,6 @@ class PresupuestoModel extends \App\Models\BaseModel $json = json_encode($values); return $json; } + + } diff --git a/ci4/app/Views/themes/vuexy/form/presupuestos/cliente/resumen.js b/ci4/app/Views/themes/vuexy/form/presupuestos/cliente/resumen.js index 1e02631b..f9e3dc47 100644 --- a/ci4/app/Views/themes/vuexy/form/presupuestos/cliente/resumen.js +++ b/ci4/app/Views/themes/vuexy/form/presupuestos/cliente/resumen.js @@ -123,6 +123,18 @@ function getTotalEnvio(){ $('#btnSave').on('click', function() { + finalizarPresupuesto(false); + +}); + +$('#btnConfirm').on('click', function() { + + finalizarPresupuesto(true); + +}); + + +function finalizarPresupuesto(confirmar){ let servicios = []; $('.servicio-extra:checked').each(function () { servicios.push($(this).attr('serv_id')); @@ -205,7 +217,9 @@ $('#btnSave').on('click', function() { tirada: tirada, peso: peso_libro, iva_reducido: $('#ivaReducido').val()==1?1:0, + confirmar: confirmar, }, + datos = Object.assign(datos, window.token_ajax) $('#loader').show(); @@ -215,15 +229,18 @@ $('#btnSave').on('click', function() { type: 'POST', data: datos, success: function(response) { - if(response.length > 0) { - + + if(Object.keys(response).length > 0) { + if(response.status > 0){ + window.location.href = response.url; + } } $('#loader').hide(); + }, error: function() { $('#loader').hide(); }, }); - -}); \ No newline at end of file +} \ No newline at end of file diff --git a/ci4/app/Views/themes/vuexy/form/presupuestos/cliente/viewPresupuestoList.php b/ci4/app/Views/themes/vuexy/form/presupuestos/cliente/viewPresupuestoList.php new file mode 100644 index 00000000..b0692def --- /dev/null +++ b/ci4/app/Views/themes/vuexy/form/presupuestos/cliente/viewPresupuestoList.php @@ -0,0 +1,342 @@ +include('themes/_commonPartialsBs/select2bs5') ?> +include('themes/_commonPartialsBs/datatables') ?> +include('themes/_commonPartialsBs/sweetalert') ?> +include('themes/_commonPartialsBs/_confirm2delete') ?> +extend('themes/vuexy/main/defaultlayout') ?> +section('content'); ?> +
+
+ +
+
+

+
+
+ + + + + + + + + + + + + + + + + + + + + + +
Número
+
+ +
+
+
+ +endSection() ?> + + +section('additionalInlineJs') ?> + +const lastColNr = $('#tableOfPresupuestos').find("tr:first th").length - 1; +const actionBtns = function(data) { + return ` + +
+ + +
+ `; +}; + +// Setup - add a text input to each footer cell +$('#tableOfPresupuestos thead tr').clone(true).appendTo('#tableOfPresupuestos thead'); +$('#tableOfPresupuestos thead tr:eq(1) th').each(function (i) { + if (!$(this).hasClass("noFilter")) { + var title = $(this).text(); + if(i==1){ + + $(this).html(''); + var bsRangePickerRange = $('#bs-rangepicker-range') + bsRangePickerRange.daterangepicker({ + ranges: { + '': [moment(), moment()], + '': [moment().subtract(1, 'days'), moment().subtract(1, 'days')], + '': [moment().subtract(6, 'days'), moment()], + '': [moment().subtract(29, 'days'), moment()], + '': [moment().startOf('month'), moment().endOf('month')], + '': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')] + }, + opens: 'right', + language: 'i18n ?>', + "locale": { + "customRangeLabel": "", + "format": "YYYY-MM-DD", + "separator": " ", + "applyLabel": "", + "cancelLabel": "", + + }, + "alwaysShowCalendars": true, + autoUpdateInput: false, + + }); + + bsRangePickerRange.on('apply.daterangepicker', function(ev, picker) { + $(this).val(picker.startDate.format('YYYY-MM-DD') + ' ' + picker.endDate.format('YYYY-MM-DD')); + theTable + .column(i) + .search(this.value) + .draw(); + }); + + bsRangePickerRange.on('cancel.daterangepicker', function(ev, picker) { + $(this).val(''); + theTable + .column(i) + .search(this.value) + .draw(); + }); + + } + else if (i == 2) { + // Agregar un selector en la tercera columna + $(this).html(''); + + // Agregar opciones al selector + var selector = $('select', this); + selector.append(''); // Opción vacía + selector.append(''); + selector.append(''); + selector.append(''); + selector.append(''); + selector.append(''); + selector.append(''); + selector.append(''); + selector.append(''); + selector.append(''); + + selector.on('change', function () { + var val = $.fn.dataTable.util.escapeRegex( + $(this).val() + ); + theTable.column(i).search(val).draw(); + }); + } + else{ + $(this).html(''); + + $('input', this).on('change clear', function () { + if (theTable.column(i).search() !== this.value) { + theTable + .column(i) + .search(this.value) + .draw(); + } + }); + } + } + else { + $(this).html(''); + } +}); + + +theTable = $('#tableOfPresupuestos').DataTable({ + orderCellsTop: true, + fixedHeader: true, + processing: true, + serverSide: true, + autoWidth: true, + responsive: true, + scrollX: true, + lengthMenu: [ 5, 10, 25, 50, 75, 100, 250, 500, 1000, 2500 ], + pageLength: 50, + lengthChange: true, + "dom": '<"mb-3"l>Brtip', + "buttons": [ + 'colvis', 'copy', 'csv', 'excel', 'print', { + extend: 'pdfHtml5', + orientation: 'landscape', + pageSize: 'A4' + } + ], + stateSave: false, + order: [[1, 'asc']], + language: { + url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json" + }, + ajax : $.fn.dataTable.pipeline( { + url: '', + method: 'POST', + data: function(q) { + q.cliente = ; + }, + headers: {'X-Requested-With': 'XMLHttpRequest'}, + async: true, + }), + columnDefs: [ + { + orderable: false, + searchable: false, + targets: [lastColNr] + } + ], + + columns : [ + { 'data': 'id' }, + { 'data': 'fecha' }, + { 'data': 'codigo', + render: function(data, type, row, meta) { + switch(data){ + case "libroCosidoTapaBlanda": + return ''; + break; + + case "libroCosidoTapaDura": + return ''; + break; + + case "libroFresadoTapaBlanda": + return ''; + break; + + case "libroFresadoTapaDura": + return ''; + break; + + + case "libroEspiralTapaDura": + return ''; + break; + + case "libroEspiralTapaBlanda": + return ''; + break; + + case "libroWireoTapaDura": + return ''; + break; + + case "libroWireoTapaBlanda": + return ''; + break; + + case "libroGrapado": + return ''; + break; + + default: + return data; // Debug + break; + + } + }, + }, + + { 'data': 'cliente' }, + + { 'data': 'titulo' }, + { 'data': 'paginas' }, + { 'data': 'tirada' }, + { 'data': 'total_presupuesto' }, + { 'data': 'estado' , + 'render': function ( data, type, row, meta ) { + if(data=='borrador') + return ''; + else if(data=='aceptado') + return ''; + } + }, + { 'data': actionBtns } + ] +}); + + +theTable.on( 'draw.dt', function () { + + const dateCols = [1]; + const priceCols = [7]; + + for (let coln of dateCols) { + theTable.column(coln, { page: 'current' }).nodes().each( function (cell, i) { + const datestr = cell.innerHTML; + const dateStrLen = datestr.toString().trim().length; + if (dateStrLen > 0) { + let dateTimeParts= datestr.split(/[- :]/); // regular expression split that creates array with: year, month, day, hour, minutes, seconds values + dateTimeParts[1]--; // monthIndex begins with 0 for January and ends with 11 for December so we need to decrement by one + const d = new Date(...dateTimeParts); // new Date(datestr); + cell.innerHTML = d.toLocaleDateString(); + } + }); + } + + for (let coln of priceCols) { + theTable.column(coln, { page: 'current' }).nodes().each( function (cell, i) { + cell.innerHTML = parseFloat(cell.innerHTML).toFixed(2); + + }); + } +}); + + +$(document).on('click', '.btn-edit', function(e) { + window.location.href = `/presupuestos/presupuestocliente/edit/${$(this).attr('data-id')}/`; +}); + + +$(document).on('click', '.btn-delete', function(e) { + $(".btn-remove").attr('data-id', $(this).attr('data-id')); +}); + + +$(document).on('click', '.btn-remove', function(e) { + const dataId = $(this).attr('data-id'); + const row = $(this).closest('tr'); + if ($.isNumeric(dataId)) { + $.ajax({ + url: `/presupuestos/presupuestocliente/delete/${dataId}`, + method: 'GET', + }).done((data, textStatus, jqXHR) => { + $('#confirm2delete').modal('toggle'); + theTable.clearPipeline(); + theTable.row($(row)).invalidate().draw(); + popSuccessAlert(data.msg ?? jqXHR.statusText); + }).fail((jqXHR, textStatus, errorThrown) => { + popErrorAlert(jqXHR.responseJSON.messages.error) + }) + } +}); +endSection() ?> + + +section('css') ?> + "> + "> + +endSection() ?> + + +section('additionalExternalJs') ?> + + + + + + + + + + +endSection() ?> + diff --git a/ci4/app/Views/themes/vuexy/form/presupuestos/cliente/viewPresupuestoclienteForm.php b/ci4/app/Views/themes/vuexy/form/presupuestos/cliente/viewPresupuestoclienteForm.php index 40fe7322..8e775b66 100644 --- a/ci4/app/Views/themes/vuexy/form/presupuestos/cliente/viewPresupuestoclienteForm.php +++ b/ci4/app/Views/themes/vuexy/form/presupuestos/cliente/viewPresupuestoclienteForm.php @@ -151,11 +151,20 @@
+ estado_id == 1) : ?> + + + -
diff --git a/ci4/app/Views/themes/vuexy/main/menu_impresion.php b/ci4/app/Views/themes/vuexy/main/menu_impresion.php index ca896b1e..7b6202bd 100644 --- a/ci4/app/Views/themes/vuexy/main/menu_impresion.php +++ b/ci4/app/Views/themes/vuexy/main/menu_impresion.php @@ -62,7 +62,7 @@