A free open source IT asset/license management system
Fixed #19691 - avoid phantom models on AxM syncing (abm_model_marketing_name)
snipeb4e6a9f5273d
diff --git a/app/SyncAdapters/SyncsHostFromRecord.php b/app/SyncAdapters/SyncsHostFromRecord.phpindex eebf5f16af..31a974ce37 100644--- a/app/SyncAdapters/SyncsHostFromRecord.php+++ b/app/SyncAdapters/SyncsHostFromRecord.php@@ -39,7 +39,7 @@ trait SyncsHostFromRecord$instance = SyncAdapterInstance::query()->where('slug', $record->sourceKey)->first();$mapping = self::loadMapping($instance);- [$asset, $isNew] = self::provisionAsset($record, $instance);+ [$asset, $isNew] = self::provisionAsset($record, $instance, $mapping);$externalUpdates = [];self::applyStandardFieldMappings($asset, $externalUpdates, $record, $instance, $mapping);@@ -92,7 +92,10 @@ trait SyncsHostFromRecord** @return array{0: Asset, 1: bool} Tuple of the resolved asset and an "isNew" flag.*/- private static function provisionAsset(HostInventoryRecord $record, ?SyncAdapterInstance $instance): array+ /**+ * @param array<string, string> $mapping+ */+ private static function provisionAsset(HostInventoryRecord $record, ?SyncAdapterInstance $instance, array $mapping = []): array{$existingSource = DB::table('asset_external_sources')->where('source', $record->sourceKey)@@ -129,7 +132,7 @@ trait SyncsHostFromRecordreturn [$adopted, false];}- $asset = self::createShellAsset($record, $instance);+ $asset = self::createShellAsset($record, $instance, $mapping);// Identity row created empty of inventory columns. the// mapping loop below fills them and the write goes out@@ -229,6 +232,15 @@ trait SyncsHostFromRecord&& ! in_array($adapterForDirection->directionFor($field), ['pull', 'both'], true)) {continue;}+ // Skip the standard `model` slot when an extra is also+ // mapped to native:model. The extras loop is the last+ // writer for model_id, so a standard-slot write here+ // would spend a resolveModelIdByName() creating an+ // AssetModel keyed on hardwareModel that gets orphaned+ // when extras overwrites the asset's model_id. #19691.+ if ($field === 'model' && $target === 'native:model' && self::hasExtraMappedTo('native:model', $mapping)) {+ continue;+ }$value = self::recordValueFor($record, $field);self::writeToTarget($asset, $externalUpdates, $target, $value, $instance, $record);@@ -529,11 +541,14 @@ trait SyncsHostFromRecord* company_id so FMCS-scoped views only see their own company's* synced hosts.*/- private static function createShellAsset(HostInventoryRecord $record, ?SyncAdapterInstance $instance): Asset+ /**+ * @param array<string, string> $mapping+ */+ private static function createShellAsset(HostInventoryRecord $record, ?SyncAdapterInstance $instance, array $mapping = []): Asset{$asset = new Asset;$asset->name = $record->sourceKey.'-'.$record->sourceId;- $asset->model_id = self::resolveModelId($record, $instance);+ $asset->model_id = self::resolveModelId($record, $instance, $mapping);$asset->status_id = self::resolveStatusId($instance);$asset->asset_tag = self::resolveAssetTag($record, $instance);$asset->company_id = self::resolveCompanyId($record, $instance);@@ -882,13 +897,75 @@ trait SyncsHostFromRecord* Auto-created models get hung off a "Discovered Hardware"* category which is itself get-or-created.*/- private static function resolveModelId(HostInventoryRecord $record, ?SyncAdapterInstance $instance = null): ?int+ /**+ * @param array<string, string> $mapping+ */+ private static function resolveModelId(HostInventoryRecord $record, ?SyncAdapterInstance $instance = null, array $mapping = []): ?int{- if ($record->hardwareModel === null || $record->hardwareModel === '') {+ $modelSource = self::resolveModelSourceValue($record, $mapping);+ if ($modelSource === null || $modelSource === '') {return null;}- return self::resolveModelIdByName($record->hardwareModel, $instance, $record);+ return self::resolveModelIdByName($modelSource, $instance, $record);+ }++ /**+ * True when at least one extra-field mapping targets the given+ * mapping target string (typically 'native:model'). Used to+ * suppress the standard-field write when an extra is going to+ * overwrite the same target further down the mapping loop.+ *+ * @param array<string, string> $mapping+ */+ private static function hasExtraMappedTo(string $target, array $mapping): bool+ {+ foreach ($mapping as $key => $mappedTarget) {+ if ($mappedTarget !== $target) {+ continue;+ }+ if (in_array($key, MappingTargets::FIELDS, true)) {+ continue;+ }++ return true;+ }++ return false;+ }++ /**+ * Pick the value that will end up as this asset's AssetModel name+ * once the mapping loop finishes. When an admin has routed an extra+ * to native:model (Apple Business Manager's marketing name is the+ * common case), the extras loop is the last writer for model_id.+ * createShellAsset must use the same source so the auto-created+ * AssetModel matches what the mapping loop would settle on. Falls+ * back to the record's hardwareModel when nothing is remapped to+ * native:model. Fixes #19691: a phantom AssetModel named after the+ * vendor's part number was left dangling on every new asset when+ * the marketing name was mapped in.+ *+ * @param array<string, string> $mapping+ */+ private static function resolveModelSourceValue(HostInventoryRecord $record, array $mapping): ?string+ {+ foreach ($mapping as $key => $target) {+ if ($target !== 'native:model') {+ continue;+ }+ if (in_array($key, MappingTargets::FIELDS, true)) {+ // Standard field slot. Its source is hardwareModel,+ // which is the same value the fallback below returns.+ continue;+ }+ $value = $record->extra[$key] ?? null;+ if ($value !== null && $value !== '') {+ return (string) $value;+ }+ }++ return $record->hardwareModel;}private static function resolveModelIdByName(string $modelName, ?SyncAdapterInstance $instance = null, ?HostInventoryRecord $record = null): intdiff --git a/tests/Feature/SyncAdapters/AppleBusinessManager/AppleBusinessManagerAdapterTest.php b/tests/Feature/SyncAdapters/AppleBusinessManager/AppleBusinessManagerAdapterTest.phpindex e4ff708237..10c0379a21 100644--- a/tests/Feature/SyncAdapters/AppleBusinessManager/AppleBusinessManagerAdapterTest.php+++ b/tests/Feature/SyncAdapters/AppleBusinessManager/AppleBusinessManagerAdapterTest.php@@ -293,6 +293,42 @@ class AppleBusinessManagerAdapterTest extends TestCase$this->assertNull($records[0]->extra['abm_mdm_server']);}+ public function test_no_phantom_model_when_marketing_name_is_mapped_to_native_model()+ {++ $adapter = $this->configuredAdapter();+ $instance = SyncAdapterInstance::where('slug', 'abm')->firstOrFail();+ SyncAdapterConfig::put($instance->id, 'mapping.abm_model_marketing_name', 'native:model');++ Http::fake([+ 'account.apple.com/*' => Http::response(['access_token' => 'stub-bearer']),+ 'api-business.apple.com/v1/mdmServers' => Http::response(['data' => []]),+ 'api-business.apple.com/v1/orgDevices*' => Http::response([+ 'data' => [+ [+ 'id' => 'abm-guid-19691',+ 'attributes' => [+ 'serialNumber' => 'C02XL9999999',+ 'partNumber' => 'MDVN4LL/A',+ 'deviceModel' => 'MacBook Air (15-inch, M3, 2024)',+ 'productFamily' => 'Mac',+ ],+ ],+ ],+ ]),+ ]);++ foreach ($adapter->pull() as $record) {+ \App\SyncAdapters\SyncAdapter::syncFromRecord($record);+ }++ // Only the marketing-name model should exist, not the+ // partNumber one.+ $this->assertDatabaseHas('models', ['name' => 'MacBook Air (15-inch, M3, 2024)']);+ $this->assertDatabaseMissing('models', ['name' => 'MDVN4LL/A']);+ $this->assertSame(1, \App\Models\Asset::query()->count());+ }+/*** @param array<int, string>|null $productFamilies null = leave the stored filter alone; [] = force to empty*/