Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
23 / 23
100.00% covered (success)
100.00%
2 / 2
CRAP
100.00% covered (success)
100.00%
1 / 1
RevokeClientPortalAction
100.00% covered (success)
100.00%
23 / 23
100.00% covered (success)
100.00%
2 / 2
3
100.00% covered (success)
100.00%
1 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 execute
100.00% covered (success)
100.00%
22 / 22
100.00% covered (success)
100.00%
1 / 1
2
1<?php
2
3declare(strict_types=1);
4
5namespace ImovelZapAi\ClientPortal\Application\Actions;
6
7use App\Models\User;
8use Illuminate\Support\Facades\DB;
9use ImovelZapAi\ClientPortal\Application\Services\PortalActivityWriter;
10use ImovelZapAi\ClientPortal\Application\Services\PortalTokenService;
11use ImovelZapAi\ClientPortal\Domain\Enums\PortalActivityEvent;
12use ImovelZapAi\ClientPortal\Domain\Enums\PortalStatus;
13use ImovelZapAi\ClientPortal\Domain\Exceptions\ClientPortalException;
14use ImovelZapAi\ClientPortal\Infrastructure\Persistence\Eloquent\ClientPortalModel;
15use ImovelZapAi\ClientPortal\Infrastructure\Persistence\Eloquent\PortalAccessTokenModel;
16
17final class RevokeClientPortalAction
18{
19    public function __construct(
20        private readonly PortalTokenService $tokens,
21        private readonly PortalActivityWriter $activity,
22    ) {}
23
24    public function execute(ClientPortalModel $portal, User $actor): ClientPortalModel
25    {
26        if ($portal->status === PortalStatus::Revoked) {
27            throw ClientPortalException::invalidState('portal já revogado.');
28        }
29
30        return DB::transaction(function () use ($portal, $actor): ClientPortalModel {
31            $portal->forceFill([
32                'status' => PortalStatus::Revoked,
33                'revoked_at' => now(),
34            ])->save();
35
36            PortalAccessTokenModel::query()
37                ->where('client_portal_id', $portal->id)
38                ->whereNull('revoked_at')
39                ->get()
40                ->each(fn (PortalAccessTokenModel $t) => $this->tokens->revoke($t));
41
42            $this->activity->write(
43                $portal->tenant_id,
44                $portal->id,
45                PortalActivityEvent::PortalRevoked,
46                actorType: 'broker',
47                actorUserId: (int) $actor->id,
48                message: 'Portal revogado.',
49            );
50
51            return $portal->fresh();
52        });
53    }
54}