460 lines
24 KiB
PHP
460 lines
24 KiB
PHP
<?php
|
|
session_start();
|
|
if (!isset($_SESSION['user_id'])) {
|
|
header('Location: login.php');
|
|
exit;
|
|
}
|
|
|
|
require_once 'db/config.php';
|
|
$pdo = db();
|
|
|
|
$user_id = $_SESSION['user_id'];
|
|
$user_role = $_SESSION['user_role'] ?? 'Asesor';
|
|
|
|
$pedido = [
|
|
'id' => '',
|
|
'dni_cliente' => '',
|
|
'nombre_completo' => '',
|
|
'celular' => '',
|
|
'agencia' => 'SHALOM',
|
|
'sede_envio' => '',
|
|
'codigo_rastreo' => '',
|
|
'codigo_tracking' => '',
|
|
'clave' => '',
|
|
'pendientes' => '',
|
|
'producto' => '',
|
|
'cantidad' => 1,
|
|
'monto_total' => '',
|
|
'monto_adelantado' => 0,
|
|
'numero_operacion' => '',
|
|
'banco' => '',
|
|
'fecha_recojo' => '',
|
|
'estado' => 'ROTULADO 📦',
|
|
'asesor_id' => $user_id, // Default to current user
|
|
'notas' => '',
|
|
'voucher_adelanto_path' => '',
|
|
'voucher_restante_path' => ''
|
|
];
|
|
$page_title = 'Crear Pedido';
|
|
|
|
if (isset($_GET['id'])) {
|
|
$page_title = 'Editar Pedido';
|
|
$stmt = $pdo->prepare('SELECT * FROM pedidos WHERE id = ?');
|
|
$stmt->execute([$_GET['id']]);
|
|
$pedido = $stmt->fetch();
|
|
if (!$pedido) {
|
|
die('Pedido no encontrado.');
|
|
}
|
|
// Security check: Asesora can only edit their own pedidos
|
|
if ($user_role === 'Asesor' && $pedido['asesor_id'] != $user_id) {
|
|
die('Acceso denegado. No tienes permiso para editar este pedido.');
|
|
}
|
|
} else {
|
|
// Security check: Only Administradors, Logistica and asesores can create new pedidos
|
|
if ($user_role !== 'Administrador' && $user_role !== 'Logistica' && $user_role !== 'Asesor') {
|
|
die('Acceso denegado. No tienes permiso para crear nuevos pedidos.');
|
|
}
|
|
}
|
|
|
|
// Fetch asesores or the current asesor's name
|
|
$asesores = [];
|
|
$current_asesor_nombre = '';
|
|
if ($user_role === 'Administrador' || $user_role === 'Logistica') {
|
|
$stmt_asesores = $pdo->query("SELECT id, nombre_asesor FROM users WHERE role = 'Asesor' ORDER BY nombre_asesor");
|
|
$asesores = $stmt_asesores->fetchAll();
|
|
} else if ($user_role === 'Asesor') {
|
|
$stmt_current_asesor = $pdo->prepare("SELECT nombre_asesor FROM users WHERE id = ?");
|
|
$stmt_current_asesor->execute([$user_id]);
|
|
$current_asesor_nombre = $stmt_current_asesor->fetchColumn();
|
|
}
|
|
|
|
// Fetch products
|
|
$stmt_products = $pdo->query("SELECT id, nombre FROM products ORDER BY nombre ASC");
|
|
$products = $stmt_products->fetchAll();
|
|
|
|
// Fetch Shalom branches
|
|
$stmt_sedes = $pdo->query("SELECT nombre_sede FROM sedes_shalom ORDER BY nombre_sede ASC");
|
|
$sedes_shalom = $stmt_sedes->fetchAll(PDO::FETCH_COLUMN);
|
|
|
|
$estados = ['ROTULADO 📦', 'EN TRANSITO 🚛', 'EN DESTINO 🏬', 'COMPLETADO ✅'];
|
|
|
|
?>
|
|
<?php
|
|
$pageTitle = $page_title;
|
|
include 'layout_header.php';
|
|
?>
|
|
|
|
<?php if (isset($_GET['error'])):
|
|
$error_message = htmlspecialchars($_GET['error']);
|
|
?>
|
|
<div class="alert alert-danger" role="alert">
|
|
<?php echo $error_message; ?>
|
|
</div>
|
|
<?php endif; ?>
|
|
|
|
<div class="card">
|
|
<div class="card-body">
|
|
<form action="save_pedido.php" method="POST" enctype="multipart/form-data">
|
|
<input type="hidden" name="id" value="<?php echo htmlspecialchars($pedido['id']); ?>">
|
|
<input type="hidden" name="referer" value="<?php echo htmlspecialchars($_SERVER['HTTP_REFERER'] ?? 'pedidos.php'); ?>">
|
|
|
|
<!-- Asesor ID handling -->
|
|
<?php if ($user_role === 'Administrador' || $user_role === 'Logistica'): ?>
|
|
<div class="mb-3">
|
|
<label for="asesor_id" class="form-label">Asesor Responsable</label>
|
|
<select class="form-select" id="asesor_id" name="asesor_id" required>
|
|
<option value="">Sin Asignar</option>
|
|
<?php foreach ($asesores as $asesor): ?>
|
|
<option value="<?php echo $asesor['id']; ?>" <?php echo ($pedido['asesor_id'] == $asesor['id']) ? 'selected' : ''; ?>><?php echo htmlspecialchars($asesor['nombre_asesor']); ?></option>
|
|
<?php endforeach; ?>
|
|
</select>
|
|
</div>
|
|
<?php else: ?>
|
|
<div class="mb-3">
|
|
<label for="asesor_nombre" class="form-label">Nombre del Asesor</label>
|
|
<input type="text" class="form-control" id="asesor_nombre" value="<?php echo htmlspecialchars($current_asesor_nombre); ?>" disabled>
|
|
<input type="hidden" name="asesor_id" value="<?php echo htmlspecialchars($user_id); ?>">
|
|
</div>
|
|
<?php endif; ?>
|
|
|
|
<div class="row">
|
|
<div class="col-md-6 mb-3">
|
|
<label for="dni_cliente" class="form-label">DNI</label>
|
|
<input type="text" class="form-control" id="dni_cliente" name="dni" value="<?php echo htmlspecialchars($pedido['dni_cliente'] ?? ''); ?>" required>
|
|
</div>
|
|
<div class="col-md-6 mb-3">
|
|
<label for="nombre_completo" class="form-label">Nombre Completo</label>
|
|
<input type="text" class="form-control" id="nombre_completo" name="nombre_completo" value="<?php echo htmlspecialchars($pedido['nombre_completo']); ?>" required>
|
|
</div>
|
|
</div>
|
|
|
|
<div class="row">
|
|
<div class="col-md-4 mb-3">
|
|
<label for="celular" class="form-label">Celular</label>
|
|
<input type="text" class="form-control" id="celular" name="celular" value="<?php echo htmlspecialchars($pedido['celular']); ?>" required>
|
|
</div>
|
|
<div class="col-md-4 mb-3">
|
|
<label for="agencia" class="form-label">Agencia</label>
|
|
<select class="form-select" id="agencia" name="agencia" required>
|
|
<option value="SHALOM" <?php echo ($pedido['agencia'] == 'SHALOM') ? 'selected' : ''; ?>>SHALOM</option>
|
|
<option value="OLVA" <?php echo ($pedido['agencia'] == 'OLVA') ? 'selected' : ''; ?>>OLVA</option>
|
|
<option value="OTROS" <?php echo ($pedido['agencia'] == 'OTROS') ? 'selected' : ''; ?>>OTROS</option>
|
|
</select>
|
|
</div>
|
|
<div class="col-md-4 mb-3">
|
|
<label for="sede_envio" class="form-label">Sede de Envío</label>
|
|
<input type="text" class="form-control" id="sede_envio" name="sede_envio" list="sedes_list" value="<?php echo htmlspecialchars($pedido['sede_envio']); ?>" required>
|
|
<datalist id="sedes_list">
|
|
<?php foreach ($sedes_shalom as $sede): ?>
|
|
<option value="<?php echo htmlspecialchars($sede); ?>">
|
|
<?php endforeach; ?>
|
|
</datalist>
|
|
</div>
|
|
</div>
|
|
|
|
<div class="row">
|
|
<div class="col-md-6 mb-3">
|
|
<label for="codigo_rastreo" class="form-label">Nº De Orden (Courier)</label>
|
|
<input type="text" class="form-control" id="codigo_rastreo" name="codigo_rastreo" value="<?php echo htmlspecialchars($pedido['codigo_rastreo']); ?>">
|
|
</div>
|
|
<div class="col-md-6 mb-3">
|
|
<label for="codigo_tracking" class="form-label">Codigo De Orden (Interno)</label>
|
|
<input type="text" class="form-control" id="codigo_tracking" name="codigo_tracking" value="<?php echo htmlspecialchars($pedido['codigo_tracking']); ?>">
|
|
</div>
|
|
</div>
|
|
|
|
<div class="row">
|
|
<div class="col-md-6 mb-3">
|
|
<label for="clave" class="form-label">Clave</label>
|
|
<div class="input-group">
|
|
<input type="password" class="form-control" id="clave" name="clave" value="<?php echo htmlspecialchars($pedido['clave'] ?? ''); ?>" readonly>
|
|
<button class="btn btn-outline-secondary" type="button" id="toggleClave" disabled>
|
|
<i class="bi bi-eye"></i> 👁️
|
|
</button>
|
|
</div>
|
|
<small class="text-muted">Ingresa un número de operación válido y selecciona el banco para ver la clave.</small>
|
|
</div>
|
|
<div class="col-md-6 mb-3">
|
|
<label for="pendientes" class="form-label">Pendientes</label>
|
|
<select class="form-select" id="pendientes" name="pendientes">
|
|
<option value="" <?php echo (empty($pedido['pendientes'])) ? 'selected' : ''; ?>>Seleccionar</option>
|
|
<option value="PENDIENTE" <?php echo ($pedido['pendientes'] == 'PENDIENTE') ? 'selected' : ''; ?>>PENDIENTE</option>
|
|
<option value="GESTIONADO" <?php echo ($pedido['pendientes'] == 'GESTIONADO') ? 'selected' : ''; ?>>GESTIONADO</option>
|
|
</select>
|
|
</div>
|
|
</div>
|
|
|
|
<hr>
|
|
<h5>Productos</h5>
|
|
<div id="productos-container">
|
|
<div class="row producto-row mb-3">
|
|
<div class="col-md-6">
|
|
<label for="producto" class="form-label">Producto</label>
|
|
<select class="form-select" name="productos[0][nombre]" required>
|
|
<option value="">Seleccione un producto</option>
|
|
<?php foreach ($products as $product): ?>
|
|
<option value="<?php echo htmlspecialchars($product['nombre']); ?>" <?php echo ($pedido['producto'] == $product['nombre']) ? 'selected' : ''; ?>>
|
|
<?php echo htmlspecialchars($product['nombre']); ?>
|
|
</option>
|
|
<?php endforeach; ?>
|
|
</select>
|
|
</div>
|
|
<div class="col-md-3">
|
|
<label for="cantidad" class="form-label">Cantidad</label>
|
|
<input type="number" class="form-control" name="productos[0][cantidad]" value="<?php echo htmlspecialchars($pedido['cantidad']); ?>" required>
|
|
</div>
|
|
<div class="col-md-3 d-flex align-items-end">
|
|
<button type="button" class="btn btn-danger btn-sm remove-producto-btn" style="display: none;">Eliminar</button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<button type="button" id="add-producto-btn" class="btn btn-success btn-sm mb-3">Agregar producto adicional</button>
|
|
<hr>
|
|
|
|
<div class="row">
|
|
<?php if ($user_role !== 'Logistica'): ?>
|
|
<div class="col-md-3 mb-3">
|
|
<label for="monto_total" class="form-label">Monto Total</label>
|
|
<input type="number" step="0.01" class="form-control" id="monto_total" name="monto_total" value="<?php echo htmlspecialchars($pedido['monto_total']); ?>" required>
|
|
</div>
|
|
<div class="col-md-3 mb-3">
|
|
<label for="monto_adelantado" class="form-label">Monto Adelantado</label>
|
|
<input type="number" step="0.01" class="form-control" id="monto_adelantado" name="monto_adelantado" value="<?php echo htmlspecialchars($pedido['monto_adelantado']); ?>">
|
|
</div>
|
|
<?php else: ?>
|
|
<input type="hidden" name="monto_total" value="<?php echo htmlspecialchars($pedido['monto_total']); ?>">
|
|
<input type="hidden" name="monto_adelantado" value="<?php echo htmlspecialchars($pedido['monto_adelantado']); ?>">
|
|
<?php endif; ?>
|
|
<div class="col-md-3 mb-3">
|
|
<label for="numero_operacion" class="form-label">Número de Operación</label>
|
|
<input type="text" class="form-control" id="numero_operacion" name="numero_operacion" value="<?php echo htmlspecialchars($pedido['numero_operacion'] ?? ''); ?>" minlength="6">
|
|
<div id="operacion-feedback" class="form-text"></div>
|
|
</div>
|
|
<div class="col-md-3 mb-3">
|
|
<label for="banco" class="form-label">Banco</label>
|
|
<select class="form-select" id="banco" name="banco">
|
|
<option value="">Seleccionar Banco</option>
|
|
<?php
|
|
$bancos = ['YAPE', 'PLIN', 'BCP', 'INTERBANK', 'BANCO DE LA NACION', 'BBVA'];
|
|
foreach ($bancos as $b): ?>
|
|
<option value="<?php echo $b; ?>" <?php echo (($pedido['banco'] ?? '') == $b) ? 'selected' : ''; ?>><?php echo $b; ?></option>
|
|
<?php endforeach; ?>
|
|
</select>
|
|
</div>
|
|
</div>
|
|
|
|
|
|
|
|
<div class="row">
|
|
<div class="col-md-6 mb-3">
|
|
<label for="voucher_adelanto" class="form-label">Voucher de Adelanto</label>
|
|
<input type="file" class="form-control" id="voucher_adelanto" name="voucher_adelanto">
|
|
<?php if (!empty($pedido['voucher_adelanto_path'])): ?>
|
|
<div class="mt-2">
|
|
<a href="<?php echo htmlspecialchars($pedido['voucher_adelanto_path']); ?>" target="_blank">Ver voucher actual</a>
|
|
</div>
|
|
<?php endif; ?>
|
|
</div>
|
|
<div class="col-md-6 mb-3">
|
|
<label for="voucher_restante" class="form-label">Voucher de Pago Restante</label>
|
|
<input type="file" class="form-control" id="voucher_restante" name="voucher_restante">
|
|
<?php if (!empty($pedido['voucher_restante_path'])): ?>
|
|
<div class="mt-2">
|
|
<a href="<?php echo htmlspecialchars($pedido['voucher_restante_path']); ?>" target="_blank">Ver voucher actual</a>
|
|
</div>
|
|
<?php endif; ?>
|
|
</div>
|
|
</div>
|
|
|
|
<div class="row">
|
|
<div class="col-md-6 mb-3">
|
|
<label for="estado" class="form-label">Estado del Pedido</label>
|
|
<select class="form-select" id="estado" name="estado" required>
|
|
<?php foreach ($estados as $estado_option): ?>
|
|
<option value="<?php echo $estado_option; ?>" <?php echo ($pedido['estado'] == $estado_option) ? 'selected' : ''; ?>><?php echo $estado_option; ?></option>
|
|
<?php endforeach; ?>
|
|
<?php if (isset($_SESSION['user_role']) && in_array($_SESSION['user_role'], ['superadmin', 'Administrador', 'admin'])): ?>
|
|
<option value="Gestion" <?php echo ($pedido['estado'] == 'Gestion') ? 'selected' : ''; ?>>GESTIONES ⚙️</option>
|
|
<?php endif; ?>
|
|
</select>
|
|
</div>
|
|
</div>
|
|
|
|
<div class="mb-3">
|
|
<label for="notas" class="form-label">Notas</label>
|
|
<textarea class="form-control" id="notas" name="notas" rows="3"><?php echo htmlspecialchars($pedido['notas']); ?></textarea>
|
|
</div>
|
|
|
|
<div class="mb-3">
|
|
<label for="observacion" class="form-label">Observación (Verificación de Pago)</label>
|
|
<textarea class="form-control" id="observacion" name="observacion" rows="2"><?php echo htmlspecialchars($pedido['observacion'] ?? ''); ?></textarea>
|
|
</div>
|
|
|
|
<button type="submit" class="btn btn-primary">Guardar Pedido</button>
|
|
<a href="<?php echo htmlspecialchars($_SERVER['HTTP_REFERER'] ?? 'pedidos.php'); ?>" class="btn btn-secondary">Cancelar</a>
|
|
</form>
|
|
</div>
|
|
</div>
|
|
|
|
<script>
|
|
document.addEventListener('DOMContentLoaded', function() {
|
|
const numeroOperacionInput = document.getElementById('numero_operacion');
|
|
const bancoInput = document.getElementById('banco');
|
|
const operacionFeedback = document.getElementById('operacion-feedback');
|
|
const claveInput = document.getElementById('clave');
|
|
const toggleClaveBtn = document.getElementById('toggleClave');
|
|
const pedidoId = document.querySelector('input[name="id"]').value;
|
|
const submitBtn = document.querySelector('button[type="submit"]');
|
|
const agenciaSelect = document.getElementById('agencia');
|
|
const sedeEnvioInput = document.getElementById('sede_envio');
|
|
|
|
function updateSedeList() {
|
|
if (agenciaSelect.value === 'SHALOM') {
|
|
sedeEnvioInput.setAttribute('list', 'sedes_list');
|
|
} else {
|
|
sedeEnvioInput.removeAttribute('list');
|
|
}
|
|
}
|
|
|
|
agenciaSelect.addEventListener('change', updateSedeList);
|
|
updateSedeList(); // Run on load
|
|
|
|
function validateOperacion() {
|
|
const value = numeroOperacionInput.value.trim();
|
|
const bancoValue = bancoInput.value;
|
|
|
|
if (value === '') {
|
|
operacionFeedback.innerHTML = '';
|
|
numeroOperacionInput.classList.remove('is-invalid', 'is-valid');
|
|
toggleClaveBtn.disabled = true;
|
|
claveInput.type = 'password';
|
|
return;
|
|
}
|
|
|
|
if (value.length < 6) {
|
|
operacionFeedback.innerHTML = '<span class="text-danger">⚠️ El número debe tener al menos 6 dígitos</span>';
|
|
numeroOperacionInput.classList.add('is-invalid');
|
|
numeroOperacionInput.classList.remove('is-valid');
|
|
toggleClaveBtn.disabled = true;
|
|
claveInput.type = 'password';
|
|
submitBtn.disabled = true;
|
|
return;
|
|
}
|
|
|
|
fetch(`check_duplicate_operation.php?numero_operacion=${encodeURIComponent(value)}&pedido_id=${pedidoId}`)
|
|
.then(response => response.json())
|
|
.then(data => {
|
|
if (data.duplicate) {
|
|
operacionFeedback.innerHTML = `<span class="text-danger">❌ Este número ya existe en el pedido #${data.pedido_id}</span>`;
|
|
numeroOperacionInput.classList.add('is-invalid');
|
|
numeroOperacionInput.classList.remove('is-valid');
|
|
toggleClaveBtn.disabled = true;
|
|
claveInput.type = 'password';
|
|
submitBtn.disabled = true;
|
|
} else {
|
|
operacionFeedback.innerHTML = '<span class="text-success">✅ Número disponible</span>';
|
|
numeroOperacionInput.classList.remove('is-invalid');
|
|
numeroOperacionInput.classList.add('is-valid');
|
|
|
|
// Solo habilitar si también hay banco seleccionado
|
|
if (bancoValue !== '') {
|
|
toggleClaveBtn.disabled = false;
|
|
} else {
|
|
toggleClaveBtn.disabled = true;
|
|
claveInput.type = 'password';
|
|
}
|
|
submitBtn.disabled = false;
|
|
}
|
|
})
|
|
.catch(error => {
|
|
console.error('Error checking duplicate:', error);
|
|
});
|
|
}
|
|
|
|
numeroOperacionInput.addEventListener('input', validateOperacion);
|
|
bancoInput.addEventListener('change', validateOperacion);
|
|
|
|
// Run validation on load if there's a value
|
|
if (numeroOperacionInput.value.trim() !== '') {
|
|
validateOperacion();
|
|
}
|
|
|
|
toggleClaveBtn.addEventListener('click', function() {
|
|
if (claveInput.type === 'password') {
|
|
claveInput.type = 'text';
|
|
this.innerHTML = '🙈';
|
|
} else {
|
|
claveInput.type = 'password';
|
|
this.innerHTML = '👁️';
|
|
}
|
|
});
|
|
});
|
|
</script>
|
|
|
|
<script>
|
|
document.addEventListener('DOMContentLoaded', function() {
|
|
const container = document.getElementById('productos-container');
|
|
const addBtn = document.getElementById('add-producto-btn');
|
|
let productIndex = 0;
|
|
|
|
// Function to initialize remove buttons for existing rows
|
|
const initRemoveButtons = () => {
|
|
container.querySelectorAll('.producto-row').forEach((row, index) => {
|
|
if (index > 0) {
|
|
const removeBtn = row.querySelector('.remove-producto-btn');
|
|
if(removeBtn) {
|
|
removeBtn.style.display = 'block';
|
|
}
|
|
}
|
|
});
|
|
};
|
|
|
|
addBtn.addEventListener('click', function() {
|
|
productIndex++;
|
|
const firstRow = container.querySelector('.producto-row');
|
|
const newRow = firstRow.cloneNode(true);
|
|
|
|
// Update names and clear values
|
|
newRow.querySelector('select').name = `productos[${productIndex}][nombre]`;
|
|
newRow.querySelector('select').value = '';
|
|
newRow.querySelector('input[type="number"]').name = `productos[${productIndex}][cantidad]`;
|
|
newRow.querySelector('input[type="number"]').value = '1';
|
|
|
|
// Show remove button
|
|
const removeBtn = newRow.querySelector('.remove-producto-btn');
|
|
if(removeBtn) {
|
|
removeBtn.style.display = 'block';
|
|
}
|
|
|
|
container.appendChild(newRow);
|
|
});
|
|
|
|
container.addEventListener('click', function(e) {
|
|
if (e.target && e.target.classList.contains('remove-producto-btn')) {
|
|
const rowToRemove = e.target.closest('.producto-row');
|
|
// Do not remove the first row
|
|
if (rowToRemove !== container.querySelector('.producto-row')) {
|
|
rowToRemove.remove();
|
|
}
|
|
}
|
|
});
|
|
|
|
// Initialize for existing rows on edit
|
|
productIndex = container.querySelectorAll('.producto-row').length - 1;
|
|
initRemoveButtons();
|
|
});
|
|
</script>
|
|
|
|
<script>
|
|
document.addEventListener('DOMContentLoaded', function() {
|
|
const urlParams = new URLSearchParams(window.location.search);
|
|
if (urlParams.has('success')) {
|
|
alert('SE AGREGO CORRECTAMENTE ✅');
|
|
// Remove the success parameter from the URL without reloading the page
|
|
const newUrl = window.location.pathname + window.location.hash;
|
|
window.history.replaceState({}, document.title, newUrl);
|
|
}
|
|
});
|
|
</script>
|
|
|
|
<?php include 'layout_footer.php'; ?>
|