This commit is contained in:
2025-06-05 08:23:52 -06:00
5 changed files with 226 additions and 9 deletions

2
.env
View File

@@ -1,4 +1,4 @@
DB_HOST=DESKTOP-22T88B6 DB_HOST=localhost
DB_DATABASE=Importaciones_HC DB_DATABASE=Importaciones_HC
DB_USERNAME=sa DB_USERNAME=sa
DB_PASSWORD=Soluciones01 DB_PASSWORD=Soluciones01

View File

@@ -774,16 +774,20 @@ function ajax_lista()
} }
function update_status() { function update_status() {
header('Content-Type: application/json; charset=utf-8'); header('Content-Type: application/json; charset=utf-8');
if (!($_SESSION['usuario_id'] ?? false)) { if (!($_SESSION['usuario_id'] ?? false)) {
http_response_code(401); http_response_code(401);
echo json_encode(['error'=>'No autorizado']); echo json_encode(['error' => 'No autorizado']);
exit; exit;
} }
$id = intval($_POST['id'] ?? 0); $id = intval($_POST['id'] ?? 0);
$status = intval($_POST['status'] ?? 0); $status = intval($_POST['status'] ?? 0);
// 1) Conexión a la BD
$conn = getConnection(); $conn = getConnection();
// 2) Actualizar el status en la tabla solicitud_importacion_factura
$sql = "UPDATE dbo.solicitud_importacion_factura $sql = "UPDATE dbo.solicitud_importacion_factura
SET status=? SET status=?
WHERE id_solicitud=? AND id_importador=?"; WHERE id_solicitud=? AND id_importador=?";
@@ -791,13 +795,202 @@ function update_status() {
$stmt = sqlsrv_query($conn, $sql, $params); $stmt = sqlsrv_query($conn, $sql, $params);
if ($stmt === false) { if ($stmt === false) {
http_response_code(500); http_response_code(500);
echo json_encode(['error'=>'Error al actualizar status']); echo json_encode(['error' => 'Error al actualizar status']);
exit; exit;
} }
echo json_encode(['success'=>true]);
// 3) Si el status actualizado es 2, hacer POST a /pedimentos/crearPedimento
if ($status === 2) {
// 3.1) Obtener o renovar el token de la API
$token = getApiToken();
if (!$token) {
error_log("[update_status] No se pudo obtener token para crearPedimento");
// Podemos optar por responder con éxito local y solo loguear el error:
echo json_encode(['success' => true, 'warning' => 'No se generó pedimento: sin token']);
exit;
}
// 3.2) Leer de la BD todos los campos de la cabecera de la solicitud
$sqlSel = "
SELECT
s.id_solicitud,
s.id_importador,
s.aduana,
s.numero_pedimento,
s.anexo22_apendice,
s.numero_factura,
s.fecha_factura,
s.incoterm,
s.pais_proveedor,
s.tipo_moneda,
s.valor_factura,
s.vinculacion,
s.transportista_id,
s.chofer_id,
s.foto_solicitud_url,
s.proveedor_clave,
s.created_at,
s.updated_at
-- Si existe columna patente agréga aquí:
, s.patente
FROM dbo.solicitud_importacion_factura s
WHERE s.id_solicitud = ? AND s.id_importador = ?
";
$stmtSel = sqlsrv_query($conn, $sqlSel, [$id, $_SESSION['usuario_id']]);
if ($stmtSel === false) {
error_log("[update_status] Error al consultar solicitud: " . print_r(sqlsrv_errors(), true));
echo json_encode(['success' => true, 'warning' => 'Status actualizado, fallo al leer datos para pedimento']);
exit;
}
$solicitud = sqlsrv_fetch_array($stmtSel, SQLSRV_FETCH_ASSOC);
sqlsrv_free_stmt($stmtSel);
if (!$solicitud) {
error_log("[update_status] No se encontró la solicitud para id={$id}");
echo json_encode(['success' => true, 'warning' => 'Status actualizado, solicitud no encontrada para pedimento']);
exit;
}
// 3.3) Formatear fechas (si vienen como DateTime) antes de construir JSON
// La API espera "YYYY-MM-DD" para fecha_factura y tipo ISO 8601 para created_at/updated_at.
$fechaFactura = null;
if ($solicitud['fecha_factura'] instanceof DateTime) {
$fechaFactura = $solicitud['fecha_factura']->format('Y-m-d');
} else {
$fechaFactura = $solicitud['fecha_factura']; // en caso de que ya venga como string
}
$createdAt = null;
if ($solicitud['created_at'] instanceof DateTime) {
// Por ejemplo: "2025-05-16T07:48:15"
$createdAt = $solicitud['created_at']->format('Y-m-d\TH:i:s');
} else {
$createdAt = $solicitud['created_at'];
}
$updatedAt = null;
if ($solicitud['updated_at'] instanceof DateTime) {
$updatedAt = $solicitud['updated_at']->format('Y-m-d\TH:i:s');
} else {
$updatedAt = $solicitud['updated_at'];
}
// 3.4) Obtener todas las partidas asociadas a esta solicitud
$sqlPart = "
SELECT
p.id_partida,
p.id_solicitud,
p.descripcion,
p.creado_en,
p.cantidad_comercial,
p.cantidad_tarifa,
p.valor_factura,
p.peso_bruto,
p.unidad_comercial_id,
p.tasa_preferencial
FROM dbo.solicitud_importacion_partidas p
WHERE p.id_solicitud = ?
ORDER BY p.id_partida
";
$stmtPart = sqlsrv_query($conn, $sqlPart, [$id]);
if ($stmtPart === false) {
error_log("[update_status] Error al consultar partidas: " . print_r(sqlsrv_errors(), true));
echo json_encode(['success' => true, 'warning' => 'Status actualizado, fallo al leer partidas para pedimento']);
exit;
}
$partidas = [];
while ($row = sqlsrv_fetch_array($stmtPart, SQLSRV_FETCH_ASSOC)) {
// Formatear creado_en si es DateTime
if ($row['creado_en'] instanceof DateTime) {
$row['creado_en'] = $row['creado_en']->format('Y-m-d\TH:i:s');
}
// Asegurarnos de que los valores numéricos sean del tipo correcto
$row['cantidad_comercial'] = floatval($row['cantidad_comercial']);
$row['cantidad_tarifa'] = floatval($row['cantidad_tarifa']);
$row['valor_factura'] = floatval($row['valor_factura']);
$row['peso_bruto'] = floatval($row['peso_bruto']);
$row['unidad_comercial_id']= intval($row['unidad_comercial_id']);
$partidas[] = $row;
}
sqlsrv_free_stmt($stmtPart);
// 3.5) Construir el arreglo PHP con la misma estructura JSON que envías
$payload = [
"id_solicitud" => intval($solicitud['id_solicitud']),
"id_importador" => intval($solicitud['id_importador']),
"aduana" => strval($solicitud['aduana']),
// Si en tu tabla tienes “patente”, la incluyes; si no, puedes dejar cadena vacía o null
"patente" => isset($solicitud['patente']) ? strval($solicitud['patente']) : "",
"anexo22_apendice" => strval($solicitud['anexo22_apendice']),
"numero_factura" => strval($solicitud['numero_factura']),
"fecha_factura" => $fechaFactura,
// Si tu tabla tiene columna "numero_pedimento", úsala directamente
"numero_pedimento" => isset($solicitud['numero_pedimento'])
? strval($solicitud['numero_pedimento'])
: "",
"incoterm" => strval($solicitud['incoterm']),
"pais_proveedor" => strval($solicitud['pais_proveedor']),
"tipo_moneda" => strval($solicitud['tipo_moneda']),
"valor_factura" => floatval($solicitud['valor_factura']),
"vinculacion" => intval($solicitud['vinculacion']),
"transportista_id" => intval($solicitud['transportista_id']),
"status" => intval($solicitud['status']), // =2
"created_at" => $createdAt,
"updated_at" => $updatedAt,
// Si en BD se usa “transporte_id” en lugar de “transportista_id”, ajústalo. Aquí lo ponemos null si no existe.
"transporte_id" => null,
"chofer_id" => intval($solicitud['chofer_id']),
"foto_solicitud_url"=> strval($solicitud['foto_solicitud_url']),
"proveedor_clave" => strval($solicitud['proveedor_clave']),
"partidas" => $partidas
];
// 3.6) Convertir a JSON
$jsonPayload = json_encode($payload);
// 3.7) Preparar cURL para hacer POST a /pedimentos/crearPedimento
$apiBase = rtrim($_ENV['API_URL'] ?? '', '/');
$urlPed = $apiBase . '/pedimentos/crearPedimento';
$ch = curl_init($urlPed);
curl_setopt_array($ch, [
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_HTTPHEADER => [
"Authorization: $token",
'Content-Type: application/json'
],
CURLOPT_POSTFIELDS => $jsonPayload,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 10,
]);
$respPed = curl_exec($ch);
$httpPed = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlErr = curl_error($ch);
curl_close($ch);
// 3.8) Verificar respuesta del endpoint pedimentos
if ($httpPed === 201 || $httpPed === 200) {
// Suponiendo que el endpoint devuelve 201 o 200 cuando se crea correctamente
error_log("[update_status] Pedimento creado con éxito para solicitud $id → HTTP $httpPed$respPed");
echo json_encode(['success' => true, 'pedimento' => json_decode($respPed, true)]);
exit;
} else {
error_log("[update_status] Error al crear pedimento (HTTP $httpPed): $respPed · cURL error: $curlErr");
// Devolvemos estado local ok, pero avisamos que falló el POST
echo json_encode([
'success' => true,
'warning' => "Status actualizado, pero fallo al crear pedimento (HTTP $httpPed)"
]);
exit;
}
}
// 4) Si el status no es 2, devolvemos normal
echo json_encode(['success' => true]);
exit; exit;
} }
// Función para generar el PDF // Función para generar el PDF
use Dompdf\Dompdf; use Dompdf\Dompdf;
use Dompdf\Options; use Dompdf\Options;

Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

View File

@@ -0,0 +1,14 @@
Numero de asunto,Descripci<EFBFBD>n del Asunto,Estatus,
T2025-04-090,LOGIN REGISTRO Y HOME DE PLATAFORMA DE IMPORTADORES,SE DEVUELVE,
T2025-04-102,SPRINT 2 CATALOGOS DE TRANSPORTES TRANSPORTISTAS SOLICITUDES DE IMPORTACIONES BITACORAS Y COMPLETARDASHBOARD DEL IMPORTADOR,SE DEVUELVE,
T2025-05-022,se solicita aplicar al home registro y login validaciones de informacion y seguridad en el front y back (controladores),EN PROGRA,
T2025-05-025,agregar catalogo de proveedores,EN PROGRA,
T2025-05-031,ALTA DE IMPORTADORES EN PLATAFORMA Y EN SISTEMA WINSAAI ESCRITORIO,EN PROGRA,
T2025-05-042,"CREACION DE UN ""<EFBFBD>OLVIDASTE CONTRASE<53>A?"" CON SU FUNCI<43>N PARA QUE EL USUARIO PUEDA REESTABLECER SU COMTRASE<53>A DE FORMA AUTONOMA DEBE LLEGARLE UN CORREO ELECTRONICO CON UN CODIGO EL CUAL SE DEBEA ALMACENAR TEMPORALMENTE POR UN TIEMPO DETERMINADO PARA QUE EL USUARIO GENERE EL CAMBIO ASI MISMO SE TIENEN QUE CREAR LAS VISTAS PARA INGRESAR EL CODIGO Y TODAS LAS NECESARIAS PARA ESTE PROCESO",EXITOSO,
T2025-05-082,PANEL DE CONFIGURACION DE PLATAFORMA HIDROCARBUROS OPCION DE INSERTAR EDITAR LA INFORMACION FALTANTE DEL CLIENTE PARA QUE SE ALMACENE EN LA TABLA CREADA informacion_general,,
T2025-05-083,VISTA DE PROVEEDORES AGREGAR FILTROS Y AGREAR LA DIRECCION ASI MISMO EN LA SOLICIUTUD DE IMPORTACION QUE SE VEA LA CLAVE DEL PROVEEDOR,,
T2025-05-084,MODULO DE EXPEDIENTE ELECTRONICO PARA LOS IMPORTADORES LA AGENCIA ADUANAL LO TRANSMITIRA POR UN CANAL DE SUBIDA SEGURO,,
T2025-05-091,MODULO DE SEGURIDAD 1 AGREGAR CORREOS EXTRA PARA NOTIFICACIONES 2 CORREO EXTRA PARA RECUPERACION DE CUENTA 3 PARAMENTRO DE AUTENTICACION DE 2 FACTORES SI ESTA ACTIVO DEBE PEDIR UN CODIGO CADA VEZ QUE HAGA LOGIN EL IMPORTADOR,,
T2025-05-092,EN EL MODULO DE BITACORAS AGREGAR LAS VISTAS DE LA BITACORA DE ACCESOS A LA PLATAFORMA DE LA TABLA: bitacora_login posteriormente habra mas bitacoras asi que agregar un card que sea de bitacora de accesos y al clickearlo se abra ahora si la vista con la bitacora debe incluir filtros y buscador,,
T2025-05-109,AGREGAR NOTIFICACIONES EN EL MODULO DE PREFERENCIAS QUE SE ACTIVEN / DESACTIVEN EN TIEMPO REAL A SELECCION DEL USUARIO AGREGAR LOS CAMPOS NECESARIOS PARA QUE SE ALMACENE HORARIOS QUE PREFIERA PARA LAS QUE APLIQUE Tipos de notificaciones del sistemaCreaci<63>n de nuevas solicitudes de importaci<63>n Notificaci<63>n inmediata al registrar una solicitud Cambio de estado de solicitudes de importaci<63>n Al modificarse el estatus de cualquier solicitud Resumen diario de solicitudes de importaci<63>n Env<6E>o de un reporte diario en el horario que elija el usuario Alertas por tiempo excedido en estados cr<63>ticos Notificaci<63>n cuando una solicitud permanezca m<>s tiempo del definido por el usuario en los estados 1 2 3 o 4 Incorporaci<63>n de documentos al expediente electr<74>nico Aviso al agregarse nuevos archivos o documentos al expediente de una solicitud Intentos fallidos de acceso: alerta al tercer intento de inicio de sesi<73>n con credenciales incorrectas Bloqueo de cuenta: notificaci<63>n al bloquearse la cuenta por superar el n<>mero m<>ximo de intentos fallidos,,
T2025-05-117,ENDPOINT PARA CREAR PEDIMENTOS EN WINSAAI DESDE PLATAFORMA SIIH,,
1 Numero de asunto Descripción del Asunto Estatus
2 T2025-04-090 LOGIN REGISTRO Y HOME DE PLATAFORMA DE IMPORTADORES SE DEVUELVE
3 T2025-04-102 SPRINT 2 CATALOGOS DE TRANSPORTES TRANSPORTISTAS SOLICITUDES DE IMPORTACIONES BITACORAS Y COMPLETARDASHBOARD DEL IMPORTADOR SE DEVUELVE
4 T2025-05-022 se solicita aplicar al home registro y login validaciones de informacion y seguridad en el front y back (controladores) EN PROGRA
5 T2025-05-025 agregar catalogo de proveedores EN PROGRA
6 T2025-05-031 ALTA DE IMPORTADORES EN PLATAFORMA Y EN SISTEMA WINSAAI ESCRITORIO EN PROGRA
7 T2025-05-042 CREACION DE UN "¿OLVIDASTE CONTRASEÑA?" CON SU FUNCIÓN PARA QUE EL USUARIO PUEDA REESTABLECER SU COMTRASEÑA DE FORMA AUTONOMA DEBE LLEGARLE UN CORREO ELECTRONICO CON UN CODIGO EL CUAL SE DEBEA ALMACENAR TEMPORALMENTE POR UN TIEMPO DETERMINADO PARA QUE EL USUARIO GENERE EL CAMBIO ASI MISMO SE TIENEN QUE CREAR LAS VISTAS PARA INGRESAR EL CODIGO Y TODAS LAS NECESARIAS PARA ESTE PROCESO EXITOSO
8 T2025-05-082 PANEL DE CONFIGURACION DE PLATAFORMA HIDROCARBUROS OPCION DE INSERTAR EDITAR LA INFORMACION FALTANTE DEL CLIENTE PARA QUE SE ALMACENE EN LA TABLA CREADA informacion_general
9 T2025-05-083 VISTA DE PROVEEDORES AGREGAR FILTROS Y AGREAR LA DIRECCION ASI MISMO EN LA SOLICIUTUD DE IMPORTACION QUE SE VEA LA CLAVE DEL PROVEEDOR
10 T2025-05-084 MODULO DE EXPEDIENTE ELECTRONICO PARA LOS IMPORTADORES LA AGENCIA ADUANAL LO TRANSMITIRA POR UN CANAL DE SUBIDA SEGURO
11 T2025-05-091 MODULO DE SEGURIDAD 1 AGREGAR CORREOS EXTRA PARA NOTIFICACIONES 2 CORREO EXTRA PARA RECUPERACION DE CUENTA 3 PARAMENTRO DE AUTENTICACION DE 2 FACTORES SI ESTA ACTIVO DEBE PEDIR UN CODIGO CADA VEZ QUE HAGA LOGIN EL IMPORTADOR
12 T2025-05-092 EN EL MODULO DE BITACORAS AGREGAR LAS VISTAS DE LA BITACORA DE ACCESOS A LA PLATAFORMA DE LA TABLA: bitacora_login posteriormente habra mas bitacoras asi que agregar un card que sea de bitacora de accesos y al clickearlo se abra ahora si la vista con la bitacora debe incluir filtros y buscador
13 T2025-05-109 AGREGAR NOTIFICACIONES EN EL MODULO DE PREFERENCIAS QUE SE ACTIVEN / DESACTIVEN EN TIEMPO REAL A SELECCION DEL USUARIO AGREGAR LOS CAMPOS NECESARIOS PARA QUE SE ALMACENE HORARIOS QUE PREFIERA PARA LAS QUE APLIQUE Tipos de notificaciones del sistemaCreación de nuevas solicitudes de importación Notificación inmediata al registrar una solicitud Cambio de estado de solicitudes de importación Al modificarse el estatus de cualquier solicitud Resumen diario de solicitudes de importación Envío de un reporte diario en el horario que elija el usuario Alertas por tiempo excedido en estados críticos Notificación cuando una solicitud permanezca más tiempo del definido por el usuario en los estados 1 2 3 o 4 Incorporación de documentos al expediente electrónico Aviso al agregarse nuevos archivos o documentos al expediente de una solicitud Intentos fallidos de acceso: alerta al tercer intento de inicio de sesión con credenciales incorrectas Bloqueo de cuenta: notificación al bloquearse la cuenta por superar el número máximo de intentos fallidos
14 T2025-05-117 ENDPOINT PARA CREAR PEDIMENTOS EN WINSAAI DESDE PLATAFORMA SIIH

View File

@@ -0,0 +1,10 @@
clave_identificador,nombre,rfc,curp,telefono,caat,pais_id,estado_id,ciudad_id,domicilio
1012,"SERVICIOS Y SOLUCIONES,TRANSPORTE LOGISTIC",SYP141574IS5,,6566198524,2CTU,MEXICO,HIDALGO,ACTOPAN,ENCINO 1708-9
1013,,OPQ145210IS6,,6566198525,3KSS,MEXICO,GUANAJUATO,LE<EFBFBD>N,BOTTEGHELLE # 2611 CANTO DE CALABRIA C.P. 38524
1014,,RHG153021IS7,,4196198526,34,MEXICO,GUADALAJARA,JALISCO,MADAGASCAR 77844 COL. OASIS
1015,,KLM257412IS8,,6566198527,6732,MEXICO,CHIHUAHUA,CUAUHTEMOC,SAN CARLOS 87-13 PASEO DE SANTA MONICA 32742
1016,,HJN4251854IS9,,6566198528,2YRI,MEXICO,BAJA CALIFORNIA,TIJUANA,"C. WATERFILL No. 520, COL. RIO BRAVO., C.P. 32553"
1017,,ERV147774IS10,,9586198529,2NJR,MEXICO,DURANGO,DURANGO,"REGION LOMBARDIA No. 1966, INT. 2. JARDINES DE SAN FELIPE, C.P. 32875"
1018,,LMK145574IS11,,7856198530,3101,MEXICO,CHIHUAHUA,CHIHUAHUA,VENUSTIANO CARRANZA 462 COL. NAMIQUIPA C.P. 32577
1019,,AQG141587IS12,,6566198531,1747,MEXICO,ZACATECAS,ZACATECAS,"CARRETERA MONTERREY MONCLOVA KM. 8.3 S/N, CENTRO GENERAL ARTEMIO, C.P. 66077"
1020,,KMV171594IS13,,6566198532,4305,MEXICO,CHIHUAHUA,JUAREZ,ECONOMIA 206 COLONIA OLGA MARIA CP 34889
1 clave_identificador nombre rfc curp telefono caat pais_id estado_id ciudad_id domicilio
2 1012 SERVICIOS Y SOLUCIONES,TRANSPORTE LOGISTIC SYP141574IS5 6566198524 2CTU MEXICO HIDALGO ACTOPAN ENCINO 1708-9
3 1013 OPQ145210IS6 6566198525 3KSS MEXICO GUANAJUATO LEÓN BOTTEGHELLE # 2611 CANTO DE CALABRIA C.P. 38524
4 1014 RHG153021IS7 4196198526 34 MEXICO GUADALAJARA JALISCO MADAGASCAR 77844 COL. OASIS
5 1015 KLM257412IS8 6566198527 6732 MEXICO CHIHUAHUA CUAUHTEMOC SAN CARLOS 87-13 PASEO DE SANTA MONICA 32742
6 1016 HJN4251854IS9 6566198528 2YRI MEXICO BAJA CALIFORNIA TIJUANA C. WATERFILL No. 520, COL. RIO BRAVO., C.P. 32553
7 1017 ERV147774IS10 9586198529 2NJR MEXICO DURANGO DURANGO REGION LOMBARDIA No. 1966, INT. 2. JARDINES DE SAN FELIPE, C.P. 32875
8 1018 LMK145574IS11 7856198530 3101 MEXICO CHIHUAHUA CHIHUAHUA VENUSTIANO CARRANZA 462 COL. NAMIQUIPA C.P. 32577
9 1019 AQG141587IS12 6566198531 1747 MEXICO ZACATECAS ZACATECAS CARRETERA MONTERREY MONCLOVA KM. 8.3 S/N, CENTRO GENERAL ARTEMIO, C.P. 66077
10 1020 KMV171594IS13 6566198532 4305 MEXICO CHIHUAHUA JUAREZ ECONOMIA 206 COLONIA OLGA MARIA CP 34889