34849-vm/test_importar_drive.php
2026-08-07 07:36:47 +00:00

195 lines
10 KiB
PHP

<?php
session_start();
require_once __DIR__ . '/db/config.php';
require_once __DIR__ . '/includes/callcenter_test_helpers.php';
require_once __DIR__ . '/includes/drive_test_orders.php';
$pageTitle = 'Importar Drive (Test)';
$pageDescription = 'Vista previa de los últimos 10 pedidos detectados en Google Sheets antes de importarlos al CRM.';
if (!cc_test_current_user_can_access_module(db())) {
http_response_code(403);
require_once __DIR__ . '/layout_header.php';
echo "<div class='container py-5'><div class='alert alert-danger mb-0'>Acceso denegado.</div></div>";
require_once __DIR__ . '/layout_footer.php';
exit();
}
require_once __DIR__ . '/layout_header.php';
require_once __DIR__ . '/vendor/autoload.php';
$credentialsPath = __DIR__ . '/google_credentials.json';
$storeKey = trim((string) ($_GET['store'] ?? 'flower'));
$storeKey = mb_strtolower($storeKey);
$availableStores = drive_test_available_stores();
if (!isset($availableStores[$storeKey])) {
$storeKey = 'flower';
}
$storeConfig = $availableStores[$storeKey];
$storeLabel = (string) ($storeConfig['label'] ?? strtoupper($storeKey));
$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'] ?? '');
$sheetTitle = trim((string) ($storeConfig['sheet_title'] ?? ''));
$spreadsheetId = (string) ($storeConfig['spreadsheet_id'] ?? '');
$rangeA1 = 'A:Z';
$sheetGid = array_key_exists('sheet_gid', $storeConfig) ? ($storeConfig['sheet_gid'] === null ? null : (int) $storeConfig['sheet_gid']) : null;
$range = $rangeA1;
$headers = [];
$previewRows = [];
$errorMessage = null;
$totalDataRows = 0;
try {
if (!file_exists($credentialsPath)) {
throw new RuntimeException('No se encontró el archivo de credenciales de Google.');
}
$client = new Google\Client();
$client->setAuthConfig($credentialsPath);
$client->addScope(Google\Service\Sheets::SPREADSHEETS_READONLY);
$service = new Google\Service\Sheets($client);
$range = drive_test_resolve_sheet_a1_range($service, $spreadsheetId, $sheetGid, $rangeA1, $sheetTitle);
$response = $service->spreadsheets_values->get($spreadsheetId, $range);
$values = $response->getValues();
if (empty($values)) {
throw new RuntimeException('La hoja está vacía o no devolvió datos.');
}
$headers = $values[0] ?? [];
$dataRows = array_slice($values, 1);
$totalDataRows = count($dataRows);
$previewRows = array_reverse(array_slice($dataRows, -10));
} catch (Throwable $exception) {
$errorMessage = $exception->getMessage();
}
?>
<div class="container py-4">
<div class="card shadow-sm border-0 mb-4">
<div class="card-body py-3">
<div class="d-flex flex-column flex-lg-row align-items-lg-center gap-3">
<div class="d-flex flex-column gap-3">
<div class="d-flex flex-wrap gap-2">
<?php foreach ($storeNavGroups as $groupKey => $group): ?>
<?php $groupConfig = $group['config'] ?? []; ?>
<a class="btn btn-sm <?php echo $activeStoreGroupKey === $groupKey ? 'btn-primary' : 'btn-outline-primary'; ?>" href="?store=<?php echo htmlspecialchars((string) $groupKey); ?>">
<?php echo htmlspecialchars((string) ($groupConfig['label'] ?? strtoupper((string) $groupKey))); ?>
</a>
<?php endforeach; ?>
</div>
<?php if (!empty($activeStoreGroupChildren)): ?>
<div class="p-3 rounded-4 border bg-light">
<div class="small text-uppercase text-muted fw-semibold mb-2">Dentro de <?php echo htmlspecialchars($activeStoreGroupLabel); ?></div>
<div class="d-flex flex-wrap gap-2">
<a class="btn btn-sm <?php echo $storeKey === $activeStoreGroupKey ? 'btn-primary' : 'btn-outline-primary'; ?>" href="?store=<?php echo htmlspecialchars((string) $activeStoreGroupKey); ?>">Pedidos <?php echo htmlspecialchars($activeStoreGroupLabel); ?></a>
<?php foreach ($activeStoreGroupChildren as $childKey => $childConfig): ?>
<a class="btn btn-sm <?php echo $storeKey === $childKey ? 'btn-primary' : 'btn-outline-primary'; ?>" href="?store=<?php echo htmlspecialchars((string) $childKey); ?>">
<?php echo htmlspecialchars((string) ($childConfig['label'] ?? strtoupper((string) $childKey))); ?>
</a>
<?php endforeach; ?>
</div>
</div>
<?php endif; ?>
</div>
<div class="ms-lg-auto d-flex flex-wrap gap-2">
<span class="badge bg-light text-dark border px-3 py-2">Tienda: <?php echo htmlspecialchars($storeLabel); ?></span>
<?php if ($sheetTitle !== ''): ?>
<span class="badge bg-light text-dark border px-3 py-2">Hoja: <?php echo htmlspecialchars($sheetTitle); ?></span>
<?php endif; ?>
<span class="badge bg-light text-dark border px-3 py-2">Desde fila: <?php echo (int) ($storeConfig['startRow'] ?? 0); ?></span>
<span class="badge bg-primary-subtle text-primary-emphasis px-3 py-2"><?php echo (int) count($previewRows); ?> visibles</span>
</div>
</div>
</div>
</div>
<div class="row g-4 align-items-stretch">
<div class="col-12 col-xl-8">
<div class="card shadow-sm border-0 h-100">
<div class="card-body p-4">
<div class="d-flex flex-column flex-md-row justify-content-between align-items-md-center gap-3 mb-3">
<div>
<h2 class="h4 mb-1">Vista previa de pedidos desde Drive</h2>
<p class="text-muted mb-0">Aquí verás solo los últimos 10 registros encontrados en la hoja, sin guardar nada todavía en la base de datos.</p>
</div>
<div class="d-flex flex-wrap gap-2 justify-content-end">
<span class="badge bg-light text-dark border px-3 py-2">Tienda: <?php echo htmlspecialchars((string) ($storeConfig['label'] ?? '')); ?></span>
<span class="badge bg-primary-subtle text-primary-emphasis px-3 py-2">
<?php echo (int) count($previewRows); ?> visibles
</span>
</div>
</div>
<?php if ($errorMessage !== null): ?>
<div class="alert alert-danger mb-0" role="alert">
<strong>No se pudo cargar la vista previa.</strong><br>
<?php echo htmlspecialchars($errorMessage); ?>
</div>
<?php elseif (empty($previewRows)): ?>
<div class="alert alert-warning mb-0" role="alert">
La hoja respondió correctamente, pero todavía no hay pedidos suficientes para mostrar una vista previa.
</div>
<?php else: ?>
<div class="table-responsive">
<table class="table table-hover align-middle">
<thead class="table-dark">
<tr>
<?php foreach ($headers as $header): ?>
<th scope="col"><?php echo htmlspecialchars((string) $header); ?></th>
<?php endforeach; ?>
</tr>
</thead>
<tbody>
<?php foreach ($previewRows as $row): ?>
<tr>
<?php for ($i = 0; $i < count($headers); $i++): ?>
<td><?php echo htmlspecialchars((string) ($row[$i] ?? '')); ?></td>
<?php endfor; ?>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php endif; ?>
</div>
</div>
</div>
<div class="col-12 col-xl-4">
<div class="card shadow-sm border-0 mb-4">
<div class="card-body p-4">
<h2 class="h5">Cómo funciona esta prueba</h2>
<ol class="mb-0 ps-3">
<li class="mb-2">Lee la hoja de Google Sheets en tiempo real.</li>
<li class="mb-2">Toma solo los últimos 10 pedidos detectados.</li>
<li class="mb-0">Muestra la información en pantalla sin importar nada al CRM.</li>
</ol>
</div>
</div>
<div class="card shadow-sm border-0">
<div class="card-body p-4">
<h2 class="h5">Resumen rápido</h2>
<ul class="list-unstyled mb-0">
<li class="mb-2"><strong>Modo:</strong> Vista previa segura</li>
<li class="mb-2"><strong>Pedidos totales detectados:</strong> <?php echo (int) $totalDataRows; ?></li>
<li class="mb-2"><strong>Pedidos visibles:</strong> <?php echo (int) count($previewRows); ?></li>
<li class="mb-0"><strong>Base de datos:</strong> Sin cambios</li>
</ul>
</div>
</div>
</div>
</div>
</div>
<?php require_once __DIR__ . '/layout_footer.php'; ?>