solicitudes impo
This commit is contained in:
@@ -559,7 +559,7 @@ function actualizar() {
|
|||||||
$vinculacion = $_POST['vinculacion'] ?? 0;
|
$vinculacion = $_POST['vinculacion'] ?? 0;
|
||||||
$transportista_id = (int)($_POST['transportista_id'] ?? 0);
|
$transportista_id = (int)($_POST['transportista_id'] ?? 0);
|
||||||
$chofer_id = (int)($_POST['chofer_id'] ?? 0);
|
$chofer_id = (int)($_POST['chofer_id'] ?? 0);
|
||||||
$status = isset($_POST['status']) ? 1 : 0;
|
$status = isset($_POST['status']) ?? 1;
|
||||||
|
|
||||||
// 5) Validar obligatorios
|
// 5) Validar obligatorios
|
||||||
if (empty($num_factura) || empty($fecha) || $transportista_id <= 0 || $chofer_id <= 0) {
|
if (empty($num_factura) || empty($fecha) || $transportista_id <= 0 || $chofer_id <= 0) {
|
||||||
@@ -674,6 +674,136 @@ function eliminar() {
|
|||||||
header('Location: /IMPORTADORES/solicitud_importacion/lista?deleted=ok'); exit;
|
header('Location: /IMPORTADORES/solicitud_importacion/lista?deleted=ok'); exit;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
function actualizar_masivo() {
|
||||||
|
header('Content-Type: application/json; charset=utf-8');
|
||||||
|
|
||||||
|
if (!($_SESSION['usuario_id'] ?? false)) {
|
||||||
|
http_response_code(401);
|
||||||
|
echo json_encode(['success' => false, 'error' => 'No autorizado']);
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
|
||||||
|
http_response_code(405);
|
||||||
|
echo json_encode(['success' => false, 'error' => 'Método no permitido']);
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
|
$ids = $_POST['ids'] ?? [];
|
||||||
|
$status = (int) ($_POST['status'] ?? 0);
|
||||||
|
|
||||||
|
if (empty($ids) || !is_array($ids)) {
|
||||||
|
echo json_encode(['success' => false, 'error' => 'No se recibieron solicitudes']);
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
|
$conn = getConnection();
|
||||||
|
$usuarioId = $_SESSION['usuario_id'];
|
||||||
|
$token = ($status === 2) ? getApiToken() : null;
|
||||||
|
|
||||||
|
$actualizadas = 0;
|
||||||
|
$fallidas = [];
|
||||||
|
$pedimentosGenerados = [];
|
||||||
|
|
||||||
|
foreach ($ids as $id) {
|
||||||
|
$id = (int)$id;
|
||||||
|
|
||||||
|
// 1. Actualizar el status
|
||||||
|
$sql = "UPDATE dbo.solicitud_importacion_factura SET status = ? WHERE id_solicitud = ? AND id_importador = ?";
|
||||||
|
$stmt = sqlsrv_query($conn, $sql, [$status, $id, $usuarioId]);
|
||||||
|
|
||||||
|
if ($stmt === false) {
|
||||||
|
$fallidas[] = $id;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$actualizadas++;
|
||||||
|
|
||||||
|
// 2. Si el status es 2, generar pedimento
|
||||||
|
if ($status === 2 && $token) {
|
||||||
|
$res = generarPedimentoDesdeSolicitud($conn, $id, $usuarioId, $token);
|
||||||
|
if ($res['success']) {
|
||||||
|
$pedimentosGenerados[$id] = $res['numeroPedimento'] ?? null;
|
||||||
|
} else {
|
||||||
|
error_log("[actualizar_masivo] Error en pedimento solicitud $id: {$res['error']}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
echo json_encode([
|
||||||
|
'success' => true,
|
||||||
|
'actualizadas' => $actualizadas,
|
||||||
|
'fallidas' => $fallidas,
|
||||||
|
'pedimentos' => $pedimentosGenerados
|
||||||
|
]);
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
|
function generarPedimentoDesdeSolicitud($conn, $id, $usuarioId, $token) {
|
||||||
|
try {
|
||||||
|
// Consulta solicitud
|
||||||
|
$sqlSel = "SELECT *, '9999' as patente FROM dbo.solicitud_importacion_factura WHERE id_solicitud = ? AND id_importador = ?";
|
||||||
|
$stmtSel = sqlsrv_query($conn, $sqlSel, [$id, $usuarioId]);
|
||||||
|
$solicitud = sqlsrv_fetch_array($stmtSel, SQLSRV_FETCH_ASSOC);
|
||||||
|
if (!$solicitud) return ['success' => false, 'error' => 'Solicitud no encontrada'];
|
||||||
|
|
||||||
|
// Fechas
|
||||||
|
$solicitud['fecha_factura'] = $solicitud['fecha_factura'] instanceof DateTime ? $solicitud['fecha_factura']->format('Y-m-d') : $solicitud['fecha_factura'];
|
||||||
|
$solicitud['created_at'] = $solicitud['created_at'] instanceof DateTime ? $solicitud['created_at']->format('Y-m-d\TH:i:s') : $solicitud['created_at'];
|
||||||
|
$solicitud['updated_at'] = $solicitud['updated_at'] instanceof DateTime ? $solicitud['updated_at']->format('Y-m-d\TH:i:s') : $solicitud['updated_at'];
|
||||||
|
|
||||||
|
// Partidas
|
||||||
|
$partidas = [];
|
||||||
|
$stmtPart = sqlsrv_query($conn, "SELECT * FROM dbo.solicitud_importacion_partidas WHERE id_solicitud = ?", [$id]);
|
||||||
|
while ($p = sqlsrv_fetch_array($stmtPart, SQLSRV_FETCH_ASSOC)) {
|
||||||
|
if ($p['creado_en'] instanceof DateTime) $p['creado_en'] = $p['creado_en']->format('Y-m-d\TH:i:s');
|
||||||
|
$p['cantidad_comercial'] = (float)$p['cantidad_comercial'];
|
||||||
|
$p['cantidad_tarifa'] = (float)$p['cantidad_tarifa'];
|
||||||
|
$p['valor_factura'] = (float)$p['valor_factura'];
|
||||||
|
$p['peso_bruto'] = (float)$p['peso_bruto'];
|
||||||
|
$p['unidad_comercial_id'] = (int)$p['unidad_comercial_id'];
|
||||||
|
$partidas[] = $p;
|
||||||
|
}
|
||||||
|
|
||||||
|
$solicitud['numero_pedimento'] = "";
|
||||||
|
$solicitud['transporte_id'] = null;
|
||||||
|
$solicitud['partidas'] = $partidas;
|
||||||
|
|
||||||
|
$jsonPayload = json_encode($solicitud);
|
||||||
|
$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);
|
||||||
|
curl_close($ch);
|
||||||
|
|
||||||
|
if ($httpPed === 200 || $httpPed === 201) {
|
||||||
|
$decoded = json_decode($respPed, true);
|
||||||
|
if (isset($decoded['pedimento']['PEDIMENTO'])) {
|
||||||
|
$numeroPed = $decoded['pedimento']['PEDIMENTO'];
|
||||||
|
sqlsrv_query($conn, "UPDATE dbo.solicitud_importacion_factura SET numero_pedimento = ? WHERE id_solicitud = ?", [$numeroPed, $id]);
|
||||||
|
return ['success' => true, 'numeroPedimento' => $numeroPed];
|
||||||
|
}
|
||||||
|
return ['success' => false, 'error' => 'Respuesta inválida de API'];
|
||||||
|
}
|
||||||
|
|
||||||
|
return ['success' => false, 'error' => "HTTP $httpPed"];
|
||||||
|
|
||||||
|
} catch (Exception $e) {
|
||||||
|
return ['success' => false, 'error' => $e->getMessage()];
|
||||||
|
}
|
||||||
|
}
|
||||||
/** GET /IMPORTADORES/solicitud_importacion/ajax_proveedores
|
/** GET /IMPORTADORES/solicitud_importacion/ajax_proveedores
|
||||||
* Devuelve JSON para poblar el select de Proveedor **/
|
* Devuelve JSON para poblar el select de Proveedor **/
|
||||||
function ajax_proveedores()
|
function ajax_proveedores()
|
||||||
@@ -1120,7 +1250,7 @@ function update_status() {
|
|||||||
error_log("[update_status] Error al crear pedimento (HTTP $httpPed): $respPed · cURL error: $curlErr");
|
error_log("[update_status] Error al crear pedimento (HTTP $httpPed): $respPed · cURL error: $curlErr");
|
||||||
echo json_encode([
|
echo json_encode([
|
||||||
'success' => true,
|
'success' => true,
|
||||||
'warning' => "Status actualizado, pero fallo al crear pedimento (HTTP $httpPed)"
|
'warning' => "Status actualizado, pero fallo al crear pedimento (HTTP $respPed)"
|
||||||
]);
|
]);
|
||||||
exit;
|
exit;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -233,7 +233,7 @@
|
|||||||
|
|
||||||
<!-- Activo -->
|
<!-- Activo -->
|
||||||
<div class="form-check mb-4">
|
<div class="form-check mb-4">
|
||||||
<input id="status" value=1 name="status" type="checkbox" class="hide form-check-input" <?= $factura['status']==1?'checked':'' ?>>
|
<input id="status" value=1 name="status" type="hidden" <?= $factura['status']==1?'checked':'' ?>>
|
||||||
<label for="status" class="hide form-check-label">Activo</label>
|
<label for="status" class="hide form-check-label">Activo</label>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@@ -41,11 +41,14 @@
|
|||||||
<div class="content">
|
<div class="content">
|
||||||
<h4>📄 Solicitudes de Importación</h4>
|
<h4>📄 Solicitudes de Importación</h4>
|
||||||
<a href="/IMPORTADORES/solicitud_importacion/crear" class="btn btn-success mb-3">➕ Nueva Solicitud</a>
|
<a href="/IMPORTADORES/solicitud_importacion/crear" class="btn btn-success mb-3">➕ Nueva Solicitud</a>
|
||||||
|
<button class="btn btn-warning mb-3" id="btn-solicitar-masivo">🚚 Solicitar Importación Masiva</button>
|
||||||
|
|
||||||
<div class="card p-3 shadow-sm">
|
<div class="card p-3 shadow-sm">
|
||||||
<div class="table-responsive">
|
<div class="table-responsive">
|
||||||
<table class="table table-striped" id="tabla-solicitudes">
|
<table class="table table-striped" id="tabla-solicitudes">
|
||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
|
<th><input type="checkbox" id="select-all"></th>
|
||||||
<th>#</th>
|
<th>#</th>
|
||||||
<th>Factura</th>
|
<th>Factura</th>
|
||||||
<th>Fecha</th>
|
<th>Fecha</th>
|
||||||
@@ -65,6 +68,9 @@
|
|||||||
<tbody>
|
<tbody>
|
||||||
<?php foreach($facturas as $f): ?>
|
<?php foreach($facturas as $f): ?>
|
||||||
<tr>
|
<tr>
|
||||||
|
<td>
|
||||||
|
<input type="checkbox" class="select-solicitud" value="<?= $f['id_solicitud'] ?>">
|
||||||
|
</td>
|
||||||
<td><?= $f['id_solicitud'] ?></td>
|
<td><?= $f['id_solicitud'] ?></td>
|
||||||
<td><?= htmlspecialchars($f['numero_factura']) ?></td>
|
<td><?= htmlspecialchars($f['numero_factura']) ?></td>
|
||||||
<td><?= htmlspecialchars($f['fecha_factura']) ?></td>
|
<td><?= htmlspecialchars($f['fecha_factura']) ?></td>
|
||||||
@@ -332,8 +338,59 @@
|
|||||||
<?php elseif(isset($_GET['created'])): ?>
|
<?php elseif(isset($_GET['created'])): ?>
|
||||||
Swal.fire('¡Listo!','Solicitud creada.','success');
|
Swal.fire('¡Listo!','Solicitud creada.','success');
|
||||||
<?php elseif(isset($_GET['updated'])): ?>
|
<?php elseif(isset($_GET['updated'])): ?>
|
||||||
Swal.fire('¡Listo!','Solicitud actualizada.','success');
|
Swal.fire('¡Listo!','Solicitud actualizada. El estatus actual cambio a en proceso. ','success');
|
||||||
<?php endif; ?>
|
<?php endif; ?>
|
||||||
|
|
||||||
|
|
||||||
|
// Marcar o desmarcar todos
|
||||||
|
$('#select-all').on('change', function () {
|
||||||
|
$('.select-solicitud').prop('checked', this.checked);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Acción masiva
|
||||||
|
$('#btn-solicitar-masivo').on('click', function () {
|
||||||
|
const selected = $('.select-solicitud:checked').map(function () {
|
||||||
|
return $(this).val();
|
||||||
|
}).get();
|
||||||
|
|
||||||
|
if (selected.length === 0) {
|
||||||
|
Swal.fire('Sin selección', 'Selecciona al menos una solicitud.', 'info');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
Swal.fire({
|
||||||
|
title: `¿Solicitar importación para ${selected.length} solicitudes?`,
|
||||||
|
text: 'Se actualizará el estatus a "Solicitar importación" (2)',
|
||||||
|
icon: 'warning',
|
||||||
|
showCancelButton: true,
|
||||||
|
confirmButtonText: 'Sí, proceder',
|
||||||
|
cancelButtonText: 'Cancelar'
|
||||||
|
}).then(result => {
|
||||||
|
if (result.isConfirmed) {
|
||||||
|
$.ajax({
|
||||||
|
url: '/IMPORTADORES/solicitud_importacion/actualizar_masivo',
|
||||||
|
method: 'POST',
|
||||||
|
data: { ids: selected, status: 2 },
|
||||||
|
dataType: 'json',
|
||||||
|
success: function (res) {
|
||||||
|
if (res.success) {
|
||||||
|
Swal.fire('¡Hecho!', `${res.actualizadas} solicitudes actualizadas.`, 'success')
|
||||||
|
.then(() => location.reload());
|
||||||
|
} else {
|
||||||
|
Swal.fire('Error', res.error || 'No se pudieron actualizar.', 'error');
|
||||||
|
}
|
||||||
|
},
|
||||||
|
error: function () {
|
||||||
|
Swal.fire('Error', 'No se pudo contactar al servidor.', 'error');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user