feat: add Snipe-IT asset synchronization

This commit is contained in:
2026-08-04 16:15:09 +01:00
parent 604180b735
commit 077015f17a
37 changed files with 1302 additions and 26 deletions

View File

@@ -0,0 +1,10 @@
<?php
namespace App\Domain\Inventory\Enums;
enum SyncRunStatus: string
{
case Running = 'running';
case Succeeded = 'succeeded';
case Failed = 'failed';
}

View File

@@ -0,0 +1,13 @@
<?php
namespace App\Domain\Inventory\Exceptions;
use RuntimeException;
class SyncAlreadyRunningException extends RuntimeException
{
public function __construct()
{
parent::__construct('Já existe uma sincronização de equipamentos em curso.');
}
}

View File

@@ -21,6 +21,7 @@ class SnipeAsset extends Model
'category_id', 'category_name', 'manufacturer', 'status_id', 'status_name',
'location_id', 'location_name', 'requestable', 'assigned_type', 'assigned_id',
'image_url', 'source_updated_at', 'synced_at', 'content_hash', 'active',
'last_seen_sync_run_id',
];
protected function casts(): array

View File

@@ -0,0 +1,45 @@
<?php
namespace App\Domain\Inventory\Models;
use App\Domain\Inventory\Enums\SyncRunStatus;
use Carbon\CarbonImmutable;
use Illuminate\Database\Eloquent\Model;
/**
* @property int $id
* @property string $type
* @property CarbonImmutable $started_at
* @property CarbonImmutable|null $finished_at
* @property SyncRunStatus $status
* @property int $records_processed
* @property int $records_created
* @property int $records_updated
* @property int $records_disabled
* @property string|null $error_message
*/
class SyncRun extends Model
{
public $timestamps = false;
protected $fillable = [
'type',
'started_at',
'finished_at',
'status',
'records_processed',
'records_created',
'records_updated',
'records_disabled',
'error_message',
];
protected function casts(): array
{
return [
'started_at' => 'datetime',
'finished_at' => 'datetime',
'status' => SyncRunStatus::class,
];
}
}

View File

@@ -0,0 +1,120 @@
<?php
namespace App\Domain\Inventory\Services;
use App\Domain\Inventory\Enums\SyncRunStatus;
use App\Domain\Inventory\Exceptions\SyncAlreadyRunningException;
use App\Domain\Inventory\Models\SnipeAsset;
use App\Domain\Inventory\Models\SyncRun;
use App\Integrations\SnipeIt\SnipeItAssetMapper;
use App\Integrations\SnipeIt\SnipeItClient;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Throwable;
final readonly class AssetSyncService
{
public function __construct(
private SnipeItClient $client,
private SnipeItAssetMapper $mapper,
) {}
public function sync(): SyncRun
{
$lock = Cache::lock('snipe-it:asset-sync', 900);
if (! $lock->get()) {
throw new SyncAlreadyRunningException;
}
try {
return $this->runSync();
} finally {
$lock->release();
}
}
private function runSync(): SyncRun
{
$startedAt = now();
$run = SyncRun::query()->create([
'type' => 'assets_full',
'started_at' => $startedAt,
'status' => SyncRunStatus::Running,
]);
$processed = 0;
$created = 0;
$updated = 0;
try {
foreach ($this->client->hardwarePages() as $page) {
DB::transaction(function () use ($page, $run, $startedAt, &$processed, &$created, &$updated): void {
foreach ($page->rows as $row) {
$assetData = $this->mapper->map($row);
$hash = $assetData->contentHash();
$asset = SnipeAsset::query()
->where('snipe_asset_id', $assetData->snipeAssetId)
->first();
$attributes = [
...$assetData->toModelAttributes(),
'synced_at' => $startedAt,
'last_seen_sync_run_id' => $run->id,
'content_hash' => $hash,
'active' => true,
];
if ($asset === null) {
SnipeAsset::query()->create($attributes);
$created++;
} else {
$changed = $asset->content_hash !== $hash || ! $asset->active;
$asset->update($attributes);
if ($changed) {
$updated++;
}
}
$processed++;
}
});
}
$disabled = DB::transaction(fn (): int => SnipeAsset::query()
->where('active', true)
->where(fn ($query) => $query
->whereNull('last_seen_sync_run_id')
->orWhere('last_seen_sync_run_id', '!=', $run->id))
->update(['active' => false]));
$run->update([
'finished_at' => now(),
'status' => SyncRunStatus::Succeeded,
'records_processed' => $processed,
'records_created' => $created,
'records_updated' => $updated,
'records_disabled' => $disabled,
]);
return $run->refresh();
} catch (Throwable $exception) {
$message = preg_replace('/Bearer\s+\S+/i', 'Bearer [redacted]', $exception->getMessage())
?? 'Falha desconhecida durante a sincronização.';
$run->update([
'finished_at' => now(),
'status' => SyncRunStatus::Failed,
'records_processed' => $processed,
'records_created' => $created,
'records_updated' => $updated,
'error_message' => Str::limit($message, 2000),
]);
throw $exception;
}
}
}