matrici cache

This commit is contained in:
r.mubarakzyanov 2026-03-31 14:25:10 +03:00
parent d983659000
commit d24836e2b1
5 changed files with 187 additions and 111 deletions

View File

@ -0,0 +1,43 @@
<?php
require_once dirname(__DIR__, 2) . '/vendor/autoload.php';
require_once __DIR__ . '/class/VisualLimsApiClient.class.php';
header('Content-Type: application/json');
ini_set('display_errors', '0');
error_reporting(E_ALL);
try {
// Cache file (1 hour TTL)
$cacheFile = __DIR__ . '/cache/matrici.json';
if (file_exists($cacheFile) && (time() - filemtime($cacheFile) < 3600)) {
readfile($cacheFile);
exit;
}
$api = VisualLimsApiClient::getInstance();
$data = $api->get('Matrice');
$matrici = [];
if (isset($data['value']) && is_array($data['value'])) {
foreach ($data['value'] as $item) {
$nome = $item['NomeMatrice'] ?? '';
if ($nome !== '' && substr($nome, 0, 1) !== '*') {
$matrici[] = [
'IdMatrice' => $item['IdMatrice'],
'NomeMatrice' => $nome,
'MacroMatrice' => $item['MacroMatrice'] ?? null,
];
}
}
usort($matrici, fn($a, $b) => strcasecmp($a['NomeMatrice'], $b['NomeMatrice']));
}
$json = json_encode(['success' => true, 'value' => $matrici]);
if (!is_dir(__DIR__ . '/cache')) mkdir(__DIR__ . '/cache', 0777, true);
file_put_contents($cacheFile, $json);
echo $json;
} catch (Exception $e) {
http_response_code(500);
echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}

View File

@ -143,7 +143,7 @@ $(document).ready(function () {
if (iddatadb) {
if (matrici.length === 0) {
$.ajax({
url: "get_matrici_db.php",
url: "get_matrici.php",
method: "GET",
dataType: "json",
success: function (data) {

View File

@ -344,7 +344,7 @@ $(document).ready(function () {
if (iddatadb) {
if (matrici.length === 0) {
$.ajax({
url: "get_matrici_db.php",
url: "get_matrici.php",
method: "GET",
dataType: "json",
success: function (data) {
@ -1615,18 +1615,6 @@ $(document).ready(function () {
return;
}
// Filtra le matrici in base alla MacroMatrice selezionata
const filteredMatrici = selectedMacro
? matrici.filter(
(matrice) => matrice.MacroMatrice === selectedMacro,
)
: matrici;
// Crea opzioni per Select2
const options = filteredMatrici.map(function (matrice) {
return { id: matrice.IdMatrice, text: matrice.NomeMatrice };
});
// Memorizza il valore corrente
const currentValue = $select.val();
@ -1635,39 +1623,39 @@ $(document).ready(function () {
$select.select2("destroy");
}
// Inizializza Select2
// Inizializza Select2 con AJAX
$select.empty().select2({
placeholder: filteredMatrici.length
? "Seleziona matrice globale"
: "Nessuna matrice disponibile",
placeholder: "Seleziona matrice globale",
allowClear: true,
data: options,
dropdownParent: $("#partsModal"),
minimumResultsForSearch: 0, // Abilita ricerca senza limite minimo di caratteri
matcher: function (params, data) {
if (!params.term) return data; // Mostra tutte le opzioni se non c'è termine di ricerca
const term = params.term.toUpperCase();
if (data.text.toUpperCase().indexOf(term) >= 0) return data;
return null;
minimumInputLength: 0,
ajax: {
url: "search_matrici.php",
dataType: "json",
delay: 150,
data: function (params) {
return { q: params.term || "", limit: 20, macro: selectedMacro || "" };
},
processResults: function (data) {
return { results: data.results || [] };
},
cache: true,
},
});
// Ripristina il valore corrente se valido
if (
currentValue &&
filteredMatrici.some((m) => m.IdMatrice == currentValue)
) {
$select.val(currentValue).trigger("change");
} else if (filteredMatrici.length === 0) {
const errorMsg = $(
'<div class="alert alert-warning temp-alert" role="alert">Nessuna matrice disponibile per la MacroMatrice selezionata.</div>',
);
$("#partsModal .modal-body").prepend(errorMsg);
setTimeout(function () {
errorMsg.fadeOut(500, function () {
$(this).remove();
});
}, 5000);
// Ripristina il valore corrente
if (currentValue) {
$.ajax({
url: "search_matrici.php",
data: { id: currentValue },
dataType: "json",
}).then(function (data) {
const item = (data.results || [])[0];
if (item) {
const option = new Option(item.text, item.id, true, true);
$select.append(option).trigger("change");
}
});
}
}
@ -1686,32 +1674,6 @@ $(document).ready(function () {
return;
}
// Filtra le matrici in base alla MacroMatrice selezionata
const filteredMatrici = selectedMacro
? matrici.filter((m) => m.MacroMatrice === selectedMacro)
: matrici;
// Crea opzioni per Select2, includendo il valore pre-selezionato se non è nel filtro
let options = filteredMatrici.map(function (matrice) {
return { id: matrice.IdMatrice, text: matrice.NomeMatrice };
});
// Se idmatrice esiste ed è fuori dal filtro, aggiungilo come opzione
if (
idmatrice &&
!filteredMatrici.some((m) => m.IdMatrice == idmatrice)
) {
const selectedMatrice = matrici.find(
(m) => m.IdMatrice == idmatrice,
);
if (selectedMatrice) {
options.push({
id: selectedMatrice.IdMatrice,
text: selectedMatrice.NomeMatrice,
});
}
}
// Memorizza il valore corrente
const currentValue = idmatrice || $select.val();
@ -1720,44 +1682,44 @@ $(document).ready(function () {
$select.select2("destroy");
}
// Inizializza Select2
// Inizializza Select2 con AJAX
$select.empty().select2({
placeholder: filteredMatrici.length
? "Seleziona matrice"
: "Nessuna matrice disponibile",
placeholder: "Seleziona matrice",
allowClear: true,
data: options,
dropdownParent: $("#partsModal"),
minimumResultsForSearch: 0, // Abilita ricerca senza limite minimo di caratteri
matcher: function (params, data) {
if (!params.term) return data; // Mostra tutte le opzioni se non c'è termine di ricerca
const term = params.term.toUpperCase();
if (data.text.toUpperCase().indexOf(term) >= 0) return data;
return null;
minimumInputLength: 0,
ajax: {
url: "search_matrici.php",
dataType: "json",
delay: 150,
data: function (params) {
return { q: params.term || "", limit: 20, macro: selectedMacro || "" };
},
processResults: function (data) {
return { results: data.results || [] };
},
cache: true,
},
});
// Ripristina il valore se valido
if (partId && partId !== "new" && currentValue) {
const matrice = matrici.find((m) => m.IdMatrice == currentValue);
if (matrice) {
const option = new Option(
matrice.NomeMatrice,
matrice.IdMatrice,
true,
true,
);
if (!fromFilter) $select.append(option).trigger("change");
else $select.append(option);
partMatrice[partNumber] = matrice.IdMatrice;
} else {
// Aggiusta valore non valido
if (!fromFilter) $select.val(null).trigger("change");
partMatrice[partNumber] = null;
}
$.ajax({
url: "search_matrici.php",
data: { id: currentValue },
dataType: "json",
}).then(function (data) {
const item = (data.results || [])[0];
if (item) {
const option = new Option(item.text, item.id, true, true);
if (!fromFilter) $select.append(option).trigger("change");
else $select.append(option);
partMatrice[partNumber] = item.id;
} else {
if (!fromFilter) $select.val(null).trigger("change");
partMatrice[partNumber] = null;
}
});
} else {
$select.val(null).trigger("change", [{ skipHandler: true }]);
}
@ -1834,18 +1796,7 @@ $(document).ready(function () {
}
});
// Mostra messaggio se non ci sono matrici
if (filteredMatrici.length === 0 && selectedMacro) {
const errorMsg = $(
'<div class="alert alert-warning temp-alert" role="alert">Nessuna matrice disponibile per la MacroMatrice selezionata.</div>',
);
$("#partsModal .modal-body").prepend(errorMsg);
setTimeout(function () {
errorMsg.fadeOut(500, function () {
$(this).remove();
});
}, 5000);
}
// Messaggio se macro selezionata ma nessun risultato sarà gestito dal placeholder Select2
// Debug per verificare inizializzazione
console.log(
@ -1861,8 +1812,13 @@ $(document).ready(function () {
$(document).on("click", ".propagate-matrice-btn", function () {
const $row = $(this).closest("tr");
const globalVal = $("#global-matrice").val();
const globalText = $("#global-matrice").find("option:selected").text();
if (globalVal) {
$row.find(".part-matrice").val(globalVal).trigger("change");
const $target = $row.find(".part-matrice");
if (!$target.find(`option[value="${globalVal}"]`).length) {
$target.append(new Option(globalText, globalVal, true, true));
}
$target.val(globalVal).trigger("change");
} else {
const errorMsg = $(
'<div class="alert alert-danger temp-alert" role="alert">Seleziona una matrice globale prima di propagare.</div>',
@ -1878,8 +1834,15 @@ $(document).ready(function () {
$(document).on("click", ".propagate-all-btn", function () {
const globalVal = $("#global-matrice").val();
const globalText = $("#global-matrice").find("option:selected").text();
if (globalVal) {
$("#partsTableBody .part-matrice").val(globalVal).trigger("change");
$("#partsTableBody .part-matrice").each(function () {
const $target = $(this);
if (!$target.find(`option[value="${globalVal}"]`).length) {
$target.append(new Option(globalText, globalVal, true, true));
}
$target.val(globalVal).trigger("change");
});
} else {
const errorMsg = $(
'<div class="alert alert-danger temp-alert" role="alert">Seleziona una matrice globale prima di propagare.</div>',

View File

@ -0,0 +1,56 @@
<?php
header('Content-Type: application/json');
ini_set('display_errors', '0');
$q = mb_strtolower(trim($_GET['q'] ?? ''));
$id = isset($_GET['id']) ? intval($_GET['id']) : null;
$limit = max(1, min(50, intval($_GET['limit'] ?? 20)));
$macro = trim($_GET['macro'] ?? '');
$cacheFile = __DIR__ . '/cache/matrici.json';
if (!file_exists($cacheFile)) {
// Trigger cache creation
require_once dirname(__DIR__, 2) . '/vendor/autoload.php';
require_once __DIR__ . '/class/VisualLimsApiClient.class.php';
$api = VisualLimsApiClient::getInstance();
$data = $api->get('Matrice');
$matrici = [];
foreach (($data['value'] ?? []) as $item) {
$nome = $item['NomeMatrice'] ?? '';
if ($nome !== '' && substr($nome, 0, 1) !== '*') {
$matrici[] = ['IdMatrice' => $item['IdMatrice'], 'NomeMatrice' => $nome, 'MacroMatrice' => $item['MacroMatrice'] ?? null];
}
}
usort($matrici, fn($a, $b) => strcasecmp($a['NomeMatrice'], $b['NomeMatrice']));
if (!is_dir(__DIR__ . '/cache')) mkdir(__DIR__ . '/cache', 0777, true);
file_put_contents($cacheFile, json_encode(['success' => true, 'value' => $matrici]));
} else {
$cached = json_decode(file_get_contents($cacheFile), true);
$matrici = $cached['value'] ?? [];
}
// Lookup by ID
if ($id !== null) {
foreach ($matrici as $m) {
if ((int)$m['IdMatrice'] === $id) {
echo json_encode(['results' => [['id' => $m['IdMatrice'], 'text' => $m['NomeMatrice']]]]);
exit;
}
}
echo json_encode(['results' => []]);
exit;
}
// Search (with optional MacroMatrice filter)
$results = [];
foreach ($matrici as $m) {
$nome = $m['NomeMatrice'] ?? '';
if ($macro !== '' && ($m['MacroMatrice'] ?? '') !== $macro) continue;
if ($q === '' || mb_strpos(mb_strtolower($nome), $q) !== false) {
$results[] = ['id' => $m['IdMatrice'], 'text' => $nome];
if (count($results) >= $limit) break;
}
}
echo json_encode(['results' => $results]);

View File

@ -98,6 +98,20 @@ try {
}
}
// 5. Matrici (from LIMS API)
warmLog('[matrici] Fetching from API...', $isCli);
$matriciData = $api->get('Matrice');
$matrici = [];
foreach (($matriciData['value'] ?? []) as $item) {
$nome = $item['NomeMatrice'] ?? '';
if ($nome !== '' && substr($nome, 0, 1) !== '*') {
$matrici[] = ['IdMatrice' => $item['IdMatrice'], 'NomeMatrice' => $nome, 'MacroMatrice' => $item['MacroMatrice'] ?? null];
}
}
usort($matrici, fn($a, $b) => strcasecmp($a['NomeMatrice'], $b['NomeMatrice']));
file_put_contents($cacheDir . '/matrici.json', json_encode(['success' => true, 'value' => $matrici]));
warmLog("[matrici] Cached " . count($matrici) . " items", $isCli);
$elapsed = round(microtime(true) - $startTime, 1);
warmLog("Done in {$elapsed}s", $isCli);