Tul xxx Tul
User / IP
:
216.73.216.159
Host / Server
:
45.84.207.204 / aircan.me
System
:
Linux lt-bnk-web1726.main-hosting.eu 5.14.0-611.36.1.el9_7.x86_64 #1 SMP PREEMPT_DYNAMIC Tue Mar 3 11:23:52 EST 2026 x86_64
Command
|
Upload
|
Create
Mass Deface
|
Jumping
|
Symlink
|
Reverse Shell
Ping
|
Port Scan
|
DNS Lookup
|
Whois
|
Header
|
cURL
:
/
home
/
u931257429
/
domains
/
consaboragourmet.com
/
public_html
/
admin
/
Viewing: delivery_history.php
<?php include '../components/connect.php'; require_once '../components/admin_roles.php'; session_start(); $admin_id = $_SESSION['admin_id'] ?? null; if(!$admin_id){ header('location:admin_login.php'); exit(); } ensureAdminRolesSchema($conn); $currentRole = getRoleBySession($conn); $canViewInsights = adminHasPermission($currentRole, 'orders_insights'); date_default_timezone_set('America/Bogota'); $today = new DateTime('today', new DateTimeZone('America/Bogota')); $tomorrow = (clone $today)->modify('+1 day'); $yesterday = (clone $today)->modify('-1 day'); // Determinar primera fecha disponible de pedidos $historic_start = $yesterday->format('Y-m-d'); $min_date_stmt = $conn->query("SELECT MIN(DATE(created_at)) AS min_date FROM `delivery_orders`"); if ($min_date_stmt) { $min_date_row = $min_date_stmt->fetch(PDO::FETCH_ASSOC); if (!empty($min_date_row['min_date'])) { $historic_start = $min_date_row['min_date']; } } // Filtros (por defecto: ayer) $max_history_date = $today->format('Y-m-d'); $fecha_desde = $canViewInsights && isset($_GET['fecha_desde']) && $_GET['fecha_desde'] !== '' ? $_GET['fecha_desde'] : $historic_start; $fecha_hasta = $canViewInsights && isset($_GET['fecha_hasta']) && $_GET['fecha_hasta'] !== '' ? $_GET['fecha_hasta'] : $max_history_date; if ($fecha_hasta > $max_history_date) $fecha_hasta = $max_history_date; if ($fecha_desde > $fecha_hasta) $fecha_desde = $fecha_hasta; $start_dt = DateTime::createFromFormat('Y-m-d H:i:s', $fecha_desde . ' 00:00:00', new DateTimeZone('America/Bogota')) ?: clone $yesterday; $start_dt->setTime(0,0,0); $end_dt = DateTime::createFromFormat('Y-m-d H:i:s', $fecha_hasta . ' 00:00:00', new DateTimeZone('America/Bogota')) ?: clone $yesterday; $end_dt->setTime(0,0,0); $end_dt->modify('+1 day'); if($end_dt > $tomorrow){ $end_dt = clone $tomorrow; } $start_datetime = $start_dt->format('Y-m-d H:i:s'); $end_datetime = $end_dt->format('Y-m-d H:i:s'); // Totales del rango (excluyendo hoy) $select_stats_range = $conn->prepare("SELECT COUNT(*) as total_pedidos, COALESCE(SUM(total_amount), 0) as total_recaudado FROM `delivery_orders` WHERE created_at >= ? AND created_at < ? AND status = 'entregado'"); $select_stats_range->execute([$start_datetime, $end_datetime]); $stats_range = $select_stats_range->fetch(PDO::FETCH_ASSOC) ?: ['total_pedidos' => 0, 'total_recaudado' => 0]; // Pedidos del rango (excluyendo hoy) $select_orders = $conn->prepare( "SELECT o.*, (SELECT GROUP_CONCAT(DISTINCT pr.name ORDER BY pr.name SEPARATOR ', ') FROM delivery_order_preparers dop JOIN preparers pr ON pr.id = dop.preparer_id WHERE dop.order_id = o.id) AS preparer_names, (SELECT GROUP_CONCAT(DISTINCT dop2.preparer_id ORDER BY dop2.preparer_id SEPARATOR ',') FROM delivery_order_preparers dop2 WHERE dop2.order_id = o.id) AS preparer_ids, prep.name AS preparer_name FROM `delivery_orders` o LEFT JOIN `preparers` prep ON o.preparer_id = prep.id WHERE o.created_at >= ? AND o.created_at < ? AND o.status = 'entregado' ORDER BY o.created_at ASC" ); $select_orders->execute([$start_datetime, $end_datetime]); $orders = $select_orders->fetchAll(PDO::FETCH_ASSOC); // Categorías y productos (para modal de edición) $select_categories = $conn->prepare("SELECT * FROM `categories` ORDER BY name ASC"); $select_categories->execute(); $categorias = $select_categories->fetchAll(PDO::FETCH_ASSOC); $select_products = $conn->prepare("SELECT p.*, c.name as category_name FROM `products` p LEFT JOIN `categories` c ON p.category = c.id ORDER BY c.name, p.name"); $select_products->execute(); $productos = $select_products->fetchAll(PDO::FETCH_ASSOC); $select_preparers = $conn->prepare("SELECT id, name FROM `preparers` WHERE status = 'activo' ORDER BY name ASC"); $select_preparers->execute(); $preparers = $select_preparers->fetchAll(PDO::FETCH_ASSOC); function normaliza_categoria($str){ $str = mb_strtolower($str, 'UTF-8'); $map = ['á'=>'a','à'=>'a','ä'=>'a','â'=>'a','Á'=>'a','À'=>'a','Â'=>'a','Ä'=>'a','é'=>'e','è'=>'e','ë'=>'e','ê'=>'e','É'=>'e','È'=>'e','Ê'=>'e','Ë'=>'e','í'=>'i','ì'=>'i','ï'=>'i','î'=>'i','Í'=>'i','Ì'=>'i','Î'=>'i','Ï'=>'i','ó'=>'o','ò'=>'o','ö'=>'o','ô'=>'o','Ó'=>'o','Ò'=>'o','Ô'=>'o','Ö'=>'o','ú'=>'u','ù'=>'u','ü'=>'u','û'=>'u','Ú'=>'u','Ù'=>'u','Û'=>'u','Ü'=>'u','ñ'=>'n','Ñ'=>'n','ç'=>'c','Ç'=>'c']; $str = strtr($str, $map); $str = preg_replace('/[^a-z0-9]+/','-',$str); $str = trim($str,'-'); return $str; } $businessName = getBusinessName($conn); $businessLogoVersion = getBusinessLogoVersion($conn); $iconHref = '../icon.php?size=64' . ($businessLogoVersion !== '' ? '&v=' . rawurlencode($businessLogoVersion) : ''); ?> <!DOCTYPE html> <html lang="es"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Historial de Pedidos | <?= htmlspecialchars($businessName); ?></title> <link rel="icon" href="<?= htmlspecialchars($iconHref); ?>" type="image/png"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css"> <link rel="stylesheet" href="../css/admin_style.css"> <style> :root { --color-primary:#b30000; --color-success:#28a745; --color-info:#17a2b8; --color-warning:#ffc107; --color-danger:#dc3545; } body { background: #f4f4f4; } .dashboard { padding: 1rem 1.2rem 3rem; } .section-title { font-size: 2.3rem; font-weight: 800; color: #111; margin: 0; } .section-header { display:flex; align-items:center; gap:.8rem; margin-bottom: 1rem; } .btn-back-header { margin-left:auto; padding:.85rem 1.8rem; border-radius:10px; border:1px solid rgba(0,0,0,0.12); background:#f3f3f3; color:#333; font-size:1.08rem; display:inline-flex; align-items:center; gap:.45rem; font-weight:700; text-decoration:none; white-space:nowrap; } .btn-back-header:hover { background:#e7e7e7; } .stats-container { display:flex; flex-wrap:wrap; gap:1.2rem; margin-bottom:2rem; align-items:stretch; } .stat-card { background: linear-gradient(135deg, rgba(255,255,255,0.95), rgba(255,255,255,0.88)); border-radius: 16px; padding: 1rem 1.2rem; box-shadow: 0 8px 20px rgba(0,0,0,0.08); color:#111; flex:1 1 320px; position:relative; overflow:hidden; } .stat-card.range { background:#ffffff; color:#111; padding: 0.9rem 1.1rem; flex:0 0 320px; max-width: 340px; border:1px solid rgba(0,0,0,0.06); box-shadow: 0 12px 28px rgba(0,0,0,0.08); } .stat-header { display:flex; align-items:center; justify-content:space-between; } .stat-label { font-weight:800; } .stat-content { display:flex; gap:0.9rem; align-items:center; justify-content:space-between; margin-top:.35rem; } .stat-left { flex:1; } .stat-value { font-size:1.9rem; font-weight:900; } .stat-right { min-width: 150px; background: rgba(255,255,255,0.18); border-radius: 12px; padding:.7rem; text-align:right; } .stat-right-label { font-size:.85rem; opacity:.9; text-transform:uppercase; letter-spacing:1px; font-weight:700; } .stat-right-amount { font-size:1.4rem; font-weight:900; } .stat-card.range .stat-right { background:#f8f9fa; border:1px solid rgba(0,0,0,0.05); } .stat-card.range .stat-right-label { color:#444; opacity:0.8; } .stat-card.range .stat-right-amount { color:#222; } .stat-card.range .stat-label { color:#222; } .order-actions { display:flex; gap:.5rem; margin-top:.6rem; } .btn-action { padding:.6rem .9rem; border:none; border-radius:8px; font-weight:800; display:inline-flex; align-items:center; gap:.4rem; cursor:pointer; } .btn-status { background:#f1f1f1; color:#333; } .btn-edit { background: linear-gradient(135deg, var(--color-info) 0%, #117a8b 100%); color:#fff; } .btn-delete { background: linear-gradient(135deg, #dc3545 0%, #a71d2a 100%); color:#fff; } .btn-action i { font-size: .9rem; } .modal-overlay { position: fixed; inset: 0; background: rgba(0,0,0,0.5); display: none; align-items: center; justify-content: center; z-index: 2000; } .modal-overlay.show { display: flex; } .modal-container { width: min(1100px, 96%); max-height: 92vh; background: #fff; border-radius: 14px; overflow: hidden; display:flex; flex-direction:column; box-shadow: 0 18px 48px rgba(0,0,0,0.2); } .modal-header { padding: 1rem 1.2rem; display:flex; justify-content:space-between; align-items:center; border-bottom: 1px solid #eee; } .modal-title { font-weight: 900; font-size: 1.2rem; } .modal-body { padding: 1rem 1.2rem; overflow: auto; } .modal-footer { padding: .9rem 1.2rem; display:flex; gap:.6rem; justify-content:flex-end; border-top: 1px solid #eee; } .form-group { margin-bottom: .8rem; } .form-label { font-weight: 700; color:#111; margin-bottom:.35rem; display:block; } .form-control, .form-select { width:100%; padding:.8rem 1rem; border:2px solid #e6e6e6; border-radius:10px; font-size:1rem; } .grid-three { display:grid; grid-template-columns: 0.9fr 1.4fr 0.9fr; gap: 1.2rem; } .products-container { max-height: 58vh; overflow: auto; border: 2px solid #f0f0f0; border-radius: 12px; padding: 1rem; background: #f9fafb; } .category-block { display:none; margin-bottom: 1.1rem; background:#fff; border-radius:10px; padding: .9rem; border:1px solid #f1f1f1; } .category-placeholder { display:flex; align-items:center; justify-content:center; text-align:center; padding:1.4rem; border:2px dashed #d9d9d9; border-radius:12px; color:#777; font-weight:600; background:#fff; min-height:120px; margin-bottom:1rem; } .category-title { color: var(--color-primary); font-size:1.1rem; font-weight:800; margin:0 0 .7rem 0; } .products-grid { display:grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap:.8rem; } .product-card { background:#fff; border:1px solid #eee; border-radius:12px; padding:.7rem; display:flex; align-items:center; gap:.8rem; transition: box-shadow .2s ease; } .product-card:hover { box-shadow: 0 10px 20px rgba(0,0,0,0.06); } .product-image { width:56px; height:56px; object-fit:cover; border-radius:10px; } .product-name { font-weight:700; color:#222; } .product-price { color: #28a745; font-weight:700; font-size:.95rem; } .product-quantity { display:flex; align-items:center; gap:.45rem; } .btn-quantity { width:32px; height:32px; border:1px solid #ddd; background:#fff; border-radius:8px; cursor:pointer; font-weight:800; } .quantity-display { min-width:28px; text-align:center; font-weight:800; } .cart-sticky { position: sticky; top: .25rem; } .cart-section { margin-top:1rem; padding:1.1rem; background:#fff; border:2px dashed #28a745; border-radius:12px; } .cart-items { max-height: 200px; overflow:auto; display:flex; flex-direction:column; gap:.45rem; } .cart-title { font-size:1.1rem; font-weight:800; margin:0 0 .6rem 0; display:flex; justify-content:space-between; align-items:center; } .cart-item { display:flex; justify-content:space-between; align-items:center; gap:.8rem; padding:.55rem .65rem; border:1px solid #e6f5ea; border-radius:10px; background:linear-gradient(90deg, rgba(232,255,239,0.7), rgba(255,255,255,0.9)); box-shadow:0 4px 10px rgba(40,167,69,0.08); transition: transform .2s ease, box-shadow .2s ease; } .cart-item:hover { transform: translateY(-2px); box-shadow:0 8px 18px rgba(40,167,69,0.12); } .cart-item-info { display:flex; flex-direction:column; color:#1f3d2c; font-weight:600; } .cart-item-actions { display:flex; align-items:center; gap:.4rem; } .cart-remove-btn { border:none; background:rgba(220,53,69,0.12); color:#dc3545; border-radius:999px; padding:.35rem .75rem; font-size:.85rem; font-weight:700; cursor:pointer; transition: background .2s ease, transform .2s ease; display:flex; align-items:center; gap:.35rem; } .cart-remove-btn:hover { background:rgba(220,53,69,0.22); transform: translateY(-1px); } .cart-item-subtotal { font-weight:800; color:#1e7e34; font-size:1rem; } .cart-total { text-align:right; font-size:1.2rem; font-weight:900; color:#28a745; margin-top:.8rem; } .cart-empty { display:flex; flex-direction:column; align-items:center; justify-content:center; gap:.35rem; color:#6f7d6d; padding:1.2rem; background:#f6fff7; border-radius:12px; border:1px dashed rgba(40,167,69,0.25); } .cart-empty i { font-size:1.7rem; color:#28a745; } .cart-empty small { font-weight:500; color:#9aa0a6; } .btn-primary { background: linear-gradient(135deg, #28a745 0%, #1e7e34 100%); color:#fff; border:none; border-radius:10px; padding:.9rem 1.4rem; font-weight:800; cursor:pointer; } .btn-secondary { background:#f1f1f1; color:#333; border:none; border-radius:10px; padding:.9rem 1.4rem; font-weight:800; cursor:pointer; } .preparer-group .preparer-control { display:flex; flex-direction:column; gap:0.65rem; } .preparer-checklist { display:grid; grid-template-columns:repeat(auto-fit,minmax(200px,1fr)); gap:0.5rem; border:1px dashed rgba(15,23,42,0.12); background:#fff; border-radius:14px; padding:0.75rem; max-height:200px; overflow:auto; } .check-item { display:flex; align-items:center; gap:0.5rem; border-radius:12px; border:1px solid rgba(15,23,42,0.08); padding:0.45rem 0.6rem; background:#f8fafc; transition:border .2s, background .2s; } .check-item.is-selected { border-color:#b30000; background:rgba(179,0,0,0.08); } .check-item.is-primary { box-shadow:0 0 0 2px rgba(179,0,0,0.25); } .checkbox-part { display:flex; align-items:center; gap:0.45rem; font-weight:600; color:#1f2937; } .checkbox-part input { width:18px; height:18px; accent-color:#b30000; } .preparer-hint { color:#6b7280; font-size:0.85rem; } @media (max-width: 1200px) { .modal-container { width: min(980px, 94%); } .grid-three { grid-template-columns: 1fr; gap: 1rem; } .cart-sticky { position: static; } } @media (max-width: 768px) { .modal-container { width: 100%; height: 100vh; max-height: none; border-radius: 0; } .modal-header, .modal-footer { padding: 0.9rem 1rem; } .modal-body { padding: 1rem; max-height: calc(100vh - 150px); } .products-container { max-height: 46vh; padding: 0.8rem; } .products-grid { grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); } .cart-section { margin-top: 0; } } @media (max-width: 540px) { .products-grid { grid-template-columns: repeat(auto-fill, minmax(160px, 1fr)); } .modal-title { font-size: 1.05rem; } .btn-primary, .btn-secondary { width: 100%; justify-content: center; } .modal-footer { flex-direction: column; align-items: stretch; } } .stat-card.filters-card { display:flex; flex-direction:column; gap:1.1rem; flex:1 1 460px; min-width:320px; } .stat-card.filters-card .filters-header { display:flex; align-items:center; gap:.6rem; font-weight:800; color:#111; font-size:1.05rem; } .filters-form { display:grid; grid-template-columns: repeat(auto-fit, minmax(170px, 1fr)); align-items:end; gap:1rem; } .filter-group { display:flex; flex-direction:column; gap:.4rem; } .filter-group label { font-weight:700; color:#111; } .filter-group input { padding:.8rem 1rem; border:2px solid #e6e6e6; border-radius:10px; font-size:1rem; } .filter-action { display:flex; align-items:stretch; } .filters-form .btn { width:100%; justify-content:center; } @media (max-width: 520px){ .filters-form { grid-template-columns: 1fr; } } .btn { padding:.9rem 1.6rem; border:none; border-radius:10px; font-weight:800; display:inline-flex; gap:.5rem; align-items:center; cursor:pointer; } .btn-filter { background: linear-gradient(135deg, var(--color-primary) 0%, #7a0000 100%); color:#fff; } .btn-reset { background:#fff; color: var(--color-primary); border:1px solid rgba(179,0,0,0.25); } .btn-back { background:#f1f1f1; color:#333; text-decoration:none; } .orders-container { display: grid; grid-template-columns: repeat(auto-fill, minmax(350px, 1fr)); gap: 2rem; margin-bottom: 3rem; } @media (max-width: 900px) { .stats-container { flex-direction: column; } .stat-card.range, .stat-card.filters-card { flex: 1 1 100%; min-width: 100%; } } @media (max-width: 768px) { .stat-card.filters-card { padding: 1rem 1.1rem; } .filters-form { grid-template-columns: 1fr; gap: 0.8rem; } .filter-group { width: 100%; } .filter-action { width: 100%; } .filter-action .btn { width: 100%; } .products-grid { grid-template-columns: 1fr; } .product-card { flex-direction: row; align-items: center; } .product-card .product-quantity { margin-left: auto; } .orders-container { grid-template-columns: minmax(0, 1fr); gap: 1.2rem; justify-items: center; } .order-card { width: min(560px, 100%); margin: 0 auto; border-radius: 18px; padding: 1.2rem; } } @media (max-width: 520px) { .filters-form { gap: 0.7rem; } .products-grid { grid-template-columns: 1fr; } .product-card { padding: 0.65rem; border-radius: 10px; } .product-card .product-name { font-size: 0.92rem; } .product-card .product-price { font-size: 0.9rem; } .orders-container { gap: 1rem; } .order-card { width: 100%; padding: 1rem; border-radius: 16px; } body.delivery-history-page .order-actions { display: flex; flex-wrap: wrap; gap: 0.6rem; } body.delivery-history-page .btn-action { flex: 1 1 calc(50% - 0.6rem); min-width: 0; } } @media (max-width: 360px) { body.delivery-history-page .btn-action { flex-basis: 100%; } } .order-card { background: rgba(255,255,255,0.95); backdrop-filter: blur(10px); border-radius: 20px; padding: 1.5rem; box-shadow: 0 10px 30px rgba(0,0,0,0.1); transition: transform 0.3s ease, box-shadow 0.3s ease; border: 1px solid rgba(0,0,0,0.05); position: relative; overflow: hidden; } .order-card:hover { transform: translateY(-5px); box-shadow: 0 15px 40px rgba(0,0,0,0.15); } .order-status { position: absolute; top: 0; right: 0; padding: 0.5rem 1rem; border-radius: 0 20px 0 20px; font-weight: 600; font-size: 0.85rem; text-transform: uppercase; } .order-status.pendiente { background: var(--color-warning); color: #333; } .order-status.en_preparacion { background: var(--color-info); color: white; } .order-status.en_camino { background: #6f42c1; color: white; } .order-status.entregado { background: var(--color-success); color: white; } .order-status.cancelado { background: var(--color-danger); color: white; } .order-header { margin-bottom: 1rem; padding-bottom: 1rem; border-bottom: 2px solid #f0f0f0; } .order-number { font-size: 1.2rem; font-weight: 800; color: var(--color-primary); margin-bottom: 0.5rem; } .order-datetime { font-size: 0.9rem; color: #666; display: flex; align-items: center; gap: 0.5rem; } .customer-info { margin-bottom: 1rem; } .customer-name { font-weight: 700; font-size: 1.1rem; margin-bottom: 0.5rem; color: #333; } .customer-detail { display: flex; align-items: center; gap: 0.5rem; margin-bottom: 0.3rem; color: #666; font-size: 0.95rem; } .order-items { background: #f8f9fa; border-radius: 10px; padding: 1rem; margin-bottom: 1rem; } .order-items-title { font-weight: 600; margin-bottom: 0.5rem; color: #333; } .order-item { display: flex; justify-content: space-between; margin-bottom: 0.3rem; padding: 0.3rem 0; border-bottom: 1px solid #e0e0e0; font-size: 0.9rem; } .order-item:last-child { border-bottom: none; } .order-total { background: #f5f5f5; color: #222; padding: 1rem; border-radius: 10px; display: flex; justify-content: space-between; align-items: center; font-size: 1.2rem; font-weight: 700; margin-bottom: 1rem; border: 1px solid #e0e0e0; } .order-total span:last-child { color: #1e7e34; } body.delivery-history-page .order-actions { display: flex; gap: 0.6rem; flex-wrap: wrap; justify-content: flex-start; } body.delivery-history-page .btn-action { flex: 1 1 150px; min-width: 150px; padding: 0.75rem 0.9rem; border: none; border-radius: 10px; font-weight: 600; cursor: pointer; transition: transform 0.2s ease, box-shadow 0.2s ease; display: flex; align-items: center; justify-content: center; gap: 0.5rem; white-space: nowrap; } .btn-action:hover { transform: translateY(-2px); box-shadow: 0 5px 15px rgba(0,0,0,0.2); } .btn-edit { background: linear-gradient(135deg, var(--color-info) 0%, #117a8b 100%); color: white; } .btn-print { background: linear-gradient(135deg, #f97316 0%, #ea580c 100%); color: #fff; } .btn-delete { background: linear-gradient(135deg, var(--color-danger) 0%, #a71d2a 100%); color: white; } .btn-status { background: linear-gradient(135deg, #a8adb7 0%, #6f7682 100%); color: #fff; } .empty-state { text-align:center; color:#666; padding:2rem 0; display:flex; flex-direction:column; gap:.6rem; align-items:center; justify-content:center; min-height:220px; background:rgba(255,255,255,0.8); border-radius:16px; box-shadow:0 10px 30px rgba(0,0,0,0.08); } body.delivery-history-page { --color-primary: #0ea5e9; --color-success: #22c55e; --color-warning: #f59e0b; --color-info: #0ea5e9; --color-danger: #ef4444; background: linear-gradient(135deg, #f5f9ff 0%, #fff7f3 100%); min-height: 100vh; } body.delivery-history-page .section-title { color: #0f172a; font-weight: 900; letter-spacing: .2px; } body.delivery-history-page .btn-back-header, body.delivery-history-page .btn-reset { background: rgba(255, 255, 255, 0.85); color: #0f172a; border: 1px solid rgba(148, 163, 184, 0.55); box-shadow: 0 10px 24px rgba(15, 23, 42, 0.10); backdrop-filter: blur(6px); } body.delivery-history-page .btn-back-header:hover, body.delivery-history-page .btn-reset:hover { background: rgba(255, 255, 255, 0.92); border-color: rgba(148, 163, 184, 0.75); box-shadow: 0 12px 28px rgba(15, 23, 42, 0.12); } body.delivery-history-page .btn-filter { background: linear-gradient(135deg, #0ea5e9, #2563eb); color: #fff; box-shadow: 0 12px 26px rgba(37, 99, 235, 0.22); } body.delivery-history-page .btn-filter:hover { filter: brightness(1.02); box-shadow: 0 14px 30px rgba(37, 99, 235, 0.26); } body.delivery-history-page .stat-card, body.delivery-history-page .order-card, body.delivery-history-page .empty-state { border: 1px solid rgba(226, 232, 240, 0.85); box-shadow: 0 18px 42px rgba(17, 24, 39, 0.10); } body.delivery-history-page .stat-card.range { box-shadow: 0 18px 42px rgba(17, 24, 39, 0.10); } body.delivery-history-page .filters-form input[type="date"] { background: rgba(255,255,255,0.92); border: 1px solid rgba(148, 163, 184, 0.55); box-shadow: 0 10px 24px rgba(15, 23, 42, 0.08); } body.delivery-history-page .filters-card { background: #fff; border-radius: 16px; padding: 1rem 1.2rem; box-shadow: 0 10px 24px rgba(15, 23, 42, 0.08); border: 1px solid rgba(15, 23, 42, 0.06); display: flex; flex-wrap: wrap; gap: 1rem; align-items: flex-end; align-content: flex-start; align-self: flex-start; margin-bottom: 0; flex: 1 1 460px; min-width: 320px; } body.delivery-history-page .filters-card label { font-weight: 700; color: #1f2937; font-size: 0.95rem; margin-bottom: 0.35rem; display: block; } body.delivery-history-page .filters-card .form-group { margin-bottom: 0; } body.delivery-history-page .filters-card input { border: 2px solid rgba(15, 23, 42, 0.08); border-radius: 12px; padding: 0.65rem 0.85rem; font-size: 1rem; min-width: 180px; } body.delivery-history-page .filters-card input:focus { border-color: #0ea5e9; outline: none; box-shadow: 0 0 0 3px rgba(14, 165, 233, 0.18); } body.delivery-history-page .filters-card .btn { border: none; border-radius: 12px; padding: 0.85rem 1.4rem; font-size: 1rem; font-weight: 700; display: inline-flex; align-items: center; gap: 0.6rem; cursor: pointer; text-decoration: none; justify-content: center; white-space: nowrap; } body.delivery-history-page .btn.btn-outline { background: rgba(255, 255, 255, 0.85); color: #0f172a; border: 1px solid rgba(148, 163, 184, 0.55); box-shadow: 0 10px 24px rgba(15, 23, 42, 0.10); backdrop-filter: blur(6px); } body.delivery-history-page .stats-container { align-items: flex-start; } @media (max-width: 900px) { body.delivery-history-page .filters-card { flex: 0 0 auto; } } @media (max-width: 768px){ body.delivery-history-page .filters-card { width: 100%; min-width: 100%; } body.delivery-history-page .filters-card input { min-width: unset; width: 100%; } body.delivery-history-page .filters-card .btn { width: 100%; } } @media (max-width: 600px){ body.delivery-history-page .filters-card { gap: 0.8rem; padding: 0.9rem; display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); grid-auto-rows: min-content; align-content: flex-start; } body.delivery-history-page .filters-card .form-group { flex: unset; } body.delivery-history-page .filters-card .form-group:nth-child(1), body.delivery-history-page .filters-card .form-group:nth-child(2) { grid-column: 1 / -1; } body.delivery-history-page .filters-card .form-group:nth-child(3) { grid-column: 1; } body.delivery-history-page .filters-card .form-group:nth-child(4) { grid-column: 2; } } body.delivery-history-page .filters-form input[type="date"]:focus { outline: none; border-color: rgba(37, 99, 235, 0.55); box-shadow: 0 0 0 4px rgba(37, 99, 235, 0.12), 0 10px 24px rgba(15, 23, 42, 0.10); } body.delivery-history-page .order-number { color: #0ea5e9; } body.delivery-history-page .btn-action { font-weight: 900; letter-spacing: .2px; } body.delivery-history-page .btn-status { background: linear-gradient(135deg, rgba(255,255,255,0.85), rgba(248,250,252,0.85)); color: #0f172a; border: 1px solid rgba(148, 163, 184, 0.55); box-shadow: 0 10px 24px rgba(15, 23, 42, 0.10); } body.delivery-history-page .btn-edit { background: linear-gradient(135deg, #0ea5e9, #2563eb); } body.delivery-history-page .btn-print { background: linear-gradient(135deg, #f97316, #ea580c); } body.delivery-history-page .btn-delete { background: linear-gradient(135deg, #ef4444, #b91c1c); } body.delivery-history-page .modal-overlay { background: rgba(17,24,39,0.55); backdrop-filter: blur(4px); } body.delivery-history-page .modal-container { border-radius: 20px; border: 1px solid rgba(226, 232, 240, 0.85); background: linear-gradient(180deg, rgba(255,255,255,0.98), rgba(255,255,255,0.94)); } body.delivery-history-page .modal-header { background: linear-gradient(90deg, rgba(14,165,233,0.08), transparent); } body.delivery-history-page .btn-primary { background: linear-gradient(135deg, #0ea5e9, #2563eb); border-radius: 14px; box-shadow: 0 12px 26px rgba(37, 99, 235, 0.22); } body.delivery-history-page .btn-secondary { background: rgba(255, 255, 255, 0.85); color: #0f172a; border: 1px solid rgba(148, 163, 184, 0.55); border-radius: 14px; box-shadow: 0 10px 24px rgba(15, 23, 42, 0.10); } </style> </head> <body class="admin-panel delivery-history-page"> <?php include '../components/admin_header.php' ?> <section class="dashboard"> <div class="section-header"> <h1 class="section-title">Historial de Pedidos</h1> <a href="delivery_orders.php" class="btn-back-header"><i class="fas fa-arrow-left"></i> Volver</a> </div> <?php if ($canViewInsights): ?> <div class="stats-container"> <div class="stat-card range"> <div class="stat-header"> <span class="stat-label">Pedidos Entregados en Rango</span> <i class="fas fa-chart-line"></i> </div> <div class="stat-content"> <div class="stat-left"> <div class="stat-value"><?php echo (int)$stats_range['total_pedidos']; ?></div> <div>Pedidos entregados</div> </div> <div class="stat-right"> <div class="stat-right-label">Total recaudado</div> <div class="stat-right-amount"><?php echo htmlspecialchars(formatMoney((float)$stats_range['total_recaudado'], $conn)); ?></div> </div> </div> </div> <form class="filters-card" method="GET"> <div class="form-group"> <label for="fecha_desde">Desde</label> <input type="date" id="fecha_desde" name="fecha_desde" value="<?php echo htmlspecialchars($fecha_desde); ?>"> </div> <div class="form-group"> <label for="fecha_hasta">Hasta</label> <input type="date" id="fecha_hasta" name="fecha_hasta" value="<?php echo htmlspecialchars($fecha_hasta); ?>"> </div> <div class="form-group"> <button class="btn btn-primary" type="submit"><i class="fas fa-search"></i> Aplicar</button> </div> <div class="form-group"> <a class="btn btn-outline" href="delivery_history.php"><i class="fas fa-undo"></i> Restablecer</a> </div> </form> </div> <?php endif; ?> <div class="orders-container"> <?php if(!empty($orders)) { foreach($orders as $index => $order){ $items = json_decode($order['order_items'], true); $preparerNames = trim((string)($order['preparer_names'] ?? '')); if($preparerNames === '' && !empty($order['preparer_name'])){ $preparerNames = (string)$order['preparer_name']; } $preparerIdsAttr = trim((string)($order['preparer_ids'] ?? '')); if($preparerIdsAttr === '' && isset($order['preparer_id']) && $order['preparer_id'] !== null){ $preparerIdsAttr = (string)(int)$order['preparer_id']; } ?> <div class="order-card" data-order-id="<?php echo (int)$order['id']; ?>" data-customer="<?php echo htmlspecialchars($order['customer_name'], ENT_QUOTES); ?>" data-phone="<?php echo htmlspecialchars($order['phone'], ENT_QUOTES); ?>" data-address="<?php echo htmlspecialchars($order['address'], ENT_QUOTES); ?>" data-payment="<?php echo htmlspecialchars($order['payment_method'], ENT_QUOTES); ?>" data-notes="<?php echo htmlspecialchars($order['notes'], ENT_QUOTES); ?>" data-status="<?php echo htmlspecialchars($order['status'], ENT_QUOTES); ?>" data-items="<?php echo htmlspecialchars(base64_encode($order['order_items']), ENT_QUOTES); ?>" data-preparer-id="<?php echo isset($order['preparer_id']) ? (int)$order['preparer_id'] : ''; ?>" data-preparer-ids="<?php echo htmlspecialchars($preparerIdsAttr, ENT_QUOTES); ?>"> <span class="order-status <?php echo htmlspecialchars($order['status']); ?>"><?php echo ucwords(str_replace('_',' ', $order['status'])); ?></span> <div class="order-header"> <div class="order-number">Pedido #<?php echo (isset($order['order_number']) && (int)$order['order_number'] > 0) ? (int)$order['order_number'] : ($index + 1); ?></div> <div class="order-datetime"><i class="far fa-clock"></i> <?php echo date('d/m/Y h:i A', strtotime($order['created_at'])); ?></div> </div> <div class="customer-info"> <div class="customer-name"><?php echo htmlspecialchars($order['customer_name']); ?></div> <div class="customer-detail"><i class="fas fa-phone"></i> <?php echo htmlspecialchars($order['phone']); ?></div> <div class="customer-detail"><i class="fas fa-map-marker-alt"></i> <?php echo htmlspecialchars($order['address']); ?></div> <div class="customer-detail"><i class="fas fa-money-bill-wave"></i> <?php echo ucfirst($order['payment_method']); ?></div> <?php if($preparerNames !== ''): ?> <div class="customer-detail"><i class="fas fa-user-tie"></i> Preparadores: <?php echo htmlspecialchars($preparerNames); ?></div> <?php endif; ?> </div> <div class="order-items"> <div class="order-items-title">Productos:</div> <?php if(is_array($items)) { foreach($items as $item) { ?> <div class="order-item"><span><?php echo (int)$item['cantidad']; ?>x <?php echo htmlspecialchars($item['nombre']); ?></span><span><?php echo htmlspecialchars(formatMoney(((float)$item['precio'] * (int)$item['cantidad']), $conn)); ?></span></div> <?php } } ?> </div> <div class="order-total"><span>Total:</span><span><?php echo htmlspecialchars(formatMoney((float)$order['total_amount'], $conn)); ?></span></div> <?php if(!empty($order['notes'])) { ?><div class="customer-detail" style="background:#fff3cd; padding:.5rem; border-radius:6px; margin-top:.5rem;"><i class="fas fa-sticky-note"></i> <?php echo htmlspecialchars($order['notes']); ?></div><?php } ?> <div class="order-actions"> <button class="btn-action btn-status" onclick="cambiarEstado(<?php echo (int)$order['id']; ?>, '<?php echo htmlspecialchars($order['status'], ENT_QUOTES); ?>')"><i class="fas fa-sync-alt"></i> Estado</button> <button class="btn-action btn-print" onclick="imprimirPedido(<?php echo (int)$order['id']; ?>)"><i class="fas fa-print"></i> Imprimir</button> <button class="btn-action btn-edit" onclick="mostrarModalEditar(this)"><i class="fas fa-edit"></i> Editar</button> <button class="btn-action btn-delete" onclick="eliminarPedido(<?php echo (int)$order['id']; ?>)"><i class="fas fa-trash"></i> Eliminar</button> </div> </div> <?php } } else { ?> <div class="empty-state" style="margin:auto; width:100%; max-width:520px;"> <i class="fas fa-box-open" style="font-size:2rem;"></i> <h3>No hay pedidos para el rango seleccionado</h3> <p>Cambia el rango de fechas para ver otros días</p> </div> <?php } ?> </div> <!-- Modal Editar Pedido --> <div class="modal-overlay" id="editOrderOverlay"> <div class="modal-container" role="dialog" aria-modal="true" aria-labelledby="editOrderTitle"> <div class="modal-header"> <div class="modal-title" id="editOrderTitle"><i class="fas fa-edit"></i> Editar Pedido a Domicilio</div> <button class="modal-close" id="closeEditOrder" aria-label="Cerrar"><i class="fas fa-times"></i></button> </div> <div class="modal-body"> <form id="editOrderForm"> <input type="hidden" name="order_id" id="editOrderId"> <div class="grid-three"> <div> <div class="form-group"> <label class="form-label" for="editCustomerName">Nombre y Apellido</label> <input type="text" id="editCustomerName" name="customer_name" class="form-control" required> </div> <div class="form-group"> <label class="form-label" for="editPhone">Teléfono Celular</label> <input type="tel" id="editPhone" name="phone" class="form-control" required> </div> <div class="form-group"> <label class="form-label" for="editAddress">Dirección</label> <textarea id="editAddress" name="address" class="form-control" rows="3" required></textarea> </div> <div class="form-group"> <label class="form-label" for="editPayment">Método de Pago</label> <select id="editPayment" name="payment_method" class="form-select" required> <option value="">Seleccione un método</option> <option value="efectivo">Efectivo</option> <option value="transferencia">Transferencia</option> </select> </div> <div class="form-group"> <label class="form-label" for="editStatus">Estado del Pedido</label> <select id="editStatus" name="status" class="form-select" required> <option value="pendiente">Pendiente</option> <option value="en_preparacion">En Preparación</option> <option value="en_camino">En Camino</option> <option value="entregado">Entregado</option> <option value="cancelado">Cancelado</option> </select> </div> <div class="form-group preparer-group"> <label class="form-label">Preparadores</label> <div class="preparer-control" data-context="history"> <div class="preparer-checklist" id="historyPreparerChecklist"> <?php foreach($preparers as $prep): ?> <div class="check-item" data-preparer-id="<?= (int)$prep['id']; ?>"> <label class="checkbox-part"> <input type="checkbox" class="preparer-checkbox" value="<?= (int)$prep['id']; ?>"> <span><?= htmlspecialchars($prep['name']); ?></span> </label> </div> <?php endforeach; ?> </div> <small class="preparer-hint">Marca a los preparadores involucrados (el primero será el principal).</small> </div> </div> <div class="form-group"> <label class="form-label" for="editNotes">Notas (Opcional)</label> <textarea id="editNotes" name="notes" class="form-control" rows="2"></textarea> </div> </div> <div> <div class="form-group"> <label class="form-label" for="editModalCategoryFilter">Filtrar por Categoría</label> <select id="editModalCategoryFilter" class="form-select"> <option value="">Seleccione una categoría</option> <?php foreach($categorias as $cat): ?> <option value="<?= normaliza_categoria($cat['name']) ?>"><?= htmlspecialchars($cat['name']) ?></option> <?php endforeach; ?> </select> </div> <div class="form-group"> <div class="products-container"> <div id="editCategoryPlaceholder" class="category-placeholder">Selecciona una categoría para ver los productos disponibles.</div> <?php $productosPorCategoria = []; foreach ($productos as $producto) { $ck = normaliza_categoria($producto['category_name']); if (!isset($productosPorCategoria[$ck])) $productosPorCategoria[$ck] = []; $productosPorCategoria[$ck][] = $producto; } foreach ($categorias as $cat): $key = normaliza_categoria($cat['name']); if (!isset($productosPorCategoria[$key])) continue; ?> <div class="category-block categoria-<?= $key ?>" data-category="<?= $key ?>"> <h3 class="category-title"><?= htmlspecialchars($cat['name']) ?></h3> <div class="products-grid"> <?php foreach ($productosPorCategoria[$key] as $p): ?> <div class="product-card"> <img src="../uploaded_img/<?= htmlspecialchars($p['image']) ?>" alt="<?= htmlspecialchars($p['name']) ?>" class="product-image"> <div style="flex:1;"> <div class="product-name"><?= htmlspecialchars($p['name']) ?></div> <div class="product-price"><?= htmlspecialchars(formatMoney((float)$p['price'], $conn)); ?></div> </div> <div class="product-quantity"> <button type="button" class="btn-quantity" onclick="updateEditQuantity(<?= (int)$p['id'] ?>, -1, '<?= htmlspecialchars($p['name'], ENT_QUOTES) ?>', <?= (float)$p['price'] ?>)">-</button> <span class="quantity-display" id="edit-qty-<?= (int)$p['id'] ?>">0</span> <button type="button" class="btn-quantity" onclick="updateEditQuantity(<?= (int)$p['id'] ?>, 1, '<?= htmlspecialchars($p['name'], ENT_QUOTES) ?>', <?= (float)$p['price'] ?>)">+</button> </div> </div> <?php endforeach; ?> </div> </div> <?php endforeach; ?> </div> </div> </div> <div class="cart-sticky"> <div class="cart-section"> <h3 class="cart-title"><span><i class="fas fa-shopping-cart"></i> Resumen del Pedido</span></h3> <div id="editModalCartItems" class="cart-items"></div> <div class="cart-total">Total: <span id="editModalTotalAmount">0</span></div> </div> </div> </div> </form> </div> <div class="modal-footer"> <button class="btn-secondary" type="button" id="cancelEditOrder">Cancelar</button> <button class="btn-primary" type="submit" form="editOrderForm" id="saveEditOrder" disabled>Actualizar Pedido</button> </div> </div> </div> </section> <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script> <script> let editCart = {}; let editTotal = 0; function getPreparerChecklist(context){ return document.getElementById(`${context}PreparerChecklist`); } function getPrimarySelection(context){ const checklist = getPreparerChecklist(context); if(!checklist) return ''; const checked = checklist.querySelector('.preparer-checkbox:checked'); return checked ? checked.value : ''; } function updatePreparerIndicators(context){ const checklist = getPreparerChecklist(context); if(!checklist) return; const primaryId = getPrimarySelection(context); checklist.querySelectorAll('.check-item').forEach(row => { const checkbox = row.querySelector('.preparer-checkbox'); const checked = !!checkbox?.checked; row.classList.toggle('is-selected', checked); row.classList.toggle('is-primary', checked && row.dataset.preparerId === primaryId); }); } function handlePreparerCheckbox(context){ updatePreparerIndicators(context); } function resetPreparerChecklist(context){ const checklist = getPreparerChecklist(context); if(!checklist) return; checklist.querySelectorAll('.preparer-checkbox').forEach(cb => { cb.checked = false; }); updatePreparerIndicators(context); } function populatePreparerChecklist(context, rawCsv){ resetPreparerChecklist(context); const checklist = getPreparerChecklist(context); if(!checklist) return; const ids = (rawCsv || '').split(',').map(v => v.trim()).filter(Boolean); ids.forEach(id => { const checkbox = checklist.querySelector(`.preparer-checkbox[value="${id}"]`); if(checkbox){ checkbox.checked = true; } }); updatePreparerIndicators(context); } function getCombinedPreparerIds(context){ const checklist = getPreparerChecklist(context); if(!checklist) return ''; const ids = []; checklist.querySelectorAll('.preparer-checkbox').forEach(cb => { if(cb.checked && cb.value && !ids.includes(cb.value)){ ids.push(cb.value); } }); return ids.join(','); } function initPreparerChecklist(context){ const checklist = getPreparerChecklist(context); if(!checklist) return; checklist.querySelectorAll('.preparer-checkbox').forEach(cb => { cb.addEventListener('change', () => handlePreparerCheckbox(context)); }); updatePreparerIndicators(context); } document.addEventListener('DOMContentLoaded', () => { initPreparerChecklist('history'); }); function mostrarModalEditar(button){ const card = button.closest('.order-card'); if (!card) return; const overlay = document.getElementById('editOrderOverlay'); overlay.classList.add('show'); document.body.style.overflow = 'hidden'; const orderId = card.dataset.orderId; const customer = card.dataset.customer || ''; const phone = card.dataset.phone || ''; const address = card.dataset.address || ''; const payment = card.dataset.payment || ''; const notes = card.dataset.notes || ''; const status = card.dataset.status || 'pendiente'; const preparerCsv = card.dataset.preparerIds || card.dataset.preparerId || ''; const encodedItems = card.dataset.items || ''; let items = []; try { const decoded = encodedItems ? atob(encodedItems) : '[]'; items = JSON.parse(decoded || '[]'); if (!Array.isArray(items)) items = []; } catch(e){ items = []; } editCart = {}; editTotal = 0; document.getElementById('editOrderId').value = orderId; document.getElementById('editCustomerName').value = customer; document.getElementById('editPhone').value = phone; document.getElementById('editAddress').value = address; document.getElementById('editPayment').value = payment; document.getElementById('editNotes').value = notes; document.getElementById('editStatus').value = status; populatePreparerChecklist('history', preparerCsv); const categorySelect = document.getElementById('editModalCategoryFilter'); if (categorySelect) categorySelect.value = ''; document.querySelectorAll('[id^="edit-qty-"]').forEach(el => el.textContent = '0'); items.forEach(item => { const id = parseInt(item.id); if (!id) return; const qEl = document.getElementById('edit-qty-' + id); if (qEl) qEl.textContent = item.cantidad; editCart[id] = { id, nombre: item.nombre, precio: parseFloat(item.precio), cantidad: parseInt(item.cantidad) }; }); updateEditCart(); filterEditModalCategory(''); } function cerrarModalEditar(){ const overlay = document.getElementById('editOrderOverlay'); overlay.classList.remove('show'); document.body.style.overflow = ''; const categorySelect = document.getElementById('editModalCategoryFilter'); if (categorySelect) categorySelect.value = ''; resetPreparerChecklist('history'); } document.getElementById('closeEditOrder')?.addEventListener('click', cerrarModalEditar); document.getElementById('cancelEditOrder')?.addEventListener('click', cerrarModalEditar); document.getElementById('editOrderOverlay')?.addEventListener('click', (e)=>{ if (e.target.id === 'editOrderOverlay') cerrarModalEditar(); }); function updateEditQuantity(id, change, name, price){ const qEl = document.getElementById('edit-qty-' + id); if (!qEl) return; let q = parseInt(qEl.textContent) || 0; q = Math.max(0, q + change); qEl.textContent = q; if (q === 0) delete editCart[id]; else editCart[id] = { id, nombre: name, precio: parseFloat(price), cantidad: q }; updateEditCart(); } function updateEditCart(){ const list = document.getElementById('editModalCartItems'); const totalEl = document.getElementById('editModalTotalAmount'); const saveBtn = document.getElementById('saveEditOrder'); if (!list || !totalEl) return; if (Object.keys(editCart).length === 0){ list.innerHTML = '<div class="cart-empty"><i class="fas fa-clipboard-list"></i><strong>No hay productos seleccionados</strong><small>Selecciona una categoría para editar el pedido</small></div>'; editTotal = 0; totalEl.textContent = '0'; if (saveBtn) saveBtn.disabled = true; return; } let html = ''; editTotal = 0; Object.values(editCart).forEach(item => { const subtotal = item.precio * item.cantidad; editTotal += subtotal; html += `<div class="cart-item"> <div class="cart-item-info"><span>${item.cantidad}x ${item.nombre}</span><small class="cart-item-subtotal">${(window.formatMoneyJs ? window.formatMoneyJs(subtotal) : subtotal.toLocaleString('es-CO'))}</small></div> <div class="cart-item-actions"> <button type="button" class="cart-remove-btn" onclick="removeFromEditCart(${item.id})"><i class="fas fa-times"></i> Quitar</button> </div> </div>`; }); list.innerHTML = html; totalEl.textContent = window.formatMoneyJs ? window.formatMoneyJs(editTotal) : editTotal.toLocaleString('es-CO'); if (saveBtn) saveBtn.disabled = false; } function removeFromEditCart(id){ if (editCart[id]){ delete editCart[id]; const qtyDisplay = document.getElementById('edit-qty-' + id); if (qtyDisplay) qtyDisplay.textContent = '0'; updateEditCart(); } } document.getElementById('editModalCategoryFilter')?.addEventListener('change', function(){ filterEditModalCategory(this.value); }); function filterEditModalCategory(cat){ const placeholder = document.getElementById('editCategoryPlaceholder'); const blocks = document.querySelectorAll('#editOrderForm .category-block'); const targetKey = (cat || '').toString().trim().toLowerCase(); let anyVisible = false; blocks.forEach(b => { const blockKey = (b.dataset.category || '').toString().trim().toLowerCase(); if (targetKey && blockKey === targetKey){ b.style.display = 'block'; anyVisible = true; } else { b.style.display = 'none'; } }); if (placeholder) placeholder.style.display = anyVisible ? 'none' : 'flex'; const productsContainer = document.querySelector('#editOrderForm .products-container'); if (productsContainer) productsContainer.scrollTop = 0; } function resetEditModalCategories(){ filterEditModalCategory(''); } function escapeHtml(value){ return String(value ?? '') .replace(/&/g, '&') .replace(/</g, '<') .replace(/>/g, '>') .replace(/"/g, '"') .replace(/'/g, '''); } function formatQty(value){ const n = Number(value); if(!isFinite(n)) return '0'; return n.toLocaleString('es-CO', { minimumFractionDigits: 0, maximumFractionDigits: 3 }); } function buildInventoryPreviewHtml(data){ const items = Array.isArray(data?.items) ? data.items : []; const summary = data?.summary || {}; const alreadyDeducted = !!data?.already_deducted; if(items.length === 0){ const msg = escapeHtml(data?.message || 'No hay insumos para descontar.'); return `<div style="text-align:left;"> ${alreadyDeducted ? '<div style="margin-bottom:.5rem;font-weight:800;color:#0f766e;">Inventario ya descontado para este pedido.</div>' : ''} <div style="color:#374151;">${msg}</div> </div>`; } let header = ''; if(alreadyDeducted){ header += '<div style="margin-bottom:.6rem;font-weight:800;color:#0f766e;">Inventario ya descontado para este pedido. No se volverá a descontar.</div>'; } if((summary.negatives || 0) > 0){ header += `<div style="margin-bottom:.35rem;font-weight:800;color:#b91c1c;">Atención: ${summary.negatives} insumo(s) quedarían en negativo.</div>`; } if((summary.lows || 0) > 0){ header += `<div style="margin-bottom:.35rem;font-weight:800;color:#b45309;">Alerta: ${summary.lows} insumo(s) quedarían por debajo del mínimo.</div>`; } const rows = items.map(it => { const negative = !!it.is_negative; const low = !!it.is_low; const bg = negative ? 'rgba(185,28,28,0.08)' : (low ? 'rgba(180,83,9,0.08)' : 'transparent'); return `<tr style="background:${bg};"> <td style="padding:.55rem .6rem;border-bottom:1px solid #eee;font-weight:800;color:#111827;">${escapeHtml(it.name)}</td> <td style="padding:.55rem .6rem;border-bottom:1px solid #eee;text-align:right;font-weight:800;">${formatQty(it.needed)}</td> <td style="padding:.55rem .6rem;border-bottom:1px solid #eee;text-align:right;">${formatQty(it.stock)}</td> <td style="padding:.55rem .6rem;border-bottom:1px solid #eee;text-align:right;font-weight:900;${negative ? 'color:#b91c1c;' : (low ? 'color:#b45309;' : 'color:#0f766e;')}">${formatQty(it.after)}</td> <td style="padding:.55rem .6rem;border-bottom:1px solid #eee;text-align:center;color:#6b7280;font-weight:800;">${escapeHtml(it.unit || 'u')}</td> </tr>`; }).join(''); return `<div style="text-align:left;"> ${header} <div style="overflow:auto;border:1px solid #eee;border-radius:12px;"> <table style="width:100%;border-collapse:collapse;min-width:720px;"> <thead> <tr style="background:#f9fafb;"> <th style="text-align:left;padding:.6rem .6rem;border-bottom:1px solid #eee;">Insumo</th> <th style="text-align:right;padding:.6rem .6rem;border-bottom:1px solid #eee;">Se descuenta</th> <th style="text-align:right;padding:.6rem .6rem;border-bottom:1px solid #eee;">Stock actual</th> <th style="text-align:right;padding:.6rem .6rem;border-bottom:1px solid #eee;">Stock después</th> <th style="text-align:center;padding:.6rem .6rem;border-bottom:1px solid #eee;">Unidad</th> </tr> </thead> <tbody>${rows}</tbody> </table> </div> </div>`; } async function confirmInventoryPreviewDelivery({ orderId, orderItemsJson, title, confirmText, confirmColor }){ const payload = new URLSearchParams(); payload.set('context', 'delivery'); if(orderId) payload.set('order_id', String(orderId)); if(orderItemsJson) payload.set('order_items', orderItemsJson); const res = await fetch('preview_inventory_deduction.php', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: payload.toString(), credentials: 'same-origin' }); const data = await res.json().catch(() => null); if(!data || !data.success){ await Swal.fire('Error', (data && data.message) ? data.message : 'No se pudo generar el preview de inventario.', 'error'); return false; } const html = buildInventoryPreviewHtml(data); const icon = (data.summary && data.summary.negatives > 0) ? 'warning' : 'info'; const result = await Swal.fire({ title: title || 'Confirmar descuento de inventario', html, icon, showCancelButton: true, confirmButtonText: confirmText || 'Confirmar', cancelButtonText: 'Cancelar', confirmButtonColor: confirmColor || '#22c55e', cancelButtonColor: '#6b7280', width: '980px' }); return !!result.isConfirmed; } document.getElementById('editOrderForm')?.addEventListener('submit', function(e){ e.preventDefault(); if (Object.keys(editCart).length === 0){ Swal.fire('Aviso','Debes agregar al menos un producto','warning'); return; } const form = e.target; const payload = new URLSearchParams(); const orderId = form.order_id?.value; if (!orderId){ Swal.fire('Error','No se pudo identificar el pedido','error'); return; } payload.set('order_id', orderId); payload.set('customer_name', form.customer_name.value.trim()); payload.set('phone', form.phone.value.trim()); payload.set('address', form.address.value.trim()); payload.set('payment_method', form.payment_method.value); payload.set('notes', form.notes.value.trim()); payload.set('status', form.status.value); const prepCsv = getCombinedPreparerIds('history'); payload.set('preparer_ids', prepCsv); const primaryPrep = prepCsv.split(',').map(v => v.trim()).filter(Boolean)[0] || ''; payload.set('preparer_id', primaryPrep); payload.set('order_items', JSON.stringify(Object.values(editCart))); payload.set('total_amount', String(editTotal)); (async () => { if(form.status.value === 'entregado'){ const ok = await confirmInventoryPreviewDelivery({ orderId, orderItemsJson: JSON.stringify(Object.values(editCart)), title: 'Confirmar entrega del pedido', confirmText: 'Sí, entregar', confirmColor: '#22c55e' }); if(!ok){ return; } } fetch('update_delivery.php', { method:'POST', headers:{'Content-Type':'application/x-www-form-urlencoded'}, body: payload.toString(), credentials: 'same-origin' }) .then(r => { if(!r.ok) throw new Error('Respuesta no válida'); return r.json(); }) .then(data => { if(data.success){ cerrarModalEditar(); Swal.fire('¡Actualizado!','El pedido ha sido modificado','success').then(()=>{ location.reload(); }); } else { Swal.fire('Error', data.message || 'No se pudo actualizar','error'); } }) .catch(err => { console.error('Error actualizando pedido', err); Swal.fire('Error','No se pudo actualizar','error'); }); })(); }); function cambiarEstado(id, estadoActual){ const estados = { 'pendiente':'Pendiente','en_preparacion':'En Preparación','en_camino':'En Camino','entregado':'Entregado','cancelado':'Cancelado' }; Swal.fire({ title:'Cambiar Estado del Pedido', input:'select', inputOptions: estados, inputValue: estadoActual, showCancelButton:true, confirmButtonText:'Cambiar', cancelButtonText:'Cancelar', confirmButtonColor:'#28a745', cancelButtonColor:'#6c757d', inputValidator:(v)=>{ if(!v) return 'Debes seleccionar un estado'; } }) .then(res=>{ if(!res.isConfirmed) return; (async () => { if(res.value === 'entregado'){ const ok = await confirmInventoryPreviewDelivery({ orderId: id, orderItemsJson: '', title: 'Confirmar entrega del pedido', confirmText: 'Sí, entregar', confirmColor: '#22c55e' }); if(!ok){ return; } } fetch('update_delivery_status.php', { method:'POST', headers:{'Content-Type':'application/x-www-form-urlencoded'}, body:'id='+id+'&status='+res.value }) .then(r=>r.json()) .then(data=>{ if(data.success){ const finalStates = new Set(['entregado']); const card = document.querySelector(`.order-card[data-order-id="${id}"]`); if(card){ card.setAttribute('data-status', res.value); const badge = card.querySelector('.order-status'); if(badge){ badge.className = 'order-status ' + res.value; badge.textContent = (estados[res.value] || res.value).toString(); } if(!finalStates.has(res.value)){ card.remove(); } } Swal.fire('¡Actualizado!','El estado del pedido ha sido actualizado.','success'); } else { Swal.fire('Error','No se pudo actualizar el estado.','error'); } }); })(); }); } function eliminarPedido(id){ Swal.fire({ title:'¿Estás seguro?', text:'Esta acción no se puede deshacer', icon:'warning', showCancelButton:true, confirmButtonText:'Sí, eliminar', cancelButtonText:'Cancelar', confirmButtonColor:'#dc3545', cancelButtonColor:'#6c757d' }) .then(res=>{ if(res.isConfirmed){ window.location.href = 'delete_delivery.php?id=' + id + '&redirect=delivery_history.php'; } }); } function imprimirPedido(id){ if(!id){ Swal.fire('Error','No se pudo identificar el pedido para imprimir.','error'); return; } const url = `delivery_order_ticket.php?id=${encodeURIComponent(id)}&print=1`; window.open(url, '_blank'); } function resetHistoryFilters(){ window.location.href = 'delivery_history.php'; } </script> </body> </html>
Coded With 💗 by
0x6ick