A free open source IT asset/license management system
Add “match by serial” checkbox
snipe1492a5028805
diff --git a/app/SyncAdapters/SyncAdapter.php b/app/SyncAdapters/SyncAdapter.phpindex 5a86f2cb33..b42102ebd7 100644--- a/app/SyncAdapters/SyncAdapter.php+++ b/app/SyncAdapters/SyncAdapter.php@@ -368,6 +368,7 @@ abstract class SyncAdapter$slug.'_default_category_id' => ['nullable', 'integer', 'exists:categories,id'],$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'],];if ($this->usesConfigurableUrl()) {@@ -613,6 +614,19 @@ abstract class SyncAdapter$request->boolean($slug.'_checkin_on_null_user') ? '1' : '0',);+ // Migration aid for customers moving from a homegrown sync+ // script that already populated the assets table. When on,+ // provisionAsset() looks up an existing asset by serial+ // before creating a new shell asset, and inserts an+ // asset_external_sources row so subsequent syncs match by+ // external_id. Default off, keeps the safe "vendor host with+ // no known link creates a fresh asset" behavior.+ SyncAdapterConfig::put(+ $this->instance->id,+ 'adopt_by_serial',+ $request->boolean($slug.'_adopt_by_serial') ? '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@@ -1291,6 +1305,18 @@ abstract class SyncAdapterreturn SyncAdapterConfig::get($this->instance->id, 'checkin_on_null_user') === '1';}+ /**+ * 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-seen vendor host. Default off, since+ * silently adopting existing assets is destructive when a+ * customer has multiple adapters or the serial isn't unique.+ */+ public function adoptsBySerial(): bool+ {+ return SyncAdapterConfig::get($this->instance->id, 'adopt_by_serial') === '1';+ }+/*** Whether this adapter's vendor exposes a groups concept* (Fleet Teams, Jamf Sites, Kandji Blueprints, etc.) thatdiff --git a/app/SyncAdapters/SyncsHostFromRecord.php b/app/SyncAdapters/SyncsHostFromRecord.phpindex eb1902093f..eebf5f16af 100644--- a/app/SyncAdapters/SyncsHostFromRecord.php+++ b/app/SyncAdapters/SyncsHostFromRecord.php@@ -117,6 +117,18 @@ trait SyncsHostFromRecordreturn [$asset, false];}+ // Migration path for customers moving from a homegrown+ // sync script. Their existing assets have a serial populated+ // but no asset_external_sources row for this adapter. When+ // the admin has turned on "adopt existing assets by serial",+ // look up a matching Snipe-IT asset before creating a fresh+ // shell. Establishes the identity link so subsequent syncs+ // treat this as an update, not a duplicate create.+ $adopted = self::adoptExistingAssetBySerial($record, $instance);+ if ($adopted !== null) {+ return [$adopted, false];+ }+$asset = self::createShellAsset($record, $instance);// Identity row created empty of inventory columns. the@@ -137,6 +149,54 @@ trait SyncsHostFromRecordreturn [$asset, true];}+ /**+ * Look up an existing Snipe-IT asset with a matching serial to+ * adopt into this adapter's external-sources link, when the+ * admin has turned on adopt_by_serial for this adapter instance.+ * Skips assets that already have an external_sources row for+ * this source so re-runs are idempotent and multi-adapter+ * installs don't accidentally re-link.+ */+ private static function adoptExistingAssetBySerial(HostInventoryRecord $record, ?SyncAdapterInstance $instance): ?Asset+ {+ if ($record->hardwareSerial === null || $record->hardwareSerial === '') {+ return null;+ }+ if ($instance === null) {+ return null;+ }++ $adapter = $instance->adapter();+ if (! ($adapter instanceof SyncAdapter) || ! $adapter->adoptsBySerial()) {+ return null;+ }++ $candidate = Asset::query()+ ->where('serial', $record->hardwareSerial)+ ->whereNotIn('id', function ($q) use ($record) {+ $q->select('asset_id')+ ->from('asset_external_sources')+ ->where('source', $record->sourceKey);+ })+ ->first();++ if ($candidate === null) {+ return null;+ }++ DB::table('asset_external_sources')->insert([+ 'asset_id' => $candidate->id,+ 'company_id' => $instance->company_id,+ 'source' => $record->sourceKey,+ 'external_id' => $record->sourceId,+ 'created_by' => auth()->id(),+ 'created_at' => now(),+ 'updated_at' => now(),+ ]);++ return $candidate;+ }+/*** Apply per-field mappings. Routes each normalized field to native* asset columns, external-source columns, custom fields, or skips@@ -739,7 +799,7 @@ trait SyncsHostFromRecordtry {$asset->purchase_date = \Carbon\Carbon::parse((string) $value)->format('Y-m-d');} catch (\Exception $e) {- Log::channel('sync-adapters')->warning("Skipping unparseable purchase_date \"{$value}\" for asset {$asset->id}: " . $e->getMessage());+ Log::channel('sync-adapters')->warning("Skipping unparseable purchase_date \"{$value}\" for asset {$asset->id}: ".$e->getMessage());}}break;diff --git a/resources/lang/en-US/admin/settings/sync_adapters.php b/resources/lang/en-US/admin/settings/sync_adapters.phpindex db2a7d68c2..9ac82438c5 100644--- a/resources/lang/en-US/admin/settings/sync_adapters.php+++ b/resources/lang/en-US/admin/settings/sync_adapters.php@@ -119,6 +119,8 @@ return ['suppress_notifications_label' => 'Suppress notifications (email, webhooks) on sync-driven assignments','checkin_on_null_user_label' => 'Check assets in when the vendor reports no assigned user','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. 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.',// 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.phpindex d1cb8b1202..a7518d1c2e 100644--- a/resources/views/blade/sync-adapter/form.blade.php+++ b/resources/views/blade/sync-adapter/form.blade.php@@ -276,6 +276,14 @@:help_text="trans('admin/settings/sync_adapters.checkin_on_null_user_help')":disabled="$locked"/>++ <x-form.checkbox-row+ :name="$slug . '_adopt_by_serial'"+ :checked="$adapter->adoptsBySerial()"+ :label="trans('admin/settings/sync_adapters.adopt_by_serial_label')"+ :help_text="trans('admin/settings/sync_adapters.adopt_by_serial_help')"+ :disabled="$locked"+ /></fieldset>{{-- Any type: field_map entries from the adapter's credentialdiff --git a/tests/Feature/SyncAdapters/Landscape/LandscapeAdapterTest.php b/tests/Feature/SyncAdapters/Landscape/LandscapeAdapterTest.phpindex e9773312b8..f5d39fffe9 100644--- a/tests/Feature/SyncAdapters/Landscape/LandscapeAdapterTest.php+++ b/tests/Feature/SyncAdapters/Landscape/LandscapeAdapterTest.php@@ -207,6 +207,126 @@ class LandscapeAdapterTest extends TestCase$this->assertSame('page2-host', $records[1]->hostname);}+ public function test_adopts_existing_asset_by_serial_when_toggle_is_on()+ {+ // Migration scenario: customer already has assets in Snipe-IT+ // (from a homegrown script that populated `serial`) but no+ // asset_external_sources rows for this adapter. With+ // adopt_by_serial turned on, the first sync should adopt the+ // existing asset instead of creating a duplicate.+ $adapter = $this->configuredLandscapeAdapter();+ $instance = SyncAdapterInstance::where('slug', 'landscape')->firstOrFail();+ SyncAdapterConfig::put($instance->id, 'adopt_by_serial', '1');++ $existing = Asset::factory()->create(['serial' => 'ADOPT-ME-001', 'name' => 'pre-existing']);++ Http::fake([+ '*/api/v2/computers*' => Http::sequence()+ ->push($this->landscapeComputersResponse([+ $this->landscapeComputer(id: 42, hostname: 'landscape-sees-it', product: 'PowerEdge', serial: 'ADOPT-ME-001'),+ ])),+ ]);++ foreach ($adapter->pull() as $record) {+ SyncAdapter::syncFromRecord($record);+ }++ $this->assertDatabaseCount('assets', 1);+ $this->assertDatabaseHas('asset_external_sources', [+ 'asset_id' => $existing->id,+ 'source' => 'landscape',+ 'external_id' => '42',+ ]);++ // Adopted asset's non-mapped columns should not be reset.+ // Name comes from the vendor via the standard mapping loop,+ // so it updates. Serial is the match key and stays put.+ $existing->refresh();+ $this->assertSame('ADOPT-ME-001', $existing->serial);+ }++ public function test_does_not_adopt_when_toggle_is_off()+ {+ // Default behavior: matching serial without an+ // asset_external_sources row does NOT auto-adopt. The+ // sync creates a fresh shell asset alongside the existing+ // one. Verifies we don't regress the safe default.+ $adapter = $this->configuredLandscapeAdapter();+ Asset::factory()->create(['serial' => 'NO-ADOPT-001', 'name' => 'pre-existing']);++ Http::fake([+ '*/api/v2/computers*' => Http::sequence()+ ->push($this->landscapeComputersResponse([+ $this->landscapeComputer(id: 42, hostname: 'landscape-sees-it', product: 'PowerEdge', serial: 'NO-ADOPT-001'),+ ])),+ ]);++ foreach ($adapter->pull() as $record) {+ SyncAdapter::syncFromRecord($record);+ }++ $this->assertDatabaseCount('assets', 2);+ }++ public function test_adopt_does_not_re_link_an_already_linked_asset()+ {+ // Idempotency guard: if the asset is already linked (its+ // asset_external_sources row exists for this source), the+ // primary matching path handles it. adoptExistingAssetBySerial+ // should not double-insert.+ $adapter = $this->configuredLandscapeAdapter();+ $instance = SyncAdapterInstance::where('slug', 'landscape')->firstOrFail();+ SyncAdapterConfig::put($instance->id, 'adopt_by_serial', '1');++ Http::fake([+ '*/api/v2/computers*' => Http::sequence()+ ->push($this->landscapeComputersResponse([+ $this->landscapeComputer(id: 42, hostname: 'first-sync', product: 'PowerEdge', serial: 'DUP-001'),+ ]))+ ->push($this->landscapeComputersResponse([+ $this->landscapeComputer(id: 42, hostname: 'second-sync', product: 'PowerEdge', serial: 'DUP-001'),+ ])),+ ]);++ foreach ($adapter->pull() as $record) {+ SyncAdapter::syncFromRecord($record);+ }+ foreach ($adapter->pull() as $record) {+ SyncAdapter::syncFromRecord($record);+ }++ $this->assertDatabaseCount('asset_external_sources', 1);+ $this->assertDatabaseCount('assets', 1);+ }++ public function test_adopt_skips_when_vendor_record_has_no_serial()+ {+ // Some Landscape installs return computer records without a+ // serial (grouped_hardware disabled, or dmidecode unavailable+ // on that host). Adoption should be a no-op in that case, not+ // adopt a random unrelated asset by matching NULL to NULL.+ $adapter = $this->configuredLandscapeAdapter();+ $instance = SyncAdapterInstance::where('slug', 'landscape')->firstOrFail();+ SyncAdapterConfig::put($instance->id, 'adopt_by_serial', '1');+ Asset::factory()->create(['serial' => null, 'name' => 'unrelated-existing']);++ Http::fake([+ '*/api/v2/computers*' => Http::sequence()+ ->push($this->landscapeComputersResponse([+ // Product info populated so createShellAsset can+ // still derive a model. serial stays null so the+ // adopt path is the thing under test.+ $this->landscapeComputer(id: 42, hostname: 'no-serial-host', product: 'PowerEdge', vendor: 'Dell', serial: null),+ ])),+ ]);++ foreach ($adapter->pull() as $record) {+ SyncAdapter::syncFromRecord($record);+ }++ $this->assertDatabaseCount('assets', 2);+ }+public function test_bearer_token_is_sent_on_every_request(){$adapter = $this->configuredLandscapeAdapter();