Merge branch 'main' into feat/ot-new-features

This commit is contained in:
amazuecos
2025-05-01 06:15:26 +02:00
24 changed files with 1189 additions and 77 deletions

View File

@ -6,20 +6,33 @@ use CodeIgniter\Router\RouteCollection;
/* Rutas para tarifas */ /* Rutas para tarifas */
$routes->group('importador', ['namespace' => 'App\Controllers\Importadores'], function ($routes) { $routes->group('importador', ['namespace' => 'App\Controllers\Importadores'], function ($routes) {
/* Libros */
/* Desde Catalogo */
$routes->group('catalogo', ['namespace' => 'App\Controllers\Importadores'], function ($routes) { $routes->group('catalogo', ['namespace' => 'App\Controllers\Importadores'], function ($routes) {
/**====================== /**======================
* Tool * Tool
*========================**/ *========================**/
$routes->get('', 'ImportadorCatalogo::index', ['as' => 'importadorCatalogoTool']); $routes->get('', 'ImportadorCatalogo::index', ['as' => 'importadorCatalogoTool']);
/**====================== /**======================
* AJAX * AJAX
*========================**/ *========================**/
$routes->post('validar-fila', 'ImportadorCatalogo::validarFila'); $routes->post('validar-fila', 'ImportadorCatalogo::validarFila');
$routes->post('importar-fila', 'ImportadorCatalogo::importarFila'); $routes->post('importar-fila', 'ImportadorCatalogo::importarFila');
});
/* Desde Cliente Bubok */
$routes->group('bubok', ['namespace' => 'App\Controllers\Importadores'], function ($routes) {
/**======================
* Tool
*========================**/
$routes->get('', 'ImportadorBubok::index', ['as' => 'importadorBubokTool']);
/**======================
* AJAX
*========================**/
$routes->post('importar-fila', 'ImportadorBubok::importarFila');
}); });
}); });

View File

@ -0,0 +1,363 @@
<?php
namespace App\Controllers\Importadores;
use App\Controllers\BaseResourceController;
use App\Controllers\Presupuestos\Presupuestocliente;
use App\Services\PresupuestoService;
class ImportadorBubok extends BaseResourceController
{
protected $format = 'json';
protected static $singularObjectName = 'Importador';
protected static $singularObjectNameCc = 'ImportadorBubok';
protected static $pluralObjectName = 'Importadores';
protected static $pluralObjectNameCc = 'importadores';
protected static $controllerSlug = 'importador';
protected static $viewPath = 'themes/vuexy/form/importador/bubok/';
protected $indexRoute = 'ImportadorBubokTool';
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
$this->viewData['pageTitle'] = lang('Importador.listingPage');
$this->viewData['usingSweetAlert'] = true;
// Breadcrumbs (IMN)
$this->viewData['breadcrumb'] = [
['title' => lang("App.menu_importadores"), 'route' => "javascript:void(0);", 'active' => false],
['title' => lang("App.menu_importadores_bubok"), 'route' => route_to('importadorBubokTool'), 'active' => true]
];
parent::initController($request, $response, $logger);
}
public function index()
{
$viewData = [
'pageSubTitle' => lang('Basic.global.ManageAllRecords', [lang('Importador.importadorCatalogoTitle')]),
];
$viewData = array_merge($this->viewData, $viewData); // merge any possible values from the parent controller class
return view(static::$viewPath . 'viewImportadorBubokTool', $viewData);
}
public function importarFila()
{
$json = $this->request->getJSON();
// Validación mínima de datos comunes
$pedido = $json->pedido ?? null;
if (!$pedido || !isset($pedido->orderNumber)) {
return $this->respond([
'status' => 400,
'message' => 'Datos comunes del pedido ausentes o inválidos.'
]);
}
// Validación mínima de existencia del producto en la linea
if (!$json || !isset($json->producto)) {
return $this->respond([
'status' => 400,
'message' => 'Producto no proporcionado o inválido.'
]);
}
$producto = $json->producto;
// 1. Datos básicos:
// Referencia del cliente
$orderNumber = $pedido->orderNumber ?? null;
$productId = $producto->id ?? null;
if (is_null($orderNumber) || is_null($productId)) {
return $this->respond([
'status' => 400,
'message' => 'Número de orden o ID del producto no reconocidos.'
]);
}
$refCliente = "$orderNumber - $productId";
// Titulo
$titulo = $producto->title ?? null;
if (is_null($titulo)) {
return $this->respond([
'status' => 400,
'message' => 'Título del libro no reconocido.'
]);
}
// Validación de páginas y tirada
$paginas = isset($producto->body->pages) ? (int) $producto->body->pages : 0;
$tirada = isset($producto->amount) ? (int) $producto->amount : 0;
if ($paginas <= 0 || $tirada <= 0) {
$errores = [];
if ($paginas <= 0) {
$errores[] = 'Número de páginas inválido.';
}
if ($tirada <= 0) {
$errores[] = 'Tirada inválida.';
}
return $this->respond([
'status' => 400,
'message' => implode(' ', $errores)
]);
}
// Ancho y alto
$ancho = null;
$alto = null;
foreach ($producto->size as $key => $val) {
if ($val == 1) {
// ejemplo: size170x235
$size = str_replace('size', '', $key);
[$ancho, $alto] = explode('x', $size);
$ancho = (int) $ancho;
$alto = (int) $alto;
break;
}
}
if (!$ancho || !$alto) {
return $this->respond([
'status' => 400,
'message' => 'Tamaño del libro no reconocido.'
]);
}
/*$numGuardaPages = 4;
$hasGuarda = !empty($producto->cover->guarda);
if ($hasGuarda)
$paginas += $numGuardaPages;*/
// 2. Interior: color o negro
// Determinar tipo de impresión interior
$interiorTipo = null;
if (isset($producto->body->color->CMYK) && $producto->body->color->CMYK == '1') {
$interiorTipo = 'color';
} elseif (isset($producto->body->color->Monochrome) && $producto->body->color->Monochrome == '1') {
$interiorTipo = 'negro';
} elseif (isset($producto->body->color->Semicolor) && $producto->body->color->Semicolor == '1') {
return $this->respond([
'status' => 400,
'message' => 'Tipo de impresión "Semicolor" no soportado.'
]);
}
if (is_null($interiorTipo)) {
return $this->respond([
'status' => 400,
'message' => 'No se pudo determinar si el interior es en color o blanco y negro.'
]);
}
// Determinar tipo de papel interior
$papelInteriorId = null;
if (isset($producto->body->paperColor->white) && $producto->body->paperColor->white == '1') {
$papelInteriorId = 3; // Offset blanco 'OFF1'
} elseif (isset($producto->body->paperColor->cream) && $producto->body->paperColor->cream == '1') {
$papelInteriorId = 4; // Offset ahuesado 'OFF2'
} else {
return $this->respond([
'status' => 400,
'message' => 'Tipo de papel interior no definido.'
]);
}
// Determinar el gramaje del papel
$gramajePapelInterior = null;
foreach ($producto->body->paperWeight as $key => $val) {
if ($val == 1) {
$gramajePapelInterior = (int) str_replace(['weight', 'gr'], '', $key);
break;
}
}
if (!$gramajePapelInterior) {
return $this->respond([
'status' => 400,
'message' => 'Gramaje del papel no válido.'
]);
}
// 3. Encuadernación
// Tapa dura
$tapaDura = isset($producto->cover->type->tapadura) && $producto->cover->type->tapadura == '1';
// Solapas
$solapas = isset($producto->cover->type->consolapas) && $producto->cover->type->consolapas == '1';
// Doble cara (a veces se activa con tapa dura) una cara => 2; dos caras => 4
$doscara = false;
// Tipo de encuadernado
$encuadernadoId = null;
if (isset($producto->cover->coverType->SoftCover) && $producto->cover->coverType->SoftCover == '1') {
if ($tapaDura) {
$encuadernadoId = 1; // Libro fresado tapa dura
$doscara = true;
} else {
$encuadernadoId = 2; // Libro fresado tapa blanda
}
} elseif (isset($producto->cover->coverType->SaddleStitch) && $producto->cover->coverType->SaddleStitch == '1') {
if ($tapaDura) {
$encuadernadoId = 3; // Libro cosido tapa dura
$doscara = true;
} else {
$encuadernadoId = $solapas ? 20 : 4; // Libro cosido tapa blanda (solapas) : (sin solapas)
}
} elseif (isset($producto->cover->coverType->CoilBinding) && $producto->cover->coverType->CoilBinding == '1') {
if ($tapaDura) {
$encuadernadoId = 5; // Libro espiral tapa dura
$doscara = true;
} else {
$encuadernadoId = 6; // Libro espiral tapa blanda
}
}
if (!$encuadernadoId) {
return $this->respond([
'status' => 400,
'message' => 'Tipo de encuadernación no identificado.'
]);
}
// Determinar el acabado de la cubierta
$acabadoId = null;
if (isset($producto->cover->acabado->brillo) && $producto->cover->acabado->brillo == '1') {
$acabadoId = 1; // Plastificado brillo 1/c
} elseif (isset($producto->cover->acabado->mate) && $producto->cover->acabado->mate == '1') {
$acabadoId = 2; // Plastificado mate 1/c
} else {
return $this->respond([
'status' => 400,
'message' => 'Tipo de acabado de cubierta no definido.'
]);
}
// 4. ENVÍO: recuperamos la primera dirección del cliente BUBOK (ID 40)
$clienteDireccionModel = model('App\Models\Clientes\ClienteDireccionesModel');
$direccionCliente = $clienteDireccionModel
->where('cliente_id', 40)
->orderBy('id', 'asc')
->first();
if (!$direccionCliente) {
return $this->respond([
'status' => 400,
'message' => 'El cliente Bubok no tiene direcciones asociadas.'
]);
}
$direcciones = [
[
'direccion' => [
'id' => (int) $direccionCliente->id,
'cliente_id' => (int) $direccionCliente->cliente_id,
'cliente_nombre' => $direccionCliente->clienteNombre,
'att' => $direccionCliente->persona_contacto ?? '',
'alias' => $direccionCliente->alias ?? '',
'email' => $direccionCliente->email ?? '',
'direccion' => $direccionCliente->direccion,
'pais_id' => (int) $direccionCliente->pais_id,
'pais' => $direccionCliente->paisNombre,
'municipio' => $direccionCliente->municipio,
'provincia' => $direccionCliente->provincia,
'cp' => $direccionCliente->cp,
'telefono' => $direccionCliente->telefono,
],
'unidades' => $tirada,
'entregaPalets' => false
]
];
// Generamos el objeto a importar
$dataToImport = [
'selectedTirada' => $tirada,
'datosCabecera' => [
'titulo' => $titulo,
'autor' => null,
'isbn' => null,
'coleccion' => null,
'referenciaCliente' => $refCliente
],
'tirada' => [$tirada],
'tamanio' => [
'ancho' => $ancho,
'alto' => $alto
],
'tipo' => '',
'tipo_presupuesto_id' => $encuadernadoId,
'clienteId' => 40, // BUBOK ID
'isColor' => ($interiorTipo === 'color') ? 1 : 0,
'isHq' => 0,
'paginas' => $paginas,
'paginasColor' => ($interiorTipo === 'color') ? $paginas : 0,
'paginasCuadernillo' => 32,
'interior' => [
'papelInterior' => $papelInteriorId,
'gramajeInterior' => $gramajePapelInterior
],
'cubierta' => [
'papelCubierta' => 2, // 'EST2'
'carasCubierta' => $doscara ? 2 : 4,
'gramajeCubierta' => in_array($encuadernadoId, [1, 3]) ? 150 : 300, // 150 gramos para "fresado tapa dura" y "cosido tapa dura"
'solapas' => !empty($producto->cover->type->consolapas) ? 80 : 0,
'acabado' => $acabadoId,
'cabezada' => 'WHI',
'lomoRedondo' => 0
],
'guardas' => [],
'sobrecubierta' => [],
'faja' => null,
'comentarios_safekat' => 'URL COVER: ' . $producto->cover->file . "\nURL BODY: " . $producto->body->file,
'direcciones' => $direcciones
];
/*return $this->respond([
'status' => 400,
'message' => $dataToImport
]);*/
// 5. Guardar
try {
$presupuestocliente = new Presupuestocliente();
$response = $presupuestocliente->guardar($dataToImport);
if (!isset($response['sk_id'])) {
return $this->respond([
'status' => 400,
'error' => 'Missing sk_id',
'message' => 'No se pudo crear el presupuesto.'
], 400);
}
return $this->respond([
'status' => 200,
'data' => [
'sk_id' => $response['sk_id'],
'sk_url' => $response['sk_url'] ?? null
]
]);
} catch (\Throwable $e) {
return $this->respond([
'status' => 500,
'error' => 'Server error',
'message' => 'Error inesperado',
'debug' => $e->getMessage()
]);
}
}
}

View File

@ -5,6 +5,7 @@ use App\Controllers\BaseResourceController;
use App\Entities\Catalogo\CatalogoLibroEntity; use App\Entities\Catalogo\CatalogoLibroEntity;
use App\Models\Catalogo\CatalogoLibroModel; use App\Models\Catalogo\CatalogoLibroModel;
use App\Controllers\Presupuestos\Presupuestocliente; use App\Controllers\Presupuestos\Presupuestocliente;
use App\Services\PresupuestoService;
class ImportadorCatalogo extends BaseResourceController class ImportadorCatalogo extends BaseResourceController
{ {
@ -43,11 +44,8 @@ class ImportadorCatalogo extends BaseResourceController
{ {
$viewData = [ $viewData = [
'currentModule' => static::$controllerSlug,
'pageSubTitle' => lang('Basic.global.ManageAllRecords', [lang('Importador.importadorCatalogoTitle')]), 'pageSubTitle' => lang('Basic.global.ManageAllRecords', [lang('Importador.importadorCatalogoTitle')]),
'catalogoLibrosEntity' => new CatalogoLibroEntity(),
'usingServerSideDataTable' => true,
]; ];
$viewData = array_merge($this->viewData, $viewData); // merge any possible values from the parent controller class $viewData = array_merge($this->viewData, $viewData); // merge any possible values from the parent controller class
@ -241,9 +239,11 @@ class ImportadorCatalogo extends BaseResourceController
'lomoRedondo' => 0 'lomoRedondo' => 0
], ],
'ivaReducido' => 1,
'guardas' => [], 'guardas' => [],
'sobrecubierta' => $sobrecubierta, 'sobrecubierta' => $sobrecubierta,
'faja' => [], //'faja' => null,
'entrega_taller' => 1, 'entrega_taller' => 1,
]; ];
@ -281,17 +281,25 @@ class ImportadorCatalogo extends BaseResourceController
] ]
]; ];
// Ajuste del precio a RAMA
$dataToUpdate = [
'total_aceptado' => ($tirada * $precio_compra),
'total_aceptado_revisado' => ($tirada * $precio_compra),
'total_precio_unidad' => $precio_compra
];
$presupuestoModel = model('App\Models\Presupuestos\Presupuestomodel');
$presupuestoModel->update($response['data']['sk_id'], $dataToUpdate);
// Ajuste del precio a RAMA
$respuesta_ajuste = PresupuestoService::ajustarPresupuesto(
$response['data']['sk_id'],
$precio_compra,
$tirada,
null,
true
);
if ($respuesta_ajuste['warning'] == true) {
$response['price_warning'] = [
'new_precio_unidad' => $respuesta_ajuste['new_precio_unidad'],
'new_total' => $respuesta_ajuste['new_total'],
];
}
// confirmar y crear pedido y ot
model('App\Models\Presupuestos\PresupuestoModel')->confirmarPresupuesto($response['data']['sk_id']);
PresupuestoService::crearPedido($response['data']['sk_id']);
return $this->respond($response); return $this->respond($response);

View File

@ -993,6 +993,8 @@ class Presupuestoadmin extends \App\Controllers\BaseResourceController
$reqData = $this->request->getPost(); $reqData = $this->request->getPost();
$calcular_merma = $reqData['calcular_merma'] ?? 0;
$type = $reqData['type'] ?? null; $type = $reqData['type'] ?? null;
// por defecto, se deja cosido tapa blanda por ahora JJO // por defecto, se deja cosido tapa blanda por ahora JJO
$tipo_impresion_id = $reqData['tipo_impresion_id'] ?? 4; $tipo_impresion_id = $reqData['tipo_impresion_id'] ?? 4;
@ -1071,8 +1073,27 @@ class Presupuestoadmin extends \App\Controllers\BaseResourceController
'a_favor_fibra' => $a_favor_fibra 'a_favor_fibra' => $a_favor_fibra
); );
$resourceData = PresupuestoService::obtenerComparadorPlana($input_data); $resourceData = PresupuestoService::obtenerComparadorPlana($input_data);
if($calcular_merma == 1 && count($resourceData) > 0 &&
count($resourceData[0]['fields']) >0 && $resourceData[0]['fields']['num_formas'] > 0) {
usort($resourceData, function ($a, $b) {
return $b['fields']['total_impresion'] <=> $a['fields']['total_impresion'];
});
$num_formas = [];
$formas_linea = $datosPedido->isCosido ? intval($resourceData[0]['fields']['num_formas']['value']) / 2 :
intval($resourceData[0]['fields']['num_formas']['value']);
array_push($num_formas, $formas_linea);
$POD = $this->getPOD();
$datosPedido->merma = PresupuestoService::calcular_merma($datosPedido->tirada,$POD, $num_formas);
$resourceData = PresupuestoService::obtenerComparadorPlana($input_data);
}
} else if ($type == 'interior_rot') { } else if ($type == 'interior_rot') {
$paginas = (object) array( $paginas = (object) array(
@ -1105,6 +1126,24 @@ class Presupuestoadmin extends \App\Controllers\BaseResourceController
$resourceData = PresupuestoService::obtenerComparadorRotativa($input_data); $resourceData = PresupuestoService::obtenerComparadorRotativa($input_data);
if($calcular_merma == 1 && count($resourceData) > 0 &&
count($resourceData[0]['fields']) >0 && $resourceData[0]['fields']['num_formas'] > 0) {
usort($resourceData, function ($a, $b) {
return $b['fields']['total_impresion'] <=> $a['fields']['total_impresion'];
});
$num_formas = [];
$formas_linea = $datosPedido->isCosido ? intval($resourceData[0]['fields']['num_formas']['value']) / 2 :
intval($resourceData[0]['fields']['num_formas']['value']);
array_push($num_formas, $formas_linea);
$POD = $this->getPOD();
$datosPedido->merma = PresupuestoService::calcular_merma($datosPedido->tirada,$POD, $num_formas);
$resourceData = PresupuestoService::obtenerComparadorRotativa($input_data);
}
} else if ($type == 'cubierta' || $type == 'sobrecubierta' || $type == 'faja') { } else if ($type == 'cubierta' || $type == 'sobrecubierta' || $type == 'faja') {
$datosPedido->solapas = $reqData['solapas']; $datosPedido->solapas = $reqData['solapas'];

View File

@ -323,17 +323,23 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
$datosPedido = (object) array( $datosPedido = (object) array(
'paginas' => $paginas, 'paginas' => $paginas,
'tirada' => $tirada[0], 'tirada' => $tirada[0],
'merma' => $this->calcular_merma($tirada[0], $POD), 'merma' => PresupuestoService::calcular_merma($tirada[0], $POD),
'ancho' => intval($tamanio['ancho']) ?? 100000, 'ancho' => intval($tamanio['ancho']) ?? 100000,
'alto' => intval($tamanio['alto']) ?? 100000, 'alto' => intval($tamanio['alto']) ?? 100000,
'isCosido' => $is_cosido, 'isCosido' => $is_cosido,
'a_favor_fibra' => 1, 'a_favor_fibra' => 1,
); );
$cliente_model = model(('App\Models\Clientes\ClienteModel'));
$cliente = $cliente_model->find($cliente_id);
// Para POD siempre es HQ // Para POD siempre es HQ
if ($tirada[0] <= $POD) { if ($tirada[0] <= $POD && !$cliente->forzar_rotativa_pod) {
$isHq = true; $isHq = true;
} }
$forzarRotativa = false;
if ($tirada[0] <= $POD && $cliente->forzar_rotativa_pod) {
$forzarRotativa = true;
}
$input_data = array( $input_data = array(
'uso' => 'interior', 'uso' => 'interior',
@ -346,7 +352,8 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
'cliente_id' => $cliente_id, 'cliente_id' => $cliente_id,
'paginas_color' => $paginas_color, 'paginas_color' => $paginas_color,
'excluirRotativa' => $excluirRotativa, 'excluirRotativa' => $excluirRotativa,
'papelInteriorDiferente' => $papelInteriorDiferente 'papelInteriorDiferente' => $papelInteriorDiferente,
'forzarRotativa' => $forzarRotativa,
); );
$interior = PresupuestoClienteService::obtenerInterior($input_data); $interior = PresupuestoClienteService::obtenerInterior($input_data);
@ -460,6 +467,7 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
$id = $reqData['id'] ?? 0; $id = $reqData['id'] ?? 0;
$cliente_id = $reqData['clienteId'] ?? -1; $cliente_id = $reqData['clienteId'] ?? -1;
$noEnvioBase = model('App\Models\Clientes\ClienteModel')->find($cliente_id)->no_envio_base ?? false;
$tirada = $reqData['tirada'] ?? 0; $tirada = $reqData['tirada'] ?? 0;
$selectedTirada = $reqData['selectedTirada'] ?? -1; $selectedTirada = $reqData['selectedTirada'] ?? -1;
@ -609,6 +617,10 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
} else { } else {
$coste = floatval($coste_direccion->coste); $coste = floatval($coste_direccion->coste);
$margen = $coste * (intval($coste_direccion->margen) / 100.0); $margen = $coste * (intval($coste_direccion->margen) / 100.0);
if ($noEnvioBase) {
$coste = 0.0;
$margen = 0.0;
}
$return_data['eb'][$i] = round($coste + $margen, 2); $return_data['eb'][$i] = round($coste + $margen, 2);
} }
} }
@ -739,17 +751,23 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
$datosPedido = (object) array( $datosPedido = (object) array(
'paginas' => $paginas, 'paginas' => $paginas,
'tirada' => $tirada[0], 'tirada' => $tirada[0],
'merma' => $tirada[0] > $POD ? $this->calcular_merma($tirada[0], $POD) : 0, 'merma' => $tirada[0] > $POD ? PresupuestoService::calcular_merma($tirada[0], $POD) : 0,
'ancho' => intval($tamanio['ancho']) ?? 100000, 'ancho' => intval($tamanio['ancho']) ?? 100000,
'alto' => intval($tamanio['alto']) ?? 100000, 'alto' => intval($tamanio['alto']) ?? 100000,
'isCosido' => $is_cosido, 'isCosido' => $is_cosido,
'a_favor_fibra' => 1, 'a_favor_fibra' => 1,
); );
$cliente_model = model(('App\Models\Clientes\ClienteModel'));
$cliente = $cliente_model->find($cliente_id);
// Para POD siempre es HQ // Para POD siempre es HQ
if ($tirada[0] <= $POD) { if ($tirada[0] <= $POD && !$cliente->forzar_rotativa_pod) {
$isHq = true; $isHq = true;
} }
$forzarRotativa = false;
if ($tirada[0] <= $POD && $cliente->forzar_rotativa_pod) {
$forzarRotativa = true;
}
$input_data = array( $input_data = array(
'uso' => 'interior', 'uso' => 'interior',
@ -762,7 +780,8 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
'cliente_id' => $cliente_id, 'cliente_id' => $cliente_id,
'paginas_color' => $paginas_color, 'paginas_color' => $paginas_color,
'excluirRotativa' => $excluirRotativa, 'excluirRotativa' => $excluirRotativa,
'papelInteriorDiferente' => $papelInteriorDiferente 'papelInteriorDiferente' => $papelInteriorDiferente,
'forzarRotativa' => $forzarRotativa,
); );
$interior = PresupuestoClienteService::obtenerInterior($input_data); $interior = PresupuestoClienteService::obtenerInterior($input_data);
@ -1126,6 +1145,7 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
$peso_libro = $resultado_presupuesto['peso'][array_search($selected_tirada, $tirada)]; $peso_libro = $resultado_presupuesto['peso'][array_search($selected_tirada, $tirada)];
// calculo del envio base (tirada_maxima) // calculo del envio base (tirada_maxima)
$noEnvioBase = model('App\Models\Clientes\ClienteModel')->find($cliente_id)->no_envio_base ?? false;
$resultado_presupuesto['eb'] = []; $resultado_presupuesto['eb'] = [];
$datos_presupuesto['envio_base'] = 0; $datos_presupuesto['envio_base'] = 0;
for ($i = 0; $i < count($tirada); $i++) { for ($i = 0; $i < count($tirada); $i++) {
@ -1139,6 +1159,10 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
); );
if (intval($selected_tirada) == intval($tirada[$i])) { if (intval($selected_tirada) == intval($tirada[$i])) {
if ($noEnvioBase) {
$coste_direccion->coste = 0.0;
$coste_direccion->margen = 0.0;
}
$datos_presupuesto['envio_base'] = round($coste_direccion->coste * (1 + $coste_direccion->margen / 100.0), 2); $datos_presupuesto['envio_base'] = round($coste_direccion->coste * (1 + $coste_direccion->margen / 100.0), 2);
} }
@ -1160,6 +1184,10 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
]; ];
return $resultado_presupuesto; return $resultado_presupuesto;
} else { } else {
if ($noEnvioBase) {
$coste_direccion->coste = 0.0;
$coste_direccion->margen = 0.0;
}
$resultado_presupuesto['eb'][$i] = round($coste_direccion->coste, 2); $resultado_presupuesto['eb'][$i] = round($coste_direccion->coste, 2);
$resultado_presupuesto['eb_margen'][$i] = round($coste_direccion->margen, 2); $resultado_presupuesto['eb_margen'][$i] = round($coste_direccion->margen, 2);
} }
@ -1176,10 +1204,10 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
for ($i = 0; $i < count($tirada); $i++) { for ($i = 0; $i < count($tirada); $i++) {
$coste_envio = 0.0; $coste_envio = 0.0;
$coste_envio += ($resultado_presupuesto['eb'][$i] / $tirada[$i]); $coste_envio += ($resultado_presupuesto['eb'][$i] / $tirada[$i]);
$resultado_presupuesto['info']['totales'][$i]['envio_base_margen'] = $resultado_presupuesto['info']['totales'][$i]['envio_base_margen'] =
floatval($resultado_presupuesto['eb'][$i])*(floatval($resultado_presupuesto['eb_margen'][$i])/100.0); 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]; $resultado_presupuesto['info']['totales'][$i]['envio_base_coste'] = $resultado_presupuesto['eb'][$i];
$resultado_presupuesto['precio_u'][$i] = round(floatval($resultado_presupuesto['precio_u'][$i]) + $coste_envio, 4); $resultado_presupuesto['precio_u'][$i] = round(floatval($resultado_presupuesto['precio_u'][$i]) + $coste_envio, 4);
} }
@ -1312,7 +1340,7 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
$datos_presupuesto['entrega_taller'] = $reqData['entrega_taller'] ?? 0; $datos_presupuesto['entrega_taller'] = $reqData['entrega_taller'] ?? 0;
$resultado_presupuesto['info']['merma'] = $this->calcular_merma($selected_tirada, $POD); $resultado_presupuesto['info']['merma'] = PresupuestoService::calcular_merma($selected_tirada, $POD);
$datos_presupuesto['faja'] = $faja; $datos_presupuesto['faja'] = $faja;
@ -1357,7 +1385,11 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
foreach ($serviciosAcabado as $service) { foreach ($serviciosAcabado as $service) {
$model = model('App\Models\Presupuestos\PresupuestoAcabadosModel'); $model = model('App\Models\Presupuestos\PresupuestoAcabadosModel');
$servicio = $model->getPrecioTarifa( $servicio = $model->getPrecioTarifa(
intval($service), intval($selected_tirada)+$resultado_presupuesto['info']['merma'], -1, $POD); intval($service),
intval($selected_tirada) + $resultado_presupuesto['info']['merma'],
-1,
$POD
);
if (count($servicio) > 0) { if (count($servicio) > 0) {
if ($servicio[0]->total > 0) { if ($servicio[0]->total > 0) {
@ -1375,8 +1407,11 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
foreach ($serviciosAcabado as $service) { foreach ($serviciosAcabado as $service) {
$model = model('App\Models\Presupuestos\PresupuestoAcabadosModel'); $model = model('App\Models\Presupuestos\PresupuestoAcabadosModel');
$servicio = $model->getPrecioTarifa( $servicio = $model->getPrecioTarifa(
intval($service), intval($service),
intval($selected_tirada) + $resultado_presupuesto['info']['merma'], -1, $POD); intval($selected_tirada) + $resultado_presupuesto['info']['merma'],
-1,
$POD
);
if (count($servicio) > 0) { if (count($servicio) > 0) {
if ($servicio[0]->total > 0) { if ($servicio[0]->total > 0) {
@ -1393,8 +1428,11 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
foreach ($serviciosAcabado as $service) { foreach ($serviciosAcabado as $service) {
$model = model('App\Models\Presupuestos\PresupuestoAcabadosModel'); $model = model('App\Models\Presupuestos\PresupuestoAcabadosModel');
$servicio = $model->getPrecioTarifa( $servicio = $model->getPrecioTarifa(
intval($service), intval($service),
intval($selected_tirada) + $resultado_presupuesto['info']['merma'], -1, $POD); intval($selected_tirada) + $resultado_presupuesto['info']['merma'],
-1,
$POD
);
if (count($servicio) > 0) { if (count($servicio) > 0) {
if ($servicio[0]->total > 0) { if ($servicio[0]->total > 0) {
@ -1407,7 +1445,7 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
$tarifa_id = model('App\Models\Configuracion\ConfigVariableModel')->getVariable('id_servicio_lomo_redondo')->value; $tarifa_id = model('App\Models\Configuracion\ConfigVariableModel')->getVariable('id_servicio_lomo_redondo')->value;
$serv_lomo = PresupuestoCLienteService::getServiciosManipulado([ $serv_lomo = PresupuestoCLienteService::getServiciosManipulado([
'tarifa_id' => intval($tarifa_id), 'tarifa_id' => intval($tarifa_id),
'tirada' => $selected_tirada+$resultado_presupuesto['info']['merma'], 'tirada' => $selected_tirada + $resultado_presupuesto['info']['merma'],
'POD' => $POD, 'POD' => $POD,
])[0]; ])[0];
@ -2029,7 +2067,7 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
$datosPedido = (object) array( $datosPedido = (object) array(
'paginas' => $paginas, 'paginas' => $paginas,
'tirada' => $tirada[$t], 'tirada' => $tirada[$t],
'merma' => $this->calcular_merma($tirada[$t], $POD), 'merma' => PresupuestoService::calcular_merma($tirada[$t], $POD),
'ancho' => intval($tamanio['ancho']) ?? 100000, 'ancho' => intval($tamanio['ancho']) ?? 100000,
'alto' => intval($tamanio['alto']) ?? 100000, 'alto' => intval($tamanio['alto']) ?? 100000,
'isCosido' => $is_cosido, 'isCosido' => $is_cosido,
@ -2039,10 +2077,16 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
$info['merma'] = $datosPedido->merma; $info['merma'] = $datosPedido->merma;
} }
$cliente_model = model(('App\Models\Clientes\ClienteModel'));
$cliente = $cliente_model->find($cliente_id);
// Para POD siempre es HQ // Para POD siempre es HQ
if ($tirada[$t] <= $POD) { if ($tirada[$t] <= $POD && !$cliente->forzar_rotativa_pod) {
$isHq = true; $isHq = true;
} }
$forzarRotativa = false;
if ($tirada[$t] <= $POD && $cliente->forzar_rotativa_pod) {
$forzarRotativa = true;
}
$input_data = array( $input_data = array(
'uso' => 'interior', 'uso' => 'interior',
@ -2055,7 +2099,8 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
'cliente_id' => $cliente_id, 'cliente_id' => $cliente_id,
'paginas_color' => $paginas_color, 'paginas_color' => $paginas_color,
'excluirRotativa' => $excluirRotativa, 'excluirRotativa' => $excluirRotativa,
'papelInteriorDiferente' => $papelInteriorDiferente 'papelInteriorDiferente' => $papelInteriorDiferente,
'forzarRotativa' => $forzarRotativa,
); );
$interior = PresupuestoClienteService::obtenerInterior($input_data); $interior = PresupuestoClienteService::obtenerInterior($input_data);
@ -2107,7 +2152,7 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
array_push($num_formas, $formas_linea); array_push($num_formas, $formas_linea);
} }
} }
$input_data['datosPedido']->merma = $this->calcular_merma($tirada[$t], $POD, $num_formas); $input_data['datosPedido']->merma = PresupuestoService::calcular_merma($tirada[$t], $POD, $num_formas);
if ($extra_info) { if ($extra_info) {
$info['merma'] = max($info['merma'], $input_data['datosPedido']->merma); $info['merma'] = max($info['merma'], $input_data['datosPedido']->merma);
} }
@ -3071,7 +3116,7 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
$sumForFactor += round($linea['precio_pedido'], 2) $sumForFactor += round($linea['precio_pedido'], 2)
- round($linea['margen_papel_pedido'], 2); - round($linea['margen_papel_pedido'], 2);
$margenPapel += round($linea['margen_papel_pedido'], 2); $margenPapel += round($linea['margen_papel_pedido'], 2);
$totalImpresion += round($linea['precio_click_pedido'], 2); $totalImpresion += round($linea['precio_click_pedido'], 2);
$totalImpresion -= round($linea['margen_click_pedido'], 2); $totalImpresion -= round($linea['margen_click_pedido'], 2);
$sumForFactor += round($linea['precio_click_pedido'], 2) $sumForFactor += round($linea['precio_click_pedido'], 2)
@ -3142,31 +3187,6 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
} }
} }
protected function calcular_merma($tirada, $POD, $formas_lineas_interior = [])
{
$merma = 0;
if ($tirada > $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);
}
if (count($merma_lineas) > 0)
$merma = max($merma_lineas);
}
return round($merma, 0);
}
protected function getPapelFormatoListItems($selId = null) protected function getPapelFormatoListItems($selId = null)
{ {
$papelFormatoModel = model('App\Models\Configuracion\PapelFormatoModel'); $papelFormatoModel = model('App\Models\Configuracion\PapelFormatoModel');

View File

@ -0,0 +1,30 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\RawSql;
use CodeIgniter\Database\Migration;
class AddClienteNoBasePODnoHQ extends Migration
{
protected array $COLUMNS = [
"no_envio_base" => [
"type" => "TINYINT",
"default" => 0,
],
"forzar_rotativa_pod" => [
"type" => "TINYINT",
"default" => 0,
],
];
public function up()
{
$this->forge->addColumn('clientes', $this->COLUMNS);
}
public function down()
{
//
$this->forge->dropColumn('clientes', array_keys($this->COLUMNS));
}
}

View File

@ -1,7 +1,9 @@
<?php <?php
namespace App\Entities\Cliente; namespace App\Entities\Clientes;
use CodeIgniter\Entity; use CodeIgniter\Entity;
use App\Models\Clientes\ClienteModel;
use App\Models\Configuracion\PaisModel;
class ClienteDireccionesEntity extends \CodeIgniter\Entity\Entity class ClienteDireccionesEntity extends \CodeIgniter\Entity\Entity
{ {
@ -23,4 +25,29 @@ class ClienteDireccionesEntity extends \CodeIgniter\Entity\Entity
"pais_id" => "int", "pais_id" => "int",
"cp" => "int", "cp" => "int",
]; ];
public function getClienteNombre(): ?string
{
if (!$this->cliente_id) {
return null;
}
$clienteModel = model(ClienteModel::class);
$cliente = $clienteModel->find($this->cliente_id);
return $cliente ? $cliente->nombre : null;
}
public function getPaisNombre(): ?string
{
if (!$this->pais_id) {
return null;
}
$paisModel = model(PaisModel::class);
$pais = $paisModel->find($this->pais_id);
return $pais ? $pais->nombre : null;
}
} }

View File

@ -48,6 +48,8 @@ class ClienteEntity extends \CodeIgniter\Entity\Entity
"updated_at" => null, "updated_at" => null,
"user_created_id" => 1, "user_created_id" => 1,
"user_update_id" => 1, "user_update_id" => 1,
"no_envio_base" => 0,
"forzar_rotativa_pod" => 0,
]; ];
protected $casts = [ protected $casts = [
"comunidad_autonoma_id" => "?int", "comunidad_autonoma_id" => "?int",
@ -70,6 +72,8 @@ class ClienteEntity extends \CodeIgniter\Entity\Entity
"is_deleted" => "int", "is_deleted" => "int",
"user_created_id" => "int", "user_created_id" => "int",
"user_update_id" => "int", "user_update_id" => "int",
"no_envio_base" => "boolean",
"forzar_rotativa_pod" => "boolean",
]; ];
public function comercial() : ?UserEntity public function comercial() : ?UserEntity

View File

@ -722,6 +722,7 @@ return [
"menu_importadores" => "Importadores", "menu_importadores" => "Importadores",
"menu_importadores_catalogo" => "Desde catálogo", "menu_importadores_catalogo" => "Desde catálogo",
"menu_importadores_bubok" => "Bubok",
"menu_catalogo" => "Catálogo", "menu_catalogo" => "Catálogo",
"menu_catalogo_libros" => "Libros", "menu_catalogo_libros" => "Libros",

View File

@ -46,6 +46,8 @@ return [
'userCreatedId' => 'User Created ID', 'userCreatedId' => 'User Created ID',
'userUpdateId' => 'User Update ID', 'userUpdateId' => 'User Update ID',
'vencimiento' => 'Vencimiento', 'vencimiento' => 'Vencimiento',
'removeEnvioBase' => 'No añadir Envio Base',
'forzarRotativaPod' => 'Forzar rotativa en POD',
'direccionesEnvio' => 'Direcciones de Envío', 'direccionesEnvio' => 'Direcciones de Envío',

View File

@ -3,6 +3,7 @@
return [ return [
'moduleTitle' => 'Importadores', 'moduleTitle' => 'Importadores',
'importadorCatalogoTitle' => 'Importador RA-MA Ediciones S.L.', 'importadorCatalogoTitle' => 'Importador RA-MA Ediciones S.L.',
'importadorBubokTitle' => 'Importador BUBOK Publishing S.L.',
'catalogo' => 'catálogo', 'catalogo' => 'catálogo',
'input' => 'ISBN', 'input' => 'ISBN',
'descripcion' => 'Título', 'descripcion' => 'Título',
@ -10,7 +11,8 @@ return [
'cnt_pedida' => 'Unidades', 'cnt_pedida' => 'Unidades',
'precio_compra' => 'Precio Compra', 'precio_compra' => 'Precio Compra',
'importar' => 'Importar', 'importar' => 'Importar',
'subirArchivo' => 'Cargar Excel proporcionado por RA-MA', 'subirArchivoRama' => 'Cargar Excel proporcionado por RA-MA',
'subirArchivoBubok' => 'Cargar XML proporcionado por BUBOK',
'libro' => 'libro', 'libro' => 'libro',
'id' => 'ID', 'id' => 'ID',

View File

@ -70,6 +70,7 @@ return [
'catalogoSection' => 'Catálogo', 'catalogoSection' => 'Catálogo',
'importadoresSection' => 'Importadores', 'importadoresSection' => 'Importadores',
'catalogoPermission' => 'Desde catálogo', 'catalogoPermission' => 'Desde catálogo',
'bubokPermission' => 'Bubok',

View File

@ -61,6 +61,8 @@ class ClienteModel extends \App\Models\BaseModel
"comentarios", "comentarios",
"user_created_id", "user_created_id",
"user_update_id", "user_update_id",
"no_envio_base",
"forzar_rotativa_pod",
]; ];
protected $returnType = ClienteEntity::class; protected $returnType = ClienteEntity::class;
protected $useSoftDeletes = true; protected $useSoftDeletes = true;

View File

@ -9,7 +9,7 @@ class EmailService
public function send(string $subject, string $body, $recipient): bool public function send(string $subject, string $body, $recipient): bool
{ {
$skEnv = env('sk_environment', 'production'); // fallback a producción si no está definido $skEnv = env('SK_ENVIRONMENT', 'production'); // fallback a producción si no está definido
// Si no estamos en producción, forzar el destinatario a uno fijo // Si no estamos en producción, forzar el destinatario a uno fijo
if ($skEnv !== 'production') { if ($skEnv !== 'production') {

View File

@ -58,7 +58,7 @@ class PresupuestoClienteService extends BaseService
if ($total_plana < 0 && $total_rotativa < 0) if ($total_plana < 0 && $total_rotativa < 0)
return []; return [];
else { else {
if ($total_plana > $total_rotativa) if ($total_plana > $total_rotativa && $data['forzarRotativa'] == 0)
return $plana; return $plana;
else else
return [$rotativa]; return [$rotativa];

View File

@ -1983,4 +1983,95 @@ class PresupuestoService extends BaseService
return $peso; return $peso;
} }
public static function ajustarPresupuesto($id, $precio_unidad = null, $unidades = null, $precio_total = null, $forzar_descuento = false){
$precio_total_asignado = 0;
$precio_unidad_asignado = $precio_unidad;
$warning = false;
$model = model('App\Models\Presupuestos\PresupuestoModel');
if($precio_unidad != null && $unidades != null){
$precio_total_asignado = round(floatval($precio_unidad) * intval($unidades), 2);
}
else{
$precio_total_asignado = floatval($precio_total);
}
$presupuesto = $model->find($id);
$costes = floatval($presupuesto->total_costes);
$envio_base = floatval($presupuesto->envio_base);
$total_descuento = 0;
$total_descuentoPercent = 0;
if($costes + $envio_base > $precio_total_asignado){
if($forzar_descuento){
$total_descuento = $costes + $envio_base - $precio_total_asignado;
$total_descuentoPercent = round($total_descuento / ($costes + $envio_base) * 100, 2);
}
else{
$precio_total_asignado = round($costes + $envio_base, 2);
$precio_unidad_asignado = round($precio_total_asignado / intval($unidades), 4);
}
$warning = true;
}
$total_margenes = $precio_total_asignado - $costes - $envio_base < 0 ?
0 :
$precio_total_asignado - $costes - $envio_base;
$sumForFactor = floatval($presupuesto->total_coste_papel) + floatval($presupuesto->total_coste_impresion);
$sumForFactorPonderado = $sumForFactor + floatval($presupuesto->total_coste_servicios);
$factor = ($precio_total_asignado - floatval($presupuesto->envio_base)
- floatval($presupuesto->total_coste_envios) - floatval($presupuesto->total_margen_envios)) / $sumForFactor;
$factorPonderado = ($precio_total_asignado - floatval($presupuesto->envio_base)
- floatval($presupuesto->total_coste_envios) - floatval($presupuesto->total_margen_envios)) / $sumForFactorPonderado;
if ($presupuesto) {
$presupuesto->total_margenes = $total_margenes;
$presupuesto->total_aceptado = $precio_total_asignado;
$presupuesto->total_aceptado_revisado = $precio_total_asignado;
$presupuesto->total_presupuesto = $precio_total_asignado;
$presupuesto->total_antes_descuento = $precio_total_asignado - $costes - $envio_base < 0 ?
$costes + $envio_base :
$precio_total_asignado;
$presupuesto->total_precio_unidad = $precio_unidad_asignado;
$presupuesto->total_descuento = $total_descuento;
$presupuesto->total_descuentoPercent = $total_descuentoPercent;
$presupuesto->total_factor = round($factor, 2);
$presupuesto->total_factor_ponderado = round($factorPonderado, 2);
$model->update($id, $presupuesto);
}
return [
"success" => true,
"warning" => $warning,
"new_total" => $precio_total_asignado,
"new_precio_unidad" => $precio_unidad_asignado,
];
}
public static function calcular_merma($tirada, $POD, $formas_lineas_interior = [])
{
$merma = 0;
if ($tirada > $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);
}
if (count($merma_lineas) > 0)
$merma = max($merma_lineas);
}
return round($merma, 0);
}
} }

View File

@ -521,6 +521,28 @@
</label> </label>
</div> </div>
</div> </div>
<div class="col-md-3">
<div class="form-check">
<label for="removeEnvioBase" class="form-check-label">
<input type="checkbox" id="removeEnvioBase"
name="no_envio_base" value="1"
class="form-check-input"<?= $clienteEntity->no_envio_base == true ? 'checked' : ''; ?>>
<?= lang('Clientes.removeEnvioBase') ?>
</label>
</div>
</div>
<div class="col-md-3">
<div class="form-check">
<label for="rotativaPOD" class="form-check-label">
<input type="checkbox" id="rotativaPOD"
name="forzar_rotativa_pod" value="1"
class="form-check-input"<?= $clienteEntity->forzar_rotativa_pod == true ? 'checked' : ''; ?>>
<?= lang('Clientes.forzarRotativaPod') ?>
</label>
</div>
</div>
</div>
<div class="row g-3 mb-3">
<div class="col-md-3"> <div class="col-md-3">
<div class="form-check"> <div class="form-check">
<label for="tiradaFlexible" class="form-check-label"> <label for="tiradaFlexible" class="form-check-label">

View File

@ -0,0 +1,103 @@
<?= $this->include('themes/_commonPartialsBs/datatables') ?>
<?= $this->include('themes/_commonPartialsBs/sweetalert') ?>
<?= $this->extend('themes/vuexy/main/defaultlayout') ?>
<?= $this->section('content'); ?>
<div class="row">
<div class="col-md-12">
<div class="card card-info">
<div class="card-header">
<h3 class="card-title"><?= lang('Importador.importadorBubokTitle') ?></h3>
</div><!--//.card-header -->
<form id="catalogoLibroForm" class="card-body" method="post" action="#">
<?= csrf_field() ?>
<!-- card-body -->
<div class="card-body">
<?= view('themes/_commonPartialsBs/_alertBoxes'); ?>
<div class="row">
<div class="col-md-6 mb-3">
<label for="xmlFile"
class="form-label"><?= lang('Importador.subirArchivoBubok') ?? 'Subir archivo XML' ?></label>
<input type="file" id="xmlFile" accept=".xml" class="form-control">
</div>
<div class="col-md-4 mb-3 d-flex align-items-end">
<button type="button" id="importBtn" class="btn btn-success w-100">
<i class="fas fa-file-import me-2"></i> <?= lang('Importador.importar') ?? 'Importar' ?>
</button>
</div>
<div class="col-md-12 mb-3">
<table id="xmlTable" class="table">
<thead>
<tr>
<th><input type="checkbox" id="selectAll" /></th>
<th>Referencia</th>
<th>Título</th>
<th>Tamaño</th>
<th>Páginas</th>
<th>Tirada</th>
<th>Interior</th>
<th>Notas</th>
<th>Acciones</th>
</tr>
<tr>
<th></th> <!-- No filtro para checkbox -->
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th> <!-- No filtro para notas -->
<th></th> <!-- No filtro para acciones -->
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
</div>
</form>
</div><!--//.card-body -->
<div class="card-footer">
</div><!--//.card-footer -->
</div><!--//.card -->
</div><!--//.col -->
</div><!--//.row -->
<?= $this->endSection() ?>
<?= $this->section('css') ?>
<link rel="stylesheet"
href="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/buttons/buttons.bootstrap5.min.css") ?>">
<link rel="stylesheet" href="<?= site_url('themes/vuexy/vendor/libs/sweetalert2/sweetalert2.css') ?>" />
<?= $this->endSection() ?>
<?= $this->section('additionalExternalJs') ?>
<script
src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/buttons/dataTables.buttons.min.js") ?>"></script>
<script
src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/buttons/buttons.bootstrap5.min.js") ?>"></script>
<script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/buttons/buttons.html5.min.js") ?>"></script>
<script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/buttons/buttons.print.min.js") ?>"></script>
<script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/jszip/jszip.min.js") ?>"></script>
<script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/pdfmake/pdfmake.min.js") ?>"
crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/pdfmake/vfs_fonts.js") ?>"></script>
<script src="<?= site_url('themes/vuexy/vendor/libs/sweetalert2/sweetalert2.js') ?>"></script>
<script type="module" src="<?= site_url("assets/js/safekat/pages/importadores/bubok/bubok_tool.js") ?>"></script>
<?= $this->endSection() ?>

View File

@ -22,7 +22,7 @@
<div class="col-md-6 mb-3"> <div class="col-md-6 mb-3">
<label for="excelFile" <label for="excelFile"
class="form-label"><?= lang('Importador.subirArchivo') ?? 'Subir archivo Excel' ?></label> class="form-label"><?= lang('Importador.subirArchivoRama') ?? 'Subir archivo Excel' ?></label>
<input type="file" class="form-control" id="excelFile" name="excelFile" <input type="file" class="form-control" id="excelFile" name="excelFile"
accept=".xlsx, .xls"> accept=".xlsx, .xls">
</div> </div>

View File

@ -20,7 +20,14 @@ if (auth()->user()->can('importadores.menu')) {
</a> </a>
</li> </li>
<?php } ?> <?php } ?>
<?php if (auth()->user()->can('importadores.bubok')) { ?>
<li class="menu-item">
<a href="<?= route_to("importadorBubokTool") ?>" class="menu-link">
<?= lang("App.menu_importadores_bubok") ?>
</a>
</li>
<?php } ?>
</ul> </ul>
</li> </li>

View File

@ -0,0 +1,344 @@
document.addEventListener('DOMContentLoaded', function () {
let dataTable;
let productosOriginales = [];
let datosComunesPedido = {};
document.getElementById('xmlFile').addEventListener('change', function (e) {
const file = e.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = function (event) {
const xmlText = event.target.result;
parseXmlAndLoadTable(xmlText);
};
reader.readAsText(file);
});
function parseXmlAndLoadTable(xmlText) {
let parser = new DOMParser();
let xmlDoc;
try {
xmlDoc = parser.parseFromString(xmlText, 'application/xml');
if (xmlDoc.getElementsByTagName('parsererror').length > 0) throw new Error('XML inválido');
} catch (e) {
Swal.fire('Error', 'No se pudo leer el XML.', 'error');
return;
}
datosComunesPedido = {
orderNumber: xmlDoc.querySelector('orderNumber')?.textContent ?? '',
shipping: {
address: xmlDoc.querySelector('shippingData > address')?.textContent ?? '',
city: xmlDoc.querySelector('shippingData > city')?.textContent ?? '',
country: xmlDoc.querySelector('shippingData > country')?.textContent ?? '',
postalCode: xmlDoc.querySelector('shippingData > postalCode')?.textContent ?? '',
name: xmlDoc.querySelector('shippingData > name')?.textContent ?? '',
phone: xmlDoc.querySelector('shippingData > phone')?.textContent ?? ''
},
labelUrl: xmlDoc.querySelector('urlPdfSeur')?.textContent ?? ''
};
const products = Array.from(xmlDoc.getElementsByTagName('product'));
productosOriginales = products.map((prod, idx) => ({ index: idx, data: prod }));
const rows = products.map((product, index) => {
const id = product.querySelector('id')?.textContent ?? '';
const title = product.querySelector('title')?.textContent ?? '';
const pages = product.querySelector('body > pages')?.textContent ?? '';
const tirada = product.querySelector('amount')?.textContent ?? '';
let interior = 'Desconocido';
const colorNode = product.querySelector('body > color');
if (colorNode) {
const monochrome = colorNode.querySelector('Monochrome')?.textContent ?? '0';
const cmyk = colorNode.querySelector('CMYK')?.textContent ?? '0';
const semicolor = colorNode.querySelector('Semicolor')?.textContent ?? '0';
if (monochrome === '1') interior = 'Negro';
else if (cmyk === '1') interior = 'Color';
else if (semicolor === '1') interior = 'Semicolor';
}
let tamano = 'Desconocido';
const sizeTags = product.querySelectorAll('size > *');
sizeTags.forEach(tag => {
if (tag.textContent === '1') {
tamano = tag.tagName.replace(/^size/, '');
}
});
return [
`<input type="checkbox" class="form-check-input select-row" checked>`,
`${datosComunesPedido.orderNumber} - ${id}`,
title,
tamano,
pages,
tirada,
interior,
'',
`<button type="button" class="btn btn-sm btn-outline-success importRow">Importar</button>
<button type="button" class="btn btn-sm btn-outline-danger deleteRow">Eliminar</button>`
];
});
if (!$.fn.DataTable.isDataTable('#xmlTable')) {
const headerHtml = `
<thead>
<tr>
<th><input type="checkbox" id="selectAll" /></th>
<th>Referencia</th>
<th>Título</th>
<th>Tamaño</th>
<th>Páginas</th>
<th>Tirada</th>
<th>Interior</th>
<th>Notas</th>
<th>Acciones</th>
</tr>
<tr>
<th></th><th></th><th></th><th></th><th></th>
<th></th><th></th><th></th><th></th>
</tr>
</thead>`;
$('#xmlTable').html(headerHtml);
}
dataTable = $('#xmlTable').DataTable({
destroy: true,
data: rows,
orderCellsTop: true,
responsive: true,
scrollX: true,
dom: 'lfrtip',
language: {
url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json"
},
order: [[1, 'asc']]
});
$('#xmlTable thead tr:eq(1) th').each(function (i) {
if (![0, 7, 8].includes(i)) {
$(this).html('<input type="text" class="form-control form-control-sm" placeholder="Filtrar..." />');
$('input', this).on('keyup change', function () {
if (dataTable.column(i).search() !== this.value) {
dataTable.column(i).search(this.value).draw();
}
});
}
});
setupEventListeners();
}
function setupEventListeners() {
$('#xmlTable tbody').off('click', '.deleteRow').on('click', '.deleteRow', function () {
dataTable.row($(this).parents('tr')).remove().draw();
});
$('#xmlTable tbody').off('click', '.importRow').on('click', '.importRow', async function () {
const $row = $(this).closest('tr');
const rowIndex = dataTable.row($row).index();
const xmlProduct = productosOriginales.find(p => p.index === rowIndex)?.data;
if (!xmlProduct) return;
try {
const response = await fetch('/importador/bubok/importar-fila', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': '<?= csrf_hash() ?>'
},
body: JSON.stringify({
producto: xmlToJson(xmlProduct),
pedido: datosComunesPedido
})
});
const result = await response.json();
const rowData = dataTable.row($row).data();
if (response.ok && result.status === 200) {
const skUrl = result.data?.sk_url?.replace('presupuestocliente', 'presupuestoadmin') ?? null;
const htmlLink = skUrl
? `<a href="${skUrl}" target="_blank" class="btn btn-sm btn-primary">Ver presupuesto</a>`
: 'Importado';
rowData[7] = htmlLink;
dataTable.row($row).data(rowData).draw(false);
Swal.fire({
title: 'Importado correctamente',
html: skUrl
? `Se importó correctamente.<br><a href="${skUrl}" target="_blank" class="btn btn-primary mt-2">Ver presupuesto</a>`
: 'Importación realizada.',
icon: 'success',
confirmButtonText: 'Aceptar',
customClass: { confirmButton: 'btn btn-success' }
});
} else {
rowData[7] = `<span class="badge bg-danger">${result.message ?? 'Error inesperado'}</span>`;
dataTable.row($row).data(rowData).draw(false);
Swal.fire({
title: 'Error',
text: result.message ?? 'Hubo un error al importar esta fila.',
icon: 'error',
confirmButtonText: 'Aceptar',
customClass: { confirmButton: 'btn btn-danger' }
});
}
dataTable.row($row).data(rowData).draw(false);
} catch (err) {
console.error(err);
Swal.fire('Error', 'Error de comunicación con el servidor.', 'error');
}
});
$('#selectAll').off('change').on('change', function () {
const checked = $(this).is(':checked');
$('#xmlTable tbody input.select-row:enabled').prop('checked', checked);
});
}
function xmlToJson(xmlNode) {
// Si es nodo de texto
if (xmlNode.nodeType === 3) {
return xmlNode.nodeValue.trim();
}
let obj = {};
// Procesar atributos si existen
if (xmlNode.attributes && xmlNode.attributes.length > 0) {
for (let attr of xmlNode.attributes) {
obj[`@${attr.name}`] = attr.value;
}
}
// Procesar hijos
if (xmlNode.hasChildNodes()) {
const children = Array.from(xmlNode.childNodes).filter(n => n.nodeType !== 8); // ignorar comentarios
// Si el único hijo es texto, devolver como string
if (children.length === 1 && children[0].nodeType === 3) {
return children[0].nodeValue.trim();
}
// Procesar nodos hijos normalmente
children.forEach(child => {
const name = child.nodeName;
const value = xmlToJson(child);
if (obj[name]) {
if (!Array.isArray(obj[name])) {
obj[name] = [obj[name]];
}
obj[name].push(value);
} else {
obj[name] = value;
}
});
}
return obj;
}
document.getElementById('importBtn').addEventListener('click', async function () {
if (!dataTable || dataTable.rows().count() === 0) {
Swal.fire({
title: 'Atención',
text: 'Primero debes cargar un archivo XML válido.',
icon: 'warning',
confirmButtonText: 'Aceptar',
customClass: { confirmButton: 'btn btn-warning' }
});
return;
}
const filasSeleccionadas = [];
dataTable.rows().every(function () {
const node = this.node();
const checkbox = $(node).find('input.select-row');
if (checkbox.length > 0 && checkbox.is(':checked') && !checkbox.is(':disabled')) {
filasSeleccionadas.push(this.index());
}
});
if (filasSeleccionadas.length === 0) {
Swal.fire({
title: 'Atención',
text: 'No hay filas seleccionadas.',
icon: 'warning',
confirmButtonText: 'Aceptar',
customClass: { confirmButton: 'btn btn-warning' }
});
return;
}
Swal.fire({
title: '¿Importar seleccionados?',
text: `Se van a importar ${filasSeleccionadas.length} filas.`,
icon: 'question',
showCancelButton: true,
confirmButtonText: 'Sí, importar',
cancelButtonText: 'Cancelar',
reverseButtons: true,
customClass: {
confirmButton: 'btn btn-primary',
cancelButton: 'btn btn-secondary'
}
}).then(async (result) => {
if (!result.isConfirmed) return;
for (const i of filasSeleccionadas) {
const productXml = productosOriginales.find(p => p.index === i)?.data;
if (!productXml) continue;
try {
const response = await fetch('/importador/bubok/importar-fila', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': '<?= csrf_hash() ?>'
},
body: JSON.stringify({
producto: xmlToJson(productXml),
pedido: datosComunesPedido
})
});
const result = await response.json();
const rowNode = dataTable.row(i).node();
const rowData = dataTable.row(i).data();
if (response.ok && result.status === 200) {
const skUrl = result.data?.sk_url?.replace('presupuestocliente', 'presupuestoadmin') ?? null;
rowData[7] = skUrl
? `<a href="${skUrl}" target="_blank" class="btn btn-sm btn-primary">Ver presupuesto</a>`
: '<span class="badge bg-success">Importado</span>';
} else {
rowData[7] = `<span class="badge bg-danger">${result.message ?? 'Error desconocido'}</span>`;
}
dataTable.row(rowNode).data(rowData).draw(false);
} catch (error) {
console.error('Importación fallida:', error);
}
}
Swal.fire({
title: 'Importación finalizada',
text: 'Se han procesado todas las filas seleccionadas.',
icon: 'success',
confirmButtonText: 'Aceptar',
customClass: { confirmButton: 'btn btn-success' }
});
});
});
});

View File

@ -169,12 +169,21 @@ document.addEventListener('DOMContentLoaded', function () {
dataTable.row($row).data(rowData).draw(false); // Redibujar la fila SIN perder scroll ni filtros dataTable.row($row).data(rowData).draw(false); // Redibujar la fila SIN perder scroll ni filtros
} }
let html = skUrl
? `La fila se importó exitosamente.<br><br><a href="${skUrl}" target="_blank" class="btn btn-primary mt-2">Ver presupuesto</a>`
: 'La fila se importó exitosamente.';
let icon = 'success';
if (result.price_warning) {
html = skUrl ? `La fila se importó exitosamente, pero el precio se ha ajustado debajo de costes.<br><br><a href="${skUrl}" target="_blank" class="btn btn-primary mt-2">Ver presupuesto</a>`
: 'La fila se importó exitosamente, pero el precio se ha ajustado debajo de costes.';
icon = 'warning';
}
Swal.fire({ Swal.fire({
title: 'Importado correctamente', title: 'Importado correctamente',
html: skUrl html: html,
? `La fila se importó exitosamente.<br><br><a href="${skUrl}" target="_blank" class="btn btn-primary mt-2">Ver presupuesto</a>` icon: icon,
: 'La fila se importó exitosamente.',
icon: 'success',
confirmButtonText: 'Aceptar', confirmButtonText: 'Aceptar',
buttonsStyling: true, buttonsStyling: true,
customClass: { confirmButton: 'btn btn-success' } customClass: { confirmButton: 'btn btn-success' }
@ -252,6 +261,9 @@ document.addEventListener('DOMContentLoaded', function () {
}).then(async (result) => { }).then(async (result) => {
if (!result.isConfirmed) return; if (!result.isConfirmed) return;
// array para contener los IDs que no se han podido ajustar
let idsNoAjustados = [];
for (const fila of filasAptas) { for (const fila of filasAptas) {
try { try {
const response = await fetch('/importador/catalogo/importar-fila', { const response = await fetch('/importador/catalogo/importar-fila', {
@ -268,6 +280,10 @@ document.addEventListener('DOMContentLoaded', function () {
if (response.ok && result.status === 200) { if (response.ok && result.status === 200) {
const skUrl = result.data?.sk_url?.replace('presupuestocliente', 'presupuestoadmin') ?? null; const skUrl = result.data?.sk_url?.replace('presupuestocliente', 'presupuestoadmin') ?? null;
if (result.price_warning) {
idsNoAjustados.push(result.data.sk_id);
}
if (skUrl) { if (skUrl) {
fila.rowData[6] = `<a href="${skUrl}" target="_blank" class="btn btn-sm btn-primary">Ver presupuesto</a>`; fila.rowData[6] = `<a href="${skUrl}" target="_blank" class="btn btn-sm btn-primary">Ver presupuesto</a>`;
} else { } else {
@ -286,10 +302,16 @@ document.addEventListener('DOMContentLoaded', function () {
} }
} }
let text = 'Se han procesado todas las filas seleccionadas.';
let icon = 'success';
if (idsNoAjustados.length > 0) {
text = 'Se han procesado todas las filas seleccionadas, pero se han ajustado los siguientes presupuestos por debajo de costes: ' + idsNoAjustados.join(', ');
icon = 'warning';
}
Swal.fire({ Swal.fire({
title: 'Importación finalizada', title: 'Importación finalizada',
text: 'Se han procesado todas las filas seleccionadas.', text: text,
icon: 'success', icon: icon,
confirmButtonText: 'Aceptar', confirmButtonText: 'Aceptar',
buttonsStyling: true, buttonsStyling: true,
customClass: { confirmButton: 'btn btn-success' } customClass: { confirmButton: 'btn btn-success' }

View File

@ -1540,6 +1540,12 @@ class LineasPresupuesto {
cliente_id: $('#clienteId').find(":selected").val(), cliente_id: $('#clienteId').find(":selected").val(),
}; };
if($('#alert-datosLibro').html().includes(window.language.Presupuestos.validation.no_lp_for_merma) &&
(uso == 'interior' || uso == 'interior_rot')){
datos.calcular_merma = 1;
}
if (datos.ancho == 0 || datos.alto == 0 || datos.ancho == '' || datos.alto == '' || isNaN(datos.ancho) || isNaN(datos.alto)) { if (datos.ancho == 0 || datos.alto == 0 || datos.ancho == '' || datos.alto == '' || isNaN(datos.ancho) || isNaN(datos.alto)) {
return; return;
} }

View File

@ -20,7 +20,12 @@ class Resumen {
}); });
$('#total_descuentoPercent').on('change', function () { $('#total_descuentoPercent').on('change', function () {
this.updateTotales({ updateLP: false, updateServicios: false, updateEnvio: false }, false); let autoTotalAceptado = AutoNumeric.getAutoNumericElement($('#total_aceptado_revisado')[0]);
let total_aceptado_revisado = autoTotalAceptado.getNumber();
if(total_aceptado_revisado && total_aceptado_revisado != 0)
this.updateTotales({ updateLP: false, updateServicios: false, updateEnvio: false }, true);
else
this.updateTotales({ updateLP: false, updateServicios: false, updateEnvio: false }, false);
}.bind(this)); }.bind(this));
$("#totalDespuesDecuento").on('change', this.updateToastSummary.bind(this)) $("#totalDespuesDecuento").on('change', this.updateToastSummary.bind(this))
@ -354,7 +359,7 @@ class Resumen {
$('#total_descuentoPercent').val(0) $('#total_descuentoPercent').val(0)
} }
let totalAntesDescuento = totalCostes + totalMargenes + totalEnvios_base; let totalAntesDescuento = totalCostes + totalMargenes + totalEnvios_base;
let totalDescuento = totalAntesDescuento * parseInt($('#total_descuentoPercent').val() || 0) / 100 let totalDescuento = totalAntesDescuento * parseFloat($('#total_descuentoPercent').val() || 0) / 100
let totalPresupuesto = totalAntesDescuento - totalDescuento; // para el calculo del precio_u solo se tiene en cuenta el base let totalPresupuesto = totalAntesDescuento - totalDescuento; // para el calculo del precio_u solo se tiene en cuenta el base
let precioUnidad = totalPresupuesto / parseInt($('#tirada').val()) let precioUnidad = totalPresupuesto / parseInt($('#tirada').val())