Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 25
0.00% covered (danger)
0.00%
0 / 3
CRAP
0.00% covered (danger)
0.00%
0 / 1
UpdateDashboardLayoutAction
0.00% covered (danger)
0.00%
0 / 25
0.00% covered (danger)
0.00%
0 / 3
110
0.00% covered (danger)
0.00%
0 / 1
 execute
0.00% covered (danger)
0.00%
0 / 19
0.00% covered (danger)
0.00%
0 / 1
30
 canManageTeam
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
6
 resolveRole
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
12
1<?php
2
3declare(strict_types=1);
4
5namespace ImovelZapAi\Analytics\Application\Actions;
6
7use App\Models\User;
8use ImovelZapAi\Analytics\Domain\Enums\DashboardRole;
9use ImovelZapAi\Analytics\Domain\Exceptions\AnalyticsException;
10use ImovelZapAi\Analytics\Infrastructure\Persistence\Eloquent\AnalyticsDashboardLayoutModel;
11use ImovelZapAi\Authentication\Domain\Enums\SystemRole;
12
13final class UpdateDashboardLayoutAction
14{
15    public function execute(
16        string $tenantId,
17        User $actor,
18        array $widgets,
19        ?int $targetUserId = null,
20    ): AnalyticsDashboardLayoutModel {
21        $userId = $targetUserId ?? $actor->id;
22
23        if ($targetUserId !== null && $targetUserId !== $actor->id && ! $this->canManageTeam($actor)) {
24            throw AnalyticsException::layoutForbidden();
25        }
26
27        $role = $this->resolveRole($actor);
28
29        $layout = AnalyticsDashboardLayoutModel::query()
30            ->where('tenant_id', $tenantId)
31            ->where('user_id', $userId)
32            ->first();
33
34        if ($layout === null) {
35            $layout = app(GetOrCreateDashboardLayoutAction::class)->execute(
36                $tenantId,
37                User::query()->findOrFail($userId),
38                $role,
39            );
40        }
41
42        $layout->update([
43            'widgets' => $widgets,
44            'updated_at' => now(),
45        ]);
46
47        return $layout->fresh();
48    }
49
50    private function canManageTeam(User $user): bool
51    {
52        return $user->hasRole(SystemRole::Admin->value) || $user->hasRole(SystemRole::Gestor->value);
53    }
54
55    private function resolveRole(User $user): DashboardRole
56    {
57        if ($user->hasRole(SystemRole::Admin->value)) {
58            return DashboardRole::Owner;
59        }
60        if ($user->hasRole(SystemRole::Gestor->value)) {
61            return DashboardRole::Manager;
62        }
63
64        return DashboardRole::Broker;
65    }
66}