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; } ?> Edit Imported Data - <?= htmlspecialchars($titlewebsite, ENT_QUOTES, 'UTF-8'); ?>
Imported (i) To LIMS (l) ( of records)
Rows per page
$lim])); ?>
1): ?>
of 1): ?> 1 2): ?>... ...
Exported to LIMS Clear filters
"; echo ""; echo ""; echo ""; } elseif ($mainFieldMapping['data_type'] === 'Data') { echo ""; echo ""; } elseif ($mainFieldMapping['data_type'] === 'INT') { echo ""; echo ""; } else { echo ""; echo ""; } ?>
"; echo ""; echo ""; echo "
"; } else { // Show auto import date/time in header too (read-only) $autoVal = getImportAutoValue($mapping); echo "
"; if (($mapping['auto_value'] ?? 'none') === 'import_date') { echo ""; echo ""; } elseif (($mapping['auto_value'] ?? 'none') === 'import_time') { echo ""; echo ""; } else { // keep empty cell for other auto fields echo ""; } echo "
"; } $autoIndex++; $topColIndex++; } } $manualIndex = 0; foreach ($allMappings as $mapping) { if ($mapping['is_manual'] && $mapping['main_field'] != 1 && $mapping['is_visible_import'] == 1) { $fieldValue = $mapping['manual_default'] ?? ''; if ($mapping['data_type'] === 'Data' && $mapping['manual_default'] === 'today') { $fieldValue = date('Y-m-d'); } $inputClass = 'manual-input'; if ($mapping['is_required']) $inputClass .= ' required-input'; echo "
"; if ($mapping['data_type'] === 'SceltaMultipla') { echo ""; } elseif ($mapping['data_type'] === 'Data') { echo ""; } elseif ($mapping['data_type'] === 'INT') { echo ""; } elseif (in_array($mapping['field_label'], $timeLabels)) { echo ""; } else { echo ""; } echo ""; echo "
"; $manualIndex++; $topColIndex++; } } echo "
"; $topColIndex++; echo "
"; $topColIndex++; echo "
"; $topColIndex++; // ---------------- FIXED FIELDS TOP (propagate) - same order as header: fixed cols, 3 empties after ConsegnaRichiesta ---------------- if (!empty($fixedFields)) { $insertedAfterConsegnaTop = false; foreach ($fixedFields as $fx => $f) { $key = $f['fixed_field_key']; // datadb column $val = fixedDefaultValue($f); $isRequired = ((int)$f['is_required'] === 1); $inputClass = 'manual-input' . ($isRequired ? ' required-input' : ''); $topRequiredClass = ($isRequired && ($val === '' || $val === null)) ? 'missing-required' : ''; echo "
"; $topColIndex++; // Forza DATE anche se per errore nel DB è diversa $isDate = ($f['data_type'] === 'DATE' || $key === 'ConsegnaRichiesta'); if ($isDate) { echo ""; } else { $isApiField = in_array($key, [ 'MoltiplicatorePrezzo', 'ClienteResponsabile', 'ClienteFornitore', 'ClienteAnalisi', 'AnagraficaCertestObject', 'AnagraficaCertestService' ], true); if ($isApiField) { $placeholder = ($key === 'ClienteResponsabile') ? 'Seleziona cliente prima...' : 'Seleziona...'; echo ""; } else { echo ""; } } // UNA SOLA freccia echo ""; echo "
"; if ($key === 'ConsegnaRichiesta' && !$insertedAfterConsegnaTop) { echo "
"; $topColIndex++; echo "
"; $topColIndex++; echo "
"; $topColIndex++; $insertedAfterConsegnaTop = true; } } } ?>
View
Status
Client
" . htmlspecialchars($mapping['field_label']) . "
"; $headerIndex++; } } foreach ($allMappings as $mapping) { if ($mapping['is_manual'] && $mapping['main_field'] != 1 && $mapping['is_visible_import'] == 1) { echo "
" . htmlspecialchars($mapping['field_label']) . "
"; $headerIndex++; } } // Aggiunta header per Tested Component echo "
Tested Component
"; $headerIndex++; echo "
AWB Number
"; $headerIndex++; echo "
Tracking Info
"; $headerIndex++; // ---------------- FIXED FIELDS HEADERS ---------------- if (!empty($fixedFields)) { $insertedAfterConsegna = false; foreach ($fixedFields as $f) { $key = $f['fixed_field_key']; $label = $slugMapping[$key] ?? $key; echo "
" . htmlspecialchars($label) . "
"; $headerIndex++; // Inseriamo le 3 colonne SOLO dopo ConsegnaRichiesta if ($key === 'ConsegnaRichiesta' && !$insertedAfterConsegna) { echo "
Import Reference Code
"; $headerIndex++; echo "
" . ($slugMapping['filename_import'] ?? 'filename_import') . "
"; $headerIndex++; echo "
" . ($slugMapping['importdate'] ?? 'importdate') . "
"; $headerIndex++; $insertedAfterConsegna = true; } } } ?>
×" : ''; return "
{$inner}{$btn}
"; } // Helper: render a select filter from a lookup array function renderFilterSelect(string $name, array $options, string $currentVal, string $style = ''): string { $html = ""; return wrapFilter($html, $currentVal !== ''); } // Helper: render a text filter function renderFilterInput(string $name, string $currentVal): string { $inner = ""; return wrapFilter($inner, $currentVal !== ''); } // Helper: render a select filter populated by JS function renderFilterSelectJS(string $name, string $currentVal, string $jsClass, string $dataAttr = ''): string { $html = ""; return wrapFilter($html, $currentVal !== ''); } // Fields that are client-id lookups $clientFilterKeys = ['ClienteFornitore', 'ClienteAnalisi']; ?>
"; if ($mapping['data_type'] === 'SceltaMultipla') { echo renderFilterSelectJS("f[$fKey]", $fVal, 'scelta-filter', "data-field-id='{$mapping['field_id']}'"); } else { echo renderFilterInput("f[$fKey]", $fVal); } echo "
"; } } // Manual fields foreach ($allMappings as $mapping) { if ($mapping['is_manual'] && $mapping['main_field'] != 1 && $mapping['is_visible_import'] == 1) { $fKey = 'detail_' . $mapping['id']; $fVal = $filters[$fKey] ?? ''; echo "
"; if ($mapping['data_type'] === 'SceltaMultipla') { echo renderFilterSelectJS("f[$fKey]", $fVal, 'scelta-filter', "data-field-id='{$mapping['field_id']}'"); } else { echo renderFilterInput("f[$fKey]", $fVal); } echo "
"; } } // Tested Component, AWB, Tracking echo "
"; echo "
"; echo "
"; // Fixed fields if (!empty($fixedFields)) { $insertedFilterAfterConsegna = false; foreach ($fixedFields as $f) { $key = $f['fixed_field_key']; $fVal = $filters[$key] ?? ''; echo "
"; if (in_array($key, $clientFilterKeys, true)) { // Client-based selects (populated by JS) echo renderFilterSelectJS("f[$key]", $fVal, 'client-filter'); } elseif (isset($fixedLookup[$key]) && !empty($fixedLookup[$key])) { // PHP-cached lookups echo renderFilterSelect("f[$key]", $fixedLookup[$key], $fVal); } elseif ($key === 'ConsegnaRichiesta') { echo renderFilterInput("f[$key]", $fVal); } else { echo renderFilterInput("f[$key]", $fVal); } echo "
"; if ($key === 'ConsegnaRichiesta' && !$insertedFilterAfterConsegna) { echo "
" . renderFilterInput('f[importreferencecode]', $filters['importreferencecode'] ?? '') . "
"; echo "
" . renderFilterInput('f[filename_import]', $filters['filename_import'] ?? '') . "
"; echo "
" . renderFilterInput('f[importdate]', $filters['importdate'] ?? '') . "
"; $insertedFilterAfterConsegna = true; } } } ?>
$row): ?>
$d['mapping_id'] == $mainFieldMapping['id'] && $d['datadb_id'] == $row['iddatadb']); $detail = reset($detail) ?: ['field_value' => $mainFieldMapping['manual_default']]; $fieldValue = $detail['field_value'] ?? $mainFieldMapping['manual_default'] ?? ''; $isScelta = ($mainFieldMapping['data_type'] === 'SceltaMultipla'); ?>
>
To LIMS
$d['datadb_id'] == $row['iddatadb']); $autoIndex = 0; foreach ($allMappings as $mapping) { if (!$mapping['is_manual'] && $mapping['main_field'] != 1 && $mapping['is_visible_import'] == 1) { $detail = array_filter($rowDetails, fn($d) => $d['mapping_id'] == $mapping['id']); $detail = reset($detail) ?: ['field_value' => $mapping['manual_default']]; $fieldValue = $detail['field_value'] ?? $mapping['manual_default'] ?? ''; $isScelta = ($mapping['data_type'] === 'SceltaMultipla'); echo "
"; echo $isScelta ? "" . htmlspecialchars($fieldValue) . "" : "" . htmlspecialchars($fieldValue) . ""; echo "
"; $cellIndex++; $autoIndex++; } } foreach ($allMappings as $mapping) { if ($mapping['is_manual'] && $mapping['main_field'] != 1 && $mapping['is_visible_import'] == 1) { $detail = array_filter($rowDetails, fn($d) => $d['mapping_id'] == $mapping['id']); $detail = reset($detail) ?: ['field_value' => $mapping['manual_default']]; $fieldValue = $detail['field_value'] ?? $mapping['manual_default'] ?? ''; $isScelta = ($mapping['data_type'] === 'SceltaMultipla'); echo "
"; echo $isScelta ? "" . htmlspecialchars($fieldValue) . "" : "" . htmlspecialchars($fieldValue) . ""; echo "
"; $cellIndex++; } } // Tested Component (empty for view) echo "
"; $cellIndex++; ?>
"; if ($isClientField && $val !== '' && $val !== null) { echo "" . htmlspecialchars((string)$val) . ""; } else { echo "" . htmlspecialchars($displayVal) . ""; } echo "
"; $cellIndex++; if ($key === 'ConsegnaRichiesta') { echo "
" . htmlspecialchars($row['importreferencecode'] ?? '') . "
"; $cellIndex++; echo ""; $cellIndex++; echo "
" . htmlspecialchars($row['importdate'] ?? '') . "
"; $cellIndex++; } } } ?>