Merge branch 'main' into dev/chat

This commit is contained in:
amazuecos
2024-09-07 20:30:51 +02:00
55 changed files with 2452 additions and 240 deletions

View File

@ -46,6 +46,7 @@ class Autoload extends AutoloadConfig
public $psr4 = [
APP_NAMESPACE => APPPATH, // For custom app namespace
'Config' => APPPATH . 'Config',
'Libraries' => APPPATH . 'Libraries',
'Dompdf' => APPPATH . 'ThirdParty/dompdf/src',
];

View File

@ -0,0 +1,27 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class PedidoXML extends BaseConfig
{
public string $host;
public int $port;
public string $username;
public string $password;
public string $base_dir; # FTP server directory
public bool $xml_enabled;
public function __construct() {
parent::__construct();
$this->host = env("HIDRIVE_HOST","10.5.0.6");
$this->port = env("HIDRIVE_PORT",21);
$this->username = env("HIDRIVE_USER","admin");
$this->password = env("HIDRIVE_PASS","A77h3b0X4OA2rOYAf4w2");
$this->base_dir = env("HIDRIVE_PATH_ROOT","/home/admin/safekat"); # FTP server directory
$this->xml_enabled = env("FTP_XML_ENABLED",false);
}
}

View File

@ -1,7 +1,6 @@
<?php
use CodeIgniter\Router\RouteCollection;
/**
* @var RouteCollection $routes
*/
@ -590,6 +589,7 @@ $routes->resource('presupuestocliente', ['namespace' => 'App\Controllers\Presupu
$routes->group('serviciosacabados', ['namespace' => 'App\Controllers\Presupuestos'], function ($routes) {
$routes->post('datatable', 'Presupuestoacabados::datatable', ['as' => 'dataTableOfPresupuestoAcabados']);
$routes->post('menuitems', 'Presupuestoacabados::menuItems', ['as' => 'menuItemsOfPresupuestoAcabados']);
$routes->post('edit/(:num)', 'Presupuestoacabados::edit/$1', ['as' => 'updatePresupuestoacabados']);
});
@ -638,6 +638,8 @@ $routes->group('pedidos', ['namespace' => 'App\Controllers\Pedidos'], function (
$routes->post('getlineas', 'Pedido::getLineas', ['as' => 'tablaLineasPedido']);
$routes->post('cambiarestado', 'Pedido::cambiarEstado', ['as' => 'cambiarEstadoPedido']);
$routes->post('update/(:any)', 'Pedido::update/$1', ['as' => 'actualizarPedido']);
$routes->get('xml/(:num)', 'Pedido::get_xml_pedido/$1',['as' => 'getXMLPedido']);
});
$routes->resource('pedidos', ['namespace' => 'App\Controllers\Pedidos', 'controller' => 'Pedido', 'except' => 'show,new,create,update']);
@ -700,6 +702,15 @@ $routes->group(
}
);
$routes->group(
'print-factura',
['namespace' => 'App\Controllers\Pdf'],
function ($routes) {
$routes->get('index/(:num)', 'PrintFacturas::index/$1', ['as' => 'viewFacturaPDF']);
$routes->get('generar/(:num)', 'PrintFacturas::generar/$1', ['as' => 'facturaToPdf']);
}
);
$routes->group(
'export-giros',
['namespace' => 'App\Controllers\Excel'],
@ -708,6 +719,14 @@ $routes->group(
}
);
$routes->group(
'export-lineas',
['namespace' => 'App\Controllers\Excel'],
function ($routes) {
$routes->get('generar/(:num)', 'PrintLineas::generateExcel/$1', ['as' => 'lineasToExcel']);
}
);
$routes->group(
'buscadorpresupuestos',
['namespace' => 'App\Controllers\Presupuestos'],

View File

@ -2,6 +2,7 @@
namespace Config;
use App\Services\FTPService;
use CodeIgniter\Config\BaseService;
/**

View File

@ -0,0 +1,70 @@
<?php
namespace App\Controllers\Excel;
use App\Controllers\BaseController;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
class PrintLineas extends BaseController
{
public function generateExcel($factura_id = null)
{
// Modelos
$lineasFacturaModel = model('App\Models\Facturas\FacturaLineaModel');
$infoLineasFactura = $lineasFacturaModel->getResourceForExcel($factura_id)->get()->getResultObject();
// Crear un nuevo Spreadsheet
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
// Especificar encabezados
$headers = [
'Factura',
'ID Pedido',
'Ref. Cliente',
'Base'
];
// Establecer los encabezados en la primera fila
$column = 'A';
foreach ($headers as $header) {
$sheet->setCellValue($column . '1', $header);
$column++;
}
// Rellenar las filas con datos
$rowNumber = 2; // Empezar en la segunda fila
foreach ($infoLineasFactura as $infoLineaFactura) {
$column = 'A';
foreach ($infoLineaFactura as $cell) {
$sheet->setCellValue($column . $rowNumber, $cell);
$column++;
}
$rowNumber++;
}
// Ajustar automáticamente el tamaño de las columnas
foreach (range('A', $column) as $col) {
$sheet->getColumnDimension($col)->setAutoSize(true);
}
// Crear un escritor para guardar el archivo
$writer = new Xlsx($spreadsheet);
// Configurar la respuesta para descarga
$fileName = 'lineas-pedido.xlsx';
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="' . $fileName . '"');
header('Cache-Control: max-age=0');
// Escribir el archivo a la salida
$writer->save('php://output');
exit;
}
}

View File

@ -0,0 +1,65 @@
<?php
namespace App\Controllers\Pdf;
use App\Controllers\BaseController;
class PrintFacturas extends BaseController
{
public function index($id_factura)
{
$facturaModel = model('App\Models\Facturas\FacturaModel');
$lineasFacturaModel = model('App\Models\Facturas\FacturaLineaModel');
$data['factura'] = $facturaModel->getResourceForPdf($id_factura)->get()->getRow();
$data['lineas_factura'] = $lineasFacturaModel->getResourceForPdf($id_factura)->get()->getResultObject();
$data['resumen_por_iva'] = $lineasFacturaModel->getResourceResumenIVAsForPdf($id_factura)->get()->getResultObject();
return view(getenv('theme.path') . 'pdfs/factura', $data);
}
public function generar($id_factura)
{
// Cargar modelos
$facturaModel = model('App\Models\Facturas\FacturaModel');
$lineasFacturaModel = model('App\Models\Facturas\FacturaLineaModel');
// Informacion del presupuesto
$data['factura'] = $facturaModel->getResourceForPdf($id_factura)->get()->getRow();
$data['lineas_factura'] = $lineasFacturaModel->getResourceForPdf($id_factura)->get()->getResultObject();
$data['resumen_por_iva'] = $lineasFacturaModel->getResourceResumenIVAsForPdf($id_factura)->get()->getResultObject();
// Crear una instancia de Dompdf
$options = new \Dompdf\Options();
$options->set('isHtml5ParserEnabled', true);
$options->set('isPhpEnabled', true);
$options->set('isRemoteEnabled', true);
$dompdf = new \Dompdf\Dompdf($options);
// Contenido HTML del documento
$dompdf->loadHtml(view(getenv('theme.path').'pdfs/factura', $data));
// Establecer el tamaño del papel
$dompdf->setPaper('A4', 'portrait');
// Renderizar el PDF
$dompdf->render();
// Obtener el contenido generado
$output = $dompdf->output();
// Establecer las cabeceras para visualizar en lugar de descargar
$file_name = $data['factura']->numero . ".pdf";
return $this->response
->setStatusCode(200)
->setHeader('Content-Type', 'application/pdf')
->setHeader('Content-Disposition', 'inline; filename="' . $file_name . '"')
->setHeader('Cache-Control', 'private, max-age=0, must-revalidate')
->setHeader('Pragma', 'public')
->setHeader('Content-Length', strlen($output))
->setBody($output);
}
}

View File

@ -5,7 +5,7 @@ use App\Controllers\BaseController;
use App\Entities\Pedidos\PedidoEntity;
use App\Models\Collection;
use App\Models\Pedidos\PedidoModel;
use App\Services\PedidoXMLService;
class Pedido extends \App\Controllers\BaseResourceController
{
@ -21,7 +21,6 @@ class Pedido extends \App\Controllers\BaseResourceController
protected $indexRoute = 'pedidoList';
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
$this->viewData['pageTitle'] = lang('Pedidos.moduleTitle');
@ -327,5 +326,11 @@ class Pedido extends \App\Controllers\BaseResourceController
$pedidoEntity->fecha_encuadernado_text = $pedidoEntity->fecha_encuadernado ? date('d/m/Y', strtotime($pedidoEntity->fecha_encuadernado)) : '';
$pedidoEntity->fecha_entrega_externo_text = $pedidoEntity->fecha_entrega_externo ? date('d/m/Y', strtotime($pedidoEntity->fecha_entrega_externo)) : '';
}
public function get_xml_pedido($pedido_id)
{
$data = PedidoXMLService::generate_xml($pedido_id);
// $xml_service = new PedidoXMLService($this->model);
return $this->respond($data);
}
}

View File

@ -99,12 +99,13 @@ class Presupuestoacabados extends \App\Controllers\BaseResourceController
$tarifa_acabado_id = $reqData['tarifa_acabado_id'] ?? 0;
$tirada = $reqData['tirada'] ?? 0;
$proveedor_id = $reqData['proveedor_id'] ?? -1;
$POD = $reqData['POD'] ?? 0;
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
$values = $this->model->getPrecioTarifa($tarifa_acabado_id, $tirada, $POD);
$values = $this->model->getPrecioTarifa($tarifa_acabado_id, $tirada, $proveedor_id, $POD);
$data = [
'values' => $values,
@ -119,4 +120,39 @@ class Presupuestoacabados extends \App\Controllers\BaseResourceController
}
public function menuItems()
{
if ($this->request->isAJAX()) {
$reqData = $this->request->getPost();
try{
$tarifa_id = $reqData['tarifa_id'] ?? -1;
$tirada = $reqData['tirada'] ?? 0;
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
$menu = $this->model->getProveedoresForSelector($tarifa_id, $tirada);
$data = [
'menu' => $menu,
$csrfTokenName => $newTokenHash
];
}
catch(Exception $e){
$data = [
'error' => $e,
$csrfTokenName => $newTokenHash
];
}
finally{
return $this->respond($data);
}
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
}

View File

@ -3,6 +3,7 @@
namespace App\Controllers\Presupuestos;
use App\Entities\Presupuestos\PresupuestoEntity;
use App\Libraries\SafekatFtpClient;
use App\Models\Collection;
use App\Models\Configuracion\PapelGenericoModel;
use App\Models\Configuracion\TipoPresupuestoModel;
@ -118,7 +119,9 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
$datosPresupuesto->tapa = 'blanda';
$datosPresupuesto->clienteList = $this->getClienteListItems($clienteId ?? null);
$datosPresupuesto->paginasCuadernillo = [32, 28, 24, 20 , 16];
$presupuestoEntity->estado_id = 1;
$presupuestoEntity->paginas_por_cuadernillo = 32;
$this->viewData['formAction'] = 'add';
@ -185,6 +188,9 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
if($presupuestoEntity->estado_id == 2){
$this->generarResumen($presupuestoEntity);
}
$datosPresupuesto->paginasCuadernillo = [32, 28, 24, 20 , 16];
$presupuestoEntity->paginas_por_cuadernillo = $this->obtenerPaginasCuadernillo($presupuestoEntity);
$this->viewData['formAction'] = 'edit';
@ -371,6 +377,8 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
$servicios = $reqData['servicios'] ?? [];
$paginasCuadernillo = $reqData['paginasCuadernillo'] ?? null;
$datos_presupuesto = array(
'tirada' => $tirada,
'tamanio' => $tamanio,
@ -378,6 +386,7 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
'clienteId' => $cliente_id,
'isColor' => $isColor,
'isHq' => $isHq,
'paginasCuadernillo' => $paginasCuadernillo,
'interior' => array(
'papel_generico' => $papel_generico,
@ -600,6 +609,7 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
$cliente_id = $reqData['datos_libro']['clienteId'] ?? -1;
$isColor = intval($reqData['datos_libro']['isColor']) ?? 0;
$isHq = intval($reqData['datos_libro']['isHq']) ?? 0;
$paginasCuadernillo = $reqData['datos_libro']['paginasCuadernillo'] ?? null;
// Interior
$papel_generico = [
@ -637,6 +647,7 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
'clienteId' => $cliente_id,
'isColor' => $isColor,
'isHq' => $isHq,
'paginasCuadernillo' => $paginasCuadernillo,
'interior' => array(
'papel_generico' => $papel_generico,
@ -882,7 +893,10 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
}
if(!is_null($new_name)){
move_uploaded_file($tmp_name, WRITEPATH . 'uploads/presupuestos/' . $new_name);
$path = WRITEPATH . 'uploads/presupuestos/' . $new_name;
move_uploaded_file($tmp_name,$path);
$ftp = new SafekatFtpClient();
$ftp->uploadFilePresupuesto($presupuesto_id);
}
}
}
@ -983,6 +997,12 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
'precio_unidad' => $servicio->precio_unidad,
'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();
@ -1086,6 +1106,7 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
$cliente_id = $datos_entrada['clienteId'] ?? -1;
$isColor = $datos_entrada['isColor'];
$isHq = $datos_entrada['isHq'];
$paginasCuadernillo = $datos_entrada['paginasCuadernillo'] ?? null;
// Interior
$papel_generico = $datos_entrada['interior']['papel_generico'];
@ -1429,6 +1450,7 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
'alto' => $datosPedido->alto,
'POD' => $POD,
'solapas' => intval($solapasCubierta) > 0 ? 1 : 0,
'paginasCuadernillo' => $paginasCuadernillo,
]);
$costeServiciosDefecto = 0.0;
foreach ($servDefecto as $servicio) {
@ -1996,4 +2018,17 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
$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
}
}

View File

@ -118,6 +118,7 @@ class Presupuestoencuadernaciones extends \App\Controllers\BaseResourceControlle
$alto = $reqData['alto'] ?? 0;
$POD = $reqData['POD'] ?? 0;
$paginas_cuadernillo = $reqData['paginas_por_cuadernillo'] ?? null;
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
@ -125,7 +126,7 @@ class Presupuestoencuadernaciones extends \App\Controllers\BaseResourceControlle
$tarifaModel = model('App\Models\Tarifas\TarifaEncuadernacionModel');
if(is_null($tipo)){
if($tarifaModel->isTarifaPorHoras($tarifa_encuadernacion_id)){
$values = $this->model->getPrecioTarifaHoras($tarifa_encuadernacion_id, $paginas, $tirada, $proveedor_id, $POD);
$values = $this->model->getPrecioTarifaHoras($tarifa_encuadernacion_id, $paginas, $tirada, $proveedor_id, $POD, $paginas_cuadernillo);
}else{
$values = $this->model->getPrecioTarifa($tarifa_encuadernacion_id, $paginas, $tirada, $ancho, $alto, $proveedor_id, $POD);
}

View File

@ -5,6 +5,10 @@ use App\Entities\Tarifas\Acabados\TarifaAcabadoEntity;
use App\Models\Collection;
use App\Models\Tarifas\Acabados\TarifaAcabadoModel;
use App\Models\Compras\ProveedorModel;
use App\Models\Compras\ProveedorTipoModel;
class TarifaAcabados extends BaseResourceController
{
@ -217,6 +221,7 @@ class TarifaAcabados extends BaseResourceController
endif; // ($requestMethod === 'post')
$this->viewData['tarifaacabadoEntity'] = $tarifaacabadoEntity;
$this->viewData['proveedores'] = $this->getProveedores();
$this->viewData['formAction'] = route_to('updateTarifaAcabado', $id);
@ -305,4 +310,12 @@ class TarifaAcabados extends BaseResourceController
}
}
private function getProveedores(){
$provTipoModel = new ProveedorTipoModel();
$provModel = new ProveedorModel();
$tipoId = $provTipoModel->getTipoId("Acabados");
return $provModel->getProvList($tipoId);
}
}

View File

@ -213,13 +213,14 @@ class TarifaAcabadosLineas extends \App\Controllers\BaseResourceController
$id_TA = $reqData['id_tarifaacabado'] ?? -1;
$searchValues = get_filter_datatables_columns($reqData);
$resourceData = $this->model->getResource("", $id_TA)->orderBy($order, $dir)->limit($length, $start)->get()->getResultObject();
$resourceData = $this->model->getResource($searchValues, $id_TA)->orderBy($order, $dir)->limit($length, $start)->get()->getResultObject();
return $this->respond(Collection::datatable(
$resourceData,
$this->model->getResource()->countAllResults(),
$this->model->getResource($search, $id_TA)->countAllResults()
$this->model->getResource($searchValues, $id_TA)->countAllResults()
));
} else {
return $this->failUnauthorized('Invalid request', 403);
@ -280,6 +281,7 @@ class TarifaAcabadosLineas extends \App\Controllers\BaseResourceController
->validator('Validate::notEmpty', array(
'message' => lang('TarifaAcabadoLineas.validation.margen.required'))
),
Field::inst('proveedor_id'),
Field::inst('tarifa_acabado_id'),
Field::inst('user_created_id'),
Field::inst('created_at'),
@ -297,6 +299,7 @@ class TarifaAcabadosLineas extends \App\Controllers\BaseResourceController
$process_data['tirada_min'] = $data['data'][$pkey]['tirada_min'];
$process_data['tirada_max'] = $data['data'][$pkey]['tirada_max'];
$process_data['proveedor_id'] = $data['data'][$pkey]['proveedor_id'];
$response = $this->model->checkIntervals($process_data, $pkey, $data['data'][$pkey]['tarifa_acabado_id']);
// No se pueden duplicar valores al crear o al editar
if (!empty($response)) {

View File

@ -9,6 +9,7 @@ class PresupuestoAcabadosEntity extends \CodeIgniter\Entity\Entity
"id" => null,
"presupuesto_id" => null,
"tarifa_acabado_id" => null,
"proveedor_id" => null,
"precio_unidad" => null,
"precio_total" => null,
"margen" => null,
@ -20,6 +21,7 @@ class PresupuestoAcabadosEntity extends \CodeIgniter\Entity\Entity
protected $casts = [
"presupuesto_id" => "int",
"tarifa_acabado_id" => "int",
"proveedor_id" => "int",
"precio_unidad" => "float",
"precio_total" => "float",
"margen" => "float",

View File

@ -11,6 +11,7 @@ class PresupuestoEncuadernacionesEntity extends \CodeIgniter\Entity\Entity
"tarifa_encuadernado_id" => null,
"proveedor_id" => null,
"precio_unidad" => null,
"paginas_por_cuadernillo" => null,
"tiempo" => null,
"precio_total" => null,
"margen" => null,
@ -22,6 +23,7 @@ class PresupuestoEncuadernacionesEntity extends \CodeIgniter\Entity\Entity
"tarifa_encuadernado_id" => "int",
"proveedor_id" => "int",
"precio_unidad" => "float",
"paginas_por_cuadernillo" => "int",
"tiempo" => "float",
"precio_total" => "float",
"margen" => "float",

View File

@ -8,6 +8,7 @@ class TarifaAcabadoLineaEntity extends \CodeIgniter\Entity\Entity
protected $attributes = [
"id" => null,
"tarifa_acabado_id" => 0,
"proveedor_id" => 0,
"tirada_min" => 0,
"tirada_max" => 0,
"precio_min" => 0,
@ -21,6 +22,7 @@ class TarifaAcabadoLineaEntity extends \CodeIgniter\Entity\Entity
];
protected $casts = [
"tarifa_acabado_id" => "int",
"proveedor_id" => "int",
"tirada_min" => "int",
"tirada_max" => "int",
"precio_min" => "float",

0
ci4/app/Helpers/general_helper.php Executable file → Normal file
View File

View File

@ -6,6 +6,7 @@ return [
'id' => 'ID',
'moduleTitle' => 'Finish rates Lines',
'deleteLine' => 'the selected register',
'proveedor' => 'Provider',
'precioMax' => 'Max Price',
'precioMin' => 'Min Price',
'precioUnidad' => 'Price Unit',

View File

@ -247,6 +247,7 @@ return [
'precio' => 'Precio',
'precioUnidad' => 'Precio unidad',
'tiempo' => 'Tiempo',
"paginasCuadernillo" => "Páginas/cuadernillo",
'precioTotal' => 'Precio total',
'serviciosDefault' => 'Servicios por defecto',
'tarifa' => 'Tarifa',

View File

@ -6,8 +6,9 @@ return [
'id' => 'ID',
'moduleTitle' => 'Tarifa Acabado Líneas',
'deleteLine' => 'el registro seleccionado',
'precioMax' => 'Precio Max',
'precioMin' => 'Precio Min',
'proveedor' => 'Proveedor',
'precioMax' => 'Precio T. Mín',
'precioMin' => 'Precio T. Máx',
'precioUnidad' => 'Precio Unidad',
'tiradaMax' => 'Tirada Max',
'tiradaMin' => 'Tirada Min',

View File

@ -6,8 +6,8 @@ return [
'id' => 'ID',
'moduleTitle' => 'Tarifa Manipulado Lineas',
'deleteLine' => 'el registro seleccionado',
'precioMax' => 'Precio Max',
'precioMin' => 'Precio Min',
'precioMax' => 'Precio T. Mín',
'precioMin' => 'Precio T. Máx',
'precioUnidad' => 'Precio Unidad',
'tiradaMax' => 'Tirada Max',
'tiradaMin' => 'Tirada Min',

View File

@ -10,9 +10,10 @@ return [
'id' => 'ID',
'moduleTitle' => 'Tarifas Encuadernación',
'nombre' => 'Nombre',
'precioMax' => 'Precio Max',
'precioMin' => 'Precio Min',
'precioMax' => 'Precio T. Mín',
'precioMin' => 'Precio T. Máx',
'importeFijo' => 'Importe Fijo',
'importeMin' => 'Importe mínimo',
'tarifaencuadernacion' => 'Tarifa Encuadernación',
'tarifaencuadernacionList' => 'Lista Tarifas Encuadernación',
'tarifasencuadernacion' => 'Tarifas Encuadernación',

View File

@ -10,8 +10,8 @@ return [
'id' => 'ID',
'moduleTitle' => 'Tarifas Manipulado',
'nombre' => 'Nombre',
'precioMax' => 'Precio Max',
'precioMin' => 'Precio Min',
'precioMax' => 'Precio T. Mín',
'precioMin' => 'Precio T. Máx',
'importeFijo' => 'Importe Fijo',
'mostrar_en_presupuesto' => 'Mostrar en presupuesto',
'tarifamanipulado' => 'Tarifa Manipulado',

View File

@ -0,0 +1,81 @@
<?php
namespace App\Libraries;
use App\Models\Pedidos\PedidoLineaModel;
use App\Models\Presupuestos\PresupuestoFicheroModel;
use Exception;
use phpseclib3\Net\SFTP;
class SafekatFtpClient
{
protected SFTP $ftp;
protected string $host;
protected int $port;
protected string $username;
protected string $password;
protected string $base_dir;
protected bool $xml_enabled;
protected object $pedido_xml_config;
public function __construct()
{
$this->pedido_xml_config = config("PedidoXML");
$this->host = $this->pedido_xml_config->host;
$this->username = $this->pedido_xml_config->username;
$this->password = $this->pedido_xml_config->password;
$this->port = $this->pedido_xml_config->port;
$this->base_dir = $this->pedido_xml_config->base_dir;
$this->xml_enabled = $this->pedido_xml_config->xml_enabled;
$this->ftp = new SFTP($this->host);
}
/**
* Upload the content of $filename to the base directory declared in App\Config\FTP.php
*
* @param string $content
* @param string $filename
* @return boolean
*/
public function uploadXML(string $content, string $filename): bool
{
try {
if ($this->xml_enabled == false) return false;
$remotePath = implode("/", [$this->base_dir,'pedidos','xml_nuevos']);
$this->ftp->login(username: $this->username, password: $this->password);
if(!$this->ftp->is_dir($remotePath)){
$this->ftp->mkdir($remotePath,recursive:true);
}
$this->ftp->put($remotePath.'/'.$filename, $content);
return true;
} catch (\Throwable $th) {
throw $th;
log_message('error', $th->getMessage());
return false;
}
}
public function uploadFilePresupuesto(int $presupuesto_id)
{
try {
$model = model(PresupuestoFicheroModel::class);
$modelPedidoLinea = model(PedidoLineaModel::class);
$pedidoLinea = $modelPedidoLinea->findByPresupuesto($presupuesto_id);
$rootIdExtern = 1e6 + $pedidoLinea->pedido_id;
$presupuestoFiles = $model->getFiles($presupuesto_id);
$this->ftp->login(username: $this->username, password: $this->password);
foreach ($presupuestoFiles as $key => $value) {
$filename = array_reverse(explode("/", $value->file_path))[0];
$remoteDir = implode("/", [$this->base_dir,"pedidos_files",$rootIdExtern]);
$remoteFile = implode("/", [$this->base_dir,"pedidos_files",$rootIdExtern,$filename]);
if(!$this->ftp->is_dir($remoteDir)){
$this->ftp->mkdir($remoteDir,recursive:true);
}
$this->ftp->put($remoteFile,$value->file_path,mode:$this->ftp::SOURCE_LOCAL_FILE);
}
} catch (Exception $e) {
log_message('error', $e->getMessage());
throw $e;
}
}
}

View File

@ -54,6 +54,76 @@ class FacturaLineaModel extends \App\Models\BaseModel {
return $builder;
}
public function getResourceResumenIVAsForPdf($factura_id = -1)
{
$builder = $this->db
->table($this->table . " t1")
->select(
"t1.iva,
ROUND(SUM(t1.base), 2) AS base,
ROUND(SUM(t1.total_iva), 2) AS total_iva,
ROUND(SUM(t1.total), 2) AS total"
)
->where("t1.factura_id", $factura_id)
->where("t1.deleted_at", null)
->groupBy('t1.iva')
->orderBy('t1.iva', 'ASC'); // Ordena por iva en forma ascendente
return $builder;
}
/**
* Get resource data for creating PDFs.
*
* @param string $search
*
* @return \CodeIgniter\Database\BaseBuilder
*/
public function getResourceForPdf($factura_id = -1)
{
$builder = $this->db
->table($this->table . " t1")
->select(
"t1.id AS id, t1.factura_id AS factura_id,
t1.pedido_linea_impresion_id AS pedido_linea_impresion_id, t1.pedido_maquetacion_id AS pedido_maquetacion_id,
t1.descripcion AS descripcion, t1.cantidad as cantidad, t1.precio_unidad AS precio_unidad, t1.iva AS iva,
t1.base AS base, t1.total_iva AS total_iva, t1.total AS total, t1.data AS data"
)
->where("t1.factura_id", $factura_id)
->where("t1.deleted_at", null);
return $builder;
}
/**
* Get resource data for creating PDFs.
*
* @param string $search
*
* @return \CodeIgniter\Database\BaseBuilder
*/
public function getResourceForExcel($factura_id = -1)
{
$builder = $this->db
->table($this->table . " t1")
->select(
"t2.numero AS ref_factura,
t3.pedido_id AS pedido_id,
t4.referencia_cliente AS referencia_cliente,
t1.base AS base"
)
->join("facturas t2", "t2.id = t1.factura_id", "left")
->join("pedidos_linea t3", "t3.id = t1.pedido_linea_impresion_id", "left")
->join("presupuestos t4", "t4.id = t3.presupuesto_id", "left")
->where("t1.factura_id", $factura_id)
->where("t1.deleted_at", null);
return $builder;
}
public function addFacturaPedidoLinea($factura_id, $pedido_linea_id, $cantidad)
{
$data = [

View File

@ -102,6 +102,41 @@ class FacturaModel extends \App\Models\BaseModel {
}
/**
* Get resource data for creating PDFs.
*
* @param string $search
*
* @return \CodeIgniter\Database\BaseBuilder
*/
public function getResourceForPdf($factura_id = -1)
{
$builder = $this->db
->table($this->table . " t1")
->select(
"t1.id AS id, t1.numero AS numero, DATE_FORMAT(t1.fecha_factura_at, '%d/%m/%Y') AS fecha_factura_at,
t1.base AS base, t1.total AS total, t1.pendiente AS pendiente,
t1.creditoAsegurado AS creditoAsegurado, t1.estado AS estado, t1.estado_pago AS estado_pago,
t4.nombre AS forma_pago,
DATE_FORMAT(MIN(CASE WHEN t3.fecha_vencimiento_at != '0000-00-00 00:00:00' THEN t3.fecha_vencimiento_at ELSE NULL END), '%d/%m/%Y') AS vencimiento,
t2.nombre AS cliente, t2.direccion AS cliente_direccion, t2.ciudad AS cliente_ciudad,
t2.cp AS cliente_cp, t2.cif AS cliente_cif, t2.vencimiento AS dias_vencimiento, t2.ccc AS cliente_ccc,
t5.nombre AS cliente_pais"
);
$builder->join("clientes t2", "t2.id = t1.cliente_id", "left");
$builder->join("facturas_pagos t3", "t3.factura_id = t1.id", "left");
$builder->join("formas_pago t4", "t3.forma_pago_id = t4.id", "left");
$builder->join("lg_paises t5", "t2.pais_id = t5.id", "left");
$builder->where("t1.id", $factura_id);
$builder->where("t1.deleted_at IS NULL");
$builder->groupBy("t1.id"); // Agrupa por id de la factura
return $builder;
}
public function getResourcePedidos($pedido_id)
{
$builder = $this->db

View File

@ -216,5 +216,10 @@ class PedidoLineaModel extends \App\Models\BaseModel
return $resultaArray;
}
public function findByPresupuesto(int $presupuestoId){
$builder = $this->db
->table($this->table)
->select();
return $builder->where('presupuesto_id',$presupuestoId)->get()->getFirstRow();
}
}

View File

@ -2,6 +2,8 @@
namespace App\Models\Pedidos;
use function PHPSTORM_META\map;
class PedidoModel extends \App\Models\BaseModel
{
protected $table = "pedidos";
@ -29,11 +31,11 @@ class PedidoModel extends \App\Models\BaseModel
];
protected $allowedFields = [
"total_precio",
"total_tirada",
"estado",
"user_created_id",
"user_updated_id",
"total_precio",
"total_tirada",
"estado",
"user_created_id",
"user_updated_id",
"user_validated_id",
"fecha_entrega_real",
"fecha_impresion",
@ -53,22 +55,25 @@ class PedidoModel extends \App\Models\BaseModel
public static $labelField = "id";
public function obtenerDatosForm($pedido_id){
public function obtenerDatosForm($pedido_id)
{
$builder = $this->db
->table($this->table . " t1")
->select(
"t4.id AS cliente_id, t4.nombre AS cliente, CONCAT(t5.first_name, ' ', t5.last_name) AS comercial");
"t4.id AS cliente_id, t4.nombre AS cliente, CONCAT(t5.first_name, ' ', t5.last_name) AS comercial"
);
$builder->join("pedidos_linea t2", "t2.pedido_id = t1.id", "left");
$builder->join("presupuestos t3", "t2.presupuesto_id = t3.id", "left");
$builder->join("pedidos_linea t2", "t2.pedido_id = t1.id", "left");
$builder->join("presupuestos t3", "t2.presupuesto_id = t3.id", "left");
$builder->join("clientes t4", "t4.id = t3.cliente_id", "left");
$builder->join("users t5", "t5.id = t4.comercial_id", "left");
return $builder->get()->getResultObject();
}
public function obtenerLineasPedido($pedido_id){
public function obtenerLineasPedido($pedido_id)
{
$builder = $this->db
->table($this->table . " t1")
->select(
@ -79,10 +84,116 @@ class PedidoModel extends \App\Models\BaseModel
$model_presupuesto = model("App\Models\Presupuestos\PresupuestoModel");
$lineasPresupuesto = [];
foreach($builder->get()->getResultObject() as $row){
foreach ($builder->get()->getResultObject() as $row) {
array_push($lineasPresupuesto, $model_presupuesto->generarLineaPedido($row->presupuesto_id)[0]);
}
return $lineasPresupuesto;
}
}
public function getPedidoPresupuestoTipoImpresion(int $presupuesto_id) : array|object|null
{
$q = $this->db->table($this->table)
->select(
[
'tipos_presupuesto.codigo',
'presupuestos.solapas'
]
)
->join('tipos_presupuestos', 'tipos_presupuestos.id = presupuestos.tipo_impresion_id', 'left')
->where('presupuestos.id', $presupuesto_id);
return $q->get()->getFirstRow();
}
public function getPedidoClientePresupuesto(int $pedido_id)
{
$query = $this->db->table($this->table)
->select([
'pedidos.id as pedidoId',
'clientes.nombre as customerName',
'presupuestos.total_aceptado as totalAceptado',
'presupuestos.id as presupuestoId',
'presupuestos.cliente_id as presupuestoClienteId',
'presupuestos.margen',
'presupuestos.inc_rei',
'presupuestos.tirada',
'presupuestos.tirada',
'presupuestos.titulo',
'presupuestos.paginas',
'presupuestos.solapas',
'presupuestos.solapas_ancho',
'presupuestos.marcapaginas',
'presupuestos.comentarios_cliente',
'presupuestos.comentarios_safekat',
'presupuestos.papel_formato_personalizado',
'presupuestos.papel_formato_ancho as papelAnchoPersonalidado ',
'presupuestos.papel_formato_alto as papelAltoPersonalidado',
'tipos_presupuestos.codigo as codigoTipoImpresion',
'lg_papel_formato.ancho as lgPapelFormatoAncho ',
'lg_papel_formato.alto as lgPapelFormatoAlto',
])
->join('pedidos_linea', 'pedidos_linea.id = pedidos.id', 'left')
->join('presupuestos', 'presupuestos.id = pedidos_linea.presupuesto_id', 'left')
->join('presupuesto_ficheros', 'presupuesto_ficheros.presupuesto_id = presupuestos.id', 'left')
->join('tipos_presupuestos', 'tipos_presupuestos.id = presupuestos.tipo_impresion_id', 'left')
// ->join('presupuesto_linea','presupuestos.id = presupuesto_linea.presupuesto_id','left')
->join('clientes', 'clientes.id = presupuestos.cliente_id', 'left')
->join('lg_papel_formato', 'lg_papel_formato.id = presupuestos.papel_formato_id', 'left')
->where('pedidos.id', $pedido_id);
$cliente_presupuesto = $query->get()->getFirstRow();
return $cliente_presupuesto;
}
public function getPedidoPresupuestoLineas(int $pedido_id)
{
$query = $this->db->table($this->table)
->select([
'pedidos.id as pedidoId',
'presupuesto_linea.tipo',
'presupuesto_linea.paginas',
'presupuesto_linea.gramaje',
'lg_papel_generico.code as papelCode',
])
->join('pedidos_linea', 'pedidos_linea.id = pedidos.id', 'left')
->join('presupuestos', 'presupuestos.id = pedidos_linea.presupuesto_id', 'left')
->join('presupuesto_linea', 'presupuestos.id = presupuesto_linea.presupuesto_id', 'left')
->join('lg_papel_generico', 'lg_papel_generico.id = presupuesto_linea.papel_id', 'left')
->where('pedidos.id', $pedido_id);
$pedido_presupuesto_lineas = $query->get()->getResultObject();
return $pedido_presupuesto_lineas;
}
public function getPedidoPresupuestoDirecciones($pedido_id)
{
$query = $this->db->table($this->table)
->select([
'pedidos.id as pedidoId',
'presupuestos.id as presupuestoId',
'clientes.nombre as customerName',
'presupuesto_direcciones.*',
'lg_paises.code3 as paisCode3'
])
->join('pedidos_linea', 'pedidos_linea.id = pedidos.id', 'left')
->join('presupuestos', 'presupuestos.id = pedidos_linea.presupuesto_id', 'left')
->join('presupuesto_direcciones', 'presupuestos.id = presupuesto_direcciones.presupuesto_id', 'left')
->join('clientes', 'clientes.id = presupuestos.cliente_id', 'left')
->join('cliente_direcciones', 'clientes.id = cliente_direcciones.cliente_id', 'left')
->join('lg_paises', 'lg_paises.id = presupuesto_direcciones.pais_id', 'left')
->where('pedidos.id', $pedido_id);
$pedido_cliente_direcciones = $query->get()->getResultObject();
return $pedido_cliente_direcciones;
}
public function getPedidoPresupuestoFicheros($pedido_id)
{
$query = $this->db->table($this->table)
->select([
'presupuesto_ficheros.nombre as fileName',
'presupuesto_ficheros.file_path as filePath'
])
->join('pedidos_linea', 'pedidos_linea.id = pedidos.id', 'left')
->join('presupuestos', 'presupuestos.id = pedidos_linea.presupuesto_id', 'left')
->join('presupuesto_ficheros', 'presupuesto_ficheros.presupuesto_id = presupuestos.id', 'left')
->where('pedidos.id', $pedido_id);
$presupuesto_ficheros = $query->get()->getFirstRow();
return $presupuesto_ficheros;
}
}

View File

@ -17,11 +17,12 @@ class PresupuestoAcabadosModel extends \App\Models\BaseModel
const SORTABLE = [
0 => "t2.nombre",
1 => "t1.precio_unidad",
2 => "t1.precio_total"
1 => "t1.proveedor_id",
2 => "t1.precio_unidad",
3 => "t1.precio_total"
];
protected $allowedFields = ["presupuesto_id", "tarifa_acabado_id", "nombre", "precio_total", "precio_unidad", "margen", "cubierta", "sobrecubierta"];
protected $allowedFields = ["presupuesto_id", "tarifa_acabado_id", "proveedor_id", "nombre", "precio_total", "precio_unidad", "margen", "cubierta", "sobrecubierta"];
protected $returnType = "App\Entities\Presupuestos\PresupuestoAcabadosEntity";
protected $useTimestamps = true;
@ -46,10 +47,29 @@ class PresupuestoAcabadosModel extends \App\Models\BaseModel
],
];
public function getPrecioTarifa($tarifa_acabado_id, $tirada, $POD){
public function getProveedoresForSelector($tarifa_acabado_id, $tirada){
$proveedores = [];
$modelTarifa = model('App\Models\Tarifas\Acabados\TarifaAcabadoModel');
$tarifa_value = $modelTarifa->getTarifaPresupuestoAcabado($tarifa_acabado_id, $tirada);
if (count($tarifa_value)>0) {
foreach($tarifa_value as $tarifa)
array_push($proveedores,
(object)[
'id'=> $tarifa->proveedor_id,
'text'=> $tarifa->proveedor_nombre,
]);
}
return $proveedores;
}
public function getPrecioTarifa($tarifa_acabado_id, $tirada, $proveedor_id, $POD){
$modelTarifa = model('App\Models\Tarifas\Acabados\TarifaAcabadoModel');
$tarifa_value = $modelTarifa->getTarifaPresupuestoAcabado($tarifa_acabado_id, $tirada);
$tarifa_value = $modelTarifa->getTarifaPresupuestoAcabado($tarifa_acabado_id, $tirada, $proveedor_id);
if (count($tarifa_value)>0) {
$result_data = $this->calcularTarifa($tarifa_value[0], $tirada, $POD<$tirada?false:true);
@ -59,6 +79,8 @@ class PresupuestoAcabadosModel extends \App\Models\BaseModel
'precio_unidad'=> $result_data[0],
'total'=> $result_data[1],
'margen'=> $result_data[2],
'proveedor' => $tarifa_value[0]->proveedor_nombre,
'proveedor_id' => $tarifa_value[0]->proveedor_id,
];
return $ret_array;
}
@ -119,6 +141,8 @@ class PresupuestoAcabadosModel extends \App\Models\BaseModel
foreach($tarifas as $tarifa){
$proveedor = $tarifa->proveedor_id=='undefined'?'NULL':$tarifa->proveedor_id;
$builder = $this->db
->table($this->table . " t1");
$builder->select("id");
@ -132,6 +156,7 @@ class PresupuestoAcabadosModel extends \App\Models\BaseModel
->table($this->table . " t1")
->where('presupuesto_id', $presupuesto_id)
->where('tarifa_acabado_id', $tarifa->tarifa_id)
->set('proveedor_id', $proveedor)
->set('precio_unidad', $tarifa->precio_unidad)
->set('precio_total', $tarifa->precio_total)
->set('margen', $tarifa->margen)
@ -146,6 +171,7 @@ class PresupuestoAcabadosModel extends \App\Models\BaseModel
->table($this->table . " t1")
->set('presupuesto_id', $presupuesto_id)
->set('tarifa_acabado_id', $tarifa->tarifa_id)
->set('proveedor_id', $proveedor, false)
->set('precio_unidad', $tarifa->precio_unidad)
->set('precio_total', $tarifa->precio_total)
->set('margen', $tarifa->margen)
@ -169,11 +195,13 @@ class PresupuestoAcabadosModel extends \App\Models\BaseModel
->table($this->table . " t1")
->select(
"t1.id AS id, t1.tarifa_acabado_id AS tarifa_acabado_id, t1.precio_unidad AS precio_unidad,
t1.precio_total AS precio_total, t1.margen AS margen, t2.nombre AS nombre, t1.cubierta AS cubierta, t1.sobrecubierta AS sobrecubierta"
t1.precio_total AS precio_total, t1.margen AS margen, t2.nombre AS nombre, t1.cubierta AS cubierta, t1.sobrecubierta AS sobrecubierta,
t1.proveedor_id AS proveedor_id, t3.nombre AS proveedor,"
);
$builder->where('t1.presupuesto_id', $presupuesto_id);
$builder->join("lg_tarifa_acabado t2", "t1.tarifa_acabado_id = t2.id", "left");
$builder->join("lg_proveedores t3", "t1.proveedor_id = t3.id", "left");
return $builder;
}

View File

@ -21,7 +21,7 @@ class PresupuestoEncuadernacionesModel extends \App\Models\BaseModel
4 => "t1.precio_total"
];
protected $allowedFields = ["presupuesto_id", "tarifa_encuadernado_id", "proveedor_id", "nombre", "precio_total", "precio_unidad", "tiempo", "margen"];
protected $allowedFields = ["presupuesto_id", "tarifa_encuadernado_id", "proveedor_id", "nombre", "precio_total", "precio_unidad", "paginas_por_cuadernillo", "tiempo", "margen"];
protected $returnType = "App\Entities\Presupuestos\PresupuestoEncuadernacionesEntity";
protected $useTimestamps = true;
@ -48,7 +48,7 @@ class PresupuestoEncuadernacionesModel extends \App\Models\BaseModel
public function initPresupuesto($tipo_presupuesto, $solapas, $tirada, $paginas, $ancho, $alto, $POD){
public function initPresupuesto($tipo_presupuesto, $solapas, $tirada, $paginas, $ancho, $alto, $POD, $paginasCuadernillo = 32){
$model = model('App\Models\Presupuestos\TipoPresupuestoServiciosDefectoModel');
$tarifas_procesar = $model->get_tarifas($tipo_presupuesto, $solapas, "encuadernacion");
@ -60,7 +60,12 @@ class PresupuestoEncuadernacionesModel extends \App\Models\BaseModel
if($modelTarifa->isTarifaPorHoras($tarifa['tarifa_id'])){
$tiempo = $this->calcularTiempo(16, $paginas, $tirada); // ID fija. Cambiar cuando se metan maquinas de corte. Velocidad en minutos
if($tarifa['tarifa_id'] == 2 || $tarifa['tarifa_id'] == 14){ // Rústica cosido hilo vegetal y Rústica cosido hilo vegetal solapas
$tiempo = $this->calcularTiempoCosido(16, $paginas, $tirada, $paginasCuadernillo); // ID fija. Cambiar cuando se metan maquinas de corte. Velocidad en minutos
}
else{
$tiempo = $this->calcularTiempo(16, $paginas, $tirada); // ID fija. Cambiar cuando se metan maquinas de corte. Velocidad en minutos
}
$tarifa_value = $modelTarifa->getTarifaPresupuestoEncuadernacionHoras($tarifa['tarifa_id'], $tiempo, $tirada);
if (count($tarifa_value)>0) {
@ -76,8 +81,7 @@ class PresupuestoEncuadernacionesModel extends \App\Models\BaseModel
$result_data[1] = $precio_total;
$result_data[2] = $tarifa_proveedor->margen ; // margen
array_push($result_array,
(object)[
$datos = [
'tarifa_id'=> $tarifa['tarifa_id'],
'tarifa_nombre'=> $tarifa_proveedor->tarifa_enc_nombre,
'precio_unidad'=> $result_data[0],
@ -86,7 +90,14 @@ class PresupuestoEncuadernacionesModel extends \App\Models\BaseModel
'margen' => $result_data[2],
'proveedor' => $tarifa_proveedor->proveedor_nombre,
'proveedor_id' => $tarifa_proveedor->proveedor_id,
]);
];
if($tarifa['tarifa_id'] == 2 || $tarifa['tarifa_id'] == 14){
$datos['paginas_por_cuadernillo'] = $paginasCuadernillo;
}
array_push($result_array,
(object)$datos);
}
usort($result_array, function($a, $b) {
@ -237,11 +248,16 @@ class PresupuestoEncuadernacionesModel extends \App\Models\BaseModel
return [];
}
public function getPrecioTarifaHoras($tarifa_encuadernacion_id, $paginas, $tirada, $proveedor_id, $POD){
public function getPrecioTarifaHoras($tarifa_encuadernacion_id, $paginas, $tirada, $proveedor_id, $POD, $paginas_cuadernillo = null){
$modelTarifa = model('App\Models\Tarifas\TarifaEncuadernacionModel');
$tiempo = $this->calcularTiempo(16, $paginas, $tirada); // ID fija. Cambiar cuando se metan maquinas de corte. Velocidad en minutos
if($tarifa_encuadernacion_id == 2 || $tarifa_encuadernacion_id == 14){ // Rústica cosido hilo vegetal y Rústica cosido hilo vegetal solapas
$tiempo = $this->calcularTiempoCosido(16, $paginas, $tirada, $paginas_cuadernillo); // ID fija. Cambiar cuando se metan maquinas de corte. Velocidad en minutos
}
else{
$tiempo = $this->calcularTiempo(16, $paginas, $tirada); // ID fija. Cambiar cuando se metan maquinas de corte. Velocidad en minutos
}
$tarifa_value = $modelTarifa->getTarifaPresupuestoEncuadernacionHoras($tarifa_encuadernacion_id, $tiempo, $tirada, $proveedor_id);
if (count($tarifa_value)>0) {
@ -256,6 +272,7 @@ class PresupuestoEncuadernacionesModel extends \App\Models\BaseModel
$result_data[0] = floatval($precio_total / $tirada); // Precio/unidad
$result_data[1] = $precio_total;
$result_data[2] = $tarifa_proveedor->margen ; // margen
array_push($ret_array,
(object)[
@ -263,6 +280,7 @@ class PresupuestoEncuadernacionesModel extends \App\Models\BaseModel
'tarifa_nombre'=> $tarifa_proveedor->tarifa_enc_nombre,
'precio_unidad'=> $result_data[0],
'tiempo' => $tiempo,
'paginas_por_cuadernillo' => $paginas_cuadernillo,
'total'=> $result_data[1],
'margen' => $result_data[2],
'proveedor' => $tarifa_proveedor->proveedor_nombre,
@ -287,6 +305,7 @@ class PresupuestoEncuadernacionesModel extends \App\Models\BaseModel
'proveedor' => lang('Presupuestos.no_disponible'),
'precio_unidad'=> 0,
'tiempo' => null,
'paginas_por_cuadernillo' => null,
'total'=> 0,
'margen' => 0,
];
@ -355,6 +374,7 @@ class PresupuestoEncuadernacionesModel extends \App\Models\BaseModel
$builder->where('presupuesto_id', $presupuesto_id);
$builder->where('tarifa_encuadernado_id', $tarifa->tarifa_id);
$result = $builder->get()->getResultObject();
$paginas_cuadernillo = $tarifa->paginas_por_cuadernillo??null;
if(count($result)>0){
$this->db
->table($this->table . " t1")
@ -365,6 +385,7 @@ class PresupuestoEncuadernacionesModel extends \App\Models\BaseModel
->set('tiempo', $tarifa->tiempo)
->set('precio_total', $tarifa->precio_total)
->set('margen', $tarifa->margen)
->set('paginas_por_cuadernillo', $paginas_cuadernillo)
->update();
@ -397,7 +418,8 @@ class PresupuestoEncuadernacionesModel extends \App\Models\BaseModel
->table($this->table . " t1")
->select(
"t1.id AS id, t1.tarifa_encuadernado_id AS tarifa_encuadernado_id, t1.precio_unidad AS precio_unidad, t1.tiempo AS tiempo,
t1.precio_total AS precio_total, t1.margen AS margen, t2.nombre AS nombre, t1.proveedor_id AS proveedor_id, t3.nombre AS proveedor"
t1.precio_total AS precio_total, t1.margen AS margen, t2.nombre AS nombre, t1.proveedor_id AS proveedor_id, t3.nombre AS proveedor,
t1.paginas_por_cuadernillo AS paginas_por_cuadernillo"
);
$builder->where('t1.presupuesto_id', $presupuesto_id);
@ -415,4 +437,13 @@ class PresupuestoEncuadernacionesModel extends \App\Models\BaseModel
$velocidad = $maquinaModel->getVelocidad($maquina_id);
return round($cuadernillos_pedido/($velocidad*60.0), 2);
}
private function calcularTiempoCosido($maquina_id, $paginas, $tirada, $cuadernillos_por_pagina = 32){
$maquinaModel = model("App\Models\Configuracion\MaquinaModel");
$velocidad = $maquinaModel->getVelocidad($maquina_id); // cuadernillos por minuto
$cuadernillos_libro = ceil($paginas/intval($cuadernillos_por_pagina));
$cuadernillos_pedido = $cuadernillos_libro*$tirada;
return round($cuadernillos_pedido/($velocidad*60.0), 2); // tiempo en segundos
}
}

View File

@ -162,7 +162,7 @@ class PresupuestoModel extends \App\Models\BaseModel
],
"pais_id" => [
"label" => "Presupuestos.paisId",
"rules" => "required|integer|greater_than[0]",
"rules" => "integer",
],
"cliente_id" => [
"label" => "Presupuestos.clienteId",
@ -326,7 +326,8 @@ class PresupuestoModel extends \App\Models\BaseModel
return $builder;
}
function getListaPresupuestosCliente($search = [] , $clienteId){
function getListaPresupuestosCliente($search = [], $clienteId)
{
$builder = $this->db
->table($this->table . " t1")
@ -343,7 +344,7 @@ class PresupuestoModel extends \App\Models\BaseModel
$builder->join("presupuesto_estados t6", "t1.estado_id = t6.id", "left");
$builder->join("tipos_presupuestos t7", "t1.tipo_impresion_id = t7.id", "left");
if($clienteId != 0)
if ($clienteId != 0)
$builder->where("t1.cliente_id", $clienteId);
$builder->where("t1.is_deleted", 0);
@ -363,7 +364,7 @@ class PresupuestoModel extends \App\Models\BaseModel
}
$builder->groupEnd();
return $builder;
}
}
}
function confirmarPresupuesto($presupuesto_id)
@ -377,16 +378,16 @@ class PresupuestoModel extends \App\Models\BaseModel
function insertarPresupuestoCliente($id, $tirada, $data, $data_cabecera, $extra_info, $resumen_totales, $iva_reducido, $excluir_rotativa, $tiradas_alternativas)
{
helper('date');
$model = model('App\Models\Configuracion\PapelFormatoModel');
$papel_formato_id = $model->where('ancho', $data['tamanio']['ancho'])->where('alto', $data['tamanio']['alto'])->first();
$is_cosido = (new TipoPresupuestoModel())->get_isCosido($data['tipo_impresion_id']);
$totalCostes = $resumen_totales['totalPapel'] + $resumen_totales['totalImpresion'] +
$resumen_totales['totalServicios']+$resumen_totales['coste_envio'];
$totalCostes = $resumen_totales['totalPapel'] + $resumen_totales['totalImpresion'] +
$resumen_totales['totalServicios'] + $resumen_totales['coste_envio'];
$totalMargenes = $resumen_totales['margenPapel'] + $resumen_totales['margenImpresion'] +
$resumen_totales['margenServicios'] + $resumen_totales['margen_envio'];
@ -400,22 +401,22 @@ class PresupuestoModel extends \App\Models\BaseModel
'faja_color' => in_array(16, $data['servicios']) ? 1 : 0,
'ferro' => in_array(24, $data['servicios']) ? 1 : 0,
'prototipo' => in_array(9, $data['servicios']) ? 1 : 0,
'papel_formato_id' => is_null($papel_formato_id) ? 0: $papel_formato_id->id,
'papel_formato_personalizado' => !$papel_formato_id ? 1:0,
'papel_formato_ancho' => !$papel_formato_id ? $data['tamanio']['ancho']:null,
'papel_formato_alto' => !$papel_formato_id ? $data['tamanio']['alto']:null,
'papel_formato_id' => is_null($papel_formato_id) ? 0 : $papel_formato_id->id,
'papel_formato_personalizado' => !$papel_formato_id ? 1 : 0,
'papel_formato_ancho' => !$papel_formato_id ? $data['tamanio']['ancho'] : null,
'papel_formato_alto' => !$papel_formato_id ? $data['tamanio']['alto'] : null,
'titulo' => $data_cabecera['titulo'],
'referencia_cliente' => $data_cabecera['referenciaCliente'],
'paginas' => $data['interior']['paginas'],
'tirada' => $tirada,
'solapas' => $data['cubierta']['solapasCubierta']>0 ? 1 : 0,
'solapas_ancho' => $data['cubierta']['solapasCubierta']>0 ? $data['cubierta']['solapasCubierta'] : 0,
'solapas_sobrecubierta' => is_null($data['sobrecubierta']) ? 0 :1,
'solapas' => $data['cubierta']['solapasCubierta'] > 0 ? 1 : 0,
'solapas_ancho' => $data['cubierta']['solapasCubierta'] > 0 ? $data['cubierta']['solapasCubierta'] : 0,
'solapas_sobrecubierta' => is_null($data['sobrecubierta']) ? 0 : 1,
'solapas_ancho_sobrecubierta' => is_null($data['sobrecubierta']) ? 0 : $data['sobrecubierta']['solapas'],
'cosido' => $is_cosido,
'merma' => $extra_info['merma'],
'merma_cubierta' => $extra_info['merma'],
'lomo_cubierta' => $extra_info['lomo_cubierta'],
'lomo_sobrecubierta' => $extra_info['lomo_sobrecubierta'],
@ -424,12 +425,12 @@ class PresupuestoModel extends \App\Models\BaseModel
'acabado_cubierta_id' => $data['acabadoCubierta'],
'acabado_sobrecubierta_id' => is_null($data['sobrecubierta']) ? 0 : $data['sobrecubierta']['acabado'],
'comp_tipo_impresion' => $data['isHq']? ($data['isColor']? 'colorhq':'negrohq'):($data['isColor']? 'color':'negro'),
'comp_tipo_impresion' => $data['isHq'] ? ($data['isColor'] ? 'colorhq' : 'negrohq') : ($data['isColor'] ? 'color' : 'negro'),
'user_created_id' => $extra_info['user_id'],
'created_at' => date('Y-m-d H:i:s', now()),
'updated_at' => date('Y-m-d H:i:s', now()),
'tirada_alternativa_json_data' => json_encode($tiradas_alternativas),
'total_coste_papel' => round($resumen_totales['totalPapel'], 2),
@ -445,32 +446,31 @@ class PresupuestoModel extends \App\Models\BaseModel
'total_margen_envios' => round($resumen_totales['margen_envio'], 2),
'total_costes' => round($totalCostes, 2),
'total_margenes' => round($totalMargenes, 2),
'total_antes_descuento' => round($totalCostes + $totalMargenes, 2),
'total_descuento' => 0,
'total_descuentoPercent' => 0,
'total_precio_unidad' => round(($totalCostes + $totalMargenes)/$tirada, 4),
'total_presupuesto' => round($totalCostes + $totalMargenes, 2),
'total_aceptado' => round($totalCostes + $totalMargenes, 2),
'total_precio_unidad' => round(($totalCostes + $totalMargenes) / $tirada, 4),
'total_presupuesto' => round($totalCostes + $totalMargenes, 2),
'total_aceptado' => round($totalCostes + $totalMargenes, 2),
'total_factor' => round(($totalCostes + $totalMargenes-$resumen_totales['coste_envio']-$resumen_totales['margen_envio'])/$resumen_totales['sumForFactor'], 2),
'total_factor_ponderado' => round(($totalCostes + $totalMargenes-$resumen_totales['coste_envio']-$resumen_totales['margen_envio'])/$resumen_totales['sumForFactorPonderado'], 2),
'total_factor' => round(($totalCostes + $totalMargenes - $resumen_totales['coste_envio'] - $resumen_totales['margen_envio']) / $resumen_totales['sumForFactor'], 2),
'total_factor_ponderado' => round(($totalCostes + $totalMargenes - $resumen_totales['coste_envio'] - $resumen_totales['margen_envio']) / $resumen_totales['sumForFactorPonderado'], 2),
'iva_reducido' => $iva_reducido,
'excluir_rotativa' => $excluir_rotativa,
];
if($id != 0){
if ($id != 0) {
$fields['id'] = $id;
$fields['updated_at'] = date('Y-m-d H:i:s', now());
}
if($id != 0){
if ($id != 0) {
$this->db->table($this->table)->where('id', $id)->update($fields);
return $id;
}
else{
} else {
$this->db->table($this->table)->insert($fields);
return $this->db->insertID();
}
@ -482,27 +482,27 @@ class PresupuestoModel extends \App\Models\BaseModel
if (is_array($data)) {
// -- INTERIOR --
// Si hay negro
if($data['interior']['paginas'] > $data['interior']['paginas_color']){
if ($data['interior']['paginas'] > $data['interior']['paginas_color']) {
if($data['isHq'])
if ($data['isHq'])
$key = 'bnhq';
else
$key = 'bn';
$values[$key] = array(
'paginas'=> intval($data['interior']['paginas'])-intval($data['interior']['paginas_color']),
'paginas' => intval($data['interior']['paginas']) - intval($data['interior']['paginas_color']),
'papel_id' => intval($data['interior']['papel_generico']['id']),
'gramaje' => intval($data['interior']['gramaje']),
);
}
// Si hay color
if($data['interior']['paginas_color']>0){
// Si hay color
if ($data['interior']['paginas_color'] > 0) {
if($data['isHq'])
if ($data['isHq'])
$key = 'colorhq';
else
$key = 'color';
$values[$key] = array(
'paginas'=> intval($data['interior']['paginas_color']),
'paginas' => intval($data['interior']['paginas_color']),
'papel_id' => intval($data['interior']['papel_generico']['id']),
'gramaje' => intval($data['interior']['gramaje']),
);
@ -516,7 +516,7 @@ class PresupuestoModel extends \App\Models\BaseModel
);
// -- SOBRECUBIERTA --
if(!is_null($data['sobrecubierta'])){
if (!is_null($data['sobrecubierta'])) {
$values['sobrecubierta'] = array(
'papel_id' => intval($data['sobrecubierta']['papel']),
'gramaje' => intval($data['sobrecubierta']['gramaje']),
@ -525,14 +525,13 @@ class PresupuestoModel extends \App\Models\BaseModel
}
// -- GUARDAS --
if($data['datos_guardas'] != 0){
if ($data['datos_guardas'] != 0) {
$values['guardas'] = array(
'papel_id' => intval($data['datos_guardas']['papel']),
'gramaje' => intval($data['datos_guardas']['gramaje']),
'paginas' => intval($data['datos_guardas']['caras']),
);
}
}
$json = json_encode($values);
return $json;
@ -557,32 +556,33 @@ class PresupuestoModel extends \App\Models\BaseModel
$builder->where("t1.is_deleted", 0);
$builder->where("t1.id", $presupuesto_id);
$presupuesto = $builder->get()->getResultObject();
if(count($presupuesto) > 0){
if (count($presupuesto) > 0) {
$modelLinea = model('App\Models\Presupuestos\PresupuestoLineaModel');
$lineas = $modelLinea->where('presupuesto_id', $presupuesto_id)->findAll();
$lineas = $modelLinea->where('presupuesto_id', $presupuesto_id)->findAll();
$presupuesto = $presupuesto[0];
// Libro
if($presupuesto->tipo < 10 || $presupuesto->tipo==20 || $presupuesto->tipo==21){
if($presupuesto->papel_formato_personalizado == 1){
$presupuesto->tamanio= $presupuesto->papel_formato_ancho . "x" . $presupuesto->papel_formato_alto;
if ($presupuesto->tipo < 10 || $presupuesto->tipo == 20 || $presupuesto->tipo == 21) {
if ($presupuesto->papel_formato_personalizado == 1) {
$presupuesto->tamanio = $presupuesto->papel_formato_ancho . "x" . $presupuesto->papel_formato_alto;
}
if($forFactura){
if ($forFactura) {
$presupuesto->concepto = sprintf(lang('Pedidos.lineasTemplates.pedido'), $pedido_id);
}
else{
} else {
$presupuesto->concepto = sprintf(lang('Pedidos.lineasTemplates.presupuesto'), $presupuesto->numero);
}
$presupuesto->concepto .= sprintf(lang('Pedidos.lineasTemplates.libro'),
$presupuesto->concepto .= sprintf(
lang('Pedidos.lineasTemplates.libro'),
$presupuesto->unidades,
$presupuesto->paginas,
$presupuesto->titulo,
$presupuesto->autor,
$presupuesto->isbn,
$presupuesto->tamanio);
$presupuesto->tamanio
);
$presupuesto->concepto .= $this->generarConceptoLineasPresupuestoLibro($lineas, $presupuesto);
$presupuesto = (object)[
@ -594,10 +594,67 @@ class PresupuestoModel extends \App\Models\BaseModel
}
return [$presupuesto];
}
}
public function getServiciosPresupuesto($presupuesto_id)
{
$queryAcabado = $this->db->table($this->table)
->select(
[
'lg_tarifa_acabado.id',
'lg_tarifa_acabado.nombre',
private function generarConceptoLineasPresupuestoLibro($lineas, $presupuesto){
]
)
->join('presupuesto_acabados', 'presupuesto_acabados.presupuesto_id = presupuestos.id', 'left')
->join('lg_tarifa_acabado', 'lg_tarifa_acabado.id = presupuesto_acabados.tarifa_acabado_id', 'left')
->where('presupuestos.id', $presupuesto_id);
$queryPreimpresion = $this->db->table($this->table)
->select(
[
'lg_tarifa_preimpresion.id',
'lg_tarifa_preimpresion.nombre',
'lg_tarifa_preimpresion.precio',
]
)
->join('presupuesto_preimpresiones', 'presupuesto_preimpresiones.presupuesto_id = presupuestos.id', 'left')
->join('lg_tarifa_preimpresion', 'lg_tarifa_preimpresion.id = presupuesto_preimpresiones.tarifa_preimpresion_id', 'left')
->where('presupuestos.id', $presupuesto_id);
$queryManipulado = $this->db->table($this->table)
->select(
[
'lg_tarifa_manipulado.id',
'lg_tarifa_manipulado.nombre',
]
)
->join('presupuesto_manipulados', 'presupuesto_manipulados.presupuesto_id = presupuestos.id', 'left')
->join('lg_tarifa_manipulado', 'lg_tarifa_manipulado.id = presupuesto_manipulados.tarifa_manipulado_id', 'left')
->where('presupuestos.id', $presupuesto_id);
$queryExtras = $this->db->table($this->table)
->select(
[
'lg_tarifa_preimpresion.id',
'lg_tarifa_preimpresion.nombre',
]
)
->join('presupuesto_serviciosExtra', 'presupuesto_serviciosExtra.presupuesto_id = presupuestos.id', 'left')
->join('lg_tarifa_preimpresion', 'lg_tarifa_preimpresion.id = presupuesto_serviciosExtra.tarifa_extra_id', 'left')
->where('presupuestos.id', $presupuesto_id);
$servicios['acabado'] = $queryAcabado->get()->getResultObject();
$servicios['manipulado'] = $queryManipulado->get()->getResultObject();
$servicios['preimpresion'] = $queryPreimpresion->get()->getResultObject();
$servicios['extra'] = $queryExtras->get()->getResultObject();
return $servicios;
}
private function generarConceptoLineasPresupuestoLibro($lineas, $presupuesto)
{
$model_papel = model('App\Models\Configuracion\PapelImpresionModel');
$description_interior = "";
@ -610,105 +667,118 @@ class PresupuestoModel extends \App\Models\BaseModel
$gramaje_negro = 0;
$gramaje_color = 0;
$lp_bn_lines = array_filter($lineas, function($linea) {
$lp_bn_lines = array_filter($lineas, function ($linea) {
return strpos($linea->tipo, 'lp_bn') === 0;
});
$lp_color_lines = array_filter($lineas, function($linea) {
$lp_color_lines = array_filter($lineas, function ($linea) {
return strpos($linea->tipo, 'lp_color') === 0;
});
$lp_rot_bn = array_filter($lineas, function($linea) {
$lp_rot_bn = array_filter($lineas, function ($linea) {
return strpos($linea->tipo, 'lp_rot_bn') === 0;
});
$lp_rot_color = array_filter($lineas, function($linea) {
$lp_rot_color = array_filter($lineas, function ($linea) {
return strpos($linea->tipo, 'lp_rot_color') === 0;
});
if(count($lp_bn_lines) > 0){
if (count($lp_bn_lines) > 0) {
$lp_bn_lines = array_values($lp_bn_lines)[0];
$paginas_negro = $lp_bn_lines->paginas;
$gramaje_negro = $lp_bn_lines->gramaje;
$papel_negro = $model_papel->where('id', $lp_bn_lines->papel_impresion_id)->first()->nombre;
$description_interior .= sprintf(lang('Pedidos.lineasTemplates.libro_linea_interior'),
$papel_negro = $model_papel->where('id', $lp_bn_lines->papel_impresion_id)->first()->nombre;
$description_interior .= sprintf(
lang('Pedidos.lineasTemplates.libro_linea_interior'),
strval($paginas_negro),
$papel_negro,
strval($gramaje_negro)) . ". ";
strval($gramaje_negro)
) . ". ";
}
if(count($lp_color_lines) > 0){
if (count($lp_color_lines) > 0) {
$lp_color_lines = array_values($lp_color_lines)[0];
$paginas_color = $lp_color_lines->paginas;
$gramaje_color = $lp_color_lines->gramaje;
$papel_color = $model_papel->where('id', $lp_color_lines->papel_impresion_id)->first()->nombre;
$description_interior .= sprintf(lang('Pedidos.lineasTemplates.libro_linea_interior'),
$papel_color = $model_papel->where('id', $lp_color_lines->papel_impresion_id)->first()->nombre;
$description_interior .= sprintf(
lang('Pedidos.lineasTemplates.libro_linea_interior'),
strval($paginas_color),
$papel_color,
strval($gramaje_color)) . ". ";
strval($gramaje_color)
) . ". ";
}
if(count($lp_rot_bn) > 0){
if (count($lp_rot_bn) > 0) {
$lp_rot_bn = array_values($lp_rot_bn)[0];
$paginas_negro = $lp_rot_bn->paginas;
$gramaje_negro = $lp_rot_bn->gramaje;
$papel_negro = $model_papel->where('id', $lp_rot_bn->papel_impresion_id)->first()->nombre;
$description_interior .= sprintf(lang('Pedidos.lineasTemplates.libro_linea_interior'),
$papel_negro = $model_papel->where('id', $lp_rot_bn->papel_impresion_id)->first()->nombre;
$description_interior .= sprintf(
lang('Pedidos.lineasTemplates.libro_linea_interior'),
strval($paginas_negro),
$papel_negro,
strval($gramaje_negro)) . ". ";
strval($gramaje_negro)
) . ". ";
}
if(count($lp_rot_color) > 0){
if (count($lp_rot_color) > 0) {
$lp_rot_color = array_values($lp_rot_color)[0];
$paginas_negro = intval($lp_rot_color->paginas)-intval($lp_rot_color->rotativa_pag_color);
$paginas_negro = intval($lp_rot_color->paginas) - intval($lp_rot_color->rotativa_pag_color);
$gramaje = $lp_rot_color->gramaje;
$papel = $model_papel->where('id', $lp_rot_color->papel_impresion_id)->first()->nombre;
if($paginas_negro > 0){
$description_interior .= sprintf(lang('Pedidos.lineasTemplates.libro_linea_interior'),
strval($paginas_negro),
$papel,
strval($gramaje)) . ". ";
$papel = $model_papel->where('id', $lp_rot_color->papel_impresion_id)->first()->nombre;
if ($paginas_negro > 0) {
$description_interior .= sprintf(
lang('Pedidos.lineasTemplates.libro_linea_interior'),
strval($paginas_negro),
$papel,
strval($gramaje)
) . ". ";
}
$description_interior .= sprintf(lang('Pedidos.lineasTemplates.libro_linea_interior'),
$description_interior .= sprintf(
lang('Pedidos.lineasTemplates.libro_linea_interior'),
strval($lp_rot_color->rotativa_pag_color),
$papel,
strval($gramaje)) . ". ";
strval($gramaje)
) . ". ";
}
$lp_cubierta = array_filter($lineas, function($linea) {
$lp_cubierta = array_filter($lineas, function ($linea) {
return strpos($linea->tipo, 'lp_cubierta') === 0;
});
$lp_sobrecubierta = array_filter($lineas, function($linea) {
$lp_sobrecubierta = array_filter($lineas, function ($linea) {
return strpos($linea->tipo, 'lp_sobrecubierta') === 0;
});
if(count($lp_cubierta) > 0){
if (count($lp_cubierta) > 0) {
$lp_cubierta = array_values($lp_cubierta)[0];
if($lp_cubierta->paginas == 2){
if ($lp_cubierta->paginas == 2) {
$lp_cubierta->caras = lang('Pedidos.unaCara');
}
else{
} else {
$lp_cubierta->caras = lang('Pedidos.dosCaras');
}
$description_cubierta = sprintf(lang('Pedidos.lineasTemplates.libro_linea_cubierta'),
$description_cubierta = sprintf(
lang('Pedidos.lineasTemplates.libro_linea_cubierta'),
$lp_cubierta->caras,
$model_papel->where('id', $lp_cubierta->papel_impresion_id)->first()->nombre,
strval($lp_cubierta->gramaje));
$description_cubierta .= ($presupuesto->solapas_cubierta==1? sprintf(lang('Pedidos.lineasTemplates.libro_solapas'), $presupuesto->solapas_ancho_cubierta):". ");
}
if(count($lp_sobrecubierta) > 0){
$model_papel->where('id', $lp_cubierta->papel_impresion_id)->first()->nombre,
strval($lp_cubierta->gramaje)
);
$description_cubierta .= ($presupuesto->solapas_cubierta == 1 ? sprintf(lang('Pedidos.lineasTemplates.libro_solapas'), $presupuesto->solapas_ancho_cubierta) : ". ");
}
if (count($lp_sobrecubierta) > 0) {
$lp_sobrecubierta = array_values($lp_sobrecubierta)[0];
$description_sobrecubierta = sprintf(lang('Pedidos.lineasTemplates.libro_linea_sobrecubierta'),
$model_papel->where('id', $lp_sobrecubierta->papel_impresion_id)->first()->nombre,
strval($lp_sobrecubierta->gramaje));
$description_sobrecubierta .= ($presupuesto->solapas_sobrecubierta==1? sprintf(lang('Pedidos.lineasTemplates.libro_solapas'), $presupuesto->solapas_ancho_sobrecubierta):". ");
}
$description_sobrecubierta = sprintf(
lang('Pedidos.lineasTemplates.libro_linea_sobrecubierta'),
$model_papel->where('id', $lp_sobrecubierta->papel_impresion_id)->first()->nombre,
strval($lp_sobrecubierta->gramaje)
);
$description_sobrecubierta .= ($presupuesto->solapas_sobrecubierta == 1 ? sprintf(lang('Pedidos.lineasTemplates.libro_solapas'), $presupuesto->solapas_ancho_sobrecubierta) : ". ");
}
$acabado = sprintf(lang('Pedidos.lineasTemplates.libro_encuadernacion'),
lang('Presupuestos.' . $presupuesto->codigo_encuadernacion));
return $description_interior. $description_cubierta . $description_sobrecubierta . $acabado;
$acabado = sprintf(
lang('Pedidos.lineasTemplates.libro_encuadernacion'),
lang('Presupuestos.' . $presupuesto->codigo_encuadernacion)
);
return $description_interior . $description_cubierta . $description_sobrecubierta . $acabado;
}
}

View File

@ -1,6 +1,9 @@
<?php
namespace App\Models\Tarifas\Acabados;
use function PHPUnit\Framework\isNan;
use function PHPUnit\Framework\isNull;
class TarifaAcabadoLineaModel extends \App\Models\BaseModel
{
protected $table = "tarifa_acabado_lineas";
@ -13,14 +16,16 @@ class TarifaAcabadoLineaModel extends \App\Models\BaseModel
protected $useAutoIncrement = true;
const SORTABLE = [
0 => "t1.tirada_min",
1 => "t1.tirada_max",
2 => "t1.precio_min",
3 => "t1.precio_max",
4 => "t1.margen",
0 => "t3.nombre",
1 => "t1.tirada_min",
2 => "t1.precio_max",
3 => "t1.tirada_max",
4 => "t1.precio_min",
5 => "t1.margen",
];
protected $allowedFields = [
"proveedor_id",
"tirada_min",
"tirada_max",
"precio_min",
@ -126,12 +131,12 @@ class TarifaAcabadoLineaModel extends \App\Models\BaseModel
*
* @return \CodeIgniter\Database\BaseBuilder
*/
public function getResource(string $search = "", $tarifa_acabado_id = -1)
public function getResource($search = [], $tarifa_acabado_id = -1)
{
$builder = $this->db
->table($this->table . " t1")
->select(
"t1.id AS id, t1.tirada_min AS tirada_min, t1.tirada_max AS tirada_max, t1.precio_min AS precio_min, t1.precio_max AS precio_max, t1.margen AS margen, t2.id AS tarifa_acabado"
"t1.id AS id, t1.proveedor_id AS proveedor_id, t3.nombre AS proveedor_nombre, t1.tirada_min AS tirada_min, t1.tirada_max AS tirada_max, t1.precio_min AS precio_min, t1.precio_max AS precio_max, t1.margen AS margen, t2.id AS tarifa_acabado"
);
//JJO
@ -139,21 +144,66 @@ class TarifaAcabadoLineaModel extends \App\Models\BaseModel
$builder->where("t1.is_deleted", 0);
$builder->join("lg_tarifa_acabado t2", "t1.tarifa_acabado_id = t2.id", "left");
$builder->join("lg_proveedores t3", "t1.proveedor_id = t3.id", "left");
return empty($search)
? $builder
: $builder
->groupStart()
->like("t1.tirada_min", $search)
->orLike("t1.tirada_max", $search)
->orLike("t1.precio_min", $search)
->orLike("t1.precio_max", $search)
->orLike("t1.tirada_min", $search)
->orLike("t1.tirada_max", $search)
->orLike("t1.precio_min", $search)
->orLike("t1.precio_max", $search)
->groupEnd();
if (empty($search))
return $builder;
else {
$filterEnabled = 0;
foreach ($search as $col_search) {
if($col_search[0] != 0){
if(strlen($col_search[2]) > 1){
$values = explode(",",$col_search[2]);
$min_val = floatval($values[0]);
$max_val = floatval($values[1]);
if(!is_nan($min_val) && !is_null($min_val) && strlen($values[0]) > 0){
if($filterEnabled == 0){
$builder->groupStart();
$filterEnabled = 1;
}
$builder->where(self::SORTABLE[$col_search[0]] . " >=", $min_val);
}
if(!is_nan($max_val) && !is_null($max_val) && strlen($values[1]) > 0){
if($filterEnabled == 0){
$builder->groupStart();
$filterEnabled = 1;
}
$builder->where(self::SORTABLE[$col_search[0]] . " <", $max_val);
}
}
}
else{
if(strlen($col_search[2]) > 1){
$values = explode(",",$col_search[2]);
if(count($values) > 1){
foreach ($values as $value) {
if($filterEnabled == 0){
$builder->groupStart();
$filterEnabled = 1;
}
$builder->orWhere("t1.proveedor_id", $value);
}
}
else{
if($filterEnabled == 0){
$builder->groupStart();
$filterEnabled = 1;
}
$builder->where("t1.proveedor_id", $col_search[2]);
}
}
}
}
if($filterEnabled == 1){
$builder->groupEnd();
}
return $builder;
}
}
public function findLineasForTarifaAcabado(int $tarifaacabado_id){
@ -181,6 +231,7 @@ class TarifaAcabadoLineaModel extends \App\Models\BaseModel
->select("id, tirada_min, tirada_max")
->where("is_deleted", 0)
->where("tarifa_acabado_id", $id_tarifa_acabado)
->where("proveedor_id", $data["proveedor_id"])
->get()->getResultObject();

View File

@ -114,16 +114,17 @@ class TarifaAcabadoModel extends \App\Models\BaseModel
return $builder->orderBy("t1.nombre", "asc")->get()->getResultObject();
}
public function getTarifaPresupuestoAcabado($tarifa_id, $tirada){
public function getTarifaPresupuestoAcabado($tarifa_id, $tirada, $proveedor_id = -1){
$builder = $this->db
->table($this->table . " t1")
->select(
"t1.id AS tarifa_acabado_id, t1.nombre AS tarifa_acabado_nombre, t1.precio_min AS tarifa_precio_min, t1.importe_fijo AS tarifa_importe_fijo,
t1.acabado_cubierta AS acabado_cubierta, t1.acabado_sobrecubierta AS acabado_sobrecubierta, t2.id AS tarifa_linea_id, t2.tirada_min AS tirada_min, t2.tirada_max AS tirada_max,
t2.precio_min AS precio_min, t2.precio_max AS precio_max, t2.margen AS margen"
t2.precio_min AS precio_min, t2.precio_max AS precio_max, t2.margen AS margen, t2.proveedor_id AS proveedor_id, t3.nombre AS proveedor_nombre"
)
->join("tarifa_acabado_lineas t2", "t1.id = t2.tarifa_acabado_id", "left")
->join("lg_proveedores t3", "t2.proveedor_id = t3.id", "left")
->where("t1.is_deleted", 0)
//->where("t1.mostrar_en_presupuesto", 1)
->where("t2.is_deleted", 0);
@ -132,6 +133,9 @@ class TarifaAcabadoModel extends \App\Models\BaseModel
$builder->where('t2.tirada_min <=', $tirada);
$builder->where('t2.tirada_max >=', $tirada);
if($proveedor_id != -1){
$builder->where('t2.proveedor_id', $proveedor_id);
}
return $builder->get()->getResultObject();
}

View File

@ -0,0 +1,222 @@
<?php
namespace App\Services;
use DOMDocument;
use App\Libraries\SafekatFtpClient;
use CodeIgniter\Config\BaseService;
use App\Models\Pedidos\PedidoModel;
use App\Models\Presupuestos\PresupuestoModel;
class PedidoXMLService extends BaseService
{
public static function get_pedido_presupuesto(int $pedido_id)
{
$data_xml = [];
$pedidoModel = model(PedidoModel::class);
$presupuestoModel = model(PresupuestoModel::class);
$data_xml['pedido_cliente_presupuesto'] = $pedidoModel->getPedidoClientePresupuesto($pedido_id);
$data_xml['pedido_presupuesto_direcciones'] = $pedidoModel->getPedidoPresupuestoDirecciones($pedido_id);
$data_xml['pedido_presupuesto_lineas'] = $pedidoModel->getPedidoPresupuestoLineas($pedido_id);
$servicios = $presupuestoModel->getServiciosPresupuesto($data_xml['pedido_cliente_presupuesto']->presupuestoId);
$data_xml['servicios'] = $servicios;
$data_xml['preimpresion'] = PedidoXMLService::parse_servicio_preimpresion($servicios['preimpresion']);
$data_xml["acabado"] = PedidoXMLService::parse_servicio_acabado($servicios['acabado']);
$data_xml["binding"] = PedidoXMLService::get_binding_code($data_xml['pedido_cliente_presupuesto']->codigoTipoImpresion,$data_xml['pedido_cliente_presupuesto']->solapas);
return $data_xml;
}
protected static function parse_servicio_acabado(array $data_xml_servicios_acabado)
{
$xml_element = [];
$service_xml_key_value = [
"ShrinkWrapping" => fn($nombre) => str_contains($nombre,"retractilado"),
"Finish" => fn($nombre) => str_contains($nombre,"brillo"),
"PlakeneT" =>fn($nombre) => str_contains($nombre,"plakene traslúcido"),];
foreach($data_xml_servicios_acabado as $servicio_acabado)
{
$service_name = strtolower($servicio_acabado->nombre);
foreach ($service_xml_key_value as $key => $value) {
$xml_element[$key] = $value($service_name) ? 1 : 0 ;
}
}
return $xml_element;
}
protected static function parse_servicio_preimpresion(array $data_xml_servicios_preimpresion)
{
$xml_element = [];
$service_xml_key_value = [
"Urgent" => fn($nombre) => str_contains($nombre,"Pedido urgente"),
"Prototype" => fn($nombre) => str_contains($nombre,"Prototipo"),
"Layout" =>fn($nombre) => str_contains($nombre,"Maquetación"),
"Correction" =>fn($nombre) => str_contains($nombre,"Corrección ortográfica"),
// "Review" =>fn($nombre) => str_contains($nombre,"Revisión Profesional de archivo"),
"Design" =>fn($nombre) => str_contains($nombre,'Diseño de Cubierta'),
];
foreach($data_xml_servicios_preimpresion as $servicio_pre)
{
$service_name = $servicio_pre->nombre;
foreach ($service_xml_key_value as $key => $value) {
$value_service = $value($service_name) ? 1 : 0 ;
if( $value_service){
$xml_element[$key] = $servicio_pre->precio ;
}else if(!isset($xml_element[$key])){
$xml_element[$key] = $value_service;
}
}
}
return $xml_element;
}
public static function generate_xml($pedido_id)
{
$papel_formato_ancho = 0;
$papel_formato_alto = 0;
$data = PedidoXMLService::get_pedido_presupuesto($pedido_id);
$xml = new DOMDocument('1.0', 'utf-8');
$xml_order_el = $xml->createElement('Order');
$xml_header_el = $xml->createElement('Header');
$offset_pedido_id = env('XML_OFFSET_CUSTOMER_ID',1000000) + $data["pedido_cliente_presupuesto"]->pedidoId;
$xml_header_el->appendChild($xml->createElement('CustomerCode', $data["pedido_cliente_presupuesto"]->presupuestoClienteId));
$xml_header_el->appendChild($xml->createElement('CodeNode', env('NODE_CODE_XML','SFK')));
$xml_header_el->appendChild($xml->createElement('ExternId', $offset_pedido_id));
$xml_header_el->appendChild($xml->createElement('NumProducts', 1));
$xml_header_el->appendChild($xml->createElement('Date', now_db()));
$xml_order_el->appendChild($xml_header_el);
$xml_products_el = $xml->createElement('Products');
$xml_product_el = $xml->createElement('Product');
$xml_product_el->appendChild($xml->createElement('ItemId', $offset_pedido_id));
$xml_product_el->appendChild($xml->createElement('Quantity', $data["pedido_cliente_presupuesto"]->tirada));
$xml_product_el->appendChild($xml->createElement('Title', $data["pedido_cliente_presupuesto"]->titulo));
$xml_product_el->appendChild($xml->createElement('Pages', $data["pedido_cliente_presupuesto"]->paginas));
$xml_product_el->appendChild($xml->createElement('Reprint', $data["pedido_cliente_presupuesto"]->inc_rei ?? 0));
if ($data["pedido_cliente_presupuesto"]->papel_formato_personalizado) {
$papel_formato_ancho = $data["pedido_cliente_presupuesto"]->papelAnchoPersonalidado;
$papel_formato_alto = $data["pedido_cliente_presupuesto"]->papelAltoPersonalidado;
} else {
$papel_formato_ancho = $data["pedido_cliente_presupuesto"]->lgPapelFormatoAncho;
$papel_formato_alto = $data["pedido_cliente_presupuesto"]->lgPapelFormatoAlto;
}
$xml_product_el->appendChild($xml->createElement('Width', $papel_formato_ancho));
$xml_product_el->appendChild($xml->createElement('Height', $papel_formato_alto));
$presupuestoLineaTipoCubierta = null;
$xml_presupuesto_lineas_el = $xml->createElement('Lines');
## Iterate throught presupuesto_lineas
foreach ($data["pedido_presupuesto_lineas"] as $row) {
if (str_contains($row->tipo, "rot") || str_contains($row->tipo, "bn") || str_contains($row->tipo, "color")) {
$colorInterior = PedidoXMLService::get_color_interior($row);
$xmlInside = $xml->createElement('Inside');
$xmlInside->appendChild($xml->createElement('TypeOfPrint', $colorInterior));
$xmlInside->appendChild($xml->createElement('HQ', str_contains($row->tipo, 'hq') ? 1 : 0));
$xmlInside->appendChild($xml->createElement('Pages', $row->paginas));
$xmlInside->appendChild($xml->createElement('Paper', $row->papelCode));
$xmlInside->appendChild($xml->createElement('Weight', $row->gramaje));
$xml_presupuesto_lineas_el->appendChild($xmlInside);
} else if (str_contains($row->tipo, "lp_cubierta") ) {//|| str_contains($row->tipo, "sobrecubierta")
//? If both exists presupuestoLineaTipoCubierta is override by sobreCubierta making null and not adding
$papelCubiertaCode = $row->papelCode;
$papelCubiertaGramaje = $row->gramaje;
$presupuestoLineaTipoCubierta = $row->tipo == "lp_cubierta" ? $row : null;
}
}
$xml_product_el->appendChild($xml_presupuesto_lineas_el);
if ($presupuestoLineaTipoCubierta) {
$containsTarifaAcabadoBrillo = isset($data['acabado']['Finish']) ? true : false;
if ($containsTarifaAcabadoBrillo) {
$acabado = "brillo";
} else {
$acabado = "mate";
}
$xmlCover = $xml->createElement('Cover');
$xmlCover->appendChild($xml->createElement('Sides', $presupuestoLineaTipoCubierta->paginas / 2));
$xmlCover->appendChild($xml->createElement('Paper', $presupuestoLineaTipoCubierta->papelCode));
$xmlCover->appendChild($xml->createElement('Weight', $presupuestoLineaTipoCubierta->gramaje));
$xmlCover->appendChild($xml->createElement('Flaps', $data["pedido_cliente_presupuesto"]->solapas));
$xmlCover->appendChild($xml->createElement('WidthFlaps', $data["pedido_cliente_presupuesto"]->solapas_ancho));
$xmlCover->appendChild($xml->createElement('Finish', $acabado));
$xml_product_el->appendChild($xmlCover);
}
$xml_product_el->appendChild($xml->createElement('Binding', $data['binding']));
$xml_services_el = $xml->createElement('Services');
$xml_services_el->appendChild($xml->createElement('Bookmark', $data["pedido_cliente_presupuesto"]->marcapaginas));
foreach ($data['preimpresion'] as $key => $value) {
$xml_services_el->appendChild($xml->createElement($key, $value));
}
foreach ($data['acabado'] as $key => $value) {
$xml_services_el->appendChild($xml->createElement($key, $value));
}
$xml_product_el->appendChild($xml_services_el);
$xml_envios_el = $xml->createElement('Shipments');
foreach ($data["pedido_presupuesto_direcciones"] as $pedido_presupuesto_direccion) {
$xml_envio_el = $xml->createElement('Shipment');
$xml_envio_el->appendChild($xml->createElement('Qty', $pedido_presupuesto_direccion->cantidad));
$xml_envio_el->appendChild($xml->createElement('Price', $pedido_presupuesto_direccion->precio));
$xml_envio_el->appendChild($xml->createElement('Attention', $pedido_presupuesto_direccion->att));
$xml_envio_el->appendChild($xml->createElement('Email', $pedido_presupuesto_direccion->email));
$xml_envio_el->appendChild($xml->createElement('Address', $pedido_presupuesto_direccion->direccion));
$xml_envio_el->appendChild($xml->createElement('Province', $pedido_presupuesto_direccion->provincia));
$xml_envio_el->appendChild($xml->createElement('City', $pedido_presupuesto_direccion->municipio));
$xml_envio_el->appendChild($xml->createElement('Zip', $pedido_presupuesto_direccion->cp));
$xml_envio_el->appendChild($xml->createElement('CountryCode', $pedido_presupuesto_direccion->paisCode3));
$xml_envio_el->appendChild($xml->createElement('Telephone', $pedido_presupuesto_direccion->telefono));
$xml_envios_el->appendChild($xml_envio_el);
}
$xml_product_el->appendChild($xml_envios_el);
$xml_product_el->appendChild($xml->createElement('Comments', $data["pedido_cliente_presupuesto"]->comentarios_safekat));
$xml_product_el->appendChild($xml->createElement('CommentsClient', $data["pedido_cliente_presupuesto"]->comentarios_cliente));
$xml_products_el->appendChild($xml_product_el);
$xml_order_el->appendChild($xml_products_el);
$xml->appendChild($xml_order_el);
$file_has_suffix = hash('sha512',$offset_pedido_id);
$file_name = PedidoXMLService::generate_xml_file_name($file_has_suffix);
$ftp = new SafekatFtpClient();
$ftp->uploadXML($xml->saveXML(),$file_name);
return $data;
}
protected static function generate_xml_file_name(string $hash) : string
{
return implode("",["SafekatNew_",$hash,".xml"]);
}
protected static function get_binding_code(string $tipo_impresion_nombre,bool $solapas) : ?string
{
$solapa = $solapas ? '1' : '0';
$key = implode("_",[$tipo_impresion_nombre,$solapa]);
$xml_mapping_binding =
[
"libroFresadoTapaBlanda_0" => 'RF',
"libroFresadoTapaBlanda_1" => 'RFS',
"libroCosidoTapaBlanda_0" => 'RCHV',
"libroCosidoTapaBlanda_1" => 'RCHVS',
"libroGrapado_0" => 'CC2',
"libroGrapado_1" => 'CC2S',
"libroCosidoTapaDura_0" => 'TDC',
"libroCosidoTapaDura_1" => 'TDC',
"libroFresadoTapaDura_0" => 'RDF',
"libroFresadoTapaDura_1" => 'RDF',
"libroEspiralTapaBlanda_0" => 'ESP',
"libroEspiralTapaBlanda_1" => 'ESP',
"libroWireoTapaBlanda_0" => 'WIO',
"libroWireoTapaBlanda_1" => 'WIO',
];
return $xml_mapping_binding[$key] ?? null;
}
protected static function get_color_interior($pre_linea): ?string
{
$color_interior = null;
$bn_tipo_array = ['lp_bn', 'lp_bnhq', 'lp_rot_bn'];
$color_tipo_array = ['lp_color', 'lp_color_hq', 'lp_rot_color'];
if (in_array($pre_linea->tipo, $bn_tipo_array)) {
$color_interior = "bn";
};
if (in_array($pre_linea->tipo, $color_tipo_array)) {
$color_interior = "color";
};
return $color_interior;
}
}

View File

@ -341,9 +341,10 @@ class PresupuestoClienteService extends BaseService
$alto = $data['alto'] ?? -1;
$POD = $data['POD'] ?? -1;
$solapas = $data['solapas'] ?? -1;
$paginasCuadernillo = $data['paginasCuadernillo'] ?? null;
$model = model('App\Models\Presupuestos\PresupuestoEncuadernacionesModel');
$values = $model->initPresupuesto($tipo_impresion_id, $solapas, $tirada, $paginas, $ancho, $alto, $POD);
$values = $model->initPresupuesto($tipo_impresion_id, $solapas, $tirada, $paginas, $ancho, $alto, $POD, $paginasCuadernillo);
return $values;
}
@ -384,7 +385,7 @@ class PresupuestoClienteService extends BaseService
$POD = $data['POD'] ?? -1;
$model = model('App\Models\Presupuestos\PresupuestoAcabadosModel');
$values = $model->getPrecioTarifa($tarifa_id, $tirada, $POD);
$values = $model->getPrecioTarifa($tarifa_id, $tirada, -1, $POD); // proveedor más barato
return $values;
}

View File

@ -1353,7 +1353,14 @@ class PresupuestoService extends BaseService
$model = new PresupuestoAcabadosModel();
foreach ($servicios as $servicio) {
$nueva_tarifa = $model->getPrecioTarifa($servicio->tarifa_acabado_id, $input_data['tirada'], $input_data['POD']);
// Si es un presupuesto duplicado hay que buscar el proveedor más barato
if($input_data['is_duplicado']){
$nueva_tarifa = $model->getPrecioTarifa($servicio->tarifa_acabado_id, $input_data['tirada'], -1, $input_data['POD']);
}
else{
$nueva_tarifa = $model->getPrecioTarifa($servicio->tarifa_acabado_id, $input_data['tirada'], $servicio->proveedor_id, $input_data['POD']);
}
if($nueva_tarifa && count($nueva_tarifa)>0){
if(round($nueva_tarifa[0]->precio_unidad, 2) != round($servicio->precio_unidad,2) ||
$nueva_tarifa[0]->margen != $servicio->margen){
@ -1421,12 +1428,14 @@ class PresupuestoService extends BaseService
// Si es un presupuesto duplicado hay que buscar el proveedor más barato
if($input_data['is_duplicado']){
if($tarifaModel->isTarifaPorHoras($servicio->tarifa_encuadernado_id)){
$paginas_cuadernillo = $servicio->paginas_por_cuadernillo??null;
$nueva_tarifa = $model->getPrecioTarifaHoras(
$servicio->tarifa_encuadernado_id,
$input_data['paginas'],
$input_data['tirada'],
-1,
$input_data['POD']);
$input_data['POD'],
$paginas_cuadernillo);
}else{
$nueva_tarifa = $model->getPrecioTarifa(
$servicio->tarifa_encuadernado_id,
@ -1443,12 +1452,14 @@ class PresupuestoService extends BaseService
// con el mismo proveedor
else{
if($tarifaModel->isTarifaPorHoras($servicio->tarifa_encuadernado_id)){
$paginas_cuadernillo = $servicio->paginas_por_cuadernillo??null;
$nueva_tarifa = $model->getPrecioTarifaHoras(
$servicio->tarifa_encuadernado_id,
$input_data['paginas'],
$input_data['tirada'],
$servicio->proveedor_id,
$input_data['POD']);
$input_data['POD'],
$paginas_cuadernillo);
}else{
$nueva_tarifa = $model->getPrecioTarifa(
$servicio->tarifa_encuadernado_id,
@ -1818,6 +1829,7 @@ class PresupuestoService extends BaseService
"user_updated_id" => auth()->user()->id,
];
$id_linea = $model_pedido_linea->insert($data_pedido_linea);
PedidoXMLService::generate_xml($pedido_id);
}
if($id_linea != 0 && $pedido_id != 0){

View File

@ -191,15 +191,15 @@
<?= lang("Basic.global.edit") ?>
</button>
<?php endif; ?>
<button
type="button"
class="btn btn-label-primary float-start me-sm-3 me-1"
name="exportar_lineas"
id="exportar_lineas" >
<span class="ti-xs ti ti-file-spreadsheet me-1"></span>
<?= lang("Facturas.exportarLineas") ?>
</button>
<?= anchor(
route_to("lineasToExcel", $facturaEntity->id),
'<span class="ti-xs ti ti-file-spreadsheet me-1"></span>' .
lang("Facturas.exportarLineas"),
[
"class" => "btn btn-label-primary float-start me-sm-3 me-1",
]
) ?>
<button
type="button"

View File

@ -44,13 +44,21 @@
value="<?= lang("Facturas.borrarFactura") ?>"
/>
<?php endif; ?>
<input type="button"
class="btn btn-info float-start me-sm-3 me-1"
id="imprimirFactura"
name="imprimirFactura"
value="<?= lang("Facturas.imprimirFactura") ?>"
/>
<?= anchor(route_to("facturasList"), lang("Basic.global.back"), ["class" => "btn btn-secondary float-start"]) ?>
<?= anchor(
route_to("facturaToPdf", $facturaEntity->id),
lang("Facturas.imprimirFactura"),
[
"class" => "btn btn-info float-start me-sm-3 me-1",
"target" => "_blank"
]
) ?>
<?= anchor(
route_to("facturasList"),
lang("Basic.global.back"),
[
"class" => "btn btn-secondary float-start"
]
) ?>
</div><!-- /.card-footer -->
</form>
</div><!-- //.card -->

View File

@ -78,11 +78,60 @@
pageLength: 250,
lengthChange: true,
"dom": 'lfBrtip',
"buttons": [
'copy', 'csv', 'excel', 'print', {
extend: 'pdfHtml5',
orientation: 'landscape',
pageSize: 'A4'
buttons: [
{
text: 'Exportar Excel Contaplus',
action: function (e, dt, button, config) {
var searchValue = theTable.search(); // Captura el valor del campo de búsqueda
var ajaxParams = theTable.ajax.params(); // Captura otros parámetros de la tabla
console.log(searchValue);
/*
$.ajax({
url: '/ruta/exportarExcel', // URL del servidor para manejar la exportación
type: 'POST',
data: {
search: searchValue,
extraParams: ajaxParams
},
xhrFields: {
responseType: 'blob' // Para manejar la descarga del archivo
},
success: function(blob, status, xhr) {
// Crear un enlace temporal para descargar el archivo
var link = document.createElement('a');
var url = window.URL.createObjectURL(blob);
link.href = url;
link.download = 'datos_personalizados.xlsx';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
window.URL.revokeObjectURL(url);
}
});
*/
}
},
{
text: 'Exportar Lineas a Excel',
action: function (e, dt, button, config) {
var searchValue = theTable.search(); // Captura el valor del campo de búsqueda
var ajaxParams = theTable.ajax.params(); // Captura otros parámetros de la tabla
console.log(searchValue);
}
},
{
text: 'Exportar Girosgit ',
action: function (e, dt, button, config) {
var searchValue = theTable.search(); // Captura el valor del campo de búsqueda
var ajaxParams = theTable.ajax.params(); // Captura otros parámetros de la tabla
console.log(searchValue);
}
}
],
stateSave: true,

View File

@ -598,6 +598,16 @@ $(document).on('change', '.albaran_linea', function(){
$(document).on('click', '#borrar_albaranes', function(){
asyncConfirmDialogWithParams(
"Borrar albaranes",
"¿Está seguro de borrar los albaranes? Esta acción no se puede deshacer.",
borrar_albaranes, function(){}, [])
});
function borrar_albaranes(){
// seleccionan todos los accordion dentro del body del accordion accordioAlbaranes
$('.accordion-albaran').each(function() {
// Aquí puedes trabajar con cada acordeón interno encontrado
@ -617,12 +627,12 @@ $(document).on('click', '#borrar_albaranes', function(){
}
}
});
});
});
});
}
function borrar_albaran(albaran_id){
$(document).on('click', '.borrar-albaran', function(){
var albaran_id = $(this).attr('id').split('_').slice(-1)[0];
var url = '<?= route_to('borrarAlbaran', ':id') ?>';
url = url.replace(':id', albaran_id );
$.ajax({
@ -637,7 +647,18 @@ $(document).on('click', '.borrar-albaran', function(){
}
}
}
});
});
}
$(document).on('click', '.borrar-albaran', function(){
var albaran_id = $(this).attr('id').split('_').slice(-1)[0];
asyncConfirmDialogWithParams(
"Borrar albarán",
"¿Está seguro de borrar el albarán? Esta acción no se puede deshacer.",
borrar_albaran, function(){}, [albaran_id])
});
$(document).on('click', '.nueva-linea-albaran', function(){

View File

@ -27,6 +27,7 @@
</div><!-- //.card -->
</div><!--//.col -->
</div><!--//.row -->
<?= view("themes/_commonPartialsBs/_modalConfirmDialog") ?>
<?= $this->endSection() ?>

View File

@ -173,7 +173,7 @@ theTable = $('#tableOfPresupuestos').DataTable({
}
],
stateSave: false,
order: [[1, 'asc']],
order: [[1, 'desc']],
language: {
url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json"
},

View File

@ -128,6 +128,21 @@
<input type="number" class="calcular-presupuesto" id="paginas" name="paginas" maxLength="8" step="1" class="form-control" value="<?= old(0, $presupuestoEntity->paginas) ?>">
</div><!--//.mb-3 -->
<div id="div_pagCuadernillo" class="col-sm-3 mb-3">
<label for="paginas_por_cuadernillo" class="form-label">
<?= lang('Presupuestos.paginasCuadernillo') ?>
</label>
<select id="paginasCuadernillo" name="paginas_por_cuadernillo" class="calcular-presupuesto form-control select2bs2" style="width: 100%;">
<?php if (isset($datosPresupuesto->paginasCuadernillo) && is_array($datosPresupuesto->paginasCuadernillo) && !empty($datosPresupuesto->paginasCuadernillo)) :
foreach ($datosPresupuesto->paginasCuadernillo as $value) : ?>
<option value="<?= $value ?>" <?= $value == $presupuestoEntity->paginas_por_cuadernillo ? ' selected' : '' ?>>
<?= $value ?>
</option>
<?php endforeach;
endif; ?>
</select>
</div><!--//.mb-3 -->
</div> <!--//.row -->
<div class="row">

View File

@ -646,11 +646,18 @@ async function calcularPresupuesto() {
clienteId: $('#clienteId').val(),
servicios: servicios,
}
// Si es cosido, se añade el número de páginas del cuadernillo
if ($('#cosidoDiv').hasClass('checked')) {
datos.paginasCuadernillo = $('#paginasCuadernillo').val();
}
// Si hay solapas de cubierta
if ($('#solapasCubierta').is(':checked')) {
datos.solapasCubierta = $('#anchoSolapasCubierta').val()
}
// Si hay sobrecubierta
if ($('#enableSobrecubierta').is(':checked')) {
if($('#papelSobrecubierta option:selected').val()>0 && $('#gramajeSobrecubierta option:selected').val()>0){

View File

@ -218,6 +218,12 @@ function finalizarPresupuesto(confirmar){
clienteId: $('#clienteId').val(),
servicios: servicios,
};
// Si es cosido, se añade el número de páginas del cuadernillo
if ($('#cosidoDiv').hasClass('checked')) {
datos_libro.paginasCuadernillo = $('#paginasCuadernillo').val();
}
// Si hay solapas de cubierta
if ($('#solapasCubierta').is(':checked')) {
datos_libro.solapasCubierta = $('#anchoSolapasCubierta').val()

View File

@ -33,6 +33,12 @@ function updateTipoLibroCheck(el)
else {
$('#tapaDuraDiv').show();
}
if(el.closest('.custom-option-tipo').id == 'cosidoDiv') {
$('#div_pagCuadernillo').show();
}
else {
$('#div_pagCuadernillo').hide();
}
} else {
el.closest('.custom-option-tipo').classList.remove('checked')
}

View File

@ -126,7 +126,7 @@
<div class="col-md-12 col-lg-3 px-4">
<div class="mb-3">
<label for="paisId" class="form-label">
<?=lang('Presupuestos.paisId') ?>*
<?=lang('Presupuestos.paisId') ?>
</label>
<select id="paisId" name="pais_id" class="form-control select2bs" style="width: 100%;" >
<option value=""><?=lang('Basic.global.pleaseSelectA', [lang('Presupuestos.paisId')]) ?></option>

View File

@ -207,12 +207,55 @@ function init_servicio_acabado(){
tableServiciosAcabado.row.add([
element.tarifa_acabado_id,
nombre_completo,
'<select id="proveedor_acabado_' + element.tarifa_acabado_id + '" class="proveedor_acabado select2bs2" style="width: 100%;">' +
'<option value="' + element.proveedor_id + '" selected >' +
element.proveedor +
'</option>' +
'</select>',
'<span id="precio_unidad_acabado_' + element.tarifa_acabado_id + '">' + parseFloat(element.precio_unidad).toFixed(2) + '</span>',
'<input class="update-totales-servicios" id="precio_total_acabado_' + element.tarifa_acabado_id +'" value="' + parseFloat(element.precio_total).toFixed(2) + '"></input>',
'<span style="display: none;" class="update-totales" id="acabado_margen_' + element.tarifa_acabado_id + '">' + parseFloat(element.margen).toFixed(2) + '</span>',
'<a href="javascript:void(0);"><i class="ti ti-trash ti-sm btn-delete-serv mx-2" data-id="' + element.tarifa_acabado_id +'" data-text="' + nombre_completo + '"></i></a>'
]).draw(false)
$('#proveedor_acabado_' + element.tarifa_acabado_id).select2({
allowClear: false,
minimumResultsForSearch: -1,
ajax: {
url: window.routes_servicios.menuItemsOfPresupuestoAcabados,
type: 'post',
dataType: 'json',
data: function (params) {
if(parseInt($('#tirada').val())>0){
var tirada = parseInt($('#tirada').val())
}
else{
var tirada = 0
}
var return_data = {
tarifa_id: element.tarifa_acabado_id,
tirada: tirada,
};
return_data = Object.assign(return_data, window.token_ajax);
return return_data;
},
delay: 60,
processResults: function (response) {
yeniden(response[window.csrf_token]);
return {
results: response.menu
};
},
cache: true
}
});
$('#proveedor_acabado_' + element.tarifa_acabado_id).on('change', select_acabado_event)
$('#precio_total_acabado_' + element.tarifa_acabado_id).on('change', function(){
updatePresupuesto({
update_lineas: false,
@ -223,9 +266,55 @@ function init_servicio_acabado(){
})
})
check_serv_acabado_error()
}
function select_acabado_event(){
if(parseInt($('#tirada').val())>0){
var tirada = parseInt($('#tirada').val()) + parseInt($('#merma').val())
}
else{
var tirada = 0
}
var tarifa_id = null;
if(this.id.includes('proveedor_acabado')){
tarifa_id = this.id.split('_')[2];
}
else{
tarifa_id = this.id.split('_')[1];
}
var datos = {
tarifa_acabado_id: tarifa_id,
tirada: tirada,
proveedor_id: parseInt($('#proveedor_acabado_' + tarifa_id).select2('data')[0].id),
POD: parseInt($('#POD').val())
};
datos = Object.assign(datos, window.token_ajax);
$.ajax({
type: "POST",
url: window.routes_servicios.dataTableOfPresupuestoAcabados,
data: datos,
success: function (data) {
$('#precio_unidad_acabado_' + datos.tarifa_acabado_id).text(parseFloat(data.values[0].precio_unidad).toFixed(2))
$('#precio_total_acabado_' + datos.tarifa_acabado_id).val(parseFloat(data.values[0].total).toFixed(2))
$('#acabado_margen_' + datos.tarifa_acabado_id).val(parseFloat(data.values[0].margen).toFixed(2))
yeniden(data[window.csrf_token]);
return true;
},
error: function(e){
return false;
}
})
return false;
}
function check_serv_acabado_error(){
var htmlString = '';
@ -280,6 +369,11 @@ function get_tarifas_acabado(tarifa_id = -1, uso=null){
tableServiciosAcabado.row.add([
row.tarifa_id,
nombre,
'<select id="proveedor_acabado_' + row.tarifa_id + '" class="proveedor_acabado select2bs2" style="width: 100%;">' +
'<option value="' + row.proveedor_id + '" selected >' +
row.proveedor +
'</option>' +
'</select>',
'<span id="precio_unidad_acabado_' + row.tarifa_id + '">' + parseFloat(row.precio_unidad).toFixed(2) + '</span>',
'<input class="update-totales-servicios" id="precio_total_acabado_' + row.tarifa_id +'" value="' + parseFloat(row.total).toFixed(2) + '"></input>',
'<span style="display: none;" class="update-totales" id="acabado_margen_' + row.tarifa_id + '">' + parseFloat(row.margen).toFixed(2) + '</span>',
@ -295,6 +389,44 @@ function get_tarifas_acabado(tarifa_id = -1, uso=null){
update_tiradas_alternativas: true})
})
$('#proveedor_acabado_' + row.tarifa_id).select2({
allowClear: false,
minimumResultsForSearch: -1,
ajax: {
url: window.routes_servicios.menuItemsOfPresupuestoAcabados,
type: 'post',
dataType: 'json',
data: function (params) {
if(parseInt($('#tirada').val())>0){
var tirada = parseInt($('#tirada').val())
}
else{
var tirada = 0
}
var return_data = {
tarifa_id: row.tarifa_id,
tirada: tirada,
};
return_data = Object.assign(return_data, window.token_ajax);
return return_data;
},
delay: 60,
processResults: function (response) {
yeniden(response[window.csrf_token]);
return {
results: response.menu
};
},
cache: true
}
});
$('#proveedor_acabado_' + row.tarifa_id).on('change', select_acabado_event)
});
check_serv_acabado_error()
@ -415,12 +547,15 @@ function get_datos_acabado(){
values['sobrecubierta'] = 0
break
case 2:
values['precio_unidad'] = $(this).text()
values['proveedor_id'] = $(this).children(":first").select2('data')[0].id
break
case 3:
values['precio_total'] = $(this).children(":first").val()
values['precio_unidad'] = $(this).text()
break
case 4:
values['precio_total'] = $(this).children(":first").val()
break
case 5:
values['margen'] = $(this).text()
break
}
@ -518,7 +653,7 @@ function init_servicio_encuadernado(){
const tarifa_id = element.tarifa_encuadernado_id
var proveedor_nombre = element.proveedor===null? window.Presupuestos.no_disponible: element.proveedor
tableServiciosEnc.row.add([
var linea = [
element.tarifa_encuadernado_id,
element.nombre,
'<select id="proveedor_enc_' + element.tarifa_encuadernado_id + '" class="proveedor_enc select2bs2" style="width: 100%;">' +
@ -527,11 +662,14 @@ function init_servicio_encuadernado(){
'</option>' +
'</select>',
'<span id="precio_unidad_encuadernado_' + element.tarifa_encuadernado_id + '">' + parseFloat(element.precio_unidad).toFixed(2) + '</span>',
'<span id="tiempo_encuadernado_' + element.tiempo + '">' + convertirTiempo(element.tiempo) + '</span>',
(element.hasOwnProperty('paginas_por_cuadernillo') && element.paginas_por_cuadernillo!=null)?selectForCuadernillos(element.tarifa_encuadernado_id, element.paginas_por_cuadernillo):'',
'<span id="tiempo_encuadernado_' + element.tarifa_encuadernado_id + '">' + convertirTiempo(element.tiempo) + '</span>',
'<input class="update-totales-servicios" id="precio_total_encuadernado_' + element.tarifa_encuadernado_id +'" value="' + parseFloat(element.precio_total).toFixed(2) + '"></input>',
'<span style="display: none;" class="update-totales" id="enc_margen_' + element.tarifa_encuadernado_id + '">' + parseFloat(element.margen).toFixed(2) + '</span>',
'<a href="javascript:void(0);"><i class="ti ti-trash ti-sm btn-delete-serv mx-2" data-id="' + element.tarifa_encuadernado_id +'"></i></a>'
]).draw(false)
]
tableServiciosEnc.row.add(linea).draw(false)
$('#precio_total_encuadernado_' + element.tarifa_encuadernado_id).on('change', function(){
updatePresupuesto({
@ -583,14 +721,40 @@ function init_servicio_encuadernado(){
cache: true
}
});
$('#proveedor_enc_' + element.tarifa_encuadernado_id).on('change', proveedor_enc_event)
$('#proveedor_enc_' + element.tarifa_encuadernado_id).on('change', select_enc_event)
if(element.hasOwnProperty('paginas_por_cuadernillo') && element.paginas_por_cuadernillo!=null){
$('#cuadernillos_' + element.tarifa_encuadernado_id).select2({
allowClear: false,
minimumResultsForSearch: -1,
});
$('#cuadernillos_' + element.tarifa_encuadernado_id).on('change', select_enc_event)
}
});
check_serv_enc_error()
}
function selectForCuadernillos(tarifa_id, select_value){
const value_list = [32, 28, 24, 20, 16];
var string =
'<select id="cuadernillos_' + tarifa_id + '" class="cuadernillo_enc select2bs2" style="width: 50%;">';
for (let i = 0; i < value_list.length; i++) {
string +=
'<option value="' + value_list[i] + '" ' + (value_list[i]==select_value?'selected':'') +'>' +
value_list[i] +
'</option>';
}
string += '</select>';
return string;
}
function convertirTiempo(horas){
if(horas != null && horas.length>0){
if(horas != null){
if(parseFloat(horas)>0){
const seconds = parseFloat(horas) * 3600;
// se convierte a formato hh:mm:ss
@ -598,32 +762,49 @@ function convertirTiempo(horas){
const minutos = Math.floor((seconds % 3600) / 60);
const segundos = seconds % 60;
return h + ':' + minutos + ':' + segundos;
}
}
else{
return "";
}
}
else{
return "";
}
}
function proveedor_enc_event(){
function select_enc_event(){
const dimension = getDimensionLibro();
if(parseInt($('#tirada').val())>0){
var tirada = parseInt($('#tirada').val())
var tirada = parseInt($('#tirada').val()) + parseInt($('#merma').val())
}
else{
var tirada = 0
}
var tarifa_id = null;
if(this.id.includes('proveedor_enc')){
tarifa_id = this.id.split('_')[2];
}
else{
tarifa_id = this.id.split('_')[1];
}
// se checkea si el elemento #cuadernillos_ + tarifa_id existe
var paginas_por_cuadernillo = null;
if($('#cuadernillos_' + tarifa_id).length){
paginas_por_cuadernillo = parseInt($('#cuadernillos_' + tarifa_id).select2('data')[0].id);
}
var datos = {
tarifa_encuadernacion_id: this.id.split('_')[2],
tarifa_encuadernacion_id: tarifa_id,
paginas: parseInt($('#paginas').val())>0?parseInt($('#paginas').val()):0,
tirada: tirada,
ancho: dimension.ancho,
alto: dimension.alto,
proveedor_id: parseInt($('#' + this.id).select2('data')[0].id),
paginas_por_cuadernillo: paginas_por_cuadernillo,
proveedor_id: parseInt($('#proveedor_enc_' + tarifa_id).select2('data')[0].id),
POD: parseInt($('#POD').val())
};
datos = Object.assign(datos, window.token_ajax);
@ -677,7 +858,7 @@ async function get_tarifas_enc(tipo=null, tarifa_id = -1){
const dimension = getDimensionLibro();
if(parseInt($('#tirada').val())>0){
var tirada = parseInt($('#tirada').val())
var tirada = parseInt($('#tirada').val()) + parseInt($('#merma').val())
}
else{
var tirada = 0
@ -685,11 +866,7 @@ async function get_tarifas_enc(tipo=null, tarifa_id = -1){
var datos = {
tarifa_encuadernacion_id : tarifa_id,
solapas: $('#solapas').is(':checked')?1:0,
paginas: parseInt($('#paginas').val())>0?parseInt($('#paginas').val()):0,
tirada: tirada,
ancho: dimension.ancho,
alto: dimension.alto,
POD: parseInt($('#POD').val())
};
datos = Object.assign(datos, window.token_ajax)
@ -719,7 +896,8 @@ async function get_tarifas_enc(tipo=null, tarifa_id = -1){
'</option>' +
'</select>',
'<span id="precio_unidad_encuadernado_' + row.tarifa_id + '">' + parseFloat(row.precio_unidad).toFixed(2) + '</span>',
'<span id="tiempo_encuadernado_' + row.tiempo + '">' + convertirTiempo(row.tiempo) + '</span>',
(row.hasOwnProperty('paginas_por_cuadernillo') && row.paginas_por_cuadernillo!=null)?selectForCuadernillos(row.tarifa_id, 32):'',
'<span id="tiempo_encuadernado_' + row.tarifa_id + '">' + convertirTiempo(row.tiempo) + '</span>',
'<input class="update-totales-servicios" id="precio_total_encuadernado_' + row.tarifa_id +'" value="' + parseFloat(row.total).toFixed(2) + '"></input>',
'<span style="display: none;" class="update-totales" id="enc_margen_' + row.tarifa_id + '">' + parseFloat(row.margen).toFixed(2) + '</span>',
'<a href="javascript:void(0);"><i class="ti ti-trash ti-sm btn-delete-serv mx-2" data-id="' + row.tarifa_id +'"></i></a>'
@ -745,7 +923,7 @@ async function get_tarifas_enc(tipo=null, tarifa_id = -1){
data: function (params) {
if( parseInt( $('#tirada').val() )>0){
var tirada = parseInt($('#tirada').val())
var tirada = parseInt($('#tirada').val()) + parseInt($('#merma').val())
}
else{
var tirada = 0
@ -755,8 +933,8 @@ async function get_tarifas_enc(tipo=null, tarifa_id = -1){
tarifa_id: row.tarifa_id,
paginas: parseInt($('#paginas').val())>0?parseInt($('#paginas').val()):0,
tirada: tirada,
ancho: ancho_libro,
alto: alto_libro,
ancho: dimension.ancho,
alto: dimension.alto,
searchtxt: params.term, // search term
}
return_data = Object.assign(return_data, window.token_ajax);
@ -773,9 +951,17 @@ async function get_tarifas_enc(tipo=null, tarifa_id = -1){
}
});
$('#proveedor_enc_' + row.tarifa_id).on('change', proveedor_enc_event)
$('#proveedor_enc_' + row.tarifa_id).on('change', select_enc_event)
if(row.hasOwnProperty('paginas_por_cuadernillo') && row.paginas_por_cuadernillo!=null){
$('#cuadernillos_' + row.tarifa_id).select2({
allowClear: false,
minimumResultsForSearch: -1,
});
$('#cuadernillos_' + row.tarifa_id).on('change', select_enc_event)
}
});
check_serv_enc_error()
yeniden(data[window.csrf_token]);
@ -821,16 +1007,21 @@ function get_datos_encuadernacion(){
case 3:
values['precio_unidad'] = $(this).text()
break
case 4:
case 4:
values['paginas_por_cuadernillo'] = $(this).children(":first").val()
// Si el valor es "undefined" se pone a null
if(values['paginas_por_cuadernillo'] == "undefined")
values['paginas_por_cuadernillo'] = null
case 5:
values['tiempo'] = $(this).text()
// se pasa el string hh:mm:ss a horas
if(values['tiempo'] != null)
values['tiempo'] = parseInt(values['tiempo'].split(':')[0]) + parseInt(values['tiempo'].split(':')[1])/60 + parseInt(values['tiempo'].split(':')[2])/3600
break
case 5:
case 6:
values['precio_total'] = $(this).children(":first").val()
break
case 6:
case 7:
values['margen'] = $(this).text()
break
}
@ -1678,9 +1869,19 @@ async function actualizar_servicios(update_preimpresion=false){
.then(response => response.json())
.then(data => {
data.lines.forEach((line) => {
$('#proveedor_acabado_' + line[0].tarifa_id).off('change')
if(line[0].hasOwnProperty('proveedor_id')){
$('#proveedor_acabado_' + line[0].tarifa_id)
.append('<option selected="selected" value="' + line[0].proveedor_id + '">' + line[0].proveedor + '</option>')
}
else{
$('#proveedor_acabado_' + line[0].tarifa_id).empty()
.append('<option selected="selected" value="' + line[0].proveedor_id + '">' + window.Presupuestos.no_disponible + '</option>')
}
$('#precio_unidad_acabado_' + line[0].tarifa_id).text(parseFloat(line[0].precio_unidad).toFixed(2))
$('#precio_total_acabado_' + line[0].tarifa_id).val(parseFloat(line[0].total).toFixed(2))
$('#acabado_margen_' + line[0].tarifa_id).text(parseFloat(line[0].margen).toFixed(2))
$('#proveedor_acabado_' + line[0].tarifa_id).on('change', select_enc_event)
});
check_serv_acabado_error()
yeniden(data[window.csrf_token]);
@ -1709,7 +1910,7 @@ async function actualizar_servicios(update_preimpresion=false){
$('#precio_unidad_encuadernado_' + line[0].tarifa_id).text(parseFloat(line[0].precio_unidad).toFixed(2))
$('#precio_total_encuadernado_' + line[0].tarifa_id).val(parseFloat(line[0].total).toFixed(2))
$('#enc_margen_' + line[0].tarifa_id).val(parseFloat(line[0].margen).toFixed(2))
$('#proveedor_enc_' + line[0].tarifa_id).on('change', proveedor_enc_event)
$('#proveedor_enc_' + line[0].tarifa_id).on('change', select_enc_event)
});
check_serv_enc_error()
yeniden(data[window.csrf_token]);

View File

@ -90,6 +90,7 @@
<tr>
<th><?= lang('Presupuestos.id') ?></th>
<th><?= lang('Tarifaacabado.tarifaacabado') ?></th>
<th><?= lang('Proveedores.proveedor') ?></th>
<th><?= lang('Presupuestos.precioUnidad') ?></th>
<th><?= lang('Presupuestos.precioTotal') ?></th>
<th></th>
@ -167,6 +168,7 @@
<th><?= lang('Presupuestos.tarifa') ?></th>
<th><?= lang('Proveedores.proveedor') ?></th>
<th><?= lang('Presupuestos.precioUnidad') ?></th>
<th><?= lang('Presupuestos.paginasCuadernillo') ?></th>
<th><?= lang('Presupuestos.tiempo') ?></th>
<th><?= lang('Presupuestos.precioTotal') ?></th>
<th></th>
@ -296,6 +298,7 @@
window.routes_servicios = {
dataTableOfPresupuestoAcabados: "<?=route_to('dataTableOfPresupuestoAcabados') ?>",
menuItemsOfPresupuestoAcabados: '<?= route_to("menuItemsOfPresupuestoAcabados") ?>',
dataTableOfPresupuestoPreimpresion: "<?=route_to('dataTableOfPresupuestoPreimpresiones') ?>",
dataTableOfPresupuestoEncuadernaciones: "<?=route_to('dataTableOfPresupuestoEncuadernaciones') ?>",
dataTableOfPresupuestoManipulados: "<?=route_to('dataTableOfPresupuestoManipulados') ?>",

View File

@ -45,12 +45,13 @@
<table id="tableOfTarifaacabadolineas" class="table table-striped table-hover" style="width: 100%;">
<thead>
<tr>
<th><?= lang('TarifaAcabadoLineas.proveedor') ?></th>
<th><?= lang('TarifaAcabadoLineas.tiradaMin') ?></th>
<th><?= lang('TarifaAcabadoLineas.precioMax') ?></th>
<th><?= lang('TarifaAcabadoLineas.tiradaMax') ?></th>
<th><?= lang('TarifaAcabadoLineas.precioMin') ?></th>
<th><?= lang('TarifaAcabadoLineas.margen') ?></th>
<th style="min-width:100px"></th>
<th class="noFilter" style="min-width:100px"></th>
</tr>
</thead>
<tbody>
@ -85,7 +86,7 @@
};
editor = new $.fn.dataTable.Editor( {
var editor = new $.fn.dataTable.Editor( {
ajax: {
url: "<?= route_to('tarifaAcabadoLineasDTE') ?>",
headers: {
@ -94,7 +95,11 @@
},
table : "#tableOfTarifaacabadolineas",
idSrc: 'id',
fields: [ {
fields: [
{
name: "proveedor_id",
type: "select",
}, {
name: "tirada_min"
}, {
name: "precio_max"
@ -107,6 +112,9 @@
}, {
"name": "tarifa_acabado_id",
"type": "hidden"
},{
name: "proveedor_nombre",
"type": "hidden"
},{
"name": "deleted_at",
"type": "hidden"
@ -117,6 +125,10 @@
]
} );
// Generación de la lista de proveedores (id, nombre) para encuadernación
const suppliersList = <?php echo json_encode($proveedores); ?>;
editor.field( 'proveedor_id' ).update( suppliersList );
editor.on( 'preSubmit', function ( e, d, type ) {
if ( type === 'create'){
d.data[0]['tarifa_acabado_id'] = id;
@ -141,18 +153,94 @@
});
function searchProviders(){
var values = [];
$('#select_Proveedor').find(':selected').each(function () {
values.push($(this).val());
});
theTable.column(0).search(values).draw();
}
// Setup - add a text input to each footer cell
$('#tableOfTarifaacabadolineas thead tr').clone(true).appendTo('#tableOfTarifaacabadolineas thead');
$('#tableOfTarifaacabadolineas thead tr:eq(1) th').each(function (i) {
if (!$(this).hasClass("noFilter")) {
var title = $(this).text();
title = title.replace(/ /g, "_").replace(/\./g, "_");
if(i==0){
// Agregar un selector en la primera columna
$(this).html(`<select id=select_${title} class="form-control select2" style="min-width:100px;max-width:120px;font-size:0.8rem !important;"></select>`);
// Agregar opciones al selector
var selector = $('select', this);
const suppliersList = <?php echo json_encode($proveedores); ?>;
//selector.append('<option value="">Todos</option>'); // Opción vacía
for (j = 0; j < suppliersList.length; j++) {
selector.append('<option value="' + suppliersList[j].value + '">' + suppliersList[j].label + '</option>');
};
$('#select_' + title).select2({
multiple: true,
placeholder: ""
});
selector.bind('select2:select', searchProviders);
selector.bind('select2:unselect', searchProviders);
$('#select_' + title).val("").trigger('change');
}
else{
$(this).html(`
<div class='d-flex'>
<input name=min_${title} id=min_${title} class="form-control" type='text' min='0' placeholder='Min' style='width: 80px;'/>
<input name=max_${title} id=max_${title} class="form-control ml-1" type='text' min='0' placeholder='Max' style='width: 80px;'/>
</div>
`);
$('input', this).on('change clear', function () {
var minInputValue = parseFloat($(`#min_${title}`).val().replace(',','.')) || "";
var maxInputValue = parseFloat($(`#max_${title}`).val().replace(',','.')) || "";
if (theTable.column(i).search() !== [minInputValue,maxInputValue]) {
theTable
.column(i)
.search([minInputValue,maxInputValue])
.draw();
}
});
}
}
else {
$(this).html('<span></span>');
}
});
var theTable = $('#tableOfTarifaacabadolineas').DataTable( {
serverSide: true,
orderCellsTop: true,
serverSide: true,
processing: true,
autoWidth: true,
responsive: true,
fixedHeader: true,
lengthMenu: [ 5, 10, 25],
order: [[ 0, "asc" ], [ 1, "asc" ]],
pageLength: 10,
lengthChange: true,
searching: false,
paging: true,
info: false,
stateSave: false,
dom: '<"mt-4"><"float-end"B><"float-start"l><t><"mt-4 mb-3"p>',
ajax : $.fn.dataTable.pipeline( {
url: '<?= route_to('tarifaAcabadoLineasDT') ?>',
@ -164,6 +252,12 @@
async: true,
}),
columns: [
{ 'data': 'proveedor_id',
render: function(data, type, row, meta) {
var value = suppliersList.find(element => element.value === data);
return value['label'];
},
},
{ 'data': 'tirada_min' },
{ 'data': 'precio_max' },
{ 'data': 'tirada_max' },
@ -180,7 +274,6 @@
searchable: false,
targets: [lastColNr]
},
{"orderData": [ 0, 1 ], "targets": 0 },
],
language: {
@ -244,6 +337,7 @@
<?=$this->section('css') ?>
<link rel="stylesheet" href="<?= site_url('themes/vuexy/css/datatables-editor/editor.dataTables.min.css') ?>">
<link rel="stylesheet" href="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/buttons/buttons.bootstrap5.min.css") ?>">
<link rel="stylesheet" href="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/fixedheader/fixedHeader.dataTables.min.css") ?>">
<?=$this->endSection() ?>

View File

@ -49,11 +49,11 @@
<th><?= lang('TarifaEncuadernacionTiradas.proveedor') ?></th>
<th><?= lang('TarifaEncuadernacionTiradas.tiradaMin') ?></th>
<th><?= lang('TarifaEncuadernacionTiradas.tiradaMax') ?></th>
<th><?= lang('Tarifaencuadernacion.precioMin') ?></th>
<th><?= lang('Tarifaencuadernacion.importeMin') ?></th>
<th><?= lang('Tarifaencuadernacion.importeFijo') ?></th>
<th></th>
</tr>
</thead>
</thead>
<tbody>
</tbody>
</table>

View File

@ -75,6 +75,13 @@ if (
</a>
</li>
<?php } ?>
<?php if (auth()->user()->can('proveedores.menu')) { ?>
<li class="menu-item">
<a href="<?= route_to("proveedorList") ?>" class="menu-link">
<?= lang("App.menu_proveedores") ?>
</a>
</li>
<?php } ?>
<?php if (auth()->user()->can('ubicaciones.menu')) { ?>
<li class="menu-item">
<a href="<?= route_to("ubicacionesList") ?>" class="menu-link">

File diff suppressed because one or more lines are too long

View File

@ -13,7 +13,9 @@
"php": "^8.2",
"codeigniter4/framework": "^4.0",
"codeigniter4/shield": "^1.0",
"dompdf/dompdf": "^2.0"
"dompdf/dompdf": "^2.0",
"nicolab/php-ftp-client": "^2.0",
"phpseclib/phpseclib": "~3.0"
},
"require-dev": {
"fakerphp/faker": "^1.9",

281
ci4/composer.lock generated
View File

@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "b2eee64c89c81ed0f0edef73637b9199",
"content-hash": "0cf49081609029ebf2165c9cebed577e",
"packages": [
{
"name": "codeigniter4/framework",
@ -399,6 +399,175 @@
},
"time": "2024-03-31T07:05:07+00:00"
},
{
"name": "nicolab/php-ftp-client",
"version": "v2.0.2",
"source": {
"type": "git",
"url": "https://github.com/Nicolab/php-ftp-client.git",
"reference": "a1d007c8b203895611f68b0da314281d4a5c3d49"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/Nicolab/php-ftp-client/zipball/a1d007c8b203895611f68b0da314281d4a5c3d49",
"reference": "a1d007c8b203895611f68b0da314281d4a5c3d49",
"shasum": ""
},
"require": {
"ext-ftp": "*",
"php": ">=5.4"
},
"type": "library",
"autoload": {
"psr-0": {
"FtpClient": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Nicolas Tallefourtane",
"email": "dev@nicolab.net",
"homepage": "http://nicolab.net"
}
],
"description": "A flexible FTP and SSL-FTP client for PHP. This lib provides helpers easy to use to manage the remote files.",
"homepage": "https://github.com/Nicolab/php-ftp-client",
"keywords": [
"file",
"ftp",
"helper",
"lib",
"server",
"sftp",
"ssl",
"ssl-ftp"
],
"support": {
"source": "https://github.com/Nicolab/php-ftp-client/tree/v2.0.2"
},
"time": "2022-08-10T11:09:32+00:00"
},
{
"name": "paragonie/constant_time_encoding",
"version": "v3.0.0",
"source": {
"type": "git",
"url": "https://github.com/paragonie/constant_time_encoding.git",
"reference": "df1e7fde177501eee2037dd159cf04f5f301a512"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/paragonie/constant_time_encoding/zipball/df1e7fde177501eee2037dd159cf04f5f301a512",
"reference": "df1e7fde177501eee2037dd159cf04f5f301a512",
"shasum": ""
},
"require": {
"php": "^8"
},
"require-dev": {
"phpunit/phpunit": "^9",
"vimeo/psalm": "^4|^5"
},
"type": "library",
"autoload": {
"psr-4": {
"ParagonIE\\ConstantTime\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Paragon Initiative Enterprises",
"email": "security@paragonie.com",
"homepage": "https://paragonie.com",
"role": "Maintainer"
},
{
"name": "Steve 'Sc00bz' Thomas",
"email": "steve@tobtu.com",
"homepage": "https://www.tobtu.com",
"role": "Original Developer"
}
],
"description": "Constant-time Implementations of RFC 4648 Encoding (Base-64, Base-32, Base-16)",
"keywords": [
"base16",
"base32",
"base32_decode",
"base32_encode",
"base64",
"base64_decode",
"base64_encode",
"bin2hex",
"encoding",
"hex",
"hex2bin",
"rfc4648"
],
"support": {
"email": "info@paragonie.com",
"issues": "https://github.com/paragonie/constant_time_encoding/issues",
"source": "https://github.com/paragonie/constant_time_encoding"
},
"time": "2024-05-08T12:36:18+00:00"
},
{
"name": "paragonie/random_compat",
"version": "v9.99.100",
"source": {
"type": "git",
"url": "https://github.com/paragonie/random_compat.git",
"reference": "996434e5492cb4c3edcb9168db6fbb1359ef965a"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/paragonie/random_compat/zipball/996434e5492cb4c3edcb9168db6fbb1359ef965a",
"reference": "996434e5492cb4c3edcb9168db6fbb1359ef965a",
"shasum": ""
},
"require": {
"php": ">= 7"
},
"require-dev": {
"phpunit/phpunit": "4.*|5.*",
"vimeo/psalm": "^1"
},
"suggest": {
"ext-libsodium": "Provides a modern crypto API that can be used to generate random bytes."
},
"type": "library",
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Paragon Initiative Enterprises",
"email": "security@paragonie.com",
"homepage": "https://paragonie.com"
}
],
"description": "PHP 5.x polyfill for random_bytes() and random_int() from PHP 7",
"keywords": [
"csprng",
"polyfill",
"pseudorandom",
"random"
],
"support": {
"email": "info@paragonie.com",
"issues": "https://github.com/paragonie/random_compat/issues",
"source": "https://github.com/paragonie/random_compat"
},
"time": "2020-10-15T08:29:30+00:00"
},
{
"name": "phenx/php-font-lib",
"version": "0.5.6",
@ -489,6 +658,116 @@
},
"time": "2024-04-08T12:52:34+00:00"
},
{
"name": "phpseclib/phpseclib",
"version": "3.0.41",
"source": {
"type": "git",
"url": "https://github.com/phpseclib/phpseclib.git",
"reference": "621c73f7dcb310b61de34d1da4c4204e8ace6ceb"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/phpseclib/phpseclib/zipball/621c73f7dcb310b61de34d1da4c4204e8ace6ceb",
"reference": "621c73f7dcb310b61de34d1da4c4204e8ace6ceb",
"shasum": ""
},
"require": {
"paragonie/constant_time_encoding": "^1|^2|^3",
"paragonie/random_compat": "^1.4|^2.0|^9.99.99",
"php": ">=5.6.1"
},
"require-dev": {
"phpunit/phpunit": "*"
},
"suggest": {
"ext-dom": "Install the DOM extension to load XML formatted public keys.",
"ext-gmp": "Install the GMP (GNU Multiple Precision) extension in order to speed up arbitrary precision integer arithmetic operations.",
"ext-libsodium": "SSH2/SFTP can make use of some algorithms provided by the libsodium-php extension.",
"ext-mcrypt": "Install the Mcrypt extension in order to speed up a few other cryptographic operations.",
"ext-openssl": "Install the OpenSSL extension in order to speed up a wide variety of cryptographic operations."
},
"type": "library",
"autoload": {
"files": [
"phpseclib/bootstrap.php"
],
"psr-4": {
"phpseclib3\\": "phpseclib/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Jim Wigginton",
"email": "terrafrost@php.net",
"role": "Lead Developer"
},
{
"name": "Patrick Monnerat",
"email": "pm@datasphere.ch",
"role": "Developer"
},
{
"name": "Andreas Fischer",
"email": "bantu@phpbb.com",
"role": "Developer"
},
{
"name": "Hans-Jürgen Petrich",
"email": "petrich@tronic-media.com",
"role": "Developer"
},
{
"name": "Graham Campbell",
"email": "graham@alt-three.com",
"role": "Developer"
}
],
"description": "PHP Secure Communications Library - Pure-PHP implementations of RSA, AES, SSH2, SFTP, X.509 etc.",
"homepage": "http://phpseclib.sourceforge.net",
"keywords": [
"BigInteger",
"aes",
"asn.1",
"asn1",
"blowfish",
"crypto",
"cryptography",
"encryption",
"rsa",
"security",
"sftp",
"signature",
"signing",
"ssh",
"twofish",
"x.509",
"x509"
],
"support": {
"issues": "https://github.com/phpseclib/phpseclib/issues",
"source": "https://github.com/phpseclib/phpseclib/tree/3.0.41"
},
"funding": [
{
"url": "https://github.com/terrafrost",
"type": "github"
},
{
"url": "https://www.patreon.com/phpseclib",
"type": "patreon"
},
{
"url": "https://tidelift.com/funding/github/packagist/phpseclib/phpseclib",
"type": "tidelift"
}
],
"time": "2024-08-12T00:13:54+00:00"
},
{
"name": "psr/log",
"version": "3.0.0",

View File

@ -0,0 +1,313 @@
/* Facturas Safekat */
* {
box-sizing: border-box;
}
body {
font-family: 'Open Sans', sans-serif;
font-size: 14px;
line-height: 1.42857143;
color: #333;
background-color: #fff;
}
table {
border-spacing: 0;
background-color: transparent;
border-collapse: collapse;
}
th {
text-align: left;
}
td {
padding: 0;
}
body table.logo {
padding: 0;
width: 100%;
color: black;
}
body table.logo td.logo img {
width: 100%;
vertical-align: middle;
}
/* Estilos intro-factura */
body table.intro-factura {
width: 100%;
font-size: 12px;
margin-top: -22px;
}
body table.intro-factura th {
background: black;
color: white;
padding: 7px;
}
body table.intro-factura th.intro_num_factura {
width: 20%;
padding-left: 15px;
}
body table.intro-factura th.num_factura {
width: 47%;
font-weight: lighter;
text-align: left;
}
body table.intro-factura th.intro_fecha {
width: 17%;
text-align: right;
}
body table.intro-factura th.fecha {
width: 15%;
text-align: right;
font-weight: lighter;
}
body table.intro-factura td {
background: #e3e4e7;
padding-left: 15px;
color: black;
font-size: 12px;
}
body table.intro-factura td.intro_direccion {
padding-top: 10px;
padding-right: 8px;
font-weight: bold;
}
body table.intro-factura td.direccion {
padding-right: 8px;
}
/* Estilos cuerpo factura */
div.cuerpo-factura {
margin-bottom: 25px;
}
table.factura-data-superior {
width: 100%;
}
table.factura-data-superior th {
padding: 5px !important;
background: #0C2C84;
color: white;
padding-left: 10px;
font-weight: lighter;
font-size: 12px;
border-right: 1px solid white;
}
table.factura-data-superior td {
border: 1px dotted #4e4e4e;
border-top: none;
padding: 5px !important;
text-align: right;
font-size: 11px;
}
table.factura-data-superior td.tipo_trabajo {
border-left: none;
text-align: left;
}
table.factura-data-superior td.subtotal {
border-right: none;
}
/* Estilos para el sello de Solunion */
.sello-solunion {
float: left; /* Hace que el sello flote a la izquierda */
margin-left: 100px; /* Espacio entre el sello y la tabla */
}
.sello-solunion img {
display: block; /* Asegura que la imagen se comporte como un bloque dentro del div */
width: 80px; /* Ajusta el tamaño de la imagen según sea necesario */
height: auto;
}
/* Contenedor para manejar el flujo de contenido */
.container {
overflow: hidden; /* Asegura que el contenedor se ajuste al contenido flotante */
}
/* Estilos para la tabla de precios inferior */
table.factura-precio-inferior {
width: 60%; /* Ajusta el ancho de la tabla al 100% del contenedor */
text-align: right;
border-collapse: collapse; /* Asegura que los bordes se colapsen para evitar espacio extra */
margin-bottom: 0; /* Elimina el margen inferior para evitar espacio extra */
}
table.factura-precio-inferior th, table.factura-precio-inferior td {
padding: 5px;
border-bottom: 1px dotted #4e4e4e;
}
table.factura-precio-inferior th.intro_base,
table.factura-precio-inferior th.intro_iva,
table.factura-precio-inferior th.intro_total {
background: #0C2C84;
color: white;
font-size: 12px;
}
table.factura-precio-inferior td.base,
table.factura-precio-inferior td.iva,
table.factura-precio-inferior td.value_iva,
table.factura-precio-inferior td.total {
font-size: 11px;
}
/* Estilos para la tabla de totales */
table.totales {
width: 28%; /* Ajusta el ancho de la tabla según sea necesario */
background: #0C2C84;
color: white;
font-size: 12px;
border-collapse: collapse; /* Asegura que los bordes se colapsen para evitar espacio extra */
margin-top: 0; /* Elimina el margen superior para evitar espacio extra */
margin-bottom: 0; /* Elimina el margen inferior para evitar espacio extra */
}
table.totales td.intro_total_factura {
width: 20%;
text-align: right;
padding: 5px;
}
table.totales td.total_factura {
width: 15%;
text-align: right;
padding-right: 10px;
}
/* Estilos factura-data-inferior-iva */
table.factura-data-inferior-iva {
width: 100%;
margin-top: 8px;
}
table.factura-data-inferior-iva th {
padding: 5px !important;
background: rgb(233, 240, 255);
font-weight: lighter;
font-size: 12px;
padding-left: 7px;
color: black;
border-right: 1px solid white;
}
table.factura-data-inferior-iva th.intro_vencimiento,
table.factura-data-inferior-iva th.inferior_intro_fecha {
width: 15%;
}
table.factura-data-inferior-iva th.intro_forma_pago {
width: 20%;
}
table.factura-data-inferior-iva th.intro_bic {
width: 50%;
}
table.factura-data-inferior-iva td {
border-bottom: 1px dotted #4e4e4e;
border-top: none;
padding-left: 8px;
padding: 3px !important;
font-size: 11px;
}
table.factura-data-inferior-iva td.vencimiento,
table.factura-data-inferior-iva td.inferior_fecha,
table.factura-data-inferior-iva td.forma_pago {
border-right: 1px dotted black;
}
/* Estilos factura-precio-inferior */
table.factura-data-inferior {
width: 100%;
background: #e3e4e7;
font-size: 12px;
margin-top: 5px;
}
table.factura-data-inferior th {
padding-top: 2px;
font-weight: lighter;
}
table.factura-data-inferior th.intro_vencimiento,
table.factura-data-inferior th.intro_base,
table.factura-data-inferior th.base {
padding-top: 8px;
}
table.factura-data-inferior th.intro_vencimiento,
table.factura-data-inferior th.inferior_intro_fecha,
table.factura-data-inferior th.intro_forma_pago,
table.factura-data-inferior th.intro_bic {
font-weight: bold;
padding-left: 10px;
}
table.factura-data-inferior th.intro_base,
table.factura-data-inferior th.intro_value_iva,
table.factura-data-inferior th.intro_iva,
table.factura-data-inferior th.intro_total {
color: #0C2C84;
text-align: right;
padding-right: 5px;
}
table.factura-data-inferior th.base,
table.factura-data-inferior th.iva,
table.factura-data-inferior th.value_iva,
table.factura-data-inferior th.total {
border-left: 1px dashed grey;
text-align: right;
padding-right: 10px;
width: 15%;
}
table.factura-data-inferior th.intro_bic,
table.factura-data-inferior th.intro_total,
table.factura-data-inferior th.total {
padding-bottom: 8px;
}
/* Estilos para el pie de página */
.footer {
width: 95%;
position: fixed; /* Fija el pie de página en la parte inferior */
bottom: 15px; /* Coloca el pie de página en la parte inferior de la página */
}
/* Estilos pie */
div.pie {
font-family: sans-serif;
font-size: 7px;
margin: 5mm 0 5mm 0;
}
/* Estilos pie-pagina */
table.pie-pagina {
font-family: sans-serif;
color: #0C2C84;
float: left;
vertical-align: bottom;
font-size: 10px;
font-weight: bold;
}