Compare commits

...
Author SHA1 Message Date
RMubarakzyanov 233a1b3678 duplicate guard 2026-10-02 14:06:44 +03:00
solocla 65608712ad fixed clone parts 2026-09-30 17:26:56 +02:00
solocla 6a7a56cd0f fixed resize column 2026-09-29 08:46:25 +02:00
solocla f31ba24008 email send afetr export routine 2026-09-23 11:40:57 +02:00
solocla bb2ebcc122 fixed export to lims 2026-09-22 15:27:35 +02:00
solocla 955c760756 Stop tracking runtime files (error_log, schemi_base_response, logs, uploads) 2026-09-22 14:08:27 +02:00
solocla 5c12d97d0e added error page and logs linked 2026-09-22 13:58:14 +02:00
solocla 9bed740223 added log step 9 2026-09-22 12:13:02 +02:00
solocla 8be7ea0b85 fixed2 clientefatturazione 2026-09-18 07:59:49 +02:00
solocla dc0209dcf1 removed clientefatturazione on export 2026-09-16 10:12:58 +02:00
solocla 9cce361b90 added clientefatturazione 2026-09-16 09:22:08 +02:00
solocla c966096060 analysis in alphabetical order 2026-09-16 08:20:26 +02:00
solocla 55da10cea4 fixed routine error 2026-09-14 16:58:27 +02:00
solocla 0d3ed2505f fixed note with slash 2026-09-08 10:29:45 +02:00
solocla def7377447 fixed sticky bars with toggle 2026-09-08 09:18:17 +02:00
solocla 9453e7a01a sticky action button on topbar 2026-09-08 08:48:26 +02:00
solocla 8f4ac3d53e added routine engine 2026-09-05 13:41:26 +02:00
solocla 34f7490e94 session keep alive 2026-09-05 13:41:26 +02:00
solocla d9d6a7ab58 cambiato ttl warm cache 2026-09-05 13:41:26 +02:00
solocla 14a7cc2738 revert stats_export files to pre-a1e91f8 version 2026-08-04 20:10:27 +02:00
solocla 601e72ca61 fixed quotations parts 2026-08-04 20:02:50 +02:00
solocla 54c164478c fixed import XLS big 2026-08-04 14:42:05 +02:00
solocla 965d2fa5bb sticky bar import XLS 2026-08-04 14:21:14 +02:00
solocla a1e91f8d76 fixed stats with comeesaa campioni 2026-08-04 12:57:00 +02:00
solocla 153cdbca98 filter analysis withput NominativoCliente 2026-08-03 12:00:37 +02:00
solocla 2603c86c5b exlcuded login time and date from validation 2026-07-30 17:07:47 +02:00
solocla e7d733a136 fixed order lines 2026-07-30 13:18:27 +02:00
solocla eb34cba7bb added search on add fields ranking 2026-07-29 16:37:58 +02:00
solocla f01bfa06c9 fixed exxcel row column 2026-07-29 12:24:58 +02:00
solocla 71d6fe1d98 fixed sample arrival and date 2026-07-23 16:00:26 +02:00
solocla 33615f65d7 Merge branch 'filter' 2026-07-23 13:09:02 +02:00
solocla 7b6d85766d change migration 2026-07-23 12:18:56 +02:00
solocla b2a79aec1b multiple analysis on same parts 2026-07-23 12:13:28 +02:00
solocla a300932421 fixed field object search ranking 2026-07-22 14:04:50 +02:00
solocla df1ddce0a6 fixed buyer in template 2026-07-22 12:07:20 +02:00
solocla 0277fb5262 warm cache run 2026-07-22 12:03:39 +02:00
solocla 0407bcdcc4 Add row included in clone and navigation parts 2026-07-22 09:33:46 +02:00
solocla b1810211d5 automatic date on part from ConsegnaRichiesta 2026-07-22 09:00:08 +02:00
solocla 48d775f4d5 sample unlock date time copy paste on arrival 2026-07-22 08:47:59 +02:00
solocla bd9bd52c10 fixed modal analysis name matrix 2026-07-20 15:48:29 +02:00
solocla 9dda4630a4 fixed modal analysis 2026-07-20 15:41:29 +02:00
solocla 6d0b98bd41 analysis fixed matrix 2026-07-20 15:21:20 +02:00
solocla 7db96a1f9c fixed matrix in analysis 2026-07-20 15:18:29 +02:00
solocla 699bffaa78 ranking custom field 2026-07-20 11:32:22 +02:00
solocla e92e107a3c search by ranking custom field 2026-07-20 11:30:26 +02:00
solocla 9330a49008 fixed stats 2 2026-07-20 10:58:12 +02:00
solocla 80dbd26929 fixed stats 2026-07-20 10:47:54 +02:00
RMubarakzyanov 69bb029d9d union ids 2026-07-19 14:23:23 +03:00
RMubarakzyanov c3f3e824dc server side filtering and ui-fixes 2026-07-19 13:05:00 +03:00
solocla 05356fc98b readded clona parti 2026-07-17 13:58:50 +02:00
solocla 232f8244bf fixed dirty rows 2026-07-17 11:01:51 +02:00
solocla 1107e003f8 update stats monthly 2026-07-17 10:53:31 +02:00
solocla c2fd2dc470 fixed export and save to selection 2026-07-17 10:46:33 +02:00
solocla 86b1c8420d fixed rebuild grid 2026-07-17 09:30:55 +02:00
solocla 1b5dd04740 Merge branch 'salvataggio-manuale-parts' into filter 2026-07-17 09:20:09 +02:00
solocla ff676376ab fixed filter 2026-07-17 09:19:23 +02:00
solocla 1a47d5649a filter on imported 2026-07-17 09:17:44 +02:00
solocla 05f5722ebd navbar update 2026-07-16 14:43:37 +02:00
solocla 546b4ced69 update stats e nota template 2026-07-16 14:34:09 +02:00
solocla d256370712 asterisc analysis 2026-07-16 13:53:53 +02:00
91 changed files with 9487 additions and 2149 deletions
+10
View File
@@ -62,3 +62,13 @@ public/userarea/schemi_base_response.json
public/userarea/cache/
public/userarea/error_log.txt
# PDF/QR generati dai template (userarea)
/public/userarea/pdftemplates/
# Runtime / rigenerati - non tracciare
public/userarea/error_log.txt
public/userarea/schemi_base_response.json
public/userarea/logs/
public/userarea/imported_trf/
public/userarea/xlstemplates/
.well-known/
+1 -1
View File
@@ -41,7 +41,7 @@
"laravel/socialite": "^5.16",
"laravel/tinker": "^2.7",
"laravel/ui": "^4.0",
"phpmailer/phpmailer": "^6.9",
"phpmailer/phpmailer": "^7.1",
"phpoffice/phpspreadsheet": "^4.1",
"proengsoft/laravel-jsvalidation": "^4.0.0",
"robmorgan/phinx": "^0.16.12",
Generated
+11 -10
View File
@@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "557df76fdde549210349be369d479f5d",
"content-hash": "e54cf3e0bbc04b94b563b01620ac3416",
"packages": [
{
"name": "akaunting/laravel-setting",
@@ -4166,16 +4166,16 @@
},
{
"name": "phpmailer/phpmailer",
"version": "v6.9.3",
"version": "v7.1.1",
"source": {
"type": "git",
"url": "https://github.com/PHPMailer/PHPMailer.git",
"reference": "2f5c94fe7493efc213f643c23b1b1c249d40f47e"
"reference": "1bc1716a507a65e039d4ac9d9adebbbd0d346e15"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/PHPMailer/PHPMailer/zipball/2f5c94fe7493efc213f643c23b1b1c249d40f47e",
"reference": "2f5c94fe7493efc213f643c23b1b1c249d40f47e",
"url": "https://api.github.com/repos/PHPMailer/PHPMailer/zipball/1bc1716a507a65e039d4ac9d9adebbbd0d346e15",
"reference": "1bc1716a507a65e039d4ac9d9adebbbd0d346e15",
"shasum": ""
},
"require": {
@@ -4189,13 +4189,14 @@
"doctrine/annotations": "^1.2.6 || ^1.13.3",
"php-parallel-lint/php-console-highlighter": "^1.0.0",
"php-parallel-lint/php-parallel-lint": "^1.3.2",
"phpcompatibility/php-compatibility": "^9.3.5",
"roave/security-advisories": "dev-latest",
"squizlabs/php_codesniffer": "^3.7.2",
"phpcompatibility/php-compatibility": "^10.0.0@dev",
"squizlabs/php_codesniffer": "^3.13.5",
"yoast/phpunit-polyfills": "^1.0.4"
},
"suggest": {
"decomplexity/SendOauth2": "Adapter for using XOAUTH2 authentication",
"directorytree/imapengine": "For uploading sent messages via IMAP, see gmail example",
"ext-imap": "Needed to support advanced email address parsing according to RFC822",
"ext-mbstring": "Needed to send email in multibyte encoding charset or decode encoded addresses",
"ext-openssl": "Needed for secure SMTP sending and DKIM signing",
"greew/oauth2-azure-provider": "Needed for Microsoft Azure XOAUTH2 authentication",
@@ -4235,7 +4236,7 @@
"description": "PHPMailer is a full-featured email creation and transfer class for PHP",
"support": {
"issues": "https://github.com/PHPMailer/PHPMailer/issues",
"source": "https://github.com/PHPMailer/PHPMailer/tree/v6.9.3"
"source": "https://github.com/PHPMailer/PHPMailer/tree/v7.1.1"
},
"funding": [
{
@@ -4243,7 +4244,7 @@
"type": "github"
}
],
"time": "2024-11-24T18:04:13+00:00"
"time": "2026-05-18T08:06:14+00:00"
},
{
"name": "phpoffice/phpspreadsheet",
@@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
use Phinx\Migration\AbstractMigration;
final class AddTemplateNoteToExcelTemplates extends AbstractMigration
{
public function change(): void
{
$this->table('excel_templates')
->addColumn('template_note', 'text', [
'null' => true,
'default' => null,
'after' => 'idroutine',
'comment' => 'Nota opzionale del template, aggiunta in fondo alle note in esportazione',
])
->update();
}
}
@@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
use Phinx\Migration\AbstractMigration;
final class DropUniqPartAnalysisIndex extends AbstractMigration
{
public function up(): void
{
$table = $this->table('identification_parts_analyses');
if ($table->hasIndexByName('uniq_part_analysis')) {
$table->removeIndexByName('uniq_part_analysis')->update();
}
}
public function down(): void
{
$table = $this->table('identification_parts_analyses');
if (!$table->hasIndexByName('uniq_part_analysis')) {
$table->addIndex(['part_id', 'analysis_recordkey'], [
'unique' => true,
'name' => 'uniq_part_analysis',
])->update();
}
}
}
@@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
use Phinx\Migration\AbstractMigration;
final class ChangeExcelrowToVarchar extends AbstractMigration
{
public function up(): void
{
$this->table('datadb')
->changeColumn('excelrow', 'string', [
'limit' => 100,
'null' => true,
])
->update();
}
public function down(): void
{
$this->table('datadb')
->changeColumn('excelrow', 'integer', [
'null' => true,
])
->update();
}
}
@@ -0,0 +1,68 @@
<?php
declare(strict_types=1);
use Phinx\Migration\AbstractMigration;
/**
* Aggiunge il flag `engine` alla tabella `routine` esistente (0 = legacy su file,
* 1 = motore generico basato su routine_step) e crea la tabella `routine_step`.
*
* Migrazione puramente additiva: le routine legacy esistenti (id 1..4) restano
* intatte e con engine = 0 continuano a funzionare come prima.
*/
final class AddEngineAndRoutineStep extends AbstractMigration
{
public function change(): void
{
// 1) Flag engine sulla tabella esistente `routine`
$routine = $this->table('routine');
if (!$routine->hasColumn('engine')) {
$routine
->addColumn('engine', 'boolean', [
'default' => 0,
'null' => false,
'comment' => '0 = routine legacy su file, 1 = motore generico (routine_step)',
'after' => 'filename',
])
->update();
}
// 2) Nuova tabella routine_step
if (!$this->hasTable('routine_step')) {
$table = $this->table('routine_step', [
'id' => 'idstep',
'signed' => false,
'engine' => 'InnoDB',
'collation' => 'utf8mb4_general_ci',
]);
$table
->addColumn('idroutine', 'integer', [
'null' => false,
'comment' => 'FK verso routine.idroutine',
])
->addColumn('step_order', 'integer', [
'default' => 1,
'null' => false,
'comment' => 'Ordine di esecuzione dello step nella routine',
])
->addColumn('operation', 'string', [
'limit' => 50,
'null' => false,
'comment' => 'Verbo operazione: merge, replace, trim, copy, clear, uppercase, lowercase',
])
->addColumn('params', 'text', [
'null' => true,
'comment' => 'Parametri operazione in formato JSON',
])
->addColumn('active', 'boolean', [
'default' => 1,
'null' => false,
'comment' => 'Se 0 lo step viene saltato',
])
->addIndex(['idroutine', 'step_order'], ['name' => 'idx_routine_order'])
->create();
}
}
}
@@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
use Phinx\Migration\AbstractMigration;
final class AddLogFileToDatadb extends AbstractMigration
{
public function change(): void
{
$table = $this->table('datadb');
if (!$table->hasColumn('log_file')) {
$table->addColumn('log_file', 'string', [
'limit' => 255,
'null' => true,
'default' => null,
'after' => 'commessaweb', // aggiusta se la colonna non esiste
])->update();
}
}
}
@@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
use Phinx\Migration\AbstractMigration;
final class AddErrorStatusToDatadb extends AbstractMigration
{
public function up(): void
{
// Aggiunge 'x' (errore export) all'enum status, preservando i valori esistenti
$this->execute("ALTER TABLE `datadb`
MODIFY `status` ENUM('i','P','l','x') NULL DEFAULT NULL");
}
public function down(): void
{
// Rollback: riporta le eventuali 'x' a NULL prima di togliere il valore
$this->execute("UPDATE `datadb` SET `status` = NULL WHERE `status` = 'x'");
$this->execute("ALTER TABLE `datadb`
MODIFY `status` ENUM('i','P','l') NULL DEFAULT NULL");
}
}
@@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
use Phinx\Migration\AbstractMigration;
final class AddNotifyExportEmailToAuthUsers extends AbstractMigration
{
public function change(): void
{
$table = $this->table('auth_users');
if (!$table->hasColumn('notify_export_email')) {
$table->addColumn('notify_export_email', 'boolean', [
'default' => true, // di default ricevono la mail
'null' => false,
'after' => 'lims_global_user_id',
])->update();
}
}
}
@@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
use Phinx\Migration\AbstractMigration;
final class AddAnalysisPriceToPartAnalyses extends AbstractMigration
{
public function change(): void
{
$this->table('identification_parts_analyses')
->addColumn('analysis_price', 'decimal', [
'precision' => 10,
'scale' => 2,
'null' => true,
'default' => null,
'after' => 'analysis_level',
])
->update();
}
}
+80
View File
@@ -0,0 +1,80 @@
<?php
declare(strict_types=1);
use Phinx\Seed\AbstractSeed;
/**
* Seed dimostrativo del motore generico.
*
* - Assicura che le routine legacy esistenti abbiano engine = 0 (nessun impatto).
* - Crea una routine di esempio "merge_D_F_H_into_J" con engine = 1
* e il relativo step: unisce le colonne D, F, H nella colonna J.
*
* Nota: filename per le routine engine punta al file motore condiviso _engine.php,
* così apply_routine.php lo risolve correttamente anche se il flusso invia il filename.
*/
final class RoutineEngineSeed extends AbstractSeed
{
public function run(): void
{
$pdo = $this->getAdapter()->getConnection();
// 1) Le legacy restano engine = 0 (idempotente).
$pdo->exec("UPDATE routine SET engine = 0 WHERE engine IS NULL");
// 2) Crea/aggiorna la routine engine di esempio.
$name = 'merge_D_F_H_into_J';
$description = 'Unisce le colonne D, F, H nella colonna J durante l\'importazione';
$filename = '_engine.php';
$check = $pdo->prepare("SELECT idroutine FROM routine WHERE name = :name LIMIT 1");
$check->execute([':name' => $name]);
$existing = $check->fetch(PDO::FETCH_ASSOC);
if ($existing) {
$idroutine = (int)$existing['idroutine'];
$upd = $pdo->prepare(
"UPDATE routine
SET description = :descr, filename = :fn, engine = 1, instruction = :instr
WHERE idroutine = :id"
);
$upd->execute([
':descr' => $description,
':fn' => $filename,
':instr' => 'Routine gestita dal motore generico (routine_step).',
':id' => $idroutine,
]);
} else {
$ins = $pdo->prepare(
"INSERT INTO routine (name, description, instruction, filename, engine, headerrow)
VALUES (:name, :descr, :instr, :fn, 1, 1)"
);
$ins->execute([
':name' => $name,
':descr' => $description,
':instr' => 'Routine gestita dal motore generico (routine_step).',
':fn' => $filename,
]);
$idroutine = (int)$pdo->lastInsertId();
}
// 3) Ripulisci eventuali step precedenti di questa routine e reinserisci.
$del = $pdo->prepare("DELETE FROM routine_step WHERE idroutine = :id");
$del->execute([':id' => $idroutine]);
// Step unico: merge D,F,H -> J. Colonne espresse in lettere per leggibilità.
$params = json_encode([
'source_columns' => ['D', 'F', 'H'],
'target_column' => 'J',
'separator' => ' ',
'skip_empty' => true,
], JSON_UNESCAPED_UNICODE);
$insStep = $pdo->prepare(
"INSERT INTO routine_step (idroutine, step_order, operation, params, active)
VALUES (:id, 1, 'merge', :params, 1)"
);
$insStep->execute([':id' => $idroutine, ':params' => $params]);
}
}
+99 -40
View File
@@ -7,7 +7,7 @@
function loadAnalysisMatrixNames() {
return $.ajax({
url: "get_matrici_db.php",
url: "search_matrici.php?full_list=1",
method: "GET",
dataType: "json",
})
@@ -106,8 +106,9 @@
}
container.innerHTML = items
.map(function (item) {
.map(function (item, index) {
const recordKey = item.analysis_recordkey || "";
const rowId = item.id != null ? item.id : "";
const title = item.analysis_name || "Unnamed analysis";
const method = item.analysis_method || "";
@@ -121,6 +122,8 @@
class="analysis-remove-btn"
data-part-id="${escapeHtml(partId)}"
data-recordkey="${escapeHtml(recordKey)}"
data-row-id="${escapeHtml(rowId)}"
data-index="${index}"
title="Remove analysis">×</button>
</div>
`;
@@ -163,22 +166,25 @@
is_web_selectable: rowEl.getAttribute("data-web") === "1" ? 1 : 0,
is_accredited:
rowEl.getAttribute("data-accredited") === "1" ? 1 : 0,
analysis_price: rowEl.getAttribute("data-price") || "0",
};
}
function addAnalysisToLocalState(partId, payload, iddatadb, idmatrice) {
function addAnalysisToLocalState(
partId,
payload,
iddatadb,
idmatrice,
newId,
) {
const key = String(partId);
if (!Array.isArray(analysisAssignedState[key])) {
analysisAssignedState[key] = [];
}
const exists = analysisAssignedState[key].some(function (item) {
return item.analysis_recordkey === payload.analysis_recordkey;
});
if (!exists) {
{
analysisAssignedState[key].push({
id: null,
id: newId || null,
part_id: parseInt(partId, 10),
iddatadb: iddatadb || null,
idmatrice: idmatrice || null,
@@ -191,21 +197,32 @@
: null,
is_web_selectable: payload.is_web_selectable,
is_accredited: payload.is_accredited,
analysis_price:
payload.analysis_price !== ""
? parseFloat(payload.analysis_price)
: null,
});
}
}
function removeAnalysisFromLocalState(partId, recordKey) {
function removeAnalysisFromLocalState(partId, recordKey, index) {
const key = String(partId);
if (!Array.isArray(analysisAssignedState[key])) {
return;
}
analysisAssignedState[key] = analysisAssignedState[key].filter(
function (item) {
return item.analysis_recordkey !== recordKey;
},
);
const i = parseInt(index, 10);
if (!isNaN(i) && i >= 0 && i < analysisAssignedState[key].length) {
analysisAssignedState[key].splice(i, 1);
return;
}
const found = analysisAssignedState[key].findIndex(function (item) {
return item.analysis_recordkey === recordKey;
});
if (found !== -1) {
analysisAssignedState[key].splice(found, 1);
}
}
function saveAnalysisAssociation(partId, payload, callback) {
@@ -235,14 +252,16 @@
analysis_level: payload.analysis_level,
is_web_selectable: payload.is_web_selectable,
is_accredited: payload.is_accredited,
analysis_price: payload.analysis_price,
},
})
.done(function () {
.done(function (resp) {
addAnalysisToLocalState(
partId,
payload,
iddatadb,
idmatrice !== "NO_MATRIX" ? idmatrice : null,
resp && resp.id ? resp.id : null,
);
renderAssignedAnalysesForPart(partId);
if (typeof callback === "function") callback(true);
@@ -257,7 +276,13 @@
});
}
function deleteAnalysisAssociation(partId, recordKey, callback) {
function deleteAnalysisAssociation(
partId,
recordKey,
rowId,
index,
callback,
) {
$.ajax({
url: "delete_part_analysis.php",
method: "POST",
@@ -265,10 +290,11 @@
data: {
part_id: partId,
analysis_recordkey: recordKey,
row_id: rowId || "",
},
})
.done(function () {
removeAnalysisFromLocalState(partId, recordKey);
removeAnalysisFromLocalState(partId, recordKey, index);
renderAssignedAnalysesForPart(partId);
if (typeof callback === "function") callback(true);
})
@@ -369,6 +395,17 @@
const selectable = item.SelezionabileSuWeb === true;
const accredited = item.Accreditato === true;
const level = item.Livello ?? "";
const rawPrice = item.Prezzo;
const priceNum =
rawPrice === null ||
rawPrice === undefined ||
rawPrice === ""
? 0
: parseFloat(String(rawPrice).replace(",", "."));
const price = isNaN(priceNum) ? 0 : priceNum;
const hasPrice = price > 0;
const searchText = (
analysisName +
" " +
@@ -394,6 +431,10 @@
"</span>";
}
if (!hasPrice) {
badges += '<span class="badge bg-danger">No price</span>';
}
return `
<div
class="list-group-item analysis-analysis-item"
@@ -403,6 +444,7 @@
data-analysis-level="${escapeHtml(level)}"
data-web="${selectable ? "1" : "0"}"
data-accredited="${accredited ? "1" : "0"}"
data-price="${escapeHtml(price)}"
data-search="${escapeHtml(searchText)}"
>
<div class="fw-semibold">${escapeHtml(analysisName)}</div>
@@ -420,7 +462,6 @@
filterAnalysisList();
syncSelectedAnalysisRows();
}
function filterAnalysisList() {
const modal = document.getElementById("analysisModal");
if (!modal) return;
@@ -517,6 +558,13 @@
.done(function (response) {
const analyses = Array.isArray(response.value)
? response.value.filter(function (item) {
const name =
item.NomeAnalisiTraduzione ||
item.NomeAnalisi ||
"";
if (name.trim().startsWith("*")) {
return false;
}
return (
item.SelezionabileSuWeb === true ||
item.SelezionabileSuWeb === 1 ||
@@ -525,6 +573,20 @@
})
: [];
analyses.sort(function (a, b) {
const nameA = (
a.NomeAnalisiTraduzione ||
a.NomeAnalisi ||
""
).toLowerCase();
const nameB = (
b.NomeAnalisiTraduzione ||
b.NomeAnalisi ||
""
).toLowerCase();
return nameA.localeCompare(nameB);
});
analysisLoadedCache[cacheKey] = analyses;
renderAnalysesList(analyses);
})
@@ -700,10 +762,18 @@
const partId = removeBtn.getAttribute("data-part-id");
const recordKey = removeBtn.getAttribute("data-recordkey");
const rowId = removeBtn.getAttribute("data-row-id");
const index = removeBtn.getAttribute("data-index");
deleteAnalysisAssociation(partId, recordKey, function () {
const stillUsed = Object.keys(analysisAssignedState).some(
function (pid) {
deleteAnalysisAssociation(
partId,
recordKey,
rowId,
index,
function () {
const stillUsed = Object.keys(
analysisAssignedState,
).some(function (pid) {
return (
Array.isArray(analysisAssignedState[pid]) &&
analysisAssignedState[pid].some(
@@ -715,15 +785,15 @@
},
)
);
},
);
});
if (!stillUsed) {
delete analysisSelectedState[recordKey];
}
if (!stillUsed) {
delete analysisSelectedState[recordKey];
}
syncSelectedAnalysisRows();
});
syncSelectedAnalysisRows();
},
);
return;
}
@@ -744,17 +814,6 @@
}
const recordKey = payload.analysis_recordkey;
const alreadySelected = !!analysisSelectedState[recordKey];
if (alreadySelected) {
selectedPartIds.forEach(function (partId) {
deleteAnalysisAssociation(partId, recordKey);
});
delete analysisSelectedState[recordKey];
syncSelectedAnalysisRows();
return;
}
let pending = selectedPartIds.length;
let atLeastOneSaved = false;
+40 -2
View File
@@ -21,12 +21,50 @@ try {
throw new Exception("Dati della routine mancanti.");
}
$routineFile = __DIR__ . '/routines/' . $filename;
// --- NUOVO: risolvi la routine dal DB per decidere legacy vs motore ---
// Riusa la connessione PDO del progetto.
require_once __DIR__ . '/class/db-functions.php';
$pdo = DBHandlerSelect::getInstance()->getConnection();
// Identifica la routine: preferisci idroutine se passato, altrimenti risali dal filename.
$idroutine = isset($input['routine_data']['idroutine'])
? (int)$input['routine_data']['idroutine']
: 0;
if ($idroutine > 0) {
$stmt = $pdo->prepare("SELECT idroutine, name, filename, engine FROM routine WHERE idroutine = :id LIMIT 1");
$stmt->execute([':id' => $idroutine]);
} else {
// Il matching per filename è ambiguo per le routine a motore: tutte
// condividono _engine.php. Senza idroutine non possiamo sapere quale
// routine engine applicare -> meglio fermarsi che eseguire quella sbagliata.
if ($filename === '_engine.php') {
throw new Exception("Routine a motore senza idroutine: impossibile determinare quale routine applicare. Verifica che il template inoltri routine_data.idroutine.");
}
$stmt = $pdo->prepare("SELECT idroutine, name, filename, engine FROM routine WHERE filename = :fn LIMIT 1");
$stmt->execute([':fn' => $filename]);
}
$routineRow = $stmt->fetch();
// engine = 1 -> motore generico (_engine.php); 0 o record assente -> legacy come oggi.
$useEngine = $routineRow && (int)$routineRow['engine'] === 1;
if ($useEngine) {
// Il motore ha bisogno di sapere quale routine caricare dagli step.
$routineData['idroutine'] = (int)$routineRow['idroutine'];
$routineData['name'] = $routineData['name'] ?? ($routineRow['name'] ?? '');
$routineFile = __DIR__ . '/routines/_engine.php';
} else {
// Percorso legacy: il vecchio file della routine, identico a prima.
$legacyFilename = $routineRow['filename'] ?? $filename;
$routineFile = __DIR__ . '/routines/' . $legacyFilename;
}
if (file_exists($routineFile)) {
include_once $routineFile;
$routineData['xls_headers'] = $_SESSION['headers'] ?? [];
applyRoutine($excelData, $routineData); // Modifica $excelData in place
error_log("Routine {$routineData['name']} applicata (file: {$filename}) per template {$template_id}, header row: {$headerrow}");
error_log("Routine " . ($routineData['name'] ?? '') . " applicata (" . ($useEngine ? "motore" : "file: {$filename}") . ") per template {$template_id}, header row: {$headerrow}");
} else {
throw new Exception("File della routine non trovato: $routineFile");
}
+50
View File
@@ -0,0 +1,50 @@
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception as PHPMailerException;
require_once __DIR__ . '/../../../vendor/autoload.php'; // aggiusta il path se serve
class Mailer
{
public static function send(array $to, string $subject, string $htmlBody, ?string $altBody = null): array
{
$mail = new PHPMailer(true);
try {
$mail->isSMTP();
$mail->Host = env('MAIL_HOST');
$mail->SMTPAuth = true;
$mail->Username = env('MAIL_USERNAME');
$mail->Password = env('MAIL_PASSWORD');
$mail->Port = (int) env('MAIL_PORT', 465);
$enc = env('MAIL_ENCRYPTION', 'ssl');
$mail->SMTPSecure = ($enc === 'tls')
? PHPMailer::ENCRYPTION_STARTTLS
: PHPMailer::ENCRYPTION_SMTPS;
$mail->CharSet = 'UTF-8';
$mail->setFrom(env('MAIL_FROM_ADDRESS'), env('MAIL_FROM_NAME', 'SmartTRF'));
foreach ($to as $addr) {
$addr = trim((string)$addr);
if ($addr !== '' && filter_var($addr, FILTER_VALIDATE_EMAIL)) {
$mail->addAddress($addr);
}
}
if (!$mail->getToAddresses()) {
return ['ok' => false, 'error' => 'Nessun destinatario valido'];
}
$mail->isHTML(true);
$mail->Subject = $subject;
$mail->Body = $htmlBody;
$mail->AltBody = $altBody ?: strip_tags($htmlBody);
$mail->send();
return ['ok' => true, 'error' => null];
} catch (PHPMailerException $e) {
error_log('Mailer error: ' . $mail->ErrorInfo);
return ['ok' => false, 'error' => $mail->ErrorInfo];
}
}
}
+27 -3
View File
@@ -14,6 +14,7 @@ $targetList = $data['target_iddatadb_list'] ?? [];
// (comportamento di default richiesto, coerente con la checkbox pre-spuntata)
$cloneNotes = array_key_exists('clone_notes', $data) ? !empty($data['clone_notes']) : true;
$cloneAnalyses = !empty($data['clone_analyses']);
$overwrite = !empty($data['overwrite']);
$targetIds = array_values(array_unique(array_filter(array_map('intval', (array)$targetList), function ($v) use ($sourceIddatadb) {
return $v > 0 && $v !== $sourceIddatadb;
@@ -68,7 +69,7 @@ try {
$stmtLoadAnalyses = $pdo->prepare("
SELECT idmatrice, analysis_recordkey, analysis_name, analysis_method,
analysis_level, is_web_selectable, is_accredited
analysis_level, analysis_price, is_web_selectable, is_accredited
FROM identification_parts_analyses
WHERE part_id = ?
ORDER BY id ASC
@@ -77,10 +78,10 @@ try {
$stmtInsertAnalysis = $pdo->prepare("
INSERT INTO identification_parts_analyses
(part_id, iddatadb, idmatrice, analysis_recordkey, analysis_name, analysis_method,
analysis_level, is_web_selectable, is_accredited, created_at, updated_at)
analysis_level, analysis_price, is_web_selectable, is_accredited, created_at, updated_at)
VALUES
(:part_id, :iddatadb, :idmatrice, :analysis_recordkey, :analysis_name, :analysis_method,
:analysis_level, :is_web_selectable, :is_accredited, NOW(), NOW())
:analysis_level, :analysis_price, :is_web_selectable, :is_accredited, NOW(), NOW())
");
$stmtInsertCF = $pdo->prepare("
@@ -93,6 +94,28 @@ try {
$details = [];
$totalClonedParts = 0;
$totalClonedAnalyses = 0;
$totalDeletedParts = 0;
// 2b. Se overwrite: elimina le parti esistenti dei target (e i loro figli)
if ($overwrite) {
$stmtSelectExisting = $pdo->prepare("SELECT id FROM identification_parts WHERE iddatadb = ?");
$stmtDeleteCFByPart = $pdo->prepare("DELETE FROM identification_parts_customfields WHERE part_id = ?");
$stmtDeleteAnByPart = $pdo->prepare("DELETE FROM identification_parts_analyses WHERE part_id = ?");
$stmtDeletePart = $pdo->prepare("DELETE FROM identification_parts WHERE id = ?");
foreach ($targetIds as $targetIddatadb) {
$stmtSelectExisting->execute([$targetIddatadb]);
$existingIds = $stmtSelectExisting->fetchAll(PDO::FETCH_COLUMN);
foreach ($existingIds as $existingPartId) {
$existingPartId = (int)$existingPartId;
$stmtDeleteCFByPart->execute([$existingPartId]);
$stmtDeleteAnByPart->execute([$existingPartId]);
$stmtDeletePart->execute([$existingPartId]);
$totalDeletedParts++;
}
}
}
// 3. Clone source parts to each target record
foreach ($targetIds as $targetIddatadb) {
@@ -138,6 +161,7 @@ try {
':analysis_name' => $an['analysis_name'] ?? null,
':analysis_method' => $an['analysis_method'] ?? null,
':analysis_level' => ($an['analysis_level'] !== null && $an['analysis_level'] !== '') ? (int)$an['analysis_level'] : null,
':analysis_price' => ($an['analysis_price'] !== null && $an['analysis_price'] !== '') ? $an['analysis_price'] : null,
':is_web_selectable' => (int)($an['is_web_selectable'] ?? 0),
':is_accredited' => (int)($an['is_accredited'] ?? 0),
]);
+25 -10
View File
@@ -15,8 +15,9 @@ try {
$partId = isset($_POST['part_id']) ? (int)$_POST['part_id'] : 0;
$analysisRecordkey = trim($_POST['analysis_recordkey'] ?? '');
$rowId = isset($_POST['row_id']) && $_POST['row_id'] !== '' ? (int)$_POST['row_id'] : 0;
if ($partId <= 0 || $analysisRecordkey === '') {
if ($partId <= 0 || ($analysisRecordkey === '' && $rowId <= 0)) {
http_response_code(400);
echo json_encode(['success' => false, 'message' => 'Missing required data']);
exit;
@@ -25,15 +26,29 @@ try {
$db = DBHandlerSelect::getInstance();
$pdo = $db->getConnection();
$stmt = $pdo->prepare("
DELETE FROM identification_parts_analyses
WHERE part_id = :part_id
AND analysis_recordkey = :analysis_recordkey
");
$stmt->execute([
':part_id' => $partId,
':analysis_recordkey' => $analysisRecordkey,
]);
if ($rowId > 0) {
$stmt = $pdo->prepare("
DELETE FROM identification_parts_analyses
WHERE id = :id
AND part_id = :part_id
LIMIT 1
");
$stmt->execute([
':id' => $rowId,
':part_id' => $partId,
]);
} else {
$stmt = $pdo->prepare("
DELETE FROM identification_parts_analyses
WHERE part_id = :part_id
AND analysis_recordkey = :analysis_recordkey
LIMIT 1
");
$stmt->execute([
':part_id' => $partId,
':analysis_recordkey' => $analysisRecordkey,
]);
}
echo json_encode([
'success' => true,
+37
View File
@@ -0,0 +1,37 @@
<?php
include('include/headscript.php');
$db = DBHandlerSelect::getInstance();
$pdo = $db->getConnection();
$logDir = __DIR__ . '/logs/api/';
$iddatadb = (int)($_GET['iddatadb'] ?? 0);
if ($iddatadb <= 0) {
http_response_code(400);
exit('iddatadb mancante');
}
$stmt = $pdo->prepare("SELECT log_file, commessaweb FROM datadb WHERE iddatadb = :id LIMIT 1");
$stmt->execute(['id' => $iddatadb]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$row || empty($row['log_file'])) {
http_response_code(404);
exit('Nessun log per questa commessa');
}
// solo basename: niente path traversal
$path = $logDir . basename($row['log_file']);
if (!is_file($path)) {
http_response_code(404);
exit('File di log non trovato: ' . basename($row['log_file']));
}
while (ob_get_level() > 0) {
ob_end_clean();
}
$label = preg_replace('/[^A-Za-z0-9_\-]/', '_', (string)($row['commessaweb'] ?: $iddatadb));
header('Content-Type: text/plain; charset=utf-8');
header('Content-Disposition: attachment; filename="log_' . $label . '_' . $iddatadb . '.log"');
header('Content-Length: ' . filesize($path));
readfile($path);
exit;
+5 -1
View File
@@ -265,7 +265,11 @@ if (!array_key_exists($currentButtonTextColor, array_change_key_case($buttonText
<label class="form-label"><?= htmlspecialchars($desctemplate, ENT_QUOTES, 'UTF-8'); ?></label>
<textarea name="description" class="form-control"><?php echo htmlspecialchars($template['description'] ?? ''); ?></textarea>
</div>
<div class="mb-3">
<label class="form-label">Template Note</label>
<textarea name="template_note" class="form-control" rows="3"><?php echo htmlspecialchars($template['template_note'] ?? ''); ?></textarea>
<small class="text-muted">If set, this note will be appended at the end of the notes during export.</small>
</div>
<div class="mb-3">
<label class="form-label"><?= htmlspecialchars($desttable, ENT_QUOTES, 'UTF-8'); ?> *</label>
<input type="text" name="target_table" class="form-control" value="<?php echo htmlspecialchars($template['target_table'] ?? 'datadb'); ?>" readonly required>
-376
View File
@@ -1,376 +0,0 @@
2025-06-10 12:21:44 - Errore nel recupero dati: HTTP 404, Risposta:
2025-06-16 11:15:30 - Errore nel recupero dati: HTTP 404, Risposta: {"title":"Not Found","status":404,"detail":"Not Found","instance":"GET /api/odata/Rapporto(2523026)","errorCode":"d25cbd678"}
2025-06-16 11:34:59 - Autenticazione fallita: HTTP 0, Errore cURL: Failed to connect to 93.43.5.102 port 443 after 21033 ms: Couldn't connect to server, Risposta:
2025-06-16 11:42:03 - Errore nella richiesta: Recv failure: Connection was reset
2025-07-04 10:42:49 - Autenticazione fallita: HTTP 400, Errore cURL: , Risposta: {"title":"Bad Request","status":400,"detail":"Cannot persist the object. It was modified or deleted (purged) by another application.","instance":"POST /api/authentication/authenticate","errorCode":"96bfc1252b"}
2025-07-04 10:44:13 - Autenticazione fallita: HTTP 400, Errore cURL: , Risposta: {"title":"Bad Request","status":400,"detail":"Cannot persist the object. It was modified or deleted (purged) by another application.","instance":"POST /api/authentication/authenticate","errorCode":"96bfc1252b"}
2025-07-04 10:48:07 - Autenticazione fallita: HTTP 400, Errore cURL: , Risposta: {"title":"Bad Request","status":400,"detail":"Cannot persist the object. It was modified or deleted (purged) by another application.","instance":"POST /api/authentication/authenticate","errorCode":"96bfc1252b"}
2025-08-19 16:29:25 - Autenticazione fallita: HTTP 400, Errore cURL: , Risposta: {"title":"Bad Request","status":400,"detail":"Cannot persist the object. It was modified or deleted (purged) by another application.","instance":"POST /api/authentication/authenticate","errorCode":"96bfc1252b"}
2025-08-26 16:47:19 - Risposta non JSON valida: <?xml version="1.0" encoding="utf-8"?><edmx:Edmx Version="4.0" xmlns:edmx="http://docs.oasis-open.org/odata/ns/edmx"><edmx:DataServices><Schema Namespace="DevExpress.ExpressApp.SystemModule" xmlns="http://docs.oasis-open.org/odata/ns/edm"><EntityType Name="DashboardViewItemDescriptor"><Key><PropertyRef Name="ViewId" /></Key><Property Name="ViewId" Type="Edm.String" Nullable="false" /></EntityType><EntityType Name="DashboardOrganizationItem" BaseType="DevExpress.ExpressApp.NonPersistentLiteObject" Abstract="true"><Property Name="Visibility" Type="DevExpress.ExpressApp.Editors.ViewItemVisibility" Nullable="false" /></EntityType><EntityType Name="DashboardOrganizationItem_1OfIModelDashboardViewItem" BaseType="DevExpress.ExpressApp.SystemModule.DashboardOrganizationItem" Abstract="true" /><EntityType Name="ViewDashboardOrganizationItem" BaseType="DevExpress.ExpressApp.SystemModule.DashboardOrganizationItem_1OfIModelDashboardViewItem"><Property Name="ObjectType" Type="System.Type" /><Proper
2025-08-26 16:48:15 - Risposta non JSON valida: <?xml version="1.0" encoding="utf-8"?><edmx:Edmx Version="4.0" xmlns:edmx="http://docs.oasis-open.org/odata/ns/edmx"><edmx:DataServices><Schema Namespace="DevExpress.ExpressApp.SystemModule" xmlns="http://docs.oasis-open.org/odata/ns/edm"><EntityType Name="DashboardViewItemDescriptor"><Key><PropertyRef Name="ViewId" /></Key><Property Name="ViewId" Type="Edm.String" Nullable="false" /></EntityType><EntityType Name="DashboardOrganizationItem" BaseType="DevExpress.ExpressApp.NonPersistentLiteObject" Abstract="true"><Property Name="Visibility" Type="DevExpress.ExpressApp.Editors.ViewItemVisibility" Nullable="false" /></EntityType><EntityType Name="DashboardOrganizationItem_1OfIModelDashboardViewItem" BaseType="DevExpress.ExpressApp.SystemModule.DashboardOrganizationItem" Abstract="true" /><EntityType Name="ViewDashboardOrganizationItem" BaseType="DevExpress.ExpressApp.SystemModule.DashboardOrganizationItem_1OfIModelDashboardViewItem"><Property Name="ObjectType" Type="System.Type" /><Proper
2025-08-26 16:48:44 - Risposta non JSON valida: <?xml version="1.0" encoding="utf-8"?><edmx:Edmx Version="4.0" xmlns:edmx="http://docs.oasis-open.org/odata/ns/edmx"><edmx:DataServices><Schema Namespace="DevExpress.ExpressApp.SystemModule" xmlns="http://docs.oasis-open.org/odata/ns/edm"><EntityType Name="DashboardViewItemDescriptor"><Key><PropertyRef Name="ViewId" /></Key><Property Name="ViewId" Type="Edm.String" Nullable="false" /></EntityType><EntityType Name="DashboardOrganizationItem" BaseType="DevExpress.ExpressApp.NonPersistentLiteObject" Abstract="true"><Property Name="Visibility" Type="DevExpress.ExpressApp.Editors.ViewItemVisibility" Nullable="false" /></EntityType><EntityType Name="DashboardOrganizationItem_1OfIModelDashboardViewItem" BaseType="DevExpress.ExpressApp.SystemModule.DashboardOrganizationItem" Abstract="true" /><EntityType Name="ViewDashboardOrganizationItem" BaseType="DevExpress.ExpressApp.SystemModule.DashboardOrganizationItem_1OfIModelDashboardViewItem"><Property Name="ObjectType" Type="System.Type" /><Proper
2025-08-26 16:49:24 - Risposta non JSON valida: <?xml version="1.0" encoding="utf-8"?><edmx:Edmx Version="4.0" xmlns:edmx="http://docs.oasis-open.org/odata/ns/edmx"><edmx:DataServices><Schema Namespace="DevExpress.ExpressApp.SystemModule" xmlns="http://docs.oasis-open.org/odata/ns/edm"><EntityType Name="DashboardViewItemDescriptor"><Key><PropertyRef Name="ViewId" /></Key><Property Name="ViewId" Type="Edm.String" Nullable="false" /></EntityType><EntityType Name="DashboardOrganizationItem" BaseType="DevExpress.ExpressApp.NonPersistentLiteObject" Abstract="true"><Property Name="Visibility" Type="DevExpress.ExpressApp.Editors.ViewItemVisibility" Nullable="false" /></EntityType><EntityType Name="DashboardOrganizationItem_1OfIModelDashboardViewItem" BaseType="DevExpress.ExpressApp.SystemModule.DashboardOrganizationItem" Abstract="true" /><EntityType Name="ViewDashboardOrganizationItem" BaseType="DevExpress.ExpressApp.SystemModule.DashboardOrganizationItem_1OfIModelDashboardViewItem"><Property Name="ObjectType" Type="System.Type" /><Proper
2025-08-26 16:50:23 - Risposta non JSON valida: <?xml version="1.0" encoding="utf-8"?><edmx:Edmx Version="4.0" xmlns:edmx="http://docs.oasis-open.org/odata/ns/edmx"><edmx:DataServices><Schema Namespace="DevExpress.ExpressApp.SystemModule" xmlns="http://docs.oasis-open.org/odata/ns/edm"><EntityType Name="DashboardViewItemDescriptor"><Key><PropertyRef Name="ViewId" /></Key><Property Name="ViewId" Type="Edm.String" Nullable="false" /></EntityType><EntityType Name="DashboardOrganizationItem" BaseType="DevExpress.ExpressApp.NonPersistentLiteObject" Abstract="true"><Property Name="Visibility" Type="DevExpress.ExpressApp.Editors.ViewItemVisibility" Nullable="false" /></EntityType><EntityType Name="DashboardOrganizationItem_1OfIModelDashboardViewItem" BaseType="DevExpress.ExpressApp.SystemModule.DashboardOrganizationItem" Abstract="true" /><EntityType Name="ViewDashboardOrganizationItem" BaseType="DevExpress.ExpressApp.SystemModule.DashboardOrganizationItem_1OfIModelDashboardViewItem"><Property Name="ObjectType" Type="System.Type" /><Proper
2025-09-08 08:39:17 - Risposta non JSON valida: <?xml version="1.0" encoding="utf-8"?><edmx:Edmx Version="4.0" xmlns:edmx="http://docs.oasis-open.org/odata/ns/edmx"><edmx:DataServices><Schema Namespace="DevExpress.ExpressApp.SystemModule" xmlns="http://docs.oasis-open.org/odata/ns/edm"><EntityType Name="DashboardViewItemDescriptor"><Key><PropertyRef Name="ViewId" /></Key><Property Name="ViewId" Type="Edm.String" Nullable="false" /></EntityType><EntityType Name="DashboardOrganizationItem" BaseType="DevExpress.ExpressApp.NonPersistentLiteObject" Abstract="true"><Property Name="Visibility" Type="DevExpress.ExpressApp.Editors.ViewItemVisibility" Nullable="false" /></EntityType><EntityType Name="DashboardOrganizationItem_1OfIModelDashboardViewItem" BaseType="DevExpress.ExpressApp.SystemModule.DashboardOrganizationItem" Abstract="true" /><EntityType Name="ViewDashboardOrganizationItem" BaseType="DevExpress.ExpressApp.SystemModule.DashboardOrganizationItem_1OfIModelDashboardViewItem"><Property Name="ObjectType" Type="System.Type" /><Proper
2026-01-27 15:33:53 - Errore nel recupero dati: HTTP 404, Risposta:
2026-01-27 15:34:06 - Errore nel recupero dati: HTTP 404, Risposta:
2026-01-27 15:34:10 - Errore nel recupero dati: HTTP 404, Risposta:
2026-01-27 15:35:13 - Errore nel recupero dati: HTTP 404, Risposta:
2026-01-29 14:33:38 [ClienteResponsabile] Errore nel recupero dati: HTTP 404, Risposta:
2026-01-29 14:33:39 [MoltiplicatorePrezzo] Autenticazione fallita: HTTP 400, Errore cURL: , Risposta: {"title":"Bad Request","status":400,"detail":"Cannot persist the object. It was modified or deleted (purged) by another application.","instance":"POST /api/authentication/authenticate","errorCode":"96bfc1252b"}
2026-01-29 14:34:04 [ClienteResponsabile] Errore nel recupero dati: HTTP 404, Risposta:
2026-01-29 14:37:29 [ClienteResponsabile] Errore nel recupero dati: HTTP 404, Risposta:
2026-01-29 14:41:55 [ClienteResponsabile] Errore nel recupero dati: HTTP 404, Risposta:
2026-01-29 14:42:03 [ClienteResponsabile] Errore nel recupero dati: HTTP 404, Risposta:
2026-01-29 14:42:52 [ClienteResponsabile] Errore nel recupero dati: HTTP 404, Risposta:
2026-01-29 14:43:00 [ClienteResponsabile] Errore nel recupero dati: HTTP 404, Risposta:
2026-01-30 10:50:43 [AnagraficaCertestService] Autenticazione fallita: HTTP 400, Errore cURL: , Risposta: {"title":"Bad Request","status":400,"detail":"Cannot persist the object. It was modified or deleted (purged) by another application.","instance":"POST /api/authentication/authenticate","errorCode":"96bfc1252b"}
2026-01-30 10:50:43 [MoltiplicatorePrezzo] Autenticazione fallita: HTTP 400, Errore cURL: , Risposta: {"title":"Bad Request","status":400,"detail":"Cannot persist the object. It was modified or deleted (purged) by another application.","instance":"POST /api/authentication/authenticate","errorCode":"96bfc1252b"}
2026-01-30 11:09:22 [MoltiplicatorePrezzo] Autenticazione fallita: HTTP 400, Errore cURL: , Risposta: {"title":"Bad Request","status":400,"detail":"Cannot persist the object. It was modified or deleted (purged) by another application.","instance":"POST /api/authentication/authenticate","errorCode":"96bfc1252b"}
2026-02-19 10:00:13 [MoltiplicatorePrezzo] Autenticazione fallita: HTTP 400, Errore cURL: , Risposta: {"title":"Bad Request","status":400,"detail":"Cannot persist the object. It was modified or deleted (purged) by another application.","instance":"POST /api/authentication/authenticate","errorCode":"96bfc1252b"}
2026-02-19 10:00:42 [AnagraficaCertestObject] Autenticazione fallita: HTTP 400, Errore cURL: , Risposta: {"title":"Bad Request","status":400,"detail":"Cannot persist the object. It was modified or deleted (purged) by another application.","instance":"POST /api/authentication/authenticate","errorCode":"96bfc1252b"}
2026-02-19 10:00:44 [MoltiplicatorePrezzo] Autenticazione fallita: HTTP 400, Errore cURL: , Risposta: {"title":"Bad Request","status":400,"detail":"Cannot persist the object. It was modified or deleted (purged) by another application.","instance":"POST /api/authentication/authenticate","errorCode":"96bfc1252b"}
2026-02-23 10:44:04 - Autenticazione fallita: HTTP 404, Errore cURL: , Risposta: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Not Found</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Not Found</h2>
<hr><p>HTTP Error 404. The requested resource is not found.</p>
</BODY></HTML>
2026-02-23 10:44:42 [AnagraficaCertestService] Autenticazione fallita: HTTP 404, Errore cURL: , Risposta: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Not Found</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Not Found</h2>
<hr><p>HTTP Error 404. The requested resource is not found.</p>
</BODY></HTML>
2026-02-23 10:44:42 [AnagraficaCertestObject] Autenticazione fallita: HTTP 404, Errore cURL: , Risposta: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Not Found</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Not Found</h2>
<hr><p>HTTP Error 404. The requested resource is not found.</p>
</BODY></HTML>
2026-02-23 10:44:42 [MoltiplicatorePrezzo] Autenticazione fallita: HTTP 404, Errore cURL: , Risposta: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Not Found</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Not Found</h2>
<hr><p>HTTP Error 404. The requested resource is not found.</p>
</BODY></HTML>
2026-02-23 10:44:42 [AnagraficaCertestService] Autenticazione fallita: HTTP 404, Errore cURL: , Risposta: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Not Found</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Not Found</h2>
<hr><p>HTTP Error 404. The requested resource is not found.</p>
</BODY></HTML>
2026-02-23 10:44:42 [AnagraficaCertestObject] Autenticazione fallita: HTTP 404, Errore cURL: , Risposta: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Not Found</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Not Found</h2>
<hr><p>HTTP Error 404. The requested resource is not found.</p>
</BODY></HTML>
2026-02-23 10:44:42 [MoltiplicatorePrezzo] Autenticazione fallita: HTTP 404, Errore cURL: , Risposta: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Not Found</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Not Found</h2>
<hr><p>HTTP Error 404. The requested resource is not found.</p>
</BODY></HTML>
2026-02-23 10:44:42 [AnagraficaCertestService] Autenticazione fallita: HTTP 404, Errore cURL: , Risposta: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Not Found</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Not Found</h2>
<hr><p>HTTP Error 404. The requested resource is not found.</p>
</BODY></HTML>
2026-02-23 10:44:42 [AnagraficaCertestObject] Autenticazione fallita: HTTP 404, Errore cURL: , Risposta: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Not Found</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Not Found</h2>
<hr><p>HTTP Error 404. The requested resource is not found.</p>
</BODY></HTML>
2026-02-23 10:44:42 [MoltiplicatorePrezzo] Autenticazione fallita: HTTP 404, Errore cURL: , Risposta: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Not Found</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Not Found</h2>
<hr><p>HTTP Error 404. The requested resource is not found.</p>
</BODY></HTML>
2026-02-23 10:44:43 [MoltiplicatorePrezzo] Autenticazione fallita: HTTP 404, Errore cURL: , Risposta: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Not Found</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Not Found</h2>
<hr><p>HTTP Error 404. The requested resource is not found.</p>
</BODY></HTML>
2026-02-23 10:44:43 [AnagraficaCertestObject] Autenticazione fallita: HTTP 404, Errore cURL: , Risposta: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Not Found</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Not Found</h2>
<hr><p>HTTP Error 404. The requested resource is not found.</p>
</BODY></HTML>
2026-02-23 10:44:43 [AnagraficaCertestService] Autenticazione fallita: HTTP 404, Errore cURL: , Risposta: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Not Found</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Not Found</h2>
<hr><p>HTTP Error 404. The requested resource is not found.</p>
</BODY></HTML>
2026-02-23 10:44:52 [AnagraficaCertestObject] Autenticazione fallita: HTTP 404, Errore cURL: , Risposta: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Not Found</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Not Found</h2>
<hr><p>HTTP Error 404. The requested resource is not found.</p>
</BODY></HTML>
2026-02-23 10:44:52 [MoltiplicatorePrezzo] Autenticazione fallita: HTTP 404, Errore cURL: , Risposta: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Not Found</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Not Found</h2>
<hr><p>HTTP Error 404. The requested resource is not found.</p>
</BODY></HTML>
2026-02-23 10:44:52 [AnagraficaCertestService] Autenticazione fallita: HTTP 404, Errore cURL: , Risposta: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Not Found</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Not Found</h2>
<hr><p>HTTP Error 404. The requested resource is not found.</p>
</BODY></HTML>
2026-02-23 10:44:52 [AnagraficaCertestObject] Autenticazione fallita: HTTP 404, Errore cURL: , Risposta: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Not Found</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Not Found</h2>
<hr><p>HTTP Error 404. The requested resource is not found.</p>
</BODY></HTML>
2026-02-23 10:44:52 [MoltiplicatorePrezzo] Autenticazione fallita: HTTP 404, Errore cURL: , Risposta: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Not Found</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Not Found</h2>
<hr><p>HTTP Error 404. The requested resource is not found.</p>
</BODY></HTML>
2026-02-23 10:44:52 [AnagraficaCertestService] Autenticazione fallita: HTTP 404, Errore cURL: , Risposta: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Not Found</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Not Found</h2>
<hr><p>HTTP Error 404. The requested resource is not found.</p>
</BODY></HTML>
2026-02-23 10:44:52 [AnagraficaCertestObject] Autenticazione fallita: HTTP 404, Errore cURL: , Risposta: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Not Found</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Not Found</h2>
<hr><p>HTTP Error 404. The requested resource is not found.</p>
</BODY></HTML>
2026-02-23 10:44:52 [MoltiplicatorePrezzo] Autenticazione fallita: HTTP 404, Errore cURL: , Risposta: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Not Found</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Not Found</h2>
<hr><p>HTTP Error 404. The requested resource is not found.</p>
</BODY></HTML>
2026-02-23 10:44:52 [AnagraficaCertestService] Autenticazione fallita: HTTP 404, Errore cURL: , Risposta: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Not Found</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Not Found</h2>
<hr><p>HTTP Error 404. The requested resource is not found.</p>
</BODY></HTML>
2026-02-23 10:44:52 [MoltiplicatorePrezzo] Autenticazione fallita: HTTP 404, Errore cURL: , Risposta: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Not Found</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Not Found</h2>
<hr><p>HTTP Error 404. The requested resource is not found.</p>
</BODY></HTML>
2026-02-23 10:44:52 [AnagraficaCertestObject] Autenticazione fallita: HTTP 404, Errore cURL: , Risposta: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Not Found</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Not Found</h2>
<hr><p>HTTP Error 404. The requested resource is not found.</p>
</BODY></HTML>
2026-02-23 10:44:53 [AnagraficaCertestService] Autenticazione fallita: HTTP 404, Errore cURL: , Risposta: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Not Found</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Not Found</h2>
<hr><p>HTTP Error 404. The requested resource is not found.</p>
</BODY></HTML>
2026-02-23 10:48:26 - Autenticazione fallita: HTTP 404, Errore cURL: , Risposta: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Not Found</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Not Found</h2>
<hr><p>HTTP Error 404. The requested resource is not found.</p>
</BODY></HTML>
2026-02-23 10:48:26 - Autenticazione fallita: HTTP 404, Errore cURL: , Risposta: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Not Found</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Not Found</h2>
<hr><p>HTTP Error 404. The requested resource is not found.</p>
</BODY></HTML>
2026-02-23 10:48:27 - Autenticazione fallita: HTTP 404, Errore cURL: , Risposta: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Not Found</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Not Found</h2>
<hr><p>HTTP Error 404. The requested resource is not found.</p>
</BODY></HTML>
2026-02-23 10:48:27 - Autenticazione fallita: HTTP 404, Errore cURL: , Risposta: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Not Found</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Not Found</h2>
<hr><p>HTTP Error 404. The requested resource is not found.</p>
</BODY></HTML>
2026-02-23 10:48:27 - Autenticazione fallita: HTTP 404, Errore cURL: , Risposta: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Not Found</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Not Found</h2>
<hr><p>HTTP Error 404. The requested resource is not found.</p>
</BODY></HTML>
2026-02-23 10:49:04 - Autenticazione fallita: HTTP 404, Errore cURL: , Risposta: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Not Found</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Not Found</h2>
<hr><p>HTTP Error 404. The requested resource is not found.</p>
</BODY></HTML>
2026-02-23 10:49:04 - Autenticazione fallita: HTTP 404, Errore cURL: , Risposta: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Not Found</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Not Found</h2>
<hr><p>HTTP Error 404. The requested resource is not found.</p>
</BODY></HTML>
2026-02-23 10:49:04 - Autenticazione fallita: HTTP 404, Errore cURL: , Risposta: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Not Found</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Not Found</h2>
<hr><p>HTTP Error 404. The requested resource is not found.</p>
</BODY></HTML>
2026-02-23 10:49:05 - Autenticazione fallita: HTTP 404, Errore cURL: , Risposta: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Not Found</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Not Found</h2>
<hr><p>HTTP Error 404. The requested resource is not found.</p>
</BODY></HTML>
2026-02-23 10:49:05 - Autenticazione fallita: HTTP 404, Errore cURL: , Risposta: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Not Found</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Not Found</h2>
<hr><p>HTTP Error 404. The requested resource is not found.</p>
</BODY></HTML>
2026-02-23 14:26:52 - Autenticazione fallita: HTTP 404, Errore cURL: , Risposta: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Not Found</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Not Found</h2>
<hr><p>HTTP Error 404. The requested resource is not found.</p>
</BODY></HTML>
2026-02-23 14:26:59 - Autenticazione fallita: HTTP 404, Errore cURL: , Risposta: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Not Found</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Not Found</h2>
<hr><p>HTTP Error 404. The requested resource is not found.</p>
</BODY></HTML>
2026-02-23 15:54:16 - Autenticazione fallita: HTTP 404, Errore cURL: , Risposta: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Not Found</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Not Found</h2>
<hr><p>HTTP Error 404. The requested resource is not found.</p>
</BODY></HTML>
2026-02-23 16:22:45 - Autenticazione fallita: HTTP 404, Errore cURL: , Risposta: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Not Found</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Not Found</h2>
<hr><p>HTTP Error 404. The requested resource is not found.</p>
</BODY></HTML>
2026-02-23 16:32:17 - Autenticazione fallita: HTTP 404, Errore cURL: , Risposta: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Not Found</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Not Found</h2>
<hr><p>HTTP Error 404. The requested resource is not found.</p>
</BODY></HTML>
2026-02-25 15:23:12 [AnagraficaCertestObject] Autenticazione fallita: HTTP 400, Errore cURL: , Risposta: {"title":"Bad Request","status":400,"detail":"Cannot persist the object. It was modified or deleted (purged) by another application.","instance":"POST /api/authentication/authenticate","errorCode":"96bfc1252b"}
2026-02-26 15:01:32 [AnagraficaCertestObject] Autenticazione fallita: HTTP 400, Errore cURL: , Risposta: {"title":"Bad Request","status":400,"detail":"Cannot persist the object. It was modified or deleted (purged) by another application.","instance":"POST /api/authentication/authenticate","errorCode":"96bfc1252b"}
2026-02-28 21:01:27 [AnagraficaCertestService] Autenticazione fallita: HTTP 400, Errore cURL: , Risposta: {"title":"Bad Request","status":400,"detail":"Cannot persist the object. It was modified or deleted (purged) by another application.","instance":"POST /api/authentication/authenticate","errorCode":"96bfc1252b"}
2026-03-01 19:11:58 [AnagraficaCertestObject] Autenticazione fallita: HTTP 400, Errore cURL: , Risposta: {"title":"Bad Request","status":400,"detail":"Cannot persist the object. It was modified or deleted (purged) by another application.","instance":"POST /api/authentication/authenticate","errorCode":"96bfc1252b"}
2026-03-18 15:51:45 [AnagraficaCertestService] Autenticazione fallita: HTTP 400, Errore cURL: , Risposta: {"title":"Bad Request","status":400,"detail":"Cannot persist the object. It was modified or deleted (purged) by another application.","instance":"POST /api/authentication/authenticate","errorCode":"96bfc1252b"}
2026-03-19 09:50:34 [AnagraficaCertestService] Autenticazione fallita: HTTP 400, Errore cURL: , Risposta: {"title":"Bad Request","status":400,"detail":"Cannot persist the object. It was modified or deleted (purged) by another application.","instance":"POST /api/authentication/authenticate","errorCode":"96bfc1252b"}
2026-03-25 14:13:34 - Autenticazione fallita: HTTP 503, Errore cURL: , Risposta: The service is unavailable.
2026-03-25 14:13:34 - Autenticazione fallita: HTTP 503, Errore cURL: , Risposta: The service is unavailable.
2026-03-26 10:57:18 [AnagraficaCertestObject] Autenticazione fallita: HTTP 500, Errore cURL: , Risposta: {"title":"Internal Server Error","status":500,"detail":"Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.","instance":"POST /api/authentication/authenticate","errorCode":"63ab532c6"}
2026-03-26 10:57:21 [AnagraficaCertestObject] Autenticazione fallita: HTTP 500, Errore cURL: , Risposta: {"title":"Internal Server Error","status":500,"detail":"Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.","instance":"POST /api/authentication/authenticate","errorCode":"63ab532c6"}
2026-03-26 10:57:21 [AnagraficaCertestService] Autenticazione fallita: HTTP 500, Errore cURL: , Risposta: {"title":"Internal Server Error","status":500,"detail":"Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.","instance":"POST /api/authentication/authenticate","errorCode":"63ab532c6"}
2026-03-26 10:57:21 [MoltiplicatorePrezzo] Autenticazione fallita: HTTP 500, Errore cURL: , Risposta: {"title":"Internal Server Error","status":500,"detail":"Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.","instance":"POST /api/authentication/authenticate","errorCode":"63ab532c6"}
2026-03-26 10:57:36 [AnagraficaCertestObject] Autenticazione fallita: HTTP 500, Errore cURL: , Risposta: {"title":"Internal Server Error","status":500,"detail":"Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.","instance":"POST /api/authentication/authenticate","errorCode":"63ab532c6"}
2026-03-26 10:57:36 [AnagraficaCertestService] Autenticazione fallita: HTTP 500, Errore cURL: , Risposta: {"title":"Internal Server Error","status":500,"detail":"Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.","instance":"POST /api/authentication/authenticate","errorCode":"63ab532c6"}
2026-03-26 10:57:36 [MoltiplicatorePrezzo] Autenticazione fallita: HTTP 500, Errore cURL: , Risposta: {"title":"Internal Server Error","status":500,"detail":"Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.","instance":"POST /api/authentication/authenticate","errorCode":"63ab532c6"}
2026-03-26 10:57:41 [MoltiplicatorePrezzo] Autenticazione fallita: HTTP 500, Errore cURL: , Risposta: {"title":"Internal Server Error","status":500,"detail":"Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.","instance":"POST /api/authentication/authenticate","errorCode":"63ab532c6"}
2026-03-26 10:57:56 [AnagraficaCertestObject] Autenticazione fallita: HTTP 500, Errore cURL: , Risposta: {"title":"Internal Server Error","status":500,"detail":"Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.","instance":"POST /api/authentication/authenticate","errorCode":"63ab532c6"}
2026-03-26 10:58:11 [AnagraficaCertestService] Autenticazione fallita: HTTP 500, Errore cURL: , Risposta: {"title":"Internal Server Error","status":500,"detail":"Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.","instance":"POST /api/authentication/authenticate","errorCode":"63ab532c6"}
2026-04-30 15:01:25 - Errore nel recupero dati: HTTP 404, Risposta: {"title":"Not Found","status":404,"detail":"Not Found","instance":"GET /api/odata/Rapporto(2621521)","errorCode":"d25cbd678"}
2026-04-30 15:02:04 - Errore nel recupero dati: HTTP 404, Risposta:
2026-04-30 15:03:19 - Errore nella richiesta: URL rejected: Malformed input to a URL function
2026-06-16 14:29:15 [MoltiplicatorePrezzo] Autenticazione fallita: HTTP 0, Errore cURL: Failed to connect to bvcpsitaly-elims.com port 443 after 21037 ms: Couldn't connect to server, Risposta:
2026-06-16 14:29:36 [ClienteResponsabile] Autenticazione fallita: HTTP 0, Errore cURL: Failed to connect to bvcpsitaly-elims.com port 443 after 21099 ms: Couldn't connect to server, Risposta:
2026-06-16 14:30:03 [MoltiplicatorePrezzo] Autenticazione fallita: HTTP 0, Errore cURL: Failed to connect to bvcpsitaly-elims.com port 443 after 21076 ms: Couldn't connect to server, Risposta:
2026-06-16 14:30:03 [AnagraficaCertestObject] Autenticazione fallita: HTTP 0, Errore cURL: Failed to connect to bvcpsitaly-elims.com port 443 after 21083 ms: Couldn't connect to server, Risposta:
2026-06-16 14:30:03 [AnagraficaCertestService] Autenticazione fallita: HTTP 0, Errore cURL: Failed to connect to bvcpsitaly-elims.com port 443 after 21083 ms: Couldn't connect to server, Risposta:
2026-06-16 14:30:34 - Autenticazione fallita: HTTP 0, Errore cURL: Failed to connect to bvcpsitaly-elims.com port 443 after 21043 ms: Couldn't connect to server, Risposta:
2026-06-16 14:30:55 - Autenticazione fallita: HTTP 0, Errore cURL: Failed to connect to bvcpsitaly-elims.com port 443 after 21053 ms: Couldn't connect to server, Risposta:
2026-06-16 14:30:55 - Autenticazione fallita: HTTP 0, Errore cURL: Failed to connect to bvcpsitaly-elims.com port 443 after 21050 ms: Couldn't connect to server, Risposta:
2026-06-16 14:31:46 [AnagraficaCertestObject] Autenticazione fallita: HTTP 0, Errore cURL: Failed to connect to bvcpsitaly-elims.com port 443 after 21048 ms: Couldn't connect to server, Risposta:
2026-06-16 14:31:46 [MoltiplicatorePrezzo] Autenticazione fallita: HTTP 0, Errore cURL: Failed to connect to bvcpsitaly-elims.com port 443 after 21043 ms: Couldn't connect to server, Risposta:
2026-06-16 14:31:46 [AnagraficaCertestService] Autenticazione fallita: HTTP 0, Errore cURL: Failed to connect to bvcpsitaly-elims.com port 443 after 21042 ms: Couldn't connect to server, Risposta:
2026-06-16 14:32:07 [ClienteResponsabile] Autenticazione fallita: HTTP 0, Errore cURL: Failed to connect to bvcpsitaly-elims.com port 443 after 21047 ms: Couldn't connect to server, Risposta:
2026-06-16 14:33:09 [MoltiplicatorePrezzo] Autenticazione fallita: HTTP 0, Errore cURL: Failed to connect to bvcpsitaly-elims.com port 443 after 21058 ms: Couldn't connect to server, Risposta:
2026-06-16 14:33:09 [AnagraficaCertestObject] Autenticazione fallita: HTTP 0, Errore cURL: Failed to connect to bvcpsitaly-elims.com port 443 after 21057 ms: Couldn't connect to server, Risposta:
2026-06-16 14:33:09 [AnagraficaCertestService] Autenticazione fallita: HTTP 0, Errore cURL: Failed to connect to bvcpsitaly-elims.com port 443 after 21057 ms: Couldn't connect to server, Risposta:
2026-06-16 14:33:30 [ClienteResponsabile] Autenticazione fallita: HTTP 0, Errore cURL: Failed to connect to bvcpsitaly-elims.com port 443 after 21047 ms: Couldn't connect to server, Risposta:
2026-06-16 14:36:11 [AnagraficaCertestService] Autenticazione fallita: HTTP 0, Errore cURL: Failed to connect to bvcpsitaly-elims.com port 443 after 21062 ms: Couldn't connect to server, Risposta:
2026-06-16 14:36:11 [AnagraficaCertestObject] Autenticazione fallita: HTTP 0, Errore cURL: Failed to connect to bvcpsitaly-elims.com port 443 after 21064 ms: Couldn't connect to server, Risposta:
2026-06-16 14:36:11 [MoltiplicatorePrezzo] Autenticazione fallita: HTTP 0, Errore cURL: Failed to connect to bvcpsitaly-elims.com port 443 after 21065 ms: Couldn't connect to server, Risposta:
2026-06-16 14:36:33 [MoltiplicatorePrezzo] Autenticazione fallita: HTTP 0, Errore cURL: Failed to connect to bvcpsitaly-elims.com port 443 after 21049 ms: Couldn't connect to server, Risposta:
2026-06-16 14:36:33 [AnagraficaCertestService] Autenticazione fallita: HTTP 0, Errore cURL: Failed to connect to bvcpsitaly-elims.com port 443 after 21057 ms: Couldn't connect to server, Risposta:
2026-06-16 14:36:33 [AnagraficaCertestObject] Autenticazione fallita: HTTP 0, Errore cURL: Failed to connect to bvcpsitaly-elims.com port 443 after 21053 ms: Couldn't connect to server, Risposta:
2026-06-16 14:37:13 [MoltiplicatorePrezzo] Autenticazione fallita: HTTP 0, Errore cURL: Failed to connect to bvcpsitaly-elims.com port 443 after 21032 ms: Couldn't connect to server, Risposta:
2026-06-16 14:37:14 [AnagraficaCertestService] Autenticazione fallita: HTTP 0, Errore cURL: Failed to connect to bvcpsitaly-elims.com port 443 after 21031 ms: Couldn't connect to server, Risposta:
2026-06-16 14:37:14 [AnagraficaCertestObject] Autenticazione fallita: HTTP 0, Errore cURL: Failed to connect to bvcpsitaly-elims.com port 443 after 21027 ms: Couldn't connect to server, Risposta:
2026-06-16 14:37:35 [ClienteResponsabile] Autenticazione fallita: HTTP 0, Errore cURL: Failed to connect to bvcpsitaly-elims.com port 443 after 21054 ms: Couldn't connect to server, Risposta:
2026-06-16 17:13:55 - Autenticazione fallita: HTTP 0, Errore cURL: Failed to connect to bvcpsitaly-elims.com port 443 after 21067 ms: Couldn't connect to server, Risposta:
2026-06-16 17:14:25 - Autenticazione fallita: HTTP 0, Errore cURL: Failed to connect to bvcpsitaly-elims.com port 443 after 21065 ms: Couldn't connect to server, Risposta:
2026-06-16 17:14:46 - Autenticazione fallita: HTTP 0, Errore cURL: Failed to connect to bvcpsitaly-elims.com port 443 after 21071 ms: Couldn't connect to server, Risposta:
2026-06-16 17:14:46 - Autenticazione fallita: HTTP 0, Errore cURL: Failed to connect to bvcpsitaly-elims.com port 443 after 21078 ms: Couldn't connect to server, Risposta:
2026-07-09 08:06:33 - Autenticazione fallita: HTTP 0, Errore cURL: Could not resolve host: bvcpsitaly-elims.com, Risposta:
2026-07-09 08:06:33 - Autenticazione fallita: HTTP 0, Errore cURL: Could not resolve host: bvcpsitaly-elims.com, Risposta:
2026-07-09 08:06:33 - Autenticazione fallita: HTTP 0, Errore cURL: Could not resolve host: bvcpsitaly-elims.com, Risposta:
2026-07-09 08:06:33 - Autenticazione fallita: HTTP 0, Errore cURL: Could not resolve host: bvcpsitaly-elims.com, Risposta:
2026-07-09 08:06:33 - Autenticazione fallita: HTTP 0, Errore cURL: Could not resolve host: bvcpsitaly-elims.com, Risposta:
2026-07-09 08:06:41 - Autenticazione fallita: HTTP 0, Errore cURL: Could not resolve host: bvcpsitaly-elims.com, Risposta:
2026-07-09 08:06:41 - Autenticazione fallita: HTTP 0, Errore cURL: Could not resolve host: bvcpsitaly-elims.com, Risposta:
2026-07-09 08:06:41 - Autenticazione fallita: HTTP 0, Errore cURL: Could not resolve host: bvcpsitaly-elims.com, Risposta:
2026-07-09 08:06:41 - Autenticazione fallita: HTTP 0, Errore cURL: Could not resolve host: bvcpsitaly-elims.com, Risposta:
2026-07-09 08:06:41 - Autenticazione fallita: HTTP 0, Errore cURL: Could not resolve host: bvcpsitaly-elims.com, Risposta:
2026-07-10 08:12:24 - Errore nella richiesta: SSL connection timeout
+364
View File
@@ -0,0 +1,364 @@
<?php
include('include/headscript.php');
$template_id = intval($_GET['id'] ?? 0);
if (!$template_id) {
header("Location: xlstemplates_grid.php?status=error&message=" . urlencode("Template ID mancante"));
exit;
}
$user_id = $iduserlogin ?? 1;
$show_all_users = isset($_GET['all_users']) && $_GET['all_users'] == '1';
$allowedLimits = [20, 40, 60, 100];
$rawLimit = (int)($_GET['limit'] ?? 20);
$perPage = in_array($rawLimit, $allowedLimits) ? $rawLimit : 20;
$page = max(1, (int)($_GET['page'] ?? 1));
$db = DBHandlerSelect::getInstance();
$pdo = $db->getConnection();
$logDir = __DIR__ . '/logs/api/';
// Estrae un riassunto breve dell'errore dal file di log della commessa
function extractErrorSummary(string $logDir, ?string $logFile): string
{
if (empty($logFile)) return '';
$path = $logDir . basename($logFile);
if (!is_file($path)) return '';
$content = @file_get_contents($path);
if ($content === false || $content === '') return '';
// 1) prova col "detail" del JSON del 500
if (preg_match('/"detail"\s*:\s*"([^"]+)"/', $content, $m)) {
return trim(stripcslashes($m[1]));
}
// 2) fallback: ultima riga MESSAGE:
if (preg_match_all('/^MESSAGE:\s*(.+)$/m', $content, $m) && !empty($m[1])) {
return trim(end($m[1]));
}
return '';
}
// Query: solo le righe in errore per questo template
$userFilter = $show_all_users ? '' : 'AND d.user_id = ?';
$baseWhere = "WHERE d.templateid = ? AND d.status = 'x' {$userFilter}";
$baseParams = [$template_id];
if (!$show_all_users) $baseParams[] = $user_id;
$countStmt = $pdo->prepare("SELECT COUNT(*) FROM datadb d {$baseWhere}");
$countStmt->execute($baseParams);
$totalRows = (int)$countStmt->fetchColumn();
$totalPages = max(1, (int)ceil($totalRows / $perPage));
if ($page > $totalPages) $page = $totalPages;
$stmt = $pdo->prepare("
SELECT d.*, CONCAT(u.first_name, ' ', u.last_name) AS user_name
FROM datadb d
LEFT JOIN auth_users u ON d.user_id = u.id
{$baseWhere}
ORDER BY d.export_date DESC, d.iddatadb DESC
LIMIT {$perPage} OFFSET " . (($page - 1) * $perPage) . "
");
$stmt->execute($baseParams);
$rowsData = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!doctype html>
<html lang="it">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="assets/images/favicon-32x32.png" type="image/png" />
<?php include('cssinclude.php'); ?>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" crossorigin="anonymous" referrerpolicy="no-referrer" />
<style>
.err-table {
width: 100%;
border-collapse: collapse;
font-size: 13px;
}
.err-table th,
.err-table td {
padding: 8px 10px;
border-bottom: 1px solid #dee2e6;
vertical-align: top;
}
.err-table th {
background: #f8f9fa;
text-align: left;
font-weight: 600;
color: #495057;
}
.err-table tr:hover {
background: #fff8f8;
}
.status-badge {
display: inline-block;
padding: 2px 8px;
font-size: 12px;
font-weight: 500;
border-radius: 12px;
}
.status-x {
background: #dc3545;
color: #fff;
}
.err-msg {
color: #b02a37;
max-width: 420px;
white-space: normal;
word-break: break-word;
}
.commessa-code {
font-size: 0.8em;
color: #555;
display: block;
margin-top: 2px;
}
.action-btn {
padding: 5px 8px;
margin-right: 4px;
border: none;
border-radius: 5px;
cursor: pointer;
color: #fff;
text-decoration: none;
display: inline-flex;
align-items: center;
}
.btn-resend {
background: #28a745;
}
.btn-log {
background: #17a2b8;
}
.btn-revert {
background: #fd7e14;
}
.pager-bar {
display: flex;
align-items: center;
justify-content: space-between;
background: #f8f9fa;
border: 1px solid #dee2e6;
border-radius: 6px;
padding: 6px 14px;
font-size: 13px;
margin-bottom: 10px;
}
.pager-num,
.pager-btn {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 28px;
height: 28px;
padding: 0 6px;
border: 1px solid #ced4da;
border-radius: 4px;
text-decoration: none;
color: #495057;
margin-left: 4px;
}
.pager-num.active {
background: #0d6efd;
color: #fff;
border-color: #0d6efd;
}
</style>
<title>Export Errors - <?= htmlspecialchars($titlewebsite ?? '', ENT_QUOTES, 'UTF-8'); ?></title>
</head>
<body>
<div class="wrapper">
<?php include('include/navbar.php'); ?>
<?php include('include/topbar.php'); ?>
<div class="page-wrapper">
<div class="page-content">
<div class="mb-3 d-flex align-items-center gap-2">
<a href="imported.php?id=<?= $template_id ?>" class="btn btn-warning me-2">Imported (i)</a>
<a href="tolims.php?id=<?= $template_id ?>" class="btn btn-success me-2">To LIMS (l)</a>
<a href="errors.php?id=<?= $template_id ?>" class="btn btn-danger">Errors (x)</a>
<span class="ms-3">
<label class="form-check-label" style="font-size:13px; cursor:pointer;">
<?php $tp = $_GET;
unset($tp['all_users']);
$toggleBase = 'errors.php?' . http_build_query($tp); ?>
<input type="checkbox" class="form-check-input" <?= $show_all_users ? 'checked' : '' ?>
onchange="window.location.href='<?= htmlspecialchars($toggleBase) ?>' + (this.checked ? '&all_users=1' : '')">
Show all users
</label>
</span>
<span class="text-muted" style="font-size:12px;">(<?= count($rowsData) ?> of <?= $totalRows ?> errori<?= !$show_all_users ? ' — my records' : '' ?>)</span>
</div>
<?php if ($totalPages > 1):
$pageQuery = $_GET;
unset($pageQuery['page']);
$pageBase = 'errors.php?' . http_build_query($pageQuery); ?>
<div class="pager-bar">
<span>Pagina <?= $page ?> di <?= $totalPages ?> — <?= $totalRows ?> righe</span>
<span>
<?php for ($p = 1; $p <= $totalPages; $p++): ?>
<a href="<?= htmlspecialchars($pageBase . '&page=' . $p) ?>" class="pager-num <?= $p === $page ? 'active' : '' ?>"><?= $p ?></a>
<?php endfor; ?>
</span>
</div>
<?php endif; ?>
<div class="card radius-10">
<div class="card-header">
<span style="font-weight:600;"><i class="fas fa-triangle-exclamation" style="color:#dc3545;"></i> Export falliti verso il LIMS</span>
</div>
<div class="card-body">
<?php if (empty($rowsData)): ?>
<p class="text-muted mb-0">Nessun errore di export. 🎉</p>
<?php else: ?>
<div style="overflow-x:auto;">
<table class="err-table">
<thead>
<tr>
<th style="width:170px;">Azioni</th>
<th>Status</th>
<th>Client</th>
<th>Errore</th>
<th style="width:150px;">Data export</th>
<th>File import</th>
</tr>
</thead>
<tbody>
<?php foreach ($rowsData as $row):
$errMsg = extractErrorSummary($logDir, $row['log_file'] ?? null); ?>
<tr data-id="<?= (int)$row['iddatadb'] ?>">
<td>
<button type="button" class="action-btn btn-resend resend-btn" data-iddatadb="<?= (int)$row['iddatadb'] ?>" title="Reinvia al LIMS"><i class="fas fa-paper-plane"></i></button>
<?php if (!empty($row['log_file'])): ?>
<a href="download_logs.php?iddatadb=<?= (int)$row['iddatadb'] ?>" class="action-btn btn-log" title="Scarica log"><i class="fas fa-file-download"></i></a>
<?php endif; ?>
<button type="button" class="action-btn btn-revert revert-btn" data-iddatadb="<?= (int)$row['iddatadb'] ?>" title="Riporta a Imported"><i class="fas fa-rotate-left"></i></button>
</td>
<td>
<span class="status-badge status-x">Error</span>
<?php if (!empty($row['commessaweb'])): ?>
<span class="commessa-code"><?= htmlspecialchars($row['commessaweb']) ?></span>
<?php endif; ?>
</td>
<td><span class="client-text" data-client-id="<?= htmlspecialchars((string)($row['idclient'] ?? '')) ?>"><?= htmlspecialchars((string)($row['idclient'] ?? '')) ?></span></td>
<td class="err-msg"><?= htmlspecialchars($errMsg ?: '—') ?></td>
<td><?= htmlspecialchars((string)($row['export_date'] ?? '')) ?></td>
<td><?php if (!empty($row['filename_import'])): ?><a href="imported_trf/<?= htmlspecialchars($row['filename_import']) ?>" target="_blank">File</a><?php endif; ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php endif; ?>
</div>
</div>
</div>
</div>
<div class="overlay toggle-icon"></div>
<?php include('include/footer.php'); ?>
</div>
<?php include('jsinclude.php'); ?>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(function() {
// Risoluzione nomi cliente (come in tolims.php)
(function() {
const ids = new Set();
document.querySelectorAll('.client-text').forEach(el => {
const id = el.dataset.clientId;
if (id) ids.add(id);
});
ids.forEach(id => {
fetch('search_clienti.php?id=' + encodeURIComponent(id))
.then(r => r.json())
.then(j => {
const it = (j.results || [])[0];
if (it) document.querySelectorAll('.client-text[data-client-id="' + id + '"]').forEach(el => el.textContent = it.text);
})
.catch(() => {});
});
})();
// Reinvia: richiama export_to_lims.php. Se la commessa era già stata creata,
// il CHECK PRELIMINARE la verifica nel LIMS e non ne crea una seconda.
$(document).on('click', '.resend-btn', function() {
const $btn = $(this);
const iddatadb = $btn.data('iddatadb');
if (!confirm('Reinviare questa commessa al LIMS? Se risulta già nel LIMS verrà solo riallineata, altrimenti ne verrà creata una nuova.')) return;
const original = $btn.html();
$btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i>');
$.ajax({
url: 'export_to_lims.php',
method: 'POST',
dataType: 'json',
data: {
iddatadb: iddatadb
},
success: function(res) {
if (res && res.success) {
const $tr = $('tr[data-id="' + iddatadb + '"]');
$tr.css('background', '#d4edda');
setTimeout(() => $tr.fadeOut(300, () => $tr.remove()), 500);
} else {
alert('Ancora errore: ' + ((res && res.message) ? res.message : 'invio non riuscito'));
$btn.prop('disabled', false).html(original);
}
},
error: function() {
alert('Errore di rete durante il reinvio.');
$btn.prop('disabled', false).html(original);
}
});
});
// Revert a Imported (i)
$(document).on('click', '.revert-btn', function() {
const $btn = $(this);
const iddatadb = $btn.data('iddatadb');
if (!confirm('Riportare questo record a Imported (i)?')) return;
$.ajax({
url: 'revert_status.php',
method: 'POST',
dataType: 'json',
data: {
iddatadb: iddatadb,
status: 'i'
},
success: function(res) {
if (res && res.success) {
const $tr = $('tr[data-id="' + iddatadb + '"]');
$tr.fadeOut(300, () => $tr.remove());
} else {
alert('Errore: ' + ((res && res.message) ? res.message : 'operazione non riuscita'));
}
},
error: function() {
alert('Errore di rete.');
}
});
});
});
</script>
</body>
</html>
+434 -123
View File
@@ -5,7 +5,7 @@
* Single export + batch export (Export All) with validation.
*/
(function () {
'use strict';
"use strict";
let pendingConfirmHandler = null;
let batchRunning = false;
@@ -17,19 +17,62 @@
// ── Helpers ──────────────────────────────────────────────────────────
function cleanupBackdrop() {
document.querySelectorAll(".modal-backdrop").forEach(b => b.remove());
document.querySelectorAll(".modal-backdrop").forEach((b) => b.remove());
document.body.classList.remove("modal-open");
document.body.style.paddingRight = "";
const overlay = document.querySelector(".overlay.toggle-icon");
if (overlay) overlay.style.display = "none";
}
function escHtml(v) {
return String(v ?? "")
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&#039;");
}
// Badge "No price" con tooltip dei nomi analisi (vuoto se count = 0)
function noPriceBadgeHTML(count, names) {
const n = parseInt(count, 10) || 0;
if (n <= 0) return "";
const title = (names || []).join("\n");
return `<span class="badge bg-danger no-price-badge" title="${escHtml(title)}" style="margin-left:6px; font-size:0.85em; cursor:help; vertical-align:middle;"><i class="fas fa-exclamation-triangle"></i> No price (${n})</span>`;
}
window.noPriceBadgeHTML = noPriceBadgeHTML;
function getGridRow(iddatadb) {
return document.querySelector(`.grid-row[data-id="${iddatadb}"]`);
}
function getRowIndexByIddatadb(iddatadb) {
return (window.gridData || []).findIndex(r => String(r.iddatadb) === String(iddatadb));
return (window.gridData || []).findIndex(
(r) => String(r.iddatadb) === String(iddatadb),
);
}
// Invia la mail di riepilogo per gli iddatadb processati (fire-and-forget).
// Una sola chiamata a fine export (singolo o batch).
function sendExportSummaryMail(iddatadbList) {
const ids = (iddatadbList || [])
.map((v) => parseInt(v, 10))
.filter(Boolean);
if (!ids.length) return;
const body = new URLSearchParams();
ids.forEach((id) => body.append("ids[]", id));
const tid = window.gridMeta && window.gridMeta.templateId;
if (tid) body.append("template_id", tid);
fetch("send_export_summary.php", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: body.toString(),
})
.then((r) => r.json())
.then((res) => console.log("Summary mail:", res))
.catch((err) => console.warn("Summary mail failed:", err));
}
// ── Validation ──────────────────────────────────────────────────────
@@ -40,21 +83,31 @@
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ rows: rowsToValidate }),
});
if (!response.ok) throw new Error(`Validation HTTP error: ${response.status}`);
if (!response.ok)
throw new Error(`Validation HTTP error: ${response.status}`);
return response.json();
}
function clearValidationErrors() {
// Clear from gridData
(window.gridData || []).forEach(row => { delete row._validationErrors; delete row._exportError; });
document.querySelectorAll(".grid-cell.validation-error").forEach(cell => {
cell.classList.remove("validation-error");
cell.querySelectorAll(".input-validation-error").forEach(el => el.classList.remove("input-validation-error"));
const tooltip = cell.querySelector(".validation-tooltip");
if (tooltip) tooltip.remove();
(window.gridData || []).forEach((row) => {
delete row._validationErrors;
delete row._exportError;
});
document.querySelectorAll(".grid-row.validation-row-error").forEach(row => row.classList.remove("validation-row-error"));
document
.querySelectorAll(".grid-cell.validation-error")
.forEach((cell) => {
cell.classList.remove("validation-error");
cell.querySelectorAll(".input-validation-error").forEach((el) =>
el.classList.remove("input-validation-error"),
);
const tooltip = cell.querySelector(".validation-tooltip");
if (tooltip) tooltip.remove();
});
document
.querySelectorAll(".grid-row.validation-row-error")
.forEach((row) => row.classList.remove("validation-row-error"));
clearAllRowErrors();
}
@@ -67,7 +120,7 @@
gridRow.classList.add("validation-row-error");
const messages = [];
errors.forEach(err => {
errors.forEach((err) => {
messages.push(err.message);
if (!err.field) return;
@@ -76,19 +129,26 @@
const label = err.field.substring("field_label:".length);
const headers = document.querySelectorAll(".grid-header");
let targetIndex = null;
headers.forEach(h => {
if (h.textContent.trim() === label) targetIndex = h.getAttribute("data-index");
headers.forEach((h) => {
if (h.textContent.trim() === label)
targetIndex = h.getAttribute("data-index");
});
if (targetIndex) {
cell = gridRow.querySelector(`.grid-cell[data-index="${targetIndex}"]`);
cell = gridRow.querySelector(
`.grid-cell[data-index="${targetIndex}"]`,
);
}
} else {
cell = gridRow.querySelector(`.grid-cell[data-col="${err.field}"]`);
cell = gridRow.querySelector(
`.grid-cell[data-col="${err.field}"]`,
);
}
if (cell) {
cell.classList.add("validation-error");
cell.querySelectorAll("input, select").forEach(el => el.classList.add("input-validation-error"));
cell.querySelectorAll("input, select").forEach((el) =>
el.classList.add("input-validation-error"),
);
let tooltip = cell.querySelector(".validation-tooltip");
if (!tooltip) {
tooltip = document.createElement("div");
@@ -109,37 +169,67 @@
formData.append("iddatadb", iddatadb);
if (batchUuid) formData.append("batch_uuid", batchUuid);
const response = await fetch("export_to_lims.php", { method: "POST", body: formData });
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
const data = await response.json();
// Marca la riga come "in export" nei dati: se il grid virtuale la ri-renderizza
// durante l'attesa, il pulsante Export resta disabilitato.
const startIdx = getRowIndexByIddatadb(iddatadb);
if (startIdx >= 0) window.gridData[startIdx]._exporting = true;
if (data.success) {
let data;
try {
const response = await fetch("export_to_lims.php", {
method: "POST",
body: formData,
});
if (!response.ok)
throw new Error(`HTTP error! status: ${response.status}`);
data = await response.json();
} finally {
const endIdx = getRowIndexByIddatadb(iddatadb);
if (endIdx >= 0) delete window.gridData[endIdx]._exporting;
}
// Rifiutato perché la riga risulta già esportata (pagina non aggiornata):
// allinea la griglia allo stato reale invece di lasciarla esportabile.
if (data.success || (data.rejected && data.status === "l")) {
// Update gridData
const idx = getRowIndexByIddatadb(iddatadb);
if (idx >= 0) {
window.gridData[idx].status = 'l';
window.gridData[idx].status = "l";
window.gridData[idx].commessaweb = data.commessaweb;
window.gridData[idx].noPriceCount = data.noPriceCount || 0;
window.gridData[idx].noPriceAnalyses =
data.noPriceAnalyses || [];
}
// Update visible DOM row
const gridRow = getGridRow(iddatadb);
if (gridRow) {
const statusBadge = gridRow.querySelector('.grid-cell[data-col="status"] .status-badge');
const statusBadge = gridRow.querySelector(
'.grid-cell[data-col="status"] .status-badge',
);
if (statusBadge) {
statusBadge.classList.remove("status-i", "status-P");
statusBadge.classList.add("status-l");
statusBadge.textContent = "To LIMS";
}
const statusCell = gridRow.querySelector('.grid-cell[data-col="status"]');
const statusCell = gridRow.querySelector(
'.grid-cell[data-col="status"]',
);
if (statusCell && data.commessaweb) {
let cwSpan = statusCell.querySelector(".commessaweb-code");
if (!cwSpan) {
cwSpan = document.createElement("span");
cwSpan.className = "commessaweb-code";
cwSpan.style.cssText = "display:block; font-size:0.75em; color:#555; margin-top:2px;";
cwSpan.style.cssText =
"display:block; font-size:0.75em; color:#555; margin-top:2px;";
statusCell.appendChild(cwSpan);
}
cwSpan.textContent = data.commessaweb;
const npHtml = noPriceBadgeHTML(
data.noPriceCount,
data.noPriceAnalyses,
);
if (npHtml) cwSpan.insertAdjacentHTML("beforeend", npHtml);
}
const exportBtn = gridRow.querySelector(".export-lims-btn");
if (exportBtn) {
@@ -164,10 +254,20 @@
const label = document.getElementById("exportResponseModalLabel");
if (data.success) {
msg.innerHTML = `${data.message.replace(/\n/g, "<br>")}` +
msg.innerHTML =
`${data.message.replace(/\n/g, "<br>")}` +
`<br>ID CommessaWeb: ${data.idcommessaweb}` +
`<br>Codice CommessaWeb: ${data.commessaweb}` +
(data.totalPhotos > 0 ? `<br>Foto: ${data.totalPhotos}` : "");
`<br>Codice CommessaWeb: ${escHtml(data.commessaweb)}` +
noPriceBadgeHTML(data.noPriceCount, data.noPriceAnalyses) +
(data.totalPhotos > 0 ? `<br>Foto: ${data.totalPhotos}` : "") +
(data.noPriceCount > 0
? `<div class="mt-2 small text-danger fw-semibold">Analisi senza prezzo:</div>` +
`<ul class="mb-0 small text-danger">` +
(data.noPriceAnalyses || [])
.map((n) => `<li>${escHtml(n)}</li>`)
.join("") +
`</ul>`
: "");
label.textContent = "Esportazione Completata";
} else {
msg.textContent = `Errore: ${data.message}`;
@@ -186,10 +286,14 @@
row.classList.remove("batch-disabled");
row.classList.add("batch-exporting");
if (btnCell) {
btnCell.querySelectorAll(".action-btn").forEach(b => { b.dataset.prevDisplay = b.style.display; b.style.display = "none"; });
btnCell.querySelectorAll(".action-btn").forEach((b) => {
b.dataset.prevDisplay = b.style.display;
b.style.display = "none";
});
const spinner = document.createElement("span");
spinner.className = "batch-row-spinner";
spinner.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Exporting...';
spinner.innerHTML =
'<i class="fas fa-spinner fa-spin"></i> Exporting...';
btnCell.appendChild(spinner);
}
} else {
@@ -197,7 +301,10 @@
if (btnCell) {
const spinner = btnCell.querySelector(".batch-row-spinner");
if (spinner) spinner.remove();
btnCell.querySelectorAll(".action-btn").forEach(b => { b.style.display = b.dataset.prevDisplay || ""; delete b.dataset.prevDisplay; });
btnCell.querySelectorAll(".action-btn").forEach((b) => {
b.style.display = b.dataset.prevDisplay || "";
delete b.dataset.prevDisplay;
});
}
}
}
@@ -213,32 +320,56 @@
errorEl.className = "batch-error-msg";
errorEl.textContent = "Warning — click for details";
errorEl.addEventListener("click", () => {
document.getElementById("exportResponseMessage").innerHTML = message.replace(/\n/g, "<br>");
document.getElementById("exportResponseModalLabel").textContent = "Error (id: " + iddatadb + ")";
new bootstrap.Modal(document.getElementById("exportResponseModal"), { keyboard: false }).show();
document.getElementById("exportResponseMessage").innerHTML =
message.replace(/\n/g, "<br>");
document.getElementById(
"exportResponseModalLabel",
).textContent = "Error (id: " + iddatadb + ")";
new bootstrap.Modal(
document.getElementById("exportResponseModal"),
{ keyboard: false },
).show();
});
btnCell.appendChild(errorEl);
}
}
function clearAllRowErrors() {
document.querySelectorAll(".grid-row.batch-row-error").forEach(row => {
row.classList.remove("batch-row-error");
const msg = row.querySelector(".batch-error-msg");
if (msg) msg.remove();
});
document
.querySelectorAll(".grid-row.batch-row-error")
.forEach((row) => {
row.classList.remove("batch-row-error");
const msg = row.querySelector(".batch-error-msg");
if (msg) msg.remove();
});
}
function disableAllRowButtons() {
document.querySelectorAll(".grid-row[data-id]").forEach(row => row.classList.add("batch-disabled"));
const toggle = document.querySelector(".actions-dropdown .dropdown-toggle");
if (toggle) { toggle.disabled = true; toggle.style.opacity = "0.5"; toggle.style.pointerEvents = "none"; }
document
.querySelectorAll(".grid-row[data-id]")
.forEach((row) => row.classList.add("batch-disabled"));
const toggle = document.querySelector(
".actions-dropdown .dropdown-toggle",
);
if (toggle) {
toggle.disabled = true;
toggle.style.opacity = "0.5";
toggle.style.pointerEvents = "none";
}
}
function enableAllRowButtons() {
document.querySelectorAll(".grid-row[data-id]").forEach(row => row.classList.remove("batch-disabled"));
const toggle = document.querySelector(".actions-dropdown .dropdown-toggle");
if (toggle) { toggle.disabled = false; toggle.style.opacity = ""; toggle.style.pointerEvents = ""; }
document
.querySelectorAll(".grid-row[data-id]")
.forEach((row) => row.classList.remove("batch-disabled"));
const toggle = document.querySelector(
".actions-dropdown .dropdown-toggle",
);
if (toggle) {
toggle.disabled = false;
toggle.style.opacity = "";
toggle.style.pointerEvents = "";
}
}
// ── Single row export: validate → confirm → send ────────────────────
@@ -250,40 +381,61 @@
if (gridRow) {
setRowExporting(gridRow, true);
const spinner = gridRow.querySelector(".batch-row-spinner");
if (spinner) spinner.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Validating...';
if (spinner)
spinner.innerHTML =
'<i class="fas fa-spinner fa-spin"></i> Validating...';
}
validateRows([{ iddatadb: parseInt(iddatadb), index: rowIndex }])
.then(validationData => {
if (gridRow) { setRowExporting(gridRow, false); gridRow.classList.remove("batch-disabled"); }
.then((validationData) => {
if (gridRow) {
setRowExporting(gridRow, false);
gridRow.classList.remove("batch-disabled");
}
if (!validationData.success) {
showExportResult({ success: false, message: validationData.message || "Validation error" });
showExportResult({
success: false,
message: validationData.message || "Validation error",
});
return;
}
const result = validationData.results[rowIndex];
if (result && !result.valid) {
if (gridRow) showValidationErrors(gridRow, iddatadb, result.errors);
if (gridRow)
showValidationErrors(gridRow, iddatadb, result.errors);
return;
}
showConfirmAndExport(iddatadb, rowIndex);
})
.catch(error => {
if (gridRow) { setRowExporting(gridRow, false); gridRow.classList.remove("batch-disabled"); }
showExportResult({ success: false, message: "Validation error: " + error.message });
.catch((error) => {
if (gridRow) {
setRowExporting(gridRow, false);
gridRow.classList.remove("batch-disabled");
}
showExportResult({
success: false,
message: "Validation error: " + error.message,
});
});
}
function showConfirmAndExport(iddatadb, rowIndex) {
const confirmModalElement = document.getElementById("exportConfirmModal");
const confirmModalElement =
document.getElementById("exportConfirmModal");
if (!confirmModalElement) return;
const confirmModal = new bootstrap.Modal(confirmModalElement, { keyboard: false });
const confirmModal = new bootstrap.Modal(confirmModalElement, {
keyboard: false,
});
document.getElementById("exportIddatadb").textContent = iddatadb;
confirmModal.show();
const confirmBtn = document.getElementById("exportConfirmBtn");
if (!confirmBtn) { confirmModal.hide(); return; }
if (!confirmBtn) {
confirmModal.hide();
return;
}
const confirmHandler = async () => {
pendingConfirmHandler = null;
@@ -294,24 +446,42 @@
try {
const data = await sendExport(iddatadb);
if (gridRow) { setRowExporting(gridRow, false); gridRow.classList.remove("batch-disabled"); }
if (!data.success) showRowError(gridRow, iddatadb, data.message || "Unknown error");
if (gridRow) {
setRowExporting(gridRow, false);
gridRow.classList.remove("batch-disabled");
}
if (!data.success)
showRowError(
gridRow,
iddatadb,
data.message || "Unknown error",
);
showExportResult(data);
// Mail di riepilogo per la singola commessa (non per un export rifiutato:
// non è stato inviato nulla e la riga può risultare già 'l')
if (!data.rejected) sendExportSummaryMail([iddatadb]);
} catch (error) {
if (gridRow) { setRowExporting(gridRow, false); gridRow.classList.remove("batch-disabled"); }
if (gridRow) {
setRowExporting(gridRow, false);
gridRow.classList.remove("batch-disabled");
}
showRowError(gridRow, iddatadb, error.message);
showExportResult({ success: false, message: error.message });
// Timeout/errore di rete: il server può aver completato lo stesso.
// La mail riporta lo stato reale della riga in DB.
sendExportSummaryMail([iddatadb]);
}
};
if (pendingConfirmHandler) confirmBtn.removeEventListener("click", pendingConfirmHandler);
if (pendingConfirmHandler)
confirmBtn.removeEventListener("click", pendingConfirmHandler);
pendingConfirmHandler = confirmHandler;
confirmBtn.addEventListener("click", confirmHandler, { once: true });
}
// ── Single row click (event delegation) ─────────────────────────────
$(document).on('click', '.export-lims-btn', function (e) {
$(document).on("click", ".export-lims-btn", function (e) {
e.preventDefault();
if (batchRunning) return;
@@ -322,24 +492,34 @@
// Check unsaved changes for this row
const dataRow = window.gridData?.[rowIndex];
if (dataRow && dataRow._dirty) {
const unsavedModal = new bootstrap.Modal(document.getElementById("exportUnsavedModal"), { keyboard: false });
const unsavedModal = new bootstrap.Modal(
document.getElementById("exportUnsavedModal"),
{ keyboard: false },
);
unsavedModal.show();
document.getElementById("saveAndExportBtn")?.addEventListener("click", () => {
unsavedModal.hide();
// Save first, then export
const formData = window.buildSavePayload(rowIndex);
fetch('save_edited_row.php', { method: 'POST', body: formData })
.then(r => r.json())
.then(result => {
if (result.success) {
dataRow._dirty = false;
startExportConfirmFlow(iddatadb, rowIndex);
} else {
alert('Save failed: ' + result.message);
}
});
}, { once: true });
document.getElementById("saveAndExportBtn")?.addEventListener(
"click",
() => {
unsavedModal.hide();
// Save first, then export
const formData = window.buildSavePayload(rowIndex);
fetch("save_edited_row.php", {
method: "POST",
body: formData,
})
.then((r) => r.json())
.then((result) => {
if (result.success) {
dataRow._dirty = false;
startExportConfirmFlow(iddatadb, rowIndex);
} else {
alert("Save failed: " + result.message);
}
});
},
{ once: true },
);
return;
}
@@ -349,18 +529,33 @@
// ── Batch export (Export All) ───────────────────────────────────────
function collectEligibleRows() {
// Read from gridData, not DOM
// Read from gridData, not DOM. Se i filtri sono attivi, limita al target set.
const target =
typeof window.getTargetGridIds === "function"
? window.getTargetGridIds()
: null;
const eligible = [];
(window.gridData || []).forEach((row, index) => {
if (row.status !== 'l') {
eligible.push({ iddatadb: row.iddatadb, index, row: getGridRow(row.iddatadb) });
}
if (row.status === "l") return;
if (target && !target.has(parseInt(row.iddatadb, 10))) return;
eligible.push({
iddatadb: row.iddatadb,
index,
row: getGridRow(row.iddatadb),
});
});
return eligible;
}
function hasUnsavedChanges() {
return (window.gridData || []).some(r => r._dirty);
const target =
typeof window.getTargetGridIds === "function"
? window.getTargetGridIds()
: null;
return (window.gridData || []).some(
(r) =>
r._dirty && (!target || target.has(parseInt(r.iddatadb, 10))),
);
}
async function validateAndFilter(eligibleRows) {
@@ -369,7 +564,8 @@
index,
}));
const validationData = await validateRows(rowsToValidate);
if (!validationData.success) throw new Error(validationData.message || "Validation error");
if (!validationData.success)
throw new Error(validationData.message || "Validation error");
const validRows = [];
let invalidCount = 0;
@@ -377,7 +573,12 @@
for (const item of eligibleRows) {
const result = validationData.results[item.index];
if (result && !result.valid) {
if (item.row) showValidationErrors(item.row, item.iddatadb, result.errors);
if (item.row)
showValidationErrors(
item.row,
item.iddatadb,
result.errors,
);
invalidCount++;
} else {
validRows.push(item);
@@ -410,54 +611,92 @@
if (validRows.length === 0) {
document.getElementById("exportResponseMessage").innerHTML =
`No valid rows for export.<br><strong>${invalidCount}</strong> rows with validation errors.`;
document.getElementById("exportResponseModalLabel").textContent = "Validation Failed";
new bootstrap.Modal(document.getElementById("exportResponseModal"), { keyboard: false }).show();
document.getElementById(
"exportResponseModalLabel",
).textContent = "Validation Failed";
new bootstrap.Modal(
document.getElementById("exportResponseModal"),
{ keyboard: false },
).show();
return;
}
const confirmModal = new bootstrap.Modal(document.getElementById("exportBatchConfirmModal"), { keyboard: false });
const confirmModal = new bootstrap.Modal(
document.getElementById("exportBatchConfirmModal"),
{ keyboard: false },
);
let countText = String(validRows.length);
if (invalidCount > 0) countText += ` (${invalidCount} excluded due to errors)`;
document.getElementById("exportBatchCount").textContent = countText;
if (invalidCount > 0)
countText += ` (${invalidCount} excluded due to errors)`;
document.getElementById("exportBatchCount").textContent =
countText;
confirmModal.show();
const confirmBtn = document.getElementById("exportBatchConfirmBtn");
if (pendingBatchConfirmHandler) confirmBtn.removeEventListener("click", pendingBatchConfirmHandler);
const confirmBtn = document.getElementById(
"exportBatchConfirmBtn",
);
if (pendingBatchConfirmHandler)
confirmBtn.removeEventListener(
"click",
pendingBatchConfirmHandler,
);
pendingBatchConfirmHandler = () => {
pendingBatchConfirmHandler = null;
confirmModal.hide();
startBatchExport(validRows);
};
confirmBtn.addEventListener("click", pendingBatchConfirmHandler, { once: true });
confirmBtn.addEventListener(
"click",
pendingBatchConfirmHandler,
{ once: true },
);
})
.catch(error => {
.catch((error) => {
showValidationSpinner(false);
document.getElementById("exportResponseMessage").textContent = "Validation error: " + error.message;
document.getElementById("exportResponseModalLabel").textContent = "Validation Error";
new bootstrap.Modal(document.getElementById("exportResponseModal"), { keyboard: false }).show();
document.getElementById("exportResponseMessage").textContent =
"Validation error: " + error.message;
document.getElementById(
"exportResponseModalLabel",
).textContent = "Validation Error";
new bootstrap.Modal(
document.getElementById("exportResponseModal"),
{ keyboard: false },
).show();
});
}
$(document).on('click', '.export-all-lims-btn', function (e) {
$(document).on("click", ".export-all-lims-btn", function (e) {
e.preventDefault();
if (batchRunning) return;
if (hasUnsavedChanges()) {
const unsavedModal = new bootstrap.Modal(document.getElementById("exportBatchUnsavedModal"), { keyboard: false });
const unsavedModal = new bootstrap.Modal(
document.getElementById("exportBatchUnsavedModal"),
{ keyboard: false },
);
unsavedModal.show();
document.getElementById("batchSaveAndExportBtn")?.addEventListener("click", () => {
unsavedModal.hide();
// Trigger save all first — listen for completion
alert("Please Save All first, then Export All.");
}, { once: true });
document.getElementById("batchSaveAndExportBtn")?.addEventListener(
"click",
() => {
unsavedModal.hide();
// Trigger save all first — listen for completion
alert("Please Save All first, then Export All.");
},
{ once: true },
);
return;
}
const eligibleRows = collectEligibleRows();
if (eligibleRows.length === 0) {
document.getElementById("exportResponseMessage").textContent = "All rows already exported to LIMS.";
document.getElementById("exportResponseModalLabel").textContent = "Export All";
new bootstrap.Modal(document.getElementById("exportResponseModal"), { keyboard: false }).show();
document.getElementById("exportResponseMessage").textContent =
"All rows already exported to LIMS.";
document.getElementById("exportResponseModalLabel").textContent =
"Export All";
new bootstrap.Modal(
document.getElementById("exportResponseModal"),
{ keyboard: false },
).show();
return;
}
showBatchConfirm(eligibleRows);
@@ -468,7 +707,12 @@
batchRunning = true;
const batchUuid = crypto.randomUUID();
const total = eligibleRows.length;
let processed = 0, succeeded = 0, failed = 0;
let processed = 0,
succeeded = 0,
failed = 0,
skipped = 0;
const exportedList = []; // { commessaweb, noPriceCount, noPriceAnalyses }
const processedIds = []; // iddatadb processati (ok o errore) per la mail
disableAllRowButtons();
@@ -479,18 +723,25 @@
if (cancelBtn) cancelBtn.disabled = false;
if (statusEl) statusEl.textContent = `Exporting 0 / ${total}...`;
cancelBtn?.addEventListener("click", () => {
batchCancelled = true;
if (statusEl) statusEl.textContent = "Cancelling... (waiting for current row)";
if (cancelBtn) cancelBtn.disabled = true;
}, { once: true });
cancelBtn?.addEventListener(
"click",
() => {
batchCancelled = true;
if (statusEl)
statusEl.textContent =
"Cancelling... (waiting for current row)";
if (cancelBtn) cancelBtn.disabled = true;
},
{ once: true },
);
(async () => {
for (let i = 0; i < eligibleRows.length; i++) {
if (batchCancelled) break;
const { iddatadb, row } = eligibleRows[i];
if (statusEl) statusEl.textContent = `Exporting ${processed + 1} / ${total} (id: ${iddatadb})...`;
if (statusEl)
statusEl.textContent = `Exporting ${processed + 1} / ${total} (id: ${iddatadb})...`;
const gridRow = row || getGridRow(iddatadb);
if (gridRow) setRowExporting(gridRow, true);
@@ -498,29 +749,56 @@
try {
const data = await sendExport(iddatadb, batchUuid);
processed++;
if (data.success) {
if (data.rejected) {
// Già esportata / export in corso altrove: niente inviato, fuori dalla mail
skipped++;
if (data.status !== "l" && gridRow)
showRowError(gridRow, iddatadb, data.message);
} else if (data.success) {
processedIds.push(iddatadb);
succeeded++;
exportedList.push({
commessaweb: data.commessaweb,
noPriceCount: data.noPriceCount || 0,
noPriceAnalyses: data.noPriceAnalyses || [],
});
} else {
failed++;
processedIds.push(iddatadb);
const errIdx = getRowIndexByIddatadb(iddatadb);
if (errIdx >= 0) window.gridData[errIdx]._exportError = data.message || "Unknown error";
if (gridRow) showRowError(gridRow, iddatadb, data.message || "Unknown error");
if (errIdx >= 0)
window.gridData[errIdx]._exportError =
data.message || "Unknown error";
if (gridRow)
showRowError(
gridRow,
iddatadb,
data.message || "Unknown error",
);
}
} catch (error) {
processed++;
failed++;
processedIds.push(iddatadb);
const errIdx = getRowIndexByIddatadb(iddatadb);
if (errIdx >= 0) window.gridData[errIdx]._exportError = error.message;
if (errIdx >= 0)
window.gridData[errIdx]._exportError = error.message;
if (gridRow) showRowError(gridRow, iddatadb, error.message);
}
if (gridRow) { setRowExporting(gridRow, false); gridRow.classList.remove("batch-disabled"); }
if (gridRow) {
setRowExporting(gridRow, false);
gridRow.classList.remove("batch-disabled");
}
}
batchRunning = false;
enableAllRowButtons();
if (bar) bar.style.display = "none";
// Mail di riepilogo unica per tutto il batch processato
sendExportSummaryMail(processedIds);
// Re-render to reflect status changes, then restore error indicators
const gr = window.gridRenderer;
if (gr) gr.renderVisibleRows();
@@ -529,7 +807,8 @@
(window.gridData || []).forEach((row, idx) => {
if (row._exportError) {
const gridRow = getGridRow(row.iddatadb);
if (gridRow) showRowError(gridRow, row.iddatadb, row._exportError);
if (gridRow)
showRowError(gridRow, row.iddatadb, row._exportError);
}
});
@@ -539,17 +818,49 @@
if (batchCancelled) {
labelEl.textContent = "Export All — Cancelled";
msgEl.innerHTML = `Exported: <strong>${succeeded}</strong><br>Errors: <strong>${failed}</strong><br>Not processed: <strong>${total - processed}</strong>`;
} else if (failed === 0) {
} else if (failed === 0 && skipped === 0) {
labelEl.textContent = "Export All — Complete";
msgEl.innerHTML = `All <strong>${succeeded}</strong> rows exported successfully.`;
} else {
labelEl.textContent = "Export All — Completed with errors";
labelEl.textContent =
failed > 0
? "Export All — Completed with errors"
: "Export All — Complete";
msgEl.innerHTML = `Exported: <strong>${succeeded}</strong><br>Errors: <strong>${failed}</strong>`;
}
if (skipped > 0)
msgEl.innerHTML += `<br>Skipped (already exported / in progress — reload the page): <strong>${skipped}</strong>`;
if (exportedList.length) {
const npCommesse = exportedList.filter(
(x) => x.noPriceCount > 0,
).length;
msgEl.innerHTML +=
`<hr class="my-2">` +
(npCommesse > 0
? `<div class="small text-danger fw-semibold mb-1"><i class="fas fa-exclamation-triangle"></i> ${npCommesse} commesse con analisi senza prezzo</div>`
: "") +
`<div class="small fw-semibold mb-1">Commesse esportate:</div>` +
`<ul class="mb-0 ps-3">` +
exportedList
.map(
(x) =>
`<li><span style="font-family:monospace;">${escHtml(x.commessaweb || "—")}</span>` +
noPriceBadgeHTML(
x.noPriceCount,
x.noPriceAnalyses,
) +
`</li>`,
)
.join("") +
`</ul>`;
}
const modalEl = document.getElementById("exportResponseModal");
new bootstrap.Modal(modalEl, { keyboard: false }).show();
modalEl.addEventListener("hidden.bs.modal", cleanupBackdrop, { once: true });
modalEl.addEventListener("hidden.bs.modal", cleanupBackdrop, {
once: true,
});
})();
}
})();
+216 -27
View File
@@ -55,22 +55,29 @@ $apiBaseUrl = 'https://93.43.5.102/limsapi/api/odata/';
// 🔹 Batch UUID — if present, all logs go to a single file
$batchUuid = $_POST['batch_uuid'] ?? null;
$writeLog = (function () use ($batchUuid, $logDir) {
$batchLogFile = $batchUuid ? $logDir . "batch_export_{$batchUuid}.log" : null;
// File unico per questa commessa (nominato per iddatadb, che conosciamo sempre)
$iddatadbForLog = $_POST['iddatadb'] ?? 'unknown';
$commessaLogFile = $logDir . "commessa_{$iddatadbForLog}_" . time() . ".log";
return function ($individualPath, $content, $stepLabel = null) use ($batchLogFile) {
if ($batchLogFile) {
$header = "\n" . str_repeat("=", 60) . "\n";
if ($stepLabel) {
$header .= "[{$stepLabel}] " . date('Y-m-d H:i:s') . "\n";
}
$header .= str_repeat("=", 60) . "\n";
file_put_contents($batchLogFile, $header . $content . "\n", FILE_APPEND);
} else {
file_put_contents($individualPath, $content);
}
};
})();
// File di lotto: resta come INDICE (quali commesse nel lotto), non più tutti gli step
$batchIndexFile = $batchUuid ? $logDir . "batch_export_{$batchUuid}.log" : null;
// $writeLog ora appende sempre sul file unico della commessa, con header di step
$writeLog = function ($individualPath, $content, $stepLabel = null) use ($commessaLogFile) {
$header = "\n" . str_repeat("=", 60) . "\n";
if ($stepLabel) {
$header .= "[{$stepLabel}] " . date('Y-m-d H:i:s') . "\n";
}
$header .= str_repeat("=", 60) . "\n";
file_put_contents($commessaLogFile, $header . $content . "\n", FILE_APPEND);
};
// Helper per registrare una riga nell'indice di lotto
$writeBatchIndex = function ($line) use ($batchIndexFile) {
if ($batchIndexFile) {
file_put_contents($batchIndexFile, "[" . date('Y-m-d H:i:s') . "] " . $line . "\n", FILE_APPEND);
}
};
// 🔹 Funzione per validare e convertire date
function validateDate($value)
@@ -136,6 +143,100 @@ function importaCommessaWithRetry($api, $commessaId, array $payload, $maxRetries
];
}
// 🔹 CHECK PRELIMINARE + LOCK: una sola esportazione per riga, mai una seconda commessa.
// Protegge da pagine non aggiornate (due schede, pagina Errors vecchia, doppio click,
// LIMS lento con richiesta ancora in corso).
$chkId = (int)($_POST['iddatadb'] ?? 0);
if ($chkId > 0) {
$rejectExport = function ($reason, $cur = null) use ($chkId, $commessaLogFile, $writeBatchIndex, $batchUuid) {
file_put_contents(
$commessaLogFile,
"\n[EXPORT RIFIUTATO] " . date('Y-m-d H:i:s') . " | {$reason}" .
" | user_id=" . ($GLOBALS['iduserlogin'] ?? 'n/d') .
" | IP=" . ($_SERVER['REMOTE_ADDR'] ?? '-') .
" | batch=" . ($batchUuid ?? '-') . "\n",
FILE_APPEND
);
$writeBatchIndex("SKIP iddatadb={$chkId} :: {$reason}");
echo json_encode([
"success" => false,
"rejected" => true,
"status" => $cur['status'] ?? null,
"commessaweb" => $cur['commessaweb'] ?? null,
"message" => "Commessa non inviata (riga {$chkId}): {$reason}. Ricarica la pagina.",
]);
exit;
};
// Lock per riga: tenuto fino a fine script (rilasciato da MySQL alla chiusura connessione)
$gotLock = (int)$pdo->query("SELECT GET_LOCK(" . $pdo->quote("lims_export_{$chkId}") . ", 0)")->fetchColumn();
if ($gotLock !== 1) {
$rejectExport("esportazione già in corso");
}
$chk = $pdo->prepare("SELECT status, idcommessaweb, commessaweb FROM datadb WHERE iddatadb = ?");
$chk->execute([$chkId]);
$cur = $chk->fetch(PDO::FETCH_ASSOC);
if (!$cur) {
$rejectExport("riga non trovata");
}
if (!in_array($cur['status'], ['i', 'x'], true)) {
$rejectExport("già esportata (status={$cur['status']}, commessa=" . ($cur['commessaweb'] ?: '-') . ")", $cur);
}
$existingId = (int)($cur['idcommessaweb'] ?? 0);
if ($existingId > 0) {
// Commessa già creata da un export precedente (fallito, o interrotto da un crash/timeout PHP):
// controlla lo stato nel LIMS invece di crearne una nuova (sarebbe un duplicato).
// NB: il revert a 'i' azzera idcommessaweb, quindi qui non arrivano le righe riportate a mano.
$api = VisualLimsApiClient::getInstance();
try {
$existing = $api->get("CommessaWeb({$existingId})");
} catch (Exception $e) {
$existing = null;
if (strpos($e->getMessage(), 'HTTP 404') === false) {
$rejectExport("impossibile verificare la commessa {$existingId} nel LIMS: " . $e->getMessage(), $cur);
}
// 404: la commessa non esiste più nel LIMS → si può esportare da capo
}
$stato = $existing['StatoCommessaWeb'] ?? null;
$notSentYet = $existing !== null && $stato === 'Nuova' && empty($existing['DataInviatoWeb']);
$writeLog(null, "IdCommessa esistente: {$existingId}\nStatoCommessaWeb: " . ($stato ?? '404') .
"\nDataInviatoWeb: " . ($existing['DataInviatoWeb'] ?? '-'), "PRECHECK - commessa esistente (iddatadb={$chkId})");
if ($stato === 'Elaborata') {
// Già importata nel LIMS: riallinea la riga, nessuna nuova commessa
$codice = substr(trim((string)($existing['CodiceCommessa'] ?? '')), 0, 30);
$pdo->prepare("UPDATE datadb SET status = 'l', commessaweb = :c, log_file = :lf WHERE iddatadb = :id")
->execute(['c' => $codice, 'lf' => basename($commessaLogFile), 'id' => $chkId]);
$writeLog(null, "Riga riallineata: status='l', commessaweb={$codice}", "PRECHECK - RECOVERED (iddatadb={$chkId})");
$writeBatchIndex("RECOVERED iddatadb={$chkId} commessa={$existingId} codice={$codice}");
echo json_encode([
"success" => true,
"recovered" => true,
"idcommessaweb" => $existingId,
"commessaweb" => $codice,
"message" => "Commessa già presente nel LIMS: riga riallineata senza crearne una nuova",
]);
exit;
}
if ($existing !== null && !$notSentYet) {
// Inviata ma non (ancora) importata: rifare l'export creerebbe un duplicato → verifica manuale
$rejectExport("commessa {$existingId} già inviata al LIMS ma non ancora importata (stato: {$stato}). " .
"Riprova tra qualche minuto o verifica nel LIMS", $cur);
}
// 404 o mai inviata al laboratorio: si ricrea da capo (la vecchia CommessaWeb resta orfana in "Nuova")
$writeBatchIndex("RECREATE iddatadb={$chkId} old_commessa={$existingId} stato=" . ($stato ?? '404'));
}
}
try {
$iddatadb = $_POST['iddatadb'] ?? null;
if (!$iddatadb) {
@@ -151,6 +252,7 @@ try {
// Also fetch fixed fields stored in datadb
$stmt = $pdo->prepare("
SELECT d.idclient AS clienteId, et.idschema AS schemaId, et.id AS templateId,
et.template_note,
d.cliente_responsabile_id,
d.moltiplicatore_prezzo_id,
d.anagrafica_certest_object_id,
@@ -271,15 +373,32 @@ try {
return strcmp((string)($a['field_label'] ?? ''), (string)($b['field_label'] ?? ''));
});
// Valori "vuoti convenzionali" da NON includere nelle note.
// Il cliente usa "/" (e simili) come placeholder di campo vuoto.
$addnotePlaceholders = ['/', '-', 'n/a', 'na', 'n.a.', '//'];
foreach ($addnoteRows as $r) {
$val = trim((string)($r['field_value'] ?? ''));
if ($val !== '') {
$addnoteChunks[] = $val;
if ($val === '') {
continue;
}
// Scarta i placeholder (confronto case-insensitive)
if (in_array(mb_strtolower($val), $addnotePlaceholders, true)) {
continue;
}
$addnoteChunks[] = $val;
}
$addnoteText = implode(' - ', $addnoteChunks);
// Nota del template: appesa in fondo alle note in esportazione
$templateNote = trim((string)($result['template_note'] ?? ''));
if ($templateNote !== '') {
$addnoteText = $addnoteText !== ''
? $addnoteText . ' - ' . $templateNote
: $templateNote;
}
// Logga i fieldValues in error_log
$logFieldValues = "FieldValues dal DB (iddatadb={$iddatadb}):\n" . json_encode($fieldValues, JSON_PRETTY_PRINT);
error_log($logFieldValues);
@@ -301,7 +420,7 @@ try {
"AnagraficaCertestService" => $anagraficaService,
"ClienteFornitore" => $clienteFornitore, // PLACEHOLDER — to be implemented
"ClienteAnalisi" => $clienteAnalisi, // PLACEHOLDER — to be implemented
// "ClienteFatturazione" => $clienteFatturazione, // ⚠️ TEMP DISABLED - problemi API lato LIMS
"ClienteFatturazione" => $clienteFatturazione, // ⚠️ TEMP DISABLED - problemi API lato LIMS
// DeliveryRequest goes to Campione, not CommessaWeb
];
@@ -323,6 +442,11 @@ try {
$commessaId = $commessaWeb["IdCommessa"];
$commessaWebCode = substr($commessaWeb["CodiceCommessa"] ?? "TEST CommessaWeb", 0, 30); // Limite a 30 caratteri
// 🔹 STEP 5.1: salva SUBITO l'id della commessa creata: se l'export fallisce più avanti,
// il CHECK PRELIMINARE sa che nel LIMS esiste già e non ne crea una seconda.
$pdo->prepare("UPDATE datadb SET idcommessaweb = :idc, commessaweb = :cw WHERE iddatadb = :id")
->execute(['idc' => $commessaId, 'cw' => $commessaWebCode, 'id' => $iddatadb]);
// 🔹 STEP 6: Create Campioni (Samples) for each part
$campioni = [];
$logContentStep6 = "";
@@ -560,7 +684,7 @@ try {
// 🔹 STEP 6.3: Add Analyses (AnalisiCampione) via Campione({id})/AddAnalisi bound action
$stmt = $pdo->prepare("
SELECT part_id, analysis_recordkey, analysis_name, analysis_method
SELECT part_id, analysis_recordkey, analysis_name, analysis_method, analysis_price
FROM identification_parts_analyses
WHERE iddatadb = :iddatadb
ORDER BY part_id, id
@@ -568,6 +692,17 @@ try {
$stmt->execute(['iddatadb' => $iddatadb]);
$analysesRows = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Analisi senza prezzo (NULL o 0), una sola volta per recordkey
$noPriceAnalyses = [];
foreach ($analysesRows as $a) {
$price = $a['analysis_price'];
if ($price === null || (float)$price <= 0) {
$rk = (string)($a['analysis_recordkey'] ?? '');
$noPriceAnalyses[$rk] = $a['analysis_name'] ?: 'Unnamed analysis';
}
}
$noPriceAnalyses = array_values($noPriceAnalyses);
$partIdToIndex = [];
foreach ($parts as $idx => $part) {
$partIdToIndex[(int)$part['part_id']] = $idx;
@@ -675,16 +810,20 @@ try {
}
}
// 🔹 STEP 8: Update datadb with idcommessaweb, commessaweb, status and export date
// 🔹 STEP 8: Update datadb with idcommessaweb, commessaweb, log_file and export date
// NB: lo status 'l' viene impostato SOLO dopo invio+import ok (vedi più sotto),
// così una riga rimasta indietro non risulta "To LIMS" per errore.
$stmt = $pdo->prepare("
UPDATE datadb
SET idcommessaweb = :idcommessaweb, commessaweb = :commessaweb, status = 'l', export_date = NOW()
SET idcommessaweb = :idcommessaweb, commessaweb = :commessaweb,
log_file = :log_file, export_date = NOW()
WHERE iddatadb = :iddatadb
");
$stmt->execute([
'idcommessaweb' => $commessaId,
'commessaweb' => $commessaWebCode,
'iddatadb' => $iddatadb
'commessaweb' => $commessaWebCode,
'log_file' => basename($commessaLogFile),
'iddatadb' => $iddatadb
]);
// 🔹 STEP 9: Send CommessaWeb to laboratory (commentato come richiesto)
@@ -728,6 +867,13 @@ try {
$logFileStep91 = $logDir . "commessa_{$commessaId}_importa_step91_" . time() . ".txt";
$writeLog($logFileStep91, $logContentStep91, "STEP 9.5 - ImportaCommessa (commessa={$commessaId}, succeeded=" . ($importSucceeded ? '1' : '0') . ")");
// Import non confermato → errore ('x'), non 'l'. Prima veniva comunque segnata 'l'
// perché CodiceCommessa (codice web) non è mai vuoto. Al reinvio il CHECK PRELIMINARE
// ricontrolla lo stato nel LIMS: se nel frattempo è "Elaborata" la riga viene solo riallineata.
if (!$importSucceeded) {
throw new Exception("ImportaCommessa non confermata dal LIMS (stato: " . ($importStato ?? 'null') . ")");
}
// 🔹 STEP 10: GET di controllo post-PATCH
$expand = "CommesseCustomFields(\$expand=CustomField)";
$commessaAfterPatch = $api->get("CommessaWeb(" . $commessaId . ")?\$expand=" . $expand);
@@ -752,9 +898,12 @@ try {
");
$stmt->execute([
'commessaweb' => substr($finalCodiceCommessa, 0, 30),
'iddatadb' => $iddatadb
'iddatadb' => $iddatadb
]);
}
// Indice di lotto: esito OK di questa commessa
$writeBatchIndex("OK iddatadb={$iddatadb} commessa={$commessaId} codice={$finalCodiceCommessa} log=" . basename($commessaLogFile));
// 🔹 STEP 11: Prepare final response
$finalCommessa = [
"Cliente" => $clienteId,
@@ -778,6 +927,8 @@ try {
"totalAnalyses" => $totalAnalyses,
"addedAnalyses" => $addedAnalyses,
"failedAnalyses" => $failedAnalyses,
"noPriceCount" => count($noPriceAnalyses),
"noPriceAnalyses" => $noPriceAnalyses,
"message" => "Export successful",
"logFiles" => [
"step5_create" => $logFileStep5,
@@ -789,12 +940,50 @@ try {
"step10_get" => $logFileStep10
]
]);
} catch (Exception $e) {
} catch (Throwable $e) {
// --- LOG ERRORE DEDICATO (accanto agli altri log in logs/api/) ---
$errIddatadb = $iddatadb ?? 'unknown';
$errCommessaId = $commessaId ?? null;
$errContent = "TIMESTAMP: " . date('Y-m-d H:i:s') . "\n";
$errContent .= "iddatadb: {$errIddatadb}\n";
$errContent .= "IdCommessa: " . ($errCommessaId ?? 'non ancora creata') . "\n";
$errContent .= "MESSAGE: " . $e->getMessage() . "\n\n";
$errContent .= "TRACE:\n" . $e->getTraceAsString() . "\n";
// Appendi l'errore in coda al file unico della commessa (se esiste),
// così resta tutto in un posto solo.
if (isset($commessaLogFile)) {
$header = "\n" . str_repeat("=", 60) . "\n[ERROR] " . date('Y-m-d H:i:s') . "\n" . str_repeat("=", 60) . "\n";
@file_put_contents($commessaLogFile, $header . $errContent . "\n", FILE_APPEND);
$errFileToSave = basename($commessaLogFile);
} else {
// fallback: file d'errore dedicato
$errName = "commessa_ERROR_{$errIddatadb}_" . time() . ".txt";
@file_put_contents($logDir . $errName, $errContent);
$errFileToSave = $errName;
}
// Segna la riga come errore ('x') e registra il log_file, senza lasciarla 'l'
if ($errIddatadb !== 'unknown') {
try {
$up = $pdo->prepare("UPDATE datadb SET status = 'x', log_file = :log_file WHERE iddatadb = :iddatadb");
$up->execute(['log_file' => $errFileToSave, 'iddatadb' => $errIddatadb]);
} catch (Exception $ignore) { /* non bloccare la risposta d'errore */
}
}
// Indice di lotto: esito KO di questa commessa
if (isset($writeBatchIndex)) {
$writeBatchIndex("FAIL iddatadb={$errIddatadb} commessa=" . ($errCommessaId ?? '-') . " log={$errFileToSave} :: " . $e->getMessage());
}
error_log("LIMS Export Error: " . $e->getMessage() . "\nTrace: " . $e->getTraceAsString());
echo json_encode([
"success" => false,
"message" => "Export failed: " . $e->getMessage(),
"success" => false,
"message" => "Export failed: " . $e->getMessage(),
"errorLog" => $logDir . $errFileToSave,
"logFiles" => [
"step5_create" => $logFileStep5 ?? null,
"step5_2_photos" => $logFilePhotos ?? null,
+394
View File
@@ -0,0 +1,394 @@
<?php
include('include/headscript.php');
require_once __DIR__ . '/include/grid_data_builder.php';
header('Content-Type: application/json');
$pdo = DBHandlerSelect::getInstance()->getConnection();
const FILTER_ALLOWED_PER_PAGE = [20, 40, 60, 100];
const FILTER_ALLIDS_CAP = 5000;
$body = json_decode(file_get_contents('php://input'), true) ?: [];
$templateId = (int)($body['template_id'] ?? 0);
if ($templateId <= 0) {
echo json_encode(['success' => false, 'message' => 'template_id mancante']);
exit;
}
$status = in_array($body['status'] ?? 'i', ['i', 'P', 'l'], true) ? $body['status'] : 'i';
$showAll = !empty($body['all_users']);
$importref = trim((string)($body['importref'] ?? '')); // scope su un singolo import
$filters = is_array($body['filters'] ?? null) ? $body['filters'] : [];
$userId = (int)($iduserlogin ?? 0);
$perPage = in_array((int)($body['per_page'] ?? 20), FILTER_ALLOWED_PER_PAGE, true) ? (int)$body['per_page'] : 20;
$page = max(1, (int)($body['page'] ?? 1));
$wantAllIds = !empty($body['want_all_ids']);
$cacheDir = __DIR__ . '/cache';
$explicitIds = [];
if (isset($body['ids']) && is_array($body['ids'])) {
$explicitIds = array_values(array_unique(array_filter(
array_map('intval', $body['ids']),
fn($v) => $v > 0
)));
}
if (!empty($explicitIds)) {
// Scoping di sicurezza: solo record del template/utente/import corretti.
$conds = ['d.templateid = ?', 'd.status = ?'];
$params = [$templateId, $status];
if (!$showAll) { $conds[] = 'd.user_id = ?'; $params[] = $userId; }
if ($importref !== '') { $conds[] = 'd.importreferencecode = ?'; $params[] = $importref; }
$ph = implode(',', array_fill(0, count($explicitIds), '?'));
$conds[] = "d.iddatadb IN ($ph)";
foreach ($explicitIds as $id) $params[] = $id;
$whereSql = implode(' AND ', $conds);
try {
$countStmt = $pdo->prepare("SELECT COUNT(*) FROM datadb d WHERE {$whereSql}");
$countStmt->execute($params);
$total = (int)$countStmt->fetchColumn();
$totalPages = max(1, (int)ceil($total / $perPage));
if ($page > $totalPages) $page = $totalPages;
$offset = ($page - 1) * $perPage;
$idStmt = $pdo->prepare("
SELECT d.iddatadb FROM datadb d
WHERE {$whereSql}
ORDER BY d.excelrow ASC, d.iddatadb ASC
LIMIT {$perPage} OFFSET {$offset}
");
$idStmt->execute($params);
$pageIds = array_map('intval', $idStmt->fetchAll(PDO::FETCH_COLUMN));
$config = buildGridConfig($pdo, $templateId);
$rows = buildGridRows($pdo, $pageIds, $config);
echo json_encode([
'success' => true,
'total' => $total,
'page' => $page,
'per_page' => $perPage,
'total_pages' => $totalPages,
'rows' => $rows,
'mode' => 'selection',
]);
} catch (Exception $e) {
error_log('filter_records (ids mode) error: ' . $e->getMessage());
echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
exit;
}
$fixedAliasMap = [
'ClienteResponsabile' => 'cliente_responsabile_id',
'ClienteFornitore' => 'cliente_fornitore_id',
'ClienteAnalisi' => 'clienteAnalisi',
'ClienteFatturazione' => 'ClienteFatturazione',
'MoltiplicatorePrezzo' => 'moltiplicatore_prezzo_id',
'AnagraficaCertestObject' => 'anagrafica_certest_object_id',
'AnagraficaCertestService' => 'anagrafica_certest_service_id',
'ConsegnaRichiesta' => 'consegna_richiesta',
];
$staticCols = ['importreferencecode', 'filename_import', 'importdate', 'commessaweb'];
// ── Risolutori "etichetta → lista di ID" via cache ────────────────────────
function cacheItems(string $file): array
{
if (!is_file($file)) return [];
$data = json_decode(file_get_contents($file), true);
if (!is_array($data)) return [];
return $data['value'] ?? $data ?? [];
}
/** Clienti: label "Nome - X - id" (come search_clienti.php). */
function resolveClientIdsByTerm(string $cacheDir, string $term): array
{
$term = mb_strtolower(trim($term));
if ($term === '') return [];
$ids = [];
foreach (cacheItems($cacheDir . '/clienti.json') as $c) {
$name = trim($c['Nominativo'] ?? '');
$id = trim((string)($c['IdCliente'] ?? ''));
$code = trim((string)($c['CodiceCliente'] ?? ''));
$parts = explode('_', $code);
$suffix = trim($parts[1] ?? '');
if ($suffix === '' && $code !== '') $suffix = substr($code, 0, 1);
if ($suffix === '') $suffix = '--';
$label = mb_strtolower($name . ' - ' . $suffix . ' - ' . $id);
if (mb_strpos($label, $term) !== false) $ids[] = (int)$c['IdCliente'];
}
return array_values(array_unique($ids));
}
/** Dropdown generico: matcha il termine su qualsiasi label field, ritorna gli id. */
function resolveIdsFromCache(string $file, string $idField, array $labelFields, string $term): array
{
$term = mb_strtolower(trim($term));
if ($term === '') return [];
$ids = [];
foreach (cacheItems($file) as $it) {
$hay = '';
foreach ($labelFields as $lf) $hay .= ' ' . ($it[$lf] ?? '');
if (mb_strpos(mb_strtolower($hay), $term) !== false && isset($it[$idField])) {
$ids[] = (int)$it[$idField];
}
}
return array_values(array_unique($ids));
}
/**
* Per un fixed field che memorizza un ID, risolve il termine in lista di id.
* Ritorna: array di id (IN), [] se il termine non matcha nulla, null se la colonna
* non è risolvibile (→ il chiamante la salta invece di fare LIKE sbagliato).
*/
function resolveFixedIds(string $cacheDir, string $key, string $term): ?array
{
switch ($key) {
case 'ClienteAnalisi':
case 'ClienteFatturazione':
return resolveClientIdsByTerm($cacheDir, $term);
case 'MoltiplicatorePrezzo':
return resolveIdsFromCache($cacheDir . '/moltiplicatori_prezzo.json', 'IdMoltiplicatorePrezzo', ['Codice', 'Descrizione'], $term);
case 'AnagraficaCertestObject':
return resolveIdsFromCache($cacheDir . '/anagrafica_certest_object.json', 'IdAnagrafica', ['Codice', 'NomeAnagrafica'], $term);
case 'AnagraficaCertestService':
return resolveIdsFromCache($cacheDir . '/anagrafica_certest_service.json', 'IdAnagrafica', ['Codice', 'NomeAnagrafica'], $term);
default:
// ClienteResponsabile (per-cliente) e altri: non risolvibili globalmente
return null;
}
}
/**
* @return array<array{0:int,1:int}> lista di [idclient, idResponsabile]
*/
function resolveResponsabilePairs(string $cacheDir, string $term): array
{
$term = mb_strtolower(trim($term));
if ($term === '') return [];
$pairs = [];
foreach (glob($cacheDir . '/cliente_responsabili_*.json') ?: [] as $file) {
if (!preg_match('/cliente_responsabili_(\d+)\.json$/', $file, $m)) continue;
$cid = (int)$m[1];
$data = json_decode(file_get_contents($file), true);
foreach (($data['Responsabili'] ?? []) as $r) {
$name = mb_strtolower((string)($r['Nominativo'] ?? ''));
if ($name !== '' && mb_strpos($name, $term) !== false && isset($r['IdClienteResponsabile'])) {
$pairs[] = [$cid, (int)$r['IdClienteResponsabile']];
}
}
}
return $pairs;
}
/** Meta di un mapping (data_type, field_id), con cache statica. */
function mappingMeta(PDO $pdo, int $mappingId): array
{
static $cache = [];
if (!array_key_exists($mappingId, $cache)) {
$st = $pdo->prepare("SELECT data_type, field_id FROM template_mapping WHERE id = ?");
$st->execute([$mappingId]);
$cache[$mappingId] = $st->fetch(PDO::FETCH_ASSOC) ?: ['data_type' => 'Testo', 'field_id' => null];
}
return $cache[$mappingId];
}
function resolveCustomFieldValueIds(string $cacheDir, $fieldId, string $term): array
{
$fieldId = (int)$fieldId;
$term = mb_strtolower(trim($term));
if ($fieldId <= 0 || $term === '') return [];
$ids = [];
foreach (cacheItems($cacheDir . "/customfield_{$fieldId}.json") as $it) {
$label = mb_strtolower((string)($it['Valore'] ?? ''));
if (mb_strpos($label, $term) !== false && isset($it['IdCustomFieldsValue'])) {
$ids[] = (int)$it['IdCustomFieldsValue'];
}
}
return array_values(array_unique($ids));
}
// ── Costruzione WHERE ──────────────────────────────────────────────────────
$conds = ['d.templateid = ?', 'd.status = ?'];
$params = [$templateId, $status];
$needUserJoin = false;
if (!$showAll) {
$conds[] = 'd.user_id = ?';
$params[] = $userId;
}
// Scope su un singolo import (come imported.php ?importref=)
if ($importref !== '') {
$conds[] = 'd.importreferencecode = ?';
$params[] = $importref;
}
/** Aggiunge una condizione "colonna id IN (lista risolta)". */
function addIdInCondition(array &$conds, array &$params, string $col, array $ids): void
{
if (empty($ids)) {
$conds[] = '1 = 0'; // termine dato ma nessun match → zero risultati
return;
}
$ph = implode(',', array_fill(0, count($ids), '?'));
$conds[] = "d.`{$col}` IN ($ph)";
foreach ($ids as $id) $params[] = (int)$id;
}
foreach ($filters as $f) {
$term = trim((string)($f['term'] ?? ''));
if ($term === '') continue;
$type = (string)($f['type'] ?? '');
$key = (string)($f['key'] ?? '');
$like = '%' . $term . '%';
switch ($type) {
case 'detail':
case 'main_field':
$mappingId = (int)$key;
if ($mappingId <= 0) break;
$mm = mappingMeta($pdo, $mappingId);
if (($mm['data_type'] ?? '') === 'SceltaMultipla') {
// Dropdown: field_value = ID valore → risolvi label→id, match IN (= non LIKE)
$vids = resolveCustomFieldValueIds($cacheDir, $mm['field_id'], $term);
if (empty($vids)) {
$conds[] = '1 = 0';
break;
}
$inph = implode(',', array_fill(0, count($vids), '?'));
$conds[] = "EXISTS (SELECT 1 FROM import_data_details x
WHERE x.id = d.iddatadb AND x.mapping_id = ? AND x.field_value IN ($inph))";
$params[] = $mappingId;
foreach ($vids as $vid) $params[] = $vid;
} else {
// Testo / Data: match testuale
$conds[] = "EXISTS (SELECT 1 FROM import_data_details x
WHERE x.id = d.iddatadb AND x.mapping_id = ? AND x.field_value LIKE ?)";
$params[] = $mappingId;
$params[] = $like;
}
break;
case 'idclient':
addIdInCondition($conds, $params, 'idclient', resolveClientIdsByTerm($cacheDir, $term));
break;
case 'cliente_fornitore_id':
addIdInCondition($conds, $params, 'cliente_fornitore_id', resolveClientIdsByTerm($cacheDir, $term));
break;
case 'tested_component':
$conds[] = 'd.tested_component LIKE ?';
$params[] = $like;
break;
case 'status':
// Il dropdown invia direttamente il codice ('i'/'P'/'l').
if (in_array($term, ['i', 'P', 'l'], true)) {
$conds[] = 'd.status = ?';
$params[] = $term;
} else {
$conds[] = '1 = 0';
}
break;
case 'fixed':
$col = $fixedAliasMap[$key] ?? null;
if ($col === null) break;
if ($key === 'ConsegnaRichiesta') {
// Data: match testuale sul valore data (es. "2026-03").
$conds[] = "CAST(d.`{$col}` AS CHAR) LIKE ?";
$params[] = $like;
} elseif ($key === 'ClienteResponsabile') {
// Match sulla coppia (idclient, id responsabile).
$pairs = resolveResponsabilePairs($cacheDir, $term);
if (empty($pairs)) {
$conds[] = '1 = 0';
break;
}
$rowvals = implode(',', array_fill(0, count($pairs), '(?,?)'));
$conds[] = "(d.idclient, d.`{$col}`) IN ($rowvals)";
foreach ($pairs as $pr) {
$params[] = $pr[0];
$params[] = $pr[1];
}
} else {
$ids = resolveFixedIds($cacheDir, $key, $term);
if ($ids === null) break; // non risolvibile → non filtrare (niente LIKE su id)
addIdInCondition($conds, $params, $col, $ids);
}
break;
case 'static':
if ($key === 'user_name') {
$needUserJoin = true;
$conds[] = "CONCAT(COALESCE(u.first_name,''),' ',COALESCE(u.last_name,'')) LIKE ?";
$params[] = $like;
} elseif (in_array($key, $staticCols, true)) {
$conds[] = "d.`{$key}` LIKE ?";
$params[] = $like;
}
break;
default:
break; // tracking/awb ecc. → non filtrabili
}
}
$whereSql = implode(' AND ', $conds);
$joinSql = $needUserJoin ? 'LEFT JOIN auth_users u ON d.user_id = u.id' : '';
try {
// Totale + pagine
$countStmt = $pdo->prepare("SELECT COUNT(*) FROM datadb d {$joinSql} WHERE {$whereSql}");
$countStmt->execute($params);
$total = (int)$countStmt->fetchColumn();
$totalPages = max(1, (int)ceil($total / $perPage));
if ($page > $totalPages) $page = $totalPages;
$offset = ($page - 1) * $perPage;
// Pagina corrente
$pageStmt = $pdo->prepare("
SELECT d.iddatadb
FROM datadb d {$joinSql}
WHERE {$whereSql}
ORDER BY d.excelrow ASC, d.iddatadb ASC
LIMIT {$perPage} OFFSET {$offset}
");
$pageStmt->execute($params);
$pageIds = array_map('intval', $pageStmt->fetchAll(PDO::FETCH_COLUMN));
$config = buildGridConfig($pdo, $templateId);
$rows = buildGridRows($pdo, $pageIds, $config);
$out = [
'success' => true,
'total' => $total,
'page' => $page,
'per_page' => $perPage,
'total_pages' => $totalPages,
'rows' => $rows,
];
// Tutti gli id del match (per "seleziona tutti"), solo su richiesta
if ($wantAllIds) {
$allStmt = $pdo->prepare("
SELECT d.iddatadb FROM datadb d {$joinSql}
WHERE {$whereSql}
ORDER BY d.excelrow ASC, d.iddatadb ASC
LIMIT " . FILTER_ALLIDS_CAP . "
");
$allStmt->execute($params);
$out['all_ids'] = array_map('intval', $allStmt->fetchAll(PDO::FETCH_COLUMN));
$out['all_ids_capped'] = $total > FILTER_ALLIDS_CAP;
}
echo json_encode($out);
} catch (Exception $e) {
error_log('filter_records error: ' . $e->getMessage());
echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
@@ -40,7 +40,7 @@ try {
$data = null;
$fromCache = false;
if (!$simulate && !$refresh && file_exists($cache_file) && (time() - filemtime($cache_file) < 3600)) { // 1 ora
if (!$simulate && !$refresh && file_exists($cache_file) && (time() - filemtime($cache_file) < 7200)) { // 1 ora
$data = json_decode(file_get_contents($cache_file), true);
$fromCache = is_array($data);
}
@@ -69,6 +69,11 @@ try {
$analisi = $data['value'] ?? [];
// Escludi le analisi con NominativoCliente compilato
$analisi = array_values(array_filter($analisi, function ($item) {
return empty(trim((string)($item['NominativoCliente'] ?? '')));
}));
echo json_encode([
'value' => $analisi,
'count' => is_array($analisi) ? count($analisi) : 0
+1 -1
View File
@@ -76,7 +76,7 @@ try {
// Cache file (1 hour TTL)
$cacheFile = __DIR__ . '/cache/clienti.json';
if (file_exists($cacheFile) && (time() - filemtime($cacheFile) < 3600)) {
if (file_exists($cacheFile) && (time() - filemtime($cacheFile) < 7200)) {
readfile($cacheFile);
exit;
}
+1 -1
View File
@@ -101,7 +101,7 @@ try {
// Cache file (1 hour TTL)
$cacheFile = __DIR__ . '/cache/clienti.json';
if (file_exists($cacheFile) && (time() - filemtime($cacheFile) < 3600)) {
if (file_exists($cacheFile) && (time() - filemtime($cacheFile) < 7200)) {
readfile($cacheFile);
exit;
}
+1 -1
View File
@@ -76,7 +76,7 @@ try {
// Cache file (1 hour TTL)
$cacheFile = __DIR__ . '/cache/clienti.json';
if (file_exists($cacheFile) && (time() - filemtime($cacheFile) < 3600)) {
if (file_exists($cacheFile) && (time() - filemtime($cacheFile) < 7200)) {
readfile($cacheFile);
exit;
}
+1 -1
View File
@@ -28,7 +28,7 @@ try {
$cacheFile = $cacheDir . '/customfield_' . $customFieldId . '.json';
// Use cache if fresh (1 hour)
if (file_exists($cacheFile) && (time() - filemtime($cacheFile) < 3600)) {
if (file_exists($cacheFile) && (time() - filemtime($cacheFile) < 7200)) {
$results[$customFieldId] = json_decode(file_get_contents($cacheFile), true);
continue;
}
+1 -1
View File
@@ -67,7 +67,7 @@ try {
}
// Caching skipped in simulate mode to avoid polluting real-data cache files
if (!$simulate && $cache_file && file_exists($cache_file) && (time() - filemtime($cache_file) < 3600)) { // 1 ora
if (!$simulate && $cache_file && file_exists($cache_file) && (time() - filemtime($cache_file) < 7200)) { // 1 ora
$data = json_decode(file_get_contents($cache_file), true);
} else {
$data = $api->get($endpoint, $options);
+6 -2
View File
@@ -2,7 +2,11 @@
require_once dirname(__DIR__, 2) . '/vendor/autoload.php';
require_once __DIR__ . '/class/db-functions.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';
@@ -13,7 +17,7 @@ error_reporting(E_ALL);
try {
// Cache file (1 hour TTL)
$cacheFile = __DIR__ . '/cache/matrici.json';
if (file_exists($cacheFile) && (time() - filemtime($cacheFile) < 3600)) {
if (file_exists($cacheFile) && (time() - filemtime($cacheFile) < 7200)) {
readfile($cacheFile);
exit;
}
+844
View File
@@ -0,0 +1,844 @@
/**
* gridFilter.js — Selezione righe + filtri colonna a scomparsa per imported.php
* Dipende da window.gridRenderer (gridRenderer.js). Includere DOPO gridRenderer.js.
*/
(function () {
"use strict";
let filtersActive = false;
let restricted = false;
const selected = new Set(); // iddatadb selezionati
const colFilters = {}; // colKey -> testo filtro
let restrictedIds = null; // Set di iddatadb visibili quando ristretto
function R() {
return window.gridRenderer;
}
function data() {
return R().getData();
}
function meta() {
return R().getMeta();
}
// ── Filtro SERVER-SIDE (paginato, come la lista normale ma filtrata) ──────
// Il filtro gira su TUTTO il template; il server restituisce UNA PAGINA di righe
// filtrate + il totale, e navighiamo le pagine del set filtrato via AJAX.
const TEMPLATE_ID =
new URLSearchParams(location.search).get("id") || (meta().templateId ?? "");
const SHOW_ALL =
new URLSearchParams(location.search).get("all_users") === "1";
const IMPORTREF =
new URLSearchParams(location.search).get("importref") || "";
const FILTER_PER_PAGE =
parseInt(new URLSearchParams(location.search).get("limit"), 10) || 20;
let serverFiltered = false;
let filterPage = 1;
let filterTotalPages = 1;
let filterTotal = 0;
let originalData = null; // snapshot della pagina originale (per ripristino)
let filterReqSeq = 0;
let showingSelection = false; // true quando mostriamo l'UNIONE dei selezionati
let pagerFn = null; // paginazione corrente (applyServerFilter | showSelectedRecords)
function collectActiveFilters() {
const cols = meta().columns || [];
const out = [];
for (const [key, term] of Object.entries(colFilters)) {
if (!term || !String(term).trim()) continue;
const col = cols.find((c) => String(c.key) === String(key));
if (!col) continue;
out.push({ key: String(key), type: col.type, term: String(term).trim() });
}
return out;
}
// Sostituisce il dataset del renderer in-place e ridisegna.
function swapData(rows) {
const arr = data();
arr.length = 0;
(rows || []).forEach((r) => arr.push(r));
R().renderVisibleRows();
}
function hidePagination(hide) {
// Durante il filtro la paginazione server (per pagina, via URL) è fuorviante.
document.querySelectorAll(".pager-bar").forEach((el) => {
el.style.display = hide ? "none" : "";
});
}
// Pager del set filtrato (Prec / pag X di Y / Succ) nella toolbar.
function updateFilterPager() {
const el = document.getElementById("filterPager");
if (!el) return;
if (!serverFiltered) {
el.style.display = "none";
el.innerHTML = "";
return;
}
el.style.display = "inline-flex";
const label = showingSelection ? "selezionati" : "trovati";
el.innerHTML =
`<button type="button" class="btn btn-outline-secondary btn-sm" id="filterPrevBtn" ${filterPage <= 1 ? "disabled" : ""}>‹</button>` +
`<span style="font-size:12px;color:#333;">${filterTotal} ${label} · pag ${filterPage}/${filterTotalPages}</span>` +
`<button type="button" class="btn btn-outline-secondary btn-sm" id="filterNextBtn" ${filterPage >= filterTotalPages ? "disabled" : ""}>›</button>`;
const go = pagerFn || applyServerFilter;
const prev = document.getElementById("filterPrevBtn");
const next = document.getElementById("filterNextBtn");
if (prev) prev.addEventListener("click", () => go(filterPage - 1));
if (next) next.addEventListener("click", () => go(filterPage + 1));
}
function restoreOriginal() {
serverFiltered = false;
filterPage = 1;
filterTotalPages = 1;
filterTotal = 0;
if (originalData) swapData(originalData);
updateFilterPager();
hidePagination(false);
updateToolbar();
}
async function applyServerFilter(page = 1) {
const active = collectActiveFilters();
if (active.length === 0) {
if (serverFiltered) restoreOriginal();
return;
}
if (!originalData) originalData = [...data()]; // snapshot pagina 1 originale
const seq = ++filterReqSeq;
try {
const resp = await fetch("filter_records.php", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
template_id: parseInt(TEMPLATE_ID, 10),
all_users: SHOW_ALL,
importref: IMPORTREF,
status: "i",
filters: active,
page: Math.max(1, page),
per_page: FILTER_PER_PAGE,
}),
});
const json = await resp.json();
if (seq !== filterReqSeq) return; // risposta obsoleta: ignora
if (!json.success) {
console.error("[gridFilter] filtro:", json.message);
return;
}
serverFiltered = true;
showingSelection = false;
pagerFn = applyServerFilter;
filterPage = json.page;
filterTotalPages = json.total_pages;
filterTotal = json.total;
swapData(json.rows || []);
updateFilterPager();
hidePagination(true);
updateToolbar();
} catch (e) {
console.error("[gridFilter] fetch filtro fallita", e);
}
}
// ── Mostra i SELEZIONATI (unione tra filtri diversi) ──────────────────
// La selezione si accumula tra filtri; questo carica dal server TUTTI i record
// selezionati (per id) e li mostra, paginati, a prescindere dai filtri correnti.
async function showSelectedRecords(page = 1) {
const ids = [...selected];
if (!ids.length) {
showingSelection = false;
updateToolbar();
return;
}
pagerFn = showSelectedRecords;
try {
const resp = await fetch("filter_records.php", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
template_id: parseInt(TEMPLATE_ID, 10),
all_users: SHOW_ALL,
importref: IMPORTREF,
status: "i",
ids: ids,
page: Math.max(1, page),
per_page: FILTER_PER_PAGE,
}),
});
const json = await resp.json();
if (!json.success) {
console.error("[gridFilter] mostra selezionati:", json.message);
return;
}
if (!originalData) originalData = [...data()];
showingSelection = true;
serverFiltered = true;
filterPage = json.page;
filterTotalPages = json.total_pages;
filterTotal = json.total;
swapData(json.rows || []);
updateFilterPager();
hidePagination(true);
updateToolbar();
} catch (e) {
console.error("[gridFilter] mostra selezionati fallita", e);
}
}
// Tumbler "Mostra selezionati" / "Torna al filtro".
function toggleShowSelected() {
if (!showingSelection) {
if (!selected.size) return;
showSelectedRecords(1);
} else {
exitSelectionView();
}
}
// Torna dal "mostra selezionati" al filtro corrente (o alla pagina originale).
function exitSelectionView() {
showingSelection = false;
pagerFn = applyServerFilter;
if (collectActiveFilters().length) {
applyServerFilter(1);
} else {
restoreOriginal();
}
updateToolbar();
}
// Deseleziona tutto.
function clearSelection() {
selected.clear();
document
.querySelectorAll("#gridRowContainer .grid-row.row-selected")
.forEach((el) => el.classList.remove("row-selected"));
document
.querySelectorAll(".filter-row-checkbox")
.forEach((cb) => (cb.checked = false));
const sa = document.getElementById("filterSelectAll");
if (sa) sa.checked = false;
if (showingSelection) {
exitSelectionView();
} else {
updateToolbar();
}
}
// "Seleziona tutti i filtrati": chiede al server TUTTI gli id del match e li seleziona.
async function selectAllMatching(on) {
if (!serverFiltered) return;
const active = collectActiveFilters();
try {
const resp = await fetch("filter_records.php", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
template_id: parseInt(TEMPLATE_ID, 10),
all_users: SHOW_ALL,
importref: IMPORTREF,
status: "i",
filters: active,
page: filterPage,
per_page: FILTER_PER_PAGE,
want_all_ids: true,
}),
});
const json = await resp.json();
if (!json.success) return;
(json.all_ids || []).forEach((id) => (on ? selected.add(id) : selected.delete(id)));
document
.querySelectorAll("#gridRowContainer .grid-row")
.forEach((rowEl) => {
rowEl.classList.toggle("row-selected", on);
const cb = rowEl.querySelector(".filter-row-checkbox");
if (cb) cb.checked = on;
});
updateToolbar();
if (json.all_ids_capped) {
alert("Selezione limitata a " + (json.all_ids || []).length + " record.");
}
} catch (e) {
console.error("[gridFilter] select-all fallita", e);
}
}
function syncFilterRow() {
const fr = document.getElementById("gridFilterRow");
const header = document.getElementById("gridHeaderContainer");
if (!fr || !header) return;
const actHeader = header.querySelector(".button-header");
const actCell = fr.querySelector(".filter-actions-cell");
if (actHeader && actCell) {
const aw = actHeader.offsetWidth;
actCell.style.flex = `0 0 ${aw}px`;
actCell.style.minWidth = `${aw}px`;
}
const headerCells = header.querySelectorAll(
".grid-header:not(.button-header)",
);
const filterCells = fr.querySelectorAll(
".grid-cell:not(.filter-actions-cell)",
);
headerCells.forEach((hc, i) => {
const fc = filterCells[i];
if (fc) fc.style.flex = `0 0 ${hc.offsetWidth}px`;
});
}
function syncStickyLeft() {
const btnHeader = document.querySelector(
"#gridHeaderContainer .button-header",
);
if (!btnHeader) return;
const w1 = btnHeader.offsetWidth; // larghezza reale colonna Actions
const fixRow = (rowEl) => {
if (!rowEl) return;
const cells = rowEl.querySelectorAll(
":scope > .grid-cell, :scope > .grid-header",
);
const c2 = cells[1];
const c3 = cells[2];
if (c2 && getComputedStyle(c2).position === "sticky") {
c2.style.left = `${w1}px`;
}
if (c3 && getComputedStyle(c3).position === "sticky") {
c3.style.left = `${w1 + (c2 ? c2.offsetWidth : 0)}px`;
}
};
fixRow(document.getElementById("gridHeaderContainer"));
document.querySelectorAll(".grid-top").forEach(fixRow);
document
.querySelectorAll("#gridRowContainer .grid-row")
.forEach(fixRow);
fixRow(document.getElementById("gridFilterRow"));
}
let _headerObs = null;
let _rowObs = null;
let _syncRaf = null;
function reconnectObservers() {
const header = document.getElementById("gridHeaderContainer");
const rows = document.getElementById("gridRowContainer");
if (_headerObs && header)
_headerObs.observe(header, {
attributes: true,
attributeFilter: ["style"],
subtree: true,
});
if (_rowObs && rows) _rowObs.observe(rows, { childList: true });
}
function scheduleSync() {
if (_syncRaf) return;
_syncRaf = requestAnimationFrame(() => {
_syncRaf = null;
if (_headerObs) _headerObs.disconnect();
if (_rowObs) _rowObs.disconnect();
syncStickyLeft();
syncFilterRow();
reconnectObservers();
});
}
function hookGridSync() {
_headerObs = new MutationObserver(scheduleSync);
_rowObs = new MutationObserver(scheduleSync);
reconnectObservers();
scheduleSync(); // primo allineamento
}
function rowMatchesFilters(row) {
if (serverFiltered) return true;
for (const [key, term] of Object.entries(colFilters)) {
if (!term) continue;
const t = term.toLowerCase();
const val = getRowColValue(row, key);
if (!String(val).toLowerCase().includes(t)) return false;
}
return true;
}
function getRowColValue(row, key) {
const cols = meta().columns || [];
const col = cols.find((c) => String(c.key) === String(key));
if (!col) return "";
switch (col.type) {
case "detail":
case "main_field":
return row.details?.[String(key)] ?? "";
case "fixed":
return row.fixedFields?.[key] ?? "";
case "idclient":
return row.idclient ?? "";
case "cliente_fornitore_id":
return row.cliente_fornitore_id ?? "";
case "tested_component":
return row.tested_component ?? "";
case "static":
return row[key] ?? "";
case "status":
return row.status ?? "";
default:
return row[key] ?? "";
}
}
// ── Applica visibilità righe (filtri + restrizione) ──
function applyVisibility() {
const rows = document.querySelectorAll("#gridRowContainer .grid-row");
rows.forEach((rowEl) => {
const id = parseInt(rowEl.dataset.id, 10);
const row = data().find((r) => String(r.iddatadb) === String(id));
let show = true;
if (row && !rowMatchesFilters(row)) show = false;
if (restricted && restrictedIds && !restrictedIds.has(id))
show = false;
rowEl.style.display = show ? "" : "none";
});
window.dispatchEvent(new Event("resize")); // ricalcola scrollbar top
}
// ── Lista iddatadb attualmente visibili (per propagazione/export ecc.) ──
window.getVisibleGridIds = function () {
if (serverFiltered) {
return data()
.map((r) => parseInt(r.iddatadb, 10))
.filter(Boolean);
}
const ids = [];
document
.querySelectorAll("#gridRowContainer .grid-row")
.forEach((el) => {
if (el.style.display !== "none")
ids.push(parseInt(el.dataset.id, 10));
});
return ids.filter(Boolean);
};
// ── Righe target per operazioni bulk (propaga/export/clona/save) ──
// Regola: filtri attivi + selezione → solo selezionate;
// filtri attivi senza selezione → solo visibili;
// filtri non attivi → null (= tutte, comportamento originale).
window.getTargetGridIds = function () {
if (!filtersActive) return null; // null = nessun vincolo
if (selected.size > 0) return new Set([...selected]);
return new Set(window.getVisibleGridIds());
};
// Helper: true se l'id è tra i target (o se non c'è vincolo)
window.isTargetGridId = function (id) {
const t = window.getTargetGridIds();
if (t === null) return true;
return t.has(parseInt(id, 10));
};
// ── Toggle selezione riga ──
function toggleRow(id, on) {
id = parseInt(id, 10);
if (on) selected.add(id);
else selected.delete(id);
const rowEl = document.querySelector(
`#gridRowContainer .grid-row[data-id="${id}"]`,
);
if (rowEl) {
rowEl.classList.toggle("row-selected", selected.has(id));
const cb = rowEl.querySelector(".filter-row-checkbox");
if (cb) cb.checked = selected.has(id);
}
updateToolbar();
}
// ── Inietta checkbox nelle righe visibili ──
// ── Inietta checkbox dentro la cella Actions (già sticky) ──
function injectCheckboxes() {
document
.querySelectorAll("#gridRowContainer .grid-row")
.forEach((rowEl) => {
const btnCell = rowEl.querySelector(".button-cell");
if (!btnCell) return;
if (btnCell.querySelector(".filter-row-checkbox")) return;
const id = parseInt(rowEl.dataset.id, 10);
const wrap = document.createElement("label");
wrap.className = "filter-cb-wrap";
wrap.innerHTML = `<input type="checkbox" class="filter-row-checkbox" ${selected.has(id) ? "checked" : ""}>`;
btnCell.insertBefore(wrap, btnCell.firstChild);
if (selected.has(id)) rowEl.classList.add("row-selected");
});
}
function removeCheckboxes() {
document
.querySelectorAll(".filter-cb-wrap")
.forEach((el) => el.remove());
document
.querySelectorAll(".grid-row.row-selected")
.forEach((el) => el.classList.remove("row-selected"));
}
// ── Riga input filtri colonna (allineata alle larghezze reali) ──
// ── Riga input filtri colonna (allineata alle larghezze reali) ──
function injectFilterRow() {
if (document.getElementById("gridFilterRow")) return;
const top = document.getElementById("gridTopContainer");
const header = document.getElementById("gridHeaderContainer");
if (!top || !header) return;
const fr = document.createElement("div");
fr.className = "grid-row grid-filter-row";
fr.id = "gridFilterRow";
// cella allineata alla colonna Actions (sticky, legge larghezza reale)
const actHeader = header.querySelector(".button-header");
const actCell = document.createElement("div");
actCell.className = "grid-cell button-cell filter-actions-cell";
const aw = actHeader ? actHeader.offsetWidth : 220;
actCell.style.flex = `0 0 ${aw}px`;
actCell.style.minWidth = `${aw}px`;
actCell.innerHTML = `<label class="filter-cb-wrap" style="display:inline-flex;" title="Seleziona tutti i filtrati"><input type="checkbox" id="filterSelectAll"></label>`;
fr.appendChild(actCell);
// una cella per colonna, larghezza letta dall'header reale
const headerCells = header.querySelectorAll(
".grid-header:not(.button-header)",
);
(meta().columns || []).forEach((col, i) => {
const hc = headerCells[i];
const w = hc ? hc.offsetWidth : col.width || 150;
const cell = document.createElement("div");
cell.className = "grid-cell";
cell.style.flex = `0 0 ${w}px`;
if (col.type === "tracking" || col.type === "awb") {
// niente filtro
} else if (col.type === "status") {
// Status: dropdown (3 valori) invece del testo libero.
const cur = colFilters[col.key] || "";
const opt = (v, lbl) =>
`<option value="${v}" ${cur === v ? "selected" : ""}>${lbl}</option>`;
cell.innerHTML =
`<select class="filter-col-input" data-col-key="${col.key}" style="width:100%;padding:3px 6px;font-size:12px;border:1px solid #ced4da;border-radius:4px;">` +
opt("", "— tutti —") +
opt("i", "Imported") +
opt("P", "In Progress") +
opt("l", "To LIMS") +
`</select>`;
} else {
cell.innerHTML = `<input type="text" class="filter-col-input" data-col-key="${col.key}" placeholder="🔍 ${col.label || ""}" value="${colFilters[col.key] || ""}" style="width:100%;padding:3px 6px;font-size:12px;border:1px solid #ced4da;border-radius:4px;">`;
}
fr.appendChild(cell);
});
top.parentNode.insertBefore(fr, top);
scheduleSync(); // allinea larghezze filtri + offset sticky
}
function removeFilterRow() {
const fr = document.getElementById("gridFilterRow");
if (fr) fr.remove();
}
// ── Toolbar (bottoni contestuali) ──
function updateToolbar() {
const bar = document.getElementById("filterActionBar");
if (!bar) return;
const count = selected.size;
bar.style.display = filtersActive ? "inline-flex" : "none";
const cntEl = document.getElementById("filterSelCount");
if (cntEl) cntEl.textContent = count;
document.getElementById("filterDeleteBtn").disabled = count === 0;
const showBtn = document.getElementById("filterRestrictBtn");
showBtn.disabled = count === 0 && !showingSelection;
showBtn.innerHTML = showingSelection
? '<i class="fas fa-eye"></i> Torna al filtro'
: '<i class="fas fa-list-check"></i> Mostra selezionati';
const clearSelBtn = document.getElementById("filterClearSelBtn");
if (clearSelBtn) clearSelBtn.disabled = count === 0;
}
// ── Main toggle ──
function toggleFilters() {
filtersActive = !filtersActive;
const grid = document.getElementById("gridContainer");
const btn = document.getElementById("filtersToggleBtn");
if (filtersActive) {
grid.classList.add("filters-on");
btn.classList.add("active");
injectCheckboxes();
injectFilterRow();
} else {
grid.classList.remove("filters-on");
btn.classList.remove("active");
removeCheckboxes();
removeFilterRow();
// reset filtri colonna + ripristina la pagina originale
Object.keys(colFilters).forEach((k) => delete colFilters[k]);
if (serverFiltered) restoreOriginal();
}
updateToolbar();
}
// ── Batch delete ──
async function batchDelete() {
const ids = [...selected];
if (!ids.length) return;
if (
!confirm(
`Eliminare ${ids.length} righe dal database? Operazione irreversibile.`,
)
)
return;
const btn = document.getElementById("filterDeleteBtn");
btn.disabled = true;
const original = btn.innerHTML;
let ok = 0,
fail = 0;
for (const id of ids) {
try {
btn.innerHTML = `<i class="fas fa-spinner fa-spin"></i> ${ok + fail + 1}/${ids.length}`;
const resp = await fetch("delete_record.php", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ id: id }),
});
const json = await resp.json();
if (json.success) {
ok++;
// rimuovi da gridData
const arr = data();
const idx = arr.findIndex(
(r) => String(r.iddatadb) === String(id),
);
if (idx !== -1) arr.splice(idx, 1);
selected.delete(id);
if (restrictedIds) restrictedIds.delete(id);
} else fail++;
} catch (e) {
fail++;
}
}
btn.innerHTML = original;
R().renderVisibleRows();
if (filtersActive) {
injectCheckboxes();
}
applyVisibility();
updateToolbar();
alert(`Eliminate: ${ok}${fail ? " — Falliti: " + fail : ""}`);
}
// ── Restringi / mostra tutti ──
function toggleRestrict() {
if (!restricted) {
if (!selected.size) return;
restrictedIds = new Set([...selected]);
restricted = true;
} else {
restricted = false;
restrictedIds = null;
}
applyVisibility();
updateToolbar();
}
// ── Costruzione UI toolbar (bottoni in cima) ──
function buildUI() {
const addBtn = document.getElementById("addRowBtn");
if (!addBtn) return;
// bottone Filters
const fBtn = document.createElement("button");
fBtn.type = "button";
fBtn.id = "filtersToggleBtn";
fBtn.className = "btn btn-outline-info btn-sm";
fBtn.style.flexShrink = "0";
fBtn.innerHTML = '<i class="fas fa-filter"></i> Filters';
addBtn.parentNode.insertBefore(fBtn, addBtn.nextSibling);
// barra azioni contestuali
const bar = document.createElement("span");
bar.id = "filterActionBar";
bar.style.cssText =
"display:none;align-items:center;gap:8px;flex-shrink:0;";
bar.innerHTML = `
<span id="filterPager" style="display:none;align-items:center;gap:6px;"></span>
<button type="button" id="filterClearBtn" class="btn btn-outline-secondary btn-sm"><i class="fas fa-times"></i> Pulisci filtri</button>
<span style="font-size:12px;color:#555;">Selezionate: <strong id="filterSelCount">0</strong></span>
<button type="button" id="filterRestrictBtn" class="btn btn-outline-primary btn-sm"><i class="fas fa-list-check"></i> Mostra selezionati</button>
<button type="button" id="filterClearSelBtn" class="btn btn-outline-secondary btn-sm"><i class="fas fa-square"></i> Deseleziona</button>
<button type="button" id="filterDeleteBtn" class="btn btn-outline-danger btn-sm"><i class="fas fa-trash"></i> Elimina selezionati</button>
`;
fBtn.parentNode.insertBefore(bar, fBtn.nextSibling);
fBtn.addEventListener("click", toggleFilters);
document
.getElementById("filterClearBtn")
.addEventListener("click", clearFilters);
document
.getElementById("filterDeleteBtn")
.addEventListener("click", batchDelete);
document
.getElementById("filterRestrictBtn")
.addEventListener("click", toggleShowSelected);
document
.getElementById("filterClearSelBtn")
.addEventListener("click", clearSelection);
}
// Svuota tutti i filtri di colonna (input + select) e torna alla pagina originale.
function clearFilters() {
Object.keys(colFilters).forEach((k) => delete colFilters[k]);
document
.querySelectorAll("#gridFilterRow .filter-col-input")
.forEach((el) => {
el.value = "";
});
if (serverFiltered) restoreOriginal();
}
// ── Event delegation ──
function attachEvents() {
// checkbox click
document.addEventListener("change", function (e) {
if (e.target.classList.contains("filter-row-checkbox")) {
const rowEl = e.target.closest(".grid-row");
toggleRow(rowEl.dataset.id, e.target.checked);
}
});
// Seleziona / deseleziona tutti i FILTRATI
document.addEventListener("change", function (e) {
if (e.target.id !== "filterSelectAll") return;
const on = e.target.checked;
// Con filtro server-side: seleziona TUTTI i match (anche altre pagine).
if (serverFiltered) {
selectAllMatching(on);
return;
}
document
.querySelectorAll("#gridRowContainer .grid-row")
.forEach((rowEl) => {
if (rowEl.style.display === "none") return;
const id = parseInt(rowEl.dataset.id, 10);
if (!id) return;
if (on) selected.add(id);
else selected.delete(id);
rowEl.classList.toggle("row-selected", on);
const cb = rowEl.querySelector(".filter-row-checkbox");
if (cb) cb.checked = on;
});
updateToolbar();
});
// click su QUALSIASI punto della riga (tranne campi interattivi) = seleziona
document.addEventListener("click", function (e) {
if (!filtersActive) return;
const rowEl = e.target.closest("#gridRowContainer .grid-row");
if (!rowEl) return;
// ignora click su elementi interattivi
if (
e.target.closest(
"input, select, textarea, button, a, .select2-container, .action-btn, .propagate-btn, .add-part-btn",
)
) {
// ma se ho cliccato proprio la checkbox, lascia fare al change
return;
}
const cb = rowEl.querySelector(".filter-row-checkbox");
if (!cb) return;
cb.checked = !cb.checked;
toggleRow(rowEl.dataset.id, cb.checked);
});
// filtri colonna testo (debounce) → filtro server-side su tutto il template
let t = null;
document.addEventListener("input", function (e) {
if (!e.target.classList.contains("filter-col-input")) return;
if (e.target.tagName === "SELECT") return; // i select li gestisce 'change'
const key = e.target.dataset.colKey;
colFilters[key] = e.target.value;
clearTimeout(t);
t = setTimeout(applyServerFilter, 250);
});
// dropdown (es. Status): applica subito, senza debounce
document.addEventListener("change", function (e) {
if (!e.target.classList.contains("filter-col-input")) return;
if (e.target.tagName !== "SELECT") return;
colFilters[e.target.dataset.colKey] = e.target.value;
applyServerFilter();
});
}
// ── Ripristina stato filtri dopo un re-render (checkbox + restrizione) ──
let _restoring = false;
function restoreFilterState() {
if (!filtersActive || _restoring) return;
_restoring = true; // evita loop con l'observer mentre iniettiamo/nascondiamo
try {
injectCheckboxes();
applyVisibility(); // ri-applica filtri colonna E restringi selezione
} finally {
// rilascia dopo il tick così le nostre mutazioni non ci ri-triggerano subito
setTimeout(() => {
_restoring = false;
}, 0);
}
}
// ── Observer: qualunque cosa ricrei le righe (propagazione, save, ecc.)
// ripristina automaticamente checkbox + restrizione. Robusto perché
// non dipende da chi chiama renderVisibleRows. ──
function hookRerender() {
const rowC = document.getElementById("gridRowContainer");
if (!rowC) return;
const obs = new MutationObserver(() => {
if (!filtersActive || _restoring) return;
// debounce leggero: aspetta che il render finisca
clearTimeout(hookRerender._t);
hookRerender._t = setTimeout(restoreFilterState, 30);
});
obs.observe(rowC, { childList: true });
}
function init() {
if (!window.gridRenderer) {
console.error("[gridFilter] gridRenderer non trovato");
return;
}
buildUI();
attachEvents();
hookRerender();
hookGridSync();
}
// parte dopo che gridRenderer ha finito init
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", () =>
setTimeout(init, 300),
);
} else {
setTimeout(init, 300);
}
})();
+375 -8
View File
@@ -143,7 +143,54 @@
}),
);
}
// Ranking inizio/centro/fine per select con dati già in memoria.
// Restituisce { matcher, sorter } da passare a select2().
function rankedLocalSelect2() {
return {
matcher: function (params, data) {
const term = $.trim(params.term || "").toLowerCase();
if (term === "") return data;
if (typeof data.text === "undefined") return null;
// AND multi-termine, posizione indipendente
const text = data.text.toLowerCase();
const terms = term.split(/\s+/).filter(Boolean);
const all = terms.every((t) => text.indexOf(t) !== -1);
return all ? data : null;
},
sorter: function (results) {
const term = $(
".select2-container--open .select2-search__field",
).val();
const search = (term || "").toLowerCase().trim();
if (!search) return results;
const first = search.split(/\s+/)[0];
function score(text) {
const t = (text || "").toLowerCase();
if (t === search) return 0; // match esatto
if (t.indexOf(first) === 0) return 1; // inizia col termine
if (new RegExp("(^|\\s)" + escapeRegExp(first)).test(t))
return 2; // inizio parola
return 3; // in mezzo
}
return results.slice().sort(function (a, b) {
const sa = score(a.text);
const sb = score(b.text);
if (sa !== sb) return sa - sb;
return (a.text || "").localeCompare(b.text || "", "it", {
sensitivity: "base",
});
});
},
};
}
function escapeRegExp(s) {
return String(s).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function sortSelect2ResultsByStart(data) {
const term = $(".select2-container--open .select2-search__field").val();
@@ -392,7 +439,6 @@
allowClear: true,
width: "100%",
minimumInputLength: 0,
sorter: sortSelect2ResultsByStart,
ajax: {
url: "search_customfield_values.php",
dataType: "json",
@@ -542,7 +588,14 @@
: "To LIMS";
let html = `<span class="status-badge status-${esc(st)}">${label}</span>`;
if (row.commessaweb) {
html += `<span class="commessaweb-code" style="display:block; font-size:0.75em; color:#555; margin-top:2px;">${esc(row.commessaweb)}</span>`;
const npBadge =
typeof window.noPriceBadgeHTML === "function"
? window.noPriceBadgeHTML(
row.noPriceCount,
row.noPriceAnalyses,
)
: "";
html += `<span class="commessaweb-code" style="display:block; font-size:0.75em; color:#555; margin-top:2px;">${esc(row.commessaweb)}${npBadge}</span>`;
}
div.innerHTML = html;
div.classList.remove("editable-cell");
@@ -684,7 +737,7 @@
const reqCls = col.isRequired ? " required-input" : "";
const req = col.isRequired ? " required" : "";
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>`;
return `<select class="cell-input manual-input fixed-input searchable-fixed ${selectClass}${reqCls}" data-fixed-key="${escAttr(col.key)}" data-current-value="${escAttr(value)}"${req}>${options}</select>`;
}
function buildDropdownOptionsHTML(fieldId, selectedValue) {
@@ -702,7 +755,8 @@
function renderActionButtons(rowIndex) {
const row = data[rowIndex];
const isExported = row.status === "l";
// _exporting: export in corso per questa riga (la riga può essere ri-renderizzata durante l'attesa)
const isExported = row.status === "l" || row._exporting === true;
const div = document.createElement("div");
div.className = "grid-cell button-cell";
div.style.flex = "0 0 auto";
@@ -849,6 +903,76 @@
updateDirtyIndicator();
}
// Aggiorna in-place SOLO le celle di una colonna in tutte le righe visibili,
// senza distruggere/ricostruire l'intera griglia (evita il freeze in propagazione).
function updateColumnCells(colKey, colType) {
if (!rowContainer) return;
const cells = rowContainer.querySelectorAll(
`.grid-cell[data-col="${CSS.escape(String(colKey))}"][data-col-type="${colType}"]`,
);
cells.forEach((cell) => {
const rowIndex = parseInt(cell.dataset.row, 10);
if (Number.isNaN(rowIndex) || !data[rowIndex]) return;
// Ricava il valore corrente dal modello dati
let value = "";
if (colType === "detail" || colType === "main_field") {
value = data[rowIndex].details?.[String(colKey)] ?? "";
} else if (colType === "fixed") {
value = data[rowIndex].fixedFields?.[colKey] ?? "";
} else if (colType === "cliente_fornitore_id") {
value = data[rowIndex].cliente_fornitore_id ?? "";
}
const input = cell.querySelector(".cell-input");
if (!input) return;
if ($(input).hasClass("select2-hidden-accessible")) {
// Assicura che l'opzione selezionata esista, poi imposta il valore
if (
value &&
!input.querySelector(
`option[value="${CSS.escape(String(value))}"]`,
)
) {
const label =
clientNameCache[value] ||
(input.dataset?.fieldId
? dropdownNameCache[
input.dataset.fieldId + "_" + value
]
: null) ||
value;
input.add(new Option(label, value, true, true));
}
$(input)
.val(value ? String(value) : "")
.trigger("change.select2");
} else if (input.tagName === "SELECT") {
// Select nativo: aggiungi opzione se manca
if (
value &&
!input.querySelector(
`option[value="${CSS.escape(String(value))}"]`,
)
) {
const label =
(input.dataset?.fieldId
? dropdownNameCache[
input.dataset.fieldId + "_" + value
]
: null) || value;
input.add(new Option(label, value, true, true));
}
input.value = value;
} else {
input.value = value;
}
cell.classList.add("cell-changed");
});
}
function renderSingleRow(rowIndex) {
const existing = rowContainer.querySelector(
`.grid-row[data-id="${data[rowIndex].iddatadb}"]`,
@@ -955,6 +1079,9 @@
if (columns[colPos]) {
columns[colPos].width = newWidth;
}
// Riallinea larghezza/posizione delle tendine Select2 aperte
$(window).trigger("resize.select2");
}
function syncVisibleRowsToGridData() {
@@ -968,6 +1095,11 @@
if (!row) return;
// Salta le righe nascoste (filtrate / non nella selezione ristretta):
// non devono essere sincronizzate né marcate dirty.
const rowEl = cell.closest(".grid-row");
if (rowEl && rowEl.style.display === "none") return;
const colType = cell.dataset.colType;
const colKey = cell.dataset.col;
const input = cell.querySelector(".cell-input");
@@ -1199,6 +1331,12 @@
items.forEach((item) =>
sel.add(new Option(item.text, item.id)),
);
$(sel).select2({
placeholder: "Seleziona...",
allowClear: true,
width: "100%",
...rankedLocalSelect2(),
});
}
});
@@ -1221,6 +1359,59 @@
function attachEvents() {
if (!rowContainer) return;
// ── Auto-copy: Sample Arrival date/time → Unlock date/time ──────────
// Coppie basate sui fieldId dei campi (source → target)
const AUTO_COPY_FIELD_PAIRS = [
{ from: 259, to: 260 }, // Sample Arrival date → Unlock Date
{ from: 348, to: 349 }, // Sample Arrival time → Unlock time
];
// Risolve fieldId → col.key (mapping id) usando le definizioni colonne
function colKeyByFieldId(fieldId) {
const col = columns.find(
(c) =>
(c.type === "detail" || c.type === "main_field") &&
String(c.fieldId) === String(fieldId),
);
return col ? String(col.key) : null;
}
// Precalcola le coppie come col.key (sourceKey → targetKey)
var AUTO_COPY_KEY_PAIRS = AUTO_COPY_FIELD_PAIRS.map((p) => ({
fromKey: colKeyByFieldId(p.from),
toKey: colKeyByFieldId(p.to),
})).filter((p) => p.fromKey && p.toKey);
function applyAutoCopy(rowIndex, changedColKey, value) {
const pair = AUTO_COPY_KEY_PAIRS.find(
(p) => p.fromKey === String(changedColKey),
);
if (!pair) return;
const row = data[rowIndex];
if (!row) return;
if (!row.details) row.details = {};
row.details[pair.toKey] = value;
row._dirty = true;
// Aggiorna la cella target visibile, se presente
const targetCell = rowContainer.querySelector(
`.grid-cell[data-row="${rowIndex}"][data-col="${pair.toKey}"]`,
);
if (targetCell) {
const input = targetCell.querySelector(".cell-input");
if (input) {
if ($(input).hasClass("select2-hidden-accessible")) {
$(input).val(value).trigger("change.select2");
} else {
input.value = value;
}
}
targetCell.classList.add("cell-changed");
}
}
// Cell value changes → write to gridData
rowContainer.addEventListener("change", function (e) {
const cell = e.target.closest(".grid-cell");
@@ -1235,6 +1426,7 @@
data[rowIndex].mainFieldValue = value;
}
setDetailValue(rowIndex, colKey, value);
applyAutoCopy(rowIndex, colKey, value);
} else if (colType === "fixed") {
setFixedValue(rowIndex, colKey, value);
} else if (colType === "idclient") {
@@ -1388,6 +1580,11 @@
if (column === "idclient") {
data.forEach((row) => {
if (
window.isTargetGridId &&
!window.isTargetGridId(row.iddatadb)
)
return;
const oldClientId = row.idclient || "";
row.idclient = value;
@@ -1421,11 +1618,19 @@
if (column === "cliente_fornitore_id") {
data.forEach((row) => {
if (
window.isTargetGridId &&
!window.isTargetGridId(row.iddatadb)
)
return;
row.cliente_fornitore_id = value;
row._dirty = true;
});
renderVisibleRows();
updateColumnCells(
"cliente_fornitore_id",
"cliente_fornitore_id",
);
updateDirtyIndicator();
return;
}
@@ -1434,21 +1639,39 @@
const fixedKey = column.replace("fixed_", "");
data.forEach((row) => {
if (
window.isTargetGridId &&
!window.isTargetGridId(row.iddatadb)
)
return;
if (!row.fixedFields) row.fixedFields = {};
row.fixedFields[fixedKey] = value;
row._dirty = true;
});
renderVisibleRows();
updateColumnCells(fixedKey, "fixed");
updateDirtyIndicator();
return;
}
if (col && (col.type === "detail" || col.type === "main_field")) {
const autoPair = AUTO_COPY_KEY_PAIRS.find(
(p) => p.fromKey === String(col.key),
);
data.forEach((row) => {
if (
window.isTargetGridId &&
!window.isTargetGridId(row.iddatadb)
)
return;
if (!row.details) row.details = {};
row.details[col.key] = value;
if (autoPair) {
row.details[autoPair.toKey] = value;
}
if (col.type === "main_field") {
row.mainFieldValue = value;
}
@@ -1456,7 +1679,15 @@
row._dirty = true;
});
renderVisibleRows();
updateColumnCells(col.key, col.type);
// Se esiste una colonna auto-copiata (es. Arrival→Unlock), aggiorna anche quella
if (autoPair) {
const pairCol = columns.find(
(c) => String(c.key) === String(autoPair.toKey),
);
if (pairCol) updateColumnCells(pairCol.key, pairCol.type);
}
updateDirtyIndicator();
return;
}
@@ -1627,9 +1858,18 @@
const fieldId = this.dataset.fieldId;
if (fieldId) $(this).select2(sceltaSelect2Config(fieldId));
});
$(this)
.find(".searchable-fixed:not(.select2-hidden-accessible)")
.each(function () {
$(this).select2({
placeholder: "Seleziona...",
allowClear: true,
width: "100%",
...rankedLocalSelect2(),
});
});
});
}
// ── Column resize ──────────────────────────────────────────────────────
function initColumnResizers() {
@@ -1672,6 +1912,9 @@
if (columns[colPos]) {
columns[colPos].width = newWidth;
}
// Riallinea larghezza/posizione delle tendine Select2 aperte
$(window).trigger("resize.select2");
}
function stopResize() {
@@ -1760,3 +2003,127 @@
},
};
})();
// ===================
// NAVIGAZIONE GRIGLIA CON FRECCE TASTIERA
// ===================
(function () {
// Naviga solo tra input di testo/numero/time e date-picker.
// I Select2 (client, fornitore, SceltaMultipla) sono esclusi:
// lì le frecce servono al dropdown.
function isNavigable(el) {
if (!el || !el.classList) return false;
if (!el.classList.contains("cell-input")) return false;
// Escludi i select (nativi o Select2)
if (el.tagName === "SELECT") return false;
if (el.classList.contains("select2-hidden-accessible")) return false;
return true;
}
// Tutte le celle navigabili della riga, ordinate per data-index
function navCellsInRow($row) {
return $row.find(".grid-cell[data-index]").filter(function () {
const input = this.querySelector(".cell-input");
return isNavigable(input);
});
}
function focusCellInput($cell) {
if (!$cell || !$cell.length) return;
const input = $cell.get(0).querySelector(".cell-input");
if (!input) return;
input.focus();
if (input.type !== "date" && typeof input.select === "function") {
try {
input.select();
} catch (e) {}
}
}
function atStart(el) {
if (el.type === "date" || el.type === "number" || el.type === "time")
return true;
return el.selectionStart === 0 && el.selectionEnd === 0;
}
function atEnd(el) {
if (el.type === "date" || el.type === "number" || el.type === "time")
return true;
const len = (el.value || "").length;
return el.selectionStart === len && el.selectionEnd === len;
}
$(document).on("keydown", "#gridRowContainer .cell-input", function (e) {
const el = this;
if (!isNavigable(el)) return;
// Ignora se un dropdown Select2 è aperto
if ($(".select2-container--open").length) return;
const key = e.key;
if (
key !== "ArrowUp" &&
key !== "ArrowDown" &&
key !== "ArrowLeft" &&
key !== "ArrowRight"
) {
return;
}
const $cell = $(el).closest(".grid-cell");
const $row = $cell.closest(".grid-row");
if (!$cell.length || !$row.length) return;
const colIndex = $cell.attr("data-index");
// --- SU / GIÙ: stessa colonna (data-index), riga adiacente ---
if (key === "ArrowUp" || key === "ArrowDown") {
const $targetRow =
key === "ArrowUp"
? $row.prev(".grid-row")
: $row.next(".grid-row");
if (!$targetRow.length) return;
e.preventDefault();
// Cella stessa colonna nella riga di destinazione
let $target = $targetRow.find(
`.grid-cell[data-index="${colIndex}"]`,
);
// Se quella colonna non è navigabile (es. è un select),
// cerca la più vicina navigabile nella riga
if (
!$target.length ||
!isNavigable($target.get(0).querySelector(".cell-input"))
) {
const $cells = navCellsInRow($targetRow);
if (!$cells.length) return;
$target = $cells.first();
}
focusCellInput($target);
return;
}
// --- SINISTRA / DESTRA: cella navigabile precedente/successiva nella riga ---
const $cells = navCellsInRow($row);
const curPos = $cells.index($cell);
if (curPos === -1) return;
if (key === "ArrowLeft") {
if (!atStart(el)) return;
if (curPos <= 0) return;
e.preventDefault();
focusCellInput($cells.eq(curPos - 1));
return;
}
if (key === "ArrowRight") {
if (!atEnd(el)) return;
if (curPos >= $cells.length - 1) return;
e.preventDefault();
focusCellInput($cells.eq(curPos + 1));
return;
}
});
})();
+173
View File
@@ -0,0 +1,173 @@
<?php
ini_set('display_errors', 0); // in AJAX gli errori devono NON sporcare il JSON
error_reporting(E_ALL);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/import_debug.log');
include('include/headscript.php');
header('Content-Type: application/json');
// Legge il body JSON
$input = json_decode(file_get_contents('php://input'), true);
if (
!$input ||
!isset($input['template_id']) ||
!isset($input['importreferencecode']) ||
!isset($input['filename']) ||
!isset($input['columns']) ||
!isset($input['batch_rows']) ||
!isset($input['batch_excelrows'])
) {
echo json_encode(['ok' => false, 'error' => 'Richiesta non valida']);
exit;
}
$template_id = intval($input['template_id']);
$importReferenceCode = (string)$input['importreferencecode'];
$newFilename = (string)$input['filename'];
$columns = $input['columns']; // array
$batchRows = $input['batch_rows']; // array di righe (ognuna array di celle)
$batchExcelrows = $input['batch_excelrows']; // array di excelrow paralleli a batchRows
$user_id = $iduserlogin ?? 1;
function normalizeColName($s): string
{
$s = (string)$s;
$s = str_replace(
["\xC2\xA0", "\xE2\x80\xAF", "\xE2\x80\x87", "\xE2\x80\x89", "\xE2\x80\x8A", "\xEF\xBB\xBF"],
' ',
$s
);
$s = preg_replace('/\s+/u', ' ', $s);
return trim((string)$s);
}
$db = DBHandlerSelect::getInstance();
$pdo = $db->getConnection();
// Recupera i mapping
$stmt = $pdo->prepare("SELECT id, excel_column, data_type, is_required, manual_default, is_manual, field_label, field_id, main_field, auto_value FROM template_mapping WHERE template_id = ?");
$stmt->execute([$template_id]);
$allMappings = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (empty($allMappings)) {
echo json_encode(['ok' => false, 'error' => 'Nessun mapping trovato per il template']);
exit;
}
// idclient di default (una volta sola)
$template_stmt = $pdo->prepare("SELECT idclient FROM excel_templates WHERE id = ?");
$template_stmt->execute([$template_id]);
$tpl = $template_stmt->fetch(PDO::FETCH_ASSOC);
$default_idclient = $tpl['idclient'] ?? null;
// lims_user_id per il campo 244 (una volta sola)
$stmtUser = $pdo->prepare("SELECT lims_user_id FROM auth_users WHERE id = ? LIMIT 1");
$stmtUser->execute([(int)$user_id]);
$limsUserId = $stmtUser->fetchColumn();
$limsUserId = ($limsUserId !== false && $limsUserId !== null && $limsUserId !== '') ? (string)$limsUserId : '';
$stmtMap = $pdo->prepare("SELECT id FROM template_mapping WHERE template_id = ? AND field_id = 244 LIMIT 1");
$stmtMap->execute([(int)$template_id]);
$mappingId244 = (int)$stmtMap->fetchColumn();
$insertedIds = [];
try {
$pdo->beginTransaction();
$insDatadb = $pdo->prepare("INSERT INTO datadb (templateid, importreferencecode, filename_import, status, user_id, limscode, importdate, excelrow, idclient) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
$insDetail = $pdo->prepare("INSERT INTO import_data_details (id, mapping_id, field_value) VALUES (?, ?, ?)");
foreach ($batchRows as $i => $row) {
$excelrow = $batchExcelrows[$i] ?? null;
if ($row === null || $excelrow === null) {
continue;
}
$insDatadb->execute([
$template_id,
$importReferenceCode,
$newFilename,
'i',
$user_id,
null,
date('Y-m-d'),
$excelrow,
$default_idclient
]);
$iddatadb = $pdo->lastInsertId();
$insertedIds[] = $iddatadb;
foreach ($allMappings as $mapping) {
$fieldValue = null;
if (!$mapping['is_manual']) {
$excelColumn = trim($mapping['excel_column']);
$excelColumnIndex = array_search(
normalizeColName($excelColumn),
array_map('normalizeColName', $columns)
);
if ($excelColumnIndex !== false && isset($row[$excelColumnIndex]) && $row[$excelColumnIndex] !== '') {
$fieldValue = $row[$excelColumnIndex];
} else {
$fieldValue = $mapping['manual_default'] ?? '';
}
switch ($mapping['data_type']) {
case 'INT':
$fieldValue = is_numeric($fieldValue) ? (int)$fieldValue : ($mapping['manual_default'] ?? 0);
break;
case 'DATE':
$fieldValue = !empty($fieldValue) ? date('Y-m-d', strtotime($fieldValue)) : ($mapping['manual_default'] === 'today' ? date('Y-m-d') : ($mapping['manual_default'] ?? ''));
break;
case 'CHAR':
$fieldValue = !empty($fieldValue) ? substr((string)$fieldValue, 0, 1) : ($mapping['manual_default'] ?? '');
break;
case 'Testo':
case 'VARCHAR':
default:
$fieldValue = !empty($fieldValue) ? (string)$fieldValue : ($mapping['manual_default'] ?? '');
break;
}
} else {
$fieldValue = $mapping['manual_default'] ?? '';
if ($mapping['data_type'] === 'DATE' && $mapping['manual_default'] === 'today') {
$fieldValue = date('Y-m-d');
}
}
if (($fieldValue === null || $fieldValue === '') && !empty($mapping['auto_value']) && $mapping['auto_value'] !== 'none') {
if ($mapping['auto_value'] === 'import_date') {
$fieldValue = date('Y-m-d');
} elseif ($mapping['auto_value'] === 'import_time') {
$fieldValue = date('H:i');
}
}
$insDetail->execute([$iddatadb, $mapping['id'], $fieldValue]);
}
// Campo 244 (Accettatore) con lims_user_id
if ($limsUserId !== '' && $mappingId244 > 0) {
$insDetail->execute([$iddatadb, $mappingId244, $limsUserId]);
}
}
$pdo->commit();
echo json_encode([
'ok' => true,
'inserted' => count($insertedIds)
]);
exit;
} catch (Exception $e) {
if ($pdo->inTransaction()) $pdo->rollBack();
error_log("[BATCH IMPORT] " . $e->getMessage());
echo json_encode([
'ok' => false,
'error' => $e->getMessage()
]);
exit;
}
+173 -20
View File
@@ -50,6 +50,9 @@ error_log("Loaded template: " . print_r($template, true));
border-radius: 0.25rem;
background: #f8f9fa;
display: none;
position: sticky;
top: 0;
z-index: 1020;
}
.top-scrollbar-inner {
@@ -161,6 +164,7 @@ error_log("Loaded template: " . print_r($template, true));
<div class="mb-3 text">
<a href="imported.php?id=<?= $id ?>" class="btn btn-warning me-2">Imported (i)</a>
<a href="tolims.php?id=<?= $id ?>" class="btn btn-success">To LIMS (l)</a>
<a href="errors.php?id=<?= $id ?>" class="btn btn-danger">Errors (x)</a>
</div>
<div class="card radius-10">
<div class="card-header">
@@ -341,8 +345,9 @@ error_log("Loaded template: " . print_r($template, true));
<input type="hidden" name="excelrows" id="selectedExcelRowsData" value="">
<input type="hidden" name="filename" value="${data.filename}">
<!-- TOP BUTTON -->
<div class="d-flex justify-content-end mb-3">
<!-- TOP BUTTON -->
<div class="d-flex justify-content-end align-items-center mb-3 gap-2">
<span class="badge bg-secondary" id="selectedCountTop">0 selezionati</span>
<button type="submit" class="btn btn-primary" id="proceedButtonTop" disabled>Prosegui</button>
</div>
@@ -383,46 +388,187 @@ error_log("Loaded template: " . print_r($template, true));
</table>
</div>
<!-- BOTTOM BUTTON -->
<button type="submit" class="btn btn-primary mt-3" id="proceedButtonBottom" disabled>Prosegui</button>
<!-- BOTTOM BUTTON -->
<div class="d-flex align-items-center mt-3 gap-2">
<span class="badge bg-secondary" id="selectedCountBottom">0 selezionati</span>
<button type="submit" class="btn btn-primary" id="proceedButtonBottom" disabled>Prosegui</button>
</div>
</form>
`;
tableContainer.innerHTML = html;
const selectRowsForm = document.getElementById('selectRowsForm');
selectRowsForm.addEventListener('submit', function(e) {
// Clic sulla cella (oltre che sulla checkbox) per selezionare/deselezionare la riga
document.querySelectorAll('#importPreviewTable tbody tr').forEach(tr => {
tr.style.cursor = 'pointer';
tr.addEventListener('click', function(e) {
// Se ho cliccato proprio sulla checkbox, lascio fare a lei (evita doppio toggle)
if (e.target.classList.contains('row-checkbox')) return;
const cb = this.querySelector('.row-checkbox');
if (!cb) return;
cb.checked = !cb.checked;
cb.dispatchEvent(new Event('change', {
bubbles: true
}));
});
});
selectRowsForm.addEventListener('submit', async function(e) {
e.preventDefault(); // gestiamo tutto via AJAX a batch
const checkedBoxes = Array.from(document.querySelectorAll('.row-checkbox:checked'));
if (checkedBoxes.length === 0) {
e.preventDefault();
alert('Seleziona almeno una riga.');
return;
}
// Raccoglie le righe selezionate (riga mappata + excelrow parallelo)
const selectedRows = [];
const selectedExcelRows = [];
checkedBoxes.forEach((cb, newIndex) => {
checkedBoxes.forEach(cb => {
const originalIndex = parseInt(cb.value, 10);
if (data.rows && data.rows[originalIndex]) {
selectedRows.push(data.rows[originalIndex]);
selectedExcelRows.push(
(data.excel_data && data.excel_data[originalIndex]) ?
data.excel_data[originalIndex].excelrow :
null
);
}
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));
const total = selectedRows.length;
if (total === 0) {
alert('Nessuna riga valida da importare.');
return;
}
document.getElementById('selectedExcelRowsData').value =
encodeURIComponent(JSON.stringify(selectedExcelRows));
// importreferencecode generato UNA volta, condiviso da tutti i batch
const importReferenceCode =
new Date().toISOString().replace(/[-:.TZ]/g, '').slice(0, 14) +
'-' + Math.random().toString(36).slice(2, 10);
const BATCH_SIZE = 20;
// Disabilita i pulsanti e mostra la barra di progresso
const btnTop = document.getElementById('proceedButtonTop');
const btnBottom = document.getElementById('proceedButtonBottom');
if (btnTop) btnTop.disabled = true;
if (btnBottom) btnBottom.disabled = true;
const progressHtml = `
<div id="importProgressWrap" style="
position: fixed;
inset: 0;
background: rgba(0,0,0,0.5);
z-index: 20000;
display: flex;
align-items: center;
justify-content: center;">
<div style="
background: #fff;
border-radius: 10px;
padding: 25px 30px;
width: 90%;
max-width: 500px;
box-shadow: 0 10px 40px rgba(0,0,0,0.3);">
<div class="mb-2"><strong>Importazione in corso...</strong>
<span id="importProgressText" class="float-end">0 / ${total}</span>
</div>
<div class="progress" style="height: 26px;">
<div id="importProgressBar" class="progress-bar progress-bar-striped progress-bar-animated"
role="progressbar" style="width: 0%;">0%</div>
</div>
<div id="importProgressError" class="alert alert-danger mt-3 mb-0" style="display:none;"></div>
</div>
</div>`;
document.body.insertAdjacentHTML('beforeend', progressHtml);
const progressBar = document.getElementById('importProgressBar');
const progressText = document.getElementById('importProgressText');
const progressErr = document.getElementById('importProgressError');
let insertedTotal = 0;
// Invia un batch e ritorna la risposta JSON
async function sendBatch(startIndex) {
const batchRows = selectedRows.slice(startIndex, startIndex + BATCH_SIZE);
const batchExcelrows = selectedExcelRows.slice(startIndex, startIndex + BATCH_SIZE);
const resp = await fetch('import_insert_batch.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
template_id: data.template_id,
importreferencecode: importReferenceCode,
filename: data.filename,
columns: data.columns,
batch_rows: batchRows,
batch_excelrows: batchExcelrows
})
});
return resp.json();
}
// Cicla i batch in sequenza
for (let start = 0; start < total; start += BATCH_SIZE) {
let result;
try {
result = await sendBatch(start);
} catch (err) {
result = {
ok: false,
error: err.message
};
}
if (!result.ok) {
// Batch fallito: chiediamo all'utente se continuare
progressErr.textContent =
'Errore su un blocco (righe ' + (start + 1) + '-' +
Math.min(start + BATCH_SIZE, total) + '): ' + (result.error || 'errore sconosciuto');
progressErr.style.display = 'block';
const continua = confirm(
'Un blocco di righe non è stato importato.\n\n' +
'Righe inserite finora: ' + insertedTotal + ' di ' + total + '.\n\n' +
'Vuoi continuare con i blocchi successivi? (Annulla = interrompi)'
);
if (!continua) {
progressBar.classList.remove('progress-bar-animated');
progressBar.classList.add('bg-warning');
return;
}
// se continua, prosegue col prossimo blocco
continue;
}
insertedTotal += (result.inserted || 0);
const done = Math.min(start + BATCH_SIZE, total);
const pct = Math.round((done / total) * 100);
progressBar.style.width = pct + '%';
progressBar.textContent = pct + '%';
progressText.textContent = insertedTotal + ' / ' + total;
}
// Fine: barra verde e redirect a imported.php
progressBar.classList.remove('progress-bar-animated', 'progress-bar-striped');
progressBar.classList.add('bg-success');
progressText.textContent = insertedTotal + ' / ' + total + ' completate';
// PAUSA temporanea di 2 secondi per vedere la barra completa (da rimuovere dopo il test)
await new Promise(r => setTimeout(r, 2000));
window.location.href = 'imported.php?id=' +
encodeURIComponent(data.template_id) +
'&importref=' + encodeURIComponent(importReferenceCode);
});
const topTableScrollbar = document.getElementById('topTableScrollbar');
@@ -472,10 +618,17 @@ error_log("Loaded template: " . print_r($template, true));
const checkboxes = document.querySelectorAll('.row-checkbox');
function updateProceedButton() {
const enabled = Array.from(checkboxes).some(cb => cb.checked);
const checkedCount = Array.from(checkboxes).filter(cb => cb.checked).length;
const enabled = checkedCount > 0;
if (proceedButtonTop) proceedButtonTop.disabled = !enabled;
if (proceedButtonBottom) proceedButtonBottom.disabled = !enabled;
const label = checkedCount + ' selezionati';
const countTop = document.getElementById('selectedCountTop');
const countBottom = document.getElementById('selectedCountBottom');
if (countTop) countTop.textContent = label;
if (countBottom) countBottom.textContent = label;
}
selectAllCheckbox.addEventListener('change', function() {
+323 -16
View File
@@ -99,7 +99,7 @@ $stmt = $pdo->prepare("
FROM datadb d
LEFT JOIN auth_users u ON d.user_id = u.id
{$baseWhere}
ORDER BY d.excelrow ASC, d.iddatadb ASC
ORDER BY CAST(d.excelrow AS UNSIGNED) ASC, d.excelrow ASC, d.iddatadb ASC
{$limitClause}
");
$stmt->execute($baseParams);
@@ -787,6 +787,7 @@ $gridMeta = [
padding: 10px 0;
min-height: 0;
flex-wrap: nowrap;
min-width: fit-content;
}
.grid-top .grid-cell {
@@ -1328,6 +1329,195 @@ $gridMeta = [
outline: 2px solid #dc3545 !important;
outline-offset: -2px;
}
/* ── Filtri / selezione righe ── */
#filtersToggleBtn.active {
background-color: #0dcaf0 !important;
color: #fff !important;
border-color: #0dcaf0 !important;
}
/* checkbox dentro la cella Actions */
.filter-cb-wrap {
display: none;
align-items: center;
justify-content: center;
margin-right: 6px;
flex-shrink: 0;
}
.grid-container.filters-on .filter-cb-wrap {
display: inline-flex;
}
.filter-cb-wrap input {
width: 18px !important;
height: 18px !important;
cursor: pointer;
}
.grid-container.filters-on .button-cell {
display: flex;
align-items: center;
}
.grid-row.row-selected {
background-color: #cfe9ff !important;
}
.grid-row.row-selected .button-cell,
.grid-row.row-selected .grid-cell:nth-child(2),
.grid-row.row-selected .grid-cell:nth-child(3) {
background-color: #cfe9ff !important;
}
.grid-filter-row {
background: #eef6f9 !important;
border-bottom: 2px solid #0dcaf0;
}
.grid-filter-row .grid-cell {
padding: 4px 8px;
}
.grid-filter-row .filter-actions-cell {
background: #eef6f9 !important;
}
.grid-container.filters-on .grid-row {
cursor: pointer;
}
.grid-container.filters-on .grid-row input,
.grid-container.filters-on .grid-row select,
.grid-container.filters-on .grid-row textarea,
.grid-container.filters-on .grid-row button,
.grid-container.filters-on .grid-row a {
cursor: auto;
}
/* Sticky su riga propagazione e filtri (fix scroll orizzontale) */
.grid-top .grid-cell.save-all-cell {
position: sticky !important;
left: 0;
z-index: 9;
background: #fff;
}
.grid-top .grid-cell:nth-child(2) {
position: sticky !important;
left: 210px;
z-index: 8;
background: #fff;
}
/* Card-header azioni sticky sotto la topbar */
:root {
--actions-top: 0px;
/* posizione verticale barra azioni: abbassa/alza questo */
--actions-height: 58px;
/* altezza reale del card-header azioni */
--scrollbar-height: 18px;
/* altezza della .top-scrollbar */
}
.card-header.sticky-actions {
position: sticky;
top: var(--actions-top);
z-index: 40;
background: #fff;
}
/* La barra di scroll superiore segue sempre il card-header sticky */
.top-scrollbar {
top: calc(var(--actions-top) + var(--actions-height)) !important;
}
/* Wrapper del grid-top: sticky verticale + scroll orizzontale proprio */
.grid-top-scroller {
position: sticky;
top: calc(var(--actions-top) + var(--actions-height) + var(--scrollbar-height));
z-index: 25;
background: #fff;
overflow-x: auto;
overflow-y: hidden;
/* nasconde la barra di scroll di questo wrapper: usiamo la top-scrollbar e la griglia */
scrollbar-width: none;
}
.grid-top-scroller::-webkit-scrollbar {
display: none;
}
/* Tastino toggle sticky */
.sticky-toggle-btn {
border: 1px solid #ced4da;
background: #fff;
color: #adb5bd;
transition: all .15s;
}
.sticky-toggle-btn:hover {
background: #f1f3f5;
color: #6c757d;
}
.sticky-toggle-btn.active {
background: #0d6efd;
border-color: #0d6efd;
color: #fff;
}
.sticky-toggle-btn.active:hover {
background: #0b5ed7;
color: #fff;
}
/* Icona ruotata quando sbloccato (puntina "storta") */
.sticky-toggle-btn:not(.active) i {
transform: rotate(45deg);
}
/* Quando sbloccato, card-header e grid-top non sono più sticky verticalmente */
.card-header.actions-unpinned {
position: static !important;
top: auto !important;
}
.grid-top-scroller.actions-unpinned {
position: static !important;
top: auto !important;
}
<?php if (isset($mainFieldMappings) && count($mainFieldMappings) >= 2): ?>.grid-top .grid-cell:nth-child(3) {
position: sticky !important;
left: 360px;
z-index: 7;
background: #fff;
}
<?php endif; ?>.grid-filter-row .filter-actions-cell {
position: sticky !important;
left: 0;
z-index: 9;
background: #eef6f9 !important;
}
.grid-filter-row .grid-cell:nth-child(2) {
position: sticky !important;
left: 210px;
z-index: 8;
background: #eef6f9 !important;
}
<?php if (isset($mainFieldMappings) && count($mainFieldMappings) >= 2): ?>.grid-filter-row .grid-cell:nth-child(3) {
position: sticky !important;
left: 360px;
z-index: 7;
background: #eef6f9 !important;
}
<?php endif; ?>
</style>
<title>Edit Imported Data - <?= htmlspecialchars($titlewebsite, ENT_QUOTES, 'UTF-8'); ?></title>
</head>
@@ -1340,7 +1530,8 @@ $gridMeta = [
<div class="page-content">
<div class="mb-3 text d-flex align-items-center gap-2">
<a href="imported.php?id=<?= $template_id ?>" class="btn btn-warning me-2">Imported (i)</a>
<a href="tolims.php?id=<?= $template_id ?>" class="btn btn-success">To LIMS (l)</a>
<a href="tolims.php?id=<?= $template_id ?>" class="btn btn-success me-2">To LIMS (l)</a>
<a href="errors.php?id=<?= $template_id ?>" class="btn btn-danger">Errors (x)</a>
<?php if ($importref === ''): ?>
<span class="ms-3">
<label class="form-check-label" style="font-size: 13px; cursor: pointer;">
@@ -1402,8 +1593,9 @@ $gridMeta = [
</div>
<?php endif; ?>
<div class="card radius-10">
<div class="card-header">
<div class="card-header sticky-actions">
<div class="d-flex align-items-center" style="min-height: 42px; gap: 12px;">
<button type="button" id="toggleStickyBtn" class="btn btn-sm sticky-toggle-btn active" style="flex-shrink:0;" title="Blocca/sblocca barra azioni"><i class="fas fa-thumbtack"></i></button>
<a href="#" class="btn btn-outline-danger btn-sm export-all-lims-btn" style="flex-shrink:0;"><i class="fas fa-upload"></i> Export All</a>
<a href="#" class="btn btn-outline-success btn-sm save-all-btn" style="flex-shrink:0;"><i class="fas fa-save"></i> Save All</a>
<button type="button" class="btn btn-outline-success btn-sm" id="addRowBtn" style="flex-shrink:0;"><i class="fas fa-plus"></i> Add Row</button>
@@ -1426,8 +1618,11 @@ $gridMeta = [
<div class="top-scrollbar-inner" id="topScrollbarInner"></div>
</div>
<div class="grid-container" id="gridContainer">
<div class="grid-top-scroller" id="gridTopScroller">
<div class="grid-top" id="gridTopContainer"></div>
</div>
<div class="grid-container" id="gridContainer">
<div class="grid-row" id="gridHeaderContainer" style="font-weight:600;"></div>
<div id="gridRowContainer"></div>
</div>
@@ -1456,6 +1651,7 @@ $gridMeta = [
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script src="tracking.js"></script>
<script src="gridRenderer.js"></script>
<script src="gridFilter.js"></script>
<script src="saveAll.js"></script>
<script src="exportLims_gridData.js"></script>
<script src="modals_gridData.js"></script>
@@ -1497,21 +1693,43 @@ $gridMeta = [
topScrollbar.scrollLeft = gridContainer.scrollLeft;
}
const gridTopScroller = document.getElementById('gridTopScroller');
let syncing = false;
function syncScroll(source) {
if (syncing) return;
syncing = true;
const x = source.scrollLeft;
if (source !== topScrollbar) topScrollbar.scrollLeft = x;
if (source !== gridContainer) gridContainer.scrollLeft = x;
if (gridTopScroller && source !== gridTopScroller) gridTopScroller.scrollLeft = x;
syncing = false;
}
topScrollbar.addEventListener('scroll', function() {
if (syncingFromGrid) return;
syncingFromTop = true;
gridContainer.scrollLeft = topScrollbar.scrollLeft;
syncingFromTop = false;
syncScroll(topScrollbar);
});
gridContainer.addEventListener('scroll', function() {
if (syncingFromTop) return;
syncingFromGrid = true;
topScrollbar.scrollLeft = gridContainer.scrollLeft;
syncingFromGrid = false;
syncScroll(gridContainer);
});
if (gridTopScroller) {
gridTopScroller.addEventListener('scroll', function() {
syncScroll(gridTopScroller);
});
}
window.addEventListener('resize', updateTopScrollbarWidth);
let rafPending = false;
function scheduleUpdate() {
if (rafPending) return;
rafPending = true;
requestAnimationFrame(function() {
rafPending = false;
updateTopScrollbarWidth();
});
}
window.addEventListener('resize', scheduleUpdate);
// Recalculate after JS grid rendering
setTimeout(updateTopScrollbarWidth, 100);
@@ -1520,13 +1738,13 @@ $gridMeta = [
setTimeout(updateTopScrollbarWidth, 1500);
// Recalculate automatically when rows/header/top controls are rendered or changed
const observer = new MutationObserver(updateTopScrollbarWidth);
const observer = new MutationObserver(scheduleUpdate);
if (gridContainer) {
observer.observe(gridContainer, {
childList: true,
subtree: true,
attributes: true
attributes: false
});
}
});
@@ -1691,7 +1909,96 @@ $gridMeta = [
</div>
</div>
</div>
<div id="sessionModal" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,.5);z-index:99999;align-items:center;justify-content:center">
<div style="background:#fff;padding:28px 32px;border-radius:14px;max-width:420px;text-align:center;box-shadow:0 20px 60px rgba(0,0,0,.3)">
<h5 style="margin:0 0 10px">La sessione sta per scadere</h5>
<p style="color:#64748b;margin:0 0 6px">Per la tua sicurezza verrai disconnesso tra</p>
<div id="sessCountdownBig" style="font:700 34px monospace;color:#dc2626;margin:8px 0 18px">00:30</div>
<button id="sessStayBtn" class="btn btn-primary btn-lg px-4">Resta connesso</button>
</div>
</div>
<script>
(function() {
// ── TEST: tempi compressi. In produzione: SESSION_MINUTES=120, WARN_SECONDS=120
const SESSION_MINUTES = 110; // durata simulata
const WARN_SECONDS = 30; // preavviso prima della scadenza
const LOGIN_URL = '../login'; // adatta al tuo path reale
const sessionMs = SESSION_MINUTES * 60 * 1000;
let lastActivity = Date.now();
let modalShown = false;
// ogni attività reale resetta il timer locale
['mousemove', 'keydown', 'click', 'scroll', 'touchstart'].forEach(ev =>
document.addEventListener(ev, () => {
lastActivity = Date.now();
if (!modalShown) return; // se il modal è aperto, l'attività NON conta: serve il click esplicito
}, {
passive: true
})
);
const modal = document.getElementById('sessionModal');
const bigCd = document.getElementById('sessCountdownBig');
document.getElementById('sessStayBtn').addEventListener('click', async () => {
try {
const r = await fetch('session_keepalive.php', {
cache: 'no-store'
});
// se la sessione era già morta, headscript reindirizza: la risposta non sarà il JSON atteso
const ct = r.headers.get('content-type') || '';
if (!ct.includes('application/json')) {
window.location.href = LOGIN_URL;
return;
}
await r.json();
lastActivity = Date.now(); // timer riparte
modalShown = false;
modal.style.display = 'none';
} catch (e) {
window.location.href = LOGIN_URL;
}
});
setInterval(() => {
const elapsed = Date.now() - lastActivity;
const remaining = Math.ceil((sessionMs - elapsed) / 1000);
if (remaining <= 0) {
window.location.href = LOGIN_URL; // scaduta
return;
}
if (remaining <= WARN_SECONDS && !modalShown) {
modalShown = true;
modal.style.display = 'flex';
}
if (modalShown) {
const m = Math.floor(remaining / 60),
s = remaining % 60;
bigCd.textContent = String(m).padStart(2, '0') + ':' + String(s).padStart(2, '0');
}
}, 1000);
})();
</script>
<script>
(function() {
const btn = document.getElementById('toggleStickyBtn');
const cardHeader = document.querySelector('.card-header.sticky-actions');
if (!btn || !cardHeader) return;
const gridTopScroller = document.getElementById('gridTopScroller');
btn.addEventListener('click', function() {
const pinned = btn.classList.toggle('active');
cardHeader.classList.toggle('actions-unpinned', !pinned);
if (gridTopScroller) gridTopScroller.classList.toggle('actions-unpinned', !pinned);
btn.title = pinned ?
'Sblocca barra azioni' :
'Blocca barra azioni';
});
})();
</script>
</body>
</html>
@@ -0,0 +1,213 @@
<?php
if (!function_exists('gdbFixedDefaultValue')) {
/** Default di un fixed field (DATE 'today' → data odierna). */
function gdbFixedDefaultValue(array $f): string
{
$v = $f['default_value'] ?? '';
if (($f['data_type'] ?? '') === 'DATE' && $v === 'today') {
return date('Y-m-d');
}
return (string)$v;
}
}
if (!function_exists('buildGridConfig')) {
/**
* Config del template necessaria per costruire le righe: fixed fields (ordinati
* come in imported.php), main field mappings, alias map, default idclient.
*
* @return array{fixedFields:array, fixedAliasMap:array, mainFieldMappings:array, default_idclient:mixed}
*/
function buildGridConfig(PDO $pdo, int $templateId): array
{
// Mappa logica fixed_field_key → colonna reale su datadb (come imported.php)
$fixedAliasMap = [
'ClienteResponsabile' => 'cliente_responsabile_id',
'ClienteFornitore' => 'cliente_fornitore_id',
'ClienteAnalisi' => 'clienteAnalisi',
'ClienteFatturazione' => 'ClienteFatturazione',
'MoltiplicatorePrezzo' => 'moltiplicatore_prezzo_id',
'AnagraficaCertestObject' => 'anagrafica_certest_object_id',
'AnagraficaCertestService' => 'anagrafica_certest_service_id',
'ConsegnaRichiesta' => 'consegna_richiesta',
];
// Fixed fields visibili, ordinati come imported.php
$fixedStmt = $pdo->prepare("
SELECT id, fixed_field_key, is_manual, data_type, is_required, default_value, is_visible_import
FROM template_fixed_mapping
WHERE template_id = ? AND is_visible_import = 1
ORDER BY id
");
$fixedStmt->execute([$templateId]);
$fixedFieldsRaw = $fixedStmt->fetchAll(PDO::FETCH_ASSOC);
$desiredOrder = [
'ClienteResponsabile', 'ClienteFornitore', 'ClienteAnalisi', 'ClienteFatturazione',
'AnagraficaCertestObject', 'AnagraficaCertestService', 'MoltiplicatorePrezzo', 'ConsegnaRichiesta',
];
$excludeFromFixed = ['ClienteFornitore']; // reso come colonna a sé
$fixedFields = [];
$tempMap = [];
foreach ($fixedFieldsRaw as $f) {
if (in_array($f['fixed_field_key'], $excludeFromFixed, true)) continue;
$tempMap[$f['fixed_field_key']] = $f;
}
foreach ($desiredOrder as $key) {
if (isset($tempMap[$key])) {
$fixedFields[] = $tempMap[$key];
unset($tempMap[$key]);
}
}
foreach ($tempMap as $f) {
$fixedFields[] = $f;
}
// Main field mappings (max 2), come imported.php
$mapStmt = $pdo->prepare("
SELECT id, field_label, data_type, is_required, field_id, field_order,
main_field, is_visible_import, manual_default
FROM template_mapping
WHERE template_id = ?
ORDER BY field_order ASC, id ASC
");
$mapStmt->execute([$templateId]);
$allMappings = $mapStmt->fetchAll(PDO::FETCH_ASSOC);
$mainFieldMappings = [];
foreach ($allMappings as $mapping) {
if ((string)$mapping['main_field'] === '1' && (int)$mapping['is_visible_import'] === 1) {
$mainFieldMappings[] = $mapping;
}
if (count($mainFieldMappings) >= 2) break;
}
// Default idclient dal template
$tplStmt = $pdo->prepare("SELECT idclient FROM excel_templates WHERE id = ?");
$tplStmt->execute([$templateId]);
$default_idclient = $tplStmt->fetchColumn();
$default_idclient = $default_idclient !== false ? $default_idclient : null;
return [
'fixedFields' => $fixedFields,
'fixedAliasMap' => $fixedAliasMap,
'mainFieldMappings' => $mainFieldMappings,
'default_idclient' => $default_idclient,
];
}
}
if (!function_exists('buildGridRows')) {
/**
* Costruisce le righe gridData per la lista di iddatadb data, nell'ordine passato.
*
* @param int[] $iddatadbList
* @param array $config output di buildGridConfig()
* @return array righe nella stessa forma di imported.php $gridDataArray
*/
function buildGridRows(PDO $pdo, array $iddatadbList, array $config): array
{
$iddatadbList = array_values(array_filter(array_map('intval', $iddatadbList), fn($v) => $v > 0));
if (empty($iddatadbList)) {
return [];
}
$fixedFields = $config['fixedFields'];
$fixedAliasMap = $config['fixedAliasMap'];
$mainFieldMappings = $config['mainFieldMappings'];
$default_idclient = $config['default_idclient'];
$ph = implode(',', array_fill(0, count($iddatadbList), '?'));
// Righe datadb + user_name
$stmt = $pdo->prepare("
SELECT d.*, CONCAT(u.first_name, ' ', u.last_name) AS user_name
FROM datadb d
LEFT JOIN auth_users u ON d.user_id = u.id
WHERE d.iddatadb IN ($ph)
");
$stmt->execute($iddatadbList);
$byId = [];
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $r) {
$byId[(int)$r['iddatadb']] = $r;
}
// Dettagli (import_data_details)
$detStmt = $pdo->prepare("
SELECT d.id AS datadb_id, d.mapping_id, d.field_value,
m.field_id, m.field_label, m.data_type, m.is_required, m.manual_default
FROM import_data_details d
JOIN template_mapping m ON d.mapping_id = m.id
WHERE d.id IN ($ph)
");
$detStmt->execute($iddatadbList);
$detailsByRow = [];
foreach ($detStmt->fetchAll(PDO::FETCH_ASSOC) as $d) {
$detailsByRow[(int)$d['datadb_id']][] = $d;
}
// Costruzione righe nell'ordine della lista passata
$rows = [];
foreach ($iddatadbList as $id) {
$row = $byId[$id] ?? null;
if ($row === null) continue;
$rowObj = [
'iddatadb' => (int)$row['iddatadb'],
'status' => $row['status'] ?? 'i',
'idclient' => $row['idclient'] ?? $default_idclient,
'cliente_fornitore_id' => $row['cliente_fornitore_id'] ?? null,
'tested_component' => $row['tested_component'] ?? '',
'commessaweb' => $row['commessaweb'] ?? null,
'user_name' => $row['user_name'] ?? '',
'importreferencecode' => $row['importreferencecode'] ?? '',
'filename_import' => $row['filename_import'] ?? '',
'importdate' => $row['importdate'] ?? '',
];
// Fixed fields
$rowObj['fixedFields'] = [];
foreach ($fixedFields as $f) {
$key = $f['fixed_field_key'];
$dbCol = $fixedAliasMap[$key] ?? $key;
$val = $row[$dbCol] ?? '';
if ($val === '' || $val === null) {
$val = gdbFixedDefaultValue($f);
}
$rowObj['fixedFields'][$key] = (string)$val;
}
// Details
$rowObj['details'] = [];
$rowDetails = $detailsByRow[$id] ?? [];
foreach ($rowDetails as $d) {
$rowObj['details'][(string)$d['mapping_id']] = $d['field_value'] ?? '';
}
// Main field values
foreach ($mainFieldMappings as $mainMapping) {
$found = null;
foreach ($rowDetails as $d) {
if ($d['mapping_id'] == $mainMapping['id']) {
$found = $d;
break;
}
}
$rowObj['details'][(string)$mainMapping['id']] =
($found['field_value'] ?? null) ?? ($mainMapping['manual_default'] ?? '');
}
if (!empty($mainFieldMappings)) {
$firstMain = $mainFieldMappings[0];
$rowObj['mainFieldValue'] = $rowObj['details'][(string)$firstMain['id']] ?? '';
}
$rowObj['_dirty'] = false;
$rows[] = $rowObj;
}
return $rows;
}
}
+9 -1
View File
@@ -56,4 +56,12 @@ $photousername = basename($avatar);
//include files
require_once(__DIR__ . '/../../languages/en/general.php');
//include("generalsettings.php");
//include("generalsettings.php");
// Timbra la sessione dell'utente a ogni pagina (rolling manuale)
try {
$pdoSess = DBHandlerSelect::getInstance()->getConnection();
$pdoSess->prepare("UPDATE auth_sessions SET last_activity = ? WHERE user_id = ? ORDER BY last_activity DESC LIMIT 1")
->execute([time(), $iduserlogin]);
} catch (\Throwable $e) { /* non bloccare la pagina */
}
+17 -1
View File
@@ -98,11 +98,27 @@
<li>
<a href="stats_export_lims.php">
<div class="parent-icon">
<i class="bx bx-user-plus"></i>
<i class="bx bx-bar-chart-alt-2"></i>
</div>
<div class="menu-title">Stats</div>
</a>
</li>
<li>
<a href="routine_admin.php">
<div class="parent-icon">
<i class="bx bx-bar-chart-alt-2"></i>
</div>
<div class="menu-title">Routines</div>
</a>
</li>
<li>
<a href="warm_cache_run.php">
<div class="parent-icon">
<i class="bx bx-bar-chart-alt-2"></i>
</div>
<div class="menu-title">Warm Cache</div>
</a>
</li>
<?php endif; ?>
<li class="menu-label">Others</li>
+2
View File
@@ -108,6 +108,8 @@
<ul class="dropdown-menu dropdown-menu-end">
<li><a class="dropdown-item d-flex align-items-center" href="user-profile.php"><i class="bx bx-user fs-5"></i><span>Profile</span></a>
</li>
<li><a class="dropdown-item d-flex align-items-center" href="notification_settings.php"><i class="bx bx-user fs-5"></i><span>Notifications</span></a>
</li>
<?php if ($user->hasRole('Admin') || $user->hasRole('SuperUser')): ?>
<li>
<a class="dropdown-item d-flex align-items-center" href="user-admin.php">
@@ -617,7 +617,11 @@ $apiSampleJson = $template['api_sample_json'] ?? '';
</td>
<td>
<strong><?php echo htmlspecialchars($fm['fixed_field_key']); ?></strong>
<strong><?php
$fixedFieldLabels = ['ClienteAnalisi' => 'Buyer'];
$fixedKey = $fm['fixed_field_key'];
echo htmlspecialchars($fixedFieldLabels[$fixedKey] ?? $fixedKey);
?></strong>
</td>
<td><?php echo htmlspecialchars($fm['data_type']); ?></td>
@@ -2192,6 +2196,10 @@ $apiSampleJson = $template['api_sample_json'] ?? '';
const tbody = document.querySelector('#fixedFieldsTable tbody');
if (!tbody) return;
const fixedFieldLabels = {
'ClienteAnalisi': 'Buyer'
};
const keysWithDropdown = [
'ClienteResponsabile',
'ClienteFornitore',
@@ -2223,7 +2231,7 @@ $apiSampleJson = $template['api_sample_json'] ?? '';
${parseInt(r.is_required) === 1 ? 'checked' : ''}>
</td>
<td><strong>${escapeHtml(r.fixed_field_key)}</strong></td>
<td><strong>${escapeHtml(fixedFieldLabels[r.fixed_field_key] || r.fixed_field_key)}</strong></td>
<td>${escapeHtml(r.data_type || '')}</td>
+6 -16
View File
@@ -136,14 +136,9 @@ $matrixGroups = array_values($matrixGroups);
<button type="button"
class="list-group-item list-group-item-action analysis-matrix-item <?= $index === 0 ? 'active' : '' ?>"
data-matrix-id="<?= htmlspecialchars((string)($group['idmatrice'] ?? 'NO_MATRIX'), ENT_QUOTES, 'UTF-8') ?>">
<div class="fw-semibold">
<?= htmlspecialchars(
!empty($group['NomeMatriceTraduzione'])
? $group['NomeMatriceTraduzione']
: (!empty($group['idmatrice']) ? ('Matrix without translation') : 'No Matrix'),
ENT_QUOTES,
'UTF-8'
) ?>
<div class="fw-semibold analysis-matrix-name"
data-matrix-id="<?= htmlspecialchars((string)($group['idmatrice'] ?? 'NO_MATRIX'), ENT_QUOTES, 'UTF-8') ?>">
<?= !empty($group['idmatrice']) ? ('#' . (int)$group['idmatrice']) : 'No Matrix' ?>
</div>
<div class="small text-muted">
ID: <?= !empty($group['idmatrice']) ? (int)$group['idmatrice'] : '-' ?>
@@ -193,14 +188,9 @@ $matrixGroups = array_values($matrixGroups);
<div class="small text-muted mt-1">
Matrix:
<strong>
<?= htmlspecialchars(
!empty($part['NomeMatriceTraduzione'])
? $part['NomeMatriceTraduzione']
: (!empty($part['idmatrice']) ? 'Matrix without translation' : 'No Matrix'),
ENT_QUOTES,
'UTF-8'
) ?>
<strong class="analysis-part-matrix-name"
data-matrix-id="<?= htmlspecialchars($matrixId, ENT_QUOTES, 'UTF-8') ?>">
<?= !empty($part['idmatrice']) ? ('#' . (int)$part['idmatrice']) : 'No Matrix' ?>
</strong>
<?php if (!empty($part['idmatrice'])): ?>
<span class="small text-muted">(ID: <?= (int)$part['idmatrice'] ?>)</span>
+9
View File
@@ -48,6 +48,9 @@
<button type="button" class="btn btn-primary btn-sm" id="clonePartsBtn" style="padding: 0.1rem 0.5rem; font-size: 0.8rem;">
<i class="fas fa-clone"></i> Clona Parti
</button>
<button type="button" class="btn btn-warning btn-sm d-none" id="quotationeBtn" style="padding: 0.1rem 0.5rem; font-size: 0.8rem;">
<i class="fas fa-file-invoice-dollar"></i> Collega Quotazione
</button>
<button type="button" class="btn btn-secondary btn-sm ms-2" id="toggleVoiceBtn" style="padding: 0.1rem 0.5rem; font-size: 0.8rem;">
<i class="fas fa-microphone"></i> Voce
</button>
@@ -214,6 +217,12 @@
Duplica anche le analisi collegate
</label>
</div>
<div class="form-check mt-2">
<input class="form-check-input" type="checkbox" id="cloneOverwriteCheckbox" checked>
<label class="form-check-label" for="cloneOverwriteCheckbox">
<strong>Sovrascrivi parti esistenti</strong> (elimina le parti già presenti nei record di destinazione prima di inserire)
</label>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Annulla</button>
+10
View File
@@ -171,6 +171,11 @@
);
if (idx >= 0) window.gridData.splice(idx, 1);
// Aggiorna la lista dei record visibili (navigazione parti + clone)
window.visibleIddatadbList = window.gridData
.map((r) => parseInt(r.iddatadb, 10))
.filter(Boolean);
// Re-render
const gr = window.gridRenderer;
if (gr) gr.renderVisibleRows();
@@ -233,6 +238,11 @@
// Add to beginning of gridData
window.gridData.unshift(newRow);
// Aggiorna la lista dei record visibili (navigazione parti + clone)
window.visibleIddatadbList = window.gridData
.map((r) => parseInt(r.iddatadb, 10))
.filter(Boolean);
// Re-render
const gr = window.gridRenderer;
if (gr) gr.renderVisibleRows();
+127
View File
@@ -0,0 +1,127 @@
<?php
include('include/headscript.php');
$db = DBHandlerSelect::getInstance();
$pdo = $db->getConnection();
$userId = (int)($iduserlogin ?? 0);
// Carica le preferenze correnti dell'utente
$prefs = ['notify_export_email' => 1];
if ($userId > 0) {
$s = $pdo->prepare("SELECT notify_export_email FROM auth_users WHERE id = ? LIMIT 1");
$s->execute([$userId]);
$row = $s->fetch(PDO::FETCH_ASSOC);
if ($row) {
$prefs['notify_export_email'] = (int)($row['notify_export_email'] ?? 1);
}
}
// Flash message post-save (via querystring)
$saved = isset($_GET['saved']) && $_GET['saved'] === '1';
?>
<!doctype html>
<html lang="it">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="assets/images/favicon-32x32.png" type="image/png" />
<?php include('cssinclude.php'); ?>
<title>SmartTRF - Notifiche</title>
<style>
.notif-row {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 16px;
padding: 16px 0;
border-bottom: 1px solid #eef0f2;
}
.notif-row:last-child {
border-bottom: none;
}
.notif-text {
max-width: 640px;
}
.notif-text h6 {
margin: 0 0 4px;
font-size: 15px;
}
.notif-text p {
margin: 0;
font-size: 13px;
color: #6c757d;
}
.form-switch .form-check-input {
width: 2.6em;
height: 1.4em;
cursor: pointer;
}
</style>
</head>
<body>
<div class="wrapper">
<?php include('include/navbar.php'); ?>
<?php include('include/topbar.php'); ?>
<div class="page-wrapper">
<div class="page-content">
<div class="card radius-10">
<div class="card-header">
<div>
<h6 class="mb-0">Preferenze notifiche</h6>
<small class="text-muted">Scegli quali email vuoi ricevere da SmartTRF.</small>
</div>
</div>
<div class="card-body">
<?php if ($saved): ?>
<div class="alert alert-success py-2" role="alert">
<i class="fas fa-check-circle me-1"></i> Preferenze salvate.
</div>
<?php endif; ?>
<form action="update_notification_prefs.php" method="POST">
<input type="hidden" name="iduserlogin" value="<?= htmlspecialchars((string)$userId, ENT_QUOTES, 'UTF-8') ?>">
<!-- Notifica: commesse esportate -->
<div class="notif-row">
<div class="notif-text">
<h6>Ricezione email commesse esportate</h6>
<p>Ricevi un riepilogo via email al termine di ogni esportazione verso il LIMS (singola o in blocco), con l'esito di ciascuna commessa.</p>
</div>
<div class="form-check form-switch">
<input class="form-check-input" type="checkbox" role="switch"
id="notify_export_email" name="notify_export_email" value="1"
<?= $prefs['notify_export_email'] === 1 ? 'checked' : '' ?>>
</div>
</div>
<!-- Qui in futuro altre notifiche, stessa struttura .notif-row -->
<div class="mt-4">
<button type="submit" class="btn btn-primary">
<i class="fas fa-save me-1"></i> Salva preferenze
</button>
</div>
</form>
</div>
</div>
</div>
</div>
<div class="overlay toggle-icon"></div>
<?php include('include/footer.php'); ?>
</div>
<?php include('jsinclude.php'); ?>
</body>
</html>
+86 -11
View File
@@ -32,6 +32,16 @@ $(document).ready(function () {
return id === "new" || id === "" || id === null ? null : id;
}
// Legge ConsegnaRichiesta del record corrente dalla griglia (fixed field data)
function getConsegnaRichiestaDefault() {
const iddatadb = $("#partsModal").data("iddatadb");
if (!iddatadb) return "";
if (typeof getGridRecordById !== "function") return "";
const record = getGridRecordById(iddatadb);
if (!record || !record.fixedFields) return "";
return record.fixedFields.ConsegnaRichiesta || "";
}
function loadPartsExtraField(iddatadb, done) {
partsExtraField = null;
@@ -210,23 +220,60 @@ $(document).ready(function () {
dropdownParent: $("#partsModal"),
minimumResultsForSearch: 0,
sorter: function (data) {
return data.sort(function (a, b) {
const textA = (a.text || "").toLowerCase();
const textB = (b.text || "").toLowerCase();
return textA.localeCompare(textB, "it", {
sensitivity: "base",
numeric: true,
});
const rawTerm = ((window.__extraFieldSearchTerm || "") + "")
.toLowerCase()
.trim();
const terms = rawTerm.split(/\s+/).filter(Boolean);
const firstTerm = terms[0] || "";
const scoreOf = function (text) {
const t = (text || "").toLowerCase();
if (!firstTerm) return 3;
if (t === rawTerm) return 0; // match esatto
if (t.indexOf(firstTerm) === 0) return 1; // inizia col primo termine
if (
new RegExp(
"(^|\\s)" +
firstTerm.replace(
/[.*+?^${}()|[\]\\]/g,
"\\$&",
),
).test(t)
)
return 2; // primo termine a inizio parola
return 3; // presente ma non a inizio parola
};
return data.slice().sort(function (a, b) {
const sa = scoreOf(a.text);
const sb = scoreOf(b.text);
if (sa !== sb) return sa - sb;
return (a.text || "")
.toLowerCase()
.localeCompare((b.text || "").toLowerCase(), "it", {
sensitivity: "base",
numeric: true,
});
});
},
matcher: function (params, data) {
if ($.trim(params.term) === "") return data;
if (typeof data.text === "undefined") return null;
const term = params.term.toLowerCase();
// memorizza il termine per il sorter (Select2 non lo passa al sorter)
window.__extraFieldSearchTerm = params.term;
const terms = params.term
.toLowerCase()
.split(/\s+/)
.filter(Boolean);
const text = data.text.toLowerCase();
return text.indexOf(term) > -1 ? data : null;
// AND: tutti i termini devono essere presenti (posizione-indipendente)
for (let i = 0; i < terms.length; i++) {
if (text.indexOf(terms[i]) === -1) return null;
}
return data;
},
});
@@ -555,6 +602,14 @@ $(document).ready(function () {
// ===================
function getVisiblePartsRecordList() {
// Se i filtri sono attivi, usa la regola selezione/visibili di gridFilter.
if (typeof window.getTargetGridIds === "function") {
const target = window.getTargetGridIds();
if (target && target.size > 0) {
return [...target].map((v) => parseInt(v, 10)).filter(Boolean);
}
}
const listFromModal = $("#partsModal").data("visible-iddatadb-list");
if (Array.isArray(listFromModal) && listFromModal.length > 0) {
@@ -1243,6 +1298,13 @@ $(document).ready(function () {
initializeSelect2($select, nextPartNumber, "", null, selectedMacro);
initializeExtraFieldSelect2($newRow);
// Default: data di consegna richiesta dal record (solo se il campo è vuoto)
const $dateInput = $newRow.find(".part-dateexpiry");
if ($dateInput.length && !$dateInput.val()) {
const consegna = getConsegnaRichiestaDefault();
if (consegna) $dateInput.val(consegna);
}
updateRowButtons();
if (!isLoadingPartsRecord) {
@@ -1573,6 +1635,13 @@ $(document).ready(function () {
`#partsTableBody tr[data-part-id="${part.id}"]`,
);
setRowMix($row, part.mix === "Y" ? "Y" : "N");
// Default consegna richiesta se la parte non ha già una data
if (!(part.dateexpiry || "")) {
const consegnaDef = getConsegnaRichiestaDefault();
if (consegnaDef) {
$row.find(".part-dateexpiry").val(consegnaDef);
}
}
if (
part.extra_value_id !== undefined &&
part.extra_value_id !== null
@@ -2265,8 +2334,11 @@ $(document).ready(function () {
const sourceIddatadb =
parseInt($("#partsModal").data("iddatadb"), 10) || null;
const visibleListRaw =
$("#partsModal").data("visible-iddatadb-list") || [];
// Target = selezione/visibili secondo gridFilter, con fallback alla lista del modal
let visibleListRaw =
typeof getVisiblePartsRecordList === "function"
? getVisiblePartsRecordList()
: $("#partsModal").data("visible-iddatadb-list") || [];
if (!sourceIddatadb) {
const errorMsg = $(
@@ -2308,6 +2380,7 @@ $(document).ready(function () {
);
$("#cloneNotesCheckbox").prop("checked", true);
$("#cloneAnalysesCheckbox").prop("checked", false);
$("#cloneOverwriteCheckbox").prop("checked", true);
const modalInstance = new bootstrap.Modal(
document.getElementById("cloneConfirmModal"),
@@ -2323,6 +2396,7 @@ $(document).ready(function () {
const targetIds = $("#cloneConfirmModal").data("target-ids") || [];
const cloneNotes = $("#cloneNotesCheckbox").is(":checked");
const cloneAnalyses = $("#cloneAnalysesCheckbox").is(":checked");
const cloneOverwrite = $("#cloneOverwriteCheckbox").is(":checked");
if (!sourceIddatadb || !targetIds.length) {
return;
@@ -2351,6 +2425,7 @@ $(document).ready(function () {
target_iddatadb_list: targetIds,
clone_notes: cloneNotes,
clone_analyses: cloneAnalyses,
overwrite: cloneOverwrite,
}),
success: function (response) {
$btn.prop("disabled", false).html(originalHtml);
@@ -39,6 +39,7 @@ try {
$button_bg_color = trim($_POST['button_bg_color'] ?? '#007bff');
$button_text_color = trim($_POST['button_text_color'] ?? '#ffffff');
$button_label = trim($_POST['button_label'] ?? 'Click Me');
$template_note = trim($_POST['template_note'] ?? '');
// Allowed source types
if (!in_array($source_type, ['XLS', 'API', 'JSON', 'PDF'], true)) {
@@ -122,6 +123,7 @@ try {
button_bg_color = ?,
button_text_color = ?,
button_label = ?,
template_note = ?,
updated_at = NOW()
WHERE id = ?
");
@@ -144,6 +146,7 @@ try {
$button_bg_color,
$button_text_color,
$button_label,
$template_note,
$id
]);
+1
View File
@@ -506,6 +506,7 @@ try {
if ($routineData) {
$response['apply_routine'] = true;
$response['routine_data'] = [
'idroutine' => (int)$routineData['idroutine'],
'name' => $routineData['name'] ?? 'Routine Sconosciuta',
'instruction' => $routineData['instruction'] ?? 'Nessuna descrizione disponibile',
'filename' => $routineData['filename'] ?? '',
+41
View File
@@ -0,0 +1,41 @@
<?php
// Evita che eventuale output di headscript rompa il JSON
ob_start();
include('include/headscript.php');
ob_end_clean();
header('Content-Type: application/json');
$iddatadb = (int)($_POST['iddatadb'] ?? 0);
$newStatus = $_POST['status'] ?? 'i';
if ($iddatadb <= 0) {
echo json_encode(['success' => false, 'message' => 'ID record mancante']);
exit;
}
// Da questa azione consentiamo solo il ritorno a 'i'
if ($newStatus !== 'i') {
echo json_encode(['success' => false, 'message' => 'Stato non consentito']);
exit;
}
try {
$db = DBHandlerSelect::getInstance();
$pdo = $db->getConnection();
// Aggiorna solo se attualmente è in stato 'l' (To LIMS).
// Azzera idcommessaweb: il revert è una scelta esplicita di riesportare, altrimenti il
// CHECK PRELIMINARE di export_to_lims.php riallineerebbe la riga alla vecchia commessa.
// commessaweb resta come traccia del codice precedente.
$stmt = $pdo->prepare("UPDATE datadb SET status = ?, idcommessaweb = NULL WHERE iddatadb = ? AND status = 'l'");
$stmt->execute([$newStatus, $iddatadb]);
if ($stmt->rowCount() > 0) {
echo json_encode(['success' => true]);
} else {
echo json_encode(['success' => false, 'message' => 'Record non trovato o già modificato']);
}
} catch (Throwable $e) {
echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
+549
View File
@@ -0,0 +1,549 @@
<?php
include('include/headscript.php');
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
if (!$user->hasRole('Admin') && !$user->hasRole('SuperUser')) {
header('Location: import_dashboard.php');
exit;
}
$db = DBHandlerSelect::getInstance();
$pdo = $db->getConnection();
/*
* Nome file del motore generico condiviso da tutte le routine engine.
* Deve corrispondere al file presente in routines/.
*/
$engineFilename = '_engine.php';
/*
* CSRF token.
*/
if (empty($_SESSION['routine_admin_csrf'])) {
$_SESSION['routine_admin_csrf'] = bin2hex(random_bytes(32));
}
$csrfToken = $_SESSION['routine_admin_csrf'];
function cleanInput($value)
{
return trim((string)($value ?? ''));
}
function redirectWithMessage($type, $message)
{
$_SESSION['routine_admin_flash'] = [
'type' => $type,
'message' => $message
];
header('Location: ' . $_SERVER['PHP_SELF']);
exit;
}
/*
* Gestione azioni POST.
*/
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
try {
$postedToken = $_POST['csrf_token'] ?? '';
if (!hash_equals($csrfToken, $postedToken)) {
throw new Exception('Token di sicurezza non valido.');
}
$action = cleanInput($_POST['action'] ?? '');
if ($action === 'create' || $action === 'update') {
$name = cleanInput($_POST['name'] ?? '');
$description = cleanInput($_POST['description'] ?? '');
$engine = (int)($_POST['engine'] ?? 0) === 1 ? 1 : 0;
$headerrow = (int)($_POST['headerrow'] ?? 1);
$filename = cleanInput($_POST['filename'] ?? '');
if ($name === '') {
throw new Exception('Il nome della routine è obbligatorio.');
}
if ($headerrow < 1) {
$headerrow = 1;
}
/*
* Se è una routine a motore, il filename è forzato al file del motore.
* Se è legacy, serve un filename di file reale.
*/
if ($engine === 1) {
$filename = $GLOBALS['engineFilename'];
} else {
if ($filename === '') {
throw new Exception('Per una routine di tipo File indica il nome del file (es. fendi.php).');
}
}
if ($action === 'create') {
// instruction è NOT NULL nello schema: valorizziamo sempre.
$instruction = $engine === 1
? 'Routine gestita dal motore generico (routine_step).'
: ('Routine su file: ' . $filename);
$stmt = $pdo->prepare("
INSERT INTO routine (name, description, instruction, filename, engine, headerrow)
VALUES (:name, :descr, :instr, :fn, :engine, :hr)
");
$stmt->execute([
':name' => $name,
':descr' => ($description !== '' ? $description : null),
':instr' => $instruction,
':fn' => $filename,
':engine' => $engine,
':hr' => $headerrow,
]);
redirectWithMessage('success', 'Routine creata correttamente.');
} else {
$idroutine = (int)($_POST['idroutine'] ?? 0);
if ($idroutine <= 0) {
throw new Exception('ID routine non valido.');
}
$stmt = $pdo->prepare("
UPDATE routine
SET name = :name,
description = :descr,
filename = :fn,
engine = :engine,
headerrow = :hr
WHERE idroutine = :id
");
$stmt->execute([
':name' => $name,
':descr' => ($description !== '' ? $description : null),
':fn' => $filename,
':engine' => $engine,
':hr' => $headerrow,
':id' => $idroutine,
]);
redirectWithMessage('success', 'Routine aggiornata correttamente.');
}
}
if ($action === 'delete') {
$idroutine = (int)($_POST['idroutine'] ?? 0);
if ($idroutine <= 0) {
throw new Exception('ID routine non valido.');
}
// Rimuove prima gli eventuali step collegati, poi la routine.
$stmt = $pdo->prepare("DELETE FROM routine_step WHERE idroutine = :id");
$stmt->execute([':id' => $idroutine]);
$stmt = $pdo->prepare("DELETE FROM routine WHERE idroutine = :id");
$stmt->execute([':id' => $idroutine]);
redirectWithMessage('success', 'Routine eliminata correttamente.');
}
throw new Exception('Azione non valida.');
} catch (Exception $e) {
redirectWithMessage('error', $e->getMessage());
}
}
/*
* Caricamento routine + conteggio step.
*/
$stmt = $pdo->query("
SELECT
r.idroutine,
r.name,
r.description,
r.filename,
r.engine,
r.headerrow,
(SELECT COUNT(*) FROM routine_step s WHERE s.idroutine = r.idroutine) AS step_count
FROM routine r
ORDER BY r.name ASC
");
$routines = $stmt->fetchAll(PDO::FETCH_ASSOC);
$flash = $_SESSION['routine_admin_flash'] ?? null;
unset($_SESSION['routine_admin_flash']);
?>
<!doctype html>
<html lang="it">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="assets/images/favicon-32x32.png" type="image/png" />
<?php include('cssinclude.php'); ?>
<title>Gestione Routine - <?= htmlspecialchars($titlewebsite, ENT_QUOTES, 'UTF-8'); ?></title>
<style>
.small-muted {
font-size: 12px;
color: #6c757d;
}
/* La tabella non deve sforare la pagina */
#routinesTable {
table-layout: fixed;
width: 100%;
}
#routinesTable td,
#routinesTable th {
overflow-wrap: break-word;
word-break: break-word;
white-space: normal;
vertical-align: middle;
}
/* Colonna descrizione: va a capo invece di allargare la tabella */
#routinesTable td.desc-cell {
white-space: normal;
overflow-wrap: break-word;
word-break: break-word;
max-width: 320px;
}
/* Le azioni restano su una riga */
#routinesTable td.table-actions {
white-space: nowrap;
}
.badge-engine {
background: #6f42c1;
color: #fff;
}
.badge-file {
background: #6c757d;
color: #fff;
}
.table-actions {
white-space: nowrap;
}
.filename-chip {
font-family: Consolas, Monaco, monospace;
font-size: 12px;
background: #f1f5f9;
border: 1px solid #e2e8f0;
border-radius: 6px;
padding: 2px 8px;
color: #334155;
}
.step-count-pill {
display: inline-block;
min-width: 26px;
text-align: center;
font-weight: 600;
border-radius: 999px;
padding: 2px 10px;
background: #eef2ff;
color: #4338ca;
border: 1px solid #e0e7ff;
}
</style>
</head>
<body>
<div class="wrapper">
<?php include('include/navbar.php'); ?>
<?php include('include/topbar.php'); ?>
<div class="page-wrapper">
<div class="page-content">
<?php include('top_stat_widget.php'); ?>
<div class="card radius-10">
<div class="card-header">
<div class="d-flex align-items-center justify-content-between">
<div>
<h6 class="mb-0">Gestione Routine</h6>
<small class="text-muted">Crea e configura le routine di importazione. Le routine di tipo Motore sono configurabili a step senza codice.</small>
</div>
<button type="button" class="btn btn-primary" id="btnAddRoutine">
<i class="bx bx-plus"></i> Nuova Routine
</button>
</div>
</div>
<div class="card-body">
<div class="table-responsive">
<table id="routinesTable" class="table table-striped table-bordered align-middle">
<thead>
<tr>
<th>Nome</th>
<th>Descrizione</th>
<th style="width: 120px;">Tipo</th>
<th style="width: 160px;">File</th>
<th style="width: 90px;">Header row</th>
<th style="width: 80px;">Step</th>
<th style="width: 130px;">Azioni</th>
</tr>
</thead>
<tbody>
<?php foreach ($routines as $row): ?>
<?php $isEngine = ((int)$row['engine'] === 1); ?>
<tr>
<td><?= htmlspecialchars($row['name'] ?? '', ENT_QUOTES, 'UTF-8'); ?></td>
<td class="small-muted desc-cell"><?= htmlspecialchars($row['description'] ?? '', ENT_QUOTES, 'UTF-8'); ?></td>
<td>
<?php if ($isEngine): ?>
<span class="badge badge-engine">Motore</span>
<?php else: ?>
<span class="badge badge-file">File</span>
<?php endif; ?>
</td>
<td><span class="filename-chip"><?= htmlspecialchars($row['filename'] ?? '', ENT_QUOTES, 'UTF-8'); ?></span></td>
<td class="text-center"><?= (int)$row['headerrow']; ?></td>
<td class="text-center">
<?php if ($isEngine): ?>
<span class="step-count-pill"><?= (int)$row['step_count']; ?></span>
<?php else: ?>
<span class="small-muted">—</span>
<?php endif; ?>
</td>
<td class="table-actions">
<?php if ($isEngine): ?>
<a class="btn btn-sm btn-outline-success"
href="routine_steps.php?idroutine=<?= (int)$row['idroutine']; ?>"
title="Gestisci step" data-bs-toggle="tooltip">
<i class="bx bx-list-ul"></i>
</a>
<?php endif; ?>
<button
type="button"
class="btn btn-sm btn-outline-primary btnEditRoutine"
data-id="<?= (int)$row['idroutine']; ?>"
data-name="<?= htmlspecialchars($row['name'] ?? '', ENT_QUOTES, 'UTF-8'); ?>"
data-description="<?= htmlspecialchars($row['description'] ?? '', ENT_QUOTES, 'UTF-8'); ?>"
data-engine="<?= (int)$row['engine']; ?>"
data-filename="<?= htmlspecialchars($row['filename'] ?? '', ENT_QUOTES, 'UTF-8'); ?>"
data-headerrow="<?= (int)$row['headerrow']; ?>"
title="Modifica" data-bs-toggle="tooltip">
<i class="bx bx-edit"></i>
</button>
<button
type="button"
class="btn btn-sm btn-outline-danger btnDeleteRoutine"
data-id="<?= (int)$row['idroutine']; ?>"
data-name="<?= htmlspecialchars($row['name'] ?? '', ENT_QUOTES, 'UTF-8'); ?>"
title="Elimina" data-bs-toggle="tooltip">
<i class="bx bx-trash"></i>
</button>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<div class="overlay toggle-icon"></div>
<a href="javaScript:;" class="back-to-top"><i class='bx bxs-up-arrow-alt'></i></a>
<?php include('include/footer.php'); ?>
</div>
<!-- Modal Routine -->
<div class="modal fade" id="routineModal" tabindex="-1" aria-hidden="true">
<div class="modal-dialog modal-lg modal-dialog-centered">
<form method="POST" class="modal-content" id="routineForm">
<input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrfToken, ENT_QUOTES, 'UTF-8'); ?>">
<input type="hidden" name="action" id="formAction" value="create">
<input type="hidden" name="idroutine" id="idroutine" value="">
<div class="modal-header">
<h5 class="modal-title" id="routineModalTitle">Nuova Routine</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Chiudi"></button>
</div>
<div class="modal-body">
<div class="row g-3">
<div class="col-md-12">
<label for="name" class="form-label">Nome *</label>
<input type="text" class="form-control" id="name" name="name" required>
</div>
<div class="col-md-12">
<label for="description" class="form-label">Descrizione</label>
<input type="text" class="form-control" id="description" name="description" maxlength="150">
</div>
<div class="col-md-6">
<label for="engine" class="form-label">Tipo routine *</label>
<select class="form-select" id="engine" name="engine" required>
<option value="1">Motore (step configurabili)</option>
<option value="0">File (legacy)</option>
</select>
<div class="small-muted mt-1">
Motore: configurabile a step da questa interfaccia. File: logica in un file PHP dedicato.
</div>
</div>
<div class="col-md-6">
<label for="headerrow" class="form-label">Riga intestazione (header row) *</label>
<input type="number" class="form-control" id="headerrow" name="headerrow" min="1" value="1" required>
</div>
<div class="col-md-12" id="filenameWrapper">
<label for="filename" class="form-label">Nome file</label>
<input type="text" class="form-control" id="filename" name="filename" placeholder="es. fendi.php">
<div class="small-muted mt-1" id="filenameHelp">
Per le routine di tipo File indica il nome del file PHP presente nella cartella routines/.
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-light" data-bs-dismiss="modal">Annulla</button>
<button type="submit" class="btn btn-primary" id="saveRoutineButton">Salva Routine</button>
</div>
</form>
</div>
</div>
<!-- Delete Form -->
<form method="POST" id="deleteRoutineForm" style="display:none;">
<input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrfToken, ENT_QUOTES, 'UTF-8'); ?>">
<input type="hidden" name="action" value="delete">
<input type="hidden" name="idroutine" id="deleteIdRoutine" value="">
</form>
<?php include('jsinclude.php'); ?>
<script>
document.addEventListener('DOMContentLoaded', function() {
const routineModal = new bootstrap.Modal(document.getElementById('routineModal'));
const formAction = document.getElementById('formAction');
const idroutine = document.getElementById('idroutine');
const routineModalTitle = document.getElementById('routineModalTitle');
const saveRoutineButton = document.getElementById('saveRoutineButton');
const name = document.getElementById('name');
const description = document.getElementById('description');
const engine = document.getElementById('engine');
const headerrow = document.getElementById('headerrow');
const filename = document.getElementById('filename');
const filenameWrapper = document.getElementById('filenameWrapper');
const filenameHelp = document.getElementById('filenameHelp');
const engineFilename = "<?= htmlspecialchars($engineFilename, ENT_QUOTES, 'UTF-8'); ?>";
/*
* Mostra/nasconde il campo filename in base al tipo di routine.
* Motore -> filename forzato al file del motore e campo di sola lettura.
*/
function applyEngineUi() {
if (engine.value === '1') {
filename.value = engineFilename;
filename.readOnly = true;
filenameHelp.textContent = 'Le routine di tipo Motore usano automaticamente il file ' + engineFilename + '.';
} else {
if (filename.value === engineFilename) {
filename.value = '';
}
filename.readOnly = false;
filenameHelp.textContent = 'Per le routine di tipo File indica il nome del file PHP presente nella cartella routines/.';
}
}
engine.addEventListener('change', applyEngineUi);
function resetModalForCreate() {
formAction.value = 'create';
idroutine.value = '';
routineModalTitle.textContent = 'Nuova Routine';
saveRoutineButton.textContent = 'Crea Routine';
name.value = '';
description.value = '';
engine.value = '1';
headerrow.value = '1';
filename.value = '';
applyEngineUi();
}
function setModalForEdit(button) {
formAction.value = 'update';
idroutine.value = button.dataset.id || '';
routineModalTitle.textContent = 'Modifica Routine';
saveRoutineButton.textContent = 'Aggiorna Routine';
name.value = button.dataset.name || '';
description.value = button.dataset.description || '';
engine.value = button.dataset.engine === '1' ? '1' : '0';
headerrow.value = button.dataset.headerrow || '1';
filename.value = button.dataset.filename || '';
applyEngineUi();
}
document.getElementById('btnAddRoutine').addEventListener('click', function() {
resetModalForCreate();
routineModal.show();
});
document.querySelectorAll('.btnEditRoutine').forEach(function(button) {
button.addEventListener('click', function() {
setModalForEdit(button);
routineModal.show();
});
});
document.querySelectorAll('.btnDeleteRoutine').forEach(function(button) {
button.addEventListener('click', function() {
const id = button.dataset.id;
const nm = button.dataset.name || 'questa routine';
Swal.fire({
title: 'Eliminare la routine?',
text: 'Vuoi eliminare "' + nm + '"? Verranno rimossi anche gli step collegati. Operazione irreversibile.',
icon: 'warning',
showCancelButton: true,
confirmButtonText: 'Sì, elimina',
cancelButtonText: 'Annulla',
confirmButtonColor: '#d33'
}).then(function(result) {
if (result.isConfirmed) {
document.getElementById('deleteIdRoutine').value = id;
document.getElementById('deleteRoutineForm').submit();
}
});
});
});
if (typeof $ !== 'undefined' && $.fn.DataTable) {
$('#routinesTable').DataTable({
pageLength: 25,
order: [
[0, 'asc']
]
});
}
<?php if ($flash): ?>
Swal.fire({
icon: '<?= htmlspecialchars($flash['type'], ENT_QUOTES, 'UTF-8'); ?>',
title: '<?= $flash['type'] === 'success' ? 'Fatto' : ($flash['type'] === 'warning' ? 'Attenzione' : 'Errore'); ?>',
text: '<?= htmlspecialchars($flash['message'], ENT_QUOTES, 'UTF-8'); ?>'
});
<?php endif; ?>
});
</script>
</body>
</html>
+184
View File
@@ -0,0 +1,184 @@
<?php
/**
* routine_preview.php
* -------------------
* Anteprima di una routine a motore su un XLS caricato temporaneamente.
*
* - Riceve via multipart/form-data: `file` (XLS/XLSX) e `idroutine`.
* - NON salva nulla: il file viene letto dal tmp di PHP ed elaborato in RAM.
* - Legge la PRIMA riga dati subito dopo l'header row (routine.headerrow).
* - Impacchetta la riga nel formato excelData atteso dal motore:
* [ ['excelrow' => N, 'data' => [0=>.., 1=>.., ...]] ]
* - Include _engine.php e applica applyRoutine().
* - Risponde JSON con la riga elaborata + intestazioni + lettere colonna.
*/
ob_start();
session_start();
require_once '../../vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
Dotenv\Dotenv::createImmutable(dirname(__DIR__, 2))->safeLoad();
date_default_timezone_set($_ENV['APP_TIMEZONE'] ?? 'Europe/Rome');
header('Content-Type: application/json');
$response = [
'error' => '',
'headers' => [], // intestazioni prese dalla header row
'letters' => [], // lettere colonna (A, B, C, ...) allineate ai valori
'row' => [], // valori della riga DOPO l'applicazione del motore
'excelrow' => 0, // numero riga excel elaborata
];
/**
* Indice zero-based -> lettera colonna Excel (0 -> A, 25 -> Z, 26 -> AA...).
*/
function previewIndexToCol($index)
{
$index = (int)$index;
if ($index < 0) {
return '';
}
$letters = '';
$index += 1;
while ($index > 0) {
$rem = ($index - 1) % 26;
$letters = chr(ord('A') + $rem) . $letters;
$index = intdiv($index - 1, 26);
}
return $letters;
}
try {
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
throw new Exception('Richiesta non valida.');
}
$idroutine = (int)($_POST['idroutine'] ?? 0);
if ($idroutine <= 0) {
throw new Exception('ID routine mancante.');
}
if (
empty($_FILES['file']) ||
!isset($_FILES['file']['tmp_name']) ||
$_FILES['file']['error'] !== UPLOAD_ERR_OK
) {
throw new Exception('Nessun file caricato o upload non riuscito.');
}
// --- Recupera la routine e verifica che sia a motore ---
require_once __DIR__ . '/class/db-functions.php';
$pdo = DBHandlerSelect::getInstance()->getConnection();
$stmt = $pdo->prepare("SELECT idroutine, name, engine, headerrow FROM routine WHERE idroutine = :id LIMIT 1");
$stmt->execute([':id' => $idroutine]);
$routine = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$routine) {
throw new Exception('Routine non trovata.');
}
if ((int)$routine['engine'] !== 1) {
throw new Exception('Questa routine non è di tipo Motore: anteprima non disponibile.');
}
$headerRow = max(1, (int)$routine['headerrow']); // riga 1-based dell'intestazione
// --- Legge l'XLS dal file temporaneo (nessun salvataggio) ---
$tmpPath = $_FILES['file']['tmp_name'];
$reader = IOFactory::createReaderForFile($tmpPath);
$reader->setReadDataOnly(true);
$spreadsheet = $reader->load($tmpPath);
$sheet = $spreadsheet->getActiveSheet();
$highestColIndex = Coordinate::columnIndexFromString($sheet->getHighestDataColumn()); // 1-based
$highestRow = $sheet->getHighestDataRow();
// --- Intestazioni dalla header row ---
$headers = [];
$letters = [];
for ($c = 1; $c <= $highestColIndex; $c++) {
$val = $sheet->getCell([$c, $headerRow])->getValue();
$headers[] = ($val === null ? '' : (string)$val);
$letters[] = previewIndexToCol($c - 1); // zero-based -> lettera
}
// --- Trova la prima riga dati valorizzata dopo l'header ---
$dataRowNumber = null;
$rowValues = null;
for ($r = $headerRow + 1; $r <= $highestRow; $r++) {
$vals = [];
$hasValue = false;
for ($c = 1; $c <= $highestColIndex; $c++) {
$v = $sheet->getCell([$c, $r])->getValue();
$v = ($v === null ? '' : (string)$v);
if ($v !== '') {
$hasValue = true;
}
$vals[$c - 1] = $v; // indice zero-based, allineato alle colonne
}
if ($hasValue) {
$dataRowNumber = $r;
$rowValues = $vals;
break;
}
}
if ($dataRowNumber === null) {
throw new Exception('Nessuna riga dati valorizzata trovata dopo la riga di intestazione (' . $headerRow . ').');
}
// --- Impacchetta nel formato excelData e applica il motore ---
$excelData = [
[
'excelrow' => $dataRowNumber,
'data' => $rowValues,
],
];
// Il motore legge gli step dal DB in base a idroutine.
$routineData = [
'idroutine' => $idroutine,
'name' => $routine['name'],
'headerrow' => $headerRow,
'xls_headers' => $headers,
];
require_once __DIR__ . '/routines/_engine.php';
applyRoutine($excelData, $routineData); // modifica in place
$processed = $excelData[0]['data'] ?? [];
// Riallinea l'output all'ampiezza delle intestazioni (il merge può creare indici nuovi).
$maxIndex = max(
count($headers) - 1,
empty($processed) ? 0 : max(array_keys($processed))
);
$outRow = [];
$outLetters = [];
$outHeaders = [];
for ($i = 0; $i <= $maxIndex; $i++) {
$outRow[] = array_key_exists($i, $processed) ? (string)$processed[$i] : '';
$outLetters[] = previewIndexToCol($i);
$outHeaders[] = array_key_exists($i, $headers) ? $headers[$i] : '';
}
$response['headers'] = $outHeaders;
$response['letters'] = $outLetters;
$response['row'] = $outRow;
$response['excelrow'] = $dataRowNumber;
} catch (Throwable $e) {
$response['error'] = 'Errore anteprima: ' . $e->getMessage();
error_log('routine_preview.php: ' . $e->getMessage());
}
ob_end_clean();
echo json_encode($response, JSON_UNESCAPED_UNICODE);
exit;
+976
View File
@@ -0,0 +1,976 @@
<?php
include('include/headscript.php');
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
if (!$user->hasRole('Admin') && !$user->hasRole('SuperUser')) {
header('Location: import_dashboard.php');
exit;
}
$db = DBHandlerSelect::getInstance();
$pdo = $db->getConnection();
/*
* CSRF token.
*/
if (empty($_SESSION['routine_steps_csrf'])) {
$_SESSION['routine_steps_csrf'] = bin2hex(random_bytes(32));
}
$csrfToken = $_SESSION['routine_steps_csrf'];
function cleanInput($value)
{
return trim((string)($value ?? ''));
}
/*
* Determina l'id routine dalla querystring (GET) o dal POST.
*/
$idroutine = 0;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$idroutine = (int)($_POST['idroutine'] ?? 0);
} else {
$idroutine = (int)($_GET['idroutine'] ?? 0);
}
function redirectToSteps($idroutine, $type, $message)
{
$_SESSION['routine_steps_flash'] = [
'type' => $type,
'message' => $message
];
header('Location: routine_steps.php?idroutine=' . (int)$idroutine);
exit;
}
/*
* Converte lettera colonna Excel in indice zero-based. Accetta anche numeri.
* A=0, B=1, ... Z=25, AA=26, ...
*/
function colToIndex($ref)
{
$ref = strtoupper(trim((string)$ref));
if ($ref === '') {
return null;
}
if (ctype_digit($ref)) {
return (int)$ref;
}
$index = 0;
$len = strlen($ref);
for ($i = 0; $i < $len; $i++) {
$c = $ref[$i];
if ($c < 'A' || $c > 'Z') {
return null;
}
$index = $index * 26 + (ord($c) - ord('A') + 1);
}
return $index - 1;
}
/*
* Converte indice zero-based in lettera Excel (per mostrare gli step salvati).
*/
function indexToCol($index)
{
$index = (int)$index;
if ($index < 0) {
return '';
}
$letters = '';
$index += 1;
while ($index > 0) {
$rem = ($index - 1) % 26;
$letters = chr(ord('A') + $rem) . $letters;
$index = intdiv($index - 1, 26);
}
return $letters;
}
/*
* Normalizza una stringa di colonne separate da virgola ("D, F, H") in
* un array di indici zero-based, validando ogni riferimento.
*/
function parseColumnList($raw)
{
$raw = trim((string)$raw);
if ($raw === '') {
return [];
}
$parts = preg_split('/[\s,;]+/', $raw);
$out = [];
foreach ($parts as $p) {
if ($p === '') {
continue;
}
$idx = colToIndex($p);
if ($idx === null) {
throw new Exception('Riferimento colonna non valido: "' . $p . '". Usa lettere come D, F, H.');
}
$out[] = $idx;
}
return $out;
}
/*
* Verifica esistenza routine ed engine = 1.
*/
$routine = null;
if ($idroutine > 0) {
$stmt = $pdo->prepare("SELECT idroutine, name, description, engine, headerrow FROM routine WHERE idroutine = :id LIMIT 1");
$stmt->execute([':id' => $idroutine]);
$routine = $stmt->fetch(PDO::FETCH_ASSOC);
}
if (!$routine) {
$_SESSION['routine_admin_flash'] = ['type' => 'error', 'message' => 'Routine non trovata.'];
header('Location: routine_admin.php');
exit;
}
if ((int)$routine['engine'] !== 1) {
$_SESSION['routine_admin_flash'] = ['type' => 'error', 'message' => 'Questa routine è di tipo File: gli step non sono configurabili da qui.'];
header('Location: routine_admin.php');
exit;
}
/*
* Vocabolario operazioni disponibili (deve combaciare con gli handler di _engine.php).
*/
$operations = ['merge', 'copy', 'clear', 'trim', 'replace', 'uppercase', 'lowercase'];
/*
* Gestione azioni POST.
*/
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
try {
$postedToken = $_POST['csrf_token'] ?? '';
if (!hash_equals($csrfToken, $postedToken)) {
throw new Exception('Token di sicurezza non valido.');
}
$action = cleanInput($_POST['action'] ?? '');
if ($action === 'create' || $action === 'update') {
$operation = strtolower(cleanInput($_POST['operation'] ?? ''));
$active = (int)($_POST['active'] ?? 1) === 1 ? 1 : 0;
if (!in_array($operation, $operations, true)) {
throw new Exception('Operazione non valida.');
}
/*
* Costruzione params in base all'operazione.
* Le colonne arrivano come lettere e vengono convertite in indici.
*/
$params = [];
if ($operation === 'merge') {
$sources = parseColumnList($_POST['source_columns'] ?? '');
$target = colToIndex($_POST['target_column'] ?? '');
if (empty($sources)) {
throw new Exception('Indica almeno una colonna sorgente (es. D, F, H).');
}
if ($target === null) {
throw new Exception('Indica la colonna di destinazione (es. J).');
}
$params = [
'source_columns' => $sources,
'target_column' => $target,
'separator' => (string)($_POST['separator'] ?? ' '),
'skip_empty' => isset($_POST['skip_empty']) ? true : false,
];
} elseif ($operation === 'copy') {
$src = colToIndex($_POST['source_column'] ?? '');
$dst = colToIndex($_POST['target_column'] ?? '');
if ($src === null || $dst === null) {
throw new Exception('Indica colonna sorgente e destinazione (es. D e J).');
}
$params = ['source_column' => $src, 'target_column' => $dst];
} elseif ($operation === 'clear' || $operation === 'trim' || $operation === 'uppercase' || $operation === 'lowercase') {
$cols = parseColumnList($_POST['columns'] ?? '');
if (empty($cols)) {
throw new Exception('Indica almeno una colonna (es. D, F).');
}
$params = ['columns' => $cols];
if ($operation === 'trim') {
$chars = (string)($_POST['chars'] ?? '');
if ($chars !== '') {
$params['chars'] = $chars;
}
}
} elseif ($operation === 'replace') {
$cols = parseColumnList($_POST['columns'] ?? '');
if (empty($cols)) {
throw new Exception('Indica almeno una colonna (es. D, F).');
}
$params = [
'columns' => $cols,
'search' => (string)($_POST['search'] ?? ''),
'replace' => (string)($_POST['replace'] ?? ''),
'regex' => isset($_POST['regex']) ? true : false,
];
}
$paramsJson = json_encode($params, JSON_UNESCAPED_UNICODE);
if ($action === 'create') {
// step_order = max + 1
$stmt = $pdo->prepare("SELECT COALESCE(MAX(step_order), 0) + 1 AS next_order FROM routine_step WHERE idroutine = :id");
$stmt->execute([':id' => $idroutine]);
$nextOrder = (int)$stmt->fetchColumn();
$stmt = $pdo->prepare("
INSERT INTO routine_step (idroutine, step_order, operation, params, active)
VALUES (:id, :ord, :op, :params, :active)
");
$stmt->execute([
':id' => $idroutine,
':ord' => $nextOrder,
':op' => $operation,
':params' => $paramsJson,
':active' => $active,
]);
redirectToSteps($idroutine, 'success', 'Step aggiunto correttamente.');
} else {
$idstep = (int)($_POST['idstep'] ?? 0);
if ($idstep <= 0) {
throw new Exception('ID step non valido.');
}
$stmt = $pdo->prepare("
UPDATE routine_step
SET operation = :op, params = :params, active = :active
WHERE idstep = :idstep AND idroutine = :id
");
$stmt->execute([
':op' => $operation,
':params' => $paramsJson,
':active' => $active,
':idstep' => $idstep,
':id' => $idroutine,
]);
redirectToSteps($idroutine, 'success', 'Step aggiornato correttamente.');
}
}
if ($action === 'delete') {
$idstep = (int)($_POST['idstep'] ?? 0);
if ($idstep <= 0) {
throw new Exception('ID step non valido.');
}
$stmt = $pdo->prepare("DELETE FROM routine_step WHERE idstep = :idstep AND idroutine = :id");
$stmt->execute([':idstep' => $idstep, ':id' => $idroutine]);
redirectToSteps($idroutine, 'success', 'Step eliminato.');
}
if ($action === 'move') {
$idstep = (int)($_POST['idstep'] ?? 0);
$dir = cleanInput($_POST['direction'] ?? '');
if ($idstep <= 0 || !in_array($dir, ['up', 'down'], true)) {
throw new Exception('Parametri di spostamento non validi.');
}
// Carica step correnti ordinati.
$stmt = $pdo->prepare("SELECT idstep, step_order FROM routine_step WHERE idroutine = :id ORDER BY step_order ASC, idstep ASC");
$stmt->execute([':id' => $idroutine]);
$all = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Trova posizione corrente.
$pos = null;
foreach ($all as $i => $s) {
if ((int)$s['idstep'] === $idstep) {
$pos = $i;
break;
}
}
if ($pos !== null) {
$swapWith = $dir === 'up' ? $pos - 1 : $pos + 1;
if ($swapWith >= 0 && $swapWith < count($all)) {
$a = $all[$pos];
$b = $all[$swapWith];
// Scambia gli step_order dei due record.
$upd = $pdo->prepare("UPDATE routine_step SET step_order = :ord WHERE idstep = :idstep AND idroutine = :id");
$upd->execute([':ord' => (int)$b['step_order'], ':idstep' => (int)$a['idstep'], ':id' => $idroutine]);
$upd->execute([':ord' => (int)$a['step_order'], ':idstep' => (int)$b['idstep'], ':id' => $idroutine]);
}
}
redirectToSteps($idroutine, 'success', 'Ordine aggiornato.');
}
throw new Exception('Azione non valida.');
} catch (Exception $e) {
redirectToSteps($idroutine, 'error', $e->getMessage());
}
}
/*
* Caricamento step della routine.
*/
$stmt = $pdo->prepare("SELECT idstep, step_order, operation, params, active FROM routine_step WHERE idroutine = :id ORDER BY step_order ASC, idstep ASC");
$stmt->execute([':id' => $idroutine]);
$steps = $stmt->fetchAll(PDO::FETCH_ASSOC);
/*
* Costruisce una descrizione leggibile dei params per la tabella.
*/
function describeStep($operation, array $p)
{
$colsToLetters = function ($arr) {
return implode(', ', array_map('indexToCol', $arr));
};
switch ($operation) {
case 'merge':
return 'Unisce ' . $colsToLetters($p['source_columns'] ?? []) .
' → ' . indexToCol($p['target_column'] ?? 0) .
' (sep: "' . ($p['separator'] ?? ' ') . '")';
case 'copy':
return 'Copia ' . indexToCol($p['source_column'] ?? 0) . ' → ' . indexToCol($p['target_column'] ?? 0);
case 'clear':
return 'Svuota ' . $colsToLetters($p['columns'] ?? []);
case 'trim':
return 'Trim ' . $colsToLetters($p['columns'] ?? []) . (isset($p['chars']) ? ' (chars: "' . $p['chars'] . '")' : '');
case 'uppercase':
return 'Maiuscolo ' . $colsToLetters($p['columns'] ?? []);
case 'lowercase':
return 'Minuscolo ' . $colsToLetters($p['columns'] ?? []);
case 'replace':
return 'Sostituisci in ' . $colsToLetters($p['columns'] ?? []) .
': "' . ($p['search'] ?? '') . '" → "' . ($p['replace'] ?? '') . '"' .
(!empty($p['regex']) ? ' (regex)' : '');
default:
return $operation;
}
}
/*
* Prepara i dati step per il JS (params già in lettere per il form di modifica).
*/
$stepsForJs = [];
foreach ($steps as $s) {
$p = json_decode($s['params'] ?? '[]', true);
if (!is_array($p)) {
$p = [];
}
// Converte indici -> lettere per il form.
$letters = function ($arr) {
return implode(', ', array_map('indexToCol', $arr));
};
$formData = ['operation' => $s['operation'], 'active' => (int)$s['active']];
if ($s['operation'] === 'merge') {
$formData['source_columns'] = $letters($p['source_columns'] ?? []);
$formData['target_column'] = indexToCol($p['target_column'] ?? 0);
$formData['separator'] = $p['separator'] ?? ' ';
$formData['skip_empty'] = !empty($p['skip_empty']);
} elseif ($s['operation'] === 'copy') {
$formData['source_column'] = indexToCol($p['source_column'] ?? 0);
$formData['target_column'] = indexToCol($p['target_column'] ?? 0);
} elseif (in_array($s['operation'], ['clear', 'trim', 'uppercase', 'lowercase'], true)) {
$formData['columns'] = $letters($p['columns'] ?? []);
if ($s['operation'] === 'trim') {
$formData['chars'] = $p['chars'] ?? '';
}
} elseif ($s['operation'] === 'replace') {
$formData['columns'] = $letters($p['columns'] ?? []);
$formData['search'] = $p['search'] ?? '';
$formData['replace'] = $p['replace'] ?? '';
$formData['regex'] = !empty($p['regex']);
}
$stepsForJs[(int)$s['idstep']] = $formData;
}
$flash = $_SESSION['routine_steps_flash'] ?? null;
unset($_SESSION['routine_steps_flash']);
?>
<!doctype html>
<html lang="it">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="assets/images/favicon-32x32.png" type="image/png" />
<?php include('cssinclude.php'); ?>
<title>Step Routine - <?= htmlspecialchars($titlewebsite, ENT_QUOTES, 'UTF-8'); ?></title>
<style>
.small-muted {
font-size: 12px;
color: #6c757d;
}
.table-actions {
white-space: nowrap;
}
.op-badge {
font-family: Consolas, Monaco, monospace;
font-size: 12px;
background: #eef2ff;
color: #4338ca;
border: 1px solid #e0e7ff;
border-radius: 6px;
padding: 2px 8px;
text-transform: uppercase;
}
.step-inactive {
opacity: 0.55;
}
.col-hint {
background: #f0fdf4;
border: 1px solid #bbf7d0;
color: #166534;
border-radius: 8px;
padding: 8px 12px;
font-size: 13px;
}
.order-btns .btn {
padding: 2px 8px;
}
</style>
</head>
<body>
<div class="wrapper">
<?php include('include/navbar.php'); ?>
<?php include('include/topbar.php'); ?>
<div class="page-wrapper">
<div class="page-content">
<?php include('top_stat_widget.php'); ?>
<div class="card radius-10">
<div class="card-header">
<div class="d-flex align-items-center justify-content-between">
<div>
<h6 class="mb-0">Step routine: <?= htmlspecialchars($routine['name'], ENT_QUOTES, 'UTF-8'); ?></h6>
<small class="text-muted">
Configura le operazioni applicate all'XLS. Vengono eseguite dall'alto verso il basso.
</small>
</div>
<div>
<a href="routine_admin.php" class="btn btn-light">
<i class="bx bx-arrow-back"></i> Torna alle routine
</a>
<button type="button" class="btn btn-primary" id="btnAddStep">
<i class="bx bx-plus"></i> Aggiungi step
</button>
</div>
</div>
</div>
<div class="card-body">
<div class="col-hint mb-3">
Le colonne si indicano con le <strong>lettere dell'Excel</strong> (A, B, C, …). Per più colonne separale con la virgola: <strong>D, F, H</strong>.
</div>
<div class="table-responsive">
<table class="table table-bordered align-middle">
<thead>
<tr>
<th style="width: 70px;">Ordine</th>
<th style="width: 120px;">Operazione</th>
<th>Dettaglio</th>
<th style="width: 90px;">Stato</th>
<th style="width: 240px;">Azioni</th>
</tr>
</thead>
<tbody>
<?php if (empty($steps)): ?>
<tr>
<td colspan="5" class="text-center small-muted py-4">
Nessuno step configurato. Usa "Aggiungi step" per iniziare.
</td>
</tr>
<?php else: ?>
<?php foreach ($steps as $i => $s): ?>
<?php
$p = json_decode($s['params'] ?? '[]', true);
if (!is_array($p)) {
$p = [];
}
$isFirst = ($i === 0);
$isLast = ($i === count($steps) - 1);
$rowClass = ((int)$s['active'] === 1) ? '' : 'step-inactive';
?>
<tr class="<?= $rowClass; ?>">
<td class="text-center">
<div class="order-btns d-inline-flex flex-column gap-1">
<button type="button" class="btn btn-sm btn-outline-secondary btnMove"
data-idstep="<?= (int)$s['idstep']; ?>" data-direction="up"
<?= $isFirst ? 'disabled' : ''; ?>>
<i class="bx bx-chevron-up"></i>
</button>
<button type="button" class="btn btn-sm btn-outline-secondary btnMove"
data-idstep="<?= (int)$s['idstep']; ?>" data-direction="down"
<?= $isLast ? 'disabled' : ''; ?>>
<i class="bx bx-chevron-down"></i>
</button>
</div>
</td>
<td><span class="op-badge"><?= htmlspecialchars($s['operation'], ENT_QUOTES, 'UTF-8'); ?></span></td>
<td><?= htmlspecialchars(describeStep($s['operation'], $p), ENT_QUOTES, 'UTF-8'); ?></td>
<td>
<?php if ((int)$s['active'] === 1): ?>
<span class="badge bg-success">Attivo</span>
<?php else: ?>
<span class="badge bg-secondary">Disattivo</span>
<?php endif; ?>
</td>
<td class="table-actions">
<button type="button" class="btn btn-sm btn-outline-primary btnEditStep"
data-idstep="<?= (int)$s['idstep']; ?>">
Modifica
</button>
<button type="button" class="btn btn-sm btn-outline-danger btnDeleteStep"
data-idstep="<?= (int)$s['idstep']; ?>">
Elimina
</button>
</td>
</tr>
<?php endforeach; ?>
<?php endif; ?>
</tbody>
</table>
</div>
<hr class="my-4">
<div class="d-flex align-items-center justify-content-between mb-2">
<div>
<h6 class="mb-0">Prova la routine</h6>
<small class="text-muted">Carica un XLS di esempio: viene mostrata la prima riga dati dopo l'intestazione, elaborata con gli step qui sopra. Il file non viene salvato.</small>
</div>
</div>
<div class="row g-2 align-items-end">
<div class="col-md-8">
<label for="previewFile" class="form-label">File XLS / XLSX di prova</label>
<input type="file" class="form-control" id="previewFile" accept=".xls,.xlsx">
</div>
<div class="col-md-4">
<button type="button" class="btn btn-outline-primary w-100" id="btnRunPreview">
<i class="bx bx-play-circle"></i> Esegui anteprima
</button>
</div>
</div>
<div id="previewStatus" class="small-muted mt-2"></div>
<div class="table-responsive mt-3" id="previewResultWrapper" style="display:none;">
<table class="table table-bordered table-sm align-middle" id="previewTable">
<thead>
<tr>
<th style="width: 90px;">Colonna</th>
<th style="width: 40%;">Intestazione</th>
<th>Valore dopo la routine</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<div class="overlay toggle-icon"></div>
<a href="javaScript:;" class="back-to-top"><i class='bx bxs-up-arrow-alt'></i></a>
<?php include('include/footer.php'); ?>
</div>
<!-- Modal Step -->
<div class="modal fade" id="stepModal" tabindex="-1" aria-hidden="true">
<div class="modal-dialog modal-lg modal-dialog-centered">
<form method="POST" class="modal-content" id="stepForm">
<input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrfToken, ENT_QUOTES, 'UTF-8'); ?>">
<input type="hidden" name="idroutine" value="<?= (int)$idroutine; ?>">
<input type="hidden" name="action" id="stepFormAction" value="create">
<input type="hidden" name="idstep" id="idstep" value="">
<div class="modal-header">
<h5 class="modal-title" id="stepModalTitle">Aggiungi step</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Chiudi"></button>
</div>
<div class="modal-body">
<div class="row g-3">
<div class="col-md-8">
<label for="operation" class="form-label">Operazione *</label>
<select class="form-select" id="operation" name="operation" required>
<option value="merge">merge — unisci più colonne in una</option>
<option value="copy">copy — copia una colonna in un'altra</option>
<option value="clear">clear — svuota colonne</option>
<option value="trim">trim — rimuovi spazi</option>
<option value="replace">replace — sostituisci testo</option>
<option value="uppercase">uppercase — MAIUSCOLO</option>
<option value="lowercase">lowercase — minuscolo</option>
</select>
</div>
<div class="col-md-4">
<label for="active" class="form-label">Stato *</label>
<select class="form-select" id="active" name="active" required>
<option value="1">Attivo</option>
<option value="0">Disattivo</option>
</select>
</div>
<!-- Campi MERGE -->
<div class="col-md-8 op-field op-merge">
<label class="form-label">Colonne sorgente *</label>
<input type="text" class="form-control" name="source_columns" id="merge_source" placeholder="es. D, F, H">
<div class="small-muted mt-1">Lettere separate da virgola.</div>
</div>
<div class="col-md-4 op-field op-merge">
<label class="form-label">Colonna destinazione *</label>
<input type="text" class="form-control" name="target_column" id="merge_target" placeholder="es. J">
</div>
<div class="col-md-8 op-field op-merge">
<label class="form-label">Separatore</label>
<input type="text" class="form-control" name="separator" id="merge_sep" value=" " placeholder="spazio">
<div class="small-muted mt-1">Carattere inserito tra i valori uniti. Default: spazio.</div>
</div>
<div class="col-md-4 op-field op-merge d-flex align-items-end">
<div class="form-check">
<input class="form-check-input" type="checkbox" name="skip_empty" id="merge_skip" checked>
<label class="form-check-label" for="merge_skip">Ignora valori vuoti</label>
</div>
</div>
<!-- Campi COPY -->
<div class="col-md-6 op-field op-copy">
<label class="form-label">Colonna sorgente *</label>
<input type="text" class="form-control" name="source_column" id="copy_source" placeholder="es. D">
</div>
<div class="col-md-6 op-field op-copy">
<label class="form-label">Colonna destinazione *</label>
<input type="text" class="form-control" name="target_column_copy" id="copy_target" placeholder="es. J">
</div>
<!-- Campi COLONNE (clear/trim/uppercase/lowercase/replace) -->
<div class="col-md-12 op-field op-columns">
<label class="form-label">Colonne *</label>
<input type="text" class="form-control" name="columns" id="columns_input" placeholder="es. D, F">
<div class="small-muted mt-1">Una o più lettere separate da virgola.</div>
</div>
<!-- Campo TRIM chars -->
<div class="col-md-12 op-field op-trim">
<label class="form-label">Caratteri da rimuovere (opzionale)</label>
<input type="text" class="form-control" name="chars" id="trim_chars" placeholder="lascia vuoto per spazi">
</div>
<!-- Campi REPLACE -->
<div class="col-md-6 op-field op-replace">
<label class="form-label">Testo da cercare</label>
<input type="text" class="form-control" name="search" id="replace_search">
</div>
<div class="col-md-6 op-field op-replace">
<label class="form-label">Testo sostitutivo</label>
<input type="text" class="form-control" name="replace" id="replace_replace">
</div>
<div class="col-md-12 op-field op-replace">
<div class="form-check">
<input class="form-check-input" type="checkbox" name="regex" id="replace_regex">
<label class="form-check-label" for="replace_regex">
Usa espressione regolare (regex) — solo se sai cosa stai facendo
</label>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-light" data-bs-dismiss="modal">Annulla</button>
<button type="submit" class="btn btn-primary" id="saveStepButton">Salva step</button>
</div>
</form>
</div>
</div>
<!-- Form nascosti -->
<form method="POST" id="deleteStepForm" style="display:none;">
<input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrfToken, ENT_QUOTES, 'UTF-8'); ?>">
<input type="hidden" name="idroutine" value="<?= (int)$idroutine; ?>">
<input type="hidden" name="action" value="delete">
<input type="hidden" name="idstep" id="deleteIdStep" value="">
</form>
<form method="POST" id="moveStepForm" style="display:none;">
<input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrfToken, ENT_QUOTES, 'UTF-8'); ?>">
<input type="hidden" name="idroutine" value="<?= (int)$idroutine; ?>">
<input type="hidden" name="action" value="move">
<input type="hidden" name="idstep" id="moveIdStep" value="">
<input type="hidden" name="direction" id="moveDirection" value="">
</form>
<?php include('jsinclude.php'); ?>
<script>
const stepsData = <?= json_encode($stepsForJs, JSON_UNESCAPED_UNICODE); ?>;
document.addEventListener('DOMContentLoaded', function() {
const stepModal = new bootstrap.Modal(document.getElementById('stepModal'));
const stepFormAction = document.getElementById('stepFormAction');
const idstep = document.getElementById('idstep');
const stepModalTitle = document.getElementById('stepModalTitle');
const saveStepButton = document.getElementById('saveStepButton');
const operation = document.getElementById('operation');
const active = document.getElementById('active');
// Mappa quali gruppi di campi mostrare per ogni operazione.
const fieldGroups = {
merge: ['op-merge'],
copy: ['op-copy'],
clear: ['op-columns'],
trim: ['op-columns', 'op-trim'],
replace: ['op-columns', 'op-replace'],
uppercase: ['op-columns'],
lowercase: ['op-columns']
};
function showFieldsForOperation(op) {
// Nasconde tutti i gruppi.
document.querySelectorAll('.op-field').forEach(function(el) {
el.style.display = 'none';
});
// Mostra i gruppi dell'operazione scelta.
(fieldGroups[op] || []).forEach(function(cls) {
document.querySelectorAll('.' + cls).forEach(function(el) {
el.style.display = '';
});
});
}
operation.addEventListener('change', function() {
showFieldsForOperation(operation.value);
});
function resetStepForm() {
document.getElementById('stepForm').reset();
// reset non ripristina i checkbox "checked" di default in modo affidabile: li forziamo
document.getElementById('merge_skip').checked = true;
document.getElementById('replace_regex').checked = false;
document.getElementById('merge_sep').value = ' ';
}
function openForCreate() {
stepFormAction.value = 'create';
idstep.value = '';
stepModalTitle.textContent = 'Aggiungi step';
saveStepButton.textContent = 'Aggiungi step';
resetStepForm();
operation.value = 'merge';
active.value = '1';
showFieldsForOperation('merge');
stepModal.show();
}
function openForEdit(id) {
const data = stepsData[id];
if (!data) {
return;
}
stepFormAction.value = 'update';
idstep.value = id;
stepModalTitle.textContent = 'Modifica step';
saveStepButton.textContent = 'Aggiorna step';
resetStepForm();
operation.value = data.operation;
active.value = String(data.active);
// Popola i campi in base all'operazione.
if (data.operation === 'merge') {
document.getElementById('merge_source').value = data.source_columns || '';
document.getElementById('merge_target').value = data.target_column || '';
document.getElementById('merge_sep').value = (data.separator !== undefined ? data.separator : ' ');
document.getElementById('merge_skip').checked = !!data.skip_empty;
} else if (data.operation === 'copy') {
document.getElementById('copy_source').value = data.source_column || '';
document.getElementById('copy_target').value = data.target_column || '';
} else if (['clear', 'trim', 'uppercase', 'lowercase'].includes(data.operation)) {
document.getElementById('columns_input').value = data.columns || '';
if (data.operation === 'trim') {
document.getElementById('trim_chars').value = data.chars || '';
}
} else if (data.operation === 'replace') {
document.getElementById('columns_input').value = data.columns || '';
document.getElementById('replace_search').value = data.search || '';
document.getElementById('replace_replace').value = data.replace || '';
document.getElementById('replace_regex').checked = !!data.regex;
}
showFieldsForOperation(data.operation);
stepModal.show();
}
/*
* NOTA sul campo destinazione di copy:
* l'input HTML si chiama target_column_copy per non collidere con merge,
* ma il backend si aspetta target_column. Rinominiamo al submit.
*/
document.getElementById('stepForm').addEventListener('submit', function(e) {
if (operation.value === 'copy') {
const copyTarget = document.getElementById('copy_target');
// Crea/aggiorna un campo hidden target_column col valore di copy.
let hidden = document.getElementById('copy_target_hidden');
if (!hidden) {
hidden = document.createElement('input');
hidden.type = 'hidden';
hidden.name = 'target_column';
hidden.id = 'copy_target_hidden';
this.appendChild(hidden);
}
hidden.value = copyTarget.value;
}
});
document.getElementById('btnAddStep').addEventListener('click', openForCreate);
document.querySelectorAll('.btnEditStep').forEach(function(btn) {
btn.addEventListener('click', function() {
openForEdit(btn.dataset.idstep);
});
});
document.querySelectorAll('.btnDeleteStep').forEach(function(btn) {
btn.addEventListener('click', function() {
Swal.fire({
title: 'Eliminare lo step?',
text: 'Operazione irreversibile.',
icon: 'warning',
showCancelButton: true,
confirmButtonText: 'Sì, elimina',
cancelButtonText: 'Annulla',
confirmButtonColor: '#d33'
}).then(function(result) {
if (result.isConfirmed) {
document.getElementById('deleteIdStep').value = btn.dataset.idstep;
document.getElementById('deleteStepForm').submit();
}
});
});
});
document.querySelectorAll('.btnMove').forEach(function(btn) {
btn.addEventListener('click', function() {
document.getElementById('moveIdStep').value = btn.dataset.idstep;
document.getElementById('moveDirection').value = btn.dataset.direction;
document.getElementById('moveStepForm').submit();
});
});
// --- Anteprima routine su XLS caricato (nessun salvataggio) ---
const previewFile = document.getElementById('previewFile');
const btnRunPreview = document.getElementById('btnRunPreview');
const previewStatus = document.getElementById('previewStatus');
const previewResultWrapper = document.getElementById('previewResultWrapper');
const previewTableBody = document.querySelector('#previewTable tbody');
const currentIdRoutine = "<?= (int)$idroutine; ?>";
btnRunPreview.addEventListener('click', function() {
if (!previewFile.files || previewFile.files.length === 0) {
Swal.fire({
icon: 'info',
title: 'Nessun file',
text: 'Seleziona un file XLS di prova.'
});
return;
}
const formData = new FormData();
formData.append('idroutine', currentIdRoutine);
formData.append('file', previewFile.files[0]);
previewStatus.textContent = 'Elaborazione in corso...';
previewResultWrapper.style.display = 'none';
previewTableBody.innerHTML = '';
btnRunPreview.disabled = true;
fetch('routine_preview.php', {
method: 'POST',
body: formData,
cache: 'no-store'
})
.then(function(res) {
return res.json();
})
.then(function(data) {
btnRunPreview.disabled = false;
if (data.error) {
previewStatus.textContent = '';
Swal.fire({
icon: 'warning',
title: 'Anteprima non riuscita',
text: data.error
});
return;
}
previewStatus.textContent = 'Riga elaborata: riga Excel ' + data.excelrow + '.';
const letters = data.letters || [];
const headers = data.headers || [];
const row = data.row || [];
for (let i = 0; i < row.length; i++) {
const tr = document.createElement('tr');
const tdCol = document.createElement('td');
tdCol.innerHTML = '<strong>' + (letters[i] || '') + '</strong>';
const tdHead = document.createElement('td');
tdHead.className = 'small-muted';
tdHead.textContent = headers[i] || '';
const tdVal = document.createElement('td');
tdVal.textContent = row[i] || '';
tr.appendChild(tdCol);
tr.appendChild(tdHead);
tr.appendChild(tdVal);
previewTableBody.appendChild(tr);
}
previewResultWrapper.style.display = '';
})
.catch(function(err) {
btnRunPreview.disabled = false;
previewStatus.textContent = '';
Swal.fire({
icon: 'error',
title: 'Errore',
text: 'Impossibile eseguire l\'anteprima.'
});
console.error(err);
});
});
<?php if ($flash): ?>
Swal.fire({
icon: '<?= htmlspecialchars($flash['type'], ENT_QUOTES, 'UTF-8'); ?>',
title: '<?= $flash['type'] === 'success' ? 'Fatto' : ($flash['type'] === 'warning' ? 'Attenzione' : 'Errore'); ?>',
text: '<?= htmlspecialchars($flash['message'], ENT_QUOTES, 'UTF-8'); ?>'
});
<?php endif; ?>
});
</script>
</body>
</html>
+296
View File
@@ -0,0 +1,296 @@
<?php
/**
* Routine motore generico (_engine.php)
* -------------------------------------
* File UNICO condiviso da tutte le routine con engine = 1.
*
* Espone la stessa firma delle routine legacy:
*
* applyRoutine(&$excelData, $routineData)
*
* così apply_routine.php lo include allo stesso modo. La differenza è che qui
* NON c'è logica hardcoded: gli step vengono letti dalla tabella routine_step
* (in base a routineData['idroutine']) ed eseguiti in ordine.
*
* Ogni step ha una `operation` (verbo del vocabolario) e `params` JSON.
* Le colonne nei params possono essere indici zero-based (3) o lettere Excel ("D").
*/
if (!function_exists('applyRoutine')) {
/**
* Converte un riferimento colonna in indice zero-based.
* Accetta int/indici numerici (3) o lettere Excel ("D", "AA", ...).
*/
function routineEngineColToIndex($ref): int
{
if (is_int($ref)) {
return $ref;
}
$ref = trim((string)$ref);
if ($ref === '') {
return 0;
}
// Numerico puro -> indice diretto
if (ctype_digit($ref)) {
return (int)$ref;
}
// Lettere Excel -> indice zero-based (A=0, B=1, ..., Z=25, AA=26, ...)
$ref = strtoupper($ref);
$index = 0;
$len = strlen($ref);
for ($i = 0; $i < $len; $i++) {
$c = $ref[$i];
if ($c < 'A' || $c > 'Z') {
continue;
}
$index = $index * 26 + (ord($c) - ord('A') + 1);
}
return $index - 1;
}
/** Normalizza una lista di riferimenti colonna in indici zero-based. */
function routineEngineColsToIndexes(array $refs): array
{
return array_map('routineEngineColToIndex', $refs);
}
/**
* Carica gli step attivi di una routine dal DB, ordinati per step_order.
* Ritorna array di ['operation' => string, 'params' => array].
*/
function routineEngineLoadSteps(int $idroutine): array
{
// Riusa la connessione PDO del progetto.
// db-functions.php sta in .../class/ rispetto alla cartella routines/.
// Aggiusta il require se nel tuo albero il path differisce.
$dbFile = dirname(__DIR__) . '/class/db-functions.php';
if (!class_exists('DBHandlerSelect') && file_exists($dbFile)) {
require_once $dbFile;
}
if (!class_exists('DBHandlerSelect')) {
throw new Exception("Motore routine: classe DBHandlerSelect non trovata (path db-functions.php da verificare).");
}
$pdo = DBHandlerSelect::getInstance()->getConnection();
$stmt = $pdo->prepare(
"SELECT operation, params
FROM routine_step
WHERE idroutine = :id AND active = 1
ORDER BY step_order ASC, idstep ASC"
);
$stmt->execute([':id' => $idroutine]);
$rows = $stmt->fetchAll();
$steps = [];
foreach ($rows as $r) {
$params = [];
if (!empty($r['params'])) {
$decoded = json_decode($r['params'], true);
if (is_array($decoded)) {
$params = $decoded;
} else {
error_log("Motore routine: params JSON non valido per operazione {$r['operation']} (routine {$idroutine}).");
}
}
$steps[] = ['operation' => strtolower(trim($r['operation'])), 'params' => $params];
}
return $steps;
}
/* ------------------------------------------------------------------ *
* HANDLERS – ogni operazione modifica $excelData in place.
* Aggiungere una capacità nuova = aggiungere un handler qui, una volta.
* ------------------------------------------------------------------ */
/**
* merge: unisce N colonne sorgente in una destinazione.
* params: source_columns [], target_column, separator=" ", skip_empty=true
*/
function routineOpMerge(array &$excelData, array $params): void
{
$sources = routineEngineColsToIndexes($params['source_columns'] ?? []);
$target = routineEngineColToIndex($params['target_column'] ?? 0);
$sep = array_key_exists('separator', $params) ? (string)$params['separator'] : ' ';
$skip = $params['skip_empty'] ?? true;
foreach ($excelData as $rowIndex => &$row) {
if (!isset($row['data']) || !is_array($row['data'])) {
error_log("merge: struttura riga non valida all'indice {$rowIndex}.");
continue;
}
$parts = [];
foreach ($sources as $col) {
$val = trim((string)($row['data'][$col] ?? ''));
if ($skip && $val === '') {
continue;
}
$parts[] = $val;
}
$row['data'][$target] = implode($sep, $parts);
}
unset($row);
}
/**
* copy: copia una colonna sorgente in una destinazione.
* params: source_column, target_column
*/
function routineOpCopy(array &$excelData, array $params): void
{
$src = routineEngineColToIndex($params['source_column'] ?? 0);
$dst = routineEngineColToIndex($params['target_column'] ?? 0);
foreach ($excelData as &$row) {
if (!isset($row['data']) || !is_array($row['data'])) {
continue;
}
$row['data'][$dst] = $row['data'][$src] ?? '';
}
unset($row);
}
/**
* clear: svuota una o più colonne.
* params: columns [] (oppure column singola)
*/
function routineOpClear(array &$excelData, array $params): void
{
$cols = $params['columns'] ?? (isset($params['column']) ? [$params['column']] : []);
$cols = routineEngineColsToIndexes($cols);
foreach ($excelData as &$row) {
if (!isset($row['data']) || !is_array($row['data'])) {
continue;
}
foreach ($cols as $c) {
$row['data'][$c] = '';
}
}
unset($row);
}
/**
* trim: rimuove spazi (o caratteri indicati) da una o più colonne.
* params: columns [] (o column), chars (opzionale)
*/
function routineOpTrim(array &$excelData, array $params): void
{
$cols = $params['columns'] ?? (isset($params['column']) ? [$params['column']] : []);
$cols = routineEngineColsToIndexes($cols);
$chars = $params['chars'] ?? null;
foreach ($excelData as &$row) {
if (!isset($row['data']) || !is_array($row['data'])) {
continue;
}
foreach ($cols as $c) {
$v = (string)($row['data'][$c] ?? '');
$row['data'][$c] = $chars === null ? trim($v) : trim($v, $chars);
}
}
unset($row);
}
/**
* replace: sostituzione testo in una o più colonne.
* params: columns [] (o column), search, replace="", regex=false
*/
function routineOpReplace(array &$excelData, array $params): void
{
$cols = $params['columns'] ?? (isset($params['column']) ? [$params['column']] : []);
$cols = routineEngineColsToIndexes($cols);
$search = $params['search'] ?? '';
$replace = $params['replace'] ?? '';
$regex = $params['regex'] ?? false;
foreach ($excelData as &$row) {
if (!isset($row['data']) || !is_array($row['data'])) {
continue;
}
foreach ($cols as $c) {
$v = (string)($row['data'][$c] ?? '');
if ($regex) {
$out = @preg_replace($search, $replace, $v);
$row['data'][$c] = $out === null ? $v : $out;
} else {
$row['data'][$c] = str_replace($search, $replace, $v);
}
}
}
unset($row);
}
/** uppercase: maiuscolo su una o più colonne. params: columns [] (o column) */
function routineOpUppercase(array &$excelData, array $params): void
{
$cols = $params['columns'] ?? (isset($params['column']) ? [$params['column']] : []);
$cols = routineEngineColsToIndexes($cols);
foreach ($excelData as &$row) {
if (!isset($row['data']) || !is_array($row['data'])) {
continue;
}
foreach ($cols as $c) {
$row['data'][$c] = mb_strtoupper((string)($row['data'][$c] ?? ''), 'UTF-8');
}
}
unset($row);
}
/** lowercase: minuscolo su una o più colonne. params: columns [] (o column) */
function routineOpLowercase(array &$excelData, array $params): void
{
$cols = $params['columns'] ?? (isset($params['column']) ? [$params['column']] : []);
$cols = routineEngineColsToIndexes($cols);
foreach ($excelData as &$row) {
if (!isset($row['data']) || !is_array($row['data'])) {
continue;
}
foreach ($cols as $c) {
$row['data'][$c] = mb_strtolower((string)($row['data'][$c] ?? ''), 'UTF-8');
}
}
unset($row);
}
/**
* Entry point richiamato da apply_routine.php.
* Stessa firma delle routine legacy.
*/
function applyRoutine(&$excelData, $routineData = [])
{
$idroutine = isset($routineData['idroutine']) ? (int)$routineData['idroutine'] : 0;
if ($idroutine <= 0) {
throw new Exception("Motore routine: idroutine mancante in routineData.");
}
$steps = routineEngineLoadSteps($idroutine);
if (empty($steps)) {
error_log("Motore routine: nessuno step attivo per routine {$idroutine}.");
return;
}
// Dispatch table verbo -> handler
$handlers = [
'merge' => 'routineOpMerge',
'copy' => 'routineOpCopy',
'clear' => 'routineOpClear',
'trim' => 'routineOpTrim',
'replace' => 'routineOpReplace',
'uppercase' => 'routineOpUppercase',
'lowercase' => 'routineOpLowercase',
];
foreach ($steps as $i => $step) {
$op = $step['operation'];
if (!isset($handlers[$op])) {
error_log("Motore routine: operazione sconosciuta '{$op}' (routine {$idroutine}, step " . ($i + 1) . ") — saltata.");
continue;
}
$handlers[$op]($excelData, $step['params']);
error_log("Motore routine: applicata operazione '{$op}' (routine {$idroutine}, step " . ($i + 1) . ").");
}
error_log("Motore routine {$idroutine} completato (" . count($steps) . " step).");
}
}
+77 -41
View File
@@ -1,8 +1,8 @@
/**
* saveAll.js — Save All functionality using gridData
*/
(function() {
'use strict';
(function () {
"use strict";
let saveAllRunning = false;
@@ -11,7 +11,7 @@
}
// ── Save single row ──────────────────────────────────────────────────
$(document).on('click', '.save-btn', async function() {
$(document).on("click", ".save-btn", async function () {
const btn = this;
const rowIndex = parseInt(btn.dataset.row);
const row = window.gridData?.[rowIndex];
@@ -23,29 +23,44 @@
try {
const formData = window.buildSavePayload(rowIndex);
const resp = await fetch('save_edited_row.php', { method: 'POST', body: formData });
const resp = await fetch("save_edited_row.php", {
method: "POST",
body: formData,
});
const result = await resp.json();
if (result.success) {
row._dirty = false;
if (window.gridRenderer?.clearDirty) window.gridRenderer.clearDirty(rowIndex);
if (window.gridRenderer?.clearDirty)
window.gridRenderer.clearDirty(rowIndex);
// Flash success on row without re-rendering (preserves Select2 state)
const gridRow = document.querySelector(`.grid-row[data-id="${row.iddatadb}"]`);
const gridRow = document.querySelector(
`.grid-row[data-id="${row.iddatadb}"]`,
);
if (gridRow) {
gridRow.classList.remove('row-dirty');
gridRow.querySelectorAll('.grid-cell').forEach(cell => {
cell.classList.remove('cell-changed');
cell.classList.add('flash-success');
gridRow.classList.remove("row-dirty");
gridRow.querySelectorAll(".grid-cell").forEach((cell) => {
cell.classList.remove("cell-changed");
cell.classList.add("flash-success");
});
setTimeout(() => gridRow.querySelectorAll('.flash-success').forEach(c => c.classList.remove('flash-success')), 500);
setTimeout(
() =>
gridRow
.querySelectorAll(".flash-success")
.forEach((c) =>
c.classList.remove("flash-success"),
),
500,
);
}
const toastEl = document.getElementById('saveSuccessToast');
if (toastEl) bootstrap.Toast.getOrCreateInstance(toastEl).show();
const toastEl = document.getElementById("saveSuccessToast");
if (toastEl)
bootstrap.Toast.getOrCreateInstance(toastEl).show();
} else {
alert('Errore: ' + result.message);
alert("Errore: " + result.message);
}
} catch (e) {
alert('Errore: ' + e.message);
alert("Errore: " + e.message);
} finally {
btn.innerHTML = origHtml;
btn.disabled = false;
@@ -53,49 +68,68 @@
});
// ── Save All ─────────────────────────────────────────────────────────
$(document).on('click', '.save-all-btn', function(e) {
$(document).on("click", ".save-all-btn", function (e) {
e.preventDefault();
if (isBusy()) return;
const modalEl = document.getElementById('saveAllConfirmModal');
const modalEl = document.getElementById("saveAllConfirmModal");
if (!modalEl) return;
new bootstrap.Modal(modalEl, { keyboard: false }).show();
});
$(document).on('click', '#saveAllConfirmBtn', async function() {
const confirmModal = bootstrap.Modal.getInstance(document.getElementById('saveAllConfirmModal'));
$(document).on("click", "#saveAllConfirmBtn", async function () {
const confirmModal = bootstrap.Modal.getInstance(
document.getElementById("saveAllConfirmModal"),
);
if (confirmModal) confirmModal.hide();
saveAllRunning = true;
const bar = document.getElementById('batchExportBar');
const statusEl = document.getElementById('batchExportStatus');
const cancelBtn = document.getElementById('exportBatchCancelBtn');
if (bar) bar.style.display = '';
if (cancelBtn) cancelBtn.style.display = 'none';
if (statusEl) statusEl.textContent = 'Saving...';
const bar = document.getElementById("batchExportBar");
const statusEl = document.getElementById("batchExportStatus");
const cancelBtn = document.getElementById("exportBatchCancelBtn");
if (bar) bar.style.display = "";
if (cancelBtn) cancelBtn.style.display = "none";
if (statusEl) statusEl.textContent = "Saving...";
const data = window.gridData || [];
const dirtyRows = data.map((r, i) => r._dirty ? i : -1).filter(i => i >= 0);
const target =
typeof window.getTargetGridIds === "function"
? window.getTargetGridIds()
: null;
const dirtyRows = data
.map((r, i) => (r._dirty ? i : -1))
.filter((i) => i >= 0)
.filter(
(i) => !target || target.has(parseInt(data[i].iddatadb, 10)),
);
if (dirtyRows.length === 0) {
saveAllRunning = false;
if (bar) bar.style.display = 'none';
const msgEl = document.getElementById('saveAllResultMessage');
if (msgEl) msgEl.textContent = 'No changes to save.';
new bootstrap.Modal(document.getElementById('saveAllResultModal')).show();
if (bar) bar.style.display = "none";
const msgEl = document.getElementById("saveAllResultMessage");
if (msgEl) msgEl.textContent = "No changes to save.";
new bootstrap.Modal(
document.getElementById("saveAllResultModal"),
).show();
return;
}
let success = 0, fail = 0;
let success = 0,
fail = 0;
for (const idx of dirtyRows) {
if (statusEl) statusEl.textContent = `Saving ${success + fail + 1} / ${dirtyRows.length}...`;
if (statusEl)
statusEl.textContent = `Saving ${success + fail + 1} / ${dirtyRows.length}...`;
try {
const formData = window.buildSavePayload(idx);
const resp = await fetch('save_edited_row.php', { method: 'POST', body: formData });
const resp = await fetch("save_edited_row.php", {
method: "POST",
body: formData,
});
const result = await resp.json();
if (result.success) {
data[idx]._dirty = false;
if (window.gridRenderer?.clearDirty) window.gridRenderer.clearDirty(idx);
if (window.gridRenderer?.clearDirty)
window.gridRenderer.clearDirty(idx);
success++;
} else {
fail++;
@@ -106,22 +140,24 @@
}
saveAllRunning = false;
if (bar) bar.style.display = 'none';
if (bar) bar.style.display = "none";
const gr = window.gridRenderer;
if (gr) gr.renderVisibleRows();
const msg = `Saved: ${success}` + (fail > 0 ? `, Errors: ${fail}` : '');
const msgEl = document.getElementById('saveAllResultMessage');
const msg = `Saved: ${success}` + (fail > 0 ? `, Errors: ${fail}` : "");
const msgEl = document.getElementById("saveAllResultMessage");
if (msgEl) msgEl.textContent = msg;
new bootstrap.Modal(document.getElementById('saveAllResultModal')).show();
new bootstrap.Modal(
document.getElementById("saveAllResultModal"),
).show();
});
// ── beforeunload ─────────────────────────────────────────────────────
window.addEventListener('beforeunload', function(e) {
if (window.gridData && window.gridData.some(r => r._dirty)) {
window.addEventListener("beforeunload", function (e) {
if (window.gridData && window.gridData.some((r) => r._dirty)) {
e.preventDefault();
e.returnValue = '';
e.returnValue = "";
}
});
+9 -12
View File
@@ -22,6 +22,8 @@ try {
$analysisLevel = isset($_POST['analysis_level']) && $_POST['analysis_level'] !== '' ? (int)$_POST['analysis_level'] : null;
$isWebSelectable = isset($_POST['is_web_selectable']) ? (int)$_POST['is_web_selectable'] : 0;
$isAccredited = isset($_POST['is_accredited']) ? (int)$_POST['is_accredited'] : 0;
$analysisPriceRaw = str_replace(',', '.', trim((string)($_POST['analysis_price'] ?? '')));
$analysisPrice = is_numeric($analysisPriceRaw) ? round((float)$analysisPriceRaw, 2) : null;
if ($partId <= 0 || $analysisRecordkey === '') {
http_response_code(400);
@@ -42,7 +44,8 @@ try {
analysis_method,
analysis_level,
is_web_selectable,
is_accredited
is_accredited,
analysis_price
) VALUES (
:part_id,
:iddatadb,
@@ -52,17 +55,9 @@ try {
:analysis_method,
:analysis_level,
:is_web_selectable,
:is_accredited
:is_accredited,
:analysis_price
)
ON DUPLICATE KEY UPDATE
analysis_name = VALUES(analysis_name),
analysis_method = VALUES(analysis_method),
analysis_level = VALUES(analysis_level),
is_web_selectable = VALUES(is_web_selectable),
is_accredited = VALUES(is_accredited),
iddatadb = VALUES(iddatadb),
idmatrice = VALUES(idmatrice),
updated_at = CURRENT_TIMESTAMP
");
$stmt->execute([
@@ -75,11 +70,13 @@ try {
':analysis_level' => $analysisLevel,
':is_web_selectable' => $isWebSelectable,
':is_accredited' => $isAccredited,
':analysis_price' => $analysisPrice,
]);
echo json_encode([
'success' => true,
'message' => 'Association saved'
'message' => 'Association saved',
'id' => (int)$pdo->lastInsertId()
]);
} catch (Throwable $e) {
http_response_code(500);
+50 -22
View File
@@ -4,6 +4,7 @@ include('include/headscript.php');
$dbHandler = DBHandlerSelect::getInstance();
$pdo = $dbHandler->getConnection();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$data = json_decode(file_get_contents('php://input'), true);
@@ -15,46 +16,73 @@ if (!$idquotations || empty($parts)) {
exit;
}
$part = $parts[0];
$partId = $part['id'] ?? null;
$partNumber = $part['part_number'] ?? null;
$partDescription = $part['part_description'] ?? '';
$mix = $part['mix'] ?? 'N';
try {
$pdo->beginTransaction();
$results = [];
foreach ($parts as $part) {
$partId = $part['id'] ?? null;
$partNumber = $part['part_number'] ?? null;
$partDescription = $part['part_description'] ?? '';
$mix = $part['mix'] ?? 'N';
$idmatrice = $part['idmatrice'] ?? null;
$note = $part['note'] ?? null;
$dateexpiry = $part['dateexpiry'] ?? null;
if ($partDescription) {
try {
if ($partId) {
// UPDATE se esiste già la parte
// UPDATE se la parte esiste
$stmt = $pdo->prepare("UPDATE identification_parts
SET part_number = :part_number,
part_description = :part_description,
mix = :mix,
idmatrice = :idmatrice,
note = :note,
dateexpiry = :dateexpiry,
updated_at = NOW()
WHERE id = :id");
WHERE id = :id AND idquotations = :idquotations");
$stmt->execute([
':id' => $partId,
':part_number' => $partNumber,
':part_description' => $partDescription,
':mix' => $mix
':mix' => $mix,
':idmatrice' => $idmatrice,
':note' => $note,
':dateexpiry' => $dateexpiry,
':idquotations' => $idquotations,
]);
echo json_encode(['success' => true, 'part_id' => $partId, 'part_number' => $partNumber, 'message' => 'Parte aggiornata con successo']);
} else {
// INSERT se è nuova
$results[] = [
'part_id' => $partId,
'part_number' => $partNumber,
'message' => 'Parte aggiornata con successo'
];
} else if ($partDescription || $note || $dateexpiry) {
// INSERT per nuova parte (solo se ha contenuto)
$stmt = $pdo->prepare("INSERT INTO identification_parts
(idquotations, part_number, part_description, mix, created_at, updated_at)
VALUES (:idquotations, :part_number, :part_description, :mix, NOW(), NOW())");
(idquotations, part_number, part_description, mix, idmatrice, note, dateexpiry, created_at, updated_at)
VALUES (:idquotations, :part_number, :part_description, :mix, :idmatrice, :note, :dateexpiry, NOW(), NOW())");
$stmt->execute([
':idquotations' => $idquotations,
':part_number' => $partNumber,
':part_description' => $partDescription,
':mix' => $mix
':mix' => $mix,
':idmatrice' => $idmatrice,
':note' => $note,
':dateexpiry' => $dateexpiry,
]);
$newId = $pdo->lastInsertId();
echo json_encode(['success' => true, 'part_id' => $newId, 'part_number' => $partNumber, 'message' => 'Parte salvata con successo']);
$newId = (int)$pdo->lastInsertId();
$results[] = [
'part_id' => $newId,
'part_number' => $partNumber,
'message' => 'Parte salvata con successo'
];
}
} catch (PDOException $e) {
echo json_encode(['success' => false, 'message' => 'Errore nel salvataggio: ' . $e->getMessage()]);
}
} else {
echo json_encode(['success' => false, 'message' => 'Descrizione mancante']);
$pdo->commit();
echo json_encode(['success' => true, 'results' => $results]);
} catch (PDOException $e) {
$pdo->rollBack();
echo json_encode(['success' => false, 'message' => 'Errore nel salvataggio: ' . $e->getMessage()]);
}
-917
View File
@@ -1,917 +0,0 @@
{
"@odata.context": "https:\/\/bvcpsitaly-elims.com\/limsapi\/api\/odata\/$metadata#SchemaCustomField",
"value": [
{
"IdSchemaCustomFields": 41,
"ConteggioClienti": 0,
"Nome": "Labostudio",
"Descrizione": null
},
{
"IdSchemaCustomFields": 42,
"ConteggioClienti": 0,
"Nome": "Schema 1",
"Descrizione": null
},
{
"IdSchemaCustomFields": 43,
"ConteggioClienti": 0,
"Nome": "Schema1",
"Descrizione": null
},
{
"IdSchemaCustomFields": 44,
"ConteggioClienti": 0,
"Nome": "Cuoio\/Pelle Standard \/ Leather",
"Descrizione": "Schema per tutti i campioni in cuoio\/pelle per i quali non \u00e8 specificato un destinatario.\r\n"
},
{
"IdSchemaCustomFields": 45,
"ConteggioClienti": 0,
"Nome": "Borse",
"Descrizione": null
},
{
"IdSchemaCustomFields": 46,
"ConteggioClienti": 0,
"Nome": "Borse Burberry",
"Descrizione": null
},
{
"IdSchemaCustomFields": 47,
"ConteggioClienti": 0,
"Nome": "pelle calzatura",
"Descrizione": null
},
{
"IdSchemaCustomFields": 48,
"ConteggioClienti": 0,
"Nome": "Standard \/ Generico",
"Descrizione": "\r\n"
},
{
"IdSchemaCustomFields": 49,
"ConteggioClienti": 0,
"Nome": "Accessori Metallici \/ Metallic Accessories",
"Descrizione": "Schema per tutti gli Accessori Metallici\r\n\r\n\r\n"
},
{
"IdSchemaCustomFields": 50,
"ConteggioClienti": 0,
"Nome": "Tessile \/ Textiles",
"Descrizione": "Schema per tutti i Tessuti\r\n"
},
{
"IdSchemaCustomFields": 52,
"ConteggioClienti": 0,
"Nome": "Brasport",
"Descrizione": null
},
{
"IdSchemaCustomFields": 54,
"ConteggioClienti": 0,
"Nome": "Chanel Calzatura",
"Descrizione": "\r\n"
},
{
"IdSchemaCustomFields": 55,
"ConteggioClienti": 0,
"Nome": "Burberry",
"Descrizione": null
},
{
"IdSchemaCustomFields": 57,
"ConteggioClienti": 0,
"Nome": "Z_Ralph Lauren - Tessile",
"Descrizione": "Schema per tutti i campioni in tessuto per Ralph Lauren.\r\n\r\n\r\n\r\n"
},
{
"IdSchemaCustomFields": 58,
"ConteggioClienti": 0,
"Nome": "LIU JO",
"Descrizione": null
},
{
"IdSchemaCustomFields": 59,
"ConteggioClienti": 0,
"Nome": "Migrazione tra Componenti",
"Descrizione": null
},
{
"IdSchemaCustomFields": 60,
"ConteggioClienti": 0,
"Nome": "Prova Outsourcing",
"Descrizione": null
},
{
"IdSchemaCustomFields": 61,
"ConteggioClienti": 0,
"Nome": "Marc Jacobs",
"Descrizione": null
},
{
"IdSchemaCustomFields": 62,
"ConteggioClienti": 0,
"Nome": "A. TESTONI",
"Descrizione": null
},
{
"IdSchemaCustomFields": 63,
"ConteggioClienti": 0,
"Nome": "Chanel CHINA PROJECT",
"Descrizione": "\r\n"
},
{
"IdSchemaCustomFields": 66,
"ConteggioClienti": 0,
"Nome": "GUESS",
"Descrizione": null
},
{
"IdSchemaCustomFields": 68,
"ConteggioClienti": 0,
"Nome": "Valentino",
"Descrizione": null
},
{
"IdSchemaCustomFields": 69,
"ConteggioClienti": 0,
"Nome": "DESIGUAL",
"Descrizione": null
},
{
"IdSchemaCustomFields": 70,
"ConteggioClienti": 0,
"Nome": "FENDI PELLETTERIA",
"Descrizione": "Solo per FENDI Pelletteria_INGLESE\r\n"
},
{
"IdSchemaCustomFields": 71,
"ConteggioClienti": 0,
"Nome": "Z_Cuoio\/Pelle Standard ACCREDIA",
"Descrizione": "Schema per tutti i campioni in cuoio\/pelle per i quali non \u00e8 specificato un destinatario.\r\n"
},
{
"IdSchemaCustomFields": 72,
"ConteggioClienti": 0,
"Nome": "Z_BALLY",
"Descrizione": "sia per calzatura che pelletteria. Aggiunto campo TEST DESCRIPTION, compreso nella fatturazione per le divisioni pelletteria.\r\n\r\n"
},
{
"IdSchemaCustomFields": 73,
"ConteggioClienti": 0,
"Nome": "Z_Ralph Lauren - Leather",
"Descrizione": null
},
{
"IdSchemaCustomFields": 74,
"ConteggioClienti": 0,
"Nome": "Z_Ralph Lauren - Fabric",
"Descrizione": null
},
{
"IdSchemaCustomFields": 76,
"ConteggioClienti": 0,
"Nome": "NORDSTROM",
"Descrizione": "\r\n"
},
{
"IdSchemaCustomFields": 77,
"ConteggioClienti": 0,
"Nome": "ONWARD LUXURY GROUP",
"Descrizione": "\r\n"
},
{
"IdSchemaCustomFields": 78,
"ConteggioClienti": 0,
"Nome": "P&G SRL_Progetto Durability",
"Descrizione": "\r\n"
},
{
"IdSchemaCustomFields": 79,
"ConteggioClienti": 0,
"Nome": "Bally qualsiasi divisione",
"Descrizione": null
},
{
"IdSchemaCustomFields": 80,
"ConteggioClienti": 0,
"Nome": "FENDI CALZATURA",
"Descrizione": "\r\n"
},
{
"IdSchemaCustomFields": 81,
"ConteggioClienti": 0,
"Nome": "LouBoutin",
"Descrizione": "\r\n"
},
{
"IdSchemaCustomFields": 82,
"ConteggioClienti": 0,
"Nome": "MONCLER Brand",
"Descrizione": "Da utilizzare solo per il Brand Diretto\r\nGR 19\/03\/2024"
},
{
"IdSchemaCustomFields": 83,
"ConteggioClienti": 0,
"Nome": "JIMMY CHOO",
"Descrizione": null
},
{
"IdSchemaCustomFields": 84,
"ConteggioClienti": 0,
"Nome": "Yves Saint Laurent",
"Descrizione": null
},
{
"IdSchemaCustomFields": 85,
"ConteggioClienti": 0,
"Nome": "BENETTON",
"Descrizione": null
},
{
"IdSchemaCustomFields": 86,
"ConteggioClienti": 0,
"Nome": "UPLOAD REPORT",
"Descrizione": null
},
{
"IdSchemaCustomFields": 87,
"ConteggioClienti": 0,
"Nome": "Hermes Calzatura",
"Descrizione": "\r\n\r\n\r\n"
},
{
"IdSchemaCustomFields": 88,
"ConteggioClienti": 0,
"Nome": "C&A",
"Descrizione": "Schema per fornitori e C&A diretto\r\n"
},
{
"IdSchemaCustomFields": 89,
"ConteggioClienti": 0,
"Nome": "AMERICAN EAGLE",
"Descrizione": "Schema per American Eagle\/Todd snyder\r\n\r\n\r\n\r\n"
},
{
"IdSchemaCustomFields": 91,
"ConteggioClienti": 0,
"Nome": "Ferragamo",
"Descrizione": "\r\n\r\n\r\n"
},
{
"IdSchemaCustomFields": 93,
"ConteggioClienti": 0,
"Nome": "Z_Alexander McQueen",
"Descrizione": "\r\n\r\n"
},
{
"IdSchemaCustomFields": 95,
"ConteggioClienti": 0,
"Nome": "Balenciaga Pelletteria",
"Descrizione": "\r\n"
},
{
"IdSchemaCustomFields": 96,
"ConteggioClienti": 0,
"Nome": "DUNHILL",
"Descrizione": "SCHEMA DUNHILL tutti i tipi di campioni\r\n"
},
{
"IdSchemaCustomFields": 97,
"ConteggioClienti": 0,
"Nome": "PRELIEVI ACQUE",
"Descrizione": null
},
{
"IdSchemaCustomFields": 98,
"ConteggioClienti": 0,
"Nome": "LouBoutin_Tossicologico",
"Descrizione": null
},
{
"IdSchemaCustomFields": 99,
"ConteggioClienti": 0,
"Nome": "ROBAN'S ",
"Descrizione": "tutte le divisioni\r\n\r\n"
},
{
"IdSchemaCustomFields": 100,
"ConteggioClienti": 0,
"Nome": "PROGETTO LUGGAGE",
"Descrizione": "Progetto Luggage Hermes\r\n\r\n\r\n\r\n"
},
{
"IdSchemaCustomFields": 102,
"ConteggioClienti": 0,
"Nome": "Balmain",
"Descrizione": "Schema per tutti i campioni Balmain"
},
{
"IdSchemaCustomFields": 103,
"ConteggioClienti": 0,
"Nome": "ZDHC",
"Descrizione": "Schema di Riferimento ZDHC Wastewaters"
},
{
"IdSchemaCustomFields": 104,
"ConteggioClienti": 0,
"Nome": "GUCCI CDC 4172",
"Descrizione": "\r\n"
},
{
"IdSchemaCustomFields": 105,
"ConteggioClienti": 0,
"Nome": "Z_ASOS",
"Descrizione": null
},
{
"IdSchemaCustomFields": 106,
"ConteggioClienti": 0,
"Nome": "Z_BOUX AVENUE",
"Descrizione": "28\/09 no indicazioni su esigenze di fatturazione (detto da Frosini)\r\n\r\n\r\n"
},
{
"IdSchemaCustomFields": 107,
"ConteggioClienti": 0,
"Nome": "BONPOINT",
"Descrizione": "05\/10 creazione\r\n\r\n\r\n\r\n"
},
{
"IdSchemaCustomFields": 108,
"ConteggioClienti": 0,
"Nome": "Canada Goose",
"Descrizione": null
},
{
"IdSchemaCustomFields": 109,
"ConteggioClienti": 0,
"Nome": "DIESEL",
"Descrizione": null
},
{
"IdSchemaCustomFields": 110,
"ConteggioClienti": 0,
"Nome": "AQC_Leather",
"Descrizione": null
},
{
"IdSchemaCustomFields": 111,
"ConteggioClienti": 0,
"Nome": "BEAUMANOIR (CC-Mor-Bon-Breal)",
"Descrizione": "04\/02\/21_ AGGIORNATO 05\/08\r\n"
},
{
"IdSchemaCustomFields": 112,
"ConteggioClienti": 0,
"Nome": "BooHoo",
"Descrizione": null
},
{
"IdSchemaCustomFields": 114,
"ConteggioClienti": 0,
"Nome": "Golden Goose",
"Descrizione": "Golden goose\r\n"
},
{
"IdSchemaCustomFields": 115,
"ConteggioClienti": 0,
"Nome": "Z_ZLABEL",
"Descrizione": "Schema per ZLABEL"
},
{
"IdSchemaCustomFields": 116,
"ConteggioClienti": 0,
"Nome": "Zadig & Voltaire",
"Descrizione": "Schema per Zadig & Voltaire"
},
{
"IdSchemaCustomFields": 117,
"ConteggioClienti": 0,
"Nome": "Gemo",
"Descrizione": "Schema solo per Gemo\r\n\r\n\r\n\r\n"
},
{
"IdSchemaCustomFields": 118,
"ConteggioClienti": 0,
"Nome": "PROMOD",
"Descrizione": "CHF 06\/08\r\n\r\n\r\n\r\n\r\n"
},
{
"IdSchemaCustomFields": 119,
"ConteggioClienti": 0,
"Nome": "LA HALLE (BEAUMANOIR)",
"Descrizione": "13\/08\/2021 CHF\r\n\r\n"
},
{
"IdSchemaCustomFields": 120,
"ConteggioClienti": 0,
"Nome": "LA REDOUTE",
"Descrizione": "14\/09\/2021 AD\r\n\r\n\r\n\r\n"
},
{
"IdSchemaCustomFields": 121,
"ConteggioClienti": 0,
"Nome": "TOD'S",
"Descrizione": "Schema per materiale gb18401 e GB20400\r\n\r\n\r\n"
},
{
"IdSchemaCustomFields": 122,
"ConteggioClienti": 0,
"Nome": "ASOS rev 1",
"Descrizione": null
},
{
"IdSchemaCustomFields": 123,
"ConteggioClienti": 0,
"Nome": "Monoprix",
"Descrizione": "Schema per Monoprix\r\n\r\n"
},
{
"IdSchemaCustomFields": 124,
"ConteggioClienti": 0,
"Nome": "DIOR Ita",
"Descrizione": "CHF 21\/03\r\n"
},
{
"IdSchemaCustomFields": 125,
"ConteggioClienti": 0,
"Nome": "GEOX - Raw Material",
"Descrizione": "SCHEMA DA USARE SOLO PER GEOX - SOLO PER LE SUOLE E MATERIALI DENOMINATI RPU \/ RAW MATERIAL"
},
{
"IdSchemaCustomFields": 126,
"ConteggioClienti": 0,
"Nome": "CAMAIEU",
"Descrizione": "SCHEMA DA USARE SOLO PER CAMAIEU\r\n"
},
{
"IdSchemaCustomFields": 127,
"ConteggioClienti": 0,
"Nome": "Z_Golden Goose FTW",
"Descrizione": "Golden goose\r\n"
},
{
"IdSchemaCustomFields": 128,
"ConteggioClienti": 0,
"Nome": "STEVE MADDEN - FOOTWEAR",
"Descrizione": "DA UTILIZZARE SOLO PER DESTINAZIONE D'USO CALZATURA\r\n"
},
{
"IdSchemaCustomFields": 129,
"ConteggioClienti": 0,
"Nome": "Z_Carhartt",
"Descrizione": "SCHEMA DA UTILIZZARE SOLO PER RICHIESTE UFFICIALI CARHARTT\r\n\r\n\r\n"
},
{
"IdSchemaCustomFields": 131,
"ConteggioClienti": 0,
"Nome": "DAMART",
"Descrizione": "\r\n\r\n\r\n\r\n"
},
{
"IdSchemaCustomFields": 132,
"ConteggioClienti": 0,
"Nome": "Gruppo OTB",
"Descrizione": "Schema per Staff International, Diesel e Brave kid\r\n\r\n\r\n\r\n\r\n"
},
{
"IdSchemaCustomFields": 133,
"ConteggioClienti": 0,
"Nome": "FERRARI",
"Descrizione": "Schema da usare per Ferrari e fornitori\r\n\r\n"
},
{
"IdSchemaCustomFields": 134,
"ConteggioClienti": 0,
"Nome": "GAP - ABBIGLIAMENTO",
"Descrizione": "Schema GAP da utilizzare solo per destinazione abbigliamento\r\n"
},
{
"IdSchemaCustomFields": 135,
"ConteggioClienti": 0,
"Nome": "GAP - CALZATURA",
"Descrizione": "Schema GAP da utilizzare solo per destinazione calzatura\r\n\r\n"
},
{
"IdSchemaCustomFields": 136,
"ConteggioClienti": 0,
"Nome": "SALLING GROUP",
"Descrizione": "Schema per Salling Group\r\n\r\n\r\n\r\n\r\n"
},
{
"IdSchemaCustomFields": 137,
"ConteggioClienti": 0,
"Nome": "SOFT SURROUNDINGS",
"Descrizione": "Schema da utilizzare per Soft Surroundings\r\n\r\n"
},
{
"IdSchemaCustomFields": 138,
"ConteggioClienti": 0,
"Nome": "E-LIMS - Cuoio\/Pelle Standard \/ Leather",
"Descrizione": "Schema da utilizzare solo per accettazioni online\r\n"
},
{
"IdSchemaCustomFields": 139,
"ConteggioClienti": 0,
"Nome": "Z_ZALANDO",
"Descrizione": "Schema per ZALANDO ------ (NON per ZLABEL che ha il suo)\r\n"
},
{
"IdSchemaCustomFields": 140,
"ConteggioClienti": 0,
"Nome": "LVMH",
"Descrizione": "gennaio 2023\r\n"
},
{
"IdSchemaCustomFields": 141,
"ConteggioClienti": 0,
"Nome": "Valentino - eLims",
"Descrizione": "SCHEMA DA UTILIZZARE SOLO PER L'ACCETTAZIONE ONLINE DI VALENTINO"
},
{
"IdSchemaCustomFields": 142,
"ConteggioClienti": 0,
"Nome": "FENDI PELLETTERIA COMPLIANCE",
"Descrizione": "Solo per FENDI Pelletteria_INGLESE 04\/05\/2023\r\n"
},
{
"IdSchemaCustomFields": 143,
"ConteggioClienti": 0,
"Nome": "TAPESTRY",
"Descrizione": "04\/05\/2023, agg secondo procedura 08\/11\/23\r\n"
},
{
"IdSchemaCustomFields": 144,
"ConteggioClienti": 0,
"Nome": "ALEXANDER MC QUEEN",
"Descrizione": "ALEXANDER MC QUEEN 15\/05\/2023\r\n\r\n\r\n"
},
{
"IdSchemaCustomFields": 145,
"ConteggioClienti": 0,
"Nome": "Hermes_Chimici_Parigi",
"Descrizione": "\r\n"
},
{
"IdSchemaCustomFields": 146,
"ConteggioClienti": 0,
"Nome": "CELINE ABBIGLIAMENTO_Progetto Speciale",
"Descrizione": "IO 202 CELINE ABBIGLIAMENTO_06\/06\/203_CHF\r\n\r\n"
},
{
"IdSchemaCustomFields": 147,
"ConteggioClienti": 0,
"Nome": "GEOX - Prodotto Finito",
"Descrizione": "SCHEMA DA USARE SOLO PER GEOX - SOLO PER PRODOTTO FINITO"
},
{
"IdSchemaCustomFields": 149,
"ConteggioClienti": 0,
"Nome": "Hermes\/IDO",
"Descrizione": "creato il 05\/07\/2023 CHF\r\n"
},
{
"IdSchemaCustomFields": 150,
"ConteggioClienti": 0,
"Nome": "Tessile \/ Textiles PER CLIENTI CON OBLO",
"Descrizione": "Schema per tutti i Tessuti QUANDO IL CLIENTE NECESSITA DI NR OBLO\r\n\r\n\r\n\r\n"
},
{
"IdSchemaCustomFields": 151,
"ConteggioClienti": 0,
"Nome": "J JIll",
"Descrizione": "Schema per cliente J JIll, necessario riportare la recommended fiber content in schema verde\r\n\r\n\r\n\r\n\r\n"
},
{
"IdSchemaCustomFields": 152,
"ConteggioClienti": 0,
"Nome": "AUCHAN - TAPE A L'OEIL",
"Descrizione": "Schema AUCHAN da utilizzare solo per la divisione TAPE A L'OEIL SA, successivamente se uguale da usare anche per le altre divisioni ed uniformarlo come generico"
},
{
"IdSchemaCustomFields": 153,
"ConteggioClienti": 0,
"Nome": "ALL SAINTS - BUSCEMI",
"Descrizione": "SCHE DA USARE SOLO PER ALL SAINTS E BUSCEMI\r\n\r\n\r\n\r\n"
},
{
"IdSchemaCustomFields": 154,
"ConteggioClienti": 0,
"Nome": "CELINE - LVMH",
"Descrizione": "Schema con aggiunta campi LVMH per estrazioni\r\nAD-29\/03\/2024"
},
{
"IdSchemaCustomFields": 155,
"ConteggioClienti": 0,
"Nome": "SeyMeChamLou",
"Descrizione": "DA USARE SOLO PER SEYMECHAMLOU (LOUBOUTIN)\r\n"
},
{
"IdSchemaCustomFields": 156,
"ConteggioClienti": 0,
"Nome": "PRADA",
"Descrizione": "PER ADESSO DA USARE PER ABBIGLIAMENTO E CALZATURA\r\n\r\n\r\n\r\n"
},
{
"IdSchemaCustomFields": 157,
"ConteggioClienti": 0,
"Nome": "Hermes_HCP",
"Descrizione": "Schema per unicamente HCP"
},
{
"IdSchemaCustomFields": 158,
"ConteggioClienti": 0,
"Nome": "STONE ISLAND",
"Descrizione": "Schema per tutti i campioni in cuoio\/pelle per i quali non \u00e8 specificato un destinatario.\r\n"
},
{
"IdSchemaCustomFields": 159,
"ConteggioClienti": 0,
"Nome": "Chanel_Pierre Damien",
"Descrizione": "Schema da usare per Campioni ricevuti da Pierre-Damien Verine e suo staff CHANEL.\r\n"
},
{
"IdSchemaCustomFields": 160,
"ConteggioClienti": 0,
"Nome": "Z_ACNE",
"Descrizione": "\r\n.\r\n"
},
{
"IdSchemaCustomFields": 161,
"ConteggioClienti": 0,
"Nome": "OBERALP GROUP",
"Descrizione": "Schema da usare solo per Oberalp Group\r\n"
},
{
"IdSchemaCustomFields": 162,
"ConteggioClienti": 0,
"Nome": "Club Monaco",
"Descrizione": "da usare solo per Club Monaco GR 20\/02\/2024"
},
{
"IdSchemaCustomFields": 163,
"ConteggioClienti": 0,
"Nome": "Devred",
"Descrizione": "Schema creato per cliente DEVRED\r\nGR 18\/03\/2024 aggiornato il 23\/04\/2026\r\n\r\n"
},
{
"IdSchemaCustomFields": 164,
"ConteggioClienti": 0,
"Nome": "MONCLER Supplier",
"Descrizione": "Da utilizzare per fornitori Moncler \r\nGR 19\/03\/2024"
},
{
"IdSchemaCustomFields": 165,
"ConteggioClienti": 0,
"Nome": "Kering Sunglasses",
"Descrizione": "Schema per tutti i campioni di qualsiasi matrice escluso cuoio\/pelle\r\n\r\n"
},
{
"IdSchemaCustomFields": 166,
"ConteggioClienti": 0,
"Nome": "Giorgio Armani",
"Descrizione": "\r\n\r\n"
},
{
"IdSchemaCustomFields": 167,
"ConteggioClienti": 0,
"Nome": "Chanel USA",
"Descrizione": "\r\n"
},
{
"IdSchemaCustomFields": 168,
"ConteggioClienti": 0,
"Nome": "Staff Calzatura",
"Descrizione": "Schema per tutti i campioni di qualsiasi matrice escluso cuoio\/pelle\r\n\r\n"
},
{
"IdSchemaCustomFields": 169,
"ConteggioClienti": 0,
"Nome": "P&G SRL",
"Descrizione": "\r\n"
},
{
"IdSchemaCustomFields": 170,
"ConteggioClienti": 0,
"Nome": "INCOM",
"Descrizione": "Schema da utilizzare per INCOM"
},
{
"IdSchemaCustomFields": 171,
"ConteggioClienti": 0,
"Nome": "RIVER ISLAND",
"Descrizione": "SCHEDA DA USARE SOLO PER RIVER ISLAND - NO CALZATURA\r\n\r\n\r\n"
},
{
"IdSchemaCustomFields": 172,
"ConteggioClienti": 0,
"Nome": "Longchamp",
"Descrizione": "Schema per tutti i campioni con RIchiesta Longchamp ufficiale\r\n"
},
{
"IdSchemaCustomFields": 173,
"ConteggioClienti": 0,
"Nome": "Bottega Veneta",
"Descrizione": "Schema per tutti i campioni di Bottega Veneta di Stella"
},
{
"IdSchemaCustomFields": 174,
"ConteggioClienti": 0,
"Nome": "Mint Velvet",
"Descrizione": "Schema per tutti i campioni di Mint Velvel con richiesta ufficiale.\r\n\r\n"
},
{
"IdSchemaCustomFields": 176,
"ConteggioClienti": 0,
"Nome": "RIVER ISLAND FOOTWEAR",
"Descrizione": "SCHEDA DA USARE SOLO PER RIVER ISLAND - USARE SOLO PER\r\n CALZATURA\r\n"
},
{
"IdSchemaCustomFields": 177,
"ConteggioClienti": 0,
"Nome": "Phoebe Philo ",
"Descrizione": "\r\n\r\n"
},
{
"IdSchemaCustomFields": 178,
"ConteggioClienti": 0,
"Nome": "New Guards Group",
"Descrizione": "\r\n"
},
{
"IdSchemaCustomFields": 179,
"ConteggioClienti": 0,
"Nome": "Giorgio Armani Operation",
"Descrizione": "\r\n\r\n"
},
{
"IdSchemaCustomFields": 180,
"ConteggioClienti": 0,
"Nome": "Chloe'",
"Descrizione": "\r\n"
},
{
"IdSchemaCustomFields": 181,
"ConteggioClienti": 0,
"Nome": "LVMH non diretti",
"Descrizione": "utilizzato ogni qualvolta siano caricati pacchetti \/ prove singole che non rientrano nel programma LVMH \r\n"
},
{
"IdSchemaCustomFields": 182,
"ConteggioClienti": 0,
"Nome": "Ralph Lauren - All testing V.10",
"Descrizione": "AGGIORNAMENTO AL 16\/03\/2026 per estrazione fatturazione"
},
{
"IdSchemaCustomFields": 183,
"ConteggioClienti": 0,
"Nome": "TWINSET",
"Descrizione": "Schema da usare per Twinset - come da mail di EP del 20\/05\/2025\r\n\r\n"
},
{
"IdSchemaCustomFields": 184,
"ConteggioClienti": 0,
"Nome": "ACNE STUDIOS rev 01",
"Descrizione": null
},
{
"IdSchemaCustomFields": 185,
"ConteggioClienti": 0,
"Nome": "Brunello cucinelli",
"Descrizione": null
},
{
"IdSchemaCustomFields": 186,
"ConteggioClienti": 0,
"Nome": "TWINSET",
"Descrizione": "Schema per tutti i campioni di qualsiasi matrice escluso cuoio\/pelle\r\n\r\n"
},
{
"IdSchemaCustomFields": 187,
"ConteggioClienti": 0,
"Nome": "LORO PIANA",
"Descrizione": "Schema per tutti i campioni Loro Piana\r\n"
},
{
"IdSchemaCustomFields": 188,
"ConteggioClienti": 0,
"Nome": "LEMAIRE",
"Descrizione": "Schema per tutti i campioni in cuoio\/pelle per i quali non \u00e8 specificato un destinatario.\r\n"
},
{
"IdSchemaCustomFields": 189,
"ConteggioClienti": 0,
"Nome": "TEST_IT_SCHEMA",
"Descrizione": "Test per IT"
},
{
"IdSchemaCustomFields": 190,
"ConteggioClienti": 0,
"Nome": "LBS Interscambio",
"Descrizione": "Schema per tutti i campioni interscambio LBS\r\n"
},
{
"IdSchemaCustomFields": 191,
"ConteggioClienti": 0,
"Nome": "KIABI",
"Descrizione": "Schema per il cliente Kiabi\r\n\r\n"
},
{
"IdSchemaCustomFields": 192,
"ConteggioClienti": 0,
"Nome": "INDITEX",
"Descrizione": "Schema da usare solo per richieste INDITEX"
},
{
"IdSchemaCustomFields": 193,
"ConteggioClienti": 0,
"Nome": "AQC_Other materials",
"Descrizione": null
},
{
"IdSchemaCustomFields": 194,
"ConteggioClienti": 0,
"Nome": "Hermes ADM & Silk",
"Descrizione": "SCHEMA DA USARE SOLO PER LA DIVISIONE ADM & SILK\r\n\r\n\r\n\r\n"
},
{
"IdSchemaCustomFields": 195,
"ConteggioClienti": 0,
"Nome": "Chloe'_APPAREL",
"Descrizione": "Schema aggiornato il 18\/12\/25 secondo modulo excel x codifica Elims\r\nGR"
},
{
"IdSchemaCustomFields": 196,
"ConteggioClienti": 0,
"Nome": "DUNHILL_DRAFT NON USARE",
"Descrizione": "SCHEMA DUNHILL NON USARE STUDIO NUOVA PROCEDURA NOVEMBRE 2025\r\n\r\n"
},
{
"IdSchemaCustomFields": 197,
"ConteggioClienti": 0,
"Nome": "BERLUTI - LVMH",
"Descrizione": "Creato per accettazione Elims\r\n"
},
{
"IdSchemaCustomFields": 198,
"ConteggioClienti": 0,
"Nome": "PIAGET (gruppo Cartier)",
"Descrizione": "Schema per tutti i campioni PIAGET (gruppo Cartier)\r\n\r\n"
},
{
"IdSchemaCustomFields": 199,
"ConteggioClienti": 0,
"Nome": "HERMES PAP FEMME",
"Descrizione": "Schema per tutti i campioni di HERMES PAP FEMME \r\n15\/01\/2025\r\n\r\n\r\n"
},
{
"IdSchemaCustomFields": 200,
"ConteggioClienti": 0,
"Nome": "CARHARTT ( provvisiorio in revisione)",
"Descrizione": "Schema per tutti i campioni CARHARTT provvissorio\r\n\r\n"
},
{
"IdSchemaCustomFields": 201,
"ConteggioClienti": 0,
"Nome": "ROSSIMODA",
"Descrizione": "Per tutti i campioni di ROSSIMODA\r\n\r\n"
},
{
"IdSchemaCustomFields": 202,
"ConteggioClienti": 0,
"Nome": "LIMS-CIM - MAX MARA",
"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"
},
{
"IdSchemaCustomFields": 206,
"ConteggioClienti": 0,
"Nome": "COLDWATER CREEK",
"Descrizione": "\r\n"
},
{
"IdSchemaCustomFields": 208,
"ConteggioClienti": 0,
"Nome": "ETON",
"Descrizione": "Schema da usare per ETON\r\n"
}
]
}
+1 -1
View File
@@ -51,7 +51,7 @@ try {
// Load from cache or API
$cacheFile = __DIR__ . '/cache/clienti.json';
if (file_exists($cacheFile) && (time() - filemtime($cacheFile) < 3600)) {
if (file_exists($cacheFile) && (time() - filemtime($cacheFile) < 7200)) {
$data = json_decode(file_get_contents($cacheFile), true);
} else {
$api = VisualLimsApiClient::getInstance();
+66 -10
View File
@@ -29,7 +29,7 @@ try {
$cacheDir = __DIR__ . '/cache';
$cacheFile = $cacheDir . '/customfield_' . $fieldId . '.json';
if (file_exists($cacheFile) && (time() - filemtime($cacheFile) < 3600)) {
if (file_exists($cacheFile) && (time() - filemtime($cacheFile) < 7200)) {
$values = json_decode(file_get_contents($cacheFile), true);
} else {
$api = VisualLimsApiClient::getInstance();
@@ -51,18 +51,74 @@ try {
exit;
}
// Search by query
$results = [];
foreach ($values as $v) {
$text = $v['Valore'] ?? '';
if ($q === '' || mb_strpos(mb_strtolower($text), $q) !== false) {
$results[] = ['id' => $v['IdCustomFieldsValue'], 'text' => $text];
if ($limit > 0 && count($results) >= $limit) break;
// Search — multi-term AND, position-independent, ranked
$terms = array_values(array_filter(
preg_split('/\s+/u', $q, -1, PREG_SPLIT_NO_EMPTY)
));
// Nessun termine digitato: alfabetico, taglio al limite
if (empty($terms)) {
$all = [];
foreach ($values as $v) {
$all[] = ['id' => $v['IdCustomFieldsValue'], 'text' => $v['Valore'] ?? ''];
}
usort($all, fn($a, $b) => strcasecmp($a['text'], $b['text']));
if ($limit > 0) $all = array_slice($all, 0, $limit);
echo json_encode(['results' => $all]);
exit;
}
// Sort alphabetically
usort($results, fn($a, $b) => strcasecmp($a['text'], $b['text']));
$firstTerm = $terms[0];
$scored = [];
foreach ($values as $v) {
$text = $v['Valore'] ?? '';
$textLower = mb_strtolower($text);
// AND: tutti i termini devono essere presenti, in qualsiasi posizione
$matchAll = true;
foreach ($terms as $t) {
if (mb_strpos($textLower, $t) === false) {
$matchAll = false;
break;
}
}
if (!$matchAll) continue;
// Punteggio di pertinenza (più basso = più rilevante)
if ($textLower === $q) {
$score = 0; // match esatto
} elseif (mb_strpos($textLower, $firstTerm) === 0) {
$score = 1; // inizia col primo termine
} elseif (preg_match('/(^|\s)' . preg_quote($firstTerm, '/') . '/u', $textLower)) {
$score = 2; // primo termine a inizio di una parola
} else {
$score = 3; // presente ma non a inizio parola
}
$scored[] = [
'id' => $v['IdCustomFieldsValue'],
'text' => $text,
'_s' => $score,
'_n' => $textLower
];
}
// Ordina per punteggio, poi alfabetico
usort($scored, function ($a, $b) {
if ($a['_s'] !== $b['_s']) return $a['_s'] - $b['_s'];
return strcmp($a['_n'], $b['_n']);
});
// Taglia DOPO l'ordinamento e rimuovi i campi interni
if ($limit > 0) {
$scored = array_slice($scored, 0, $limit);
}
$results = array_map(
fn($r) => ['id' => $r['id'], 'text' => $r['text']],
$scored
);
echo json_encode(['results' => $results]);
} catch (Exception $e) {
+5 -1
View File
@@ -62,7 +62,11 @@ if (isset($_GET['macro_list'])) {
echo json_encode(['success' => true, 'value' => $macros]);
exit;
}
// Return full matrix list (same shape as get_matrici_db.php)
if (isset($_GET['full_list'])) {
echo json_encode(['success' => true, 'value' => $matrici]);
exit;
}
// Search (with optional MacroMatrice filter) - multi-term AND, position-independent, ranked
$terms = array_values(array_filter(
preg_split('/\s+/u', $q, -1, PREG_SPLIT_NO_EMPTY)
+315
View File
@@ -0,0 +1,315 @@
<?php
include('include/headscript.php');
require_once __DIR__ . '/class/Mailer.class.php';
header('Content-Type: application/json');
/**
* Risolve [IdCliente => Nominativo] leggendo la stessa cache di search_clienti.php.
* Non chiama l'API: usa cache/clienti.json (già mantenuto aggiornato dalla ricerca clienti).
*/
function resolveClientNames(array $ids): array
{
$ids = array_values(array_filter(array_map('intval', $ids), fn($v) => $v > 0));
if (empty($ids)) return [];
$cacheFile = __DIR__ . '/cache/clienti.json';
if (!file_exists($cacheFile)) return [];
$data = json_decode((string)@file_get_contents($cacheFile), true);
$clients = $data['value'] ?? [];
if (empty($clients)) return [];
// indicizza per IdCliente
$byId = [];
foreach ($clients as $c) {
$cid = (int)($c['IdCliente'] ?? 0);
if ($cid > 0) {
$byId[$cid] = trim((string)($c['Nominativo'] ?? ''));
}
}
$out = [];
foreach ($ids as $id) {
if (isset($byId[$id]) && $byId[$id] !== '') {
$out[$id] = $byId[$id];
}
}
return $out;
}
$db = DBHandlerSelect::getInstance();
$pdo = $db->getConnection();
// input: solo POST (endpoint che invia email — niente attivazione via URL)
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode(['success' => false, 'message' => 'Metodo non consentito']);
exit;
}
$ids = $_POST['ids'] ?? [];
if (!is_array($ids)) $ids = explode(',', (string)$ids);
$ids = array_values(array_filter(array_map('intval', $ids), fn($v) => $v > 0));
$templateId = (int)($_POST['template_id'] ?? 0);
if (empty($ids)) {
echo json_encode(['success' => false, 'message' => 'Nessun id']);
exit;
}
// Fallback: se il template_id non arriva, ricavalo dalla prima commessa
if ($templateId <= 0) {
$tq = $pdo->prepare("SELECT templateid FROM datadb WHERE iddatadb = ? LIMIT 1");
$tq->execute([$ids[0]]);
$templateId = (int)$tq->fetchColumn();
}
// tutti i main field del template (possono essere fino a 2), in ordine
$mainMappingIds = [];
$templateName = '';
if ($templateId > 0) {
$s = $pdo->prepare("
SELECT id FROM template_mapping
WHERE template_id = ? AND main_field = '1' AND is_visible_import = 1
ORDER BY field_order ASC, id ASC
");
$s->execute([$templateId]);
$mainMappingIds = array_map('intval', $s->fetchAll(PDO::FETCH_COLUMN));
// nome del template per l'intestazione mail
$t = $pdo->prepare("SELECT name FROM excel_templates WHERE id = ? LIMIT 1");
$t->execute([$templateId]);
$templateName = (string)$t->fetchColumn();
}
// esiti delle commesse
$ph = implode(',', array_fill(0, count($ids), '?'));
$sql = "
SELECT d.iddatadb, d.commessaweb, d.status, d.user_id,
d.idclient, d.ClienteFatturazione,
CONCAT(u.first_name,' ',u.last_name) AS user_name,
u.email AS user_email, u.notify_export_email
FROM datadb d
LEFT JOIN auth_users u ON d.user_id = u.id
WHERE d.iddatadb IN ($ph)
ORDER BY FIELD(d.iddatadb, $ph)
";
$stmt = $pdo->prepare($sql);
$stmt->execute(array_merge($ids, $ids));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (empty($rows)) {
echo json_encode(['success' => false, 'message' => 'Righe non trovate']);
exit;
}
// --- Risoluzione nomi cliente (idclient + ClienteFatturazione) ---
$clientIdsToResolve = [];
foreach ($rows as $r) {
if (!empty($r['idclient'])) $clientIdsToResolve[(int)$r['idclient']] = true;
if (!empty($r['ClienteFatturazione'])) $clientIdsToResolve[(int)$r['ClienteFatturazione']] = true;
}
$clientNames = resolveClientNames(array_keys($clientIdsToResolve)); // [id => nome]
// helper: id cliente → nome, con fallback all'id se non risolto
$clientLabel = function ($id) use ($clientNames) {
$id = (int)$id;
if ($id <= 0) return '—';
return htmlspecialchars($clientNames[$id] ?? (string)$id);
};
// valori dei main field per ogni iddatadb — concatena i main valorizzati
$mainValues = [];
if (!empty($mainMappingIds)) {
$mph = implode(',', array_fill(0, count($mainMappingIds), '?'));
$s = $pdo->prepare("
SELECT id AS iddatadb, mapping_id, field_value
FROM import_data_details
WHERE id IN ($ph) AND mapping_id IN ($mph)
");
$s->execute(array_merge($ids, $mainMappingIds));
// raggruppa per iddatadb, mantenendo l'ordine dei main
$byRow = []; // iddatadb => [mapping_id => value]
foreach ($s->fetchAll(PDO::FETCH_ASSOC) as $r) {
$byRow[(int)$r['iddatadb']][(int)$r['mapping_id']] = $r['field_value'];
}
foreach ($byRow as $idd => $vals) {
$parts = [];
foreach ($mainMappingIds as $mid) { // ordine dei main
$v = trim((string)($vals[$mid] ?? ''));
if ($v !== '') $parts[] = $v;
}
$mainValues[$idd] = implode(' — ', $parts); // es. "descrizione — style code"
}
}
// analisi senza prezzo (NULL o 0) per ogni iddatadb
$noPriceByRow = []; // iddatadb => [ [part_number, part_description, analysis_name], ... ]
$s = $pdo->prepare("
SELECT a.iddatadb, MAX(a.analysis_name) AS analysis_name
FROM identification_parts_analyses a
WHERE a.iddatadb IN ($ph)
AND (a.analysis_price IS NULL OR a.analysis_price <= 0)
GROUP BY a.iddatadb, a.analysis_recordkey
ORDER BY a.iddatadb, analysis_name
");
$s->execute($ids);
foreach ($s->fetchAll(PDO::FETCH_ASSOC) as $r) {
$noPriceByRow[(int)$r['iddatadb']][] = $r;
}
$noPriceTotal = array_sum(array_map('count', $noPriceByRow));
// destinatari: utente/i dell'export che hanno la notifica attiva + admin fisso
$recipients = [];
foreach ($rows as $r) {
if (!empty($r['user_email']) && (int)($r['notify_export_email'] ?? 1) === 1) {
$recipients[$r['user_email']] = true;
}
}
$adminEmail = env('EXPORT_SUMMARY_ADMIN', 'admin@cesoft.io'); // sempre, indipendente dalla preferenza
if ($adminEmail) $recipients[$adminEmail] = true;
$recipients = array_keys($recipients);
// Se dopo il filtro non resta nessuno, non inviare
if (empty($recipients)) {
echo json_encode(['success' => true, 'message' => 'Nessun destinatario (notifiche disattivate)', 'recipients' => []]);
exit;
}
// conteggi. La mail riflette lo stato in DB al momento dell'invio: una riga ancora 'i'
// (export interrotto da timeout/errore di rete, o ancora in corso) NON è un successo.
$okCount = 0;
$errCount = 0;
$pendingCount = 0;
foreach ($rows as $r) {
if ($r['status'] === 'l') $okCount++;
elseif ($r['status'] === 'x') $errCount++;
else $pendingCount++;
}
$hasError = $errCount > 0;
$hasPending = $pendingCount > 0;
// --- tabella righe ---
$rowsHtml = '';
foreach ($rows as $r) {
$st = $r['status'];
if ($st === 'l') {
$label = 'Inviata';
$bg = '#e6f4ea';
$col = '#1e7e34';
} elseif ($st === 'x') {
$label = 'ERRORE';
$bg = '#fdecea';
$col = '#c0392b';
} else {
$label = 'NON CONFERMATA';
$bg = '#fff8e1';
$col = '#8a6d3b';
}
$commessa = htmlspecialchars($r['commessaweb'] ?: '—');
$main = htmlspecialchars($mainValues[(int)$r['iddatadb']] ?? '—');
$committente = $clientLabel($r['idclient'] ?? 0);
$fatturazione = $clientLabel($r['ClienteFatturazione'] ?? 0);
$rowsHtml .= "<tr>
<td style='padding:10px 10px;border-bottom:1px solid #eee;font-family:monospace;white-space:nowrap;vertical-align:top;'>{$commessa}</td>
<td style='padding:10px 10px;border-bottom:1px solid #eee;word-break:break-word;vertical-align:top;'>{$committente}</td>
<td style='padding:10px 10px;border-bottom:1px solid #eee;word-break:break-word;vertical-align:top;'>{$fatturazione}</td>
<td style='padding:10px 10px;border-bottom:1px solid #eee;word-break:break-word;vertical-align:top;'>{$main}</td>
<td style='padding:10px 10px;border-bottom:1px solid #eee;text-align:center;white-space:nowrap;vertical-align:top;'>
<span style='display:inline-block;padding:3px 10px;border-radius:12px;background:{$bg};color:{$col};font-weight:600;font-size:13px;'>{$label}</span>
</td>
</tr>";
// sotto-riga: solo le analisi No Price di questa commessa
$np = $noPriceByRow[(int)$r['iddatadb']] ?? [];
if (!empty($np)) {
$items = '';
foreach ($np as $n) {
$analysisName = htmlspecialchars((string)($n['analysis_name'] ?: 'Unnamed analysis'));
$items .= "<li style='margin:2px 0;'>{$analysisName}</li>";
}
$npCount = count($np);
$rowsHtml .= "<tr>
<td colspan='5' style='padding:8px 12px 12px 24px;border-bottom:1px solid #eee;background:#fff5f5;'>
<div style='margin-bottom:4px;font-size:12px;color:#c0392b;font-weight:600;'>
<span style='display:inline-block;padding:2px 8px;border-radius:10px;background:#c0392b;color:#fff;font-size:11px;'>No price</span>
&nbsp;Analisi senza prezzo ({$npCount})
</div>
<ul style='margin:0;padding-left:18px;font-size:13px;color:#555;'>{$items}</ul>
</td>
</tr>";
}
}
if ($hasError) {
$headerColor = '#c0392b';
$headerText = 'Export completato con errori';
} elseif ($hasPending) {
$headerColor = '#b7791f';
$headerText = 'Export da verificare';
} else {
$headerColor = '#1e7e34';
$headerText = 'Export completato con successo';
}
$total = count($rows);
// Committente / Fatturazione in testata solo se uguali per tutte le righe (batch misti → "vari")
$headerClient = function ($col) use ($rows, $clientLabel) {
$vals = array_unique(array_map(fn($r) => (int)($r[$col] ?? 0), $rows));
return count($vals) === 1 ? $clientLabel(reset($vals)) : 'vari';
};
$html = "
<div style='font-family:Arial,Helvetica,sans-serif;max-width:820px;margin:0 auto;border:1px solid #e0e0e0;border-radius:8px;overflow:hidden;'>
<div style='background:{$headerColor};color:#fff;padding:18px 24px;'>
<h2 style='margin:0;font-size:18px;'>{$headerText}</h2>
<p style='margin:6px 0 0;font-size:13px;opacity:.9;'>Riepilogo esportazione verso LIMS" .
($templateName !== '' ? " &middot; Template: <strong>" . htmlspecialchars($templateName) . "</strong>" : "") . "</p>
<p style='margin:6px 0 0;font-size:13px;opacity:.95;'>
Committente: <strong>" . $headerClient('idclient') . "</strong>
&nbsp;&middot;&nbsp;
FatturazioneAvanzata: <strong>" . $headerClient('ClienteFatturazione') . "</strong>
</p>
</div>
<div style='padding:20px 24px;'>
<p style='margin:0 0 14px;font-size:14px;color:#333;'>
Totale commesse: <strong>{$total}</strong> &nbsp;•&nbsp;
<span style='color:#1e7e34;'>Inviate: {$okCount}</span> &nbsp;•&nbsp;
<span style='color:#c0392b;'>Errori: {$errCount}</span>" .
($pendingCount > 0 ? " &nbsp;•&nbsp; <span style='color:#8a6d3b;'>Non confermate: {$pendingCount}</span>" : "") .
($noPriceTotal > 0 ? " &nbsp;•&nbsp; <span style='color:#c0392b;'>Analisi No price: {$noPriceTotal}</span>" : "") . "
</p>
<table style='width:100%;border-collapse:collapse;font-size:14px;table-layout:fixed;'>
<thead>
<tr style='background:#f5f5f5;'>
<th style='padding:10px 10px;text-align:left;border-bottom:2px solid #ddd;width:14%;'>Commessa</th>
<th style='padding:10px 10px;text-align:left;border-bottom:2px solid #ddd;width:24%;'>Committente</th>
<th style='padding:10px 10px;text-align:left;border-bottom:2px solid #ddd;width:24%;'>Fatturazione</th>
<th style='padding:10px 10px;text-align:left;border-bottom:2px solid #ddd;width:24%;'>Riferimento</th>
<th style='padding:10px 10px;text-align:center;border-bottom:2px solid #ddd;width:14%;'>Status</th>
</tr>
</thead>
<tbody>{$rowsHtml}</tbody>
</table>
" . ($hasError ? "<p style='margin:18px 0 0;padding:12px;background:#fdecea;border-left:4px solid #c0392b;color:#c0392b;font-size:13px;border-radius:4px;'>⚠️ Alcune commesse non sono state inviate al LIMS. Controlla la sezione <strong>Errors</strong> nell'applicazione per i dettagli e per rilanciarle.</p>" : "") .
($hasPending ? "<p style='margin:18px 0 0;padding:12px;background:#fff8e1;border-left:4px solid #b7791f;color:#8a6d3b;font-size:13px;border-radius:4px;'>⚠️ Per alcune commesse l'esito non è ancora confermato (timeout o errore di rete durante l'invio). <strong>Non rilanciarle</strong>: ricarica la pagina tra qualche minuto e verifica lo stato.</p>" : "") . "
</div>
<div style='background:#fafafa;padding:14px 24px;font-size:12px;color:#999;border-top:1px solid #eee;'>
Messaggio automatico da SmartTRF — non rispondere a questa email.
</div>
</div>";
$subjectPrefix = $hasError ? '⚠️ Errori Export LIMS' : ($hasPending ? '⏳ Export LIMS da verificare' : '✅ Export LIMS OK');
$subject = "{$subjectPrefix} — {$total} commesse ({$okCount} ok, {$errCount} err" . ($pendingCount > 0 ? ", {$pendingCount} non confermate" : "") . ")";
$res = Mailer::send($recipients, $subject, $html);
echo json_encode([
'success' => $res['ok'],
'message' => $res['ok'] ? 'Mail inviata' : ('Mail non inviata: ' . $res['error']),
'recipients' => $recipients,
'counts' => ['ok' => $okCount, 'err' => $errCount, 'pending' => $pendingCount, 'total' => $total],
]);
+16
View File
@@ -0,0 +1,16 @@
<?php
require_once __DIR__ . '/include/headscript.php'; // autentica e dà $iduserlogin
require_once __DIR__ . '/class/db-functions.php';
header('Content-Type: application/json');
try {
$pdo = DBHandlerSelect::getInstance()->getConnection();
$stmt = $pdo->prepare(
"UPDATE auth_sessions SET last_activity = ? WHERE user_id = ? ORDER BY last_activity DESC LIMIT 1"
);
$stmt->execute([time(), $iduserlogin]);
echo json_encode(['ok' => true, 'rows' => $stmt->rowCount(), 'ts' => time()]);
} catch (\Throwable $e) {
echo json_encode(['ok' => false, 'error' => $e->getMessage()]);
}
+94 -29
View File
@@ -47,6 +47,27 @@
.filter-bar {
gap: .75rem;
}
.stat-card-extra {
background: linear-gradient(135deg, #021bff 0%, #010983 100%);
border: none;
}
.stat-card-extra .stat-label {
color: #d7d2f5;
}
.stat-card-extra .stat-value {
color: #ffffff !important;
}
.stat-card-extra small.text-muted {
color: #c9c2ec !important;
}
.kpi-row {
margin-bottom: 1rem;
}
</style>
</head>
@@ -71,7 +92,10 @@
<button class="btn btn-outline-secondary" id="btnToday">Oggi</button>
<button class="btn btn-outline-secondary" id="btnYesterday">Ieri</button>
</div>
<button class="btn btn-primary btn-sm ms-auto" id="btnRefresh">
<a href="stats_export_lims_monthly.php" class="btn btn-outline-primary btn-sm ms-auto">
<i class="bx bx-calendar-alt"></i> Vista mensile
</a>
<button class="btn btn-primary btn-sm ms-2" id="btnRefresh">
<i class="bx bx-refresh"></i> Aggiorna
</button>
</div>
@@ -79,39 +103,50 @@
</div>
<!-- ===== KPI ===== -->
<div class="row">
<div class="col-12 col-lg-3 col-md-6">
<div class="card radius-10 stat-card">
<div class="row row-cols-2 row-cols-md-3 row-cols-lg-5 g-3 kpi-row">
<div class="col">
<div class="card radius-10 stat-card stat-card-extra h-100">
<div class="card-body">
<div class="stat-label">Export (status L)</div>
<div class="stat-value text-primary" id="kpiExport">0</div>
<div class="stat-label">Campioni mese <span id="kpiMonthLabel"></span></div>
<div class="stat-value" id="kpiPartsMonth">0</div>
<small class="text-muted">Commesse: <span id="kpiExportMonth">0</span> · dal 16/07/2026</small>
</div>
</div>
</div>
<div class="col-12 col-lg-3 col-md-6">
<div class="card radius-10 stat-card">
<div class="col">
<div class="card radius-10 stat-card stat-card-extra h-100">
<div class="card-body">
<div class="stat-label">Campioni anno <span id="kpiYearLabel"></span></div>
<div class="stat-value" id="kpiPartsYear">0</div>
<small class="text-muted">Commesse: <span id="kpiExportYear">0</span> · dal 16/07/2026</small>
</div>
</div>
</div>
<div class="col">
<div class="card radius-10 stat-card h-100">
<div class="card-body">
<div class="stat-label">Campioni esportati (giorno)</div>
<div class="stat-value text-primary" id="kpiParts">0</div>
<small class="text-muted">Commesse: <span id="kpiExport">0</span></small>
</div>
</div>
</div>
<div class="col">
<div class="card radius-10 stat-card h-100">
<div class="card-body">
<div class="stat-label">Campioni inseriti LIMS</div>
<div class="stat-value text-info" id="kpiLimsSamples">0</div>
</div>
</div>
</div>
<div class="col-12 col-lg-3 col-md-6">
<div class="card radius-10 stat-card">
<div class="col">
<div class="card radius-10 stat-card h-100">
<div class="card-body">
<div class="stat-label">% Esportati / inseriti</div>
<div class="stat-value text-success" id="kpiPerc">—</div>
</div>
</div>
</div>
<div class="col-12 col-lg-3 col-md-6">
<div class="card radius-10 stat-card">
<div class="card-body">
<div class="stat-label">Clienti distinti</div>
<div class="stat-value text-warning" id="kpiClienti">0</div>
</div>
</div>
</div>
</div>
<!-- ===== DATO GIORNALIERO CAMPIONI LIMS ===== -->
@@ -180,7 +215,8 @@
<tr>
<th>ID Cliente</th>
<th>Cliente</th>
<th>Export</th>
<th>Campioni</th>
<th>Commesse</th>
</tr>
</thead>
<tbody></tbody>
@@ -201,7 +237,8 @@
<tr>
<th>ID Utente</th>
<th>Utente</th>
<th>Export</th>
<th>Campioni</th>
<th>Commesse</th>
</tr>
</thead>
<tbody></tbody>
@@ -253,6 +290,10 @@
data: 'clientname',
defaultContent: '—'
},
{
data: 'parts',
className: 'text-end'
},
{
data: 'tot',
className: 'text-end'
@@ -276,6 +317,10 @@
data: 'username',
defaultContent: '—'
},
{
data: 'parts',
className: 'text-end'
},
{
data: 'tot',
className: 'text-end'
@@ -386,32 +431,52 @@
return;
}
// KPI
$('#kpiExport').text(res.totals.export);
$('#kpiClienti').text(res.byClient.length);
// KPI — dato principale = parti/campioni, sotto le commesse
$('#kpiParts').text(res.totals.parts ?? 0);
$('#kpiExport').text(res.totals.export ?? 0);
$('#kpiPartsMonth').text(res.totalsMonth ? (res.totalsMonth.parts ?? 0) : 0);
$('#kpiExportMonth').text(res.totalsMonth ? (res.totalsMonth.export ?? 0) : 0);
$('#kpiPartsYear').text(res.totalsYear ? (res.totalsYear.parts ?? 0) : 0);
$('#kpiExportYear').text(res.totalsYear ? (res.totalsYear.export ?? 0) : 0);
$('#kpiLimsSamples').text(res.limsSamples ?? 0);
$('#limsSamplesInput').val(res.limsSamples ?? '');
// Etichette mese/anno dei box totali
if (res.month) {
const MESI_IT = ['Gennaio', 'Febbraio', 'Marzo', 'Aprile', 'Maggio', 'Giugno',
'Luglio', 'Agosto', 'Settembre', 'Ottobre', 'Novembre', 'Dicembre'
];
const mParts = res.month.split('-');
const mIdx = parseInt(mParts[1], 10) - 1;
if (mIdx >= 0 && mIdx < 12) {
$('#kpiMonthLabel').text('(' + MESI_IT[mIdx] + ' ' + mParts[0] + ')');
}
}
if (res.year) {
$('#kpiYearLabel').text('(' + res.year + ')');
}
const limsTot = parseInt(res.limsSamples ?? 0, 10);
const partsTot = parseInt(res.totals.parts ?? 0, 10);
if (limsTot > 0) {
const perc = (res.totals.export / limsTot) * 100;
const perc = (partsTot / limsTot) * 100;
$('#kpiPerc').text(perc.toFixed(1) + '%');
} else {
$('#kpiPerc').text('—');
}
// Torta esportati vs totale
renderPie(res.totals.export, limsTot);
// Torta parti esportate vs totale inserito nel LIMS
renderPie(partsTot, limsTot);
// Grafici
// Grafici — valori = campioni/parti
const clientTop = topN(res.byClient);
const userTop = topN(res.byUser);
chartClienti = renderBarChart(chartClienti, 'chartClienti',
clientTop.map(r => r.clientname ? (r.clientname + ' (' + r.idclient + ')') : ('ID ' + r.idclient)),
clientTop.map(r => r.tot), 'Export');
clientTop.map(r => r.parts), 'Campioni');
chartUtenti = renderBarChart(chartUtenti, 'chartUtenti',
userTop.map(r => r.username ? (r.username + ' (' + r.user_id + ')') : ('ID ' + r.user_id)),
userTop.map(r => r.tot), 'Export');
userTop.map(r => r.parts), 'Campioni');
// Tabelle
dtClienti.clear().rows.add(res.byClient).draw();
+76 -10
View File
@@ -15,14 +15,17 @@ try {
}
// --- Export per cliente (status = 'l', giornata su export_date) ---
// tot = numero commesse, parts = numero parti/campioni
$stmtC = $pdo->prepare("
SELECT d.idclient AS idclient,
COUNT(*) AS tot
COUNT(DISTINCT d.iddatadb) AS tot,
COUNT(ip.id) AS parts
FROM datadb d
LEFT JOIN identification_parts ip ON ip.iddatadb = d.iddatadb
WHERE d.status = 'l'
AND DATE(d.export_date) = :d
GROUP BY d.idclient
ORDER BY tot DESC
ORDER BY parts DESC
");
$stmtC->execute(['d' => $date]);
$byClient = $stmtC->fetchAll(PDO::FETCH_ASSOC);
@@ -38,16 +41,19 @@ try {
}
// --- Export per utente (status = 'l', giornata su export_date) ---
// tot = numero commesse, parts = numero parti/campioni
$stmtU = $pdo->prepare("
SELECT d.user_id AS user_id,
TRIM(CONCAT(COALESCE(u.first_name,''),' ',COALESCE(u.last_name,''))) AS username,
COUNT(*) AS tot
COUNT(DISTINCT d.iddatadb) AS tot,
COUNT(ip.id) AS parts
FROM datadb d
LEFT JOIN auth_users u ON u.id = d.user_id
LEFT JOIN identification_parts ip ON ip.iddatadb = d.iddatadb
WHERE d.status = 'l'
AND DATE(d.export_date) = :d
GROUP BY d.user_id, username
ORDER BY tot DESC
ORDER BY parts DESC
");
$stmtU->execute(['d' => $date]);
$byUser = $stmtU->fetchAll(PDO::FETCH_ASSOC);
@@ -56,6 +62,7 @@ try {
foreach ($byClient as &$r) {
$r['idclient'] = $r['idclient'] !== null ? (int)$r['idclient'] : null;
$r['tot'] = (int)$r['tot'];
$r['parts'] = (int)$r['parts'];
$nm = $clientNames[$r['idclient']] ?? '';
$r['clientname'] = $nm !== '' ? $nm : null;
}
@@ -63,6 +70,7 @@ try {
foreach ($byUser as &$r) {
$r['user_id'] = $r['user_id'] !== null ? (int)$r['user_id'] : null;
$r['tot'] = (int)$r['tot'];
$r['parts'] = (int)$r['parts'];
if (isset($r['username'])) $r['username'] = $r['username'] !== null && $r['username'] !== '' ? $r['username'] : null;
}
unset($r);
@@ -70,6 +78,60 @@ try {
// --- Totale export della giornata ---
$totExport = array_sum(array_column($byClient, 'tot'));
// --- Totale PARTI/CAMPIONI della giornata (righe identification_parts legate
// ai datadb esportati status='l' in questa giornata) ---
$stmtP = $pdo->prepare("
SELECT COUNT(*)
FROM identification_parts ip
INNER JOIN datadb d ON d.iddatadb = ip.iddatadb
WHERE d.status = 'l'
AND DATE(d.export_date) = :d
");
$stmtP->execute(['d' => $date]);
$totParts = (int)$stmtP->fetchColumn();
// --- Totale COMMESSE del MESE (status = 'l') ---
$stmtM = $pdo->prepare("
SELECT COUNT(*)
FROM datadb d
WHERE d.status = 'l'
AND DATE_FORMAT(d.export_date, '%Y-%m') = :m
");
$stmtM->execute(['m' => $d->format('Y-m')]);
$totExportMonth = (int)$stmtM->fetchColumn();
// --- Totale PARTI del MESE (status = 'l') ---
$stmtMP = $pdo->prepare("
SELECT COUNT(*)
FROM identification_parts ip
INNER JOIN datadb d ON d.iddatadb = ip.iddatadb
WHERE d.status = 'l'
AND DATE_FORMAT(d.export_date, '%Y-%m') = :m
");
$stmtMP->execute(['m' => $d->format('Y-m')]);
$totPartsMonth = (int)$stmtMP->fetchColumn();
// --- Totale COMMESSE dell'ANNO (status = 'l') ---
$stmtY = $pdo->prepare("
SELECT COUNT(*)
FROM datadb d
WHERE d.status = 'l'
AND YEAR(d.export_date) = :y
");
$stmtY->execute(['y' => $d->format('Y')]);
$totExportYear = (int)$stmtY->fetchColumn();
// --- Totale PARTI dell'ANNO (status = 'l') ---
$stmtYP = $pdo->prepare("
SELECT COUNT(*)
FROM identification_parts ip
INNER JOIN datadb d ON d.iddatadb = ip.iddatadb
WHERE d.status = 'l'
AND YEAR(d.export_date) = :y
");
$stmtYP->execute(['y' => $d->format('Y')]);
$totPartsYear = (int)$stmtYP->fetchColumn();
// --- Campioni totali inseriti nel LIMS per la giornata (tabella lims_daily_samples) ---
$stmtL = $pdo->prepare("SELECT total_samples FROM lims_daily_samples WHERE sample_date = :d LIMIT 1");
$stmtL->execute(['d' => $date]);
@@ -77,12 +139,16 @@ try {
$limsSamples = ($limsSamples !== false) ? (int)$limsSamples : null;
echo json_encode([
'success' => true,
'date' => $date,
'totals' => ['export' => (int)$totExport],
'byClient' => $byClient,
'byUser' => $byUser,
'limsSamples' => $limsSamples,
'success' => true,
'date' => $date,
'month' => $d->format('Y-m'),
'year' => (int)$d->format('Y'),
'totals' => ['export' => (int)$totExport, 'parts' => $totParts],
'totalsMonth' => ['export' => $totExportMonth, 'parts' => $totPartsMonth],
'totalsYear' => ['export' => $totExportYear, 'parts' => $totPartsYear],
'byClient' => $byClient,
'byUser' => $byUser,
'limsSamples' => $limsSamples,
]);
} catch (Exception $e) {
error_log('Stats export LIMS error: ' . $e->getMessage());
@@ -0,0 +1,440 @@
<?php include('include/headscript.php'); ?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="assets/images/favicon-32x32.png" type="image/png" />
<?php include('cssinclude.php'); ?>
<title>TRF-Project - Statistiche Export LIMS Mensili</title>
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css">
<style>
.stat-card .card-body {
padding: 1rem 1.25rem;
}
.stat-value {
font-size: 1.75rem;
font-weight: 700;
line-height: 1.1;
}
.stat-label {
font-size: 0.8rem;
text-transform: uppercase;
letter-spacing: .03em;
color: #6c757d;
}
.chart-wrap {
position: relative;
height: 420px;
}
#tblClienti,
#tblUtenti {
font-size: 13px;
}
#tblClienti th,
#tblClienti td,
#tblUtenti th,
#tblUtenti td {
vertical-align: middle;
}
.filter-bar {
gap: .75rem;
}
.month-label {
font-size: 1.05rem;
font-weight: 600;
}
.stat-card-extra {
background: linear-gradient(135deg, #021bff 0%, #010983 100%);
border: none;
}
.stat-card-extra .stat-label {
color: #c9cfff;
}
.stat-card-extra .stat-value {
color: #ffffff !important;
}
.stat-card-extra small.text-muted {
color: #b3bbff !important;
}
</style>
</head>
<body>
<div class="wrapper">
<?php include('include/navbar.php'); ?>
<?php include('include/topbar.php'); ?>
<div class="page-wrapper">
<div class="page-content">
<!-- ===== FILTRO MESE ===== -->
<div class="card radius-10">
<div class="card-body">
<div class="d-flex align-items-center flex-wrap filter-bar">
<h6 class="mb-0 me-3"><i class="bx bx-bar-chart-alt-2"></i> Statistiche Export LIMS — Mensili</h6>
<div class="d-flex align-items-center">
<label for="filterMonth" class="me-2 mb-0 fw-semibold">Mese:</label>
<input type="month" id="filterMonth" class="form-control form-control-sm" style="width:auto;">
</div>
<div class="btn-group btn-group-sm ms-2" role="group">
<button class="btn btn-outline-secondary" id="btnCurrentMonth">Mese corrente</button>
<button class="btn btn-outline-secondary" id="btnPrevMonth">Mese precedente</button>
</div>
<span class="month-label ms-2 text-primary" id="monthLabel">—</span>
<a href="stats_export_lims.php" class="btn btn-outline-primary btn-sm ms-auto">
<i class="bx bx-calendar"></i> Vista giornaliera
</a>
<button class="btn btn-primary btn-sm ms-2" id="btnRefresh">
<i class="bx bx-refresh"></i> Aggiorna
</button>
</div>
</div>
</div>
<!-- ===== KPI (una sola riga) ===== -->
<div class="row row-cols-2 row-cols-md-3 row-cols-lg-5 g-3">
<div class="col">
<div class="card radius-10 stat-card h-100">
<div class="card-body">
<div class="stat-label">Campioni mese</div>
<div class="stat-value text-primary" id="kpiParts">0</div>
<small class="text-muted">Commesse: <span id="kpiExport">0</span></small>
</div>
</div>
</div>
<div class="col">
<div class="card radius-10 stat-card stat-card-extra h-100">
<div class="card-body">
<div class="stat-label">Campioni anno <span id="yearLabel">—</span></div>
<div class="stat-value" id="kpiPartsYear">0</div>
<small class="text-muted">Commesse: <span id="kpiExportYear">0</span> · dal 16/07/2026</small>
</div>
</div>
</div>
<div class="col">
<div class="card radius-10 stat-card h-100">
<div class="card-body">
<div class="stat-label">Campioni inseriti LIMS (mese)</div>
<div class="stat-value text-info" id="kpiLimsSamples">0</div>
</div>
</div>
</div>
<div class="col">
<div class="card radius-10 stat-card h-100">
<div class="card-body">
<div class="stat-label">% Esportati / inseriti</div>
<div class="stat-value text-success" id="kpiPerc">—</div>
</div>
</div>
</div>
<div class="col">
<div class="card radius-10 stat-card h-100">
<div class="card-body">
<div class="stat-label">Clienti distinti (mese)</div>
<div class="stat-value text-warning" id="kpiClienti">0</div>
</div>
</div>
</div>
</div>
<!-- ===== GRAFICI ===== -->
<div class="row mt-1">
<div class="col-12 col-lg-6">
<div class="card radius-10">
<div class="card-header">
<h6 class="mb-0">Campioni per cliente (idclient) <small class="text-muted">— top 15</small></h6>
</div>
<div class="card-body">
<div class="chart-wrap"><canvas id="chartClienti"></canvas></div>
</div>
</div>
</div>
<div class="col-12 col-lg-6">
<div class="card radius-10">
<div class="card-header">
<h6 class="mb-0">Campioni per utente (user_id) <small class="text-muted">— top 15</small></h6>
</div>
<div class="card-body">
<div class="chart-wrap"><canvas id="chartUtenti"></canvas></div>
</div>
</div>
</div>
</div>
<!-- ===== LISTE ===== -->
<div class="row">
<div class="col-12 col-lg-6">
<div class="card radius-10">
<div class="card-header">
<h6 class="mb-0">Dettaglio per cliente</h6>
</div>
<div class="card-body">
<div class="table-responsive">
<table id="tblClienti" class="table table-striped table-bordered table-sm w-100">
<thead>
<tr>
<th>ID Cliente</th>
<th>Cliente</th>
<th>Campioni</th>
<th>Commesse</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
</div>
</div>
<div class="col-12 col-lg-6">
<div class="card radius-10">
<div class="card-header">
<h6 class="mb-0">Dettaglio per utente</h6>
</div>
<div class="card-body">
<div class="table-responsive">
<table id="tblUtenti" class="table table-striped table-bordered table-sm w-100">
<thead>
<tr>
<th>ID Utente</th>
<th>Utente</th>
<th>Campioni</th>
<th>Commesse</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="overlay toggle-icon"></div>
<a href="javaScript:;" class="back-to-top"><i class='bx bxs-up-arrow-alt'></i></a>
<?php include('include/footer.php'); ?>
</div>
<?php include('jsinclude.php'); ?>
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js"></script>
<script>
let chartClienti = null;
let chartUtenti = null;
let dtClienti = null;
let dtUtenti = null;
const MESI_IT = ['Gennaio', 'Febbraio', 'Marzo', 'Aprile', 'Maggio', 'Giugno',
'Luglio', 'Agosto', 'Settembre', 'Ottobre', 'Novembre', 'Dicembre'
];
function currentMonthStr() {
const d = new Date();
const y = d.getFullYear();
const m = String(d.getMonth() + 1).padStart(2, '0');
return `${y}-${m}`;
}
function monthLabelFromStr(monthStr) {
const parts = (monthStr || '').split('-');
if (parts.length !== 2) return '—';
const y = parseInt(parts[0], 10);
const m = parseInt(parts[1], 10);
if (isNaN(y) || isNaN(m) || m < 1 || m > 12) return '—';
return `${MESI_IT[m - 1]} ${y}`;
}
function initTables() {
dtClienti = $('#tblClienti').DataTable({
paging: false,
searching: false,
info: false,
order: [
[2, 'desc']
],
columns: [{
data: 'idclient'
},
{
data: 'clientname',
defaultContent: '—'
},
{
data: 'parts',
className: 'text-end'
},
{
data: 'tot',
className: 'text-end'
}
],
language: {
emptyTable: 'Nessun export in questo mese'
}
});
dtUtenti = $('#tblUtenti').DataTable({
paging: false,
searching: false,
info: false,
order: [
[2, 'desc']
],
columns: [{
data: 'user_id'
},
{
data: 'username',
defaultContent: '—'
},
{
data: 'parts',
className: 'text-end'
},
{
data: 'tot',
className: 'text-end'
}
],
language: {
emptyTable: 'Nessun export in questo mese'
}
});
}
function renderBarChart(existing, canvasId, labels, values, label) {
if (existing) existing.destroy();
const ctx = document.getElementById(canvasId).getContext('2d');
return new Chart(ctx, {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: label,
data: values,
borderWidth: 1
}]
},
options: {
indexAxis: 'y',
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
display: false
}
},
scales: {
x: {
beginAtZero: true,
ticks: {
precision: 0
}
}
}
}
});
}
const CHART_TOP_N = 15;
function topN(arr) {
return arr.slice(0, CHART_TOP_N);
}
function loadStats() {
const month = $('#filterMonth').val() || currentMonthStr();
$('#monthLabel').text(monthLabelFromStr(month));
$.getJSON('stats_export_lims_monthly_data.php', {
month: month
}, function(res) {
if (!res || !res.success) {
Swal.fire('Errore', (res && res.message) || 'Errore nel caricamento', 'error');
return;
}
// KPI mese — dato principale = campioni/parti, sotto le commesse
$('#kpiParts').text(res.totals.parts ?? 0);
$('#kpiExport').text(res.totals.export ?? 0);
$('#kpiClienti').text(res.byClient.length);
$('#kpiLimsSamples').text(res.limsSamples ?? 0);
const limsTot = parseInt(res.limsSamples ?? 0, 10);
const partsTot = parseInt(res.totals.parts ?? 0, 10);
if (limsTot > 0) {
const perc = (partsTot / limsTot) * 100;
$('#kpiPerc').text(perc.toFixed(1) + '%');
} else {
$('#kpiPerc').text('—');
}
// Box annuale — campioni + commesse
$('#kpiPartsYear').text(res.totalsYear ? (res.totalsYear.parts ?? 0) : 0);
$('#kpiExportYear').text(res.totalsYear ? (res.totalsYear.export ?? 0) : 0);
$('#yearLabel').text(res.year);
// Grafici — valori = campioni/parti
const clientTop = topN(res.byClient);
const userTop = topN(res.byUser);
chartClienti = renderBarChart(chartClienti, 'chartClienti',
clientTop.map(r => r.clientname ? (r.clientname + ' (' + r.idclient + ')') : ('ID ' + r.idclient)),
clientTop.map(r => r.parts), 'Campioni');
chartUtenti = renderBarChart(chartUtenti, 'chartUtenti',
userTop.map(r => r.username ? (r.username + ' (' + r.user_id + ')') : ('ID ' + r.user_id)),
userTop.map(r => r.parts), 'Campioni');
// Tabelle
dtClienti.clear().rows.add(res.byClient).draw();
dtUtenti.clear().rows.add(res.byUser).draw();
}).fail(function(xhr) {
Swal.fire('Errore', 'Richiesta fallita: ' + xhr.status, 'error');
});
}
$(document).ready(function() {
$('#filterMonth').val(currentMonthStr());
initTables();
loadStats();
$('#btnRefresh').on('click', loadStats);
$('#filterMonth').on('change', loadStats);
$('#btnCurrentMonth').on('click', function() {
$('#filterMonth').val(currentMonthStr());
loadStats();
});
$('#btnPrevMonth').on('click', function() {
const cur = $('#filterMonth').val() || currentMonthStr();
const parts = cur.split('-');
let y = parseInt(parts[0], 10);
let m = parseInt(parts[1], 10);
m -= 1;
if (m < 1) {
m = 12;
y -= 1;
}
$('#filterMonth').val(`${y}-${String(m).padStart(2, '0')}`);
loadStats();
});
});
</script>
</body>
</html>
@@ -0,0 +1,137 @@
<?php
include('include/headscript.php');
header('Content-Type: application/json');
$dbHandler = DBHandlerSelect::getInstance();
$pdo = $dbHandler->getConnection();
try {
// Mese richiesto (default mese corrente). Formato atteso: Y-m
$month = $_GET['month'] ?? date('Y-m');
$dm = DateTime::createFromFormat('Y-m', $month);
if (!$dm || $dm->format('Y-m') !== $month) {
throw new Exception('Mese non valido');
}
$year = $dm->format('Y');
// --- Export per cliente (status = 'l', filtro mese) ---
// tot = numero commesse, parts = numero parti/campioni
$stmtC = $pdo->prepare("
SELECT d.idclient AS idclient,
COUNT(DISTINCT d.iddatadb) AS tot,
COUNT(ip.id) AS parts
FROM datadb d
LEFT JOIN identification_parts ip ON ip.iddatadb = d.iddatadb
WHERE d.status = 'l'
AND DATE_FORMAT(d.export_date, '%Y-%m') = :m
GROUP BY d.idclient
ORDER BY parts DESC
");
$stmtC->execute(['m' => $month]);
$byClient = $stmtC->fetchAll(PDO::FETCH_ASSOC);
// --- Risolvi Nominativo cliente dalla cache locale ---
$clientNames = [];
$cacheFile = __DIR__ . '/cache/clienti.json';
if (is_file($cacheFile)) {
$cache = json_decode(file_get_contents($cacheFile), true);
foreach (($cache['value'] ?? []) as $c) {
$clientNames[(int)($c['IdCliente'] ?? 0)] = trim($c['Nominativo'] ?? '');
}
}
// --- Export per utente (status = 'l', filtro mese) ---
// tot = numero commesse, parts = numero parti/campioni
$stmtU = $pdo->prepare("
SELECT d.user_id AS user_id,
TRIM(CONCAT(COALESCE(u.first_name,''),' ',COALESCE(u.last_name,''))) AS username,
COUNT(DISTINCT d.iddatadb) AS tot,
COUNT(ip.id) AS parts
FROM datadb d
LEFT JOIN auth_users u ON u.id = d.user_id
LEFT JOIN identification_parts ip ON ip.iddatadb = d.iddatadb
WHERE d.status = 'l'
AND DATE_FORMAT(d.export_date, '%Y-%m') = :m
GROUP BY d.user_id, username
ORDER BY parts DESC
");
$stmtU->execute(['m' => $month]);
$byUser = $stmtU->fetchAll(PDO::FETCH_ASSOC);
// Normalizza tipi
foreach ($byClient as &$r) {
$r['idclient'] = $r['idclient'] !== null ? (int)$r['idclient'] : null;
$r['tot'] = (int)$r['tot'];
$r['parts'] = (int)$r['parts'];
$nm = $clientNames[$r['idclient']] ?? '';
$r['clientname'] = $nm !== '' ? $nm : null;
}
unset($r);
foreach ($byUser as &$r) {
$r['user_id'] = $r['user_id'] !== null ? (int)$r['user_id'] : null;
$r['tot'] = (int)$r['tot'];
$r['parts'] = (int)$r['parts'];
if (isset($r['username'])) $r['username'] = $r['username'] !== null && $r['username'] !== '' ? $r['username'] : null;
}
unset($r);
// --- Totale COMMESSE del mese ---
$totExport = array_sum(array_column($byClient, 'tot'));
// --- Totale PARTI/CAMPIONI del mese (status = 'l') ---
$stmtP = $pdo->prepare("
SELECT COUNT(*)
FROM identification_parts ip
INNER JOIN datadb d ON d.iddatadb = ip.iddatadb
WHERE d.status = 'l'
AND DATE_FORMAT(d.export_date, '%Y-%m') = :m
");
$stmtP->execute(['m' => $month]);
$totParts = (int)$stmtP->fetchColumn();
// --- Totale COMMESSE dell'ANNO del mese selezionato ---
$stmtY = $pdo->prepare("
SELECT COUNT(*)
FROM datadb d
WHERE d.status = 'l'
AND YEAR(d.export_date) = :y
");
$stmtY->execute(['y' => $year]);
$totExportYear = (int)$stmtY->fetchColumn();
// --- Totale PARTI dell'ANNO del mese selezionato ---
$stmtYP = $pdo->prepare("
SELECT COUNT(*)
FROM identification_parts ip
INNER JOIN datadb d ON d.iddatadb = ip.iddatadb
WHERE d.status = 'l'
AND YEAR(d.export_date) = :y
");
$stmtYP->execute(['y' => $year]);
$totPartsYear = (int)$stmtYP->fetchColumn();
// --- Campioni LIMS: somma dei total_samples di tutti i giorni del mese ---
$stmtL = $pdo->prepare("
SELECT COALESCE(SUM(total_samples), 0)
FROM lims_daily_samples
WHERE DATE_FORMAT(sample_date, '%Y-%m') = :m
");
$stmtL->execute(['m' => $month]);
$limsSamples = (int)$stmtL->fetchColumn();
echo json_encode([
'success' => true,
'month' => $month,
'year' => (int)$year,
'totals' => ['export' => (int)$totExport, 'parts' => $totParts],
'totalsYear' => ['export' => $totExportYear, 'parts' => $totPartsYear],
'byClient' => $byClient,
'byUser' => $byUser,
'limsSamples' => $limsSamples,
]);
} catch (Exception $e) {
error_log('Stats export LIMS monthly error: ' . $e->getMessage());
echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
+284 -82
View File
@@ -227,8 +227,9 @@ function fixedDefaultValue(array $f): string
// ── Build lookup maps: id → label for fixed fields ──
$fixedLookup = []; // e.g. $fixedLookup['MoltiplicatorePrezzo'][2] = 'Urgente (1.5x)'
function loadCacheJson(string $path): ?array {
if (file_exists($path) && (time() - filemtime($path) < 3600)) {
function loadCacheJson(string $path): ?array
{
if (file_exists($path) && (time() - filemtime($path) < 7200)) {
return json_decode(file_get_contents($path), true);
}
return null;
@@ -278,7 +279,8 @@ foreach ($clienteIds as $cid) {
}
// Helper: resolve fixed field id → label
function resolveFixedValue(string $key, $val, array $fixedLookup): string {
function resolveFixedValue(string $key, $val, array $fixedLookup): string
{
if ($val === '' || $val === null) return '';
if (isset($fixedLookup[$key][(int)$val])) return $fixedLookup[$key][(int)$val];
return (string)$val;
@@ -649,6 +651,7 @@ function resolveFixedValue(string $key, $val, array $fixedLookup): string {
.grid-top {
display: none !important;
}
.grid-top-original {
display: flex;
align-items: stretch;
@@ -819,12 +822,12 @@ function resolveFixedValue(string $key, $val, array $fixedLookup): string {
}
.action-btn {
padding: 6px 8px;
margin-right: 5px;
padding: 6px 4px;
margin-right: 3px;
border: none;
border-radius: 5px;
cursor: pointer;
width: 35px;
width: 26px;
box-sizing: border-box;
}
@@ -952,15 +955,35 @@ function resolveFixedValue(string $key, $val, array $fixedLookup): string {
}
/* Hide grid-top (propagate row) */
.grid-top { display: none !important; }
.grid-top {
display: none !important;
}
/* Text cells styling */
.grid-row .grid-cell span { font-size: 12px; padding: 2px 4px; }
.propagate-btn { display: none !important; }
.button-cell { flex: 0 0 120px !important; }
.grid-row .grid-cell span {
font-size: 12px;
padding: 2px 4px;
}
.propagate-btn {
display: none !important;
}
.button-cell {
flex: 0 0 120px !important;
}
/* View modals — ensure they sit above backdrop */
#partsViewModal, #photosViewModal { z-index: 1060 !important; }
.modal-backdrop { z-index: 1050 !important; }
#partsViewModal,
#photosViewModal,
#revertStatusModal {
z-index: 1060 !important;
}
.modal-backdrop {
z-index: 1050 !important;
}
/* ── Grid filter row ── */
.grid-filter-row {
background: #f0f4f8 !important;
@@ -969,12 +992,15 @@ function resolveFixedValue(string $key, $val, array $fixedLookup): string {
top: 0;
z-index: 5;
}
.grid-filter-row:hover {
background: #f0f4f8 !important;
}
.grid-filter-row .grid-cell {
padding: 4px 6px !important;
}
.grid-filter-input {
width: 100% !important;
padding: 3px 6px !important;
@@ -985,30 +1011,36 @@ function resolveFixedValue(string $key, $val, array $fixedLookup): string {
color: #333 !important;
box-sizing: border-box;
}
.grid-filter-input:focus {
border-color: #80bdff !important;
box-shadow: 0 0 0 2px rgba(0,123,255,.15) !important;
box-shadow: 0 0 0 2px rgba(0, 123, 255, .15) !important;
outline: none !important;
}
.grid-filter-input::placeholder {
color: #adb5bd;
font-style: italic;
}
.grid-filter-row .grid-filter-input.has-value {
border-color: #0d6efd !important;
background: #f0f7ff !important;
}
select.grid-filter-input {
cursor: pointer;
padding-right: 18px !important;
appearance: auto;
}
/* Select2 inside filter row */
.grid-filter-row .select2-container {
width: 100% !important;
min-width: 0;
flex: 1;
}
.grid-filter-row .select2-container .select2-selection--single {
height: 26px !important;
min-height: 26px !important;
@@ -1020,6 +1052,7 @@ function resolveFixedValue(string $key, $val, array $fixedLookup): string {
border-radius: 3px;
position: relative;
}
.grid-filter-row .select2-container .select2-selection__rendered {
line-height: 1 !important;
font-size: 11px;
@@ -1029,32 +1062,39 @@ function resolveFixedValue(string $key, $val, array $fixedLookup): string {
text-overflow: ellipsis;
white-space: nowrap;
}
.grid-filter-row .select2-container .select2-selection__arrow {
height: 26px !important;
position: absolute;
right: 2px;
top: 0;
}
.grid-filter-row .filter-wrap {
overflow: visible;
}
/* Hide our clear button when Select2 is active — Select2 has its own allowClear */
.filter-wrap:has(.select2-container) .filter-clear-btn {
display: none;
}
.grid-filter-row .grid-cell {
overflow: visible !important;
}
.filter-wrap {
display: flex;
align-items: center;
gap: 2px;
width: 100%;
}
.filter-wrap .grid-filter-input {
flex: 1;
min-width: 0;
}
.filter-clear-btn {
flex-shrink: 0;
border: none;
@@ -1066,12 +1106,15 @@ function resolveFixedValue(string $key, $val, array $fixedLookup): string {
line-height: 1;
border-radius: 3px;
}
.filter-clear-btn:hover {
background: #c82333;
}
.grid-filter-row .grid-cell {
background: #f0f4f8 !important;
}
/* First sticky cell fills full row height */
.grid-filter-row .grid-cell.button-cell {
align-self: stretch;
@@ -1089,21 +1132,25 @@ function resolveFixedValue(string $key, $val, array $fixedLookup): string {
font-size: 13px;
color: #495057;
}
.pager-rows-per-page {
display: flex;
align-items: center;
gap: 8px;
}
.pager-label {
font-weight: 500;
white-space: nowrap;
}
.pager-limit-group {
display: inline-flex;
border: 1px solid #ced4da;
border-radius: 4px;
overflow: hidden;
}
.pager-limit-btn {
padding: 3px 10px;
text-decoration: none;
@@ -1112,24 +1159,41 @@ function resolveFixedValue(string $key, $val, array $fixedLookup): string {
transition: background .15s, color .15s;
font-weight: 500;
}
.pager-limit-btn:last-child { border-right: none; }
.pager-limit-btn:hover { background: #e9ecef; text-decoration: none; color: #212529; }
.pager-limit-btn:last-child {
border-right: none;
}
.pager-limit-btn:hover {
background: #e9ecef;
text-decoration: none;
color: #212529;
}
.pager-limit-btn.active {
background: #0d6efd;
color: #fff;
}
.pager-limit-btn.active:hover { background: #0b5ed7; color: #fff; }
.pager-limit-btn.active:hover {
background: #0b5ed7;
color: #fff;
}
.pager-nav {
display: flex;
align-items: center;
gap: 4px;
}
.pager-info {
margin-right: 8px;
font-weight: 500;
white-space: nowrap;
}
.pager-btn, .pager-num {
.pager-btn,
.pager-num {
display: inline-flex;
align-items: center;
justify-content: center;
@@ -1143,16 +1207,25 @@ function resolveFixedValue(string $key, $val, array $fixedLookup): string {
font-weight: 500;
transition: background .15s, color .15s, border-color .15s;
}
.pager-btn:hover, .pager-num:hover { background: #e9ecef; text-decoration: none; color: #212529; }
.pager-btn:hover,
.pager-num:hover {
background: #e9ecef;
text-decoration: none;
color: #212529;
}
.pager-num.active {
background: #0d6efd;
color: #fff;
border-color: #0d6efd;
}
.pager-btn.disabled {
pointer-events: none;
opacity: .4;
}
.pager-dots {
padding: 0 2px;
color: #adb5bd;
@@ -1170,7 +1243,8 @@ function resolveFixedValue(string $key, $val, array $fixedLookup): string {
<div class="page-content">
<div class="mb-3 text d-flex align-items-center gap-2">
<a href="imported.php?id=<?= $template_id ?>" class="btn btn-warning me-2">Imported (i)</a>
<a href="tolims.php?id=<?= $template_id ?>" class="btn btn-success">To LIMS (l)</a>
<a href="tolims.php?id=<?= $template_id ?>" class="btn btn-success me-2">To LIMS (l)</a>
<a href="errors.php?id=<?= $template_id ?>" class="btn btn-danger">Errors (x)</a>
<span class="ms-3">
<label class="form-check-label" style="font-size: 13px; cursor: pointer;">
<?php
@@ -1188,48 +1262,48 @@ function resolveFixedValue(string $key, $val, array $fixedLookup): string {
</span>
</div>
<?php
$baseQuery = $_GET;
unset($baseQuery['limit'], $baseQuery['page']);
$pageQuery = $_GET;
unset($pageQuery['page']);
$pageBase = 'tolims.php?' . http_build_query($pageQuery);
$fromRow = ($page - 1) * $perPage + 1;
$toRow = min($page * $perPage, $totalRows);
$baseQuery = $_GET;
unset($baseQuery['limit'], $baseQuery['page']);
$pageQuery = $_GET;
unset($pageQuery['page']);
$pageBase = 'tolims.php?' . http_build_query($pageQuery);
$fromRow = ($page - 1) * $perPage + 1;
$toRow = min($page * $perPage, $totalRows);
?>
<div class="pager-bar mb-2">
<div class="pager-rows-per-page">
<span class="pager-label">Rows per page</span>
<div class="pager-limit-group">
<?php foreach ($allowedLimits as $lim):
$isActive = ($perPage === $lim);
$url = 'tolims.php?' . http_build_query(array_merge($baseQuery, ['limit' => $lim]));
?>
<a href="<?= htmlspecialchars($url) ?>" class="pager-limit-btn <?= $isActive ? 'active' : '' ?>"><?= $lim ?></a>
<?php endforeach; ?>
<?php foreach ($allowedLimits as $lim):
$isActive = ($perPage === $lim);
$url = 'tolims.php?' . http_build_query(array_merge($baseQuery, ['limit' => $lim]));
?>
<a href="<?= htmlspecialchars($url) ?>" class="pager-limit-btn <?= $isActive ? 'active' : '' ?>"><?= $lim ?></a>
<?php endforeach; ?>
</div>
</div>
<?php if ($totalPages > 1): ?>
<div class="pager-nav">
<span class="pager-info"><?= $fromRow ?>–<?= $toRow ?> of <?= $totalRows ?></span>
<a href="<?= htmlspecialchars($pageBase . '&page=1') ?>" class="pager-btn <?= $page <= 1 ? 'disabled' : '' ?>" title="First"><i class="fas fa-angle-double-left"></i></a>
<a href="<?= htmlspecialchars($pageBase . '&page=' . ($page - 1)) ?>" class="pager-btn <?= $page <= 1 ? 'disabled' : '' ?>" title="Previous"><i class="fas fa-angle-left"></i></a>
<?php
$startPage = max(1, $page - 2);
$endPage = min($totalPages, $page + 2);
if ($startPage > 1): ?>
<a href="<?= htmlspecialchars($pageBase . '&page=1') ?>" class="pager-num">1</a>
<?php if ($startPage > 2): ?><span class="pager-dots">...</span><?php endif; ?>
<?php endif;
for ($p = $startPage; $p <= $endPage; $p++): ?>
<a href="<?= htmlspecialchars($pageBase . '&page=' . $p) ?>" class="pager-num <?= $p === $page ? 'active' : '' ?>"><?= $p ?></a>
<?php endfor;
if ($endPage < $totalPages): ?>
<?php if ($endPage < $totalPages - 1): ?><span class="pager-dots">...</span><?php endif; ?>
<a href="<?= htmlspecialchars($pageBase . '&page=' . $totalPages) ?>" class="pager-num"><?= $totalPages ?></a>
<?php endif; ?>
<a href="<?= htmlspecialchars($pageBase . '&page=' . ($page + 1)) ?>" class="pager-btn <?= $page >= $totalPages ? 'disabled' : '' ?>" title="Next"><i class="fas fa-angle-right"></i></a>
<a href="<?= htmlspecialchars($pageBase . '&page=' . $totalPages) ?>" class="pager-btn <?= $page >= $totalPages ? 'disabled' : '' ?>" title="Last"><i class="fas fa-angle-double-right"></i></a>
</div>
<div class="pager-nav">
<span class="pager-info"><?= $fromRow ?>–<?= $toRow ?> of <?= $totalRows ?></span>
<a href="<?= htmlspecialchars($pageBase . '&page=1') ?>" class="pager-btn <?= $page <= 1 ? 'disabled' : '' ?>" title="First"><i class="fas fa-angle-double-left"></i></a>
<a href="<?= htmlspecialchars($pageBase . '&page=' . ($page - 1)) ?>" class="pager-btn <?= $page <= 1 ? 'disabled' : '' ?>" title="Previous"><i class="fas fa-angle-left"></i></a>
<?php
$startPage = max(1, $page - 2);
$endPage = min($totalPages, $page + 2);
if ($startPage > 1): ?>
<a href="<?= htmlspecialchars($pageBase . '&page=1') ?>" class="pager-num">1</a>
<?php if ($startPage > 2): ?><span class="pager-dots">...</span><?php endif; ?>
<?php endif;
for ($p = $startPage; $p <= $endPage; $p++): ?>
<a href="<?= htmlspecialchars($pageBase . '&page=' . $p) ?>" class="pager-num <?= $p === $page ? 'active' : '' ?>"><?= $p ?></a>
<?php endfor;
if ($endPage < $totalPages): ?>
<?php if ($endPage < $totalPages - 1): ?><span class="pager-dots">...</span><?php endif; ?>
<a href="<?= htmlspecialchars($pageBase . '&page=' . $totalPages) ?>" class="pager-num"><?= $totalPages ?></a>
<?php endif; ?>
<a href="<?= htmlspecialchars($pageBase . '&page=' . ($page + 1)) ?>" class="pager-btn <?= $page >= $totalPages ? 'disabled' : '' ?>" title="Next"><i class="fas fa-angle-right"></i></a>
<a href="<?= htmlspecialchars($pageBase . '&page=' . $totalPages) ?>" class="pager-btn <?= $page >= $totalPages ? 'disabled' : '' ?>" title="Last"><i class="fas fa-angle-double-right"></i></a>
</div>
<?php endif; ?>
</div>
<div class="card radius-10">
@@ -1512,14 +1586,16 @@ function resolveFixedValue(string $key, $val, array $fixedLookup): string {
<!-- Filter row (server-side) -->
<?php
// Helper: wrap filter element with clear button
function wrapFilter(string $inner, bool $hasValue): string {
function wrapFilter(string $inner, bool $hasValue): string
{
$btn = $hasValue
? "<button type='button' class='filter-clear-btn' onclick='clearOneFilter(this)' title='Clear'>&times;</button>"
: '';
return "<div class='filter-wrap'>{$inner}{$btn}</div>";
}
// Helper: render a select filter from a lookup array
function renderFilterSelect(string $name, array $options, string $currentVal, string $style = ''): string {
function renderFilterSelect(string $name, array $options, string $currentVal, string $style = ''): string
{
$html = "<select class='grid-filter-input' name='" . htmlspecialchars($name) . "' style='" . htmlspecialchars($style) . "' onchange='submitFilters()'>";
$html .= "<option value=''>All</option>";
foreach ($options as $id => $label) {
@@ -1530,12 +1606,14 @@ function resolveFixedValue(string $key, $val, array $fixedLookup): string {
return wrapFilter($html, $currentVal !== '');
}
// Helper: render a text filter
function renderFilterInput(string $name, string $currentVal): string {
function renderFilterInput(string $name, string $currentVal): string
{
$inner = "<input type='text' class='grid-filter-input' name='" . htmlspecialchars($name) . "' value='" . htmlspecialchars($currentVal) . "' placeholder='&#8981;'>";
return wrapFilter($inner, $currentVal !== '');
}
// Helper: render a select filter populated by JS
function renderFilterSelectJS(string $name, string $currentVal, string $jsClass, string $dataAttr = ''): string {
function renderFilterSelectJS(string $name, string $currentVal, string $jsClass, string $dataAttr = ''): string
{
$html = "<select class='grid-filter-input {$jsClass}' name='" . htmlspecialchars($name) . "' {$dataAttr} onchange='submitFilters()'>";
$html .= "<option value=''>All</option>";
if ($currentVal !== '') {
@@ -1639,6 +1717,8 @@ function resolveFixedValue(string $key, $val, array $fixedLookup): string {
<div class="grid-cell button-cell" style="flex: 0 0 120px; position: relative;">
<button type="button" class="photos-btn action-btn" data-row="<?= $index ?>" data-iddatadb="<?= $row['iddatadb'] ?>" title="Photos" style="background: #007bff; color: white; border: none; border-radius: 5px; cursor: pointer;"><i class="fas fa-camera"></i></button>
<button type="button" class="parts-btn action-btn" data-row="<?= $index ?>" data-iddatadb="<?= $row['iddatadb'] ?>" title="Parts" style="background: #ffc107; color: white; border: none; border-radius: 5px; cursor: pointer;"><i class="fas fa-puzzle-piece"></i></button>
<button type="button" class="revert-btn action-btn" data-row="<?= $index ?>" data-iddatadb="<?= $row['iddatadb'] ?>" data-commessaweb="<?= htmlspecialchars($row['commessaweb'] ?? '', ENT_QUOTES) ?>" title="Riporta a Imported (i)" style="background: #fd7e14; color: white; border: none; border-radius: 5px; cursor: pointer;"><i class="fas fa-rotate-left"></i></button>
<a href="download_logs.php?iddatadb=<?= (int)$row['iddatadb'] ?>" class="logs-btn action-btn" title="Scarica log LIMS" style="background:#17a2b8; color:white; border:none; border-radius:5px; cursor:pointer; display:inline-flex; align-items:center; justify-content:center; text-decoration:none;"><i class="fas fa-file-download"></i></a>
</div>
<?php if ($mainFieldMapping):
$detail = array_filter($manualDetails, fn($d) => $d['mapping_id'] == $mainFieldMapping['id'] && $d['datadb_id'] == $row['iddatadb']);
@@ -1775,6 +1855,25 @@ function resolveFixedValue(string $key, $val, array $fixedLookup): string {
</div>
</div>
</div>
<!-- Revert to Imported Modal -->
<div class="modal fade" id="revertStatusModal" tabindex="-1" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title"><i class="fas fa-rotate-left" style="color:#fd7e14;"></i> Riporta a Imported</h5>
<button type="button" class="btn-close close-revert-modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<p>Vuoi riportare questo record allo stato <strong>Imported (i)</strong>?</p>
<p class="text-muted" id="revertRecordInfo" style="font-size:13px;"></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary btn-sm close-revert-modal">Annulla</button>
<button type="button" class="btn btn-warning btn-sm" id="confirmRevertBtn"><i class="fas fa-check"></i> Conferma</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
@@ -1792,10 +1891,14 @@ function resolveFixedValue(string $key, $val, array $fixedLookup): string {
(function() {
const sceltaEls = document.querySelectorAll('.scelta-value');
const fieldIds = new Set();
sceltaEls.forEach(el => { if (el.dataset.fieldId) fieldIds.add(el.dataset.fieldId); });
sceltaEls.forEach(el => {
if (el.dataset.fieldId) fieldIds.add(el.dataset.fieldId);
});
if (!fieldIds.size) return;
$.getJSON('get_customfield_values.php', { field_ids: [...fieldIds].join(',') }, function(data) {
$.getJSON('get_customfield_values.php', {
field_ids: [...fieldIds].join(',')
}, function(data) {
const lookup = {};
for (const [fid, values] of Object.entries(data)) {
lookup[fid] = {};
@@ -1836,8 +1939,18 @@ function resolveFixedValue(string $key, $val, array $fixedLookup): string {
url: 'search_customfield_values.php',
dataType: 'json',
delay: 150,
data: function(params) { return { field_id: fieldId, q: params.term || '', limit: 20 }; },
processResults: function(data) { return { results: data.results || [] }; },
data: function(params) {
return {
field_id: fieldId,
q: params.term || '',
limit: 20
};
},
processResults: function(data) {
return {
results: data.results || []
};
},
cache: true
}
});
@@ -1859,16 +1972,16 @@ function resolveFixedValue(string $key, $val, array $fixedLookup): string {
const promises = [...ids].map(id =>
fetch('search_clienti.php?id=' + encodeURIComponent(id))
.then(r => r.json())
.then(json => {
const item = (json.results || [])[0];
if (item) {
document.querySelectorAll(`.client-text[data-client-id="${id}"]`).forEach(el => {
el.textContent = item.text;
});
}
})
.catch(() => {})
.then(r => r.json())
.then(json => {
const item = (json.results || [])[0];
if (item) {
document.querySelectorAll(`.client-text[data-client-id="${id}"]`).forEach(el => {
el.textContent = item.text;
});
}
})
.catch(() => {})
);
Promise.all(promises);
})();
@@ -1893,8 +2006,17 @@ function resolveFixedValue(string $key, $val, array $fixedLookup): string {
url: 'search_clienti.php',
dataType: 'json',
delay: 150,
data: function(params) { return { q: params.term || '', limit: 20 }; },
processResults: function(data) { return { results: data.results || [] }; },
data: function(params) {
return {
q: params.term || '',
limit: 20
};
},
processResults: function(data) {
return {
results: data.results || []
};
},
cache: true
}
});
@@ -1909,8 +2031,17 @@ function resolveFixedValue(string $key, $val, array $fixedLookup): string {
url: 'search_clienti.php',
dataType: 'json',
delay: 150,
data: function(params) { return { q: params.term || '', limit: 20 }; },
processResults: function(data) { return { results: data.results || [] }; },
data: function(params) {
return {
q: params.term || '',
limit: 20
};
},
processResults: function(data) {
return {
results: data.results || []
};
},
cache: true
}
});
@@ -1942,14 +2073,16 @@ function resolveFixedValue(string $key, $val, array $fixedLookup): string {
$('#partsViewContent').html('<i class="fas fa-spinner fa-spin"></i> Loading...');
new bootstrap.Modal(document.getElementById('partsViewModal')).show();
$.getJSON('load_parts.php', { iddatadb: iddatadb }, function(data) {
$.getJSON('load_parts.php', {
iddatadb: iddatadb
}, function(data) {
if (!data.parts || data.parts.length === 0) {
$('#partsViewContent').html('<p class="text-muted">No parts found.</p>');
return;
}
let html = '<table class="table table-sm table-bordered"><thead><tr><th>#</th><th>Description</th><th>Material</th><th>Color</th><th>Matrice</th><th>Note</th></tr></thead><tbody>';
data.parts.forEach(p => {
html += '<tr><td>' + (p.part_number||'') + '</td><td>' + (p.part_description||'') + '</td><td>' + (p.material||'') + '</td><td>' + (p.color||'') + '</td><td>' + (p.idmatrice||'') + '</td><td>' + (p.note||'') + '</td></tr>';
html += '<tr><td>' + (p.part_number || '') + '</td><td>' + (p.part_description || '') + '</td><td>' + (p.material || '') + '</td><td>' + (p.color || '') + '</td><td>' + (p.idmatrice || '') + '</td><td>' + (p.note || '') + '</td></tr>';
});
html += '</tbody></table>';
$('#partsViewContent').html(html);
@@ -1964,7 +2097,9 @@ function resolveFixedValue(string $key, $val, array $fixedLookup): string {
$('#photosViewContent').html('<i class="fas fa-spinner fa-spin"></i> Loading...');
new bootstrap.Modal(document.getElementById('photosViewModal')).show();
$.getJSON('load_photo.php', { iddatadb: iddatadb }, function(data) {
$.getJSON('load_photo.php', {
iddatadb: iddatadb
}, function(data) {
if (!data.success || !data.photos || data.photos.length === 0) {
$('#photosViewContent').html('<p class="text-muted">No photos found.</p>');
return;
@@ -1979,14 +2114,74 @@ function resolveFixedValue(string $key, $val, array $fixedLookup): string {
$('#photosViewContent').html('<p class="text-danger">Error loading photos.</p>');
});
});
// ── Revert status to Imported (i) ──
let revertIddatadb = null;
$(document).on('click', '.revert-btn', function() {
revertIddatadb = $(this).data('iddatadb');
const cw = $(this).data('commessaweb') || '';
$('#revertRecordInfo').text(cw ? ('Commessa: ' + cw) : ('ID: ' + revertIddatadb));
new bootstrap.Modal(document.getElementById('revertStatusModal')).show();
});
$(document).on('click', '.close-revert-modal', function() {
const modal = bootstrap.Modal.getInstance(document.getElementById('revertStatusModal'));
if (modal) modal.hide();
});
$(document).on('hidden.bs.modal', '#revertStatusModal', function() {
$('.modal-backdrop').remove();
$('body').removeClass('modal-open').css('padding-right', '');
});
$(document).on('click', '#confirmRevertBtn', function() {
if (!revertIddatadb) return;
const $btn = $(this);
$btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Attendere...');
$.ajax({
url: 'revert_status.php',
method: 'POST',
dataType: 'json',
data: {
iddatadb: revertIddatadb,
status: 'i'
},
success: function(res) {
if (res && res.success) {
const modal = bootstrap.Modal.getInstance(document.getElementById('revertStatusModal'));
if (modal) modal.hide();
const $row = $('.grid-row[data-id="' + revertIddatadb + '"]');
$row.addClass('flash-success');
setTimeout(function() {
$row.fadeOut(300, function() {
$row.remove();
});
}, 400);
} else {
alert('Errore: ' + ((res && res.message) ? res.message : 'operazione non riuscita'));
}
},
error: function() {
alert('Errore di rete durante l\'operazione.');
},
complete: function() {
$btn.prop('disabled', false).html('<i class="fas fa-check"></i> Conferma');
}
});
});
});
// ── Column filters ──
function clearOneFilter(btn) {
const wrap = btn.closest('.filter-wrap');
const el = wrap.querySelector('.grid-filter-input');
if (el) { el.value = ''; submitFilters(); }
if (el) {
el.value = '';
submitFilters();
}
}
function submitFilters() {
const filterRow = document.getElementById('gridFilterRow');
if (!filterRow) return;
@@ -2004,7 +2199,10 @@ function resolveFixedValue(string $key, $val, array $fixedLookup): string {
const filterRow = document.getElementById('gridFilterRow');
if (!filterRow) return;
filterRow.addEventListener('keydown', function(e) {
if (e.key === 'Enter') { e.preventDefault(); submitFilters(); }
if (e.key === 'Enter') {
e.preventDefault();
submitFilters();
}
});
filterRow.querySelectorAll('.grid-filter-input').forEach(el => {
el.classList.toggle('has-value', el.value.trim() !== '');
@@ -2016,7 +2214,10 @@ function resolveFixedValue(string $key, $val, array $fixedLookup): string {
// ── Column resize ──
(function() {
const resizers = document.querySelectorAll('.resizer');
let currentResizer = null, startX = 0, startWidth = 0, columnIndex = null;
let currentResizer = null,
startX = 0,
startWidth = 0,
columnIndex = null;
function resize(e) {
if (!currentResizer || columnIndex === null) return;
@@ -2059,4 +2260,5 @@ function resolveFixedValue(string $key, $val, array $fixedLookup): string {
})();
</script>
</body>
</html>
</html>
+8
View File
@@ -0,0 +1,8 @@
<?php
session_start();
require_once __DIR__ . '/class/db-functions.php';
$sid = session_id(); // oppure l'id Laravel, da verificare
$pdo = DBHandlerSelect::getInstance()->getConnection();
$pdo->prepare("UPDATE auth_sessions SET last_activity = ? WHERE id = ?")
->execute([time(), $sid]);
echo json_encode(['ok' => true, 'sid' => $sid, 'ts' => time()]);
@@ -0,0 +1,38 @@
<?php
include('include/headscript.php');
$db = DBHandlerSelect::getInstance();
$pdo = $db->getConnection();
$userId = (int)($iduserlogin ?? 0);
if ($userId <= 0) {
header("Location: login.php");
exit;
}
// Ogni preferenza: colonna DB => 1 se checkbox spuntata, 0 altrimenti
$prefsMap = [
'notify_export_email' => isset($_POST['notify_export_email']) ? 1 : 0,
// in futuro: 'notify_altra_cosa' => isset($_POST['notify_altra_cosa']) ? 1 : 0,
];
try {
$sets = [];
$params = [];
foreach ($prefsMap as $col => $val) {
$sets[] = "`{$col}` = :{$col}";
$params[$col] = $val;
}
$params['id'] = $userId;
$sql = "UPDATE auth_users SET " . implode(', ', $sets) . " WHERE id = :id";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
header("Location: notification_settings.php?saved=1");
exit;
} catch (Exception $e) {
error_log("Notification prefs update error: " . $e->getMessage());
header("Location: notification_settings.php?saved=0");
exit;
}
+5
View File
@@ -217,6 +217,10 @@ try {
}
// Required custom fields that are visible in the import grid (excluding filed_id = 189 Tested component)
// Required custom fields that are visible in the import grid (excluding filed_id = 189 Tested component)
// Also exclude field_id 258 (Login Date) and 350 (Login Time): auto-populated at
// export time (save_export_lims.php STEP 4a), so they must not block validation
// even when empty at this stage.
$stmt = $pdo->prepare("
SELECT id AS mapping_id, template_id, field_label
FROM template_mapping
@@ -224,6 +228,7 @@ try {
AND is_required = 1
AND is_visible_import = 1
AND id <> 189
AND field_id NOT IN (258, 350)
");
$stmt->execute($templateIds);
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $r) {
+68 -22
View File
@@ -6,6 +6,11 @@
$startTime = microtime(true);
$isCli = (php_sapi_name() === 'cli');
$isStream = (!$isCli && isset($_GET['stream']));
// Analisi incluse? Default SÌ (il cron non passa il parametro → fa tutto).
// Solo una richiesta HTTP con analisi=0 le salta.
$includeAnalisi = !(!$isCli && isset($_GET['analisi']) && $_GET['analisi'] === '0');
if (!$isCli) {
// When called via HTTP, require auth
@@ -15,7 +20,17 @@ if (!$isCli) {
echo json_encode(['error' => 'Unauthorized']);
exit;
}
header('Content-Type: application/json');
if ($isStream) {
// Streaming mode: send progress line-by-line (Server-Sent Events)
set_time_limit(0);
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('X-Accel-Buffering: no'); // disable nginx buffering
while (ob_get_level() > 0) ob_end_flush();
} else {
header('Content-Type: application/json');
}
}
require_once dirname(__DIR__, 2) . '/vendor/autoload.php';
@@ -23,15 +38,38 @@ require_once __DIR__ . '/class/VisualLimsApiClient.class.php';
require_once __DIR__ . '/class/db-functions.php';
$cacheDir = __DIR__ . '/cache';
if (!is_dir($cacheDir)) mkdir($cacheDir, 0777, true);
if (!is_dir($cacheDir)) mkdir($cacheDir, 0755, true);
$log = [];
// Prevent two runs at the same time (e.g. cron + manual click)
$lockHandle = fopen($cacheDir . '/.warm.lock', 'w');
if ($lockHandle === false || !flock($lockHandle, LOCK_EX | LOCK_NB)) {
$busyMsg = 'Un aggiornamento è già in corso in questo momento. Riprova tra poco.';
if ($isCli) {
echo $busyMsg . PHP_EOL;
} elseif ($isStream) {
header('Content-Type: text/event-stream');
echo "event: busy\ndata: " . $busyMsg . "\n\n";
@flush();
} else {
echo json_encode(['success' => false, 'busy' => true, 'message' => $busyMsg]);
}
exit;
}
function warmLog(string $msg, bool $isCli)
{
global $log;
global $log, $isStream;
$line = date('H:i:s') . " $msg";
$log[] = $line;
if ($isCli) echo $line . PHP_EOL;
if ($isCli) {
echo $line . PHP_EOL;
} elseif (!empty($isStream)) {
echo "data: " . str_replace("\n", ' ', $line) . "\n\n";
@ob_flush();
@flush();
}
}
try {
@@ -115,30 +153,38 @@ try {
// 6. Analisi — only for matrici actually used by parts (warming all ~2500 matrici
// would mean one API call each; the used set is a few dozen).
$stmt = $pdo->query("SELECT DISTINCT idmatrice FROM identification_parts WHERE idmatrice IS NOT NULL AND idmatrice > 0 ORDER BY idmatrice ASC");
$matriceIds = $stmt->fetchAll(PDO::FETCH_COLUMN);
warmLog("[analisi] Fetching for " . count($matriceIds) . " matrici in use...", $isCli);
if (!$includeAnalisi) {
warmLog('[analisi] Saltate su richiesta.', $isCli);
} else {
$stmt = $pdo->query("SELECT DISTINCT idmatrice FROM identification_parts WHERE idmatrice IS NOT NULL AND idmatrice > 0 ORDER BY idmatrice ASC");
$matriceIds = $stmt->fetchAll(PDO::FETCH_COLUMN);
warmLog("[analisi] Fetching for " . count($matriceIds) . " matrici in use...", $isCli);
foreach ($matriceIds as $mid) {
$mid = (int)$mid;
// Same query as get_analisi_matrice_filter.php with web_only=1 (what the analysis modal requests)
$filter = rawurlencode("Matrice/IdMatrice eq $mid and SelezionabileSuWeb eq true");
try {
$data = $api->get("Analisi?\$filter={$filter}");
$values = $data['value'] ?? [];
file_put_contents($cacheDir . '/analisi_matrice_' . $mid . '.json', json_encode(['value' => $values]));
warmLog("[analisi] Matrice $mid: " . count($values) . " analisi", $isCli);
} catch (Exception $e) {
warmLog("[analisi] Matrice $mid: ERROR " . $e->getMessage(), $isCli);
foreach ($matriceIds as $mid) {
$mid = (int)$mid;
// Same query as get_analisi_matrice_filter.php with web_only=1 (what the analysis modal requests)
$filter = rawurlencode("Matrice/IdMatrice eq $mid and SelezionabileSuWeb eq true");
try {
$data = $api->get("Analisi?\$filter={$filter}");
$values = $data['value'] ?? [];
file_put_contents($cacheDir . '/analisi_matrice_' . $mid . '.json', json_encode(['value' => $values]));
warmLog("[analisi] Matrice $mid: " . count($values) . " analisi", $isCli);
} catch (Exception $e) {
warmLog("[analisi] Matrice $mid: ERROR " . $e->getMessage(), $isCli);
}
}
}
} // fine if includeAnalisi
$elapsed = round(microtime(true) - $startTime, 1);
warmLog("Done in {$elapsed}s", $isCli);
warmLog("Aggiornamento completato in {$elapsed}s", $isCli);
} catch (Exception $e) {
warmLog("FATAL: " . $e->getMessage(), $isCli);
$elapsed = round(microtime(true) - $startTime, 1);
warmLog("ERRORE: " . $e->getMessage(), $isCli);
}
if (!$isCli) {
if ($isStream) {
echo "event: done\ndata: " . json_encode(['elapsed' => $elapsed ?? 0]) . "\n\n";
@flush();
} elseif (!$isCli) {
echo json_encode(['success' => true, 'log' => $log]);
}
+519
View File
@@ -0,0 +1,519 @@
<?php
include('include/headscript.php');
/*
* NOTE PERMESSI:
* Il login è già gestito da headscript.php (Auth::check + redirect).
* Se vuoi limitare questa pagina a determinati ruoli, aggiungi qui il tuo
* controllo, esattamente come nelle altre pagine. Esempio:
*
* if (!$user->hasRole('Admin') && !$user->hasRole('SuperUser')) {
* header('Location: import_dashboard.php');
* exit;
* }
*/
?>
<!doctype html>
<html lang="it">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="assets/images/favicon-32x32.png" type="image/png" />
<?php include('cssinclude.php'); ?>
<title>Aggiornamento dati - <?= htmlspecialchars($titlewebsite ?? 'SmartTRF', ENT_QUOTES, 'UTF-8'); ?></title>
<style>
.warm-hero {
display: flex;
align-items: center;
gap: 18px;
}
.warm-hero .warm-icon {
width: 64px;
height: 64px;
border-radius: 16px;
display: flex;
align-items: center;
justify-content: center;
font-size: 30px;
color: #fff;
background: linear-gradient(135deg, #0f172a, #1d4ed8);
flex-shrink: 0;
}
.warm-progress-wrap {
display: none;
}
.warm-progress-wrap.is-visible {
display: block;
}
.progress.warm-progress {
height: 22px;
border-radius: 12px;
background: #eef2f7;
}
.progress.warm-progress .progress-bar {
font-size: 12px;
font-weight: 600;
}
.warm-steps {
list-style: none;
padding: 0;
margin: 18px 0 0 0;
}
.warm-steps li {
display: flex;
align-items: center;
gap: 12px;
padding: 10px 12px;
border-radius: 10px;
margin-bottom: 6px;
background: #f8fafc;
border: 1px solid #eef2f7;
transition: background .2s, border-color .2s;
}
.warm-steps li .step-icon {
width: 26px;
height: 26px;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
font-size: 14px;
flex-shrink: 0;
background: #e5e7eb;
color: #94a3b8;
}
.warm-steps li.is-active {
background: #eff6ff;
border-color: #bfdbfe;
}
.warm-steps li.is-active .step-icon {
background: #2563eb;
color: #fff;
}
.warm-steps li.is-done {
background: #f0fdf4;
border-color: #bbf7d0;
}
.warm-steps li.is-done .step-icon {
background: #16a34a;
color: #fff;
}
.warm-steps li .step-label {
font-weight: 600;
color: #1f2937;
}
.warm-steps li .step-detail {
font-size: 12px;
color: #64748b;
margin-left: auto;
text-align: right;
}
.warm-log {
display: none;
margin-top: 18px;
}
.warm-log.is-visible {
display: block;
}
.warm-log pre {
max-height: 320px;
overflow: auto;
background: #0f172a;
color: #cbd5e1;
padding: 16px;
border-radius: 12px;
font-size: 12px;
line-height: 1.6;
margin: 0;
}
.warm-result {
display: none;
margin-top: 18px;
}
.warm-result.is-visible {
display: block;
}
</style>
</head>
<body>
<div class="wrapper">
<?php include('include/navbar.php'); ?>
<?php include('include/topbar.php'); ?>
<div class="page-wrapper">
<div class="page-content">
<div class="card radius-10">
<div class="card-body p-4">
<div class="warm-hero">
<div class="warm-icon"><i class="bx bx-refresh"></i></div>
<div>
<h5 class="mb-1">Aggiornamento dati dal gestionale</h5>
<p class="mb-0 text-muted">
Ricarica clienti, matrici, analisi e le altre liste dal software di laboratorio.
Da usare quando sono state fatte modifiche sul gestionale e vuoi vederle subito
senza aspettare l'aggiornamento automatico.
</p>
</div>
</div>
<hr class="my-4">
<div class="form-check form-switch mb-3" id="analisiSwitchWrap">
<input class="form-check-input" type="checkbox" role="switch" id="includeAnalisi" checked>
<label class="form-check-label" for="includeAnalisi">
Aggiorna anche le <strong>analisi</strong>
<span class="text-muted small">(più lento &mdash; togli la spunta se hai modificato solo clienti o altre liste)</span>
</label>
</div>
<button type="button" class="btn btn-primary btn-lg px-4" id="btnStart">
<i class="bx bx-play-circle me-1"></i> Avvia aggiornamento
</button>
<div class="small text-muted mt-2" id="idleHint">
L'operazione può richiedere da qualche secondo a un paio di minuti.
</div>
<!-- Progress -->
<div class="warm-progress-wrap mt-4" id="progressWrap">
<div class="d-flex justify-content-between align-items-center mb-2">
<span class="fw-semibold" id="progressTitle">Aggiornamento in corso…</span>
<span class="text-muted small" id="progressElapsed">0s</span>
</div>
<div class="progress warm-progress">
<div class="progress-bar progress-bar-striped progress-bar-animated bg-primary"
id="progressBar" role="progressbar" style="width: 0%;">0%</div>
</div>
<ul class="warm-steps" id="stepsList">
<!-- steps injected by JS -->
</ul>
<div class="mt-3">
<a href="javascript:;" class="small text-decoration-none" id="toggleLog">
<i class="bx bx-code-alt"></i> Mostra dettaglio tecnico
</a>
</div>
<div class="warm-log" id="logBox">
<pre id="logPre"></pre>
</div>
</div>
<!-- Result -->
<div class="warm-result" id="resultBox">
<div class="alert d-flex align-items-center" id="resultAlert" role="alert">
<i class="bx me-2 fs-4" id="resultIcon"></i>
<div id="resultText"></div>
</div>
<button type="button" class="btn btn-outline-primary" id="btnAgain">
<i class="bx bx-refresh me-1"></i> Esegui di nuovo
</button>
</div>
</div>
</div>
</div>
</div>
<div class="overlay toggle-icon"></div>
<a href="javaScript:;" class="back-to-top"><i class='bx bxs-up-arrow-alt'></i></a>
<?php include('include/footer.php'); ?>
</div>
<?php include('jsinclude.php'); ?>
<script>
document.addEventListener('DOMContentLoaded', function() {
/*
* Se sposti warm_cache.php in un'altra cartella, cambia SOLO questa riga.
*/
const WARM_ENDPOINT = 'warm_cache.php';
const btnStart = document.getElementById('btnStart');
const btnAgain = document.getElementById('btnAgain');
const idleHint = document.getElementById('idleHint');
const includeAnalisi = document.getElementById('includeAnalisi');
const progressWrap = document.getElementById('progressWrap');
const progressBar = document.getElementById('progressBar');
const progressTitle = document.getElementById('progressTitle');
const progressElapsed = document.getElementById('progressElapsed');
const stepsList = document.getElementById('stepsList');
const toggleLog = document.getElementById('toggleLog');
const logBox = document.getElementById('logBox');
const logPre = document.getElementById('logPre');
const resultBox = document.getElementById('resultBox');
const resultAlert = document.getElementById('resultAlert');
const resultIcon = document.getElementById('resultIcon');
const resultText = document.getElementById('resultText');
/*
* I "passi" mostrati al cliente in modo leggibile.
* key = frammento che compare nel log tecnico (dentro le parentesi quadre)
* label = nome umano
* Il progresso avanza man mano che questi tag compaiono nel log.
*/
const STEPS = [{
key: 'clients',
label: 'Clienti'
},
{
key: 'MoltiplicatorePrezzo',
label: 'Listini prezzi'
},
{
key: 'AnagraficaCertest',
label: 'Anagrafiche Certest'
},
{
key: 'ClienteResponsabile',
label: 'Responsabili cliente'
},
{
key: 'CustomField',
label: 'Campi personalizzati'
},
{
key: 'matrici',
label: 'Matrici'
},
{
key: 'analisi',
label: 'Analisi'
}
];
let stepEls = {};
let currentStepIndex = -1;
let timerId = null;
let startedAt = 0;
let activeSteps = []; // i passi effettivamente in gioco per questa esecuzione
function buildSteps() {
stepsList.innerHTML = '';
stepEls = {};
// Se le analisi sono disattivate, escludo quel passo dalla lista.
const withAnalisi = includeAnalisi.checked;
activeSteps = STEPS.filter(function(s) {
return withAnalisi || s.key !== 'analisi';
});
activeSteps.forEach(function(step, i) {
const li = document.createElement('li');
li.dataset.index = i;
li.innerHTML =
'<span class="step-icon"><i class="bx bx-time"></i></span>' +
'<span class="step-label">' + step.label + '</span>' +
'<span class="step-detail"></span>';
stepsList.appendChild(li);
stepEls[i] = li;
});
}
function markStep(index, state, detail) {
const li = stepEls[index];
if (!li) return;
li.classList.remove('is-active', 'is-done');
const icon = li.querySelector('.step-icon i');
if (state === 'active') {
li.classList.add('is-active');
icon.className = 'bx bx-loader-alt bx-spin';
} else if (state === 'done') {
li.classList.add('is-done');
icon.className = 'bx bx-check';
}
if (detail !== undefined) {
li.querySelector('.step-detail').textContent = detail;
}
}
function advanceTo(index, detail) {
if (index <= currentStepIndex) {
// stesso passo, aggiorna solo il dettaglio (es. conteggio)
if (detail !== undefined) markStep(index, 'active', detail);
return;
}
// chiudi i passi precedenti
for (let i = 0; i <= currentStepIndex; i++) markStep(i, 'done');
currentStepIndex = index;
markStep(index, 'active', detail);
const pct = Math.round(((index) / activeSteps.length) * 100);
setProgress(Math.max(pct, 3));
}
function setProgress(pct) {
pct = Math.max(0, Math.min(100, pct));
progressBar.style.width = pct + '%';
progressBar.textContent = pct + '%';
}
function matchStep(line) {
// cerca [clients], [matrici], [analisi] ecc. nella riga di log
for (let i = 0; i < activeSteps.length; i++) {
if (line.indexOf('[' + activeSteps[i].key) !== -1 ||
line.indexOf(activeSteps[i].key + ']') !== -1) {
return i;
}
}
return -1;
}
function extractDetail(line) {
// prova a estrarre un conteggio tipo "Cached 128 clients" o "34 analisi"
const m = line.match(/(\d+)\s+(clients|items|values|responsabili|analisi)/i);
if (m) return m[1] + ' elementi';
return undefined;
}
function startTimer() {
startedAt = Date.now();
timerId = setInterval(function() {
const s = Math.round((Date.now() - startedAt) / 1000);
progressElapsed.textContent = s + 's';
}, 1000);
}
function stopTimer() {
if (timerId) clearInterval(timerId);
timerId = null;
}
function resetUI() {
buildSteps();
currentStepIndex = -1;
setProgress(0);
logPre.textContent = '';
progressTitle.textContent = 'Aggiornamento in corso…';
progressElapsed.textContent = '0s';
resultBox.classList.remove('is-visible');
progressWrap.classList.add('is-visible');
}
function showResult(type, message) {
stopTimer();
progressBar.classList.remove('progress-bar-animated', 'progress-bar-striped');
resultAlert.className = 'alert d-flex align-items-center';
if (type === 'success') {
resultAlert.classList.add('alert-success');
resultIcon.className = 'bx bx-check-circle me-2 fs-4';
progressBar.classList.add('bg-success');
} else if (type === 'warning') {
resultAlert.classList.add('alert-warning');
resultIcon.className = 'bx bx-error me-2 fs-4';
progressBar.classList.add('bg-warning');
} else {
resultAlert.classList.add('alert-danger');
resultIcon.className = 'bx bx-x-circle me-2 fs-4';
progressBar.classList.add('bg-danger');
}
resultText.textContent = message;
resultBox.classList.add('is-visible');
btnStart.disabled = false;
includeAnalisi.disabled = false;
}
function run() {
btnStart.disabled = true;
includeAnalisi.disabled = true;
idleHint.style.display = 'none';
resetUI();
startTimer();
const analisiParam = includeAnalisi.checked ? '1' : '0';
const es = new EventSource(WARM_ENDPOINT + '?stream=1&analisi=' + analisiParam);
es.onmessage = function(e) {
const line = e.data;
logPre.textContent += line + '\n';
logPre.scrollTop = logPre.scrollHeight;
const idx = matchStep(line);
if (idx !== -1) {
advanceTo(idx, extractDetail(line));
}
};
es.addEventListener('busy', function(e) {
es.close();
showResult('warning', e.data ||
'Un aggiornamento è già in corso. Attendi qualche istante e riprova.');
});
es.addEventListener('done', function(e) {
es.close();
// completa tutti i passi
for (let i = 0; i < activeSteps.length; i++) markStep(i, 'done');
setProgress(100);
let elapsed = '';
try {
elapsed = JSON.parse(e.data).elapsed;
} catch (err) {}
// se nel log è comparsa la parola ERRORE, segnala come warning
if (logPre.textContent.indexOf('ERRORE') !== -1) {
showResult('warning',
'Aggiornamento terminato, ma alcuni dati potrebbero non essere stati caricati. ' +
'Controlla il dettaglio tecnico.');
} else {
progressTitle.textContent = 'Completato';
showResult('success',
'Dati aggiornati correttamente' +
(elapsed ? ' in ' + elapsed + ' secondi.' : '.') +
' Le nuove informazioni sono ora disponibili.');
}
});
es.onerror = function() {
// EventSource tenta il reconnect da solo: lo blocchiamo.
es.close();
stopTimer();
// Se avevamo già finito, il done è già scattato: non sovrascrivere.
if (!resultBox.classList.contains('is-visible')) {
showResult('error',
'Connessione interrotta durante l\'aggiornamento. ' +
'Verifica la rete e riprova.');
}
};
}
btnStart.addEventListener('click', run);
btnAgain.addEventListener('click', run);
toggleLog.addEventListener('click', function() {
logBox.classList.toggle('is-visible');
toggleLog.innerHTML = logBox.classList.contains('is-visible') ?
'<i class="bx bx-hide"></i> Nascondi dettaglio tecnico' :
'<i class="bx bx-code-alt"></i> Mostra dettaglio tecnico';
});
});
</script>
</body>
</html>
+11 -10
View File
@@ -5806,17 +5806,17 @@
},
{
"name": "phpmailer/phpmailer",
"version": "v6.9.3",
"version_normalized": "6.9.3.0",
"version": "v7.1.1",
"version_normalized": "7.1.1.0",
"source": {
"type": "git",
"url": "https://github.com/PHPMailer/PHPMailer.git",
"reference": "2f5c94fe7493efc213f643c23b1b1c249d40f47e"
"reference": "1bc1716a507a65e039d4ac9d9adebbbd0d346e15"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/PHPMailer/PHPMailer/zipball/2f5c94fe7493efc213f643c23b1b1c249d40f47e",
"reference": "2f5c94fe7493efc213f643c23b1b1c249d40f47e",
"url": "https://api.github.com/repos/PHPMailer/PHPMailer/zipball/1bc1716a507a65e039d4ac9d9adebbbd0d346e15",
"reference": "1bc1716a507a65e039d4ac9d9adebbbd0d346e15",
"shasum": ""
},
"require": {
@@ -5830,13 +5830,14 @@
"doctrine/annotations": "^1.2.6 || ^1.13.3",
"php-parallel-lint/php-console-highlighter": "^1.0.0",
"php-parallel-lint/php-parallel-lint": "^1.3.2",
"phpcompatibility/php-compatibility": "^9.3.5",
"roave/security-advisories": "dev-latest",
"squizlabs/php_codesniffer": "^3.7.2",
"phpcompatibility/php-compatibility": "^10.0.0@dev",
"squizlabs/php_codesniffer": "^3.13.5",
"yoast/phpunit-polyfills": "^1.0.4"
},
"suggest": {
"decomplexity/SendOauth2": "Adapter for using XOAUTH2 authentication",
"directorytree/imapengine": "For uploading sent messages via IMAP, see gmail example",
"ext-imap": "Needed to support advanced email address parsing according to RFC822",
"ext-mbstring": "Needed to send email in multibyte encoding charset or decode encoded addresses",
"ext-openssl": "Needed for secure SMTP sending and DKIM signing",
"greew/oauth2-azure-provider": "Needed for Microsoft Azure XOAUTH2 authentication",
@@ -5846,7 +5847,7 @@
"symfony/polyfill-mbstring": "To support UTF-8 if the Mbstring PHP extension is not enabled (^1.2)",
"thenetworg/oauth2-azure": "Needed for Microsoft XOAUTH2 authentication"
},
"time": "2024-11-24T18:04:13+00:00",
"time": "2026-05-18T08:06:14+00:00",
"type": "library",
"installation-source": "dist",
"autoload": {
@@ -5878,7 +5879,7 @@
"description": "PHPMailer is a full-featured email creation and transfer class for PHP",
"support": {
"issues": "https://github.com/PHPMailer/PHPMailer/issues",
"source": "https://github.com/PHPMailer/PHPMailer/tree/v6.9.3"
"source": "https://github.com/PHPMailer/PHPMailer/tree/v7.1.1"
},
"funding": [
{
+5 -5
View File
@@ -3,7 +3,7 @@
'name' => 'loshmis/vanguard',
'pretty_version' => 'dev-main',
'version' => 'dev-main',
'reference' => 'b19963808e5545f0b99bf0eba214b0c85b2f4b7b',
'reference' => 'bb2ebcc1223dd084e59588774fecbca9875d9daf',
'type' => 'project',
'install_path' => __DIR__ . '/../../',
'aliases' => array(),
@@ -742,7 +742,7 @@
'loshmis/vanguard' => array(
'pretty_version' => 'dev-main',
'version' => 'dev-main',
'reference' => 'b19963808e5545f0b99bf0eba214b0c85b2f4b7b',
'reference' => 'bb2ebcc1223dd084e59588774fecbca9875d9daf',
'type' => 'project',
'install_path' => __DIR__ . '/../../',
'aliases' => array(),
@@ -941,9 +941,9 @@
'dev_requirement' => true,
),
'phpmailer/phpmailer' => array(
'pretty_version' => 'v6.9.3',
'version' => '6.9.3.0',
'reference' => '2f5c94fe7493efc213f643c23b1b1c249d40f47e',
'pretty_version' => 'v7.1.1',
'version' => '7.1.1.0',
'reference' => '1bc1716a507a65e039d4ac9d9adebbbd0d346e15',
'type' => 'library',
'install_path' => __DIR__ . '/../phpmailer/phpmailer',
'aliases' => array(),
-15
View File
@@ -1,15 +0,0 @@
root = true
[*]
charset = utf-8
indent_size = 4
indent_style = space
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
[*.md]
trim_trailing_whitespace = false
[*.{yml,yaml}]
indent_size = 2
+13 -12
View File
@@ -6,9 +6,9 @@
[![Test status](https://github.com/PHPMailer/PHPMailer/workflows/Tests/badge.svg)](https://github.com/PHPMailer/PHPMailer/actions)
[![codecov.io](https://codecov.io/gh/PHPMailer/PHPMailer/branch/master/graph/badge.svg?token=iORZpwmYmM)](https://codecov.io/gh/PHPMailer/PHPMailer)
[![Latest Stable Version](https://poser.pugx.org/phpmailer/phpmailer/v/stable.svg)](https://packagist.org/packages/phpmailer/phpmailer)
[![Total Downloads](https://poser.pugx.org/phpmailer/phpmailer/downloads)](https://packagist.org/packages/phpmailer/phpmailer)
[![License](https://poser.pugx.org/phpmailer/phpmailer/license.svg)](https://packagist.org/packages/phpmailer/phpmailer)
[![Latest Stable Version](https://img.shields.io/packagist/v/phpmailer/phpmailer?label=stable)](https://packagist.org/packages/phpmailer/phpmailer)
[![Total Downloads](https://img.shields.io/packagist/dt/phpmailer/phpmailer)](https://packagist.org/packages/phpmailer/phpmailer)
[![License](https://img.shields.io/github/license/PHPMailer/PHPMailer)](https://packagist.org/packages/phpmailer/phpmailer)
[![API Docs](https://github.com/phpmailer/phpmailer/workflows/Docs/badge.svg)](https://phpmailer.github.io/PHPMailer/)
[![OpenSSF Scorecard](https://api.securityscorecards.dev/projects/github.com/PHPMailer/PHPMailer/badge)](https://api.securityscorecards.dev/projects/github.com/PHPMailer/PHPMailer)
@@ -20,25 +20,26 @@
- Multipart/alternative emails for mail clients that do not read HTML email
- Add attachments, including inline
- Support for UTF-8 content and 8bit, base64, binary, and quoted-printable encodings
- SMTP authentication with LOGIN, PLAIN, CRAM-MD5, and XOAUTH2 mechanisms over SMTPS and SMTP+STARTTLS transports
- Full UTF-8 support when using servers that support `SMTPUTF8`.
- Support for iCal events in multiparts and attachments
- SMTP authentication with `LOGIN`, `PLAIN`, `CRAM-MD5`, and `XOAUTH2` mechanisms over SMTPS and SMTP+STARTTLS transports
- Validates email addresses automatically
- Protects against header injection attacks
- Error messages in over 50 languages!
- DKIM and S/MIME signing support
- Compatible with PHP 5.5 and later, including PHP 8.2
- Compatible with PHP 5.5 and later, including PHP 8.5
- Namespaced to prevent name clashes
- Much more!
## Why you might need it
Many PHP developers need to send email from their code. The only PHP function that supports this directly is [`mail()`](https://www.php.net/manual/en/function.mail.php). However, it does not provide any assistance for making use of popular features such as encryption, authentication, HTML messages, and attachments.
Many PHP developers need to send email from their code. The only PHP function that supports this directly is [`mail()`](https://www.php.net/manual/en/function.mail.php). However, it does not provide any assistance for making use of popular features such as authentication, HTML messages, and attachments.
Formatting email correctly is surprisingly difficult. There are myriad overlapping (and conflicting) standards, requiring tight adherence to horribly complicated formatting and encoding rules – the vast majority of code that you'll find online that uses the `mail()` function directly is just plain wrong, if not unsafe!
The PHP `mail()` function usually sends via a local mail server, typically fronted by a `sendmail` binary on Linux, BSD, and macOS platforms, however, Windows usually doesn't include a local mail server; PHPMailer's integrated SMTP client allows email sending on all platforms without needing a local mail server. Be aware though, that the `mail()` function should be avoided when possible; it's both faster and [safer](https://exploitbox.io/paper/Pwning-PHP-Mail-Function-For-Fun-And-RCE.html) to use SMTP to localhost.
*Please* don't be tempted to do it yourself – if you don't use PHPMailer, there are many other excellent libraries that
you should look at before rolling your own. Try [SwiftMailer](https://swiftmailer.symfony.com/)
, [Laminas/Mail](https://docs.laminas.dev/laminas-mail/), [ZetaComponents](https://github.com/zetacomponents/Mail), etc.
you should look at before rolling your own. Try [Symfony Mailer](https://symfony.com/doc/current/mailer.html), [Laminas/Mail](https://docs.laminas.dev/laminas-mail/), [ZetaComponents](https://github.com/zetacomponents/Mail), etc.
## License
This software is distributed under the [LGPL 2.1](https://www.gnu.org/licenses/old-licenses/lgpl-2.1.html) license, along with the [GPL Cooperation Commitment](https://gplcc.github.io/gplcc/). Please read [LICENSE](https://github.com/PHPMailer/PHPMailer/blob/master/LICENSE) for information on the software availability and distribution.
@@ -47,7 +48,7 @@ This software is distributed under the [LGPL 2.1](https://www.gnu.org/licenses/o
PHPMailer is available on [Packagist](https://packagist.org/packages/phpmailer/phpmailer) (using semantic versioning), and installation via [Composer](https://getcomposer.org) is the recommended way to install PHPMailer. Just add this line to your `composer.json` file:
```json
"phpmailer/phpmailer": "^6.9.2"
"phpmailer/phpmailer": "^7.0.0"
```
or run
@@ -74,10 +75,10 @@ require 'path/to/PHPMailer/src/PHPMailer.php';
require 'path/to/PHPMailer/src/SMTP.php';
```
If you're not using the `SMTP` class explicitly (you're probably not), you don't need a `use` line for the SMTP class. Even if you're not using exceptions, you do still need to load the `Exception` class as it is used internally.
If you're not using the `SMTP` class explicitly (you're probably not), you don't need a `use` line for it. Even if you're not using exceptions, you do still need to load the `Exception` class as it is used internally.
## Legacy versions
PHPMailer 5.2 (which is compatible with PHP 5.0 — 7.0) is no longer supported, even for security updates. You will find the latest version of 5.2 in the [5.2-stable branch](https://github.com/PHPMailer/PHPMailer/tree/5.2-stable). If you're using PHP 5.5 or later (which you should be), switch to the 6.x releases.
PHPMailer 5.2 (which is compatible with PHP 5.0 — 7.0) is no longer supported, even for security updates. You will find the latest version of 5.2 in the [5.2-stable branch](https://github.com/PHPMailer/PHPMailer/tree/5.2-stable). If you're using PHP 5.5 or later (which you should be), upgrade to a later release.
### Upgrading from 5.2
The biggest changes are that source files are now in the `src/` folder, and PHPMailer now declares the namespace `PHPMailer\PHPMailer`. This has several important effects – [read the upgrade guide](https://github.com/PHPMailer/PHPMailer/tree/master/UPGRADING.md) for more details.
@@ -95,7 +96,7 @@ use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
//Load Composer's autoloader
//Load Composer's autoloader (created by composer, not included with PHPMailer)
require 'vendor/autoload.php';
//Create an instance; passing `true` enables exceptions
+1 -1
View File
@@ -1 +1 @@
6.9.3
7.1.1
+8 -4
View File
@@ -42,22 +42,25 @@
"doctrine/annotations": "^1.2.6 || ^1.13.3",
"php-parallel-lint/php-console-highlighter": "^1.0.0",
"php-parallel-lint/php-parallel-lint": "^1.3.2",
"phpcompatibility/php-compatibility": "^9.3.5",
"roave/security-advisories": "dev-latest",
"squizlabs/php_codesniffer": "^3.7.2",
"phpcompatibility/php-compatibility": "^10.0.0@dev",
"squizlabs/php_codesniffer": "^3.13.5",
"yoast/phpunit-polyfills": "^1.0.4"
},
"suggest": {
"decomplexity/SendOauth2": "Adapter for using XOAUTH2 authentication",
"ext-imap": "Needed to support advanced email address parsing according to RFC822",
"ext-mbstring": "Needed to send email in multibyte encoding charset or decode encoded addresses",
"ext-openssl": "Needed for secure SMTP sending and DKIM signing",
"greew/oauth2-azure-provider": "Needed for Microsoft Azure XOAUTH2 authentication",
"hayageek/oauth2-yahoo": "Needed for Yahoo XOAUTH2 authentication",
"league/oauth2-google": "Needed for Google XOAUTH2 authentication",
"psr/log": "For optional PSR-3 debug logging",
"symfony/polyfill-mbstring": "To support UTF-8 if the Mbstring PHP extension is not enabled (^1.2)",
"thenetworg/oauth2-azure": "Needed for Microsoft XOAUTH2 authentication",
"symfony/polyfill-mbstring": "To support UTF-8 if the Mbstring PHP extension is not enabled (^1.2)"
"directorytree/imapengine": "For uploading sent messages via IMAP, see gmail example"
},
"minimum-stability": "dev",
"prefer-stable": true,
"autoload": {
"psr-4": {
"PHPMailer\\PHPMailer\\": "src/"
@@ -71,6 +74,7 @@
"license": "LGPL-2.1-only",
"scripts": {
"check": "./vendor/bin/phpcs",
"style": "./vendor/bin/phpcbf",
"test": "./vendor/bin/phpunit --no-coverage",
"coverage": "./vendor/bin/phpunit",
"lint": [
+1 -1
View File
@@ -178,5 +178,5 @@ if (!isset($_GET['code'])) {
);
//Use this to interact with an API on the users behalf
//Use this to get a new access token if the old one expires
echo 'Refresh Token: ', htmlspecialchars($token->getRefreshToken());
echo 'Refresh Token: ', htmlspecialchars($token->getRefreshToken(), ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401);
}
@@ -34,3 +34,6 @@ $PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP Connect() fejlede.';
$PHPMAILER_LANG['smtp_detail'] = 'Detalje: ';
$PHPMAILER_LANG['smtp_error'] = 'SMTP server fejl: ';
$PHPMAILER_LANG['variable_set'] = 'Kunne ikke definere eller nulstille variablen: ';
$PHPMAILER_LANG['no_smtputf8'] = 'Serveren understøtter ikke SMTPUTF8 som påkrævet for at sende til Unicode adresser';
$PHPMAILER_LANG['imap_recommended'] = 'Brug af forenklet adresseparser anbefales ikke. Installer PHP IMAP udvidelsen for fuld RFC822 parsing.';
$PHPMAILER_LANG['deprecated_argument'] = 'Udfaset argument: ';
+29 -18
View File
@@ -3,24 +3,35 @@
/**
* Esperanto PHPMailer language file: refer to English translation for definitive list
* @package PHPMailer
* @author Robin van der Vliet <info@robinvandervliet.com>
*/
$PHPMAILER_LANG['authenticate'] = 'Eraro de servilo SMTP : aŭtentigo malsukcesis.';
$PHPMAILER_LANG['connect_host'] = 'Eraro de servilo SMTP : konektado al servilo malsukcesis.';
$PHPMAILER_LANG['data_not_accepted'] = 'Eraro de servilo SMTP : neĝustaj datumoj.';
$PHPMAILER_LANG['empty_message'] = 'Teksto de mesaĝo mankas.';
$PHPMAILER_LANG['authenticate'] = 'SMTP-eraro: Ne eblis aŭtentigi.';
$PHPMAILER_LANG['buggy_php'] = 'Via versio de PHP estas trafita de cimo, kiu povas kaŭzi difektitajn mesaĝojn. Por ripari tion, ŝanĝu al sendado per SMTP, malŝaltu la opcion mail.add_x_header en via php.ini, ŝanĝu al MacOS aŭ Linux, aŭ ĝisdatigu vian PHP al versio 7.0.17+ aŭ 7.1.3+.';
$PHPMAILER_LANG['connect_host'] = 'SMTP-eraro: Ne eblis konektiĝi al la SMTP-gastiganto.';
$PHPMAILER_LANG['data_not_accepted'] = 'SMTP-eraro: Datumoj ne akceptitaj.';
$PHPMAILER_LANG['empty_message'] = 'Mesaĝokorpo malplena';
$PHPMAILER_LANG['encoding'] = 'Nekonata kodoprezento: ';
$PHPMAILER_LANG['execute'] = 'Lanĉi rulumadon ne eblis: ';
$PHPMAILER_LANG['file_access'] = 'Aliro al dosiero ne sukcesis: ';
$PHPMAILER_LANG['file_open'] = 'Eraro de dosiero: malfermo neeblas: ';
$PHPMAILER_LANG['from_failed'] = 'Jena adreso de sendinto malsukcesis: ';
$PHPMAILER_LANG['instantiate'] = 'Genero de retmesaĝa funkcio neeblis.';
$PHPMAILER_LANG['invalid_address'] = 'Retadreso ne validas: ';
$PHPMAILER_LANG['mailer_not_supported'] = ' mesaĝilo ne subtenata.';
$PHPMAILER_LANG['provide_address'] = 'Vi devas tajpi almenaŭ unu recevontan retadreson.';
$PHPMAILER_LANG['recipients_failed'] = 'Eraro de servilo SMTP : la jenaj poŝtrecivuloj kaŭzis eraron: ';
$PHPMAILER_LANG['signing'] = 'Eraro de subskribo: ';
$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP konektado malsukcesis.';
$PHPMAILER_LANG['smtp_error'] = 'Eraro de servilo SMTP : ';
$PHPMAILER_LANG['variable_set'] = 'Variablo ne pravalorizeblas aŭ ne repravalorizeblas: ';
$PHPMAILER_LANG['extension_missing'] = 'Mankas etendo: ';
$PHPMAILER_LANG['execute'] = 'Ne eblis plenumi: ';
$PHPMAILER_LANG['extension_missing'] = 'Kromprogramo mankas: ';
$PHPMAILER_LANG['file_access'] = 'Ne eblis aliri la dosieron: ';
$PHPMAILER_LANG['file_open'] = 'Dosiera eraro: Ne eblis malfermi la dosieron: ';
$PHPMAILER_LANG['from_failed'] = 'La sekva(j) sendinto(j) malsukcesis: ';
$PHPMAILER_LANG['instantiate'] = 'Ne eblis funkciigi la retpoŝtan funkcion.';
$PHPMAILER_LANG['invalid_address'] = 'Nevalida adreso: ';
$PHPMAILER_LANG['invalid_header'] = 'Nevalida kaplinia nomo aŭ valoro';
$PHPMAILER_LANG['invalid_hostentry'] = 'Nevalida enigo de gastiganto: ';
$PHPMAILER_LANG['invalid_host'] = 'Nevalida gastiganto: ';
$PHPMAILER_LANG['mailer_not_supported'] = ' retpoŝtilo ne estas subtenata.';
$PHPMAILER_LANG['provide_address'] = 'Vi devas provizi almenaŭ unu retpoŝtadreson de ricevonto.';
$PHPMAILER_LANG['recipients_failed'] = 'SMTP-eraro: La sekva(j) ricevonto(j) malsukcesis: ';
$PHPMAILER_LANG['signing'] = 'Subskriba eraro: ';
$PHPMAILER_LANG['smtp_code'] = 'SMTP-kodo: ';
$PHPMAILER_LANG['smtp_code_ex'] = 'Pliaj SMTP-informoj: ';
$PHPMAILER_LANG['smtp_connect_failed'] = 'La SMTP-konektiĝo malsukcesis.';
$PHPMAILER_LANG['smtp_detail'] = 'Informoj: ';
$PHPMAILER_LANG['smtp_error'] = 'Eraro de SMTP-servilo: ';
$PHPMAILER_LANG['variable_set'] = 'Ne eblas agordi aŭ reagordi la variablon: ';
$PHPMAILER_LANG['no_smtputf8'] = 'La servilo ne subtenas SMTPUTF8, kiu estas bezonata por sendi al Unicode-adresoj.';
$PHPMAILER_LANG['imap_recommended'] = 'Uzado de la simpligita adresanalizilo ne estas rekomendita. Instalu la IMAP-kromprogramon por PHP por plena RFC822-analizado.';
$PHPMAILER_LANG['deprecated_argument'] = 'Malrekomendita argumento: ';
+4 -2
View File
@@ -9,7 +9,7 @@
*/
$PHPMAILER_LANG['authenticate'] = 'Error SMTP: Imposible autentificar.';
$PHPMAILER_LANG['buggy_php'] = 'Tu versión de PHP está afectada por un bug que puede resultar en mensajes corruptos. Para arreglarlo, cambia a enviar usando SMTP, deshabilita la opción mail.add_x_header en tu php.ini, cambia a MacOS o Linux, o actualiza tu PHP a la versión 7.0.17+ o 7.1.3+.';
$PHPMAILER_LANG['buggy_php'] = 'Tu versión de PHP ha sido afectada por un bug que puede resultar en mensajes corruptos. Para arreglarlo, cambia a enviar usando SMTP, deshabilita la opción mail.add_x_header en tu php.ini, cambia a MacOS o Linux, o actualiza tu PHP a la versión 7.0.17+ o 7.1.3+.';
$PHPMAILER_LANG['connect_host'] = 'Error SMTP: Imposible conectar al servidor SMTP.';
$PHPMAILER_LANG['data_not_accepted'] = 'Error SMTP: Datos no aceptados.';
$PHPMAILER_LANG['empty_message'] = 'El cuerpo del mensaje está vacío.';
@@ -18,7 +18,7 @@ $PHPMAILER_LANG['execute'] = 'Imposible ejecutar: ';
$PHPMAILER_LANG['extension_missing'] = 'Extensión faltante: ';
$PHPMAILER_LANG['file_access'] = 'Imposible acceder al archivo: ';
$PHPMAILER_LANG['file_open'] = 'Error de Archivo: Imposible abrir el archivo: ';
$PHPMAILER_LANG['from_failed'] = 'La(s) siguiente(s) direcciones de remitente fallaron: ';
$PHPMAILER_LANG['from_failed'] = 'La siguiente dirección de remitente falló: ';
$PHPMAILER_LANG['instantiate'] = 'Imposible crear una instancia de la función Mail.';
$PHPMAILER_LANG['invalid_address'] = 'Imposible enviar: dirección de email inválido: ';
$PHPMAILER_LANG['invalid_header'] = 'Nombre o valor de encabezado no válido';
@@ -34,3 +34,5 @@ $PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP Connect() falló.';
$PHPMAILER_LANG['smtp_detail'] = 'Detalle: ';
$PHPMAILER_LANG['smtp_error'] = 'Error del servidor SMTP: ';
$PHPMAILER_LANG['variable_set'] = 'No se pudo configurar la variable: ';
$PHPMAILER_LANG['imap_recommended'] = 'No se recomienda usar el analizador de direcciones simplificado. Instala la extensión IMAP de PHP para un análisis RFC822 más completo.';
$PHPMAILER_LANG['deprecated_argument'] = 'Argumento obsoleto: ';
+10 -6
View File
@@ -3,27 +3,28 @@
/**
* Norwegian Bokmål PHPMailer language file: refer to English translation for definitive list
* @package PHPMailer
* @author Wera AS <wordpress@wera.no>
*/
$PHPMAILER_LANG['authenticate'] = 'SMTP-feil: Kunne ikke autentiseres.';
$PHPMAILER_LANG['buggy_php'] = 'Din versjon av PHP er berørt av en feil som kan føre til ødelagte meldinger. For å løse problemet kan du bytte til SMTP, deaktivere alternativet mail.add_x_header i php.ini, bytte til MacOS eller Linux eller oppgradere PHP til versjon 7.0.17+ eller 7.1.3+.';
$PHPMAILER_LANG['authenticate'] = 'SMTP-feil: Kunne ikke autentisere.';
$PHPMAILER_LANG['buggy_php'] = 'Din versjon av PHP er påvirket av en feil som kan føre til ødelagte meldinger. For å løse problemet kan du bytte til sending via SMTP, deaktivere mail.add_x_header-alternativet i php.ini, bytte til MacOS eller Linux, eller oppgradere PHP til versjon 7.0.17+ eller 7.1.3+.';
$PHPMAILER_LANG['connect_host'] = 'SMTP-feil: Kunne ikke koble til SMTP-vert.';
$PHPMAILER_LANG['data_not_accepted'] = 'SMTP-feil: data ikke akseptert.';
$PHPMAILER_LANG['empty_message'] = 'Meldingstekst mangler';
$PHPMAILER_LANG['empty_message'] = 'Meldingsinnholdet er tomt';
$PHPMAILER_LANG['encoding'] = 'Ukjent koding: ';
$PHPMAILER_LANG['execute'] = 'Kunne ikke utføres: ';
$PHPMAILER_LANG['extension_missing'] = 'Utvidelse mangler: ';
$PHPMAILER_LANG['file_access'] = 'Kunne ikke få tilgang til filen: ';
$PHPMAILER_LANG['file_open'] = 'Feil i fil: Kunne ikke åpne filen: ';
$PHPMAILER_LANG['from_failed'] = 'Følgende Fra-adresse mislyktes: ';
$PHPMAILER_LANG['instantiate'] = 'Kunne ikke instansiere e-postfunksjonen.';
$PHPMAILER_LANG['from_failed'] = 'Følgende avsenderadresse mislyktes: ';
$PHPMAILER_LANG['instantiate'] = 'Kunne ikke starte e-postfunksjonen.';
$PHPMAILER_LANG['invalid_address'] = 'Ugyldig adresse: ';
$PHPMAILER_LANG['invalid_header'] = 'Ugyldig headernavn eller verdi';
$PHPMAILER_LANG['invalid_hostentry'] = 'Ugyldig vertsinngang: ';
$PHPMAILER_LANG['invalid_host'] = 'Ugyldig vert: ';
$PHPMAILER_LANG['mailer_not_supported'] = ' sender er ikke støttet.';
$PHPMAILER_LANG['provide_address'] = 'Du må oppgi minst én mottaker-e-postadresse.';
$PHPMAILER_LANG['recipients_failed'] = 'SMTP Feil: Følgende mottakeradresse feilet: ';
$PHPMAILER_LANG['recipients_failed'] = 'SMTP-feil: Følgende mottakeradresser feilet: ';
$PHPMAILER_LANG['signing'] = 'Signeringsfeil: ';
$PHPMAILER_LANG['smtp_code'] = 'SMTP-kode: ';
$PHPMAILER_LANG['smtp_code_ex'] = 'Ytterligere SMTP-info: ';
@@ -31,3 +32,6 @@
$PHPMAILER_LANG['smtp_detail'] = 'Detaljer: ';
$PHPMAILER_LANG['smtp_error'] = 'SMTP-serverfeil: ';
$PHPMAILER_LANG['variable_set'] = 'Kan ikke angi eller tilbakestille variabel: ';
$PHPMAILER_LANG['no_smtputf8'] = 'Serveren støtter ikke SMTPUTF8, som er nødvendig for å sende til Unicode-adresser.';
$PHPMAILER_LANG['imap_recommended'] = 'Det anbefales ikke å bruke forenklet adresseanalyse. Installer PHP IMAP-utvidelsen for full RFC822-analyse.';
$PHPMAILER_LANG['deprecated_argument'] = 'Avviklet argument: ';
+11 -7
View File
@@ -4,10 +4,11 @@
* Dutch PHPMailer language file: refer to PHPMailer.php for definitive list.
* @package PHPMailer
* @author Tuxion <team@tuxion.nl>
* @author Robin van der Vliet <info@robinvandervliet.com>
*/
$PHPMAILER_LANG['authenticate'] = 'SMTP-fout: authenticatie mislukt.';
$PHPMAILER_LANG['buggy_php'] = 'PHP versie gededecteerd die onderhavig is aan een bug die kan resulteren in gecorrumpeerde berichten. Om dit te voorkomen, gebruik SMTP voor het verzenden van berichten, zet de mail.add_x_header optie in uw php.ini file uit, gebruik MacOS of Linux, of pas de gebruikte PHP versie aan naar versie 7.0.17+ or 7.1.3+.';
$PHPMAILER_LANG['buggy_php'] = 'PHP-versie gedetecteerd die onderhevig is aan een bug die kan resulteren in gecorrumpeerde berichten. Om dit te voorkomen, gebruik SMTP voor het verzenden van berichten, zet de optie mail.add_x_header in uw php.ini uit, gebruik MacOS of Linux, of pas de gebruikte PHP-versie aan naar versie 7.0.17+ or 7.1.3+.';
$PHPMAILER_LANG['connect_host'] = 'SMTP-fout: kon niet verbinden met SMTP-host.';
$PHPMAILER_LANG['data_not_accepted'] = 'SMTP-fout: data niet geaccepteerd.';
$PHPMAILER_LANG['empty_message'] = 'Berichttekst is leeg';
@@ -16,19 +17,22 @@ $PHPMAILER_LANG['execute'] = 'Kon niet uitvoeren: ';
$PHPMAILER_LANG['extension_missing'] = 'Extensie afwezig: ';
$PHPMAILER_LANG['file_access'] = 'Kreeg geen toegang tot bestand: ';
$PHPMAILER_LANG['file_open'] = 'Bestandsfout: kon bestand niet openen: ';
$PHPMAILER_LANG['from_failed'] = 'Het volgende afzendersadres is mislukt: ';
$PHPMAILER_LANG['from_failed'] = 'Het volgende afzenderadres is mislukt: ';
$PHPMAILER_LANG['instantiate'] = 'Kon mailfunctie niet initialiseren.';
$PHPMAILER_LANG['invalid_address'] = 'Ongeldig adres: ';
$PHPMAILER_LANG['invalid_header'] = 'Ongeldige header naam of waarde';
$PHPMAILER_LANG['invalid_header'] = 'Ongeldige headernaam of -waarde';
$PHPMAILER_LANG['invalid_hostentry'] = 'Ongeldige hostentry: ';
$PHPMAILER_LANG['invalid_host'] = 'Ongeldige host: ';
$PHPMAILER_LANG['mailer_not_supported'] = ' mailer wordt niet ondersteund.';
$PHPMAILER_LANG['provide_address'] = 'Er moet minstens één ontvanger worden opgegeven.';
$PHPMAILER_LANG['recipients_failed'] = 'SMTP-fout: de volgende ontvangers zijn mislukt: ';
$PHPMAILER_LANG['signing'] = 'Signeerfout: ';
$PHPMAILER_LANG['smtp_code'] = 'SMTP code: ';
$PHPMAILER_LANG['smtp_code_ex'] = 'Aanvullende SMTP informatie: ';
$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP Verbinding mislukt.';
$PHPMAILER_LANG['smtp_code'] = 'SMTP-code: ';
$PHPMAILER_LANG['smtp_code_ex'] = 'Aanvullende SMTP-informatie: ';
$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP-verbinding mislukt.';
$PHPMAILER_LANG['smtp_detail'] = 'Detail: ';
$PHPMAILER_LANG['smtp_error'] = 'SMTP-serverfout: ';
$PHPMAILER_LANG['variable_set'] = 'Kan de volgende variabele niet instellen of resetten: ';
$PHPMAILER_LANG['variable_set'] = 'Kan de volgende variabele niet instellen of herstellen: ';
$PHPMAILER_LANG['no_smtputf8'] = 'De server ondersteunt geen SMTPUTF8 dat nodig is om naar Unicode-adressen te sturen.';
$PHPMAILER_LANG['imap_recommended'] = 'Het gebruik van de vereenvoudigde adresparser is niet aanbevolen. Installeer de IMAP-extensie voor PHP voor volledige RFC822-ondersteuning.';
$PHPMAILER_LANG['deprecated_argument'] = 'Verouderd argument: ';
+22 -22
View File
@@ -5,29 +5,29 @@
* @package PHPMailer
*/
$PHPMAILER_LANG['authenticate'] = 'Błąd SMTP: Nie można przeprowadzić uwierzytelnienia.';
$PHPMAILER_LANG['buggy_php'] = 'Twoja wersja PHP zawiera błąd, który może powodować uszkodzenie wiadomości. Aby go naprawić, przełącz się na wysyłanie za pomocą SMTP, wyłącz opcję mail.add_x_header w php.ini, przełącz się na MacOS lub Linux lub zaktualizuj PHP do wersji 7.0.17+ lub 7.1.3+.';
$PHPMAILER_LANG['connect_host'] = 'Błąd SMTP: Nie można połączyć się z wybranym hostem.';
$PHPMAILER_LANG['data_not_accepted'] = 'Błąd SMTP: Dane nie zostały przyjęte.';
$PHPMAILER_LANG['empty_message'] = 'Wiadomość jest pusta.';
$PHPMAILER_LANG['encoding'] = 'Błędny sposób kodowania znaków: ';
$PHPMAILER_LANG['execute'] = 'Nie można uruchomić: ';
$PHPMAILER_LANG['extension_missing'] = 'Brakujące rozszerzenie: ';
$PHPMAILER_LANG['authenticate'] = 'Błąd SMTP: nie udało się przeprowadzić uwierzytelnienia.';
$PHPMAILER_LANG['buggy_php'] = 'Używana wersja PHP zawiera błąd, który może powodować uszkodzenie wiadomości. Aby temu zapobiec, użyj wysyłki przez SMTP, wyłącz opcję mail.add_x_header w php.ini, przejdź na macOS lub Linux, lub zaktualizuj PHP do wersji 7.0.17+ albo 7.1.3+.';
$PHPMAILER_LANG['connect_host'] = 'Błąd SMTP: nie udało się połączyć z serwerem (hostem).';
$PHPMAILER_LANG['data_not_accepted'] = 'Błąd SMTP: dane wiadomości nie zostały przyjęte przez serwer.';
$PHPMAILER_LANG['empty_message'] = 'Nie można wysłać pustej wiadomości.';
$PHPMAILER_LANG['encoding'] = 'Nieobsługiwane kodowanie znaków: ';
$PHPMAILER_LANG['execute'] = 'Nie udało się uruchomić polecenia: ';
$PHPMAILER_LANG['extension_missing'] = 'Brak wymaganego rozszerzenia PHP: ';
$PHPMAILER_LANG['file_access'] = 'Brak dostępu do pliku: ';
$PHPMAILER_LANG['file_open'] = 'Nie można otworzyć pliku: ';
$PHPMAILER_LANG['from_failed'] = 'Następujący adres nadawcy jest nieprawidłowy lub nie istnieje: ';
$PHPMAILER_LANG['instantiate'] = 'Nie można wywołać funkcji mail(). Sprawdź konfigurację serwera.';
$PHPMAILER_LANG['invalid_address'] = 'Nie można wysłać wiadomości, ' . 'następujący adres odbiorcy jest nieprawidłowy lub nie istnieje: ';
$PHPMAILER_LANG['invalid_header'] = 'Nieprawidłowa nazwa lub wartość nagłówka';
$PHPMAILER_LANG['file_open'] = 'Nie udało się otworzyć pliku: ';
$PHPMAILER_LANG['from_failed'] = 'Nieprawidłowy adres nadawcy: ';
$PHPMAILER_LANG['instantiate'] = 'Nie można zainicjować funkcji mail(). Sprawdź konfigurację serwera.';
$PHPMAILER_LANG['invalid_address'] = 'Nie można wysłać wiadomości. Nieprawidłowy adres odbiorcy: ';
$PHPMAILER_LANG['invalid_header'] = 'Nieprawidłowa nazwa lub wartość nagłówka.';
$PHPMAILER_LANG['invalid_hostentry'] = 'Nieprawidłowy wpis hosta: ';
$PHPMAILER_LANG['invalid_host'] = 'Nieprawidłowy host: ';
$PHPMAILER_LANG['provide_address'] = 'Należy podać prawidłowy adres email odbiorcy.';
$PHPMAILER_LANG['invalid_host'] = 'Nieprawidłowa nazwa hosta: ';
$PHPMAILER_LANG['provide_address'] = 'Musisz podać co najmniej jeden prawidłowy adres e-mail odbiorcy.';
$PHPMAILER_LANG['mailer_not_supported'] = 'Wybrana metoda wysyłki wiadomości nie jest obsługiwana.';
$PHPMAILER_LANG['recipients_failed'] = 'Błąd SMTP: Następujący odbiorcy są nieprawidłowi lub nie istnieją: ';
$PHPMAILER_LANG['signing'] = 'Błąd podpisywania wiadomości: ';
$PHPMAILER_LANG['smtp_code'] = 'Kod SMTP: ';
$PHPMAILER_LANG['smtp_code_ex'] = 'Dodatkowe informacje SMTP: ';
$PHPMAILER_LANG['smtp_connect_failed'] = 'Wywołanie funkcji SMTP Connect() zostało zakończone niepowodzeniem.';
$PHPMAILER_LANG['smtp_detail'] = 'Szczegóły: ';
$PHPMAILER_LANG['smtp_error'] = 'Błąd SMTP: ';
$PHPMAILER_LANG['recipients_failed'] = 'Błąd SMTP: nie udało się wysłać do następujących odbiorców: ';
$PHPMAILER_LANG['signing'] = 'Błąd podpisywania wiadomości cyfrowo: ';
$PHPMAILER_LANG['smtp_code'] = 'Kod odpowiedzi SMTP: ';
$PHPMAILER_LANG['smtp_code_ex'] = 'Dodatkowe informacje serwera SMTP: ';
$PHPMAILER_LANG['smtp_connect_failed'] = 'Nie udało się nawiązać połączenia za pomocą SMTP Connect().';
$PHPMAILER_LANG['smtp_detail'] = 'Szczegóły błędu: ';
$PHPMAILER_LANG['smtp_error'] = 'Błąd serwera SMTP: ';
$PHPMAILER_LANG['variable_set'] = 'Nie można ustawić lub zmodyfikować zmiennej: ';
+24 -17
View File
@@ -3,25 +3,32 @@
/**
* Portuguese (European) PHPMailer language file: refer to English translation for definitive list
* @package PHPMailer
* @author Jonadabe <jonadabe@hotmail.com>
* @author João Vieira <mail@joaovieira.eu>
*/
$PHPMAILER_LANG['authenticate'] = 'Erro do SMTP: Não foi possível realizar a autenticação.';
$PHPMAILER_LANG['connect_host'] = 'Erro do SMTP: Não foi possível realizar ligação com o servidor SMTP.';
$PHPMAILER_LANG['data_not_accepted'] = 'Erro do SMTP: Os dados foram rejeitados.';
$PHPMAILER_LANG['empty_message'] = 'A mensagem no e-mail está vazia.';
$PHPMAILER_LANG['authenticate'] = 'Erro SMTP: Falha na autenticação.';
$PHPMAILER_LANG['buggy_php'] = 'A sua versão do PHP tem um bug que pode causar mensagens corrompidas. Para resolver, utilize o envio por SMTP, desative a opção mail.add_x_header no ficheiro php.ini, mude para MacOS ou Linux, ou atualize o PHP para a versão 7.0.17+ ou 7.1.3+.';
$PHPMAILER_LANG['connect_host'] = 'Erro SMTP: Não foi possível ligar ao servidor SMTP.';
$PHPMAILER_LANG['data_not_accepted'] = 'Erro SMTP: Dados não aceites.';
$PHPMAILER_LANG['empty_message'] = 'A mensagem de e-mail está vazia.';
$PHPMAILER_LANG['encoding'] = 'Codificação desconhecida: ';
$PHPMAILER_LANG['execute'] = 'Não foi possível executar: ';
$PHPMAILER_LANG['file_access'] = 'Não foi possível aceder o ficheiro: ';
$PHPMAILER_LANG['file_open'] = 'Abertura do ficheiro: Não foi possível abrir o ficheiro: ';
$PHPMAILER_LANG['from_failed'] = 'Ocorreram falhas nos endereços dos seguintes remententes: ';
$PHPMAILER_LANG['instantiate'] = 'Não foi possível iniciar uma instância da função mail.';
$PHPMAILER_LANG['invalid_address'] = 'Não foi enviado nenhum e-mail para o endereço de e-mail inválido: ';
$PHPMAILER_LANG['mailer_not_supported'] = ' mailer não é suportado.';
$PHPMAILER_LANG['provide_address'] = 'Tem de fornecer pelo menos um endereço como destinatário do e-mail.';
$PHPMAILER_LANG['recipients_failed'] = 'Erro do SMTP: O endereço do seguinte destinatário falhou: ';
$PHPMAILER_LANG['signing'] = 'Erro ao assinar: ';
$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP Connect() falhou.';
$PHPMAILER_LANG['smtp_error'] = 'Erro de servidor SMTP: ';
$PHPMAILER_LANG['variable_set'] = 'Não foi possível definir ou redefinir a variável: ';
$PHPMAILER_LANG['extension_missing'] = 'Extensão em falta: ';
$PHPMAILER_LANG['file_access'] = 'Não foi possível aceder ao ficheiro: ';
$PHPMAILER_LANG['file_open'] = 'Erro ao abrir o ficheiro: ';
$PHPMAILER_LANG['from_failed'] = 'O envio falhou para o seguinte endereço do remetente: ';
$PHPMAILER_LANG['instantiate'] = 'Não foi possível instanciar a função mail.';
$PHPMAILER_LANG['invalid_address'] = 'Endereço de e-mail inválido: ';
$PHPMAILER_LANG['invalid_header'] = 'Nome ou valor do cabeçalho inválido.';
$PHPMAILER_LANG['invalid_hostentry'] = 'Entrada de host inválida: ';
$PHPMAILER_LANG['invalid_host'] = 'Host inválido: ';
$PHPMAILER_LANG['mailer_not_supported'] = 'O cliente de e-mail não é suportado.';
$PHPMAILER_LANG['provide_address'] = 'Deve fornecer pelo menos um endereço de destinatário.';
$PHPMAILER_LANG['recipients_failed'] = 'Erro SMTP: Falha no envio para os seguintes destinatários: ';
$PHPMAILER_LANG['signing'] = 'Erro ao assinar: ';
$PHPMAILER_LANG['smtp_code'] = 'Código SMTP: ';
$PHPMAILER_LANG['smtp_code_ex'] = 'Informações adicionais SMTP: ';
$PHPMAILER_LANG['smtp_connect_failed'] = 'Falha na função SMTP connect().';
$PHPMAILER_LANG['smtp_detail'] = 'Detalhes: ';
$PHPMAILER_LANG['smtp_error'] = 'Erro do servidor SMTP: ';
$PHPMAILER_LANG['variable_set'] = 'Não foi possível definir ou redefinir a variável: ';
@@ -8,6 +8,7 @@
* @author Mehmet Benlioğlu
* @author @yasinaydin
* @author Ogün Karakuş
* @author Mustafa Deniz Buksur
*/
$PHPMAILER_LANG['authenticate'] = 'SMTP Hatası: Oturum açılamadı.';
@@ -36,3 +37,7 @@ $PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP connect() fonksiyonu başarısı
$PHPMAILER_LANG['smtp_detail'] = 'SMTP SMTP Detayı: ';
$PHPMAILER_LANG['smtp_error'] = 'SMTP sunucu hatası: ';
$PHPMAILER_LANG['variable_set'] = 'Değişken ayarlanamadı ya da sıfırlanamadı: ';
$PHPMAILER_LANG['no_smtputf8'] = 'Unicode adreslere gönderim için gereken SMTPUTF8 desteği sunucu tarafından desteklenmiyor.';
$PHPMAILER_LANG['imap_recommended'] = 'Basitleştirilmiş adres ayrıştırıcısını kullanmanız önerilmez. ' .
'Tam RFC822 ayrıştırma için PHP IMAP eklentisini yükleyin.';
$PHPMAILER_LANG['deprecated_argument'] = 'Kullanımdan kaldırılmış argüman: ';
File diff suppressed because it is too large Load Diff
+20 -6
View File
@@ -45,8 +45,9 @@ class POP3
* The POP3 PHPMailer Version number.
*
* @var string
* @deprecated This constant will be removed in PHPMailer 8.0. Use `PHPMailer::VERSION` instead.
*/
const VERSION = '6.9.3';
const VERSION = '7.1.1';
/**
* Default POP3 port number.
@@ -211,9 +212,9 @@ class POP3
} else {
$this->tval = (int) $timeout;
}
$this->do_debug = $debug_level;
$this->username = $username;
$this->password = $password;
$this->do_debug = (int) $debug_level;
$this->username = self::stripControls($username);
$this->password = self::stripControls($password);
//Reset the error log
$this->errors = [];
//Connect
@@ -318,7 +319,8 @@ class POP3
if (empty($password)) {
$password = $this->password;
}
$username = self::stripControls($username);
$password = self::stripControls($password);
//Send the Username
$this->sendString("USER $username" . static::LE);
$pop3_response = $this->getResponse();
@@ -406,7 +408,7 @@ class POP3
/**
* Checks the POP3 server response.
* Looks for for +OK or -ERR.
* Looks for +OK or -ERR.
*
* @param string $string
*
@@ -466,4 +468,16 @@ class POP3
"errno: $errno errstr: $errstr; errfile: $errfile; errline: $errline"
);
}
/**
* Strip all control chars from a string.
*
* @param $string
*
* @return string
*/
protected static function stripControls($string)
{
return preg_replace('/[\x00-\x1F\x7F]/u', '', $string);
}
}
+121 -13
View File
@@ -34,8 +34,9 @@ class SMTP
* The PHPMailer SMTP version number.
*
* @var string
* @deprecated This constant will be removed in PHPMailer 8.0. Use `PHPMailer::VERSION` instead.
*/
const VERSION = '6.9.3';
const VERSION = '7.1.1';
/**
* SMTP line break constant.
@@ -159,6 +160,15 @@ class SMTP
*/
public $do_verp = false;
/**
* Whether to use SMTPUTF8.
*
* @see https://www.rfc-editor.org/rfc/rfc6531
*
* @var bool
*/
public $do_smtputf8 = false;
/**
* The timeout value for connection, in seconds.
* Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2.
@@ -196,6 +206,7 @@ class SMTP
'Haraka' => '/[\d]{3} Message Queued \((.*)\)/',
'ZoneMTA' => '/[\d]{3} Message queued as (.*)/',
'Mailjet' => '/[\d]{3} OK queued as (.*)/',
'Gsmtp' => '/[\d]{3} 2\.0\.0 OK (.*) - gsmtp/',
];
/**
@@ -484,7 +495,9 @@ class SMTP
//PHP 5.6.7 dropped inclusion of TLS 1.1 and 1.2 in STREAM_CRYPTO_METHOD_TLS_CLIENT
//so add them back in manually if we can
if (defined('STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT')) {
// phpcs:ignore PHPCompatibility.Constants.NewConstants.stream_crypto_method_tlsv1_2_clientFound
$crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT;
// phpcs:ignore PHPCompatibility.Constants.NewConstants.stream_crypto_method_tlsv1_1_clientFound
$crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT;
}
@@ -623,11 +636,48 @@ class SMTP
if (null === $OAuth) {
return false;
}
$oauth = $OAuth->getOauth64();
//Start authentication
if (!$this->sendCommand('AUTH', 'AUTH XOAUTH2 ' . $oauth, 235)) {
return false;
try {
$oauth = $OAuth->getOauth64();
} catch (\Exception $e) {
// We catch all exceptions and convert them to PHPMailer exceptions to be able to
// handle them correctly later
throw new Exception("SMTP authentication error", 0, $e);
}
/*
* An SMTP command line can have a maximum length of 512 bytes, including the command name,
* so the base64-encoded OAUTH token has a maximum length of:
* 512 - 13 (AUTH XOAUTH2) - 2 (CRLF) = 497 bytes
* If the token is longer than that, the command and the token must be sent separately as described in
* https://www.rfc-editor.org/rfc/rfc4954#section-4
*/
if ($oauth === '') {
//Sending an empty auth token is legitimate, but it must be encoded as '='
//to indicate it's not a 2-part command
if (!$this->sendCommand('AUTH', 'AUTH XOAUTH2 =', 235)) {
return false;
}
} elseif (strlen($oauth) <= 497) {
//Authenticate using a token in the initial-response part
if (!$this->sendCommand('AUTH', 'AUTH XOAUTH2 ' . $oauth, 235)) {
return false;
}
} else {
//The token is too long, so we need to send it in two parts.
//Send the auth command without a token and expect a 334
if (!$this->sendCommand('AUTH', 'AUTH XOAUTH2', 334)) {
return false;
}
//Send the token
if (!$this->sendCommand('OAuth TOKEN', $oauth, [235, 334])) {
return false;
}
//If the server answers with 334, send an empty line and wait for a 235
if (
substr($this->last_reply, 0, 3) === '334'
&& $this->sendCommand('AUTH End', '', 235)
) {
return false;
}
}
break;
default:
@@ -720,6 +770,25 @@ class SMTP
}
}
private function iterateLines($s)
{
$start = 0;
$length = strlen($s);
for ($i = 0; $i < $length; $i++) {
$c = $s[$i];
if ($c === "\n" || $c === "\r") {
yield substr($s, $start, $i - $start);
if ($c === "\r" && $i + 1 < $length && $s[$i + 1] === "\n") {
$i++;
}
$start = $i + 1;
}
}
yield substr($s, $start);
}
/**
* Send an SMTP DATA command.
* Issues a data command and sends the msg_data to the server,
@@ -748,15 +817,16 @@ class SMTP
* NOTE: this does not count towards line-length limit.
*/
//Normalize line breaks before exploding
$lines = explode("\n", str_replace(["\r\n", "\r"], "\n", $msg_data));
//Iterate over lines with normalized line breaks
$lines = $this->iterateLines($msg_data);
/* To distinguish between a complete RFC822 message and a plain message body, we check if the first field
* of the first line (':' separated) does not contain a space then it _should_ be a header, and we will
* process all lines before a blank line as headers.
*/
$field = substr($lines[0], 0, strpos($lines[0], ':'));
$first_line = $lines->current();
$field = substr($first_line, 0, strpos($first_line, ':'));
$in_headers = false;
if (!empty($field) && strpos($field, ' ') === false) {
$in_headers = true;
@@ -913,7 +983,15 @@ class SMTP
* $from. Returns true if successful or false otherwise. If True
* the mail transaction is started and then one or more recipient
* commands may be called followed by a data command.
* Implements RFC 821: MAIL <SP> FROM:<reverse-path> <CRLF>.
* Implements RFC 821: MAIL <SP> FROM:<reverse-path> <CRLF> and
* two extensions, namely XVERP and SMTPUTF8.
*
* The server's EHLO response is not checked. If use of either
* extensions is enabled even though the server does not support
* that, mail submission will fail.
*
* XVERP is documented at https://www.postfix.org/VERP_README.html
* and SMTPUTF8 is specified in RFC 6531.
*
* @param string $from Source address of this message
*
@@ -922,10 +1000,11 @@ class SMTP
public function mail($from)
{
$useVerp = ($this->do_verp ? ' XVERP' : '');
$useSmtputf8 = ($this->do_smtputf8 ? ' SMTPUTF8' : '');
return $this->sendCommand(
'MAIL FROM',
'MAIL FROM:<' . $from . '>' . $useVerp,
'MAIL FROM:<' . $from . '>' . $useSmtputf8 . $useVerp,
250
);
}
@@ -1210,7 +1289,7 @@ class SMTP
* 3. EHLO has been sent -
* $name == 'HELO'|'EHLO': returns the server name
* $name == any other string: if extension $name exists, returns True
* or its options (e.g. AUTH mechanisms supported). Otherwise returns False.
* or its options (e.g. AUTH mechanisms supported). Otherwise, returns False.
*
* @param string $name Name of SMTP extension or 'HELO'|'EHLO'
*
@@ -1291,7 +1370,16 @@ class SMTP
//stream_select returns false when the `select` system call is interrupted
//by an incoming signal, try the select again
if (stripos($message, 'interrupted system call') !== false) {
if (
stripos($message, 'interrupted system call') !== false ||
(
// on applications with a different locale than english, the message above is not found because
// it's translated. So we also check for the SOCKET_EINTR constant which is defined under
// Windows and UNIX-like platforms (if available on the platform).
defined('SOCKET_EINTR') &&
stripos($message, 'stream_select(): Unable to select [' . SOCKET_EINTR . ']') !== false
)
) {
$this->edebug(
'SMTP -> get_lines(): retrying stream_select',
self::DEBUG_LOWLEVEL
@@ -1364,6 +1452,26 @@ class SMTP
return $this->do_verp;
}
/**
* Enable or disable use of SMTPUTF8.
*
* @param bool $enabled
*/
public function setSMTPUTF8($enabled = false)
{
$this->do_smtputf8 = $enabled;
}
/**
* Get SMTPUTF8 use.
*
* @return bool
*/
public function getSMTPUTF8()
{
return $this->do_smtputf8;
}
/**
* Set error messages and codes.
*