Skip to content

A free open source IT asset/license management system

Fixed #19752 - add checkbox to skip adding new assets if no existing match

snipe66a57069b954
diff --git a/app/Console/Commands/PullInventory.php b/app/Console/Commands/PullInventory.php
index 5c4bd0aca5..91c3af66ea 100644
--- a/app/Console/Commands/PullInventory.php
+++ b/app/Console/Commands/PullInventory.php
@@ -14,7 +14,7 @@ class PullInventory extends Command
protected $description = 'Pull host inventory from configured sync-adapter instances and upsert as Snipe-IT assets.';
- private const TABLE_HEADERS = ['Adapter', 'Status', 'Synced', 'Errors', 'Elapsed'];
+ private const TABLE_HEADERS = ['Adapter', 'Status', 'Synced', 'Skipped', 'Errors', 'Elapsed'];
public function handle(): int
{
@@ -110,6 +110,7 @@ class PullInventory extends Command
set_time_limit(0);
$seen = 0;
+ $skipped = 0;
$errors = 0;
Log::channel('sync-adapters')->info("{$slug} sync starting (CLI)");
@@ -117,8 +118,12 @@ class PullInventory extends Command
try {
foreach ($adapter->pull() as $record) {
try {
- SyncAdapter::syncFromRecord($record);
- $seen++;
+ $result = SyncAdapter::syncFromRecord($record);
+ if ($result === null) {
+ $skipped++;
+ } else {
+ $seen++;
+ }
} catch (Throwable $e) {
$errors++;
$sourceId = $record->sourceId;
@@ -138,10 +143,10 @@ class PullInventory extends Command
$elapsed = self::formatElapsed($startedAt);
$this->error("{$slug} {$abortSummary} ({$elapsed})");
- Log::channel('sync-adapters')->warning("{$slug} sync aborted after {$seen} record(s), {$errors} error(s), elapsed {$elapsed}: {$message}", [
+ Log::channel('sync-adapters')->warning("{$slug} sync aborted after {$seen} record(s), {$skipped} skipped, {$errors} error(s), elapsed {$elapsed}: {$message}", [
'exception' => $e,
]);
- $rows[] = [$slug, 'Aborted', $seen, $errors, $elapsed];
+ $rows[] = [$slug, 'Aborted', $seen, $skipped, $errors, $elapsed];
return self::FAILURE;
}
@@ -150,6 +155,7 @@ class PullInventory extends Command
// on the settings page.
$result = trans('admin/settings/sync_adapters.sync_complete', [
'count' => $seen,
+ 'skipped' => $skipped,
'errors' => $errors,
]);
$instance->last_synced_at = now();
@@ -157,10 +163,10 @@ class PullInventory extends Command
$instance->save();
$elapsed = self::formatElapsed($startedAt);
- Log::channel('sync-adapters')->info("{$slug} sync complete: {$seen} record(s) processed, {$errors} error(s), elapsed {$elapsed}");
+ Log::channel('sync-adapters')->info("{$slug} sync complete: {$seen} record(s) processed, {$skipped} skipped, {$errors} error(s), elapsed {$elapsed}");
$status = $errors > 0 ? 'Errors' : 'OK';
- $rows[] = [$slug, $status, $seen, $errors, $elapsed];
+ $rows[] = [$slug, $status, $seen, $skipped, $errors, $elapsed];
return $errors > 0 ? self::FAILURE : self::SUCCESS;
}
diff --git a/app/Http/Controllers/SettingsController.php b/app/Http/Controllers/SettingsController.php
index 622186eb9a..9257faba80 100644
--- a/app/Http/Controllers/SettingsController.php
+++ b/app/Http/Controllers/SettingsController.php
@@ -1099,6 +1099,7 @@ class SettingsController extends Controller
set_time_limit(0);
$seen = 0;
+ $skipped = 0;
$errors = 0;
$startedAt = microtime(true);
@@ -1107,8 +1108,12 @@ class SettingsController extends Controller
try {
foreach ($adapter->pull() as $record) {
try {
- \App\SyncAdapters\SyncAdapter::syncFromRecord($record);
- $seen++;
+ $result = \App\SyncAdapters\SyncAdapter::syncFromRecord($record);
+ if ($result === null) {
+ $skipped++;
+ } else {
+ $seen++;
+ }
} catch (\Throwable $e) {
$errors++;
Log::channel('sync-adapters')->warning(sprintf(
@@ -1145,6 +1150,7 @@ class SettingsController extends Controller
$result = trans('admin/settings/sync_adapters.sync_complete', [
'count' => $seen,
+ 'skipped' => $skipped,
'errors' => $errors,
]);
$instance->last_synced_at = now();
@@ -1152,7 +1158,7 @@ class SettingsController extends Controller
$instance->save();
$elapsed = number_format(microtime(true) - $startedAt, 1);
- Log::channel('sync-adapters')->info("{$instance->slug} sync complete: {$seen} record(s) processed, {$errors} error(s), elapsed {$elapsed}s");
+ Log::channel('sync-adapters')->info("{$instance->slug} sync complete: {$seen} record(s) processed, {$skipped} skipped, {$errors} error(s), elapsed {$elapsed}s");
// at least one seen, no errors -> success (green)
// at least one seen, some errors -> warning (orange, admin should check log)
@@ -1584,7 +1590,7 @@ class SettingsController extends Controller
'filename' => basename($file),
'filesize' => Setting::fileSizeConvert($disk->size($file)),
'modified_value' => $file_timestamp,
- 'modified_display' => date($settings->date_display_format . ' ' . $settings->time_display_format, $file_timestamp),
+ 'modified_display' => date($settings->date_display_format.' '.$settings->time_display_format, $file_timestamp),
];
}
@@ -1649,7 +1655,7 @@ class SettingsController extends Controller
}
if (! config('app.lock_passwords')) {
- $path = $backupName . '/' . $filename;
+ $path = $backupName.'/'.$filename;
if (Storage::disk('backup')->exists($path)) {
Log::warning('User '.auth()->user()->username.' is attempting to download backup file: '.$filename);
@@ -1684,7 +1690,7 @@ class SettingsController extends Controller
if (! config('app.lock_passwords')) {
// Same disk + path so S3-destination backup is deletable from the UI.
$disk = Storage::disk('backup');
- $path = config('backup.backup.name', 'backups') . '/' . $filename;
+ $path = config('backup.backup.name', 'backups').'/'.$filename;
if ($disk->exists($path)) {
@@ -1770,9 +1776,9 @@ class SettingsController extends Controller
// and the name defaults to 'backups'.
$backupDisk = Storage::disk('backup');
$backupName = config('backup.backup.name', 'backups');
- $diskPath = $backupName . '/' . $filename;
+ $diskPath = $backupName.'/'.$filename;
- if (!$backupDisk->exists($diskPath)) {
+ if (! $backupDisk->exists($diskPath)) {
return redirect()->route('settings.backups.index')->with('error', trans('admin/settings/message.backup.file_not_found'));
}
@@ -1789,12 +1795,12 @@ class SettingsController extends Controller
$absolutePath = $backupDisk->path($diskPath);
} else {
$tempDir = storage_path('app/restore-temp');
- if (!is_dir($tempDir) && !mkdir($tempDir, 0755, true) && !is_dir($tempDir)) {
- Log::error('Restore aborted: could not create temp directory ' . $tempDir);
+ if (! is_dir($tempDir) && ! mkdir($tempDir, 0755, true) && ! is_dir($tempDir)) {
+ Log::error('Restore aborted: could not create temp directory '.$tempDir);
return redirect()->route('settings.backups.index')->with('error', trans('admin/settings/message.restore.archive_invalid', ['filename' => $filename]));
}
- $localTempPath = $tempDir . '/' . $filename;
+ $localTempPath = $tempDir.'/'.$filename;
// readStream returns null on failure, fopen returns false.
$srcStream = $backupDisk->readStream($diskPath);
$dstStream = fopen($localTempPath, 'w');
@@ -1805,7 +1811,7 @@ class SettingsController extends Controller
if (is_resource($dstStream)) {
fclose($dstStream);
}
- Log::error('Restore aborted: failed to open streams for temp copy of ' . $diskPath);
+ Log::error('Restore aborted: failed to open streams for temp copy of '.$diskPath);
return redirect()->route('settings.backups.index')->with('error', trans('admin/settings/message.restore.archive_invalid', ['filename' => $filename]));
}
@@ -1826,7 +1832,7 @@ class SettingsController extends Controller
// Refuse to proceed if the PHP zip extension is not loaded. The
// downstream snipeit:restore command needs ZipArchive too, so
// running it without ext-zip would fail after the wipe.
- if (!class_exists(ZipArchive::class)) {
+ if (! class_exists(ZipArchive::class)) {
Log::error('Restore aborted: PHP zip extension is not loaded, cannot validate archive before wiping database.');
return redirect()->route('settings.backups.index')->with('error', trans('admin/settings/message.restore.zip_extension_missing'));
@@ -1835,7 +1841,7 @@ class SettingsController extends Controller
$zip = new ZipArchive;
$openResult = $zip->open($absolutePath);
if ($openResult !== true) {
- Log::warning('Restore aborted: archive at ' . $absolutePath . ' failed zip open with code ' . $openResult);
+ Log::warning('Restore aborted: archive at '.$absolutePath.' failed zip open with code '.$openResult);
return redirect()->route('settings.backups.index')->with('error', trans('admin/settings/message.restore.archive_invalid', ['filename' => $filename]));
}
@@ -1847,27 +1853,27 @@ class SettingsController extends Controller
// Take a fresh pre-restore backup so we can point the operator at
// it if the restore fails after we wipe. This is the mitigation
// the pre-existing
- $requestedBackupFilename = 'pre-restore-' . date('Y-m-d-H-i-s') . '.zip';
+ $requestedBackupFilename = 'pre-restore-'.date('Y-m-d-H-i-s').'.zip';
// spatie prepends filename_prefix to the filename provided so this is the actual name on disk:
- $preRestoreBackupFilename = config('backup.backup.destination.filename_prefix') . $requestedBackupFilename;
- $preRestoreDiskPath = $backupName . '/' . $preRestoreBackupFilename;
+ $preRestoreBackupFilename = config('backup.backup.destination.filename_prefix').$requestedBackupFilename;
+ $preRestoreDiskPath = $backupName.'/'.$preRestoreBackupFilename;
$preBackupHint = config('filesystems.disks.backup.driver') === 'local'
? $backupDisk->path($preRestoreDiskPath)
- : 'backup disk (' . $preRestoreDiskPath . ')';
+ : 'backup disk ('.$preRestoreDiskPath.')';
- Log::debug('Running pre-restore backup: ' . $preRestoreBackupFilename);
+ Log::debug('Running pre-restore backup: '.$preRestoreBackupFilename);
$preBackupExit = Artisan::call('snipeit:backup', [
'--filename' => $requestedBackupFilename,
'--force' => true,
]);
- if ($preBackupExit !== 0 || !$backupDisk->exists($preRestoreDiskPath)) {
- Log::warning('Pre-restore backup failed (exit ' . $preBackupExit . '); aborting restore to protect existing data.');
+ if ($preBackupExit !== 0 || ! $backupDisk->exists($preRestoreDiskPath)) {
+ Log::warning('Pre-restore backup failed (exit '.$preBackupExit.'); aborting restore to protect existing data.');
return redirect()->route('settings.backups.index')->with('error', trans('admin/settings/message.restore.pre_backup_failed'));
}
- Log::warning('User ' . auth()->user()->username . ' is attempting to restore from: ' . $absolutePath . ' (pre-restore backup at ' . $preBackupHint . ')');
+ Log::warning('User '.auth()->user()->username.' is attempting to restore from: '.$absolutePath.' (pre-restore backup at '.$preBackupHint.')');
$restore_params = [
'--force' => true,
@@ -1893,7 +1899,7 @@ class SettingsController extends Controller
// run the restore command
$restoreExit = Artisan::call('snipeit:restore', $restore_params);
$restoreOutput = Artisan::output();
- Log::debug('snipeit:restore output: ' . $restoreOutput);
+ Log::debug('snipeit:restore output: '.$restoreOutput);
// snipeit:restore returns 0 even on some internal errors, so we also
// scan its output for its own "Could not access file" / "DB_CONNECTION
@@ -1901,7 +1907,7 @@ class SettingsController extends Controller
$restoreLooksFailed = $restoreExit !== 0 || str_contains(strtolower($restoreOutput), 'could not access file') || str_contains(strtolower($restoreOutput), 'db_connection must be mysql');
if ($restoreLooksFailed) {
- Log::error('Restore failed after db:wipe. Pre-restore backup available at ' . $preBackupHint);
+ Log::error('Restore failed after db:wipe. Pre-restore backup available at '.$preBackupHint);
return redirect()->route('settings.backups.index')->with('error', trans('admin/settings/message.restore.failed_with_backup', [
'backup' => $preRestoreBackupFilename,
@@ -1915,7 +1921,7 @@ class SettingsController extends Controller
Log::debug($migrate_output);
if ($migrateExit !== 0) {
- Log::error('Migrate failed after restore. Pre-restore backup available at ' . $preBackupHint);
+ Log::error('Migrate failed after restore. Pre-restore backup available at '.$preBackupHint);
return redirect()->route('settings.backups.index')->with('error', trans('admin/settings/message.restore.failed_with_backup', [
'backup' => $preRestoreBackupFilename,
@@ -1924,12 +1930,12 @@ class SettingsController extends Controller
$find_user = DB::table('users')->where('username', $user->username)->exists();
- if (!$find_user) {
- Log::warning('Attempting to restore user: ' . $user->username);
+ if (! $find_user) {
+ Log::warning('Attempting to restore user: '.$user->username);
$new_user = $user->replicate();
$new_user->push();
} else {
- Log::debug('User: ' . $user->username . ' already exists.');
+ Log::debug('User: '.$user->username.' already exists.');
}
Log::debug('Logging all users out..');
diff --git a/app/SyncAdapters/SyncAdapter.php b/app/SyncAdapters/SyncAdapter.php
index 1b5a62649e..ccbafe91d5 100644
--- a/app/SyncAdapters/SyncAdapter.php
+++ b/app/SyncAdapters/SyncAdapter.php
@@ -370,6 +370,7 @@ abstract class SyncAdapter
$slug.'_default_status_id' => ['required', 'integer', 'exists:status_labels,id'],
$slug.'_user_match_strategy' => ['nullable', 'string', 'in:none,email,username,username_then_email'],
$slug.'_adopt_by_serial' => ['nullable', 'boolean'],
+ $slug.'_create_snipeit_assets_on_pull' => ['nullable', 'boolean'],
];
if ($this->usesConfigurableUrl()) {
@@ -632,6 +633,17 @@ abstract class SyncAdapter
$request->boolean($slug.'_adopt_by_serial') ? '1' : '0',
);
+ // Opt-out: skip asset creation on pull when the vendor record
+ // has no existing Snipe-IT counterpart. Default on so existing
+ // installs keep the "vendor row with no match creates a fresh
+ // asset" behavior. Off = update rows already linked via
+ // asset_external_sources, log and skip anything with no match.
+ SyncAdapterConfig::put(
+ $this->instance->id,
+ 'create_snipeit_assets_on_pull',
+ $request->boolean($slug.'_create_snipeit_assets_on_pull', true) ? '1' : '0',
+ );
+
// Push dry-run flag. When on, adapters log the push payload
// instead of sending it, so admins can verify mapping +
// direction config against real assets without any vendor
@@ -1365,7 +1377,6 @@ abstract class SyncAdapter
* Migration aid: when on, the sync loop looks for an existing
* Snipe-IT asset with a matching serial before creating a new
* shell asset for a first-time sync vendor host.
- *
*/
public function adoptsBySerial(): bool
{
@@ -1377,6 +1388,21 @@ abstract class SyncAdapter
return $this->instance->last_synced_at === null;
}
+ /**
+ * When off, pull-side vendor records with no `asset_external_sources`
+ * link are logged and skipped rather than creating a new Snipe-IT
+ * asset. Default on so existing installs behave unchanged. Admins
+ * flip it off when their vendor data contains rows that shouldn't
+ * become Snipe-IT assets (e.g. Intune devices with generic serials
+ * that would duplicate manually-entered rows).
+ */
+ public function createsSnipeitAssetsOnPull(): bool
+ {
+ $stored = SyncAdapterConfig::get($this->instance->id, 'create_snipeit_assets_on_pull');
+
+ return $stored === null ? true : $stored === '1';
+ }
+
/**
* Whether this adapter's vendor exposes a groups concept
* (Fleet Teams, Jamf Sites, Kandji Blueprints, etc.) that
diff --git a/app/SyncAdapters/SyncsHostFromRecord.php b/app/SyncAdapters/SyncsHostFromRecord.php
index f170af2f7d..399dc067e0 100644
--- a/app/SyncAdapters/SyncsHostFromRecord.php
+++ b/app/SyncAdapters/SyncsHostFromRecord.php
@@ -33,13 +33,17 @@ use RuntimeException;
*/
trait SyncsHostFromRecord
{
- public static function syncFromRecord(HostInventoryRecord $record): Asset
+ public static function syncFromRecord(HostInventoryRecord $record): ?Asset
{
return DB::transaction(function () use ($record) {
$instance = SyncAdapterInstance::query()->where('slug', $record->sourceKey)->first();
$mapping = self::loadMapping($instance);
- [$asset, $isNew] = self::provisionAsset($record, $instance, $mapping);
+ $provisioned = self::provisionAsset($record, $instance, $mapping);
+ if ($provisioned === null) {
+ return null;
+ }
+ [$asset, $isNew] = $provisioned;
$externalUpdates = [];
self::applyStandardFieldMappings($asset, $externalUpdates, $record, $instance, $mapping);
@@ -103,14 +107,13 @@ trait SyncsHostFromRecord
* or creates a fresh shell asset + identity row for first-sync
* cases. Also handles the update-sync group-reassignment case
* where a device moved to a different vendor group that maps to
- * a different Snipe-IT company.
+ * a different Snipe-IT company. Returns null when the record was
+ * intentionally skipped (no match + create-on-pull disabled).
*
- * @return array{0: Asset, 1: bool} Tuple of the resolved asset and an "isNew" flag.
- */
- /**
* @param array<string, string> $mapping
+ * @return array{0: Asset, 1: bool}|null
*/
- private static function provisionAsset(HostInventoryRecord $record, ?SyncAdapterInstance $instance, array $mapping = []): array
+ private static function provisionAsset(HostInventoryRecord $record, ?SyncAdapterInstance $instance, array $mapping = []): ?array
{
$existingSource = DB::table('asset_external_sources')
->where('source', $record->sourceKey)
@@ -147,6 +150,22 @@ trait SyncsHostFromRecord
return [$adopted, false];
}
+ // Opt-out: when the admin has turned "Create new Snipe-IT
+ // assets on sync" off, skip unmatched vendor records entirely
+ // instead of creating a shell. Log at warning so admins can
+ // spot drift between vendor + Snipe-IT inventories.
+ $adapter = $instance?->adapter();
+ if ($adapter instanceof SyncAdapter && ! $adapter->createsSnipeitAssetsOnPull()) {
+ Log::channel('sync-adapters')->warning(sprintf(
+ '%s sync: skipped %s record %s (no existing Snipe-IT match and asset creation on pull is off)',
+ $adapter->name(),
+ $record->sourceKey,
+ $record->sourceId,
+ ));
+
+ return null;
+ }
+
$asset = self::createShellAsset($record, $instance, $mapping);
// Identity row created empty of inventory columns. the
diff --git a/resources/lang/en-US/admin/settings/sync_adapters.php b/resources/lang/en-US/admin/settings/sync_adapters.php
index b486cac15d..09011ab088 100644
--- a/resources/lang/en-US/admin/settings/sync_adapters.php
+++ b/resources/lang/en-US/admin/settings/sync_adapters.php
@@ -13,7 +13,7 @@ return [
'push_not_supported' => 'This adapter does not support pushing data to the vendor.',
'push_nothing_configured' => 'Push aborted: no fields on the mapping table are directed "Push to vendor" and no composed-notes template is configured. Set at least one before hitting Push Now.',
'not_configured' => 'This adapter has not been configured yet.',
- 'sync_complete' => 'Sync complete. Synced :count host(s), :errors error(s).',
+ 'sync_complete' => 'Sync complete. Synced :count host(s), :skipped skipped, :errors error(s).',
'sync_failed' => 'Sync failed: :summary. See storage/logs/sync-adapters.log for full details.',
'sync_failed_network' => 'network error',
'last_synced_label' => 'Last Synced',
@@ -121,6 +121,8 @@ return [
'checkin_on_null_user_help' => 'When the vendor stops reporting an assigned user for a device, check the asset in from whoever had it. Off by default because a single missed sync cycle (device offline, empty field on a fresh enrollment) would unassign the asset. Turn this on only if you trust your vendor\'s user reporting to be consistent every sync.',
'adopt_by_serial_label' => 'Match vendor hosts to existing assets by serial number',
'adopt_by_serial_help' => 'Migration aid for customers moving from a homegrown sync script that already populated the assets table or manually entered devices. When enabled, this adapter will first check for an existing Snipe-IT asset with the same serial number and link them. Turn this off after your initial migration if you want new vendor assets to always create fresh asset rows.',
+ 'create_snipeit_assets_on_pull_label' => 'Create new Snipe-IT assets for vendor records with no existing match',
+ 'create_snipeit_assets_on_pull_help' => 'Turn this OFF if your vendor data contains records that should not become Snipe-IT assets (e.g. devices with generic serials that would duplicate rows you entered manually). The sync will update rows already linked to this adapter and log-and-skip anything with no match.',
// Push dry-run + composite notes push
'push_dry_run_label' => 'Dry-run push (log payloads, do not send)',
diff --git a/resources/views/blade/sync-adapter/form.blade.php b/resources/views/blade/sync-adapter/form.blade.php
index c27c18a105..f89aaeafb9 100644
--- a/resources/views/blade/sync-adapter/form.blade.php
+++ b/resources/views/blade/sync-adapter/form.blade.php
@@ -284,6 +284,14 @@
:help_text="trans('admin/settings/sync_adapters.adopt_by_serial_help')"
:disabled="$locked"
/>
+
+ <x-form.checkbox-row
+ :name="$slug . '_create_snipeit_assets_on_pull'"
+ :checked="$adapter->createsSnipeitAssetsOnPull()"
+ :label="trans('admin/settings/sync_adapters.create_snipeit_assets_on_pull_label')"
+ :help_text="trans('admin/settings/sync_adapters.create_snipeit_assets_on_pull_help')"
+ :disabled="$locked"
+ />
</fieldset>
{{-- Push dry-run only shows for adapters that actually support
diff --git a/tests/Feature/SyncAdapters/CreateSnipeitAssetsOnPullTest.php b/tests/Feature/SyncAdapters/CreateSnipeitAssetsOnPullTest.php
new file mode 100644
index 0000000000..fde7e39ee5
--- /dev/null
+++ b/tests/Feature/SyncAdapters/CreateSnipeitAssetsOnPullTest.php
@@ -0,0 +1,106 @@
+<?php
+
+namespace Tests\Feature\SyncAdapters;
+
+use App\Models\Asset;
+use App\Models\AssetExternalSource;
+use App\Models\Statuslabel;
+use App\Models\SyncAdapterConfig;
+use App\Models\SyncAdapterInstance;
+use App\SyncAdapters\Fleet\FleetAdapter;
+use App\SyncAdapters\HostInventoryRecord;
+use App\SyncAdapters\SyncAdapter;
+use Illuminate\Support\Facades\Crypt;
+use Tests\TestCase;
+
+/**
+ * Coverage for the per-adapter opt-out that stops `syncFromRecord`
+ * from creating new Snipe-IT assets for vendor records with no
+ * existing match. Addresses #19752.
+ */
+class CreateSnipeitAssetsOnPullTest extends TestCase
+{
+ protected function setUp(): void
+ {
+ parent::setUp();
+
+ Statuslabel::factory()->rtd()->create();
+ }
+
+ public function test_defaults_on_so_existing_installs_keep_creating()
+ {
+ $instance = $this->configuredFleet();
+
+ $this->assertTrue((new FleetAdapter($instance))->createsSnipeitAssetsOnPull());
+ }
+
+ public function test_unmatched_vendor_record_creates_asset_when_toggle_on()
+ {
+ $this->configuredFleet();
+
+ $result = SyncAdapter::syncFromRecord(new HostInventoryRecord(
+ sourceKey: 'fleet',
+ sourceId: 'fleet-1',
+ hostname: 'wksn-01',
+ hardwareSerial: 'SN-01',
+ hardwareModel: 'MacBook Pro',
+ ));
+
+ $this->assertNotNull($result);
+ $this->assertDatabaseHas('assets', ['name' => 'wksn-01']);
+ }
+
+ public function test_unmatched_vendor_record_is_skipped_when_toggle_off()
+ {
+ $instance = $this->configuredFleet();
+ SyncAdapterConfig::put($instance->id, 'create_snipeit_assets_on_pull', '0');
+
+ $result = SyncAdapter::syncFromRecord(new HostInventoryRecord(
+ sourceKey: 'fleet',
+ sourceId: 'fleet-skip',
+ hostname: 'wksn-skipped',
+ hardwareSerial: 'SN-SKIP',
+ hardwareModel: 'MacBook Pro',
+ ));
+
+ $this->assertNull($result);
+ $this->assertDatabaseMissing('assets', ['name' => 'wksn-skipped']);
+ $this->assertDatabaseMissing('asset_external_sources', ['source' => 'fleet', 'external_id' => 'fleet-skip']);
+ }
+
+ public function test_matched_vendor_record_still_updates_when_toggle_off()
+ {
+ // Previously-linked assets must keep syncing. Only the no-match
+ // branch is gated.
+ $instance = $this->configuredFleet();
+ SyncAdapterConfig::put($instance->id, 'create_snipeit_assets_on_pull', '0');
+
+ $asset = Asset::factory()->create(['name' => 'wksn-existing', 'serial' => 'SN-EXISTING']);
+ AssetExternalSource::create([
+ 'asset_id' => $asset->id,
+ 'source' => 'fleet',
+ 'external_id' => 'fleet-linked',
+ ]);
+
+ $result = SyncAdapter::syncFromRecord(new HostInventoryRecord(
+ sourceKey: 'fleet',
+ sourceId: 'fleet-linked',
+ hostname: 'wksn-updated',
+ hardwareSerial: 'SN-EXISTING',
+ hardwareModel: 'MacBook Pro',
+ ));
+
+ $this->assertNotNull($result);
+ $this->assertSame($asset->id, $result->id);
+ $this->assertDatabaseHas('assets', ['id' => $asset->id, 'name' => 'wksn-updated']);
+ }
+
+ private function configuredFleet(): SyncAdapterInstance
+ {
+ $instance = SyncAdapterInstance::where('slug', 'fleet')->firstOrFail();
+ SyncAdapterConfig::put($instance->id, 'url', 'https://example.com/fleet');
+ SyncAdapterConfig::put($instance->id, 'token', Crypt::encrypt('fake-token'));
+
+ return $instance->fresh();
+ }
+}