@@ -471,10 +729,16 @@ require_once 'layout_header.php';
Asignar a asesora
+
diff --git a/includes/drive_test_orders.php b/includes/drive_test_orders.php
index d2b9ec1b..61b8cec7 100644
--- a/includes/drive_test_orders.php
+++ b/includes/drive_test_orders.php
@@ -10,6 +10,76 @@ function drive_test_normalize_header(string $header): string
return $header;
}
+function drive_test_available_stores(): array
+{
+ return [
+ // Hoja original que ya venía funcionando.
+ 'flower' => [
+ 'label' => 'Flower',
+ 'spreadsheet_id' => '1SSmQuR9quxeQbMKNMDkRe8-n1gU7WuEfsFaJ3WKFO-c',
+ 'sheet_gid' => null,
+ 'startRow' => 5552,
+ ],
+ // Segunda tienda (nuevo link que pasaste).
+ 'otra_tienda' => [
+ 'label' => 'TUANI',
+ 'spreadsheet_id' => '1QYKeBJIIqYm6yW6Ka-5gKdxhUHwXOAc0No7RjnimxTw',
+ 'sheet_gid' => 1523126328,
+ 'startRow' => 5552,
+ ],
+ ];
+}
+
+function drive_test_get_store_config(string $storeKey): array
+{
+ $storeKey = trim(mb_strtolower($storeKey));
+ $stores = drive_test_available_stores();
+
+ if (!isset($stores[$storeKey])) {
+ return $stores['flower'];
+ }
+
+ return $stores[$storeKey] + ['key' => $storeKey];
+}
+
+function drive_test_resolve_sheet_a1_range($service, string $spreadsheetId, ?int $sheetGid, string $rangeA1): string
+{
+ if ($sheetGid === null) {
+ return $rangeA1;
+ }
+
+ static $cache = [];
+ $cacheKey = $spreadsheetId . '|' . (string) $sheetGid . '|' . $rangeA1;
+ if (isset($cache[$cacheKey])) {
+ return $cache[$cacheKey];
+ }
+
+ try {
+ $meta = $service->spreadsheets->get($spreadsheetId, ['fields' => 'sheets(properties(sheetId,title))']);
+ foreach (($meta->getSheets() ?? []) as $sheet) {
+ $props = $sheet->getProperties();
+ if (!$props) {
+ continue;
+ }
+
+ if ((int) $props->getSheetId() === (int) $sheetGid) {
+ $title = trim((string) ($props->getTitle() ?? ''));
+ if ($title !== '') {
+ // Sheet names with spaces/special chars must be quoted.
+ $escaped = str_replace("'", "''", $title);
+ $cache[$cacheKey] = "'{$escaped}'!{$rangeA1}";
+ return $cache[$cacheKey];
+ }
+ }
+ }
+ } catch (Throwable $exception) {
+ // Fallback to default range.
+ }
+
+ $cache[$cacheKey] = $rangeA1;
+ return $rangeA1;
+}
+
function drive_test_get_cell(array $row, array $indexes, array $aliases, string $default = ''): string
{
foreach ($aliases as $alias) {
@@ -22,11 +92,18 @@ function drive_test_get_cell(array $row, array $indexes, array $aliases, string
return $default;
}
-function drive_test_fetch_orders(int $limit = 10, int $startRow = 5552): array
+function drive_test_fetch_orders(int $limit = 10, int $startRow = 5552, string $storeKey = 'flower'): array
{
+ $storeConfig = drive_test_get_store_config($storeKey);
+
$credentialsPath = __DIR__ . '/../google_credentials.json';
- $spreadsheetId = '1SSmQuR9quxeQbMKNMDkRe8-n1gU7WuEfsFaJ3WKFO-c';
- $range = 'A:Z';
+ $spreadsheetId = (string) ($storeConfig['spreadsheet_id'] ?? '');
+ $sheetGid = array_key_exists('sheet_gid', $storeConfig) ? ($storeConfig['sheet_gid'] === null ? null : (int) $storeConfig['sheet_gid']) : null;
+ $rangeA1 = 'A:Z';
+
+ if ($spreadsheetId === '') {
+ throw new RuntimeException('Configuración de Drive para la tienda no válida.');
+ }
if (!file_exists($credentialsPath)) {
throw new RuntimeException('No se encontró el archivo de credenciales de Google.');
@@ -37,6 +114,9 @@ function drive_test_fetch_orders(int $limit = 10, int $startRow = 5552): array
$client->addScope(Google\Service\Sheets::SPREADSHEETS_READONLY);
$service = new Google\Service\Sheets($client);
+
+ $range = drive_test_resolve_sheet_a1_range($service, $spreadsheetId, $sheetGid, $rangeA1);
+
$response = $service->spreadsheets_values->get($spreadsheetId, $range);
$values = $response->getValues();
@@ -59,16 +139,16 @@ function drive_test_fetch_orders(int $limit = 10, int $startRow = 5552): array
}
$dataRows = array_slice($values, 1);
+
$startIndex = max(0, $startRow - 2);
- if ($startIndex > 0) {
+ if ($startIndex > 0 && $startIndex < count($dataRows)) {
$dataRows = array_slice($dataRows, $startIndex);
}
- if ($limit > 0) {
- $previewRows = array_reverse(array_slice($dataRows, -$limit));
- } else {
- $previewRows = array_reverse($dataRows);
- }
+ $previewRows = $limit > 0
+ ? array_reverse(array_slice($dataRows, -$limit))
+ : array_reverse($dataRows);
+
$orders = [];
foreach ($previewRows as $row) {
@@ -89,7 +169,15 @@ function drive_test_fetch_orders(int $limit = 10, int $startRow = 5552): array
$direccion = drive_test_get_cell($row, $headerIndexes, ['DIRECION', 'DIRECCION']);
$referencia = drive_test_get_cell($row, $headerIndexes, ['REFERENCIA']);
$distrito = drive_test_get_cell($row, $headerIndexes, ['DISTRITO']);
- $sourceKey = sha1(implode('|', [$codigo, $importId, $nombre, $celular, $producto]));
+
+ // Importante: para 'flower' mantenemos EXACTAMENTE el algoritmo anterior
+ // para no romper el historial/tracking ya existente.
+ $sourceKeyBase = implode('|', [$codigo, $importId, $nombre, $celular, $producto]);
+ if (($storeConfig['key'] ?? 'flower') === 'flower') {
+ $sourceKey = sha1($sourceKeyBase);
+ } else {
+ $sourceKey = sha1(($storeConfig['key'] ?? $storeKey) . '|' . $sourceKeyBase);
+ }
$orders[] = [
'source_key' => $sourceKey,
diff --git a/index.php b/index.php
index d693afda..3372832b 100644
--- a/index.php
+++ b/index.php
@@ -104,7 +104,7 @@ $pageDescription = 'Entrada rápida al sistema CRM y panel de administración.';
-
Abrir Call Center de prueba
+
Abrir Base de Datos Pedidos
-
- visibles
-
+
+ Tienda:
+
+ visibles
+
+
diff --git a/update_callcenter_test_tracking.php b/update_callcenter_test_tracking.php
index 824173a3..8fad7a65 100644
--- a/update_callcenter_test_tracking.php
+++ b/update_callcenter_test_tracking.php
@@ -71,10 +71,26 @@ try {
$pdo = db();
cc_test_ensure_tracking_table($pdo);
- $stmtCurrent = $pdo->prepare('SELECT estado, numero_cuenta_enviado_at FROM callcenter_test_tracking WHERE source_key = ? LIMIT 1');
+ $stmtCurrent = $pdo->prepare('SELECT estado, numero_cuenta_enviado_at, user_id FROM callcenter_test_tracking WHERE source_key = ? LIMIT 1');
$stmtCurrent->execute([$sourceKey]);
$currentTracking = $stmtCurrent->fetch(PDO::FETCH_ASSOC) ?: null;
+ $role = (string) ($_SESSION['user_role'] ?? '');
+ $isAdmin = in_array($role, ['Administrador', 'admin'], true);
+ if (!$isAdmin) {
+ $currentUserId = (int) ($_SESSION['user_id'] ?? 0);
+ $trackingUserId = $currentTracking ? (int) ($currentTracking['user_id'] ?? 0) : null;
+ if (!$currentTracking || $trackingUserId !== $currentUserId) {
+ http_response_code(403);
+ echo json_encode(['success' => false, 'message' => 'No autorizado para gestionar este pedido.']);
+ exit;
+ }
+ }
+
+ $userIdToSet = $isAdmin
+ ? ($currentTracking ? ($currentTracking['user_id'] ?? null) : null)
+ : (int) $_SESSION['user_id'];
+
$proximaRaw = trim((string) ($_POST['proxima_llamada_at'] ?? ''));
$proximaLlamada = null;
if ($proximaRaw !== '') {
@@ -204,7 +220,7 @@ try {
':source_key' => $sourceKey,
':estado' => $estado,
':nota' => $nota,
- ':user_id' => (int) $_SESSION['user_id'],
+ ':user_id' => $userIdToSet,
':direccion' => $direccion,
':referencia' => $referencia,
':agencia' => $agencia,