79 lines
2.5 KiB
PHP
79 lines
2.5 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers\Api\V1\Integration;
|
|
|
|
use App\Http\Controllers\Controller;
|
|
use App\Http\Controllers\Concerns\RespondsWithJson;
|
|
use App\Http\Requests\Api\V1\Integration\AckCommandRequest;
|
|
use App\Http\Requests\Api\V1\Integration\HeartbeatRequest;
|
|
use App\Http\Requests\Api\V1\Integration\MachineEventRequest;
|
|
use App\Models\MachineCommand;
|
|
use App\Models\MachineIntegration;
|
|
use App\Services\MachineIntegrationService;
|
|
use Illuminate\Http\JsonResponse;
|
|
|
|
class MachineEventController extends Controller
|
|
{
|
|
use RespondsWithJson;
|
|
|
|
public function __construct(
|
|
private readonly MachineIntegrationService $machineIntegrationService,
|
|
) {}
|
|
|
|
public function store(MachineEventRequest $request): JsonResponse
|
|
{
|
|
$payload = $request->validated();
|
|
|
|
$this->machineIntegrationService->handleInboundEvent(
|
|
$payload['provider'],
|
|
$payload,
|
|
);
|
|
|
|
return $this->created(['received' => true], 'Événement enregistré.');
|
|
}
|
|
|
|
public function heartbeat(HeartbeatRequest $request): JsonResponse
|
|
{
|
|
$payload = $request->validated();
|
|
$payload['event_type'] = 'heartbeat';
|
|
$payload['occurred_at'] = $payload['occurred_at'] ?? now()->toIso8601String();
|
|
|
|
$integration = MachineIntegration::query()
|
|
->where('provider', $payload['provider'])
|
|
->where('external_machine_id', $payload['machine_external_id'])
|
|
->where('is_active', true)
|
|
->with('machine')
|
|
->first();
|
|
|
|
if ($integration?->machine !== null) {
|
|
$integration->machine->update(['last_heartbeat_at' => now()]);
|
|
}
|
|
|
|
$this->machineIntegrationService->handleInboundEvent(
|
|
$payload['provider'],
|
|
$payload,
|
|
);
|
|
|
|
return $this->success(['received' => true], 'Heartbeat enregistré.');
|
|
}
|
|
|
|
public function ackCommand(AckCommandRequest $request, string $uuid): JsonResponse
|
|
{
|
|
$command = MachineCommand::query()->where('uuid', $uuid)->firstOrFail();
|
|
|
|
$command->update([
|
|
'status' => $request->string('status')->toString(),
|
|
'external_reference' => $request->input('external_reference'),
|
|
'responded_at' => now(),
|
|
'payload' => array_merge($command->payload ?? [], [
|
|
'ack' => $request->input('data', []),
|
|
]),
|
|
]);
|
|
|
|
return $this->success([
|
|
'command_uuid' => $command->uuid,
|
|
'status' => $command->status,
|
|
], 'Accusé de réception enregistré.');
|
|
}
|
|
}
|