format('Y-m-d') : ''; $kpiPeriodTitleLabel = match ($kpiPeriodKey) { 'today' => 'diario', 'yesterday' => 'ayer', '7', '15', '30' => 'los ' . mb_strtolower($kpiPeriodLabel), default => mb_strtolower($kpiPeriodLabel), }; $kpiPeriodStart = $kpiPeriodConfig['start'] instanceof DateTimeImmutable ? $kpiPeriodConfig['start'] : new DateTimeImmutable('today'); $kpiPeriodEnd = $kpiPeriodConfig['end'] instanceof DateTimeImmutable ? $kpiPeriodConfig['end'] : $kpiPeriodStart; $kpiPeriodButtons = [ 'today' => 'Hoy', 'yesterday' => 'Ayer', '7' => '7 Días', '15' => '15 Días', '30' => '30 Días', 'month' => 'Este Mes', ]; if (!cc_test_current_user_can_access_module($pdo)) { http_response_code(403); require_once 'layout_header.php'; echo "
Acceso denegado.
"; require_once 'layout_footer.php'; exit(); } $sedesShalom = cc_test_fetch_shalom_sedes($pdo); function cc_test_parse_datetime(?string $value): ?DateTimeImmutable { $value = trim((string) $value); if ($value === '') { return null; } try { return new DateTimeImmutable($value); } catch (Throwable $exception) { return null; } } function cc_test_format_datetime(?string $value, string $fallback = 'Sin programar'): string { $date = cc_test_parse_datetime($value); return $date ? $date->format('d/m/Y h:i A') : $fallback; } function cc_test_format_datetime_input(?string $value): string { $date = cc_test_parse_datetime($value); return $date ? $date->format('Y-m-d\TH:i') : ''; } function cc_test_format_date(?string $value, string $fallback = 'Sin fecha'): string { $date = cc_test_parse_datetime($value); return $date ? $date->format('d/m/Y') : $fallback; } function cc_test_format_date_input(?string $value): string { $date = cc_test_parse_datetime($value); return $date ? $date->format('Y-m-d\TH:i') : ''; } function cc_test_is_working_day(DateTimeImmutable $date): bool { return (int) $date->format('N') !== 7; } function cc_test_last_working_day_keys(DateTimeImmutable $todayStart, int $days = 3): array { $days = max(1, $days); $cursor = $todayStart->setTime(0, 0, 0); while (!cc_test_is_working_day($cursor)) { $cursor = $cursor->sub(new DateInterval('P1D')); } $keys = []; while (count($keys) < $days) { if (cc_test_is_working_day($cursor)) { $keys[] = $cursor->format('Y-m-d'); } $cursor = $cursor->sub(new DateInterval('P1D')); } return $keys; } function cc_test_recent_followup_anchor(array $order): ?DateTimeImmutable { $assignedDate = cc_test_parse_datetime($order['assigned_at'] ?? null); if ($assignedDate instanceof DateTimeImmutable) { return $assignedDate; } return cc_test_followup_started_at($order); } function cc_test_is_within_last_days_window(array $order, DateTimeImmutable $todayStart, int $days = 3): bool { if ($days < 1) { return false; } $anchorDate = cc_test_recent_followup_anchor($order); if (!$anchorDate instanceof DateTimeImmutable) { return false; } $anchorKey = $anchorDate->setTime(0, 0, 0)->format('Y-m-d'); return in_array($anchorKey, cc_test_last_working_day_keys($todayStart, $days), true); } function cc_test_format_price(?string $value): string { $value = trim((string) $value); return $value !== '' ? 'S/ ' . $value : 'No registrado'; } function cc_test_display_value(?string $value, string $fallback = 'No registrado'): string { $value = trim((string) $value); return $value !== '' ? $value : $fallback; } function cc_test_build_url(string $path, array $params = []): string { foreach ($params as $key => $value) { if ($value === '' || $value === null) { unset($params[$key]); } } $query = http_build_query($params); return $query !== '' ? $path . '?' . $query : $path; } function cc_test_find_assessor_key_by_user_id(?int $userId, array $assessors): ?string { $userId = $userId !== null && $userId > 0 ? $userId : null; if ($userId === null) { return null; } foreach ($assessors as $assessorKey => $assessor) { if ((int) ($assessor['id'] ?? 0) === $userId) { return (string) $assessorKey; } } return null; } function cc_test_order_label(array $order): string { $codigo = trim((string) ($order['codigo'] ?? '')); if ($codigo !== '') { return '#' . ltrim($codigo, '#'); } if (!empty($order['is_agregado'])) { return 'AGREGADOS'; } return 'Sin número'; } function cc_test_promo_final_badge_info(array $order): ?array { if (empty($order['es_promo_final'])) { return null; } return [ 'label' => 'Promo Final', 'title' => 'Pedido movido a Promo Final', 'class' => 'bg-success-subtle text-success-emphasis border', ]; } function cc_test_badge_class(string $estado): string { return match (cc_test_normalize_state($estado)) { 'POR LLAMAR', 'DEVOLVER LLAMADA' => 'bg-white text-dark border', 'OBSERVADO' => 'bg-warning-subtle text-warning-emphasis', 'SE ENVIO NUMERO DE CUENTA' => 'bg-success-subtle text-success-emphasis', 'CONFIRMADO CONTRAENTREGA' => 'cc-badge-orange', 'CONFIRMADO ENVIO' => 'bg-success text-white', 'CANCELADO' => 'bg-danger-subtle text-danger-emphasis', 'REPETIDO' => 'bg-secondary-subtle text-secondary-emphasis', default => 'bg-white text-dark border', }; } function cc_test_order_time(array $order): int { foreach (['proxima_llamada_at', 'numero_cuenta_enviado_at', 'ultima_gestion_at', 'seguimiento_actualizado'] as $field) { $date = cc_test_parse_datetime($order[$field] ?? null); if ($date) { return $date->getTimestamp(); } } // Fallback recency for Drive imports where import_id is not a datetime (e.g. "#35898"). return cc_test_import_time($order); } function cc_test_import_time(array $order): int { foreach (['drive_imported_at', 'first_seen_at'] as $field) { $date = cc_test_parse_datetime($order[$field] ?? null); if ($date) { return $date->getTimestamp(); } } $sourceRow = (int) ($order['source_row'] ?? 0); if ($sourceRow > 0) { return $sourceRow; } $importRaw = trim((string) ($order['import_id'] ?? '')); if ($importRaw !== '') { $date = cc_test_parse_datetime($importRaw); if ($date) { return $date->getTimestamp(); } $digits = preg_replace('/\D+/', '', $importRaw); if ($digits !== '') { return (int) $digits; } } $codigoRaw = trim((string) ($order['codigo'] ?? '')); $digits = preg_replace('/\D+/', '', $codigoRaw); if ($digits !== '') { return (int) $digits; } return (int) ($order['id'] ?? 0); } function cc_test_order_priority_value(array $order): int { $codigo = trim((string) ($order['codigo'] ?? '')); if ($codigo !== '') { $digits = preg_replace('/\D+/', '', $codigo); if ($digits !== '') { return (int) $digits; } } $sourceRow = (int) ($order['source_row'] ?? 0); if ($sourceRow > 0) { return $sourceRow; } return (int) ($order['id'] ?? 0); } function cc_test_followup_semaforo(array $order): ?array { if (cc_test_normalize_state((string) ($order['estado'] ?? '')) !== 'SE ENVIO NUMERO DE CUENTA') { return null; } return cc_test_account_followup_semaforo($order['numero_cuenta_enviado_at'] ?? null); } function cc_test_panel_orders_signature(array $orders): string { $payload = []; foreach ($orders as $order) { $payload[] = [ 'source_key' => (string) ($order['source_key'] ?? ''), 'user_id' => (int) ($order['user_id'] ?? 0), 'estado' => cc_test_normalize_state((string) ($order['estado'] ?? '')), 'pedido_repetido_en_tienda' => !empty($order['pedido_repetido_en_tienda']) ? 1 : 0, 'assigned_at' => trim((string) ($order['assigned_at'] ?? '')), 'updated_at' => trim((string) ($order['updated_at'] ?? ($order['seguimiento_actualizado'] ?? ''))), 'eliminado_at' => trim((string) ($order['eliminado_at'] ?? '')), ]; } usort($payload, static function (array $a, array $b): int { return strcmp($a['source_key'], $b['source_key']); }); return sha1(json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)); } $view = cc_test_resolve_callcenter_context_key($_GET['view'] ?? '', cc_test_callcenter_view_session_key()); $availableStores = drive_test_available_stores(); $storeKey = cc_test_resolve_callcenter_context_key($_GET['store'] ?? '', cc_test_callcenter_store_session_key(), 'flower'); if (!isset($availableStores[$storeKey])) { $storeKey = 'flower'; } $storeConfig = $availableStores[$storeKey]; $storeLabel = (string) ($storeConfig['label'] ?? strtoupper($storeKey)); $recoverablesStoreKey = trim((string) ($storeConfig['recoverables_store_key'] ?? '')); $recoverablesStoreLabel = $recoverablesStoreKey !== '' && isset($availableStores[$recoverablesStoreKey]) ? (string) ($availableStores[$recoverablesStoreKey]['label'] ?? strtoupper($recoverablesStoreKey)) : ''; $recoverablesMainStoreKey = trim((string) ($storeConfig['main_store_key'] ?? '')); $recoverablesMainStoreLabel = $recoverablesMainStoreKey !== '' && isset($availableStores[$recoverablesMainStoreKey]) ? (string) ($availableStores[$recoverablesMainStoreKey]['label'] ?? strtoupper($recoverablesMainStoreKey)) : $storeLabel; $recoverablesStoreLabelHtml = htmlspecialchars($storeLabel); $recoverablesMainStoreLabelHtml = htmlspecialchars($recoverablesMainStoreLabel); $canOpenRecoverablesStore = $recoverablesStoreKey !== '' && isset($availableStores[$recoverablesStoreKey]); $usesIncrementalSync = !empty($storeConfig['incremental_sync']); $storeNav = drive_test_store_navigation_state($availableStores, $storeKey); $storeNavGroups = $storeNav['groups']; $activeStoreGroupKey = (string) ($storeNav['active_group_key'] ?? $storeKey); $activeStoreGroupLabel = (string) ($storeNav['active_group_label'] ?? $storeLabel); $activeStoreGroupChildren = $storeNav['active_group_children'] ?? []; $parentStoreLabel = (string) ($storeNav['parent_label'] ?? ''); $isMainTuaniStore = cc_test_is_tuani_main_store_key($storeKey); $isTuaniRecuperablesStore = cc_test_is_recoverables_store_key($storeKey); if ($isTuaniRecuperablesStore && trim((string) ($_GET['view'] ?? '')) === '') { $view = 'todos'; } $canShowTuaniLogisticaButton = $isMainTuaniStore || $isTuaniRecuperablesStore; $postedAction = trim((string) ($_POST['action'] ?? '')); $recoverablesResyncRequested = $isTuaniRecuperablesStore && $isAdmin && $postedAction === 'reimport_recoverables_queue'; $recoverablesResyncRow = $isTuaniRecuperablesStore ? (int) ($storeConfig['startRow'] ?? 2000) : null; $viewCardColumnClass = $isTuaniRecuperablesStore ? 'col-md-6 col-xl-2' : 'col-md-6 col-xl-2'; $defaultView = cc_test_callcenter_pro_default_view_key($storeKey); $viewCards = $isTuaniRecuperablesStore ? [ 'todos' => [ 'label' => 'Todos', 'heading' => 'Todos los pedidos cargados', 'stat_key' => 'total', 'active_class' => 'bg-light border', ], 'confirmados' => [ 'label' => 'Confirmados', 'heading' => 'Confirmados', 'stat_key' => 'confirmados', 'active_class' => 'bg-success-subtle border border-success', ], 'recuperados' => [ 'label' => 'Recuperados', 'heading' => 'Recuperados', 'stat_key' => 'recuperados', 'active_class' => 'bg-warning-subtle border border-warning', ], 'seguimiento' => [ 'label' => 'Seguimiento', 'heading' => 'Seguimiento', 'stat_key' => 'seguimiento', 'active_class' => 'bg-primary-subtle border border-primary', ], 'observados' => [ 'label' => 'Observados', 'heading' => 'Observados', 'stat_key' => 'observados', 'active_class' => 'bg-warning-subtle border border-warning', ], 'pendientes_hoy' => [ 'label' => $storeLabel, 'heading' => $storeLabel, 'stat_key' => 'pendientes_hoy', 'active_class' => 'bg-dark text-white', ], ] : [ 'nuevos_hoy' => [ 'label' => 'Asignados hoy', 'heading' => 'Pedidos asignados hoy', 'stat_key' => 'nuevos_hoy', 'active_class' => 'bg-primary-subtle border border-primary', ], 'ultimos_3_dias' => [ 'label' => 'Últimos 4 días hábiles', 'heading' => 'Pedidos asignados de los últimos 4 días hábiles', 'stat_key' => 'ultimos_3_dias', 'active_class' => 'bg-info-subtle border border-info', ], 'observados' => [ 'label' => 'Observados', 'heading' => 'Observados', 'stat_key' => 'observados', 'active_class' => 'bg-warning-subtle border border-warning', ], 'seguimiento' => [ 'label' => 'Seguimiento', 'heading' => 'Seguimiento', 'stat_key' => 'seguimiento', 'active_class' => 'bg-primary-subtle border border-primary', ], 'confirmados' => [ 'label' => 'Confirmados', 'heading' => 'Confirmados', 'stat_key' => 'confirmados', 'active_class' => 'bg-success-subtle border border-success', ], 'recuperados' => [ 'label' => 'Recuperados', 'heading' => 'Recuperados', 'stat_key' => 'recuperados', 'active_class' => 'bg-warning-subtle border border-warning', ], 'promo_final' => [ 'label' => 'Promo Final', 'heading' => 'Promo Final', 'stat_key' => 'promo_final', 'active_class' => 'bg-danger-subtle border border-danger', ], 'cerrados' => [ 'label' => 'Cerrados', 'heading' => 'Cerrados / descartados', 'stat_key' => 'cerrados', 'active_class' => 'bg-secondary-subtle border border-secondary', ], 'pendientes_hoy' => [ 'label' => 'Bandeja principal', 'heading' => 'Bandeja principal', 'stat_key' => 'pendientes_hoy', 'active_class' => 'bg-dark text-white', ], 'todos' => [ 'label' => 'Todos', 'heading' => 'Todos los pedidos cargados', 'stat_key' => 'total', 'active_class' => 'bg-light border', ], ]; $allowedViews = []; foreach ($viewCards as $viewKey => $cardConfig) { $allowedViews[$viewKey] = $cardConfig['heading']; } if ($view === '') { $view = $defaultView; } if (!isset($allowedViews[$view])) { $view = isset($allowedViews[$defaultView]) ? $defaultView : (array_key_first($allowedViews) ?: 'pendientes_hoy'); } $_SESSION[cc_test_callcenter_store_session_key()] = cc_test_normalize_context_key($storeKey); $_SESSION[cc_test_callcenter_view_session_key()] = cc_test_normalize_context_key($view); $viewStatesNote = $isTuaniRecuperablesStore ? 'Estados disponibles: ' . $recoverablesStoreLabelHtml . ', Seguimiento, Observados, Confirmados, Recuperados y Todos. Esta bandeja abre por defecto en Todos. La bandeja compartida está disponible para cualquier asesora y, cuando una asesora gestiona un carrito recuperable, el sistema lo asigna automáticamente a quien lo trabaja. Si el teléfono ya existe en ' . $recoverablesMainStoreLabelHtml . ' principal, se marca en gris como Pedido repetido en tienda solo en esta bandeja. Las vistas ' . $recoverablesStoreLabelHtml . ' y Todos arrancan en la fila ' . (int) ($storeConfig['startRow'] ?? 0) . ', solo toman pedidos desde esa fila y se ordenan por el número #D más alto, lo que mantiene arriba el código más reciente, al más antiguo, en bloques de 200 pedidos.' : 'Estados disponibles: Por llamar, Devolver llamada, Observado, Se envió número de cuenta, Confirmado contraentrega, Confirmado envío, Cancelado y Repetido. Promo Final se habilita para mover el pedido desde el Día 4; la imagen de sustento se puede cargar desde el Día 3 para dejarlo listo antes del pase. Además, esta bandeja principal incluye reparto intercalado diario: en modo automático reparte pedidos sin asignar entre asesoras activas; en modo manual el supervisor los mueve pedido por pedido. También puedes usar la vista Últimos 4 días hábiles para concentrar el seguimiento reciente.'; $errorMessage = null; $noticeMessage = null; $assessors = []; $orders = []; $visibleOrders = []; $modalsHtml = []; $isAdmin = false; $selectedAssessorFilter = ''; $selectedAssessorFilterLabel = ''; $totalRows = 0; $agregadosCount = 0; $lastProcessedRow = null; $recoverablesImportCount = 0; $recoverablesFirstSourceRow = null; $recoverablesLastSourceRow = null; $recoverablesNotice = null; $startRow = (int) ($storeConfig['startRow'] ?? 0); $recoverablesMinimumSourceRow = $isTuaniRecuperablesStore ? (int) ($storeConfig['startRow'] ?? 0) : 0; $catalogoProductos = []; $stats = [ 'total' => 0, 'pendientes_hoy' => 0, 'nuevos_hoy' => 0, 'ultimos_3_dias' => 0, 'confirmados' => 0, 'recuperados' => 0, 'seguimiento' => 0, 'promo_final' => 0, 'observados' => 0, 'cerrados' => 0, ]; $repartoSettings = [ 'store_key' => $storeKey, 'reparto_mode' => 'manual', 'rotation_date' => null, 'rotation_index' => 0, 'assessor_states' => [], ]; $repartoPreview = [ 'mode' => 'manual', 'mode_label' => 'Manual', 'sequence' => [], 'ordered_keys' => [], 'states' => [], 'available_count' => 0, 'total_count' => 0, 'rotation_index' => 0, 'rotation_date' => null, 'next_key' => null, 'next_label' => '', 'next_position' => null, ]; $repartoUnassignedCount = 0; $repartoSourceOrders = []; try { cc_test_ensure_tracking_table($pdo); cc_test_ensure_historial_llamadas_table($pdo); $assessors = cc_test_fetch_assessors($pdo); if ($isMainTuaniStore) { $repartoSettings = cc_test_fetch_reparto_settings($pdo, $storeKey, $assessors); } try { $stmtProductos = $pdo->query("SELECT id, nombre FROM products ORDER BY nombre ASC"); $catalogoProductos = $stmtProductos->fetchAll(PDO::FETCH_ASSOC); } catch (Throwable $exception) { $catalogoProductos = []; } if ($usesIncrementalSync) { $syncInfo = drive_test_sync_orders_incremental($pdo, $storeKey, 0, $recoverablesResyncRequested ? $recoverablesResyncRow : null); $totalRows = (int) ($syncInfo['drive_rows_total'] ?? 0); $lastProcessedRow = (int) ($syncInfo['last_processed_row'] ?? 0); $startRow = (int) ($syncInfo['next_start_row'] ?? $startRow); $orders = drive_test_fetch_orders_from_db($pdo, $storeKey); $agregadosCount = 0; foreach ($orders as $o) { if (!empty($o['is_agregado'])) { $agregadosCount++; } } } else { $preview = drive_test_fetch_orders(100, $startRow, $storeKey); $totalRows = (int) ($preview['total_rows'] ?? 0); $orders = $preview['orders'] ?? []; $agregadosOrders = drive_test_fetch_orders_from_db($pdo, $storeKey, true); $agregadosCount = count($agregadosOrders); if (!empty($agregadosOrders)) { $orders = array_merge($orders, $agregadosOrders); } } if ($recoverablesResyncRequested) { $noticeMessage = 'Reimportación desde fila ' . $recoverablesResyncRow . ' completada. La cola volvió a contrastarse sin duplicar pedidos ya cargados.'; } $tracking = drive_test_fetch_tracking($pdo, array_column($orders, 'source_key')); $orders = drive_test_merge_tracking($orders, $tracking); $orders = array_values(array_filter($orders, static function (array $order): bool { return empty($order['eliminado']); })); $orders = array_values(array_filter($orders, static function (array $order): bool { return empty($order['eliminado']); })); if ($isTuaniRecuperablesStore) { $orders = cc_test_filter_recoverables_orders($orders, $recoverablesMinimumSourceRow); $recoverablesSummary = cc_test_recoverables_summary($orders); if ($recoverablesSummary !== null) { $recoverablesImportCount = (int) ($recoverablesSummary['import_count'] ?? count($orders)); $recoverablesFirstSourceRow = $recoverablesSummary['first_source_row'] !== null ? (int) $recoverablesSummary['first_source_row'] : null; $recoverablesLastSourceRow = $recoverablesSummary['last_source_row'] !== null ? (int) $recoverablesSummary['last_source_row'] : null; $recoverablesNotice = $recoverablesSummary['notice'] ?? null; $recoverablesNotice = null; } else { $recoverablesImportCount = count($orders); $recoverablesFirstSourceRow = null; $recoverablesLastSourceRow = null; $recoverablesNotice = null; } } $postedAction = trim((string) ($_POST['action'] ?? '')); if ($_SERVER['REQUEST_METHOD'] === 'POST') { if ($postedAction === 'assign_assessor') { $sourceKey = trim((string) ($_POST['source_key'] ?? '')); $targetValue = trim((string) ($_POST['target_assessor'] ?? '')); if ($sourceKey === '' || !preg_match('/^[a-f0-9]{40}$/', $sourceKey)) { throw new RuntimeException('Pedido de prueba inválido para asignar.'); } $targetKey = trim(mb_strtoupper($targetValue)); $targetKey = preg_replace('/\s+/', ' ', $targetKey) ?? $targetKey; $selectedAssessor = $targetKey !== '' ? ($assessors[$targetKey] ?? null) : null; if ($targetKey !== '' && !$selectedAssessor) { throw new RuntimeException('No se encontró la asesora seleccionada.'); } $targetUserId = $selectedAssessor ? (int) $selectedAssessor['id'] : null; $stmtCurrent = $pdo->prepare('SELECT user_id FROM callcenter_test_tracking WHERE source_key = ? LIMIT 1'); $stmtCurrent->execute([$sourceKey]); $currentAssignedUserIdRaw = $stmtCurrent->fetchColumn(); $currentAssignedUserId = $currentAssignedUserIdRaw !== null ? ((int) $currentAssignedUserIdRaw > 0 ? (int) $currentAssignedUserIdRaw : null) : null; $isAdmin = in_array((string) ($_SESSION['user_role'] ?? ''), ['Administrador', 'admin'], true); // Los asesores no pueden cambiar pedidos de otra asesora; el administrador sí puede reasignar directamente. if (!$isAdmin && $currentAssignedUserId !== null && $targetUserId !== null && (int) $currentAssignedUserId !== (int) $targetUserId) { $currentLabel = 'otra asesora'; foreach ($assessors as $assessorKey => $assessor) { if ((int) ($assessor['id'] ?? 0) === (int) $currentAssignedUserId) { $currentLabel = (string) ($assessor['label'] ?? $assessorKey); break; } } throw new RuntimeException('Este pedido ya está asignado a ' . $currentLabel . '. Para cambiarlo primero déjalo en "Sin asignar".'); } cc_test_upsert_assignee($pdo, $sourceKey, $targetUserId); $noticeMessage = $selectedAssessor ? 'Pedido asignado a ' . $selectedAssessor['label'] . '.' : 'Pedido dejado sin asignar.'; if ($isMainTuaniStore && $currentAssignedUserId === null && $targetUserId !== null) { $repartoPreviewBefore = cc_test_reparto_preview($assessors, $repartoSettings); $orderedKeys = $repartoPreviewBefore['ordered_keys'] ?? []; $targetPosition = array_search($targetKey, $orderedKeys, true); if ($targetPosition !== false && !empty($orderedKeys)) { $repartoSettings['rotation_date'] = (new DateTimeImmutable('today'))->format('Y-m-d'); $repartoSettings['rotation_index'] = (((int) $targetPosition) + 1) % count($orderedKeys); cc_test_upsert_reparto_settings($pdo, $storeKey, $repartoSettings); $repartoSettings = cc_test_fetch_reparto_settings($pdo, $storeKey, $assessors); } } $tracking = drive_test_fetch_tracking($pdo, array_column($orders, 'source_key')); $orders = drive_test_merge_tracking($orders, $tracking); } elseif ($postedAction === 'save_reparto_config') { if (!$isMainTuaniStore) { throw new RuntimeException('Esta configuración solo aplica a TUANI principal.'); } $postedMode = cc_test_normalize_reparto_mode($_POST['reparto_mode'] ?? 'manual'); $postedStates = $_POST['assessor_state'] ?? []; if (!is_array($postedStates)) { $postedStates = []; } $repartoSettings['reparto_mode'] = $postedMode; $repartoSettings['assessor_states'] = cc_test_reparto_normalize_states($postedStates, $assessors); cc_test_upsert_reparto_settings($pdo, $storeKey, $repartoSettings); $noticeMessage = 'Configuración de reparto guardada.'; } elseif ($postedAction === 'run_daily_reparto') { if (!$isMainTuaniStore) { throw new RuntimeException('El reparto intercalado solo está disponible en TUANI principal.'); } $repartoResult = cc_test_run_locked_reparto_job( $pdo, $storeKey, $assessors, static function () use ($pdo, $storeKey): array { return cc_test_load_reparto_orders($pdo, $storeKey); }, $repartoSettings, static function (array $orders) use ($storeKey, $storeConfig): array { return cc_test_filter_reparto_orders($orders, $storeKey, $storeConfig); } ); $assignedCount = (int) ($repartoResult['assigned_count'] ?? 0); $noticeMessage = $assignedCount > 0 ? 'Reparto intercalado: ' . $assignedCount . ' pedido(s) asignado(s).' : (string) ($repartoResult['message'] ?? 'No había pedidos pendientes o no había asesoras disponibles.'); if ($assignedCount > 0) { $orders = cc_test_load_reparto_orders($pdo, $storeKey); } $repartoSettings = $repartoResult['settings'] ?? $repartoSettings; } } if ($isMainTuaniStore && cc_test_reparto_mode_is_auto($repartoSettings['reparto_mode'] ?? 'manual')) { $autoRepartoResult = cc_test_run_locked_reparto_job( $pdo, $storeKey, $assessors, static function () use ($pdo, $storeKey): array { return cc_test_load_reparto_orders($pdo, $storeKey); }, $repartoSettings, static function (array $orders) use ($storeKey, $storeConfig): array { return cc_test_filter_reparto_orders($orders, $storeKey, $storeConfig); } ); $autoAssignedCount = (int) ($autoRepartoResult['assigned_count'] ?? 0); if ($autoAssignedCount > 0) { $noticeMessage = trim((string) ($noticeMessage !== null ? $noticeMessage . ' ' : '') . 'Reparto automático: ' . $autoAssignedCount . ' pedido(s) asignado(s).'); $orders = cc_test_load_reparto_orders($pdo, $storeKey); } $repartoSettings = $autoRepartoResult['settings'] ?? $repartoSettings; } if ($isMainTuaniStore) { $repartoSettings = cc_test_fetch_reparto_settings($pdo, $storeKey, $assessors); $repartoPreview = cc_test_reparto_preview($assessors, $repartoSettings); } $repartoSourceOrders = $orders; $repartoUnassignedCount = 0; foreach ($repartoSourceOrders as $repartoOrder) { if ((int) ($repartoOrder['user_id'] ?? 0) <= 0) { $repartoUnassignedCount++; } } $sourceKeys = array_column($orders, 'source_key'); $callCounts = []; if (!empty($sourceKeys)) { $placeholders = implode(',', array_fill(0, count($sourceKeys), '?')); $stmtCalls = $pdo->prepare("SELECT pedido_id, COUNT(*) as total FROM historial_llamadas WHERE pedido_id IN ($placeholders) GROUP BY pedido_id"); $stmtCalls->execute($sourceKeys); $callCounts = $stmtCalls->fetchAll(PDO::FETCH_KEY_PAIR); } $role = (string) ($_SESSION['user_role'] ?? ''); $currentUserId = (int) ($_SESSION['user_id'] ?? 0); $isAdmin = in_array($role, ['Administrador', 'admin'], true); if ($isAdmin) { $selectedAssessorFilter = $isTuaniRecuperablesStore ? '' : cc_test_resolve_callcenter_assessor_filter($assessors, $_GET['assessor'] ?? null, !$isTuaniRecuperablesStore, true); } else { unset($_SESSION[cc_test_callcenter_assessor_filter_session_key()]); $selectedAssessorFilter = ''; } $selectedAssessorFilterLabel = $selectedAssessorFilter !== '' ? (string) ($assessors[$selectedAssessorFilter]['label'] ?? $selectedAssessorFilter) : ''; if (!$isAdmin && !$isTuaniRecuperablesStore) { $orders = array_values(array_filter($orders, static function (array $order) use ($currentUserId): bool { return (int) ($order['user_id'] ?? 0) === $currentUserId; })); } $todayStart = new DateTimeImmutable('today'); $todayEnd = $todayStart->setTime(23, 59, 59); $openStates = cc_test_open_states(); $closedStates = cc_test_closed_states(); $recoverablesRecentSourceRowThreshold = null; if ($isTuaniRecuperablesStore) { $recoverablesMaxSourceRow = 0; foreach ($orders as $recoverablesThresholdOrder) { $recoverablesSourceRow = (int) ($recoverablesThresholdOrder['source_row'] ?? 0); if ($recoverablesSourceRow > $recoverablesMaxSourceRow) { $recoverablesMaxSourceRow = $recoverablesSourceRow; } } if ($recoverablesMaxSourceRow > 0) { $recoverablesRecentSourceRowThreshold = max(0, $recoverablesMaxSourceRow - 4); } } foreach ($orders as &$order) { $order['estado'] = cc_test_normalize_state((string) ($order['estado'] ?? '')); $order['total_llamadas'] = (int) ($callCounts[$order['source_key']] ?? 0); $assignedDate = cc_test_parse_datetime($order['assigned_at'] ?? null); $proximaDate = cc_test_parse_datetime($order['proxima_llamada_at'] ?? null); $followupDayInfo = cc_test_followup_day_info($order); $order['seguimiento_dia_info'] = $followupDayInfo; $order['dias_seguimiento'] = $followupDayInfo['day_number'] ?? null; $order['promo_final_habilitado'] = !empty($followupDayInfo['is_promo_final']); $order['promo_final_evidencia_habilitada'] = !empty($followupDayInfo['can_upload_promo_final_evidence']); $order['promo_final_evidencia_cargada'] = trim((string) ($order['promo_final_evidencia_path'] ?? '')) !== ''; $order['es_promo_final'] = $order['promo_final_habilitado'] && $order['promo_final_evidencia_cargada']; $order['promo_final_pendiente'] = $order['promo_final_habilitado'] && !$order['promo_final_evidencia_cargada']; $order['llamada_bloqueada_dia3'] = false; $order['llamada_bloqueada_dia3_mensaje'] = ''; $order['pendiente_logistica_destino'] = cc_test_is_tuani_store_key($storeKey) ? cc_test_pending_logistica_destination($order) : null; $order['pendiente_logistica'] = $order['pendiente_logistica_destino'] !== null; if ($isTuaniRecuperablesStore) { $order['es_nuevo_hoy'] = $recoverablesRecentSourceRowThreshold !== null && (int) ($order['source_row'] ?? 0) >= $recoverablesRecentSourceRowThreshold; } else { $order['es_nuevo_hoy'] = $assignedDate ? $assignedDate->format('Y-m-d') === $todayStart->format('Y-m-d') : false; } $order['es_ultimos_3_dias'] = cc_test_is_within_last_days_window($order, $todayStart, 4); $order['es_pendiente_hoy'] = !$order['es_promo_final'] && (in_array($order['estado'], $openStates, true) || $order['pendiente_logistica']); $order['es_cerrado'] = in_array($order['estado'], $closedStates, true); $order['assessor_key'] = cc_test_find_assessor_key_by_user_id(isset($order['user_id']) ? (int) $order['user_id'] : null, $assessors); $order['assessor_label'] = $order['assessor_key'] !== null ? (string) ($assessors[$order['assessor_key']]['label'] ?? $order['assessor_key']) : 'Sin asignar'; $order['matches_assessor_filter'] = $selectedAssessorFilter === '' || (($order['assessor_key'] ?? '') === $selectedAssessorFilter); if (!$order['matches_assessor_filter']) { continue; } $stats['total']++; if ($order['es_nuevo_hoy']) { $stats['nuevos_hoy']++; } if ($order['es_ultimos_3_dias']) { $stats['ultimos_3_dias']++; } if ($order['es_promo_final']) { $stats['promo_final']++; } if ($order['es_pendiente_hoy']) { $stats['pendientes_hoy']++; } if (in_array($order['estado'], cc_test_confirmed_states(), true)) { $stats['confirmados']++; } if (cc_test_is_recovered_today($order, $todayStart)) { $stats['recuperados']++; } if ($order['estado'] === 'SE ENVIO NUMERO DE CUENTA' && !$order['es_promo_final']) { $stats['seguimiento']++; } if ($order['estado'] === 'OBSERVADO' && !$order['es_promo_final']) { $stats['observados']++; } if ($order['es_cerrado']) { $stats['cerrados']++; } } unset($order); $pendingPromoFinalCounts = cc_test_followup_pending_promo_final_counts($orders); $performanceOrders = $orders; if ($selectedAssessorFilter !== '') { $performanceOrders = array_values(array_filter($orders, static function (array $order) use ($selectedAssessorFilter): bool { return ($order['matches_assessor_filter'] ?? false) === true; })); } $performanceValueOverride = ''; $performanceMetaTitleOverride = ''; $performanceDashboard = cc_test_build_performance_dashboard_period($performanceOrders, $assessors, $kpiPeriodStart, $kpiPeriodEnd); if ($isTuaniRecuperablesStore) { $performanceDashboard = cc_test_filter_dashboard_status_chart($performanceDashboard, ['Confirmados nuevos', 'Recuperados']); $recoverablesStatusDataset = (array) (($performanceDashboard['status_chart']['datasets'][0] ?? []) ?: []); $recoverablesStatusValues = array_map(static function ($value) { return (int) $value; }, array_values((array) ($recoverablesStatusDataset['data'] ?? []))); if (array_sum($recoverablesStatusValues) > 0) { $performanceValueOverride = ''; $performanceMetaTitleOverride = 'Confirmados nuevos + recuperados cubren el periodo mostrado.'; } } $performanceStatusHeading = $kpiPeriodKey === 'today' ? 'Detalle del KPI de hoy (%)' : 'Detalle del KPI del periodo (%)'; $performanceSubtitle = $isTuaniRecuperablesStore ? 'En carritos recuperables solo se muestran confirmados nuevos y recuperados; cuando hay datos, esas dos categorías visibles cubren el periodo mostrado y los repetidos solo suman cantidad.' : ($isAdmin ? 'Confirmación = pedidos asignados en el periodo confirmados en el mismo periodo, sin contar repetidos. Recuperación = pedidos asignados antes del periodo confirmados dentro del periodo. Rendimiento = confirmados totales (nuevos + recuperados) sobre asignados efectivos sin repetidos.' : 'Tus KPIs del periodo seleccionado se calculan sobre tus pedidos asignados en ese rango. Confirmación = asignados del periodo confirmados en el mismo periodo, sin contar repetidos. Recuperación = asignados antes del periodo confirmados dentro del periodo. Rendimiento = confirmados totales (nuevos + recuperados) sobre asignados efectivos sin repetidos.'); if ($isTuaniRecuperablesStore) { $performanceTitle = $kpiPeriodKey === 'today' ? 'KPI compartido de recuperación' : 'KPI compartido de recuperación · ' . $kpiPeriodLabel; $performanceChart1Title = 'Confirmados nuevos vs recuperados'; $performanceChart1Note = 'La dona muestra solo confirmados nuevos y recuperados en esta bandeja.'; $performanceChart2Title = $kpiPeriodKey === 'today' ? 'Evolución de hoy' : 'Evolución de ' . $kpiPeriodTitleLabel; $performanceChart2Note = 'La línea muestra cómo se mueve la bandeja compartida en el periodo seleccionado.'; $performanceFootnote = 'Los indicadores se calculan sobre todos los pedidos visibles de esta bandeja compartida; los repetidos solo suman cantidad y no bajan el porcentaje.'; $performanceLabel = 'Rendimiento del periodo'; $performanceValueOverride = ''; $performanceMetaTitleOverride = 'Confirmados nuevos + recuperados cubren el periodo mostrado.'; $performanceStatusHeading = 'Detalle del KPI del periodo (%)'; } else { if ($isAdmin) { $performanceTitle = $selectedAssessorFilterLabel !== '' ? ($kpiPeriodKey === 'today' ? 'KPI diario · ' . $selectedAssessorFilterLabel : 'KPI de ' . $kpiPeriodTitleLabel . ' · ' . $selectedAssessorFilterLabel) : ($kpiPeriodKey === 'today' ? 'KPI diario por asesora' : 'KPI de ' . $kpiPeriodTitleLabel . ' por asesora'); } else { $performanceTitle = $kpiPeriodKey === 'today' ? 'Mi KPI diario' : 'Mi KPI de ' . $kpiPeriodTitleLabel; } $performanceChart1Title = $isAdmin ? 'Distribución de estados' : 'Mi distribución de estados'; $performanceChart1Note = 'La dona separa los pedidos del periodo seleccionado por estado: confirmados nuevos, recuperados, POR LLAMAR, DEVOLVER LLAMADA, OBSERVADO, SE ENVIO NUMERO DE CUENTA, repetidos (solo cantidad) y cancelados.'; $performanceChart2Title = $kpiPeriodKey === 'today' ? ($isAdmin ? 'Evolución de hoy' : 'Tu evolución de hoy') : ($isAdmin ? 'Evolución de ' . $kpiPeriodTitleLabel : 'Tu evolución de ' . $kpiPeriodTitleLabel); $performanceChart2Note = 'La línea de confirmados separa pedidos asignados y recuperados dentro del periodo seleccionado.'; $performanceFootnote = 'Seguimiento abierto = pedidos asignados en el periodo en POR LLAMAR, DEVOLVER LLAMADA, OBSERVADO y SE ENVIO NUMERO DE CUENTA que todavía no pasan a Promo Final.'; } $performanceDashboardHtml = cc_test_render_performance_dashboard($performanceDashboard, [ 'title' => $performanceTitle, 'subtitle' => $performanceSubtitle, 'chart1_title' => $performanceChart1Title, 'chart1_note' => $performanceChart1Note, 'chart2_title' => $performanceChart2Title, 'chart2_note' => $performanceChart2Note, 'footnote' => $performanceFootnote, 'performance_label' => $performanceLabel, 'performance_value_hidden' => $isTuaniRecuperablesStore, 'status_detail_heading' => $performanceStatusHeading, 'performance_value' => $performanceValueOverride, 'performance_meta_title' => $performanceMetaTitleOverride, ]); $visibleOrders = array_values(array_filter($orders, static function (array $order) use ($view, $selectedAssessorFilter, $todayStart): bool { if ($selectedAssessorFilter !== '' && !($order['matches_assessor_filter'] ?? false)) { return false; } return match ($view) { 'pendientes_hoy' => (bool) ($order['es_pendiente_hoy'] ?? false), 'nuevos_hoy' => (bool) ($order['es_nuevo_hoy'] ?? false), 'ultimos_3_dias' => (bool) ($order['es_ultimos_3_dias'] ?? false), 'confirmados' => in_array(($order['estado'] ?? ''), cc_test_confirmed_states(), true), 'recuperados' => cc_test_is_recovered_today($order, $todayStart), 'seguimiento' => ($order['estado'] ?? '') === 'SE ENVIO NUMERO DE CUENTA' && !($order['es_promo_final'] ?? false), 'promo_final' => (bool) ($order['es_promo_final'] ?? false), 'observados' => ($order['estado'] ?? '') === 'OBSERVADO' && !($order['es_promo_final'] ?? false), 'cerrados' => (bool) ($order['es_cerrado'] ?? false), default => true, }; })); usort($visibleOrders, static function (array $a, array $b) use ($view, $storeKey): int { $aImport = cc_test_import_time($a); $bImport = cc_test_import_time($b); if (cc_test_is_recoverables_store_key($storeKey) && in_array($view, ['pendientes_hoy', 'todos'], true)) { return cc_test_compare_recoverables_orders_desc($a, $b); } if ($view === 'nuevos_hoy') { $aOrderNumberValue = cc_test_order_priority_value($a); $bOrderNumberValue = cc_test_order_priority_value($b); if ($aOrderNumberValue !== $bOrderNumberValue) { return $bOrderNumberValue <=> $aOrderNumberValue; } $aAssigned = cc_test_parse_datetime($a['assigned_at'] ?? null); $bAssigned = cc_test_parse_datetime($b['assigned_at'] ?? null); if ($aAssigned && $bAssigned && $aAssigned != $bAssigned) { return $bAssigned <=> $aAssigned; } if ($aAssigned && !$bAssigned) { return -1; } if (!$aAssigned && $bAssigned) { return 1; } } if ($view === 'ultimos_3_dias') { $aOrderNumberValue = cc_test_order_priority_value($a); $bOrderNumberValue = cc_test_order_priority_value($b); if ($aOrderNumberValue !== $bOrderNumberValue) { return $bOrderNumberValue <=> $aOrderNumberValue; } $aRecent = cc_test_recent_followup_anchor($a); $bRecent = cc_test_recent_followup_anchor($b); $aRecentTs = $aRecent instanceof DateTimeImmutable ? $aRecent->getTimestamp() : null; $bRecentTs = $bRecent instanceof DateTimeImmutable ? $bRecent->getTimestamp() : null; if ($aRecentTs !== null && $bRecentTs !== null && $aRecentTs !== $bRecentTs) { return $bRecentTs <=> $aRecentTs; } if ($aRecentTs !== null && $bRecentTs === null) { return -1; } if ($aRecentTs === null && $bRecentTs !== null) { return 1; } if ($aImport !== $bImport) { return $bImport <=> $aImport; } } if ($view === 'recuperados') { $aRecovered = cc_test_dashboard_action_datetime($a); $bRecovered = cc_test_dashboard_action_datetime($b); if ($aRecovered && $bRecovered && $aRecovered != $bRecovered) { return $bRecovered <=> $aRecovered; } if ($aRecovered && !$bRecovered) { return -1; } if (!$aRecovered && $bRecovered) { return 1; } } if ($view === 'promo_final') { $aDays = (int) ($a['dias_seguimiento'] ?? 0); $bDays = (int) ($b['dias_seguimiento'] ?? 0); if ($aDays !== $bDays) { return $bDays <=> $aDays; } if ($aImport !== $bImport) { return $aImport <=> $bImport; } } if ($view === "pendientes_hoy") { $aPendientePromoFinal = !empty($a['promo_final_pendiente']); $bPendientePromoFinal = !empty($b['promo_final_pendiente']); if ($aPendientePromoFinal !== $bPendientePromoFinal) { return $aPendientePromoFinal ? -1 : 1; } $aPendienteLogistica = !empty($a['pendiente_logistica']); $bPendienteLogistica = !empty($b['pendiente_logistica']); if ($aPendienteLogistica !== $bPendienteLogistica) { return $aPendienteLogistica ? -1 : 1; } $aAssigned = cc_test_parse_datetime($a['assigned_at'] ?? null); $bAssigned = cc_test_parse_datetime($b['assigned_at'] ?? null); if ($aAssigned && $bAssigned && $aAssigned != $bAssigned) { return $bAssigned <=> $aAssigned; } if ($aAssigned && !$bAssigned) { return -1; } if (!$aAssigned && $bAssigned) { return 1; } $aDue = cc_test_parse_datetime($a["proxima_llamada_at"] ?? null); $bDue = cc_test_parse_datetime($b["proxima_llamada_at"] ?? null); if ($aDue && $bDue && $aDue != $bDue) { return $aDue <=> $bDue; } if ($aDue && !$bDue) { return 1; } if (!$aDue && $bDue) { return -1; } if (cc_test_is_tuani_store_key($storeKey)) { $aSourceRow = (int) ($a['source_row'] ?? 0); $bSourceRow = (int) ($b['source_row'] ?? 0); if ($aSourceRow > 0 && $bSourceRow > 0 && $aSourceRow !== $bSourceRow) { return $bSourceRow <=> $aSourceRow; } } } if ($view === 'todos') { if (cc_test_is_recoverables_store_key($storeKey)) { return cc_test_compare_recoverables_orders_desc($a, $b); } if ($aImport !== $bImport) { return $bImport <=> $aImport; } $aSourceRow = (int) ($a['source_row'] ?? 0); $bSourceRow = (int) ($b['source_row'] ?? 0); if ($aSourceRow !== $bSourceRow) { return $bSourceRow <=> $aSourceRow; } $aId = (int) ($a['id'] ?? 0); $bId = (int) ($b['id'] ?? 0); if ($aId !== $bId) { return $bId <=> $aId; } return strcmp((string) ($a['source_key'] ?? ''), (string) ($b['source_key'] ?? '')); } if ($aImport !== $bImport) { return $bImport <=> $aImport; } return cc_test_order_time($b) <=> cc_test_order_time($a); }); $assessorInboxLockedOrders = []; if (!$isAdmin && !$isTuaniRecuperablesStore) { $currentUserLockKey = $currentUserId > 0 ? 'user:' . $currentUserId : ''; if ($currentUserLockKey !== '') { $assessorInboxLockedOrders = array_values(array_filter($orders, static function (array $order) use ($currentUserLockKey): bool { return cc_test_followup_owner_lock_key($order) === $currentUserLockKey && !empty($order['promo_final_pendiente']); })); } } $assessorInboxLockedCount = count($assessorInboxLockedOrders); $assessorInboxLocked = $assessorInboxLockedCount > 0; $assessorInboxLockedView = $assessorInboxLocked && $view === 'nuevos_hoy'; $assessorInboxLockNotice = $assessorInboxLocked ? 'Tienes ' . $assessorInboxLockedCount . ' pedido' . ($assessorInboxLockedCount === 1 ? '' : 's') . ' pendiente' . ($assessorInboxLockedCount === 1 ? '' : 's') . ' de Promo Final. Mientras existan pendientes de sustento, los pedidos de Día 1 mantienen el número oculto; cuando ya no queden pendientes, el celular volverá a mostrarse.' : ''; $visibleOrdersTotalCount = count($visibleOrders); $todosPageSize = 200; $todosPage = 1; $todosTotalPages = 1; $todosPageStart = 0; $todosPageEnd = 0; $todosPaginationPages = []; $requestedPage = (int) ($_GET['page'] ?? 1); if ($requestedPage < 1) { $requestedPage = 1; } $todosTotalPages = max(1, (int) ceil($visibleOrdersTotalCount / $todosPageSize)); if ($requestedPage > $todosTotalPages) { $requestedPage = $todosTotalPages; } $todosPage = $requestedPage; $todosPageStart = ($todosPage - 1) * $todosPageSize; $visibleOrders = array_slice($visibleOrders, $todosPageStart, $todosPageSize); $todosPageEnd = $todosPageStart + count($visibleOrders); if ($isTuaniRecuperablesStore) { $visibleOrders = cc_test_mark_recoverables_duplicate_orders($pdo, $visibleOrders, $storeKey); } if ($todosTotalPages <= 7) { $todosPaginationPages = range(1, $todosTotalPages); } else { $todosPaginationPages[] = 1; $windowStart = max(2, $todosPage - 1); $windowEnd = min($todosTotalPages - 1, $todosPage + 1); if ($windowStart > 2) { $todosPaginationPages[] = 'ellipsis'; } for ($pageNumber = $windowStart; $pageNumber <= $windowEnd; $pageNumber++) { $todosPaginationPages[] = $pageNumber; } if ($windowEnd < $todosTotalPages - 1) { $todosPaginationPages[] = 'ellipsis'; } $todosPaginationPages[] = $todosTotalPages; } } catch (Throwable $exception) { $errorMessage = $exception->getMessage(); } $callCenterBaseParams = [ 'view' => $view, 'store' => $storeKey, 'kpi_period' => $kpiPeriodKey, ]; if ($kpiPeriodCustomDateInput !== '') { $callCenterBaseParams['kpi_date'] = $kpiPeriodCustomDateInput; } $callCenterDatabaseParams = $callCenterBaseParams; if ($isAdmin) { $callCenterDatabaseParams['view'] = 'todos'; } $callCenterParams = $callCenterBaseParams; if ($selectedAssessorFilter !== '') { $callCenterParams['assessor'] = $selectedAssessorFilter; } $panelOrdersSignature = isset($visibleOrders) && is_array($visibleOrders) ? cc_test_panel_orders_signature($visibleOrders) : ''; if (!empty($_GET['ajax_refresh'])) { header('Content-Type: application/json; charset=utf-8'); if ($errorMessage !== null) { echo json_encode([ 'success' => false, 'error' => $errorMessage, ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); } else { echo json_encode([ 'success' => true, 'signature' => $panelOrdersSignature, 'count' => $visibleOrdersTotalCount, 'view' => $view, 'store' => $storeKey, ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); } exit; } if ($isTuaniRecuperablesStore) { $pageTitle = $storeLabel . ' | Bandeja compartida'; $pageDescription = 'Bandeja compartida para que cualquier asesora gestione ' . mb_strtolower($storeLabel) . ' con vistas de seguimiento y observados desde Drive.'; } else { $pageTitle = 'Pedidos Asignados | Bandeja de la asesora'; $pageDescription = 'Bandeja para que cada asesora gestione sus pedidos asignados con vistas de hoy, últimos 4 días hábiles, estados, historial y acciones.'; } $callCenterSectionLabel = $isTuaniRecuperablesStore ? $storeLabel : 'Pedidos Asignados'; require_once 'layout_header.php'; ?>

Tienda activa: Solo pedidos válidos: IDs #D... Abrir (#D...)
Dentro de
Pedidos $childConfig): ?>
Drive detectado: filas Agregados: : última fila del Drive · último pedido : distribución desde fila · último procesado Extracción: desde fila Actualización en vivo cada 5 min Ver vista previa Drive
Filtro KPI

Panel KPI ·

Filtra el panel para ver el avance del periodo seleccionado.
$periodLabel): ?>
Aviso rápido
Última fila real del Drive: · Último pedido detectado:
Te ayuda a comprobar de un vistazo si la cola llegó al final.
$viewCard): ?>
Agregar asesora Ver todas
Usa este filtro para revisar solo los pedidos de una asesora y ver sus tarjetas por estado dentro de esta misma pantalla.

Este resumen muestra solo los pedidos importados desde la hoja, no contadores de otras pantallas.

Asesora: Pedidos importados: Filas de origen: Página de · hasta por página pedidos únicos en esta bandeja 1): ?> Página de · 200 por página Pedidos con sustento pendiente para Promo Final
Pedidos con sustento pendiente para Promo Final
Usa Últimos 4 días hábiles si necesitas completar ese sustento más rápido.
Ir a Últimos 4 días hábiles
'Falta subirlo a Ruta Contraentrega.', 'rotulado' => 'Falta subirlo a Pedidos Rotulados.', default => '', }; $subirLogisticaButtonLabel = 'Subir pedido'; $subirLogisticaNoteClass = 'alert alert-secondary py-2 px-3 mt-2 mb-0'; $subirLogisticaNoteHtml = 'Selecciona CONFIRMADO CONTRAENTREGA o CONFIRMADO ENVIO y completa Confirmación de pedido (producto, cantidad y precio) para enviarlo a logística.'; if ($canShowTuaniLogisticaButton) { if ($order['estado'] === 'CONFIRMADO CONTRAENTREGA') { if (!empty($order['ruta_contraentrega_pedido_id'])) { $subirLogisticaButtonLabel = 'Actualizar en ruta'; $subirLogisticaNoteClass = 'alert alert-success py-2 px-3 mt-2 mb-0'; $subirLogisticaNoteHtml = 'En Ruta Contraentrega #' . (int) $order['ruta_contraentrega_pedido_id'] . '. Si cambias algo, usa este botón para actualizarlo.'; } else { $subirLogisticaButtonLabel = 'Subir a ruta'; $subirLogisticaNoteClass = 'alert alert-warning py-2 px-3 mt-2 mb-0'; $subirLogisticaNoteHtml = 'ALERTA: este pedido está en CONFIRMADO CONTRAENTREGA, pero aún no se ha subido a Ruta Contraentrega. Usa este botón para subirlo.'; } } elseif ($order['estado'] === 'CONFIRMADO ENVIO') { if (!empty($order['pedido_rotulado_pedido_id'])) { $subirLogisticaButtonLabel = 'Actualizar rotulado'; $subirLogisticaNoteClass = 'alert alert-success py-2 px-3 mt-2 mb-0'; $subirLogisticaNoteHtml = 'En Pedidos Rotulados #' . (int) $order['pedido_rotulado_pedido_id'] . '. Si cambias algo, usa este botón para actualizarlo.'; } else { $subirLogisticaButtonLabel = 'Subir a rotulados'; $subirLogisticaNoteClass = 'alert alert-warning py-2 px-3 mt-2 mb-0'; $subirLogisticaNoteHtml = 'ALERTA: este pedido está en CONFIRMADO ENVIO, pero aún no se ha subido a Pedidos Rotulados. Usa este botón para subirlo.'; } } } $rowBackgroundStyle = cc_test_row_background_style((string) ($order['estado'] ?? 'POR LLAMAR')); if ($isTuaniRecuperablesStore && !empty($order['pedido_repetido_en_tienda'])) { $rowBackgroundStyle .= '--cc-row-bg:#CCCCCC;'; } $phoneLocked = false; $phoneLockMessage = (string) ($order['llamada_bloqueada_dia3_mensaje'] ?? ''); if ($phoneLocked && $phoneLockMessage === '') { $phoneLockMessage = 'Celular oculto mientras completas los pendientes del Día 4.'; } $phoneHiddenByDay1 = cc_test_followup_day1_phone_hidden($order, $pendingPromoFinalCounts); $phoneRowHiddenLabel = 'Número oculto'; $phoneRowHiddenTitle = 'Número oculto hasta completar Promo Final'; ob_start(); ?>
N° Pedido Cliente Ubicación editable Pedido Gestión Acciones
No hay pedidos únicos en esta bandeja para . No hay pedidos únicos en esta bandeja por ahora.
00:00
DÍA
Celular:
DNI:
Dirección:
Referencia:
Departamento:
Provincia:
Distrito:
Coordenadas:
DISTRITO 1:
Cantidad: ·
Ingreso Drive:
Observación Drive:
llamadas Seguimiento
Número de cuenta enviado hace día ·
Seguimiento: · desde
Próxima llamada:
Entrega programada:
Subido a Ruta Contraentrega # ·
Subido a Pedidos Rotulados # ·
Última gestión:
Nota:
0 ? (int) $orderUserId : null) : null; $unassigned = $orderUserIdNorm === null; $assignedAssessorKey = $order['assessor_key'] ?? null; $assignFormClass = 'border rounded-3 p-1 text-start cc-callcenter-assign-form'; $assignFormStyle = ''; if ($unassigned) { $assignFormClass .= ' is-unassigned'; } elseif ($assignedAssessorKey !== null) { $assignFormClass .= ' has-accent'; $assignFormStyle = cc_test_assessor_css_vars($assignedAssessorKey, $assessors[$assignedAssessorKey]['color_hex'] ?? null); } else { $assignFormClass .= ' is-neutral'; } $selectedAssessorKeyForSelect = $unassigned ? '' : ($assignedAssessorKey !== null ? (string) $assignedAssessorKey : ''); $buttonLabel = $unassigned ? 'Asignar pedido' : ($assignedAssessorKey !== null ? 'Guardar asignación' : 'Desasignar'); ?>
autocomplete="off">
Asignar a asesora
Sin asignar Asignado
WhatsApp
1): ?>
0): ?> Mostrando - de pedidos · 200 por página No hay pedidos para mostrar en esta vista.
1): ?>
Llamada preparada para AirDroid

Número listo para copiar

Pedido
-
Cliente
-
Número
-