@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
final class DeclaredOriginStatistics
|
||||
{
|
||||
/** @return array<string, list<array{code: string|null, name: string, count: int}>> */
|
||||
public function forManager(User $actor, ?string $origin = null): array
|
||||
{
|
||||
abort_unless($actor->can('manage-portal'), 403);
|
||||
$names = array_column(app(CountryCatalogue::class)->all(), 'name', 'code');
|
||||
$groups = [];
|
||||
foreach (DB::table('interest_requests')->whereNull('deleted_at')->select('metadata')->cursor() as $row) {
|
||||
$metadata = json_decode($row->metadata ?? '{}', true);
|
||||
$code = $metadata['declared_origin_country_code'] ?? null;
|
||||
$key = is_string($code) && isset($names[$code]) ? $code : '';
|
||||
$groups[$key] = ($groups[$key] ?? 0) + 1;
|
||||
}
|
||||
$desk = [];
|
||||
if (Schema::hasTable('desk_requests')) {
|
||||
foreach (DB::table('desk_requests')->whereNotIn('status', ['draft', 'cancelled'])->select('payload')->cursor() as $row) {
|
||||
$code = app(VirtualDesk::class)->decode($row->payload)['declared_origin_country_code'] ?? null;
|
||||
$key = is_string($code) && isset($names[$code]) ? $code : '';
|
||||
$desk[$key] = ($desk[$key] ?? 0) + 1;
|
||||
}
|
||||
}
|
||||
// Distinct request collections; summing them could count the same investor twice.
|
||||
if ($origin !== null && $origin !== '') {
|
||||
$key = $origin === 'unknown' ? '' : $origin;
|
||||
$groups = array_intersect_key($groups, [$key => true]);
|
||||
$desk = array_intersect_key($desk, [$key => true]);
|
||||
}
|
||||
|
||||
return ['interests' => $this->format($groups, $names), 'desk' => $this->format($desk, $names)];
|
||||
}
|
||||
|
||||
/** @param array<string, int> $counts
|
||||
* @param array<string, string> $names
|
||||
* @return list<array{code: string|null, name: string, count: int}> */
|
||||
private function format(array $counts, array $names): array
|
||||
{
|
||||
ksort($counts);
|
||||
|
||||
return array_map(fn (string $code, int $count) => ['code' => $code ?: null, 'name' => $names[$code] ?? 'Não informado', 'count' => $count], array_keys($counts), array_values($counts));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user