Files
trf_certest/public/userarea/process_import_pdf.php
T
2026-08-18 16:00:06 +02:00

257 lines
8.8 KiB
PHP

<?php
/*
* process_import_pdf.php
* ------------------------------------------------------------------
* Riceve N PDF (multipart, campo pdf_files[]) + template_id + importreferencecode.
* Per ogni PDF:
* 1. salva il file in public/userarea/imported_pdf/
* 2. estrae i valori dai riquadri (pdf_extract_lib.php)
* 3. inserisce UNA riga in datadb + i dettagli in import_data_details
* applicando la STESSA logica di import_insert_batch.php
* (tipi di dato, auto_value, campo 244 con lims_user_id)
*
* Tutti i PDF del gruppo condividono lo stesso importreferencecode.
*
* Ritorna JSON: { ok, results: [ {filename, ok, iddatadb, values{}, error} ] }
* ------------------------------------------------------------------
*/
ini_set('display_errors', 0);
error_reporting(E_ALL);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/pdf_import_debug.log');
include('include/headscript.php');
require_once __DIR__ . '/pdf_extract_lib.php';
header('Content-Type: application/json; charset=utf-8');
function respond(array $payload): void
{
echo json_encode($payload);
exit;
}
// ----- Validazione input -----
$template_id = isset($_POST['template_id']) ? (int)$_POST['template_id'] : 0;
$importReferenceCode = isset($_POST['importreferencecode']) ? (string)$_POST['importreferencecode'] : '';
if ($template_id <= 0) {
respond(['ok' => false, 'error' => 'template_id non valido']);
}
if ($importReferenceCode === '') {
respond(['ok' => false, 'error' => 'importreferencecode mancante']);
}
if (empty($_FILES['pdf_files']) || !is_array($_FILES['pdf_files']['name'])) {
respond(['ok' => false, 'error' => 'Nessun PDF ricevuto']);
}
$user_id = $iduserlogin ?? 1;
$db = DBHandlerSelect::getInstance();
$pdo = $db->getConnection();
// ----- Mapping del template -----
$stmt = $pdo->prepare("
SELECT id, pdf_regions, data_type, is_required, manual_default, is_manual,
field_label, field_id, main_field, auto_value
FROM template_mapping
WHERE template_id = ?
");
$stmt->execute([$template_id]);
$allMappings = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (empty($allMappings)) {
respond(['ok' => false, 'error' => 'Nessun mapping trovato per il template']);
}
// ----- idclient di default -----
$tplStmt = $pdo->prepare("SELECT idclient FROM excel_templates WHERE id = ?");
$tplStmt->execute([$template_id]);
$tpl = $tplStmt->fetch(PDO::FETCH_ASSOC);
$default_idclient = $tpl['idclient'] ?? null;
// ----- lims_user_id per il campo 244 (come nel batch XLS) -----
$stmtUser = $pdo->prepare("SELECT lims_user_id FROM auth_users WHERE id = ? LIMIT 1");
$stmtUser->execute([(int)$user_id]);
$limsUserId = $stmtUser->fetchColumn();
$limsUserId = ($limsUserId !== false && $limsUserId !== null && $limsUserId !== '') ? (string)$limsUserId : '';
$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();
// ----- Cartella di destinazione dei PDF importati -----
$importFolder = __DIR__ . DIRECTORY_SEPARATOR . 'pdftemplates' . DIRECTORY_SEPARATOR . 'imported';
if (!is_dir($importFolder)) {
@mkdir($importFolder, 0775, true);
}
/**
* Applica la conversione del valore in base al data_type,
* REPLICA della logica di import_insert_batch.php.
*/
function convertFieldValue(array $mapping, ?string $rawValue): string
{
$fieldValue = $rawValue;
if (!$mapping['is_manual']) {
// Valore estratto dal PDF; se vuoto, fallback al manual_default
if ($fieldValue === null || $fieldValue === '') {
$fieldValue = $mapping['manual_default'] ?? '';
}
switch ($mapping['data_type']) {
case 'INT':
$fieldValue = is_numeric($fieldValue) ? (int)$fieldValue : ($mapping['manual_default'] ?? 0);
break;
case 'DATE':
$fieldValue = !empty($fieldValue)
? date('Y-m-d', strtotime($fieldValue))
: ($mapping['manual_default'] === 'today' ? date('Y-m-d') : ($mapping['manual_default'] ?? ''));
break;
case 'CHAR':
$fieldValue = !empty($fieldValue) ? substr((string)$fieldValue, 0, 1) : ($mapping['manual_default'] ?? '');
break;
case 'Testo':
case 'VARCHAR':
default:
$fieldValue = !empty($fieldValue) ? (string)$fieldValue : ($mapping['manual_default'] ?? '');
break;
}
} else {
// Campo manuale: usa manual_default
$fieldValue = $mapping['manual_default'] ?? '';
if ($mapping['data_type'] === 'DATE' && $mapping['manual_default'] === 'today') {
$fieldValue = date('Y-m-d');
}
}
// auto_value se ancora vuoto (come nel batch XLS)
if (($fieldValue === null || $fieldValue === '') && !empty($mapping['auto_value']) && $mapping['auto_value'] !== 'none') {
if ($mapping['auto_value'] === 'import_date') {
$fieldValue = date('Y-m-d');
} elseif ($mapping['auto_value'] === 'import_time') {
$fieldValue = date('H:i');
}
}
return (string)($fieldValue ?? '');
}
$results = [];
$nFiles = count($_FILES['pdf_files']['name']);
for ($i = 0; $i < $nFiles; $i++) {
$origName = $_FILES['pdf_files']['name'][$i];
$tmpName = $_FILES['pdf_files']['tmp_name'][$i];
$err = $_FILES['pdf_files']['error'][$i];
$fileResult = [
'filename' => $origName,
'ok' => false,
'iddatadb' => null,
'values' => [],
'error' => '',
];
// Errore di upload
if ($err !== UPLOAD_ERR_OK) {
$fileResult['error'] = 'Errore upload (codice ' . $err . ')';
$results[] = $fileResult;
continue;
}
// Estensione PDF
if (strtolower(pathinfo($origName, PATHINFO_EXTENSION)) !== 'pdf') {
$fileResult['error'] = 'Non è un PDF';
$results[] = $fileResult;
continue;
}
// Nome sicuro e univoco
$safeBase = preg_replace('/[^A-Za-z0-9_\-]/', '_', pathinfo($origName, PATHINFO_FILENAME));
$safeBase = trim($safeBase, '_') ?: 'pdf';
$storedName = 'imp' . $template_id . '_' . $safeBase . '_' . date('YmdHis') . '_' . $i . '.pdf';
$storedPath = $importFolder . DIRECTORY_SEPARATOR . $storedName;
if (!move_uploaded_file($tmpName, $storedPath)) {
$fileResult['error'] = 'Impossibile salvare il file';
$results[] = $fileResult;
continue;
}
// ----- Estrazione dai riquadri -----
try {
$extracted = pdf_extract_values($storedPath, $allMappings); // [mapping_id => testo]
} catch (Throwable $e) {
$fileResult['error'] = 'Estrazione fallita: ' . $e->getMessage();
$results[] = $fileResult;
continue;
}
// ----- Inserimento in datadb + dettagli (una riga per PDF) -----
try {
$pdo->beginTransaction();
$insDatadb = $pdo->prepare("INSERT INTO datadb (templateid, importreferencecode, filename_import, status, user_id, limscode, importdate, excelrow, idclient) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
$insDetail = $pdo->prepare("INSERT INTO import_data_details (id, mapping_id, field_value) VALUES (?, ?, ?)");
// excelrow non ha senso per il PDF: usiamo 0 (o l'indice del file)
$insDatadb->execute([
$template_id,
$importReferenceCode,
$storedName,
'i',
$user_id,
null,
date('Y-m-d'),
0,
$default_idclient
]);
$iddatadb = $pdo->lastInsertId();
$fileResult['iddatadb'] = $iddatadb;
$shownValues = [];
foreach ($allMappings as $mapping) {
$rawValue = $extracted[(int)$mapping['id']] ?? null;
$fieldValue = convertFieldValue($mapping, $rawValue);
$insDetail->execute([$iddatadb, $mapping['id'], $fieldValue]);
// per il feedback UI mostra solo i campi con riquadro
if (!empty($mapping['pdf_regions'])) {
$shownValues[$mapping['field_label'] ?? ('#' . $mapping['id'])] = $fieldValue;
}
}
// Campo 244 (Accettatore) con lims_user_id
if ($limsUserId !== '' && $mappingId244 > 0) {
$insDetail->execute([$iddatadb, $mappingId244, $limsUserId]);
}
$pdo->commit();
$fileResult['ok'] = true;
$fileResult['values'] = $shownValues;
} catch (Throwable $e) {
if ($pdo->inTransaction()) {
$pdo->rollBack();
}
error_log('[PDF IMPORT] ' . $e->getMessage());
$fileResult['error'] = 'Inserimento DB fallito: ' . $e->getMessage();
}
$results[] = $fileResult;
}
respond([
'ok' => true,
'importreferencecode' => $importReferenceCode,
'template_id' => $template_id,
'results' => $results,
]);