lan_kiosk/app/Console/Commands/SyncCustomers.php
Anna-Sara Sélea df9f1cf17e Swish feature
2026-08-22 16:13:42 +02:00

115 lines
3.7 KiB
PHP

<?php
namespace App\Console\Commands;
use App\Models\Customer;
use App\Models\Tableversion;
use GuzzleHttp\Client;
use Illuminate\Console\Command;
class SyncCustomers extends Command
{
protected $signature = 'app:sync-customers';
protected $description = 'Sync participants and volunteers from the LAN API';
public function handle(): void
{
$client = new Client();
$versions = $this->fetchVersions($client);
if (!$versions) {
return;
}
$participantVersion = $this->ensureVersion('participants', $versions['participants']);
$volunteerVersion = $this->ensureVersion('volunteers', $versions['volunteers']);
if (
$participantVersion->version >= $versions['participants'] &&
$volunteerVersion->version >= $versions['volunteers']
) {
$this->info('Already up to date.');
return;
}
$data = $this->fetchData($client);
if (!$data) {
return;
}
foreach ($data['participants'] as $participant) {
Customer::updateOrCreate(
['lan_id' => $participant['lan_id']],
[
'name' => $participant['first_name'] . ' ' . $participant['surname'],
'guardian_name' => $participant['guardian_name'],
]
);
}
foreach ($data['volunteers'] as $volunteer) {
Customer::updateOrCreate(
['lan_id' => $volunteer['lan_id']],
[
'name' => $volunteer['first_name'] . ' ' . $volunteer['surname'],
'guardian_name' => $volunteer['first_name'] . ' ' . $volunteer['surname'],
]
);
}
if ($participantVersion->version < $versions['participants']) {
Tableversion::create(['table' => 'participants', 'version' => $participantVersion->version + 1]);
$this->info('Participants synced.');
}
if ($volunteerVersion->version < $versions['volunteers']) {
Tableversion::create(['table' => 'volunteers', 'version' => $volunteerVersion->version + 1]);
$this->info('Volunteers synced.');
}
}
private function ensureVersion(string $table, int $latestVersion): Tableversion
{
$version = Tableversion::where('table', $table)->latest()->first();
if (!$version) {
$version = Tableversion::create(['table' => $table, 'version' => $latestVersion - 1]);
}
return $version;
}
private function fetchVersions(Client $client): ?array
{
try {
$response = $client->get(config('app.apilan_url') . 'version', $this->requestOptions());
return json_decode((string) $response->getBody(), true);
} catch (\Exception $e) {
$this->error('Failed to fetch versions: ' . $e->getMessage());
return null;
}
}
private function fetchData(Client $client): ?array
{
try {
$response = $client->get(config('app.apilan_url') . 'data', $this->requestOptions());
return json_decode((string) $response->getBody(), true);
} catch (\Exception $e) {
$this->error('Failed to fetch data: ' . $e->getMessage());
return null;
}
}
private function requestOptions(): array
{
return [
'headers' => [
'X-Api-Key' => config('app.apilan_key'),
'Accept' => 'application/json',
'Content-Type' => 'application/json',
],
'cert' => config('app.apilan_clientcert_path'),
];
}
}