@@ -1418,7 +1616,7 @@ require_once 'layout_header.php';
|
- No hay pedidos en esta bandeja por ahora.
+ No hay pedidos únicos en esta bandeja por ahora.
|
diff --git a/includes/callcenter_test_management.php b/includes/callcenter_test_management.php
index af584ecc..bb44db65 100644
--- a/includes/callcenter_test_management.php
+++ b/includes/callcenter_test_management.php
@@ -160,10 +160,10 @@ function cc_test_ensure_schema(PDO $pdo): void
$pdo->exec("CREATE TABLE IF NOT EXISTS `callcenter_test_orders` (
`id` INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
`source_key` CHAR(40) NOT NULL,
- `codigo` VARCHAR(80) DEFAULT NULL,
- `import_id` VARCHAR(120) DEFAULT NULL,
+ `codigo` TEXT NULL,
+ `import_id` TEXT NULL,
`drive_imported_at` DATETIME NULL,
- `nombre` VARCHAR(255) DEFAULT NULL,
+ `nombre` TEXT NULL,
`direccion_drive` TEXT NULL,
`referencia_drive` TEXT NULL,
`sede_drive` VARCHAR(120) NULL,
@@ -171,13 +171,13 @@ function cc_test_ensure_schema(PDO $pdo): void
`distrito_drive` VARCHAR(120) NULL,
`dni_drive` LONGTEXT NULL,
`observaciones_drive` TEXT NULL,
- `celular` VARCHAR(40) DEFAULT NULL,
+ `celular` TEXT NULL,
`producto` TEXT NULL,
- `cantidad` VARCHAR(60) NULL,
- `precio` VARCHAR(60) NULL,
- `pais` VARCHAR(80) NULL,
- `coordenadas` VARCHAR(255) NULL,
- `metodo` VARCHAR(120) NULL,
+ `cantidad` TEXT NULL,
+ `precio` TEXT NULL,
+ `pais` TEXT NULL,
+ `coordenadas` TEXT NULL,
+ `metodo` TEXT NULL,
`first_seen_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
`last_seen_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
UNIQUE KEY `uniq_callcenter_test_orders_source_key` (`source_key`),
@@ -205,6 +205,48 @@ function cc_test_ensure_schema(PDO $pdo): void
error_log('cc_test_ensure_schema: ' . $exception->getMessage());
}
+ $textColumns = [
+ 'codigo' => 'AFTER `source_key`',
+ 'import_id' => 'AFTER `codigo`',
+ 'nombre' => 'AFTER `import_id`',
+ 'celular' => 'AFTER `observaciones_drive`',
+ 'cantidad' => 'AFTER `producto`',
+ 'precio' => 'AFTER `cantidad`',
+ 'pais' => 'AFTER `precio`',
+ 'coordenadas' => 'AFTER `pais`',
+ 'metodo' => 'AFTER `coordenadas`',
+ ];
+
+ foreach ($textColumns as $columnName => $afterClause) {
+ cc_test_ensure_column($pdo, 'callcenter_test_orders', $columnName, "TEXT NULL {$afterClause}");
+ }
+
+ try {
+ $colStmt = $pdo->prepare("
+ SELECT COLUMN_NAME, DATA_TYPE
+ FROM information_schema.COLUMNS
+ WHERE TABLE_SCHEMA = DATABASE()
+ AND TABLE_NAME = 'callcenter_test_orders'
+ AND COLUMN_NAME IN ('codigo', 'import_id', 'nombre', 'celular', 'cantidad', 'precio', 'pais', 'coordenadas', 'metodo')
+ ");
+ $colStmt->execute();
+
+ $dataTypes = [];
+ foreach ($colStmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
+ $columnName = strtolower((string) ($row['COLUMN_NAME'] ?? ''));
+ $dataTypes[$columnName] = strtolower((string) ($row['DATA_TYPE'] ?? ''));
+ }
+
+ foreach ($textColumns as $columnName => $afterClause) {
+ $dataType = $dataTypes[$columnName] ?? '';
+ if (!in_array($dataType, ['text', 'mediumtext', 'longtext'], true)) {
+ $pdo->exec("ALTER TABLE `callcenter_test_orders` MODIFY COLUMN `{$columnName}` TEXT NULL {$afterClause}");
+ }
+ }
+ } catch (Throwable $exception) {
+ error_log('cc_test_ensure_schema text columns: ' . $exception->getMessage());
+ }
+
$pdo->exec("CREATE TABLE IF NOT EXISTS `callcenter_test_tracking` (
`id` INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
`source_key` CHAR(40) NOT NULL,
diff --git a/includes/drive_test_orders.php b/includes/drive_test_orders.php
index ab7657a3..d0c593fb 100644
--- a/includes/drive_test_orders.php
+++ b/includes/drive_test_orders.php
@@ -29,8 +29,8 @@ function drive_test_available_stores(): array
'sheet_title' => 'TUANI PEDIDOS',
'spreadsheet_id' => '1QYKeBJIIqYm6yW6Ka-5gKdxhUHwXOAc0No7RjnimxTw',
'sheet_gid' => 1523126328,
- 'startRow' => 6804,
- 'enforce_db_start_row' => true,
+ 'startRow' => 5552,
+ 'enforce_db_start_row' => false,
'incremental_sync' => true,
],
// Bandeja compartida de carritos recuperables: misma estructura, pero desde la fila 2000.
@@ -354,6 +354,31 @@ function drive_test_fetch_tracking(PDO $pdo, array $sourceKeys): array
return $tracking;
}
+
+function drive_test_get_existing_source_keys_by_row(PDO $pdo, string $storeKey): array
+{
+ $storeKey = mb_strtolower(trim($storeKey));
+ if ($storeKey === '') {
+ return [];
+ }
+
+ drive_test_ensure_orders_table($pdo);
+
+ $stmt = $pdo->prepare('SELECT source_row, source_key FROM callcenter_test_orders WHERE store_key = ? AND source_row IS NOT NULL ORDER BY COALESCE(drive_imported_at, first_seen_at) DESC, id DESC');
+ $stmt->execute([$storeKey]);
+
+ $sourceKeysByRow = [];
+ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
+ $sourceRow = isset($row['source_row']) ? (int) $row['source_row'] : 0;
+ $sourceKey = trim((string) ($row['source_key'] ?? ''));
+ if ($sourceRow > 0 && $sourceKey !== '' && !isset($sourceKeysByRow[$sourceRow])) {
+ $sourceKeysByRow[$sourceRow] = $sourceKey;
+ }
+ }
+
+ return $sourceKeysByRow;
+}
+
function drive_test_merge_tracking(array $orders, array $tracking): array
{
$editableFields = ['direccion', 'referencia', 'agencia', 'sede_agencia', 'sede', 'ciudad', 'distrito', 'dni', 'numero_cuenta_sede_id', 'numero_cuenta_dni', 'observaciones', 'coordenadas', 'producto', 'cantidad', 'precio', 'monto_adelantado', 'confirmacion_producto', 'confirmacion_cantidad', 'confirmacion_precio', 'confirmacion_producto_extra', 'confirmacion_cantidad_extra', 'confirmacion_precio_extra'];
@@ -451,12 +476,12 @@ function drive_test_ensure_orders_table(PDO $pdo): void
`id` INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
`store_key` VARCHAR(50) NULL,
`source_key` CHAR(40) NOT NULL,
- `codigo` VARCHAR(80) DEFAULT NULL,
- `import_id` VARCHAR(120) DEFAULT NULL,
+ `codigo` TEXT NULL,
+ `import_id` TEXT NULL,
`source_row` INT NULL,
`is_agregado` TINYINT(1) NOT NULL DEFAULT 0,
`drive_imported_at` DATETIME NULL,
- `nombre` VARCHAR(255) DEFAULT NULL,
+ `nombre` TEXT NULL,
`direccion_drive` TEXT NULL,
`referencia_drive` TEXT NULL,
`sede_drive` TEXT NULL,
@@ -464,13 +489,13 @@ function drive_test_ensure_orders_table(PDO $pdo): void
`distrito_drive` TEXT NULL,
`dni_drive` LONGTEXT NULL,
`observaciones_drive` TEXT NULL,
- `celular` VARCHAR(40) DEFAULT NULL,
+ `celular` TEXT NULL,
`producto` TEXT NULL,
- `cantidad` VARCHAR(60) NULL,
- `precio` VARCHAR(60) NULL,
- `pais` VARCHAR(80) NULL,
- `coordenadas` VARCHAR(255) NULL,
- `metodo` VARCHAR(120) NULL,
+ `cantidad` TEXT NULL,
+ `precio` TEXT NULL,
+ `pais` TEXT NULL,
+ `coordenadas` TEXT NULL,
+ `metodo` TEXT NULL,
`first_seen_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
`last_seen_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
UNIQUE KEY `uniq_callcenter_test_orders_source_key` (`source_key`),
@@ -485,6 +510,22 @@ function drive_test_ensure_orders_table(PDO $pdo): void
// Asegura columna para pedidos cargados manualmente (Agregados)
cc_test_ensure_column($pdo, "callcenter_test_orders", "is_agregado", "TINYINT(1) NOT NULL DEFAULT 0");
+ $textColumns = [
+ 'codigo' => 'AFTER `source_key`',
+ 'import_id' => 'AFTER `codigo`',
+ 'nombre' => 'AFTER `import_id`',
+ 'celular' => 'AFTER `observaciones_drive`',
+ 'cantidad' => 'AFTER `producto`',
+ 'precio' => 'AFTER `cantidad`',
+ 'pais' => 'AFTER `precio`',
+ 'coordenadas' => 'AFTER `pais`',
+ 'metodo' => 'AFTER `coordenadas`',
+ ];
+
+ foreach ($textColumns as $columnName => $afterClause) {
+ cc_test_ensure_column($pdo, 'callcenter_test_orders', $columnName, "TEXT NULL {$afterClause}");
+ }
+
// Asegurar que los campos de ubicación y DNI soporten valores largos desde Google Sheets.
try {
$colStmt = $pdo->prepare("
@@ -517,6 +558,32 @@ function drive_test_ensure_orders_table(PDO $pdo): void
error_log('drive_test_ensure_orders_table: ' . $exception->getMessage());
}
+ try {
+ $colStmt = $pdo->prepare("
+ SELECT COLUMN_NAME, DATA_TYPE
+ FROM information_schema.COLUMNS
+ WHERE TABLE_SCHEMA = DATABASE()
+ AND TABLE_NAME = 'callcenter_test_orders'
+ AND COLUMN_NAME IN ('codigo', 'import_id', 'nombre', 'celular', 'cantidad', 'precio', 'pais', 'coordenadas', 'metodo')
+ ");
+ $colStmt->execute();
+
+ $dataTypes = [];
+ foreach ($colStmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
+ $columnName = strtolower((string) ($row['COLUMN_NAME'] ?? ''));
+ $dataTypes[$columnName] = strtolower((string) ($row['DATA_TYPE'] ?? ''));
+ }
+
+ foreach ($textColumns as $columnName => $afterClause) {
+ $dataType = $dataTypes[$columnName] ?? '';
+ if (!in_array($dataType, ['text', 'mediumtext', 'longtext'], true)) {
+ $pdo->exec("ALTER TABLE `callcenter_test_orders` MODIFY COLUMN `{$columnName}` TEXT NULL {$afterClause}");
+ }
+ }
+ } catch (Throwable $exception) {
+ error_log('drive_test_ensure_orders_table text columns: ' . $exception->getMessage());
+ }
+
$checked = true;
}
@@ -550,6 +617,8 @@ function drive_test_sync_orders_incremental(PDO $pdo, string $storeKey, int $ove
drive_test_ensure_orders_table($pdo);
drive_test_ensure_import_checkpoints_table($pdo);
+ $existingSourceKeysByRow = drive_test_get_existing_source_keys_by_row($pdo, $storeKey);
+
$stmtCheckpoint = $pdo->prepare('SELECT last_processed_row, baseline_start_row FROM drive_test_import_checkpoints WHERE store_key = ? LIMIT 1');
$stmtCheckpoint->execute([$storeKey]);
$checkpointData = $stmtCheckpoint->fetch(PDO::FETCH_ASSOC) ?: [];
@@ -647,6 +716,9 @@ function drive_test_sync_orders_incremental(PDO $pdo, string $storeKey, int $ove
foreach ($driveOrders as $order) {
$driveImportedAt = drive_test_parse_datetime_mysql($order['import_id'] ?? null);
$sourceRow = isset($order['source_row']) && (int) $order['source_row'] > 0 ? (int) $order['source_row'] : null;
+ if ($sourceRow !== null && isset($existingSourceKeysByRow[$sourceRow])) {
+ $order['source_key'] = $existingSourceKeysByRow[$sourceRow];
+ }
$stmtUpsert->execute([
':store_key' => $storeKey,
@@ -754,14 +826,16 @@ function drive_test_fetch_orders_from_db(PDO $pdo, string $storeKey, ?bool $only
$stmt->execute($params);
$orders = [];
- $minCodigoNumber = isset($storeConfig['min_codigo_number']) ? (int) ($storeConfig['min_codigo_number'] ?? 0) : 0;
+ $seenSourceRows = [];
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
$isAgregado = (int) ($row['is_agregado'] ?? 0);
$codigo = (string) ($row['codigo'] ?? '');
- $codigoNumber = drive_test_extract_codigo_number($codigo);
-
- if ($minCodigoNumber > 0 && $isAgregado !== 1 && ($codigoNumber === null || $codigoNumber < $minCodigoNumber)) {
- continue;
+ $sourceRow = isset($row['source_row']) && (int) $row['source_row'] > 0 ? (int) $row['source_row'] : null;
+ if ($sourceRow !== null) {
+ if (isset($seenSourceRows[$sourceRow])) {
+ continue;
+ }
+ $seenSourceRows[$sourceRow] = true;
}
$orders[] = [
@@ -770,7 +844,7 @@ function drive_test_fetch_orders_from_db(PDO $pdo, string $storeKey, ?bool $only
'source_key' => (string) ($row['source_key'] ?? ''),
'codigo' => $codigo,
'import_id' => (string) ($row['import_id'] ?? ''),
- 'source_row' => isset($row['source_row']) && (int) $row['source_row'] > 0 ? (int) $row['source_row'] : null,
+ 'source_row' => $sourceRow,
'drive_imported_at' => (string) ($row['drive_imported_at'] ?? ''),
'first_seen_at' => (string) ($row['first_seen_at'] ?? ''),
'nombre' => (string) ($row['nombre'] ?? ''),