transfer auto-detect header

This commit is contained in:
2026-03-31 13:41:31 +03:00
parent 4f0dbc7e91
commit d983659000
3 changed files with 151 additions and 61 deletions
-46
View File
@@ -58,11 +58,6 @@ try {
$stmt->execute([$template_id]);
$mappings = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Also fetch excel_column labels for auto-detect
$stmtLabels = $pdo->prepare("SELECT excel_column FROM template_mapping WHERE template_id = ? AND is_manual = 0 AND excel_column IS NOT NULL AND excel_column != ''");
$stmtLabels->execute([$template_id]);
$templateLabels = array_map('trim', array_map('mb_strtolower', $stmtLabels->fetchAll(PDO::FETCH_COLUMN)));
// Debug dei mapping
error_log("Mappings found for template_id $template_id: " . print_r($mappings, true));
@@ -76,47 +71,6 @@ try {
$highestColumn = $worksheet->getHighestColumn();
$highestColumnIndex = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($highestColumn);
// ── Auto-detect header row and start column ──
// Scan all rows/columns to find the best match against template excel_column labels
if (!empty($templateLabels)) {
$bestRow = max(1, $header_row);
$bestCol = max(1, $start_column);
$bestScore = 0;
$scanLimit = min($highestRow, 50);
for ($scanRow = 1; $scanRow <= $scanLimit; $scanRow++) {
$score = 0;
for ($col = 1; $col <= $highestColumnIndex; $col++) {
$colLetter = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex($col);
$cellVal = $worksheet->getCell($colLetter . $scanRow)->getCalculatedValue();
$cellVal = mb_strtolower(trim((string)$cellVal));
if ($cellVal !== '' && in_array($cellVal, $templateLabels, true)) {
$score++;
}
}
if ($score > $bestScore) {
$bestScore = $score;
$bestRow = $scanRow;
}
}
$header_row = $bestRow;
// Determine start_column: first non-empty cell in the detected header row
for ($col = 1; $col <= $highestColumnIndex; $col++) {
$colLetter = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex($col);
$cellVal = $worksheet->getCell($colLetter . $header_row)->getCalculatedValue();
if (trim((string)$cellVal) !== '') {
$start_column = $col;
break;
}
}
error_log("Auto-detected header row: $header_row, start column: $start_column (score: $bestScore/" . count($templateLabels) . ")");
$response['auto_header_row'] = $header_row;
$response['auto_header_score'] = $bestScore;
$response['auto_header_total'] = count($templateLabels);
}
$startRow = max(1, $header_row);
$startColumn = max(1, $start_column);