viewData['usingSweetAlert'] = true; // Se indica que este controlador trabaja con soft_delete $this->soft_delete = true; // Se indica el flag para los ficheros borrados $this->delete_flag = 1; $this->viewData = ['usingServerSideDataTable' => true]; // JJO parent::initController($request, $response, $logger); $this->model = new PresupuestoModel(); } public function list($tipo_impresion_id = 4) { $viewData = [ 'currentModule' => static::$controllerSlug, 'pageSubTitle' => lang('Basic.global.ManageAllRecords', [lang('Presupuestos.presupuesto')]), 'presupuestoEntity' => new PresupuestoEntity(), 'usingServerSideDataTable' => true, 'tipo_impresion_id' => $tipo_impresion_id ]; $viewData = array_merge($viewData, $this->getStringsFromTipoImpresion($tipo_impresion_id)); $viewData = array_merge($this->viewData, $viewData); // merge any possible values from the parent controller class return view(static::$viewPath . 'viewCosidotapablandaList', $viewData); } public function add($tipo_impresion_id = null) { if ($this->request->getPost()) : $nullIfEmpty = true; // !(phpversion() >= '8.1'); $postData = $this->request->getPost(); $sanitizedData = $this->sanitized($postData, $nullIfEmpty); // JJO $sanitizedData['user_created_id'] = auth()->user()->id; 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/cosidotapablanda/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') $this->viewData['tipo_impresion_id'] = $tipo_impresion_id; // Cosido tapa blanda JJO $presupuestoEntity = isset($sanitizedData) ? new PresupuestoEntity($sanitizedData) : new PresupuestoEntity(); $this->viewData['presupuestoEntity'] = $presupuestoEntity; $this->viewData['isCosido'] = (new TipoPresupuestoModel())->get_isCosido($this->viewData['tipo_impresion_id']); $this->viewData['isTapaDura'] = (new TipoPresupuestoModel())->get_isTapaDura($this->viewData['tipo_impresion_id']); $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['paisList'] = $this->getPaisListItems(); $this->viewData['papelFormatoList'] = $this->getPapelFormatoListItems($presupuestoEntity->papel_formato_id ?? null); $this->viewData['POD'] = $this->getPOD(); $this->viewData['formAction'] = route_to('createCosidotapablanda', $tipo_impresion_id); $this->viewData = array_merge($this->viewData, $this->getStringsFromTipoImpresion($tipo_impresion_id)); $this->viewData['boxTitle'] = lang('Basic.global.addNew') . ' ' . $this->viewData['pageTitle'] . ' ' . lang('Basic.global.addNewSuffix'); return $this->displayForm(__METHOD__); } // end function add() public function edit($requestedId = null) { if ($requestedId == null) : return $this->redirect2listView(); endif; $id = filter_var($requestedId, FILTER_SANITIZE_URL); $presupuestoEntity = $this->model->find($id); if ($presupuestoEntity == false) : $message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Presupuestos.presupuesto')), $id]); return $this->redirect2listView('sweet-error', $message); endif; if ($this->request->getPost()) : $nullIfEmpty = true; // !(phpversion() >= '8.1'); $postData = $this->request->getPost(); $postData['updated_at'] = gmdate('Y-m-d H:m:s', time()); $sanitizedData = $this->sanitized($postData, $nullIfEmpty); // JJO $sanitizedData['user_updated_id'] = auth()->user()->id; 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'))]) . '.'; // $message .= anchor("admin/presupuestos/{$id}/edit", lang('Basic.global.continueEditing') . '?'); //$message = ucfirst(str_replace("'", "\'", $message)); if ($thenRedirect) : if (!empty($this->indexRoute)) : return redirect()->to(route_to($this->indexRoute))->with('sweet-success', $message); 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)); $this->viewData['formAction'] = route_to('updateCosidotapablanda', $id); // Si se ha llamado a esta funcion porque se ha duplicado el presupuesto // se actualiza la bbdd para que sólo ejecute algunas funciones una vez 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(...) /** * Delete the designated resource object from the model. * * @param int $id * * @return array an array */ public function delete($id = null) { if (!empty(static::$pluralObjectNameCc) && !empty(static::$singularObjectNameCc)) { $objName = mb_strtolower(lang(ucfirst(static::$pluralObjectNameCc).'.'.static::$singularObjectNameCc)); } else { $objName = lang('Basic.global.record'); } if (!$this->soft_delete){ if (!$this->model->delete($id)) { return $this->failNotFound(lang('Basic.global.deleteError', [$objName])); } } else{ $datetime = (new \CodeIgniter\I18n\Time("now")); $rawResult = $this->model->where('id',$id) ->set(['deleted_at' => $datetime->format('Y-m-d H:i:s'), 'is_deleted' => $this->delete_flag]) ->update(); if (!$rawResult) { return $this->failNotFound(lang('Basic.global.deleteError', [$objName])); } } // Se borran las lineas de presupuesto $model = new PresupuestoLineaModel(); $model->where("presupuesto_id", $id)->delete(); // Se borran las direcciones de presupuesto $model = new PresupuestoDireccionesModel(); $model->where("presupuesto_id", $id)->delete(); // Se borran los servicios de acabado $model = new PresupuestoAcabadosModel(); $model->where("presupuesto_id", $id)->delete(); // Se borran los servicios de preimpresion $model = new PresupuestoPreimpresionesModel(); $model->where("presupuesto_id", $id)->delete(); // Se borran los servicios de encuadernacion $model = new PresupuestoEncuadernacionesModel(); $model->where("presupuesto_id", $id)->delete(); // Se borran los servicios de manipulado $model = new PresupuestoManipuladosModel(); $model->where("presupuesto_id", $id)->delete(); // Se borran los servicios extra $model = new PresupuestoServiciosExtraModel(); $model->where("presupuesto_id", $id)->delete(); // $message = lang('Basic.global.deleteSuccess', [$objName]); IMN commented $message = lang('Basic.global.deleteSuccess', [lang('Basic.global.record')]); $response = $this->respondDeleted(['id' => $id, 'msg' => $message]); return $response; } public function datatable() { if ($this->request->isAJAX()) { $reqData = $this->request->getPost(); $type = $reqData['type'] ?? null; 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']; } $start = $reqData['start'] ?? 0; $length = $reqData['length'] ?? 5; $requestedOrder1 = $reqData['order']['0']['column'] ?? 0; $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'; $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; if (is_null($type)) { $searchValues = get_filter_datatables_columns($reqData); $resourceData = $this->model->getResource($searchValues, $tipo_impresion_id)->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; } else { $isColor = $reqData['color'] ?? false; $isHq = $reqData['hq'] ?? false; $datosPedido = (object)array( 'paginas' => intval($reqData['paginas']) ?? 0, 'tirada' => intval($reqData['tirada']) ?? 0, 'merma' => intval($reqData['merma']) ?? 0, 'ancho' => intval($reqData['ancho']) ?? 100000, 'alto' => intval($reqData['alto']) ?? 100000, 'a_favor_fibra' => $reqData['a_favor_fibra'] ?? 1, 'isCosido' => (new TipoPresupuestoModel())->get_isCosido($tipo_impresion_id), // JJO esto es custom por cada tipo de presupuesto ); $papel_generico = [ 'id' => $reqData['papel_generico_id'] ?? 0, 'nombre' => $reqData['papel_generico'] ?? "", ]; $gramaje = $reqData['gramaje'] ?? 0; $cliente_id = $reqData['cliente_id'] ?? -1; $resourceData = []; if ($type == 'interior' || $type == 'guardas') { $datosTipolog = $reqData['negro'] ?? null; if (!is_null($datosTipolog)) { $datosTipolog = []; $data = (object)array( 'negro' => floatval($reqData['negro']) ?? 0, 'cyan' => floatval($reqData['cyan']) ?? 0, 'magenta' => floatval($reqData['magenta']) ?? 0, 'amarillo' => floatval($reqData['amarillo']) ?? 0, 'cg' => floatval($reqData['cg']) ?? 0, 'gota_negro' => floatval($reqData['gota_negro']) ?? 0, 'gota_color' => floatval($reqData['gota_color']) ?? 0, ); array_push($datosTipolog, $data); } if ($type == 'guardas') { $datosPedido->paginas_impresion = intval($reqData['paginas_impresion']) ?? 0; // Para el caso de Fresado y Cosido tapa dura, las guardas son un diptico // y hay que imprimirlas como "cosido" (dos hojas pegadas). En el caso de espiral // o wire-o tapa dura, las guardas se imprimen como hojas sueltas if ($tipo_impresion_id == 1 || $tipo_impresion_id == 3) { $datosPedido->isCosido = true; } else if ($tipo_impresion_id == 5 || $tipo_impresion_id == 7) { $datosPedido->isCosido = false; } } $a_favor_fibra = $reqData['a_favor_fibra'] ?? false; $input_data = array( 'uso' => $type, 'tipo_impresion_id' => $tipo_impresion_id, 'datosPedido' => $datosPedido, 'papel_generico' => $papel_generico, 'gramaje' => $gramaje, 'isColor' => $isColor, 'isHq' => $isHq, 'cliente_id' => $cliente_id, 'datosTipolog' => $datosTipolog, 'a_favor_fibra' => $a_favor_fibra ); $resourceData = PresupuestoService::obtenerComparadorPlana($input_data); } else if ($type == 'interior_rot') { $paginas = (object)array( 'negro' => intval($reqData['paginas_negro'] ?? 0), 'color' => intval($reqData['paginas_color'] ?? 0), ); $datosTipolog = $reqData['negro'] ?? null; if (!is_null($datosTipolog)) { $datosTipolog = []; $data = (object)array( 'negro' => floatval($reqData['negro']) ?? 0, 'cyan' => floatval($reqData['cyan']) ?? 0, 'magenta' => floatval($reqData['magenta']) ?? 0, 'amarillo' => floatval($reqData['amarillo']) ?? 0, 'gota_negro' => floatval($reqData['gota_negro']) ?? 0, 'gota_color' => floatval($reqData['gota_color']) ?? 0, ); array_push($datosTipolog, $data); } $input_data = [ 'datosPedido' => $datosPedido, 'papel_generico' => $papel_generico, 'gramaje' => $gramaje, 'paginas' => $paginas, 'cliente_id' => $cliente_id, 'datosTipolog' => $datosTipolog ]; $resourceData = PresupuestoService::obtenerComparadorRotativa($input_data); } else if ($type == 'cubierta' || $type == 'sobrecubierta') { $datosPedido->solapas = $reqData['solapas']; $datosPedido->solapas_ancho = $reqData['solapas_ancho']; $datosPedido->lomo = $reqData['lomo']; $input_data = array( 'uso' => $type, 'tipo_impresion_id' => $tipo_impresion_id, 'datosPedido' => $datosPedido, 'papel_generico' => $papel_generico, 'gramaje' => $gramaje, 'isColor' => 1, // Cubierta y sobrecubierta siempre color HQ 'isHq' => 1, 'cliente_id' => $cliente_id, ); $resourceData = PresupuestoService::obtenerComparadorPlana($input_data); } $newTokenHash = csrf_hash(); $csrfTokenName = csrf_token(); $data = [ 'lineas' => $resourceData, $csrfTokenName => $newTokenHash ]; return $this->respond($data); } return $this->respond(Collection::datatable( $resourceData, $this->model->getResource("", $tipo_impresion_id)->countAllResults(), $this->model->getResource($search, $tipo_impresion_id)->countAllResults() )); } else { return $this->failUnauthorized('Invalid request', 403); } } public function datatable_2() { if ($this->request->isAJAX()) { $reqData = $this->request->getPost(); $tipo = $reqData['tipo'] ?? ''; if ($tipo == 'lineasPresupuesto') { $model = model('App\Models\Presupuestos\PresupuestoLineaModel'); $datos = $reqData['datos'] ?? null; $presupuesto_id = $reqData['presupuesto_id'] ?? -1; $model->where("presupuesto_id", $presupuesto_id)->delete(); if ($datos != null) { $model->insertLineasPresupuesto($presupuesto_id, $datos); } $newTokenHash = csrf_hash(); $csrfTokenName = csrf_token(); $data = [ $csrfTokenName => $newTokenHash ]; return $this->respond($data); } else if ($tipo == 'duplicar'){ $presupuesto_id = $reqData['presupuesto_id'] ?? -1; $result = $this->duplicarPresupuesto($presupuesto_id); $newTokenHash = csrf_hash(); $csrfTokenName = csrf_token(); if($result['success']){ $data = [ 'id' => $result['id'], $csrfTokenName => $newTokenHash ]; return $this->respond($data); } else{ $data = [ 'error' => $result['message'], $csrfTokenName => $newTokenHash ]; return $this->respond($data); } } $newTokenHash = csrf_hash(); $csrfTokenName = csrf_token(); $data = [ $csrfTokenName => $newTokenHash ]; return $this->respond($data); } else { return $this->failUnauthorized('Invalid request', 403); } } private function getStringsFromTipoImpresion($tipo_impresion_id) { $breadcrumbTitle = ""; switch ($tipo_impresion_id) { // Fresado tapa dura case 1: $viewData['pageTitle'] = lang('Presupuestos.moduleTitleFresadoTD'); $viewData['isCosido'] = 0; $viewData['isTapaDura'] = 1; $breadcrumbTitle = lang("App.menu_libros_fresasdo_tapa_dura"); break; // Fresado tapa blanda case 2: $viewData['pageTitle'] = lang('Presupuestos.moduleTitleFresadoTB'); $viewData['isCosido'] = 0; $viewData['isTapaDura'] = 0; $breadcrumbTitle = lang("App.menu_libros_fresasdo_tapa_blanda"); break; // Cosido tapa dura case 3: $viewData['pageTitle'] = lang('Presupuestos.moduleTitleCosidoTD'); $viewData['isCosido'] = 1; $viewData['isTapaDura'] = 1; $breadcrumbTitle = lang("App.menu_libros_cosido_tapa_dura"); break; // Cosido tapa blanda case 4: $viewData['pageTitle'] = lang('Presupuestos.moduleTitleCosidoTB'); $viewData['isCosido'] = 1; $viewData['isTapaDura'] = 0; $breadcrumbTitle = lang("App.menu_libros_cosido_tapa_blanda"); break; // Espiral tapa dura case 5: $viewData['pageTitle'] = lang('Presupuestos.moduleTitleEspiralTD'); $viewData['isCosido'] = 0; $viewData['isTapaDura'] = 1; $breadcrumbTitle = lang("App.menu_libros_espiral_tapa_dura"); break; // Espiral tapa blanda case 6: $viewData['pageTitle'] = lang('Presupuestos.moduleTitleEspiralTB'); $viewData['isCosido'] = 0; $viewData['isTapaDura'] = 0; $breadcrumbTitle = lang("App.menu_libros_espiral_tapa_blanda"); break; // Wire-o tapa dura case 7: $viewData['pageTitle'] = lang('Presupuestos.moduleTitleWireoTD'); $viewData['isCosido'] = 0; $viewData['isTapaDura'] = 1; $breadcrumbTitle = lang("App.menu_libros_wireo_tapa_dura"); break; // Wire-o tapa blanda case 8: $viewData['pageTitle'] = lang('Presupuestos.moduleTitleWireoTB'); $viewData['isCosido'] = 0; $viewData['isTapaDura'] = 0; $breadcrumbTitle = lang("App.menu_libros_wireo_tapa_blanda"); break; // Grapado case 21: $viewData['pageTitle'] = lang('Presupuestos.moduleTitleGrapado'); $viewData['isCosido'] = 0; $viewData['isTapaDura'] = 0; $breadcrumbTitle = lang("App.menu_libros_grapados"); break; default: return "A IMPLEMENTAR!"; } // Breadcrumbs $viewData['breadcrumb'] = [ ['title' => lang("App.menu_presupuestos"), 'route' => "javascript:void(0);", 'active' => false], ['title' => $breadcrumbTitle, 'route' => site_url('presupuestos/cosidotapablanda/list/' . $tipo_impresion_id), 'active' => true] ]; return $viewData; } /** * Duplica un presupuesto dado por su ID. * * Esta función duplica un presupuesto y todas sus entidades relacionadas como acabados, encuadernaciones, manipulados, * preimpresiones, direcciones y lineas. El presupuesto duplicado se marca como tal y a su título se le añade * una cadena 'duplicado'. La función devuelve un array con un estado de éxito y el ID del nuevo presupuesto. * * @param int $id El ID del presupuesto a duplicar. * @return array Un array asociativo que contiene una clave 'success' que indica el estado de éxito de la operación, * y una clave 'id' que contiene el ID del nuevo presupuesto si la operación fue exitosa. * Si ocurre una excepción, la clave 'success' será false y una clave 'message' contendrá el mensaje de la excepción. * @throws \Exception Si ocurre un error durante la operación. */ private function duplicarPresupuesto($id){ try{ $presupuesto = $this->model->find($id); $presupuesto->titulo = $presupuesto->titulo .' - ' . lang('Presupuestos.duplicado'); $presupuesto->is_duplicado = 1; $new_id = $this->model->insert($presupuesto); $presupuestoAcabadosModel = model('App\Models\Presupuestos\PresupuestoAcabadosModel'); foreach ($presupuestoAcabadosModel->where('presupuesto_id', $presupuesto->id)->findAll() as $acabado) { $acabado->presupuesto_id = $new_id; $presupuestoAcabadosModel->insert($acabado); } $presupuestoEncuadernacionesModel = model('App\Models\Presupuestos\PresupuestoEncuadernacionesModel'); foreach ($presupuestoEncuadernacionesModel->where('presupuesto_id', $presupuesto->id)->findAll() as $encuadernacion) { $encuadernacion->presupuesto_id = $new_id; $presupuestoEncuadernacionesModel->insert($encuadernacion); } $presupuestoManipuladosModel = model('App\Models\Presupuestos\PresupuestoManipuladosModel'); foreach ($presupuestoManipuladosModel->where('presupuesto_id', $presupuesto->id)->findAll() as $manipulado) { $manipulado->presupuesto_id = $new_id; $presupuestoManipuladosModel->insert($manipulado); } $presupuestoPreimpresionesModel = model('App\Models\Presupuestos\PresupuestoPreimpresionesModel'); foreach ($presupuestoPreimpresionesModel->where('presupuesto_id', $presupuesto->id)->findAll() as $preimpresion) { $preimpresion->presupuesto_id = $new_id; $presupuestoPreimpresionesModel->insert($preimpresion); } $presupuestoServiciosExtraModel = model('App\Models\Presupuestos\PresupuestoServiciosExtraModel'); foreach ($presupuestoServiciosExtraModel->where('presupuesto_id', $presupuesto->id)->findAll() as $servicioExtra) { $servicioExtra->presupuesto_id = $new_id; $presupuestoServiciosExtraModel->insert($preimpresion); } $presupuestoDireccionesModel = model('App\Models\Presupuestos\PresupuestoDireccionesModel'); foreach ($presupuestoDireccionesModel->where('presupuesto_id', $presupuesto->id)->findAll() as $direccion) { $direccion->presupuesto_id = $new_id; $presupuestoDireccionesModel->insert($direccion); } $presupuestoLineaModel = model('App\Models\Presupuestos\PresupuestoLineaModel'); $presupuestoLineaModel->duplicateLineasPresupuesto($presupuesto->id, $new_id); return [ 'success' => true, 'id' => $new_id ]; }catch(\Exception $e){ return [ 'success' => false, 'message' => $e->getMessage() ]; } } public function allItemsSelect() { if ($this->request->isAJAX()) { $onlyActiveOnes = true; $reqVal = $this->request->getPost('val') ?? 'id'; $menu = $this->model->getAllForMenu($reqVal . ', titulo', 'titulo', $onlyActiveOnes, false); $nonItem = new \stdClass; $nonItem->id = ''; $nonItem->titulo = '- ' . lang('Basic.global.None') . ' -'; array_unshift($menu, $nonItem); $newTokenHash = csrf_hash(); $csrfTokenName = csrf_token(); $data = [ 'menu' => $menu, $csrfTokenName => $newTokenHash ]; return $this->respond($data); } else { return $this->failUnauthorized('Invalid request', 403); } } public function menuItems() { if ($this->request->isAJAX()) { $reqData = $this->request->getPost(); try { $tipo = $reqData['tipo'] ?? null; $uso = $reqData['uso'] ?? null; $datos = $reqData['datos'] ?? null; //$searchStr = goSanitize($this->request->getPost('searchTerm'))[0]; $newTokenHash = csrf_hash(); $csrfTokenName = csrf_token(); if ($tipo == 'gramaje') { // En este caso contiene el nombre del papel generico $tirada = $reqData['tirada'] ?? 0; $merma = $reqData['merma'] ?? 0; $model = new PapelGenericoModel(); $menu = $model->getGramajeComparador($datos, $uso, intval($tirada + $merma)); $data = [ 'menu' => $menu, $csrfTokenName => $newTokenHash ]; } elseif ($tipo == 'gramajeLineasPresupuesto') { $tipoLinea = $reqData['tipoLinea'] ?? null; // En este caso contiene el id del papel generico $model = new PapelGenericoModel(); $menu = $model->getGramajeLineasPresupuesto($datos, $tipoLinea, $uso); $data = [ 'menu' => $menu, $csrfTokenName => $newTokenHash ]; } elseif ($tipo == 'papelImpresion') { $gramaje = $reqData['gramaje'] ?? null; $tipoLinea = $reqData['tipoLinea'] ?? null; // En este caso contiene el nombre del papel generico // Uso: negro, negrohq, color, colorhq, rot_bn, rot_color, $model = new PapelImpresionModel(); $menu = $model->getPapelesImpresionForMenu($datos, $gramaje, $tipoLinea, $uso); $data = [ 'menu' => $menu, $csrfTokenName => $newTokenHash ]; } elseif ($tipo == 'maquina') { $is_rotativa = $reqData['is_rotativa'] ?? null; $papel_impresion = $reqData['papel_impresion'] ?? null; $tipo_linea = $reqData['tipoLinea'] ?? null; $ancho = $reqData['ancho'] ?? null; $alto = $reqData['alto'] ?? null; // Datos contiene la tirada // uso: negro, negrohq, color, colorhq, $uso_tarifa = $reqData['uso_tarifa'] ?? 'interior'; $model = new MaquinaModel(); $maquinas = $model->getMaquinaImpresionForPresupuesto($is_rotativa, $uso, $uso_tarifa, $datos, $papel_impresion); $menu = []; foreach ($maquinas as $maquina) { $formas = PresupuestoService::getNumFormasPlana($tipo_linea, $maquina, floatval($ancho), floatval($alto), true); if ($formas['num_formas'] != 'n/a') { array_push($menu, $maquina); } } $data = [ 'menu' => $menu, $csrfTokenName => $newTokenHash ]; } else { $data = [ 'tipo' => $tipo, $csrfTokenName => $newTokenHash ]; } } catch (Exception $e) { $data = [ 'error' => $e, $csrfTokenName => $newTokenHash ]; } finally { return $this->respond($data); } } else { return $this->failUnauthorized('Invalid request', 403); } } protected function getClienteListItems($selId = null) { $data = ['' => lang('Basic.global.pleaseSelectA', [mb_strtolower(lang('Clientes.cliente'))])]; if (!empty($selId)) : $clienteModel = model('App\Models\Clientes\ClienteModel'); $selOption = $clienteModel->where('id', $selId)->findColumn('nombre'); if (!empty($selOption)) : $data[$selId] = $selOption[0]; endif; endif; return $data; } protected function getPaisListItems() { $paisModel = model('App\Models\Configuracion\PaisModel'); $onlyActiveOnes = true; $data = $paisModel->getAllForMenu('id, nombre', 'nombre', $onlyActiveOnes); return $data; } protected function getCcaaListItems($selId = null) { $ccaaModel = model('App\Models\Configuracion\ComunidadAutonomaModel'); $onlyActiveOnes = true; $data = $ccaaModel->getAllForMenu('id, nombre', 'nombre', $onlyActiveOnes); return $data; } protected function getAcabadosCubierta() { $model = model('App\Models\Tarifas\TarifaacabadoModel'); $data = $model->getServiciosAcabadoCubierta(); array_unshift($data, (object)['id' => '', 'label' => lang('Basic.global.None')]); return $data; } protected function getAcabadosSobrecubierta() { $model = model('App\Models\Tarifas\TarifaacabadoModel'); $data = $model->getServiciosAcabadoSobrecubierta(); array_unshift($data, (object)['id' => '', 'label' => lang('Basic.global.None')]); return $data; } protected function getPapelGenericoRotativaNegro() { $model = model('App\Models\Configuracion\PapelGenericoModel'); $data = $model->getPapelForComparador('negro', false, false, true); array_unshift($data, (object)array( "id" => 0, "nombre" => lang('Basic.global.pleaseSelectA', [mb_strtolower(lang('Presupuestos.papel'))]) )); return $data; } protected function getPapelGenericoRotativaColor() { $model = model('App\Models\Configuracion\PapelGenericoModel'); $data = $model->getPapelForComparador('color', false, false, true); array_unshift($data, (object)array( "id" => 0, "nombre" => lang('Basic.global.pleaseSelectA', [mb_strtolower(lang('Presupuestos.papel'))]) )); return $data; } protected function getPapelGenericoNegro() { $model = model('App\Models\Configuracion\PapelGenericoModel'); $data = $model->getPapelForComparador('negro', false, false); array_unshift($data, (object)array( "id" => 0, "nombre" => lang('Basic.global.pleaseSelectA', [mb_strtolower(lang('Presupuestos.papel'))]) )); return $data; } protected function getPapelGenericoNegroHQ() { $model = model('App\Models\Configuracion\PapelGenericoModel'); $data = $model->getPapelForComparador('negrohq', false, false); array_unshift($data, (object)array( "id" => 0, "nombre" => lang('Basic.global.pleaseSelectA', [mb_strtolower(lang('Presupuestos.papel'))]) )); return $data; } protected function getPapelGenericoColor() { $model = model('App\Models\Configuracion\PapelGenericoModel'); $data = $model->getPapelForComparador('color', false, false); array_unshift($data, (object)array( "id" => 0, "nombre" => lang('Basic.global.pleaseSelectA', [mb_strtolower(lang('Presupuestos.papel'))]) )); return $data; } protected function getPapelGenericoColorHQ() { $model = model('App\Models\Configuracion\PapelGenericoModel'); $data = $model->getPapelForComparador('colorhq', false, false); array_unshift($data, (object)array( "id" => 0, "nombre" => lang('Basic.global.pleaseSelectA', [mb_strtolower(lang('Presupuestos.papel'))]) )); return $data; } protected function getPapelGenericoCubierta() { $model = model('App\Models\Configuracion\PapelGenericoModel'); $data = $model->getPapelForComparador('colorhq', true, false); array_unshift($data, (object)array( "id" => 0, "nombre" => lang('Basic.global.pleaseSelectA', [mb_strtolower(lang('Presupuestos.papel'))]) )); return $data; } protected function getPapelGenericoGuardas() { $model = model('App\Models\Configuracion\PapelGenericoModel'); $data = $model->getPapelForComparador('colorhq', false, false, false, true); array_unshift($data, (object)array( "id" => 0, "nombre" => lang('Basic.global.pleaseSelectA', [mb_strtolower(lang('Presupuestos.papel'))]) )); return $data; } protected function getPapelGenericoSobreCubierta() { $model = model('App\Models\Configuracion\PapelGenericoModel'); $data = $model->getPapelForComparador('colorhq', false, true); array_unshift($data, (object)array( "id" => 0, "nombre" => lang('Basic.global.pleaseSelectA', [mb_strtolower(lang('Presupuestos.papel'))]) )); return $data; } protected function getServiciosPreimpresion() { $model = model('App\Models\Tarifas\TarifapreimpresionModel'); $data = $model->getServiciosPreimpresionSelector(); array_unshift($data, (object)array( "value" => 0, "label" => lang('Basic.global.pleaseSelectA', [mb_strtolower(lang('Presupuestos.servicioPreimpresion'))]) )); return $data; } protected function getServiciosExtra() { $model = model('App\Models\Tarifas\TarifaextraModel'); $data = $model->getServiciosExtraSelector(); array_unshift($data, (object)array( "value" => 0, "label" => lang('Basic.global.pleaseSelectA', [mb_strtolower(lang('Presupuestos.servicioExtra'))]) )); return $data; } protected function getServiciosEncuadernacion() { $model = model('App\Models\Tarifas\TarifaEncuadernacionModel'); $data = $model->getServiciosEncuadernacionSelector(); return $data; } protected function getPapelFormatoListItems($selId = null) { $papelFormatoModel = model('App\Models\Configuracion\PapelFormatoModel'); $data = $papelFormatoModel->getElementsForMenu(); array_shift($data); array_unshift($data, (object)['id' => '', 'tamanio' => lang('Basic.global.pleaseSelectA', [mb_strtolower(lang('Presupuestos.papelFormatoId'))])]); return $data; } protected function getServiciosAcabado() { $model = model('App\Models\Tarifas\TarifaacabadoModel'); $data = $model->getServiciosAcabadoSelector(); return $data; } protected function getServiciosManipulado() { $model = model('App\Models\Tarifas\TarifaManipuladoModel'); $data = $model->getServiciosManipuladoSelector(); array_unshift($data, (object)array( "value" => 0, "label" => lang('Basic.global.pleaseSelectA', [mb_strtolower(lang('Presupuestos.servicioManipulado'))]) )); return $data; } protected function getPOD() { $model = model('App\Models\Configuracion\ConfiguracionSistemaModel'); return $model->getPOD(); } 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); } }