A free open source IT asset/license management system
Better map categories in ABM and pull images
snipeab909f6024dd
diff --git a/app/SyncAdapters/AdapterRegistry.php b/app/SyncAdapters/AdapterRegistry.phpindex 0d3f09f4cc..41d7431b2c 100644--- a/app/SyncAdapters/AdapterRegistry.php+++ b/app/SyncAdapters/AdapterRegistry.php@@ -38,7 +38,7 @@ class AdapterRegistryprivate const TYPES = ['fleet' => FleetAdapter::class,'addigy' => AddigyAdapter::class,- 'apple_business_manager' => AppleBusinessManagerAdapter::class,+ 'abm' => AppleBusinessManagerAdapter::class,'intune' => IntuneAdapter::class,'jamf' => JamfAdapter::class,'jamf_school' => JamfSchoolAdapter::class,diff --git a/app/SyncAdapters/AppleBusinessManager/AppleBusinessManagerAdapter.php b/app/SyncAdapters/AppleBusinessManager/AppleBusinessManagerAdapter.phpindex a9fedd284a..bb149d8e1f 100644--- a/app/SyncAdapters/AppleBusinessManager/AppleBusinessManagerAdapter.php+++ b/app/SyncAdapters/AppleBusinessManager/AppleBusinessManagerAdapter.php@@ -34,22 +34,62 @@ use Illuminate\Support\Arr;*/class AppleBusinessManagerAdapter extends ConfigurableAdapter{+ /**+ * Apple's fixed productFamily enum -> friendly display name.+ * Drives the product-family filter's option list.+ *+ * @var array<string, string>+ */+ private const PRODUCT_FAMILIES = [+ 'Mac' => 'Mac',+ 'iPhone' => 'iPhone',+ 'iPad' => 'iPad',+ 'AppleTV' => 'Apple TV',+ 'Watch' => 'Apple Watch',+ 'Vision' => 'Apple Vision',+ ];++ /**+ * Per-category-selector config keys -> friendly display name.+ * Distinct from PRODUCT_FAMILIES because Mac's productFamily+ * collapses laptops and desktops into one bucket, but admins+ * usually want to route them to different Snipe-IT categories+ * ("Laptops" vs "Desktops"), so the "Mac" family gets split+ * into two selectors driven by deviceModel prefix.+ * categoryConfigKeyForFamily() encodes the mapping in the other+ * direction.+ *+ * @var array<string, string>+ */+ private const CATEGORY_SELECTORS = [+ 'category_id_mac_laptop' => 'Mac Laptop',+ 'category_id_mac_desktop' => 'Mac Desktop',+ 'category_id_iphone' => 'iPhone',+ 'category_id_ipad' => 'iPad',+ 'category_id_appletv' => 'Apple TV',+ 'category_id_watch' => 'Apple Watch',+ 'category_id_vision' => 'Apple Vision',+ ];+public static function typeLabel(): string{return 'Apple Business Manager';}- public function baseUrlPlaceholder(): ?string+ /**+ * ABM/ASM base URLs are host-fixed per mode (business or school),+ * so the admin never types a URL. Mode selection in the+ * credential schema controls host + scope inside+ * AppleBusinessManagerClient::apiBaseUrl.+ */+ public function usesConfigurableUrl(): bool{- // ABM/ASM base URLs are host-fixed per mode (business or- // school), so we don't expose a URL field. The mode selection- // in the credential schema controls host + scope.- return null;+ return false;}public function credentialSchema(): array{- return [+ $schema = [['key' => 'mode','label' => 'Portal',@@ -82,15 +122,8 @@ class AppleBusinessManagerAdapter extends ConfigurableAdapter'key' => 'product_family_filter','label' => 'Product Families','type' => 'multiselect',- 'options' => [- 'Mac' => 'Mac',- 'iPhone' => 'iPhone',- 'iPad' => 'iPad',- 'AppleTV' => 'Apple TV',- 'Watch' => 'Apple Watch',- 'Vision' => 'Apple Vision',- ],- 'default' => ['Mac', 'iPhone', 'iPad', 'AppleTV', 'Watch', 'Vision'],+ 'options' => self::PRODUCT_FAMILIES,+ 'default' => array_keys(self::PRODUCT_FAMILIES),'required' => false,'help' => trans('admin/settings/sync_adapters.abm_product_family_filter_help'),],@@ -102,6 +135,26 @@ class AppleBusinessManagerAdapter extends ConfigurableAdapter'help' => trans('admin/settings/sync_adapters.abm_pull_model_images_help'),],];++ // Per-family category overrides. Apple's productFamily is a+ // fixed enum, so admins can route iPads to "Tablets", Watches+ // to "Wearables", etc. Mac is split into laptop + desktop+ // because Apple lumps them together and admins usually want+ // them in separate Snipe-IT categories. Empty selection falls+ // back to default_category_id. Label + help share one+ // :family-templated translation each so localizers translate+ // the strings once rather than seven times.+ foreach (self::CATEGORY_SELECTORS as $key => $displayName) {+ $schema[] = [+ 'key' => $key,+ 'label' => trans('admin/settings/sync_adapters.abm_category_family_label', ['family' => $displayName]),+ 'type' => 'category',+ 'required' => false,+ 'help' => trans('admin/settings/sync_adapters.abm_category_family_help', ['family' => $displayName]),+ ];+ }++ return $schema;}public function extraFields(): array@@ -128,6 +181,78 @@ class AppleBusinessManagerAdapter extends ConfigurableAdapter];}+ /**+ * Route each record to a per-productFamily category when the+ * admin configured one. Apple's productFamily is a fixed+ * six-value enum (Mac, iPhone, iPad, AppleTV, Watch, Vision), so+ * the mapping is exhaustive by design. Any family the admin+ * hasn't overridden falls through to defaultCategoryId() via+ * the framework's null-return convention.+ */+ public function categoryIdForRecord(HostInventoryRecord $record): ?int+ {+ $configKey = self::categoryConfigKeyForRecord($record);+ if ($configKey === null) {+ return null;+ }++ try {+ $stored = $this->credential($configKey);+ } catch (\Throwable) {+ return null;+ }++ return $stored === '' ? null : (int) $stored;+ }++ /**+ * Which per-family credential key applies to this record. Mac is+ * split into laptop / desktop based on the marketing name prefix:+ * "MacBook*" is a laptop, anything starting with iMac, Mac mini,+ * Mac Studio, or Mac Pro is a desktop. Marketing name is used+ * because productType lost its form-factor tag on Apple Silicon+ * (M-series desktops all report bare "Mac14,x"/"Mac15,x" with no+ * iMac/Macmini/MacPro prefix).+ *+ * Returns null when the family is unrecognized OR for Macs with+ * an unparseable marketing name, so the framework falls back to+ * defaultCategoryId() rather than saving under an arbitrary+ * bucket.+ */+ private static function categoryConfigKeyForRecord(HostInventoryRecord $record): ?string+ {+ $family = $record->extra['abm_product_family'] ?? null;+ if (! is_string($family)) {+ return null;+ }++ if ($family === 'Mac') {+ $deviceModel = $record->extra['abm_model_marketing_name'] ?? '';+ if (! is_string($deviceModel) || $deviceModel === '') {+ return null;+ }+ if (str_starts_with($deviceModel, 'MacBook')) {+ return 'category_id_mac_laptop';+ }+ foreach (['iMac', 'Mac mini', 'Mac Studio', 'Mac Pro'] as $desktopPrefix) {+ if (str_starts_with($deviceModel, $desktopPrefix)) {+ return 'category_id_mac_desktop';+ }+ }++ return null;+ }++ return match ($family) {+ 'iPhone' => 'category_id_iphone',+ 'iPad' => 'category_id_ipad',+ 'AppleTV' => 'category_id_appletv',+ 'Watch' => 'category_id_watch',+ 'Vision' => 'category_id_vision',+ default => null,+ };+ }+public function pull(): iterable{$client = new AppleBusinessManagerClient(@@ -193,9 +318,10 @@ class AppleBusinessManagerAdapter extends ConfigurableAdapter* - If no productType is on the record, skip (nothing to key* appledb.dev on).* - If the model exists AND it already carries an image, skip- * (respect admin curation).- * - If the model exists AND its category has an image, skip- * (category fallback already covers the display case).+ * (respect admin curation). The category's image is a display+ * fallback in AssetModel::getImageUrl, not a signal to skip:+ * per-model images still populate over a category icon so+ * admins get Apple's marketing shots per SKU.* - Otherwise fetch the image, write it to storage, and set* model.image. The framework's later resolveModelIdByName* find the model we (or a prior sync) created.@@ -217,6 +343,12 @@ class AppleBusinessManagerAdapter extends ConfigurableAdapter: $record->hardwareModel;if ($modelName === null || $modelName === '') {+ \Log::channel('sync-adapters')->info(sprintf(+ '%s image skip for device %s: no model name resolvable (hardwareModel and abm_model_marketing_name both blank)',+ $this->name(),+ $record->sourceId,+ ));+return $imagesHandled;}@@ -227,50 +359,74 @@ class AppleBusinessManagerAdapter extends ConfigurableAdapter$productType = $record->extra['abm_product_type'] ?? null;if (! is_string($productType) || $productType === '') {+ \Log::channel('sync-adapters')->info(sprintf(+ '%s image skip for model "%s": ABM did not return a productType, nothing to look up on appledb.dev',+ $this->name(),+ $modelName,+ ));+return $imagesHandled;}$existing = AssetModel::query()->where('name', $modelName)- ->with('category')->first();- if ($existing !== null && $this->existingModelAlreadyHasImageCoverage($existing)) {+ if ($existing !== null && ! empty($existing->image)) {+ \Log::channel('sync-adapters')->info(sprintf(+ '%s image skip for model "%s": model already has an image (%s)',+ $this->name(),+ $modelName,+ $existing->image,+ ));+return $imagesHandled;}$color = $record->extra['abm_color'] ?? null;$filename = AppleDBImageFetcher::fetch($productType, is_string($color) ? $color : null);if ($filename === null) {+ \Log::channel('sync-adapters')->info(sprintf(+ '%s image skip for model "%s" (productType=%s): appledb.dev returned no usable image',+ $this->name(),+ $modelName,+ $productType,+ ));+return $imagesHandled;}- if ($existing !== null) {- $existing->image = $filename;- $existing->save();+ if ($existing === null) {+ // First-pass timing: the framework hasn't created the+ // AssetModel row yet (SyncHostFromAdapter builds it after+ // pull() yields), so there's nothing to update. The image+ // is already downloaded and cached under public/uploads/+ // models/ by the fetcher, so the next sync will find the+ // model row and only need to set model.image (no+ // re-download).+ \Log::channel('sync-adapters')->info(sprintf(+ '%s image staged for model "%s" (productType=%s, file=%s): AssetModel row not yet created, image will be assigned on the next sync',+ $this->name(),+ $modelName,+ $productType,+ $filename,+ ));++ return $imagesHandled;}- // If the model doesn't exist yet, the framework's- // resolveModelIdByName will create it on demand. We can't- // pre-create here without duplicating category-resolution- // logic, so we let the framework build the shell. A follow-- // up sync re-runs this method and finds the model, then- // backfills the image on the second pass.- return $imagesHandled;- }+ $existing->image = $filename;+ $existing->save();- /**- * Returns true when the existing model or its category already- * provides an image, so we don't overwrite curated content.- */- private function existingModelAlreadyHasImageCoverage(AssetModel $model): bool- {- if (! empty($model->image)) {- return true;- }- $category = $model->category;+ \Log::channel('sync-adapters')->info(sprintf(+ '%s image assigned to model "%s" (productType=%s, file=%s)',+ $this->name(),+ $modelName,+ $productType,+ $filename,+ ));- return $category !== null && ! empty($category->image);+ return $imagesHandled;}/**diff --git a/app/SyncAdapters/AppleBusinessManager/AppleDBImageFetcher.php b/app/SyncAdapters/AppleBusinessManager/AppleDBImageFetcher.phpindex 4143a2b4ee..eeca74d350 100644--- a/app/SyncAdapters/AppleBusinessManager/AppleDBImageFetcher.php+++ b/app/SyncAdapters/AppleBusinessManager/AppleDBImageFetcher.php@@ -68,11 +68,21 @@ class AppleDBImageFetcher$imageKey = $device['imageKey'] ?? null;$colors = $device['colors'] ?? [];if (! is_string($imageKey) || $imageKey === '' || ! is_array($colors) || $colors === []) {+ Log::channel('sync-adapters')->info(sprintf(+ 'appledb.dev entry for productType %s is missing imageKey or colors; skipping image',+ $productType,+ ));+return null;}$colorKey = self::pickColorKey($colors, $colorHint);if ($colorKey === null) {+ Log::channel('sync-adapters')->info(sprintf(+ 'appledb.dev entry for productType %s has no usable colorKey; skipping image',+ $productType,+ ));+return null;}@@ -99,6 +109,12 @@ class AppleDBImageFetcher}if (! $response->successful()) {+ Log::channel('sync-adapters')->info(sprintf(+ 'appledb.dev has no catalog entry for productType %s (status %d); skipping image',+ $productType,+ $response->status(),+ ));+return null;}@@ -161,11 +177,24 @@ class AppleDBImageFetcher}if (! $response->successful()) {+ Log::channel('sync-adapters')->info(sprintf(+ 'appledb.dev image CDN returned %d for %s (%s); skipping image',+ $response->status(),+ $productType,+ $colorKey,+ ));+return null;}$bytes = $response->body();if ($bytes === '') {+ Log::channel('sync-adapters')->info(sprintf(+ 'appledb.dev image CDN returned empty body for %s (%s); skipping image',+ $productType,+ $colorKey,+ ));+return null;}@@ -180,6 +209,13 @@ class AppleDBImageFetcherreturn null;}+ Log::channel('sync-adapters')->info(sprintf(+ 'appledb.dev image saved for productType %s (color=%s, file=%s)',+ $productType,+ $colorKey,+ $filename,+ ));+return $filename;}diff --git a/app/SyncAdapters/Support/ConfigurableAdapter.php b/app/SyncAdapters/Support/ConfigurableAdapter.phpindex 058aaffd02..414d9d5367 100644--- a/app/SyncAdapters/Support/ConfigurableAdapter.php+++ b/app/SyncAdapters/Support/ConfigurableAdapter.php@@ -134,7 +134,7 @@ abstract class ConfigurableAdapter implements HostInventoryAdapterreturn false;}- if (empty(SyncAdapterConfig::get($this->instance->id, 'url'))) {+ if ($this->usesConfigurableUrl() && empty(SyncAdapterConfig::get($this->instance->id, 'url'))) {return false;}@@ -147,6 +147,19 @@ abstract class ConfigurableAdapter implements HostInventoryAdapterreturn true;}+ /**+ * Whether the admin needs to configure a base URL for this+ * adapter. Defaults to true because most vendors expose a+ * tenant-specific host. Adapters whose host is fixed (Apple ABM+ * derives the host from the Portal enum, so there's nothing for+ * the admin to type) override to false, and the shared form,+ * validation, and isEnabled() gate all skip the URL field.+ */+ public function usesConfigurableUrl(): bool+ {+ return true;+ }+/*** Three-state readiness for the settings-page tab indicator:*@@ -185,13 +198,16 @@ abstract class ConfigurableAdapter implements HostInventoryAdapter$slug = $this->instance->slug;$rules = [- $slug.'_url' => ['required', new ExternalUrl],$slug.'_asset_tag_pattern' => ['nullable', 'string', 'max:191'],$slug.'_default_category_id' => ['required', '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'],];+ if ($this->usesConfigurableUrl()) {+ $rules[$slug.'_url'] = ['required', new ExternalUrl];+ }+foreach ($this->credentialSchema() as $field) {// Auth fields default to required so admins can't save a// half-configured adapter that then silently refuses to@@ -215,6 +231,14 @@ abstract class ConfigurableAdapter implements HostInventoryAdaptercontinue;}+ // Category selectors post the chosen category id (or an+ // empty string to fall back to default_category_id).+ if ($type === 'category') {+ $rules[$fieldName] = [$required ? 'required' : 'nullable', 'integer', 'exists:categories,id'];++ continue;+ }+$rules[$fieldName] = [$required ? 'required' : 'nullable','string',@@ -228,7 +252,9 @@ abstract class ConfigurableAdapter implements HostInventoryAdapter{$slug = $this->instance->slug;- $this->persistUrl($request, $slug);+ if ($this->usesConfigurableUrl()) {+ $this->persistUrl($request, $slug);+ }$this->persistCredentialsFromSchema($request, $slug);$this->persistOperationalSettings($request, $slug);@@ -295,6 +321,20 @@ abstract class ConfigurableAdapter implements HostInventoryAdaptercontinue;}+ // Category selector: empty means "fall back to the+ // instance-wide default_category_id". Store as-is so a+ // deliberate clear overwrites a previous pick.+ if ($type === 'category') {+ $value = $request->input($fieldName, '');+ SyncAdapterConfig::put(+ $this->instance->id,+ $field['key'],+ $value === null ? '' : (string) $value,+ );++ continue;+ }+if (! $request->filled($fieldName)) {continue;}@@ -702,6 +742,22 @@ abstract class ConfigurableAdapter implements HostInventoryAdapterreturn $stored === null || $stored === '' ? null : (int) $stored;}+ /**+ * Per-record category override. Adapters that can classify a+ * record's device type (Apple's productFamily, Intune's+ * deviceCategory, etc.) override this to route each record to a+ * more specific category than the instance-wide default.+ *+ * Return null to fall through to defaultCategoryId(). The+ * framework calls this from SyncHostFromAdapter when creating a+ * new AssetModel row, so a null return is equivalent to today's+ * one-category-per-instance behavior.+ */+ public function categoryIdForRecord(\App\SyncAdapters\HostInventoryRecord $record): ?int+ {+ return null;+ }+/*** Default status label id for auto-created assets from this* adapter. When null, SyncHostFromAdapter falls back to thediff --git a/app/SyncAdapters/SyncHostFromAdapter.php b/app/SyncAdapters/SyncHostFromAdapter.phpindex 30ead0d290..eb2f0aa9c0 100644--- a/app/SyncAdapters/SyncHostFromAdapter.php+++ b/app/SyncAdapters/SyncHostFromAdapter.php@@ -160,7 +160,7 @@ class SyncHostFromAdapter}$value = self::recordValueFor($record, $field);- self::writeToTarget($asset, $externalUpdates, $target, $value, $instance);+ self::writeToTarget($asset, $externalUpdates, $target, $value, $instance, $record);}}@@ -203,7 +203,7 @@ class SyncHostFromAdapter$record->extra[$extraKey] ?? null,self::extraFieldType($extraFields, $extraKey),);- self::writeExtraValueToTarget($asset, $target, $value, $instance);+ self::writeExtraValueToTarget($asset, $target, $value, $instance, $record);}}@@ -219,6 +219,7 @@ class SyncHostFromAdapterstring $target,?string $value,SyncAdapterInstance $instance,+ ?HostInventoryRecord $record = null,): void {if ($target === 'skip' || $value === null) {return;@@ -231,7 +232,7 @@ class SyncHostFromAdapter}if (str_starts_with($target, 'native:')) {- self::writeNative($asset, substr($target, 7), $value, $instance);+ self::writeNative($asset, substr($target, 7), $value, $instance, $record);}}@@ -611,7 +612,7 @@ class SyncHostFromAdapter** @param array<string, mixed> $externalUpdates passed by reference*/- private static function writeToTarget(Asset $asset, array &$externalUpdates, string $target, mixed $value, ?SyncAdapterInstance $instance = null): void+ private static function writeToTarget(Asset $asset, array &$externalUpdates, string $target, mixed $value, ?SyncAdapterInstance $instance = null, ?HostInventoryRecord $record = null): void{if ($value === null && $target !== 'native:model') {// Nothing to write. Skip so we don't blank existing data on@@ -623,7 +624,7 @@ class SyncHostFromAdapterswitch ($type) {case 'native':- self::writeNative($asset, $id, $value, $instance);+ self::writeNative($asset, $id, $value, $instance, $record);break;case 'external':// Normalized field names get translated to actual@@ -644,7 +645,7 @@ class SyncHostFromAdapter}}- private static function writeNative(Asset $asset, string $column, mixed $value, ?SyncAdapterInstance $instance = null): void+ private static function writeNative(Asset $asset, string $column, mixed $value, ?SyncAdapterInstance $instance = null, ?HostInventoryRecord $record = null): void{switch ($column) {case 'name':@@ -672,11 +673,12 @@ class SyncHostFromAdapter}break;case 'model':- // Model comes as a string name. Resolve or auto-create- // using the instance's configured default category- // (or fall back to "Discovered Hardware" when unset).+ // Model comes as a string name. Resolve or auto-create,+ // routing to a per-record category when the adapter+ // provides one (e.g. ABM productFamily) and falling+ // back to the instance-wide default_category_id.if ($value !== null && $value !== '') {- $asset->model_id = self::resolveModelIdByName((string) $value, $instance);+ $asset->model_id = self::resolveModelIdByName((string) $value, $instance, $record);}break;}@@ -725,33 +727,53 @@ class SyncHostFromAdapterreturn null;}- return self::resolveModelIdByName($record->hardwareModel, $instance);+ return self::resolveModelIdByName($record->hardwareModel, $instance, $record);}- private static function resolveModelIdByName(string $modelName, ?SyncAdapterInstance $instance = null): int+ private static function resolveModelIdByName(string $modelName, ?SyncAdapterInstance $instance = null, ?HostInventoryRecord $record = null): int{$model = AssetModel::where('name', $modelName)->first();if ($model !== null) {+ // Re-sync the category ONLY when the adapter has a+ // per-record opinion (e.g. ABM's productFamily ++ // deviceModel routing). Falling through to+ // default_category_id doesn't touch the existing+ // category, because admins often curate model categories+ // by hand and the instance-wide default would clobber+ // that work every sync.+ $perRecordId = self::perRecordCategoryId($instance, $record);+ if ($perRecordId !== null && $model->category_id !== $perRecordId) {+ $model->category_id = $perRecordId;+ $model->save();+ }+return $model->id;}$model = new AssetModel;$model->name = $modelName;- $model->category_id = self::categoryIdFor($instance);+ $model->category_id = self::categoryIdFor($instance, $record);$model->save();return $model->id;}/**- * Category id auto-created models get hung off. Uses the- * adapter's configured default_category_id when set (and the- * category still exists), else falls back to a get-or-create- * "Discovered Hardware" category so we always produce a valid- * category_id (AssetModel requires one).+ * Category id auto-created models get hung off. Precedence:+ * 1. Adapter's per-record override (e.g. ABM productFamily+ * routing to family-specific categories) via+ * categoryIdForRecord($record).+ * 2. Adapter's instance-wide default_category_id.+ * 3. Get-or-create "Discovered Hardware" fallback so we always+ * produce a valid category_id (AssetModel requires one).*/- private static function categoryIdFor(?SyncAdapterInstance $instance): int+ private static function categoryIdFor(?SyncAdapterInstance $instance, ?HostInventoryRecord $record = null): int{+ $perRecordId = self::perRecordCategoryId($instance, $record);+ if ($perRecordId !== null) {+ return $perRecordId;+ }+if ($instance !== null) {$adapter = $instance->adapter();if ($adapter instanceof ConfigurableAdapter) {@@ -767,6 +789,31 @@ class SyncHostFromAdapter)->id;}+ /**+ * Adapter-declared per-record category id, validated to still+ * exist. Returns null when the adapter has no per-record opinion+ * OR the id it returned no longer resolves (e.g. an admin+ * deleted the target category after configuring the override).+ * Null return means "no explicit re-sync intent" and callers+ * should fall through to their own defaults.+ */+ private static function perRecordCategoryId(?SyncAdapterInstance $instance, ?HostInventoryRecord $record): ?int+ {+ if ($instance === null || $record === null) {+ return null;+ }+ $adapter = $instance->adapter();+ if (! $adapter instanceof ConfigurableAdapter) {+ return null;+ }+ $id = $adapter->categoryIdForRecord($record);+ if ($id === null || ! Category::whereKey($id)->exists()) {+ return null;+ }++ return $id;+ }+/*** Look up the vendor-reported user on the record against Snipe-IT* users per the adapter's configured match strategy, and assigndiff --git a/resources/lang/en-US/admin/settings/sync_adapters.php b/resources/lang/en-US/admin/settings/sync_adapters.phpindex 28fb1d67d6..045dea28c8 100644--- a/resources/lang/en-US/admin/settings/sync_adapters.php+++ b/resources/lang/en-US/admin/settings/sync_adapters.php@@ -175,7 +175,9 @@ return ['abm_key_id_help' => 'Paired with the Client ID. Shown on the same key detail page in the ABM/ASM console.','abm_private_key_help' => 'Paste the contents of the .pem private-key file you downloaded when you created the API key. Apple only lets you download the key once.','abm_product_family_filter_help' => 'Only sync devices in the selected product families.',- 'abm_pull_model_images_help' => 'Fetch product images from appledb.dev when auto-populating asset models from ABM devices. Existing model images and category images are never overwritten.',+ 'abm_pull_model_images_help' => 'Fetch product images from appledb.dev when auto-populating asset models from ABM devices. Existing model images are never overwritten. The category image serves only as a display fallback for models that have none.',+ 'abm_category_family_label' => 'Category for :family',+ 'abm_category_family_help' => 'Route the :family product family to a specific category, overriding the default category above. Leave blank to inherit the default.',// Extras / mapping section wrappers'extra_fields_section_title' => ':type-specific fields',diff --git a/resources/views/blade/sync-adapter-form.blade.php b/resources/views/blade/sync-adapter-form.blade.phpindex b8a9538350..c87fae8173 100644--- a/resources/views/blade/sync-adapter-form.blade.php+++ b/resources/views/blade/sync-adapter-form.blade.php@@ -60,26 +60,28 @@:disabled="$locked"/>- <x-form.row- :label="trans('admin/settings/sync_adapters.base_url')"- :name="$urlField"- input_div_class="col-md-8"- :help_text="trans('admin/settings/sync_adapters.base_url_help', ['type' => $adapter::typeLabel()])"- required- >- <x-slot:input>- <x-input.text- type="url"- :name="$urlField"- :value="old($urlField, $adapter->getUrl())"- :disabled="$locked"- :placeholder="$adapter->baseUrlPlaceholder()"- input_icon="link"- input_group_addon="right"- required- />- </x-slot:input>- </x-form.row>+ @if ($adapter->usesConfigurableUrl())+ <x-form.row+ :label="trans('admin/settings/sync_adapters.base_url')"+ :name="$urlField"+ input_div_class="col-md-8"+ :help_text="trans('admin/settings/sync_adapters.base_url_help', ['type' => $adapter::typeLabel()])"+ required+ >+ <x-slot:input>+ <x-input.text+ type="url"+ :name="$urlField"+ :value="old($urlField, $adapter->getUrl())"+ :disabled="$locked"+ :placeholder="$adapter->baseUrlPlaceholder()"+ input_icon="link"+ input_group_addon="right"+ required+ />+ </x-slot:input>+ </x-form.row>+ @endif{{ $slot }}diff --git a/resources/views/settings/adapters/adapter_credentials.blade.php b/resources/views/settings/adapters/adapter_credentials.blade.phpindex 6db0f3b85a..7e2b94ba29 100644--- a/resources/views/settings/adapters/adapter_credentials.blade.php+++ b/resources/views/settings/adapters/adapter_credentials.blade.php@@ -76,6 +76,19 @@:help_text="$field['help'] ?? null":disabled="$locked"/>+ @elseif ($fieldType === 'category')+ {{-- Per-record category selector. Empty means "fall back+ to the instance-wide default_category_id". Uses the+ same AJAX-backed select2 component as the shell's+ default category picker. --}}+ <x-input.category-select+ :name="$fieldName"+ :label="$field['label']"+ :selected="old($fieldName, $storedValue !== '' ? (int) $storedValue : null)"+ :categoryType="$field['categoryType'] ?? 'asset'"+ :help_text="$field['help'] ?? null"+ hideNewButton+ />@else<x-form.row:label="$field['label']"@@ -97,6 +110,7 @@:options="$field['options'] ?? []":selected="old($fieldName, $storedValue)":required="$isRequired"+ style="width: 100%"/>@elseif ($fieldType === 'multiselect')@phpdiff --git a/tests/Feature/SyncAdapters/AppleBusinessManager/AppleBusinessManagerAdapterTest.php b/tests/Feature/SyncAdapters/AppleBusinessManager/AppleBusinessManagerAdapterTest.phpindex d58445dd78..e4ff708237 100644--- a/tests/Feature/SyncAdapters/AppleBusinessManager/AppleBusinessManagerAdapterTest.php+++ b/tests/Feature/SyncAdapters/AppleBusinessManager/AppleBusinessManagerAdapterTest.php@@ -65,7 +65,7 @@ class AppleBusinessManagerAdapterTest extends TestCase$this->assertCount(1, $records);$record = $records[0];- $this->assertSame('apple_business_manager', $record->sourceKey);+ $this->assertSame('abm', $record->sourceKey);$this->assertSame('abm-guid-1', $record->sourceId);$this->assertSame('C02XL1234567', $record->hardwareSerial);// Default hardwareModel is partNumber (always populated per@@ -234,7 +234,7 @@ class AppleBusinessManagerAdapterTest extends TestCasepublic function test_validation_rules_accept_array_value_for_multiselect_product_family_filter(){$this->configuredAdapter();- $instance = SyncAdapterInstance::where('slug', 'apple_business_manager')->firstOrFail();+ $instance = SyncAdapterInstance::where('slug', 'abm')->firstOrFail();$adapter = new AppleBusinessManagerAdapter($instance->fresh());// The form posts the multiselect as `name[]`, so it arrives@@ -242,14 +242,14 @@ class AppleBusinessManagerAdapterTest extends TestCase// declare every credential field as 'string', which rejected// the array with "must be a string" on submit.$validator = \Illuminate\Support\Facades\Validator::make([- 'apple_business_manager_url' => 'https://api-business.apple.com/',- 'apple_business_manager_mode' => 'business',- 'apple_business_manager_client_id' => 'stub-client-id',- 'apple_business_manager_key_id' => 'stub-key-id',- 'apple_business_manager_private_key' => $this->privateKeyPem,- 'apple_business_manager_product_family_filter' => ['Mac', 'iPhone'],- 'apple_business_manager_default_category_id' => \App\Models\Category::factory()->assetLaptopCategory()->create()->id,- 'apple_business_manager_default_status_id' => Statuslabel::first()->id,+ 'abm_url' => 'https://api-business.apple.com/',+ 'abm_mode' => 'business',+ 'abm_client_id' => 'stub-client-id',+ 'abm_key_id' => 'stub-key-id',+ 'abm_private_key' => $this->privateKeyPem,+ 'abm_product_family_filter' => ['Mac', 'iPhone'],+ 'abm_default_category_id' => \App\Models\Category::factory()->assetLaptopCategory()->create()->id,+ 'abm_default_status_id' => Statuslabel::first()->id,], $adapter->validationRules());$this->assertFalse($validator->fails(), 'validationRules() must accept an array for multiselect fields: '.$validator->errors()->first());@@ -258,14 +258,14 @@ class AppleBusinessManagerAdapterTest extends TestCasepublic function test_saveconfig_clears_family_filter_when_nothing_selected(){$this->configuredAdapter(productFamilies: ['Mac', 'iPhone']);- $instance = SyncAdapterInstance::where('slug', 'apple_business_manager')->firstOrFail();+ $instance = SyncAdapterInstance::where('slug', 'abm')->firstOrFail();// Simulate re-saving the form with no families selected.// The multiselect handler in the base class overwrites the// stored JSON with an empty array.$adapter = new AppleBusinessManagerAdapter($instance->fresh());$adapter->saveConfig(\Illuminate\Http\Request::create('/', 'POST', [- 'apple_business_manager_url' => '',+ 'abm_url' => '',]));$stored = SyncAdapterConfig::get($instance->id, 'product_family_filter');@@ -298,7 +298,7 @@ class AppleBusinessManagerAdapterTest extends TestCase*/private function configuredAdapter(string $mode = 'business', ?array $productFamilies = null): AppleBusinessManagerAdapter{- $instance = SyncAdapterInstance::where('slug', 'apple_business_manager')->firstOrFail();+ $instance = SyncAdapterInstance::where('slug', 'abm')->firstOrFail();SyncAdapterConfig::put($instance->id, 'mode', $mode);SyncAdapterConfig::put($instance->id, 'client_id', 'stub-client-id');SyncAdapterConfig::put($instance->id, 'key_id', 'stub-key-id');diff --git a/tests/Feature/SyncAdapters/AppleBusinessManager/AppleCareEnrichmentTest.php b/tests/Feature/SyncAdapters/AppleBusinessManager/AppleCareEnrichmentTest.phpindex efd6494cf9..873bcf8316 100644--- a/tests/Feature/SyncAdapters/AppleBusinessManager/AppleCareEnrichmentTest.php+++ b/tests/Feature/SyncAdapters/AppleBusinessManager/AppleCareEnrichmentTest.php@@ -42,7 +42,7 @@ class AppleCareEnrichmentTest extends TestCase$customField = CustomField::factory()->create(['element' => 'text', 'name' => 'Warranty End']);$adapter = $this->configuredAdapter();- $instance = SyncAdapterInstance::where('slug', 'apple_business_manager')->firstOrFail();+ $instance = SyncAdapterInstance::where('slug', 'abm')->firstOrFail();SyncAdapterConfig::put($instance->id, 'mapping.abm_applecare_end_date', 'custom:'.$customField->id);Http::fake([@@ -107,7 +107,7 @@ class AppleCareEnrichmentTest extends TestCase$customField = CustomField::factory()->create(['element' => 'text', 'name' => 'Warranty']);$adapter = $this->configuredAdapter();- $instance = SyncAdapterInstance::where('slug', 'apple_business_manager')->firstOrFail();+ $instance = SyncAdapterInstance::where('slug', 'abm')->firstOrFail();SyncAdapterConfig::put($instance->id, 'mapping.abm_applecare_agreement_number', 'custom:'.$customField->id);Http::fake([@@ -145,7 +145,7 @@ class AppleCareEnrichmentTest extends TestCase$customField = CustomField::factory()->create(['element' => 'text', 'name' => 'Warranty']);$adapter = $this->configuredAdapter();- $instance = SyncAdapterInstance::where('slug', 'apple_business_manager')->firstOrFail();+ $instance = SyncAdapterInstance::where('slug', 'abm')->firstOrFail();SyncAdapterConfig::put($instance->id, 'mapping.abm_applecare_agreement_number', 'custom:'.$customField->id);Http::fake([@@ -181,7 +181,7 @@ class AppleCareEnrichmentTest extends TestCase$customField = CustomField::factory()->create(['element' => 'text', 'name' => 'Warranty']);$adapter = $this->configuredAdapter();- $instance = SyncAdapterInstance::where('slug', 'apple_business_manager')->firstOrFail();+ $instance = SyncAdapterInstance::where('slug', 'abm')->firstOrFail();SyncAdapterConfig::put($instance->id, 'mapping.abm_applecare_agreement_number', 'custom:'.$customField->id);Http::fake([@@ -217,7 +217,7 @@ class AppleCareEnrichmentTest extends TestCase$customField = CustomField::factory()->create(['element' => 'text', 'name' => 'Warranty']);$adapter = $this->configuredAdapter();- $instance = SyncAdapterInstance::where('slug', 'apple_business_manager')->firstOrFail();+ $instance = SyncAdapterInstance::where('slug', 'abm')->firstOrFail();SyncAdapterConfig::put($instance->id, 'mapping.abm_applecare_end_date', 'custom:'.$customField->id);Http::fake([@@ -241,7 +241,7 @@ class AppleCareEnrichmentTest extends TestCase$customField = CustomField::factory()->create(['element' => 'text', 'name' => 'Warranty']);$adapter = $this->configuredAdapter();- $instance = SyncAdapterInstance::where('slug', 'apple_business_manager')->firstOrFail();+ $instance = SyncAdapterInstance::where('slug', 'abm')->firstOrFail();SyncAdapterConfig::put($instance->id, 'mapping.abm_applecare_end_date', 'custom:'.$customField->id);Http::fake([@@ -259,7 +259,7 @@ class AppleCareEnrichmentTest extends TestCaseprivate function configuredAdapter(): AppleBusinessManagerAdapter{- $instance = SyncAdapterInstance::where('slug', 'apple_business_manager')->firstOrFail();+ $instance = SyncAdapterInstance::where('slug', 'abm')->firstOrFail();SyncAdapterConfig::put($instance->id, 'mode', 'business');SyncAdapterConfig::put($instance->id, 'client_id', 'stub-client-id');SyncAdapterConfig::put($instance->id, 'key_id', 'stub-key-id');diff --git a/tests/Feature/SyncAdapters/AppleBusinessManager/ModelImageEnrichmentTest.php b/tests/Feature/SyncAdapters/AppleBusinessManager/ModelImageEnrichmentTest.phpindex 0b5d9cfc43..f6f6e09426 100644--- a/tests/Feature/SyncAdapters/AppleBusinessManager/ModelImageEnrichmentTest.php+++ b/tests/Feature/SyncAdapters/AppleBusinessManager/ModelImageEnrichmentTest.php@@ -79,8 +79,14 @@ class ModelImageEnrichmentTest extends TestCase$this->assertSame('admin-uploaded.png', $model->image);}- public function test_pull_does_not_touch_model_when_category_already_has_image()+ public function test_pull_still_backfills_model_image_when_category_has_its_own_image(){+ // The category-image shortcut used to block per-model images+ // entirely when the category carried a fallback icon, which+ // meant admins with curated category icons never got Apple's+ // marketing shots on individual models. Now the category+ // image only serves as a fallback in AssetModel::getImageUrl;+ // per-model images still populate on top.$adapter = $this->configuredAdapter(pullImages: true);$category = Category::factory()->assetLaptopCategory()->create(['image' => 'category-image.png']);$model = AssetModel::factory()->create([@@ -96,7 +102,7 @@ class ModelImageEnrichmentTest extends TestCase}$model->refresh();- $this->assertNull($model->image);+ $this->assertNotNull($model->image);}public function test_pull_skips_appledb_calls_entirely_when_toggle_is_off()@@ -112,6 +118,49 @@ class ModelImageEnrichmentTest extends TestCaseHttp::assertNotSent(fn ($request) => str_contains($request->url(), 'appledb.dev'));}+ public function test_first_sync_stages_image_to_disk_even_when_model_row_does_not_exist_yet()+ {+ // Timing gap: ensureModelImage runs inside pull(), before+ // SyncHostFromAdapter has created the AssetModel row. First+ // sync must still hit appledb.dev and cache the PNG so the+ // second sync only needs to assign existing->image (no+ // re-download) once the framework creates the row.+ $adapter = $this->configuredAdapter(pullImages: true);+ $this->assertSame(0, AssetModel::query()->count());++ // Wildcard on the device endpoint sidesteps rawurlencode+ // turning the comma in "MacBookPro18,3" into "%2C" (which+ // the literal Http::fake pattern would miss). Http::fake+ // doesn't preventStrayRequests, so a missed pattern silently+ // falls through to the real internet, defeating hermeticity.+ 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' => [$this->deviceWithMarketingName()],+ ]),+ 'api.appledb.dev/device/*' => Http::response([+ 'imageKey' => 'macbook-pro-14-m4',+ 'colors' => [['key' => 'silver']],+ ]),+ 'img.appledb.dev/*' => Http::response(str_repeat("\x89PNG\r\n\x1a\n", 4)),+ ]);++ // Consume records without running SyncHostFromAdapter so no+ // AssetModel gets created. Simulates "framework hasn't built+ // the row yet" at the point ensureModelImage runs.+ iterator_to_array($adapter->pull());++ // File landed on disk keyed off (productType, colorKey).+ // AppleDBImageFetcher::filenameFor uses sha1(productType|colorKey)[0:16].+ $expectedFilename = 'abm-'.substr(hash('sha1', 'MacBookPro18,3|silver'), 0, 16).'.png';+ Storage::disk('public')->assertExists('models/'.$expectedFilename);++ // No model was created (pull() alone doesn't build rows), so+ // nothing to assert on the AssetModel side.+ $this->assertSame(0, AssetModel::query()->count());+ }+public function test_pull_survives_appledb_outage(){$adapter = $this->configuredAdapter(pullImages: true);@@ -220,7 +269,7 @@ class ModelImageEnrichmentTest extends TestCaseprivate function configuredAdapter(bool $pullImages): AppleBusinessManagerAdapter{- $instance = SyncAdapterInstance::where('slug', 'apple_business_manager')->firstOrFail();+ $instance = SyncAdapterInstance::where('slug', 'abm')->firstOrFail();SyncAdapterConfig::put($instance->id, 'mode', 'business');SyncAdapterConfig::put($instance->id, 'client_id', 'stub-client-id');SyncAdapterConfig::put($instance->id, 'key_id', 'stub-key-id');diff --git a/tests/Feature/SyncAdapters/AppleBusinessManager/PerFamilyCategoryRoutingTest.php b/tests/Feature/SyncAdapters/AppleBusinessManager/PerFamilyCategoryRoutingTest.phpnew file mode 100644index 0000000000..8dd8e7639a--- /dev/null+++ b/tests/Feature/SyncAdapters/AppleBusinessManager/PerFamilyCategoryRoutingTest.php@@ -0,0 +1,287 @@+<?php++namespace Tests\Feature\SyncAdapters\AppleBusinessManager;++use App\Models\AssetModel;+use App\Models\Category;+use App\Models\Statuslabel;+use App\Models\SyncAdapterConfig;+use App\Models\SyncAdapterInstance;+use App\SyncAdapters\AppleBusinessManager\AppleBusinessManagerAdapter;+use App\SyncAdapters\SyncHostFromAdapter;+use Illuminate\Support\Facades\Crypt;+use Illuminate\Support\Facades\Http;+use Tests\TestCase;++/**+ * Coverage for the ABM adapter's per-productFamily category routing.+ * ABM knows each device's family (Mac, iPhone, iPad, AppleTV, Watch,+ * Vision) so admins can drop each family into its own Snipe-IT+ * category instead of collapsing everything into the instance's+ * default_category_id. Unset families fall back to the default.+ */+class PerFamilyCategoryRoutingTest extends TestCase+{+ private string $privateKeyPem;++ protected function setUp(): void+ {+ parent::setUp();+ Statuslabel::factory()->rtd()->create();++ $key = openssl_pkey_new([+ 'private_key_type' => OPENSSL_KEYTYPE_EC,+ 'curve_name' => 'prime256v1',+ ]);+ $pem = '';+ openssl_pkey_export($key, $pem);+ $this->privateKeyPem = $pem;+ }++ public function test_ipad_routes_to_the_configured_ipad_category_instead_of_default()+ {+ $laptopCategory = Category::factory()->assetLaptopCategory()->create();+ $tabletCategory = Category::factory()->assetTabletCategory()->create();+ $adapter = $this->configuredAdapter([+ 'default_category_id' => $laptopCategory->id,+ 'category_id_ipad' => (string) $tabletCategory->id,+ ]);++ 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' => 'g-ipad', 'attributes' => ['serialNumber' => 'IPADSN', 'partNumber' => 'IPD1', 'productFamily' => 'iPad']],+ ],+ ]),+ ]);++ foreach ($adapter->pull() as $record) {+ SyncHostFromAdapter::run($record);+ }++ $model = AssetModel::where('name', 'IPD1')->firstOrFail();+ $this->assertSame($tabletCategory->id, $model->category_id);+ }++ public function test_macbook_pro_routes_to_mac_laptop_category()+ {+ $default = Category::factory()->assetDesktopCategory()->create();+ $laptop = Category::factory()->assetLaptopCategory()->create();+ $adapter = $this->configuredAdapter([+ 'default_category_id' => $default->id,+ 'category_id_mac_laptop' => (string) $laptop->id,+ ]);++ 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' => 'g-mbp', 'attributes' => [+ 'serialNumber' => 'MBPSN', 'partNumber' => 'MBP1',+ 'productFamily' => 'Mac',+ 'deviceModel' => 'MacBook Pro (14-inch, M4, 2024)',+ ]],+ ],+ ]),+ ]);++ foreach ($adapter->pull() as $record) {+ SyncHostFromAdapter::run($record);+ }++ $model = AssetModel::where('name', 'MBP1')->firstOrFail();+ $this->assertSame($laptop->id, $model->category_id);+ }++ public function test_mac_mini_routes_to_mac_desktop_category()+ {+ $default = Category::factory()->assetLaptopCategory()->create();+ $desktop = Category::factory()->assetDesktopCategory()->create();+ $adapter = $this->configuredAdapter([+ 'default_category_id' => $default->id,+ 'category_id_mac_desktop' => (string) $desktop->id,+ ]);++ 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' => 'g-mini', 'attributes' => [+ 'serialNumber' => 'MINISN', 'partNumber' => 'MINI1',+ 'productFamily' => 'Mac',+ 'deviceModel' => 'Mac mini (M2, 2023)',+ ]],+ ],+ ]),+ ]);++ foreach ($adapter->pull() as $record) {+ SyncHostFromAdapter::run($record);+ }++ $model = AssetModel::where('name', 'MINI1')->firstOrFail();+ $this->assertSame($desktop->id, $model->category_id);+ }++ public function test_mac_with_unparseable_marketing_name_falls_through_to_default()+ {+ // Guardrail against a future Apple naming change or a Mac+ // whose deviceModel comes back blank. The framework should+ // fall back to defaultCategoryId rather than lumping the+ // record into an arbitrary bucket.+ $default = Category::factory()->assetLaptopCategory()->create();+ $laptop = Category::factory()->assetLaptopCategory()->create();+ $desktop = Category::factory()->assetDesktopCategory()->create();+ $adapter = $this->configuredAdapter([+ 'default_category_id' => $default->id,+ 'category_id_mac_laptop' => (string) $laptop->id,+ 'category_id_mac_desktop' => (string) $desktop->id,+ ]);++ 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' => 'g-mystery', 'attributes' => [+ 'serialNumber' => 'MYSTSN', 'partNumber' => 'MYST1',+ 'productFamily' => 'Mac',+ 'deviceModel' => 'HoloDeck 9000',+ ]],+ ],+ ]),+ ]);++ foreach ($adapter->pull() as $record) {+ SyncHostFromAdapter::run($record);+ }++ $model = AssetModel::where('name', 'MYST1')->firstOrFail();+ $this->assertSame($default->id, $model->category_id);+ }++ public function test_existing_model_migrates_to_new_per_family_category_on_next_sync()+ {+ // Simulates: admin ran a sync with only default_category_id+ // set, so all iPads landed in "Laptops". Then admin+ // configures category_id_ipad = Tablets. Next sync must+ // migrate existing iPad models to the newly-mapped category+ // rather than leaving them stuck under the old default.+ $default = Category::factory()->assetLaptopCategory()->create();+ $tablets = Category::factory()->assetTabletCategory()->create();+ $existingModel = AssetModel::factory()->create([+ 'name' => 'IPD1',+ 'category_id' => $default->id,+ ]);+ $adapter = $this->configuredAdapter([+ 'default_category_id' => $default->id,+ 'category_id_ipad' => (string) $tablets->id,+ ]);++ 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' => 'g-ipad', 'attributes' => ['serialNumber' => 'IPADSN', 'partNumber' => 'IPD1', 'productFamily' => 'iPad']],+ ],+ ]),+ ]);++ foreach ($adapter->pull() as $record) {+ SyncHostFromAdapter::run($record);+ }++ $existingModel->refresh();+ $this->assertSame($tablets->id, $existingModel->category_id);+ }++ public function test_fall_through_to_default_does_not_overwrite_existing_model_category()+ {+ // Sync must NOT overwrite admin-curated category assignments+ // when the adapter has no per-record opinion. iPhone here+ // has no category_id_iphone override, so categoryIdForRecord+ // returns null and the framework falls through to+ // default_category_id -- but that fall-through is only for+ // fresh model creation, not for re-syncing existing rows.+ $default = Category::factory()->assetLaptopCategory()->create();+ $adminPicked = Category::factory()->assetMobileCategory()->create();+ $existingModel = AssetModel::factory()->create([+ 'name' => 'IPH1',+ 'category_id' => $adminPicked->id,+ ]);+ $adapter = $this->configuredAdapter([+ 'default_category_id' => $default->id,+ // No category_id_iphone -> adapter has no opinion.+ ]);++ 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' => 'g-iphone', 'attributes' => ['serialNumber' => 'IPHSN', 'partNumber' => 'IPH1', 'productFamily' => 'iPhone']],+ ],+ ]),+ ]);++ foreach ($adapter->pull() as $record) {+ SyncHostFromAdapter::run($record);+ }++ $existingModel->refresh();+ $this->assertSame($adminPicked->id, $existingModel->category_id);+ }++ public function test_deleted_configured_category_falls_back_to_default()+ {+ // Guardrail: if the admin picked a category that later got+ // deleted, the framework's category-exists check should force+ // fallback to defaultCategoryId rather than saving a dangling+ // foreign-key-shaped id on the AssetModel.+ $laptopCategory = Category::factory()->assetLaptopCategory()->create();+ $adapter = $this->configuredAdapter([+ 'default_category_id' => $laptopCategory->id,+ 'category_id_ipad' => '99999999',+ ]);++ 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' => 'g-ipad', 'attributes' => ['serialNumber' => 'IPADSN', 'partNumber' => 'IPD1', 'productFamily' => 'iPad']],+ ],+ ]),+ ]);++ foreach ($adapter->pull() as $record) {+ SyncHostFromAdapter::run($record);+ }++ $model = AssetModel::where('name', 'IPD1')->firstOrFail();+ $this->assertSame($laptopCategory->id, $model->category_id);+ }++ /**+ * @param array<string, string|int> $configOverrides+ */+ private function configuredAdapter(array $configOverrides): AppleBusinessManagerAdapter+ {+ $instance = SyncAdapterInstance::where('slug', 'abm')->firstOrFail();+ SyncAdapterConfig::put($instance->id, 'mode', 'business');+ SyncAdapterConfig::put($instance->id, 'client_id', 'stub-client-id');+ SyncAdapterConfig::put($instance->id, 'key_id', 'stub-key-id');+ SyncAdapterConfig::put($instance->id, 'private_key', Crypt::encrypt($this->privateKeyPem));++ foreach ($configOverrides as $key => $value) {+ SyncAdapterConfig::put($instance->id, $key, (string) $value);+ }++ return new AppleBusinessManagerAdapter($instance->fresh());+ }+}