Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions app-modules/events/lang/en/check_in.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,8 @@
'check_in_code_exhausted' => 'Code has reached maximum uses.',
'check_in_code_wrong_date' => 'Code is not valid for today.',
'check_in_code_rate_limited' => 'Too many attempts. Try again in :seconds seconds.',
'bot_user_not_linked' => 'Your account is not linked to this platform.',
'bot_no_active_enrollment' => 'No active enrollment found for an event happening today.',
'bot_multiple_active_events' => 'More than one event uses this code today. Please check in through the panel.',
'bot_check_in_success' => 'Check-in confirmed. See you there!',
];
4 changes: 4 additions & 0 deletions app-modules/events/lang/pt_BR/check_in.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,8 @@
'check_in_code_exhausted' => 'O código atingiu o limite máximo de usos.',
'check_in_code_wrong_date' => 'O código não é válido para hoje.',
'check_in_code_rate_limited' => 'Muitas tentativas. Tente novamente em :seconds segundos.',
'bot_user_not_linked' => 'Sua conta não está vinculada a esta plataforma.',
'bot_no_active_enrollment' => 'Nenhuma inscrição ativa encontrada para um evento de hoje.',
'bot_multiple_active_events' => 'Mais de um evento usa esse código hoje. Faça o check-in pelo painel.',
'bot_check_in_success' => 'Check-in confirmado. Até lá!',
];
11 changes: 11 additions & 0 deletions app-modules/events/src/CheckIn/Enums/BotCheckInStatus.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php

declare(strict_types=1);

namespace He4rt\Events\CheckIn\Enums;

enum BotCheckInStatus: string
{
case Success = 'success';
case Error = 'error';
}
26 changes: 26 additions & 0 deletions app-modules/events/src/CheckIn/Events/CheckInProcessed.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

declare(strict_types=1);

namespace He4rt\Events\CheckIn\Events;

use He4rt\Events\CheckIn\Enums\BotCheckInStatus;
use He4rt\Identity\ExternalIdentity\Enums\IdentityProvider;
use Illuminate\Foundation\Events\Dispatchable;

final readonly class CheckInProcessed
{
use Dispatchable;

/**
* @param array<string, mixed> $channelContext Echoed back from the request for reply routing.
*/
public function __construct(
public IdentityProvider $provider,
public string $externalUserId,
public BotCheckInStatus $status,
public string $message,
public array $channelContext = [],
public ?string $enrollmentId = null,
) {}
}
25 changes: 25 additions & 0 deletions app-modules/events/src/CheckIn/Events/CheckInRequested.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php

declare(strict_types=1);

namespace He4rt\Events\CheckIn\Events;

use He4rt\Identity\ExternalIdentity\Enums\IdentityProvider;
use Illuminate\Foundation\Events\Dispatchable;

final readonly class CheckInRequested
{
use Dispatchable;

/**
* @param array<string, mixed> $channelContext Opaque routing data the bot uses to reply to the member.
*/
public function __construct(
public IdentityProvider $provider,
public string $externalUserId,
public string $code,
public string $tenantId,
public ?string $eventId = null,
public array $channelContext = [],
) {}
}
16 changes: 16 additions & 0 deletions app-modules/events/src/CheckIn/Exceptions/CheckInException.php
Original file line number Diff line number Diff line change
Expand Up @@ -104,4 +104,20 @@ public static function checkInCodeRateLimited(int $seconds): self
Response::HTTP_TOO_MANY_REQUESTS,
);
}

public static function botNoActiveEnrollment(): self
{
return new self(
__('events::check_in.bot_no_active_enrollment'),
Response::HTTP_NOT_FOUND,
);
}

public static function botMultipleActiveEvents(): self
{
return new self(
__('events::check_in.bot_multiple_active_events'),
Response::HTTP_UNPROCESSABLE_ENTITY,
);
}
}
118 changes: 118 additions & 0 deletions app-modules/events/src/CheckIn/Listeners/HandleBotCheckIn.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
<?php

declare(strict_types=1);

namespace He4rt\Events\CheckIn\Listeners;

use He4rt\Events\CheckIn\Actions\NumericCodeCheckInAction;
use He4rt\Events\CheckIn\DTOs\NumericCodeCheckInDTO;
use He4rt\Events\CheckIn\Enums\BotCheckInStatus;
use He4rt\Events\CheckIn\Events\CheckInProcessed;
use He4rt\Events\CheckIn\Events\CheckInRequested;
use He4rt\Events\CheckIn\Exceptions\CheckInException;
use He4rt\Events\CheckIn\Models\CheckInCode;
use He4rt\Events\Enrollment\Enums\EnrollmentStatus;
use He4rt\Events\Enrollment\Models\Enrollment;
use He4rt\Events\Event\Enums\EventStatus;
use He4rt\Identity\ExternalIdentity\Actions\FindExternalIdentity;
use He4rt\Identity\ExternalIdentity\Exceptions\ExternalIdentityException;
use Illuminate\Database\Eloquent\Builder;

final readonly class HandleBotCheckIn
{
public function __construct(
private FindExternalIdentity $findExternalIdentity,
private NumericCodeCheckInAction $numericCodeCheckIn,
) {}

public function handle(CheckInRequested $event): void
{
try {
$userId = $this->resolveUserId($event);
$enrollment = $this->resolveEnrollment($event, $userId);

$checkIn = $this->numericCodeCheckIn->handle(
new NumericCodeCheckInDTO(
enrollment: $enrollment,
code: $event->code,
eventDate: now(),
),
);

$this->dispatchSuccess($event, $checkIn->enrollment_id);
} catch (ExternalIdentityException) {
$this->dispatchError($event, __('events::check_in.bot_user_not_linked'));
} catch (CheckInException $exception) {
$this->dispatchError($event, $exception->getMessage());
}
}

private function resolveUserId(CheckInRequested $event): string
{
return $this->findExternalIdentity->handle(
provider: $event->provider->value,
providerId: $event->externalUserId,
tenantId: $event->tenantId,
)->model_id;
}

private function resolveEnrollment(CheckInRequested $event, string $userId): Enrollment
{
$today = now()->toDateString();

$enrollments = Enrollment::query()
->where('user_id', $userId)
->whereIn('status', [EnrollmentStatus::Confirmed, EnrollmentStatus::CheckedIn])
->whereHas('event', function (Builder $query) use ($event, $today): void {
$query->where('tenant_id', $event->tenantId)
->where('status', EventStatus::Published)
->whereDate('starts_at', '<=', $today)
->whereDate('ends_at', '>=', $today);
})
->get();

$enrollment = $enrollments->first();
throw_unless($enrollment, CheckInException::botNoActiveEnrollment());

if ($enrollments->count() === 1) {
return $enrollment;
}

$matchingEventIds = CheckInCode::query()
->whereIn('event_id', $enrollments->pluck('event_id'))
->where('code', $event->code)
->whereDate('event_date', $today)
->pluck('event_id');

$matching = $enrollments->whereIn('event_id', $matchingEventIds);

$matched = $matching->first();
throw_unless($matched, CheckInException::invalidCheckInCode());
throw_if($matching->count() > 1, CheckInException::botMultipleActiveEvents());

return $matched;
}

private function dispatchSuccess(CheckInRequested $event, string $enrollmentId): void
{
event(new CheckInProcessed(
provider: $event->provider,
externalUserId: $event->externalUserId,
status: BotCheckInStatus::Success,
message: __('events::check_in.bot_check_in_success'),
channelContext: $event->channelContext,
enrollmentId: $enrollmentId,
));
}

private function dispatchError(CheckInRequested $event, string $message): void
{
event(new CheckInProcessed(
provider: $event->provider,
externalUserId: $event->externalUserId,
status: BotCheckInStatus::Error,
message: $message,
channelContext: $event->channelContext,
));
}
}
3 changes: 3 additions & 0 deletions app-modules/events/src/EventsServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@

namespace He4rt\Events;

use He4rt\Events\CheckIn\Events\CheckInRequested;
use He4rt\Events\CheckIn\Listeners\GenerateQrTokenOnConfirmed;
use He4rt\Events\CheckIn\Listeners\HandleBotCheckIn;
use He4rt\Events\Console\Commands\ClosePendingEventsCommand;
use He4rt\Events\Enrollment\Events\EnrollmentConfirmed;
use Illuminate\Console\Scheduling\Schedule;
Expand All @@ -24,6 +26,7 @@ public function boot(): void
$this->loadTranslationsFrom(__DIR__.'/../lang', 'events');

Event::listen(EnrollmentConfirmed::class, GenerateQrTokenOnConfirmed::class);
Event::listen(CheckInRequested::class, HandleBotCheckIn::class);

if ($this->app->runningInConsole()) {
$this->app->make(Schedule::class)
Expand Down
Loading