Compare commits
21 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 4dd7b89c22 | |||
| dec42b4442 | |||
| dab8d9aebf | |||
| 375a10a678 | |||
| 15990be884 | |||
| c3a6dd73b6 | |||
| 44ed1186e0 | |||
| 9050cb1006 | |||
| e6820fdb62 | |||
| 5da37a7836 | |||
| c5f27cb69a | |||
| 1d81d6c996 | |||
| 0c72dbf5ae | |||
| 8455be04e1 | |||
| e42d1b9c51 | |||
| 3e69e3c322 | |||
| 0eb4f7a2ad | |||
| 4f2cfc1930 | |||
| df075dd76a | |||
| 6460454201 | |||
| 67bbd9bbbb |
@@ -47,6 +47,7 @@ yarn-error.log
|
|||||||
/public/userarea/class/curl_auth_debug.log
|
/public/userarea/class/curl_auth_debug.log
|
||||||
/public/userarea/class/curl_request_debug.log
|
/public/userarea/class/curl_request_debug.log
|
||||||
/public/userarea/schema_dettagli_response.json
|
/public/userarea/schema_dettagli_response.json
|
||||||
|
public/userarea/schemi_base_response.json
|
||||||
|
|
||||||
# File XLSX temporanei importati
|
# File XLSX temporanei importati
|
||||||
/public/userarea/imported_trf/*.xlsx
|
/public/userarea/imported_trf/*.xlsx
|
||||||
|
|||||||
@@ -431,7 +431,7 @@
|
|||||||
const emptyEl = modal.querySelector("#analysisEmptyBox");
|
const emptyEl = modal.querySelector("#analysisEmptyBox");
|
||||||
const errorEl = modal.querySelector("#analysisErrorBox");
|
const errorEl = modal.querySelector("#analysisErrorBox");
|
||||||
|
|
||||||
const webOnly = webOnlyEl ? webOnlyEl.checked : false;
|
const webOnly = true;
|
||||||
const searchValue = searchEl ? searchEl.value.trim().toLowerCase() : "";
|
const searchValue = searchEl ? searchEl.value.trim().toLowerCase() : "";
|
||||||
|
|
||||||
let visibleCount = 0;
|
let visibleCount = 0;
|
||||||
@@ -496,8 +496,10 @@
|
|||||||
emptyEl.classList.add("d-none");
|
emptyEl.classList.add("d-none");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (analysisLoadedCache[String(matrixId)]) {
|
const cacheKey = String(matrixId) + "_WEB_ONLY";
|
||||||
renderAnalysesList(analysisLoadedCache[String(matrixId)]);
|
|
||||||
|
if (analysisLoadedCache[cacheKey]) {
|
||||||
|
renderAnalysesList(analysisLoadedCache[cacheKey]);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -509,13 +511,21 @@
|
|||||||
dataType: "json",
|
dataType: "json",
|
||||||
data: {
|
data: {
|
||||||
id_matrice: matrixId,
|
id_matrice: matrixId,
|
||||||
|
web_only: 1,
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
.done(function (response) {
|
.done(function (response) {
|
||||||
const analyses = Array.isArray(response.value)
|
const analyses = Array.isArray(response.value)
|
||||||
? response.value
|
? response.value.filter(function (item) {
|
||||||
|
return (
|
||||||
|
item.SelezionabileSuWeb === true ||
|
||||||
|
item.SelezionabileSuWeb === 1 ||
|
||||||
|
item.SelezionabileSuWeb === "1"
|
||||||
|
);
|
||||||
|
})
|
||||||
: [];
|
: [];
|
||||||
analysisLoadedCache[String(matrixId)] = analyses;
|
|
||||||
|
analysisLoadedCache[cacheKey] = analyses;
|
||||||
renderAnalysesList(analyses);
|
renderAnalysesList(analyses);
|
||||||
})
|
})
|
||||||
.fail(function (xhr) {
|
.fail(function (xhr) {
|
||||||
@@ -674,12 +684,7 @@
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const webOnlyEl = modal.querySelector("#analysisWebOnly");
|
// WEB only is now fixed by default
|
||||||
if (webOnlyEl) {
|
|
||||||
webOnlyEl.addEventListener("change", function () {
|
|
||||||
filterAnalysisList();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const searchEl = modal.querySelector("#analysisSearchInput");
|
const searchEl = modal.querySelector("#analysisSearchInput");
|
||||||
if (searchEl) {
|
if (searchEl) {
|
||||||
|
|||||||
@@ -59,6 +59,49 @@ function formatDateToExport($value)
|
|||||||
return null; // Imposta null se non è una data valida
|
return null; // Imposta null se non è una data valida
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ImportaCommessa con retry: la chiamata è asincrona lato LIMS e a volte
|
||||||
|
// risponde 200 senza importare (StatoCommessaWeb resta "Inviata"/"Nuova").
|
||||||
|
// Riprova con backoff esponenziale finché non passa a "Elaborata".
|
||||||
|
function importaCommessaWithRetry($api, $commessaId, array $payload, $maxRetries = 3, $initialBackoff = 1)
|
||||||
|
{
|
||||||
|
$result = null;
|
||||||
|
$stato = null;
|
||||||
|
$succeeded = false;
|
||||||
|
$log = "";
|
||||||
|
$backoff = $initialBackoff;
|
||||||
|
|
||||||
|
set_time_limit(120); // i backoff non devono far scadere il timeout della richiesta
|
||||||
|
|
||||||
|
for ($attempt = 1; $attempt <= $maxRetries + 1; $attempt++) {
|
||||||
|
try {
|
||||||
|
$result = $api->post("CommessaWeb({$commessaId})/ImportaCommessa", $payload);
|
||||||
|
$stato = $result['StatoCommessaWeb'] ?? null;
|
||||||
|
$log .= "Attempt {$attempt}: HTTP 200, StatoCommessaWeb=" . ($stato ?? 'null') . "\n";
|
||||||
|
} catch (Exception $e) {
|
||||||
|
$stato = null;
|
||||||
|
$log .= "Attempt {$attempt}: EXCEPTION " . $e->getMessage() . "\n";
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($stato === 'Elaborata') {
|
||||||
|
$succeeded = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($attempt <= $maxRetries) {
|
||||||
|
$log .= " -> not Elaborata, waiting {$backoff}s before retry\n";
|
||||||
|
sleep($backoff);
|
||||||
|
$backoff *= 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return [
|
||||||
|
'succeeded' => $succeeded,
|
||||||
|
'stato' => $stato,
|
||||||
|
'result' => $result,
|
||||||
|
'log' => $log,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
$iddatadb = $_POST['iddatadb'] ?? null;
|
$iddatadb = $_POST['iddatadb'] ?? null;
|
||||||
if (!$iddatadb) {
|
if (!$iddatadb) {
|
||||||
@@ -434,6 +477,71 @@ try {
|
|||||||
$logFilePhotos = $logDir . "commessa_{$commessaId}_photos_step5_2_" . time() . ".txt";
|
$logFilePhotos = $logDir . "commessa_{$commessaId}_photos_step5_2_" . time() . ".txt";
|
||||||
$writeLog($logFilePhotos, $logContentPhotos, "STEP 6.2 - Photos (commessa={$commessaId})");
|
$writeLog($logFilePhotos, $logContentPhotos, "STEP 6.2 - Photos (commessa={$commessaId})");
|
||||||
|
|
||||||
|
// 🔹 STEP 6.3: Add Analyses (AnalisiCampione) via Campione({id})/AddAnalisi bound action
|
||||||
|
$stmt = $pdo->prepare("
|
||||||
|
SELECT part_id, analysis_recordkey, analysis_name, analysis_method
|
||||||
|
FROM identification_parts_analyses
|
||||||
|
WHERE iddatadb = :iddatadb
|
||||||
|
ORDER BY part_id, id
|
||||||
|
");
|
||||||
|
$stmt->execute(['iddatadb' => $iddatadb]);
|
||||||
|
$analysesRows = $stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||||
|
|
||||||
|
$partIdToIndex = [];
|
||||||
|
foreach ($parts as $idx => $part) {
|
||||||
|
$partIdToIndex[(int)$part['part_id']] = $idx;
|
||||||
|
}
|
||||||
|
|
||||||
|
$totalAnalyses = count($analysesRows);
|
||||||
|
$addedAnalyses = 0;
|
||||||
|
$failedAnalyses = [];
|
||||||
|
$logContentStep63Analisi = "Analyses for iddatadb={$iddatadb}: total={$totalAnalyses}\n\n";
|
||||||
|
|
||||||
|
foreach ($analysesRows as $a) {
|
||||||
|
$partId = (int)$a['part_id'];
|
||||||
|
$recordKey = trim((string)($a['analysis_recordkey'] ?? ''));
|
||||||
|
$idx = $partIdToIndex[$partId] ?? null;
|
||||||
|
|
||||||
|
if ($idx === null || !isset($campioni[$idx]) || $recordKey === '') {
|
||||||
|
$logContentStep63Analisi .= "SKIP (no campione for part_id={$partId} / empty recordkey): '{$recordKey}'\n";
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$campioneId = (int)($campioni[$idx]['IdCampione'] ?? 0);
|
||||||
|
if ($campioneId <= 0) {
|
||||||
|
$logContentStep63Analisi .= "SKIP (invalid IdCampione for part_id={$partId}): '{$recordKey}'\n";
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$payload = ['RecordKey' => $recordKey];
|
||||||
|
$jsonPayload = json_encode($payload, JSON_UNESCAPED_SLASHES);
|
||||||
|
|
||||||
|
$logContentStep63Analisi .= "curl --location --request POST '{$apiBaseUrl}Campione({$campioneId})/AddAnalisi' \\\n" .
|
||||||
|
"--header 'Content-Type: application/json' \\\n" .
|
||||||
|
"--header 'Authorization: Bearer ••••••' \\\n" .
|
||||||
|
"--data '{$jsonPayload}'\n";
|
||||||
|
|
||||||
|
try {
|
||||||
|
$result = $api->post("Campione({$campioneId})/AddAnalisi", $payload);
|
||||||
|
$logContentStep63Analisi .= "OK (part_id={$partId}, campione={$campioneId}): " .
|
||||||
|
($a['analysis_name'] ?? '') . "\n---\n";
|
||||||
|
$addedAnalyses++;
|
||||||
|
} catch (Exception $e) {
|
||||||
|
$errMsg = $e->getMessage();
|
||||||
|
$logContentStep63Analisi .= "FAIL: {$errMsg}\n---\n";
|
||||||
|
$failedAnalyses[] = [
|
||||||
|
'part_id' => $partId,
|
||||||
|
'campione_id' => $campioneId,
|
||||||
|
'analysis_recordkey' => $recordKey,
|
||||||
|
'analysis_name' => $a['analysis_name'] ?? '',
|
||||||
|
'error' => $errMsg,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$logFileStep63Analisi = $logDir . "commessa_{$commessaId}_analyses_step63_" . time() . ".txt";
|
||||||
|
$writeLog($logFileStep63Analisi, $logContentStep63Analisi, "STEP 6.3 - AddAnalisi (commessa={$commessaId})");
|
||||||
|
|
||||||
// 🔹 STEP 7: Update Custom Fields for CommessaWeb
|
// 🔹 STEP 7: Update Custom Fields for CommessaWeb
|
||||||
if (!empty($fieldValues)) {
|
if (!empty($fieldValues)) {
|
||||||
// GET con espansione per CustomField
|
// GET con espansione per CustomField
|
||||||
@@ -512,9 +620,8 @@ try {
|
|||||||
$writeLog($logFileStep9, $logContentStep9, "STEP 9 - InviaCommessa (commessa={$commessaId})");
|
$writeLog($logFileStep9, $logContentStep9, "STEP 9 - InviaCommessa (commessa={$commessaId})");
|
||||||
|
|
||||||
|
|
||||||
// 🔹 STEP 9.5: Importazione da CommessaWeb a Commessa (commentato come richiesto)
|
// 🔹 STEP 9.5: Importazione da CommessaWeb a Commessa (con retry)
|
||||||
// Supplier call: POST api/odata/CommessaWeb(XXX)/ImportaCommessa
|
// Supplier call: POST api/odata/CommessaWeb(XXX)/ImportaCommessa
|
||||||
|
|
||||||
$importUserId = (!empty($lims_global_user_id) && is_numeric($lims_global_user_id))
|
$importUserId = (!empty($lims_global_user_id) && is_numeric($lims_global_user_id))
|
||||||
? (int) $lims_global_user_id
|
? (int) $lims_global_user_id
|
||||||
: 285;
|
: 285;
|
||||||
@@ -522,17 +629,23 @@ try {
|
|||||||
$importPayload = [
|
$importPayload = [
|
||||||
"IdUtente" => $importUserId
|
"IdUtente" => $importUserId
|
||||||
];
|
];
|
||||||
$importResult = $api->post("CommessaWeb({$commessaId})/ImportaCommessa", $importPayload);
|
|
||||||
|
|
||||||
$importPayloadLog = json_encode($importPayload, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
|
$importPayloadLog = json_encode($importPayload, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
|
||||||
// Logga il POST
|
|
||||||
|
$importOutcome = importaCommessaWithRetry($api, $commessaId, $importPayload);
|
||||||
|
$importResult = $importOutcome['result'];
|
||||||
|
$importStato = $importOutcome['stato'];
|
||||||
|
$importSucceeded = $importOutcome['succeeded'];
|
||||||
|
|
||||||
|
// Logga il POST (tutti i tentativi)
|
||||||
$logContentStep91 = "curl --location --request POST '{$apiBaseUrl}CommessaWeb({$commessaId})/ImportaCommessa' \\\n" .
|
$logContentStep91 = "curl --location --request POST '{$apiBaseUrl}CommessaWeb({$commessaId})/ImportaCommessa' \\\n" .
|
||||||
"--header 'Content-Type: application/json' \\\n" .
|
"--header 'Content-Type: application/json' \\\n" .
|
||||||
"--header 'Authorization: Bearer ••••••' \\\n" .
|
"--header 'Authorization: Bearer ••••••' \\\n" .
|
||||||
"--data '{$importPayloadLog}'\n\n" .
|
"--data '{$importPayloadLog}'\n\n" .
|
||||||
"RESPONSE:\n" . json_encode($importResult, JSON_PRETTY_PRINT);
|
"ATTEMPTS:\n" . $importOutcome['log'] . "\n" .
|
||||||
|
"SUCCEEDED: " . ($importSucceeded ? 'yes' : 'NO') . "\n\n" .
|
||||||
|
"LAST RESPONSE:\n" . json_encode($importResult, JSON_PRETTY_PRINT);
|
||||||
$logFileStep91 = $logDir . "commessa_{$commessaId}_importa_step91_" . time() . ".txt";
|
$logFileStep91 = $logDir . "commessa_{$commessaId}_importa_step91_" . time() . ".txt";
|
||||||
$writeLog($logFileStep91, $logContentStep91, "STEP 9.5 - ImportaCommessa (commessa={$commessaId})");
|
$writeLog($logFileStep91, $logContentStep91, "STEP 9.5 - ImportaCommessa (commessa={$commessaId}, succeeded=" . ($importSucceeded ? '1' : '0') . ")");
|
||||||
|
|
||||||
// 🔹 STEP 10: GET di controllo post-PATCH
|
// 🔹 STEP 10: GET di controllo post-PATCH
|
||||||
$expand = "CommesseCustomFields(\$expand=CustomField)";
|
$expand = "CommesseCustomFields(\$expand=CustomField)";
|
||||||
@@ -581,11 +694,15 @@ try {
|
|||||||
"totalCampioni" => count($campioni),
|
"totalCampioni" => count($campioni),
|
||||||
"totalCustomFields" => count($commessaAfterPatch["CommesseCustomFields"] ?? []),
|
"totalCustomFields" => count($commessaAfterPatch["CommesseCustomFields"] ?? []),
|
||||||
"totalPhotos" => count($photos),
|
"totalPhotos" => count($photos),
|
||||||
|
"totalAnalyses" => $totalAnalyses,
|
||||||
|
"addedAnalyses" => $addedAnalyses,
|
||||||
|
"failedAnalyses" => $failedAnalyses,
|
||||||
"message" => "Export successful",
|
"message" => "Export successful",
|
||||||
"logFiles" => [
|
"logFiles" => [
|
||||||
"step5_create" => $logFileStep5,
|
"step5_create" => $logFileStep5,
|
||||||
"step5_2_photos" => $logFilePhotos,
|
"step5_2_photos" => $logFilePhotos,
|
||||||
"step6_campioni" => $logFileStep6,
|
"step6_campioni" => $logFileStep6,
|
||||||
|
"step63_analyses" => $logFileStep63Analisi,
|
||||||
"step7_patch" => $logFileStep7 ?? null,
|
"step7_patch" => $logFileStep7 ?? null,
|
||||||
"step9_1_importa" => $logFileStep91,
|
"step9_1_importa" => $logFileStep91,
|
||||||
"step10_get" => $logFileStep10
|
"step10_get" => $logFileStep10
|
||||||
@@ -601,6 +718,7 @@ try {
|
|||||||
"step5_create" => $logFileStep5 ?? null,
|
"step5_create" => $logFileStep5 ?? null,
|
||||||
"step5_2_photos" => $logFilePhotos ?? null,
|
"step5_2_photos" => $logFilePhotos ?? null,
|
||||||
"step6_campioni" => $logFileStep6 ?? null,
|
"step6_campioni" => $logFileStep6 ?? null,
|
||||||
|
"step63_analyses" => $logFileStep63Analisi ?? null,
|
||||||
"step7_patch" => $logFileStep7 ?? null,
|
"step7_patch" => $logFileStep7 ?? null,
|
||||||
"step9_1_importa" => $logFileStep91 ?? null,
|
"step9_1_importa" => $logFileStep91 ?? null,
|
||||||
"step10_get" => $logFileStep10 ?? null
|
"step10_get" => $logFileStep10 ?? null
|
||||||
|
|||||||
@@ -18,7 +18,15 @@ try {
|
|||||||
|
|
||||||
$api = VisualLimsApiClient::getInstance();
|
$api = VisualLimsApiClient::getInstance();
|
||||||
|
|
||||||
$filter = rawurlencode("Matrice/IdMatrice eq $idMatrice");
|
$webOnly = isset($_GET['web_only']) ? (int)$_GET['web_only'] : 1;
|
||||||
|
|
||||||
|
$filterString = "Matrice/IdMatrice eq $idMatrice";
|
||||||
|
|
||||||
|
if ($webOnly === 1) {
|
||||||
|
$filterString .= " and SelezionabileSuWeb eq true";
|
||||||
|
}
|
||||||
|
|
||||||
|
$filter = rawurlencode($filterString);
|
||||||
$endpoint = "Analisi?\$filter={$filter}";
|
$endpoint = "Analisi?\$filter={$filter}";
|
||||||
|
|
||||||
$base_url = 'https://93.43.5.102/limsapi/api/odata/';
|
$base_url = 'https://93.43.5.102/limsapi/api/odata/';
|
||||||
|
|||||||
+129
-12
@@ -36,6 +36,15 @@
|
|||||||
return d.innerHTML;
|
return d.innerHTML;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function escAttr(str) {
|
||||||
|
if (str === null || str === undefined) return "";
|
||||||
|
return String(str)
|
||||||
|
.replace(/&/g, "&")
|
||||||
|
.replace(/"/g, """)
|
||||||
|
.replace(/'/g, "'")
|
||||||
|
.replace(/</g, "<")
|
||||||
|
.replace(/>/g, ">");
|
||||||
|
}
|
||||||
function getDetailValue(rowIndex, mappingId) {
|
function getDetailValue(rowIndex, mappingId) {
|
||||||
return data[rowIndex].details[String(mappingId)] ?? "";
|
return data[rowIndex].details[String(mappingId)] ?? "";
|
||||||
}
|
}
|
||||||
@@ -125,12 +134,35 @@
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function sortSelect2ResultsByStart(data) {
|
||||||
|
const term = $(".select2-container--open .select2-search__field").val();
|
||||||
|
|
||||||
|
if (!term) {
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
const search = term.toLowerCase().trim();
|
||||||
|
|
||||||
|
return data.sort(function (a, b) {
|
||||||
|
const textA = (a.text || "").toLowerCase().trim();
|
||||||
|
const textB = (b.text || "").toLowerCase().trim();
|
||||||
|
|
||||||
|
const aStarts = textA.startsWith(search);
|
||||||
|
const bStarts = textB.startsWith(search);
|
||||||
|
|
||||||
|
if (aStarts && !bStarts) return -1;
|
||||||
|
if (!aStarts && bStarts) return 1;
|
||||||
|
|
||||||
|
return textA.localeCompare(textB, "it", { sensitivity: "base" });
|
||||||
|
});
|
||||||
|
}
|
||||||
// Select2 AJAX config for client selects
|
// Select2 AJAX config for client selects
|
||||||
const clientSelect2Config = {
|
const clientSelect2Config = {
|
||||||
placeholder: "Search client...",
|
placeholder: "Search client...",
|
||||||
allowClear: true,
|
allowClear: true,
|
||||||
width: "100%",
|
width: "100%",
|
||||||
minimumInputLength: 0,
|
minimumInputLength: 0,
|
||||||
|
sorter: sortSelect2ResultsByStart,
|
||||||
dropdownCssClass: "select2-dropdown-smaller",
|
dropdownCssClass: "select2-dropdown-smaller",
|
||||||
ajax: {
|
ajax: {
|
||||||
url: "search_clienti.php",
|
url: "search_clienti.php",
|
||||||
@@ -332,6 +364,7 @@
|
|||||||
allowClear: true,
|
allowClear: true,
|
||||||
width: "100%",
|
width: "100%",
|
||||||
minimumInputLength: 0,
|
minimumInputLength: 0,
|
||||||
|
sorter: sortSelect2ResultsByStart,
|
||||||
ajax: {
|
ajax: {
|
||||||
url: "search_customfield_values.php",
|
url: "search_customfield_values.php",
|
||||||
dataType: "json",
|
dataType: "json",
|
||||||
@@ -340,7 +373,7 @@
|
|||||||
return {
|
return {
|
||||||
field_id: fieldId,
|
field_id: fieldId,
|
||||||
q: params.term || "",
|
q: params.term || "",
|
||||||
limit: 10,
|
limit: 0, // 0 = no limit for custom field values
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
processResults: function (data) {
|
processResults: function (data) {
|
||||||
@@ -463,13 +496,13 @@
|
|||||||
const row = data[rowIndex];
|
const row = data[rowIndex];
|
||||||
|
|
||||||
switch (col.type) {
|
switch (col.type) {
|
||||||
case "main_field":
|
case "main_field": {
|
||||||
div.innerHTML = createInputHTML(
|
const val = getDetailValue(rowIndex, col.key);
|
||||||
col,
|
|
||||||
row.mainFieldValue || "",
|
div.innerHTML = createInputHTML(col, val || "", rowIndex);
|
||||||
rowIndex,
|
|
||||||
);
|
|
||||||
break;
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
case "status": {
|
case "status": {
|
||||||
const st = row.status || "i";
|
const st = row.status || "i";
|
||||||
@@ -519,7 +552,7 @@
|
|||||||
case "tested_component":
|
case "tested_component":
|
||||||
div.style.overflow = "visible";
|
div.style.overflow = "visible";
|
||||||
div.innerHTML = `<div style="display:flex; align-items:center; gap:4px; width:100%; height:100%;">
|
div.innerHTML = `<div style="display:flex; align-items:center; gap:4px; width:100%; height:100%;">
|
||||||
<input type="text" class="cell-input manual-input tested-component-input" value="${esc(row.tested_component || "")}" style="flex:1; min-width:0; height:28px;">
|
<input type="text" class="cell-input manual-input tested-component-input" value="${escAttr(row.tested_component || "")}" style="flex:1; min-width:0; height:28px;">
|
||||||
<button type="button" class="add-part-btn btn btn-sm btn-primary" data-row="${rowIndex}" data-iddatadb="${row.iddatadb}" style="display:inline-flex; align-items:center; justify-content:center; min-width:28px; width:28px; height:28px; padding:0; font-size:12px; flex-shrink:0; text-align:center;">
|
<button type="button" class="add-part-btn btn btn-sm btn-primary" data-row="${rowIndex}" data-iddatadb="${row.iddatadb}" style="display:inline-flex; align-items:center; justify-content:center; min-width:28px; width:28px; height:28px; padding:0; font-size:12px; flex-shrink:0; text-align:center;">
|
||||||
<i class="fas fa-plus" style="margin:0; padding:0;"></i>
|
<i class="fas fa-plus" style="margin:0; padding:0;"></i>
|
||||||
</button>
|
</button>
|
||||||
@@ -565,7 +598,7 @@
|
|||||||
const cls = col.isManual ? "manual-input" : "auto-input";
|
const cls = col.isManual ? "manual-input" : "auto-input";
|
||||||
const reqCls = col.isRequired ? " required-input" : "";
|
const reqCls = col.isRequired ? " required-input" : "";
|
||||||
const req = col.isRequired ? " required" : "";
|
const req = col.isRequired ? " required" : "";
|
||||||
const v = esc(value);
|
const v = escAttr(value);
|
||||||
|
|
||||||
if (col.dataType === "SceltaMultipla") {
|
if (col.dataType === "SceltaMultipla") {
|
||||||
const options = buildDropdownOptionsHTML(col.fieldId, value);
|
const options = buildDropdownOptionsHTML(col.fieldId, value);
|
||||||
@@ -590,7 +623,7 @@
|
|||||||
if (col.dataType === "DATE") {
|
if (col.dataType === "DATE") {
|
||||||
const reqCls = col.isRequired ? " required-input" : "";
|
const reqCls = col.isRequired ? " required-input" : "";
|
||||||
const req = col.isRequired ? " required" : "";
|
const req = col.isRequired ? " required" : "";
|
||||||
return `<input type="text" class="cell-input date-picker manual-input${reqCls} fixed-input" data-fixed-key="${col.key}" value="${esc(value)}"${req}>`;
|
return `<input type="text" class="cell-input date-picker manual-input${reqCls} fixed-input" data-fixed-key="${escAttr(col.key)}" value="${escAttr(value)}"${req}>`;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Client-sourced fields → AJAX Select2 (like idclient)
|
// Client-sourced fields → AJAX Select2 (like idclient)
|
||||||
@@ -603,7 +636,7 @@
|
|||||||
const label = clientNameCache[value] || value;
|
const label = clientNameCache[value] || value;
|
||||||
opts += `<option value="${esc(String(value))}" selected>${esc(String(label))}</option>`;
|
opts += `<option value="${esc(String(value))}" selected>${esc(String(label))}</option>`;
|
||||||
}
|
}
|
||||||
return `<select class="cell-input manual-input fixed-input searchable-client api-fixed-select${reqCls}" data-fixed-key="${col.key}" data-current-value="${esc(value)}"${req}>${opts}</select>`;
|
return `<select class="cell-input manual-input fixed-input searchable-client api-fixed-select${reqCls}" data-fixed-key="${escAttr(col.key)}" data-current-value="${escAttr(value)}"${req}>${opts}</select>`;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Select — build from cache
|
// Select — build from cache
|
||||||
@@ -621,7 +654,7 @@
|
|||||||
|
|
||||||
const reqCls = col.isRequired ? " required-input" : "";
|
const reqCls = col.isRequired ? " required-input" : "";
|
||||||
const req = col.isRequired ? " required" : "";
|
const req = col.isRequired ? " required" : "";
|
||||||
return `<select class="cell-input manual-input fixed-input ${selectClass}${reqCls}" data-fixed-key="${col.key}" data-current-value="${esc(value)}"${req}>${options}</select>`;
|
return `<select class="cell-input manual-input fixed-input ${selectClass}${reqCls}" data-fixed-key="${escAttr(col.key)}" data-current-value="${escAttr(value)}"${req}>${options}</select>`;
|
||||||
}
|
}
|
||||||
|
|
||||||
function buildDropdownOptionsHTML(fieldId, selectedValue) {
|
function buildDropdownOptionsHTML(fieldId, selectedValue) {
|
||||||
@@ -826,6 +859,75 @@
|
|||||||
flatpickr(this, { dateFormat: "Y-m-d", allowInput: true });
|
flatpickr(this, { dateFormat: "Y-m-d", allowInput: true });
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
function getInputTextWidth(input) {
|
||||||
|
const span = document.createElement("span");
|
||||||
|
const style = window.getComputedStyle(input);
|
||||||
|
|
||||||
|
span.style.position = "absolute";
|
||||||
|
span.style.visibility = "hidden";
|
||||||
|
span.style.whiteSpace = "pre";
|
||||||
|
span.style.font = style.font;
|
||||||
|
span.style.fontSize = style.fontSize;
|
||||||
|
span.style.fontFamily = style.fontFamily;
|
||||||
|
span.style.fontWeight = style.fontWeight;
|
||||||
|
span.textContent = input.value || input.placeholder || "";
|
||||||
|
|
||||||
|
document.body.appendChild(span);
|
||||||
|
|
||||||
|
const width = span.offsetWidth + 60;
|
||||||
|
|
||||||
|
document.body.removeChild(span);
|
||||||
|
|
||||||
|
return width;
|
||||||
|
}
|
||||||
|
|
||||||
|
function autoExpandColumnFromInput(input) {
|
||||||
|
if (!input) return;
|
||||||
|
|
||||||
|
const cell = input.closest(".grid-cell");
|
||||||
|
if (!cell || !cell.dataset.index) return;
|
||||||
|
|
||||||
|
const columnIndex = parseInt(cell.dataset.index, 10);
|
||||||
|
if (!columnIndex) return;
|
||||||
|
|
||||||
|
const wantedWidth = Math.max(120, getInputTextWidth(input));
|
||||||
|
const currentWidth = cell.offsetWidth || 0;
|
||||||
|
|
||||||
|
// Only expand, do not shrink automatically
|
||||||
|
if (wantedWidth <= currentWidth) return;
|
||||||
|
|
||||||
|
const newWidth = Math.min(wantedWidth, 900);
|
||||||
|
|
||||||
|
const header = document.querySelector(
|
||||||
|
`.grid-header[data-index="${columnIndex}"]`,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (header) {
|
||||||
|
header.style.flex = `0 0 ${newWidth}px`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const topCell = document.querySelector(
|
||||||
|
`.grid-top .grid-cell:nth-child(${columnIndex + 1})`,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (topCell) {
|
||||||
|
topCell.style.flex = `0 0 ${newWidth}px`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const cells = document.querySelectorAll(
|
||||||
|
`.grid-row .grid-cell[data-index="${columnIndex}"]`,
|
||||||
|
);
|
||||||
|
|
||||||
|
cells.forEach((c) => {
|
||||||
|
c.style.flex = `0 0 ${newWidth}px`;
|
||||||
|
});
|
||||||
|
|
||||||
|
const colPos = columnIndex - 1;
|
||||||
|
|
||||||
|
if (columns[colPos]) {
|
||||||
|
columns[colPos].width = newWidth;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function syncVisibleRowsToGridData() {
|
function syncVisibleRowsToGridData() {
|
||||||
if (!rowContainer) return;
|
if (!rowContainer) return;
|
||||||
@@ -1055,6 +1157,7 @@
|
|||||||
placeholder: "Seleziona...",
|
placeholder: "Seleziona...",
|
||||||
allowClear: true,
|
allowClear: true,
|
||||||
width: "100%",
|
width: "100%",
|
||||||
|
sorter: sortSelect2ResultsByStart,
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
const items = fixedFieldCache[fieldKey] || [];
|
const items = fixedFieldCache[fieldKey] || [];
|
||||||
@@ -1127,6 +1230,10 @@
|
|||||||
const cell = e.target.closest(".grid-cell");
|
const cell = e.target.closest(".grid-cell");
|
||||||
if (!cell || !cell.dataset.row) return;
|
if (!cell || !cell.dataset.row) return;
|
||||||
|
|
||||||
|
if (e.target.classList.contains("cell-input")) {
|
||||||
|
autoExpandColumnFromInput(e.target);
|
||||||
|
}
|
||||||
|
|
||||||
const rowIndex = parseInt(cell.dataset.row, 10);
|
const rowIndex = parseInt(cell.dataset.row, 10);
|
||||||
const colType = cell.dataset.colType;
|
const colType = cell.dataset.colType;
|
||||||
|
|
||||||
@@ -1138,6 +1245,16 @@
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
rowContainer.addEventListener("focusin", function (e) {
|
||||||
|
if (!e.target.classList.contains("cell-input")) return;
|
||||||
|
|
||||||
|
autoExpandColumnFromInput(e.target);
|
||||||
|
|
||||||
|
setTimeout(() => {
|
||||||
|
autoExpandColumnFromInput(e.target);
|
||||||
|
}, 50);
|
||||||
|
});
|
||||||
|
|
||||||
// Persist tested_component before clicking +
|
// Persist tested_component before clicking +
|
||||||
document.addEventListener("mousedown", function (e) {
|
document.addEventListener("mousedown", function (e) {
|
||||||
const btn = e.target.closest(".add-part-btn");
|
const btn = e.target.closest(".add-part-btn");
|
||||||
|
|||||||
@@ -337,8 +337,8 @@ error_log("Loaded template: " . print_r($template, true));
|
|||||||
<form id="selectRowsForm" action="import_insert.php" method="POST">
|
<form id="selectRowsForm" action="import_insert.php" method="POST">
|
||||||
<input type="hidden" name="template_id" value="${data.template_id}">
|
<input type="hidden" name="template_id" value="${data.template_id}">
|
||||||
<input type="hidden" name="columns" value="${encodeURIComponent(JSON.stringify(data.columns))}">
|
<input type="hidden" name="columns" value="${encodeURIComponent(JSON.stringify(data.columns))}">
|
||||||
<input type="hidden" name="rows" value="${encodeURIComponent(JSON.stringify(data.rows))}">
|
<input type="hidden" name="rows" id="selectedRowsData" value="">
|
||||||
<input type="hidden" name="excelrows" value="${encodeURIComponent(JSON.stringify(data.excel_data.map(r => r.excelrow)))}">
|
<input type="hidden" name="excelrows" id="selectedExcelRowsData" value="">
|
||||||
<input type="hidden" name="filename" value="${data.filename}">
|
<input type="hidden" name="filename" value="${data.filename}">
|
||||||
|
|
||||||
<!-- TOP BUTTON -->
|
<!-- TOP BUTTON -->
|
||||||
@@ -389,6 +389,42 @@ error_log("Loaded template: " . print_r($template, true));
|
|||||||
`;
|
`;
|
||||||
tableContainer.innerHTML = html;
|
tableContainer.innerHTML = html;
|
||||||
|
|
||||||
|
const selectRowsForm = document.getElementById('selectRowsForm');
|
||||||
|
|
||||||
|
selectRowsForm.addEventListener('submit', function(e) {
|
||||||
|
const checkedBoxes = Array.from(document.querySelectorAll('.row-checkbox:checked'));
|
||||||
|
|
||||||
|
if (checkedBoxes.length === 0) {
|
||||||
|
e.preventDefault();
|
||||||
|
alert('Seleziona almeno una riga.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const selectedRows = [];
|
||||||
|
const selectedExcelRows = [];
|
||||||
|
|
||||||
|
checkedBoxes.forEach((cb, newIndex) => {
|
||||||
|
const originalIndex = parseInt(cb.value, 10);
|
||||||
|
|
||||||
|
if (data.rows && data.rows[originalIndex]) {
|
||||||
|
selectedRows.push(data.rows[originalIndex]);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (data.excel_data && data.excel_data[originalIndex]) {
|
||||||
|
selectedExcelRows.push(data.excel_data[originalIndex].excelrow);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reindex selected_rows so import_insert.php receives only the reduced rows array
|
||||||
|
cb.value = newIndex;
|
||||||
|
});
|
||||||
|
|
||||||
|
document.getElementById('selectedRowsData').value =
|
||||||
|
encodeURIComponent(JSON.stringify(selectedRows));
|
||||||
|
|
||||||
|
document.getElementById('selectedExcelRowsData').value =
|
||||||
|
encodeURIComponent(JSON.stringify(selectedExcelRows));
|
||||||
|
});
|
||||||
|
|
||||||
const topTableScrollbar = document.getElementById('topTableScrollbar');
|
const topTableScrollbar = document.getElementById('topTableScrollbar');
|
||||||
const topTableScrollbarInner = document.getElementById('topTableScrollbarInner');
|
const topTableScrollbarInner = document.getElementById('topTableScrollbarInner');
|
||||||
const mainTableContainer = document.getElementById('mainTableContainer');
|
const mainTableContainer = document.getElementById('mainTableContainer');
|
||||||
|
|||||||
@@ -20,9 +20,10 @@ $db = DBHandlerSelect::getInstance();
|
|||||||
$pdo = $db->getConnection();
|
$pdo = $db->getConnection();
|
||||||
|
|
||||||
// Recupera tutti i mapping dal template, includendo is_visible_import
|
// 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
|
$stmt = $pdo->prepare("SELECT id, excel_column, data_type, is_required, manual_default, is_manual, field_label, field_id, field_order, main_field, is_visible_import, auto_value
|
||||||
FROM template_mapping
|
FROM template_mapping
|
||||||
WHERE template_id = ?");
|
WHERE template_id = ?
|
||||||
|
ORDER BY field_order ASC, id ASC");
|
||||||
$stmt->execute([$template_id]);
|
$stmt->execute([$template_id]);
|
||||||
$allMappings = $stmt->fetchAll(PDO::FETCH_ASSOC);
|
$allMappings = $stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||||
|
|
||||||
@@ -55,15 +56,22 @@ if (empty($allMappings)) {
|
|||||||
exit;
|
exit;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Trova il campo main_field
|
// Find up to 2 main fields
|
||||||
$mainFieldMapping = null;
|
$mainFieldMappings = [];
|
||||||
|
|
||||||
foreach ($allMappings as $mapping) {
|
foreach ($allMappings as $mapping) {
|
||||||
if ($mapping['main_field'] == 1 && $mapping['is_visible_import'] == 1) {
|
if ((string)$mapping['main_field'] === '1' && (int)$mapping['is_visible_import'] === 1) {
|
||||||
$mainFieldMapping = $mapping;
|
$mainFieldMappings[] = $mapping;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (count($mainFieldMappings) >= 2) {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Backward compatibility: first main field
|
||||||
|
$mainFieldMapping = $mainFieldMappings[0] ?? null;
|
||||||
|
|
||||||
// Recupera l'idclient di default dal template (se presente)
|
// Recupera l'idclient di default dal template (se presente)
|
||||||
$template_stmt = $pdo->prepare("SELECT idclient FROM excel_templates WHERE id = ?");
|
$template_stmt = $pdo->prepare("SELECT idclient FROM excel_templates WHERE id = ?");
|
||||||
$template_stmt->execute([$template_id]);
|
$template_stmt->execute([$template_id]);
|
||||||
@@ -224,11 +232,18 @@ foreach ($importedData as $index => $row) {
|
|||||||
$rowObj['details'][(string)$d['mapping_id']] = $d['field_value'] ?? '';
|
$rowObj['details'][(string)$d['mapping_id']] = $d['field_value'] ?? '';
|
||||||
}
|
}
|
||||||
|
|
||||||
// Main field value
|
// Main field values
|
||||||
|
foreach ($mainFieldMappings as $mainMapping) {
|
||||||
|
$mainDetail = array_filter($rowDetails, fn($d) => $d['mapping_id'] == $mainMapping['id']);
|
||||||
|
$mainDetail = reset($mainDetail) ?: ['field_value' => $mainMapping['manual_default'] ?? ''];
|
||||||
|
|
||||||
|
$rowObj['details'][(string)$mainMapping['id']] =
|
||||||
|
$mainDetail['field_value'] ?? $mainMapping['manual_default'] ?? '';
|
||||||
|
}
|
||||||
|
|
||||||
|
// Backward compatibility: first main value
|
||||||
if ($mainFieldMapping) {
|
if ($mainFieldMapping) {
|
||||||
$mainDetail = array_filter($rowDetails, fn($d) => $d['mapping_id'] == $mainFieldMapping['id']);
|
$rowObj['mainFieldValue'] = $rowObj['details'][(string)$mainFieldMapping['id']] ?? '';
|
||||||
$mainDetail = reset($mainDetail) ?: ['field_value' => $mainFieldMapping['manual_default'] ?? ''];
|
|
||||||
$rowObj['mainFieldValue'] = $mainDetail['field_value'] ?? $mainFieldMapping['manual_default'] ?? '';
|
|
||||||
}
|
}
|
||||||
|
|
||||||
$rowObj['_dirty'] = false;
|
$rowObj['_dirty'] = false;
|
||||||
@@ -238,18 +253,27 @@ foreach ($importedData as $index => $row) {
|
|||||||
// Build columns in display order
|
// Build columns in display order
|
||||||
$gridColumns = [];
|
$gridColumns = [];
|
||||||
|
|
||||||
// 1. Main field
|
// 1. Main fields first, immediately after buttons
|
||||||
if ($mainFieldMapping) {
|
foreach ($allMappings as $mapping) {
|
||||||
$gridColumns[] = [
|
if (
|
||||||
'type' => 'main_field',
|
(int)$mapping['is_visible_import'] === 1
|
||||||
'key' => (string)$mainFieldMapping['id'],
|
&& (string)$mapping['main_field'] === '1'
|
||||||
'label' => $mainFieldMapping['field_label'],
|
&& trim((string)$mapping['field_label']) !== 'Tested Component:'
|
||||||
'dataType' => $mainFieldMapping['data_type'],
|
) {
|
||||||
'isManual' => (bool)$mainFieldMapping['is_manual'],
|
$gridColumns[] = [
|
||||||
'isRequired' => (bool)$mainFieldMapping['is_required'],
|
'type' => 'main_field',
|
||||||
'fieldId' => $mainFieldMapping['field_id'] ?? null,
|
'key' => (string)$mapping['id'],
|
||||||
'width' => 150,
|
'label' => $mapping['field_label'],
|
||||||
];
|
'dataType' => $mapping['data_type'],
|
||||||
|
'isManual' => (bool)$mapping['is_manual'],
|
||||||
|
'isRequired' => (bool)$mapping['is_required'],
|
||||||
|
'fieldId' => $mapping['field_id'] ?? null,
|
||||||
|
'fieldOrder' => (int)($mapping['field_order'] ?? 9999),
|
||||||
|
'manualDefault' => $mapping['manual_default'] ?? '',
|
||||||
|
'autoValue' => $mapping['auto_value'] ?? 'none',
|
||||||
|
'width' => 150,
|
||||||
|
];
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. Status
|
// 2. Status
|
||||||
@@ -261,50 +285,30 @@ $gridColumns[] = ['type' => 'idclient', 'key' => 'idclient', 'label' => 'Client'
|
|||||||
// 4. Cliente Fornitore
|
// 4. Cliente Fornitore
|
||||||
$gridColumns[] = ['type' => 'cliente_fornitore_id', 'key' => 'cliente_fornitore_id', 'label' => $slugMapping['ClienteFornitore'] ?? 'ClienteFornitore', 'width' => 300];
|
$gridColumns[] = ['type' => 'cliente_fornitore_id', 'key' => 'cliente_fornitore_id', 'label' => $slugMapping['ClienteFornitore'] ?? 'ClienteFornitore', 'width' => 300];
|
||||||
|
|
||||||
// 5. Auto fields
|
// 5. Other custom fields in schema order
|
||||||
foreach ($allMappings as $mapping) {
|
foreach ($allMappings as $mapping) {
|
||||||
if (
|
if (
|
||||||
!$mapping['is_manual']
|
(int)$mapping['is_visible_import'] === 1
|
||||||
&& $mapping['main_field'] != 1
|
&& (string)$mapping['main_field'] !== '1'
|
||||||
&& $mapping['is_visible_import'] == 1
|
|
||||||
&& trim((string)$mapping['field_label']) !== 'Tested Component:'
|
&& trim((string)$mapping['field_label']) !== 'Tested Component:'
|
||||||
) {
|
) {
|
||||||
|
$isMainField = ((string)$mapping['main_field'] === '1');
|
||||||
|
|
||||||
$gridColumns[] = [
|
$gridColumns[] = [
|
||||||
'type' => 'detail',
|
'type' => $isMainField ? 'main_field' : 'detail',
|
||||||
'key' => (string)$mapping['id'],
|
'key' => (string)$mapping['id'],
|
||||||
'label' => $mapping['field_label'],
|
'label' => $mapping['field_label'],
|
||||||
'dataType' => $mapping['data_type'],
|
'dataType' => $mapping['data_type'],
|
||||||
'isManual' => false,
|
'isManual' => (bool)$mapping['is_manual'],
|
||||||
'isRequired' => (bool)$mapping['is_required'],
|
'isRequired' => (bool)$mapping['is_required'],
|
||||||
'fieldId' => $mapping['field_id'] ?? null,
|
'fieldId' => $mapping['field_id'] ?? null,
|
||||||
|
'fieldOrder' => (int)($mapping['field_order'] ?? 9999),
|
||||||
|
'manualDefault' => $mapping['manual_default'] ?? '',
|
||||||
'autoValue' => $mapping['auto_value'] ?? 'none',
|
'autoValue' => $mapping['auto_value'] ?? 'none',
|
||||||
'width' => 150,
|
'width' => 150,
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 6. Manual fields
|
|
||||||
foreach ($allMappings as $mapping) {
|
|
||||||
if (
|
|
||||||
$mapping['is_manual']
|
|
||||||
&& $mapping['main_field'] != 1
|
|
||||||
&& $mapping['is_visible_import'] == 1
|
|
||||||
&& trim((string)$mapping['field_label']) !== 'Tested Component:'
|
|
||||||
) {
|
|
||||||
$gridColumns[] = [
|
|
||||||
'type' => 'detail',
|
|
||||||
'key' => (string)$mapping['id'],
|
|
||||||
'label' => $mapping['field_label'],
|
|
||||||
'dataType' => $mapping['data_type'],
|
|
||||||
'isManual' => true,
|
|
||||||
'isRequired' => (bool)$mapping['is_required'],
|
|
||||||
'fieldId' => $mapping['field_id'] ?? null,
|
|
||||||
'manualDefault' => $mapping['manual_default'] ?? '',
|
|
||||||
'width' => 150,
|
|
||||||
];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 7. Tested Component
|
// 7. Tested Component
|
||||||
$gridColumns[] = ['type' => 'tested_component', 'key' => 'tested_component', 'label' => 'Tested Component', 'width' => 150];
|
$gridColumns[] = ['type' => 'tested_component', 'key' => 'tested_component', 'label' => 'Tested Component', 'width' => 150];
|
||||||
|
|
||||||
@@ -342,7 +346,8 @@ $gridMeta = [
|
|||||||
'slugMapping' => $slugMapping,
|
'slugMapping' => $slugMapping,
|
||||||
'timeLabels' => $timeLabels,
|
'timeLabels' => $timeLabels,
|
||||||
'columns' => $gridColumns,
|
'columns' => $gridColumns,
|
||||||
'mainFieldMapping' => $mainFieldMapping,
|
'mainFieldMapping' => $mainFieldMapping,
|
||||||
|
'mainFieldMappings' => $mainFieldMappings,
|
||||||
'totalRows' => count($gridDataArray),
|
'totalRows' => count($gridDataArray),
|
||||||
];
|
];
|
||||||
|
|
||||||
@@ -669,7 +674,33 @@ $gridMeta = [
|
|||||||
flex-shrink: 0;
|
flex-shrink: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.grid-row .grid-header:nth-child(2) {
|
<?php if (isset($mainFieldMappings) && count($mainFieldMappings) >= 2): ?>
|
||||||
|
|
||||||
|
/* Sticky second Main column - only when the template has 2 Main fields */
|
||||||
|
.grid-top .grid-cell:nth-child(3),
|
||||||
|
#gridHeaderContainer .grid-header:nth-child(3),
|
||||||
|
.grid-row .grid-cell:nth-child(3) {
|
||||||
|
position: sticky !important;
|
||||||
|
left: 360px;
|
||||||
|
z-index: 7;
|
||||||
|
background: white;
|
||||||
|
overflow: visible;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
#gridHeaderContainer .grid-header:nth-child(3) {
|
||||||
|
background-color: #e9ecef;
|
||||||
|
}
|
||||||
|
|
||||||
|
.grid-row:nth-child(even) .grid-cell:nth-child(3) {
|
||||||
|
background-color: #f8f9fa;
|
||||||
|
}
|
||||||
|
|
||||||
|
.grid-row:hover .grid-cell:nth-child(3) {
|
||||||
|
background-color: #e9ecef;
|
||||||
|
}
|
||||||
|
|
||||||
|
<?php endif; ?>.grid-row .grid-header:nth-child(2) {
|
||||||
background-color: #e9ecef;
|
background-color: #e9ecef;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -57,7 +57,8 @@ $isSchemajsonEmpty = empty(trim($template['schemajson'] ?? ''));
|
|||||||
$stmt = $pdo->prepare("
|
$stmt = $pdo->prepare("
|
||||||
SELECT
|
SELECT
|
||||||
id,
|
id,
|
||||||
field_id,
|
field_id,
|
||||||
|
field_order,
|
||||||
excel_column,
|
excel_column,
|
||||||
json_node,
|
json_node,
|
||||||
is_manual,
|
is_manual,
|
||||||
@@ -79,6 +80,7 @@ $stmt = $pdo->prepare("
|
|||||||
is_visible_parts
|
is_visible_parts
|
||||||
FROM template_mapping
|
FROM template_mapping
|
||||||
WHERE template_id = ?
|
WHERE template_id = ?
|
||||||
|
ORDER BY field_order ASC, id ASC
|
||||||
");
|
");
|
||||||
$stmt->execute([$id]);
|
$stmt->execute([$id]);
|
||||||
$mappings = $stmt->fetchAll(PDO::FETCH_ASSOC);
|
$mappings = $stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||||
@@ -205,28 +207,37 @@ $apiSampleJson = $template['api_sample_json'] ?? '';
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* Type */
|
/* Type */
|
||||||
|
/* Order */
|
||||||
#schemaFieldsTable th:nth-child(5),
|
#schemaFieldsTable th:nth-child(5),
|
||||||
#schemaFieldsTable td:nth-child(5) {
|
#schemaFieldsTable td:nth-child(5) {
|
||||||
|
width: 70px;
|
||||||
|
text-align: center;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Type */
|
||||||
|
#schemaFieldsTable th:nth-child(6),
|
||||||
|
#schemaFieldsTable td:nth-child(6) {
|
||||||
width: 120px;
|
width: 120px;
|
||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Mapping = wide but NOT insane */
|
/* Mapping = wide but NOT insane */
|
||||||
#schemaFieldsTable th:nth-child(6),
|
#schemaFieldsTable th:nth-child(7),
|
||||||
#schemaFieldsTable td:nth-child(6) {
|
#schemaFieldsTable td:nth-child(7) {
|
||||||
width: 380px;
|
width: 380px;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Default Value = wider */
|
/* Default Value = wider */
|
||||||
#schemaFieldsTable th:nth-child(7),
|
#schemaFieldsTable th:nth-child(8),
|
||||||
#schemaFieldsTable td:nth-child(7) {
|
#schemaFieldsTable td:nth-child(8) {
|
||||||
width: 320px;
|
width: 320px;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* selects fill the cell */
|
/* selects fill the cell */
|
||||||
#schemaFieldsTable td:nth-child(6) .form-select,
|
#schemaFieldsTable td:nth-child(7) .form-select,
|
||||||
#schemaFieldsTable td:nth-child(7) .form-control,
|
#schemaFieldsTable td:nth-child(8) .form-control,
|
||||||
#schemaFieldsTable td:nth-child(7) .form-select {
|
#schemaFieldsTable td:nth-child(8) .form-select {
|
||||||
width: 100% !important;
|
width: 100% !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -254,6 +265,47 @@ $apiSampleJson = $template['api_sample_json'] ?? '';
|
|||||||
font-family: Consolas, Monaco, monospace;
|
font-family: Consolas, Monaco, monospace;
|
||||||
font-size: 13px;
|
font-size: 13px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.select2-container--default .select2-results__option {
|
||||||
|
white-space: nowrap;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
max-width: 520px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.select2-json-node {
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.select2-json-value {
|
||||||
|
color: #6c757d;
|
||||||
|
font-size: 12px;
|
||||||
|
margin-left: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.select2-json-row {
|
||||||
|
display: block;
|
||||||
|
margin: -6px;
|
||||||
|
padding: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.select2-results__option:has(.select2-json-row.used-option) {
|
||||||
|
background-color: #fff3cd !important;
|
||||||
|
color: #856404 !important;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.select2-results__option:has(.select2-json-row.used-option).select2-results__option--highlighted {
|
||||||
|
background-color: #ffe69c !important;
|
||||||
|
color: #856404 !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.select2-json-row.used-option .select2-json-node::after {
|
||||||
|
content: " (already used)";
|
||||||
|
color: #856404;
|
||||||
|
font-size: 12px;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
|
|
||||||
@@ -347,6 +399,7 @@ $apiSampleJson = $template['api_sample_json'] ?? '';
|
|||||||
<th style="width:45px; text-align:center;">Import</th>
|
<th style="width:45px; text-align:center;">Import</th>
|
||||||
<th style="width:45px; text-align:center;">Parts</th>
|
<th style="width:45px; text-align:center;">Parts</th>
|
||||||
<th style="width:320px;">Title</th>
|
<th style="width:320px;">Title</th>
|
||||||
|
<th style="width:70px; text-align:center;">Order</th>
|
||||||
<th style="width:120px;">Type</th>
|
<th style="width:120px;">Type</th>
|
||||||
<th><?php echo $sourceType === 'API' ? 'JSON Mapping' : 'Mapping'; ?></th>
|
<th><?php echo $sourceType === 'API' ? 'JSON Mapping' : 'Mapping'; ?></th>
|
||||||
<th>Default Value</th>
|
<th>Default Value</th>
|
||||||
@@ -383,6 +436,12 @@ $apiSampleJson = $template['api_sample_json'] ?? '';
|
|||||||
<?php endif; ?>
|
<?php endif; ?>
|
||||||
</td>
|
</td>
|
||||||
|
|
||||||
|
<td class="text-center">
|
||||||
|
<?php echo (int)($mapping['field_order'] ?? 9999); ?>
|
||||||
|
</td>
|
||||||
|
|
||||||
|
<td><?php echo htmlspecialchars($mapping['data_type'] ?? 'N/A'); ?></td>
|
||||||
|
|
||||||
<td><?php echo htmlspecialchars($mapping['data_type'] ?? 'N/A'); ?></td>
|
<td><?php echo htmlspecialchars($mapping['data_type'] ?? 'N/A'); ?></td>
|
||||||
|
|
||||||
<td>
|
<td>
|
||||||
@@ -1000,6 +1059,42 @@ $apiSampleJson = $template['api_sample_json'] ?? '';
|
|||||||
return escapeHtmlText(str);
|
return escapeHtmlText(str);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let jsonNodeLabels = {};
|
||||||
|
|
||||||
|
function getLastJsonNodeName(path) {
|
||||||
|
return String(path || '')
|
||||||
|
.replace(/\[\]/g, '')
|
||||||
|
.split('.')
|
||||||
|
.pop();
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatJsonSampleValue(value) {
|
||||||
|
if (value === null || value === undefined) return '';
|
||||||
|
|
||||||
|
let text = '';
|
||||||
|
|
||||||
|
if (Array.isArray(value)) {
|
||||||
|
text = '[Array]';
|
||||||
|
} else if (typeof value === 'object') {
|
||||||
|
text = '{Object}';
|
||||||
|
} else {
|
||||||
|
text = String(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
text = text
|
||||||
|
.replace(/[\r\n\t]+/g, ' ')
|
||||||
|
.replace(/\s+/g, ' ')
|
||||||
|
.trim();
|
||||||
|
|
||||||
|
if (text === '/' || text === '\\/') return '';
|
||||||
|
|
||||||
|
if (text.length > 38) {
|
||||||
|
text = text.substring(0, 38) + '...';
|
||||||
|
}
|
||||||
|
|
||||||
|
return text;
|
||||||
|
}
|
||||||
|
|
||||||
function flattenJsonNodes(obj, prefix = '') {
|
function flattenJsonNodes(obj, prefix = '') {
|
||||||
let nodes = [];
|
let nodes = [];
|
||||||
|
|
||||||
@@ -1018,6 +1113,14 @@ $apiSampleJson = $template['api_sample_json'] ?? '';
|
|||||||
if (value !== null && typeof value === 'object') {
|
if (value !== null && typeof value === 'object') {
|
||||||
nodes = nodes.concat(flattenJsonNodes(value, path));
|
nodes = nodes.concat(flattenJsonNodes(value, path));
|
||||||
} else {
|
} else {
|
||||||
|
const sample = formatJsonSampleValue(value);
|
||||||
|
const shortName = getLastJsonNodeName(path);
|
||||||
|
|
||||||
|
jsonNodeLabels[path] = {
|
||||||
|
shortName: shortName,
|
||||||
|
sample: sample
|
||||||
|
};
|
||||||
|
|
||||||
nodes.push(path);
|
nodes.push(path);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -1043,18 +1146,128 @@ $apiSampleJson = $template['api_sample_json'] ?? '';
|
|||||||
if (!clean) return '';
|
if (!clean) return '';
|
||||||
|
|
||||||
const isUsed = uniqueUsedNodes.includes(clean) && clean !== currentValue;
|
const isUsed = uniqueUsedNodes.includes(clean) && clean !== currentValue;
|
||||||
const label = isUsed ? `⚠ ${clean} (already used)` : clean;
|
const info = jsonNodeLabels[clean] || {};
|
||||||
|
const shortName = info.shortName || getLastJsonNodeName(clean);
|
||||||
|
const sample = info.sample || '';
|
||||||
|
|
||||||
|
let label = shortName;
|
||||||
|
if (sample) {
|
||||||
|
label += ` — ${sample}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isUsed) {
|
||||||
|
label = `⚠ ${label} (already used)`;
|
||||||
|
}
|
||||||
|
|
||||||
const isSelected = clean === currentValue ? 'selected' : '';
|
const isSelected = clean === currentValue ? 'selected' : '';
|
||||||
|
|
||||||
return `<option value="${escapeHtmlAttr(clean)}" class="${isUsed ? 'used-option' : ''}" ${isSelected}>${escapeHtmlText(label)}</option>`;
|
return `
|
||||||
|
<option
|
||||||
|
value="${escapeHtmlAttr(clean)}"
|
||||||
|
data-short-name="${escapeHtmlAttr(shortName)}"
|
||||||
|
data-sample="${escapeHtmlAttr(sample)}"
|
||||||
|
data-full-path="${escapeHtmlAttr(clean)}"
|
||||||
|
class="${isUsed ? 'used-option' : ''}"
|
||||||
|
data-used="${isUsed ? '1' : '0'}"
|
||||||
|
${isSelected}>
|
||||||
|
${escapeHtmlText(label)}
|
||||||
|
</option>
|
||||||
|
`;
|
||||||
})
|
})
|
||||||
.join('');
|
.join('');
|
||||||
|
|
||||||
select.innerHTML = '<option value="">Select JSON Node</option>' + options;
|
select.innerHTML = '<option value="">Select JSON Node</option>' + options;
|
||||||
select.dataset.currentJson = currentValue;
|
select.dataset.currentJson = currentValue;
|
||||||
});
|
});
|
||||||
|
|
||||||
|
initSelect2ForJsonDropdowns();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function initSelect2ForJsonDropdowns() {
|
||||||
|
if (!(window.jQuery && $.fn.select2)) return;
|
||||||
|
|
||||||
|
$('.json-nodes').filter(function() {
|
||||||
|
const tr = this.closest('tr');
|
||||||
|
const mappingSelect = tr ? tr.querySelector('.mapping-select') : null;
|
||||||
|
return mappingSelect && mappingSelect.value === 'json';
|
||||||
|
}).each(function() {
|
||||||
|
const $el = $(this);
|
||||||
|
if (this.style.display === 'none') {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if ($el.hasClass('select2-hidden-accessible')) {
|
||||||
|
$el.select2('destroy');
|
||||||
|
}
|
||||||
|
|
||||||
|
$el.select2({
|
||||||
|
width: '100%',
|
||||||
|
placeholder: 'Select JSON Node',
|
||||||
|
allowClear: true,
|
||||||
|
dropdownAutoWidth: false,
|
||||||
|
|
||||||
|
templateResult: function(data) {
|
||||||
|
if (!data.id) return data.text;
|
||||||
|
|
||||||
|
const option = data.element;
|
||||||
|
const shortName = option.getAttribute('data-short-name') || data.text;
|
||||||
|
const sample = option.getAttribute('data-sample') || '';
|
||||||
|
const isUsed = option.getAttribute('data-used') === '1';
|
||||||
|
|
||||||
|
const $row = $('<span class="select2-json-row"></span>');
|
||||||
|
if (isUsed) {
|
||||||
|
$row.addClass('used-option');
|
||||||
|
}
|
||||||
|
$row.append(`<span class="select2-json-node">${escapeHtmlText(shortName)}</span>`);
|
||||||
|
|
||||||
|
if (sample) {
|
||||||
|
$row.append(`<span class="select2-json-value">${escapeHtmlText(sample)}</span>`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $row;
|
||||||
|
},
|
||||||
|
|
||||||
|
templateSelection: function(data) {
|
||||||
|
if (!data.id) return data.text;
|
||||||
|
|
||||||
|
const option = data.element;
|
||||||
|
const shortName = option.getAttribute('data-short-name') || data.text;
|
||||||
|
const sample = option.getAttribute('data-sample') || '';
|
||||||
|
|
||||||
|
if (sample) {
|
||||||
|
return `${shortName} — ${sample}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
return shortName;
|
||||||
|
},
|
||||||
|
|
||||||
|
matcher: function(params, data) {
|
||||||
|
if ($.trim(params.term) === '') {
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
const term = params.term.toLowerCase();
|
||||||
|
const option = data.element;
|
||||||
|
|
||||||
|
const fullPath = option?.getAttribute('data-full-path')?.toLowerCase() || '';
|
||||||
|
const shortName = option?.getAttribute('data-short-name')?.toLowerCase() || '';
|
||||||
|
const sample = option?.getAttribute('data-sample')?.toLowerCase() || '';
|
||||||
|
|
||||||
|
if (
|
||||||
|
fullPath.includes(term) ||
|
||||||
|
shortName.includes(term) ||
|
||||||
|
sample.includes(term)
|
||||||
|
) {
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
function saveJsonNodes(sampleJson, nodes) {
|
function saveJsonNodes(sampleJson, nodes) {
|
||||||
return fetch('update_api_json_nodes.php', {
|
return fetch('update_api_json_nodes.php', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
@@ -1445,225 +1658,221 @@ $apiSampleJson = $template['api_sample_json'] ?? '';
|
|||||||
document.getElementById('updateSchemaButton').addEventListener('click', updateSchemaDetails);
|
document.getElementById('updateSchemaButton').addEventListener('click', updateSchemaDetails);
|
||||||
|
|
||||||
document.getElementById('schemaFieldsBody').addEventListener('change', function(event) {
|
document.getElementById('schemaFieldsBody').addEventListener('change', function(event) {
|
||||||
|
if (!event.target.classList.contains('mapping-select')) return;
|
||||||
|
|
||||||
if (event.target.classList.contains('mapping-select')) {
|
const mappingSelect = event.target;
|
||||||
let tr = event.target.closest('tr');
|
const tr = mappingSelect.closest('tr');
|
||||||
let mappingId = event.target.getAttribute('data-id');
|
const mappingId = mappingSelect.getAttribute('data-id');
|
||||||
|
|
||||||
let xlsSelect = tr.querySelector('.xls-columns');
|
const xlsSelect = tr.querySelector('.xls-columns');
|
||||||
let jsonSelect = tr.querySelector('.json-nodes');
|
const jsonSelect = tr.querySelector('.json-nodes');
|
||||||
let manualInput = tr.querySelector('.manual-default');
|
const manualInput = tr.querySelector('.manual-default');
|
||||||
let autoSelect = tr.querySelector('.auto-value-select');
|
const autoSelect = tr.querySelector('.auto-value-select');
|
||||||
|
|
||||||
let mappedColumn = tr.querySelector('.mapped-column');
|
const mappedColumn = tr.querySelector('.mapped-column');
|
||||||
let mappedJsonNode = tr.querySelector('.mapped-json-node');
|
const mappedJsonNode = tr.querySelector('.mapped-json-node');
|
||||||
|
|
||||||
let removeBtn = tr.querySelector('.remove-xls');
|
const removeBtn = tr.querySelector('.remove-xls');
|
||||||
let removeJsonBtn = tr.querySelector('.remove-json');
|
const removeJsonBtn = tr.querySelector('.remove-json');
|
||||||
|
|
||||||
if (event.target.value === 'xls') {
|
function destroyJsonSelect2() {
|
||||||
if (xlsSelect) xlsSelect.style.display = 'block';
|
if (jsonSelect && window.jQuery && $(jsonSelect).hasClass('select2-hidden-accessible')) {
|
||||||
if (jsonSelect) jsonSelect.style.display = 'none';
|
$(jsonSelect).select2('destroy');
|
||||||
if (autoSelect) autoSelect.style.display = 'none';
|
|
||||||
|
|
||||||
if (manualInput) {
|
|
||||||
manualInput.style.display = 'none';
|
|
||||||
manualInput.value = '';
|
|
||||||
}
|
|
||||||
|
|
||||||
if (mappedColumn) mappedColumn.style.display = 'none';
|
|
||||||
if (mappedJsonNode) mappedJsonNode.style.display = 'none';
|
|
||||||
|
|
||||||
if (removeBtn) removeBtn.style.display = xlsSelect && xlsSelect.value ? 'inline-block' : 'none';
|
|
||||||
if (removeJsonBtn) removeJsonBtn.style.display = 'none';
|
|
||||||
|
|
||||||
} else if (event.target.value === 'json') {
|
|
||||||
if (xlsSelect) xlsSelect.style.display = 'none';
|
|
||||||
if (jsonSelect) jsonSelect.style.display = 'block';
|
|
||||||
if (autoSelect) autoSelect.style.display = 'none';
|
|
||||||
|
|
||||||
if (manualInput) {
|
|
||||||
manualInput.style.display = 'none';
|
|
||||||
manualInput.value = '';
|
|
||||||
}
|
|
||||||
|
|
||||||
if (mappedColumn) mappedColumn.style.display = 'none';
|
|
||||||
if (mappedJsonNode) mappedJsonNode.style.display = 'none';
|
|
||||||
|
|
||||||
if (removeBtn) removeBtn.style.display = 'none';
|
|
||||||
if (removeJsonBtn) removeJsonBtn.style.display = jsonSelect && jsonSelect.value ? 'inline-block' : 'none';
|
|
||||||
|
|
||||||
} else if (event.target.value === 'manual') {
|
|
||||||
if (xlsSelect) xlsSelect.style.display = 'none';
|
|
||||||
if (jsonSelect) jsonSelect.style.display = 'none';
|
|
||||||
if (autoSelect) autoSelect.style.display = 'none';
|
|
||||||
|
|
||||||
if (manualInput) {
|
|
||||||
manualInput.style.display = 'block';
|
|
||||||
}
|
|
||||||
|
|
||||||
if (mappedColumn) mappedColumn.style.display = 'none';
|
|
||||||
if (mappedJsonNode) mappedJsonNode.style.display = 'none';
|
|
||||||
|
|
||||||
if (removeBtn) removeBtn.style.display = 'none';
|
|
||||||
if (removeJsonBtn) removeJsonBtn.style.display = 'none';
|
|
||||||
|
|
||||||
} else if (event.target.value === 'auto') {
|
|
||||||
if (xlsSelect) {
|
|
||||||
xlsSelect.style.display = 'none';
|
|
||||||
xlsSelect.value = '';
|
|
||||||
}
|
|
||||||
|
|
||||||
if (jsonSelect) {
|
|
||||||
jsonSelect.style.display = 'none';
|
|
||||||
jsonSelect.value = '';
|
|
||||||
}
|
|
||||||
|
|
||||||
if (manualInput) {
|
|
||||||
manualInput.style.display = 'none';
|
|
||||||
manualInput.value = '';
|
|
||||||
}
|
|
||||||
|
|
||||||
if (mappedColumn) mappedColumn.style.display = 'none';
|
|
||||||
if (mappedJsonNode) mappedJsonNode.style.display = 'none';
|
|
||||||
|
|
||||||
if (removeBtn) removeBtn.style.display = 'none';
|
|
||||||
if (removeJsonBtn) removeJsonBtn.style.display = 'none';
|
|
||||||
|
|
||||||
if (autoSelect) autoSelect.style.display = 'block';
|
|
||||||
|
|
||||||
} else {
|
|
||||||
if (xlsSelect) xlsSelect.style.display = 'none';
|
|
||||||
if (jsonSelect) jsonSelect.style.display = 'none';
|
|
||||||
if (autoSelect) autoSelect.style.display = 'none';
|
|
||||||
|
|
||||||
if (manualInput) {
|
|
||||||
manualInput.style.display = 'none';
|
|
||||||
manualInput.value = '';
|
|
||||||
}
|
|
||||||
|
|
||||||
if (mappedColumn) mappedColumn.style.display = 'none';
|
|
||||||
if (mappedJsonNode) mappedJsonNode.style.display = 'none';
|
|
||||||
|
|
||||||
if (removeBtn) removeBtn.style.display = 'none';
|
|
||||||
if (removeJsonBtn) removeJsonBtn.style.display = 'none';
|
|
||||||
}
|
}
|
||||||
|
|
||||||
saveMapping(
|
|
||||||
mappingId,
|
|
||||||
event.target.value,
|
|
||||||
manualInput ? manualInput.value : '',
|
|
||||||
xlsSelect ? xlsSelect.value : null,
|
|
||||||
autoSelect ? autoSelect.value : null,
|
|
||||||
jsonSelect ? jsonSelect.value : null
|
|
||||||
);
|
|
||||||
|
|
||||||
if (sourceType === 'XLS') updateXlsDropdowns();
|
|
||||||
if (sourceType === 'API') updateJsonDropdowns();
|
|
||||||
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (event.target.classList.contains('main-field-checkbox')) {
|
if (mappingSelect.value === 'xls') {
|
||||||
const checkbox = event.target;
|
if (xlsSelect) xlsSelect.style.display = 'block';
|
||||||
const mappingId = checkbox.dataset.mappingId;
|
|
||||||
const value = checkbox.checked ? 1 : 0;
|
|
||||||
|
|
||||||
const checkedMainFields = document.querySelectorAll('.main-field-checkbox:checked');
|
destroyJsonSelect2();
|
||||||
|
if (jsonSelect) {
|
||||||
if (checkedMainFields.length > 2) {
|
jsonSelect.style.display = 'none';
|
||||||
checkbox.checked = false;
|
jsonSelect.value = '';
|
||||||
alert('Puoi selezionare al massimo 2 campi Main.');
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fetch('update_main_field.php', {
|
if (autoSelect) autoSelect.style.display = 'none';
|
||||||
method: 'POST',
|
|
||||||
headers: {
|
|
||||||
'Content-Type': 'application/json'
|
|
||||||
},
|
|
||||||
body: JSON.stringify({
|
|
||||||
template_id: <?php echo $id; ?>,
|
|
||||||
mapping_id: mappingId,
|
|
||||||
value: value
|
|
||||||
})
|
|
||||||
})
|
|
||||||
.then(response => response.json())
|
|
||||||
.then(data => {
|
|
||||||
if (!data.success) {
|
|
||||||
console.error("❌ Error updating main_field:", data.message);
|
|
||||||
|
|
||||||
document.querySelectorAll('.main-field-checkbox').forEach(cb => {
|
if (manualInput) {
|
||||||
cb.checked = cb.dataset.originalChecked === 'true';
|
manualInput.style.display = 'none';
|
||||||
});
|
manualInput.value = '';
|
||||||
|
|
||||||
alert(data.message || 'Errore durante il salvataggio del campo Main.');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
document.querySelectorAll('.main-field-checkbox').forEach(cb => {
|
|
||||||
cb.dataset.originalChecked = cb.checked ? 'true' : 'false';
|
|
||||||
});
|
|
||||||
})
|
|
||||||
.catch(error => {
|
|
||||||
console.error("❌ Fetch error:", error);
|
|
||||||
|
|
||||||
document.querySelectorAll('.main-field-checkbox').forEach(cb => {
|
|
||||||
cb.checked = cb.dataset.originalChecked === 'true';
|
|
||||||
});
|
|
||||||
|
|
||||||
alert('Errore di comunicazione durante il salvataggio del campo Main.');
|
|
||||||
});
|
|
||||||
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (event.target.classList.contains('visible-parts-checkbox')) {
|
|
||||||
const checkbox = event.target;
|
|
||||||
const mappingId = checkbox.dataset.mappingId;
|
|
||||||
const value = checkbox.checked ? 1 : 0;
|
|
||||||
const prevChecked = checkbox.checked;
|
|
||||||
|
|
||||||
if (value === 1) {
|
|
||||||
document.querySelectorAll('.visible-parts-checkbox').forEach(cb => {
|
|
||||||
if (cb !== checkbox) cb.checked = false;
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fetch('update_visible_parts.php', {
|
if (mappedColumn) mappedColumn.style.display = 'none';
|
||||||
method: 'POST',
|
if (mappedJsonNode) mappedJsonNode.style.display = 'none';
|
||||||
headers: {
|
|
||||||
'Content-Type': 'application/json'
|
|
||||||
},
|
|
||||||
body: JSON.stringify({
|
|
||||||
template_id: <?php echo $id; ?>,
|
|
||||||
mapping_id: mappingId,
|
|
||||||
value: value
|
|
||||||
})
|
|
||||||
})
|
|
||||||
.then(r => r.json())
|
|
||||||
.then(data => {
|
|
||||||
if (!data.success) {
|
|
||||||
console.error("❌ Error updating is_visible_parts:", data.message);
|
|
||||||
checkbox.checked = !prevChecked;
|
|
||||||
location.reload();
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.catch(error => {
|
|
||||||
console.error("❌ Fetch error:", error);
|
|
||||||
checkbox.checked = !prevChecked;
|
|
||||||
location.reload();
|
|
||||||
});
|
|
||||||
|
|
||||||
return;
|
if (removeBtn) removeBtn.style.display = xlsSelect && xlsSelect.value ? 'inline-block' : 'none';
|
||||||
|
if (removeJsonBtn) removeJsonBtn.style.display = 'none';
|
||||||
|
|
||||||
|
} else if (mappingSelect.value === 'json') {
|
||||||
|
if (xlsSelect) {
|
||||||
|
xlsSelect.style.display = 'none';
|
||||||
|
xlsSelect.value = '';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (jsonSelect) {
|
||||||
|
jsonSelect.style.display = 'block';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (autoSelect) autoSelect.style.display = 'none';
|
||||||
|
|
||||||
|
if (manualInput) {
|
||||||
|
manualInput.style.display = 'none';
|
||||||
|
manualInput.value = '';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (mappedColumn) mappedColumn.style.display = 'none';
|
||||||
|
if (mappedJsonNode) mappedJsonNode.style.display = 'none';
|
||||||
|
|
||||||
|
if (removeBtn) removeBtn.style.display = 'none';
|
||||||
|
if (removeJsonBtn) removeJsonBtn.style.display = jsonSelect && jsonSelect.value ? 'inline-block' : 'none';
|
||||||
|
|
||||||
|
updateJsonDropdowns();
|
||||||
|
|
||||||
|
} else if (mappingSelect.value === 'manual') {
|
||||||
|
if (xlsSelect) xlsSelect.style.display = 'none';
|
||||||
|
|
||||||
|
destroyJsonSelect2();
|
||||||
|
if (jsonSelect) {
|
||||||
|
jsonSelect.style.display = 'none';
|
||||||
|
jsonSelect.value = '';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (autoSelect) autoSelect.style.display = 'none';
|
||||||
|
|
||||||
|
if (manualInput) {
|
||||||
|
manualInput.style.display = 'block';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (mappedColumn) mappedColumn.style.display = 'none';
|
||||||
|
if (mappedJsonNode) mappedJsonNode.style.display = 'none';
|
||||||
|
|
||||||
|
if (removeBtn) removeBtn.style.display = 'none';
|
||||||
|
if (removeJsonBtn) removeJsonBtn.style.display = 'none';
|
||||||
|
|
||||||
|
} else if (mappingSelect.value === 'auto') {
|
||||||
|
if (xlsSelect) {
|
||||||
|
xlsSelect.style.display = 'none';
|
||||||
|
xlsSelect.value = '';
|
||||||
|
}
|
||||||
|
|
||||||
|
destroyJsonSelect2();
|
||||||
|
if (jsonSelect) {
|
||||||
|
jsonSelect.style.display = 'none';
|
||||||
|
jsonSelect.value = '';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (manualInput) {
|
||||||
|
manualInput.style.display = 'none';
|
||||||
|
manualInput.value = '';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (mappedColumn) mappedColumn.style.display = 'none';
|
||||||
|
if (mappedJsonNode) mappedJsonNode.style.display = 'none';
|
||||||
|
|
||||||
|
if (removeBtn) removeBtn.style.display = 'none';
|
||||||
|
if (removeJsonBtn) removeJsonBtn.style.display = 'none';
|
||||||
|
|
||||||
|
if (autoSelect) autoSelect.style.display = 'block';
|
||||||
|
|
||||||
|
} else {
|
||||||
|
if (xlsSelect) xlsSelect.style.display = 'none';
|
||||||
|
|
||||||
|
destroyJsonSelect2();
|
||||||
|
if (jsonSelect) {
|
||||||
|
jsonSelect.style.display = 'none';
|
||||||
|
jsonSelect.value = '';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (autoSelect) autoSelect.style.display = 'none';
|
||||||
|
|
||||||
|
if (manualInput) {
|
||||||
|
manualInput.style.display = 'none';
|
||||||
|
manualInput.value = '';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (mappedColumn) mappedColumn.style.display = 'none';
|
||||||
|
if (mappedJsonNode) mappedJsonNode.style.display = 'none';
|
||||||
|
|
||||||
|
if (removeBtn) removeBtn.style.display = 'none';
|
||||||
|
if (removeJsonBtn) removeJsonBtn.style.display = 'none';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
saveMapping(
|
||||||
|
mappingId,
|
||||||
|
mappingSelect.value,
|
||||||
|
manualInput ? manualInput.value : '',
|
||||||
|
xlsSelect ? xlsSelect.value : null,
|
||||||
|
autoSelect ? autoSelect.value : null,
|
||||||
|
jsonSelect ? jsonSelect.value : null
|
||||||
|
);
|
||||||
|
|
||||||
|
if (sourceType === 'XLS') updateXlsDropdowns();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
function saveJsonNodeSelection(jsonSelect) {
|
||||||
|
if (!jsonSelect) return;
|
||||||
|
|
||||||
// Salva lo stato originale dei checkbox al caricamento
|
let tr = jsonSelect.closest('tr');
|
||||||
document.querySelectorAll('.main-field-checkbox').forEach(cb => {
|
let mappingId = jsonSelect.getAttribute('data-id');
|
||||||
cb.dataset.originalChecked = cb.checked;
|
let manualInput = tr.querySelector('.manual-default');
|
||||||
|
let mappedJsonNode = tr.querySelector('.mapped-json-node');
|
||||||
|
let removeJsonBtn = tr.querySelector('.remove-json');
|
||||||
|
let mappingSelect = tr.querySelector('.mapping-select');
|
||||||
|
|
||||||
|
if (mappingSelect && mappingSelect.value !== 'json') {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!mappedJsonNode) {
|
||||||
|
mappedJsonNode = document.createElement('span');
|
||||||
|
mappedJsonNode.className = 'mapped-json-node';
|
||||||
|
mappedJsonNode.style.marginLeft = '5px';
|
||||||
|
tr.querySelector('td:nth-child(7)').appendChild(mappedJsonNode);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!removeJsonBtn) {
|
||||||
|
removeJsonBtn = document.createElement('button');
|
||||||
|
removeJsonBtn.className = 'btn btn-danger btn-sm remove-json';
|
||||||
|
removeJsonBtn.textContent = 'X';
|
||||||
|
removeJsonBtn.style.marginLeft = '5px';
|
||||||
|
removeJsonBtn.setAttribute('data-id', mappingId);
|
||||||
|
tr.querySelector('td:nth-child(7)').appendChild(removeJsonBtn);
|
||||||
|
}
|
||||||
|
|
||||||
|
mappedJsonNode.textContent = jsonSelect.value ? `(${jsonSelect.value})` : '';
|
||||||
|
mappedJsonNode.style.display = jsonSelect.value ? 'inline' : 'none';
|
||||||
|
removeJsonBtn.style.display = jsonSelect.value ? 'inline-block' : 'none';
|
||||||
|
|
||||||
|
console.log('[JSON NODE SAVE]', {
|
||||||
|
mappingId: mappingId,
|
||||||
|
value: jsonSelect.value
|
||||||
|
});
|
||||||
|
|
||||||
|
saveMapping(
|
||||||
|
mappingId,
|
||||||
|
'json',
|
||||||
|
manualInput ? manualInput.value : '',
|
||||||
|
null,
|
||||||
|
null,
|
||||||
|
jsonSelect.value
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
document.getElementById('schemaFieldsBody').addEventListener('change', function(event) {
|
||||||
|
if (!event.target.classList.contains('json-nodes')) return;
|
||||||
|
saveJsonNodeSelection(event.target);
|
||||||
|
});
|
||||||
|
|
||||||
|
if (window.jQuery) {
|
||||||
|
$(document).on('select2:select select2:clear', 'select.json-nodes', function() {
|
||||||
|
saveJsonNodeSelection(this);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// Save original Main checkbox state
|
||||||
|
document.querySelectorAll('#schemaFieldsBody .main-field-checkbox').forEach(cb => {
|
||||||
|
cb.dataset.originalChecked = cb.checked ? 'true' : 'false';
|
||||||
});
|
});
|
||||||
|
|
||||||
// AUTO VALUE select change -> save auto_value
|
// AUTO VALUE select change -> save auto_value
|
||||||
@@ -1700,7 +1909,7 @@ $apiSampleJson = $template['api_sample_json'] ?? '';
|
|||||||
mappedColumn = document.createElement('span');
|
mappedColumn = document.createElement('span');
|
||||||
mappedColumn.className = 'mapped-column';
|
mappedColumn.className = 'mapped-column';
|
||||||
mappedColumn.style.marginLeft = '5px';
|
mappedColumn.style.marginLeft = '5px';
|
||||||
tr.querySelector('td:nth-child(6)').appendChild(mappedColumn);
|
tr.querySelector('td:nth-child(7)').appendChild(mappedColumn);
|
||||||
}
|
}
|
||||||
if (!removeBtn) {
|
if (!removeBtn) {
|
||||||
removeBtn = document.createElement('button');
|
removeBtn = document.createElement('button');
|
||||||
@@ -1708,7 +1917,7 @@ $apiSampleJson = $template['api_sample_json'] ?? '';
|
|||||||
removeBtn.textContent = 'X';
|
removeBtn.textContent = 'X';
|
||||||
removeBtn.style.marginLeft = '5px';
|
removeBtn.style.marginLeft = '5px';
|
||||||
removeBtn.setAttribute('data-id', mappingId);
|
removeBtn.setAttribute('data-id', mappingId);
|
||||||
tr.querySelector('td:nth-child(6)').appendChild(removeBtn);
|
tr.querySelector('td:nth-child(7)').appendChild(removeBtn);
|
||||||
|
|
||||||
removeBtn.addEventListener('click', function(e) {
|
removeBtn.addEventListener('click', function(e) {
|
||||||
let tr = e.target.closest('tr');
|
let tr = e.target.closest('tr');
|
||||||
@@ -1742,51 +1951,6 @@ $apiSampleJson = $template['api_sample_json'] ?? '';
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
document.getElementById('schemaFieldsBody').addEventListener('change', function(event) {
|
|
||||||
if (event.target.classList.contains('json-nodes')) {
|
|
||||||
let tr = event.target.closest('tr');
|
|
||||||
let mappingId = event.target.getAttribute('data-id');
|
|
||||||
let manualInput = tr.querySelector('.manual-default');
|
|
||||||
let mappedJsonNode = tr.querySelector('.mapped-json-node');
|
|
||||||
let removeJsonBtn = tr.querySelector('.remove-json');
|
|
||||||
|
|
||||||
if (!mappedJsonNode) {
|
|
||||||
mappedJsonNode = document.createElement('span');
|
|
||||||
mappedJsonNode.className = 'mapped-json-node';
|
|
||||||
mappedJsonNode.style.marginLeft = '5px';
|
|
||||||
tr.querySelector('td:nth-child(6)').appendChild(mappedJsonNode);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!removeJsonBtn) {
|
|
||||||
removeJsonBtn = document.createElement('button');
|
|
||||||
removeJsonBtn.className = 'btn btn-danger btn-sm remove-json';
|
|
||||||
removeJsonBtn.textContent = 'X';
|
|
||||||
removeJsonBtn.style.marginLeft = '5px';
|
|
||||||
removeJsonBtn.setAttribute('data-id', mappingId);
|
|
||||||
tr.querySelector('td:nth-child(6)').appendChild(removeJsonBtn);
|
|
||||||
}
|
|
||||||
|
|
||||||
mappedJsonNode.textContent = event.target.value ? `(${event.target.value})` : '';
|
|
||||||
mappedJsonNode.style.display = event.target.value ? 'inline' : 'none';
|
|
||||||
removeJsonBtn.style.display = event.target.value ? 'inline-block' : 'none';
|
|
||||||
|
|
||||||
const mappingSelect = tr.querySelector('.mapping-select');
|
|
||||||
if (mappingSelect && mappingSelect.value !== 'json') {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
saveMapping(
|
|
||||||
mappingId,
|
|
||||||
'json',
|
|
||||||
manualInput ? manualInput.value : '',
|
|
||||||
null,
|
|
||||||
null,
|
|
||||||
event.target.value
|
|
||||||
);
|
|
||||||
|
|
||||||
updateJsonDropdowns();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
document.getElementById('schemaFieldsBody').addEventListener('change', function(event) {
|
document.getElementById('schemaFieldsBody').addEventListener('change', function(event) {
|
||||||
if (event.target.classList.contains('manual-default') && event.target.tagName === 'SELECT') {
|
if (event.target.classList.contains('manual-default') && event.target.tagName === 'SELECT') {
|
||||||
@@ -1913,9 +2077,11 @@ $apiSampleJson = $template['api_sample_json'] ?? '';
|
|||||||
updateXlsDropdowns();
|
updateXlsDropdowns();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (data.success && mappingType === 'json' && jsonNode) {
|
if (data.success && mappingType === 'json') {
|
||||||
usedJsonNodesFromDB = usedJsonNodesFromDB.filter(node => node !== jsonNode);
|
usedJsonNodesFromDB = Array.from(document.querySelectorAll('select.json-nodes'))
|
||||||
usedJsonNodesFromDB.push(jsonNode);
|
.map(select => select.value || select.dataset.currentJson || '')
|
||||||
|
.filter(Boolean);
|
||||||
|
|
||||||
updateJsonDropdowns();
|
updateJsonDropdowns();
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
@@ -2150,6 +2316,17 @@ $apiSampleJson = $template['api_sample_json'] ?? '';
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (sourceType === 'API' && availableJsonNodes.length) {
|
if (sourceType === 'API' && availableJsonNodes.length) {
|
||||||
|
const rawJson = document.getElementById('apiJsonExample')?.value || '';
|
||||||
|
|
||||||
|
if (rawJson.trim()) {
|
||||||
|
try {
|
||||||
|
jsonNodeLabels = {};
|
||||||
|
flattenJsonNodes(JSON.parse(rawJson));
|
||||||
|
} catch (e) {
|
||||||
|
console.warn('Cannot rebuild JSON labels from sample JSON', e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
updateJsonDropdowns();
|
updateJsonDropdowns();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -259,11 +259,9 @@ $matrixGroups = array_values($matrixGroups);
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="d-flex flex-wrap align-items-center gap-2 mb-3">
|
<div class="d-flex flex-wrap align-items-center gap-2 mb-3">
|
||||||
<div class="form-check m-0">
|
<input type="hidden" id="analysisWebOnly" value="1">
|
||||||
<input class="form-check-input" type="checkbox" id="analysisWebOnly">
|
<div class="small text-success fw-semibold">
|
||||||
<label class="form-check-label small" for="analysisWebOnly">
|
Showing WEB analyses only
|
||||||
Web only
|
|
||||||
</label>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="flex-grow-1" style="min-width: 220px;">
|
<div class="flex-grow-1" style="min-width: 220px;">
|
||||||
|
|||||||
@@ -0,0 +1,71 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Routine: burberry
|
||||||
|
*
|
||||||
|
* Purpose:
|
||||||
|
* For each imported XLS row:
|
||||||
|
* - read the value from column S
|
||||||
|
* - read the value from column T
|
||||||
|
* - merge the values
|
||||||
|
* - save the final value into column S
|
||||||
|
*
|
||||||
|
* Target:
|
||||||
|
* Column S must be mapped to the destination field in the template mapping.
|
||||||
|
*/
|
||||||
|
|
||||||
|
function applyRoutine(&$excelData, $routineData = [])
|
||||||
|
{
|
||||||
|
/*
|
||||||
|
* This routine does not require external routine data.
|
||||||
|
* Columns are fixed.
|
||||||
|
*
|
||||||
|
* Excel column indexes are zero-based:
|
||||||
|
*
|
||||||
|
* S = 18
|
||||||
|
* T = 19
|
||||||
|
*/
|
||||||
|
$targetColumnIndex = 18; // S
|
||||||
|
|
||||||
|
$columnSIndex = 18; // S
|
||||||
|
$columnTIndex = 19; // T
|
||||||
|
|
||||||
|
foreach ($excelData as $rowIndex => &$row) {
|
||||||
|
if (!isset($row['data']) || !is_array($row['data'])) {
|
||||||
|
error_log("Routine burberry: invalid row structure at index {$rowIndex}.");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$valueS = trim((string)($row['data'][$columnSIndex] ?? ''));
|
||||||
|
$valueT = trim((string)($row['data'][$columnTIndex] ?? ''));
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Merge values, ignoring empty values.
|
||||||
|
*/
|
||||||
|
$mergedValues = [];
|
||||||
|
|
||||||
|
if ($valueS !== '') {
|
||||||
|
$mergedValues[] = $valueS;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($valueT !== '') {
|
||||||
|
$mergedValues[] = $valueT;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Save final value into column S.
|
||||||
|
*/
|
||||||
|
$row['data'][$targetColumnIndex] = implode(' ', $mergedValues);
|
||||||
|
|
||||||
|
error_log(
|
||||||
|
"Routine burberry: row " .
|
||||||
|
($row['excelrow'] ?? $rowIndex) .
|
||||||
|
" generated value in column S: " .
|
||||||
|
$row['data'][$targetColumnIndex]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
unset($row);
|
||||||
|
|
||||||
|
error_log("Routine burberry completed.");
|
||||||
|
}
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Routine: merge_column_T_and_U_into_T
|
||||||
|
*
|
||||||
|
* Purpose:
|
||||||
|
* For each imported XLS row:
|
||||||
|
* - read the value from column T
|
||||||
|
* - read the value from column U
|
||||||
|
* - merge both values
|
||||||
|
* - save the final value into column T
|
||||||
|
*
|
||||||
|
* Target:
|
||||||
|
* Column T must be mapped to the destination field in the template mapping.
|
||||||
|
*/
|
||||||
|
|
||||||
|
function applyRoutine(&$excelData, $routineData = [])
|
||||||
|
{
|
||||||
|
/*
|
||||||
|
* Excel column indexes are zero-based:
|
||||||
|
*
|
||||||
|
* T = 19
|
||||||
|
* U = 20
|
||||||
|
*/
|
||||||
|
$targetColumnIndex = 19; // T
|
||||||
|
$firstColumnIndex = 19; // T
|
||||||
|
$secondColumnIndex = 20; // U
|
||||||
|
|
||||||
|
foreach ($excelData as $rowIndex => &$row) {
|
||||||
|
if (!isset($row['data']) || !is_array($row['data'])) {
|
||||||
|
error_log("Routine merge T+U: invalid row structure at index {$rowIndex}.");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$valueT = trim((string)($row['data'][$firstColumnIndex] ?? ''));
|
||||||
|
$valueU = trim((string)($row['data'][$secondColumnIndex] ?? ''));
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Merge values, ignoring empty values.
|
||||||
|
*/
|
||||||
|
$mergedValues = [];
|
||||||
|
|
||||||
|
if ($valueT !== '') {
|
||||||
|
$mergedValues[] = $valueT;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($valueU !== '') {
|
||||||
|
$mergedValues[] = $valueU;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Save final value into column T.
|
||||||
|
*/
|
||||||
|
$row['data'][$targetColumnIndex] = implode(' ', $mergedValues);
|
||||||
|
|
||||||
|
error_log(
|
||||||
|
"Routine merge T+U: row " .
|
||||||
|
($row['excelrow'] ?? $rowIndex) .
|
||||||
|
" generated value in column T: " .
|
||||||
|
$row['data'][$targetColumnIndex]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
unset($row);
|
||||||
|
|
||||||
|
error_log("Routine merge T+U completed.");
|
||||||
|
}
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Routine: paulshark
|
||||||
|
*
|
||||||
|
* Purpose:
|
||||||
|
* For each imported XLS row:
|
||||||
|
* - read the value from column D
|
||||||
|
* - read the value from column E
|
||||||
|
* - read the value from column J
|
||||||
|
* - merge the values
|
||||||
|
* - save the final value into column D
|
||||||
|
*
|
||||||
|
* Target:
|
||||||
|
* Column D must be mapped to the destination field in the template mapping.
|
||||||
|
*/
|
||||||
|
|
||||||
|
function applyRoutine(&$excelData, $routineData = [])
|
||||||
|
{
|
||||||
|
/*
|
||||||
|
* Excel column indexes are zero-based:
|
||||||
|
*
|
||||||
|
* D = 3
|
||||||
|
* E = 4
|
||||||
|
* J = 9
|
||||||
|
*/
|
||||||
|
$targetColumnIndex = 3; // D
|
||||||
|
|
||||||
|
$columnDIndex = 3; // D
|
||||||
|
$columnEIndex = 4; // E
|
||||||
|
$columnJIndex = 9; // J
|
||||||
|
|
||||||
|
foreach ($excelData as $rowIndex => &$row) {
|
||||||
|
if (!isset($row['data']) || !is_array($row['data'])) {
|
||||||
|
error_log("Routine paulshark: invalid row structure at index {$rowIndex}.");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$valueD = trim((string)($row['data'][$columnDIndex] ?? ''));
|
||||||
|
$valueE = trim((string)($row['data'][$columnEIndex] ?? ''));
|
||||||
|
$valueJ = trim((string)($row['data'][$columnJIndex] ?? ''));
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Merge values, ignoring empty values.
|
||||||
|
*/
|
||||||
|
$mergedValues = [];
|
||||||
|
|
||||||
|
if ($valueD !== '') {
|
||||||
|
$mergedValues[] = $valueD;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($valueE !== '') {
|
||||||
|
$mergedValues[] = $valueE;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($valueJ !== '') {
|
||||||
|
$mergedValues[] = $valueJ;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Save final value into column D.
|
||||||
|
*/
|
||||||
|
$row['data'][$targetColumnIndex] = implode(' ', $mergedValues);
|
||||||
|
|
||||||
|
error_log(
|
||||||
|
"Routine paulshark: row " .
|
||||||
|
($row['excelrow'] ?? $rowIndex) .
|
||||||
|
" generated value in column D: " .
|
||||||
|
$row['data'][$targetColumnIndex]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
unset($row);
|
||||||
|
|
||||||
|
error_log("Routine paulshark completed.");
|
||||||
|
}
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Routine: Richemont Pelletteria
|
||||||
|
*
|
||||||
|
* Purpose:
|
||||||
|
* For each imported XLS row:
|
||||||
|
* - read the value from column D
|
||||||
|
* - read the value from column E
|
||||||
|
* - merge the values
|
||||||
|
* - save the final value into column D
|
||||||
|
*
|
||||||
|
* Target:
|
||||||
|
* Column D must be mapped to the destination field in the template mapping.
|
||||||
|
*/
|
||||||
|
|
||||||
|
function applyRoutine(&$excelData, $routineData = [])
|
||||||
|
{
|
||||||
|
/*
|
||||||
|
* This routine does not require external routine data.
|
||||||
|
* Columns are fixed.
|
||||||
|
*
|
||||||
|
* Excel column indexes are zero-based:
|
||||||
|
*
|
||||||
|
* D = 3
|
||||||
|
* E = 4
|
||||||
|
*/
|
||||||
|
$targetColumnIndex = 3; // D
|
||||||
|
|
||||||
|
$columnDIndex = 3; // D
|
||||||
|
$columnEIndex = 4; // E
|
||||||
|
|
||||||
|
foreach ($excelData as $rowIndex => &$row) {
|
||||||
|
if (!isset($row['data']) || !is_array($row['data'])) {
|
||||||
|
error_log("Routine Richemont Pelletteria: invalid row structure at index {$rowIndex}.");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$valueD = trim((string)($row['data'][$columnDIndex] ?? ''));
|
||||||
|
$valueE = trim((string)($row['data'][$columnEIndex] ?? ''));
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Merge values, ignoring empty values.
|
||||||
|
*/
|
||||||
|
$mergedValues = [];
|
||||||
|
|
||||||
|
if ($valueD !== '') {
|
||||||
|
$mergedValues[] = $valueD;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($valueE !== '') {
|
||||||
|
$mergedValues[] = $valueE;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Save final value into column D.
|
||||||
|
*/
|
||||||
|
$row['data'][$targetColumnIndex] = implode(' ', $mergedValues);
|
||||||
|
|
||||||
|
error_log(
|
||||||
|
"Routine Richemont Pelletteria: row " .
|
||||||
|
($row['excelrow'] ?? $rowIndex) .
|
||||||
|
" generated value in column D: " .
|
||||||
|
$row['data'][$targetColumnIndex]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
unset($row);
|
||||||
|
|
||||||
|
error_log("Routine Richemont Pelletteria completed.");
|
||||||
|
}
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Routine: build_field_347_from_x_columns
|
||||||
|
*
|
||||||
|
* Purpose:
|
||||||
|
* For each imported XLS row:
|
||||||
|
* - check columns P to AT
|
||||||
|
* - when a cell contains "x", take the related column title from row 6
|
||||||
|
* - append the free text value from column AU
|
||||||
|
* - save the final comma-separated text into column P
|
||||||
|
*
|
||||||
|
* Target:
|
||||||
|
* Column P must be mapped to field_id 347.
|
||||||
|
*/
|
||||||
|
|
||||||
|
function applyRoutine(&$excelData, $routineData = [])
|
||||||
|
{
|
||||||
|
/*
|
||||||
|
* Excel column indexes are zero-based:
|
||||||
|
*
|
||||||
|
* P = 15
|
||||||
|
* AT = 45
|
||||||
|
* AU = 46
|
||||||
|
*/
|
||||||
|
$targetColumnIndex = 15; // P
|
||||||
|
$startColumnIndex = 15; // P
|
||||||
|
$endColumnIndex = 45; // AT
|
||||||
|
$extraColumnIndex = 46; // AU
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Headers must come from XLS row 6.
|
||||||
|
* Usually they are passed inside $routineData['xls_headers'].
|
||||||
|
*/
|
||||||
|
$headers = $routineData['xls_headers'] ?? [];
|
||||||
|
|
||||||
|
if (empty($headers) || !is_array($headers)) {
|
||||||
|
error_log("Routine field_id 347: missing XLS headers from row 6.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach ($excelData as $rowIndex => &$row) {
|
||||||
|
if (!isset($row['data']) || !is_array($row['data'])) {
|
||||||
|
error_log("Routine field_id 347: invalid row structure at index {$rowIndex}.");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$selectedValues = [];
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Check columns from P to AT.
|
||||||
|
* If the cell contains x, take the related column header.
|
||||||
|
*/
|
||||||
|
for ($columnIndex = $startColumnIndex; $columnIndex <= $endColumnIndex; $columnIndex++) {
|
||||||
|
$cellValue = strtolower(trim((string)($row['data'][$columnIndex] ?? '')));
|
||||||
|
|
||||||
|
if ($cellValue === 'x') {
|
||||||
|
$headerTitle = trim((string)($headers[$columnIndex] ?? ''));
|
||||||
|
|
||||||
|
if ($headerTitle !== '') {
|
||||||
|
$selectedValues[] = $headerTitle;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Add free text from column AU.
|
||||||
|
*/
|
||||||
|
$extraText = '';
|
||||||
|
|
||||||
|
if (isset($row['data'][$extraColumnIndex])) {
|
||||||
|
$extraText = trim((string)$row['data'][$extraColumnIndex]);
|
||||||
|
} elseif (isset($row['data']['AU'])) {
|
||||||
|
$extraText = trim((string)$row['data']['AU']);
|
||||||
|
}
|
||||||
|
|
||||||
|
error_log(
|
||||||
|
"Routine field_id 347: row " .
|
||||||
|
($row['excelrow'] ?? $rowIndex) .
|
||||||
|
" AU index {$extraColumnIndex} value: " .
|
||||||
|
print_r($row['data'][$extraColumnIndex] ?? null, true) .
|
||||||
|
" | AU key value: " .
|
||||||
|
print_r($row['data']['AU'] ?? null, true)
|
||||||
|
);
|
||||||
|
|
||||||
|
if ($extraText !== '') {
|
||||||
|
$selectedValues[] = $extraText;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Remove empty and duplicate values.
|
||||||
|
*/
|
||||||
|
$selectedValues = array_values(array_unique(array_filter($selectedValues, function ($value) {
|
||||||
|
return trim((string)$value) !== '';
|
||||||
|
})));
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Save final value into column P.
|
||||||
|
* Column P must be mapped to field_id 347 in the template mapping.
|
||||||
|
*/
|
||||||
|
$row['data'][$targetColumnIndex] = implode(', ', $selectedValues);
|
||||||
|
|
||||||
|
error_log(
|
||||||
|
"Routine field_id 347: row " .
|
||||||
|
($row['excelrow'] ?? $rowIndex) .
|
||||||
|
" generated value: " .
|
||||||
|
$row['data'][$targetColumnIndex]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
unset($row);
|
||||||
|
|
||||||
|
error_log("Routine field_id 347 completed.");
|
||||||
|
}
|
||||||
@@ -46,8 +46,8 @@
|
|||||||
{
|
{
|
||||||
"IdSchemaCustomFields": 48,
|
"IdSchemaCustomFields": 48,
|
||||||
"ConteggioClienti": 0,
|
"ConteggioClienti": 0,
|
||||||
"Nome": "Standard Generico \/ Generic Standard",
|
"Nome": "Standard \/ Generico",
|
||||||
"Descrizione": "Schema per tutti i campioni di qualsiasi matrice escluso cuoio\/pelle\r\n\r\n"
|
"Descrizione": "\r\n"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"IdSchemaCustomFields": 49,
|
"IdSchemaCustomFields": 49,
|
||||||
@@ -882,6 +882,24 @@
|
|||||||
"ConteggioClienti": 0,
|
"ConteggioClienti": 0,
|
||||||
"Nome": "LIMS-CIM - MAX MARA",
|
"Nome": "LIMS-CIM - MAX MARA",
|
||||||
"Descrizione": "Schema per MAX MARA scambio dati Database"
|
"Descrizione": "Schema per MAX MARA scambio dati Database"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"IdSchemaCustomFields": 203,
|
||||||
|
"ConteggioClienti": 0,
|
||||||
|
"Nome": "Vince",
|
||||||
|
"Descrizione": "Schema per tutti i campioni di VINCE\r\n\r\n"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"IdSchemaCustomFields": 204,
|
||||||
|
"ConteggioClienti": 0,
|
||||||
|
"Nome": "Max Mara",
|
||||||
|
"Descrizione": "Schema da usare per Max Mara\r\n"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"IdSchemaCustomFields": 205,
|
||||||
|
"ConteggioClienti": 0,
|
||||||
|
"Nome": "Chanel Flammability",
|
||||||
|
"Descrizione": "Schema per Chanel Flammability\r\n"
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -2,7 +2,11 @@
|
|||||||
require_once dirname(__DIR__, 2) . '/vendor/autoload.php';
|
require_once dirname(__DIR__, 2) . '/vendor/autoload.php';
|
||||||
require_once __DIR__ . '/class/db-functions.php';
|
require_once __DIR__ . '/class/db-functions.php';
|
||||||
include dirname(__DIR__) . '/../extra/auth.php';
|
include dirname(__DIR__) . '/../extra/auth.php';
|
||||||
if (!Auth::check()) { http_response_code(401); echo json_encode(['error' => 'Unauthorized']); exit; }
|
if (!Auth::check()) {
|
||||||
|
http_response_code(401);
|
||||||
|
echo json_encode(['error' => 'Unauthorized']);
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
require_once __DIR__ . '/class/VisualLimsApiClient.class.php';
|
require_once __DIR__ . '/class/VisualLimsApiClient.class.php';
|
||||||
|
|
||||||
@@ -13,7 +17,8 @@ error_reporting(E_ALL);
|
|||||||
$fieldId = intval($_GET['field_id'] ?? 0);
|
$fieldId = intval($_GET['field_id'] ?? 0);
|
||||||
$q = mb_strtolower(trim($_GET['q'] ?? ''));
|
$q = mb_strtolower(trim($_GET['q'] ?? ''));
|
||||||
$id = isset($_GET['id']) ? intval($_GET['id']) : null;
|
$id = isset($_GET['id']) ? intval($_GET['id']) : null;
|
||||||
$limit = max(1, min(50, intval($_GET['limit'] ?? 20)));
|
$rawLimit = intval($_GET['limit'] ?? 20);
|
||||||
|
$limit = $rawLimit <= 0 ? 0 : max(1, min(500, $rawLimit));
|
||||||
|
|
||||||
if (!$fieldId) {
|
if (!$fieldId) {
|
||||||
echo json_encode(['results' => []]);
|
echo json_encode(['results' => []]);
|
||||||
@@ -52,7 +57,7 @@ try {
|
|||||||
$text = $v['Valore'] ?? '';
|
$text = $v['Valore'] ?? '';
|
||||||
if ($q === '' || mb_strpos(mb_strtolower($text), $q) !== false) {
|
if ($q === '' || mb_strpos(mb_strtolower($text), $q) !== false) {
|
||||||
$results[] = ['id' => $v['IdCustomFieldsValue'], 'text' => $text];
|
$results[] = ['id' => $v['IdCustomFieldsValue'], 'text' => $text];
|
||||||
if (count($results) >= $limit) break;
|
if ($limit > 0 && count($results) >= $limit) break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
<?php
|
||||||
|
require_once "class/VisualLimsApiClient.class.php";
|
||||||
|
include('include/headscript.php');
|
||||||
|
|
||||||
|
header("Content-Type: application/json; charset=utf-8");
|
||||||
|
|
||||||
|
try {
|
||||||
|
$api = VisualLimsApiClient::getInstance();
|
||||||
|
|
||||||
|
$commessaId = 577818;
|
||||||
|
|
||||||
|
$endpoint = "CommessaWeb({$commessaId})?\$expand=CommesseCustomFields(\$expand=CustomField)";
|
||||||
|
|
||||||
|
$result = $api->get($endpoint);
|
||||||
|
|
||||||
|
echo json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
|
||||||
|
} catch (Exception $e) {
|
||||||
|
http_response_code(500);
|
||||||
|
echo json_encode([
|
||||||
|
"success" => false,
|
||||||
|
"error" => $e->getMessage()
|
||||||
|
], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
|
||||||
|
}
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
<?php
|
||||||
|
require_once dirname(__DIR__, 2) . '/vendor/autoload.php';
|
||||||
|
require_once dirname(__FILE__) . '/class/VisualLimsApiClient.class.php';
|
||||||
|
require_once dirname(__FILE__) . '/include/headscript.php';
|
||||||
|
|
||||||
|
header('Content-Type: application/json');
|
||||||
|
ini_set('display_errors', '0');
|
||||||
|
error_reporting(E_ALL);
|
||||||
|
|
||||||
|
try {
|
||||||
|
$db = DBHandlerSelect::getInstance();
|
||||||
|
$pdo = $db->getConnection();
|
||||||
|
|
||||||
|
$api = VisualLimsApiClient::getInstance();
|
||||||
|
|
||||||
|
// Get all schemas currently used in template_mapping
|
||||||
|
$stmtSchemas = $pdo->query("
|
||||||
|
SELECT DISTINCT schema_id
|
||||||
|
FROM template_mapping
|
||||||
|
WHERE schema_id IS NOT NULL
|
||||||
|
AND schema_id > 0
|
||||||
|
ORDER BY schema_id ASC
|
||||||
|
");
|
||||||
|
|
||||||
|
$schemaIds = $stmtSchemas->fetchAll(PDO::FETCH_COLUMN);
|
||||||
|
|
||||||
|
if (empty($schemaIds)) {
|
||||||
|
throw new Exception('No schema_id found in template_mapping');
|
||||||
|
}
|
||||||
|
|
||||||
|
$stmtUpdate = $pdo->prepare("
|
||||||
|
UPDATE template_mapping
|
||||||
|
SET field_order = ?
|
||||||
|
WHERE schema_id = ?
|
||||||
|
AND field_id = ?
|
||||||
|
");
|
||||||
|
|
||||||
|
$summary = [];
|
||||||
|
$totalUpdated = 0;
|
||||||
|
|
||||||
|
foreach ($schemaIds as $schemaId) {
|
||||||
|
$schemaId = (int)$schemaId;
|
||||||
|
|
||||||
|
$endpoint = "SchemaCustomField($schemaId)?\$expand=SchemiCustomFieldsDettagli(\$expand=CustomField)";
|
||||||
|
$data = $api->get($endpoint);
|
||||||
|
|
||||||
|
if (empty($data['SchemiCustomFieldsDettagli']) || !is_array($data['SchemiCustomFieldsDettagli'])) {
|
||||||
|
$summary[] = [
|
||||||
|
'schema_id' => $schemaId,
|
||||||
|
'success' => false,
|
||||||
|
'message' => 'No SchemiCustomFieldsDettagli found'
|
||||||
|
];
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$schemaUpdated = 0;
|
||||||
|
$notFound = [];
|
||||||
|
|
||||||
|
foreach ($data['SchemiCustomFieldsDettagli'] as $detail) {
|
||||||
|
$order = intval($detail['Ordine'] ?? 9999);
|
||||||
|
$fieldId = intval($detail['CustomField']['IdCustomField'] ?? 0);
|
||||||
|
|
||||||
|
if ($fieldId <= 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$stmtUpdate->execute([
|
||||||
|
$order,
|
||||||
|
$schemaId,
|
||||||
|
$fieldId
|
||||||
|
]);
|
||||||
|
|
||||||
|
if ($stmtUpdate->rowCount() > 0) {
|
||||||
|
$schemaUpdated++;
|
||||||
|
$totalUpdated++;
|
||||||
|
} else {
|
||||||
|
$notFound[] = [
|
||||||
|
'field_id' => $fieldId,
|
||||||
|
'order' => $order,
|
||||||
|
'label' => $detail['CustomField']['Titolo'] ?? ''
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$summary[] = [
|
||||||
|
'schema_id' => $schemaId,
|
||||||
|
'success' => true,
|
||||||
|
'updated' => $schemaUpdated,
|
||||||
|
'not_found_count' => count($notFound),
|
||||||
|
'not_found' => $notFound
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
echo json_encode([
|
||||||
|
'success' => true,
|
||||||
|
'schemas_processed' => count($schemaIds),
|
||||||
|
'total_updated' => $totalUpdated,
|
||||||
|
'summary' => $summary
|
||||||
|
], JSON_PRETTY_PRINT);
|
||||||
|
} catch (Exception $e) {
|
||||||
|
http_response_code(500);
|
||||||
|
|
||||||
|
echo json_encode([
|
||||||
|
'success' => false,
|
||||||
|
'message' => $e->getMessage()
|
||||||
|
], JSON_PRETTY_PRINT);
|
||||||
|
}
|
||||||
@@ -7,13 +7,15 @@ include('include/headscript.php');
|
|||||||
|
|
||||||
header('Content-Type: application/json');
|
header('Content-Type: application/json');
|
||||||
|
|
||||||
// Read JSON payload
|
|
||||||
$data = json_decode(file_get_contents('php://input'), true);
|
$data = json_decode(file_get_contents('php://input'), true);
|
||||||
|
|
||||||
$template_id = intval($data['template_id'] ?? 0);
|
$template_id = intval($data['template_id'] ?? 0);
|
||||||
$mapping_id = intval($data['mapping_id'] ?? 0);
|
$mapping_id = intval($data['mapping_id'] ?? 0);
|
||||||
$value = intval($data['value'] ?? 0);
|
$value = intval($data['value'] ?? 0);
|
||||||
|
|
||||||
|
// IMPORTANT: main_field may be ENUM('0','1'), so use string values
|
||||||
|
$mainValue = ($value === 1) ? '1' : '0';
|
||||||
|
|
||||||
if ($template_id <= 0 || $mapping_id <= 0) {
|
if ($template_id <= 0 || $mapping_id <= 0) {
|
||||||
echo json_encode(['success' => false, 'message' => 'Invalid IDs']);
|
echo json_encode(['success' => false, 'message' => 'Invalid IDs']);
|
||||||
exit;
|
exit;
|
||||||
@@ -25,13 +27,12 @@ $pdo = $db->getConnection();
|
|||||||
try {
|
try {
|
||||||
$pdo->beginTransaction();
|
$pdo->beginTransaction();
|
||||||
|
|
||||||
// If user is trying to activate a Main field, check current number of active Main fields
|
if ($mainValue === '1') {
|
||||||
if ($value === 1) {
|
|
||||||
$stmt = $pdo->prepare("
|
$stmt = $pdo->prepare("
|
||||||
SELECT COUNT(*)
|
SELECT COUNT(*)
|
||||||
FROM template_mapping
|
FROM template_mapping
|
||||||
WHERE template_id = ?
|
WHERE template_id = ?
|
||||||
AND main_field = 1
|
AND main_field = '1'
|
||||||
AND id <> ?
|
AND id <> ?
|
||||||
");
|
");
|
||||||
$stmt->execute([$template_id, $mapping_id]);
|
$stmt->execute([$template_id, $mapping_id]);
|
||||||
@@ -39,22 +40,23 @@ try {
|
|||||||
|
|
||||||
if ($currentMainCount >= 2) {
|
if ($currentMainCount >= 2) {
|
||||||
$pdo->rollBack();
|
$pdo->rollBack();
|
||||||
|
|
||||||
echo json_encode([
|
echo json_encode([
|
||||||
'success' => false,
|
'success' => false,
|
||||||
'message' => 'Maximum 2 Main fields allowed'
|
'message' => 'Maximum 2 Main fields allowed',
|
||||||
|
'currentMainCount' => $currentMainCount
|
||||||
]);
|
]);
|
||||||
exit;
|
exit;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Update only this mapping
|
|
||||||
$stmt = $pdo->prepare("
|
$stmt = $pdo->prepare("
|
||||||
UPDATE template_mapping
|
UPDATE template_mapping
|
||||||
SET main_field = ?
|
SET main_field = ?
|
||||||
WHERE id = ?
|
WHERE id = ?
|
||||||
AND template_id = ?
|
AND template_id = ?
|
||||||
");
|
");
|
||||||
$stmt->execute([$value, $mapping_id, $template_id]);
|
$stmt->execute([$mainValue, $mapping_id, $template_id]);
|
||||||
|
|
||||||
$pdo->commit();
|
$pdo->commit();
|
||||||
|
|
||||||
|
|||||||
@@ -82,6 +82,7 @@ try {
|
|||||||
template_id,
|
template_id,
|
||||||
schema_id,
|
schema_id,
|
||||||
field_id,
|
field_id,
|
||||||
|
field_order,
|
||||||
data_type,
|
data_type,
|
||||||
is_required,
|
is_required,
|
||||||
default_value,
|
default_value,
|
||||||
@@ -97,6 +98,7 @@ try {
|
|||||||
:template_id,
|
:template_id,
|
||||||
:schema_id,
|
:schema_id,
|
||||||
:field_id,
|
:field_id,
|
||||||
|
:field_order,
|
||||||
:data_type,
|
:data_type,
|
||||||
:is_required,
|
:is_required,
|
||||||
:default_value,
|
:default_value,
|
||||||
@@ -116,6 +118,7 @@ try {
|
|||||||
UPDATE template_mapping
|
UPDATE template_mapping
|
||||||
SET
|
SET
|
||||||
schema_id = :schema_id,
|
schema_id = :schema_id,
|
||||||
|
field_order = :field_order,
|
||||||
data_type = :data_type,
|
data_type = :data_type,
|
||||||
is_required = :is_required,
|
is_required = :is_required,
|
||||||
default_value = :default_value,
|
default_value = :default_value,
|
||||||
@@ -172,6 +175,7 @@ try {
|
|||||||
|
|
||||||
$data = [
|
$data = [
|
||||||
':schema_id' => $schema_id,
|
':schema_id' => $schema_id,
|
||||||
|
':field_order' => (int)($field['Ordine'] ?? 9999),
|
||||||
':data_type' => $newDataType,
|
':data_type' => $newDataType,
|
||||||
':is_required' => !empty($custom_field['ObbligatorioWeb']) ? 1 : 0,
|
':is_required' => !empty($custom_field['ObbligatorioWeb']) ? 1 : 0,
|
||||||
':default_value' => $custom_field['ValoreDefault'] ?? null,
|
':default_value' => $custom_field['ValoreDefault'] ?? null,
|
||||||
@@ -234,7 +238,6 @@ try {
|
|||||||
|
|
||||||
$response["success"] = true;
|
$response["success"] = true;
|
||||||
$response["message"] = "Schema JSON updated, mappings synchronized, removed fields deleted, and changed fields updated successfully.";
|
$response["message"] = "Schema JSON updated, mappings synchronized, removed fields deleted, and changed fields updated successfully.";
|
||||||
|
|
||||||
} catch (Exception $e) {
|
} catch (Exception $e) {
|
||||||
if (isset($pdo) && $pdo->inTransaction()) {
|
if (isset($pdo) && $pdo->inTransaction()) {
|
||||||
$pdo->rollback();
|
$pdo->rollback();
|
||||||
@@ -243,4 +246,4 @@ try {
|
|||||||
$response["message"] = $e->getMessage();
|
$response["message"] = $e->getMessage();
|
||||||
}
|
}
|
||||||
|
|
||||||
echo json_encode($response);
|
echo json_encode($response);
|
||||||
|
|||||||
@@ -0,0 +1,79 @@
|
|||||||
|
<?php
|
||||||
|
require_once dirname(__DIR__, 2) . '/vendor/autoload.php';
|
||||||
|
require_once dirname(__FILE__) . '/class/VisualLimsApiClient.class.php';
|
||||||
|
require_once dirname(__FILE__) . '/include/headscript.php';
|
||||||
|
|
||||||
|
header('Content-Type: application/json');
|
||||||
|
ini_set('display_errors', '0');
|
||||||
|
error_reporting(E_ALL);
|
||||||
|
|
||||||
|
try {
|
||||||
|
$schemaId = isset($_GET['schema_id']) && is_numeric($_GET['schema_id'])
|
||||||
|
? intval($_GET['schema_id'])
|
||||||
|
: 0;
|
||||||
|
|
||||||
|
if ($schemaId <= 0) {
|
||||||
|
throw new Exception('Missing or invalid schema_id');
|
||||||
|
}
|
||||||
|
|
||||||
|
$api = VisualLimsApiClient::getInstance();
|
||||||
|
|
||||||
|
$endpoint = "SchemaCustomField($schemaId)?\$expand=SchemiCustomFieldsDettagli(\$expand=CustomField)";
|
||||||
|
$data = $api->get($endpoint);
|
||||||
|
|
||||||
|
if (empty($data['SchemiCustomFieldsDettagli']) || !is_array($data['SchemiCustomFieldsDettagli'])) {
|
||||||
|
throw new Exception('No SchemiCustomFieldsDettagli found');
|
||||||
|
}
|
||||||
|
|
||||||
|
$db = DBHandlerSelect::getInstance();
|
||||||
|
$pdo = $db->getConnection();
|
||||||
|
|
||||||
|
$updated = 0;
|
||||||
|
$notFound = [];
|
||||||
|
|
||||||
|
$stmt = $pdo->prepare("
|
||||||
|
UPDATE template_mapping
|
||||||
|
SET field_order = ?
|
||||||
|
WHERE schema_id = ?
|
||||||
|
AND field_id = ?
|
||||||
|
");
|
||||||
|
|
||||||
|
foreach ($data['SchemiCustomFieldsDettagli'] as $detail) {
|
||||||
|
$order = intval($detail['Ordine'] ?? 9999);
|
||||||
|
$fieldId = intval($detail['CustomField']['IdCustomField'] ?? 0);
|
||||||
|
|
||||||
|
if ($fieldId <= 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$stmt->execute([
|
||||||
|
$order,
|
||||||
|
$schemaId,
|
||||||
|
$fieldId
|
||||||
|
]);
|
||||||
|
|
||||||
|
if ($stmt->rowCount() > 0) {
|
||||||
|
$updated++;
|
||||||
|
} else {
|
||||||
|
$notFound[] = [
|
||||||
|
'field_id' => $fieldId,
|
||||||
|
'order' => $order,
|
||||||
|
'label' => $detail['CustomField']['Titolo'] ?? ''
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
echo json_encode([
|
||||||
|
'success' => true,
|
||||||
|
'schema_id' => $schemaId,
|
||||||
|
'updated' => $updated,
|
||||||
|
'not_found' => $notFound
|
||||||
|
]);
|
||||||
|
} catch (Exception $e) {
|
||||||
|
http_response_code(500);
|
||||||
|
|
||||||
|
echo json_encode([
|
||||||
|
'success' => false,
|
||||||
|
'message' => $e->getMessage()
|
||||||
|
]);
|
||||||
|
}
|
||||||
@@ -88,6 +88,58 @@ $validators[] = function (int $iddatadb, array $ctx): array {
|
|||||||
return [];
|
return [];
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// 3. All LIMS-mandatory fields must be filled.
|
||||||
|
$validators[] = function (int $iddatadb, array $ctx): array {
|
||||||
|
$record = $ctx['record'] ?? null;
|
||||||
|
if (!$record) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
$errors = [];
|
||||||
|
|
||||||
|
// Fixed fields (stored as columns in datadb)
|
||||||
|
foreach (($ctx['requiredFixed'] ?? []) as $key => $label) {
|
||||||
|
$col = $ctx['fixedAliasMap'][$key] ?? null;
|
||||||
|
$val = $col !== null ? ($record[$col] ?? null) : null;
|
||||||
|
if ($val === null || $val === '' || (int) $val === 0) {
|
||||||
|
$errors[] = [
|
||||||
|
'field' => $key,
|
||||||
|
'message' => $label . ' è obbligatorio.',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Custom fields (values stored in import_data_details, keyed by mapping_id)
|
||||||
|
foreach (($ctx['requiredCustom'] ?? []) as $cf) {
|
||||||
|
$val = $ctx['customValues'][(int) $cf['mapping_id']] ?? null;
|
||||||
|
if ($val === null || trim((string) $val) === '') {
|
||||||
|
$errors[] = [
|
||||||
|
'field' => 'field_label:' . $cf['field_label'],
|
||||||
|
'message' => rtrim($cf['field_label'], ': ') . ' è obbligatorio.',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $errors;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Logical fixed_field_key - real datadb column (mirrors imported.php $fixedAliasMap)
|
||||||
|
$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',
|
||||||
|
];
|
||||||
|
|
||||||
|
// Fixed keys NOT enforced by the generic mandatory check above:
|
||||||
|
// - ConsegnaRichiesta: handled by its dedicated validator (also checks the date)
|
||||||
|
// - ClienteFornitore / ClienteAnalisi: nullable placeholders, sent as null on
|
||||||
|
// export and accepted by LIMS.
|
||||||
|
$skipRequiredFixed = ['ConsegnaRichiesta', 'ClienteFornitore', 'ClienteAnalisi'];
|
||||||
|
|
||||||
// ── Main ────────────────────────────────────────────────────────────────────
|
// ── Main ────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -104,9 +156,12 @@ try {
|
|||||||
$iddatadbList = array_column($rows, 'iddatadb');
|
$iddatadbList = array_column($rows, 'iddatadb');
|
||||||
$placeholders = implode(',', array_fill(0, count($iddatadbList), '?'));
|
$placeholders = implode(',', array_fill(0, count($iddatadbList), '?'));
|
||||||
|
|
||||||
// Records (datadb) for fixed field validation
|
// Records (datadb) — templateid + fixed-field columns for mandatory validation
|
||||||
$stmt = $pdo->prepare("
|
$stmt = $pdo->prepare("
|
||||||
SELECT iddatadb, consegna_richiesta
|
SELECT iddatadb, templateid, consegna_richiesta,
|
||||||
|
cliente_responsabile_id, moltiplicatore_prezzo_id,
|
||||||
|
anagrafica_certest_object_id, anagrafica_certest_service_id,
|
||||||
|
cliente_fornitore_id, clienteAnalisi
|
||||||
FROM datadb
|
FROM datadb
|
||||||
WHERE iddatadb IN ($placeholders)
|
WHERE iddatadb IN ($placeholders)
|
||||||
");
|
");
|
||||||
@@ -128,6 +183,62 @@ try {
|
|||||||
$partsInfo[(int)$r['iddatadb']][] = $r;
|
$partsInfo[(int)$r['iddatadb']][] = $r;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Mandatory-field config per template
|
||||||
|
$templateIds = array_values(array_unique(array_filter(array_map(
|
||||||
|
fn ($r) => (int)($r['templateid'] ?? 0),
|
||||||
|
$recordsInfo
|
||||||
|
))));
|
||||||
|
|
||||||
|
$requiredFixedByTemplate = []; // template_id => [ fixed_field_key => label ]
|
||||||
|
$requiredCustomByTemplate = []; // template_id => [ { mapping_id, field_label }, ... ]
|
||||||
|
|
||||||
|
if (!empty($templateIds)) {
|
||||||
|
$tplPlaceholders = implode(',', array_fill(0, count($templateIds), '?'));
|
||||||
|
|
||||||
|
// Required fixed fields (is_required synced from LIMS ObbligatorioWeb)
|
||||||
|
$stmt = $pdo->prepare("
|
||||||
|
SELECT template_id, fixed_field_key
|
||||||
|
FROM template_fixed_mapping
|
||||||
|
WHERE template_id IN ($tplPlaceholders) AND is_required = 1
|
||||||
|
");
|
||||||
|
$stmt->execute($templateIds);
|
||||||
|
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $r) {
|
||||||
|
$key = $r['fixed_field_key'];
|
||||||
|
if (in_array($key, $skipRequiredFixed, true)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
$requiredFixedByTemplate[(int)$r['template_id']][$key] = $key;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Required custom fields that are visible in the import grid
|
||||||
|
$stmt = $pdo->prepare("
|
||||||
|
SELECT id AS mapping_id, template_id, field_label
|
||||||
|
FROM template_mapping
|
||||||
|
WHERE template_id IN ($tplPlaceholders)
|
||||||
|
AND is_required = 1
|
||||||
|
AND is_visible_import = 1
|
||||||
|
");
|
||||||
|
$stmt->execute($templateIds);
|
||||||
|
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $r) {
|
||||||
|
$requiredCustomByTemplate[(int)$r['template_id']][] = [
|
||||||
|
'mapping_id' => (int)$r['mapping_id'],
|
||||||
|
'field_label' => $r['field_label'],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Custom field values per record (import_data_details.id is the FK to datadb)
|
||||||
|
$stmt = $pdo->prepare("
|
||||||
|
SELECT id AS iddatadb, mapping_id, field_value
|
||||||
|
FROM import_data_details
|
||||||
|
WHERE id IN ($placeholders)
|
||||||
|
");
|
||||||
|
$stmt->execute($iddatadbList);
|
||||||
|
$customValuesByRecord = []; // iddatadb => [ mapping_id => field_value ]
|
||||||
|
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $r) {
|
||||||
|
$customValuesByRecord[(int)$r['iddatadb']][(int)$r['mapping_id']] = $r['field_value'];
|
||||||
|
}
|
||||||
|
|
||||||
// ── Run validators per row ──────────────────────────────────────────────
|
// ── Run validators per row ──────────────────────────────────────────────
|
||||||
|
|
||||||
$results = [];
|
$results = [];
|
||||||
@@ -137,9 +248,15 @@ try {
|
|||||||
$index = $rowInfo['index'];
|
$index = $rowInfo['index'];
|
||||||
|
|
||||||
// Build context for validators
|
// Build context for validators
|
||||||
|
$record = $recordsInfo[$iddatadb] ?? null;
|
||||||
|
$templateId = (int)($record['templateid'] ?? 0);
|
||||||
$ctx = [
|
$ctx = [
|
||||||
'record' => $recordsInfo[$iddatadb] ?? null,
|
'record' => $record,
|
||||||
'parts' => $partsInfo[$iddatadb] ?? [],
|
'parts' => $partsInfo[$iddatadb] ?? [],
|
||||||
|
'fixedAliasMap' => $fixedAliasMap,
|
||||||
|
'requiredFixed' => $requiredFixedByTemplate[$templateId] ?? [],
|
||||||
|
'requiredCustom' => $requiredCustomByTemplate[$templateId] ?? [],
|
||||||
|
'customValues' => $customValuesByRecord[$iddatadb] ?? [],
|
||||||
];
|
];
|
||||||
|
|
||||||
$errors = [];
|
$errors = [];
|
||||||
|
|||||||
Reference in New Issue
Block a user