73 lines
2.1 KiB
PHP
73 lines
2.1 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace Infrastructure\Adapters\Services;
|
|
|
|
use App\Models\OrderTunnelAttempt;
|
|
use Domain\Models\ValueObjects\Entities\OrderId;
|
|
use Domain\Models\ValueObjects\Entities\ShopperId;
|
|
use Domain\Ports\Services\TunnelAttemptTrackerService;
|
|
use Illuminate\Contracts\Session\Session;
|
|
use Illuminate\Support\Facades\Date;
|
|
use Webmozart\Assert\Assert;
|
|
|
|
class DatabaseTunnelAttemptTrackerService implements TunnelAttemptTrackerService
|
|
{
|
|
public function __construct(
|
|
private readonly Session $session,
|
|
private readonly string $sessionKey,
|
|
) {
|
|
Assert::stringNotEmpty(trim($sessionKey));
|
|
}
|
|
|
|
#[\Override]
|
|
public function recordEntry(ShopperId $customerId): void
|
|
{
|
|
$attemptId = $this->session->get($this->sessionKey);
|
|
|
|
if (is_string($attemptId) && $attemptId !== '') {
|
|
$exists = OrderTunnelAttempt::query()
|
|
->whereKey($attemptId)
|
|
->whereNull('converted_at')
|
|
->where('customer_id', $customerId->value->toString())
|
|
->exists();
|
|
|
|
if ($exists) {
|
|
return;
|
|
}
|
|
}
|
|
|
|
$attempt = new OrderTunnelAttempt();
|
|
$attempt->customer_id = $customerId->value->toString();
|
|
$attempt->saveOrFail();
|
|
|
|
$this->session->put($this->sessionKey, $attempt->id);
|
|
}
|
|
|
|
#[\Override]
|
|
public function markConverted(OrderId $orderId): void
|
|
{
|
|
$attemptId = $this->session->get($this->sessionKey);
|
|
|
|
if (! is_string($attemptId) || $attemptId === '') {
|
|
return;
|
|
}
|
|
|
|
$attempt = OrderTunnelAttempt::query()->find($attemptId);
|
|
|
|
if ($attempt !== null && $attempt->converted_at === null) {
|
|
$attempt->order_id = $orderId->value->toString();
|
|
$attempt->converted_at = Date::now();
|
|
$attempt->saveOrFail();
|
|
}
|
|
|
|
$this->session->forget($this->sessionKey);
|
|
}
|
|
|
|
#[\Override]
|
|
public function clearActiveSession(): void
|
|
{
|
|
$this->session->forget($this->sessionKey);
|
|
}
|
|
}
|