getConnection(); // 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; // Maps logical fixed_field_key → real datadb column name $fixedAliasMap = [ 'ClienteResponsabile' => 'cliente_responsabile_id', 'ClienteFornitore' => 'cliente_fornitore_id', 'ClienteAnalisi' => 'clienteAnalisi', 'MoltiplicatorePrezzo' => 'moltiplicatore_prezzo_id', 'AnagraficaCertestObject' => 'anagrafica_certest_object_id', 'AnagraficaCertestService' => 'anagrafica_certest_service_id', 'ConsegnaRichiesta' => 'consegna_richiesta', ]; // Fetch records with status='l' (exported to LIMS) for this template $userFilter = $show_all_users ? '' : 'AND d.user_id = ?'; $filters = $_GET['f'] ?? []; if (!is_array($filters)) $filters = []; // Map of filter keys → datadb columns (direct columns) $directColumnMap = [ 'commessaweb' => 'd.commessaweb', 'idclient' => 'd.idclient', 'importreferencecode' => 'd.importreferencecode', 'importdate' => 'd.importdate', 'filename_import' => 'd.filename_import', 'user_name' => "CONCAT(u.first_name, ' ', u.last_name)", ]; // Add fixed field columns foreach ($fixedAliasMap as $fixedKey => $dbCol) { $directColumnMap[$fixedKey] = 'd.' . $dbCol; } $filterSQL = ''; $filterParams = []; foreach ($filters as $key => $val) { $val = trim($val); if ($val === '') continue; if (isset($directColumnMap[$key])) { // Direct datadb column $filterSQL .= " AND {$directColumnMap[$key]} LIKE ?"; $filterParams[] = '%' . $val . '%'; } elseif (str_starts_with($key, 'detail_')) { // import_data_details field: detail_{mapping_id} $mappingId = (int)substr($key, 7); if ($mappingId > 0) { $filterSQL .= " AND EXISTS (SELECT 1 FROM import_data_details dd WHERE dd.id = d.iddatadb AND dd.mapping_id = ? AND dd.field_value LIKE ?)"; $filterParams[] = $mappingId; $filterParams[] = '%' . $val . '%'; } } } $baseWhere = "WHERE d.templateid = ? AND d.status = 'l' {$userFilter} {$filterSQL}"; $baseParams = [$template_id]; if (!$show_all_users) $baseParams[] = $user_id; $baseParams = array_merge($baseParams, $filterParams); // Check if any filter is active $hasActiveFilters = !empty(array_filter($filters, fn($v) => trim($v) !== '')); $countStmt = $pdo->prepare("SELECT COUNT(*) FROM datadb d LEFT JOIN auth_users u ON d.user_id = u.id {$baseWhere}"); $countStmt->execute($baseParams); $totalRows = (int)$countStmt->fetchColumn(); $totalPages = max(1, (int)ceil($totalRows / $perPage)); if ($page > $totalPages) $page = $totalPages; $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 {$baseWhere} ORDER BY d.iddatadb DESC LIMIT {$perPage} OFFSET " . (($page - 1) * $perPage) . " "); $stmt->execute($baseParams); $importedData = $stmt->fetchAll(PDO::FETCH_ASSOC); $insertedIds = array_column($importedData, 'iddatadb'); // Fetch custom field details $manualDetails = []; if (!empty($insertedIds)) { $placeholders = implode(',', array_fill(0, count($insertedIds), '?')); $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 ({$placeholders}) "); $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', 'ClienteFornitore', 'ClienteAnalisi', 'AnagraficaCertestObject', 'AnagraficaCertestService', 'MoltiplicatorePrezzo', 'ConsegnaRichiesta', // se ci sono altri campi fixed li mettiamo dopo ]; // No exclusions: fixed fields will be rendered together at the end $excludeFromFixed = []; $fixedFields = []; $tempMap = []; foreach ($fixedFieldsRaw as $f) { if (in_array($f['fixed_field_key'], $excludeFromFixed, true)) continue; $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; } // 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; } // ── Build lookup maps: id → label for fixed fields ── $fixedLookup = []; // e.g. $fixedLookup['MoltiplicatorePrezzo'][2] = 'Urgente (1.5x)' function loadCacheJson(string $path): ?array { if (file_exists($path) && (time() - filemtime($path) < 3600)) { return json_decode(file_get_contents($path), true); } return null; } // MoltiplicatorePrezzo $cached = loadCacheJson(__DIR__ . '/cache/moltiplicatori_prezzo.json'); if ($cached) { $items = $cached['value'] ?? $cached; foreach ($items as $item) { $id = $item['IdMoltiplicatorePrezzo'] ?? null; if ($id !== null) $fixedLookup['MoltiplicatorePrezzo'][$id] = $item['Descrizione'] ?? $item['Codice'] ?? $id; } } // AnagraficaCertestObject $cached = loadCacheJson(__DIR__ . '/cache/anagrafica_certest_object.json'); if ($cached) { $items = $cached['value'] ?? $cached; foreach ($items as $item) { $id = $item['IdAnagrafica'] ?? null; if ($id !== null) $fixedLookup['AnagraficaCertestObject'][$id] = $item['NomeAnagrafica'] ?? $item['Codice'] ?? $id; } } // AnagraficaCertestService $cached = loadCacheJson(__DIR__ . '/cache/anagrafica_certest_service.json'); if ($cached) { $items = $cached['value'] ?? $cached; foreach ($items as $item) { $id = $item['IdAnagrafica'] ?? null; if ($id !== null) $fixedLookup['AnagraficaCertestService'][$id] = $item['NomeAnagrafica'] ?? $item['Codice'] ?? $id; } } // ClienteResponsabile — per-client cache files $clienteIds = array_unique(array_filter(array_column($importedData, 'idclient'))); foreach ($clienteIds as $cid) { $cached = loadCacheJson(__DIR__ . '/cache/cliente_responsabili_' . (int)$cid . '.json'); if ($cached) { $items = $cached['Responsabili'] ?? []; foreach ($items as $item) { $id = $item['IdClienteResponsabile'] ?? null; if ($id !== null) $fixedLookup['ClienteResponsabile'][$id] = $item['Nominativo'] ?? $id; } } } // Helper: resolve fixed field id → label function resolveFixedValue(string $key, $val, array $fixedLookup): string { if ($val === '' || $val === null) return ''; if (isset($fixedLookup[$key][(int)$val])) return $fixedLookup[$key][(int)$val]; return (string)$val; } ?>