Merge branch 'mod/pedidos_produccion_a_facturas' into 'main'

corregidos varios problemas con los presupuestos (calculo envio base debido al...

See merge request jjimenez/safekat!863
This commit is contained in:
2025-06-24 15:07:20 +00:00
31 changed files with 1275 additions and 1204 deletions

View File

@ -17,6 +17,8 @@ $routes->group('presupuestoadmin', ['namespace' => 'App\Controllers\Presupuestos
$routes->post('allmenuitems', 'Presupuestoadmin::allItemsSelect', ['as' => 'select2ItemsOfPresupuestoAdmin']);
$routes->post('menuitems', 'Presupuestoadmin::menuItems', ['as' => 'menuItemsOfPresupuestoAdmin']);
$routes->get('checklomointerior', 'Presupuestoadmin::checkLomo');
$routes->get('cargar/(:any)', 'Presupuestoadmin::cargar/$1');
$routes->post('comparadorinterior', 'Presupuestoadmin::obtenerComparadorInterior');
$routes->post('comparadorexteriores', 'Presupuestoadmin::obtenerComparadorExteriores');

View File

@ -1841,6 +1841,18 @@ class Presupuestoadmin extends \App\Controllers\BaseResourceController
}
}
public function checkLomo()
{
if ($this->request->isAJAX()) {
$tipo_impresion_id = $this->request->getGet('tipo_impresion_id');
$lomo = $this->request->getGet('lomo') ?? 0;
$response = PresupuestoService::check_lomo_interior($tipo_impresion_id, $lomo);
return $this->respond($response);
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function reprintPresupuesto()
{

View File

@ -130,7 +130,7 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
$this->viewData['paisList'] = model('App\Models\Configuracion\PaisModel')->getAllForMenu('id, nombre', 'nombre', true);
$this->viewData['clienteId'] = $clienteId;
$this->viewData['POD'] = $POD;
$this->viewData['lomo_maximo'] = model('App\Models\Configuracion\ConfigVariableModel')->getVariable('lomo_maximo')->value;
$this->viewData['lomo_maximo_fresado_cosido'] = model('App\Models\Configuracion\ConfigVariableModel')->getVariable('lomo_maximo_fresado_cosido')->value;
$this->viewData['lomo_minimo_fresado_cosido'] = model('App\Models\Configuracion\ConfigVariableModel')->getVariable('lomo_minimo_fresado_cosido')->value;
$this->viewData['eb'] = 0;
@ -175,7 +175,7 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
$this->viewData['clienteId'] = $clienteId;
$this->viewData['POD'] = model('App\Models\Configuracion\ConfigVariableModel')->getVariable('POD')->value;
$this->viewData['lomo_maximo'] = model('App\Models\Configuracion\ConfigVariableModel')->getVariable('lomo_maximo')->value;
$this->viewData['lomo_maximo_fresado_cosido'] = model('App\Models\Configuracion\ConfigVariableModel')->getVariable('lomo_maximo_fresado_cosido')->value;
$this->viewData['lomo_minimo_fresado_cosido'] = model('App\Models\Configuracion\ConfigVariableModel')->getVariable('lomo_minimo_fresado_cosido')->value;
$this->viewData['eb'] = $presupuestoEntity->envio_base;
@ -418,21 +418,53 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
'value' => ""
];
$lomo_minimo_fresado_cosido = intval(model('App\Models\Configuracion\ConfigVariableModel')->getVariable('lomo_minimo_fresado_cosido')->value);
$lomo_maximo = intval(model('App\Models\Configuracion\ConfigVariableModel')->getVariable('lomo_maximo')->value);
$lomo_maximo_fresado_cosido = intval(model('App\Models\Configuracion\ConfigVariableModel')->getVariable('lomo_maximo_fresado_cosido')->value);
$lomo_maximo_espiral = intval(model('App\Models\Configuracion\ConfigVariableModel')->getVariable('lomo_maximo_espiral')->value);
$lomo_maximo_wireo = intval(model('App\Models\Configuracion\ConfigVariableModel')->getVariable('lomo_maximo_wireo')->value);
if ($tipo == 'cosido' || $tipo == 'fresado') {
if ($lomo < $lomo_minimo_fresado_cosido) {
$errors['status'] = 1;
$errors['value'] = 'No se pueden encuadernar libros cosidos o fresados con lomo inferior a '
. $lomo_minimo_fresado_cosido . ' mm. El lomo actual es de ' . $lomo . ' mm. ' .
"Por favor, aumente el número de páginas o el gramaje del papel para que sea encuadernable.";
$errors['value'] = lang(
'Presupuestos.errores.error_lomo_minimo',
[
lang('Presupuestos.cosido') . "/" . lang('Presupuestos.fresado'),
$lomo_minimo_fresado_cosido,
$lomo,
]
);
}
if ($lomo > $lomo_maximo) {
if ($lomo > $lomo_maximo_fresado_cosido) {
$errors['status'] = 1;
$errors['value'] = 'No se pueden encuadernar con un lomo superior a '
. $lomo_maximo . ' mm. El lomo actual es de ' . $lomo . ' mm. ' .
"Por favor, disminuya el número de páginas o el gramaje del papel para que sea encuadernable.";
$errors['value'] = lang(
'Presupuestos.errores.error_lomo_maximo',
[
lang('Presupuestos.cosido') . "/" . lang('Presupuestos.fresado'),
$lomo_maximo_fresado_cosido,
$lomo,
]
);
}
} else if ($tipo == 'espiral' && $lomo > $lomo_maximo_espiral) {
$errors['status'] = 1;
$errors['value'] = lang(
'Presupuestos.errores.error_lomo_maximo',
[
lang('Presupuestos.espiral'),
$lomo_maximo_espiral,
$lomo,
]
);
} else if ($tipo == 'wireo' && $lomo > $lomo_maximo_wireo) {
$errors['status'] = 1;
$errors['value'] = lang(
'Presupuestos.errores.error_lomo_maximo',
[
lang('Presupuestos.wireo'),
$lomo_maximo_wireo,
$lomo,
]
);
}
$data = (object) array(
@ -469,7 +501,7 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
$noEnvioBase = model('App\Models\Clientes\ClienteModel')->find($cliente_id)->no_envio_base ?? false;
$tirada = $reqData['tirada'] ?? 0;
$selectedTirada = $reqData['selectedTirada'] ?? -1;
$selectedTirada = $reqData['selectedTirada'] ?? (is_array($tirada) ? $tirada[0] : $tirada);
$tamanio = $reqData['tamanio'];
$paginas = $reqData['paginas'] ?? 0;
$paginas_color = $reqData['paginasColor'] ?? 0;
@ -565,7 +597,8 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
'servicios' => $reqData['servicios'] ?? [],
);
$return_data = $this->calcular_presupuesto($datos_presupuesto, 0, false); //TRUE FOR DEBUG
$develoment_mode = getenv('SK_ENVIRONMENT') !== 'production';
$return_data = $this->calcular_presupuesto($datos_presupuesto, $selectedTirada, $develoment_mode); //TRUE FOR DEBUG
if (array_key_exists('errors', $return_data)) {
if ($return_data['errors']->status == 1) {
$return_data = [
@ -631,13 +664,13 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
$return_data['precio_u'][$i] = round(floatval($return_data['precio_u'][$i]) + $coste_envio, 4);
}
$envio_base = true;
$coste_envio = 0.0; // se inicializa para calcular los costes de envíos restantes si es que hay
$return_data['coste_envio'] = [];
if (count($direcciones) > 0) {
for ($i = 0; $i < count($tirada); $i++) {
$coste_envio = 0.0;
$envio_base = true;
foreach ($direcciones as $direccion) {
// El primer envio no se calcula ya que se añade el base
if ($envio_base) {
@ -1200,12 +1233,14 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
// para el calculo del precio unidad, sólo se tiene en cuenta el envío base
for ($i = 0; $i < count($tirada); $i++) {
$coste_envio = 0.0;
$coste_envio += ($resultado_presupuesto['eb'][$i] / $tirada[$i]);
$resultado_presupuesto['info']['totales'][$i]['envio_base_margen'] =
floatval($resultado_presupuesto['eb'][$i]) * (floatval($resultado_presupuesto['eb_margen'][$i]) / 100.0);
$resultado_presupuesto['info']['totales'][$i]['envio_base_coste'] = $resultado_presupuesto['eb'][$i];
$coste_envio = round(round($resultado_presupuesto['info']['totales'][$i]['envio_base_margen'] +
$resultado_presupuesto['info']['totales'][$i]['envio_base_coste'], 2) / 50, 4);
$resultado_presupuesto['precio_u'][$i] = round(floatval($resultado_presupuesto['precio_u'][$i]) + $coste_envio, 4);
}
@ -2125,9 +2160,11 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
foreach ($interior as $linea) {
if (count($linea) > 0) {
$costeInterior += round(floatval($linea['total_impresion']), 2);
$peso_interior += floatval($linea['peso']);
$lomo += floatval($linea['mano']);
$info['lomo_interior'] += floatval($linea['mano']);
$peso_interior += round(floatval($linea['peso']), 2);
if (intval($tirada[$t]) == intval($selected_tirada)) {
$lomo += floatval($linea['mano']);
$info['lomo_interior'] += floatval($linea['mano']);
}
if ($extra_info) {
$this->calcular_coste_linea(
$linea,
@ -2186,8 +2223,11 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
foreach ($interior as $linea) {
if (count($linea) > 0) {
$costeInterior += round(floatval($linea['total_impresion']), 2);
if (intval($tirada[$t]) == intval($selected_tirada)) {
$info['lomo_interior'] += floatval($linea['mano']);
$lomo += floatval($linea['mano']);
}
$peso_interior += floatval($linea['peso']);
$lomo += floatval($linea['mano']);
if ($extra_info) {
$this->calcular_coste_linea(
@ -2238,8 +2278,11 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
$peso_cubierta = 0.0;
if (count($cubierta) > 0) {
$coste_cubierta += round(floatval($cubierta['total_impresion']), 2);
$peso_cubierta += floatval($cubierta['peso']);
$lomo += floatval($cubierta['mano']);
$peso_cubierta += round(floatval($cubierta['peso']), 2);
if (intval($tirada[$t]) == intval($selected_tirada)) {
$lomo += floatval($cubierta['mano']);
}
if ($extra_info) {
$this->calcular_coste_linea(
@ -2302,9 +2345,10 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
}
$coste_servicios += round(floatval($acabadoCubierta[0]->total), 2);
if ($extra_info) {
$totalServicios += round(floatval($acabadoCubierta[0]->total), 2);
//$totalServicios += round(floatval($acabadoCubierta[0]->total), 2);
$base = round(floatval($acabadoCubierta[0]->total / (1 + $acabadoCubierta[0]->margen / 100.0)), 2);
$base = round(floatval($base / $cantidad_total), 2) * $cantidad_total;
$totalServicios += $base;
$margenServicios += round(floatval($acabadoCubierta[0]->total - $base), 2);
}
}
@ -2341,9 +2385,10 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
}
$coste_servicios += round(floatval($resultado[0]->total), 2);
if ($extra_info) {
$totalServicios += round(floatval($resultado[0]->total), 2);
//$totalServicios += round(floatval($resultado[0]->total), 2);
$base = round(floatval($resultado[0]->total / (1 + $resultado[0]->margen / 100.0)), 2);
$base = round(floatval($base / $cantidad_total), 2) * $cantidad_total;
$totalServicios += $base;
$margenServicios += round(floatval($resultado[0]->total - $base), 2);
}
@ -2374,7 +2419,7 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
if (count($linea_sobrecubierta) > 0) {
$coste_sobrecubierta += round(floatval($linea_sobrecubierta['total_impresion']), 2);
$peso_sobrecubierta += floatval($linea_sobrecubierta['peso']);
$peso_sobrecubierta += round(floatval($linea_sobrecubierta['peso']), 2);
if ($extra_info) {
$this->calcular_coste_linea(
@ -2437,9 +2482,10 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
$coste_servicios += round(floatval($acabadoSobrecubierta[0]->total), 2);
if ($extra_info) {
$totalServicios += round(floatval($acabadoSobrecubierta[0]->total), 2);
//$totalServicios += round(floatval($acabadoSobrecubierta[0]->total), 2);
$base = round(floatval($acabadoSobrecubierta[0]->total / (1 + $acabadoSobrecubierta[0]->margen / 100.0)), 2);
$base = round(floatval($base / $cantidad_total), 2) * $cantidad_total;
$totalServicios += $base;
$margenServicios += round(floatval($acabadoSobrecubierta[0]->total - $base), 2);
}
}
@ -2479,7 +2525,10 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
if (count($guardas) > 0) {
$coste_guardas += round(floatval($guardas['total_impresion']), 2);
$peso_guardas += floatval($guardas['peso']);
$peso_guardas += round(floatval($guardas['peso']), 2);
if (intval($tirada[$t]) == intval($selected_tirada)) {
$lomo += floatval($guardas['mano']);
}
if ($extra_info) {
$this->calcular_coste_linea(
@ -2595,9 +2644,10 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
$coste_servicios += round(floatval($acabadoFaja[0]->total), 2);
if ($extra_info) {
$totalServicios += round(floatval($acabadoFaja[0]->total), 2);
//$totalServicios += round(floatval($acabadoFaja[0]->total), 2);
$base = round(floatval($acabadoFaja[0]->total / (1 + $acabadoFaja[0]->margen / 100.0)), 2);
$base = round(floatval($base / $cantidad_total), 2) * $cantidad_total;
$totalServicios += $base;
$margenServicios += round(floatval($acabadoFaja[0]->total - $base), 2);
}
}
@ -2649,9 +2699,10 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
$costeServiciosDefecto += round(floatval($servicio->total), 2);
if ($extra_info) {
$totalServicios += round(floatval($servicio->total), 2);
//$totalServicios += round(floatval($servicio->total), 2);
$base = round(floatval($servicio->total / (1 + $servicio->margen / 100.0)), 2);
$base = round(floatval($base / $cantidad_total), 2) * $cantidad_total;
$totalServicios += $base;
$margenServicios += round(floatval($servicio->total - $base), 2);
}
}
@ -2686,9 +2737,10 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
$costeServiciosDefecto += round(floatval($servicio->total), 2);
if ($extra_info) {
$totalServicios += round(floatval($servicio->total), 2);
//$totalServicios += round(floatval($servicio->total), 2);
$base = round(floatval($servicio->total / (1 + $servicio->margen / 100.0)), 2);
$base = round(floatval($base / $cantidad_total), 2) * $cantidad_total;
$totalServicios += $base;
$margenServicios += round(floatval($servicio->total - $base), 2);
}
}
@ -2791,9 +2843,10 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
$coste_servicios += round(floatval($resultado[0]->total), 2);
if ($extra_info) {
$totalServicios += round(floatval($resultado[0]->total), 2);
//$totalServicios += round(floatval($resultado[0]->total), 2);
$base = round(floatval($resultado[0]->total / (1 + $resultado[0]->margen / 100.0)), 2);
$base = round(floatval($base / $cantidad_total), 2) * $cantidad_total;
$totalServicios += $base;
$margenServicios += round(floatval($resultado[0]->total - $base), 2);
}
} else if ($servicio->nombre == "ferro" || $servicio->nombre == "prototipo") {
@ -2823,9 +2876,10 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
$coste_servicios += round(floatval($resultado[0]->precio), 2);
if ($extra_info) {
$totalServicios += round(floatval($resultado[0]->precio), 2);
//$totalServicios += round(floatval($resultado[0]->precio), 2);
$base = round(floatval($resultado[0]->total / (1 + $resultado[0]->margen / 100.0)), 2);
$base = round(floatval($base / $cantidad_total), 2) * $cantidad_total;
$totalServicios += $base;
$margenServicios += round(floatval($resultado[0]->total - $base), 2);
}
} else if ($servicio->nombre == 'solapas_cubierta' || $servicio->nombre == 'solapas_sobrecubierta' || $servicio->nombre == 'solapas_faja') {
@ -2857,9 +2911,10 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
$coste_servicios += round(floatval($resultado[0]->total), 2);
if ($extra_info) {
$totalServicios += round(floatval($resultado[0]->total), 2);
//$totalServicios += round(floatval($resultado[0]->total), 2);
$base = round(floatval($resultado[0]->total / (1 + $resultado[0]->margen / 100.0)), 2);
$base = round(floatval($base / $cantidad_total), 2) * $cantidad_total;
$totalServicios += $base;
$margenServicios += round(floatval($resultado[0]->total - $base), 2);
}
}
@ -2898,9 +2953,10 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
$coste_servicios += round(floatval($resultado[0]->precio), 2);
if ($extra_info) {
$totalServicios += round(floatval($resultado[0]->precio), 2);
//$totalServicios += round(floatval($resultado[0]->precio), 2);
$base = round(floatval($resultado[0]->precio / (1 + $resultado[0]->margen / 100.0)), 2);
$base = round(floatval($base / $cantidad_total), 2) * $cantidad_total;
$totalServicios += $base;
$margenServicios += round(floatval($resultado[0]->precio - $base), 2);
}
}
@ -2937,9 +2993,10 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
$coste_servicios += round(floatval($resultado[0]->total), 2);
if ($extra_info) {
$totalServicios += round(floatval($resultado[0]->total), 2);
//$totalServicios += round(floatval($resultado[0]->total), 2);
$base = round(floatval($resultado[0]->total / (1 + $resultado[0]->margen / 100.0)), 2);
$base = round(floatval($base / $cantidad_total), 2) * $cantidad_total;
$totalServicios += $base;
$margenServicios += round(floatval($resultado[0]->total - $base), 2);
}
}
@ -2974,9 +3031,10 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
$coste_servicios += round(floatval($resultado[0]->total), 2);
if ($extra_info) {
$totalServicios += round(floatval($resultado[0]->total), 2);
//$totalServicios += round(floatval($resultado[0]->total), 2);
$base = round(floatval($resultado[0]->total / (1 + $resultado[0]->margen / 100.0)), 2);
$base = round(floatval($base / $cantidad_total), 2) * $cantidad_total;
$totalServicios += $base;
$margenServicios += round(floatval($resultado[0]->total - $base), 2);
}
}
@ -3011,19 +3069,23 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
$coste_servicios += round(floatval($resultado[0]->total), 2);
if ($extra_info) {
$totalServicios += round(floatval($resultado[0]->total), 2);
//$totalServicios += round(floatval($resultado[0]->total), 2);
$base = round(floatval($resultado[0]->total / (1 + $resultado[0]->margen / 100.0)), 2);
$base = round(floatval($base / $cantidad_total), 2) * $cantidad_total;
$totalServicios += $base;
$margenServicios += round(floatval($resultado[0]->total - $base), 2);
}
}
$total_por_tirada = $costeInterior +
/*$total_por_tirada = $costeInterior +
$coste_cubierta +
$coste_sobrecubierta +
$coste_guardas +
$coste_faja +
$costeServiciosDefecto + $coste_servicios;
$costeServiciosDefecto + $coste_servicios;*/
$total_por_tirada = $totalPapel + $margenPapel +
$totalImpresion + $margenImpresion +
$totalServicios + $margenServicios;
array_push(
$precio_u,
round(($total_por_tirada) / $tirada[$t], 4)
@ -3031,7 +3093,7 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
array_push($peso, round($peso_interior + $peso_cubierta + $peso_sobrecubierta + $peso_guardas + $peso_faja, 2));
if ($extra_info) {
$totalServicios -= $margenServicios;
//$totalServicios -= $margenServicios;
if (($margenServicios + $totalServicios) > 0) {
$porcentajeMargenServicios = $margenServicios / ($totalServicios) * 100;
} else {
@ -3047,20 +3109,26 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
'totalImpresion' => $totalImpresion,
'margenImpresion' => $margenImpresion,
'sumForFactor' => $sumForFactor,
'sumForFactorPonderado' => $sumForFactorPonderado,
'totalServicios' => $totalServicios,
'margenServicios' => $margenServicios,
'porcentajeMargenPapel' => $porcentajeMargenPapel,
'porcentajeMargenImpresion' => $porcentajeMargenImpresion,
'porcentajeMargenServicios' => $porcentajeMargenServicios
'porcentajeMargenPapel' => round($porcentajeMargenPapel, 0),
'porcentajeMargenImpresion' => round($porcentajeMargenImpresion, 0),
'porcentajeMargenServicios' => round($porcentajeMargenServicios, 0),
'sumForFactor' => $sumForFactor,
'sumForFactorPonderado' => $sumForFactorPonderado,
'total' => round($total_por_tirada, 2),
'precio_u' => round(($total_por_tirada) / $tirada[$t], 4),
));
}
$info['lomo_cubierta'] = round(floatval($lomo), 2);
$info['lomo_sobrecubierta'] = round(floatval($lomo_sobrecubierta), 2);
if (intval($tirada[$t]) == intval($selected_tirada)) {
$info['lomo_cubierta'] = round(floatval($lomo), 2);
$info['lomo_sobrecubierta'] = round(floatval($lomo_sobrecubierta), 2);
}
$return_data['info'] = $info;
@ -3112,12 +3180,14 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
return;
$totalPapel += round($linea['precio_pedido'], 2);
$totalPapel -= round($linea['margen_papel_pedido'], 2);
$totalPapel = round($totalPapel, 2);
$sumForFactor += round($linea['precio_pedido'], 2)
- round($linea['margen_papel_pedido'], 2);
$margenPapel += round($linea['margen_papel_pedido'], 2);
$totalImpresion += round($linea['precio_click_pedido'], 2);
$totalImpresion -= round($linea['margen_click_pedido'], 2);
$totalImpresion = round($totalImpresion, 2);
$sumForFactor += round($linea['precio_click_pedido'], 2)
- round($linea['margen_click_pedido'], 2);
@ -3132,6 +3202,7 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
$margenImpresion += round($linea['precio_impresion_horas'], 2); // coste de maquina y magen son MARGEN, no COSTE
$margenImpresion += round($linea['margen_impresion_horas'], 2);
$margenImpresion += round($linea['margen_click_pedido'], 2);
$margenImpresion = round($margenImpresion, 2);
}

View File

@ -80,7 +80,7 @@ class ServiciosAcabado extends BaseResourceController
$sanitizedData['user_updated_id'] = auth()->user()->id;
if ($this->request->getPost('mostrar_en_presupuesto_cliente') == null) {
$sanitizedData['mostrar_en_presupuesto'] = false;
$sanitizedData['mostrar_en_presupuesto_cliente'] = false;
}
if ($this->request->getPost('acabado_cubierta') == null) {
@ -174,7 +174,7 @@ class ServiciosAcabado extends BaseResourceController
$sanitizedData['user_updated_id'] = auth()->user()->id;
if ($this->request->getPost('mostrar_en_presupuesto_cliente') == null) {
$sanitizedData['mostrar_en_presupuesto'] = false;
$sanitizedData['mostrar_en_presupuesto_cliente'] = false;
}
if ($this->request->getPost('acabado_cubierta') == null) {

View File

@ -0,0 +1,47 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class LomoMaximoLibros extends Migration
{
public function up()
{
// Renombrar campo
$this->db->table('config_variables_app')
->where('name', 'lomo_maximo')
->set('name', 'lomo_maximo_fresado_cosido')
->update();
// Insertar nuevo campo: lomo_maximo_espiral
$this->db->table('config_variables_app')->insert([
'name' => 'lomo_maximo_espiral',
'value' => '45',
'description' => 'Tamaño máximo (mm) para el lomo de los libros espiral',
'created_at' => date('Y-m-d H:i:s')
]);
// Insertar nuevo campo: lomo_maximo_wireo
$this->db->table('config_variables_app')->insert([
'name' => 'lomo_maximo_wireo',
'value' => '26',
'description' => 'Tamaño máximo (mm) para el lomo de los libros wire-O',
'created_at' => date('Y-m-d H:i:s')
]);
}
public function down()
{
// Revertir nombre
$this->db->table('config_variables_app')
->where('name', 'lomo_maximo_fresado_cosido')
->set('name', 'lomo_maximo')
->update();
// Borrar los nuevos campos
$this->db->table('config_variables_app')->whereIn('name', [
'lomo_maximo_espiral',
'lomo_maximo_wireo'
])->delete();
}
}

View File

@ -31,6 +31,12 @@ return [
'libroWireoTapaBlanda' => "Wire-o Tapa Blanda",
'libroGrapado' => "Grapado",
'cosido' => 'Cosido',
'fresado' => 'Fresado',
'espiral' => 'Espiral',
'wireo' => 'Wire-o',
'grapado' => 'Grapado',
'datosPresupuesto' => 'Datos generales del presupuesto',
'datosLibro' => 'Datos del libro',
'datosServicios' => 'Otros Servicios',
@ -380,6 +386,18 @@ return [
],
'validation' => [
'fix_errors' => 'Corrija los siguientes errores antes de continuar:',
'titulo_requerido' => 'El campo "Título" es obligatorio.',
'tirada_integer_greatherThan_0' => 'Los valores de las tiradas deben ser enteros mayores que 0.',
'tirada_pod_nopod' => 'No se pueden mezclar tiradas POD (menor o igual que 30 unidades) con tiradas no POD (mayor que 30 unidades).',
'papelFormatoAncho' => 'Seleccione un ancho de libro válido.',
'papelFormatoAlto' => 'Seleccione un alto de libro válido.',
'papelFormato' => 'Seleccione un formato de libro válido.',
'paginasColor' => 'El número de páginas a color debe ser un número entero mayor o igual que 0.',
'paginasNegro' => 'El número de páginas en negro debe ser un número entero mayor o igual que 0.',
'paginas' => 'El total de páginas tiene que ser mayor que 0.',
'paginas_pares' => 'El número de páginas debe ser par.',
'tipo_libro' => 'Seleccione el tipo de libro que desea para el presupuesto.',
'decimal' => 'El campo {field} debe contener un número decimal.',
'integer' => 'El campo {field} debe contener un número entero.',
'requerido' => 'El campo {field} es obligatorio.',
@ -388,19 +406,34 @@ return [
'no_lp_for_merma' => 'Inserte líneas de presupuesto para calcular la merma',
'ejemplares_envio' => 'El número de ejemplares enviados no coincide con la tirada',
'cliente' => 'Debe seleccionar un cliente',
'papelFormato' => 'Seleccione un formato',
'tipo_libro' => 'Seleccione un tipo de libro',
'disenio_interior' => 'Seleccione el diseño del interior',
'papel_interior' => 'Seleccione el tipo de papel',
'gramaje_interior' => 'Seleccione el gramaje',
'disenio_interior' => 'Seleccione el tipo de impresión del interior',
'papel_interior' => 'Seleccione el tipo de papel para el interior',
'papel_interior_especial' => 'Seleccione el papel especial en el desplegable para el interior',
'gramaje_interior' => 'Seleccione el gramaje para el interior',
'tipo_cubierta' => 'Seleccione el tipo de cubierta',
'papel_guardas' => 'Seleccione el tipo de papel para las guardas',
'gramaje_guardas' => 'Seleccione el gramaje para las guardas',
'papel_cubierta' => 'Seleccione el tipo de papel para la cubierta',
'papel_cubierta_especial' => 'Seleccione el papel especial en el desplegable para la cubierta',
'gramaje_cubierta' => 'Seleccione el gramaje para la cubierta',
'papel_sobrecubierta' => 'Seleccione el tipo de papel para la sobrecubierta',
'gramaje_sobrecubierta' => 'Seleccione el gramaje para la sobrecubierta',
'papel_faja' => 'Seleccione el tipo de papel para la faja',
'gramaje_faja' => 'Seleccione el gramaje para la faja',
'unidades_envio_mayor_tirada' => 'El número de unidades enviadas debe ser igual a {field} unidades.',
'pais' => 'Debe seleccionar un país',
'integer_greatherThan_0' => 'Número entero > 0 requerido',
'greater_than_0' => 'El campo {field} debe ser mayor que 0',
'tirada_no_valida' => "Tirada no valida",
'sin_gramaje' => "Seleccione gramaje",
'tipo_cubierta' => 'Seleccione tipo de cubierta',
'opcion_solapas' => 'Seleccione la opción para las solapas',
'paginas_multiplo_4' => 'El número de páginas para <b>cosido</b> o <b>grapado</b> debe ser múltiplo de 4',
'paginas_multiplo_4' => 'El número total de páginas para <b>cosido</b> y <b>grapado</b> debe ser múltiplo de 4',
'paginas_pares' => 'El número de páginas debe ser par',
'extras_cubierta' => 'Rellene todos los campos',
],
@ -425,7 +458,11 @@ return [
'noCubiertaSobrecubierta' => 'No se hay resultados para cubierta/sobrecubierta',
'errorPresupuesto' => 'Se ha producido un error al calcular el presupuesto. Póngase en contacto con el administrador',
'error_sobrecubierta_sin_solapas' => 'Debe seleccionar "sobrecubierta" en los datos del libro para introducir el ancho de solapa',
'error_faja_sin_solapas' => 'Debe seleccionar "faja" en los datos del libro para introducir el ancho de solapa'
'error_faja_sin_solapas' => 'Debe seleccionar "faja" en los datos del libro para introducir el ancho de solapa',
'error_lomo_maximo' => "No se pueden encuadernar libros {0} con un lomo interior superior a {1} mm. El lomo actual es de {2} mm. <br>
Por favor, disminuya el número de páginas o el gramaje del papel para que sea encuadernable.",
'error_lomo_minimo' => "No se pueden encuadernar libros {0} con un lomo interior inferior a {1} mm. El lomo actual es de {2} mm. <br>
Por favor, aumente el número de páginas o el gramaje del papel para que sea encuadernable.",
],
'resize_preview' => 'Refrescar vista esquema'

View File

@ -241,6 +241,8 @@ class PedidoLineaModel extends \App\Models\BaseModel
// Ejecutar la consulta y devolver resultados
$query = $builder->get();
$data = $query->getResult();
$query_text = $this->db->getLastQuery();
foreach($data as $register) {
$item = (object)[

View File

@ -509,7 +509,11 @@ class PresupuestoModel extends \App\Models\BaseModel
$totalCostes + $totalMargenes +
$resumen_totales['coste_envio']+$resumen_totales['margen_envio'] +
$data['envio_base'], 2),
'total_aceptado' => round($totalCostes + $totalMargenes + $resumen_totales['coste_envio']+$resumen_totales['margen_envio'], 2),
'total_aceptado' => round(
$totalCostes + $totalMargenes +
$resumen_totales['coste_envio']+$resumen_totales['margen_envio'] +
$data['envio_base'], 2
),
'total_factor' => round(
($totalCostes + $totalMargenes ) /

View File

@ -2077,18 +2077,20 @@ class PresupuestoService extends BaseService
$merma = 0;
if ($tirada == 0) {
if ($tirada == 1) {
$merma = 0;
}
else if ($tirada > $POD) {
} else if ($tirada > intval($POD)) {
$merma = $tirada * 0.1;
} else {
$merma_lineas = [];
foreach ($formas_lineas_interior as $formas_linea) {
if ($formas_linea > $tirada)
array_push($merma_lineas, $formas_linea - $tirada);
else
array_push($merma_lineas, $tirada % $formas_linea);
else {
$total_pliegos = ceil($tirada / $formas_linea);
$total_formas = $total_pliegos * $formas_linea;
array_push($merma_lineas, $total_formas - $tirada);
}
}
if (count($merma_lineas) > 0)
$merma = max($merma_lineas);
@ -2124,27 +2126,25 @@ class PresupuestoService extends BaseService
$presupuesto->titulo = $presupuesto->titulo . ' - ' . lang('Presupuestos.duplicado');
$presupuesto->is_duplicado = 1;
$presupuesto->estado_id = 1;
if($is_reimpresion && boolval($copy_files)){
if ($is_reimpresion && boolval($copy_files)) {
$presupuesto->inc_rei = "reimpresion";
$modelPedidoLinea = model('App\Models\Pedidos\PedidoLineaModel');
$pedido_linea = $modelPedidoLinea->where('presupuesto_id', $id)->first();
if($pedido_linea){
$text = "REIMPRESION [" . date('Y-m-d H:i:s') . "] - PEDIDO: " . $pedido_linea->pedido_id .
"\n================================================\n";
$presupuesto->comentarios_safekat = $text . $presupuesto->comentarios_safekat ;
}
}
else if($is_reimpresion){
$presupuesto->inc_rei = null;
$modelPedidoLinea = model('App\Models\Pedidos\PedidoLineaModel');
$pedido_linea = $modelPedidoLinea->where('presupuesto_id', $id)->first();
if($pedido_linea){
$text = "DUPLICADO [" . date('Y-m-d H:i:s') . "] - PEDIDO: " . $pedido_linea->pedido_id .
if ($pedido_linea) {
$text = "REIMPRESION [" . date('Y-m-d H:i:s') . "] - PEDIDO: " . $pedido_linea->pedido_id .
"\n================================================\n";
$presupuesto->comentarios_safekat = $text . $presupuesto->comentarios_safekat;
}
}
else{
} else if ($is_reimpresion) {
$presupuesto->inc_rei = null;
$modelPedidoLinea = model('App\Models\Pedidos\PedidoLineaModel');
$pedido_linea = $modelPedidoLinea->where('presupuesto_id', $id)->first();
if ($pedido_linea) {
$text = "DUPLICADO [" . date('Y-m-d H:i:s') . "] - PEDIDO: " . $pedido_linea->pedido_id .
"\n================================================\n";
$presupuesto->comentarios_safekat = $text . $presupuesto->comentarios_safekat;
}
} else {
$presupuesto->inc_rei = null;
}
$new_id = $modelPresupuesto->insert($presupuesto);
@ -2189,7 +2189,7 @@ class PresupuestoService extends BaseService
$presupuestoLineaModel->duplicateLineasPresupuesto($presupuesto->id, $new_id);
if (boolval($copy_files)== true) {
if (boolval($copy_files) == true) {
$presupuestoFilesModel = model('App\Models\Presupuestos\PresupuestoFicheroModel');
$presupuestoFilesModel->copyFiles($presupuesto->id, $new_id);
}
@ -2197,7 +2197,7 @@ class PresupuestoService extends BaseService
return [
'success' => true,
'id' => $new_id,
'message' => lang('Presupuestos.presupuestoGenerado'),
'message' => lang('Presupuestos.presupuestoGenerado'),
];
} catch (\Exception $e) {
@ -2207,4 +2207,96 @@ class PresupuestoService extends BaseService
];
}
}
public static function check_lomo_interior($tipo_impresion_id, $lomo = 0)
{
$lomo_maximo = 0;
$lomo_minimo = 0;
if ($lomo == 0) {
return [
'status' => true,
'message' => 'Lomo interior 0'
];
}
switch ($tipo_impresion_id) {
case 1: // Fresado
case 2:
case 3: // Cosido
case 4:
$lomo_minimo = intval(model('App\Models\Configuracion\ConfigVariableModel')->getVariable('lomo_minimo_fresado_cosido')->value);
$lomo_maximo = intval(model('App\Models\Configuracion\ConfigVariableModel')->getVariable('lomo_maximo_fresado_cosido')->value);
if ($lomo != 0 && $lomo < $lomo_minimo) {
return [
'status' => false,
'message' => lang(
'Presupuestos.errores.error_lomo_minimo',
[
lang('Presupuestos.cosido') . "/" . lang('Presupuestos.fresado'),
$lomo_minimo,
$lomo,
]
)
];
} else if ($lomo != 0 && $lomo > $lomo_maximo) {
return [
'status' => false,
'message' => lang(
'Presupuestos.errores.error_lomo_maximo',
[
lang('Presupuestos.cosido') . "/" . lang('Presupuestos.fresado'),
$lomo_maximo,
$lomo,
]
)
];
}
break;
case 5: // Espiral
case 6:
$lomo_maximo = intval(model('App\Models\Configuracion\ConfigVariableModel')->getVariable('lomo_maximo_espiral')->value);
if ($lomo != 0 && $lomo > $lomo_maximo) {
return [
'status' => false,
'message' => lang(
'Presupuestos.errores.error_lomo_maximo',
[
lang('Presupuestos.espiral'),
$lomo_maximo,
$lomo,
]
)
];
}
break;
case 7: // Wire-O
case 8:
$lomo_maximo = intval(model('App\Models\Configuracion\ConfigVariableModel')->getVariable('lomo_maximo_wireo')->value);
$lomo_maximo = intval(model('App\Models\Configuracion\ConfigVariableModel')->getVariable('lomo_maximo_espiral')->value);
if ($lomo != 0 && $lomo > $lomo_maximo) {
return [
'status' => false,
'message' => lang(
'Presupuestos.errores.error_lomo_maximo',
[
lang('Presupuestos.wireo'),
$lomo_maximo,
$lomo,
]
)
];
}
break;
default:
return [
'status' => true,
'message' => 'Lomo valido'
];
}
return [
'status' => true,
'message' => 'Lomo valido'
];
}
}

View File

@ -10,7 +10,7 @@
<div id="accordionFacturasTip" class="accordion-collapse collapse show" data-bs-parent="#accordioFacturas">
<div class="accordion-body">
<?php if ($pedidoEntity->estado == 'finalizado') : ?>
<?php if ($pedidoEntity->estado == 'finalizado' || $pedidoEntity->estado == 'enviado' || $pedidoEntity->estado == 'produccion') : ?>
<div class="d-flex justify-content-end">
<button type="button" class="btn btn-primary btn-md" id="add-factura" ><span><?= lang("Pedidos.addFactura") ?><i class="ti ti-receipt-2 ti-xs"></i></span></button>
</div>

View File

@ -14,6 +14,7 @@
<?= csrf_field() ?>
<?= view("themes/_commonPartialsBs/_alertBoxes") ?>
<div id="sk-alert-lomo"></div>
<?= view("themes/vuexy/form/presupuestos/cliente/loader") ?>
<?= !empty($validation->getErrors()) ? $validation->listErrors("bootstrap_style") : "" ?>

View File

@ -66,8 +66,8 @@
<div id="divExcluirRotativa"
class="col-sm-5 mb-3 d-flex flex-column align-items-center <?= (auth()->user()->inGroup('cliente-admin') || auth()->user()->inGroup('cliente-editor')) ? " d-none" : "" ?>">
<div class="form-check form-switch mb-2">
<input <?= (auth()->user()->inGroup('cliente-admin') || auth()->user()->inGroup('cliente-editor')) ? " hidden" : "" ?> class=" calcular-solapas calcular-presupuesto form-check-input" type="checkbox" id="excluirRotativa"
name="excluir_rotativa" value="1">
<input <?= (auth()->user()->inGroup('cliente-admin') || auth()->user()->inGroup('cliente-editor')) ? " hidden" : "" ?> class=" calcular-solapas calcular-presupuesto form-check-input" type="checkbox"
id="excluirRotativa" name="excluir_rotativa" value="1">
<label <?= (auth()->user()->inGroup('cliente-admin') || auth()->user()->inGroup('cliente-editor')) ? " hidden" : "" ?> class="form-check-label" for="excluirRotativa">Excluir rotativa</label>
</div>
</div>
@ -78,32 +78,36 @@
<label for="tirada" class="form-label">
<?= lang('Presupuestos.tirada') ?> 1*
</label>
<input type="number" class="calcular-presupuesto calcular-solapas form-control text-center num-input" id="tirada"
name="tirada" step="1" value="50">
<input type="number"
class="calcular-presupuesto calcular-solapas form-control text-center num-input tirada-presupuesto"
id="tirada" name="tirada" step="1" value="50">
</div>
<div class="col-sm-2 d-flex flex-column align-items-center mx-1 div-num-input">
<label for="tirada2" class="form-label">
<?= lang('Presupuestos.tirada') ?> 2
</label>
<input type="number" class="calcular-presupuesto calcular-solapas form-control text-center num-input" id="tirada2"
name="tirada2" step="1" value="">
<input type="number"
class="calcular-presupuesto calcular-solapas form-control text-center num-input tirada-presupuesto"
id="tirada2" name="tirada2" step="1" value="">
</div>
<div class="col-sm-2 d-flex flex-column align-items-center mx-1 div-num-input">
<label for="tirada3" class="form-label">
<?= lang('Presupuestos.tirada') ?> 3
</label>
<input type="number" class="calcular-presupuesto calcular-solapas form-control text-center num-input" id="tirada3"
name="tirada3" step="1" value="">
<input type="number"
class="calcular-presupuesto calcular-solapas form-control text-center num-input tirada-presupuesto"
id="tirada3" name="tirada3" step="1" value="">
</div>
<div class="col-sm-2 d-flex flex-column align-items-center mx-1 div-num-input">
<label for="tirada4" class="form-label">
<?= lang('Presupuestos.tirada') ?> 4
</label>
<input type="number" class="calcular-presupuesto calcular-solapas form-control text-center num-input" id="tirada4"
name="tirada4" step="1" value="">
<input type="number"
class="calcular-presupuesto calcular-solapas form-control text-center num-input tirada-presupuesto"
id="tirada4" name="tirada4" step="1" value="">
</div>
</div> <!--//.row -->
@ -113,8 +117,8 @@
<label id="label_papelFormatoId" for="papelFormatoId" class="form-label">
Formato Libro*
</label>
<select id="papelFormatoId" name="papel_formato_id" class="form-control select2bs2 calcular-presupuesto calcular-solapas"
style="width: 100%;">
<select id="papelFormatoId" name="papel_formato_id"
class="form-control select2bs2 calcular-presupuesto calcular-solapas" style="width: 100%;">
</select>
</div>
@ -123,21 +127,23 @@
<div class="col-sm-3 mb-1 mx-1 div-num-input">
<label class="form-label" for="papelFormatoAncho">Ancho Libro*</label>
<input type="number" id="papelFormatoAncho" name="papel_formato_ancho" step="1"
class="form-control formato_libro calcular-presupuesto calcular-solapas num-input" min="110" value="110">
class="form-control formato_libro calcular-presupuesto calcular-solapas num-input" min="110"
value="110">
</div>
<div class="col-sm-3 mb-1 mx-1 div-num-input">
<label class="form-label" for="papelFormatoAlto">Alto Libro*</label>
<input type="number" id="papelFormatoAlto" name="papel_formato_alto" step="1"
class="form-control formato_libro calcular-presupuesto calcular-solapas num-input" min="170" value="170">
class="form-control formato_libro calcular-presupuesto calcular-solapas num-input" min="170"
value="170">
</div>
</div>
<div class="row col-sm-4 mb-3 d-flex flex-column align-items-center">
<div class="form-check form-switch mb-2">
<input class="calcular-presupuesto calcular-solapas form-check-input" type="checkbox" id="papelFormatoPersonalizado"
name="papel_formato_personalizado" value="1">
<input class="calcular-presupuesto calcular-solapas form-check-input" type="checkbox"
id="papelFormatoPersonalizado" name="papel_formato_personalizado" value="1">
<label class="form-check-label"
for="papelFormatoPersonalizado"><?= lang('Presupuestos.papelFormatoPersonalizado') ?></label>
</div>
@ -146,15 +152,15 @@
</div>
<div class="row col-sm-9 mb-5 justify-content-center">
<div class="row col-sm-9 mb-3 justify-content-center">
<div class="row justify-content-center">
<div class="col-sm-3">
<label for="paginasColor" class="form-label">
<?= lang('Presupuestos.paginasColor') ?>
</label>
<input type="number" class="form-control calcular-presupuesto calcular-solapas input-paginas num-input" id="paginasColor"
name="paginasColor" step="1" value="0">
<input type="number" step="2" class="form-control calcular-presupuesto calcular-solapas input-paginas num-input"
id="paginasColor" name="paginasColor" step="1" value="0">
<div class="form-text">
Siempre deben ser pares
@ -166,8 +172,8 @@
<label for="paginasNegro" class="form-label">
<?= lang('Presupuestos.paginasNegro') ?>
</label>
<input type="number" class="form-control calcular-presupuesto calcular-solapas input-paginas num-input" id="paginasNegro"
name="paginasNegro" step="1" value="32">
<input type="number" step="2" class="form-control calcular-presupuesto calcular-solapas input-paginas num-input"
id="paginasNegro" name="paginasNegro" step="1" value="32">
<div class="form-text">
Siempre deben ser pares
@ -179,8 +185,7 @@
<label for="paginas" class="form-label">
<?= lang('Presupuestos.totalPaginas') ?>
</label>
<input disabled class="form-control calcular-lomo" id="paginas" name="paginas" step="1"
value="32">
<input disabled class="form-control calcular-lomo" id="paginas" name="paginas" step="1" value="32">
</div>
</div>
@ -230,46 +235,51 @@
</div>
</div>
<div id="divTipoLibro" name="div_tipo_libro" class="row col-sm-10 mb-3 justify-content-center">
<div id="fresado" class="tipo-libro calcular-solapas calcular-presupuesto imagen-selector image-container">
<img class="image-presupuesto" src="<?= site_url("assets/img/presupuestoCliente/fresado.png") ?>"
alt="Fresado">
<div class="form-text text-center">
Fresado (a partir de 32 páginas)
<div id="divTipoLibro" class="container mb-3">
<div class="row justify-content-center">
<div id="fresado"
class="col-12 col-md-4 text-center mb-4 tipo-libro imagen-selector image-container">
<img class="image-presupuesto" src="<?= site_url("assets/img/presupuestoCliente/fresado.png") ?>"
alt="Fresado">
<div class="form-text text-center">Fresado (a partir de 32 páginas)</div>
</div>
</div>
<div id="grapado" class="tipo-libro calcular-solapas calcular-presupuesto imagen-selector image-container">
<img class="image-presupuesto" src="<?= site_url("assets/img/presupuestoCliente/grapado.png") ?>"
alt="Grapado">
<div class="form-text text-center">
Grapado (entre 12 y 40 páginas)
<div id="cosido"
class="col-12 col-md-4 text-center mb-4 tipo-libro imagen-selector image-container">
<img class="image-presupuesto" src="<?= site_url("assets/img/presupuestoCliente/cosido.png") ?>"
alt="Cosido">
<div class="form-text text-center">Cosido (a partir de 32 páginas)</div>
</div>
</div>
<div id="espiral" class="tipo-libro calcular-solapas calcular-presupuesto imagen-selector image-container">
<img class="image-presupuesto" src="<?= site_url("assets/img/presupuestoCliente/espiral.png") ?>"
alt="Espiral">
<div class="form-text text-center">
Espiral
<div id="grapado"
class="col-12 col-md-4 text-center mb-4 tipo-libro imagen-selector image-container">
<img class="image-presupuesto" src="<?= site_url("assets/img/presupuestoCliente/grapado.png") ?>"
alt="Grapado">
<div class="form-text text-center">Grapado (entre 12 y 40 páginas)</div>
</div>
</div>
<div id="cosido" class="tipo-libro calcular-solapas calcular-presupuesto imagen-selector image-container">
<img class="image-presupuesto" src="<?= site_url("assets/img/presupuestoCliente/cosido.png") ?>"
alt="Cosido">
<div class="form-text text-center">
Cosido (a partir de 32 páginas)
<div id="espiral"
class="col-12 col-md-4 text-center mb-4 tipo-libro imagen-selector image-container">
<img class="image-presupuesto" src="<?= site_url("assets/img/presupuestoCliente/espiral.png") ?>"
alt="Espiral">
<div class="form-text text-center">Espiral (a partir de 20 páginas)</div>
</div>
<div id="wireo"
class="col-12 col-md-4 text-center mb-4 tipo-libro imagen-selector image-container">
<img class="image-presupuesto" src="<?= site_url("assets/img/presupuestoCliente/wire-o.png") ?>"
alt="Wire-O">
<div class="form-text text-center">Wire-O (a partir de 20 páginas)</div>
</div>
</div>
</div>
<div class="col-sm-8 mb-3 d-flex flex-column align-items-center">
<h3 class="mb-1 fw-bold"> Servicios extra </h3>
</div>
<div class="row col-sm-8 mb-3 d-flex flex-column align-items-left">
<div class="row align-items-center" >
<div class="row align-items-center">
<div class="col-sm-3 form-check form-switch mb-2 d-flex align-items-center gap-2">
<input class="calcular-presupuesto form-check-input" type="checkbox" id="retractilado"
name="retractilado" value="1">

View File

@ -62,8 +62,6 @@
</div>
</div>
<div id="divErrorEnvios" name="div_error_envios" class="col-sm-10 mb-3 justify-content-center"></div>
<div id="divDirecciones" class="calcular-presupuesto col-sm-12 d-flex flex-column align-items-center div-direcciones">
</div>

View File

@ -5,7 +5,7 @@
<div class="col-sm-8 mb-3 d-flex flex-column align-items-center">
<h5 class="mb-1 "> Precio unidad: <span id="resumenPrecioU"></span> </h5>
<h4 class="mb-1 "> Total base: <span id="resumenTotalBase"></span> </h4>
<h4 class="mt-3 mb-1 "> Total base: <span id="resumenTotalBase"></span> </h4>
<h4 class="mb-1 "> Envío: <span id="resumenTotalEnvio"></span> </h4>
<h4 class="mb-1 "> Total antes de I.V.A: <span id="resumenTotalAntesIVA"></span> </h4>
<h4 class="mb-1 "> Iva (<span id="resumenIvaPorcentaje"></span>%): <span id="resumenIva"></span> </h4>

View File

@ -20,12 +20,23 @@
<?php endif; ?>
<?= csrf_field() ?>
<?= view("themes/_commonPartialsBs/_alertBoxes") ?>
<div id="sk-alert-lomo">
</div>
<div id="alert-cubierta-sin-acabado" class="alert alert-warning d-flex align-items-baseline d-none" role="alert">
<span class="alert-icon alert-icon-lg text-primary me-2">
<i class="ti ti-bell ti-sm"></i>
</span>
<div class="d-flex flex-column ps-1">
<h5 class="alert-heading mb-2"><?= lang('Presupuestos.cubiertaSinAcabadoText') ?></h5>
</div>
</div>
<?= !empty($validation->getErrors()) ? $validation->listErrors("bootstrap_style") : "" ?>
<input hidden id="lc" value=""></input>
<input hidden id="lsc" value=""></input>
<input readonly hidden id="pod" value="<?= $POD ?>"></input>
<input readonly hidden id="lomo_maximo" value="<?= $lomo_maximo ?>"></input>
<input readonly hidden id="lomo_maximo_fresado_cosido" value="<?= $lomo_maximo_fresado_cosido ?>"></input>
<input readonly hidden id="lomo_minimo_fresado_cosido" value="<?= $lomo_minimo_fresado_cosido ?>"></input>
<input readonly hidden id="pod" value="<?= $POD ?>"></input>
<input readonly hidden id="c" value="<?= $clienteId ?>"></input>

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 MiB

View File

@ -0,0 +1,3 @@
[ZoneTransfer]
ZoneId=3
HostUrl=https://chatgpt.com/

View File

@ -64,6 +64,49 @@ class PresupuestoAdminAdd {
this.tamanioPersonalizado.on('change', this.changeTipoTamanio.bind(this));
this.guardar.on('click', this.guardarPresupuesto.bind(this));
this.tirada.on('change', this.calcular_mermas.bind(this));
actualizarLimitesPaginas();
}
actualizarLimitesPaginas() {
let min = 1;
let max = null;
switch (this.tipo_impresion.val()) {
case 1: // Fresado
case 2:
case 3: // Cosido
case 4:
min = 32;
max = null; // Sin límite superior
break;
case 5: // Espiral
case 6:
case 7: // Wire-O
case 8:
min = 1;
max = null; // Sin límite superior
break;
case 21: // Grapado
min = 12;
max = 4;
break;
default:
min = 1;
max = null;
}
this.paginas.attr('min', min);
this.paginas.attr('max', max);
// Verificamos y corregimos el valor actual si está fuera de rango
let valorActual = parseInt(this.paginas.val(), 10);
if (isNaN(valorActual) || valorActual < min) {
this.paginas.val(min);
} else if (valorActual > max) {
this.paginas.val(max);
}
}
changeTipoTamanio() {

View File

@ -354,7 +354,7 @@ class PresupuestoAdminEdit {
// Ejecutar los pasos de forma secuencial si están habilitados
if (update_lineas) {
$(document).trigger('update-lineas-presupuesto');
await waitForEvent('update-lineas-presupuesto-completed');
await waitForEvent('update-lineas-presupuesto-completed');
}
if (update_servicios) {
@ -698,30 +698,30 @@ class PresupuestoAdminEdit {
buttonsStyling: false
}).then((result) => {
if (result.isDenied || result.isConfirmed) {
new Ajax('/presupuestoadmin/reprint',
{ id: id, duplicateFiles: result.isConfirmed ? 1 : 0 }, {},
function (response) {
if (response.success === true) {
Swal.fire({
text: response.message,
icon: 'success',
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
})
window.open('/presupuestoadmin/edit/' + response.id, '_blank');
} else {
popErrorAlert(response.mensaje);
new Ajax('/presupuestoadmin/reprint',
{ id: id, duplicateFiles: result.isConfirmed ? 1 : 0 }, {},
function (response) {
if (response.success === true) {
Swal.fire({
text: response.message,
icon: 'success',
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
})
window.open('/presupuestoadmin/edit/' + response.id, '_blank');
} else {
popErrorAlert(response.mensaje);
}
},
function (error) {
popErrorAlert(error);
}
},
function (error) {
popErrorAlert(error);
}
).post();
}
).post();
}
});
}

View File

@ -1213,7 +1213,7 @@ class Comparador {
}
const datosPedido = {
let datosPedido = {
paginas: paginas,
tirada: $('#tirada').val(),
merma: $('#merma').val(),
@ -1262,7 +1262,14 @@ class Comparador {
}
else if (uso == 'guardas') {
datos.datosPedido.isCosido = 1;
// Para el caso de Fresado y Cosido tapa dura, las guardas son un diptico
// y hay que imprimirlas como "cosido" (dos hojas pegadas). En el caso de espiral
// o wire-o tapa dura, las guardas se imprimen como hojas sueltas
if (this.tipo_impresion_id == 1 || this.tipo_impresion_id == 3) {
datos.datosPedido.isCosido = 1;
} else if (this.tipo_impresion_id == 5 || this.tipo_impresion_id == 7) {
datos.datosPedido.isCosido = 0;
}
datos.datosPedido.isHq = 1;
datos.paginas_color = datos.datosPedido.paginas;
datos.paginas_impresion = this.carasGuardas.val();
@ -1458,7 +1465,7 @@ class Comparador {
return;
}
if (this.tipo_impresion_id != 5 && this.tipo_impresion_id != 6 && this.tipo_impresion_id != 7 && this.tipo_impresion_id != 8 && this.tipo_impresion_id != 21) {
if (this.sobrecubierta.select2('data').length >0 && parseInt(this.sobrecubierta.select2('data')[0].id) == 1) {
if (this.sobrecubierta.select2('data').length > 0 && parseInt(this.sobrecubierta.select2('data')[0].id) == 1) {
datosComp.sobrecubierta = this.getDataForComp('sobrecubierta');
if (datosComp.sobrecubierta.error) {
return;

View File

@ -14,6 +14,8 @@ class DatosLibro {
this.csrf_token = getToken();
this.csrf_hash = $('#mainContainer').find('input[name="' + this.csrf_token + '"]').val();
this.tipo_impresion_id = parseInt($("#tipo_impresion_id").val());
this.paginas = this.domItem.find('#paginas');
this.tirada = this.domItem.find('#tirada');
this.tamanio = new ClassSelect($("#papelFormatoId"), '/papel-formato/getSelect2', window.language.Presupuestos.formatoLibro);
@ -77,6 +79,8 @@ class DatosLibro {
const self = this;
this.actualizarLimitesPaginas();
this.tamanio.init();
this.acabadoCubierta.init();
this.acabadoSobrecubierta.init();
@ -84,7 +88,7 @@ class DatosLibro {
this.acabadoCubierta.item.on('select2:select', function () {
if (this.cargando){
if (this.cargando) {
return;
}
@ -106,9 +110,9 @@ class DatosLibro {
this.acabadoSobrecubierta.item.on('select2:select', function () {
if (this.cargando){
if (this.cargando) {
return;
}
}
if (self.acabadoCubierta.getVal() == 0) {
$(document).trigger('remove-servicio-lineas', 'acabadoSobrecubierta');
@ -125,7 +129,7 @@ class DatosLibro {
}
}
});
this.acabadoFaja.item.on('select2:select', function () {
if (this.cargando)
@ -245,7 +249,7 @@ class DatosLibro {
}
else {
$(document).trigger('remove-servicio-lineas', 'ferro');
if(!this.prototipo.prop('checked')){
if (!this.prototipo.prop('checked')) {
const table = $('#tableOfDireccionesEnvio').DataTable();
const rows = table.rows().data();
for (let i = 0; i < rows.length; i++) {
@ -297,7 +301,7 @@ class DatosLibro {
}
else {
$(document).trigger('remove-servicio-lineas', 'prototipo');
if(!this.ferro.prop('checked')){
if (!this.ferro.prop('checked')) {
const table = $('#tableOfDireccionesEnvio').DataTable();
const rows = table.rows().data();
for (let i = 0; i < rows.length; i++) {
@ -573,6 +577,8 @@ class DatosLibro {
update_tiradas_alternativas: true
});
this.actualizarLimitesPaginas();
}
}
@ -601,7 +607,7 @@ class DatosLibro {
this.updateComparador();
const url = window.location.href;
if (url.includes('edit')) {
$(document).trigger('update-presupuesto', {
@ -754,6 +760,47 @@ class DatosLibro {
this.ferroDigital.prop('checked', datos.ferroDigital);
this.marcapaginas.prop('checked', datos.marcapaginas);
}
actualizarLimitesPaginas() {
let min = 1;
let max = null;
switch (this.tipo_impresion_id) {
case 1: // Fresado
case 2:
case 3: // Cosido
case 4:
min = 32;
max = null; // Sin límite superior
break;
case 5: // Espiral
case 6:
case 7: // Wire-O
case 8:
min = 20;
max = null; // Sin límite superior
break;
case 21: // Grapado
min = 12;
max = 4;
break;
default:
min = 1;
max = null;
}
this.paginas.attr('min', min);
this.paginas.attr('max', max);
// Verificamos y corregimos el valor actual si está fuera de rango
let valorActual = parseInt(this.paginas.val(), 10);
if (isNaN(valorActual) || valorActual < min) {
this.paginas.val(min);
} else if (valorActual > max) {
this.paginas.val(max);
}
}
}

View File

@ -485,7 +485,9 @@ class LineasPresupuesto {
if (lp.tipo == 'lp_guardas')
lp['paginas_impresion'] = lp.paginas_impresion;
});
})
this.checkLomo();
}
async guardarLineasPresupuesto() {
@ -1723,6 +1725,39 @@ class LineasPresupuesto {
this.table.columns.adjust();
this.checkLomo();
}
checkLomo() {
let lomo = 0.0;
for (let i = 0; i < this.table.rows().count(); i++) {
var rowData = this.table.row(i).data();
if (rowData.row_id !== 'lp_cubierta' && rowData.row_id !== 'lp_sobrecubierta' && rowData.row_id !== 'lp_guardas' && rowData.row_id !== 'lp_faja') {
if (rowData.lomo && rowData.lomo !== null && rowData.lomo !== '') {
lomo += parseFloat(rowData.lomo);
}
}
}
new Ajax('/presupuestoadmin/checklomointerior',
{ tipo_impresion_id: $("#tipo_impresion_id").val(), lomo: lomo}, {},
function (response) {
if (response.status !== true) {
popErrorAlert(response.message, 'sk-alert-lomo', false);
$(window).scrollTop(0);
}
else{
popAlert2Hide('sk-alert-lomo');
}
},
function (error) {
popErrorAlert(error.statusText? error.statusText : error);
}
).get();
}

View File

@ -8,6 +8,9 @@ class PreviewFormasAdmin {
this.isCosido = $("#isCosido").val();
this.tipoTapa = tipoTapa;
this.tipo_impresion_id = parseInt($('#tipo_impresion_id').val());
// Container para el esquema de cubierta
this.preview = new preview($('#pv_ec_shape'), tipoLibro, tipoTapa, "fullImage", data);
}
@ -66,8 +69,18 @@ class PreviewFormasAdmin {
$('#tab-pv-guardas').on("click", function () {
let cosidoGuardas = false;
// Para el caso de Fresado y Cosido tapa dura, las guardas son un diptico
// y hay que imprimirlas como "cosido" (dos hojas pegadas). En el caso de espiral
// o wire-o tapa dura, las guardas se imprimen como hojas sueltas
if (self.tipo_impresion_id == 1 || self.tipo_impresion_id == 3) {
cosidoGuardas = true;
} /*else if (self.tipo_impresion_id == 5 || self.tipo_impresion_id == 7) {
cosidoGuardas = false;
}*/
self.preview.setData(self.data);
self.preview.previewInteriorPlana('guardas', self.isCosido, self.tipoTapa.includes("dura") ? 1 : 0);
self.preview.previewInteriorPlana('guardas', cosidoGuardas, self.tipoTapa.includes("dura") ? 1 : 0);
});

View File

@ -214,8 +214,14 @@ class Resumen {
let margen_servicio = parseFloat(rowData.margen);
let importe_fijo = parseFloat(rowData.importe_fijo);
totalServicios += total_servicio
let base = self.roundToTwoDecimals((total_servicio-importe_fijo) / (1 + margen_servicio / 100.0));
margenServicios += self.roundToTwoDecimals(parseFloat(total_servicio - base));
let calculoMargen = self.roundToTwoDecimals((total_servicio-importe_fijo) / parseInt($('#tirada').val()));
calculoMargen = self.roundToTwoDecimals(calculoMargen / (1 + margen_servicio / 100.0));
calculoMargen = total_servicio - self.roundToTwoDecimals(calculoMargen * parseInt($('#tirada').val()));
margenServicios += calculoMargen
/*let base = self.roundToTwoDecimals((total_servicio-importe_fijo) / (1 + margen_servicio / 100.0));
margenServicios += self.roundToTwoDecimals(parseFloat(total_servicio - base));*/
});
}

View File

@ -5,7 +5,6 @@ class DatosGenerales {
constructor(domItem, wizardForm, validatorStepper) {
this.domItem = domItem;
this.allowNext = true;
this.wizardStep = wizardForm.querySelector('#datos-generales');
this.validatorStepper = validatorStepper;
@ -35,6 +34,7 @@ class DatosGenerales {
this.cosido = $(this.domItem.find("#cosido")[0]);
this.grapado = $(this.domItem.find("#grapado")[0]);
this.espiral = $(this.domItem.find("#espiral")[0]);
this.wireo = $(this.domItem.find("#wireo")[0]);
this.tiposLibro = this.domItem.find(".tipo-libro");
@ -78,17 +78,18 @@ class DatosGenerales {
this.cargando = false;
this.initValidation();
this.errores = [];
}
init() {
const self = this;
// Selects
this.formatoLibro.init();
this.cliente.init();
// Inicializa el tipo de impresion
this.#handlePaginas();
@ -102,6 +103,20 @@ class DatosGenerales {
this.pagColorConsecutivas.on('change', this.#handPaginasConsecutivas.bind(this));
this.papelDiferente.on('change', this.#handlePapelDiferente.bind(this));
$('.tirada-presupuesto').on('change', () => {
self.validate(false);
let tiradas = self.getTiradas();
if (!Array.isArray(tiradas)) {
tiradas = [tiradas];
}
const data = {
tiradas: self.getTiradas(),
tiradaSeleccionada: self.selectedTirada || parseInt(self.tirada1.val())
};
$(document).trigger('update-tiradas-envios', data);
});
this.anchoPersonalizado.on("change", this.#checkValue.bind(this));
this.altoPersonalizado.on("change", this.#checkValue.bind(this));
@ -111,303 +126,157 @@ class DatosGenerales {
this.retractilado5.on('change', this.#eventRetractilado.bind(this));
}
initValidation() {
const stepper = this.validatorStepper;
validate(goToNext = true) {
this.formValidation = FormValidation.formValidation(this.wizardStep, {
fields: {
titulo: {
validators: {
notEmpty: {
message: window.translations["validation"].requerido_short
},
}
},
cliente_id: {
validators: {
callback: {
message: window.translations["validation"].cliente,
callback: function (input) {
// Get the selected options
if (!$(this.excluirRotativa).prop('hidden'))
return true;
const options = $("#clienteId").select2('data');
const hasValidOption = options.some(option => parseInt(option.id) > 0);
return options !== null && options.length > 0 && hasValidOption;
},
}
}
},
tirada: {
validators: {
callback: {
message: window.translations["validation"].integer_greatherThan_0,
callback: function (input) {
const value = $("#tirada").val();
const value2 = $("#tirada2").val();
const value3 = $("#tirada3").val();
const value4 = $("#tirada4").val();
let tiradas = [value];
this.errores = [];
if (!(value.length > 0 && Number.isInteger(parseInt(value)) && parseInt(value) > 0)) {
return {
valid: false,
message: window.translations["validation"].integer_greatherThan_0,
};
}
if (value2.length > 0 && Number.isInteger(parseInt(value2)) && parseInt(value2) > 0) {
tiradas.push(value2);
}
if (value3.length > 0 && Number.isInteger(parseInt(value3)) && parseInt(value3) > 0) {
tiradas.push(value3);
}
if (value4.length > 0 && Number.isInteger(parseInt(value4)) && parseInt(value4) > 0) {
tiradas.push(value4);
}
// comprobar si hay valores > 30
const noPOD = (tiradas.some(tirada => parseInt(tirada) > 30));
const siPOD = (tiradas.some(tirada => parseInt(tirada) <= 30));
if (noPOD && siPOD) {
return {
valid: false,
message: "No se pueden mezclar tiradas <30 con >30",
}
}
// Titulo
if (this.titulo.val().trim() === '') {
this.errores.push(window.translations["validation"].titulo_requerido);
this.titulo.addClass('is-invalid');
} else {
this.titulo.removeClass('is-invalid');
}
return true;
},
}
}
},
tirada2: {
validators: {
callback: {
message: window.translations["validation"].integer_greatherThan_0,
callback: function (input) {
let field = $("#tirada2");
field.val(field.val().replace(/[^0-9]/g, ''));
let value = field.value;
if (value == '')
return true;
return value.length > 0 && Number.isInteger(parseInt(value)) && parseInt(value) > 0;
},
}
}
},
tirada3: {
validators: {
callback: {
message: window.translations["validation"].integer_greatherThan_0,
callback: function (input) {
let field = $("#tirada3");
field.val(field.val().replace(/[^0-9]/g, ''));
let value = field.value;
if (value == '')
return true;
return value.length > 0 && Number.isInteger(parseInt(value)) && parseInt(value) > 0;
},
}
}
},
tirada4: {
validators: {
callback: {
message: window.translations["validation"].integer_greatherThan_0,
callback: function (input) {
let field = $("#tirada4");
field.val(field.val().replace(/[^0-9]/g, ''));
let value = field.value;
if (value == '')
return true;
return value.length > 0 && Number.isInteger(parseInt(value)) && parseInt(value) > 0;
},
}
}
},
papel_formato_id: {
validators: {
callback: {
message: window.translations["validation"].papelFormato,
callback: function (input) {
// Get the selected options
const options = $("#papelFormatoId").select2('data');
const hasValidOption = options.some(option => parseInt(option.id) > 0);
const custom_format = $("#papelFormatoPersonalizado").is(":checked");
if (custom_format)
return true;
return options !== null && options.length > 0 && hasValidOption;
},
}
}
},
papel_formato_ancho: {
validators: {
callback: {
message: window.translations["validation"].integer_greatherThan_0,
callback: function (input) {
// Get the selected options
const custom_format = $("#papelFormatoPersonalizado").is(":checked");
if (!custom_format)
return true;
const value = $("#papelFormatoAncho").val();
return value.length > 0 && Number.isInteger(parseInt(value)) && parseInt(value) > 0;
},
}
}
},
papel_formato_alto: {
validators: {
callback: {
message: window.translations["validation"].integer_greatherThan_0,
callback: function (input) {
// Get the selected options
const custom_format = $("#papelFormatoPersonalizado").is(":checked");
if (!custom_format)
return true;
const value = $("#papelFormatoAlto").val();
return value.length > 0 && Number.isInteger(parseInt(value)) && parseInt(value) > 0;
},
}
}
},
paginasColor: {
validators: {
callback: {
message: window.translations["validation"].integer_greatherThan_0,
callback: function (input) {
// Get the selected options
const value = $("#paginasColor").val();
if (value.length >= 0 && Number.isInteger(parseInt(value)) && parseInt(value) >= 0) {
// Cliente
if ($(this.excluirRotativa).prop('hidden')) {
if ($('#clienteId').val() === null || $('#clienteId').val().length === 0) {
this.errores.push(window.translations["validation"].cliente);
$('#clienteId').addClass('is-invalid');
} else {
$('#clienteId').removeClass('is-invalid');
}
} else {
if (this.cliente.getVal() <= 0) {
this.errores.push(window.translations["validation"].cliente);
this.cliente.item.addClass('is-invalid');
} else {
this.cliente.item.removeClass('is-invalid');
}
}
if (parseInt(value) % 2 != 0) {
return {
valid: false,
message: window.translations["validation"].paginas_pares
};
}
return true;
}
return false;
},
}
}
},
paginasNegro: {
validators: {
callback: {
message: window.translations["validation"].integer_greatherThan_0,
callback: function (input) {
// Get the selected options
const value = $("#paginasNegro").val();
if (value.length >= 0 && Number.isInteger(parseInt(value)) && parseInt(value) >= 0) {
// Tirada
let tiradas = this.getTiradas();
if (tiradas.length === 0 || tiradas.some(tirada =>
!Number.isInteger(tirada) ||
parseInt(tirada) <= 0 ||
tirada == "")) {
if (parseInt(value) % 2 != 0) {
return {
valid: false,
message: window.translations["validation"].paginas_pares
};
}
return true;
}
return false;
},
}
}
},
paginas: {
validators: {
callback: {
message: window.translations["validation"].integer_greatherThan_0,
callback: function (input) {
// Get the selected options
const value = $("#paginas").val();
return value.length > 0 && Number.isInteger(parseInt(value)) && parseInt(value) > 0;
},
}
}
},
div_tipo_libro: {
validators: {
callback: {
callback: function (input) {
const divTipoLibro = $('#divTipoLibro'); // Selecciona el div
this.errores.push(window.translations["validation"].tirada_integer_greatherThan_0);
this.tirada1.addClass('is-invalid');
divTipoLibro.find('.fv-plugins-message-container').remove();
if ($('.tipo-libro.selected').length > 0) {
if ($('#cosido').hasClass('selected') || $('#grapado').hasClass('selected')) {
const value = parseInt($("#paginas").val());
if (value % 4 != 0) {
divTipoLibro.append(`
<div class="fv-plugins-message-container invalid-feedback">
<div data-field="div_tipo_libro" data-validator="callback" style="margin-top: 50px;">
${window.translations["validation"].paginas_multiplo_4}
</div>
</div>
`);
return false;
}
return true;
}
} else {
this.tirada1.removeClass('is-invalid');
// Comprobar tiradas POD
const noPOD = tiradas.some(tirada => parseInt(tirada) > 30);
const siPOD = tiradas.some(tirada => parseInt(tirada) <= 30);
if (noPOD && siPOD) {
this.errores.push(window.translations["validation"].tirada_pod_nopod);
this.tirada1.addClass('is-invalid');
}
else {
this.tirada1.removeClass('is-invalid');
}
}
return true;
}
else {
divTipoLibro.append(`
<div class="fv-plugins-message-container invalid-feedback">
<div data-field="div_tipo_libro" data-validator="callback" style="margin-top: 50px;">
${window.translations["validation"].tipo_libro}
</div>
</div>
`);
return false;
}
// formato libro
if (this.checkFormatoPersonalizado.is(':checked')) {
if (this.anchoPersonalizado.val().length === 0 || isNaN(this.anchoPersonalizado.val()) ||
parseFloat(this.anchoPersonalizado.val()) <= 0) {
this.errores.push(window.translations["validation"].papelFormatoAncho);
this.anchoPersonalizado.addClass('is-invalid');
} else {
this.anchoPersonalizado.removeClass('is-invalid');
}
if (this.altoPersonalizado.val().length === 0 || isNaN(this.altoPersonalizado.val()) ||
parseFloat(this.altoPersonalizado.val()) <= 0) {
this.errores.push(window.translations["validation"].papelFormatoAlto);
this.altoPersonalizado.addClass('is-invalid');
} else {
this.altoPersonalizado.removeClass('is-invalid');
}
} else {
const options = $("#papelFormatoId").select2('data');
const hasValidOption = options.some(option => parseInt(option.id) > 0);
if (options !== null && options.length > 0 && hasValidOption) {
this.papelFormatoId.removeClass('is-invalid');
} else {
this.errores.push(window.translations["validation"].papelFormato);
this.papelFormatoId.addClass('is-invalid');
}
}
},
}
// Paginas
if (this.paginasColor.val() == '' || isNaN(this.paginasColor.val()) || parseInt(this.paginasColor.val()) < 0) {
this.errores.push(window.translations["validation"].paginasColor);
this.paginasColor.addClass('is-invalid');
}
else if (parseInt(this.paginasColor.val()) % 2 != 0) {
this.errores.push(window.translations["validation"].paginas_pares);
this.paginasColor.addClass('is-invalid');
}
else {
this.paginasColor.removeClass('is-invalid');
}
if (this.paginasNegro.val() == '' || isNaN(this.paginasNegro.val()) || parseInt(this.paginasNegro.val()) < 0) {
this.errores.push(window.translations["validation"].paginasNegro);
this.paginasNegro.addClass('is-invalid');
}
else if (parseInt(this.paginasNegro.val()) % 2 != 0) {
this.errores.push(window.translations["validation"].paginas_pares);
this.paginasNegro.addClass('is-invalid');
}
else {
this.paginasNegro.removeClass('is-invalid');
}
if (this.paginas.val() == '' || isNaN(this.paginas.val()) || parseInt(this.paginas.val()) <= 0) {
this.errores.push(window.translations["validation"].paginas);
this.paginas.addClass('is-invalid');
} else {
this.paginas.removeClass('is-invalid');
}
// Tipo de libro
if ($('.tipo-libro.selected').length > 0) {
if ($('#cosido').hasClass('selected') || $('#grapado').hasClass('selected')) {
const value = parseInt($("#paginas").val());
if (value % 4 != 0) {
if (parseInt(this.paginas.val()) % 4 != 0) {
this.errores.push(window.translations["validation"].paginas_multiplo_4);
this.paginas.addClass('is-invalid');
} else {
this.paginas.removeClass('is-invalid');
}
}
},
plugins: {
trigger: new FormValidation.plugins.Trigger(),
bootstrap5: new FormValidation.plugins.Bootstrap5({
// Use this for enabling/changing valid/invalid class
// eleInvalidClass: '',
eleValidClass: '',
rowSelector: function (field, ele) {
// field is the field name
// ele is the field element
switch (field) {
case 'div_tipo_libro':
return '.col-sm-10';
case 'titulo':
return '.col-sm-8';
case 'cliente_id':
return '.col-sm-5';
case 'papel_formato_id':
return '.col-sm-4';
case 'papel_formato_ancho':
case 'papel_formato_ancho':
return '.col-sm-3';
case 'tirada':
case 'tirada2':
case 'tirada3':
case 'tirada4':
return '.col-sm-2';
default:
return '.col-sm-3';
}
}
}),
autoFocus: new FormValidation.plugins.AutoFocus(),
submitButton: new FormValidation.plugins.SubmitButton()
}
}).on('core.form.valid', () => {
if (this.allowNext)
this.domItem.find('#divTipoLibro').removeClass('is-invalid');
} else {
this.errores.push(window.translations["validation"].tipo_libro);
this.domItem.find('#divTipoLibro').addClass('is-invalid');
}
stepper.next();
});
const skAlert = document.getElementById('sk-alert');
skAlert.innerHTML = '';
const uniqueErrors = [...new Set(this.errores)];
if (uniqueErrors.length > 0) {
const message = window.translations["validation"].fix_errors +
`<ul class="mb-0">
${uniqueErrors.map(err => `<li>${err}</li>`).join('')}
</ul>`;
popErrorAlert(message, 'sk-alert', false);
this.errores = [];
return false;
}
else {
document.getElementById('sk-alert').innerHTML = '';
this.errores = [];
if (goToNext)
this.validatorStepper.next();
else
return true;
}
}
@ -425,11 +294,11 @@ class DatosGenerales {
else {
this.rl_tipo.addClass('d-none');
}
if($('.tipo-cubierta.selected').length>0){
if ($('.tipo-cubierta.selected').length > 0) {
this.rl_tipo_cubierta.text($($('.tipo-cubierta.selected').find('.form-label')).text());
this.rl_tipo_cubierta.removeClass('d-none');
}
else{
else {
this.rl_tipo_cubierta.addClass('d-none');
}
if (this.checkFormatoPersonalizado.is(':checked')) {
@ -478,33 +347,9 @@ class DatosGenerales {
// servicios extra
menu_off = true;
/*if(this.prototipo.is(':checked')){
this.rl_prototipo.removeClass("d-none");
menu_off = false;
}
else{
this.rl_prototipo.addClass('d-none');
}
if(this.ferro.is(':checked')){
this.rl_ferro.removeClass("d-none");
menu_off = false;
}
else{
this.rl_ferro.addClass('d-none');
}
if(this.ferroDigital.is(':checked')){
this.rl_ferroDigital.removeClass("d-none");
menu_off = false;
}
else{
this.rl_ferroDigital.addClass('d-none');
}
*/
$('#rl-servicios-extra-items').empty();
if(this.marcapaginas.is(':checked')){
if (this.marcapaginas.is(':checked')) {
let $ul = $('<ul>', {
class: 'list-group list-group-timeline'
});
@ -519,7 +364,7 @@ class DatosGenerales {
menu_off = false;
}
if(this.retractilado.is(':checked')){
if (this.retractilado.is(':checked')) {
let $ul = $('<ul>', {
class: 'list-group list-group-timeline'
});
@ -534,7 +379,7 @@ class DatosGenerales {
menu_off = false;
}
if(this.retractilado5.is(':checked')){
if (this.retractilado5.is(':checked')) {
let $ul = $('<ul>', {
class: 'list-group list-group-timeline'
});
@ -550,7 +395,7 @@ class DatosGenerales {
}
const serviciosExtra = $('input[type="checkbox"][data-tarifa-tipo="extra"]:checked');
for(let i=0; i<serviciosExtra.length; i++){
for (let i = 0; i < serviciosExtra.length; i++) {
let $ul = $('<ul>', {
class: 'list-group list-group-timeline'
});
@ -564,10 +409,10 @@ class DatosGenerales {
$('#rl-servicios-extra-items').append($ul);
}
if(!menu_off){
if (!menu_off) {
this.rl_servicios_extra.removeClass('d-none');
}
else{
else {
this.rl_servicios_extra.addClass('d-none');
}
@ -588,7 +433,7 @@ class DatosGenerales {
this.cliente.setOption(datos.clienteId, datos.clienteNombre);
this.cliente.setVal(datos.clienteId);
if(datos.selectedTirada){
if (datos.selectedTirada) {
this.selectedTirada = datos.selectedTirada;
}
$(this.cliente).trigger('change');
@ -609,7 +454,6 @@ class DatosGenerales {
this.checkFormatoPersonalizado.prop('checked', true);
this.formatoEstandar.addClass('d-none');
this.formatoPersonalizado.removeClass('d-none');
this.formValidation.revalidateField('papel_formato_id');
this.altoPersonalizado.val(datos.papelFormatoAlto);
this.anchoPersonalizado.val(datos.papelFormatoAncho);
}
@ -636,17 +480,17 @@ class DatosGenerales {
this.tiposLibro.find('.image-presupuesto').removeClass('selected');
this.domItem.find('#' + datos.tipo).addClass('selected');
if(datos.tipo == 'cosido'){
if (datos.tipo == 'cosido') {
this.divPaginasCuaderillo.removeClass('d-none');
}
}
if(datos.serviciosExtra){
if (datos.serviciosExtra) {
let serviciosExtra = $('input[type="checkbox"][data-tarifa-tipo="extra"]');
$(serviciosExtra).each(function() {
$(serviciosExtra).each(function () {
let tarifaId = $(this).data('tarifa-id') + "";
if (datos.serviciosExtra.includes(tarifaId)) {
@ -654,10 +498,6 @@ class DatosGenerales {
}
});
}
//this.prototipo.prop('checked', datos.prototipo);
//this.ferro.prop('checked', datos.ferro);
//this.ferroDigital.prop('checked', datos.ferroDigital);
this.marcapaginas.prop('checked', datos.marcapaginas);
this.retractilado.prop('checked', datos.retractilado);
this.retractilado5.prop('checked', datos.retractilado5);
@ -702,11 +542,11 @@ class DatosGenerales {
getTiradas() {
let tiradas = [];
tiradas.push(parseInt(this.tirada1.val()));
if (this.tirada2.val().length > 0 && parseInt(this.tirada2.val()) > 0)
if (this.tirada2.val().length > 0)
tiradas.push(parseInt(this.tirada2.val()));
if (this.tirada3.val().length > 0 && parseInt(this.tirada3.val()) > 0)
if (this.tirada3.val().length > 0)
tiradas.push(parseInt(this.tirada3.val()));
if (this.tirada4.val().length > 0 && parseInt(this.tirada4.val()) > 0)
if (this.tirada4.val().length > 0)
tiradas.push(parseInt(this.tirada4.val()));
return tiradas;
}
@ -725,21 +565,18 @@ class DatosGenerales {
if (this.checkFormatoPersonalizado.is(':checked')) {
this.formatoEstandar.addClass('d-none');
this.formatoPersonalizado.removeClass('d-none');
this.formValidation.revalidateField('papel_formato_id');
}
else {
this.formatoEstandar.removeClass('d-none');
this.formatoPersonalizado.addClass('d-none');
this.formValidation.revalidateField('papel_formato_ancho');
this.formValidation.revalidateField('papel_formato_alto');
}
const alto = this.getDimensionLibro().alto;
$('#altoFaja').closest('.config-faja').find('.form-text').text('Entre 50 y ' + alto + ' mm');
}
#checkValue(event){
#checkValue(event) {
let target = event.target;
if(target.value < target.min){
if (target.value < target.min) {
target.value = target.min;
}
}
@ -763,7 +600,7 @@ class DatosGenerales {
// Accede al ID del elemento que disparó el evento
const element = $(event.target);
let containers = element.closest('.tipo-libro').parent().find('.tipo-libro');
let containers = $('#divTipoLibro').find('.tipo-libro');
for (let container of containers) {
if (container != element.closest('.tipo-libro')[0]) {
$(container).removeClass('selected');
@ -790,9 +627,19 @@ class DatosGenerales {
this.divPaginasCuaderillo.addClass('d-none');
}
if (this.grapado.hasClass('selected') || this.espiral.hasClass('selected')) {
if (this.grapado.hasClass('selected') || this.espiral.hasClass('selected') || this.wireo.hasClass('selected')) {
$('#addSobrecubierta').prop('checked', false).trigger('change');
$(".sobrecubierta-items").addClass('d-none');
if (this.grapado.hasClass('selected')){
$("#tapaBlanda").addClass('selected');
$("#tapaBlanda").removeClass('d-none');
$("#tapaDura").addClass('d-none');
$("#tapaDura").removeClass('selected');
$("#tapaDuraLomoRedondo").addClass('d-none');
$("#tapaDuraLomoRedondo").addClass('selected');
}
}
else {
if ($('#addSobrecubierta').hasClass('d-none')) {
@ -800,10 +647,10 @@ class DatosGenerales {
}
}
this.checkPaginasMultiplo4();
this.validate(false);
// Para recalcular el presupuesto
element.trigger('change');
$('#paginas').trigger('change');
}
#handlePaginas() {
@ -844,7 +691,19 @@ class DatosGenerales {
else {
this.domItem.find('#grapado').show();
}
this.formValidation.revalidateField('paginas');
if( totalPaginas < 20){
this.domItem.find('#espiral').removeClass('selected');
this.domItem.find('#espiral').find('.image-presupuesto').removeClass('selected');
this.domItem.find('#espiral').hide();
this.domItem.find('#wireo').removeClass('selected');
this.domItem.find('#wireo').find('.image-presupuesto').removeClass('selected');
this.domItem.find('#wireo').hide();
}
else {
this.domItem.find('#espiral').show();
this.domItem.find('#wireo').show();
}
// Se configura dependiento si hay color o no
const lastLayoutColor = $('#negroEstandar').hasClass('d-none');
@ -856,11 +715,12 @@ class DatosGenerales {
this.posPaginasColor.val("");
this.pagColorConsecutivas.prop('checked', false);
if(lastLayoutColor && !this.cargando){
if (lastLayoutColor && !this.cargando) {
$('#divPapelInterior').empty();
$('#divGramajeInterior').empty();
$('#negroEstandar').trigger('click');
$(".divTiradasPrecio").empty();
}
}
else {
@ -871,7 +731,7 @@ class DatosGenerales {
this.divPaginasColorConsecutivas.removeClass('d-none');
this.divPosPaginasColor.removeClass('d-none');
if(!lastLayoutColor && !this.cargando){
if (!lastLayoutColor && !this.cargando) {
$('#divPapelInterior').empty();
$('#divGramajeInterior').empty();
@ -880,29 +740,6 @@ class DatosGenerales {
}
$('.calcular-lomo').trigger('change');
this.checkPaginasMultiplo4();
}
checkPaginasMultiplo4(){
const divTipoLibro = $('#divTipoLibro'); // Selecciona el div
divTipoLibro.find('.fv-plugins-message-container').remove();
if ($('#cosido').hasClass('selected') || $('#grapado').hasClass('selected')) {
const value = parseInt($("#paginas").val());
if (value % 4 != 0) {
divTipoLibro.append(`
<div class="fv-plugins-message-container invalid-feedback">
<div data-field="div_tipo_libro" data-validator="callback" style="margin-top: 50px;">
${window.translations["validation"].paginas_multiplo_4}
</div>
</div>
`);
return false;
}
}
return true;
}
@ -982,7 +819,7 @@ class DatosGenerales {
let servicios = [];
$(serviciosExtra).each(function() {
$(serviciosExtra).each(function () {
let tarifaId = $(this).data('tarifa-id');
if (tarifaId) {
servicios.push(tarifaId);

View File

@ -33,14 +33,13 @@ class Direcciones {
this.tiradaSeleccionada = null;
this.direcciones.calcularPresupuesto = false;
this.initValidation();
}
init() {
const self = this;
$("#clienteId").on('change', this.handleChangeCliente.bind(this));
this.recogidaTaller.on('change', () => {
@ -60,6 +59,27 @@ class Direcciones {
this.direccionesCliente.init();
this.btnAdd.on('click', this.#insertDireccion.bind(this));
this.btnNew.on('click', this.#nuevaDireccion.bind(this));
// evento para actualizar el selector de tiradas
$(document).on('update-tiradas-envios', (event, data) => {
self.divTiradas.empty();
if (data.tiradas.length > 0) {
data.tiradas.forEach(tirada => {
self.insertTirada(tirada);
});
if (data.tiradaSeleccionada) {
self.divTiradas.find('.check-tirada-envio[tirada="' + data.tiradaSeleccionada + '"]').trigger('click');
self.selectedTirada = data.tiradaSeleccionada;
}
else {
self.tiradaSeleccionada = null;
}
self.divTiradas.trigger('change');
}
});
}
@ -161,6 +181,48 @@ class Direcciones {
}
}
validate(goToNext = true) {
let errores = [];
$('#divDirecciones').removeClass('is-invalid');
if ($('.check-tirada-envio:checked').length > 0) {
let unidades = parseInt($($('.check-tirada-envio:checked')[0]).attr('tirada'));
let total_envio = 0;
// se recorre el array this.direcciones
this.direcciones.forEach(direccion => {
total_envio += parseInt(direccion.getUnidades());
});
if (total_envio > unidades) {
$('#divDirecciones').addClass('is-invalid');
errores.push(window.translations["validation"].unidades_envio_mayor_tirada.replace('{field}', total_envio));
}
}
const skAlert = document.getElementById('sk-alert');
skAlert.innerHTML = '';
const uniqueErrors = [...new Set(errores)];
if (uniqueErrors.length > 0) {
const message = window.translations["validation"].fix_errors +
`<ul class="mb-0">
${uniqueErrors.map(err => `<li>${err}</li>`).join('')}
</ul>`;
popErrorAlert(message, 'sk-alert', false);
errores = [];
return false;
}
else {
document.getElementById('sk-alert').innerHTML = '';
errores = [];
if (goToNext)
this.validatorStepper.next();
else
return true;
}
}
initValidation() {
const stepper = this.validatorStepper;
@ -171,7 +233,7 @@ class Direcciones {
validators: {
callback: {
callback: () => {
const div = $('#divErrorEnvios'); // Selecciona el div
div.find('.fv-plugins-message-container').remove();
@ -244,7 +306,7 @@ class Direcciones {
let direcciones = [];
this.direcciones.forEach(direccion => {
let dir = {
direccion: direccion.getDireccion(),
direccion: direccion.getDireccion(),
unidades: direccion.getUnidades(),
entregaPalets: direccion.getEntregaPalets()
};
@ -340,7 +402,7 @@ class Direcciones {
popErrorAlert("Tiene que seleccionar una tirada para insertar una dirección");
return;
}
if (unidades > this.getSelectedTirada()) {
popErrorAlert("El total de unidades enviadas tiene que ser menor que " + this.getSelectedTirada());
return;

View File

@ -213,7 +213,8 @@ class DisenioCubierta {
false,
{
[this.csrf_token]: this.csrf_hash,
"cubierta": 1
"cubierta": 1,
"cliente": 1
}
);
@ -223,7 +224,8 @@ class DisenioCubierta {
false,
{
[this.csrf_token]: this.csrf_hash,
"sobrecubierta": 1
"sobrecubierta": 1,
"cliente": 1
}
);
@ -233,11 +235,11 @@ class DisenioCubierta {
false,
{
[this.csrf_token]: this.csrf_hash,
"sobrecubierta": 1
"sobrecubierta": 1,
"cliente": 1
}
);
this.initValidation();
// Creamos un nuevo observador que detecta cambios en los atributos
this.observer = new MutationObserver(mutations => {
@ -325,37 +327,42 @@ class DisenioCubierta {
this.gramaje = datosCubierta.gramaje;
if (datosCubierta.lomoRedondo) {
this.tapaDuraLomoRedondo.trigger('click');
}
else {
if (datosCubierta.tapa == "dura") {
if (datosCubierta.lomoRedondo || datosCubierta.tapa == "dura") {
if (datosCubierta.lomoRedondo)
this.tapaDuraLomoRedondo.trigger('click');
else
this.tapaDuraLomoRecto.trigger('click');
}
else {
this.tapaBlanda.trigger('click');
}
}
setTimeout(() => {
if (datosCubierta.tapa == "dura") {
setTimeout(() => {
this.papelGuardas.setOption(datosGuardas.papel_id, datosGuardas.papel);
this.gramajeGuardas.setOption(datosGuardas.gramaje, datosGuardas.gramaje);
this.guardasImpresas.val(datosGuardas.paginas).trigger('change');
this.cabezada.val(datosCubierta.cabezada).trigger('change');
}
else {
this.carasCubierta.val(datosCubierta.paginas).trigger('change');
if (datosCubierta.solapas) {
this.conSolapas.trigger('click');
this.tamanioSolapasCubierta.val(datosCubierta.solapas_ancho);
}, 100);
}
else {
this.tapaBlanda.addClass('selected');
this.#handleMenuTipoCubierta();
setTimeout(() => {
this.carasCubierta.val(datosCubierta.paginas).trigger('change');
if (datosCubierta.solapas) {
// Activar con-solapas
this.conSolapas.addClass('selected')
.find('.image-presupuesto').addClass('selected');
this.sinSolapas.removeClass('selected')
.find('.image-presupuesto').removeClass('selected');
this.divTamanioSolapas.removeClass('d-none');
this.tamanioSolapasCubierta.val(datosCubierta.solapas_ancho);
} else {
// Asegurar que sin-solapas queda seleccionado (no togglear)
this.divTamanioSolapas.addClass('d-none');
}
else {
this.sinSolapas.trigger('click');
}
}
}, 0);
}, 100);
}
this.divPapelCubierta.find(`[cod="${datosCubierta.papel.code}"]`).addClass('selected');
@ -385,244 +392,114 @@ class DisenioCubierta {
}
initValidation() {
validate(goToNext = true) {
const stepper = this.validatorStepper;
let errores = [];
this.formValidation = FormValidation.formValidation(this.wizardStep, {
fields: {
div_tipo_cubierta: {
validators: {
callback: {
callback: function (input) {
const div = $('#divTipoCubierta'); // Selecciona el div
let continueCheck = true;
div.find('.fv-plugins-message-container').remove();
if ($('.tipo-cubierta.selected').length > 0) {
return true;
}
else {
div.append(`
<div class="fv-plugins-message-container invalid-feedback">
<div data-field="div_tipo_cubierta" data-validator="callback" style="margin-top: 50px;">
${window.translations["validation"].tipo_cubierta}
</div>
</div>
`);
}
return false;
},
}
}
},
div_solapas_cubierta: {
validators: {
callback: {
callback: function (input) {
const div = $('#divSolapasCubierta');
if (div.hasClass("d-none")) return true;
// diseño cubierta
$('#divTipoCubierta').removeClass('is-invalid');
if ($('.tipo-cubierta.selected').length == 0) {
$('#divTipoCubierta').addClass('is-invalid');
errores.push(window.translations["validation"].tipo_cubierta);
continueCheck = false;
}
div.find('.fv-plugins-message-container').remove();
if ($('.solapas-cubierta.selected').length > 0) {
return true;
}
else {
div.append(`
<div class="fv-plugins-message-container invalid-feedback">
<div data-field="div_solapas_cubierta" data-validator="callback" style="margin-top: 50px;">
${window.translations["validation"].opcion_solapas}
</div>
</div>
`);
}
return false;
},
}
}
},
div_papel_cubierta: {
validators: {
callback: {
callback: function (input) {
// solapas cubierta
$('#divSolapasCubierta').removeClass('is-invalid');
if (!$('#divSolapasCubierta').hasClass("d-none") && $('.solapas-cubierta.selected').length == 0 && continueCheck) {
$('#divSolapasCubierta').addClass('is-invalid');
errores.push(window.translations["validation"].opcion_solapas);
}
$('#divPapelCubierta').find('.fv-plugins-message-container').remove();
$('#divPapelEspecialCubierta').find('.fv-plugins-message-container').remove();
const papelSeleccionado = $('.custom-selector-papel-cubierta input[type="radio"]:checked');
if (papelSeleccionado.length > 0) {
return true;
}
else {
$('#divPapelCubierta').append(`
<div class="fv-plugins-message-container invalid-feedback">
<div data-field="div_impresion_interior" data-validator="callback" style="margin-top: 50px;">
${window.translations["validation"].papel_interior}
</div>
</div>
`);
}
return false;
},
}
}
},
div_papel_especial_cubierta: {
validators: {
callback: {
callback: function (input) {
$('#divPapelEspecialCubierta').find('.fv-plugins-message-container').remove();
if ($('#divPapelEspecialCubierta').hasClass("d-none")) return true;
if ($('#papelEspecialCubiertaSel').select2('data').length > 0)
return true;
else {
$('#divPapelEspecialCubierta').append(`
<div class="fv-plugins-message-container invalid-feedback">
<div data-field="div_impresion_interior" data-validator="callback" style="margin-top: 50px;">
${window.translations["validation"].papel_interior}
</div>
</div>
`);
return false;
}
}
}
}
},
div_gramaje_cubierta: {
validators: {
callback: {
callback: function (input) {
const divGramajeInterior = $('#divGramajeCubierta'); // Selecciona el div
divGramajeInterior.find('.fv-plugins-message-container').remove();
const gramajeSeleccionado = $('.custom-selector-gramaje-cubierta input[type="radio"]:checked');
if (gramajeSeleccionado.length > 0) {
return true;
}
else {
divGramajeInterior.append(`
<div class="fv-plugins-message-container invalid-feedback">
<div data-field="div_impresion_interior" data-validator="callback" style="margin-top: 50px;">
${window.translations["validation"].gramaje_interior}
</div>
</div>
`);
}
return false;
},
}
}
},
div_config_tapa_dura: {
validators: {
callback: {
callback: function (input) {
const div = $('#divConfigTapaDura'); // Selecciona el div
div.find('.fv-plugins-message-container').remove();
if ($('divConfigTapaDura').hasClass('d-none'))
return true;
const papelGuardas = $('#papelGuardas').select2('data').length > 0;
const gramajeGuardas = $('#gramajeGuardas').select2('data').length > 0;
if (papelGuardas && gramajeGuardas) {
return true;
}
else {
div.append(`
<div class="fv-plugins-message-container invalid-feedback">
<div data-field="div_impresion_interior" data-validator="callback" style="margin-top: 50px;">
${window.translations["validation"].extras_cubierta}
</div>
</div>
`);
return false;
}
},
}
}
},
div_extras: {
validators: {
callback: {
callback: function (input) {
const div = $('#divExtras'); // Selecciona el div
div.find('.fv-plugins-message-container').remove();
let error = false;
if ($("#addFaja").prop("checked") == true) {
const papelFaja = $('#papelFaja').select2('data').length > 0;
const gramajeFaja = $('#gramajeFaja').select2('data').length > 0;
if (!papelFaja || !gramajeFaja) {
error = true;
}
}
if ($("#addSobrecubierta").prop("checked") == true) {
const papelSobrecubierta = $('#papelSobrecubierta').select2('data').length > 0;
const gramajeSobrecubierta = $('#gramajeSobrecubierta').select2('data').length > 0;
if (!papelSobrecubierta || !gramajeSobrecubierta) {
error = true;
}
}
if (error) {
div.append(`
<div class="fv-plugins-message-container invalid-feedback">
<div data-field="div_impresion_interior" data-validator="callback" style="margin-top: 50px;">
${window.translations["validation"].extras_cubierta}
</div>
</div>
`);
return false;
}
},
}
}
},
},
plugins: {
trigger: new FormValidation.plugins.Trigger(),
bootstrap5: new FormValidation.plugins.Bootstrap5({
// Use this for enabling/changing valid/invalid class
// eleInvalidClass: '',
eleValidClass: '',
rowSelector: function (field, ele) {
// field is the field name
// ele is the field element
switch (field) {
case 'div_tipo_cubierta':
case 'div_solapas_cubierta':
case 'div_papel_cubierta':
case 'div_gramaje_cubierta':
case 'div_papel_especial_cubierta':
case 'div_config_tapa_dura':
return '.col-sm-10';
case 'div_extras':
return '.col-sm-12';
default:
return '.col-sm-3';
}
}
}),
autoFocus: new FormValidation.plugins.AutoFocus(),
submitButton: new FormValidation.plugins.SubmitButton()
// opciones tapa dura y lomo redondo
$('#papelGuardas').removeClass('is-invalid');
$('#gramajeGuardas').removeClass('is-invalid');
if (!$('#divConfigTapaDura').hasClass('d-none') && continueCheck) {
if ($('#papelGuardas').select2('data').length == 0) {
$('#papelGuardas').addClass('is-invalid');
errores.push(window.translations["validation"].papel_guardas);
}
}).on('core.form.valid', () => {
if (this.allowNext)
stepper.next();
});
if ($('#gramajeGuardas').select2('data').length == 0) {
$('#gramajeGuardas').addClass('is-invalid');
errores.push(window.translations["validation"].gramaje_guardas);
}
}
// papel
$('#divPapelCubierta').removeClass('is-invalid');
if ($('.custom-selector-papel-cubierta input[type="radio"]:checked').length == 0 && continueCheck) {
$('#divPapelCubierta').addClass('is-invalid');
errores.push(window.translations["validation"].papel_cubierta);
continueCheck = false;
}
else if (!$('#divPapelEspecialCubierta').hasClass("d-none")) {
if ($('#papelEspecialCubiertaSel').select2('data').length == 0 && continueCheck) {
$('#divPapelEspecialCubierta').addClass('is-invalid');
errores.push(window.translations["validation"].papel_cubierta_especial);
continueCheck = false;
}
}
// gramaje
$('#divGramajeCubierta').removeClass('is-invalid');
if ($('.custom-selector-gramaje-cubierta input[type="radio"]:checked').length == 0 && continueCheck) {
$('#divGramajeCubierta').addClass('is-invalid');
errores.push(window.translations["validation"].gramaje_cubierta);
}
// sobrecubierta
$('#papelSobrecubierta').removeClass('is-invalid');
$('#gramajeSobrecubierta').removeClass('is-invalid');
if ($("#addSobrecubierta").prop("checked") == true) {
if ($('#papelSobrecubierta').select2('data').length == 0) {
$('#papelSobrecubierta').addClass('is-invalid');
errores.push(window.translations["validation"].papel_sobrecubierta);
}
if ($('#gramajeSobrecubierta').select2('data').length == 0) {
$('#gramajeSobrecubierta').addClass('is-invalid');
errores.push(window.translations["validation"].gramaje_sobrecubierta);
}
}
// faja
$('#papelFaja').removeClass('is-invalid');
$('#gramajeFaja').removeClass('is-invalid');
if ($("#addFaja").prop("checked") == true) {
if ($('#papelFaja').select2('data').length == 0) {
$('#papelFaja').addClass('is-invalid');
errores.push(window.translations["validation"].papel_faja);
}
if ($('#gramajeFaja').select2('data').length == 0) {
$('#gramajeFaja').addClass('is-invalid');
errores.push(window.translations["validation"].gramaje_faja);
}
}
const skAlert = document.getElementById('sk-alert');
skAlert.innerHTML = '';
const uniqueErrors = [...new Set(errores)];
if (uniqueErrors.length > 0) {
const message = window.translations["validation"].fix_errors +
`<ul class="mb-0">
${uniqueErrors.map(err => `<li>${err}</li>`).join('')}
</ul>`;
popErrorAlert(message, 'sk-alert', false);
errores = [];
return false;
}
else {
document.getElementById('sk-alert').innerHTML = '';
errores = [];
if (goToNext)
this.validatorStepper.next();
else
return true;
}
}
getLomoCubierta() {
@ -903,6 +780,14 @@ class DisenioCubierta {
// Accede al ID del elemento que disparó el evento
const element = $(event.target);
this.divPapelCubierta.removeClass('is-invalid');
this.divGramajeCubierta.removeClass('is-invalid');
this.divGramajeCubierta.empty();
this.divPapelCubierta.empty();
this.textoPapelCubierta.addClass('d-none');
let class2Find = '.tipo-cubierta';
let containers = element.closest(class2Find).parent().find(class2Find);
@ -987,23 +872,26 @@ class DisenioCubierta {
#handleMenuPapel() {
this.divGramajeCubierta.empty();
const tapa_dura = this.tapaBlanda.hasClass("selected") ? 0 : 1;
new Ajax('/configuracion/papelesgenericos/getpapelcliente',
{
[this.csrf_token]: this.csrf_hash,
tipo: 'colorhq',
cubierta: 1,
ancho: this.presupuestoCliente.datosGenerales.getDimensionLibro().ancho,
alto: this.presupuestoCliente.datosGenerales.getDimensionLibro().alto,
solapas: $('#solapas_cubierta').hasClass("d-none") ? 0 : $('#solapas_cubierta').val(),
lomo: $('#lc').val(),
tapa_dura: tapa_dura,
tirada: this.presupuestoCliente.datosGenerales.getTiradas()[0],
},
{},
(response) => { this.fillPapeles(response); },
(response) => { console.log(response); }
).get();
this.divGramajeCubierta.removeClass("is-invalid");
if ($('.tipo-cubierta.selected').length > 0) {
const tapa_dura = this.tapaBlanda.hasClass("selected") ? 0 : 1;
new Ajax('/configuracion/papelesgenericos/getpapelcliente',
{
[this.csrf_token]: this.csrf_hash,
tipo: 'colorhq',
cubierta: 1,
ancho: this.presupuestoCliente.datosGenerales.getDimensionLibro().ancho,
alto: this.presupuestoCliente.datosGenerales.getDimensionLibro().alto,
solapas: $('#solapas_cubierta').hasClass("d-none") ? 0 : $('#solapas_cubierta').val(),
lomo: $('#lc').val(),
tapa_dura: tapa_dura,
tirada: this.presupuestoCliente.datosGenerales.getTiradas()[0],
},
{},
(response) => { this.fillPapeles(response); },
(response) => { console.log(response); }
).get();
}
}

View File

@ -16,7 +16,6 @@ class DisenioInterior {
this.wizardStep = wizardForm.querySelector('#interior-libro');
this.validatorStepper = validatorStepper;
this.allowNext = true;
this.disenioInterior = this.domItem.find(".disenio-interior");
this.divPapelInterior = this.domItem.find("#divPapelInterior");
@ -56,10 +55,10 @@ class DisenioInterior {
false,
{
[this.csrf_token]: this.csrf_hash,
tipo: () => {return this.getTipoImpresion()},
tirada: () => {{return this.presupuestoCliente.datosGenerales.getTiradas()[0]}},
ancho: () => {return this.presupuestoCliente.datosGenerales.getDimensionLibro().ancho},
alto: () => {return this.presupuestoCliente.datosGenerales.getDimensionLibro().alto},
tipo: () => { return this.getTipoImpresion() },
tirada: () => { { return this.presupuestoCliente.datosGenerales.getTiradas()[0] } },
ancho: () => { return this.presupuestoCliente.datosGenerales.getDimensionLibro().ancho },
alto: () => { return this.presupuestoCliente.datosGenerales.getDimensionLibro().alto },
solapas: 0,
lomo: 0,
cubierta: 0,
@ -71,10 +70,10 @@ class DisenioInterior {
false,
{
[this.csrf_token]: this.csrf_hash,
tipo: () => {return this.getTipoImpresion()},
tirada: () => {{return this.presupuestoCliente.datosGenerales.getTiradas()[0]}},
ancho: () => {return this.presupuestoCliente.datosGenerales.getDimensionLibro().ancho},
alto: () => {return this.presupuestoCliente.datosGenerales.getDimensionLibro().alto},
tipo: () => { return this.getTipoImpresion() },
tirada: () => { { return this.presupuestoCliente.datosGenerales.getTiradas()[0] } },
ancho: () => { return this.presupuestoCliente.datosGenerales.getDimensionLibro().ancho },
alto: () => { return this.presupuestoCliente.datosGenerales.getDimensionLibro().alto },
solapas: 0,
lomo: 0,
cubierta: 0,
@ -94,8 +93,6 @@ class DisenioInterior {
this.gramajeNegroForResumen = "";
this.papelColorForResumen = "";
this.gramajeColorForResumen = "";
this.initValidation();
}
@ -378,229 +375,83 @@ class DisenioInterior {
}
initValidation() {
validate(goToNext = true) {
const stepper = this.validatorStepper;
let errores = [];
this.formValidation = FormValidation.formValidation(this.wizardStep, {
fields: {
div_impresion_interior: {
validators: {
callback: {
callback: function (input) {
const divImpresionInterior = $('#divImpresionInterior'); // Selecciona el div
let continueCheck = true;
divImpresionInterior.find('.fv-plugins-message-container').remove();
if ($('.disenio-interior.selected').length > 0) {
return true;
}
else {
divImpresionInterior.append(`
<div class="fv-plugins-message-container invalid-feedback">
<div data-field="div_impresion_interior" data-validator="callback" style="margin-top: 50px;">
${window.translations["validation"].disenio_interior}
</div>
</div>
`);
}
return false;
},
}
// impresion interior
if ($('.disenio-interior.selected').length > 0) {
$('#divImpresionInterior').removeClass('is-invalid');
}
else {
errores.push(window.translations["validation"].disenio_interior);
$('#divImpresionInterior').addClass('is-invalid');
continueCheck = false;
}
// papel interior
if (continueCheck) {
const papelSeleccionado = $('.custom-selector-papel input[type="radio"]:checked');
if (papelSeleccionado.length > 0) {
if (!$('#divPapelEspecialInterior').hasClass("d-none")) {
if ($('#papelEspecialInterior').select2('data').length == 0) {
$('#divPapelInterior').addClass('is-invalid');
errores.push(window.translations["validation"].papel_interior_especial);
continueCheck = false;
}
},
div_papel_interior: {
validators: {
callback: {
callback: function (input) {
$('#divPapelInterior').find('.fv-plugins-message-container').remove();
$('#divPapelEspecialInterior').find('.fv-plugins-message-container').remove();
const papelSeleccionado = $('.custom-selector-papel input[type="radio"]:checked');
if (papelSeleccionado.length > 0) {
return true;
}
else {
$('#divPapelInterior').append(`
<div class="fv-plugins-message-container invalid-feedback">
<div data-field="div_impresion_interior" data-validator="callback" style="margin-top: 50px;">
${window.translations["validation"].papel_interior}
</div>
</div>
`);
}
return false;
},
}
else {
$('#divPapelInterior').removeClass('is-invalid');
}
},
div_papel_especial_interior: {
validators: {
callback: {
callback: function (input) {
$('#divPapelEspecialInterior').find('.fv-plugins-message-container').remove();
if ($('#divPapelEspecialInterior').hasClass("d-none")) return true;
if ($('#papelEspecialInterior').select2('data').length > 0)
return true;
else {
$('#divPapelEspecialInterior').append(`
<div class="fv-plugins-message-container invalid-feedback">
<div data-field="div_impresion_interior" data-validator="callback" style="margin-top: 50px;">
${window.translations["validation"].papel_interior}
</div>
</div>
`);
return false;
}
}
}
}
},
div_gramaje_interior: {
validators: {
callback: {
callback: function (input) {
const divGramajeInterior = $('#divGramajeInterior'); // Selecciona el div
const gramajeSeleccionado = $('.custom-selector-gramaje input[type="radio"]:checked');
if (gramajeSeleccionado.length > 0) {
return true;
}
else {
divGramajeInterior.append(`
<div class="fv-plugins-message-container invalid-feedback">
<div data-field="div_impresion_interior" data-validator="callback" style="margin-top: 50px;">
${window.translations["validation"].gramaje_interior}
</div>
</div>
`);
}
return false;
},
}
}
},
div_impresion_interior_color: {
validators: {
callback: {
callback: function (input) {
const divImpresionInterior = $('#divImpresionInteriorColor'); // Selecciona el div
if (divImpresionInterior.hasClass("d-none")) return true;
divImpresionInterior.find('.fv-plugins-message-container').remove();
if ($('.disenio-interior-color.selected').length > 0) {
return true;
}
else {
divImpresionInterior.append(`
<div class="fv-plugins-message-container invalid-feedback">
<div data-field="div_impresion_interior_color" data-validator="callback" style="margin-top: 50px;">
${window.translations["validation"].disenio_interior}
</div>
</div>
`);
}
return false;
},
}
}
},
div_papel_interior_color: {
validators: {
callback: {
callback: function (input) {
const divPapelInterior = $('#divPapelInteriorColor'); // Selecciona el div
if (divPapelInteriorColor.hasClass("d-none")) return true;
$('#divPapelInteriorColor').find('.fv-plugins-message-container').remove();
$('#divPapelEspecialInteriorColor').find('.fv-plugins-message-container').remove();
const papelSeleccionado = $('.custom-selector-papel-color input[type="radio"]:checked');
if (papelSeleccionado.length > 0) {
return true;
}
else {
$('#divPapelInteriorColor').append(`
<div class="fv-plugins-message-container invalid-feedback">
<div data-field="div_impresion_interior" data-validator="callback" style="margin-top: 50px;">
${window.translations["validation"].papel_interior}
</div>
</div>
`);
}
return false;
},
}
}
},
div_gramaje_interior_color: {
validators: {
callback: {
callback: function (input) {
const divGramajeInteriorColor = $('#divGramajeInteriorColor'); // Selecciona el div
if (divGramajeInteriorColor.hasClass("d-none")) return true;
const gramajeSeleccionado = $('.custom-selector-gramaje-color input[type="radio"]:checked');
if (gramajeSeleccionado.length > 0) {
return true;
}
else {
divGramajeInteriorColor.append(`
<div class="fv-plugins-message-container invalid-feedback">
<div data-field="div_impresion_interior" data-validator="callback" style="margin-top: 50px;">
${window.translations["validation"].gramaje_interior}
</div>
</div>
`);
}
return false;
},
}
}
},
},
plugins: {
trigger: new FormValidation.plugins.Trigger(),
bootstrap5: new FormValidation.plugins.Bootstrap5({
// Use this for enabling/changing valid/invalid class
// eleInvalidClass: '',
eleValidClass: '',
rowSelector: function (field, ele) {
// field is the field name
// ele is the field element
switch (field) {
case 'div_impresion_interior':
case 'div_papel_interior':
case 'div_gramaje_interior':
case 'div_impresion_interior_color':
case 'div_papel_interior_color':
case 'div_gramaje_interior_color':
case 'div_papel_especial_interior':
return '.col-sm-10';
default:
return '.col-sm-3';
}
}
}),
autoFocus: new FormValidation.plugins.AutoFocus(),
submitButton: new FormValidation.plugins.SubmitButton()
}
else {
$('#divPapelInterior').removeClass('is-invalid');
}
} else {
$('#divPapelInterior').addClass('is-invalid');
errores.push(window.translations["validation"].papel_interior);
continueCheck = false;
}
}).on('core.form.valid', () => {
if (this.allowNext)
stepper.next();
});
}
// gramaje interior
if (continueCheck) {
const gramajeSeleccionado = $('.custom-selector-gramaje input[type="radio"]:checked');
if (gramajeSeleccionado.length > 0) {
$('#divGramajeInterior').removeClass('is-invalid');
}
else {
$('#divGramajeInterior').addClass('is-invalid');
errores.push(window.translations["validation"].gramaje_interior);
}
}
const skAlert = document.getElementById('sk-alert');
skAlert.innerHTML = '';
const uniqueErrors = [...new Set(errores)];
if (uniqueErrors.length > 0) {
const message = window.translations["validation"].fix_errors +
`<ul class="mb-0">
${uniqueErrors.map(err => `<li>${err}</li>`).join('')}
</ul>`;
popErrorAlert(message, 'sk-alert', false);
errores = [];
return false;
}
else {
document.getElementById('sk-alert').innerHTML = '';
errores = [];
if (goToNext)
this.validatorStepper.next();
else
return true;
}
}
getTipoImpresion() {
let tipo = 'negro';
@ -831,6 +682,10 @@ class DisenioInterior {
// Accede al ID del elemento que disparó el evento
const element = $(event.target);
$('#divImpresionInterior').removeClass('is-invalid');
$('#divPapelInterior').removeClass('is-invalid');
$('#divGramajeInterior').removeClass('is-invalid');
let class2Find = '.disenio-interior';
if (element[0].closest('.image-container').id.includes('Color')) {
this.divGramajeInteriorColor.empty();
@ -841,6 +696,8 @@ class DisenioInterior {
this.papelInteriorColor = null;
this.gramajeColor = null;
class2Find = '.disenio-interior-color';
this.divPapelInteriorColor.empty();
}
else {
this.divGramajeInterior.empty();
@ -850,6 +707,7 @@ class DisenioInterior {
$('#papelEspecialInterior').on("change", this.#handlePapelInteriorEspecial.bind(this));
this.papelInterior = null;
this.gramaje = null;
this.divPapelInterior.empty();
}
let containers = element.closest(class2Find).parent().find(class2Find);
@ -866,10 +724,12 @@ class DisenioInterior {
// Para recalcular el presupuesto
element.trigger('change');
if (class2Find == '.disenio-interior-color')
this.updatePapeles('color');
else
this.updatePapeles();
if ($('.disenio-interior.selected').length != 0) {
if (class2Find == '.disenio-interior-color')
this.updatePapeles('color');
else
this.updatePapeles();
}
}
@ -877,6 +737,9 @@ class DisenioInterior {
const context = this;
$('#divPapelInterior').removeClass('is-invalid');
$('#divGramajeInterior').removeClass('is-invalid');
// Accede al ID del elemento que disparó el evento
const element = $(event.target);
const papel = element[0].id.split('_')[1];
@ -928,6 +791,9 @@ class DisenioInterior {
const context = this;
$('#divPapelInterior').removeClass('is-invalid');
$('#divGramajeInterior').removeClass('is-invalid');
this.papelInterior = this.papelEspecial.getVal();
let tipo = this.getTipoImpresion();
@ -955,6 +821,9 @@ class DisenioInterior {
const context = this;
$('#divPapelInterior').removeClass('is-invalid');
$('#divGramajeInterior').removeClass('is-invalid');
// Accede al ID del elemento que disparó el evento
const element = $(event.target);
const papel = element[0].id.split('_')[1];
@ -1006,6 +875,9 @@ class DisenioInterior {
const context = this;
$('#divPapelInterior').removeClass('is-invalid');
$('#divGramajeInterior').removeClass('is-invalid');
this.papelInteriorColor = this.papelEspecialColor.getVal();
let tipo = this.getTipoImpresionColor();
@ -1032,6 +904,7 @@ class DisenioInterior {
fillGramajes(response) {
$('#divGramajeInterior').removeClass('is-invalid');
this.divGramajeInterior.empty()
let showGramaje = false;
@ -1094,6 +967,7 @@ class DisenioInterior {
fillGramajesColor(response) {
$('#divGramajeInterior').removeClass('is-invalid');
this.divGramajeInteriorColor.empty()
let showGramaje = false;

View File

@ -114,12 +114,14 @@ class PresupuestoCliente {
}
else {
this.calcularPresupuesto = true;
$('.tirada-presupuesto').trigger('change');
}
$(".calcular-presupuesto").on('change', this.checkForm.bind(this));
$(".calcular-solapas").on('change', this.calcularSolapas.bind(this));
$(".calcular-lomo").on('change', this.checkLomoInterior.bind(this));
}
@ -131,39 +133,6 @@ class PresupuestoCliente {
}
#checkTiradas() {
let tiradas = [parseInt(this.datosGenerales.tirada1.val())];
if (this.datosGenerales.tirada2.val().length > 0 &&
Number.isInteger(parseInt(this.datosGenerales.tirada2.val())) &&
parseInt(this.datosGenerales.tirada2.val()) > 0 &&
this.datosGenerales.tirada2.val() != "") {
tiradas.push(parseInt(this.datosGenerales.tirada2.val()));
}
if (this.datosGenerales.tirada3.val().length > 0 &&
Number.isInteger(parseInt(this.datosGenerales.tirada3.val())) &&
parseInt(this.datosGenerales.tirada3.val()) > 0 &&
this.datosGenerales.tirada3.val() != "") {
tiradas.push(parseInt(this.datosGenerales.tirada3.val()));
}
if (this.datosGenerales.tirada4.val().length > 0 &&
Number.isInteger(parseInt(this.datosGenerales.tirada4.val())) &&
parseInt(this.datosGenerales.tirada4.val()) > 0 &&
this.datosGenerales.tirada4.val() != "") {
tiradas.push(parseInt(this.datosGenerales.tirada4.val()));
}
const noPOD = (tiradas.some(tirada => parseInt(tirada) > 30));
const siPOD = (tiradas.some(tirada => parseInt(tirada) <= 30));
this.datosGenerales.formValidation.validateField('tirada');
return !(noPOD && siPOD);
}
calcularSolapas() {
/* Solapas Max */
@ -202,10 +171,10 @@ class PresupuestoCliente {
return;
}
if (response.errors.status == 1) {
popErrorAlert('' + response.errors.value, "sk-alert", false);
popErrorAlert('' + response.errors.value, "sk-alert-lomo", false);
}
else {
popAlert2Hide('sk-alert');
popAlert2Hide('sk-alert-lomo');
}
},
() => { }
@ -217,13 +186,39 @@ class PresupuestoCliente {
this.#processResumenLateral();
if (!this.#checkTiradas()) {
return;
}
$(".divTiradasPrecio").empty();
if (this.calcularPresupuesto) {
const element = $('.fv-plugins-bootstrap5.fv-plugins-framework.active');
switch (element.attr('id')) {
case 'datos-generales':
if(!this.datosGenerales.validate(false)) {
return;
}
break;
case 'interior-libro':
if(!this.disenioInterior.validate(false)) {
return;
}
break;
case 'cubierta-libro':
if(!this.disenioCubierta.validate(false)) {
return;
}
break;
case 'direcciones-libro':
if(!this.direcciones.validate(false)) {
return;
}
break;
default:
break;
}
if (event.target.id === 'divDirecciones') {
this.actualizarTiradasEnvio = false;
@ -236,27 +231,25 @@ class PresupuestoCliente {
}
else {
this.actualizarTiradasEnvio = true;
this.direcciones.divTiradas.empty();
//this.direcciones.divTiradas.empty();
}
this.divTiradasPrecios.empty();
let datos_to_check = this.#prepareData();
if (Object.values(datos_to_check).every(this.#isValidDataForm)) {
// buscar elementos dentro de #mainContainer que tengan la clase is-invalid
const invalidElements = $('#mainContainer').find('.is-invalid');
if (invalidElements.length > 0) {
// si hay elementos inválidos, no se procede con el
return;
}
try {
if (!this.datosGenerales.checkPaginasMultiplo4()) {
popErrorAlert("Compruebe que todos los campos son correctos.");
return;
}
setTimeout(function () {
$('#loader').modal('show');
}, 0);
// Si se está ejecutando la petición, abortar la petición anterior
this.ajax_calcular.abort();
@ -291,10 +284,7 @@ class PresupuestoCliente {
if (currentElement !== 'resumen-libro') {
this.#validateCurrentForm(currentElement, nextElement);
if (currentElement === 'cubierta-libro' && this.disenioCubierta.acabadoCubierta.getVal() == 0) {
alertWarningMessage(window.translations.cubiertaSinAcabado, window.translations.cubiertaSinAcabadoText);
}
this.#goToForm(nextElement);
//this.#goToForm(nextElement);
}
else {
this.#goToForm(nextElement);
@ -339,74 +329,24 @@ class PresupuestoCliente {
switch (form) {
case 'datos-generales':
this.datosGenerales.allowNext = false;
validateForm(this.datosGenerales.formValidation).then((status) => {
if (status !== 'Valid') {
this.datosGenerales.allowNext = true;
return false;
}
if (this.datosGenerales.validate(false))
this.#goToForm(nextForm);
this.datosGenerales.allowNext = true;
return true;
}).catch(error => {
this.datosGenerales.allowNext = true;
console.error('Error al validar:', error);
return false;
});
break;
case 'interior-libro':
this.disenioInterior.allowNext = false;
validateForm(this.disenioInterior.formValidation).then((status) => {
if (status !== 'Valid') {
this.disenioInterior.allowNext = true;
return false;
}
if (this.disenioInterior.validate(false))
this.#goToForm(nextForm);
this.disenioInterior.allowNext = true;
return true;
}
).catch(error => {
this.disenioInterior.allowNext = true;
console.error('Error al validar:', error);
return false;
});
break;
case 'cubierta-libro':
this.disenioCubierta.allowNext = false;
validateForm(this.disenioCubierta.formValidation).then((status) => {
if (status !== 'Valid') {
this.disenioCubierta.allowNext = true;
return false;
}
if (this.disenioCubierta.validate(false))
this.#goToForm(nextForm);
this.disenioCubierta.allowNext = true;
return true;
}
).catch(error => {
this.disenioCubierta.allowNext = true;
console.error('Error al validar:', error);
return false;
});
break;
case 'direcciones-libro':
this.direcciones.allowNext = false;
validateForm(this.direcciones.formValidation).then((status) => {
if (status !== 'Valid') {
this.direcciones.allowNext = true;
return false;
}
if (this.direcciones.validate(false)) {
this.#goToForm(nextForm);
this.direcciones.allowNext = true;
return true;
}
).catch(error => {
this.direcciones.allowNext = true;
console.error('Error al validar:', error);
return false;
});
break;
default:
@ -535,12 +475,6 @@ class PresupuestoCliente {
return;
}
if (!this.datosGenerales.checkPaginasMultiplo4()) {
popErrorAlert("Compruebe que todos los campos son correctos.");
$('#loader').modal('hide');
return;
}
this.#getDatos(true);
if (confirmar) {
@ -568,8 +502,13 @@ class PresupuestoCliente {
if (response.error) {
popErrorAlert("Presupuesto no válido, corrija los errores antes de guardar.");
}
else
else {
$('.is-invalid').removeClass('is-invalid');
const skAlert = document.getElementById('sk-alert');
skAlert.innerHTML = '';
popSuccessAlert(response.message);
}
}
},
() => { $('#loader').modal('hide'); }
@ -590,12 +529,14 @@ class PresupuestoCliente {
if (response === null || response === undefined || response === "") {
popErrorAlert("No se ha podido calcular el presupuesto para los datos proporcionados. Por favor, póngase en contacto con el departamento comercial."
, "sk-alert-2", false);
this.divTiradasPrecios.empty();
return;
}
if (Object.values(response.errors).some((value) => value !== "")) {
if (response.errors.status == 1) {
popErrorAlert("No se ha podido calcular el presupuesto para los datos proporcionados. Por favor, póngase en contacto con el departamento comercial."
, "sk-alert-2", false);
this.divTiradasPrecios.empty();
return;
}
}
@ -605,9 +546,14 @@ class PresupuestoCliente {
let tiradas = { ...response.tiradas };
tiradas = Object.keys(tiradas).map((key) => tiradas[key]);
tiradas.sort((a, b) => a - b);
this.divTiradasPrecios.empty();
popAlert2Hide();
if (this.actualizarTiradasEnvio) {
this.direcciones.divTiradas.empty();
}
popAlert2Hide("sk-alert-2");
this.divTiradasPrecios.empty();
for (let i = 0; i < response.tiradas.length; i++) {
if (i == 0) {
@ -637,9 +583,28 @@ class PresupuestoCliente {
this.lc.val(parseFloat(response.info.lomo_cubierta).toFixed(2));
this.lsc.val(parseFloat(response.info.lomo_sobrecubierta).toFixed(2));
setTimeout(() => {
$(`#containerTiradasEnvios .tirada-envio input[tirada="${this.direcciones.tiradaSeleccionada}"]`).trigger('click');
}, 0);
this.disenioCubierta.processMenuLateral();
$('.is-invalid').removeClass('is-invalid');
const skAlert = document.getElementById('sk-alert');
skAlert.innerHTML = '';
const acabadoCubierta = this.disenioCubierta.getAcabados();
if (acabadoCubierta && acabadoCubierta != null && acabadoCubierta > 0) {
$('#alert-cubierta-sin-acabado').addClass('d-none');
}
else {
$('#alert-cubierta-sin-acabado').removeClass('d-none');
$(window).scrollTop(0);
}
if (this.datos.cubierta && this.datos.cubierta.acabado)
setTimeout(() => {
$(`#containerTiradasEnvios .tirada-envio input[tirada="${this.direcciones.tiradaSeleccionada}"]`).trigger('click');
}, 0);
}
$('#loader').modal('hide');
// DEBUG
@ -651,23 +616,20 @@ class PresupuestoCliente {
switch (this.validationStepper._currentIndex) {
case 0:
this.datosGenerales.formValidation.validate();
this.datosGenerales.validate();
break;
case 1:
this.disenioInterior.formValidation.validate();
this.disenioInterior.validate();
break;
case 2:
if (this.disenioCubierta.acabadoCubierta.getVal() == 0) {
alertWarningMessage(window.translations.cubiertaSinAcabado, window.translations.cubiertaSinAcabadoText);
}
this.disenioCubierta.formValidation.validate();
this.disenioCubierta.validate();
break;
case 3:
this.direcciones.formValidation.validate();
this.direcciones.validate();
break;
default:
@ -678,13 +640,27 @@ class PresupuestoCliente {
#prevtStep() {
if (this.validationStepper._currentIndex >= 1 && this.validationStepper._currentIndex <= 4) {
if (this.validationStepper._currentIndex == 2) {
if (this.disenioCubierta.acabadoCubierta.getVal() == 0) {
alertWarningMessage(window.translations.cubiertaSinAcabado, window.translations.cubiertaSinAcabadoText);
}
}
this.validationStepper.previous();
switch (this.validationStepper._currentIndex) {
case 1:
if (this.disenioInterior.validate(false))
this.validationStepper.previous();
break;
case 2:
if (this.disenioCubierta.validate(false))
this.validationStepper.previous();
break;
case 3:
if (this.direcciones.formValidation.validate(false))
this.validationStepper.previous();
break;
default:
this.validationStepper.previous();
break;
}
$('html, body').animate({ scrollTop: 0 }, 'slow');
}
@ -896,8 +872,8 @@ class PresupuestoCliente {
$('#menu_resumen_button').trigger('click');
setTimeout(() => {
self.resumen.init_dropzone();
self.resumen.generate_total(response.data.resumen.base,
response.data.resumen.precio_unidad,
self.resumen.generate_total(response.data.resumen.base,
response.data.resumen.precio_unidad,
response.data.resumen.total_envio,
response.data.datosGenerales.ivaReducido);
}, 0);
@ -926,19 +902,6 @@ class PresupuestoCliente {
}
async function validateForm(formValidation) {
try {
const validationResult = await formValidation.validate();
return validationResult;
} catch (error) {
console.error('Error durante la validación:', error);
throw error;
}
}
function isValid(value) {
if (value === null || value === undefined || value === '') {
return false;

View File

@ -352,26 +352,27 @@ class Resumen {
let envios = tarjetaPrecio.find('.tarjeta-tiradas-precios-envio').val();
this.total_envios.text(this.#changeDecimalFormat(parseFloat(envios).toFixed(2)));
this.total_envios.text(this.#changeDecimalFormat(parseFloat(envios || 0).toFixed(2)));
let precio_u_text = tarjetaPrecio.find('.tarjeta-tiradas-precios-precio-unidad').text();
precio_u_text = precio_u_text.replace('€/ud', '');
const base = tarjetaPrecio.find('.tarjeta-tiradas-precios-precio').attr('data');
let base_text = this.#changeDecimalFormat(parseFloat(base).toFixed(2));
let base_text = this.#changeDecimalFormat(parseFloat(base || 0).toFixed(2));
const total_antes_iva_text = this.#changeDecimalFormat((parseFloat(base) + parseFloat(envios)).toFixed(2));
const total_antes_iva_text = this.#changeDecimalFormat((parseFloat(base || 0) + parseFloat(envios || 0)).toFixed(2));
const iva_porcentaje = parseInt(this.datosGenerales.ivaReducido.find('option:selected').val()) == 1 ? 0.04 : 0.21;
const iva = ((parseFloat(base) + parseFloat(envios)) * iva_porcentaje).toFixed(2);
const iva = ((parseFloat(base || 0) + parseFloat(envios || 0)) * iva_porcentaje).toFixed(2);
let iva_text = this.#changeDecimalFormat(iva);
const total = (parseFloat(base) + parseFloat(envios) + parseFloat(iva)).toFixed(2);
const total = (parseFloat(base || 0) + parseFloat(envios || 0) + parseFloat(iva || 0)).toFixed(2);
let total_text = this.#changeDecimalFormat(total);
this.precio_unidad.text(precio_u_text);
this.total_base.text(base_text);
this.total_antes_iva.text(total_antes_iva_text);
this.iva_porcentaje.text(this.datosGenerales.ivaReducido.find('option:selected').val() == 1 ? '4' : '21');
this.iva.text(iva_text);
this.total.text(total_text);

View File

@ -143,4 +143,9 @@
.dt-no-reorder {
cursor: auto !important;
}
div.is-invalid {
border: 1px solid #ea5455;
padding: 0.5rem;
}