Rapport-Laravel/app/Helpers/TgicsHelper.php

62 lines
1.9 KiB
PHP

<?php
namespace App\Helpers;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
class TgicsHelper
{
/**
* Batch survey counts from TGICS API keyed by contact_id.
*
* @param array<int, string> $contactIds
* @return array{counts: array<string, int>, total: int}
*/
public static function getSurveyCounts(array $contactIds): array
{
$ids = array_values(array_unique(array_filter(array_map(static function ($id) {
return trim((string) $id);
}, $contactIds))));
if (count($ids) === 0) {
return ['counts' => [], 'total' => 0];
}
$base = rtrim((string) env('TGICS_API_BASE', ''), '/');
if ($base === '') {
Log::warning('TGICS_API_BASE is not configured; survey counts defaulting to 0');
return ['counts' => array_fill_keys($ids, 0), 'total' => 0];
}
try {
$response = Http::timeout(8)->acceptJson()->get($base.'/api/surveys/counts', [
'contact_ids' => implode(',', $ids),
]);
if (!$response->successful()) {
Log::warning('TGICS survey counts request failed', [
'status' => $response->status(),
'body' => $response->body(),
]);
return ['counts' => array_fill_keys($ids, 0), 'total' => 0];
}
$json = $response->json();
$countsRaw = $json['data']['counts'] ?? [];
$counts = [];
$total = 0;
foreach ($ids as $id) {
$n = (int) ($countsRaw[$id] ?? 0);
$counts[$id] = $n;
$total += $n;
}
return ['counts' => $counts, 'total' => $total];
} catch (\Throwable $e) {
Log::error('TGICS survey counts error: '.$e->getMessage());
return ['counts' => array_fill_keys($ids, 0), 'total' => 0];
}
}
}