user(); if (!$user) { return redirect()->route('login'); } // 1. Obtener y asegurar sucursal_id y empresa_id $empresaId = $user->empresa_id; $sucursalId = session('sucursal_id') ?? $user->sucursal_asignada_id; if (empty($sucursalId) && !empty($empresaId)) { $sucursalDef = DB::table('Nucleo_Sucursales') ->where('empresa_id', $empresaId) ->where('activo', 1) ->first(); if ($sucursalDef) { $sucursalId = $sucursalDef->id_sucursal; session(['sucursal_id' => $sucursalId]); } } // 2. Datos de la Empresa y Sucursal $empresa = DB::table('Nucleo_Empresas')->where('id_empresa', $empresaId)->first(); $sucursal = DB::table('Nucleo_Sucursales')->where('id_sucursal', $sucursalId)->first(); // 3. Colores Dinámicos del Dueño de la Empresa $ownerUser = DB::table('Seguridad_Usuarios as u') ->join('Seguridad_Perfiles as p', 'u.perfil_id', '=', 'p.id_perfil') ->where('u.empresa_id', $empresaId) ->where('p.nombre', 'LIKE', '%DUEÑO%') ->select('u.color_preferido', 'u.color_fondo_preferido') ->first(); $convertColor = function ($color, $default) { if (empty($color)) return $default; $color = trim($color); if (str_starts_with($color, '#')) return $color; if (str_starts_with($color, '0x') || str_starts_with($color, '0X')) { return '#' . substr($color, -6); } return $color; }; $colorPrimario = $convertColor($ownerUser->color_preferido ?? $user->color_preferido, '#EA580C'); $colorFondo = $convertColor($ownerUser->color_fondo_preferido ?? $user->color_fondo_preferido, '#FFFFFF'); // Determinar luminancia (YIQ) del color de fondo escogido por el dueño $cleanHexBg = str_replace('#', '', $colorFondo); if (strlen($cleanHexBg) == 3) { $cleanHexBg = $cleanHexBg[0].$cleanHexBg[0].$cleanHexBg[1].$cleanHexBg[1].$cleanHexBg[2].$cleanHexBg[2]; } $r = hexdec(substr($cleanHexBg, 0, 2)) ?: 255; $g = hexdec(substr($cleanHexBg, 2, 2)) ?: 255; $b = hexdec(substr($cleanHexBg, 4, 2)) ?: 255; $yiq = (($r * 299) + ($g * 587) + ($b * 114)) / 1000; $isLightMode = ($yiq >= 128); // 4. Conteos para badges del Sidebar $totalStaff = DB::table('Seguridad_Usuarios') ->where('empresa_id', $empresaId) ->where(function($q) use ($sucursalId) { $q->where('sucursal_asignada_id', $sucursalId) ->orWhereNull('sucursal_asignada_id'); }) ->where('estado', 'Activo') ->count(); $totalMesas = DB::table('Nucleo_Recursos') ->where('sucursal_id', $sucursalId) ->where('activo', 1) ->count(); return view('manager.dashboard', [ 'user' => $user, 'empresa' => $empresa, 'sucursal' => $sucursal, 'colorPrimario' => $colorPrimario, 'colorFondo' => $colorFondo, 'isLightMode' => $isLightMode, 'totalStaff' => $totalStaff, 'totalMesas' => $totalMesas, 'sucursalId' => $sucursalId, 'empresaId' => $empresaId, ]); } /** * API para obtener métricas y datos en vivo del Dashboard de Inicio con filtros de fecha */ public function getDashboardData(Request $request) { $user = Auth::guard('admin')->user(); if (!$user) { return response()->json(['success' => false, 'message' => 'No autorizado'], 401); } $sucursalId = session('sucursal_id') ?? $user->sucursal_asignada_id; $empresaId = $user->empresa_id; if (empty($sucursalId)) { $sucursalDef = DB::table('Nucleo_Sucursales')->where('empresa_id', $empresaId)->where('activo', 1)->first(); $sucursalId = $sucursalDef ? $sucursalDef->id_sucursal : null; } // Resolución de Rango de Fechas $period = $request->query('period', 'hoy'); $now = Carbon::now(); switch ($period) { case 'semana': $startDate = $now->copy()->startOfWeek(); $endDate = $now->copy()->endOfWeek(); $periodLabel = 'Esta Semana'; break; case 'mes': $startDate = $now->copy()->startOfMonth(); $endDate = $now->copy()->endOfMonth(); $periodLabel = $now->translatedFormat('F Y'); break; case 'ano': $startDate = $now->copy()->startOfYear(); $endDate = $now->copy()->endOfYear(); $periodLabel = 'Año ' . $now->year; break; case 'rango': $s = $request->query('start_date'); $e = $request->query('end_date'); $startDate = $s ? Carbon::parse($s)->startOfDay() : $now->copy()->startOfDay(); $endDate = $e ? Carbon::parse($e)->endOfDay() : $now->copy()->endOfDay(); $periodLabel = $startDate->format('d/m/Y') . ' - ' . $endDate->format('d/m/Y'); break; case 'hoy': default: $startDate = $now->copy()->startOfDay(); $endDate = $now->copy()->endOfDay(); $periodLabel = 'Hoy, ' . $now->format('d/m/Y'); break; } // 1. Métricas de Ventas y Comandas $ordenesQuery = DB::table('Ventas_Ordenes') ->where('sucursal_id', $sucursalId) ->whereBetween('creado_at', [$startDate, $endDate]) ->whereNotIn('estado', ['CANCELADO', 'ANULADO', 'FALLIDA']); $totalVentas = (float) $ordenesQuery->sum('monto_total'); $totalOrdenes = $ordenesQuery->count(); $ticketPromedio = $totalOrdenes > 0 ? round($totalVentas / $totalOrdenes, 2) : 0; $margenEstimado = round($totalVentas * 0.65, 2); // 65% de margen estimado // Meta sugerida según período $metaSugerida = match ($period) { 'hoy' => 1500.00, 'semana' => 10000.00, 'mes' => 45000.00, 'ano' => 500000.00, default => max(1500.00, round($totalVentas * 1.25, 2)) }; $porcentajeMeta = $metaSugerida > 0 ? min(100, round(($totalVentas / $metaSugerida) * 100, 1)) : 0; // 2. Estado de Mesas en Vivo $mesas = DB::table('Nucleo_Recursos') ->where('sucursal_id', $sucursalId) ->where('activo', 1) ->select('id_recurso', 'nombre', 'capacidad', 'estado', 'ubicacion', 'es_vip', 'permite_union') ->get(); $totalMesas = $mesas->count(); $mesasOcupadas = $mesas->where('estado', 'OCUPADA')->count(); $mesasLibres = $mesas->where('estado', 'LIBRE')->count(); $mesasReservadas = $mesas->where('estado', 'RESERVADA')->count(); $ocupacionPorcentaje = $totalMesas > 0 ? round(($mesasOcupadas / $totalMesas) * 100, 1) : 0; // 3. Top 5 Platos de Mayor Rotación $topPlatos = DB::table('Ventas_Detalle_Orden as d') ->join('Ventas_Ordenes as o', 'd.orden_id', '=', 'o.id_ordenes') ->join('Ventas_Productos as p', 'd.producto_id', '=', 'p.id_producto') ->where('o.sucursal_id', $sucursalId) ->whereBetween('o.creado_at', [$startDate, $endDate]) ->whereNotIn('o.estado', ['CANCELADO', 'ANULADO']) ->select( 'p.id_producto', 'p.nombre', 'p.sku', 'p.categoria', 'p.imagen_url', DB::raw('SUM(d.cantidad) as total_unidades'), DB::raw('SUM(d.subtotal) as total_facturado') ) ->groupBy('p.id_producto', 'p.nombre', 'p.sku', 'p.categoria', 'p.imagen_url') ->orderByDesc('total_unidades') ->limit(5) ->get() ->map(function ($item, $idx) { // Limpieza de ruta de imagen $img = $item->imagen_url; if (!empty($img) && !str_starts_with($img, 'http')) { $img = url('/middleware/uploads/' . ltrim(str_replace(['uploads/', 'uploads\\'], '', $img), '/')); } return [ 'rank' => $idx + 1, 'id' => $item->id_producto, 'nombre' => $item->nombre, 'sku' => $item->sku ?? 'PL-' . ($idx + 1), 'categoria' => $item->categoria ?? 'Platos', 'imagen' => $img, 'unidades' => (int) $item->total_unidades, 'facturado' => (float) $item->total_facturado, ]; }); // 4. Tendencia de Ventas (Para el gráfico) $chartLabels = []; $chartData = []; if ($period === 'hoy') { // Agrupar por hora de 8 AM a 11 PM $horas = DB::table('Ventas_Ordenes') ->where('sucursal_id', $sucursalId) ->whereBetween('creado_at', [$startDate, $endDate]) ->whereNotIn('estado', ['CANCELADO', 'ANULADO']) ->select(DB::raw('DATEPART(HOUR, creado_at) as hora'), DB::raw('SUM(monto_total) as total')) ->groupBy(DB::raw('DATEPART(HOUR, creado_at)')) ->pluck('total', 'hora') ->toArray(); for ($h = 8; $h <= 23; $h++) { $label = sprintf('%02d:00', $h); $chartLabels[] = $label; $chartData[] = isset($horas[$h]) ? (float) $horas[$h] : 0.0; } } else { // Agrupar por día $dias = DB::table('Ventas_Ordenes') ->where('sucursal_id', $sucursalId) ->whereBetween('creado_at', [$startDate, $endDate]) ->whereNotIn('estado', ['CANCELADO', 'ANULADO']) ->select(DB::raw('CAST(creado_at AS DATE) as fecha'), DB::raw('SUM(monto_total) as total')) ->groupBy(DB::raw('CAST(creado_at AS DATE)')) ->pluck('total', 'fecha') ->toArray(); $curr = $startDate->copy(); while ($curr->lte($endDate) && count($chartLabels) < 31) { $key = $curr->format('Y-m-d'); $chartLabels[] = $curr->format('d/m'); $chartData[] = isset($dias[$key]) ? (float) $dias[$key] : 0.0; $curr->addDay(); } } // 5. Últimas Órdenes en Vivo $ultimasOrdenes = DB::table('Ventas_Ordenes as o') ->leftJoin('Nucleo_Recursos as r', 'o.recurso_id', '=', 'r.id_recurso') ->leftJoin('Seguridad_Usuarios as u', 'o.usuario_id', '=', 'u.id_usuario') ->leftJoin('Ventas_Pagos as vp', 'o.id_ordenes', '=', 'vp.pedido_id') ->where('o.sucursal_id', $sucursalId) ->whereNotIn('o.estado', ['CANCELADO']) ->orderByDesc('o.creado_at') ->limit(60) ->select( 'o.id_ordenes', 'o.monto_total', 'o.estado', 'o.creado_at', 'r.nombre as mesa_nombre', 'u.nombre_completo as mesero_nombre', 'vp.metodo_pago' ) ->get() ->map(function ($ord) { $dt = Carbon::parse($ord->creado_at); $metodo = strtoupper($ord->metodo_pago ?? 'EFECTIVO'); return [ 'id' => substr((string)$ord->id_ordenes, -6), 'id_completo' => $ord->id_ordenes, 'mesa' => $ord->mesa_nombre ?? 'Barra / Llevar', 'mesero' => $ord->mesero_nombre ?? 'Staff', 'total' => (float) $ord->monto_total, 'estado' => $ord->estado, 'hora' => $dt->format('h:i A'), 'metodo_pago' => $metodo ]; }); // 6. Caja de Turno $cajaDiaria = DB::table('Pagos_Cajas_Diarias') ->where('sucursal_id', $sucursalId) ->first(); $cajaHistorial = null; if ($cajaDiaria) { $cajaHistorial = DB::table('Pagos_Cajas_Historial') ->where('caja_id', $cajaDiaria->id_cajaDi) ->orderByDesc('id_historial') ->first(); } $cajaInfo = [ 'activa' => $cajaDiaria && strtolower($cajaDiaria->estado) === 'abierta', 'monto_apertura' => $cajaHistorial ? (float) $cajaHistorial->monto_inicial : 0.0, 'fecha_apertura' => ($cajaHistorial && $cajaHistorial->fecha_apertura) ? Carbon::parse($cajaHistorial->fecha_apertura)->format('d/m/Y h:i A') : 'Sin apertura', 'id_caja' => $cajaDiaria ? $cajaDiaria->id_cajaDi : null, ]; return response()->json([ 'success' => true, 'period' => $period, 'period_label' => $periodLabel, 'kpis' => [ 'total_ventas' => $totalVentas, 'total_ordenes' => $totalOrdenes, 'ticket_promedio' => $ticketPromedio, 'margen_estimado' => $margenEstimado, 'meta_sugerida' => $metaSugerida, 'porcentaje_meta' => $porcentajeMeta, ], 'mesas_stats' => [ 'total' => $totalMesas, 'ocupadas' => $mesasOcupadas, 'libres' => $mesasLibres, 'reservadas' => $mesasReservadas, 'porcentaje_ocupacion' => $ocupacionPorcentaje, ], 'mesas_detalle' => $mesas, 'top_platos' => $topPlatos, 'chart' => [ 'labels' => $chartLabels, 'data' => $chartData, ], 'ultimas_ordenes' => $ultimasOrdenes, 'caja' => $cajaInfo, ]); } }