fix: api_report busca URL en company_endpoints por endpoint_key

- executeApiReport ahora consulta company_endpoints para obtener la URL
- Soporta metodos GET/POST segun configuracion
- Date_mode: today/last_30 para fechas dinámicas
This commit is contained in:
Lizandro Guarnizo
2026-06-27 11:38:25 -05:00
parent 51c187e47d
commit 010613846c
2 changed files with 39 additions and 17 deletions
+33 -11
View File
@@ -100,32 +100,54 @@ class NormalBot
private static function executeApiReport(array $params, array $context, array $company, int $ctxId): ?array
{
$endpoint = $params['endpoint'] ?? '';
if ($endpoint === '') {
$endpointKey = $params['endpoint_key'] ?? '';
if ($endpointKey === '') {
return self::sendText('Error: endpoint no configurado.', $context['from'], $company);
}
$baseUrl = rtrim($company['api_base_url'] ?? '', '/');
$url = $baseUrl . '/' . ltrim($endpoint, '/');
$apiKey = $company['api_key'] ?? '';
$stmt = db()->prepare("SELECT url, method FROM company_endpoints WHERE company_id = ? AND endpoint_key = ? AND is_active = 1 LIMIT 1");
$stmt->execute([(int)$company['id'], $endpointKey]);
$ep = $stmt->fetch();
$query = $params['query'] ?? [];
if (!empty($query)) {
$url .= '?' . http_build_query($query);
if (!$ep || empty($ep['url'])) {
self::log("API report: endpoint_key '{$endpointKey}' no configurado para company {$company['id']}");
return self::sendText('El informe solicitado no está configurado. Contacta al administrador.', $context['from'], $company);
}
$url .= (str_contains($url, '?') ? '&' : '?') . 'telefono=' . urlencode($context['from']) . '&nombre=' . urlencode($context['name'] ?? '');
$url = $ep['url'];
$method = strtoupper($ep['method'] ?? 'GET');
$apiKey = $company['api_key'] ?? '';
$extraQuery = $params['query'] ?? [];
$dateMode = $params['date_mode'] ?? '';
if ($dateMode === 'today') {
$extraQuery['fecha'] = date('Y-m-d');
} elseif ($dateMode === 'last_30') {
$extraQuery['fecha_inicio'] = date('Y-m-d', strtotime('-30 days'));
$extraQuery['fecha_fin'] = date('Y-m-d');
}
$extraQuery['telefono'] = $context['from'];
$extraQuery['nombre'] = $context['name'] ?? '';
$glue = str_contains($url, '?') ? '&' : '?';
$url .= $glue . http_build_query($extraQuery);
$ch = curl_init($url);
curl_setopt_array($ch, [
$curlOpts = [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_TIMEOUT => 60,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . $apiKey,
'X-API-Key: ' . $apiKey,
'User-Agent: bot-palmas360/1.0',
],
]);
];
if ($method === 'POST') {
$curlOpts[CURLOPT_POST] = true;
$curlOpts[CURLOPT_POSTFIELDS] = '{}';
}
curl_setopt_array($ch, $curlOpts);
$content = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);