Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
40 / 40 |
|
100.00% |
1 / 1 |
CRAP | |
100.00% |
1 / 1 |
| GetImportDashboardQuery | |
100.00% |
40 / 40 |
|
100.00% |
1 / 1 |
4 | |
100.00% |
1 / 1 |
| execute | |
100.00% |
40 / 40 |
|
100.00% |
1 / 1 |
4 | |||
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace ImovelZapAi\Importing\Application\Queries; |
| 6 | |
| 7 | use ImovelZapAi\Importing\Domain\Enums\ImportJobStatus; |
| 8 | use ImovelZapAi\Importing\Infrastructure\Persistence\Eloquent\ImportJobModel; |
| 9 | |
| 10 | final class GetImportDashboardQuery |
| 11 | { |
| 12 | /** |
| 13 | * @return array<string, mixed> |
| 14 | */ |
| 15 | public function execute(string $tenantId): array |
| 16 | { |
| 17 | $latest = ImportJobModel::query() |
| 18 | ->where('tenant_id', $tenantId) |
| 19 | ->latest() |
| 20 | ->first(); |
| 21 | |
| 22 | $completed = ImportJobModel::query() |
| 23 | ->where('tenant_id', $tenantId) |
| 24 | ->whereIn('status', [ |
| 25 | ImportJobStatus::Completed, |
| 26 | ImportJobStatus::CompletedWithErrors, |
| 27 | ]) |
| 28 | ->get(); |
| 29 | |
| 30 | $totalImported = (int) $completed->sum('imported_count') + (int) $completed->sum('updated_count'); |
| 31 | $totalErrors = (int) $completed->sum('failed_count') + (int) $completed->sum('error_listings'); |
| 32 | |
| 33 | $durations = $completed |
| 34 | ->filter(static fn (ImportJobModel $job) => $job->processing_started_at !== null && $job->completed_at !== null) |
| 35 | ->map(static fn (ImportJobModel $job) => $job->processing_started_at->diffInSeconds($job->completed_at)) |
| 36 | ->all(); |
| 37 | |
| 38 | $avgDuration = $durations === [] ? null : (int) round(array_sum($durations) / count($durations)); |
| 39 | |
| 40 | $queued = ImportJobModel::query() |
| 41 | ->where('tenant_id', $tenantId) |
| 42 | ->whereIn('status', [ |
| 43 | ImportJobStatus::Queued, |
| 44 | ImportJobStatus::Processing, |
| 45 | ImportJobStatus::Analyzing, |
| 46 | ]) |
| 47 | ->count(); |
| 48 | |
| 49 | return [ |
| 50 | 'latest' => $latest === null ? null : [ |
| 51 | 'id' => $latest->id, |
| 52 | 'status' => $latest->status->value ?? (string) $latest->status, |
| 53 | 'total_listings' => $latest->total_listings, |
| 54 | 'imported_count' => $latest->imported_count, |
| 55 | 'failed_count' => $latest->failed_count, |
| 56 | 'created_at' => $latest->created_at?->toIso8601String(), |
| 57 | ], |
| 58 | 'properties_imported' => $totalImported, |
| 59 | 'errors' => $totalErrors, |
| 60 | 'average_duration_seconds' => $avgDuration, |
| 61 | 'queue_size' => $queued, |
| 62 | ]; |
| 63 | } |
| 64 | } |