Files
safekat/ci4/app/Controllers/Presupuestos/Presupuestocliente.php

559 lines
25 KiB
PHP
Executable File

<?php
namespace App\Controllers\Presupuestos;
use App\Models\Collection;
use App\Entities\Presupuestos\PresupuestoEntity;
use App\Models\Presupuestos\PresupuestoDireccionesModel;
use App\Models\Presupuestos\PresupuestoModel;
use App\Models\Configuracion\TipoPresupuestoModel;
use App\Models\Presupuestos\PresupuestoLineaModel;
use App\Models\Presupuestos\PresupuestoEncuadernacionesModel;
use App\Models\Presupuestos\PresupuestoAcabadosModel;
use App\Models\Presupuestos\PresupuestoManipuladosModel;
use App\Models\Presupuestos\PresupuestoPreimpresionesModel;
use App\Models\Presupuestos\PresupuestoServiciosExtraModel;
use App\Services\PresupuestoService;
use App\Models\Configuracion\PapelGenericoModel;
use App\Models\Configuracion\PapelImpresionModel;
use App\Models\Configuracion\MaquinaModel;
use Exception;
class Presupuestocliente extends \App\Controllers\GoBaseResourceController
{
protected $modelName = "PresupuestoModel";
protected $format = 'json';
protected static $singularObjectName = 'Presupuesto';
protected static $singularObjectNameCc = 'Presupuestocliente';
protected static $pluralObjectName = 'Presupuesto';
protected static $pluralObjectNameCc = 'Presupuestoscliente';
protected static $controllerSlug = 'presupuestocliente';
protected static $viewPath = 'themes/backend/vuexy/form/presupuestos/cliente/';
protected $indexRoute = 'cosidotapablandaList';
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
$this->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()
{
// 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
$presupuestoEntity = isset($sanitizedData) ? new PresupuestoEntity($sanitizedData) : new PresupuestoEntity();
$presupuestoEntity->POD = model('App\Models\Configuracion\ConfiguracionSistemaModel')->getPOD();
$presupuestoEntity->clienteId = $clienteId;
$datosPresupuesto = (object)array();
$datosPresupuesto->paisList = model('App\Models\Configuracion\PaisModel')->getAllForMenu('id, nombre', 'nombre', true);
$this->viewData['formAction'] = route_to('crearPresupuestoCliente');
$this->viewData['presupuestoEntity'] = $presupuestoEntity;
$this->viewData['datosPresupuesto'] = $datosPresupuesto;
$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)
{
// JJO
$session = session();
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;
$requestMethod = $this->request->getMethod();
if ($requestMethod === 'post') :
$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'] = $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));
$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;
$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;
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);
}
}
}