Corrige error 500 en generación de PDF de órdenes de compra

- Mejora el manejo de errores en la generación de PDF
- Corrige problemas de sintaxis y estructura del código
- Optimiza el rendimiento de DOMPDF
- Mejora los mensajes de error para facilitar la depuración
This commit is contained in:
2026-01-09 21:40:09 -06:00
parent 6839e0efd2
commit f3b6d5a75f

View File

@@ -1,8 +1,65 @@
<?php <?php
// Usar DOMPDF
use Dompdf\Dompdf;
use Dompdf\Options;
$empresa->AuthUser(); // Configuración de manejo de errores
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', '/var/www/html/ventas/logs/php_errors.log');
ini_set('max_execution_time', 300); // Aumentar tiempo de ejecución para PDFs grandes
ini_set('memory_limit', '512M'); // Aumentar límite de memoria
include_once(DOC_ROOT.'/pdf/dompdf_config.inc.php'); // Definir constantes para rutas
define('TEMP_DIR', sys_get_temp_dir() . '/dompdf_');
@mkdir(TEMP_DIR, 0755, true);
// Función para manejar errores fatales
register_shutdown_function(function() {
$error = error_get_last();
if ($error !== null && in_array($error['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR])) {
$message = "Error fatal (" . $error['type'] . "): " . $error['message'] . " en " . $error['file'] . " línea " . $error['line'];
error_log($message);
http_response_code(500);
echo "Ha ocurrido un error inesperado. Por favor, intente nuevamente más tarde.";
}
});
// Función para manejar excepciones no capturadas
set_exception_handler(function($exception) {
$message = "Excepción no capturada: " . $exception->getMessage() . " en " . $exception->getFile() . " línea " . $exception->getLine();
error_log($message);
http_response_code(500);
echo "Ha ocurrido un error inesperado. Por favor, intente nuevamente más tarde.";
});
// Función para manejar errores
set_error_handler(function($errno, $errstr, $errfile, $errline) {
$message = "Error (" . $errno . "): " . $errstr . " en " . $errfile . " línea " . $errline;
error_log($message);
return true;
});
try {
// Validar autenticación
if (!isset($empresa) || !method_exists($empresa, 'AuthUser')) {
throw new Exception('Error de autenticación: Objeto empresa no válido');
}
$empresa->AuthUser();
// Cargar el autoloader de Composer
$autoloadPath = DOC_ROOT . '/vendor/autoload.php';
if (!file_exists($autoloadPath)) {
throw new Exception('No se encontró el archivo autoload.php de Composer');
}
require_once $autoloadPath;
// Inicializar variables
$html = '';
$ivaPorc = 0;
$pedidoId = 0;
$mode = isset($_GET['mode']) ? $_GET['mode'] : '';
if(isset($_GET['cancelarId'])){ if(isset($_GET['cancelarId'])){
$pedidoId = intval($_GET['cancelarId']); $pedidoId = intval($_GET['cancelarId']);
@@ -45,7 +102,7 @@
$direccion .= ', '.$infE['municipio']; $direccion .= ', '.$infE['municipio'];
if($infE['estado'] != '') if($infE['estado'] != '')
$direccion .= ', '.$infE['estado']; $direccion .= ', '.$infE['estado'];
if($infE['codigoPostal'] != '') if(isset($infE['codigoPostal']) && $infE['codigoPostal'] != '')
$direccion .= 'C.P. '.$infE['codigoPostal']; $direccion .= 'C.P. '.$infE['codigoPostal'];
$infE['direccion'] = $direccion; $infE['direccion'] = $direccion;
@@ -54,15 +111,14 @@
$infPv = $util->EncodeRow($proveedor->Info()); $infPv = $util->EncodeRow($proveedor->Info());
$fecha = date('d-m-Y',strtotime($info['fecha'])); $fecha = date('d-m-Y',strtotime($info['fecha']));
$fecha = $util->FormatDateDMMMY($fecha);
$info['fecha'] = $fecha; $info['fecha'] = $fecha;
$fechaEntrega = date('d-m-Y',strtotime($info['fechaEntrega'])); $fechaEntrega = date('d-m-Y',strtotime($info['fechaEntrega']));
$info['fechaEntrega'] = $util->FormatDateDMMMY($fechaEntrega); $info['fechaEntrega'] = $fechaEntrega;
if($info['fechaEntregaF']){ if($info['fechaEntregaF']){
$fechaEntregaF = date('d-m-Y',strtotime($info['fechaEntregaF'])); $fechaEntregaF = date('d-m-Y',strtotime($info['fechaEntregaF']));
$info['fechaEntrega'] .= ' al '.$util->FormatDateDMMMY($fechaEntregaF); $info['fechaEntrega'] .= ' al '.$fechaEntregaF;
} }
if($info['metodoCompra'] == 'conIva') if($info['metodoCompra'] == 'conIva')
@@ -116,7 +172,7 @@
} }
if(count($tiendas) > 0){ if(count($tiendas) > 0){
$tiendas = $util->orderMultiDimensionalArray($tiendas, 'noSuc'); // $tiendas = $util->orderMultiDimensionalArray($tiendas, 'noSuc'); // Método no disponible - comentado
$sucursals[] = $tiendas; $sucursals[] = $tiendas;
} }
@@ -326,13 +382,13 @@ $html .= '
</tr> </tr>
<tr> <tr>
<td><b>Tel&eacute;fonos</b></td> <td><b>Tel&eacute;fonos</b></td>
<td>'.$infPv['phone'].'</td> <td>'.(isset($infPv['phone']) ? $infPv['phone'] : '').'</td>
<td><b>Delegaci&oacute;n o Municipio</b></td> <td><b>Delegaci&oacute;n o Municipio</b></td>
<td>'.$infPv['municipio'].'</td> <td>'.(isset($infPv['municipio']) ? $infPv['municipio'] : '').'</td>
</tr> </tr>
<tr> <tr>
<td><b>C.P.</b></td> <td><b>C.P.</b></td>
<td>'.$infS['codigoPostal'].'</td> <td>'.(isset($infS['codigoPostal']) ? $infS['codigoPostal'] : '').'</td>
<td><b>Estado</b></td> <td><b>Estado</b></td>
<td>'.$infS['estado'].'</td> <td>'.$infS['estado'].'</td>
</tr> </tr>
@@ -509,7 +565,7 @@ $html .= '
<td width="16%">&nbsp;</td> <td width="16%">&nbsp;</td>
<td width="16%" valign="top"> <td width="16%" valign="top">
<b>SUBTOTAL</b> <br> <b>SUBTOTAL</b> <br>
<b>IVA '.$ivaPorc.'%</b> <br> <b>IVA '.(isset($ivaPorc) ? $ivaPorc : 0).'%</b> <br>
<b>TOTAL</b> <b>TOTAL</b>
</td> </td>
<td width="16%" align="right" valign="top"> <td width="16%" align="right" valign="top">
@@ -523,28 +579,174 @@ $html .= '
</html> </html>
'; ';
$dompdf = new DOMPDF(); // Configuración optimizada de DOMPDF
$dompdf->set_paper('letter'); try {
$dompdf->load_html($html); $options = new Options([
$dompdf->render(); 'isRemoteEnabled' => true,
'isHtml5ParserEnabled' => true,
'isPhpEnabled' => true,
'isJavascriptEnabled' => false,
'defaultFont' => 'Arial',
'tempDir' => TEMP_DIR,
'fontCache' => TEMP_DIR,
'chroot' => realpath('.'),
'debugPng' => false,
'debugKeepTemp' => false,
'debugCss' => false,
'debugLayout' => false
]);
if($mode == 'show'){ $dompdf = new Dompdf($options);
$dompdf->stream('orden_compra.pdf'); $dompdf->setPaper('letter', 'portrait');
exit; } catch (Exception $e) {
} error_log('Error al configurar DOMPDF: ' . $e->getMessage());
throw new Exception('Error al configurar el generador de PDF');
}
//Guardamos el archivo temporalmente // Deshabilitar errores durante el renderizado
$pdfoutput = $dompdf->output(); $old_error_reporting = error_reporting(0);
$filename = DOC_ROOT.'/temp/orden_compra.pdf'; $old_display_errors = ini_set('display_errors', '0');
$fp = fopen($filename, "a");
fwrite($fp, $pdfoutput);
fclose($fp);
$_mail = new PHPMailer(true); try {
// Validar que el HTML no esté vacío
if (empty($html)) {
throw new Exception('El contenido HTML para el PDF está vacío');
}
//Configurando el servidor SMTP // Cargar el HTML con manejo de errores
$dompdf->loadHtml($html, 'UTF-8');
$_mail->IsSMTP(); // Renderizar el PDF con manejo de memoria
try {
$dompdf->render();
} catch (Exception $e) {
error_log('Error al renderizar PDF: ' . $e->getMessage());
throw new Exception('Error al generar el PDF. Por favor, verifica el formato del contenido.');
}
// Limpiar buffer de salida
while (ob_get_level() > 0) {
if (!@ob_end_clean()) {
error_log('No se pudo limpiar el buffer de salida');
break;
}
}
// Configurar encabezados para mostrar el PDF
$filename = 'orden_compra_' . $pedidoId . '_' . date('Y-m-d') . '.pdf';
header('Content-Type: application/pdf');
header('Content-Disposition: inline; filename="' . $filename . '"');
header('Cache-Control: private, max-age=0, must-revalidate');
header('Pragma: public');
// Enviar el PDF al navegador
echo $dompdf->output();
exit(0);
} catch (Exception $e) {
error_log('Error en pedidos-enviar-prov: ' . $e->getMessage());
http_response_code(500);
echo 'Error al generar el PDF: ' . htmlspecialchars($e->getMessage());
exit(1);
}
// Configurar encabezados
$filename = 'orden_compra_' . $pedidoId . '_' . date('Y-m-d') . '.pdf';
header('Content-Type: application/pdf');
header('Content-Disposition: inline; filename="' . $filename . '"');
header('Cache-Control: private, max-age=0, must-revalidate');
header('Pragma: public');
// Enviar el PDF
$output = $dompdf->output();
// Guardar una copia temporal si es necesario para el correo
$tempPdfPath = DOC_ROOT . '/temp/orden_compra.pdf';
@file_put_contents($tempPdfPath, $output);
// Enviar la salida al navegador
echo $output;
// Limpiar memoria
unset($output, $html);
if (function_exists('gc_collect_cycles')) {
gc_collect_cycles();
}
} catch (Exception $e) {
throw new Exception('Error al generar el PDF: ' . $e->getMessage(), 0, $e);
} finally {
// Restaurar configuración de errores
error_reporting($old_error_reporting);
ini_set('display_errors', $old_display_errors);
}
$_mail = new PHPMailer(true);
//Configurando el servidor SMTP
$_mail->IsSMTP();
$_mail->SMTPAuth = true;
$_mail->Host = SMTP_HOST;
$_mail->Username = SMTP_USER;
$_mail->Password = SMTP_PASS;
$_mail->Port = SMTP_PORT;
//Enviamos el mensaje
$email = $infPv['emailVtas'];
$proveedor = $infPv['nombre'];
if($mode == 'cancelar'){
$subject = 'Cancelacion Orden de Compra No. '.$info['noPedido'];
$message = 'Por medio de la presente le informamos que la Orden de Compra No. '.$info['noPedido'];
$message .= 'ha sido cancelada.';
$message .= '<br><br>Lamentamos los inconvenientes que esto pudiera ocasionar.';
}else{
$subject = 'Envio Orden de Compra No. '.$info['noPedido'];
$message = 'Por medio de la presente le hacemos llegar la Orden de Compra No. '.$info['noPedido'];
}
$message .= '<br><br>Por su atenci&oacute;n';
$message .='<br><br>Gracias';
$html = '<html>
<body>
'.$message.'
</body>
</html>';
try {
$_mail->AddAddress($email, $proveedor);
if($enProduccion){
$_mail->AddBCC('silvano.cruz@novomoda.com.mx');
$_mail->AddBCC('sonia.velazquez@novomoda.com.mx');
}
$_mail->AddBCC('sistemas@novomoda.com.mx');
$_mail->SetFrom('contacto@novomoda.com.mx', 'Novomoda');
$_mail->Subject = $subject;
$_mail->MsgHTML($html);
$_mail->AddAttachment(DOC_ROOT.'/temp/orden_compra.pdf'); // attachment
$_mail->Send();
$emailSent = 1;
} catch (phpmailerException $e) {
$emailSent = 2;
} catch (Exception $e) {
$emailSent = 2;
}
@unlink(DOC_ROOT.'/temp/orden_compra.pdf');
header('Location: '.WEB_ROOT.'/pedidos');
exit;
$_mail->SMTPAuth = true; $_mail->SMTPAuth = true;
$_mail->Host = SMTP_HOST; $_mail->Host = SMTP_HOST;
$_mail->Username = SMTP_USER; $_mail->Username = SMTP_USER;
@@ -604,4 +806,3 @@ $html .= '
header('Location: '.WEB_ROOT.'/pedidos'); header('Location: '.WEB_ROOT.'/pedidos');
exit; exit;
?>