631 lines
35 KiB
PHP
631 lines
35 KiB
PHP
<?php
|
||
session_start();
|
||
if (!isset($_SESSION['user_id'])) {
|
||
header('Location: login.php');
|
||
exit;
|
||
}
|
||
|
||
require_once 'db/config.php';
|
||
|
||
function getStatusStyle($status) {
|
||
$style = 'color: white;'; // Default text color
|
||
$bgColor = '#0dcaf0'; // Default info blue
|
||
|
||
switch (strtoupper(trim($status))) {
|
||
case 'ROTULADO':
|
||
$bgColor = '#ffc107'; // yellow
|
||
$style = 'color: black;';
|
||
break;
|
||
case 'EN TRANSITO':
|
||
$bgColor = '#90EE90'; // light green
|
||
$style = 'color: black;';
|
||
break;
|
||
case 'EN DESTINO':
|
||
$bgColor = '#800080'; // purple
|
||
break;
|
||
case 'COMPLETADO':
|
||
case 'COMPLETADO ✅':
|
||
$bgColor = '#198754'; // dark green
|
||
break;
|
||
case 'GESTION':
|
||
$bgColor = '#6c757d'; // secondary grey
|
||
break;
|
||
}
|
||
return "background-color: {$bgColor} !important; {$style}";
|
||
}
|
||
|
||
$pdo = db();
|
||
|
||
$user_id = $_SESSION['user_id'];
|
||
$user_role = $_SESSION['user_role'] ?? 'Asesor';
|
||
|
||
// Fetch years for the filter
|
||
$years_query = "SELECT DISTINCT YEAR(created_at) as year FROM pedidos";
|
||
if ($user_role === 'Asesor') {
|
||
$years_query .= " WHERE asesor_id = ?";
|
||
$years_stmt = $pdo->prepare($years_query);
|
||
$years_stmt->execute([$user_id]);
|
||
} else {
|
||
$years_stmt = $pdo->query($years_query);
|
||
}
|
||
$years = $years_stmt->fetchAll(PDO::FETCH_COLUMN);
|
||
|
||
|
||
// Filter logic
|
||
$selected_month = $_GET['mes'] ?? '';
|
||
$selected_year = $_GET['año'] ?? '';
|
||
$search_query = $_GET['q'] ?? '';
|
||
|
||
$sql = "SELECT p.*, u.nombre_asesor as asesor_nombre FROM pedidos p LEFT JOIN users u ON p.asesor_id = u.id WHERE p.estado = 'EN TRANSITO 🚛'";
|
||
$params = [];
|
||
|
||
if ($user_role === 'Asesor') {
|
||
$sql .= " AND p.asesor_id = ?";
|
||
$params[] = $user_id;
|
||
}
|
||
|
||
if (!empty($search_query)) {
|
||
$sql .= " AND (p.nombre_completo LIKE ? OR p.dni_cliente LIKE ? OR p.celular LIKE ?)";
|
||
$params[] = "%$search_query%";
|
||
$params[] = "%$search_query%";
|
||
$params[] = "%$search_query%";
|
||
}
|
||
|
||
if (!empty($selected_month)) {
|
||
$sql .= " AND MONTH(p.created_at) = ?";
|
||
$params[] = $selected_month;
|
||
}
|
||
if (!empty($selected_year)) {
|
||
$sql .= " AND YEAR(p.created_at) = ?";
|
||
$params[] = $selected_year;
|
||
}
|
||
|
||
$sql .= " ORDER BY p.created_at DESC";
|
||
$stmt = $pdo->prepare($sql);
|
||
$stmt->execute($params);
|
||
$pedidos = $stmt->fetchAll();
|
||
|
||
$months = [
|
||
1 => 'Enero', 2 => 'Febrero', 3 => 'Marzo', 4 => 'Abril', 5 => 'Mayo', 6 => 'Junio',
|
||
7 => 'Julio', 8 => 'Agosto', 9 => 'Septiembre', 10 => 'Octubre', 11 => 'Noviembre', 12 => 'Diciembre'
|
||
];
|
||
|
||
?>
|
||
<?php
|
||
$pageTitle = "Pedidos en Tránsito";
|
||
include 'layout_header.php';
|
||
?>
|
||
|
||
<!-- Modal for tracking status -->
|
||
<div class="modal fade" id="trackingModal" tabindex="-1" aria-labelledby="trackingModalLabel" aria-hidden="true">
|
||
<div class="modal-dialog modal-xl" style="max-width: 950px;">
|
||
<div class="modal-content">
|
||
<div class="modal-header">
|
||
<h5 class="modal-title" id="trackingModalLabel">Estado del Envío - Shalom</h5>
|
||
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
|
||
</div>
|
||
<div class="modal-body" style="padding: 0;">
|
||
<div class="p-3">
|
||
<p class="mb-1"><strong>Nº De Orden:</strong> <span id="modal-order-number"></span></p>
|
||
<p class="mb-0"><strong>Código De Orden:</strong> <span id="modal-order-code"></span></p>
|
||
</div>
|
||
<hr class="my-0">
|
||
<div id="modal-tracking-status">
|
||
<p class="text-center p-5">Consultando estado en Shalom...</p>
|
||
</div>
|
||
</div>
|
||
<div class="modal-footer">
|
||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cerrar</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
|
||
<?php if (isset($_SESSION['flash_message'])):
|
||
$flash = $_SESSION['flash_message'];
|
||
unset($_SESSION['flash_message']);
|
||
?>
|
||
<div class="alert alert-<?php echo htmlspecialchars($flash['type']); ?> alert-dismissible fade show" role="alert">
|
||
<?php echo htmlspecialchars($flash['message']); ?>
|
||
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
|
||
</div>
|
||
<?php endif; ?>
|
||
|
||
|
||
<div class="card mb-4">
|
||
<div class="card-body">
|
||
<form method="GET" action="pedidos_en_transito.php" class="row g-3 align-items-center">
|
||
<div class="col-auto">
|
||
<label for="q" class="form-label">Buscar</label>
|
||
<input type="text" name="q" id="q" class="form-control" value="<?php echo htmlspecialchars($search_query); ?>" placeholder="Nombre, DNI o Celular">
|
||
</div>
|
||
<div class="col-auto">
|
||
<label for="mes" class="form-label">Mes</label>
|
||
<select name="mes" id="mes" class="form-select">
|
||
<option value="">Todos</option>
|
||
<?php foreach ($months as $num => $name): ?>
|
||
<option value="<?php echo $num; ?>" <?php echo $selected_month == $num ? 'selected' : ''; ?>><?php echo $name; ?></option>
|
||
<?php endforeach; ?>
|
||
</select>
|
||
</div>
|
||
<div class="col-auto">
|
||
<label for="año" class="form-label">Año</label>
|
||
<select name="año" id="año" class="form-select">
|
||
<option value="">Todos</option>
|
||
<?php foreach ($years as $year): ?>
|
||
<option value="<?php echo $year; ?>" <?php echo $selected_year == $year ? 'selected' : ''; ?>><?php echo $year; ?></option>
|
||
<?php endforeach; ?>
|
||
</select>
|
||
</div>
|
||
<div class="col-auto mt-4">
|
||
<button type="submit" class="btn btn-info">Filtrar</button>
|
||
<a href="pedidos_en_transito.php" class="btn btn-secondary">Limpiar</a>
|
||
<button type="button" id="verify-statuses-btn" class="btn btn-primary">Verificar Estados Ahora</button>
|
||
</div>
|
||
</form>
|
||
</div>
|
||
</div>
|
||
|
||
<div class="card">
|
||
<div class="card-body">
|
||
<div class="table-responsive">
|
||
<table id="pedidos-table" class="table table-striped">
|
||
<thead>
|
||
<tr>
|
||
<th>ID</th>
|
||
<th>Cliente</th>
|
||
<th>DNI</th>
|
||
<th>Celular</th>
|
||
<th>Agencia</th>
|
||
<th>Producto</th>
|
||
<th>Sede de Envío</th>
|
||
<th>Cantidad</th>
|
||
<th>Monto Total</th>
|
||
<th>Monto Debe</th>
|
||
<th>Nº De Orden</th>
|
||
<th>Codigo De Orden</th>
|
||
<th>CLAVE</th>
|
||
<th>Estado</th>
|
||
<th>Estado Shalom</th>
|
||
<?php if ($user_role !== 'Asesor'): ?><th>Asesor</th><?php endif; ?>
|
||
<th>Fecha Creación</th>
|
||
<th>Voucher Restante</th>
|
||
<th>Acciones</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody>
|
||
<?php foreach ($pedidos as $pedido): ?>
|
||
<tr id="pedido-<?php echo $pedido['id']; ?>" data-order-number="<?php echo htmlspecialchars($pedido['codigo_rastreo'] ?? ''); ?>" data-order-code="<?php echo htmlspecialchars($pedido['codigo_tracking'] ?? ''); ?>">
|
||
<td><?php echo htmlspecialchars($pedido['id']); ?></td>
|
||
<td><?php echo htmlspecialchars($pedido['nombre_completo']); ?></td>
|
||
<td><?php echo htmlspecialchars($pedido['dni_cliente'] ?? 'N/A'); ?></td>
|
||
<td>
|
||
<?php
|
||
echo htmlspecialchars($pedido['celular']);
|
||
|
||
// Prepare WhatsApp message
|
||
$nombre_cliente = $pedido['nombre_completo'];
|
||
$producto = $pedido['producto'];
|
||
$sede_envio = $pedido['sede_envio'] ?? 'su agencia de destino';
|
||
$monto_total = (float)($pedido['monto_total'] ?? 0);
|
||
$monto_debe = (float)($pedido['monto_debe'] ?? 0);
|
||
$adelanto = $monto_total - $monto_debe;
|
||
|
||
$template = "Estimado(a) {NOMBRE_CLIENTE} 👋
|
||
"
|
||
. "Le informamos que su pedido de {PRODUCTO} ya se encuentra disponible en su ciudad 📦
|
||
|
||
"
|
||
. "📍 Lugar de recojo: Shalom – {SEDE_ENVIO}
|
||
|
||
"
|
||
. "💰 Detalle de pago:
|
||
|
||
"
|
||
. "• Monto total del pedido: S/ {MONTO_TOTAL}
|
||
"
|
||
. "• Adelanto realizado: S/ {ADELANTO} ✅
|
||
"
|
||
. "• Saldo pendiente: S/ {SALDO_PENDIENTE}
|
||
|
||
"
|
||
. "Para continuar, le solicitamos enviar la captura de su pago restante por este medio 📄
|
||
|
||
"
|
||
. "Una vez confirmado su pago ✅, le enviaremos su clave de recojo 🔐, para que pueda retirar su pedido en la agencia sin inconvenientes 📦
|
||
|
||
"
|
||
. "Quedamos atentos a su confirmación.
|
||
"
|
||
. "Muchas gracias por su confianza 🤝
|
||
|
||
"
|
||
. "Floower Store 🛍️
|
||
"
|
||
. "Área de Atención al Cliente";
|
||
|
||
$replacements = [
|
||
'{NOMBRE_CLIENTE}' => $nombre_cliente,
|
||
'{PRODUCTO}' => $producto,
|
||
'{SEDE_ENVIO}' => $sede_envio,
|
||
'{MONTO_TOTAL}' => number_format($monto_total, 2),
|
||
'{ADELANTO}' => number_format($adelanto, 2),
|
||
'{SALDO_PENDIENTE}' => number_format($monto_debe, 2)
|
||
];
|
||
|
||
$whatsappMessage = str_replace(array_keys($replacements), array_values($replacements), $template);
|
||
$whatsappMessage = urlencode($whatsappMessage);
|
||
|
||
$celular = preg_replace('/[^0-9]/', '', $pedido['celular']);
|
||
if (strlen($celular) == 9) {
|
||
$celular = '51' . $celular;
|
||
}
|
||
|
||
$whatsappUrl = "https://api.whatsapp.com/send?phone={$celular}&text={$whatsappMessage}";
|
||
?>
|
||
<div class="mt-1">
|
||
<button type="button" class="btn btn-sm btn-info" title="Consultar Estado" data-bs-toggle="modal" data-bs-target="#trackingModal" data-order-number="<?php echo htmlspecialchars($pedido['codigo_rastreo'] ?? 'N/A'); ?>" data-order-code="<?php echo htmlspecialchars($pedido['codigo_tracking'] ?? 'N/A'); ?>">🔍</button>
|
||
<a href="https://rastrea.shalom.pe/rastrea" target="_blank" class="btn btn-sm btn-primary" title="Rastreo Shalom">🚚</a>
|
||
<a href="<?php echo $whatsappUrl; ?>" target="_blank" class="btn btn-sm btn-secondary whatsapp-icon" id="whatsapp-icon-<?php echo $pedido['id']; ?>" title="Enviar WhatsApp">💬</a>
|
||
</div>
|
||
</td>
|
||
<td><?php echo htmlspecialchars($pedido['agencia'] ?? 'SHALOM'); ?></td>
|
||
<td><?php echo htmlspecialchars($pedido['producto']); ?></td>
|
||
<td><?php echo htmlspecialchars($pedido['sede_envio'] ?? 'N/A'); ?></td>
|
||
<td><?php echo htmlspecialchars($pedido['cantidad'] ?: 1); ?></td>
|
||
<td><?php echo htmlspecialchars($pedido['monto_total']); ?></td>
|
||
<td><?php echo htmlspecialchars($pedido['monto_debe']); ?></td>
|
||
<td><?php echo htmlspecialchars($pedido['codigo_rastreo'] ?? 'N/A'); ?></td>
|
||
<td class="editable" data-id="<?php echo $pedido['id']; ?>" data-field="codigo_tracking"><?php echo htmlspecialchars($pedido['codigo_tracking'] ?? 'N/A'); ?></td>
|
||
<?php
|
||
$canSeeClave = ($user_role !== 'Asesor' || (!empty($pedido['numero_operacion']) && !empty($pedido['banco'])));
|
||
$isEditableClave = ($user_role !== 'Asesor') ? 'editable' : '';
|
||
?>
|
||
<td class="<?php echo $isEditableClave; ?>" data-id="<?php echo $pedido['id']; ?>" data-field="clave">
|
||
<?php echo $canSeeClave ? htmlspecialchars($pedido['clave'] ?? 'N/A') : '<i class="fas fa-eye-slash text-muted" title="Suba el número de operación y seleccione el banco para ver la clave"></i> <span class="text-muted" style="font-size: 0.8rem;">Oculto</span>'; ?>
|
||
</td>
|
||
<td><span class="badge" style="<?php echo getStatusStyle($pedido['estado']); ?>"><?php echo ($pedido['estado'] == 'Gestion') ? 'GESTIONES ⚙️' : htmlspecialchars($pedido['estado']); ?></span></td>
|
||
<td id="live-status-<?php echo $pedido['id']; ?>"><span class="badge bg-light text-dark">Pendiente</span></td>
|
||
<?php if ($user_role !== 'Asesor'): ?><td><?php echo htmlspecialchars($pedido['asesor_nombre'] ?? 'N/A'); ?></td><?php endif; ?>
|
||
<td><?php echo htmlspecialchars($pedido['created_at']); ?></td>
|
||
<td>
|
||
<?php if (!empty($pedido['voucher_restante_path'])): ?>
|
||
<a href="<?php echo htmlspecialchars($pedido['voucher_restante_path']); ?>" target="_blank">Ver</a>
|
||
<?php else:
|
||
?>N/A
|
||
<?php endif; ?>
|
||
</td>
|
||
<td>
|
||
<a href="pedido_form.php?id=<?php echo $pedido['id']; ?>" class="btn btn-sm btn-warning">Editar</a>
|
||
<?php if ($user_role === 'Administrador'): ?>
|
||
<a href="delete_pedido.php?id=<?php echo $pedido['id']; ?>" class="btn btn-sm btn-danger" onclick="return confirm('¿Estás seguro de que quieres eliminar este pedido?');">Eliminar</a>
|
||
<?php endif; ?>
|
||
</td>
|
||
</tr>
|
||
<?php endforeach; ?>
|
||
</tbody>
|
||
</table>
|
||
<?php if (empty($pedidos)): ?>
|
||
<p class="text-center">No hay pedidos que coincidan con el filtro.</p>
|
||
<?php endif; ?>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
|
||
|
||
<?php include 'layout_footer.php'; ?>
|
||
|
||
<script>
|
||
// DataTable initialization and existing modal logic
|
||
$(document).ready(function() {
|
||
$("#pedidos-table").DataTable({
|
||
"language": {
|
||
"url": "//cdn.datatables.net/plug-ins/1.10.25/i18n/Spanish.json"
|
||
},
|
||
"order": [[ 0, "desc" ]],
|
||
"paging": false,
|
||
"lengthChange": false,
|
||
"info": false
|
||
});
|
||
});
|
||
|
||
document.addEventListener('DOMContentLoaded', function() {
|
||
const table = document.querySelector('.table');
|
||
|
||
// Logic for editable cells (existing logic)
|
||
table.addEventListener('click', function(e) {
|
||
if (e.target && e.target.classList.contains('editable')) {
|
||
// ... (la lógica de edición en línea se mantiene igual)
|
||
}
|
||
});
|
||
|
||
// Logic for tracking modal (existing logic)
|
||
var trackingModal = document.getElementById('trackingModal');
|
||
trackingModal.addEventListener('show.bs.modal', function (event) {
|
||
var button = event.relatedTarget;
|
||
var orderNumber = button.getAttribute('data-order-number');
|
||
var orderCode = button.getAttribute('data-order-code');
|
||
|
||
var modalOrderNumberSpan = trackingModal.querySelector('#modal-order-number');
|
||
var modalOrderCodeSpan = trackingModal.querySelector('#modal-order-code');
|
||
var modalStatusDiv = trackingModal.querySelector('#modal-tracking-status');
|
||
|
||
modalOrderNumberSpan.textContent = orderNumber;
|
||
modalOrderCodeSpan.textContent = orderCode;
|
||
modalStatusDiv.innerHTML = '<p class="text-center">Consultando estado en Shalom...</p>';
|
||
|
||
if (orderNumber === 'N/A' || orderCode === 'N/A' || !orderNumber || !orderCode) {
|
||
modalStatusDiv.innerHTML = '<p class="text-danger text-center">No hay suficientes datos (Nº de Orden o Código de Orden) para consultar.</p>';
|
||
return;
|
||
}
|
||
|
||
fetch(`shalom_api.php?orderNumber=${encodeURIComponent(orderNumber)}&orderCode=${encodeURIComponent(orderCode)}`)
|
||
.then(response => {
|
||
if (!response.ok) {
|
||
return response.json().then(errorData => {
|
||
throw new Error(errorData.error || `Error del servidor: ${response.status}`);
|
||
});
|
||
}
|
||
return response.json();
|
||
})
|
||
.then(data => {
|
||
if (data.error) {
|
||
modalStatusDiv.innerHTML = `<p class="text-danger text-center"><strong>Error:</strong> ${data.error}</p>`;
|
||
} else if (data.search && data.search.success) {
|
||
const searchData = data.search.data;
|
||
const statusData = data.statuses.data;
|
||
const statusMessage = data.statuses.message || 'No disponible';
|
||
const upperStatus = statusMessage.toUpperCase();
|
||
|
||
// Determine progress and description
|
||
let progressWidth = 0;
|
||
let activeStep = 0;
|
||
let descriptionText = 'Su pedido está siendo procesado.';
|
||
|
||
if (upperStatus.includes('ENTREGADO')) {
|
||
progressWidth = 100;
|
||
activeStep = 4;
|
||
descriptionText = 'El pedido ha sido entregado satisfactoriamente.';
|
||
} else if (upperStatus.includes('DESTINO') || upperStatus.includes('REPARTO')) {
|
||
progressWidth = 66;
|
||
activeStep = 3;
|
||
descriptionText = 'Está listo para su recojo.';
|
||
} else if (upperStatus.includes('TRANSITO') || upperStatus.includes('TRÁNSITO')) {
|
||
progressWidth = 33;
|
||
activeStep = 2;
|
||
descriptionText = 'Su pedido se encuentra en camino a la ciudad de destino.';
|
||
} else {
|
||
progressWidth = 0;
|
||
activeStep = 1;
|
||
descriptionText = 'El pedido ha sido recibido en nuestra agencia de origen.';
|
||
}
|
||
|
||
// Format date
|
||
let formattedDate = new Date().toLocaleString('es-PE', { day: '2-digit', month: '2-digit', year: '2-digit', hour: '2-digit', minute: '2-digit' });
|
||
if (statusData.registrado && statusData.registrado.fecha) {
|
||
formattedDate = new Date(statusData.registrado.fecha).toLocaleString('es-PE', { day: '2-digit', month: '2-digit', year: '2-digit', hour: '2-digit', minute: '2-digit' });
|
||
}
|
||
|
||
const steps = ['En origen', 'En tránsito', 'En destino', 'Entregado'];
|
||
let stepsHtml = '';
|
||
steps.forEach((step, index) => {
|
||
const stepNum = index + 1;
|
||
const isActive = stepNum <= activeStep;
|
||
const isCurrent = stepNum === activeStep;
|
||
|
||
stepsHtml += `
|
||
<div class="text-center" style="width: 100px; position: relative; z-index: 2;">
|
||
<div style="width: 32px; height: 32px; background-color: ${isActive ? '#e30613' : 'white'}; border: 2px solid ${isActive ? '#e30613' : '#fce4e4'}; border-radius: 50%; margin: 0 auto 10px; display: flex; align-items: center; justify-content: center;">
|
||
${isActive ? '<i class="fas fa-check" style="color: white; font-size: 16px;"></i>' : ''}
|
||
</div>
|
||
<span style="font-size: 1rem; font-weight: ${isCurrent ? 'bold' : 'normal'}; color: ${isActive ? '#1a1a6e' : '#999'}; display: block; white-space: nowrap;">${step}</span>
|
||
</div>
|
||
`;
|
||
});
|
||
|
||
let html = `
|
||
<div style="font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; color: #333; background: white; padding: 40px 50px; border-radius: 15px; border: 1px solid #eee; box-shadow: 0 4px 12px rgba(0,0,0,0.05);">
|
||
<!-- Header Section -->
|
||
<div class="d-flex justify-content-between align-items-start mb-3 flex-wrap">
|
||
<div class="d-flex align-items-center mb-2">
|
||
<div class="me-4">
|
||
<!-- Illustration -->
|
||
<svg width="160" height="160" viewBox="0 0 200 200">
|
||
<!-- Dashed path -->
|
||
<path d="M40 80C60 80 70 130 100 130C130 130 140 80 160 80" stroke="#94a3b8" stroke-width="3" stroke-dasharray="6 6" fill="none" />
|
||
|
||
<!-- Small pin in distance -->
|
||
<g transform="translate(30, 65) scale(0.6)">
|
||
<path d="M15 0C6.7 0 0 6.7 0 15C0 26 15 40 15 40C15 40 30 26 30 15C30 6.7 23.3 0 15 0Z" fill="#1a1a6e"/>
|
||
<circle cx="15" cy="15" r="6" fill="white"/>
|
||
</g>
|
||
|
||
<!-- The Box -->
|
||
<g transform="translate(85, 95)">
|
||
<!-- Front face -->
|
||
<path d="M0 20 L55 38 V90 L0 72 Z" fill="#e30613"/>
|
||
<!-- Side face -->
|
||
<path d="M55 38 L95 22 V74 L55 90 Z" fill="#b90510"/>
|
||
<!-- Top face -->
|
||
<path d="M0 20 L40 0 L95 22 L55 38 Z" fill="#f14b55"/>
|
||
|
||
<!-- White stripe on top -->
|
||
<path d="M18 9 L58 27 L78 36 L38 18 Z" fill="white"/>
|
||
<!-- White stripe on side -->
|
||
<path d="M75 30 L95 22 V35 L75 43 Z" fill="white"/>
|
||
|
||
<!-- SHALOM Text -->
|
||
<text x="6" y="58" fill="white" font-family="Arial Black" font-weight="900" font-style="italic" font-size="11" transform="skewY(18)">SHALOM</text>
|
||
</g>
|
||
|
||
<!-- Large pin on box -->
|
||
<g transform="translate(108, 40)">
|
||
<path d="M25 0C11.2 0 0 11.2 0 25C0 43.3 25 66.7 25 66.7C25 66.7 50 43.3 50 25C50 11.2 38.8 0 25 0Z" fill="#1a1a6e"/>
|
||
<circle cx="25" cy="25" r="10" fill="white"/>
|
||
</g>
|
||
</svg>
|
||
</div>
|
||
<div>
|
||
<div class="d-flex align-items-center mb-1">
|
||
<h1 style="color: #e30613 !important; font-weight: 900; margin: 0; margin-right: 15px; text-transform: uppercase; font-size: 2.8rem;">${statusMessage.toUpperCase()}</h1>
|
||
<span style="border: 3px solid #e30613; color: #e30613; border-radius: 25px; padding: 4px 15px; font-size: 1.1rem; font-weight: bold;">
|
||
<i class="fas fa-download"></i> GRT
|
||
</span>
|
||
</div>
|
||
<p class="mb-1" style="color: #666; font-size: 1.1rem;">${descriptionText}</p>
|
||
<p style="color: #e30613; font-weight: bold; font-size: 1rem; margin: 0;">
|
||
<i class="fas fa-chevron-right"></i> Tiempo referencial de llegada 1 día.
|
||
</p>
|
||
</div>
|
||
</div>
|
||
<div class="text-sm-end">
|
||
<p class="mb-1" style="font-weight: bold; font-size: 1.1rem; color: #1a1a6e;">N° DE ORDEN: ${orderNumber}</p>
|
||
<p class="text-muted" style="font-size: 1rem;">Desde el ${formattedDate}</p>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Progress Bar -->
|
||
<div class="position-relative mb-4 mt-4" style="padding: 0 40px;">
|
||
<div class="progress" style="height: 10px; background-color: #fce4e4; border-radius: 5px;">
|
||
<div class="progress-bar" role="progressbar" style="width: ${progressWidth}%; background-color: #e30613;"></div>
|
||
</div>
|
||
<div class="d-flex justify-content-between position-absolute top-50 start-0 translate-middle-y w-100" style="padding: 0 20px;">
|
||
${stepsHtml}
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Footer Section -->
|
||
<div class="row mt-4 pt-4 border-top">
|
||
<div class="col-md-6 mb-2 mb-md-0">
|
||
<p class="mb-1" style="font-weight: bold; color: #1a1a6e; font-size: 1.1rem;">Origen: <span style="color: #888; font-weight: normal;">${searchData.origen.nombre || 'N/A'}</span></p>
|
||
</div>
|
||
<div class="col-md-6">
|
||
<p class="mb-1" style="font-weight: bold; color: #1a1a6e; font-size: 1.1rem;">Destino: <span style="color: #888; font-weight: normal;">${searchData.destino.nombre || 'N/A'}</span></p>
|
||
<p class="text-muted mb-0" style="font-size: 1rem;">${searchData.destino.direccion || ''}</p>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="d-grid gap-2 mt-4">
|
||
<button class="btn btn-success btn-lg" onclick="copyStatusToClipboard('${statusMessage}', '${orderNumber}', '${searchData.destino.nombre}')">
|
||
<i class="fab fa-whatsapp"></i> Copiar Resumen para Cliente
|
||
</button>
|
||
</div>
|
||
`;
|
||
|
||
modalStatusDiv.innerHTML = html;
|
||
} else {
|
||
modalStatusDiv.innerHTML = `<p class="text-warning text-center">No se pudo encontrar la guía.</p>`;
|
||
}
|
||
})
|
||
.catch(error => {
|
||
console.error('Error fetching tracking status:', error);
|
||
modalStatusDiv.innerHTML = `<p class="text-danger text-center"><strong>Error al consultar:</strong> ${error.message}</p>`;
|
||
});
|
||
});
|
||
|
||
// --- NEW ---
|
||
function verificarEstados() {
|
||
const rows = document.querySelectorAll('tr[data-order-number][data-order-code]');
|
||
const verifyButton = document.getElementById('verify-statuses-btn');
|
||
if(verifyButton) {
|
||
verifyButton.disabled = true;
|
||
verifyButton.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Verificando...';
|
||
}
|
||
|
||
|
||
rows.forEach((row, index) => {
|
||
setTimeout(() => {
|
||
const orderNumber = row.dataset.orderNumber;
|
||
const orderCode = row.dataset.orderCode;
|
||
const pedidoId = row.id.split('-')[1];
|
||
const statusCell = document.getElementById(`live-status-${pedidoId}`);
|
||
const whatsappIcon = document.getElementById(`whatsapp-icon-${pedidoId}`);
|
||
|
||
if (!statusCell) return;
|
||
|
||
if (orderCode === '26') {
|
||
statusCell.innerHTML = '<span class="badge bg-info">OLVA COURIER</span>';
|
||
return;
|
||
}
|
||
|
||
if (!orderNumber || !orderCode || orderNumber === 'N/A' || orderCode === 'N/A') {
|
||
statusCell.innerHTML = '<span class="badge bg-light text-dark">Sin datos</span>';
|
||
return;
|
||
}
|
||
|
||
statusCell.innerHTML = '<span class="badge bg-info text-dark">Verificando...</span>';
|
||
|
||
fetch(`shalom_api.php?orderNumber=${encodeURIComponent(orderNumber)}&orderCode=${encodeURIComponent(orderCode)}`)
|
||
.then(response => {
|
||
if (!response.ok) { throw new Error('Network response was not ok.'); }
|
||
return response.json();
|
||
})
|
||
.then(data => {
|
||
if (data.error) {
|
||
statusCell.innerHTML = `<span class="badge bg-danger" title="${data.error}">Error</span>`;
|
||
} else if (data.statuses && data.statuses.message) {
|
||
const statusMessage = data.statuses.message;
|
||
let badgeClass = 'bg-secondary';
|
||
let whatsappClass = 'btn-secondary';
|
||
|
||
if (statusMessage.toUpperCase().includes('EN DESTINO')) {
|
||
badgeClass = 'bg-success';
|
||
whatsappClass = 'btn-success'; // Green
|
||
} else if (statusMessage.toUpperCase().includes('EN TRANSITO')) {
|
||
badgeClass = 'bg-primary';
|
||
} else if (statusMessage.toUpperCase().includes('REGISTRADO')) {
|
||
badgeClass = 'bg-warning text-dark';
|
||
}
|
||
|
||
statusCell.innerHTML = `<span class="badge ${badgeClass}">${statusMessage}</span>`;
|
||
|
||
if (whatsappIcon) {
|
||
whatsappIcon.classList.remove('btn-secondary', 'btn-success');
|
||
whatsappIcon.classList.add(whatsappClass);
|
||
}
|
||
} else {
|
||
statusCell.innerHTML = '<span class="badge bg-warning text-dark">Inválido</span>';
|
||
}
|
||
})
|
||
.catch(error => {
|
||
console.error('Error fetching status:', error);
|
||
statusCell.innerHTML = '<span class="badge bg-danger">Fallo</span>';
|
||
})
|
||
.finally(() => {
|
||
// Re-enable button after the last request is done
|
||
if (index === rows.length - 1 && verifyButton) {
|
||
verifyButton.disabled = false;
|
||
verifyButton.innerHTML = 'Verificar Estados Ahora';
|
||
}
|
||
});
|
||
}, index * 500); // Stagger requests to avoid overwhelming the server/API
|
||
});
|
||
}
|
||
|
||
// Initial check on page load
|
||
verificarEstados();
|
||
|
||
// Add event listener for the manual verification button
|
||
const verifyButton = document.getElementById('verify-statuses-btn');
|
||
if (verifyButton) {
|
||
verifyButton.addEventListener('click', verificarEstados);
|
||
}
|
||
});
|
||
|
||
function copyStatusToClipboard(status, order, destination) {
|
||
const text = `📦 *Estado de tu pedido Shalom*\n\n` +
|
||
`🔖 *Nro de Orden:* ${order}\n` +
|
||
`📍 *Destino:* ${destination}\n` +
|
||
`🚚 *Estado:* ${status}\n\n` +
|
||
`¡Tu pedido está en camino! Gracias por tu confianza. ✨`;
|
||
|
||
navigator.clipboard.writeText(text).then(() => {
|
||
alert('Resumen copiado al portapapeles. Ya puedes pegarlo en WhatsApp.');
|
||
}).catch(err => {
|
||
console.error('Error al copiar:', err);
|
||
});
|
||
}
|
||
</script>
|