Files
scappoinspiaggianew/public/userarea/stats_export_lims_data.php
T

91 lines
3.2 KiB
PHP

<?php
include('include/headscript.php');
header('Content-Type: application/json');
$dbHandler = DBHandlerSelect::getInstance();
$pdo = $dbHandler->getConnection();
try {
// Data richiesta (default oggi). Formato atteso: Y-m-d
$date = $_GET['date'] ?? date('Y-m-d');
$d = DateTime::createFromFormat('Y-m-d', $date);
if (!$d || $d->format('Y-m-d') !== $date) {
throw new Exception('Data non valida');
}
// --- Export per cliente (status = 'l', giornata su export_date) ---
$stmtC = $pdo->prepare("
SELECT d.idclient AS idclient,
COUNT(*) AS tot
FROM datadb d
WHERE d.status = 'l'
AND DATE(d.export_date) = :d
GROUP BY d.idclient
ORDER BY tot DESC
");
$stmtC->execute(['d' => $date]);
$byClient = $stmtC->fetchAll(PDO::FETCH_ASSOC);
// --- Risolvi Nominativo cliente dalla cache locale (search_clienti.php) ---
$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', giornata su export_date) ---
$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
FROM datadb d
LEFT JOIN auth_users u ON u.id = d.user_id
WHERE d.status = 'l'
AND DATE(d.export_date) = :d
GROUP BY d.user_id, username
ORDER BY tot DESC
");
$stmtU->execute(['d' => $date]);
$byUser = $stmtU->fetchAll(PDO::FETCH_ASSOC);
// Normalizza tipi (COUNT torna stringa in PDO)
foreach ($byClient as &$r) {
$r['idclient'] = $r['idclient'] !== null ? (int)$r['idclient'] : null;
$r['tot'] = (int)$r['tot'];
$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'];
if (isset($r['username'])) $r['username'] = $r['username'] !== null && $r['username'] !== '' ? $r['username'] : null;
}
unset($r);
// --- Totale export della giornata ---
$totExport = array_sum(array_column($byClient, 'tot'));
// --- 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]);
$limsSamples = $stmtL->fetchColumn();
$limsSamples = ($limsSamples !== false) ? (int)$limsSamples : null;
echo json_encode([
'success' => true,
'date' => $date,
'totals' => ['export' => (int)$totExport],
'byClient' => $byClient,
'byUser' => $byUser,
'limsSamples' => $limsSamples,
]);
} catch (Exception $e) {
error_log('Stats export LIMS error: ' . $e->getMessage());
echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}