Files
html/api/ethica-stats-api.php

68 lines
2.8 KiB
PHP

<?php
require_once __DIR__ . '/_secrets.php';
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");
$pg = pg_connect("host=10.1.0.3 dbname=adx_system user=admin password=" . weval_secret('WEVAL_PG_ADMIN_PASS') . "");
if (!$pg) { echo json_encode(["error"=>"DB"]); exit; }
$total = (int)pg_fetch_result(pg_query($pg, "SELECT count(*) FROM ethica.medecins_real"), 0, 0);
$email = (int)pg_fetch_result(pg_query($pg, "SELECT count(*) FROM ethica.medecins_real WHERE email IS NOT NULL AND email!=''"), 0, 0);
$tel = (int)pg_fetch_result(pg_query($pg, "SELECT count(*) FROM ethica.medecins_real WHERE telephone IS NOT NULL AND telephone!=''"), 0, 0);
// Breakdown par pays
$countries = [];
$res = pg_query($pg, "
SELECT
COALESCE(UPPER(pays), 'UNKNOWN') as country,
COUNT(*) as hcps,
COUNT(email) FILTER (WHERE email IS NOT NULL AND email != '') as with_email,
COUNT(telephone) FILTER (WHERE telephone IS NOT NULL AND telephone != '') as with_tel
FROM ethica.medecins_real
GROUP BY UPPER(pays)
ORDER BY 2 DESC
");
while ($r = pg_fetch_assoc($res)) {
$countries[] = [
'country' => $r['country'],
'hcps' => (int)$r['hcps'],
'with_email' => (int)$r['with_email'],
'with_tel' => (int)$r['with_tel'],
'pct_email' => $r['hcps'] > 0 ? round(100.0 * $r['with_email'] / $r['hcps'], 1) : 0,
'pct_tel' => $r['hcps'] > 0 ? round(100.0 * $r['with_tel'] / $r['hcps'], 1) : 0,
];
}
// Consent log count
$consent = (int)pg_fetch_result(pg_query($pg, "SELECT count(*) FROM ethica.consent_log"), 0, 0);
// Campaigns
$campaigns_count = (int)pg_fetch_result(pg_query($pg, "SELECT count(*) FROM ethica.campaigns"), 0, 0);
// Tracking (opens/clicks/conversions last 30d)
$opens_30d = (int)pg_fetch_result(pg_query($pg, "SELECT count(*) FROM ethica.tracking_opens WHERE opened_at > NOW() - INTERVAL '30 days'"), 0, 0);
$clicks_30d = (int)pg_fetch_result(pg_query($pg, "SELECT count(*) FROM ethica.tracking_clicks WHERE clicked_at > NOW() - INTERVAL '30 days'"), 0, 0);
$conversions_30d = (int)pg_fetch_result(pg_query($pg, "SELECT count(*) FROM ethica.tracking_conversions WHERE converted_at > NOW() - INTERVAL '30 days'"), 0, 0);
echo json_encode([
"ok" => true,
"ts" => date('c'),
"total" => $total,
"with_email" => $email,
"with_telephone" => $tel,
"gap_email" => $total - $email,
"gap_telephone" => $total - $tel,
"pct_email" => $total > 0 ? round(100.0 * $email / $total, 1) : 0,
"pct_telephone" => $total > 0 ? round(100.0 * $tel / $total, 1) : 0,
"by_country" => $countries,
"consent_log" => $consent,
"campaigns" => $campaigns_count,
"last_30d" => [
"opens" => $opens_30d,
"clicks" => $clicks_30d,
"conversions" => $conversions_30d,
],
"source" => "PG ethica.medecins_real live",
], JSON_UNESCAPED_UNICODE);
pg_close($pg);