Skip to content

Commit e49a2d2

Browse files
feat(events): endpoints mobile de eventos (Feature 2, sem QR) (#585)
2 parents 3812550 + 3126c1c commit e49a2d2

6 files changed

Lines changed: 498 additions & 0 deletions

File tree

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
use He4rt\Events\Http\Controllers\Mobile\MobileEventController;
6+
use Illuminate\Support\Facades\Route;
7+
8+
Route::prefix('api/mobile')
9+
->middleware(['api', 'auth:api'])
10+
->group(static function (): void {
11+
Route::get('/events', [MobileEventController::class, 'index'])
12+
->name('mobile.events.index');
13+
14+
Route::get('/events/{event}', [MobileEventController::class, 'show'])
15+
->name('mobile.events.show');
16+
17+
Route::post('/events/{event}/enroll', [MobileEventController::class, 'enroll'])
18+
->name('mobile.events.enroll');
19+
20+
Route::post('/events/{event}/check-in', [MobileEventController::class, 'checkIn'])
21+
->name('mobile.events.check-in');
22+
});
Lines changed: 174 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,174 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace He4rt\Events\Http\Controllers\Mobile;
6+
7+
use App\Http\Controllers\Controller;
8+
use He4rt\Events\CheckIn\Actions\NumericCodeCheckInAction;
9+
use He4rt\Events\CheckIn\DTOs\NumericCodeCheckInDTO;
10+
use He4rt\Events\CheckIn\Exceptions\CheckInException;
11+
use He4rt\Events\CheckIn\Rules\CheckInCodeRule;
12+
use He4rt\Events\Enrollment\Actions\EnrollUserAction;
13+
use He4rt\Events\Enrollment\DTOs\EnrollUserDTO;
14+
use He4rt\Events\Enrollment\Enums\EnrollmentStatus;
15+
use He4rt\Events\Enrollment\Exceptions\EnrollmentException;
16+
use He4rt\Events\Enrollment\Models\Enrollment;
17+
use He4rt\Events\Event\Models\Event;
18+
use He4rt\Events\Http\Resources\EventDetailResource;
19+
use He4rt\Events\Http\Resources\EventResource;
20+
use He4rt\Identity\User\Models\User;
21+
use Illuminate\Database\Eloquent\Relations\Relation;
22+
use Illuminate\Http\JsonResponse;
23+
use Illuminate\Http\Request;
24+
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
25+
use Illuminate\Http\Response;
26+
use Illuminate\Support\Facades\Date;
27+
use Illuminate\Support\Facades\RateLimiter;
28+
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
29+
30+
final class MobileEventController extends Controller
31+
{
32+
/**
33+
* Listar eventos
34+
*
35+
* Retorna os eventos visíveis a participantes (publicados, concluídos
36+
* ou cancelados), mais próximos primeiro, com o status de inscrição
37+
* do usuário autenticado quando houver.
38+
*/
39+
public function index(Request $request): AnonymousResourceCollection
40+
{
41+
/** @var User $user */
42+
$user = $request->user();
43+
44+
$events = Event::query()
45+
->with(['enrollments' => fn (Relation $query): Relation => $query->where('user_id', $user->id)])
46+
->viewableByParticipant()
47+
->orderBy('starts_at')
48+
->simplePaginate(20);
49+
50+
return EventResource::collection($events);
51+
}
52+
53+
/**
54+
* Detalhe do evento
55+
*
56+
* Inclui a inscrição do usuário (se houver) e os mesmos booleans que
57+
* o painel web usa pra decidir a ação disponível (can_apply,
58+
* can_confirm_presence, is_event_full).
59+
*/
60+
public function show(Request $request, Event $event): EventDetailResource
61+
{
62+
throw_unless($event->status->isViewableByParticipant(), NotFoundHttpException::class);
63+
64+
$event->load('enrollmentPolicy');
65+
66+
/** @var User $user */
67+
$user = $request->user();
68+
69+
$enrollment = Enrollment::query()
70+
->where('event_id', $event->id)
71+
->where('user_id', $user->id)
72+
->first();
73+
74+
return new EventDetailResource($event, $enrollment);
75+
}
76+
77+
/**
78+
* Inscrever-se no evento
79+
*
80+
* Cobre RSVP e candidatura (application) — a mesma Action decide o
81+
* status inicial (confirmed, waitlisted ou pending) de acordo com a
82+
* política de inscrição do evento.
83+
*/
84+
public function enroll(Request $request, Event $event, EnrollUserAction $enrollUser): JsonResponse
85+
{
86+
throw_unless($event->status->isViewableByParticipant(), NotFoundHttpException::class);
87+
88+
$request->validate([
89+
'application_data' => ['sometimes', 'array'],
90+
]);
91+
92+
/** @var array<string, mixed>|null $applicationData */
93+
$applicationData = $request->input('application_data');
94+
95+
/** @var User $user */
96+
$user = $request->user();
97+
98+
try {
99+
$enrollment = $enrollUser->handle(new EnrollUserDTO(
100+
eventId: $event->id,
101+
userId: $user->id,
102+
applicationData: $applicationData,
103+
));
104+
} catch (EnrollmentException $enrollmentException) {
105+
return response()->json(['message' => $enrollmentException->getMessage()], $enrollmentException->getCode());
106+
}
107+
108+
return response()->json([
109+
'status' => $enrollment->status->value,
110+
'waitlist_position' => $enrollment->waitlist_position,
111+
], Response::HTTP_CREATED);
112+
}
113+
114+
/**
115+
* Check-in por código numérico
116+
*
117+
* Único método de check-in self-service disponível hoje (QR fica pra
118+
* uma iteração futura — ver docs/plans/2026-09-22-api-mobile-jwt.md).
119+
*/
120+
public function checkIn(Request $request, Event $event, NumericCodeCheckInAction $checkIn): JsonResponse
121+
{
122+
throw_unless($event->status->isViewableByParticipant(), NotFoundHttpException::class);
123+
124+
$request->validate([
125+
'code' => ['required', 'string', new CheckInCodeRule],
126+
]);
127+
128+
$code = $request->string('code')->toString();
129+
130+
/** @var User $user */
131+
$user = $request->user();
132+
133+
$enrollment = Enrollment::query()
134+
->where('event_id', $event->id)
135+
->where('user_id', $user->id)
136+
->first();
137+
138+
if (!$enrollment instanceof Enrollment || !in_array($enrollment->status, [EnrollmentStatus::Confirmed, EnrollmentStatus::CheckedIn], strict: true)) {
139+
return response()->json(['message' => 'Not enrolled in this event.'], Response::HTTP_UNPROCESSABLE_ENTITY);
140+
}
141+
142+
$rateLimitKey = $this->checkInRateLimitKey($user->id, $event->id, $request->ip());
143+
144+
if (RateLimiter::tooManyAttempts($rateLimitKey, 5)) {
145+
return response()->json([
146+
'message' => CheckInException::checkInCodeRateLimited(RateLimiter::availableIn($rateLimitKey))->getMessage(),
147+
], Response::HTTP_TOO_MANY_REQUESTS);
148+
}
149+
150+
RateLimiter::hit($rateLimitKey, 60);
151+
152+
try {
153+
$checkInRecord = $checkIn->handle(new NumericCodeCheckInDTO(
154+
enrollment: $enrollment,
155+
code: $code,
156+
eventDate: Date::today(),
157+
));
158+
} catch (CheckInException $checkInException) {
159+
return response()->json(['message' => $checkInException->getMessage()], $checkInException->getCode());
160+
}
161+
162+
RateLimiter::clear($rateLimitKey);
163+
164+
return response()->json([
165+
'event_date' => $checkInRecord->event_date->toDateString(),
166+
'checked_in_at' => $checkInRecord->checked_in_at?->toIso8601String(),
167+
], Response::HTTP_CREATED);
168+
}
169+
170+
private function checkInRateLimitKey(string $userId, string $eventId, ?string $ip): string
171+
{
172+
return sprintf('numeric-code-check-in:%s:%s:%s', $userId, $eventId, md5($ip ?? 'unknown'));
173+
}
174+
}
Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace He4rt\Events\Http\Resources;
6+
7+
use He4rt\Events\Enrollment\Enums\EnrollmentMethod;
8+
use He4rt\Events\Enrollment\Models\Enrollment;
9+
use He4rt\Events\Enrollment\Models\EnrollmentPolicy;
10+
use He4rt\Events\Event\Enums\EventStatus;
11+
use He4rt\Events\Event\Models\Event;
12+
use Illuminate\Http\Request;
13+
use Illuminate\Http\Resources\Json\JsonResource;
14+
15+
/**
16+
* @mixin Event
17+
*/
18+
final class EventDetailResource extends JsonResource
19+
{
20+
public function __construct(
21+
Event $event,
22+
private readonly ?Enrollment $enrollment,
23+
) {
24+
parent::__construct($event);
25+
}
26+
27+
/**
28+
* @return array<string, mixed>
29+
*/
30+
public function toArray(Request $request): array
31+
{
32+
$policy = $this->enrollmentPolicy;
33+
34+
return [
35+
'id' => $this->id,
36+
'slug' => $this->slug,
37+
'title' => $this->title,
38+
'description' => $this->description,
39+
'event_type' => $this->event_type->value,
40+
'location' => $this->location,
41+
'starts_at' => $this->starts_at->toIso8601String(),
42+
'ends_at' => $this->ends_at->toIso8601String(),
43+
'status' => $this->status->value,
44+
'enrollment_method' => $policy?->enrollment_method->value,
45+
'capacity' => $policy?->capacity,
46+
'has_waitlist' => $policy === null ? false : $policy->has_waitlist,
47+
'enrollment' => $this->enrollment instanceof Enrollment ? [
48+
'status' => $this->enrollment->status->value,
49+
'waitlist_position' => $this->enrollment->waitlist_position,
50+
'enrolled_at' => $this->enrollment->enrolled_at?->toIso8601String(),
51+
'confirmed_at' => $this->enrollment->confirmed_at?->toIso8601String(),
52+
'checked_in_at' => $this->enrollment->checked_in_at?->toIso8601String(),
53+
] : null,
54+
'can_apply' => $this->canApply($policy),
55+
'can_confirm_presence' => $this->canConfirmPresence($policy),
56+
'is_event_full' => $this->isEventFull($policy),
57+
];
58+
}
59+
60+
private function canConfirmPresence(?EnrollmentPolicy $policy): bool
61+
{
62+
if ($this->status !== EventStatus::Published || $this->enrollment instanceof Enrollment) {
63+
return false;
64+
}
65+
66+
if (!in_array($policy?->enrollment_method, [EnrollmentMethod::Rsvp, EnrollmentMethod::RsvpCheckin], strict: true)) {
67+
return false;
68+
}
69+
70+
if (!$this->starts_at->isFuture()) {
71+
return false;
72+
}
73+
74+
if ($policy->capacity === null) {
75+
return true;
76+
}
77+
78+
return $this->occupiedCount() < $policy->capacity || $policy->has_waitlist;
79+
}
80+
81+
private function canApply(?EnrollmentPolicy $policy): bool
82+
{
83+
if ($this->status !== EventStatus::Published || $this->enrollment instanceof Enrollment) {
84+
return false;
85+
}
86+
87+
if ($policy?->enrollment_method !== EnrollmentMethod::Application) {
88+
return false;
89+
}
90+
91+
return $this->starts_at->isFuture();
92+
}
93+
94+
private function isEventFull(?EnrollmentPolicy $policy): bool
95+
{
96+
if ($this->enrollment instanceof Enrollment || $policy?->capacity === null || $policy->has_waitlist) {
97+
return false;
98+
}
99+
100+
return $this->occupiedCount() >= $policy->capacity;
101+
}
102+
103+
private function occupiedCount(): int
104+
{
105+
return Enrollment::query()
106+
->where('event_id', $this->id)
107+
->active()
108+
->count();
109+
}
110+
}
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace He4rt\Events\Http\Resources;
6+
7+
use He4rt\Events\Enrollment\Models\Enrollment;
8+
use He4rt\Events\Event\Models\Event;
9+
use Illuminate\Http\Request;
10+
use Illuminate\Http\Resources\Json\JsonResource;
11+
12+
/**
13+
* @mixin Event
14+
*/
15+
final class EventResource extends JsonResource
16+
{
17+
/**
18+
* @return array<string, mixed>
19+
*/
20+
public function toArray(Request $request): array
21+
{
22+
/** @var Enrollment|null $enrollment */
23+
$enrollment = $this->relationLoaded('enrollments') ? $this->enrollments->first() : null;
24+
25+
return [
26+
'id' => $this->id,
27+
'slug' => $this->slug,
28+
'title' => $this->title,
29+
'description' => $this->description,
30+
'event_type' => $this->event_type->value,
31+
'location' => $this->location,
32+
'starts_at' => $this->starts_at->toIso8601String(),
33+
'ends_at' => $this->ends_at->toIso8601String(),
34+
'status' => $this->status->value,
35+
'enrollment_status' => $enrollment?->status->value,
36+
];
37+
}
38+
}

0 commit comments

Comments
 (0)