mirror of
https://git.imnavajas.es/jjimenez/safekat.git
synced 2025-07-25 22:52:08 +00:00
3722 lines
161 KiB
PHP
Executable File
3722 lines
161 KiB
PHP
Executable File
<?php
|
|
|
|
namespace App\Controllers\Presupuestos;
|
|
|
|
use App\Entities\Presupuestos\PresupuestoEntity;
|
|
use App\Libraries\SafekatFtpClient;
|
|
use App\Models\Collection;
|
|
use App\Models\Clientes\ClienteModel;
|
|
use App\Models\Configuracion\PapelFormatoModel;
|
|
use App\Models\Configuracion\PapelGenericoModel;
|
|
use App\Models\Configuracion\TipoPresupuestoModel;
|
|
use App\Models\Presupuestos\PresupuestoAcabadosModel;
|
|
use App\Models\Presupuestos\PresupuestoDireccionesModel;
|
|
use App\Models\Presupuestos\PresupuestoEncuadernacionesModel;
|
|
use App\Models\Presupuestos\PresupuestoLineaModel;
|
|
use App\Models\Presupuestos\PresupuestoManipuladosModel;
|
|
use App\Models\Presupuestos\PresupuestoModel;
|
|
use App\Models\Presupuestos\PresupuestoPreimpresionesModel;
|
|
use App\Models\Presupuestos\PresupuestoServiciosExtraModel;
|
|
use App\Models\Presupuestos\ErrorPresupuesto;
|
|
use App\Services\MessageService;
|
|
use App\Services\PresupuestoClienteService;
|
|
use App\Services\PresupuestoService;
|
|
use Exception;
|
|
|
|
use stdClass;
|
|
use function PHPUnit\Framework\containsOnly;
|
|
|
|
|
|
class Presupuestocliente extends \App\Controllers\BaseResourceController
|
|
{
|
|
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/vuexy/form/presupuestos/cliente/';
|
|
|
|
protected $indexRoute = 'listaPresupuestos';
|
|
|
|
protected MessageService $messageService;
|
|
|
|
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
|
|
|
|
// Breadcrumbs
|
|
$this->viewData['breadcrumb'] = [
|
|
['title' => lang("App.menu_presupuestos"), 'route' => "javascript:void(0);", 'active' => false],
|
|
['title' => "Listado", 'route' => site_url('presupuestocliente/list'), 'active' => true]
|
|
];
|
|
$this->messageService = service('messages');
|
|
|
|
parent::initController($request, $response, $logger);
|
|
$this->model = new PresupuestoModel();
|
|
}
|
|
|
|
|
|
public function list()
|
|
{
|
|
checkPermission('presupuesto-cliente.menu');
|
|
|
|
$viewData = [
|
|
'currentModule' => static::$controllerSlug,
|
|
'pageSubTitle' => lang('Basic.global.ManageAllRecords', [lang('Presupuestos.presupuesto')]),
|
|
'presupuestoEntity' => new PresupuestoEntity(),
|
|
'usingServerSideDataTable' => true,
|
|
'pageTitle' => lang('Presupuestos.presupuestos'),
|
|
];
|
|
|
|
if (auth()->user()->inGroup('cliente-admin') || auth()->user()->inGroup('cliente-editor')) {
|
|
// Se obtiene el cliente ID a partir del usuario de la sesion
|
|
$model_user = model('App\Models\Usuarios\UserModel');
|
|
$user = $model_user->find(auth()->user()->id);
|
|
$clienteId = $user->cliente_id;
|
|
} else {
|
|
$clienteId = 0;
|
|
}
|
|
|
|
$viewData['clienteId'] = $clienteId;
|
|
return view(static::$viewPath . 'viewPresupuestoList', $viewData);
|
|
}
|
|
|
|
|
|
public function add()
|
|
{
|
|
checkPermission('presupuesto-cliente.create');
|
|
|
|
$this->viewData['breadcrumb'] = [
|
|
['title' => lang("App.menu_presupuestos"), 'route' => "javascript:void(0);", 'active' => false],
|
|
['title' => "Listado", 'route' => site_url('presupuestocliente/list'), 'active' => true]
|
|
];
|
|
|
|
// Se obtiene el cliente ID a partir del usuario de la sesion
|
|
$model_user = model('App\Models\Usuarios\UserModel');
|
|
|
|
$user = $model_user->find(auth()->user()->id);
|
|
$clienteId = $user->cliente_id;
|
|
|
|
if (auth()->user()->inGroup('cliente-admin') || auth()->user()->inGroup('cliente-editor')) {
|
|
if ($clienteId === false || $clienteId === null) {
|
|
return $this->failNotFound('Su usuario no tiene asociado un cliente de Safekat. Póngase en contacto con el administrador.');
|
|
}
|
|
}
|
|
|
|
$POD = model('App\Models\Configuracion\ConfigVariableModel')->getVariable('POD')->value;
|
|
|
|
$this->viewData['breadcrumb'] = [
|
|
['title' => lang("App.menu_presupuestos"), 'route' => site_url('presupuestocliente/list'), 'active' => false],
|
|
['title' => "Añadir Presupuesto", 'route' => "javascript:void(0);", 'active' => true]
|
|
];
|
|
|
|
$this->viewData['formAction'] = 'add';
|
|
|
|
$this->viewData['state'] = 1;
|
|
|
|
$this->viewData['paisList'] = model('App\Models\Configuracion\PaisModel')->getAllForMenu('id, nombre', 'nombre', true);
|
|
$this->viewData['clienteId'] = $clienteId;
|
|
$this->viewData['POD'] = $POD;
|
|
$this->viewData['lomo_maximo_fresado_cosido'] = model('App\Models\Configuracion\ConfigVariableModel')->getVariable('lomo_maximo_fresado_cosido')->value;
|
|
$this->viewData['lomo_minimo_fresado_cosido'] = model('App\Models\Configuracion\ConfigVariableModel')->getVariable('lomo_minimo_fresado_cosido')->value;
|
|
$this->viewData['eb'] = 0;
|
|
|
|
$this->viewData['boxTitle'] = lang('Basic.global.addNew') . ' ' . $this->viewData['pageTitle'] . ' ' . lang('Basic.global.addNewSuffix');
|
|
|
|
$this->viewData['serviciosExtra'] = $this->getServiciosExtra();
|
|
|
|
return $this->displayForm(__METHOD__);
|
|
} // end function add()
|
|
|
|
|
|
public function edit($requestedId = null)
|
|
{
|
|
checkPermission('presupuesto-cliente.edit');
|
|
|
|
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;
|
|
|
|
// Se obtiene el cliente ID a partir del usuario de la sesion
|
|
$model_user = model('App\Models\Usuarios\UserModel');
|
|
$user = $model_user->find(auth()->user()->id);
|
|
if (auth()->user()->inGroup('cliente-admin') || auth()->user()->inGroup('cliente-editor')) {
|
|
$clienteId = $user->cliente_id;
|
|
if ($clienteId === false || $clienteId === null) {
|
|
return $this->failNotFound('Su usuario no tiene asociado un cliente de Safekat. Póngase en contacto con el administrador.');
|
|
}
|
|
} else {
|
|
$clienteId = $presupuestoEntity->cliente_id;
|
|
}
|
|
|
|
$this->viewData['formAction'] = 'edit';
|
|
|
|
$this->viewData['paisList'] = $this->getPaisListItems();
|
|
|
|
$this->viewData['clienteId'] = $clienteId;
|
|
$this->viewData['POD'] = model('App\Models\Configuracion\ConfigVariableModel')->getVariable('POD')->value;
|
|
$this->viewData['lomo_maximo_fresado_cosido'] = model('App\Models\Configuracion\ConfigVariableModel')->getVariable('lomo_maximo_fresado_cosido')->value;
|
|
$this->viewData['lomo_minimo_fresado_cosido'] = model('App\Models\Configuracion\ConfigVariableModel')->getVariable('lomo_minimo_fresado_cosido')->value;
|
|
$this->viewData['eb'] = $presupuestoEntity->envio_base;
|
|
|
|
// 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['presupuestoId'] = $presupuestoEntity->id;
|
|
$this->viewData['state'] = intval($presupuestoEntity->estado_id);
|
|
$this->viewData['boxTitle'] = lang('Basic.global.edit2') . ' ' . $this->viewData['pageTitle'] . ' ' . lang('Basic.global.edit3');
|
|
|
|
$this->viewData['serviciosExtra'] = $this->getServiciosExtra();
|
|
|
|
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]));
|
|
}
|
|
}
|
|
|
|
$this->borrarRelacionesPresupuesto($id);
|
|
|
|
// $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();
|
|
|
|
$clienteId = $reqData['cliente'] ?? 0;
|
|
|
|
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_CLIENTE[$requestedOrder1 >= 0 ? $requestedOrder1 : 0];
|
|
$dir1 = $reqData['order']['0']['dir'] ?? 'asc';
|
|
$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->getListaPresupuestosCliente($searchValues, $clienteId)->orderBy($order1, $dir1)->orderBy($order2, $dir2)
|
|
->orderBy($order3, $dir3)->limit($length, $start)->get()->getResultObject();
|
|
|
|
return $this->respond(Collection::datatable(
|
|
$resourceData,
|
|
$this->model->getListaPresupuestosCliente([], $clienteId)->countAllResults(),
|
|
$this->model->getListaPresupuestosCliente($searchValues, $clienteId)->countAllResults()
|
|
));
|
|
} else {
|
|
return $this->failUnauthorized('Invalid request', 403);
|
|
}
|
|
}
|
|
|
|
|
|
public function check_lomo_interior()
|
|
{
|
|
if ($this->request->isAJAX()) {
|
|
|
|
$reqData = $this->request->getPost();
|
|
$modelPapelGenerico = new PapelGenericoModel();
|
|
|
|
$POD = model('App\Models\Configuracion\ConfigVariableModel')->getVariable('POD')->value;
|
|
|
|
$cliente_id = $reqData['clienteId'] ?? -1;
|
|
|
|
$tirada = $reqData['tirada'] ?? 0;
|
|
$tamanio = $reqData['tamanio'];
|
|
$paginas = $reqData['paginas'] ?? 0;
|
|
$paginas_color = $reqData['paginasColor'] ?? 0;
|
|
$papelInteriorDiferente = intval($reqData['papelInteriorDiferente']) ?? null;
|
|
$excluirRotativa = $reqData['excluirRotativa'] ?? 0;
|
|
$excluirRotativa = intval($excluirRotativa);
|
|
|
|
$tipo = $reqData['tipo'];
|
|
$tipoCubierta = 'blanda'; // solapas sólo tapa blanda y sobre cubierta
|
|
|
|
$isColor = intval($reqData['isColor']) ?? 0;
|
|
$isHq = intval($reqData['isHq']) ?? 0;
|
|
|
|
$tipo_impresion_id = $this->getTipoImpresion($tipo, $tipoCubierta);
|
|
$is_cosido = (new TipoPresupuestoModel())->get_isCosido($tipo_impresion_id);
|
|
|
|
$interior = $reqData['interior'] ?? [];
|
|
|
|
if ($papelInteriorDiferente) {
|
|
$papel['negro'] = $modelPapelGenerico->where('id', $interior['papelInterior']['negro'])->first()->toArray();
|
|
$papel['color'] = $modelPapelGenerico->where('id', $interior['papelInterior']['color'])->first()->toArray();
|
|
$gramaje['negro'] = intval($interior['gramajeInterior']['negro']);
|
|
$gramaje['color'] = intval($interior['gramajeInterior']['color']);
|
|
} else {
|
|
$papel = $modelPapelGenerico->where('id', $interior['papelInterior'])->first()->toArray();
|
|
$gramaje = intval($interior['gramajeInterior']);
|
|
}
|
|
|
|
$datosPedido = (object) array(
|
|
'paginas' => $paginas,
|
|
'tirada' => $tirada[0],
|
|
'merma' => PresupuestoService::calcular_merma($tirada[0], $POD),
|
|
'ancho' => intval($tamanio['ancho']) ?? 100000,
|
|
'alto' => intval($tamanio['alto']) ?? 100000,
|
|
'isCosido' => $is_cosido,
|
|
'a_favor_fibra' => 1,
|
|
);
|
|
|
|
$cliente_model = model(('App\Models\Clientes\ClienteModel'));
|
|
$cliente = $cliente_model->find($cliente_id);
|
|
|
|
$forzarRotativa = false;
|
|
if ($tirada[0] <= $POD && $cliente->forzar_rotativa_pod) {
|
|
$forzarRotativa = true;
|
|
} else if ($tirada[0] <= $POD && !$cliente->forzar_rotativa_pod) {
|
|
$excluirRotativa = true;
|
|
}
|
|
|
|
|
|
$input_data = array(
|
|
'uso' => 'interior',
|
|
'tipo_impresion_id' => $tipo_impresion_id,
|
|
'datosPedido' => $datosPedido,
|
|
'papel_generico' => $papel,
|
|
'gramaje' => $gramaje,
|
|
'isColor' => $isColor,
|
|
'isHq' => $isHq,
|
|
'cliente_id' => $cliente_id,
|
|
'paginas_color' => $paginas_color,
|
|
'excluirRotativa' => $excluirRotativa,
|
|
'papelInteriorDiferente' => $papelInteriorDiferente,
|
|
'forzarRotativa' => $forzarRotativa,
|
|
);
|
|
|
|
$interior = PresupuestoClienteService::obtenerInterior($input_data);
|
|
if ($interior == null) {
|
|
return $this->failServerError('Error al calcular el interior');
|
|
}
|
|
|
|
$lomo = 0.0;
|
|
foreach ($interior as $linea) {
|
|
if (count($linea) > 0) {
|
|
$lomo += floatval($linea['mano']);
|
|
}
|
|
}
|
|
|
|
//Guardas
|
|
$guardas = $reqData['guardas'] ?? [];
|
|
if ($guardas != "false" && $guardas != null) {
|
|
$datos_guardas = [
|
|
'papel' => intval($guardas['papel']),
|
|
'gramaje' => intval($guardas['gramaje']),
|
|
'caras' => intval($guardas['caras']),
|
|
];
|
|
} else
|
|
$datos_guardas = false;
|
|
$guardas = [];
|
|
$peso_guardas = 0.0;
|
|
$coste_guardas = 0.0;
|
|
if ($datos_guardas != 0) {
|
|
if (count($datos_guardas) != 0 && $datos_guardas) {
|
|
|
|
$guardas = $datos_guardas;
|
|
$input_data['papel_generico']['id'] = $datos_guardas['papel'] ?? 0;
|
|
$input_data['gramaje'] = $datos_guardas['gramaje'] ?? 0;
|
|
$input_data['datosPedido']->paginas = 8;
|
|
$input_data['paginas_color'] = 8;
|
|
$input_data['datosPedido']->paginas_impresion = $datos_guardas['caras'] ?? 0;
|
|
$input_data['datosPedido']->solapas_ancho = 0;
|
|
$input_data['datosPedido']->solapas = 0;
|
|
$input_data['isColor'] = 1;
|
|
$input_data['isHq'] = 1;
|
|
$input_data['uso'] = 'guardas';
|
|
|
|
// 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) {
|
|
$input_data['datosPedido']->isCosido = true;
|
|
} else if ($tipo_impresion_id == 5 || $tipo_impresion_id == 7) {
|
|
$input_data['datosPedido']->isCosido = false;
|
|
}
|
|
|
|
$guardas = PresupuestoClienteService::obtenerGuardas($input_data);
|
|
|
|
if ($guardas != null && count($guardas) > 0) {
|
|
$lomo += floatval($guardas['mano']);
|
|
}
|
|
}
|
|
}
|
|
|
|
$lomo = round($lomo, 2);
|
|
$errors = [
|
|
'status' => 0,
|
|
'value' => ""
|
|
];
|
|
$lomo_minimo_fresado_cosido = intval(model('App\Models\Configuracion\ConfigVariableModel')->getVariable('lomo_minimo_fresado_cosido')->value);
|
|
$lomo_maximo_fresado_cosido = intval(model('App\Models\Configuracion\ConfigVariableModel')->getVariable('lomo_maximo_fresado_cosido')->value);
|
|
$lomo_maximo_espiral = intval(model('App\Models\Configuracion\ConfigVariableModel')->getVariable('lomo_maximo_espiral')->value);
|
|
$lomo_maximo_wireo = intval(model('App\Models\Configuracion\ConfigVariableModel')->getVariable('lomo_maximo_wireo')->value);
|
|
|
|
if ($tipo == 'cosido' || $tipo == 'fresado') {
|
|
if ($lomo < $lomo_minimo_fresado_cosido) {
|
|
$errors['status'] = 1;
|
|
$errors['value'] = lang(
|
|
'Presupuestos.errores.error_lomo_minimo',
|
|
[
|
|
lang('Presupuestos.cosido') . "/" . lang('Presupuestos.fresado'),
|
|
$lomo_minimo_fresado_cosido,
|
|
$lomo,
|
|
]
|
|
);
|
|
}
|
|
if ($lomo > $lomo_maximo_fresado_cosido) {
|
|
$errors['status'] = 1;
|
|
$errors['value'] = lang(
|
|
'Presupuestos.errores.error_lomo_maximo',
|
|
[
|
|
lang('Presupuestos.cosido') . "/" . lang('Presupuestos.fresado'),
|
|
$lomo_maximo_fresado_cosido,
|
|
$lomo,
|
|
]
|
|
);
|
|
}
|
|
} else if ($tipo == 'espiral' && $lomo > $lomo_maximo_espiral) {
|
|
$errors['status'] = 1;
|
|
$errors['value'] = lang(
|
|
'Presupuestos.errores.error_lomo_maximo',
|
|
[
|
|
lang('Presupuestos.espiral'),
|
|
$lomo_maximo_espiral,
|
|
$lomo,
|
|
]
|
|
);
|
|
} else if ($tipo == 'wireo' && $lomo > $lomo_maximo_wireo) {
|
|
$errors['status'] = 1;
|
|
$errors['value'] = lang(
|
|
'Presupuestos.errores.error_lomo_maximo',
|
|
[
|
|
lang('Presupuestos.wireo'),
|
|
$lomo_maximo_wireo,
|
|
$lomo,
|
|
]
|
|
);
|
|
}
|
|
|
|
$data = (object) array(
|
|
'lomo' => $lomo,
|
|
'errors' => $errors
|
|
);
|
|
return $this->respond($data);
|
|
|
|
} else {
|
|
return $this->failUnauthorized('Invalid request', 403);
|
|
}
|
|
}
|
|
|
|
public function calcular($data = -1)
|
|
{
|
|
if ($this->request) {
|
|
if ($this->request->isAJAX())
|
|
$reqData = $this->request->getPost();
|
|
} else {
|
|
if ($data == -1) {
|
|
return "Error: sin datos";
|
|
}
|
|
$reqData = $data;
|
|
}
|
|
|
|
try {
|
|
|
|
//$reqData = $this->request->getPost();
|
|
$modelPapelGenerico = new PapelGenericoModel();
|
|
|
|
$id = $reqData['id'] ?? 0;
|
|
|
|
$cliente_id = $reqData['clienteId'] ?? -1;
|
|
$noEnvioBase = model('App\Models\Clientes\ClienteModel')->find($cliente_id)->no_envio_base ?? false;
|
|
|
|
$tirada = $reqData['tirada'] ?? 0;
|
|
$selectedTirada = $reqData['selectedTirada'] ?? (is_array($tirada) ? $tirada[0] : $tirada);
|
|
$tamanio = $reqData['tamanio'];
|
|
$paginas = $reqData['paginas'] ?? 0;
|
|
$paginas_color = $reqData['paginasColor'] ?? 0;
|
|
$tipo = $reqData['tipo'] ?? 'cosido';
|
|
|
|
$paginasCuadernillo = $reqData['paginasCuadernillo'] ?? null;
|
|
$papelInteriorDiferente = intval($reqData['papelInteriorDiferente'] ?? null);
|
|
|
|
$isColor = intval($reqData['isColor']) ?? 0;
|
|
$isHq = intval($reqData['isHq']) ?? 0;
|
|
|
|
$interior = $reqData['interior'] ?? [];
|
|
$cubierta = $reqData['cubierta'] ?? [];
|
|
$sobrecubierta = $reqData['sobrecubierta'] ?? [];
|
|
$guardas = $reqData['guardas'] ?? [];
|
|
$faja = $reqData['faja'] ?? [];
|
|
$excluirRotativa = $reqData['excluirRotativa'] ?? 0;
|
|
$excluirRotativa = intval($excluirRotativa);
|
|
|
|
$direcciones = $reqData['direcciones'] ?? [];
|
|
|
|
$tipo_impresion_id = intval($reqData['tipo_presupuesto_id'] ?? 0) == 0 ?
|
|
$this->getTipoImpresion($tipo, $cubierta['tipoCubierta']) : intval($reqData['tipo_presupuesto_id']);
|
|
$lomoRedondo = $cubierta['lomoRedondo'] ?? 0;
|
|
|
|
if ($papelInteriorDiferente) {
|
|
$papel['negro'] = $modelPapelGenerico->where('id', $interior['papelInterior']['negro'])->first()->toArray();
|
|
$papel['color'] = $modelPapelGenerico->where('id', $interior['papelInterior']['color'])->first()->toArray();
|
|
$gramaje['negro'] = intval($interior['gramajeInterior']['negro']);
|
|
$gramaje['color'] = intval($interior['gramajeInterior']['color']);
|
|
} else {
|
|
$papel = $modelPapelGenerico->where('id', $interior['papelInterior'])->first()->toArray();
|
|
$gramaje = intval($interior['gramajeInterior']);
|
|
}
|
|
// Interior
|
|
$interior = [
|
|
'papel_generico' => $papel,
|
|
'gramaje' => $gramaje,
|
|
'excluirRotativa' => $excluirRotativa,
|
|
'paginas' => $paginas,
|
|
'paginas_color' => $paginas_color,
|
|
'papelInteriorDiferente' => $papelInteriorDiferente
|
|
];
|
|
|
|
|
|
// Cubierta
|
|
$cubierta = [
|
|
'papel_generico_cubierta' => $modelPapelGenerico->where('id', $cubierta['papelCubierta'])->first()->toArray(),
|
|
'gramajeCubierta' => intval($cubierta['gramajeCubierta']),
|
|
'carasCubierta' => intval($cubierta['carasImpresion'] ?? 0),
|
|
'solapasCubierta' => intval($cubierta['solapas'] ?? 0) == 1 ? intval($cubierta['tamanioSolapas']) : 0,
|
|
'acabado' => $cubierta['acabado'] ?? 0,
|
|
'lomoRedondo' => $lomoRedondo,
|
|
];
|
|
|
|
// Sobrecubierta
|
|
if ($sobrecubierta != "false" && $sobrecubierta != null) {
|
|
$sobrecubierta = [
|
|
'papel' => $modelPapelGenerico->where('id', $sobrecubierta['papel'])->first()->toArray(),
|
|
'gramaje' => intval($sobrecubierta['gramaje']),
|
|
'solapas' => intval($sobrecubierta['solapas'] ?? 0),
|
|
'acabado' => $sobrecubierta['acabado'] ?? 0,
|
|
];
|
|
} else
|
|
$sobrecubierta = false;
|
|
|
|
// Guardas
|
|
if ($guardas != "false" && $guardas != null) {
|
|
$datos_guardas = [
|
|
'papel' => $modelPapelGenerico->where('id', $guardas['papel'])->first()->toArray(),
|
|
'gramaje' => intval($guardas['gramaje']),
|
|
'caras' => intval($guardas['caras']),
|
|
];
|
|
} else
|
|
$datos_guardas = false;
|
|
|
|
$datos_presupuesto = array(
|
|
'id' => $id,
|
|
'tirada' => $tirada,
|
|
'tamanio' => $tamanio,
|
|
'tipo_impresion_id' => $tipo_impresion_id,
|
|
'clienteId' => $cliente_id,
|
|
'isColor' => $isColor,
|
|
'isHq' => $isHq,
|
|
'paginasCuadernillo' => $paginasCuadernillo,
|
|
|
|
'interior' => $interior,
|
|
'cubierta' => $cubierta,
|
|
'sobrecubierta' => $sobrecubierta,
|
|
'datos_guardas' => $datos_guardas,
|
|
'faja' => $faja,
|
|
|
|
'servicios' => $reqData['servicios'] ?? [],
|
|
);
|
|
|
|
$develoment_mode = getenv('SK_ENVIRONMENT') !== 'production';
|
|
$return_data = $this->calcular_presupuesto($datos_presupuesto, $selectedTirada, $develoment_mode); //TRUE FOR DEBUG
|
|
if (array_key_exists('errors', $return_data)) {
|
|
if ($return_data['errors']->status == 1) {
|
|
$return_data = [
|
|
'errors' => (object) ([
|
|
'status' => 1
|
|
]),
|
|
];
|
|
return $return_data;
|
|
}
|
|
}
|
|
|
|
if (array_key_exists('exception', $return_data)) {
|
|
|
|
return $this->failServerError(
|
|
$return_data['exception'] . ' - ' .
|
|
$return_data['file'] . ' - ' . $return_data['line']
|
|
);
|
|
}
|
|
|
|
// calculo del envio base (tirada_maxima)
|
|
$return_data['eb'] = [];
|
|
for ($i = 0; $i < count($tirada); $i++) {
|
|
$direccion = [];
|
|
$coste_direccion = $this->getCosteEnvio(
|
|
$direccion,
|
|
$return_data['peso'][$i],
|
|
$tirada[$i],
|
|
false,
|
|
true
|
|
);
|
|
|
|
if (!property_exists($coste_direccion, 'coste')) {
|
|
$errorModel = new ErrorPresupuesto();
|
|
$data['direccion'] = 'Sin direccion';
|
|
$data['peso'] = $return_data['peso'][$i];
|
|
$data['palets'] = 'Sin direccion';
|
|
$errorModel->insertError(
|
|
$id,
|
|
auth()->user()->id,
|
|
'No se ha podido calcular el coste de envío',
|
|
$data
|
|
);
|
|
$return_data = [
|
|
'errors' => (object) ([
|
|
'status' => 1
|
|
]),
|
|
];
|
|
return $return_data;
|
|
} else {
|
|
$coste = floatval($coste_direccion->coste);
|
|
$margen = $coste * (intval($coste_direccion->margen) / 100.0);
|
|
if ($noEnvioBase) {
|
|
$coste = 0.0;
|
|
$margen = 0.0;
|
|
}
|
|
$return_data['eb'][$i] = round($coste + $margen, 2);
|
|
}
|
|
}
|
|
|
|
// para el calculo del precio unidad, sólo se tiene en cuenta el envío base
|
|
for ($i = 0; $i < count($tirada); $i++) {
|
|
$coste_envio = 0.0;
|
|
$coste_envio += ($return_data['eb'][$i] / $tirada[$i]);
|
|
$return_data['precio_u'][$i] = round(floatval($return_data['precio_u'][$i]) + $coste_envio, 4);
|
|
}
|
|
|
|
$coste_envio = 0.0; // se inicializa para calcular los costes de envíos restantes si es que hay
|
|
$return_data['coste_envio'] = [];
|
|
if (count($direcciones) > 0) {
|
|
|
|
for ($i = 0; $i < count($tirada); $i++) {
|
|
$coste_envio = 0.0;
|
|
$envio_base = true;
|
|
foreach ($direcciones as $direccion) {
|
|
// El primer envio no se calcula ya que se añade el base
|
|
if ($envio_base) {
|
|
$envio_base = false;
|
|
continue;
|
|
}
|
|
if ($selectedTirada > 0) {
|
|
$unidades = floor($direccion['unidades'] * $tirada[$i] / $selectedTirada);
|
|
} else {
|
|
$unidades = $direccion['unidades'];
|
|
}
|
|
$coste_direccion = $this->getCosteEnvio(
|
|
$direccion['direccion'],
|
|
$return_data['peso'][$i],
|
|
$unidades,
|
|
$direccion['entregaPalets'] == 'true' ? 1 : 0,
|
|
false,
|
|
);
|
|
|
|
if (!property_exists($coste_direccion, 'coste')) {
|
|
|
|
$errorModel = new ErrorPresupuesto();
|
|
$data['direccion'] = $direccion;
|
|
$data['peso'] = $return_data['peso'][$i];
|
|
$data['palets'] = $direccion['entregaPalets'] == 'true' ? 1 : 0;
|
|
$errorModel->insertError(
|
|
$id,
|
|
auth()->user()->id,
|
|
'No se ha podido calcular el coste de envío',
|
|
$data
|
|
);
|
|
$return_data = [
|
|
'errors' => (object) ([
|
|
'status' => 1
|
|
]),
|
|
];
|
|
return $return_data;
|
|
} else {
|
|
$coste = floatval($coste_direccion->coste);
|
|
$margen = $coste * (intval($coste_direccion->margen) / 100.0);
|
|
$coste_envio += $coste + $margen;
|
|
}
|
|
}
|
|
|
|
$return_data['coste_envio'][$i] = round($coste_envio, 2);
|
|
}
|
|
}
|
|
|
|
// Se suma el coste de envío a cada precio unidad
|
|
for ($i = 0; $i < count($tirada); $i++) {
|
|
if ($return_data['coste_envio'] && isset($return_data['coste_envio'][$i]) && $return_data['coste_envio'][$i] > 0)
|
|
$return_data['precio_u'][$i] = round(floatval($return_data['precio_u'][$i]) + $return_data['coste_envio'][$i] / $tirada[$i], 4);
|
|
}
|
|
|
|
if ($this->request) {
|
|
if ($this->request->isAJAX())
|
|
return $this->respond($return_data);
|
|
} else {
|
|
return $return_data;
|
|
}
|
|
|
|
} catch (Exception $e) {
|
|
if ($this->request) {
|
|
if ($this->request->isAJAX())
|
|
return $this->failServerError($e->getMessage() . ' - ' . $e->getFile() . ' - ' . $e->getLine());
|
|
} else {
|
|
return "Error: " . $e->getMessage();
|
|
}
|
|
}
|
|
|
|
}
|
|
|
|
|
|
public function calcularMaxSolapas()
|
|
{
|
|
if ($this->request->isAJAX()) {
|
|
|
|
$reqData = $this->request->getPost();
|
|
$modelPapelGenerico = new PapelGenericoModel();
|
|
|
|
$POD = model('App\Models\Configuracion\ConfigVariableModel')->getVariable('POD')->value;
|
|
|
|
$cliente_id = $reqData['clienteId'] ?? -1;
|
|
|
|
$tirada = $reqData['tirada'] ?? 0;
|
|
$tamanio = $reqData['tamanio'];
|
|
$paginas = $reqData['paginas'] ?? 0;
|
|
$paginas_color = $reqData['paginasColor'] ?? 0;
|
|
$papelInteriorDiferente = intval($reqData['papelInteriorDiferente']) ?? null;
|
|
$excluirRotativa = $reqData['excluirRotativa'] ?? 0;
|
|
$excluirRotativa = intval($excluirRotativa);
|
|
|
|
$tipo = $reqData['tipo'] ?? 'cosido';
|
|
$tipoCubierta = 'blanda'; // solapas sólo tapa blanda y sobre cubierta
|
|
|
|
$isColor = intval($reqData['isColor']) ?? 0;
|
|
$isHq = intval($reqData['isHq']) ?? 0;
|
|
|
|
$tipo_impresion_id = $this->getTipoImpresion($tipo, $tipoCubierta);
|
|
$is_cosido = (new TipoPresupuestoModel())->get_isCosido($tipo_impresion_id);
|
|
|
|
$interior = $reqData['interior'] ?? [];
|
|
|
|
if ($papelInteriorDiferente) {
|
|
$papel['negro'] = $modelPapelGenerico->where('id', $interior['papelInterior']['negro'])->first()->toArray();
|
|
$papel['color'] = $modelPapelGenerico->where('id', $interior['papelInterior']['color'])->first()->toArray();
|
|
$gramaje['negro'] = intval($interior['gramajeInterior']['negro']);
|
|
$gramaje['color'] = intval($interior['gramajeInterior']['color']);
|
|
} else {
|
|
$papel = $modelPapelGenerico->where('id', $interior['papelInterior'])->first()->toArray();
|
|
$gramaje = intval($interior['gramajeInterior']);
|
|
}
|
|
|
|
$datosPedido = (object) array(
|
|
'paginas' => $paginas,
|
|
'tirada' => $tirada[0],
|
|
'merma' => $tirada[0] > $POD ? PresupuestoService::calcular_merma($tirada[0], $POD) : 0,
|
|
'ancho' => intval($tamanio['ancho']) ?? 100000,
|
|
'alto' => intval($tamanio['alto']) ?? 100000,
|
|
'isCosido' => $is_cosido,
|
|
'a_favor_fibra' => 1,
|
|
);
|
|
|
|
$cliente_model = model(('App\Models\Clientes\ClienteModel'));
|
|
$cliente = $cliente_model->find($cliente_id);
|
|
|
|
$forzarRotativa = false;
|
|
if ($tirada[0] <= $POD && $cliente->forzar_rotativa_pod) {
|
|
$forzarRotativa = true;
|
|
} else if ($tirada[0] <= $POD && !$cliente->forzar_rotativa_pod) {
|
|
$excluirRotativa = true;
|
|
}
|
|
|
|
$input_data = array(
|
|
'uso' => 'interior',
|
|
'tipo_impresion_id' => $tipo_impresion_id,
|
|
'datosPedido' => $datosPedido,
|
|
'papel_generico' => $papel,
|
|
'gramaje' => $gramaje,
|
|
'isColor' => $isColor,
|
|
'isHq' => $isHq,
|
|
'cliente_id' => $cliente_id,
|
|
'paginas_color' => $paginas_color,
|
|
'excluirRotativa' => $excluirRotativa,
|
|
'papelInteriorDiferente' => $papelInteriorDiferente,
|
|
'forzarRotativa' => $forzarRotativa,
|
|
);
|
|
|
|
$interior = PresupuestoClienteService::obtenerInterior($input_data);
|
|
if ($interior == null) {
|
|
return $this->failServerError('Error al calcular el interior');
|
|
}
|
|
|
|
$anchoTotal = 0;
|
|
if (count($interior) == 2) {
|
|
|
|
if (count($interior[0]) > 0)
|
|
$anchoTotal += $interior[0]['mano'];
|
|
if (count($interior[1]) > 0)
|
|
$anchoTotal += $interior[1]['mano'];
|
|
} else {
|
|
if (count($interior) > 0)
|
|
$anchoTotal += $interior[0]['mano'];
|
|
}
|
|
|
|
|
|
// le añadimos 2*ancho libro
|
|
$anchoTotal += 2 * $datosPedido->ancho;
|
|
// le añadimos los dobleces de las solapas
|
|
$anchoTotal += 6;
|
|
// le añadimos la sangre
|
|
$anchoTotal += PresupuestoService::SANGRE_FORMAS;
|
|
// 863 es el ancho máximo permitido por las máquinas
|
|
$maxSolapa = (865 - floor($anchoTotal)) / 2;
|
|
$maxSolapa = min($maxSolapa, 0.95 * $datosPedido->ancho);
|
|
return $this->respond($maxSolapa);
|
|
|
|
} else {
|
|
return $this->failUnauthorized('Invalid request', 403);
|
|
}
|
|
|
|
}
|
|
|
|
|
|
public function getDireccionesCliente()
|
|
{
|
|
if ($this->request->isAJAX()) {
|
|
|
|
$newTokenHash = csrf_hash();
|
|
$csrfTokenName = csrf_token();
|
|
|
|
$reqData = $this->request->getPost();
|
|
$cliente_id = $reqData['id'] ?? 0;
|
|
$model = model('App\Models\Clientes\ClienteDireccionesModel');
|
|
$data = $model->getMenuDirecciones($cliente_id);
|
|
array_unshift($data, ['id' => 0, 'text' => 'Agregar nueva dirección']);
|
|
|
|
return $this->respond([
|
|
'menu' => $data,
|
|
$csrfTokenName => $newTokenHash
|
|
]);
|
|
|
|
} else {
|
|
return $this->failUnauthorized('Invalid request', 403);
|
|
}
|
|
}
|
|
|
|
|
|
|
|
public function getNuevaDireccion()
|
|
{
|
|
|
|
if ($this->request->isAJAX()) {
|
|
|
|
$newTokenHash = csrf_hash();
|
|
$csrfTokenName = csrf_token();
|
|
|
|
$reqData = $this->request->getPost();
|
|
|
|
$data = [
|
|
'cliente_id' => $reqData['cliente_id'] ?? 0,
|
|
'alias' => $reqData['alias'] ?? "",
|
|
'att' => $reqData['att'] ?? "",
|
|
'email' => $reqData['email'] ?? "",
|
|
'direccion' => $reqData['direccion'] ?? "",
|
|
'pais_id' => $reqData['pais_id'] ?? 0,
|
|
'municipio' => $reqData['municipio'] ?? "",
|
|
'provincia' => $reqData['provincia'] ?? "",
|
|
'cp' => $reqData['cp'] ?? "",
|
|
'telefono' => $reqData['telefono'] ?? ""
|
|
];
|
|
|
|
$model = model('App\Models\Clientes\ClienteDireccionesModel');
|
|
$id = $model->nuevaDireccion($data);
|
|
|
|
$menu = $model->getMenuDirecciones($data['cliente_id']);
|
|
|
|
return $this->respond([
|
|
'data' => $menu,
|
|
$csrfTokenName => $newTokenHash
|
|
]);
|
|
} else {
|
|
return $this->failUnauthorized('Invalid request', 403);
|
|
}
|
|
}
|
|
|
|
public function duplicarPresupuesto()
|
|
{
|
|
if ($this->request->isAJAX()) {
|
|
|
|
$reqData = $this->request->getPost();
|
|
|
|
$newTokenHash = csrf_hash();
|
|
$csrfTokenName = csrf_token();
|
|
|
|
$id = $reqData['id'] ?? 0;
|
|
|
|
if ($id > 0) {
|
|
try {
|
|
|
|
$presupuesto = $this->model->find($id);
|
|
$presupuesto->titulo = $presupuesto->titulo . ' - ' . lang('Presupuestos.duplicado');
|
|
$presupuesto->is_duplicado = 1;
|
|
$presupuesto->estado_id = 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 $this->respond([
|
|
'success' => true,
|
|
'id' => $new_id,
|
|
$csrfTokenName => $newTokenHash
|
|
]);
|
|
} catch (\Exception $e) {
|
|
return $this->respond([
|
|
'success' => false,
|
|
'message' => $e->getMessage(),
|
|
$csrfTokenName => $newTokenHash
|
|
]);
|
|
}
|
|
}
|
|
|
|
return $this->respond([
|
|
'success' => false,
|
|
'message' => "No existe el presupuesto",
|
|
$csrfTokenName => $newTokenHash
|
|
|
|
]);
|
|
} else {
|
|
return $this->failUnauthorized('Invalid request', 403);
|
|
}
|
|
}
|
|
|
|
public function guardar($data = -1)
|
|
{
|
|
|
|
if ($this->request) {
|
|
if ($this->request->isAJAX())
|
|
$reqData = $this->request->getPost();
|
|
} else {
|
|
if ($data == -1) {
|
|
return "Error: sin datos";
|
|
}
|
|
$reqData = $data;
|
|
}
|
|
|
|
$modelPapelGenerico = new PapelGenericoModel();
|
|
|
|
//$reqData = $this->request->getPost();
|
|
|
|
$POD = model('App\Models\Configuracion\ConfigVariableModel')->getVariable('POD')->value;
|
|
|
|
$id = $reqData['id'] ?? 0;
|
|
$id = intval($id);
|
|
|
|
$datosCabecera = $reqData['datosCabecera'] ?? [];
|
|
|
|
|
|
$confirmar = $reqData['confirmar'] ?? 0;
|
|
$confirmar = intval($confirmar);
|
|
|
|
$cliente_id = $reqData['clienteId'] ?? -1;
|
|
|
|
$tirada = $reqData['tirada'] ?? [];
|
|
$selected_tirada = $reqData['selectedTirada'] ?? 0;
|
|
$tamanio = $reqData['tamanio'];
|
|
$paginas = $reqData['paginas'] ?? 0;
|
|
$paginas_color = $reqData['paginasColor'] ?? 0;
|
|
|
|
$envio_base = $reqData['eb'] ?? 0;
|
|
|
|
$posPaginasColor = $reqData['posPaginasColor'] ?? "";
|
|
$paginasColorConsecutivas = $reqData['pagColorConsecutivas'] ?? 0;
|
|
$papelInteriorDiferente = $reqData['papelInteriorDiferente'] ?? 0;
|
|
|
|
$tipo = $reqData['tipo'] ?? "";
|
|
|
|
$paginasCuadernillo = $reqData['paginasCuadernillo'] ?? 32;
|
|
$papelInteriorDiferente = intval($reqData['papelInteriorDiferente'] ?? null);
|
|
|
|
$isColor = intval($reqData['isColor']) ?? 0;
|
|
$isHq = intval($reqData['isHq']) ?? 0;
|
|
|
|
$prototipo = intval($reqData['prototipo'] ?? 0);
|
|
$ferro = intval($reqData['ferro'] ?? 0);
|
|
$ferroDigital = intval($reqData['ferroDigital'] ?? 0);
|
|
$marcapaginas = intval($reqData['marcapaginas'] ?? 0);
|
|
$retractilado = intval($reqData['retractilado'] ?? 0);
|
|
$retractilado5 = intval($reqData['retractilado5'] ?? 0);
|
|
|
|
$interior = $reqData['interior'] ?? [];
|
|
$cubierta = $reqData['cubierta'] ?? [];
|
|
$sobrecubierta = $reqData['sobrecubierta'] ?? [];
|
|
$guardas = $reqData['guardas'] ?? [];
|
|
$faja = $reqData['faja'] ?? [];
|
|
$excluirRotativa = $reqData['excluirRotativa'] ?? 0;
|
|
$excluirRotativa = intval($excluirRotativa);
|
|
$ivaReducido = intval($reqData['ivaReducido'] ?? 0);
|
|
|
|
$direcciones = $reqData['direcciones'] ?? [];
|
|
|
|
$direccionesFP1 = $reqData['direccionesFP1'] ?? [];
|
|
$direccionesFP2 = $reqData['direccionesFP2'] ?? [];
|
|
|
|
if ($tipo != "")
|
|
$tipo_impresion_id = $this->getTipoImpresion($tipo, $cubierta['tipoCubierta']);
|
|
else
|
|
$tipo_impresion_id = $reqData['tipo_presupuesto_id'] ?? 0;
|
|
|
|
if ($papelInteriorDiferente) {
|
|
$papel['negro'] = $modelPapelGenerico->where('id', $interior['papelInterior']['negro'])->first()->toArray();
|
|
$papel['color'] = $modelPapelGenerico->where('id', $interior['papelInterior']['color'])->first()->toArray();
|
|
$gramaje['negro'] = intval($interior['gramajeInterior']['negro']);
|
|
$gramaje['color'] = intval($interior['gramajeInterior']['color']);
|
|
} else {
|
|
$papel = $modelPapelGenerico->where('id', $interior['papelInterior'])->first()->toArray();
|
|
$gramaje = intval($interior['gramajeInterior']);
|
|
}
|
|
// Interior
|
|
$interior = [
|
|
'papel_generico' => $papel,
|
|
'gramaje' => $gramaje,
|
|
'excluirRotativa' => $excluirRotativa,
|
|
'paginas' => $paginas,
|
|
'paginas_color' => $paginas_color,
|
|
'pos_paginas_color' => $posPaginasColor,
|
|
'paginas_color_consecutivas' => $paginasColorConsecutivas,
|
|
'papelInteriorDiferente' => $papelInteriorDiferente
|
|
];
|
|
|
|
|
|
// Cubierta
|
|
$cubierta = [
|
|
'papel_generico_cubierta' => $modelPapelGenerico->where('id', $cubierta['papelCubierta'])->first()->toArray(),
|
|
'gramajeCubierta' => intval($cubierta['gramajeCubierta']),
|
|
'carasCubierta' => intval($cubierta['carasImpresion'] ?? 2),
|
|
'solapasCubierta' => intval($cubierta['solapas'] ?? 0) == 1 ? intval($cubierta['tamanioSolapas']) : 0,
|
|
'acabado' => $cubierta['acabado'] ?? 0,
|
|
'lomoRedondo' => $cubierta['lomoRedondo'] ?? 0,
|
|
'cabezada' => $cubierta['cabezada'] ?? 'WHI',
|
|
];
|
|
|
|
// Sobrecubierta
|
|
if ($sobrecubierta != "false" && $sobrecubierta != null) {
|
|
$sobrecubierta = [
|
|
'papel' => $modelPapelGenerico->where('id', $sobrecubierta['papel'])->first()->toArray(),
|
|
'gramaje' => intval($sobrecubierta['gramaje']),
|
|
'solapas' => intval($sobrecubierta['solapas'] ?? 0),
|
|
'acabado' => $sobrecubierta['acabado'] ?? 0,
|
|
];
|
|
} else
|
|
$sobrecubierta = false;
|
|
|
|
// Guardas
|
|
if ($guardas != "false" && $guardas != null) {
|
|
$datos_guardas = [
|
|
'papel' => $modelPapelGenerico->where('id', $guardas['papel'])->first()->toArray(),
|
|
'gramaje' => intval($guardas['gramaje']),
|
|
'caras' => intval($guardas['caras']),
|
|
];
|
|
} else
|
|
$datos_guardas = false;
|
|
|
|
$datos_presupuesto = array(
|
|
'tirada' => $tirada,
|
|
'tamanio' => $tamanio,
|
|
'tipo_impresion_id' => $tipo_impresion_id,
|
|
'clienteId' => $cliente_id,
|
|
'isColor' => $isColor,
|
|
'isHq' => $isHq,
|
|
'paginasCuadernillo' => $paginasCuadernillo,
|
|
|
|
'interior' => $interior,
|
|
'cubierta' => $cubierta,
|
|
'sobrecubierta' => $sobrecubierta,
|
|
'datos_guardas' => $datos_guardas,
|
|
'faja' => $faja,
|
|
|
|
'servicios' => $reqData['servicios'] ?? [],
|
|
);
|
|
|
|
$datos_presupuesto['id'] = $id;
|
|
|
|
$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)) {
|
|
if ($this->request) {
|
|
return $this->respond([
|
|
'error' => $error,
|
|
]);
|
|
} else {
|
|
return $error;
|
|
}
|
|
}
|
|
}
|
|
} else if (isset($resultado_presupuesto['exception'])) {
|
|
if ($this->request) {
|
|
return $this->respond([
|
|
'error' => $resultado_presupuesto['exception'],
|
|
'file' => $resultado_presupuesto['file'],
|
|
'line' => $resultado_presupuesto['line'],
|
|
]);
|
|
} else {
|
|
return $resultado_presupuesto['exception'];
|
|
}
|
|
}
|
|
|
|
|
|
// seleccionamos el peso de la tirada seleccionada
|
|
$peso_libro = $resultado_presupuesto['peso'][array_search($selected_tirada, $tirada)];
|
|
|
|
// calculo del envio base (tirada_maxima)
|
|
$noEnvioBase = model('App\Models\Clientes\ClienteModel')->find($cliente_id)->no_envio_base ?? false;
|
|
$resultado_presupuesto['eb'] = [];
|
|
$datos_presupuesto['envio_base'] = 0;
|
|
for ($i = 0; $i < count($tirada); $i++) {
|
|
$direccion = [];
|
|
$coste_direccion = $this->getCosteEnvio(
|
|
$direccion,
|
|
$resultado_presupuesto['peso'][$i],
|
|
$tirada[$i],
|
|
false,
|
|
true
|
|
);
|
|
|
|
if (intval($selected_tirada) == intval($tirada[$i])) {
|
|
if ($noEnvioBase) {
|
|
$coste_direccion->coste = 0.0;
|
|
$coste_direccion->margen = 0.0;
|
|
}
|
|
$datos_presupuesto['envio_base'] = round($coste_direccion->coste * (1 + $coste_direccion->margen / 100.0), 2);
|
|
}
|
|
|
|
if (!property_exists($coste_direccion, 'coste')) {
|
|
$errorModel = new ErrorPresupuesto();
|
|
$data['direccion'] = 'Sin direccion';
|
|
$data['peso'] = $resultado_presupuesto['peso'][$i];
|
|
$data['palets'] = 'Sin direccion';
|
|
$errorModel->insertError(
|
|
$id,
|
|
auth()->user()->id,
|
|
'No se ha podido calcular el coste de envío',
|
|
$data
|
|
);
|
|
$resultado_presupuesto = [
|
|
'errors' => (object) ([
|
|
'status' => 1
|
|
]),
|
|
];
|
|
return $resultado_presupuesto;
|
|
} else {
|
|
if ($noEnvioBase) {
|
|
$coste_direccion->coste = 0.0;
|
|
$coste_direccion->margen = 0.0;
|
|
}
|
|
$resultado_presupuesto['eb'][$i] = round($coste_direccion->coste, 2);
|
|
$resultado_presupuesto['eb_margen'][$i] = round($coste_direccion->margen, 2);
|
|
}
|
|
}
|
|
|
|
|
|
for ($i = 0; $i < count($tirada); $i++) {
|
|
|
|
$resultado_presupuesto['info']['totales'][$i]['coste_envio'] = 0.0;
|
|
$resultado_presupuesto['info']['totales'][$i]['margen_envio'] = 0.0;
|
|
}
|
|
|
|
// para el calculo del precio unidad, sólo se tiene en cuenta el envío base
|
|
for ($i = 0; $i < count($tirada); $i++) {
|
|
|
|
$resultado_presupuesto['info']['totales'][$i]['envio_base_margen'] =
|
|
floatval($resultado_presupuesto['eb'][$i]) * (floatval($resultado_presupuesto['eb_margen'][$i]) / 100.0);
|
|
$resultado_presupuesto['info']['totales'][$i]['envio_base_coste'] = $resultado_presupuesto['eb'][$i];
|
|
|
|
$coste_envio = round(round($resultado_presupuesto['info']['totales'][$i]['envio_base_margen'] +
|
|
$resultado_presupuesto['info']['totales'][$i]['envio_base_coste'], 2) / 50, 4);
|
|
|
|
$resultado_presupuesto['precio_u'][$i] = round(floatval($resultado_presupuesto['precio_u'][$i]) + $coste_envio, 4);
|
|
}
|
|
|
|
$coste_envio = 0.0; // se inicializa para calcular los costes de envíos restantes si es que hay
|
|
$resultado_presupuesto['coste_envio'] = [];
|
|
if (count($direcciones) > 0) {
|
|
|
|
for ($i = 0; $i < count($tirada); $i++) {
|
|
|
|
$envio_base = true;
|
|
$coste_envio = 0.0;
|
|
$margen_envio = 0.0;
|
|
foreach ($direcciones as $direccion) {
|
|
// El primer envio no se calcula ya que se añade el base
|
|
if ($envio_base) {
|
|
$envio_base = false;
|
|
continue;
|
|
}
|
|
|
|
$unidades = floor($direccion['unidades'] * $tirada[$i] / $selected_tirada);
|
|
$coste_direccion = $this->getCosteEnvio(
|
|
$direccion['direccion'],
|
|
$resultado_presupuesto['peso'][$i],
|
|
$unidades,
|
|
$direccion['entregaPalets'] == 'true' ? 1 : 0,
|
|
false,
|
|
);
|
|
|
|
if (!property_exists($coste_direccion, 'coste')) {
|
|
|
|
$errorModel = new ErrorPresupuesto();
|
|
$data['direccion'] = $direccion;
|
|
$data['peso'] = $resultado_presupuesto['peso'][$i];
|
|
$data['palets'] = $direccion['entregaPalets'] == 'true' ? 1 : 0;
|
|
$errorModel->insertError(
|
|
$id,
|
|
auth()->user()->id,
|
|
'No se ha podido calcular el coste de envío',
|
|
$data
|
|
);
|
|
$resultado_presupuesto = [
|
|
'errors' => (object) ([
|
|
'status' => 1
|
|
]),
|
|
];
|
|
return $resultado_presupuesto;
|
|
} else {
|
|
//aporte del envio al precio unidad
|
|
$coste_envio += ($coste_direccion->coste / $tirada[$i]);
|
|
$resultado_presupuesto['info']['totales'][$i]['coste_envio'] += $coste_direccion->coste - $coste_direccion->margen;
|
|
$resultado_presupuesto['info']['totales'][$i]['margen_envio'] += $coste_direccion->margen;
|
|
|
|
}
|
|
}
|
|
$resultado_presupuesto['coste_envio'][$i] = round($coste_envio, 2);
|
|
}
|
|
}
|
|
|
|
$model_presupuesto = new PresupuestoModel();
|
|
$tiradas_alternativas = [];
|
|
$resumen_totales = [];
|
|
|
|
for ($i = 0; $i < count($tirada); $i++) {
|
|
|
|
if ($tirada[$i] != $selected_tirada) {
|
|
|
|
$coste_total = $resultado_presupuesto['info']['totales'][$i]['totalImpresion'] + $resultado_presupuesto['info']['totales'][$i]['totalPapel'] +
|
|
$resultado_presupuesto['info']['totales'][$i]['margenImpresion'] + $resultado_presupuesto['info']['totales'][$i]['margenPapel'];
|
|
$coste_envio = $resultado_presupuesto['info']['totales'][$i]['coste_envio'] + $resultado_presupuesto['info']['totales'][$i]['margen_envio'];
|
|
$margen_total = round(($resultado_presupuesto['info']['totales'][$i]['margenImpresion'] +
|
|
$resultado_presupuesto['info']['totales'][$i]['margenPapel'] +
|
|
$resultado_presupuesto['info']['totales'][$i]['margen_envio']) / ($coste_total + $coste_envio) * 100.0, 2);
|
|
$total_pedido = round(($coste_total + $resultado_presupuesto['info']['totales'][$i]['totalServicios'] + $resultado_presupuesto['info']['totales'][$i]['margenServicios'] + $coste_envio), 2);
|
|
$precio_u = round($resultado_presupuesto['precio_u'][$i], 4);
|
|
|
|
array_push($tiradas_alternativas, (object) array(
|
|
'tirada' => $tirada[$i],
|
|
'coste_impresion' => round($coste_total, 2),
|
|
'coste_envio' => $coste_envio,
|
|
'margen' => $margen_total,
|
|
'total_pedido' => $total_pedido,
|
|
'precio_unidad' => $precio_u,
|
|
));
|
|
} else {
|
|
$resumen_totales = $resultado_presupuesto['info']['totales'][$i];
|
|
$resumen_totales['precio_unidad'] = round($resultado_presupuesto['precio_u'][$i], 4);
|
|
|
|
}
|
|
}
|
|
|
|
$borrar_antes = false;
|
|
if ($id != 0) {
|
|
$borrar_antes = true;
|
|
}
|
|
|
|
$servicio_ferro = (object) [
|
|
'nombre' => 'ferro',
|
|
'id' => model('App\Models\Configuracion\ConfigVariableModel')->getVariable('id_servicio_ferro')->value
|
|
];
|
|
|
|
$servicio_ferro_digital = (object) [
|
|
'nombre' => 'ferro_digital',
|
|
'id' => model('App\Models\Configuracion\ConfigVariableModel')->getVariable('id_servicio_ferro_digital')->value
|
|
];
|
|
$servicio_prototipo = (object) [
|
|
'nombre' => 'prototipo',
|
|
'id' => model('App\Models\Configuracion\ConfigVariableModel')->getVariable('id_servicio_prototipo')->value
|
|
];
|
|
|
|
|
|
if (isset($resultado_presupuesto['values']['servicios_extra'])) {
|
|
foreach ($resultado_presupuesto['values']['servicios_extra'] as $servicio) {
|
|
if ($servicio->tarifa_id == $servicio_ferro->id) {
|
|
$ferro = 1;
|
|
} else if ($servicio->tarifa_id == $servicio_ferro_digital->id) {
|
|
$ferroDigital = 1;
|
|
} else if ($servicio->tarifa_id == $servicio_prototipo->id) {
|
|
$prototipo = 1;
|
|
}
|
|
}
|
|
}
|
|
|
|
|
|
$datos_presupuesto['prototipo'] = $prototipo;
|
|
$datos_presupuesto['ferro'] = $ferro;
|
|
$datos_presupuesto['ferro_digital'] = $ferroDigital;
|
|
$datos_presupuesto['marcapaginas'] = $marcapaginas;
|
|
$datos_presupuesto['retractilado'] = $retractilado;
|
|
$datos_presupuesto['retractilado5'] = $retractilado5;
|
|
$datos_presupuesto['entrega_taller'] = $reqData['entrega_taller'] ?? 0;
|
|
|
|
|
|
$resultado_presupuesto['info']['merma'] = isset($resultado_presupuesto['info']['num_formas']) ?
|
|
PresupuestoService::calcular_merma($selected_tirada, $POD, $resultado_presupuesto['info']['num_formas']) : PresupuestoService::calcular_merma($selected_tirada, $POD);
|
|
|
|
$datos_presupuesto['faja'] = $faja;
|
|
|
|
$reqData['datosCabecera'] ?? [];
|
|
$datos_presupuesto['direcciones_fp_checks'] = $reqData['direcciones_fp_checks'] ?? (object) [
|
|
'addFP1isAddMain' => "false",
|
|
'addFP2isAddMain' => "false",
|
|
'addFP2isaddFP1' => "false"
|
|
];
|
|
|
|
$id = $model_presupuesto->insertarPresupuestoCliente(
|
|
$id,
|
|
$selected_tirada,
|
|
$datos_presupuesto,
|
|
$datosCabecera,
|
|
$resultado_presupuesto['info'],
|
|
$resumen_totales,
|
|
$ivaReducido,
|
|
$excluirRotativa,
|
|
$tiradas_alternativas
|
|
);
|
|
|
|
// Lineas Presupuesto
|
|
if ($borrar_antes && $id > 0) {
|
|
$this->borrarRelacionesPresupuesto($id);
|
|
}
|
|
|
|
foreach ($resultado_presupuesto['values']['interior'] as $linea) {
|
|
|
|
if (count($linea) > 0)
|
|
$this->guardarLineaPresupuesto($id, $linea);
|
|
}
|
|
if (count($resultado_presupuesto['values']['cubierta']) > 0)
|
|
$this->guardarLineaPresupuesto($id, $resultado_presupuesto['values']['cubierta']);
|
|
if (count($resultado_presupuesto['values']['sobrecubierta']) > 0)
|
|
$this->guardarLineaPresupuesto($id, $resultado_presupuesto['values']['sobrecubierta']);
|
|
if (count($resultado_presupuesto['values']['faja']) > 0)
|
|
$this->guardarLineaPresupuesto($id, $resultado_presupuesto['values']['faja']);
|
|
if (count($resultado_presupuesto['values']['guardas']) > 0)
|
|
$this->guardarLineaPresupuesto($id, $resultado_presupuesto['values']['guardas']);
|
|
|
|
// Servicios
|
|
if ($sobrecubierta) {
|
|
if (intval($sobrecubierta['acabado']) > 0) {
|
|
|
|
$modelServicioAcabado = model('App\Models\Tarifas\Acabados\TarifasAcabadoServiciosAcabadoModel');
|
|
$serviciosAcabado = $modelServicioAcabado->getTarifasForServicio($sobrecubierta['acabado']);
|
|
|
|
foreach ($serviciosAcabado as $service) {
|
|
$model = model('App\Models\Presupuestos\PresupuestoAcabadosModel');
|
|
$servicio = $model->getPrecioTarifa(
|
|
intval($service),
|
|
intval($selected_tirada) + $resultado_presupuesto['info']['merma'],
|
|
-1,
|
|
$POD
|
|
);
|
|
|
|
if (count($servicio) > 0) {
|
|
if ($servicio[0]->total > 0) {
|
|
$this->guardarServicio($id, $servicio[0], 'acabado', false, true);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if (intval($cubierta['acabado']) > 0) {
|
|
|
|
$modelServicioAcabado = model('App\Models\Tarifas\Acabados\TarifasAcabadoServiciosAcabadoModel');
|
|
$serviciosAcabado = $modelServicioAcabado->getTarifasForServicio($cubierta['acabado']);
|
|
|
|
foreach ($serviciosAcabado as $service) {
|
|
$model = model('App\Models\Presupuestos\PresupuestoAcabadosModel');
|
|
$servicio = $model->getPrecioTarifa(
|
|
intval($service),
|
|
intval($selected_tirada) + $resultado_presupuesto['info']['merma'],
|
|
-1,
|
|
$POD
|
|
);
|
|
|
|
if (count($servicio) > 0) {
|
|
if ($servicio[0]->total > 0) {
|
|
$this->guardarServicio($id, $servicio[0], 'acabado', true, false);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if (is_array($faja) && $faja !== [] && intval($faja['acabado']) > 0) {
|
|
|
|
$modelServicioAcabado = model('App\Models\Tarifas\Acabados\TarifasAcabadoServiciosAcabadoModel');
|
|
$serviciosAcabado = $modelServicioAcabado->getTarifasForServicio($faja['acabado']);
|
|
|
|
foreach ($serviciosAcabado as $service) {
|
|
$model = model('App\Models\Presupuestos\PresupuestoAcabadosModel');
|
|
$servicio = $model->getPrecioTarifa(
|
|
intval($service),
|
|
intval($selected_tirada) + $resultado_presupuesto['info']['merma'],
|
|
-1,
|
|
$POD
|
|
);
|
|
|
|
if (count($servicio) > 0) {
|
|
if ($servicio[0]->total > 0) {
|
|
$this->guardarServicio($id, $servicio[0], 'acabado', false, false, true);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if (intval($cubierta['lomoRedondo']) == 1) {
|
|
$tarifa_id = model('App\Models\Configuracion\ConfigVariableModel')->getVariable('id_servicio_lomo_redondo')->value;
|
|
$serv_lomo = PresupuestoCLienteService::getServiciosManipulado([
|
|
'tarifa_id' => intval($tarifa_id),
|
|
'tirada' => $selected_tirada + $resultado_presupuesto['info']['merma'],
|
|
'POD' => $POD,
|
|
])[0];
|
|
|
|
$this->guardarServicio($id, $serv_lomo, 'manipulado');
|
|
}
|
|
foreach ($resultado_presupuesto['values']['serviciosDefecto']['encuadernacion'] as $servicio) {
|
|
$this->guardarServicio($id, $servicio, 'encuadernacion');
|
|
}
|
|
foreach ($resultado_presupuesto['values']['serviciosDefecto']['manipulado'] as $servicio) {
|
|
$this->guardarServicio($id, $servicio, 'manipulado');
|
|
}
|
|
|
|
$servicio_retractilado = (object) [
|
|
'nombre' => 'retractilado',
|
|
'id' => model('App\Models\Configuracion\ConfigVariableModel')->getVariable('id_servicio_retractilado')->value
|
|
];
|
|
$servicio_retractilado5 = (object) [
|
|
'nombre' => 'retractilado5',
|
|
'id' => model('App\Models\Configuracion\ConfigVariableModel')->getVariable('id_servicio_retractilado5')->value
|
|
];
|
|
$servicio_solapas_cubierta = (object) [
|
|
'nombre' => 'solapas_cubierta',
|
|
'id' => model('App\Models\Configuracion\ConfigVariableModel')->getVariable('servicio_solapas_cubierta')->value
|
|
];
|
|
$servicio_solapas_sobrecubierta = (object) [
|
|
'nombre' => 'solapas_sobrecubierta',
|
|
'id' => model('App\Models\Configuracion\ConfigVariableModel')->getVariable('servicio_solapas_sobrecubierta')->value
|
|
];
|
|
$servicio_solapas_faja = (object) [
|
|
'nombre' => 'solapas_faja',
|
|
'id' => model('App\Models\Configuracion\ConfigVariableModel')->getVariable('servicio_solapas_faja')->value
|
|
];
|
|
$servicio_solapas_grandes_cubierta = (object) [
|
|
'nombre' => 'solapas_grandes_cubierta',
|
|
'id' => model('App\Models\Configuracion\ConfigVariableModel')->getVariable('id_servicio_plegado_exceso_solapas_cubierta')->value
|
|
];
|
|
$servicio_solapas_grandes_sobrecubierta = (object) [
|
|
'nombre' => 'solapas_grandes_sobrecubierta',
|
|
'id' => model('App\Models\Configuracion\ConfigVariableModel')->getVariable('id_servicio_plegado_exceso_solapas_sobrecubierta')->value
|
|
];
|
|
$servicio_solapas_grandes_faja = (object) [
|
|
'nombre' => 'solapas_grandes_faja',
|
|
'id' => model('App\Models\Configuracion\ConfigVariableModel')->getVariable('id_servicio_plegado_exceso_solapas_faja')->value
|
|
];
|
|
|
|
// Funcionalidad servicios extra
|
|
foreach ($resultado_presupuesto['values']['servicios_extra'] as $servicio) {
|
|
$this->guardarServicio($id, $servicio, 'extra');
|
|
}
|
|
|
|
foreach ($resultado_presupuesto['values']['servicios_automaticos'] as $servicio) {
|
|
if ($servicio->tarifa_id == $servicio_retractilado->id || $servicio->tarifa_id == $servicio_retractilado5->id) {
|
|
// Servicios acabado
|
|
$this->guardarServicio($id, $servicio, 'acabado');
|
|
} else if ($servicio->tarifa_id == $servicio_ferro->id || $servicio->tarifa_id == $servicio_prototipo->id) {
|
|
// Servicios extra
|
|
$this->guardarServicio($id, $servicio, 'extra');
|
|
} else if (
|
|
$servicio->tarifa_id == $servicio_solapas_cubierta->id ||
|
|
$servicio->tarifa_id == $servicio_solapas_sobrecubierta->id ||
|
|
$servicio->tarifa_id == $servicio_solapas_faja->id ||
|
|
$servicio->tarifa_id == $servicio_solapas_grandes_cubierta->id ||
|
|
$servicio->tarifa_id == $servicio_solapas_grandes_sobrecubierta->id ||
|
|
$servicio->tarifa_id == $servicio_solapas_grandes_faja->id
|
|
) {
|
|
// Servicios manipulado
|
|
$this->guardarServicio($id, $servicio, 'manipulado');
|
|
}
|
|
}
|
|
|
|
if (array_key_exists('direcciones', $reqData)) {
|
|
|
|
foreach ($reqData['direcciones'] as $direccion) {
|
|
$this->guardarLineaEnvio($id, $direccion, $peso_libro);
|
|
}
|
|
}
|
|
|
|
if (count($direccionesFP1) > 0) {
|
|
$this->guardarLineaEnvio($id, $direccionesFP1, $peso_libro, true, true, 1);
|
|
|
|
}
|
|
if (count($direccionesFP2) > 0) {
|
|
$this->guardarLineaEnvio($id, $direccionesFP2, $peso_libro, true, true, 2);
|
|
}
|
|
|
|
if ($confirmar) {
|
|
$model_presupuesto->confirmarPresupuesto($id);
|
|
PresupuestoService::crearPedido($id);
|
|
}
|
|
|
|
if ($this->request) {
|
|
|
|
return $this->respond([
|
|
'status' => $id,
|
|
'url' => site_url('presupuestos/presupuestocliente/edit'),
|
|
'message' => lang('Basic.global.saveSuccess', [lang('Basic.global.record')]),
|
|
]);
|
|
} else {
|
|
return [
|
|
'sk_id' => $id,
|
|
'sk_url' => site_url('presupuestos/presupuestocliente/edit/' . $id)
|
|
];
|
|
}
|
|
}
|
|
|
|
|
|
public function cargar($id)
|
|
{
|
|
if ($this->request->isAJAX()) {
|
|
|
|
$modelPapelFormato = new PapelFormatoModel();
|
|
$modelCliente = new ClienteModel();
|
|
|
|
$presupuesto = $this->model->find($id);
|
|
$data = [];
|
|
if ($presupuesto) {
|
|
$data['lc'] = $presupuesto->lomo_cubierta;
|
|
$data['lsc'] = $presupuesto->lomo_sobrecubierta;
|
|
$data['eb'] = $presupuesto->envio_base;
|
|
$data['state'] = intval($presupuesto->estado_id);
|
|
if ($presupuesto->estado_id == 2) { // confirmado
|
|
$data['datosGenerales']['selectedTirada'] = $presupuesto->tirada;
|
|
}
|
|
$data['datosGenerales']['titulo'] = $presupuesto->titulo;
|
|
$data['datosGenerales']['autor'] = $presupuesto->autor;
|
|
$data['datosGenerales']['isbn'] = $presupuesto->isbn;
|
|
$data['datosGenerales']['coleccion'] = $presupuesto->coleccion;
|
|
$data['datosGenerales']['referenciaCliente'] = $presupuesto->referencia_cliente;
|
|
$data['datosGenerales']['paginas'] = $presupuesto->paginas;
|
|
$data['datosGenerales']['paginasCuadernillo'] = $presupuesto->paginasCuadernillo;
|
|
$data['datosGenerales']['tirada'] = $presupuesto->tirada;
|
|
$data['datosGenerales']['selectedTirada'] = $presupuesto->tirada;
|
|
$data['datosGenerales']['ivaReducido'] = $presupuesto->iva_reducido;
|
|
$data['datosGenerales']['excluirRotativa'] = $presupuesto->excluir_rotativa;
|
|
$data['datosGenerales']['clienteId'] = $presupuesto->cliente_id;
|
|
$data['datosGenerales']['clienteNombre'] = $modelCliente->getNombre($presupuesto->cliente_id);
|
|
model('App\Models\Clientes\ClienteModel')
|
|
->find($presupuesto->cliente_id)->nombre;
|
|
$data['datosGenerales']['papelFormatoId'] = $presupuesto->papel_formato_id;
|
|
$data['datosGenerales']['papelFormatoNombre'] = $modelPapelFormato->getNombre($presupuesto->papel_formato_id);
|
|
$data['datosGenerales']['papelFormatoPersonalizado'] = $presupuesto->papel_formato_personalizado;
|
|
$data['datosGenerales']['papelFormatoAncho'] = $presupuesto->papel_formato_ancho;
|
|
$data['datosGenerales']['papelFormatoAlto'] = $presupuesto->papel_formato_alto;
|
|
|
|
$data['datosGenerales']['posPaginasColor'] = $presupuesto->comp_pos_paginas_color;
|
|
$data['datosGenerales']['papelInteriorDiferente'] = $presupuesto->papel_interior_diferente;
|
|
$data['datosGenerales']['paginasColorConsecutivas'] = $presupuesto->paginas_color_consecutivas;
|
|
|
|
$data['datosGenerales']['tipo'] = $this->getTipoLibro($presupuesto->tipo_impresion_id ?? null);
|
|
$data['datosGenerales']['prototipo'] = $presupuesto->prototipo;
|
|
$data['datosGenerales']['ferro'] = $presupuesto->ferro;
|
|
$data['datosGenerales']['ferroDigital'] = $presupuesto->ferro_digital;
|
|
$data['datosGenerales']['marcapaginas'] = $presupuesto->marcapaginas;
|
|
$data['datosGenerales']['retractilado'] = $presupuesto->retractilado;
|
|
$data['datosGenerales']['retractilado5'] = $presupuesto->retractilado5;
|
|
|
|
$modelServiciosExtra = new PresupuestoServiciosExtraModel();
|
|
$data['datosGenerales']['serviciosExtra'] = $modelServiciosExtra
|
|
->where('presupuesto_id', $id)->findColumn('tarifa_extra_id');
|
|
|
|
$datos_papel = $this->obtenerDatosPapel($presupuesto->id);
|
|
if (array_key_exists('interior', $datos_papel)) {
|
|
$data['interior'] = $datos_papel['interior'];
|
|
} else {
|
|
$data['interior'] = [];
|
|
}
|
|
|
|
if (array_key_exists('cubierta', $datos_papel)) {
|
|
$data['cubierta'] = $datos_papel['cubierta'];
|
|
} else {
|
|
$data['cubierta'] = [];
|
|
}
|
|
$data['cubierta']['tapa'] = $this->obtenerTipoTapa($presupuesto->tipo_impresion_id ?? null);
|
|
$data['cubierta']['lomoRedondo'] = $presupuesto->lomo_redondo ? 1 : 0;
|
|
$data['cubierta']['solapas'] = $presupuesto->solapas ? 1 : 0;
|
|
$data['cubierta']['solapas_ancho'] = $presupuesto->solapas_ancho;
|
|
$data['cubierta']['cabezada'] = $presupuesto->cabezada;
|
|
$modelAcabado = model("App\Models\Tarifas\Acabados\ServicioAcabadoModel");
|
|
$data['cubierta']['acabado']['id'] = $presupuesto->acabado_cubierta_id;
|
|
if ($presupuesto->acabado_cubierta_id == 0) {
|
|
$data['cubierta']['acabado']['text'] = "Ninguno";
|
|
} else {
|
|
$data['cubierta']['acabado']['text'] = $modelAcabado->find($presupuesto->acabado_cubierta_id)->nombre;
|
|
}
|
|
$data['cubierta']['retractilado'] = $presupuesto->retractilado ? 1 : 0;
|
|
|
|
$data['sobrecubierta'] = array_key_exists('sobrecubierta', $datos_papel) ? $datos_papel['sobrecubierta'] : [];
|
|
$data['sobrecubierta']['solapas'] = $presupuesto->solapas_sobrecubierta ? 1 : 0;
|
|
$data['sobrecubierta']['solapas_ancho'] = $presupuesto->solapas_ancho_sobrecubierta;
|
|
$data['sobrecubierta']['acabado']['id'] = $presupuesto->acabado_sobrecubierta_id;
|
|
if ($presupuesto->acabado_sobrecubierta_id == 0) {
|
|
$data['sobrecubierta']['acabado']['text'] = "Ninguno";
|
|
} else {
|
|
$data['sobrecubierta']['acabado']['text'] = $modelAcabado->find($presupuesto->acabado_sobrecubierta_id)->nombre;
|
|
}
|
|
|
|
if (array_key_exists('faja', $datos_papel)) {
|
|
$data['faja']['papel'] = $datos_papel['faja'];
|
|
$data['faja']['alto'] = $presupuesto->alto_faja_color;
|
|
$data['faja']['solapas'] = 1;
|
|
$data['faja']['solapas_ancho'] = $presupuesto->solapas_ancho_faja_color;
|
|
$data['faja']['acabado']['id'] = $presupuesto->acabado_sobrecubierta_id;
|
|
if ($presupuesto->acabado_faja_id == 0) {
|
|
$data['faja']['acabado']['text'] = "Ninguno";
|
|
} else {
|
|
$data['faja']['acabado']['text'] = $modelAcabado->find($presupuesto->acabado_faja_id)->nombre;
|
|
}
|
|
} else {
|
|
$data['faja'] = [];
|
|
}
|
|
|
|
$data['guardas'] = array_key_exists('guardas', $datos_papel) ? $datos_papel['guardas'] : [];
|
|
|
|
$modelLinea = new PresupuestoLineaModel();
|
|
$lineas = $modelLinea->where('presupuesto_id', $id)->findAll();
|
|
|
|
[$data['datosGenerales']['paginasNegro'], $data['datosGenerales']['paginasColor']] =
|
|
$this->getPaginas($lineas);
|
|
|
|
if (intval($presupuesto->recoger_en_taller) == 1) {
|
|
$data['direcciones']['entrega_taller'] = 1;
|
|
} else {
|
|
$data['direcciones'] = $this->obtenerDireccionesEnvio($id);
|
|
}
|
|
|
|
$direccionesFerroPrototipo = $this->obtenerDireccionesEnvioFerro($id);
|
|
if ($direccionesFerroPrototipo && count($direccionesFerroPrototipo) > 0) {
|
|
$data['direccionesFerroPrototipo'] = $direccionesFerroPrototipo;
|
|
}
|
|
|
|
$data['direccionesFPChecks'] = $presupuesto->getDireccionFPChecks();
|
|
|
|
if (intval($presupuesto->estado_id) == 2) {
|
|
$data['resumen']['base'] = $presupuesto->total_antes_descuento;
|
|
$data['resumen']['total_envio'] = round(
|
|
floatval($presupuesto->total_coste_envios) +
|
|
floatval($presupuesto->total_margen_envios),
|
|
2
|
|
);
|
|
$data['resumen']['precio_unidad'] = $presupuesto->total_precio_unidad;
|
|
}
|
|
|
|
$tiradas_alternativas = json_decode($presupuesto->tirada_alternativa_json_data);
|
|
if (!is_null($tiradas_alternativas)) {
|
|
for ($i = 0; $i < count($tiradas_alternativas); $i++) {
|
|
$tirada = $tiradas_alternativas[$i];
|
|
$data['datosGenerales']['tirada' . ($i + 2)] = $tirada->tirada;
|
|
}
|
|
}
|
|
|
|
return $this->respond([
|
|
'status' => 1,
|
|
'data' => $data
|
|
]);
|
|
}
|
|
} else {
|
|
return $this->failUnauthorized('Invalid request', 403);
|
|
}
|
|
}
|
|
|
|
public function get_files()
|
|
{
|
|
|
|
// Check if the request is a POST request
|
|
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
|
|
|
|
$presupuesto_id = $this->request->getPost()['presupuesto_id'] ?? 0;
|
|
|
|
$model = model('App\Models\Presupuestos\PresupuestoFicheroModel');
|
|
$files = $model->getFiles($presupuesto_id);
|
|
|
|
$result = [];
|
|
|
|
foreach ($files as $file) {
|
|
|
|
$size = filesize($file->file_path);
|
|
$splitPath = explode("presupuestos/", $file->file_path);
|
|
|
|
// se crea un objeto con el nombre del fichero y el tamaño
|
|
$obj = (object) array(
|
|
'name' => $file->nombre,
|
|
'size' => $size,
|
|
'hash' => $splitPath[1] ?? $file->file_path
|
|
);
|
|
|
|
|
|
// se añade el objeto al array
|
|
array_push($result, $obj);
|
|
}
|
|
|
|
return json_encode($result);
|
|
}
|
|
}
|
|
|
|
public function upload_files()
|
|
{
|
|
|
|
$model = model('App\Models\Presupuestos\PresupuestoFicheroModel');
|
|
|
|
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
|
|
|
|
$presupuesto_id = $_POST['presupuesto_id'];
|
|
$old_files = json_decode($_POST['oldFiles']);
|
|
$ftp = new SafekatFtpClient();
|
|
|
|
// Comprobar si se han subido archivos
|
|
if (!empty($_FILES['file']) || !empty($old_files)) {
|
|
|
|
|
|
// Borrar los archivos existentes del presupuesto
|
|
$ftp->removeFiles($presupuesto_id);
|
|
$model->deleteFiles($presupuesto_id, $old_files);
|
|
|
|
if (!empty($_FILES['file'])) {
|
|
$files = $_FILES['file'];
|
|
|
|
// Iterar sobre los archivos
|
|
for ($i = 0; $i < count($files['name']); $i++) {
|
|
// Aquí puedes acceder a las propiedades del archivo
|
|
$name = $files['name'][$i];
|
|
$extension = explode('.', $files['name'][$i])[1];
|
|
$tmp_name = $files['tmp_name'][$i];
|
|
|
|
$new_name = $model->saveFileInBBDD($presupuesto_id, $name, $extension, auth()->id());
|
|
|
|
// Se sube el fichero
|
|
// Pero primero se comprueba que la carpeta presupuestos exista
|
|
if (!is_dir(WRITEPATH . 'uploads/presupuestos')) {
|
|
mkdir(WRITEPATH . 'uploads/presupuestos', 0777, true);
|
|
}
|
|
|
|
if (!is_null($new_name)) {
|
|
$path = WRITEPATH . 'uploads/presupuestos/' . $new_name;
|
|
move_uploaded_file($tmp_name, $path);
|
|
}
|
|
}
|
|
$ftp->uploadFilePresupuesto($presupuesto_id);
|
|
}
|
|
} else {
|
|
// Borrar los archivos existentes del presupuesto
|
|
$ftp->removeFiles($presupuesto_id);
|
|
$model->deleteFiles($presupuesto_id);
|
|
}
|
|
}
|
|
return json_encode(['message' => 'Archivos subidos correctamente']);
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/***********************
|
|
*
|
|
* Funciones auxiliares
|
|
*
|
|
**********************/
|
|
protected function borrarRelacionesPresupuesto($id)
|
|
{
|
|
// 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();
|
|
}
|
|
|
|
protected function guardarLineaPresupuesto($presupuestoId, $linea)
|
|
{
|
|
|
|
$model = new PresupuestoLineaModel();
|
|
$model->insertLPFromBackend($presupuestoId, $linea);
|
|
}
|
|
|
|
|
|
protected function guardarLineaEnvio($presupuestoId, $direccion, $peso_libro, $coste_cero = false, $is_ferro_prototipo = false, $num_ferro_prototipo = 0)
|
|
{
|
|
|
|
$unidades = intval($direccion['unidades']);
|
|
$peso_envio = $peso_libro * $unidades / 1000.0;
|
|
|
|
|
|
$data = $this->getCosteEnvio(
|
|
$direccion['direccion'],
|
|
$peso_libro,
|
|
$direccion['unidades'],
|
|
($direccion['entregaPalets'] == 'false' || $direccion['entregaPalets'] == 0) ? 0 : 1,
|
|
false
|
|
);
|
|
|
|
if (isset($data->coste)) {
|
|
|
|
$data->presupuesto_id = $presupuestoId;
|
|
$data->tarifa_id = $data->id;
|
|
unset($data->id);
|
|
if ($coste_cero) {
|
|
$data->coste = 0;
|
|
if ($is_ferro_prototipo) {
|
|
$data->is_ferro_prototipo = 1;
|
|
$data->num_ferro_prototipo = $num_ferro_prototipo;
|
|
}
|
|
} else {
|
|
$data->precio = $data->coste;
|
|
}
|
|
unset($data->coste);
|
|
$data->entregaPieCalle = ($direccion['entregaPalets'] == 'false' || $direccion['entregaPalets'] == 0) ? 0 : 1;
|
|
unset($data->tipo);
|
|
$data->peso = $peso_envio;
|
|
$data->cantidad = $unidades;
|
|
|
|
$model = new PresupuestoDireccionesModel();
|
|
$model->insert($data);
|
|
}
|
|
}
|
|
|
|
|
|
protected function guardarServicio($presupuestoId, $servicio, $tipo, $cubierta = false, $sobrecubierta = false, $faja = false)
|
|
{
|
|
|
|
if ($tipo == 'encuadernacion') {
|
|
$model = new PresupuestoEncuadernacionesModel();
|
|
|
|
$data = [
|
|
'presupuesto_id' => $presupuestoId,
|
|
'tarifa_encuadernado_id' => $servicio->tarifa_id,
|
|
'proveedor_id' => $servicio->proveedor_id,
|
|
'tiempo' => $servicio->tiempo,
|
|
'precio_total' => round($servicio->total, 2),
|
|
'precio_unidad' => round($servicio->precio_unidad, 2),
|
|
'margen' => $servicio->margen,
|
|
];
|
|
|
|
// Se comprueba que $servicio tiene paginasCuadernillo
|
|
if (isset($servicio->paginas_por_cuadernillo)) {
|
|
$data['paginas_por_cuadernillo'] = $servicio->paginas_por_cuadernillo;
|
|
}
|
|
|
|
$model->insert($data);
|
|
} else if ($tipo == 'extra') {
|
|
$model = new PresupuestoServiciosExtraModel();
|
|
|
|
$data = [
|
|
'presupuesto_id' => $presupuestoId,
|
|
'tarifa_extra_id' => intval($servicio->tarifa_id),
|
|
'precio' => round($servicio->precio, 2),
|
|
'margen' => floatval($servicio->margen),
|
|
];
|
|
$errors = null;
|
|
|
|
if (!$model->insert($data)) {
|
|
$errors = $model->errors();
|
|
}
|
|
} else if ($tipo == 'acabado') {
|
|
$model = new PresupuestoAcabadosModel();
|
|
|
|
$data = [
|
|
'presupuesto_id' => $presupuestoId,
|
|
'tarifa_acabado_id' => $servicio->tarifa_id,
|
|
'precio_total' => round($servicio->total, 2),
|
|
'precio_unidad' => round($servicio->precio_unidad, 2),
|
|
'margen' => $servicio->margen,
|
|
'proveedor_id' => $servicio->proveedor_id,
|
|
'cubierta' => $cubierta,
|
|
'sobrecubierta' => $sobrecubierta,
|
|
'faja' => $faja,
|
|
];
|
|
$model->insert($data);
|
|
} else if ($tipo == 'manipulado') {
|
|
$model = new PresupuestoManipuladosModel();
|
|
|
|
$data = [
|
|
'presupuesto_id' => $presupuestoId,
|
|
'tarifa_manipulado_id' => $servicio->tarifa_id,
|
|
'precio_total' => round($servicio->total, 2),
|
|
'precio_unidad' => round($servicio->precio_unidad, 2),
|
|
'margen' => $servicio->margen,
|
|
];
|
|
$model->insert($data);
|
|
}
|
|
}
|
|
|
|
|
|
protected function getCosteEnvio($direccion, $peso, $unidades, $entregaPieCalle, $calcular_envio_base)
|
|
{
|
|
$return_data = $direccion;
|
|
|
|
if ($calcular_envio_base) {
|
|
|
|
$pais_id = 1; // españa
|
|
$cp = 18000; // envio nacional
|
|
} else {
|
|
$pais_id = $direccion['pais_id'];
|
|
$cp = $direccion['cp'];
|
|
}
|
|
|
|
|
|
$modelTarifaEnvio = model('App\Models\Tarifas\TarifaEnvioModel');
|
|
$coste = 0;
|
|
$margen = 0;
|
|
|
|
|
|
$peso_envio = round(floatval(ceil(floatval($peso)) * floatval($unidades) / 1000.0), 3); // peso libro * unidades y se pasa a kilogramos
|
|
$tarifas_envio = $modelTarifaEnvio->getTarifaEnvio($pais_id, $cp, $peso_envio, $entregaPieCalle ? 'palets' : 'cajas');
|
|
for ($i = 0; $i < count($tarifas_envio); $i++) {
|
|
if ($peso_envio > $tarifas_envio[$i]->peso_max || floatval($tarifas_envio[$i]->precio_max) == 0) {
|
|
$tarifas_envio[$i]->precio = number_format(floatval($tarifas_envio[$i]->precio_max) + ($peso_envio - floatval($tarifas_envio[$i]->peso_max)) * floatval($tarifas_envio[$i]->precio_adicional), 2);
|
|
}
|
|
// si no se calcula linealmente
|
|
else {
|
|
$m = (($tarifas_envio[$i]->precio_max - $tarifas_envio[$i]->precio_min) / ($tarifas_envio[$i]->peso_max - $tarifas_envio[$i]->peso_min));
|
|
$b = $tarifas_envio[$i]->precio_max - $m * $tarifas_envio[$i]->peso_max;
|
|
$tarifas_envio[$i]->precio = number_format($m * $peso_envio + $b, 2);
|
|
}
|
|
$margen = $tarifas_envio[$i]->margen;
|
|
}
|
|
|
|
$tarifa_envio_final = null;
|
|
if (count($tarifas_envio) > 1) {
|
|
$tarifa_envio_final = array_reduce($tarifas_envio, function ($previous, $current) {
|
|
return $current->precio < $previous->precio ? $current : $previous;
|
|
});
|
|
} else {
|
|
if (count($tarifas_envio) > 0) {
|
|
$tarifa_envio_final = $tarifas_envio[0];
|
|
}
|
|
}
|
|
$coste = $tarifa_envio_final->precio;
|
|
$margen = $tarifa_envio_final->margen;
|
|
|
|
if (!isset($return_data['id'])) {
|
|
$return_data['id'] = $tarifa_envio_final->id;
|
|
}
|
|
|
|
$return_data['coste'] = $coste;
|
|
$return_data['tipo'] = $entregaPieCalle ? 'palets' : 'cajas';
|
|
$return_data['margen'] = $margen;
|
|
$return_data['proveedor'] = $tarifas_envio[0]->proveedor;
|
|
$return_data['proveedor_id'] = $tarifas_envio[0]->proveedor_id;
|
|
|
|
return (object) $return_data;
|
|
}
|
|
|
|
protected function calcular_presupuesto($datos_entrada, $selected_tirada, $extra_info = false)
|
|
{
|
|
try {
|
|
$return_data = [];
|
|
|
|
$info = [
|
|
'merma' => 0,
|
|
'lomo_interior' => 0.0,
|
|
'lomo_cubierta' => 0.0,
|
|
'lomo_sobrecubierta' => 0.0,
|
|
'user_id' => auth()->user()->id,
|
|
];
|
|
|
|
$tirada = $datos_entrada['tirada'];
|
|
$tamanio = $datos_entrada['tamanio'];
|
|
$tipo_impresion_id = $datos_entrada['tipo_impresion_id'];
|
|
$cliente_id = $datos_entrada['clienteId'] ?? -1;
|
|
$isColor = $datos_entrada['isColor'];
|
|
$isHq = $datos_entrada['isHq'];
|
|
$paginasCuadernillo = $datos_entrada['paginasCuadernillo'] ?? null;
|
|
|
|
|
|
// Interior
|
|
$papelInteriorDiferente = $datos_entrada['interior']['papelInteriorDiferente'] ?? false;
|
|
$papel_generico = $datos_entrada['interior']['papel_generico'];
|
|
$gramaje = $datos_entrada['interior']['gramaje'];
|
|
$excluirRotativa = $datos_entrada['interior']['excluirRotativa'];
|
|
$paginas = $datos_entrada['interior']['paginas'];
|
|
$paginas_color = $datos_entrada['interior']['paginas_color'];
|
|
|
|
|
|
// Cubierta
|
|
$papel_generico_cubierta = $datos_entrada['cubierta']['papel_generico_cubierta'];
|
|
$gramajeCubierta = $datos_entrada['cubierta']['gramajeCubierta'];
|
|
$carasCubierta = $datos_entrada['cubierta']['carasCubierta'];
|
|
$solapasCubierta = $datos_entrada['cubierta']['solapasCubierta'];
|
|
$lomoRedondo = $datos_entrada['cubierta']['lomoRedondo'];
|
|
|
|
// Sobrecubierta
|
|
$sobreCubierta = $datos_entrada["sobrecubierta"] ?? null;
|
|
|
|
// Faja
|
|
$faja = $datos_entrada["faja"] ?? null;
|
|
|
|
// Guardas
|
|
$datos_guardas = $datos_entrada['datos_guardas'] ?? [];
|
|
|
|
// Servicios
|
|
$servicios = $datos_entrada['servicios'] ?? [];
|
|
|
|
$coste_servicios = 0.0;
|
|
|
|
$POD = model('App\Models\Configuracion\ConfigVariableModel')->getVariable('POD')->value;
|
|
|
|
$precio_u = [];
|
|
$peso = [];
|
|
if ($extra_info)
|
|
$totales = [];
|
|
$lomo = 0.0;
|
|
|
|
for ($t = 0; $t < count($tirada); $t++) {
|
|
|
|
// Inicialización para los totalizadores
|
|
$totalPapel = 0.0;
|
|
$margenPapel = 0.0;
|
|
$totalImpresion = 0.0;
|
|
$margenImpresion = 0.0;
|
|
|
|
$sumForFactor = 0.0;
|
|
$sumForFactorPonderado = 0.0;
|
|
|
|
$totalServicios = 0.0;
|
|
$margenServicios = 0.0;
|
|
|
|
$tirada[$t] = intval($tirada[$t]);
|
|
|
|
$is_cosido = (new TipoPresupuestoModel())->get_isCosido($tipo_impresion_id);
|
|
|
|
$datosPedido = (object) array(
|
|
'paginas' => $paginas,
|
|
'tirada' => $tirada[$t],
|
|
'merma' => PresupuestoService::calcular_merma($tirada[$t], $POD),
|
|
'ancho' => intval($tamanio['ancho']) ?? 100000,
|
|
'alto' => intval($tamanio['alto']) ?? 100000,
|
|
'isCosido' => $is_cosido,
|
|
'a_favor_fibra' => 1,
|
|
);
|
|
if ($extra_info) {
|
|
$info['merma'] = $datosPedido->merma;
|
|
}
|
|
|
|
$cliente_model = model(('App\Models\Clientes\ClienteModel'));
|
|
$cliente = $cliente_model->find($cliente_id);
|
|
|
|
$forzarRotativa = false;
|
|
if ($tirada[$t] <= $POD && $cliente->forzar_rotativa_pod) {
|
|
$forzarRotativa = true;
|
|
} else if ($tirada[0] <= $POD && !$cliente->forzar_rotativa_pod) {
|
|
$excluirRotativa = true;
|
|
}
|
|
|
|
$input_data = array(
|
|
'uso' => 'interior',
|
|
'tipo_impresion_id' => $tipo_impresion_id,
|
|
'datosPedido' => $datosPedido,
|
|
'papel_generico' => $papel_generico,
|
|
'gramaje' => $gramaje,
|
|
'isColor' => $isColor,
|
|
'isHq' => $isHq,
|
|
'cliente_id' => $cliente_id,
|
|
'paginas_color' => $paginas_color,
|
|
'excluirRotativa' => $excluirRotativa,
|
|
'papelInteriorDiferente' => $papelInteriorDiferente,
|
|
'forzarRotativa' => $forzarRotativa,
|
|
);
|
|
|
|
$interior = PresupuestoClienteService::obtenerInterior($input_data);
|
|
|
|
if ($interior == -1) {
|
|
$errorModel = new ErrorPresupuesto();
|
|
$errorModel->insertError(
|
|
$datos_entrada['id'] == 0 ? null : $datos_entrada['id'],
|
|
auth()->user()->id,
|
|
'
|
|
No se puede obtener el interior',
|
|
$input_data
|
|
);
|
|
$return_data = [
|
|
'errors' => (object) ([
|
|
'status' => 1
|
|
]),
|
|
];
|
|
return $return_data;
|
|
}
|
|
|
|
$costeInterior = 0.0;
|
|
$peso_interior = 0.0;
|
|
foreach ($interior as $linea) {
|
|
if (count($linea) > 0) {
|
|
$costeInterior += round(floatval($linea['total_impresion']), 2);
|
|
$peso_interior += round(floatval($linea['peso']), 2);
|
|
if (intval($tirada[$t]) == intval($selected_tirada)) {
|
|
$lomo += floatval($linea['mano']);
|
|
$info['lomo_interior'] += floatval($linea['mano']);
|
|
}
|
|
if ($extra_info) {
|
|
$this->calcular_coste_linea(
|
|
$linea,
|
|
$totalPapel,
|
|
$margenPapel,
|
|
$sumForFactor,
|
|
$totalImpresion,
|
|
$margenImpresion
|
|
);
|
|
}
|
|
}
|
|
}
|
|
|
|
// Si es POD hay que volver a calcular para incluir la merma correcta
|
|
if ($tirada[$t] <= $POD) {
|
|
$num_formas = [];
|
|
foreach ($interior as $linea) {
|
|
if (count($linea) > 0) {
|
|
$formas_linea = $is_cosido ? intval($linea['num_formas']['value']) / 2 : intval($linea['num_formas']['value']);
|
|
array_push($num_formas, $formas_linea);
|
|
}
|
|
}
|
|
$input_data['datosPedido']->merma = PresupuestoService::calcular_merma($tirada[$t], $POD, $num_formas);
|
|
if ($extra_info) {
|
|
$info['merma'] = max($info['merma'], $input_data['datosPedido']->merma);
|
|
$info['num_formas'] = $num_formas;
|
|
}
|
|
$interior = PresupuestoClienteService::obtenerInterior($input_data);
|
|
if ($interior == -1) {
|
|
|
|
$errorModel = new ErrorPresupuesto();
|
|
$errorModel->insertError(
|
|
$datos_entrada['id'],
|
|
auth()->user()->id,
|
|
'No se puede obtener el interior',
|
|
$input_data
|
|
);
|
|
$return_data = [
|
|
'errors' => (object) ([
|
|
'status' => 1
|
|
]),
|
|
];
|
|
return $return_data;
|
|
}
|
|
|
|
$costeInterior = 0.0;
|
|
$peso_interior = 0.0;
|
|
$lomo = 0;
|
|
if ($extra_info) {
|
|
$totalPapel = 0.0;
|
|
$margenPapel = 0.0;
|
|
$sumForFactor = 0.0;
|
|
$totalImpresion = 0.0;
|
|
$margenImpresion = 0.0;
|
|
}
|
|
foreach ($interior as $linea) {
|
|
if (count($linea) > 0) {
|
|
$costeInterior += round(floatval($linea['total_impresion']), 2);
|
|
if (intval($tirada[$t]) == intval($selected_tirada)) {
|
|
$info['lomo_interior'] += floatval($linea['mano']);
|
|
$lomo += floatval($linea['mano']);
|
|
}
|
|
$peso_interior += floatval($linea['peso']);
|
|
if ($extra_info) {
|
|
|
|
$this->calcular_coste_linea(
|
|
$linea,
|
|
$totalPapel,
|
|
$margenPapel,
|
|
$sumForFactor,
|
|
$totalImpresion,
|
|
$margenImpresion
|
|
);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
if ($costeInterior <= 0) {
|
|
|
|
$errorModel = new ErrorPresupuesto();
|
|
$errorModel->insertError(
|
|
$datos_entrada['id'],
|
|
auth()->user()->id,
|
|
'No se puede obtener el interior',
|
|
$input_data
|
|
);
|
|
$return_data = [
|
|
'errors' => (object) ([
|
|
'status' => 1
|
|
]),
|
|
];
|
|
return $return_data;
|
|
}
|
|
|
|
// Cubierta
|
|
$input_data['papel_generico'] = $papel_generico_cubierta;
|
|
$input_data['gramaje'] = $gramajeCubierta;
|
|
$input_data['datosPedido']->paginas = $carasCubierta;
|
|
$input_data['paginas_color'] = $carasCubierta;
|
|
$input_data['datosPedido']->solapas_ancho = $solapasCubierta;
|
|
$input_data['datosPedido']->solapas = $input_data['datosPedido']->solapas_ancho > 0 ? 1 : 0;
|
|
$input_data['datosPedido']->lomo = $this->calcular_lomo($interior, 0);
|
|
$input_data['isColor'] = 1;
|
|
$input_data['isHq'] = 1;
|
|
$input_data['uso'] = 'cubierta';
|
|
$input_data['lomoRedondo'] = $lomoRedondo;
|
|
|
|
$cubierta = PresupuestoClienteService::obtenerCubierta($input_data);
|
|
$coste_cubierta = 0.0;
|
|
$peso_cubierta = 0.0;
|
|
if (count($cubierta) > 0) {
|
|
$coste_cubierta += round(floatval($cubierta['total_impresion']), 2);
|
|
$peso_cubierta += round(floatval($cubierta['peso']), 2);
|
|
if (intval($tirada[$t]) == intval($selected_tirada)) {
|
|
$lomo += floatval($cubierta['mano']);
|
|
}
|
|
|
|
if ($extra_info) {
|
|
|
|
$this->calcular_coste_linea(
|
|
$cubierta,
|
|
$totalPapel,
|
|
$margenPapel,
|
|
$sumForFactor,
|
|
$totalImpresion,
|
|
$margenImpresion
|
|
);
|
|
}
|
|
}
|
|
if ($coste_cubierta <= 0) {
|
|
|
|
$errorModel = new ErrorPresupuesto();
|
|
$errorModel->insertError(
|
|
$datos_entrada['id'],
|
|
auth()->user()->id,
|
|
'No se puede obtener la cubierta',
|
|
$input_data
|
|
);
|
|
$return_data = [
|
|
'errors' => (object) ([
|
|
'status' => 1
|
|
]),
|
|
];
|
|
return $return_data;
|
|
}
|
|
|
|
$cantidad_total = intval($datosPedido->tirada);// + intval($datosPedido->merma);
|
|
|
|
// Acabado Cubierta
|
|
if (intval($datos_entrada['cubierta']['acabado']) != 0) {
|
|
|
|
$modelServicioAcabado = model('App\Models\Tarifas\Acabados\TarifasAcabadoServiciosAcabadoModel');
|
|
$serviciosAcabado = $modelServicioAcabado->getTarifasForServicio(intval($datos_entrada['cubierta']['acabado']));
|
|
|
|
foreach ($serviciosAcabado as $servicio) {
|
|
$model = model('App\Models\Presupuestos\PresupuestoAcabadosModel');
|
|
|
|
$acabadoCubierta = $model->getPrecioTarifa(intval($servicio), $cantidad_total, -1, $POD);
|
|
|
|
if (count($acabadoCubierta) > 0) {
|
|
if ($acabadoCubierta[0]->total <= 0) {
|
|
|
|
$input_data['tarifas_acabado_cubierta'] = intval($servicio);
|
|
$errorModel = new ErrorPresupuesto();
|
|
$errorModel->insertError(
|
|
$datos_entrada['id'],
|
|
auth()->user()->id,
|
|
'No se puede obtener acabados de cubierta',
|
|
$input_data
|
|
);
|
|
$return_data = [
|
|
'errors' => (object) ([
|
|
'status' => 1
|
|
]),
|
|
];
|
|
return $return_data;
|
|
}
|
|
$coste_servicios += round(floatval($acabadoCubierta[0]->total), 2);
|
|
if ($extra_info) {
|
|
//$totalServicios += round(floatval($acabadoCubierta[0]->total), 2);
|
|
$base = round(floatval($acabadoCubierta[0]->total / (1 + $acabadoCubierta[0]->margen / 100.0)), 2);
|
|
$base = round(floatval($base / $cantidad_total), 2) * $cantidad_total;
|
|
$totalServicios += $base;
|
|
$margenServicios += round(floatval($acabadoCubierta[0]->total - $base), 2);
|
|
}
|
|
}
|
|
}
|
|
|
|
}
|
|
|
|
if ($lomoRedondo) {
|
|
|
|
$tarifa = model('App\Models\Configuracion\ConfigVariableModel')->getVariable('id_servicio_lomo_redondo')->value;
|
|
$resultado = PresupuestoCLienteService::getServiciosManipulado([
|
|
'tarifa_id' => intval($tarifa),
|
|
'tirada' => $cantidad_total,
|
|
'POD' => $POD,
|
|
]);
|
|
|
|
if (count($resultado) > 0) {
|
|
if ($resultado[0]->total <= 0) {
|
|
|
|
$input_data['tarifa_manipulado'] = intval($tarifa);
|
|
$errorModel = new ErrorPresupuesto();
|
|
$errorModel->insertError(
|
|
$datos_entrada['id'],
|
|
auth()->user()->id,
|
|
'No se puede obtener servicio lomo redondo',
|
|
$input_data
|
|
);
|
|
$return_data = [
|
|
'errors' => (object) ([
|
|
'status' => 1
|
|
]),
|
|
];
|
|
return $return_data;
|
|
}
|
|
$coste_servicios += round(floatval($resultado[0]->total), 2);
|
|
if ($extra_info) {
|
|
//$totalServicios += round(floatval($resultado[0]->total), 2);
|
|
$base = round(floatval($resultado[0]->total / (1 + $resultado[0]->margen / 100.0)), 2);
|
|
$base = round(floatval($base / $cantidad_total), 2) * $cantidad_total;
|
|
$totalServicios += $base;
|
|
$margenServicios += round(floatval($resultado[0]->total - $base), 2);
|
|
}
|
|
|
|
}
|
|
}
|
|
|
|
|
|
// Sobrecubierta
|
|
$coste_sobrecubierta = 0.0;
|
|
$peso_sobrecubierta = 0.0;
|
|
$linea_sobrecubierta = [];
|
|
$acabadoSobrecubierta = [];
|
|
$lomo_sobrecubierta = 0.0;
|
|
if (!is_null($sobreCubierta) && $sobreCubierta) {
|
|
|
|
$input_data['papel_generico'] = $sobreCubierta['papel'] ?? 0;
|
|
$input_data['gramaje'] = $sobreCubierta['gramaje'] ?? 0;
|
|
$input_data['datosPedido']->paginas = 4;
|
|
$input_data['paginas_color'] = 4;
|
|
$input_data['datosPedido']->solapas_ancho = intval($sobreCubierta['solapas'] ?? 0);
|
|
$input_data['datosPedido']->solapas = $sobreCubierta['solapas'] > 0 ? 1 : 0;
|
|
$input_data['datosPedido']->lomo = $this->calcular_lomo([$cubierta], $input_data['datosPedido']->lomo);
|
|
$input_data['isColor'] = 1;
|
|
$input_data['isHq'] = 1;
|
|
$input_data['uso'] = 'sobrecubierta';
|
|
|
|
$linea_sobrecubierta = PresupuestoClienteService::obtenerSobrecubierta($input_data);
|
|
|
|
if (count($linea_sobrecubierta) > 0) {
|
|
$coste_sobrecubierta += round(floatval($linea_sobrecubierta['total_impresion']), 2);
|
|
$peso_sobrecubierta += round(floatval($linea_sobrecubierta['peso']), 2);
|
|
if ($extra_info) {
|
|
|
|
$this->calcular_coste_linea(
|
|
$linea_sobrecubierta,
|
|
$totalPapel,
|
|
$margenPapel,
|
|
$sumForFactor,
|
|
$totalImpresion,
|
|
$margenImpresion
|
|
);
|
|
}
|
|
}
|
|
if ($coste_sobrecubierta <= 0) {
|
|
|
|
$errorModel = new ErrorPresupuesto();
|
|
$errorModel->insertError(
|
|
$datos_entrada['id'],
|
|
auth()->user()->id,
|
|
'No se puede obtener la sobrecubierta',
|
|
$input_data
|
|
);
|
|
$return_data = [
|
|
'errors' => (object) ([
|
|
'status' => 1
|
|
]),
|
|
];
|
|
return $return_data;
|
|
}
|
|
$lomo_sobrecubierta = $lomo + floatval($linea_sobrecubierta['mano']);
|
|
|
|
// Acabado sobrecubierta
|
|
if (intval($datos_entrada['sobrecubierta']['acabado']) != 0) {
|
|
|
|
$modelServicioAcabado = model('App\Models\Tarifas\Acabados\TarifasAcabadoServiciosAcabadoModel');
|
|
$serviciosAcabado = $modelServicioAcabado->getTarifasForServicio(intval($datos_entrada['sobrecubierta']['acabado']));
|
|
|
|
foreach ($serviciosAcabado as $servicio) {
|
|
$model = model('App\Models\Presupuestos\PresupuestoAcabadosModel');
|
|
$acabadoSobrecubierta = $model->getPrecioTarifa(intval($servicio), $cantidad_total, -1, $POD);
|
|
|
|
if (count($acabadoSobrecubierta) > 0) {
|
|
|
|
if ($acabadoSobrecubierta[0]->total <= 0) {
|
|
|
|
$input_data['tarifas_acabado_sobrecubierta'] = intval($servicio);
|
|
$errorModel = new ErrorPresupuesto();
|
|
$errorModel->insertError(
|
|
$datos_entrada['id'],
|
|
auth()->user()->id,
|
|
'No se puede obtener acabados de sobrecubierta',
|
|
$input_data
|
|
);
|
|
$return_data = [
|
|
'errors' => (object) ([
|
|
'status' => 1
|
|
]),
|
|
];
|
|
return $return_data;
|
|
}
|
|
|
|
$coste_servicios += round(floatval($acabadoSobrecubierta[0]->total), 2);
|
|
if ($extra_info) {
|
|
//$totalServicios += round(floatval($acabadoSobrecubierta[0]->total), 2);
|
|
$base = round(floatval($acabadoSobrecubierta[0]->total / (1 + $acabadoSobrecubierta[0]->margen / 100.0)), 2);
|
|
$base = round(floatval($base / $cantidad_total), 2) * $cantidad_total;
|
|
$totalServicios += $base;
|
|
$margenServicios += round(floatval($acabadoSobrecubierta[0]->total - $base), 2);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
//Guardas
|
|
$guardas = [];
|
|
$peso_guardas = 0.0;
|
|
$coste_guardas = 0.0;
|
|
if ($datos_guardas != 0) {
|
|
if (count($datos_guardas) != 0 && $datos_guardas) {
|
|
|
|
$guardas = $datos_guardas;
|
|
$input_data['papel_generico'] = $datos_guardas['papel'] ?? 0;
|
|
$input_data['gramaje'] = $datos_guardas['gramaje'] ?? 0;
|
|
$input_data['datosPedido']->paginas = 8;
|
|
$input_data['paginas_color'] = 8;
|
|
$input_data['datosPedido']->paginas_impresion = $datos_guardas['caras'] ?? 0;
|
|
$input_data['datosPedido']->solapas_ancho = 0;
|
|
$input_data['datosPedido']->solapas = 0;
|
|
$input_data['isColor'] = $isColor;
|
|
$input_data['isHq'] = 1;
|
|
$input_data['uso'] = 'guardas';
|
|
|
|
// 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) {
|
|
$input_data['datosPedido']->isCosido = true;
|
|
} else if ($tipo_impresion_id == 5 || $tipo_impresion_id == 7) {
|
|
$input_data['datosPedido']->isCosido = false;
|
|
}
|
|
|
|
$guardas = PresupuestoClienteService::obtenerGuardas($input_data);
|
|
|
|
if (count($guardas) > 0) {
|
|
$coste_guardas += round(floatval($guardas['total_impresion']), 2);
|
|
$peso_guardas += round(floatval($guardas['peso']), 2);
|
|
if (intval($tirada[$t]) == intval($selected_tirada)) {
|
|
$lomo += floatval($guardas['mano']);
|
|
}
|
|
if ($extra_info) {
|
|
|
|
$this->calcular_coste_linea(
|
|
$guardas,
|
|
$totalPapel,
|
|
$margenPapel,
|
|
$sumForFactor,
|
|
$totalImpresion,
|
|
$margenImpresion
|
|
);
|
|
}
|
|
}
|
|
if ($coste_guardas <= 0) {
|
|
$errorModel = new ErrorPresupuesto();
|
|
$errorModel->insertError(
|
|
$datos_entrada['id'],
|
|
auth()->user()->id,
|
|
'No se puede obtener las guardas',
|
|
$input_data
|
|
);
|
|
$return_data = [
|
|
'errors' => (object) ([
|
|
'status' => 1
|
|
]),
|
|
];
|
|
return $return_data;
|
|
}
|
|
}
|
|
}
|
|
|
|
$coste_faja = 0.0;
|
|
$peso_faja = 0.0;
|
|
$linea_faja = [];
|
|
$acabadoFaja = [];
|
|
if (!is_null($faja) && $faja && $faja != false) {
|
|
|
|
$input_data['papel_generico']['id'] = $faja['papel'] ?? 0;
|
|
$input_data['gramaje'] = $faja['gramaje'] ?? 0;
|
|
$input_data['datosPedido']->paginas = 4;
|
|
$input_data['datosPedido']->alto = floatval($faja['alto'] ?? 0);
|
|
$input_data['paginas_color'] = 4;
|
|
$input_data['datosPedido']->solapas_ancho = intval($faja['solapas'] ?? 0);
|
|
$input_data['datosPedido']->solapas = 1;
|
|
$input_data['datosPedido']->lomo = $this->calcular_lomo([$cubierta], $input_data['datosPedido']->lomo);
|
|
$input_data['isColor'] = 1;
|
|
$input_data['isHq'] = 1;
|
|
$input_data['uso'] = 'faja';
|
|
|
|
$linea_faja = PresupuestoClienteService::obtenerSobrecubierta($input_data);
|
|
|
|
if (count($linea_faja) > 0) {
|
|
$linea_faja['tipo_linea'] = 'lp_faja';
|
|
$coste_faja += round(floatval($linea_faja['total_impresion']), 2);
|
|
$peso_faja += floatval($linea_faja['peso']);
|
|
if ($extra_info) {
|
|
|
|
$this->calcular_coste_linea(
|
|
$linea_faja,
|
|
$totalPapel,
|
|
$margenPapel,
|
|
$sumForFactor,
|
|
$totalImpresion,
|
|
$margenImpresion
|
|
);
|
|
}
|
|
}
|
|
if ($coste_faja <= 0) {
|
|
|
|
$errorModel = new ErrorPresupuesto();
|
|
$errorModel->insertError(
|
|
$datos_entrada['id'],
|
|
auth()->user()->id,
|
|
'No se puede obtener la faja',
|
|
$input_data
|
|
);
|
|
$return_data = [
|
|
'errors' => (object) ([
|
|
'status' => 1
|
|
]),
|
|
];
|
|
return $return_data;
|
|
}
|
|
|
|
// Acabado faja
|
|
if (intval($faja['acabado']) != 0) {
|
|
|
|
$modelServicioAcabado = model('App\Models\Tarifas\Acabados\TarifasAcabadoServiciosAcabadoModel');
|
|
$serviciosAcabado = $modelServicioAcabado->getTarifasForServicio(intval($faja['acabado']));
|
|
|
|
foreach ($serviciosAcabado as $servicio)
|
|
$model = model('App\Models\Presupuestos\PresupuestoAcabadosModel');
|
|
$acabadoFaja = $model->getPrecioTarifa(intval($servicio), $cantidad_total, -1, $POD);
|
|
|
|
if (count($acabadoFaja) > 0) {
|
|
|
|
if ($acabadoFaja[0]->total <= 0) {
|
|
|
|
$input_data['tarifas_acabado_faja'] = intval($servicio);
|
|
$errorModel = new ErrorPresupuesto();
|
|
$errorModel->insertError(
|
|
$datos_entrada['id'],
|
|
auth()->user()->id,
|
|
'No se puede obtener acabados de faja',
|
|
$input_data
|
|
);
|
|
$return_data = [
|
|
'errors' => (object) ([
|
|
'status' => 1
|
|
]),
|
|
];
|
|
return $return_data;
|
|
}
|
|
|
|
$coste_servicios += round(floatval($acabadoFaja[0]->total), 2);
|
|
if ($extra_info) {
|
|
//$totalServicios += round(floatval($acabadoFaja[0]->total), 2);
|
|
$base = round(floatval($acabadoFaja[0]->total / (1 + $acabadoFaja[0]->margen / 100.0)), 2);
|
|
$base = round(floatval($base / $cantidad_total), 2) * $cantidad_total;
|
|
$totalServicios += $base;
|
|
$margenServicios += round(floatval($acabadoFaja[0]->total - $base), 2);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
|
|
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;
|
|
}
|
|
|
|
// Servicios defecto
|
|
$costeServiciosDefecto = 0.0;
|
|
$servDefectoEnc = PresupuestoCLienteService::getServiciosEncuadernacionDefault([
|
|
'tipo_impresion_id' => $tipo_impresion_id,
|
|
'tirada' => $cantidad_total,
|
|
'paginas' => intval($paginas) ?? 0,
|
|
'ancho' => $datosPedido->ancho,
|
|
'alto' => $datosPedido->alto,
|
|
'POD' => $POD,
|
|
'solapas' => intval($solapasCubierta) > 0 ? 1 : 0,
|
|
'paginasCuadernillo' => $paginasCuadernillo,
|
|
]);
|
|
|
|
|
|
foreach ($servDefectoEnc as $servicio) {
|
|
if ($servicio->total <= 0) {
|
|
|
|
$input_data['servicios'] = $servDefectoEnc;
|
|
$errorModel = new ErrorPresupuesto();
|
|
$errorModel->insertError(
|
|
$datos_entrada['id'],
|
|
auth()->user()->id,
|
|
'No se puede obtener servicios',
|
|
$input_data
|
|
);
|
|
$return_data = [
|
|
'errors' => (object) ([
|
|
'status' => 1
|
|
]),
|
|
];
|
|
return $return_data;
|
|
}
|
|
|
|
|
|
$costeServiciosDefecto += round(floatval($servicio->total), 2);
|
|
if ($extra_info) {
|
|
//$totalServicios += round(floatval($servicio->total), 2);
|
|
$base = round(floatval($servicio->total / (1 + $servicio->margen / 100.0)), 2);
|
|
$base = round(floatval($base / $cantidad_total), 2) * $cantidad_total;
|
|
$totalServicios += $base;
|
|
$margenServicios += round(floatval($servicio->total - $base), 2);
|
|
}
|
|
}
|
|
|
|
$servDefectoMan = PresupuestoCLienteService::getServiciosManipuladoDefault([
|
|
'tipo_impresion_id' => $tipo_impresion_id,
|
|
'tirada' => $cantidad_total,
|
|
'POD' => $POD,
|
|
'solapas' => intval($solapasCubierta) > 0 ? 1 : 0,
|
|
]);
|
|
|
|
|
|
foreach ($servDefectoMan as $servicio) {
|
|
if ($servicio->total <= 0) {
|
|
|
|
$input_data['servicios'] = $servDefectoMan;
|
|
$errorModel = new ErrorPresupuesto();
|
|
$errorModel->insertError(
|
|
$datos_entrada['id'],
|
|
auth()->user()->id,
|
|
'No se puede obtener servicios',
|
|
$input_data
|
|
);
|
|
$return_data = [
|
|
'errors' => (object) ([
|
|
'status' => 1
|
|
]),
|
|
];
|
|
return $return_data;
|
|
}
|
|
|
|
|
|
$costeServiciosDefecto += round(floatval($servicio->total), 2);
|
|
if ($extra_info) {
|
|
//$totalServicios += round(floatval($servicio->total), 2);
|
|
$base = round(floatval($servicio->total / (1 + $servicio->margen / 100.0)), 2);
|
|
$base = round(floatval($base / $cantidad_total), 2) * $cantidad_total;
|
|
$totalServicios += $base;
|
|
$margenServicios += round(floatval($servicio->total - $base), 2);
|
|
}
|
|
}
|
|
|
|
if ($extra_info) {
|
|
$sumForFactorPonderado = $sumForFactor;
|
|
}
|
|
|
|
// Servicios
|
|
$serviciosAutomaticos = [];
|
|
$servicios = [];
|
|
|
|
$servicio_ferro = (object) [
|
|
'nombre' => 'ferro',
|
|
'id' => model('App\Models\Configuracion\ConfigVariableModel')->getVariable('id_servicio_ferro')->value
|
|
];
|
|
$servicio_prototipo = (object) [
|
|
'nombre' => 'prototipo',
|
|
'id' => model('App\Models\Configuracion\ConfigVariableModel')->getVariable('id_servicio_prototipo')->value
|
|
];
|
|
$servicio_retractilado = (object) [
|
|
'nombre' => 'retractilado',
|
|
'id' => model('App\Models\Configuracion\ConfigVariableModel')->getVariable('id_servicio_retractilado')->value
|
|
];
|
|
$servicio_retractilado5 = (object) [
|
|
'nombre' => 'retractilado5',
|
|
'id' => model('App\Models\Configuracion\ConfigVariableModel')->getVariable('id_servicio_retractilado5')->value
|
|
];
|
|
$servicio_solapas_cubierta = (object) [
|
|
'nombre' => 'solapas_cubierta',
|
|
'id' => model('App\Models\Configuracion\ConfigVariableModel')->getVariable('servicio_solapas_cubierta')->value
|
|
];
|
|
$servicio_solapas_sobrecubierta = (object) [
|
|
'nombre' => 'solapas_sobrecubierta',
|
|
'id' => model('App\Models\Configuracion\ConfigVariableModel')->getVariable('servicio_solapas_sobrecubierta')->value
|
|
];
|
|
$servicio_solapas_faja = (object) [
|
|
'nombre' => 'solapas_faja',
|
|
'id' => model('App\Models\Configuracion\ConfigVariableModel')->getVariable('servicio_solapas_faja')->value
|
|
];
|
|
$servicio_solapas_grandes_cubierta = (object) [
|
|
'nombre' => 'solapas_grandes_cubierta',
|
|
'id' => model('App\Models\Configuracion\ConfigVariableModel')->getVariable('id_servicio_plegado_exceso_solapas_cubierta')->value
|
|
];
|
|
$servicio_solapas_grandes_sobrecubierta = (object) [
|
|
'nombre' => 'solapas_grandes_sobrecubierta',
|
|
'id' => model('App\Models\Configuracion\ConfigVariableModel')->getVariable('id_servicio_plegado_exceso_solapas_sobrecubierta')->value
|
|
];
|
|
$servicio_solapas_grandes_faja = (object) [
|
|
'nombre' => 'solapas_grandes_faja',
|
|
'id' => model('App\Models\Configuracion\ConfigVariableModel')->getVariable('id_servicio_plegado_exceso_solapas_faja')->value
|
|
];
|
|
|
|
if ($datos_entrada['servicios'] !== []) {
|
|
|
|
if (isset($datos_entrada['servicios']['retractilado']) && $datos_entrada['servicios']['retractilado']) // acabado
|
|
array_push($servicios, $servicio_retractilado);
|
|
if (isset($datos_entrada['servicios']['retractilado5']) && $datos_entrada['servicios']['retractilado5']) // acabado
|
|
array_push($servicios, $servicio_retractilado5);
|
|
if (isset($datos_entrada['servicios']['prototipo']) && $datos_entrada['servicios']['prototipo']) // extra
|
|
array_push($servicios, $servicio_prototipo);
|
|
if (isset($datos_entrada['servicios']['ferro']) && $datos_entrada['servicios']['ferro']) // extra
|
|
array_push($servicios, $servicio_ferro);
|
|
if ($solapasCubierta > 0)
|
|
array_push($servicios, $servicio_solapas_cubierta);
|
|
if (!is_null($sobreCubierta) && $sobreCubierta) // Si hay sobrecubierta, siempre con solapas
|
|
array_push($servicios, $servicio_solapas_sobrecubierta);
|
|
if (!is_null($faja) && $faja && $faja != false) // Si hay faja, siempre con solapas
|
|
array_push($servicios, $servicio_solapas_faja);
|
|
}
|
|
|
|
|
|
foreach ($servicios as $servicio) {
|
|
|
|
if ($servicio->nombre == "retractilado" || $servicio->nombre == "retractilado5") {
|
|
// Servicios acabado
|
|
$resultado = PresupuestoCLienteService::getServiciosAcabados([
|
|
'tarifa_id' => intval($servicio->id),
|
|
'tirada' => $cantidad_total,
|
|
'POD' => $POD,
|
|
]);
|
|
array_push($serviciosAutomaticos, $resultado[0]);
|
|
|
|
if ($resultado[0]->total <= 0) {
|
|
|
|
$errorModel = new ErrorPresupuesto();
|
|
$errorModel->insertError(
|
|
$datos_entrada['id'],
|
|
auth()->user()->id,
|
|
'No se puede obtener servicio con id ' . ((string) $servicio),
|
|
$input_data
|
|
);
|
|
$return_data = [
|
|
'errors' => (object) ([
|
|
'status' => 1
|
|
]),
|
|
];
|
|
return $return_data;
|
|
}
|
|
|
|
$coste_servicios += round(floatval($resultado[0]->total), 2);
|
|
if ($extra_info) {
|
|
//$totalServicios += round(floatval($resultado[0]->total), 2);
|
|
$base = round(floatval($resultado[0]->total / (1 + $resultado[0]->margen / 100.0)), 2);
|
|
$base = round(floatval($base / $cantidad_total), 2) * $cantidad_total;
|
|
$totalServicios += $base;
|
|
$margenServicios += round(floatval($resultado[0]->total - $base), 2);
|
|
}
|
|
} else if ($servicio->nombre == "ferro" || $servicio->nombre == "prototipo") {
|
|
// Extra
|
|
$resultado = PresupuestoCLienteService::getServiciosExtra([
|
|
'tarifa_id' => intval($servicio->id),
|
|
]);
|
|
|
|
if ($resultado[0]->precio <= 0) {
|
|
|
|
$errorModel = new ErrorPresupuesto();
|
|
$errorModel->insertError(
|
|
$datos_entrada['id'],
|
|
auth()->user()->id,
|
|
'No se puede obtener servicio con id ' . ((string) $servicio),
|
|
$input_data
|
|
);
|
|
$return_data = [
|
|
'errors' => (object) ([
|
|
'status' => 1
|
|
]),
|
|
];
|
|
return $return_data;
|
|
}
|
|
|
|
array_push($serviciosAutomaticos, $resultado[0]);
|
|
|
|
$coste_servicios += round(floatval($resultado[0]->precio), 2);
|
|
if ($extra_info) {
|
|
//$totalServicios += round(floatval($resultado[0]->precio), 2);
|
|
$base = round(floatval($resultado[0]->total / (1 + $resultado[0]->margen / 100.0)), 2);
|
|
$base = round(floatval($base / $cantidad_total), 2) * $cantidad_total;
|
|
$totalServicios += $base;
|
|
$margenServicios += round(floatval($resultado[0]->total - $base), 2);
|
|
}
|
|
} else if ($servicio->nombre == 'solapas_cubierta' || $servicio->nombre == 'solapas_sobrecubierta' || $servicio->nombre == 'solapas_faja') {
|
|
// Servicios manipulado
|
|
$resultado = PresupuestoCLienteService::getServiciosManipulado([
|
|
'tarifa_id' => intval($servicio->id),
|
|
'tirada' => $cantidad_total,
|
|
'POD' => $POD,
|
|
]);
|
|
|
|
if ($resultado[0]->total <= 0) {
|
|
|
|
$errorModel = new ErrorPresupuesto();
|
|
$errorModel->insertError(
|
|
$datos_entrada['id'],
|
|
auth()->user()->id,
|
|
'No se puede obtener servicio de manupulado con ' . ((string) $servicio->nombre),
|
|
$input_data
|
|
);
|
|
$return_data = [
|
|
'errors' => (object) ([
|
|
'status' => 1
|
|
]),
|
|
];
|
|
return $return_data;
|
|
} else {
|
|
array_push($serviciosAutomaticos, $resultado[0]);
|
|
}
|
|
|
|
$coste_servicios += round(floatval($resultado[0]->total), 2);
|
|
if ($extra_info) {
|
|
//$totalServicios += round(floatval($resultado[0]->total), 2);
|
|
$base = round(floatval($resultado[0]->total / (1 + $resultado[0]->margen / 100.0)), 2);
|
|
$base = round(floatval($base / $cantidad_total), 2) * $cantidad_total;
|
|
$totalServicios += $base;
|
|
$margenServicios += round(floatval($resultado[0]->total - $base), 2);
|
|
}
|
|
}
|
|
}
|
|
|
|
$serviciosExtra = [];
|
|
// funcionalidad para los servicios extra añadidos por el usuario
|
|
if (
|
|
$datos_entrada['servicios'] !== [] && isset($datos_entrada['servicios']['serviciosExtra']) &&
|
|
$datos_entrada['servicios']['serviciosExtra'] !== []
|
|
) {
|
|
|
|
foreach ($datos_entrada['servicios']['serviciosExtra'] as $servicio) {
|
|
$resultado = PresupuestoCLienteService::getServiciosExtra([
|
|
'tarifa_id' => intval($servicio),
|
|
]);
|
|
|
|
if ($resultado[0]->precio <= 0) {
|
|
|
|
$errorModel = new ErrorPresupuesto();
|
|
$errorModel->insertError(
|
|
$datos_entrada['id'],
|
|
auth()->user()->id,
|
|
'No se puede obtener servicio con id ' . ((string) $servicio),
|
|
$input_data
|
|
);
|
|
$return_data = [
|
|
'errors' => (object) ([
|
|
'status' => 1
|
|
]),
|
|
];
|
|
return $return_data;
|
|
}
|
|
|
|
array_push($serviciosExtra, $resultado[0]);
|
|
|
|
$coste_servicios += round(floatval($resultado[0]->precio), 2);
|
|
if ($extra_info) {
|
|
//$totalServicios += round(floatval($resultado[0]->precio), 2);
|
|
$base = round(floatval($resultado[0]->precio / (1 + $resultado[0]->margen / 100.0)), 2);
|
|
$base = round(floatval($base / $cantidad_total), 2) * $cantidad_total;
|
|
$totalServicios += $base;
|
|
$margenServicios += round(floatval($resultado[0]->precio - $base), 2);
|
|
}
|
|
}
|
|
|
|
}
|
|
|
|
// Plegado de solapas grandes
|
|
if (intval($solapasCubierta) > 0 && intval($cubierta['dimension_desarrollo']['ancho']) > 630) {
|
|
// Servicios manipulado
|
|
$resultado = PresupuestoCLienteService::getServiciosManipulado([
|
|
'tarifa_id' => intval($servicio_solapas_grandes_cubierta->id),
|
|
'tirada' => $cantidad_total,
|
|
'POD' => $POD,
|
|
]);
|
|
|
|
if ($resultado[0]->total <= 0) {
|
|
|
|
$errorModel = new ErrorPresupuesto();
|
|
$errorModel->insertError(
|
|
$datos_entrada['id'],
|
|
auth()->user()->id,
|
|
'No se puede obtener servicio de manupulado con ' . ((string) $servicio->nombre),
|
|
$input_data
|
|
);
|
|
$return_data = [
|
|
'errors' => (object) ([
|
|
'status' => 1
|
|
]),
|
|
];
|
|
return $return_data;
|
|
} else {
|
|
array_push($serviciosAutomaticos, $resultado[0]);
|
|
}
|
|
|
|
$coste_servicios += round(floatval($resultado[0]->total), 2);
|
|
if ($extra_info) {
|
|
//$totalServicios += round(floatval($resultado[0]->total), 2);
|
|
$base = round(floatval($resultado[0]->total / (1 + $resultado[0]->margen / 100.0)), 2);
|
|
$base = round(floatval($base / $cantidad_total), 2) * $cantidad_total;
|
|
$totalServicios += $base;
|
|
$margenServicios += round(floatval($resultado[0]->total - $base), 2);
|
|
}
|
|
}
|
|
|
|
if (is_array($sobreCubierta) && ($sobreCubierta['solapas'] > 0 && intval($linea_sobrecubierta['dimension_desarrollo']['ancho']) > 630)) {
|
|
|
|
// Servicios manipulado
|
|
$resultado = PresupuestoCLienteService::getServiciosManipulado([
|
|
'tarifa_id' => intval($servicio_solapas_grandes_sobrecubierta->id),
|
|
'tirada' => $cantidad_total,
|
|
'POD' => $POD,
|
|
]);
|
|
|
|
if ($resultado[0]->total <= 0) {
|
|
|
|
$errorModel = new ErrorPresupuesto();
|
|
$errorModel->insertError(
|
|
$datos_entrada['id'],
|
|
auth()->user()->id,
|
|
'No se puede obtener servicio de manupulado ' . ((string) $servicio->nombre),
|
|
$input_data
|
|
);
|
|
$return_data = [
|
|
'errors' => (object) ([
|
|
'status' => 1
|
|
]),
|
|
];
|
|
return $return_data;
|
|
} else {
|
|
array_push($serviciosAutomaticos, $resultado[0]);
|
|
}
|
|
|
|
$coste_servicios += round(floatval($resultado[0]->total), 2);
|
|
if ($extra_info) {
|
|
//$totalServicios += round(floatval($resultado[0]->total), 2);
|
|
$base = round(floatval($resultado[0]->total / (1 + $resultado[0]->margen / 100.0)), 2);
|
|
$base = round(floatval($base / $cantidad_total), 2) * $cantidad_total;
|
|
$totalServicios += $base;
|
|
$margenServicios += round(floatval($resultado[0]->total - $base), 2);
|
|
}
|
|
}
|
|
|
|
if (is_array($faja) && $faja !== [] && ($faja['solapas'] > 0 && intval($linea_faja['dimension_desarrollo']['ancho']) > 630)) {
|
|
|
|
// Servicios manipulado
|
|
$resultado = PresupuestoCLienteService::getServiciosManipulado([
|
|
'tarifa_id' => intval($servicio_solapas_grandes_faja->id),
|
|
'tirada' => $cantidad_total,
|
|
'POD' => $POD,
|
|
]);
|
|
|
|
if ($resultado[0]->total <= 0) {
|
|
|
|
$errorModel = new ErrorPresupuesto();
|
|
$errorModel->insertError(
|
|
$datos_entrada['id'],
|
|
auth()->user()->id,
|
|
'No se puede obtener servicio de manupulado ' . ((string) $servicio->nombre),
|
|
$input_data
|
|
);
|
|
$return_data = [
|
|
'errors' => (object) ([
|
|
'status' => 1
|
|
]),
|
|
];
|
|
return $return_data;
|
|
} else {
|
|
array_push($serviciosAutomaticos, $resultado[0]);
|
|
}
|
|
|
|
$coste_servicios += round(floatval($resultado[0]->total), 2);
|
|
if ($extra_info) {
|
|
//$totalServicios += round(floatval($resultado[0]->total), 2);
|
|
$base = round(floatval($resultado[0]->total / (1 + $resultado[0]->margen / 100.0)), 2);
|
|
$base = round(floatval($base / $cantidad_total), 2) * $cantidad_total;
|
|
$totalServicios += $base;
|
|
$margenServicios += round(floatval($resultado[0]->total - $base), 2);
|
|
}
|
|
}
|
|
|
|
/*$total_por_tirada = $costeInterior +
|
|
$coste_cubierta +
|
|
$coste_sobrecubierta +
|
|
$coste_guardas +
|
|
$coste_faja +
|
|
$costeServiciosDefecto + $coste_servicios;*/
|
|
$total_por_tirada = $totalPapel + $margenPapel +
|
|
$totalImpresion + $margenImpresion +
|
|
$totalServicios + $margenServicios;
|
|
array_push(
|
|
$precio_u,
|
|
round(($total_por_tirada) / $tirada[$t], 4)
|
|
);
|
|
array_push($peso, round($peso_interior + $peso_cubierta + $peso_sobrecubierta + $peso_guardas + $peso_faja, 2));
|
|
|
|
if ($extra_info) {
|
|
//$totalServicios -= $margenServicios;
|
|
if (($margenServicios + $totalServicios) > 0) {
|
|
$porcentajeMargenServicios = $margenServicios / ($totalServicios) * 100;
|
|
} else {
|
|
$porcentajeMargenServicios = 0;
|
|
}
|
|
$sumForFactorPonderado += $totalServicios;
|
|
}
|
|
|
|
if ($extra_info) {
|
|
array_push($totales, array(
|
|
'totalPapel' => $totalPapel,
|
|
'margenPapel' => $margenPapel,
|
|
'totalImpresion' => $totalImpresion,
|
|
'margenImpresion' => $margenImpresion,
|
|
|
|
'totalServicios' => $totalServicios,
|
|
'margenServicios' => $margenServicios,
|
|
|
|
'porcentajeMargenPapel' => round($porcentajeMargenPapel, 0),
|
|
'porcentajeMargenImpresion' => round($porcentajeMargenImpresion, 0),
|
|
'porcentajeMargenServicios' => round($porcentajeMargenServicios, 0),
|
|
|
|
'sumForFactor' => $sumForFactor,
|
|
'sumForFactorPonderado' => $sumForFactorPonderado,
|
|
|
|
'total' => round($total_por_tirada, 2),
|
|
'precio_u' => round(($total_por_tirada) / $tirada[$t], 4),
|
|
));
|
|
}
|
|
|
|
if (intval($tirada[$t]) == intval($selected_tirada)) {
|
|
$info['lomo_cubierta'] = round(floatval($lomo), 2);
|
|
$info['lomo_sobrecubierta'] = round(floatval($lomo_sobrecubierta), 2);
|
|
}
|
|
|
|
$return_data['info'] = $info;
|
|
|
|
|
|
if ($extra_info && ($tirada[$t] == $selected_tirada)) {
|
|
|
|
$return_data['values']['interior'] = $interior;
|
|
$return_data['values']['cubierta'] = $cubierta;
|
|
$return_data['values']['sobrecubierta'] = $linea_sobrecubierta;
|
|
$return_data['values']['guardas'] = $guardas;
|
|
$return_data['values']['faja'] = $linea_faja;
|
|
$return_data['values']['serviciosDefecto']['encuadernacion'] = $servDefectoEnc;
|
|
$return_data['values']['serviciosDefecto']['manipulado'] = $servDefectoMan;
|
|
$return_data['values']['servicios_automaticos'] = $serviciosAutomaticos;
|
|
$return_data['values']['servicios_extra'] = $serviciosExtra;
|
|
}
|
|
}
|
|
|
|
$return_data += [
|
|
'errors' => (object) ([
|
|
'status' => 0,
|
|
]),
|
|
//'total_lp' => $costeInterior + $coste_cubierta + $coste_sobrecubierta,
|
|
//'acabadoCubierta' => $acabadoCubierta,
|
|
//'acabadoSobrecubierta' => $acabadoSobrecubierta,
|
|
//'total_servicios_defecto' => $costeServiciosDefecto,
|
|
//'total_servicios_automaticos' => $coste_servicios,
|
|
'tiradas' => $tirada,
|
|
'precio_u' => $precio_u,
|
|
'peso' => $peso,
|
|
];
|
|
|
|
if ($extra_info) {
|
|
$return_data['info']['totales'] = $totales;
|
|
}
|
|
|
|
return $return_data;
|
|
} catch (Exception $e) {
|
|
return [
|
|
'exception' => $e->getMessage(),
|
|
"line" => $e->getLine(),
|
|
"file" => $e->getFile()
|
|
];
|
|
}
|
|
}
|
|
|
|
protected function calcular_coste_linea($linea, &$totalPapel, &$margenPapel, &$sumForFactor, &$totalImpresion, &$margenImpresion)
|
|
{
|
|
if (count($linea) == 0)
|
|
return;
|
|
$totalPapel += round($linea['precio_pedido'], 2);
|
|
$totalPapel -= round($linea['margen_papel_pedido'], 2);
|
|
$totalPapel = round($totalPapel, 2);
|
|
$sumForFactor += round($linea['precio_pedido'], 2)
|
|
- round($linea['margen_papel_pedido'], 2);
|
|
$margenPapel += round($linea['margen_papel_pedido'], 2);
|
|
|
|
$totalImpresion += round($linea['precio_click_pedido'], 2);
|
|
$totalImpresion -= round($linea['margen_click_pedido'], 2);
|
|
$totalImpresion = round($totalImpresion, 2);
|
|
$sumForFactor += round($linea['precio_click_pedido'], 2)
|
|
- round($linea['margen_click_pedido'], 2);
|
|
|
|
if ($linea['tipo_maquina'] == 'inkjet') {
|
|
$totalImpresion += round($linea['precio_tinta'], 2);
|
|
$sumForFactor += round($linea['precio_tinta'], 2);
|
|
if (array_key_exists('total_corte', $linea)) {
|
|
$totalImpresion += round($linea['total_corte'], 2);
|
|
$sumForFactor += round($linea['total_corte'], 2);
|
|
}
|
|
}
|
|
$margenImpresion += round($linea['precio_impresion_horas'], 2); // coste de maquina y magen son MARGEN, no COSTE
|
|
$margenImpresion += round($linea['margen_impresion_horas'], 2);
|
|
$margenImpresion += round($linea['margen_click_pedido'], 2);
|
|
$margenImpresion = round($margenImpresion, 2);
|
|
|
|
}
|
|
|
|
protected function calcular_lomo($lineas, $lomo_inicial)
|
|
{
|
|
$lomo = $lomo_inicial;
|
|
foreach ($lineas as $linea) {
|
|
if (count($linea) > 0) {
|
|
$lomo += floatval($linea['mano']);
|
|
}
|
|
}
|
|
return floatval($lomo);
|
|
}
|
|
|
|
protected function getTipoImpresion($tipo, $tapa)
|
|
{
|
|
|
|
$tipo_impresion_id = -1;
|
|
|
|
try {
|
|
if ($tipo == 'fresado') {
|
|
|
|
if (strpos(strtolower($tapa), 'blanda') !== false)
|
|
$tipo_impresion_id = 2;
|
|
else
|
|
$tipo_impresion_id = 1;
|
|
} else if ($tipo == 'cosido') {
|
|
|
|
if (strpos(strtolower($tapa), 'blanda') !== false)
|
|
$tipo_impresion_id = 4;
|
|
else
|
|
$tipo_impresion_id = 3;
|
|
} else if ($tipo == 'espiral') {
|
|
|
|
if (strpos(strtolower($tapa), 'blanda') !== false)
|
|
$tipo_impresion_id = 6;
|
|
else
|
|
$tipo_impresion_id = 5;
|
|
} else if ($tipo == 'wireo') {
|
|
|
|
if (strpos(strtolower($tapa), 'blanda') !== false)
|
|
$tipo_impresion_id = 8;
|
|
else
|
|
$tipo_impresion_id = 7;
|
|
} else if ($tipo == 'grapado') {
|
|
$tipo_impresion_id = 21;
|
|
}
|
|
|
|
return $tipo_impresion_id;
|
|
} catch (Exception $e) {
|
|
return -1;
|
|
}
|
|
}
|
|
|
|
protected function getPapelFormatoListItems($selId = null)
|
|
{
|
|
$papelFormatoModel = model('App\Models\Configuracion\PapelFormatoModel');
|
|
$data = $papelFormatoModel->getElementsForMenu();
|
|
array_shift($data);
|
|
return $data;
|
|
}
|
|
|
|
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 getTipoLibro($tipo_impresion_id)
|
|
{
|
|
if ($tipo_impresion_id == 1 || $tipo_impresion_id == 2) {
|
|
return 'fresado';
|
|
} else if ($tipo_impresion_id == 3 || $tipo_impresion_id == 4) {
|
|
return 'cosido';
|
|
} else if ($tipo_impresion_id == 5 || $tipo_impresion_id == 6) {
|
|
return 'espiral';
|
|
} else if ($tipo_impresion_id == 7 || $tipo_impresion_id == 8) {
|
|
return 'wireo';
|
|
} else if ($tipo_impresion_id == 21) {
|
|
return 'grapado';
|
|
} else
|
|
return '';
|
|
}
|
|
|
|
protected function obtenerTipoTapa($tipo_impresion_id)
|
|
{
|
|
$model = model('App\Models\Configuracion\TipoPresupuestoModel');
|
|
$data = $model->get_isTapaDura($tipo_impresion_id);
|
|
if ($data) {
|
|
return 'dura';
|
|
} else {
|
|
return 'blanda';
|
|
}
|
|
}
|
|
|
|
|
|
protected function getTipoInterior($presupuestoId)
|
|
{
|
|
|
|
$calidad = 'estandar';
|
|
$color = 'negro';
|
|
|
|
$model = model('App\Models\Presupuestos\PresupuestoLineaModel');
|
|
$data = $model->where('presupuesto_id', $presupuestoId)->findAll();
|
|
;
|
|
foreach ($data as $linea) {
|
|
|
|
if (strpos($linea->tipo, "hq") !== false) { // $linea->tipo contains the substring "hq"
|
|
$calidad = 'premium';
|
|
}
|
|
if (strpos($linea->tipo, "color") !== false) { // $linea->tipo contains the substring "color"
|
|
$color = 'color';
|
|
}
|
|
}
|
|
|
|
$tipo = "negro";
|
|
|
|
if ($calidad == 'premium' && $color == 'negro')
|
|
$tipo = "negroHq";
|
|
else if ($calidad == 'estandar' && $color == 'color')
|
|
$tipo = "color";
|
|
else if ($calidad == 'premium' && $color == 'color')
|
|
$tipo = "colorHq";
|
|
|
|
return $tipo;
|
|
}
|
|
|
|
protected function getTapa($tipo_impresion_id)
|
|
{
|
|
|
|
$tapa = 'blanda';
|
|
|
|
if (
|
|
$tipo_impresion_id == 1 || $tipo_impresion_id == 3 ||
|
|
$tipo_impresion_id == 5 || $tipo_impresion_id == 7
|
|
)
|
|
$tapa = 'dura';
|
|
|
|
return $tapa;
|
|
}
|
|
|
|
protected function obtenerPaginasColor($presupuestoEntity)
|
|
{
|
|
$comparador_data = json_decode($presupuestoEntity->comparador_json_data);
|
|
if (!is_null($comparador_data)) {
|
|
if (property_exists($comparador_data, 'color')) {
|
|
$presupuestoEntity->paginasColor = $comparador_data->color->paginas;
|
|
}
|
|
if (property_exists($comparador_data, 'colorhq')) {
|
|
$presupuestoEntity->paginasColor = $comparador_data->colorhq->paginas;
|
|
} else {
|
|
$presupuestoEntity->paginasColor = 0;
|
|
}
|
|
} else
|
|
$presupuestoEntity->paginasColor = 0;
|
|
}
|
|
|
|
protected function obtenerTiradas($presupuestoEntity)
|
|
{
|
|
|
|
$tiradas_alternativas = json_decode($presupuestoEntity->tirada_alternativa_json_data, true);
|
|
$tiradas = array();
|
|
array_push($tiradas, $presupuestoEntity->tirada);
|
|
if (!is_null($tiradas_alternativas)) {
|
|
if (count($tiradas_alternativas) > 0) {
|
|
foreach ($tiradas_alternativas as $tirada) {
|
|
array_push($tiradas, intval($tirada['tirada']));
|
|
}
|
|
}
|
|
}
|
|
sort($tiradas);
|
|
$presupuestoEntity->selected_tirada = $presupuestoEntity->tirada;
|
|
for ($i = 0; $i < count($tiradas); $i++) {
|
|
$key = 'tirada' . ($i == 0 ? '' : strval($i + 1));
|
|
$presupuestoEntity->$key = $tiradas[$i];
|
|
}
|
|
}
|
|
|
|
protected function obtenerDireccionesEnvio($id)
|
|
{
|
|
$model = model('App\Models\Presupuestos\PresupuestoDireccionesModel');
|
|
$direcciones = $model->where('presupuesto_id', $id)
|
|
->where('is_ferro_prototipo', 0)->asArray()->findAll();
|
|
|
|
return $direcciones;
|
|
}
|
|
|
|
protected function obtenerDireccionesEnvioFerro($id)
|
|
{
|
|
$model = model('App\Models\Presupuestos\PresupuestoDireccionesModel');
|
|
$direcciones = $model->where('presupuesto_id', $id)
|
|
->where('is_ferro_prototipo', 1)->get()->getResultArray();
|
|
|
|
return $direcciones;
|
|
}
|
|
|
|
protected function obtenerDatosPapel($presupuesto_id)
|
|
{
|
|
|
|
$return_data = [];
|
|
|
|
$model = model('App\Models\Presupuestos\PresupuestoLineaModel');
|
|
$data = $model->where('presupuesto_id', $presupuesto_id)->findAll();
|
|
|
|
$modelPapelGenerico = model('App\Models\Configuracion\PapelGenericoModel');
|
|
|
|
if (count($data) > 0) {
|
|
foreach ($data as $linea) {
|
|
if ($linea->tipo == 'lp_bn' || $linea->tipo == 'lp_bnhq' || $linea->tipo == 'lp_rot_bn') {
|
|
$return_data['interior']['negro']['tipo'] = $linea->tipo == 'lp_bn' || $linea->tipo == 'lp_rot_bn' ? 'negroEstandar' : 'negroPremium';
|
|
$return_data['interior']['negro']['papel'] = $modelPapelGenerico->getNombre($linea->papel_id);
|
|
$return_data['interior']['negro']['papel']['id'] = $linea->papel_id;
|
|
$return_data['interior']['negro']['gramaje'] = $linea->gramaje;
|
|
} else if ($linea->tipo == 'lp_color' || $linea->tipo == 'lp_colorhq' || $linea->tipo == 'lp_rot_color') {
|
|
$return_data['interior']['color']['tipo'] = $linea->tipo == 'lp_color' || $linea->tipo == 'lp_rot_color' ? 'colorEstandar' : 'colorPremium';
|
|
$return_data['interior']['color']['papel'] = $modelPapelGenerico->getNombre($linea->papel_id);
|
|
$return_data['interior']['color']['papel']['id'] = $linea->papel_id;
|
|
$return_data['interior']['color']['gramaje'] = $linea->gramaje;
|
|
} else if ($linea->tipo == 'lp_cubierta') {
|
|
$return_data['cubierta']['papel'] = $modelPapelGenerico->getNombre($linea->papel_id);
|
|
$return_data['cubierta']['papel']['id'] = $linea->papel_id;
|
|
$return_data['cubierta']['gramaje'] = $linea->gramaje;
|
|
$return_data['cubierta']['paginas'] = $linea->paginas;
|
|
} else if ($linea->tipo == 'lp_sobrecubierta') {
|
|
$return_data['sobrecubierta']['papel'] = $modelPapelGenerico->getNombre($linea->papel_id)['nombre'];
|
|
$return_data['sobrecubierta']['papel_id'] = $linea->papel_id;
|
|
$return_data['sobrecubierta']['gramaje'] = $linea->gramaje;
|
|
$return_data['sobrecubierta']['paginas'] = $linea->paginas;
|
|
} else if ($linea->tipo == 'lp_faja') {
|
|
$return_data['faja']['papel'] = $modelPapelGenerico->getNombre($linea->papel_id)['nombre'];
|
|
$return_data['faja']['papel_id'] = $linea->papel_id;
|
|
$return_data['faja']['gramaje'] = $linea->gramaje;
|
|
$return_data['faja']['paginas'] = $linea->paginas;
|
|
} else if ($linea->tipo == 'lp_guardas') {
|
|
$return_data['guardas']['papel'] = $modelPapelGenerico->getNombre($linea->papel_id)['nombre'];
|
|
$return_data['guardas']['papel_id'] = $linea->papel_id;
|
|
$return_data['guardas']['gramaje'] = $linea->gramaje;
|
|
$return_data['guardas']['paginas'] = $linea->paginas;
|
|
}
|
|
}
|
|
}
|
|
|
|
return $return_data;
|
|
}
|
|
|
|
protected function generarResumen($presupuestoEntity)
|
|
{
|
|
|
|
$presupuestoEntity->resumen = (object) [
|
|
'titulo' => $this->generarTitulo($presupuestoEntity),
|
|
'tamanio' => $this->obtenerTamanio($presupuestoEntity),
|
|
'tipo_impresion' => $this->obtenerTipoImpresion($presupuestoEntity)
|
|
];
|
|
|
|
$model_papelGenerico = model('App\Models\Configuracion\PapelGenericoModel');
|
|
if (!is_null($presupuestoEntity->papel_interior)) {
|
|
$nombre = $model_papelGenerico->where('id', $presupuestoEntity->papel_interior)->first()->nombre;
|
|
if ($nombre != null)
|
|
$presupuestoEntity->papel_interior_nombre = $nombre;
|
|
}
|
|
if (!is_null($presupuestoEntity->papel_cubierta)) {
|
|
$nombre = $model_papelGenerico->where('id', $presupuestoEntity->papel_interior)->first()->nombre;
|
|
if ($nombre != null)
|
|
$presupuestoEntity->papel_cubierta_nombre = $nombre;
|
|
}
|
|
if (!is_null($presupuestoEntity->papel_sobrecubierta)) {
|
|
$nombre = $model_papelGenerico->where('id', $presupuestoEntity->papel_sobrecubierta)->first()->nombre;
|
|
if ($nombre != null)
|
|
$presupuestoEntity->papel_sobrecubierta_nombre = $nombre;
|
|
}
|
|
if (!is_null($presupuestoEntity->papel_guardas)) {
|
|
$nombre = $model_papelGenerico->where('id', $presupuestoEntity->papel_guardas)->first()->nombre;
|
|
if ($nombre != null)
|
|
$presupuestoEntity->papel_guardas_nombre = $nombre;
|
|
}
|
|
}
|
|
|
|
protected function generarTitulo($presupuestoEntity)
|
|
{
|
|
|
|
$model = model('App\Models\Configuracion\TipoPresupuestoModel');
|
|
$codigo = $model->where('id', $presupuestoEntity->tipo_impresion_id)->first()->codigo;
|
|
$titulo = lang('Presupuestos.titulos.' . $codigo);
|
|
return $titulo;
|
|
}
|
|
|
|
protected function obtenerTamanio($presupuestoEntity)
|
|
{
|
|
|
|
$ancho = 0;
|
|
$alto = 0;
|
|
|
|
$model = model('App\Models\Presupuestos\PresupuestoModel');
|
|
$data = $model->where('id', $presupuestoEntity->id)->first();
|
|
|
|
if ($data != null) {
|
|
if ($data->papel_formato_personalizado == 0) {
|
|
|
|
$model_papel_formato = model('App\Models\Configuracion\PapelFormatoModel');
|
|
$data_papel_formato = $model_papel_formato->where('id', $data->papel_formato_id)->first();
|
|
$ancho = $data_papel_formato->ancho;
|
|
$alto = $data_papel_formato->alto;
|
|
} else {
|
|
$ancho = $data->papel_formato_ancho;
|
|
$alto = $data->papel_formato_alto;
|
|
}
|
|
}
|
|
|
|
return $ancho . "x" . $alto;
|
|
}
|
|
|
|
protected function obtenerTipoImpresion($presupuestoEntity)
|
|
{
|
|
|
|
$id = $presupuestoEntity->id;
|
|
|
|
$isColor = false;
|
|
$isHq = false;
|
|
|
|
$model = model('App\Models\Presupuestos\PresupuestoLineaModel');
|
|
$data = $model->where('presupuesto_id', $id)->findAll();
|
|
if (count($data) > 0) {
|
|
foreach ($data as $linea) {
|
|
if (strpos($linea->tipo, "hq") !== false) {
|
|
$isHq = true;
|
|
}
|
|
if (strpos($linea->tipo, "color") !== false) {
|
|
$isColor = true;
|
|
}
|
|
}
|
|
}
|
|
$tipo = "" . ($isColor ? "Color" : "Negro") . " " . ($isHq ? "premium" : "estándar");
|
|
return $tipo;
|
|
}
|
|
|
|
protected function obtenerPaginasCuadernillo($presupuestoEntity)
|
|
{
|
|
|
|
$model = model('App\Models\Presupuestos\PresupuestoEncuadernacionesModel');
|
|
$lineas = $model->getResource($presupuestoEntity->id)->get()->getResultObject();
|
|
|
|
foreach ($lineas as $linea) {
|
|
// check if exist
|
|
if ($linea->paginas_por_cuadernillo != null)
|
|
return $linea->paginas_por_cuadernillo;
|
|
}
|
|
return 32; // valor por defecto
|
|
}
|
|
|
|
protected function obtenerTarifasAcabado($acabados)
|
|
{
|
|
$tarifas = [];
|
|
|
|
$model = model('App\Models\Tarifas\Acabados\TarifaAcabadoModel');
|
|
|
|
|
|
foreach ($acabados as $acabado => $value) {
|
|
|
|
if ($value != 'NONE') {
|
|
$data = $model->where('code', $value)->first();
|
|
$tarifas[$acabado] = $data->id;
|
|
}
|
|
}
|
|
|
|
return $tarifas;
|
|
}
|
|
|
|
|
|
private function getPaginas($lineas)
|
|
{
|
|
|
|
$paginasNegro = 0;
|
|
$paginasColor = 0;
|
|
|
|
foreach ($lineas as $linea) {
|
|
if (strpos($linea->tipo, "lp_bn") !== false || strpos($linea->tipo, "lp_bnhq") !== false) {
|
|
$paginasNegro = $linea->paginas;
|
|
}
|
|
|
|
if (strpos($linea->tipo, "lp_color") !== false || strpos($linea->tipo, "lp_colorhq") !== false) {
|
|
$paginasColor = $linea->paginas;
|
|
}
|
|
|
|
if (strpos($linea->tipo, "lp_rot_bn") !== false) {
|
|
$paginasNegro = $linea->paginas;
|
|
}
|
|
|
|
if (strpos($linea->tipo, "lp_rot_color") !== false) {
|
|
$paginasColor = $linea->rotativa_pag_color;
|
|
$paginasNegro = $linea->paginas - $linea->rotativa_pag_color;
|
|
}
|
|
}
|
|
|
|
return [$paginasNegro, $paginasColor];
|
|
}
|
|
|
|
private function getServiciosExtra()
|
|
{
|
|
|
|
$servicios = [];
|
|
|
|
$model = model('App\Models\Tarifas\TarifaextraModel');
|
|
$data = $model->where('deleted_at', null)->where('mostrar_en_presupuesto_cliente', 1)->findAll();
|
|
|
|
foreach ($data as $servicio) {
|
|
$id = "service_extra_" . $servicio->id;
|
|
|
|
$tarifa_excluyente = false;
|
|
if (str_contains(strtolower($servicio->nombre), 'ferro') || str_contains(strtolower($servicio->nombre), 'prototipo')) {
|
|
$tarifa_excluyente = true;
|
|
}
|
|
$atributo_excluyente = $tarifa_excluyente ? 'data-tarifa-extra-excluyente="1"' : '';
|
|
|
|
array_push(
|
|
$servicios,
|
|
"<input class=\"calcular-presupuesto form-check-input\" type=\"checkbox\" id=\"{$id}\"
|
|
name=\"{$id}\" value=\"1\" data-tarifa-id=\"{$servicio->id}\" data-tarifa-tipo=\"extra\" data-tarifa-nombre=\"{$servicio->nombre}\"
|
|
{$atributo_excluyente}>
|
|
<label class=\"form-check-label\" for=\"{$id}\">{$servicio->nombre}</label>"
|
|
);
|
|
}
|
|
|
|
return $servicios;
|
|
}
|
|
|
|
public function download_zip()
|
|
{
|
|
$presupuesto_id = $this->request->getPost('presupuesto_id');
|
|
$ot_id = $this->request->getPost('ot_id');
|
|
|
|
if (!$presupuesto_id) {
|
|
return $this->response->setStatusCode(400)->setBody('Presupuesto ID requerido');
|
|
}
|
|
|
|
// Definir prefijo si se recibió un ot_id válido
|
|
$prefijo = (!empty($ot_id) && is_numeric($ot_id)) ? "OT_{$ot_id}" : null;
|
|
|
|
$ftpClient = new \App\Libraries\SafekatFtpClient();
|
|
try {
|
|
$zipPath = $ftpClient->downloadZipPresupuesto((int) $presupuesto_id, $prefijo);
|
|
|
|
if ($zipPath === null || !file_exists($zipPath)) {
|
|
return $this->response->setStatusCode(404)->setBody('No se encontraron archivos');
|
|
}
|
|
|
|
$nombreArchivo = $prefijo
|
|
? "{$prefijo}_PRESUPUESTO_{$presupuesto_id}.zip"
|
|
: "archivos_presupuesto_{$presupuesto_id}.zip";
|
|
|
|
return $this->response
|
|
->download($zipPath, null)
|
|
->setFileName($nombreArchivo);
|
|
} catch (\Throwable $e) {
|
|
log_message('error', $e->getMessage());
|
|
return $this->response->setStatusCode(500)->setBody('Error interno');
|
|
}
|
|
}
|
|
|
|
|
|
|
|
}
|