A free open source IT asset/license management system
Fixed #19687 - auto-create/return ID models based on name
snipe50d120222cd4
diff --git a/app/SyncAdapters/SyncsHostFromRecord.php b/app/SyncAdapters/SyncsHostFromRecord.phpindex 6f8f5426dc..bab062cd74 100644--- a/app/SyncAdapters/SyncsHostFromRecord.php+++ b/app/SyncAdapters/SyncsHostFromRecord.php@@ -7,6 +7,7 @@ use App\Models\Asset;use App\Models\AssetModel;use App\Models\Category;use App\Models\CustomField;+use App\Models\Manufacturer;use App\Models\Statuslabel;use App\Models\SyncAdapterConfig;use App\Models\SyncAdapterInstance;@@ -51,8 +52,8 @@ trait SyncsHostFromRecord// when the mapping directs last_seen to a custom field (target custom:X).// Otherwise the vendor's heartbeat lands on the asset and fires AssetObserver::updating// on save, which writes an `update` Actionlog.- if (!$isNew && self::isHeartbeatOnlyAssetDirty($asset, $mapping, $instance)) {- if (!$asset->saveQuietly()) {+ if (! $isNew && self::isHeartbeatOnlyAssetDirty($asset, $mapping, $instance)) {+ if (! $asset->saveQuietly()) {throw new RuntimeException('Failed to save asset during heartbeat-only sync.');}} else {@@ -753,19 +754,19 @@ trait SyncsHostFromRecordarray $mapping,?SyncAdapterInstance $instance,): bool {- if (!$asset->isDirty()) {+ if (! $asset->isDirty()) {return false;}if ($instance === null) {return false;}$adapter = $instance->adapter();- if (!$adapter instanceof SyncAdapter || $adapter->logsHeartbeats()) {+ if (! $adapter instanceof SyncAdapter || $adapter->logsHeartbeats()) {return false;}$lastSeenTarget = $mapping['last_seen'] ?? MappingTargets::defaultTarget('last_seen');- if (!str_starts_with($lastSeenTarget, 'custom:')) {+ if (! str_starts_with($lastSeenTarget, 'custom:')) {return false;}@@ -836,11 +837,38 @@ trait SyncsHostFromRecord$model = new AssetModel;$model->name = $modelName;$model->category_id = self::categoryIdFor($instance, $record);+ $model->manufacturer_id = self::manufacturerIdFor($record);$model->save();return $model->id;}+ /**+ * Resolve the manufacturer for a new model. MySQL's default+ * collation is case-insensitive, so firstOrCreate matches 'apple'+ * or 'APPLE' to an existing 'Apple' row without a duplicate. When+ * we do create a new one, log a warning so admins can spot near-+ * duplicates like 'Apple' vs 'Apple, Inc.' that the collation+ * won't catch. Returns null when the record carries no+ * manufacturer so we don't stamp a default.+ */+ private static function manufacturerIdFor(?HostInventoryRecord $record): ?int+ {+ $name = $record?->manufacturer;+ if (! is_string($name) || trim($name) === '') {+ return null;+ }++ $manufacturer = Manufacturer::firstOrCreate(['name' => trim($name)]);+ if ($manufacturer->wasRecentlyCreated) {+ Log::channel('sync-adapters')->warning(+ "Sync adapter created new manufacturer \"{$manufacturer->name}\". If this duplicates an existing manufacturer under a different spelling, reassign the affected asset models to the manufacturer you want to keep and delete the extra one.",+ );+ }++ return (int) $manufacturer->id;+ }+/*** Category id auto-created models get hung off. Precedence:* 1. Adapter's per-record override (e.g. ABM productFamilydiff --git a/tests/Feature/SyncAdapters/ManufacturerAutoCreateTest.php b/tests/Feature/SyncAdapters/ManufacturerAutoCreateTest.phpnew file mode 100644index 0000000000..ca95614246--- /dev/null+++ b/tests/Feature/SyncAdapters/ManufacturerAutoCreateTest.php@@ -0,0 +1,114 @@+<?php++namespace Tests\Feature\SyncAdapters;++use App\Models\AssetModel;+use App\Models\Manufacturer;+use App\Models\Statuslabel;+use App\SyncAdapters\HostInventoryRecord;+use App\SyncAdapters\SyncAdapter;+use Tests\TestCase;++class ManufacturerAutoCreateTest extends TestCase+{+ protected function setUp(): void+ {+ parent::setUp();+ Statuslabel::factory()->rtd()->create();+ }++ public function test_new_model_gets_the_records_manufacturer()+ {+ SyncAdapter::syncFromRecord(new HostInventoryRecord(+ sourceKey: 'fleet',+ sourceId: '1',+ hostname: 'wksn-01',+ hardwareSerial: 'SN-ABC123',+ hardwareModel: 'MacBook Pro',+ manufacturer: 'Apple',+ ));++ $model = AssetModel::where('name', 'MacBook Pro')->first();+ $this->assertNotNull($model);+ $this->assertNotNull($model->manufacturer_id);+ $this->assertSame('Apple', $model->manufacturer->name);+ }++ public function test_existing_manufacturer_is_reused_not_duplicated()+ {+ // Case-insensitive matching on MySQL's default collation+ // handles casing differences in production. The test DB+ // is SQLite (BINARY collation by default), so this pins+ // the same-case reuse case.+ $existing = Manufacturer::factory()->create(['name' => 'Apple']);++ SyncAdapter::syncFromRecord(new HostInventoryRecord(+ sourceKey: 'fleet',+ sourceId: '1',+ hostname: 'wksn-01',+ hardwareSerial: 'SN-ABC123',+ hardwareModel: 'MacBook Pro',+ manufacturer: 'Apple',+ ));++ $this->assertSame(1, Manufacturer::where('name', 'Apple')->count(), 'Existing manufacturer should be reused, not duplicated.');++ $model = AssetModel::where('name', 'MacBook Pro')->first();+ $this->assertSame($existing->id, $model->manufacturer_id);+ }++ public function test_no_manufacturer_on_record_leaves_manufacturer_id_null()+ {+ SyncAdapter::syncFromRecord(new HostInventoryRecord(+ sourceKey: 'fleet',+ sourceId: '1',+ hostname: 'wksn-01',+ hardwareSerial: 'SN-ABC123',+ hardwareModel: 'MacBook Pro',+ manufacturer: null,+ ));++ $model = AssetModel::where('name', 'MacBook Pro')->first();+ $this->assertNotNull($model);+ $this->assertNull($model->manufacturer_id);+ }++ public function test_blank_manufacturer_string_leaves_manufacturer_id_null()+ {+ SyncAdapter::syncFromRecord(new HostInventoryRecord(+ sourceKey: 'fleet',+ sourceId: '1',+ hostname: 'wksn-01',+ hardwareSerial: 'SN-ABC123',+ hardwareModel: 'MacBook Pro',+ manufacturer: ' ',+ ));++ $model = AssetModel::where('name', 'MacBook Pro')->first();+ $this->assertNull($model->manufacturer_id);+ }++ public function test_existing_model_is_not_reassigned_on_resync()+ {+ // Preserve hand-curated manufacturer values on models the+ // admin already touched. This is the "leave existing alone"+ // half of the reporter's suggested fix.+ $handPickedManufacturer = Manufacturer::factory()->create(['name' => 'Apple, Inc.']);+ $existing = AssetModel::factory()->create([+ 'name' => 'MacBook Pro',+ 'manufacturer_id' => $handPickedManufacturer->id,+ ]);++ SyncAdapter::syncFromRecord(new HostInventoryRecord(+ sourceKey: 'fleet',+ sourceId: '1',+ hostname: 'wksn-01',+ hardwareSerial: 'SN-ABC123',+ hardwareModel: 'MacBook Pro',+ manufacturer: 'Apple',+ ));++ $existing->refresh();+ $this->assertSame($handPickedManufacturer->id, $existing->manufacturer_id, 'Existing model manufacturer should not be clobbered by sync.');+ }+}