This commit is contained in:
amazuecos
2025-05-22 18:33:44 +02:00
21 changed files with 1036 additions and 259 deletions

View File

@ -765,6 +765,7 @@ $routes->group('produccion', ['namespace' => 'App\Controllers\Produccion'], func
$routes->get('tareas/datatable/(:num)', 'Ordentrabajo::tareas_datatable/$1', ['as' => 'datatableTareasOrdenTrabajo']);
$routes->get('maquinas/ots/datatable/(:num)','Ordentrabajo::datatable_maquina_ordenes_trabajo/$1');
$routes->get('maquinas/ots/(:num)','Ordentrabajo::get_maquina_ots/$1');
/**======================
* UPDATES
*========================**/
@ -871,6 +872,8 @@ $routes->group('logistica', ['namespace' => 'App\Controllers\Logistica'], functi
$routes->get('selectForNewEnvio', 'LogisticaController::findForNewEnvio');
$routes->get('selectDireccionForEnvio', 'LogisticaController::selectDireccionForEnvio');
$routes->post('imprimirEtiquetas', 'LogisticaController::imprimirEtiquetas');
$routes->post('ficharEmbalaje', 'LogisticaController::ficharEmbalaje');
$routes->get('datatableProximosEnvios/(:num)', 'LogisticaController::datatable_proximosEnvios/$1');
$routes->get('listAlbaranes', 'LogisticaController::listAlbaranes', ['as' => 'albaranesList']);
});

View File

@ -450,6 +450,76 @@ class ImportadorBubok extends BaseResourceController
], 400);
}
// Descarga y subida de archivos al SFTP
$presupuestoFicheroModel = model('App\Models\Presupuestos\PresupuestoFicheroModel');
$ftp = new \App\Libraries\SafekatFtpClient();
$archivoUrls = [
'cover' => $producto->cover->file ?? null,
'body' => $producto->body->file ?? null,
];
foreach ($archivoUrls as $tipo => $url) {
if (!$url)
continue;
try {
$contenido = @file_get_contents($url); // silenciar errores de PHP
if ($contenido === false || strlen($contenido) === 0) {
// No se pudo descargar el archivo: generar archivo de error para FTP
$errorMessage = "ERROR: No se pudo descargar el archivo remoto para $tipo desde la URL: $url";
$remoteDir = $ftp->getPresupuestoRemotePath($response['sk_id']); // crea esta función si no existe
$remoteErrorFile = $remoteDir . '/ERROR_' . strtoupper($tipo) . '.txt';
// Crear archivo temporal con el mensaje de error
$tempErrorFile = WRITEPATH . 'uploads/presupuestos/ERROR_' . $tipo . '.txt';
file_put_contents($tempErrorFile, $errorMessage);
if (!$ftp->is_dir($remoteDir)) {
$ftp->mkdir($remoteDir, recursive: true);
}
$ftp->put($remoteErrorFile, $tempErrorFile, $ftp::SOURCE_LOCAL_FILE);
continue; // no procesar este archivo
}
// ✅ Procesar normalmente si la descarga tuvo éxito
$nombreOriginal = basename(parse_url($url, PHP_URL_PATH));
$extension = pathinfo($nombreOriginal, PATHINFO_EXTENSION);
$nombreLimpio = $presupuestoFicheroModel->saveFileInBBDD(
$response['sk_id'],
$nombreOriginal,
$extension,
auth()->id()
);
if (is_null($nombreLimpio))
continue;
$rutaLocal = WRITEPATH . 'uploads/presupuestos/';
if (!is_dir($rutaLocal)) {
mkdir($rutaLocal, 0777, true);
}
file_put_contents($rutaLocal . $nombreLimpio, $contenido);
} catch (\Throwable $e) {
//log_message('error', 'Error inesperado en descarga de archivo remoto: ' . $e->getMessage());
}
}
// Subir al FTP después de guardar localmente
try {
$ftp->uploadFilePresupuesto($response['sk_id']);
} catch (\Throwable $e) {
log_message('error', 'Error subiendo archivos al FTP: ' . $e->getMessage());
}
return $this->respond([
'status' => 200,
'data' => [
@ -458,6 +528,7 @@ class ImportadorBubok extends BaseResourceController
]
]);
} catch (\Throwable $e) {
return $this->respond([
'status' => 500,

View File

@ -163,10 +163,10 @@ class EtiquetasTitulosController extends BaseController
$modelImpresora = model('App\Models\Configuracion\ImpresoraEtiquetaModel');
$impresoras = $modelImpresora->select('id, name')
$impresoras = $modelImpresora->select('id, name, description')
->where('deleted_at', null)
->where('tipo', 1)
->orderBy('name', 'desc')
->orderBy('name', 'asc')
->findAll();
$etiquetaEntity->impresoras = $impresoras;
@ -440,7 +440,7 @@ class EtiquetasTitulosController extends BaseController
$impresora_id = $this->request->getPost('impresora_id') ?? null;
$modelImpresora = model('App\Models\Configuracion\ImpresoraEtiquetaModel');
$impresora = $modelImpresora->select('id, name, ip, port, user, pass')
$impresora = $modelImpresora->select('id, name, description, ip, port, user, pass')
->where('deleted_at', null)
->where('id', $impresora_id)
->orderBy('name', 'asc')

View File

@ -98,7 +98,8 @@ class LogisticaController extends BaseController
return view(static::$viewPath . 'viewImpresionEtiquetas', $viewData);
}
public function listAlbaranes(){
public function listAlbaranes()
{
$viewData = [
'currentModule' => static::$controllerSlug,
'boxTitle' => lang('Albaran.albaranes'),
@ -117,7 +118,7 @@ class LogisticaController extends BaseController
$tipo_envio = $this->request->getGet('tipo_envio') ?? 'estandar';
if($tipo_envio == 'ferro_prototipo'){
if ($tipo_envio == 'ferro_prototipo') {
$query = LogisticaService::findForNewEnvioFerro();
} else {
$query = LogisticaService::findForNewEnvio();
@ -132,22 +133,25 @@ class LogisticaController extends BaseController
$result = $query->orderBy("name", "asc")->get()->getResultObject();
$query = model('App\Models\Logistica\EnvioModel')->db->getLastQuery();
return $this->response->setJSON($result);
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function selectDireccionForEnvio(){
public function selectDireccionForEnvio()
{
if ($this->request->isAJAX()) {
$ot = $this->request->getGet('ot_id');
if($ot == null || $ot == 0){
if ($ot == null || $ot == 0) {
return [];
}
$searchVal = $this->request->getGet("q") ?? "";
$result = LogisticaService::findDireccionesNewEnvio($ot, $searchVal);
return $this->response->setJSON($result);
} else {
return $this->failUnauthorized('Invalid request', 403);
@ -185,12 +189,12 @@ class LogisticaController extends BaseController
public function imprimirEtiquetas()
{
if ($this->request->isAJAX()) {
$envio_id = $this->request->getPost('envio_id');
$envio_id = $this->request->getPost('envio_id');
$ids = $this->request->getPost('envio_lineas');
$cajas = $this->request->getPost('cajas');
$printer_id = $this->request->getPost('printer_id');
if($cajas == null || $cajas == 0){
if ($cajas == null || $cajas == 0) {
return $this->response->setJSON([
'status' => false,
'message' => 'Cajas no válidas'
@ -202,7 +206,7 @@ class LogisticaController extends BaseController
->join('clientes', 'clientes.id = envios.cliente_id', 'left')
->where('envios.id', $envio_id)
->first();
if($envio == null){
if ($envio == null) {
return $this->response->setJSON([
'status' => false,
'message' => 'Envio no válido'
@ -213,7 +217,7 @@ class LogisticaController extends BaseController
$lineas = $model->select('envios_lineas.*, presupuestos.titulo as titulo, presupuestos.referencia_cliente as referencia_cliente')
->join('presupuestos', 'presupuestos.id = envios_lineas.presupuesto_id', 'left')
->whereIn('envios_lineas.id', $ids)->findAll();
if($lineas == null){
if ($lineas == null) {
return $this->response->setJSON([
'status' => false,
'message' => 'Lineas no válidas'
@ -221,12 +225,12 @@ class LogisticaController extends BaseController
}
$modelImpresora = model('App\Models\Configuracion\ImpresoraEtiquetaModel');
$impresora = $modelImpresora->select('id, name, ip, port, user, pass')
$impresora = $modelImpresora->select('id, name, description, ip, port, user, pass')
->where('deleted_at', null)
->where('id', $printer_id)
->orderBy('name', 'asc')
->first();
if($impresora == null){
if ($impresora == null) {
return $this->response->setJSON([
'status' => false,
'message' => 'Impresora no válida'
@ -330,22 +334,22 @@ class LogisticaController extends BaseController
if (empty($envioEntity)) {
return redirect()->to(base_url('logistica/selectEnvios/simple'))->with('error', lang('Logistica.errors.noEnvio'));
}
$modelProveedor = model('App\Models\Compras\ProveedorModel');
$proveedor = $modelProveedor->select('id, nombre')
->where('deleted_at', null)
->where('id', $envioEntity->proveedor_id)
->orderBy('nombre', 'asc')
->first();
if(!empty($proveedor)){
if (!empty($proveedor)) {
$envioEntity->proveedor_nombre = $proveedor->nombre;
}
$modelImpresora = model('App\Models\Configuracion\ImpresoraEtiquetaModel');
$impresoras = $modelImpresora->select('id, name')
$impresoras = $modelImpresora->select('id, name, description')
->where('deleted_at', null)
->where('tipo', 1)
->orderBy('name', 'desc')
->orderBy('name', 'asc')
->findAll();
$envioEntity->impresoras = $impresoras;
@ -384,7 +388,7 @@ class LogisticaController extends BaseController
$id = $this->request->getPost('id') ?? null;
$finalizar_ots = $this->request->getPost('finalizar_ots') ?? false;
$result = LogisticaService::finalizarEnvio($id, $finalizar_ots);
return $this->response->setJSON($result);
} else {
@ -392,6 +396,17 @@ class LogisticaController extends BaseController
}
}
public function ficharEmbalaje()
{
if ($this->request->isAJAX()) {
$ids = $this->request->getPost('ids') ?? [];
$result = LogisticaService::ficharEmbalaje($ids);
return $this->response->setJSON($result);
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function datatable_enviosEdit($idEnvio)
{
@ -406,6 +421,12 @@ class LogisticaController extends BaseController
return '<input type="checkbox" class="form-check-input checkbox-linea-envio" name="row_selected[]" value="' . $q->id . '">';
}
)
->edit(
"ordenTrabajo",
function ($row, $meta) {
return '<a href="' . base_url('produccion/ordentrabajo/edit/' . $row->ordenTrabajo) . '" target="_blank">' . $row->ordenTrabajo . '</a>';
}
)
->edit(
"pedido",
function ($row, $meta) {
@ -420,17 +441,35 @@ class LogisticaController extends BaseController
)->edit(
"unidadesEnvio",
function ($row, $meta) {
if($row->finalizado == 1 || $row->tipo_envio == 'ferro_prototipo'){
if ($row->finalizado == 1 || $row->tipo_envio == 'ferro_prototipo') {
return $row->unidadesEnvio;
}
return '<input type="number" class="form-control input-lineas input-unidades text-center"
data-id="'. $row->id.'" data-name="unidades_envio" value="' . $row->unidadesEnvio . '">';
data-id="' . $row->id . '" data-name="unidades_envio" value="' . $row->unidadesEnvio . '">';
}
);
return $result->toJson(returnAsObject: true);
}
public function datatable_proximosEnvios($envio_id = null)
{
$q = LogisticaService::findNextEnvios($envio_id);
$result = DataTable::of($q)
->edit(
"ot",
function ($row, $meta) {
return '<a href="' . base_url('produccion/ordentrabajo/edit/' . $row->ot) . '" target="_blank">' . $row->ot . '</a>';
}
);
$result = $result->toJson(returnAsObject: true);
$query = model('App\Models\Logistica\EnvioModel')->db->getLastQuery();
return $result;
}
public function setCajaLinea()
{
@ -471,7 +510,7 @@ class LogisticaController extends BaseController
$fieldName = $this->request->getPost('name');
$fieldValue = $this->request->getPost('value');
if (!$id || !$fieldName || ($fieldName=='unidades_envio' && !$fieldValue)) {
if (!$id || !$fieldName || ($fieldName == 'unidades_envio' && !$fieldValue)) {
return $this->response->setJSON([
'status' => false,
'message' => 'Datos inválidos'
@ -480,7 +519,7 @@ class LogisticaController extends BaseController
$model = model('App\Models\Logistica\EnvioLineaModel');
$updated = $model->update($id, [
"" . $fieldName => $fieldValue==""? null: $fieldValue,
"" . $fieldName => $fieldValue == "" ? null : $fieldValue,
]);
return $this->response->setJSON([
@ -503,7 +542,7 @@ class LogisticaController extends BaseController
$model = model('App\Models\Logistica\EnvioModel');
$updated = $model->update($id, [
"codigo_seguimiento" => $fieldValue==""? null: $fieldValue,
"codigo_seguimiento" => $fieldValue == "" ? null : $fieldValue,
]);
return $this->response->setJSON([
@ -526,7 +565,7 @@ class LogisticaController extends BaseController
$model = model('App\Models\Logistica\EnvioModel');
$updated = $model->update($id, [
"proveedor_id" => $fieldValue==""? null: $fieldValue,
"proveedor_id" => $fieldValue == "" ? null : $fieldValue,
]);
return $this->response->setJSON([

View File

@ -951,7 +951,7 @@ class Ordentrabajo extends BaseController
}
$modelImpresora = model('App\Models\Configuracion\ImpresoraEtiquetaModel');
$impresora = $modelImpresora->select('id, name, ip, port, user, pass')
$impresora = $modelImpresora->select('id, name, description, ip, port, user, pass')
->where('deleted_at', null)
->where('id', $impresora_id)
->orderBy('name', 'asc')

View File

@ -44,6 +44,7 @@ return [
'totales' => 'Totales',
'cajas' => 'Cajas',
'ordenTrabajo' => 'OT',
'pedido' => 'Pedido',
'presupuesto' => 'Presupuesto',
'unidadesEnvio' => 'Unidades envío',
@ -59,9 +60,11 @@ return [
'selectAll' => 'Seleccionar todo',
'peso' => 'Peso (kg): ',
'unidadesTotalesFooter' => 'Unidades:',
'fechaEncuadernado' => 'Fecha encuadernado',
'codigoSeguimiento' => 'Código de seguimiento',
'empresaMensajería' => 'Empresa de mensajería',
'ficharEmbalaje' => 'Fichar embalaje',
'finalizarEnvio' => 'Finalizar envío',
'finalizarEnvioYOTs' => 'Finalizar envío y OTS',
@ -90,6 +93,7 @@ return [
'errorInsertarEtiqueta' => 'Error al insertar la etiqueta',
'noEtiqueta' => 'No se ha encontrado la etiqueta',
'noEtiquetaLineas' => 'No se han encontrado líneas de etiqueta',
'noLineas' => 'No se ha seleccionado ninguna línea',
],
'success' => [
'finalizado' => 'El envío se ha finalizado correctamente',
@ -101,6 +105,7 @@ return [
'comentariosUpdated' => 'Comentarios actualizados correctamente',
'successReordenarCajas' => 'Cajas reordenadas correctamente',
'imprimirEtiquetas' => 'Etiquetas impresas correctamente',
'successFicharEmbalaje' => 'Embalaje fichado correctamente',
],
];

View File

@ -182,6 +182,7 @@ return [
'duplicate_estado_tarea_progress' => "Último estado de la tarea repetido",
'task_already_finished' => "La tarea se ha marcado como finalizada.",
'print_label' => "Imprimir etiqueta",
'fichar_embalaje' => "Fichar embalaje",
'click_init' => "Clicks al inicio",
'click_end' => "Clicks al final",
"comentarios" => "Comentarios",

View File

@ -40,13 +40,14 @@ class SafekatFtpClient
public function uploadXML(string $content, string $filename): bool
{
try {
if ($this->xml_enabled == false) return false;
$remotePath = implode("/", [$this->base_dir,'pedidos','xml_nuevos']);
if ($this->xml_enabled == false)
return false;
$remotePath = implode("/", [$this->base_dir, 'pedidos', 'xml_nuevos']);
$this->ftp->login(username: $this->username, password: $this->password);
if(!$this->ftp->is_dir($remotePath)){
$this->ftp->mkdir($remotePath,recursive:true);
if (!$this->ftp->is_dir($remotePath)) {
$this->ftp->mkdir($remotePath, recursive: true);
}
$this->ftp->put($remotePath.'/'.$filename, $content);
$this->ftp->put($remotePath . '/' . $filename, $content);
return true;
} catch (\Throwable $th) {
@ -58,22 +59,23 @@ class SafekatFtpClient
public function uploadFilePresupuesto(int $presupuesto_id)
{
try {
if ($this->xml_enabled == false) return false;
if ($this->xml_enabled == false)
return false;
$model = model(PresupuestoFicheroModel::class);
$modelPedidoLinea = model(PedidoLineaModel::class);
$pedidoLinea = $modelPedidoLinea->findByPresupuesto($presupuesto_id);
$rootIdExtern = $this->pedido_xml_config->id_offset + $pedidoLinea->pedido_id;
$presupuestoFiles = $model->getFiles($presupuesto_id);
$this->ftp->login(username: $this->username, password: $this->password);
foreach ($presupuestoFiles as $key => $value) {
$filename = array_reverse(explode("/", $value->file_path))[0];
$remoteDir = implode("/", [$this->base_dir,"pedidos_files",$rootIdExtern]);
$remoteFile = implode("/", [$this->base_dir,"pedidos_files",$rootIdExtern,$filename]);
if(!$this->ftp->is_dir($remoteDir)){
$this->ftp->mkdir($remoteDir,recursive:true);
$remoteDir = implode("/", [$this->base_dir, "pedidos_files", $rootIdExtern]);
$remoteFile = implode("/", [$this->base_dir, "pedidos_files", $rootIdExtern, $filename]);
if (!$this->ftp->is_dir($remoteDir)) {
$this->ftp->mkdir($remoteDir, recursive: true);
}
$this->ftp->put($remoteFile,$value->file_path,mode:$this->ftp::SOURCE_LOCAL_FILE);
$this->ftp->put($remoteFile, $value->file_path, mode: $this->ftp::SOURCE_LOCAL_FILE);
}
$this->ftp->disconnect();
} catch (Exception $e) {
@ -91,10 +93,10 @@ class SafekatFtpClient
$rootIdExtern = $this->pedido_xml_config->id_offset + $pedidoLinea->pedido_id;
$presupuestoFiles = $model->getFiles($presupuesto_id);
$this->ftp->login(username: $this->username, password: $this->password);
foreach ($presupuestoFiles as $key => $value) {
$filename = array_reverse(explode("/", $value->file_path))[0];
$remoteFile = implode("/", [$this->base_dir,"pedidos_files",$rootIdExtern,$filename]);
$remoteFile = implode("/", [$this->base_dir, "pedidos_files", $rootIdExtern, $filename]);
$this->ftp->delete($remoteFile);
}
$this->ftp->disconnect();
@ -103,4 +105,13 @@ class SafekatFtpClient
throw $e;
}
}
public function getPresupuestoRemotePath(int $presupuesto_id): string
{
$modelPedidoLinea = model(PedidoLineaModel::class);
$pedidoLinea = $modelPedidoLinea->findByPresupuesto($presupuesto_id);
$rootIdExtern = $this->pedido_xml_config->id_offset + $pedidoLinea->pedido_id;
return implode('/', [$this->base_dir, 'pedidos_files', $rootIdExtern]);
}
}

View File

@ -35,7 +35,7 @@ class EnvioLineaModel extends Model
$builder = $this->db
->table($this->table . " t1")
->select(
"t1.id, t1.pedido_id as pedido, t3.id as presupuesto,
"t1.id, t1.pedido_id as pedido, t3.id as presupuesto, t4.id as ordenTrabajo,
t3.titulo as titulo, t1.unidades_envio as unidadesEnvio, t1.unidades_envio as unidadesEnvioRaw,
t1.unidades_total as unidadesTotal, t2.tipo_envio as tipo_envio,
IFNULL((
@ -59,6 +59,7 @@ class EnvioLineaModel extends Model
);
$builder->join("envios t2", "t1.envio_id = t2.id", "left");
$builder->join("presupuestos t3", "t1.presupuesto_id = t3.id", "left");
$builder->join("ordenes_trabajo t4", "t1.pedido_id = t4.pedido_id", "left");
$builder->where("t1.envio_id", $envio_id);

View File

@ -143,4 +143,25 @@ class OrdenTrabajoModel extends Model
->groupBy('orden_trabajo_tareas.id');
return $query;
}
public function queryProximosEnvios()
{
$query = $this->builder()
->select([
'ordenes_trabajo.id as ot',
'orden_trabajo_dates.encuadernacion_at as fechaEncuadernado',
])
->join('pedidos', 'pedidos.id = ordenes_trabajo.pedido_id', 'left')
->join('pedidos_linea', 'pedidos.id = pedidos_linea.pedido_id', 'left')
->join('presupuestos', 'presupuestos.id = pedidos_linea.presupuesto_id', 'left')
->join('presupuesto_direcciones', 'presupuestos.id = presupuesto_direcciones.presupuesto_id', 'left')
->join('orden_trabajo_dates', 'orden_trabajo_dates.orden_trabajo_id = ordenes_trabajo.id', 'left')
->where('ordenes_trabajo.deleted_at', null)
->where('orden_trabajo_dates.encuadernacion_at !=', null)
//->where('orden_trabajo_dates.fecha_encuadernado_at >=', 0)
//->where('ordenes_trabajo.fecha_entrega_warning >=', date("Y-m-d H:i:s"))
->groupBy('ordenes_trabajo.id');
return $query;
}
}

View File

@ -25,7 +25,7 @@ class ImportadorModel extends \App\Models\BaseModel
$builder = $db->table('pedido_libro');
$builder->select('id as id, CONCAT(id, " - ", titulo) as name');
$builder->where('customer_id', $clienteId);
$builder->whereIn('estado', ['finalizado', 'validado']);
$builder->whereIn('estado', ['finalizado', 'validado', 'presupuesto']);
$builder->where('deleted_at', NULL);
$builder->orderBy('updated_at', 'DESC');

View File

@ -13,7 +13,7 @@ class EmailService
// Si no estamos en producción, forzar el destinatario a uno fijo
if ($skEnv !== 'production') {
$recipient = env('MAIL_DEV_RECIPIENT', 'imnavajas@coit.es'); // fallback opcional
$recipient = env('MAIL_DEV_RECIPIENT', 'imnavajas@coit.es,info@jjimenez.eu'); // fallback opcional
}
$settings_model = model('App\Models\Configuracion\ConfigVariableModel');
@ -43,7 +43,13 @@ class EmailService
$email->setSubject($subject);
$email->setMessage($body);
return $email->send();
if (!$email->send()) {
log_message('error', 'Error enviando email: ' . $email->printDebugger(['headers', 'subject', 'body']));
return false;
}
return true;
} catch (\Throwable $e) {
log_message('error', 'EmailService failed: ' . $e->getMessage());
return false;

View File

@ -57,7 +57,8 @@ class LogisticaService
->join('orden_trabajo_dates ot_dates', 'ot_dates.orden_trabajo_id = ot.id')
->whereIn('pr.id', $presupuestoIds)
->whereIn('p.estado', ['finalizado', 'produccion'])
->where('ot_dates.embalaje_at IS NOT NULL')
->where('p.fecha_encuadernado IS NOT NULL')
->where('DATE(p.fecha_encuadernado) <=', date('Y-m-d'))
->where("NOT EXISTS (
SELECT 1
FROM envios_lineas el
@ -78,6 +79,79 @@ class LogisticaService
return $builder;
}
public static function findNextEnvios(int $envio_id)
{
$db = \Config\Database::connect();
// 1. Dirección del envío actual
$envio = $db->table('envios')->select('direccion')->where('id', $envio_id)->get()->getRow();
if (!$envio) {
return $db->table('(SELECT NULL AS id, NULL AS name) AS empty')->where('1 = 0');
}
$direccionNormalizada = str_replace(' ', '', strtolower(trim($envio->direccion)));
$direccionSQL = $db->escape($direccionNormalizada);
// 2. Obtener presupuestos con esa dirección
$presupuestosConEsaDireccion = $db->table('presupuesto_direcciones')
->select('presupuesto_id')
->where("REPLACE(LOWER(TRIM(direccion)), ' ', '') = $direccionSQL", null, false)
->get()
->getResultArray();
$presupuestoIds = array_column($presupuestosConEsaDireccion, 'presupuesto_id');
if (empty($presupuestoIds)) {
return $db->table('(SELECT NULL AS id, NULL AS name) AS empty')->where('1 = 0');
}
$hoy = date('Y-m-d');
$sieteDiasDespues = date('Y-m-d', strtotime('+7 days'));
// 3. Subconsulta principal
$subBuilder = $db->table('pedidos_linea pl')
->select("
ot.id AS ot,
DATE(p.fecha_encuadernado) as fechaEncuadernado,
(
SELECT IFNULL(SUM(el.unidades_envio), 0)
FROM envios_lineas el
JOIN envios e ON e.id = el.envio_id
WHERE el.pedido_id = p.id
AND el.presupuesto_id = pr.id
AND REPLACE(LOWER(TRIM(e.direccion)), ' ', '') = $direccionSQL
AND (e.finalizado = 1 OR e.id = $envio_id)
) AS unidades_enviadas,
pd.cantidad AS cantidad
")
->join('pedidos p', 'p.id = pl.pedido_id')
->join('presupuestos pr', 'pr.id = pl.presupuesto_id')
->join('presupuesto_direcciones pd', 'pd.presupuesto_id = pr.id')
->join('ordenes_trabajo ot', 'ot.pedido_id = p.id')
->join('orden_trabajo_dates ot_dates', 'ot_dates.orden_trabajo_id = ot.id')
->whereIn('pr.id', $presupuestoIds)
->whereIn('p.estado', ['finalizado', 'produccion'])
->where('p.fecha_encuadernado IS NOT NULL')
->where('DATE(p.fecha_encuadernado) >=', $hoy)
->where('DATE(p.fecha_encuadernado) <=', $sieteDiasDespues)
->where("NOT EXISTS (
SELECT 1
FROM envios_lineas el
WHERE el.envio_id = $envio_id
AND el.pedido_id = p.id
AND el.presupuesto_id = pr.id
GROUP BY el.pedido_id, el.presupuesto_id
HAVING SUM(el.unidades_envio) >= pd.cantidad
)", null, false)
->groupBy('pl.id');
// 4. Envolver y filtrar por unidades pendientes
$builder = $db->table("({$subBuilder->getCompiledSelect(false)}) AS sub");
$builder->select('ot, fechaEncuadernado');
$builder->where('cantidad > unidades_enviadas');
return $builder;
}
public static function findForNewEnvio()
{
@ -103,16 +177,15 @@ class LogisticaService
->join('presupuestos pr', 'pr.id = pl.presupuesto_id')
->join('presupuesto_direcciones pd', 'pd.presupuesto_id = pr.id')
->join('ordenes_trabajo ot', 'ot.pedido_id = p.id')
->join('orden_trabajo_dates ot_dates', 'ot_dates.orden_trabajo_id = ot.id')
->whereIn('p.estado', ['finalizado', 'produccion'])
->where('ot_dates.embalaje_at IS NOT NULL')
->where('p.fecha_encuadernado IS NOT NULL')
->where('DATE(p.fecha_encuadernado) <=', date('Y-m-d'))
->groupBy('pl.id');
// 4. Envolver y filtrar por unidades pendientes
$builder = $db->table("({$subBuilder->getCompiledSelect(false)}) AS sub");
$builder->select('id, name');
$builder->where('cantidad > unidades_enviadas');
$builder->orderBy('name', 'ASC');
return $builder;
}
@ -289,6 +362,81 @@ class LogisticaService
}
public static function sendConfirmacionEnvio($envio, $lineaEnvio, $isFerro = false)
{
$view = \Config\Services::renderer();
if ($isFerro)
$subject = '[Safekat]' . " El envio del ferro de su pedido se ha realizado";
else
$subject = '[Safekat]' . " El envio de su pedido se ha realizado";
$presupuestoModel = model('App\Models\Presupuestos\PresupuestoModel');
$presupuesto = $presupuestoModel->find($lineaEnvio->presupuesto_id);
$proveedorModel = model('App\Models\Compras\ProveedorModel');
$proveedor = $proveedorModel->find($envio->proveedor_id);
$userModel = model('App\Models\Usuarios\UserModel');
$datos_correo = $userModel->select("CONCAT(users.first_name, ' ', users.last_name) as comercial_nombre, auth_identities.secret as comercial_correo, clientes.email as cliente_email")
->join('auth_identities', 'auth_identities.user_id = users.id')
->join('clientes', 'clientes.comercial_id = users.id')
->where('clientes.id', $presupuesto->cliente_id)
->first();
$pedido = (object) [
'pedido_id' => $lineaEnvio->pedido_id,
'titulo' => $presupuesto->titulo,
'cp' => $envio->cp,
'proveedor_nombre' => $proveedor->nombre,
'codigo_seguimiento' => $envio->codigo_seguimiento,
'comercial_nombre' => $datos_correo->comercial_nombre,
'comercial_correo' => $datos_correo->comercial_correo,
];
if ($proveedor->nombre == "GLS") {
$pedido->url = 'https://m.asmred.com/e/' . $envio->codigo_seguimiento . '/' . $envio->cp;
}
$content = $view->setVar('datos_pedido', $pedido)
->render('themes/vuexy/mail/envio_pedido');
// Renderiza la plantilla completa
if ($isFerro)
$finalBody = $view->setVar('emailTitle2', "El ferro de su pedido " . $lineaEnvio->pedido_id . " ha sido enviado el " . date('d/m/Y'))
->setVar('content', $content)
->render('themes/vuexy/mail/mail_layout_2');
else
$finalBody = $view->setVar('emailTitle2', "Su pedido " . $lineaEnvio->pedido_id . " ha sido enviado el " . date('d/m/Y'))
->setVar('content', $content)
->render('themes/vuexy/mail/mail_layout_2');
$email = service('emailService');
$result = $email->send($subject, $finalBody, $datos_correo->cliente_email);
$chat = Service('chat');
$data = [
'chat_department_id' => 5,
'client' => $presupuesto->cliente_id,
'message' => "El pedido " . $lineaEnvio->pedido_id . " ha sido enviado el " . date('d/m/Y') . ".<br><br>" .
"CP:" . $envio->cp . ".<br>" .
"Proveedor envío: " . $proveedor->nombre . ".<br>" .
"Código de seguimiento: " . $envio->codigo_seguimiento . ".<br>"
];
if ($proveedor->nombre == "GLS") {
$data['message'] = $data['message'] . 'URL segumiento: <a style="color:white;" target="_blank" href="' . 'https://m.asmred.com/e/' . $envio->codigo_seguimiento . '/' . $envio->cp . ' ">' .
'https://m.asmred.com/e/' . $envio->codigo_seguimiento . '/' . $envio->cp . '</a>';
}
$chat->storeChatMessage(5, "pedido", $lineaEnvio->pedido_id, $data);
return [
'status' => $result,
'message' => $result ? lang('Logistica.success.emailSent') : lang('Logistica.errors.emailNotSent'),
];
}
public static function generateEnvio($ot_id, $direccion = null)
{
@ -533,16 +681,29 @@ class LogisticaService
"name" => "ferro_en_cliente_at",
"ferro_en_cliente_at" => date('Y-m-d H:i:s')
]);
LogisticaService::sendConfirmacionEnvio($envio, $linea, true);
} else {
if ($cantidad_enviada + $linea->unidades_envio == $pedido->total_tirada) {
if ($cantidad_enviada + $linea->unidades_envio >= $pedido->total_tirada) {
$otModel = model('App\Models\OrdenTrabajo\OrdenTrabajoModel');
$ot = $otModel->where('pedido_id', $linea->pedido_id)
->first();
$ps = (new ProductionService())->init($ot->id);
$date = $ps->getOrdenTrabajo()->dates()->embalaje_at;
if (is_null($date) || empty($date)) {
$ps->updateOrdenTrabajoDate([
"name" => "embalaje_at",
"embalaje_at" => date('Y-m-d H:i:s')
]);
}
$ps->updateOrdenTrabajoDate([
"name" => "envio_at",
"envio_at" => date('Y-m-d H:i:s')
]);
LogisticaService::sendConfirmacionEnvio($envio, $linea);
if ($finalizar_ot) {
$ps->updateOrdenTrabajo(
[
@ -572,6 +733,29 @@ class LogisticaService
return $data_return;
}
public static function ficharEmbalaje($ids = null)
{
if (is_null($ids) || empty($ids) || count($ids) == 0) {
return [
'status' => false,
'message' => lang('Logistica.errors.noLineas'),
];
}
for ($index = 0; $index < count($ids); $index++) {
$ps = (new ProductionService())->init($ids[$index]);
$ps->updateOrdenTrabajoDate([
"name" => "embalaje_at",
"embalaje_at" => date('Y-m-d')
]);
}
return [
'status' => true,
'message' => lang('Logistica.success.successFicharEmbalaje'),
];
}
public static function generateEtiquetasTitulos($envio, $lineas, $printer, $cajas)
{
$data = [

View File

@ -10,7 +10,7 @@
<div class="card">
<div class="card-header">
<h4><?= $boxTitle ?>
<?= ($envioEntity->tipo_envio == 'ferro_prototipo') ? '<span class="badge text-bg-warning fw-lg">FERRO</span>':'' ?>
<?= ($envioEntity->tipo_envio == 'ferro_prototipo') ? '<span class="badge text-bg-warning fw-lg">FERRO</span>' : '' ?>
<?= ($envioEntity->finalizado == 0) ? '' : '<span class="badge text-bg-success fw-lg">FINALIZADO</span>' ?>
</h4>
</div>
@ -114,7 +114,7 @@
</div>
</div>
<?php if ($envioEntity->finalizado == 0 && $envioEntity->tipo_envio=='estandar'): ?>
<?php if ($envioEntity->finalizado == 0 && $envioEntity->tipo_envio == 'estandar'): ?>
<div class="accordion accordion-bordered">
<div class="card accordion-item active mb-5">
<h4 class="accordion-header px-4 py-3">
@ -130,6 +130,7 @@
</div>
<div class="d-flex flex-row mb-3">
<div class="col-sm-6 px-3">
<label for="buscadorPedidos" class="form-label">
<?= lang("Logistica.buscadorPedidosTitle2") ?>
@ -145,229 +146,280 @@
<ti class="ti ti-circle-plus"></ti>
</button>
</div>
</div>
</div>
</div>
</div>
<?php endif; ?>
<div class="col-sm-4 px-3">
<div class="accordion accordion-bordered">
<div class="card accordion-item active mb-5">
<h4 class="accordion-header px-4 py-3">
<?= lang("Logistica.lineasEnvio") ?>
</h4>
<div class="accordion accordion-bordered mt-3 mb-5" id="accordioAlbaranes">
<div id="accordionDatosEnvioTip" class="accordion-collapse collapse show">
<div class="accordion-body px-4 py-3">
<div class="d-flex flex-row">
<p><?= lang('Logistica.buttonsActions') ?></p>
</div>
<div class="d-flex flex-row mb-3 align-items-end">
<div class="col-sm-2 px-3">
<button id="btnSelectAll" name="btnSelectAll" tabindex="1"
class="btn btn-primary w-100">
<?= lang("Logistica.selectAll") ?>
<i class="ti ti-select"></i>
</button>
</div>
<?php if ($envioEntity->finalizado == 0 && $envioEntity->tipo_envio=='estandar'): ?>
<div class="col-sm-2 px-3">
<button id="btnEliminarLineas" name="btnEliminarLineas" tabindex="1"
class="btn btn-danger w-100">
<?= lang("Logistica.eliminar") ?>
<i class="ti ti-trash"></i>
</button>
</div>
<?php endif; ?>
<div class="col-sm-2 px-3">
<button id="btnGenerarAlbaran" name="btnGenerarAlbaran" tabindex="1"
class="btn btn-success w-100">
<?= lang("Logistica.generarAlbaran") ?>
<i class="ti ti-file-check"></i>
</button>
</div>
<div class="col-sm-2 px-3">
<button id="btnImprimirEtiquetas" name="btnImprimirEtiquetas" tabindex="1"
class="btn btn-info w-100">
<?= lang("Logistica.imprimirEtiquetas") ?>
<i class="ti ti-printer"></i>
</button>
</div>
<div class="card accordion-item">
<h2 class="accordion-header" id="headingAlbaranes">
<button type="button" class="accordion-button" data-bs-toggle="collapse"
data-bs-target="#proximosEnviosTip" aria-expanded="false"
aria-controls="proximosEnviosTip">
<h4>Proximos envíos (1 semana)</h4>
</button>
</h2>
<div id="proximosEnviosTip" class="accordion-collapse collapse"
data-bs-parent="#accordioAlbaranes">
<div id="" class="accordion-body">
<div class="col-sm-2 px-3 d-flex flex-column justify-content-end">
<div class="d-flex flex-column justify-content-end h-100">
<label for="impresoraEtiquetas" class="form-label">
<?= lang("Logistica.impresoraEtiquetas") ?>
</label>
<select id="impresoraEtiquetas" name="impresora_etiquetas" tabindex="1"
maxlength="50" class="form-control select2bs2" style="width: 100%;">
<?php foreach ($envioEntity->impresoras as $impresora): ?>
<option value="<?= $impresora->id ?>">
<?= $impresora->name ?>
</option>
<?php endforeach; ?>
</select>
</div>
</div>
<table id="tableProximosEnvios"
class="table table-striped table-hover w-100">
<thead>
<tr>
<th><?= lang("Logistica.ordenTrabajo") ?></th>
<th><?= lang("Logistica.fechaEncuadernado") ?></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<div class="row mb-3">
<table id="tableLineasEnvio" class="table table-striped table-hover w-100">
<thead>
<tr>
<th></th>
<th><?= lang("Logistica.pedido") ?></th>
<th><?= lang("Logistica.presupuesto") ?></th>
<th><?= lang("Logistica.titulo") ?></th>
<th class="text-center" style="width: 10%;">
<?= lang("Logistica.unidadesEnvio") ?>
</th>
<th class="text-center" style="width: 10%;">
<?= lang("Logistica.unidadesEnviadas") ?>
</th>
<th class="text-center" style="width: 10%;">
<?= lang("Logistica.unidadesTotales") ?>
</th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<th colspan="10">
<div class="text-end">
<?= lang("Logistica.unidadesTotalesFooter") ?>
<span id="footer-unidades-envio"></span>
</div>
</th>
</tr>
<tr>
<th colspan="10">
<div class="text-end">
<?= lang("Logistica.peso") ?>
<span id="footer-peso"></span>
</div>
</th>
</tr>
</tfoot>
</table>
</div>
<div class="col-sm-2 px-3">
<label for="cajas" class="form-label">
<?= lang("Logistica.cajas") ?>
</label>
<input type="number" id="cajas" name="cajas" tabindex="1" maxlength="50"
class="form-control" value="<?= old('cajas', $envioEntity->cajas) ?>">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="accordion accordion-bordered mt-3 mb-5" id="accordioAlbaranes">
<div class="card accordion-item active">
<h2 class="accordion-header" id="headingAlbaranes">
<button type="button" class="accordion-button" data-bs-toggle="collapse"
data-bs-target="#accordionAlbaranesTip" aria-expanded="false"
aria-controls="accordionAlbaranesTip">
<h3><?= lang("Pedidos.albaranes") ?></h3>
</button>
</h2>
<div id="accordionAlbaranesTip" class="accordion-collapse collapse show"
data-bs-parent="#accordioAlbaranes">
<div id="contenedorAlbaranes" class="accordion-body">
<?php endif; ?>
</div>
<div class="accordion accordion-bordered">
<div class="card accordion-item active mb-5">
<h4 class="accordion-header px-4 py-3">
<?= lang("Logistica.lineasEnvio") ?>
</h4>
</div>
</div>
</div>
<div class="accordion accordion-bordered">
<div class="card accordion-item active mb-5">
<h4 class="accordion-header px-4 py-3">
<?= lang("Logistica.acciones") ?>
</h4>
<div class="d-flex flex-row mb-3">
<div class="col-sm-3 px-3">
<label for="codigoSeguimiento" class="form-label">
<?= lang("Logistica.codigoSeguimiento") ?>
</label>
<input type="text" id="codigoSeguimiento" name="codigo_seguimiento" tabindex="1"
maxlength="100" class="form-control" <?= ($envioEntity->finalizado == 0) ? '' : 'readonly' ?>
value="<?= esc(old('codigo_seguimiento', $envioEntity->codigo_seguimiento)) ?>">
</div>
<div class="col-sm-3 px-3">
<label for="empresaMensajeria" class="form-label">
<?= lang("Logistica.empresaMensajería") ?>
</label>
<?php if ($envioEntity->finalizado == 0): ?>
<select id="empresaMensajeria" name="empresa_mensajeria" tabindex="1" maxlength="50"
class="form-control select2bs2" style="width: 100%;">
<?php if ($envioEntity->proveedor_id): ?>
<option value="<?= $envioEntity->proveedor_id ?>" "selected">
<?= $envioEntity->proveedor_nombre ?>
</option>
<div id="accordionDatosEnvioTip" class="accordion-collapse collapse show">
<div class="accordion-body px-4 py-3">
<div class="d-flex flex-row">
<p><?= lang('Logistica.buttonsActions') ?></p>
</div>
<div class="d-flex flex-row mb-3 align-items-end">
<div class="col-sm-2 px-3">
<button id="btnSelectAll" name="btnSelectAll" tabindex="1"
class="btn btn-primary w-100">
<?= lang("Logistica.selectAll") ?>
<i class="ti ti-select"></i>
</button>
</div>
<?php if ($envioEntity->finalizado == 0 && $envioEntity->tipo_envio == 'estandar'): ?>
<div class="col-sm-2 px-3">
<button id="btnEliminarLineas" name="btnEliminarLineas" tabindex="1"
class="btn btn-danger w-100">
<?= lang("Logistica.eliminar") ?>
<i class="ti ti-trash"></i>
</button>
</div>
<?php endif; ?>
</select>
<?php else: ?>
<input type="text" id="empresaMensajeriaInput" name="empresa_mensajeria_input"
tabindex="1" maxlength="100" class="form-control" readonly
value="<?= old('empresa_mensajeria', $envioEntity->proveedor_nombre) ?>">
<?php endif; ?>
<div class="col-sm-2 px-3">
<button id="btnGenerarAlbaran" name="btnGenerarAlbaran" tabindex="1"
class="btn btn-success w-100">
<?= lang("Logistica.generarAlbaran") ?>
<i class="ti ti-file-check"></i>
</button>
</div>
<div class="col-sm-2 px-3">
<button id="ficharEmbalaje" name="fichar_embalaje" tabindex="1"
class="btn btn-primary mt-4 w-100 btn-finalizar">
<?= lang("Logistica.ficharEmbalaje") ?>
<ti class="ti ti-check"></ti>
</button>
</div>
<div class="col-sm-2 px-3">
<button id="btnImprimirEtiquetas" name="btnImprimirEtiquetas"
tabindex="1" class="btn btn-info w-100">
<?= lang("Logistica.imprimirEtiquetas") ?>
<i class="ti ti-printer"></i>
</button>
</div>
<div class="col-sm-3 px-3 d-flex flex-column justify-content-end">
<div class="d-flex flex-column justify-content-end h-100">
<label for="impresoraEtiquetas" class="form-label">
<?= lang("Logistica.impresoraEtiquetas") ?>
</label>
<select id="impresoraEtiquetas" name="impresora_etiquetas"
tabindex="1" maxlength="50" class="form-control select2bs2"
style="width: 100%;">
<?php foreach ($envioEntity->impresoras as $impresora): ?>
<option value="<?= $impresora->id ?>">
<?= $impresora->description ? "$impresora->name [$impresora->description]" : $impresora->name ?>
</option>
<?php endforeach; ?>
</select>
</div>
</div>
</div>
<div class="row mb-3">
<table id="tableLineasEnvio" class="table table-striped table-hover w-100">
<thead>
<tr>
<th></th>
<th><?= lang("Logistica.ordenTrabajo") ?></th>
<th><?= lang("Logistica.pedido") ?></th>
<th><?= lang("Logistica.presupuesto") ?></th>
<th><?= lang("Logistica.titulo") ?></th>
<th class="text-center" style="width: 10%;">
<?= lang("Logistica.unidadesEnvio") ?>
</th>
<th class="text-center" style="width: 10%;">
<?= lang("Logistica.unidadesEnviadas") ?>
</th>
<th class="text-center" style="width: 10%;">
<?= lang("Logistica.unidadesTotales") ?>
</th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<th colspan="11">
<div class="text-end">
<?= lang("Logistica.unidadesTotalesFooter") ?>
<span id="footer-unidades-envio"></span>
</div>
</th>
</tr>
<tr>
<th colspan="11">
<div class="text-end">
<?= lang("Logistica.peso") ?>
<span id="footer-peso"></span>
</div>
</th>
</tr>
</tfoot>
</table>
<div class="col-sm-2 px-3">
<label for="cajas" class="form-label">
<?= lang("Logistica.cajas") ?>
</label>
<input type="number" id="cajas" name="cajas" tabindex="1" maxlength="50"
class="form-control"
value="<?= old('cajas', $envioEntity->cajas) ?>">
</div>
</div>
</div>
</div>
<?php if ($envioEntity->finalizado == 0): ?>
<div class="col-sm-3 px-3">
<button id="finalizarEnvio" name="finalizar_envio" tabindex="1"
class="btn btn-primary mt-4 w-100 btn-finalizar">
<?= lang("Logistica.finalizarEnvio") ?>
<ti class="ti ti-check"></ti>
</button>
</div>
<?php if ($envioEntity->tipo_envio=='estandar'): ?>
<div class="col-sm-3 px-3">
<button id="finalizarEnvioYOTs" name="finalizar_envio_ots" tabindex="1"
class="btn btn-primary mt-4 w-100 btn-finalizar">
<?= lang("Logistica.finalizarEnvioYOTs") ?>
<ti class="ti ti-checks"></ti>
</button>
</div>
<?php endif; ?>
<?php endif; ?>
</div>
<div class="accordion accordion-bordered mt-3 mb-5" id="accordioAlbaranes">
<div class="card accordion-item active">
<h2 class="accordion-header" id="headingAlbaranes">
<button type="button" class="accordion-button" data-bs-toggle="collapse"
data-bs-target="#accordionAlbaranesTip" aria-expanded="false"
aria-controls="accordionAlbaranesTip">
<h3><?= lang("Pedidos.albaranes") ?></h3>
</button>
</h2>
<div id="accordionAlbaranesTip" class="accordion-collapse collapse show"
data-bs-parent="#accordioAlbaranes">
<div id="contenedorAlbaranes" class="accordion-body">
</div>
</div>
</div>
</div>
<div class="accordion accordion-bordered">
<div class="card accordion-item active mb-5">
<h4 class="accordion-header px-4 py-3">
<?= lang("Logistica.acciones") ?>
</h4>
<div class="d-flex flex-row mb-3">
<div class="col-sm-3 px-3">
<label for="codigoSeguimiento" class="form-label">
<?= lang("Logistica.codigoSeguimiento") ?>
</label>
<input type="text" id="codigoSeguimiento" name="codigo_seguimiento"
tabindex="1" maxlength="100" class="form-control"
<?= ($envioEntity->finalizado == 0) ? '' : 'readonly' ?>
value="<?= esc(old('codigo_seguimiento', $envioEntity->codigo_seguimiento)) ?>">
</div>
<div class="col-sm-3 px-3">
<label for="empresaMensajeria" class="form-label">
<?= lang("Logistica.empresaMensajería") ?>
</label>
<?php if ($envioEntity->finalizado == 0): ?>
<select id="empresaMensajeria" name="empresa_mensajeria" tabindex="1"
maxlength="50" class="form-control select2bs2" style="width: 100%;">
<?php if ($envioEntity->proveedor_id): ?>
<option value="<?= $envioEntity->proveedor_id ?>" "selected">
<?= $envioEntity->proveedor_nombre ?>
</option>
<?php endif; ?>
</select>
<?php else: ?>
<input type="text" id="empresaMensajeriaInput"
name="empresa_mensajeria_input" tabindex="1" maxlength="100"
class="form-control" readonly
value="<?= old('empresa_mensajeria', $envioEntity->proveedor_nombre) ?>">
<?php endif; ?>
</div>
<?php if ($envioEntity->finalizado == 0): ?>
<div class="col-sm-3 px-3">
<button id="finalizarEnvio" name="finalizar_envio" tabindex="1"
class="btn btn-primary mt-4 w-100 btn-finalizar">
<?= lang("Logistica.finalizarEnvio") ?>
<ti class="ti ti-check"></ti>
</button>
</div>
<?php if ($envioEntity->tipo_envio == 'estandar'): ?>
<div class="col-sm-3 px-3">
<button id="finalizarEnvioYOTs" name="finalizar_envio_ots" tabindex="1"
class="btn btn-primary mt-4 w-100 btn-finalizar">
<?= lang("Logistica.finalizarEnvioYOTs") ?>
<ti class="ti ti-checks"></ti>
</button>
</div>
<?php endif; ?>
<?php endif; ?>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<?= $this->endSection() ?>
<?= $this->endSection() ?>
<?= $this->section('css') ?>
<link rel="stylesheet" href="<?= site_url('themes/vuexy/vendor/libs/sweetalert2/sweetalert2.css') ?>" />
<link rel="stylesheet" href="https://cdn.datatables.net/rowreorder/1.4.1/css/rowReorder.dataTables.min.css">
<link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
<link rel="stylesheet" href="<?= site_url("/themes/vuexy/vendor/libs/flatpickr/flatpickr.css") ?>">
<?= $this->section('css') ?>
<link rel="stylesheet" href="<?= site_url('themes/vuexy/vendor/libs/sweetalert2/sweetalert2.css') ?>" />
<link rel="stylesheet" href="https://cdn.datatables.net/rowreorder/1.4.1/css/rowReorder.dataTables.min.css">
<link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
<link rel="stylesheet" href="<?= site_url("/themes/vuexy/vendor/libs/flatpickr/flatpickr.css") ?>">
<link rel="stylesheet"
href="<?= site_url("/themes/vuexy/vendor/libs/perfect-scrollbar/perfect-scrollbar.css") ?>" />
<?= $this->endSection() ?>
<?= $this->endSection() ?>
<?= $this->section('additionalExternalJs') ?>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>
<script src="<?= site_url('themes/vuexy/vendor/libs/sweetalert2/sweetalert2.js') ?>"></script>
<script src="https://cdn.datatables.net/rowgroup/1.3.1/js/dataTables.rowGroup.min.js"></script>
<script type="module" src="<?= site_url("assets/js/safekat/pages/logistica/envioEdit.js") ?>"></script>
<?= $this->endSection() ?>
<?= $this->section('additionalExternalJs') ?>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>
<script src="<?= site_url('themes/vuexy/vendor/libs/sweetalert2/sweetalert2.js') ?>"></script>
<script src="<?= site_url('themes/vuexy/vendor/libs/perfect-scrollbar/perfect-scrollbar.js') ?>"><script>
<script src="https://cdn.datatables.net/rowgroup/1.3.1/js/dataTables.rowGroup.min.js"></script>
<script type="module" src="<?= site_url("assets/js/safekat/pages/logistica/envioEdit.js") ?>"></script>
<?= $this->endSection() ?>

View File

@ -158,7 +158,7 @@
</button>
</div>
<div class="col-sm-2 px-3 d-flex flex-column justify-content-end">
<div class="col-sm-3 px-3 d-flex flex-column justify-content-end">
<div class="d-flex flex-column justify-content-end h-100">
<label for="impresoraEtiquetas" class="form-label">
<?= lang("Logistica.impresoraEtiquetas") ?>
@ -167,7 +167,7 @@
maxlength="50" class="form-control select2bs2" style="width: 100%;">
<?php foreach ($etiquetaEntity->impresoras as $impresora): ?>
<option value="<?= $impresora->id ?>">
<?= $impresora->name ?>
<?= $impresora->description ? "$impresora->name [$impresora->description]" : $impresora->name ?>
</option>
<?php endforeach; ?>
</select>

View File

@ -48,6 +48,9 @@
<div class="col-md-12 d-flex justify-content-end mb-2">
<button id="btn-print-labels" class="btn-primary btn d-flex justify-content-evenly gap-2" data-id="<?=$ot_tarea?->maquina_actual()->id?>"><span class="ti ti-barcode ti-lg"></span><?= lang('Produccion.print_label') ?></button>
</div>
<div class="col-md-12 d-flex justify-content-end mb-2">
<button id="btn-fichar-embalaje" class="btn-primary btn d-flex justify-content-evenly gap-2" data-id="<?=$ot_tarea?->maquina_actual()->id?>"><span class="ti ti-calendar ti-lg"></span><?= lang('Produccion.fichar_embalaje') ?></button>
</div>
<?php endif; ?>
<div class="col-md-6 tarea-card-info-block">
<?= view("/themes/vuexy/components/cards/tarea_card.php") ?>

View File

@ -0,0 +1,41 @@
<table width="600" bgcolor="#ffffff">
<tr>
<td
style="font-family: Helvetica, arial, sans-serif; font-size: 15px; color: #333333; text-align:center; line-height: 15px;">
Número pedido: <?= esc($datos_pedido->pedido_id) ?></td>
</tr>
<tr>
<td
style="font-family: Helvetica, arial, sans-serif; font-size: 15px; color: #333333; text-align:center; line-height: 15px;">
Título: <?= esc($datos_pedido->titulo) ?></td>
</tr>
<tr>
<td
style="font-family: Helvetica, arial, sans-serif; font-size: 15px; color: #333333; text-align:center; line-height: 15px;">
CP: <?= esc($datos_pedido->cp) ?></td>
</tr>
<tr>
<td
style="font-family: Helvetica, arial, sans-serif; font-size: 15px; color: #333333; text-align:center; line-height: 15px;">
Proveedor envío: <?= esc($datos_pedido->proveedor_nombre) ?></td>
</tr>
<tr>
<td
style="font-family: Helvetica, arial, sans-serif; font-size: 15px; color: #333333; text-align:center; line-height: 15px;">
Código seguimiento: <?= esc($datos_pedido->codigo_seguimiento) ?></td>
</tr>
<?php if (!empty($datos_pedido->url)): ?>
<tr>
<td
style="font-family: Helvetica, arial, sans-serif; font-size: 15px; color: #333333; text-align:center; line-height: 15px;">
URL seguimiento: <a href="<?= esc($datos_pedido->url) ?>"><?= esc($datos_pedido->url) ?></a>
</td>
</tr>
<?php endif; ?>
<tr>
<td height="20" align="center">
<p style="margin-top: 20px;font-family: Helvetica, arial, sans-serif; font-size: 15px; color: #333333;">Consulte con su comercial <?= esc($datos_pedido->comercial_nombre) ?> en el correo
<?= esc($datos_pedido->comercial_correo) ?></p>
</td>
</tr>
</table>

View File

@ -0,0 +1,156 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title><?= esc($emailTitle ?? 'Correo de Safekat') ?></title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style type="text/css">
/* Copia aquí todo el CSS de tu layout Blade */
body {
margin: 0;
padding: 0;
width: 100% !important;
-webkit-text-size-adjust: 100%;
-ms-text-size-adjust: 100%;
}
table {
border-collapse: collapse;
}
img {
border: none;
outline: none;
text-decoration: none;
display: block;
}
h2 {
font-family: Helvetica, Arial, sans-serif;
font-size: 30px;
color: #333;
text-align: center;
}
p {
font-family: Helvetica, Arial, sans-serif;
font-size: 16px;
color: #666;
text-align: center;
line-height: 30px;
}
@media only screen and (max-width: 640px) {
a[href^="tel"],
a[href^="sms"] {
text-decoration: none;
color: #0a8cce;
/* or whatever your want */
pointer-events: none;
cursor: default;
}
.mobile_link a[href^="tel"],
.mobile_link a[href^="sms"] {
text-decoration: default;
color: #0a8cce !important;
pointer-events: auto;
cursor: default;
}
table[class=devicewidth] {
width: 440px !important;
text-align: center !important;
}
table[class=devicewidthinner] {
width: 420px !important;
text-align: center !important;
}
img[class=banner] {
width: 440px !important;
height: 220px !important;
}
img[class=colimg2] {
width: 440px !important;
height: 220px !important;
}
}
/*IPHONE STYLES*/
@media only screen and (max-width: 480px) {
a[href^="tel"],
a[href^="sms"] {
text-decoration: none;
color: #0a8cce;
/* or whatever your want */
pointer-events: none;
cursor: default;
}
.mobile_link a[href^="tel"],
.mobile_link a[href^="sms"] {
text-decoration: default;
color: #0a8cce !important;
pointer-events: auto;
cursor: default;
}
table[class=devicewidth] {
width: 280px !important;
text-align: center !important;
}
table[class=devicewidthinner] {
width: 260px !important;
text-align: center !important;
}
img[class=banner] {
width: 280px !important;
height: 140px !important;
}
img[class=colimg2] {
width: 280px !important;
height: 140px !important;
}
}
</style>
</head>
<body>
<table width="100%" bgcolor="#ffffff">
<tr>
<td align="center">
<!-- Logo -->
<img src="<?= site_url('themes/vuexy/img/safekat/logos/sk-logo.png') ?>" alt="Safekat" width="108"
height="45">
</td>
</tr>
<tr>
<td height="20"></td>
</tr>
<tr>
<td align="center">
<h3><?= esc($emailTitle2 ?? '') ?></h3>
</td>
</tr>
<tr>
<td align="center">
<?= esc($content) ?>
</tr>
</table>
</body>
</html>

View File

@ -14,6 +14,7 @@ class MaquinistaTareaView {
this.tareaCardClass = '.tarea-card-action-block'
this.inputClick = $('.ot-tarea-click')
this.btnPrintLabels = this.item.find('#btn-print-labels')
this.btnFicharEmbalaje = this.item.find('#btn-fichar-embalaje')
}
init() {
this.actionButtons.on('click', this.eventActionButton.bind(this))
@ -22,6 +23,7 @@ class MaquinistaTareaView {
this.handleGetTareaProgress();
this.inputClick.on('input', this.handleUpdateClickInput.bind(this))
this.btnPrintLabels.on('click', this.handlePrintLabels.bind(this))
this.btnFicharEmbalaje.on('click', this.handleFicharEmbalaje.bind(this))
}
eventActionButton(event) {
@ -301,6 +303,51 @@ class MaquinistaTareaView {
});
}
handleFicharEmbalaje() {
const ot_id = [$('#otId').html()];
$.post('/logistica/ficharEmbalaje', {
ids: ot_id,
}, function (response) {
if (response.status) {
Swal.fire({
text: response.message,
icon: 'success',
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
});
} else {
Swal.fire({
title: 'Error',
text: response.message,
icon: 'error',
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
});
table.ajax.reload();
}
}).fail(() => {
Swal.fire({
title: 'Error',
text: 'No se pudo realizar el fichaje.',
icon: 'error',
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
});
table.ajax.reload();
});
}
}
export default MaquinistaTareaView;

View File

@ -49,7 +49,7 @@ document.addEventListener('DOMContentLoaded', function () {
}
Swal.close();
Swal.fire('Éxito', `${xmlFiles.length} archivos XML cargados.`, 'success');
Swal.fire('Éxito', `${xmlFiles.length} archivos XML detectados, proceda a la importación.`, 'success');
} catch (err) {
console.error(err);
Swal.fire('Error', 'No se pudo procesar el ZIP.', 'error');

View File

@ -7,6 +7,7 @@ class EnvioEdit {
constructor() {
this.tableCols = [
{ data: "rowSelected" },
{ data: "ordenTrabajo" },
{ data: "pedido" },
{ data: "presupuesto" },
{ data: "titulo" },
@ -19,6 +20,7 @@ class EnvioEdit {
];
this.table = null;
this.tableProximosEnvios = null;
this.buscarPedidos = new ClassSelect($("#buscadorPedidos"), '/logistica/selectAddLinea', "", true, { 'envio': $("#id").val() });
@ -84,16 +86,56 @@ class EnvioEdit {
"searchable": false,
},
{
"targets": [1, 2, 4, 5, 6],
"targets": [1, 2, 4, 5, 6, 7],
"className": "text-center",
},
{
targets: [7, 8, 9],
targets: [8, 9, 10],
visible: false
}
]
});
this.tableProximosEnvios = $('#tableProximosEnvios').DataTable({
processing: true,
serverSide: true,
autoWidth: true,
responsive: true,
scrollX: true,
orderCellsTop: true,
orderable: false,
order: [[1, 'asc']],
lengthMenu: [5, 10, 25, 50, 75, 100, 250, 500, 1000, 2500],
pageLength: 5,
"dom": 'tp',
"ajax": {
"url": "/logistica/datatableProximosEnvios/" + $('#id').val(),
},
"columns": [
{data: 'ot'},
{data: 'fechaEncuadernado'}
],
"language": {
url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json"
},
"columnDefs": [
{
"targets": [0, 1],
"className": "text-center",
},
],
drawCallback: function(){
$(this.api().table().container()).find('table').css('width', '100%');
this.api().columns.adjust();
}
});
$('#proximosEnviosTip' + this.id).on('shown.bs.collapse', () => {
if (this.tableProximosEnvios) {
this.tableProximosEnvios.columns.adjust().draw(false);
}
});
$('#btnImprimirEtiquetas').on('click', () => {
const table = this.table;
const selectedRows = table.rows({ page: 'current' }).nodes().filter((node) => {
@ -121,7 +163,7 @@ class EnvioEdit {
}
const idEnvio = $('#id').val();
let num_cajas = this.cajas.val();
if(ids.length != table.rows().count()){
if (ids.length != table.rows().count()) {
// se preguntará el numero de cajas en un swal con un input para obtener el valor
Swal.fire({
title: 'Atención!',
@ -146,7 +188,7 @@ class EnvioEdit {
}
});
}
else{
else {
this._imprimirEtiquetas(idEnvio, ids, num_cajas);
}
});
@ -485,9 +527,14 @@ class EnvioEdit {
});
});
$('#ficharEmbalaje').on('click', (e) => {
this._ficharEmbalajeLineas();
});
this._getAlbaranes();
}
_imprimirEtiquetas(envio_id, ids, num_cajas) {
$.post('/logistica/imprimirEtiquetas', {
@ -510,7 +557,7 @@ class EnvioEdit {
},
buttonsStyling: false
}).then(() => {
if(response.data){
if (response.data) {
// show xml in a new tab
const blob = new Blob([response.data], { type: 'application/xml' });
const url = URL.createObjectURL(blob);
@ -520,7 +567,7 @@ class EnvioEdit {
a.click();
URL.revokeObjectURL(url);
a.remove();
}
});
}
@ -671,6 +718,95 @@ class EnvioEdit {
});
}
_ficharEmbalajeLineas() {
const table = this.table;
const selectedRows = table.rows({ page: 'current' }).nodes().filter((node) => {
const checkbox = $(node).find('.checkbox-linea-envio');
return checkbox.is(':checked');
});
const ids = selectedRows.map((node) => {
const rowData = table.row(node).data();
const parser = new DOMParser();
const doc = parser.parseFromString(rowData.ordenTrabajo, 'text/html');
return doc.body.textContent.trim(); // extrae solo el texto dentro del <a>
}).toArray();
if (ids.length > 0) {
Swal.fire({
title: 'Fichar embalaje',
text: '¿Está seguro de fichar el embalaje de las líneas seleccionadas?',
icon: 'warning',
showCancelButton: true,
confirmButtonText: 'Sí',
cancelButtonText: 'Cancelar',
customClass: {
confirmButton: 'btn btn-danger me-1',
cancelButton: 'btn btn-secondary'
},
buttonsStyling: false
}).then((result) => {
if (result.isConfirmed) {
$.post('/logistica/ficharEmbalaje', {
ids: ids
}, function (response) {
if (response.status) {
Swal.fire({
text: response.message,
icon: 'success',
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
});
} else {
Swal.fire({
title: 'Error',
text: response.message,
icon: 'error',
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
});
table.ajax.reload();
}
}).fail(() => {
Swal.fire({
title: 'Error',
text: 'No se pudo realizar el fichaje.',
icon: 'error',
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
});
table.ajax.reload();
});
}
});
} else {
Swal.fire({
title: 'Sin filas seleccionadas',
text: 'Marca al menos una línea para eliminarla.',
icon: 'info',
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
});
}
}
_deleteLineas() {
const table = this.table;
const selectedRows = table.rows({ page: 'current' }).nodes().filter((node) => {