1108 lines
43 KiB
PHP
1108 lines
43 KiB
PHP
<?php
|
||
session_start();
|
||
require_once __DIR__ . '/../../config/database.php';
|
||
// 1) Composer autoload (phpdotenv y demás libs)
|
||
require_once __DIR__ . '/../../vendor/autoload.php';
|
||
|
||
// 2) Carga nuestro helper de entorno y dispara la carga de .env
|
||
require_once __DIR__ . '/../helpers/env.php';
|
||
loadEnv();
|
||
|
||
require_once __DIR__ . '/../../vendor/autoload.php';
|
||
require_once __DIR__ . '/../helpers/crypto.php';
|
||
|
||
/** Obtiene (y cachea en sesión) el JWT de la API usando las credenciales de $_ENV **/
|
||
/** Obtiene (y cachea) el JWT de la API usando credenciales de $_ENV
|
||
* Gestiona expiración: asume 1 hora de vida y renueva si ha pasado. **/
|
||
function getApiToken(): ?string
|
||
{
|
||
// Duración en segundos del token (60 min)
|
||
$ttl = 3600;
|
||
|
||
// 1) Si ya tenemos token y no ha expirado, lo devolvemos
|
||
if (!empty($_SESSION['api_token']) && !empty($_SESSION['api_token_time'])) {
|
||
$age = time() - $_SESSION['api_token_time'];
|
||
if ($age < $ttl) {
|
||
error_log("[getApiToken] Usando token en caché (edad: {$age}s)");
|
||
return $_SESSION['api_token'];
|
||
}
|
||
error_log("[getApiToken] Token expirado (edad: {$age}s), obteniendo uno nuevo");
|
||
}
|
||
|
||
// 2) Sí o sí hacemos login en la API
|
||
$url = rtrim($_ENV['API_URL'] ?? '', '/') . '/auth/login';
|
||
$user = $_ENV['API_USER'] ?? '';
|
||
$pass = $_ENV['API_PASS'] ?? '';
|
||
$body = json_encode(['username' => $user, 'password' => $pass]);
|
||
|
||
error_log("[getApiToken] POST $url → $body");
|
||
|
||
$ch = curl_init($url);
|
||
curl_setopt_array($ch, [
|
||
CURLOPT_POST => true,
|
||
CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
|
||
CURLOPT_POSTFIELDS => $body,
|
||
CURLOPT_RETURNTRANSFER => true,
|
||
CURLOPT_TIMEOUT => 5,
|
||
]);
|
||
$resp = curl_exec($ch);
|
||
$http = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||
curl_close($ch);
|
||
|
||
error_log("[getApiToken] HTTP $http → $resp");
|
||
|
||
if ($http === 200 && ($data = json_decode($resp, true)) && !empty($data['token'])) {
|
||
// 3) Guardamos token y tiempo actual
|
||
$_SESSION['api_token'] = $data['token'];
|
||
$_SESSION['api_token_time'] = time();
|
||
return $data['token'];
|
||
}
|
||
|
||
// 4) Si no se pudo obtener, devolvemos null
|
||
error_log('[getApiToken] No se pudo obtener token de la API');
|
||
return null;
|
||
}
|
||
|
||
/** Listado de solicitudes de importación (facturas) del importador logueado **/
|
||
function lista() {
|
||
if (!($_SESSION['usuario_id'] ?? false)) {
|
||
header('Location: /IMPORTADORES/login');
|
||
exit;
|
||
}
|
||
$id_importador = $_SESSION['usuario_id'];
|
||
$conn = getConnection();
|
||
|
||
$sql = "
|
||
SELECT
|
||
f.*,
|
||
tr.nombre AS transportista,
|
||
(c.nombre + ' ' + c.apellido) AS chofer,
|
||
p.nombre AS nombre_pais_proveedor,
|
||
f.foto_solicitud_url
|
||
FROM dbo.solicitud_importacion_factura f
|
||
JOIN dbo.transportistas tr
|
||
ON f.transportista_id = tr.id_transportista
|
||
LEFT JOIN dbo.choferes c
|
||
ON f.chofer_id = c.id_chofer
|
||
LEFT JOIN dbo.paises p
|
||
ON f.pais_proveedor = p.id_pais
|
||
WHERE f.id_importador = ?
|
||
AND f.status >= 1
|
||
ORDER BY f.created_at DESC
|
||
";
|
||
$stmt = sqlsrv_query($conn, $sql, [$id_importador]);
|
||
if ($stmt === false) {
|
||
die("Error en lista(): " . print_r(sqlsrv_errors(), true));
|
||
}
|
||
|
||
$facturas = [];
|
||
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
|
||
if ($row['fecha_factura'] instanceof DateTime) {
|
||
$row['fecha_factura'] = $row['fecha_factura']->format('Y-m-d');
|
||
}
|
||
$facturas[] = $row;
|
||
}
|
||
|
||
include __DIR__ . '/../../views/solicitud_importacion/lista.php';
|
||
}
|
||
|
||
/** Formulario de nueva factura **/
|
||
function crear()
|
||
{
|
||
if (!($_SESSION['usuario_id'] ?? false)) {
|
||
header('Location: /IMPORTADORES/login');
|
||
exit;
|
||
}
|
||
$id_importador = $_SESSION['usuario_id'];
|
||
$conn = getConnection();
|
||
|
||
// Carga de datos para selects
|
||
$transportistas = [];
|
||
$stmtT = sqlsrv_query($conn, "SELECT id_transportista, clave_identificador, nombre FROM dbo.transportistas WHERE id_usuario=? AND activo=1 ORDER BY nombre",[$id_importador]);
|
||
while ($r = sqlsrv_fetch_array($stmtT, SQLSRV_FETCH_ASSOC)) { $transportistas[] = $r; }
|
||
|
||
$choferes = [];
|
||
$stmtC = sqlsrv_query($conn, "SELECT c.id_chofer, c.nombre+' '+c.apellido AS nombre FROM dbo.choferes c JOIN dbo.transportistas t ON c.transportista_id=t.id_transportista WHERE t.id_usuario=? AND c.status=1 ORDER BY c.nombre",[$id_importador]);
|
||
while ($r = sqlsrv_fetch_array($stmtC, SQLSRV_FETCH_ASSOC)) { $choferes[] = $r; }
|
||
|
||
$paises = [];
|
||
$stmtP = sqlsrv_query($conn, "SELECT id_pais, nombre FROM dbo.paises ORDER BY nombre");
|
||
while ($r = sqlsrv_fetch_array($stmtP, SQLSRV_FETCH_ASSOC)) { $paises[] = $r; }
|
||
|
||
$aduanas = [];
|
||
$stmtA = sqlsrv_query($conn, "SELECT DISTINCT RIGHT(REPLICATE('0', 3) + CAST(aduana_seccion AS VARCHAR), 3) AS aduana_seccion, nombre FROM dbo.aduanas ORDER BY aduana_seccion");
|
||
while ($r = sqlsrv_fetch_array($stmtA, SQLSRV_FETCH_ASSOC)) { $aduanas[] = $r; }
|
||
|
||
$incoterms = [];
|
||
$stmtI = sqlsrv_query($conn, "SELECT INCOTERM, DESCESPANOL FROM dbo.gIncoterms ORDER BY INCOTERM");
|
||
while ($r = sqlsrv_fetch_array($stmtI, SQLSRV_FETCH_ASSOC)) { $incoterms[] = $r; }
|
||
|
||
$unidades_medida = [];
|
||
$stmtU = sqlsrv_query($conn, "SELECT id, descripcion FROM dbo.unidades_medida_apendice7 ORDER BY id");
|
||
while ($r = sqlsrv_fetch_array($stmtU, SQLSRV_FETCH_ASSOC)) {
|
||
$unidades_medida[] = $r;
|
||
}
|
||
|
||
include __DIR__ . '/../../views/solicitud_importacion/crear.php';
|
||
}
|
||
|
||
/** Procesa la creación de una nueva factura y sus partidas **/
|
||
function guardar()
|
||
{
|
||
if (!($_SESSION['usuario_id'] ?? false)) {
|
||
die("⚠️ No autorizado.");
|
||
}
|
||
$id_importador = $_SESSION['usuario_id'];
|
||
$aduana_seccion = $_POST['anexo22_apendice'] ?? null;
|
||
$num_factura = trim($_POST['numero_factura'] ?? '');
|
||
$fecha = $_POST['fecha_factura'] ?? null;
|
||
$incoterm = $_POST['incoterm'] ?? null;
|
||
$pais_proveedor = $_POST['pais_proveedor'] ?? null;
|
||
$tipo_moneda = $_POST['tipo_moneda'] ?? null;
|
||
$valor_factura = $_POST['valor_factura'] ?? null;
|
||
$vinculacion = $_POST['vinculacion'] ?? 0;
|
||
$transportista_id = $_POST['transportista_id'] ?? null;
|
||
$chofer_id = $_POST['chofer_id'] ?? null;
|
||
$status = isset($_POST['status']) ? 1 : 0;
|
||
$proveedor_clave = trim($_POST['proveedor_id'] ?? '');
|
||
|
||
if (empty($num_factura) || empty($fecha) || empty($transportista_id) || empty($chofer_id)) {
|
||
die("❌ Faltan campos obligatorios.");
|
||
}
|
||
|
||
// Foto solicitud
|
||
$fotoUrl=null;
|
||
if (!empty($_FILES['foto_solicitud']['tmp_name']) && $_FILES['foto_solicitud']['error']===UPLOAD_ERR_OK) {
|
||
$ext=pathinfo($_FILES['foto_solicitud']['name'],PATHINFO_EXTENSION);
|
||
$dest=__DIR__.'/../../public/uploads/solicitud_'.uniqid().".$ext";
|
||
if (!is_dir(dirname($dest))) mkdir(dirname($dest),0755,true);
|
||
if(move_uploaded_file($_FILES['foto_solicitud']['tmp_name'],$dest)) {
|
||
$fotoUrl="/IMPORTADORES/public/uploads/".basename($dest);
|
||
}
|
||
}
|
||
|
||
$conn = getConnection();
|
||
|
||
$params = [
|
||
$id_importador,
|
||
$aduana_seccion,
|
||
$aduana_seccion,
|
||
$num_factura,
|
||
$fecha,
|
||
$incoterm,
|
||
$pais_proveedor,
|
||
$tipo_moneda,
|
||
$valor_factura,
|
||
$vinculacion,
|
||
(int)$transportista_id,
|
||
(int)$chofer_id,
|
||
$fotoUrl,
|
||
$status,
|
||
$proveedor_clave
|
||
];
|
||
|
||
$sql = "INSERT INTO dbo.solicitud_importacion_factura
|
||
(id_importador, aduana, anexo22_apendice, numero_factura, fecha_factura,
|
||
numero_pedimento, incoterm, pais_proveedor, tipo_moneda,
|
||
valor_factura, vinculacion, transportista_id, chofer_id,
|
||
foto_solicitud_url, status, proveedor_clave)
|
||
OUTPUT INSERTED.id_solicitud
|
||
VALUES(?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
|
||
|
||
$stmt = sqlsrv_query($conn, $sql, $params, ['Scrollable' => SQLSRV_CURSOR_KEYSET]);
|
||
if ($stmt === false) {
|
||
die("❌ Error ejecutando INSERT con OUTPUT: " . print_r(sqlsrv_errors(), true));
|
||
}
|
||
|
||
$new = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
|
||
if (!$new || empty($new['id_solicitud'])) {
|
||
die("❌ No se pudo recuperar el ID insertado de la factura.");
|
||
}
|
||
|
||
$id_solicitud = (int)$new['id_solicitud'];
|
||
|
||
try {
|
||
// Verificar configuración de notificaciones del usuario
|
||
$sqlNotif = "
|
||
SELECT
|
||
u.nombre,
|
||
u.email,
|
||
u.notificaciones,
|
||
u.notificaciones_extra,
|
||
COALESCE(p.nuevas_solicitudes, 0) as nuevas_solicitudes,
|
||
ce.correo as correo_extra
|
||
FROM usuarios_sistema u
|
||
LEFT JOIN preferencias_notificaciones_usuario p ON u.id_usuario = p.id_usuario
|
||
LEFT JOIN correo_extra ce ON u.id_usuario = ce.id_usuario
|
||
WHERE u.id_usuario = ?";
|
||
|
||
$stmtNotif = sqlsrv_prepare($conn, $sqlNotif, [$id_importador]);
|
||
|
||
if ($stmtNotif && sqlsrv_execute($stmtNotif)) {
|
||
$notifConfig = sqlsrv_fetch_array($stmtNotif, SQLSRV_FETCH_ASSOC);
|
||
sqlsrv_free_stmt($stmtNotif);
|
||
|
||
// 🔐 Desencriptar datos
|
||
if ($notifConfig) {
|
||
// Correo
|
||
$notifConfig['email'] = decrypt($notifConfig['email']);
|
||
// Nombre
|
||
$notifConfig['nombre'] = decrypt($notifConfig['nombre']);
|
||
}
|
||
|
||
// Verificar si debe enviar notificaciones
|
||
if ($notifConfig &&
|
||
$notifConfig['notificaciones'] == 1 &&
|
||
$notifConfig['nuevas_solicitudes'] == 1) {
|
||
|
||
// Preparar datos para la notificación
|
||
$datosNotificacion = [
|
||
'id_solicitud' => $id_solicitud,
|
||
'numero_factura' => $num_factura,
|
||
'fecha_factura' => $fecha,
|
||
'valor_factura' => $valor_factura,
|
||
'tipo_moneda' => $tipo_moneda
|
||
];
|
||
|
||
// Enviar al correo principal
|
||
$resultadoPrincipal = enviarNotificacionNuevaSolicitud(
|
||
$notifConfig['email'],
|
||
$notifConfig['nombre'],
|
||
$datosNotificacion
|
||
);
|
||
|
||
// Enviar al correo adicional si está configurado
|
||
if ($notifConfig['notificaciones_extra'] == 1 && !empty($notifConfig['correo_extra'])) {
|
||
$resultadoExtra = enviarNotificacionNuevaSolicitud(
|
||
$notifConfig['correo_extra'],
|
||
$notifConfig['nombre'],
|
||
$datosNotificacion,
|
||
true // Indicar que es correo adicional
|
||
);
|
||
}
|
||
// Log de notificaciones enviadas (opcional)
|
||
error_log("✅ Notificación enviada para solicitud ID: $id_solicitud");
|
||
} else {
|
||
// Log informativo
|
||
error_log("ℹ️ Usuario ID: $id_importador no tiene notificaciones de nuevas solicitudes habilitadas");
|
||
}
|
||
} else {
|
||
error_log("⚠️ No se pudo consultar configuración de notificaciones para usuario ID: $id_importador");
|
||
}
|
||
} catch (Exception $e) {
|
||
// No fallar el proceso por errores de notificación
|
||
error_log("❌ Error en sistema de notificaciones: " . $e->getMessage());
|
||
}
|
||
|
||
// Partidas
|
||
if(!empty($_POST['partidas'])&&is_array($_POST['partidas'])){
|
||
|
||
$sqlP = "INSERT INTO dbo.solicitud_importacion_partidas
|
||
(id_solicitud, descripcion, cantidad_comercial, cantidad_tarifa, valor_factura, peso_bruto, unidad_comercial_id, tasa_preferencial)
|
||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
|
||
|
||
$partidas_insertadas = 0; // ← contador
|
||
|
||
foreach ($_POST['partidas'] as $i => $p) {
|
||
error_log("Partida $i: " . print_r($p, true));
|
||
$params = [
|
||
$id_solicitud,
|
||
trim($p['descripcion'] ?? ''),
|
||
|
||
floatval($p['cantidad_comercial'] ?? 0),
|
||
floatval($p['cantidad_tarifa'] ?? 0),
|
||
floatval($p['valor_factura'] ?? 0),
|
||
floatval($p['peso_bruto'] ?? 0),
|
||
intval($p['unidad_comercial_id'] ?? 0) ?: null,
|
||
|
||
trim($p['tasa_preferencial'] ?? '')
|
||
];
|
||
|
||
if ($params[1] !== '' && $params[2] > 0) {
|
||
$stmtPartida = sqlsrv_query($conn, $sqlP, $params);
|
||
if ($stmtPartida === false) {
|
||
die("❌ Error insertando partida $i: " . print_r(sqlsrv_errors(), true));
|
||
} else {
|
||
$partidas_insertadas++;
|
||
}
|
||
}
|
||
}
|
||
if ($partidas_insertadas === 0) {
|
||
///header('Location: /IMPORTADORES/solicitud_importacion/crear?error_partidas=1');
|
||
// exit;
|
||
|
||
}
|
||
}
|
||
header('Location: /IMPORTADORES/solicitud_importacion/lista?created=ok');
|
||
exit;
|
||
}
|
||
|
||
/** Función para generar la notificación **/
|
||
use PHPMailer\PHPMailer\PHPMailer;
|
||
use PHPMailer\PHPMailer\Exception;
|
||
|
||
function enviarNotificacionNuevaSolicitud($email, $nombreUsuario, $datosSolicitud, $esCorreoExtra = false) {
|
||
$mail = new PHPMailer(true);
|
||
|
||
try {
|
||
// Configuración SMTP
|
||
$mail->isSMTP();
|
||
$mail->Host = 'secure.emailsrvr.com';
|
||
$mail->SMTPAuth = true;
|
||
$mail->Username = 'noreply@aduanasoft.com.mx';
|
||
$mail->Password = $_ENV['SMTP_PASS'] ?? '';
|
||
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
|
||
$mail->Port = 587;
|
||
$mail->CharSet = 'UTF-8';
|
||
|
||
// Configuración del mensaje
|
||
$mail->setFrom('noreply@aduanasoft.com.mx', 'SIIH | AduanaSoft');
|
||
$mail->addAddress($email);
|
||
$mail->isHTML(true);
|
||
|
||
// Personalizar subject si es correo adicional
|
||
$subjectPrefix = $esCorreoExtra ? '[COPIA] ' : '';
|
||
$mail->Subject = $subjectPrefix . '📦 Nueva Solicitud de Importación Registrada';
|
||
|
||
// Formatear datos para el email
|
||
$idSolicitud = $datosSolicitud['id_solicitud'];
|
||
$numeroFactura = htmlspecialchars($datosSolicitud['numero_factura']);
|
||
$fechaFactura = htmlspecialchars($datosSolicitud['fecha_factura']);
|
||
$valorFactura = number_format($datosSolicitud['valor_factura'], 2);
|
||
$tipoMoneda = htmlspecialchars($datosSolicitud['tipo_moneda']);
|
||
|
||
$tipoNotificacion = $esCorreoExtra ?
|
||
'<div style="background: #fff3cd; padding: 10px; border-radius: 5px; margin-bottom: 15px; border-left: 4px solid #ffc107;">
|
||
<small><strong>📧 Copia enviada a correo adicional</strong></small>
|
||
</div>' : '';
|
||
|
||
$mail->Body = "
|
||
<div style='font-family: Segoe UI, sans-serif; background-color: #f4f6f9; padding: 30px;'>
|
||
<div style='max-width: 600px; margin: auto; background: #fff; border: 1px solid #ccc; border-radius: 10px;'>
|
||
<div style='background: linear-gradient(to right, #003366, #0055A5); padding: 20px; text-align: center;'>
|
||
<h2 style='color: white; margin: 0;'>📥 Nueva Solicitud Registrada</h2>
|
||
</div>
|
||
<div style='padding: 20px;'>
|
||
$tipoNotificacion
|
||
<p>Hola <strong>" . htmlspecialchars($nombreUsuario) . "</strong>,</p>
|
||
<p>Tu solicitud de importación ha sido registrada correctamente con los siguientes datos:</p>
|
||
|
||
<div style='background: #f8f9fa; padding: 15px; border-radius: 8px; margin: 15px 0;'>
|
||
<table style='width: 100%; border-collapse: collapse;'>
|
||
<tr>
|
||
<td style='padding: 5px 0; font-weight: bold;'>ID Solicitud:</td>
|
||
<td style='padding: 5px 0;'>$idSolicitud</td>
|
||
</tr>
|
||
<tr>
|
||
<td style='padding: 5px 0; font-weight: bold;'>Número de Factura:</td>
|
||
<td style='padding: 5px 0;'>$numeroFactura</td>
|
||
</tr>
|
||
<tr>
|
||
<td style='padding: 5px 0; font-weight: bold;'>Fecha:</td>
|
||
<td style='padding: 5px 0;'>$fechaFactura</td>
|
||
</tr>
|
||
<tr>
|
||
<td style='padding: 5px 0; font-weight: bold;'>Valor:</td>
|
||
<td style='padding: 5px 0;'>$valorFactura $tipoMoneda</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
|
||
<p>Puedes consultar el estado de tu solicitud accediendo a tu panel de control.</p>
|
||
<br>
|
||
<p style='color: #888; font-size: 14px;'>Si no realizaste esta acción, contacta al administrador del sistema.</p>
|
||
</div>
|
||
<div style='background: #e9ecef; text-align: center; padding: 10px; font-size: 13px; color: #666;'>
|
||
© " . date('Y') . " SIIH · Desarrollado por AduanaSoft
|
||
</div>
|
||
</div>
|
||
</div>";
|
||
|
||
$envioExitoso = $mail->send();
|
||
|
||
if ($envioExitoso) {
|
||
$tipoCorreo = $esCorreoExtra ? 'correo adicional' : 'correo principal';
|
||
error_log("✅ Notificación enviada exitosamente al $tipoCorreo: $email");
|
||
return true;
|
||
}
|
||
|
||
return false;
|
||
|
||
} catch (Exception $e) {
|
||
$tipoCorreo = $esCorreoExtra ? 'correo adicional' : 'correo principal';
|
||
error_log("❌ Error al enviar notificación al $tipoCorreo ($email): {$mail->ErrorInfo}");
|
||
return false;
|
||
}
|
||
}
|
||
|
||
/** Formulario de edición de factura **/
|
||
function editar() {
|
||
if (!($_SESSION['usuario_id'] ?? false)) {
|
||
header('Location: /IMPORTADORES/login'); exit;
|
||
}
|
||
|
||
$id_solicitud = $_GET['id']??null;
|
||
if(!$id_solicitud || !is_numeric($id_solicitud)) {
|
||
die("❌ ID inválido.");
|
||
}
|
||
$id_importador = $_SESSION['usuario_id'];
|
||
$conn = getConnection();
|
||
|
||
$stmt = sqlsrv_query($conn,"SELECT * FROM dbo.solicitud_importacion_factura WHERE id_solicitud=? AND id_importador=?",[(int)$id_solicitud,$id_importador]);
|
||
if($stmt === false) {
|
||
die(print_r(sqlsrv_errors(),true));
|
||
}
|
||
$factura = sqlsrv_fetch_array($stmt,SQLSRV_FETCH_ASSOC);
|
||
if(!$factura) {
|
||
die("❌ No autorizado.");
|
||
}
|
||
if($factura['fecha_factura'] instanceof DateTime) {
|
||
$factura['fecha_factura'] = $factura['fecha_factura']->format('Y-m-d');
|
||
}
|
||
|
||
// Solo necesitamos la clave del proveedor actual para JavaScript
|
||
$proveedor_clave_actual = $factura['proveedor_clave'] ?? '';
|
||
|
||
// Carga selects (igual que crear)
|
||
// Transportistas
|
||
$transportistas = []; $stmtT = sqlsrv_query($conn,"SELECT id_transportista, nombre FROM dbo.transportistas WHERE id_usuario=? AND activo=1 ORDER BY nombre",[$id_importador]);
|
||
while($r = sqlsrv_fetch_array($stmtT,SQLSRV_FETCH_ASSOC)) {
|
||
$transportistas[] = $r;
|
||
}
|
||
// Choferes
|
||
$choferes = []; $stmtC = sqlsrv_query($conn,"SELECT c.id_chofer, c.nombre+' '+c.apellido AS nombre FROM dbo.choferes c JOIN dbo.transportistas t ON c.transportista_id=t.id_transportista
|
||
WHERE t.id_usuario=? AND c.status=1 ORDER BY c.nombre",[$id_importador]);
|
||
while($r=sqlsrv_fetch_array($stmtC,SQLSRV_FETCH_ASSOC)) {
|
||
$choferes[] = $r;
|
||
}
|
||
// Paises
|
||
$paises = []; $stmtP = sqlsrv_query($conn,"SELECT id_pais, nombre FROM dbo.paises ORDER BY nombre");
|
||
while($r=sqlsrv_fetch_array($stmtP,SQLSRV_FETCH_ASSOC)) {
|
||
$paises[] = $r;
|
||
}
|
||
// Aduanas
|
||
$aduanas = []; $stmtA = sqlsrv_query($conn,"SELECT DISTINCT RIGHT(REPLICATE('0', 3) + CAST(aduana_seccion AS VARCHAR), 3) AS aduana_seccion, nombre FROM dbo.aduanas ORDER BY aduana_seccion");
|
||
while($r = sqlsrv_fetch_array($stmtA,SQLSRV_FETCH_ASSOC)) {
|
||
$aduanas[] = $r;
|
||
}
|
||
// Incoterms
|
||
$incoterms = []; $stmtI = sqlsrv_query($conn,"SELECT INCOTERM,DESCESPANOL FROM dbo.gIncoterms ORDER BY INCOTERM");
|
||
while($r = sqlsrv_fetch_array($stmtI,SQLSRV_FETCH_ASSOC)) {
|
||
$incoterms[] = $r;
|
||
}
|
||
// Unidades de Medida
|
||
$unidades_medida = []; $stmtU = sqlsrv_query($conn, "SELECT id, descripcion FROM dbo.unidades_medida_apendice7 ORDER BY id");
|
||
while ($r = sqlsrv_fetch_array($stmtU, SQLSRV_FETCH_ASSOC)) {
|
||
$unidades_medida[] = $r;
|
||
}
|
||
|
||
// Partidas existentes
|
||
$partidas = [];
|
||
$stmtPar = sqlsrv_query($conn,
|
||
"SELECT id_partida, descripcion, cantidad_comercial, cantidad_tarifa, valor_factura, peso_bruto, unidad_comercial_id, tasa_preferencial
|
||
FROM dbo.solicitud_importacion_partidas WHERE id_solicitud=? ORDER BY id_partida", [(int)$id_solicitud]);
|
||
while($r=sqlsrv_fetch_array($stmtPar,SQLSRV_FETCH_ASSOC)) {
|
||
$partidas[]=$r;
|
||
}
|
||
|
||
include __DIR__ . '/../../views/solicitud_importacion/editar.php';
|
||
}
|
||
|
||
/** Procesa la actualización de una factura y sus partidas **/
|
||
function actualizar() {
|
||
session_start();
|
||
if (!($_SESSION['usuario_id'] ?? false)) {
|
||
die("⚠️ No autorizado.");
|
||
}
|
||
|
||
$id_solicitud = (int)($_POST['id_solicitud'] ?? 0);
|
||
if ($id_solicitud <= 0) {
|
||
die("❌ ID inválido.");
|
||
}
|
||
|
||
// 1) Conexión
|
||
$conn = getConnection();
|
||
|
||
// 2) Obtener URL de foto actual desde BD para conservar si no suben nueva
|
||
$fotoUrl = null;
|
||
$stmtFoto = sqlsrv_query(
|
||
$conn,
|
||
"SELECT foto_solicitud_url
|
||
FROM dbo.solicitud_importacion_factura
|
||
WHERE id_solicitud = ? AND id_importador = ?",
|
||
[ $id_solicitud, $_SESSION['usuario_id'] ]
|
||
);
|
||
if ($stmtFoto !== false && ($row = sqlsrv_fetch_array($stmtFoto, SQLSRV_FETCH_ASSOC))) {
|
||
$fotoUrl = $row['foto_solicitud_url'];
|
||
}
|
||
|
||
// 3) Procesar posible nueva foto
|
||
if (!empty($_FILES['foto_solicitud']['tmp_name'])
|
||
&& $_FILES['foto_solicitud']['error'] === UPLOAD_ERR_OK) {
|
||
$ext = pathinfo($_FILES['foto_solicitud']['name'], PATHINFO_EXTENSION);
|
||
$dest = __DIR__ . '/../../public/uploads/solicitud_' . uniqid() . ".$ext";
|
||
if (!is_dir(dirname($dest))) {
|
||
mkdir(dirname($dest), 0755, true);
|
||
}
|
||
if (move_uploaded_file($_FILES['foto_solicitud']['tmp_name'], $dest)) {
|
||
$fotoUrl = "/IMPORTADORES/public/uploads/" . basename($dest);
|
||
}
|
||
}
|
||
|
||
// 4) Extraer campos del formulario
|
||
$aduana_seccion = $_POST['anexo22_apendice'] ?? null;
|
||
$num_factura = trim($_POST['numero_factura'] ?? '');
|
||
$fecha = $_POST['fecha_factura'] ?? null;
|
||
$incoterm = $_POST['incoterm'] ?? null;
|
||
$pais_proveedor = $_POST['pais_proveedor'] ?? null;
|
||
$tipo_moneda = $_POST['tipo_moneda'] ?? null;
|
||
$valor_factura = $_POST['valor_factura'] ?? null;
|
||
$vinculacion = $_POST['vinculacion'] ?? 0;
|
||
$transportista_id = (int)($_POST['transportista_id'] ?? 0);
|
||
$chofer_id = (int)($_POST['chofer_id'] ?? 0);
|
||
$status = isset($_POST['status']) ? 1 : 0;
|
||
|
||
// 5) Validar obligatorios
|
||
if (empty($num_factura) || empty($fecha) || $transportista_id <= 0 || $chofer_id <= 0) {
|
||
die("❌ Faltan campos obligatorios.");
|
||
}
|
||
|
||
// 6) UPDATE de la cabecera
|
||
$sqlU = "
|
||
UPDATE dbo.solicitud_importacion_factura
|
||
SET aduana = ?,
|
||
anexo22_apendice = ?,
|
||
numero_factura = ?,
|
||
fecha_factura = ?,
|
||
incoterm = ?,
|
||
pais_proveedor = ?,
|
||
tipo_moneda = ?,
|
||
valor_factura = ?,
|
||
vinculacion = ?,
|
||
transportista_id = ?,
|
||
chofer_id = ?,
|
||
foto_solicitud_url = ?,
|
||
status = ?,
|
||
updated_at = GETDATE()
|
||
WHERE id_solicitud = ?
|
||
AND id_importador = ?
|
||
";
|
||
$paramsU = [
|
||
$aduana_seccion,
|
||
$aduana_seccion,
|
||
$num_factura,
|
||
$fecha,
|
||
$incoterm,
|
||
$pais_proveedor,
|
||
$tipo_moneda,
|
||
$valor_factura,
|
||
$vinculacion,
|
||
$transportista_id,
|
||
$chofer_id,
|
||
$fotoUrl,
|
||
$status,
|
||
$id_solicitud,
|
||
$_SESSION['usuario_id']
|
||
];
|
||
$stmtU = sqlsrv_query($conn, $sqlU, $paramsU);
|
||
if ($stmtU === false) {
|
||
die("❌ Error ejecutando UPDATE: " . print_r(sqlsrv_errors(), true));
|
||
}
|
||
|
||
// 7) Borrar partidas anteriores
|
||
$del = sqlsrv_query(
|
||
$conn,
|
||
"DELETE FROM dbo.solicitud_importacion_partidas WHERE id_solicitud = ?",
|
||
[ $id_solicitud ]
|
||
);
|
||
if ($del === false) {
|
||
die("❌ Error borrando partidas previas: " . print_r(sqlsrv_errors(), true));
|
||
}
|
||
|
||
// 8) Reinsertar partidas desde el formulario
|
||
if (!empty($_POST['partidas']) && is_array($_POST['partidas'])) {
|
||
$sqlP = "
|
||
INSERT INTO dbo.solicitud_importacion_partidas
|
||
(id_solicitud, descripcion, cantidad_comercial, cantidad_tarifa,
|
||
valor_factura, peso_bruto, unidad_comercial_id, tasa_preferencial)
|
||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||
";
|
||
foreach ($_POST['partidas'] as $i => $p) {
|
||
$desc = trim($p['descripcion'] ?? '');
|
||
$cantCom = floatval($p['cantidad_comercial'] ?? 0);
|
||
$cantTar = floatval($p['cantidad_tarifa'] ?? 0);
|
||
$valPart = floatval($p['valor_factura'] ?? 0);
|
||
$peso = floatval($p['peso_bruto'] ?? 0);
|
||
$umId = intval($p['unidad_comercial_id'] ?? 0) ?: null;
|
||
$tasaPref = trim($p['tasa_preferencial'] ?? '');
|
||
|
||
// Sólo inserta si descripción y cantidad comercial válidos
|
||
if ($desc !== '' && $cantCom > 0) {
|
||
$paramsP = [
|
||
$id_solicitud,
|
||
$desc,
|
||
$cantCom,
|
||
$cantTar,
|
||
$valPart,
|
||
$peso,
|
||
$umId,
|
||
$tasaPref
|
||
];
|
||
$stmtP = sqlsrv_query($conn, $sqlP, $paramsP);
|
||
if ($stmtP === false) {
|
||
die("❌ Error insertando partida #$i: " . print_r(sqlsrv_errors(), true));
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
// 9) Redirigir
|
||
header('Location: /IMPORTADORES/solicitud_importacion/lista?updated=ok');
|
||
exit;
|
||
}
|
||
|
||
|
||
/** “Soft-delete” de una factura **/
|
||
function eliminar() {
|
||
if (!($_SESSION['usuario_id'] ?? false)) { header('Location: /IMPORTADORES/login'); exit; }
|
||
$id=(int)($_GET['id']??0);
|
||
$conn=getConnection();
|
||
sqlsrv_query($conn,"UPDATE dbo.solicitud_importacion_factura SET status=0,updated_at=GETDATE() WHERE id_solicitud=? AND id_importador=?",[$id,$_SESSION['usuario_id']]);
|
||
header('Location: /IMPORTADORES/solicitud_importacion/lista?deleted=ok'); exit;
|
||
}
|
||
|
||
/** GET /IMPORTADORES/solicitud_importacion/ajax_proveedores
|
||
* Devuelve JSON para poblar el select de Proveedor **/
|
||
function ajax_proveedores()
|
||
{
|
||
// 1) Asegura que la respuesta sea JSON
|
||
header('Content-Type: application/json; charset=utf-8');
|
||
|
||
// 2) Obtén o renueva tu token (usa tu función existente)
|
||
$token = getApiToken();
|
||
if (!$token) {
|
||
echo json_encode(['results' => []]);
|
||
return;
|
||
}
|
||
|
||
// 3) Llama al endpoint de la API de proveedores
|
||
$apiBase = rtrim($_ENV['API_URL'] ?? '', '/');
|
||
$url = $apiBase . '/proveedores';
|
||
|
||
$ch = curl_init($url);
|
||
curl_setopt_array($ch, [
|
||
CURLOPT_HTTPHEADER => ["Authorization: $token", 'Accept: application/json'],
|
||
CURLOPT_RETURNTRANSFER => true,
|
||
CURLOPT_TIMEOUT => 5,
|
||
]);
|
||
$resp = curl_exec($ch);
|
||
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||
curl_close($ch);
|
||
|
||
// 4) Parsear y transformar al formato { results: [ {id,text}, … ] }
|
||
$out = ['results' => []];
|
||
if ($status === 200 && ($json = json_decode($resp, true)) && is_array($json)) {
|
||
foreach ($json as $p) {
|
||
$clave = $p['Clave'] ?? '';
|
||
$nombre = $p['Nombre'] ?? '';
|
||
$out['results'][] = [
|
||
'id' => $clave,
|
||
'text' => "[$clave] - $nombre"
|
||
];
|
||
}
|
||
}
|
||
|
||
// 5) Devolver JSON
|
||
echo json_encode($out);
|
||
exit;
|
||
}
|
||
|
||
function ajax_lista()
|
||
{
|
||
// 1) Fijamos el header JSON
|
||
header('Content-Type: application/json; charset=utf-8');
|
||
|
||
// 2) Obtener o renovar token
|
||
$token = getApiToken();
|
||
if (!$token) {
|
||
error_log('[ajax_lista] Sin token válido');
|
||
// Devolvemos estructura vacía
|
||
echo json_encode(['data' => []]);
|
||
return;
|
||
}
|
||
|
||
// 3) Construimos la URL de la API
|
||
$apiBase = rtrim($_ENV['API_URL'] ?? '', '/');
|
||
$url = $apiBase . '/proveedores';
|
||
error_log("[ajax_lista] GET $url");
|
||
|
||
// 4) Ejecutamos cURL
|
||
$ch = curl_init($url);
|
||
curl_setopt_array($ch, [
|
||
CURLOPT_HTTPHEADER => ["Authorization: $token", 'Accept: application/json'],
|
||
CURLOPT_RETURNTRANSFER => true,
|
||
CURLOPT_TIMEOUT => 5,
|
||
]);
|
||
$resp = curl_exec($ch);
|
||
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||
curl_close($ch);
|
||
|
||
error_log("[ajax_lista] HTTP $status → $resp");
|
||
|
||
// 5) Parseamos y formateamos
|
||
$dataList = [];
|
||
if ($status === 200 && ($json = json_decode($resp, true)) && is_array($json)) {
|
||
foreach ($json as $p) {
|
||
$clave = htmlspecialchars($p['Clave'] ?? '', ENT_QUOTES);
|
||
$dataList[] = [
|
||
$clave,
|
||
htmlspecialchars($p['Nombre'] ?? '', ENT_QUOTES),
|
||
htmlspecialchars($p['RFC'] ?? '', ENT_QUOTES),
|
||
htmlspecialchars($p['Ciudad'] ?? '', ENT_QUOTES),
|
||
htmlspecialchars($p['Telefono']?? '', ENT_QUOTES),
|
||
// Acciones
|
||
"<a href=\"/IMPORTADORES/proveedores/editar?clave=" . rawurlencode($clave) . "\" class=\"btn btn-sm btn-primary\">✏️</a>
|
||
<button class=\"btn btn-sm btn-danger\" onclick=\"confirmDelete('{$clave}')\">🗑️</button>"
|
||
];
|
||
}
|
||
} else {
|
||
error_log('[ajax_lista] Respuesta inválida o status != 200');
|
||
}
|
||
|
||
// 6) Devolvemos siempre HTTP 200 con data (posiblemente vacío)
|
||
echo json_encode(['data' => $dataList]);
|
||
}
|
||
|
||
function update_status() {
|
||
|
||
header('Content-Type: application/json; charset=utf-8');
|
||
if (!($_SESSION['usuario_id'] ?? false)) {
|
||
http_response_code(401);
|
||
echo json_encode(['error'=>'No autorizado']);
|
||
exit;
|
||
}
|
||
$id = intval($_POST['id'] ?? 0);
|
||
$status = intval($_POST['status'] ?? 0);
|
||
$conn = getConnection();
|
||
$sql = "UPDATE dbo.solicitud_importacion_factura
|
||
SET status=?
|
||
WHERE id_solicitud=? AND id_importador=?";
|
||
$params = [$status, $id, $_SESSION['usuario_id']];
|
||
$stmt = sqlsrv_query($conn, $sql, $params);
|
||
if ($stmt === false) {
|
||
http_response_code(500);
|
||
echo json_encode(['error'=>'Error al actualizar status']);
|
||
exit;
|
||
}
|
||
echo json_encode(['success'=>true]);
|
||
exit;
|
||
}
|
||
|
||
function pdf() {
|
||
// Verificar que se recibió el ID
|
||
if (!isset($_GET['id'])) {
|
||
http_response_code(400);
|
||
echo "ID de solicitud requerido";
|
||
return;
|
||
}
|
||
|
||
$id_solicitud = (int)$_GET['id'];
|
||
|
||
try {
|
||
// 1. Conexión
|
||
$conn = getConnection();
|
||
|
||
// 2. Obtener datos de la solicitud principal
|
||
$sql = "
|
||
SELECT
|
||
s.*,
|
||
i.nombre as importador_nombre,
|
||
i.rfc as importador_rfc,
|
||
i.calle,
|
||
i.num_exterior,
|
||
i.num_interior,
|
||
i.ciudad,
|
||
i.colonia,
|
||
i.codigo_postal,
|
||
i.estado,
|
||
i.telefono,
|
||
i.correo,
|
||
t.nombre as transportista_nombre,
|
||
c.nombre as chofer_nombre
|
||
FROM solicitud_importacion_factura s
|
||
LEFT JOIN informacion_general i ON s.id_importador = i.id_usuario
|
||
LEFT JOIN transportistas t ON s.transportista_id = t.id_transportista
|
||
LEFT JOIN choferes c ON s.chofer_id = c.id_chofer
|
||
WHERE s.id_solicitud = ?
|
||
";
|
||
|
||
$params = array($id_solicitud);
|
||
$stmt = sqlsrv_query($conn, $sql, $params);
|
||
|
||
if ($stmt === false) {
|
||
throw new Exception("Error en la consulta: " . print_r(sqlsrv_errors(), true));
|
||
}
|
||
|
||
$solicitud = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
|
||
sqlsrv_free_stmt($stmt);
|
||
|
||
if (!$solicitud) {
|
||
http_response_code(404);
|
||
echo "Solicitud no encontrada";
|
||
return;
|
||
}
|
||
|
||
// 3. Obtener partidas de la solicitud
|
||
$sql = "
|
||
SELECT
|
||
p.*,
|
||
u.descripcion as unidad_descripcion
|
||
FROM solicitud_importacion_partidas p
|
||
LEFT JOIN unidades_medida_apendice7 u ON p.unidad_comercial_id = u.id
|
||
WHERE p.id_solicitud = ?
|
||
ORDER BY p.id_partida
|
||
";
|
||
|
||
$params = array($id_solicitud);
|
||
$stmt = sqlsrv_query($conn, $sql, $params);
|
||
|
||
if ($stmt === false) {
|
||
throw new Exception("Error en la consulta de partidas: " . print_r(sqlsrv_errors(), true));
|
||
}
|
||
|
||
$partidas = array();
|
||
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
|
||
$partidas[] = $row;
|
||
}
|
||
sqlsrv_free_stmt($stmt);
|
||
|
||
// 4. Configuración del sistema
|
||
global $config;
|
||
$nombre_sistema = $config['nombre_plataforma'] ?? 'Sistema Integral para Importadores de Hidrocarburos';
|
||
$siglas = $config['siglas'] ?? 'SIIH';
|
||
$logo_url = $config['logo_url'] ?? 'assets/img/logo_siih.png';
|
||
|
||
// 5. Generar HTML del PDF
|
||
$html = generarHTMLPDF($solicitud, $partidas, $nombre_sistema, $siglas, $logo_url);
|
||
|
||
// 6. Configurar headers para PDF
|
||
header('Content-Type: application/pdf');
|
||
header('Content-Disposition: inline; filename="solicitud_importacion_' . $id_solicitud . '.pdf"');
|
||
|
||
// 7. Generar PDF usando DomPDF
|
||
// Opción 1: DomPDF v0.8.x (compatible con PHP 5.x)
|
||
if (file_exists('lib/dompdf/dompdf-0.8.6/dompdf_config.inc.php')) {
|
||
require_once 'lib/dompdf/dompdf-0.8.6/dompdf_config.inc.php';
|
||
|
||
$dompdf = new DOMPDF();
|
||
$dompdf->load_html($html);
|
||
$dompdf->set_paper('A4', 'portrait');
|
||
$dompdf->render();
|
||
|
||
// Headers
|
||
header('Content-Type: application/pdf');
|
||
header('Content-Disposition: inline; filename="solicitud_importacion_' . $id_solicitud . '.pdf"');
|
||
|
||
echo $dompdf->output();
|
||
|
||
// Opción 2: DomPDF v1.x/2.x (PHP 7+)
|
||
} elseif (file_exists('vendor/autoload.php') && PHP_VERSION_ID >= 70000) {
|
||
require_once 'vendor/autoload.php';
|
||
|
||
$options = new \Dompdf\Options();
|
||
$options->set('defaultFont', 'Arial');
|
||
$options->set('isRemoteEnabled', true);
|
||
|
||
$dompdf = new \Dompdf\Dompdf($options);
|
||
$dompdf->loadHtml($html);
|
||
$dompdf->setPaper('A4', 'portrait');
|
||
$dompdf->render();
|
||
|
||
header('Content-Type: application/pdf');
|
||
header('Content-Disposition: inline; filename="solicitud_importacion_' . $id_solicitud . '.pdf"');
|
||
|
||
echo $dompdf->output();
|
||
|
||
// Opción 3: Alternativa usando mPDF (compatible con PHP 5.6+)
|
||
} elseif (file_exists('lib/mpdf/mpdf.php')) {
|
||
require_once 'lib/mpdf/mpdf.php';
|
||
|
||
$mpdf = new mPDF();
|
||
$mpdf->WriteHTML($html);
|
||
$mpdf->Output('solicitud_importacion_' . $id_solicitud . '.pdf', 'I');
|
||
|
||
// Opción 4: TCPDF (muy compatible)
|
||
} elseif (file_exists('lib/tcpdf/tcpdf.php')) {
|
||
require_once 'lib/tcpdf/tcpdf.php';
|
||
|
||
$pdf = new TCPDF();
|
||
$pdf->AddPage();
|
||
$pdf->writeHTML($html, true, false, true, false, '');
|
||
$pdf->Output('solicitud_importacion_' . $id_solicitud . '.pdf', 'I');
|
||
|
||
} else {
|
||
throw new Exception("No hay librerías PDF disponibles. Instala DomPDF, mPDF o TCPDF.");
|
||
}
|
||
|
||
} catch (Exception $e) {
|
||
error_log("Error generando PDF: " . $e->getMessage());
|
||
http_response_code(500);
|
||
echo "Error interno del servidor: " . $e->getMessage();
|
||
}
|
||
}
|
||
|
||
function generarHTMLPDF($solicitud, $partidas, $nombre_sistema, $siglas, $logo_url) {
|
||
// Formatear fecha
|
||
$fecha_expedicion = date('d/m/Y');
|
||
$fecha_factura = $solicitud['fecha_factura']->format('d/m/Y');
|
||
$fecha_vencimiento = (clone $solicitud['fecha_factura'])->modify('+30 days')->format('d/m/Y');
|
||
|
||
|
||
// Construir dirección del importador
|
||
$direccion_completa = trim(
|
||
($solicitud['calle'] ?? '') . ' ' .
|
||
($solicitud['num_exterior'] ?? '') . ' ' .
|
||
($solicitud['num_interior'] ? 'Int. ' . $solicitud['num_interior'] : '') . ', ' .
|
||
($solicitud['colonia'] ?? '') . ', ' .
|
||
($solicitud['ciudad'] ?? '') . ', ' .
|
||
($solicitud['estado'] ?? '') . ' ' .
|
||
($solicitud['codigo_postal'] ?? '')
|
||
);
|
||
|
||
// Calcular totales
|
||
$subtotal = 0;
|
||
foreach ($partidas as $partida) {
|
||
$subtotal += (float)$partida['valor_factura'];
|
||
}
|
||
$descuento_pct = 0; // Puedes calcularlo si tienes descuentos
|
||
$descuento = $subtotal * ($descuento_pct / 100);
|
||
$total = $subtotal - $descuento;
|
||
|
||
$html = '
|
||
<!DOCTYPE html>
|
||
<html>
|
||
<head>
|
||
<meta charset="UTF-8">
|
||
<title>Solicitud de Importación</title>
|
||
<style>
|
||
body { font-family: Arial, sans-serif; font-size: 9px; margin: 0; padding: 15px; line-height: 1.2; }
|
||
.header { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 10px; border-bottom: 2px solid #000; padding-bottom: 10px; }
|
||
.logo-section { width: 120px; }
|
||
.logo { max-width: 100px; height: auto; }
|
||
.company-info { flex: 1; text-align: center; margin: 0 20px; }
|
||
.company-name { font-weight: bold; font-size: 12px; margin-bottom: 3px; }
|
||
.invoice-info { width: 180px; border: 1px solid #000; padding: 8px; }
|
||
.invoice-title { background-color: #f0f0f0; text-align: center; font-weight: bold; margin-bottom: 5px; padding: 3px; }
|
||
.info-section { display: flex; margin-bottom: 15px; }
|
||
.client-info, .dates-info { flex: 1; border: 1px solid #000; margin-right: 10px; padding: 8px; }
|
||
.dates-info { margin-right: 0; width: 200px; }
|
||
.section-title { background-color: #d0d0d0; font-weight: bold; padding: 3px; margin-bottom: 5px; text-align: center; }
|
||
.products-table { width: 100%; border-collapse: collapse; margin-bottom: 15px; border: 1px solid #000; }
|
||
.products-table th,
|
||
.products-table td { border: 1px solid #000; padding: 4px; text-align: left; font-size: 8px; }
|
||
.products-table th { background-color: #f0f0f0; font-weight: bold; text-align: center; }
|
||
.text-center { text-align: center; }
|
||
.text-right { text-align: right; }
|
||
.font-bold { font-weight: bold; }
|
||
.totals-section { float: right; width: 250px; margin-top: 10px; }
|
||
.total-row { display: flex; justify-content: space-between; margin-bottom: 3px; }
|
||
.footer-info { clear: both; margin-top: 30px; font-size: 8px; background-color: #e0e0e0; padding: 5px; text-align: center; }
|
||
</style>
|
||
</head>
|
||
<body>
|
||
<!-- ENCABEZADO -->
|
||
<div class="header">
|
||
<div class="logo-section">
|
||
<img src="' . htmlspecialchars($logo_url) . '" alt="Logo" class="logo">
|
||
<div style="font-size: 8px; margin-top: 5px;">' . htmlspecialchars($siglas) . '</div>
|
||
</div>
|
||
|
||
<div class="company-info">
|
||
<div class="company-name">' . htmlspecialchars($nombre_sistema) . '</div>
|
||
<div>' . htmlspecialchars($direccion_completa ?: 'Dirección no disponible') . '</div>
|
||
<div>RFC: ' . htmlspecialchars($solicitud['importador_rfc'] ?? 'No disponible') . '</div>
|
||
<div>Tel: ' . htmlspecialchars($solicitud['telefono'] ?? 'No disponible') . '</div>
|
||
<div>Email: ' . htmlspecialchars($solicitud['correo'] ?? 'No disponible') . '</div>
|
||
</div>
|
||
|
||
<div class="invoice-info">
|
||
<div class="invoice-title">Solicitud de Importación</div>
|
||
<div><strong>No. ' . htmlspecialchars($solicitud['id_solicitud']) . '</strong></div>
|
||
<div>Régimen simplificado de confianza (RESICO) - 626</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- INFORMACIÓN DEL CLIENTE Y FECHAS -->
|
||
<div class="info-section">
|
||
<div class="client-info">
|
||
<div class="section-title">RAZÓN SOCIAL / ' . htmlspecialchars($solicitud['importador_nombre'] ?? 'No disponible') . '</div>
|
||
<div><strong>DOMICILIO FISCAL:</strong> ' . htmlspecialchars($direccion_completa) . '</div>
|
||
<div style="margin-top: 10px;">
|
||
<div><strong>RFC:</strong> ' . htmlspecialchars($solicitud['importador_rfc'] ?? 'No disponible') . '</div>
|
||
<div><strong>TELÉFONO:</strong> ' . htmlspecialchars($solicitud['telefono'] ?? 'No disponible') . '</div>
|
||
</div>
|
||
<div style="margin-top: 10px;">
|
||
<div><strong>RÉGIMEN FISCAL:</strong> 601-General de Ley Personas Morales</div>
|
||
</div>
|
||
</div>
|
||
|
||
<div class="dates-info">
|
||
<div class="section-title">FECHA DE EXPEDICIÓN</div>
|
||
<div class="text-center font-bold" style="font-size: 12px;">' . $fecha_expedicion . '</div>
|
||
<div class="section-title" style="margin-top: 10px;">FECHA DE VENCIMIENTO</div>
|
||
<div class="text-center">' . $fecha_vencimiento . '</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- TABLA DE PRODUCTOS/PARTIDAS -->
|
||
<table class="products-table">
|
||
<thead>
|
||
<tr>
|
||
<th>Producto</th>
|
||
<th>Unidad de Medida</th>
|
||
<th>Precio Unitario</th>
|
||
<th>Cantidad</th>
|
||
<th>Descuento</th>
|
||
<th>Total</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody>';
|
||
|
||
// Agregar partidas
|
||
foreach ($partidas as $partida) {
|
||
$precio_unitario = (float)($partida['precio_unitario'] ?? 0);
|
||
$cantidad = (float)($partida['cantidad_comercial'] ?? 0);
|
||
$valor_partida = (float)($partida['valor_factura'] ?? 0);
|
||
|
||
$html .= '<tr>
|
||
<td>' . htmlspecialchars($partida['descripcion']) . '</td>
|
||
<td>' . htmlspecialchars($partida['unidad_descripcion'] ?? 'Unidad de servicio (E48)') . '</td>
|
||
<td class="text-right">$' . number_format($precio_unitario > 0 ? $precio_unitario : $valor_partida, 2) . '</td>
|
||
<td class="text-center">' . number_format($cantidad > 0 ? $cantidad : 1, 0) . '</td>
|
||
<td class="text-right">' . number_format($descuento_pct, 1) . '%</td>
|
||
<td class="text-right">$' . number_format($valor_partida, 2) . '</td>
|
||
</tr>';
|
||
}
|
||
|
||
$html .= '
|
||
</tbody>
|
||
</table>
|
||
|
||
<!-- TOTALES -->
|
||
<div class="totals-section">
|
||
<div class="total-row">
|
||
<span><strong>Total:</strong></span>
|
||
<span><strong>$' . number_format($total, 2) . '</strong></span>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- NOTA INFERIOR -->
|
||
<div class="footer-note">
|
||
Veinticinco mil seiscientos 50/100 M.N
|
||
</div>
|
||
|
||
</body>
|
||
</html>';
|
||
|
||
return $html;
|
||
} |