getConnection(); // Genera un UUID univoco per importreferencecode $importReferenceCode = date('YmdHis') . '-' . uniqid(); // Recupera tutti i mapping dal template, includendo is_visible_import $stmt = $pdo->prepare("SELECT id, excel_column, data_type, is_required, manual_default, is_manual, field_label, field_id, main_field, is_visible_import, auto_value FROM template_mapping WHERE template_id = ?"); $stmt->execute([$template_id]); $allMappings = $stmt->fetchAll(PDO::FETCH_ASSOC); $timeLabels = [ 'Sample Arrival Time:', 'Sample Unlock Time:', 'Login Time:', 'Presa in carico, Orario:', ]; // Returns the auto value for current session (import) based on mapping.auto_value function getImportAutoValue(array $mapping): string { $auto = $mapping['auto_value'] ?? 'none'; if ($auto === 'import_date') { return date('Y-m-d'); } if ($auto === 'import_time') { // HTML expects HH:MM (seconds optional) return date('H:i'); } return ''; } if (empty($allMappings)) { header("Location: import_xls.php?id=$template_id&status=error&message=" . urlencode("Nessun mapping trovato per il template")); exit; } // Trova il campo main_field $mainFieldMapping = null; foreach ($allMappings as $mapping) { if ($mapping['main_field'] == 1 && $mapping['is_visible_import'] == 1) { $mainFieldMapping = $mapping; break; } } // Recupera l'idclient di default dal template (se presente) $template_stmt = $pdo->prepare("SELECT idclient FROM excel_templates WHERE id = ?"); $template_stmt->execute([$template_id]); $template = $template_stmt->fetch(PDO::FETCH_ASSOC); $default_idclient = $template['idclient'] ?? null; $insertedIds = $_POST['inserted_ids'] ?? $_SESSION['inserted_ids']; // ------------------------------------------------------------ // AUTO SET: schema field_id = 244 with auth_users.lims_user_id (if present) // ------------------------------------------------------------ try { // 1) Read logged user lims_user_id $stmtUser = $pdo->prepare("SELECT lims_user_id FROM auth_users WHERE id = ? LIMIT 1"); $stmtUser->execute([(int)$user_id]); $limsUserId = $stmtUser->fetchColumn(); // normalize $limsUserId = ($limsUserId !== false && $limsUserId !== null && $limsUserId !== '') ? (string)$limsUserId : ''; if ($limsUserId !== '' && !empty($insertedIds)) { // 2) Find mapping_id for field_id = 244 in this template $stmtMap = $pdo->prepare("SELECT id FROM template_mapping WHERE template_id = ? AND field_id = 244 LIMIT 1"); $stmtMap->execute([(int)$template_id]); $mappingId244 = (int)$stmtMap->fetchColumn(); if ($mappingId244 > 0) { // 3) Upsert value into import_data_details for every inserted datadb row $pdo->beginTransaction(); $updStmt = $pdo->prepare("UPDATE import_data_details SET field_value = ? WHERE id = ? AND mapping_id = ?"); $insStmt = $pdo->prepare("INSERT INTO import_data_details (id, mapping_id, field_value) VALUES (?, ?, ?)"); foreach ($insertedIds as $iddatadb) { $iddatadb = (int)$iddatadb; if ($iddatadb <= 0) continue; $updStmt->execute([$limsUserId, $iddatadb, $mappingId244]); if ($updStmt->rowCount() === 0) { $insStmt->execute([$iddatadb, $mappingId244, $limsUserId]); } } $pdo->commit(); } } } catch (Exception $e) { // Do not block import page if this fails; just log error_log("[AUTO FIELD 244] " . $e->getMessage()); if ($pdo->inTransaction()) $pdo->rollBack(); } // Recupera i dati appena inseriti con i nomi degli utenti $stmt = $pdo->prepare(" SELECT d.*, CONCAT(u.first_name, ' ', u.last_name) AS user_name FROM datadb d LEFT JOIN auth_users u ON d.user_id = u.id WHERE d.iddatadb IN (" . implode(',', array_fill(0, count($insertedIds), '?')) . ") "); $stmt->execute($insertedIds); $importedData = $stmt->fetchAll(PDO::FETCH_ASSOC); // Recupera i dettagli manuali da import_data_details $stmt = $pdo->prepare(" SELECT d.id AS detail_id, d.id AS datadb_id, d.mapping_id, d.field_value, m.field_id, m.field_label, m.data_type, m.is_required, m.manual_default FROM import_data_details d JOIN template_mapping m ON d.mapping_id = m.id WHERE d.id IN (" . implode(',', array_fill(0, count($insertedIds), '?')) . ") "); $stmt->execute($insertedIds); $manualDetails = $stmt->fetchAll(PDO::FETCH_ASSOC); // Recupera il mapping globale per mostrare gli slug leggibili $stmt = $pdo->query("SELECT mysql_column_name, user_friendly_slug FROM column_mapping"); $slugMapping = []; foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) { $slugMapping[$row['mysql_column_name']] = $row['user_friendly_slug']; } // --- FIX LABELS ONLY (do not change keys) --- $slugMapping['AnagraficaCertestObject'] = 'Object'; $slugMapping['AnagraficaCertestService'] = 'Service'; // ---------------- FIXED FIELDS (from template_fixed_mapping) ---------------- $fixedStmt = $pdo->prepare(" SELECT id, fixed_field_key, is_manual, data_type, is_required, default_value, is_visible_import FROM template_fixed_mapping WHERE template_id = ? AND is_visible_import = 1 ORDER BY id "); $fixedStmt->execute([$template_id]); $fixedFieldsRaw = $fixedStmt->fetchAll(PDO::FETCH_ASSOC); // Ordine desiderato: Cliente Responsabile prima, poi gli altri, ConsegnaRichiesta prima delle 3 speciali $desiredOrder = [ 'ClienteResponsabile', 'AnagraficaCertestObject', 'AnagraficaCertestService', 'MoltiplicatorePrezzo', 'ConsegnaRichiesta', // se ci sono altri campi fixed li mettiamo dopo ]; $fixedFields = []; $tempMap = []; foreach ($fixedFieldsRaw as $f) { $tempMap[$f['fixed_field_key']] = $f; } foreach ($desiredOrder as $key) { if (isset($tempMap[$key])) { $fixedFields[] = $tempMap[$key]; unset($tempMap[$key]); } } // Aggiunge eventuali campi fixed non elencati sopra (alla fine) foreach ($tempMap as $f) { $fixedFields[] = $f; } // Maps logical fixed_field_key → real datadb column name (mirrors JS fixedAliasMap) $fixedAliasMap = [ 'ClienteResponsabile' => 'cliente_responsabile_id', 'MoltiplicatorePrezzo' => 'moltiplicatore_prezzo_id', 'AnagraficaCertestObject' => 'anagrafica_certest_object_id', 'AnagraficaCertestService' => 'anagrafica_certest_service_id', 'ClienteFornitore' => 'cliente_fornitore_id', 'ConsegnaRichiesta' => 'consegna_richiesta', ]; // helper default (DATE can use 'today' if you already use it elsewhere) function fixedDefaultValue(array $f): string { $v = $f['default_value'] ?? ''; if ($f['data_type'] === 'DATE' && $v === 'today') return date('Y-m-d'); return (string)$v; } ?>