908 lines
39 KiB
PHP
908 lines
39 KiB
PHP
<?php include __DIR__ . '/../partials/sidebar_importador.php'; ?>
|
||
|
||
<!DOCTYPE html>
|
||
<html lang="es">
|
||
<head>
|
||
<meta charset="UTF-8">
|
||
<title>➕ Nueva Solicitud de Importación</title>
|
||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
|
||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/choices.js/public/assets/styles/choices.min.css"/>
|
||
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
|
||
<link href="https://cdn.datatables.net/1.13.4/css/jquery.dataTables.min.css" rel="stylesheet">
|
||
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
|
||
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
|
||
<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
|
||
<!-- Font Awesome -->
|
||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
|
||
<!-- Animate.css para animaciones adicionales -->
|
||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css">
|
||
<style>
|
||
body { font-family: 'Segoe UI', sans-serif; background-color: #f4f6f9; }
|
||
.sidebar { width: 220px; height: 100vh; background-color: #343a40; position: fixed; top: 0; left: 0; padding-top: 56px; z-index: 1040; }
|
||
.sidebar .nav-link { font-weight: bold; color: white; transition: all 0.3s ease; }
|
||
.sidebar .nav-link:hover, .sidebar .nav-link.active { background-color: #495057; color: #fff; }
|
||
.content { margin-top: 56px; padding: 40px 20px; position: relative; z-index: 1; background-color: #f4f6f9; transition: margin-left 0.3s ease; }
|
||
@media (min-width: 768px) { .content { margin-left: 250px; } }
|
||
@media (max-width: 767.98px) {
|
||
.content { margin-left: 0; }
|
||
.sidebar .nav-link { font-weight: normal; color: #343a40; background-color: transparent; }
|
||
.sidebar .nav-link:hover, .sidebar .nav-link.active { background-color: #e9ecef; color: #212529; }
|
||
}
|
||
.card { border-radius: 12px; }
|
||
/* Animaciones personalizadas */
|
||
.card-hover { transition: all 0.3s ease; cursor: pointer; }
|
||
.card-hover:hover { transform: translateY(-8px) scale(1.02); box-shadow: 0 1rem 2rem rgba(0, 0, 0, 0.15) !important; }
|
||
.btn-pulse { animation: pulse 2s infinite; }
|
||
@keyframes pulse {
|
||
0% { transform: scale(1); }
|
||
50% { transform: scale(1.05); }
|
||
100% { transform: scale(1); }
|
||
}
|
||
.fade-in-up { animation: fadeInUp 0.8s ease-out; }
|
||
@keyframes fadeInUp {
|
||
from { opacity: 0; transform: translateY(30px); }
|
||
to { opacity: 1; transform: translateY(0); }
|
||
}
|
||
/* Responsive animations */
|
||
@media (max-width: 768px) { .card-hover:hover { transform: translateY(-4px) scale(1.01); } }
|
||
/* Efecto de glow para elementos activos */
|
||
.btn.active { box-shadow: 0 0 20px rgba(var(--bs-primary-rgb), 0.5); }
|
||
/* Animación para el título */
|
||
.title-glow { text-shadow: 0 0 10px rgba(0, 123, 255, 0.3); }
|
||
/* Efecto para botones */
|
||
.btn-animated { transition: all 0.3s ease; position: relative; overflow: hidden; }
|
||
.btn-animated:hover { transform: translateY(-2px); box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2); }
|
||
.btn-animated::before { content: ''; position: absolute; top: 0; left: -100%; width: 100%; height: 100%;
|
||
background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent); transition: left 0.5s; }
|
||
.btn-animated:hover::before { left: 100%; }
|
||
.hide { display: none !important; }
|
||
.alert { top: 75px; left: 275px; right: 50px; position: fixed; z-index: 1050; width: calc(100% - 285px); }
|
||
/* ========== ANIMACIONES PARA INPUTS TEXTO ========== */
|
||
.form-control:not(.no-animation) { transition: all 0.3s ease; border: 2px solid #dee2e6; position: relative; }
|
||
.form-control:not(.no-animation).shake { animation: shake 0.5s ease-in-out; }
|
||
@keyframes shake {
|
||
0%, 100% { transform: translateX(0); }
|
||
25% { transform: translateX(-5px); }
|
||
75% { transform: translateX(5px); }
|
||
}
|
||
/* Animación para los campos del formulario */
|
||
.form-group-animated { opacity: 0; transform: translateY(20px); animation: slideUp 0.6s ease-out forwards; }
|
||
.form-group-animated:nth-child(1) { animation-delay: 0.1s; }
|
||
.form-group-animated:nth-child(2) { animation-delay: 0.2s; }
|
||
.form-group-animated:nth-child(3) { animation-delay: 0.3s; }
|
||
.form-group-animated:nth-child(4) { animation-delay: 0.4s; }
|
||
.form-group-animated:nth-child(5) { animation-delay: 0.5s; }
|
||
.form-group-animated:nth-child(6) { animation-delay: 0.6s; }
|
||
.form-group-animated:nth-child(7) { animation-delay: 0.7s; }
|
||
.form-group-animated:nth-child(8) { animation-delay: 0.8s; }
|
||
.form-group-animated:nth-child(9) { animation-delay: 0.9s; }
|
||
.form-group-animated:nth-child(10) { animation-delay: 1.0s; }
|
||
@keyframes slideUp { to { opacity: 1; transform: translateY(0); } }
|
||
/* Estilos para las sugerencias de autocompletado */
|
||
#global-autocomplete-suggestions { box-shadow: 0 4px 12px rgba(0,0,0,0.15) !important; border: 1px solid #dee2e6 !important; width: calc(100% - 30px) !important; /* Ajusta según el padding de tu contenedor */ }
|
||
#global-autocomplete-suggestions .autocomplete-item { transition: background-color 0.15s ease; }
|
||
#global-autocomplete-suggestions .autocomplete-item:hover,
|
||
#global-autocomplete-suggestions .autocomplete-item.active { background-color: #f8f9fa !important; }
|
||
#global-autocomplete-suggestions .autocomplete-item:last-child { border-bottom: none; }
|
||
/* Estilos para validación */
|
||
.choices.required .choices__inner { border: 1px solid #ced4da; }
|
||
.choices.is-invalid .choices__inner { border: 1px solid #dc3545; background-color: #fff5f5; }
|
||
.choices.is-valid .choices__inner { border: 1px solid #28a745; background-color: #f5fff5; }
|
||
.choices__input { opacity: 1 !important; }
|
||
</style>
|
||
</head>
|
||
<body>
|
||
|
||
<?php if (!isset($_SESSION['id_agencia_en_uso']) || !$_SESSION['id_agencia_en_uso']): ?>
|
||
<div class="container mt-4">
|
||
<div class="row">
|
||
<div class="col-12">
|
||
<div class="alert alert-warning mt-4">
|
||
<h5>⚠️ No tienes una agencia activa vinculada.</h5>
|
||
<p>Para poder gestionar tus solicitudes de importación, primero debes <strong>vincularte a una agencia</strong>.</p>
|
||
<a href="/IMPORTADORES/vinculaciones/nuevaVinculacion" class="btn btn-primary btn-animated">Ir a Vinculaciones</a>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<?php return; ?>
|
||
<?php endif; ?>
|
||
|
||
<div class="content">
|
||
<h4 class="mb-4 animate__animated animate__fadeInDown title_glow">➕ Nueva Solicitud de Importación</h4>
|
||
<div class="card p-4 bg-white shadow-sm card-hover position-relative h-auto fade-in-up">
|
||
<form id="solicitudForm" action="/IMPORTADORES/solicitud_importacion/guardar" method="POST" enctype="multipart/form-data">
|
||
|
||
<!-- Sección principal -->
|
||
<div class="row">
|
||
<div class="col-md-3 mb-3 form-group-animated">
|
||
<label for="numero_factura" class="form-label">Número de Factura</label>
|
||
<input id="numero_factura" name="numero_factura" type="text" class="form-control" required>
|
||
</div>
|
||
|
||
<div class="col-md-3 mb-3 form-group-animated">
|
||
<label for="fecha_factura" class="form-label">Fecha de Factura</label>
|
||
<input id="fecha_factura" name="fecha_factura" type="date" class="form-control" required>
|
||
</div>
|
||
|
||
<div class="col-md-3 mb-3">
|
||
<label for="proveedor_id" class="form-label">Proveedor</label>
|
||
<select id="proveedor_id" name="proveedor_id" class="form-select searchable" data-required="true" required>
|
||
<option value="">Cargando proveedores…</option>
|
||
</select>
|
||
</div>
|
||
|
||
<div class="col-md-3 mb-3">
|
||
<label for="anexo22_apendice" class="form-label">Anexo 22 – Apéndice</label>
|
||
<select id="anexo22_apendice" name="anexo22_apendice" class="form-select searchable" data-required="true" required>
|
||
<option value="">-- Selecciona Aduana --</option>
|
||
<?php foreach($aduanas as $a): ?>
|
||
<option value="<?= htmlspecialchars($a['aduana_seccion']) ?>">
|
||
<?= htmlspecialchars($a['aduana_seccion'].' – '.$a['nombre']) ?>
|
||
</option>
|
||
<?php endforeach; ?>
|
||
</select>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Segunda fila: Patente, Incoterm, País, Moneda -->
|
||
<div class="row">
|
||
<div class="col-md-3 mb-3">
|
||
<label for="patente" class="form-label">Patente Aduanal</label>
|
||
<select id="patente" name="patente" class="form-select searchable" data-required="true" required>
|
||
<option value="">-- Selecciona Patente --</option>
|
||
<?php foreach($patentes as $pt): ?>
|
||
<option value="<?= htmlspecialchars($pt['id_agente']) ?>">
|
||
<?= htmlspecialchars($pt['patente'].' - '.$pt['agente_aduanal']) ?>
|
||
</option>
|
||
<?php endforeach; ?>
|
||
</select>
|
||
</div>
|
||
|
||
<div class="col-md-3 mb-3">
|
||
<label for="incoterm" class="form-label">INCOTERM</label>
|
||
<select id="incoterm" name="incoterm" class="form-select searchable" data-required="true" required>
|
||
<option value="">-- Selecciona Incoterm --</option>
|
||
<?php foreach($incoterms as $inc): ?>
|
||
<option value="<?= htmlspecialchars($inc['INCOTERM']) ?>">
|
||
<?= htmlspecialchars($inc['INCOTERM'].' - '.$inc['DESCESPANOL']) ?>
|
||
</option>
|
||
<?php endforeach; ?>
|
||
</select>
|
||
</div>
|
||
|
||
<div class="col-md-3 mb-3">
|
||
<label for="pais_proveedor" class="form-label">País (Proveedor)</label>
|
||
<select id="pais_proveedor" name="pais_proveedor" class="form-select searchable" data-required="true" required>
|
||
<option value="">-- Selecciona País --</option>
|
||
<?php foreach($paises as $p): ?>
|
||
<option value="<?= htmlspecialchars($p['id_pais']) ?>"><?= htmlspecialchars($p['nombre']) ?></option>
|
||
<?php endforeach; ?>
|
||
</select>
|
||
</div>
|
||
|
||
<div class="col-md-3 mb-3">
|
||
<label for="tipo_moneda" class="form-label">Moneda</label>
|
||
<select id="tipo_moneda" name="tipo_moneda" class="form-select searchable" data-required="true" required>
|
||
<?php foreach(['MXN'=>'Peso Mexicano','USD'=>'Dólar USD','EUR'=>'Euro','CNY'=>'Yuan','GBP'=>'Libra GBP','JPY'=>'Yen'] as $code=>$label): ?>
|
||
<option value="<?= $code ?>"><?= "$label ($code)" ?></option>
|
||
<?php endforeach; ?>
|
||
</select>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Valor y vinculación -->
|
||
<div class="row">
|
||
<div class="col-md-8 mb-3 form-group-animated">
|
||
<label for="valor_factura" class="form-label">Valor Factura</label>
|
||
<input id="valor_factura" name="valor_factura" type="number" step="0.01" min="0" class="form-control" required>
|
||
</div>
|
||
|
||
<div class="col-md-4 mb-3">
|
||
<label for="vinculacion" class="form-label">Vinculación</label>
|
||
<select id="vinculacion" name="vinculacion" class="form-select searchable" data-required="true" required>
|
||
<option value="0">No existe</option>
|
||
<option value="1">Existe, no afecta</option>
|
||
<option value="2">Existe y afecta</option>
|
||
</select>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Transportista, Chofer, Foto Solicitud -->
|
||
<div class="row">
|
||
<div class="col-md-4 mb-3">
|
||
<label for="transportista_id" class="form-label">Transportista</label>
|
||
<select id="transportista_id" name="transportista_id" class="form-select searchable" data-required="true" required>
|
||
<option value="">-- Selecciona --</option>
|
||
<?php foreach($transportistas as $t): ?>
|
||
<option value="<?= htmlspecialchars($t['id_transportista']) ?>">
|
||
<?= htmlspecialchars($t['clave_identificador'] . ' - ' . $t['nombre']) ?>
|
||
</option>
|
||
<?php endforeach; ?>
|
||
</select>
|
||
</div>
|
||
|
||
<div class="col-md-4 mb-3">
|
||
<label for="chofer_id" class="form-label">Chofer</label>
|
||
<select id="chofer_id" name="chofer_id" class="form-select searchable" data-required="true" required>
|
||
<option value="">-- Selecciona Chofer --</option>
|
||
<?php foreach($choferes as $c): ?>
|
||
<option value="<?= htmlspecialchars($c['id_chofer']) ?>">
|
||
<?= htmlspecialchars($c['nombre']) ?>
|
||
</option>
|
||
<?php endforeach; ?>
|
||
</select>
|
||
</div>
|
||
|
||
<div class="col-md-4 mb-3 form-group-animated">
|
||
<label for="foto_solicitud" class="form-label">Foto de la Carga (PIPA)</label>
|
||
<input id="foto_solicitud" name="foto_solicitud" type="file" class="form-control" accept="image/*">
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Partidas dinámicas -->
|
||
<hr>
|
||
<h5 class="form-group-animated">📦 Partidas</h5>
|
||
<div class="table-responsive">
|
||
<table class="table table-sm form-group-animated" id="tabla-partidas">
|
||
<thead>
|
||
<tr>
|
||
<th>Descripción</th>
|
||
<th>Cantidad Comercial</th>
|
||
<th>Cantidad de Tarifa</th>
|
||
<th>Unidad Comercial</th>
|
||
<th>Valor Factura</th>
|
||
<th>Peso Bruto</th>
|
||
<th>Tasa Preferencial</th>
|
||
<th class="hide">Precio Unitario</th>
|
||
<th class="hide">OMA (Factura)</th>
|
||
<th></th>
|
||
</tr>
|
||
</thead>
|
||
<tbody>
|
||
<tr>
|
||
<td>
|
||
<div class="position-relative">
|
||
<input name="partidas[0][descripcion]" class="form-control w-auto descripcion-input" required autocomplete="off">
|
||
</div>
|
||
</td>
|
||
<td><input name="partidas[0][cantidad_comercial]" type="number" step="0.0001" class="form-control w-auto" min="0" required></td>
|
||
<td><input name="partidas[0][cantidad_tarifa]" type="number" step="0.0001" class="form-control w-auto" min="0" required></td>
|
||
<td>
|
||
<div class="mb-3">
|
||
<select name="partidas[0][unidad_comercial_id]" class="form-select searchable" data-required="true" required>
|
||
<option value="">-- Unidad --</option>
|
||
<?php foreach($unidades_medida as $um): ?>
|
||
<option value="<?= htmlspecialchars($um['id']) ?>"><?= htmlspecialchars($um['descripcion']) ?></option>
|
||
<?php endforeach; ?>
|
||
</select>
|
||
</div>
|
||
</td>
|
||
<td><input name="partidas[0][valor_factura]" type="number" step="0.01" class="form-control valor-partida w-auto" min="0" required></td>
|
||
<td><input name="partidas[0][peso_bruto]" type="number" step="0.0001" class="form-control w-auto" min="0" required></td>
|
||
<td>
|
||
<div class="mb-3">
|
||
<select name="partidas[0][tasa_preferencial]" class="form-select searchable" data-required="true" required>
|
||
<option value="">-- Selecciona --</option>
|
||
<option>General</option>
|
||
<option>TLC</option>
|
||
<option>PROSEC</option>
|
||
<option>ALADI</option>
|
||
<option>COMERCIALIZADORA</option>
|
||
</select>
|
||
</div>
|
||
</td>
|
||
<td class="hide"><input name="partidas[0][precio_unitario]" type="number" class="form-control w-auto"></td>
|
||
<td class="hide"><input name="partidas[0][oma_factura]" class="form-control w-auto"></td>
|
||
<td><button type="button" class="btn btn-danger btn-sm remove-row mt-auto w-auto btn-animated">✖️</button></td>
|
||
</tr>
|
||
</tbody>
|
||
</table>
|
||
</div>
|
||
<div class="form-group-animated">
|
||
<button type="button" class="btn btn-secondary btn-sm mt-auto w-auto btn-animated" id="add-partida">➕ Agregar partida</button>
|
||
</div>
|
||
|
||
<!-- Activo -->
|
||
<div class="form-check mt-4">
|
||
<input id="status" name="status" type="checkbox" class="hide form-check-input" checked>
|
||
<label for="status" class="hide form-check-label">Activo</label>
|
||
</div>
|
||
|
||
<!-- Botones finales -->
|
||
<div class="text-end mt-4 form-group-animated">
|
||
<button type="submit" class="btn btn-success mt-3 mt-auto w-auto btn-animated">Guardar</button>
|
||
<a href="/IMPORTADORES/solicitud_importacion/lista" class="btn btn-secondary mt-3 ms-2 mt-auto w-auto btn-animated">Cancelar</a>
|
||
</div>
|
||
</form>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Choices.js JS -->
|
||
<script src="https://cdn.jsdelivr.net/npm/choices.js/public/assets/scripts/choices.min.js"></script>
|
||
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
|
||
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0/dist/js/select2.min.js"></script>
|
||
|
||
<script>
|
||
function safeInitializeChoices(element) {
|
||
if (!element._choices) {
|
||
const isRequired = element.hasAttribute('required');
|
||
if (isRequired) {
|
||
element.removeAttribute('required');
|
||
element.setAttribute('data-required', 'true');
|
||
}
|
||
|
||
element._choices = new Choices(element, {
|
||
searchEnabled: true,
|
||
itemSelectText: '',
|
||
shouldSort: false,
|
||
silent: true
|
||
});
|
||
|
||
if (isRequired) {
|
||
const container = element.closest('.choices');
|
||
if (container) { container.classList.add('required'); }
|
||
element.addEventListener('change', validateChoice.bind(null, element));
|
||
}
|
||
}
|
||
}
|
||
|
||
document.addEventListener('DOMContentLoaded', () => {
|
||
// Primero cargamos proveedores, luego inicializamos Choices en todos los selects
|
||
cargarProveedores().then(() => { document.querySelectorAll('.searchable').forEach(safeInitializeChoices); });
|
||
|
||
// Inicializamos los eventos adicionales
|
||
inicializarEventos();
|
||
});
|
||
|
||
// Función para cargar proveedores (retorna promesa)
|
||
function cargarProveedores() {
|
||
const proveedorEl = document.getElementById('proveedor_id');
|
||
|
||
return fetch('/IMPORTADORES/solicitud_importacion/ajax_proveedores')
|
||
.then(res => {
|
||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||
return res.json();
|
||
})
|
||
.then(json => {
|
||
proveedorEl.innerHTML = '<option value="">-- Selecciona Proveedor --</option>';
|
||
json.results.forEach(item => {
|
||
const opt = document.createElement('option');
|
||
opt.value = item.id;
|
||
opt.textContent = item.text;
|
||
proveedorEl.appendChild(opt);
|
||
});
|
||
})
|
||
.catch(err => {
|
||
console.error('❌ Error cargando proveedores:', err);
|
||
proveedorEl.innerHTML = '<option value="">Error cargando proveedores</option>';
|
||
});
|
||
}
|
||
|
||
// Inicializamos Choices globalmente (todos los .searchable)
|
||
function inicializarChoicesGlobal() {
|
||
document.querySelectorAll('.searchable').forEach(el => {
|
||
if (!el._choices) {
|
||
// Eliminar el atributo 'required' del select original
|
||
el.removeAttribute('required');
|
||
|
||
// Configuración de Choices sin espacios en classNames
|
||
el._choices = new Choices(el, {
|
||
searchEnabled: true,
|
||
itemSelectText: '',
|
||
shouldSort: false,
|
||
searchFields: ['label'],
|
||
silent: true
|
||
});
|
||
|
||
// Agregar clase 'required' al contenedor externo manualmente
|
||
if (el.hasAttribute('data-required')) {
|
||
const container = el.closest('.choices');
|
||
if (container) {
|
||
container.classList.add('required');
|
||
}
|
||
}
|
||
|
||
// Agregar validación personalizada
|
||
el.addEventListener('change', function() {
|
||
validateChoice(this);
|
||
});
|
||
}
|
||
});
|
||
}
|
||
|
||
// Función para validar los selects de Choices
|
||
function validateChoice(selectElement) {
|
||
const choicesInstance = selectElement._choices;
|
||
if (choicesInstance) {
|
||
const container = selectElement.closest('.choices');
|
||
const hasValue = choicesInstance.getValue(true).length > 0;
|
||
const isRequired = selectElement.hasAttribute('data-required');
|
||
if (isRequired) {
|
||
if (hasValue) {
|
||
container.classList.remove('is-invalid');
|
||
container.classList.add('is-valid');
|
||
} else {
|
||
container.classList.remove('is-valid');
|
||
container.classList.add('is-invalid');
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
// Validar todos los selects antes de enviar el formulario
|
||
document.getElementById('solicitudForm').addEventListener('submit', function(e) {
|
||
let isValid = true;
|
||
|
||
document.querySelectorAll('.searchable[data-required]').forEach(el => {
|
||
validateChoice(el);
|
||
const choicesInstance = el._choices;
|
||
if (choicesInstance && choicesInstance.getValue(true).length === 0) {
|
||
isValid = false;
|
||
// Desplazarse al primer error
|
||
if (isValid === false) { el.closest('.choices').scrollIntoView({ behavior: 'smooth', block: 'center' }); }
|
||
}
|
||
});
|
||
|
||
if (!isValid) {
|
||
e.preventDefault();
|
||
Swal.fire({ icon: 'error', title: 'Campos requeridos', text: 'Por favor complete todos los campos obligatorios marcados en rojo', confirmButtonColor: '#3085d6' });
|
||
}
|
||
});
|
||
|
||
// Eventos principales del formulario
|
||
function inicializarEventos() {
|
||
// Agregar partidas dinámicamente
|
||
document.getElementById('add-partida').addEventListener('click', () => {
|
||
const tbody = document.querySelector('#tabla-partidas tbody');
|
||
const idx = tbody.querySelectorAll('tr').length;
|
||
const row = document.createElement('tr');
|
||
|
||
row.innerHTML = `
|
||
<td>
|
||
<div class="position-relative">
|
||
<input name="partidas[0][descripcion]" class="form-control w-auto descripcion-input" required autocomplete="off">
|
||
</div>
|
||
</td>
|
||
<td><input name="partidas[${idx}][cantidad_comercial]" type="number" step="0.0001" class="form-control w-auto"></td>
|
||
<td><input name="partidas[${idx}][cantidad_tarifa]" type="number" step="0.0001" class="form-control w-auto"></td>
|
||
<td>
|
||
<select name="partidas[${idx}][unidad_comercial_id]" class="form-select searchable" data-required="true" required>
|
||
<option value="">-- Unidad --</option>
|
||
<?php foreach($unidades_medida as $um): ?>
|
||
<option value="<?= htmlspecialchars($um['id']) ?>"><?= htmlspecialchars($um['descripcion']) ?></option>
|
||
<?php endforeach; ?>
|
||
</select>
|
||
</td>
|
||
<td><input name="partidas[${idx}][valor_factura]" type="number" step="0.01" class="form-control valor-partida w-auto"></td>
|
||
<td><input name="partidas[${idx}][peso_bruto]" type="number" step="0.0001" class="form-control w-auto"></td>
|
||
<td>
|
||
<select name="partidas[${idx}][tasa_preferencial]" class="form-select searchable" data-required="true" required>
|
||
<option value="">-- Selecciona --</option>
|
||
<option>General</option>
|
||
<option>TLC</option>
|
||
<option>PROSEC</option>
|
||
<option>ALADI</option>
|
||
<option>COMERCIALIZADORA</option>
|
||
</select>
|
||
</td>
|
||
<td class="hide"><input name="partidas[${idx}][precio_unitario]" type="number" class="form-control w-auto"></td>
|
||
<td class="hide"><input name="partidas[${idx}][oma_factura]" class="form-control w-auto"></td>
|
||
<td><button type="button" class="btn btn-danger btn-sm remove-row mt-auto w-auto btn-animated">✖️</button></td>
|
||
`;
|
||
|
||
tbody.appendChild(row);
|
||
// Inicializamos Choices en los nuevos selects
|
||
setTimeout(() => {
|
||
row.querySelectorAll('.searchable').forEach(el => {
|
||
if (!el._choices) {
|
||
el._choices = new Choices(el, {
|
||
searchEnabled: true,
|
||
itemSelectText: '',
|
||
shouldSort: false,
|
||
silent: true
|
||
});
|
||
// Agregar clase required si corresponde
|
||
if (el.hasAttribute('data-required')) {
|
||
const container = el.closest('.choices');
|
||
if (container) { container.classList.add('required'); }
|
||
}
|
||
|
||
el.addEventListener('change', function() { validateChoice(this); });
|
||
}
|
||
});
|
||
}, 50);
|
||
});
|
||
|
||
// Eliminar partidas
|
||
document.querySelector('#tabla-partidas tbody').addEventListener('click', e => {
|
||
if (e.target.matches('.remove-row')) {
|
||
const row = e.target.closest('tr');
|
||
row.querySelectorAll('.searchable').forEach(el => {
|
||
if (el._choices) el._choices.destroy();
|
||
});
|
||
row.remove();
|
||
}
|
||
});
|
||
|
||
// Control overflow tabla cuando se abre el dropdown
|
||
document.addEventListener('click', function(e) {
|
||
const tableContainer = document.querySelector('.table-responsive');
|
||
if (!tableContainer) return;
|
||
if (e.target.closest('.choices__inner')) {
|
||
tableContainer.style.overflow = 'visible';
|
||
} else {
|
||
tableContainer.style.overflow = 'auto';
|
||
}
|
||
});
|
||
|
||
// Validación suma de partidas al enviar
|
||
$('#solicitudForm').submit(function(e){
|
||
const total = parseFloat($('#valor_factura').val()) || 0;
|
||
let sum = 0;
|
||
$('.valor-partida').each(function(){ sum += parseFloat($(this).val()) || 0; });
|
||
if(Math.abs(sum - total) > 0.001){
|
||
e.preventDefault();
|
||
Swal.fire({
|
||
icon: 'error',
|
||
title: 'Error de validación',
|
||
text: `La suma de partidas (${sum.toFixed(2)}) no coincide con Valor Factura (${total.toFixed(2)}).`
|
||
});
|
||
}
|
||
});
|
||
}
|
||
|
||
document.addEventListener('DOMContentLoaded', function() {
|
||
const transportistaSelect = document.getElementById('transportista_id');
|
||
const choferSelect = document.getElementById('chofer_id');
|
||
|
||
// Inicializar Choices.js si está disponible
|
||
let choferChoices = null;
|
||
if (typeof Choices !== 'undefined') {
|
||
choferChoices = new Choices(choferSelect, {
|
||
searchEnabled: true,
|
||
placeholderValue: '-- Selecciona Transportista primero --',
|
||
noResultsText: 'No se encontraron resultados',
|
||
itemSelectText: '',
|
||
searchPlaceholderValue: 'Buscar chofer...'
|
||
});
|
||
}
|
||
|
||
transportistaSelect.addEventListener('change', function() {
|
||
const transportistaId = this.value;
|
||
|
||
// Limpiar opciones del chofer
|
||
if (choferChoices) {
|
||
choferChoices.clearStore();
|
||
choferChoices.setChoices([{
|
||
value: '',
|
||
label: transportistaId ? '-- Cargando choferes... --' : '-- Selecciona Transportista primero --',
|
||
disabled: true
|
||
}], 'value', 'label', true);
|
||
} else {
|
||
choferSelect.innerHTML = '<option value="">' +
|
||
(transportistaId ? '-- Cargando choferes... --' : '-- Selecciona Transportista primero --') +
|
||
'</option>';
|
||
}
|
||
|
||
if (!transportistaId) {
|
||
return;
|
||
}
|
||
|
||
// Hacer petición AJAX para obtener choferes
|
||
fetch(`/IMPORTADORES/solicitud_importacion/obtenerChoferesPorTransportista?transportista_id=${transportistaId}`)
|
||
.then(response => {
|
||
console.log('Response status:', response.status);
|
||
console.log('Response headers:', response.headers.get('content-type'));
|
||
|
||
if (!response.ok) {
|
||
return response.text().then(text => {
|
||
console.error('Error response:', text);
|
||
throw new Error(`Error ${response.status}: ${text}`);
|
||
});
|
||
}
|
||
|
||
// Verificar que la respuesta sea JSON
|
||
const contentType = response.headers.get('content-type');
|
||
if (!contentType || !contentType.includes('application/json')) {
|
||
return response.text().then(text => {
|
||
console.error('Non-JSON response:', text);
|
||
throw new Error('La respuesta no es JSON válido');
|
||
});
|
||
}
|
||
|
||
return response.json();
|
||
})
|
||
.then(choferes => {
|
||
const opciones = [{
|
||
value: '',
|
||
label: '-- Selecciona Chofer --',
|
||
disabled: false
|
||
}];
|
||
|
||
choferes.forEach(chofer => {
|
||
opciones.push({
|
||
value: chofer.id_chofer,
|
||
label: chofer.nombre,
|
||
disabled: false
|
||
});
|
||
});
|
||
|
||
if (choferChoices) {
|
||
choferChoices.clearStore();
|
||
choferChoices.setChoices(opciones, 'value', 'label', true);
|
||
} else {
|
||
choferSelect.innerHTML = '';
|
||
opciones.forEach(opcion => {
|
||
const option = document.createElement('option');
|
||
option.value = opcion.value;
|
||
option.textContent = opcion.label;
|
||
if (opcion.disabled) option.disabled = true;
|
||
choferSelect.appendChild(option);
|
||
});
|
||
}
|
||
})
|
||
.catch(error => {
|
||
console.error('Error al cargar choferes:', error);
|
||
|
||
const errorMessage = '-- Error al cargar choferes --';
|
||
if (choferChoices) {
|
||
choferChoices.clearStore();
|
||
choferChoices.setChoices([{
|
||
value: '',
|
||
label: errorMessage,
|
||
disabled: true
|
||
}], 'value', 'label', true);
|
||
} else {
|
||
choferSelect.innerHTML = `<option value="">${errorMessage}</option>`;
|
||
}
|
||
});
|
||
});
|
||
});
|
||
|
||
$(document).ready(function() {
|
||
let timeoutId;
|
||
let currentRequest = null;
|
||
let currentInput = null; // Para rastrear qué input está activo
|
||
|
||
// Crear un único contenedor de sugerencias al final del body
|
||
if ($('#global-autocomplete-suggestions').length === 0) {
|
||
$('#tabla-partidas').after(`
|
||
<div id="global-autocomplete-suggestions"
|
||
class="bg-white border shadow-lg w-100"
|
||
style="display: none;
|
||
max-height: 200px;
|
||
overflow-y: auto;
|
||
border-radius: 4px;
|
||
margin-top: 5px;
|
||
margin-bottom: 10px;">
|
||
</div>
|
||
`);
|
||
}
|
||
|
||
const $globalSuggestions = $('#global-autocomplete-suggestions');
|
||
|
||
// Función para configurar autocompletado en un input
|
||
function setupAutocomplete(input) {
|
||
const $input = $(input);
|
||
const $row = $input.closest('tr');
|
||
|
||
$input.off('input').on('input', function() {
|
||
const query = $(this).val().trim();
|
||
currentInput = $input; // Guardar referencia del input activo
|
||
|
||
clearTimeout(timeoutId);
|
||
if (currentRequest) currentRequest.abort();
|
||
|
||
if (query.length < 2) {
|
||
$globalSuggestions.hide().empty();
|
||
return;
|
||
}
|
||
|
||
timeoutId = setTimeout(() => {
|
||
currentRequest = $.ajax({
|
||
url: '/IMPORTADORES/solicitud_importacion/buscar_productos',
|
||
method: 'GET',
|
||
data: { q: query },
|
||
dataType: 'json',
|
||
success: function(productos) {
|
||
$globalSuggestions.empty();
|
||
|
||
if (productos && productos.length > 0) {
|
||
productos.forEach(function(producto) {
|
||
const $item = $(`
|
||
<div class="autocomplete-item px-3 py-2 cursor-pointer border-bottom hover-bg-light"
|
||
style="cursor: pointer;">
|
||
<strong style="color: #333;">${producto.sinonimo}</strong>
|
||
<div class="small text-muted mt-1">
|
||
<div>Fracción: ${producto.fraccion || 'Sin fracción'}</div>
|
||
<div>Desc: ${producto.descripcion?.substring(0, 50) || ''}${producto.descripcion?.length > 50 ? '...' : ''}</div>
|
||
</div>
|
||
</div>
|
||
`).data('producto', producto);
|
||
|
||
// Efectos hover
|
||
$item.on('mouseenter', function() {
|
||
$globalSuggestions.find('.autocomplete-item').removeClass('active');
|
||
$(this).addClass('active').css('background-color', '#f8f9fa');
|
||
}).on('mouseleave', function() {
|
||
$(this).removeClass('active').css('background-color', '');
|
||
});
|
||
|
||
$item.on('click', function() {
|
||
selectProduct($(this).data('producto'), currentInput.closest('tr'));
|
||
});
|
||
|
||
$globalSuggestions.append($item);
|
||
});
|
||
|
||
// Posicionar y mostrar
|
||
$globalSuggestions.show();
|
||
}
|
||
else {
|
||
$globalSuggestions.hide();
|
||
}
|
||
},
|
||
error: function(xhr, status, error) {
|
||
if (status !== 'abort') {
|
||
console.error("Error en búsqueda:", error);
|
||
}
|
||
$globalSuggestions.hide();
|
||
},
|
||
complete: function() {
|
||
currentRequest = null;
|
||
}
|
||
});
|
||
}, 300);
|
||
});
|
||
|
||
// Manejar eventos de foco
|
||
$input.on('focus', function() {
|
||
currentInput = $input;
|
||
});
|
||
|
||
// Manejar teclado
|
||
$input.on('keydown', function(e) {
|
||
if (!$globalSuggestions.is(':visible')) return;
|
||
|
||
const $items = $globalSuggestions.find('.autocomplete-item');
|
||
const $active = $items.filter('.active');
|
||
|
||
switch(e.key) {
|
||
case 'ArrowDown':
|
||
e.preventDefault();
|
||
$items.removeClass('active').css('background-color', '');
|
||
const $next = $active.length ? $active.next() : $items.first();
|
||
$next.addClass('active').css('background-color', '#f8f9fa');
|
||
|
||
// Scroll automático
|
||
const containerHeight = $globalSuggestions.height();
|
||
const itemTop = $next.position().top;
|
||
const itemHeight = $next.outerHeight();
|
||
if (itemTop + itemHeight > containerHeight) {
|
||
$globalSuggestions.scrollTop($globalSuggestions.scrollTop() + itemHeight);
|
||
}
|
||
break;
|
||
|
||
case 'ArrowUp':
|
||
e.preventDefault();
|
||
$items.removeClass('active').css('background-color', '');
|
||
const $prev = $active.length ? $active.prev() : $items.last();
|
||
$prev.addClass('active').css('background-color', '#f8f9fa');
|
||
|
||
// Scroll automático
|
||
if ($prev.position().top < 0) {
|
||
$globalSuggestions.scrollTop($globalSuggestions.scrollTop() - $prev.outerHeight());
|
||
}
|
||
break;
|
||
|
||
case 'Enter':
|
||
if ($active.length) {
|
||
e.preventDefault();
|
||
selectProduct($active.data('producto'), $input.closest('tr'));
|
||
}
|
||
break;
|
||
|
||
case 'Tab':
|
||
if ($globalSuggestions.is(':visible')) {
|
||
e.preventDefault();
|
||
const $first = $items.first();
|
||
if ($first.length) {
|
||
selectProduct($first.data('producto'), $input.closest('tr'));
|
||
}
|
||
}
|
||
break;
|
||
|
||
case 'Escape':
|
||
$globalSuggestions.hide();
|
||
break;
|
||
}
|
||
});
|
||
}
|
||
|
||
// Ocultar sugerencias al hacer clic fuera o al hacer scroll
|
||
$(document).on('click', function(e) {
|
||
if (!currentInput ||
|
||
(!currentInput.is(e.target) &&
|
||
!$globalSuggestions.is(e.target) &&
|
||
!$globalSuggestions.has(e.target).length)) {
|
||
$globalSuggestions.hide();
|
||
}
|
||
});
|
||
|
||
// Ocultar al hacer scroll (opcional)
|
||
$(window).on('scroll resize', function() {
|
||
if ($globalSuggestions.is(':visible') && currentInput) {
|
||
// Reposicionar en lugar de ocultar
|
||
positionGlobalSuggestions(currentInput);
|
||
}
|
||
});
|
||
|
||
// Función para seleccionar un producto
|
||
function selectProduct(producto, $row) {
|
||
// Campos básicos
|
||
$row.find('input[name*="[descripcion]"]').val(producto.sinonimo);
|
||
|
||
// Tasa preferencial
|
||
if (producto.preferencia) {
|
||
const $select = $row.find('select[name*="[tasa_preferencial]"]');
|
||
if ($select[0] && $select[0]._choices) {
|
||
$select[0]._choices.setChoiceByValue(producto.preferencia);
|
||
} else {
|
||
$select.val(producto.preferencia).trigger('change');
|
||
}
|
||
}
|
||
|
||
// Unidad de medida
|
||
if (producto.umc_id) {
|
||
const $select = $row.find('select[name*="[unidad_comercial_id]"]');
|
||
setTimeout(() => {
|
||
if ($select[0] && $select[0]._choices) {
|
||
$select[0]._choices.setChoiceByValue(producto.umc_id.toString());
|
||
} else {
|
||
$select.val(producto.umc_id).trigger('change');
|
||
}
|
||
}, 50);
|
||
}
|
||
|
||
// Número de parte
|
||
if (producto.numero_parte) {
|
||
$row.find('input[name*="[oma_factura]"]').val(producto.numero_parte);
|
||
}
|
||
|
||
// Incrementar frecuencia
|
||
$.ajax({
|
||
url: '/IMPORTADORES/solicitud_importacion/incrementar_frecuencia',
|
||
method: 'POST',
|
||
data: { producto_id: producto.id }
|
||
});
|
||
|
||
// Ocultar sugerencias
|
||
$globalSuggestions.hide();
|
||
|
||
// Enfocar el siguiente campo si existe
|
||
const $nextInput = $row.next('tr').find('.descripcion-input');
|
||
if ($nextInput.length) {
|
||
setTimeout(() => $nextInput.focus(), 100);
|
||
}
|
||
}
|
||
|
||
// Inicializar autocompletado en inputs existentes
|
||
$('.descripcion-input').each(function() {
|
||
setupAutocomplete(this);
|
||
});
|
||
|
||
// Configurar autocompletado para nuevas filas
|
||
$('#add-partida').on('click', function() {
|
||
setTimeout(function() {
|
||
$('.descripcion-input').last().each(function() {
|
||
setupAutocomplete(this);
|
||
});
|
||
}, 100);
|
||
});
|
||
});
|
||
</script>
|
||
|
||
</body>
|
||
</html>
|