A free open source IT asset/license management system
Handle model images in ABM
snipe89b973506584
diff --git a/app/SyncAdapters/AppleBusinessManager/AppleBusinessManagerAdapter.php b/app/SyncAdapters/AppleBusinessManager/AppleBusinessManagerAdapter.phpindex 6d2fbbd1ef..a9fedd284a 100644--- a/app/SyncAdapters/AppleBusinessManager/AppleBusinessManagerAdapter.php+++ b/app/SyncAdapters/AppleBusinessManager/AppleBusinessManagerAdapter.php@@ -2,11 +2,10 @@namespace App\SyncAdapters\AppleBusinessManager;-use App\Models\SyncAdapterConfig;+use App\Models\AssetModel;use App\SyncAdapters\HostInventoryRecord;use App\SyncAdapters\Support\ConfigurableAdapter;use Carbon\Carbon;-use Illuminate\Http\Request;use Illuminate\Support\Arr;/**@@ -54,6 +53,11 @@ class AppleBusinessManagerAdapter extends ConfigurableAdapter['key' => 'mode','label' => 'Portal',+ 'type' => 'select',+ 'options' => [+ 'business' => 'Apple Business Manager',+ 'school' => 'Apple School Manager',+ ],'help' => trans('admin/settings/sync_adapters.abm_mode_help'),],[@@ -69,15 +73,34 @@ class AppleBusinessManagerAdapter extends ConfigurableAdapter['key' => 'private_key','label' => 'Private Key (PEM)',+ 'type' => 'textarea','secret' => true,'help' => trans('admin/settings/sync_adapters.abm_private_key_help'),+ 'placeholder' => "-----BEGIN PRIVATE KEY-----\n1234567890\n-----END PRIVATE KEY-----",],['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'],'required' => false,'help' => trans('admin/settings/sync_adapters.abm_product_family_filter_help'),],+ [+ 'key' => 'pull_model_images',+ 'label' => 'Pull model images from appledb.dev',+ 'type' => 'checkbox',+ 'required' => false,+ 'help' => trans('admin/settings/sync_adapters.abm_pull_model_images_help'),+ ],];}@@ -105,25 +128,6 @@ class AppleBusinessManagerAdapter extends ConfigurableAdapter];}- /**- * Overrides the base saveConfig to give the product-family filter- * clear-on-blank semantics. Base persistCredentialsFromSchema()- * intentionally preserves blank values so admins can update the- * URL without re-entering every secret, but the filter is a- * different kind of setting: blanking it must switch back to- * "sync every family," not preserve the previous list.- */- public function saveConfig(Request $request): void- {- parent::saveConfig($request);-- SyncAdapterConfig::put(- $this->instance->id,- 'product_family_filter',- (string) $request->input($this->instance->slug.'_product_family_filter', ''),- );- }-public function pull(): iterable{$client = new AppleBusinessManagerClient(@@ -158,6 +162,13 @@ class AppleBusinessManagerAdapter extends ConfigurableAdapter// Empty means "all families".$allowedFamilies = $this->allowedProductFamilies();+ // Model-image enrichment fetches from appledb.dev, so it's+ // opt-in and off by default. Per-pull cache keyed by+ // hardwareModel avoids re-fetching the same image when a+ // tenant has many devices of the same model.+ $pullImages = $this->shouldPullModelImages();+ $imagesHandled = [];+foreach ($client->devices() as $device) {$family = strtolower((string) ($device['attributes']['productFamily'] ?? ''));if ($allowedFamilies !== [] && ! in_array($family, $allowedFamilies, true)) {@@ -167,17 +178,120 @@ class AppleBusinessManagerAdapter extends ConfigurableAdapterif ($enrichWithAppleCare) {$record = $this->enrichRecordWithAppleCare($record, $client);}+ if ($pullImages) {+ $imagesHandled = $this->ensureModelImage($record, $imagesHandled);+ }yield $record;}}/**- * Parse the admin-configured product-family filter (comma-- * separated list) into a lower-cased array. Empty / unset- * returns an empty array, which pull() reads as "allow every- * family." Unknown family names still flow through, since the vendor- * naming may evolve, and we'd rather let admins opt into a new- * family without waiting for a Snipe-IT release than block them.+ * When the "Pull model images" toggle is on, populate the+ * AssetModel image for the record's hardwareModel from+ * appledb.dev. Idempotent and safe to call for every record:+ *+ * - 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).+ * - 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.+ *+ * Cache is keyed by hardwareModel so the same model in a 500-+ * device pull triggers one fetch, not 500.+ *+ * @param array<string, bool> $imagesHandled modelName => true. Any key present means "already tried this model in this pull, skip".+ * @return array<string, bool> Updated cache with this record's modelName marked.+ */+ private function ensureModelImage(HostInventoryRecord $record, array $imagesHandled): array+ {+ // Whichever field the admin routed to native:model becomes+ // the AssetModel's name after sync. Mirror that pick here so+ // our image lookup targets the same model row the framework+ // will create or update.+ $modelName = $this->mappingFor('abm_model_marketing_name') === 'native:model'+ ? ($record->extra['abm_model_marketing_name'] ?? $record->hardwareModel)+ : $record->hardwareModel;++ if ($modelName === null || $modelName === '') {+ return $imagesHandled;+ }++ if (array_key_exists($modelName, $imagesHandled)) {+ return $imagesHandled;+ }+ $imagesHandled[$modelName] = true;++ $productType = $record->extra['abm_product_type'] ?? null;+ if (! is_string($productType) || $productType === '') {+ return $imagesHandled;+ }++ $existing = AssetModel::query()+ ->where('name', $modelName)+ ->with('category')+ ->first();++ if ($existing !== null && $this->existingModelAlreadyHasImageCoverage($existing)) {+ return $imagesHandled;+ }++ $color = $record->extra['abm_color'] ?? null;+ $filename = AppleDBImageFetcher::fetch($productType, is_string($color) ? $color : null);+ if ($filename === null) {+ return $imagesHandled;+ }++ if ($existing !== null) {+ $existing->image = $filename;+ $existing->save();+ }+ // 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;+ }++ /**+ * 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;++ return $category !== null && ! empty($category->image);+ }++ /**+ * Read the "Pull model images" checkbox. Persists as '1' or '0'+ * via the base class's schema handler, so a plain string compare+ * is enough here.+ */+ private function shouldPullModelImages(): bool+ {+ try {+ return $this->credential('pull_model_images') === '1';+ } catch (\Throwable) {+ return false;+ }+ }++ /**+ * Parse the admin-configured product-family multiselect into a+ * lower-cased array. Empty / unset returns an empty array, which+ * pull() reads as "allow every family." Persisted as JSON by+ * the base class's multiselect handler.** @return array<int, string>*/@@ -193,9 +307,12 @@ class AppleBusinessManagerAdapter extends ConfigurableAdapterreturn [];}- $parts = preg_split('/[,\s]+/', strtolower($raw)) ?: [];+ $decoded = json_decode($raw, true);+ if (! is_array($decoded)) {+ return [];+ }- return array_values(array_filter(array_map('trim', $parts), fn ($p) => $p !== ''));+ return array_values(array_map('strtolower', array_filter($decoded, 'is_string')));}/**diff --git a/app/SyncAdapters/AppleBusinessManager/AppleDBImageFetcher.php b/app/SyncAdapters/AppleBusinessManager/AppleDBImageFetcher.phpnew file mode 100644index 0000000000..4143a2b4ee--- /dev/null+++ b/app/SyncAdapters/AppleBusinessManager/AppleDBImageFetcher.php@@ -0,0 +1,195 @@+<?php++namespace App\SyncAdapters\AppleBusinessManager;++use Illuminate\Http\Client\ConnectionException;+use Illuminate\Http\Client\RequestException;+use Illuminate\Support\Facades\Http;+use Illuminate\Support\Facades\Log;+use Illuminate\Support\Facades\Storage;++/**+ * Fetches product images from appledb.dev, a community-maintained+ * catalog of Apple hardware keyed by hardware-identifier strings+ * ("Mac16,10", "iPhone16,2", etc). Used exclusively by+ * AppleBusinessManagerAdapter when the "Pull model images" toggle is+ * on and an incoming device carries a productType.+ *+ * Everything here fails soft: upstream unavailability, unknown+ * productType, malformed JSON, image download failure, disk write+ * failure all return null and log a warning. Sync never aborts on an+ * image miss because images are cosmetic. The asset record still+ * carries value without one.+ *+ * appledb.dev API + CDN endpoints:+ * - https://api.appledb.dev/device/{productType}.json+ * Returns { imageKey: string, colors: [{key: string}] }+ * - https://img.appledb.dev/device@main/{imageKey}/{colorKey}.png+ * Returns raw PNG bytes.+ *+ * Storage: images land under public/uploads/models/ via the public+ * disk (Snipe-IT aliases the public disk to local_public which+ * roots at public/uploads/, so this is the same location where+ * admin-uploaded model images already live and where+ * AssetModel::getImageUrl reads from). Filenames are keyed by a+ * hash of productType + colorKey so re-fetches deduplicate and+ * browser caching stays effective.+ */+class AppleDBImageFetcher+{+ private const INFO_HOST = 'https://api.appledb.dev';++ private const IMAGE_HOST = 'https://img.appledb.dev';++ private const REQUEST_TIMEOUT_SECONDS = 10;++ /**+ * Fetch the image for a given productType and return the filename+ * stored under the models upload path. Returns null on any+ * failure (network, unknown productType, disk write). Caller+ * assigns the returned filename to AssetModel::image before save.+ *+ * $colorHint lets ABM pass through the device's vendor-reported+ * Color attribute so we prefer the matching variant when+ * appledb.dev lists multiple colors. Nulls / non-matches fall+ * back to the catalog's first-listed color.+ */+ public static function fetch(string $productType, ?string $colorHint = null): ?string+ {+ if ($productType === '') {+ return null;+ }++ $device = self::fetchDeviceInfo($productType);+ if ($device === null) {+ return null;+ }++ $imageKey = $device['imageKey'] ?? null;+ $colors = $device['colors'] ?? [];+ if (! is_string($imageKey) || $imageKey === '' || ! is_array($colors) || $colors === []) {+ return null;+ }++ $colorKey = self::pickColorKey($colors, $colorHint);+ if ($colorKey === null) {+ return null;+ }++ return self::downloadAndStore($productType, $imageKey, $colorKey);+ }++ /**+ * @return array<string, mixed>|null+ */+ private static function fetchDeviceInfo(string $productType): ?array+ {+ try {+ $response = Http::timeout(self::REQUEST_TIMEOUT_SECONDS)+ ->acceptJson()+ ->get(self::INFO_HOST.'/device/'.rawurlencode($productType).'.json');+ } catch (ConnectionException|RequestException $e) {+ Log::channel('sync-adapters')->warning(sprintf(+ 'appledb.dev device-info fetch failed for %s: %s',+ $productType,+ $e->getMessage(),+ ));++ return null;+ }++ if (! $response->successful()) {+ return null;+ }++ $body = $response->json();++ return is_array($body) ? $body : null;+ }++ /**+ * Pick the colorKey that best matches the hinted color. Falls+ * back to the first-listed key when the hint is null / unknown.+ *+ * @param array<int, array<string, mixed>> $colors+ */+ private static function pickColorKey(array $colors, ?string $colorHint): ?string+ {+ if (is_string($colorHint) && $colorHint !== '') {+ $needle = strtolower($colorHint);+ foreach ($colors as $color) {+ $key = $color['key'] ?? null;+ if (is_string($key) && strtolower($key) === $needle) {+ return $key;+ }+ }+ }++ $first = $colors[0]['key'] ?? null;++ return is_string($first) && $first !== '' ? $first : null;+ }++ /**+ * Download the PNG bytes from the CDN and write them to the+ * public disk under models/. Returns the filename portion so the+ * caller can assign to AssetModel::image.+ */+ private static function downloadAndStore(string $productType, string $imageKey, string $colorKey): ?string+ {+ $filename = self::filenameFor($productType, $colorKey);+ $relativePath = app('models_upload_path').$filename;++ // Idempotent: if a prior pull already stored this image,+ // return the cached filename without re-downloading.+ if (Storage::disk('public')->exists($relativePath)) {+ return $filename;+ }++ try {+ $response = Http::timeout(self::REQUEST_TIMEOUT_SECONDS)+ ->get(sprintf('%s/device@main/%s/%s.png', self::IMAGE_HOST, rawurlencode($imageKey), rawurlencode($colorKey)));+ } catch (ConnectionException|RequestException $e) {+ Log::channel('sync-adapters')->warning(sprintf(+ 'appledb.dev image download failed for %s (%s): %s',+ $productType,+ $colorKey,+ $e->getMessage(),+ ));++ return null;+ }++ if (! $response->successful()) {+ return null;+ }++ $bytes = $response->body();+ if ($bytes === '') {+ return null;+ }++ $ok = Storage::disk('public')->put($relativePath, $bytes);+ if (! $ok) {+ Log::channel('sync-adapters')->warning(sprintf(+ 'appledb.dev image write failed for %s (%s): Storage::put returned false',+ $productType,+ $colorKey,+ ));++ return null;+ }++ return $filename;+ }++ /**+ * Stable filename per (productType, colorKey) pair. Hash keeps+ * the filename short and safe regardless of what characters live+ * in the vendor strings.+ */+ private static function filenameFor(string $productType, string $colorKey): string+ {+ return 'abm-'.substr(hash('sha1', $productType.'|'.$colorKey), 0, 16).'.png';+ }+}diff --git a/app/SyncAdapters/Intune/IntuneAdapter.php b/app/SyncAdapters/Intune/IntuneAdapter.phpindex 24b6a23bf1..56ec90c1c0 100644--- a/app/SyncAdapters/Intune/IntuneAdapter.php+++ b/app/SyncAdapters/Intune/IntuneAdapter.php@@ -103,7 +103,7 @@ class IntuneAdapter extends ConfigurableAdapter implements PushableAdapter/*** Convert a Graph managedDevice payload into the normalized record- * shape. Graph's stable id is `id` (a GUID); we key+ * shape. Graph's stable id is `id` (a GUID), and we key* asset_external_sources on it. Ethernet MAC is preferred over* WiFi because it's more likely to be a hardware-inventory MAC* that survives OS reinstall.diff --git a/app/SyncAdapters/NinjaOne/NinjaOneAdapter.php b/app/SyncAdapters/NinjaOne/NinjaOneAdapter.phpindex 81756709e8..853adc9ed9 100644--- a/app/SyncAdapters/NinjaOne/NinjaOneAdapter.php+++ b/app/SyncAdapters/NinjaOne/NinjaOneAdapter.php@@ -227,7 +227,7 @@ class NinjaOneAdapter extends ConfigurableAdapter implements PushableAdapter* multiple field name / value pairs in one request, so asset_tag* and the composed-notes target get merged when both are* configured. Admin sets the notes-target field via the composed-- * notes fieldset override; nothing is defaulted because Ninja+ * notes fieldset override. Nothing is defaulted because Ninja* has no built-in notes concept for us to guess.** @return array<string, mixed>diff --git a/app/SyncAdapters/Support/ConfigurableAdapter.php b/app/SyncAdapters/Support/ConfigurableAdapter.phpindex 2d14641748..9bed957525 100644--- a/app/SyncAdapters/Support/ConfigurableAdapter.php+++ b/app/SyncAdapters/Support/ConfigurableAdapter.php@@ -58,14 +58,26 @@ abstract class ConfigurableAdapter implements HostInventoryAdapter* Field entry keys:* - key (required) storage key AND form-field-name suffix* - label (required) display label rendered next to the input+ * - type (optional, default 'text') one of 'text', 'password',+ * 'textarea', 'checkbox', 'select'. 'password' also+ * implied when secret => true.+ * - options (optional) for type='select', a map of+ * value => display-label pairs.* - secret (optional, default false) render as password with* show/hide toggle AND encrypt the value at rest* - required (optional, default true) treat as required for the* isEnabled() gate. UI hint is up to the label copy* - help (optional, default null) inline help text under the* field, passed straight to `<x-form.row help_text=...>`+ * - placeholder (optional) placeholder text shown inside an+ * empty text / textarea input. Ignored for other+ * types.+ * - default (optional) initial-render fallback used when+ * nothing is stored yet. For type='multiselect' pass+ * an array of option keys to pre-select on first+ * render.*- * @return array<int, array{key: string, label: string, secret?: bool, required?: bool, help?: string|null}>+ * @return array<int, array{key: string, label: string, type?: string, options?: array<string, string>, secret?: bool, required?: bool, help?: string|null, placeholder?: string|null, default?: array<int, string>|string|null}>*/abstract public function credentialSchema(): array;@@ -239,6 +251,38 @@ abstract class ConfigurableAdapter implements HostInventoryAdapter{foreach ($this->credentialSchema() as $field) {$fieldName = $slug.'_'.$field['key'];+ $type = $field['type'] ?? 'text';++ // Checkbox fields always overwrite: an unchecked box is+ // a real value ("off") and needs to overwrite a+ // previously-saved "on". Text and password fields+ // preserve blank input so admins can update the URL+ // without re-entering every secret.+ if ($type === 'checkbox') {+ SyncAdapterConfig::put(+ $this->instance->id,+ $field['key'],+ $request->boolean($fieldName) ? '1' : '0',+ );++ continue;+ }++ // Multiselect also always overwrites. Empty selection+ // is a real value (means "sync all"). Store as JSON so+ // values with commas / special chars round-trip cleanly.+ if ($type === 'multiselect') {+ $values = (array) $request->input($fieldName, []);+ $values = array_values(array_filter($values, fn ($v) => $v !== null && $v !== ''));+ SyncAdapterConfig::put(+ $this->instance->id,+ $field['key'],+ json_encode($values),+ );++ continue;+ }+if (! $request->filled($fieldName)) {continue;}diff --git a/app/SyncAdapters/WorkspaceOne/WorkspaceOneAdapter.php b/app/SyncAdapters/WorkspaceOne/WorkspaceOneAdapter.phpindex c1a6d64a63..a319b229fc 100644--- a/app/SyncAdapters/WorkspaceOne/WorkspaceOneAdapter.php+++ b/app/SyncAdapters/WorkspaceOne/WorkspaceOneAdapter.php@@ -229,7 +229,7 @@ class WorkspaceOneAdapter extends ConfigurableAdapter implements PushableAdapter/*** Push top-level device fields (AssetNumber, etc.) via PUT- * /devices/{uuid}. Null $client means dry-run; log the payload+ * /devices/{uuid}. Null $client means dry-run: log the payload* and skip the HTTP call.** @param array<string, mixed> $payloaddiff --git a/config/logging.php b/config/logging.phpindex bab78d3bf7..e64e6fce49 100644--- a/config/logging.php+++ b/config/logging.php@@ -111,13 +111,7 @@ $config = ['path' => storage_path('logs/scim.log'),],- // Settings-admin audit trail. Wizard-style config screens (LDAP- // wizard test runs, etc.) write here instead of `action_logs`- // so operational messages that reference server URLs, base DNs,- // and other bind-shape info stay in files only the server- // operator can read. Separate file so log rotation stays sane- // and grepping doesn't have to filter out the noisier default- // laravel.log.+ // Settings-admin audit trail'admin' => ['driver' => 'daily','path' => storage_path('logs/admin.log'),@@ -125,12 +119,7 @@ $config = ['days' => 30,],- // Sync-adapter operational log. Every per-record failure,- // unmatched-user warning, and sync-run abort from the adapter- // pipeline lands here instead of the default laravel.log so- // admins can tail a focused stream when troubleshooting a- // Fleet / Kandji / Intune / etc. sync without wading through- // unrelated warnings. Same daily-rotation shape as `admin`.+ // Sync-adapter log'sync-adapters' => ['driver' => 'single','path' => storage_path('logs/sync-adapters.log'),diff --git a/resources/lang/en-US/admin/settings/sync_adapters.php b/resources/lang/en-US/admin/settings/sync_adapters.phpindex 1f2b29f242..28fb1d67d6 100644--- a/resources/lang/en-US/admin/settings/sync_adapters.php+++ b/resources/lang/en-US/admin/settings/sync_adapters.php@@ -170,11 +170,12 @@ return ['ninjaone_asset_tag_field_help' => 'Optional. NinjaOne has no built-in asset_tag column, so push writes to a per-device Custom Field instead. Create the field under Administration -> Devices -> Custom Fields in your Ninja dashboard, then paste its exact name here. Leave blank if you are not pushing asset_tag to Ninja.','kaseya_vsa10_token_id_help' => 'Generate an API token pair under Settings -> Extensions -> API Tokens in your VSA 10 admin console. Grant the token read access to the Devices resource. Copy the Token ID (the first half of the pair) here.','kaseya_vsa10_token_secret_help' => 'Paired with the Token ID above. VSA 10 shows the secret once at token creation time.',- 'abm_mode_help' => 'Enter "business" if your org uses Apple Business Manager, or "school" if your org uses Apple School Manager. Defaults to business when blank.',+ 'abm_mode_help' => 'The Apple portal your organization uses. Determines the API host and OAuth scope the adapter connects to.','abm_client_id_help' => 'Create an API key under Settings -> API in your Apple Business Manager or Apple School Manager console. Copy the Client ID from the key detail page.','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. Include the -----BEGIN PRIVATE KEY----- and -----END PRIVATE KEY----- lines. Apple only lets you download the key once.',- 'abm_product_family_filter_help' => 'Comma-separated list of product families to sync (Mac, iPhone, iPad, AppleTV, Watch, Vision). Leave blank to sync everything. Match is case-insensitive.',+ '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.',// Extras / mapping section wrappers'extra_fields_section_title' => ':type-specific fields',diff --git a/resources/views/blade/input/select.blade.php b/resources/views/blade/input/select.blade.phpindex c1c32ef1fc..1a3fb5c73d 100644--- a/resources/views/blade/input/select.blade.php+++ b/resources/views/blade/input/select.blade.php@@ -19,7 +19,7 @@{{-- map the simple key => value pairs when nothing is passed in via the slot --}}@if($slot->isEmpty())@foreach($options as $key => $value)- <option value="{{ $key }}" @selected($selected == $key)>{{ $value }}</option>+ <option value="{{ $key }}" @selected(is_array($selected) ? in_array($key, $selected) : $selected == $key)>{{ $value }}</option>@endforeach@else{{ $slot }}diff --git a/resources/views/settings/adapters/adapter_credentials.blade.php b/resources/views/settings/adapters/adapter_credentials.blade.phpindex 1ea3185618..6db0f3b85a 100644--- a/resources/views/settings/adapters/adapter_credentials.blade.php+++ b/resources/views/settings/adapters/adapter_credentials.blade.php@@ -63,40 +63,88 @@@foreach ($adapter->credentialSchema() as $field)@php$fieldName = $slug.'_'.$field['key'];+ $fieldType = $field['type'] ?? 'text';$isSecret = $field['secret'] ?? false;$isRequired = $field['required'] ?? true;$storedValue = $adapter->credentialForDisplay($field['key']);@endphp- <x-form.row- :label="$field['label']"- :name="$fieldName"- input_div_class="col-md-8"- :help_text="$field['help'] ?? null"- :required="$isRequired"- >- <x-slot:input>- @if ($locked)- <x-input.text- :name="$fieldName"- value="XXXXXXXXXXXXXXXXXXXXXXX"- disabled- />- @elseif ($isSecret)- <x-input.password- :name="$fieldName"- :value="old($fieldName, $storedValue)"- :required="$isRequired"- ignoreAutofill- />- @else- <x-input.text- :name="$fieldName"- :value="old($fieldName, $storedValue)"- :required="$isRequired"- />- @endif- </x-slot:input>- </x-form.row>+ @if ($fieldType === 'checkbox')+ <x-form.checkbox-row+ :name="$fieldName"+ :checked="old($fieldName, $storedValue === '1')"+ :label="$field['label']"+ :help_text="$field['help'] ?? null"+ :disabled="$locked"+ />+ @else+ <x-form.row+ :label="$field['label']"+ :name="$fieldName"+ input_div_class="col-md-8"+ :help_text="$field['help'] ?? null"+ :required="$isRequired"+ >+ <x-slot:input>+ @if ($locked)+ <x-input.text+ :name="$fieldName"+ value="XXXXXXXXXXXXXXXXXXXXXXX"+ disabled+ />+ @elseif ($fieldType === 'select')+ <x-input.select+ :name="$fieldName"+ :options="$field['options'] ?? []"+ :selected="old($fieldName, $storedValue)"+ :required="$isRequired"+ />+ @elseif ($fieldType === 'multiselect')+ @php+ $selectedValues = old(+ $fieldName,+ is_string($storedValue) && $storedValue !== '' ? (json_decode($storedValue, true) ?: []) : []+ );+ // First-render fallback: when nothing is+ // stored yet, adapters can declare a+ // `default` array to seed the selection so+ // admins see the intended baseline instead+ // of an empty widget.+ if (empty($selectedValues) && ! empty($field['default']) && is_array($field['default'])) {+ $selectedValues = $field['default'];+ }+ @endphp+ <x-input.select+ :name="$fieldName . '[]'"+ :options="$field['options'] ?? []"+ :selected="$selectedValues"+ multiple+ style="width: 100%"+ />+ @elseif ($fieldType === 'textarea')+ <x-input.textarea+ :name="$fieldName"+ :value="old($fieldName, $storedValue)"+ :required="$isRequired"+ :placeholder="$field['placeholder'] ?? null"+ rows="8"+ />+ @elseif ($isSecret)+ <x-input.password+ :name="$fieldName"+ :value="old($fieldName, $storedValue)"+ :required="$isRequired"+ ignoreAutofill+ />+ @else+ <x-input.text+ :name="$fieldName"+ :value="old($fieldName, $storedValue)"+ :required="$isRequired"+ />+ @endif+ </x-slot:input>+ </x-form.row>+ @endif@endforeach</x-sync-adapter-form>diff --git a/tests/Feature/SyncAdapters/AppleBusinessManager/AppleBusinessManagerAdapterTest.php b/tests/Feature/SyncAdapters/AppleBusinessManager/AppleBusinessManagerAdapterTest.phpindex 572d307288..972db94e39 100644--- a/tests/Feature/SyncAdapters/AppleBusinessManager/AppleBusinessManagerAdapterTest.php+++ b/tests/Feature/SyncAdapters/AppleBusinessManager/AppleBusinessManagerAdapterTest.php@@ -167,7 +167,7 @@ class AppleBusinessManagerAdapterTest extends TestCasepublic function test_product_family_filter_limits_pulled_devices(){- $adapter = $this->configuredAdapter(productFamilies: 'Mac, iPad');+ $adapter = $this->configuredAdapter(productFamilies: ['Mac', 'iPad']);Http::fake(['account.apple.com/*' => Http::response(['access_token' => 'stub-bearer']),@@ -190,7 +190,10 @@ class AppleBusinessManagerAdapterTest extends TestCasepublic function test_product_family_filter_is_case_insensitive(){- $adapter = $this->configuredAdapter(productFamilies: 'MAC');+ // Lower-case entry filters against ABM's "Mac" family. If+ // stored casing ever drifts from the canonical form, matching+ // still works.+ $adapter = $this->configuredAdapter(productFamilies: ['mac']);Http::fake(['account.apple.com/*' => Http::response(['access_token' => 'stub-bearer']),@@ -210,7 +213,7 @@ class AppleBusinessManagerAdapterTest extends TestCasepublic function test_blank_product_family_filter_passes_every_device_through(){- $adapter = $this->configuredAdapter(productFamilies: '');+ $adapter = $this->configuredAdapter(productFamilies: []);Http::fake(['account.apple.com/*' => Http::response(['access_token' => 'stub-bearer']),@@ -228,23 +231,21 @@ class AppleBusinessManagerAdapterTest extends TestCase$this->assertCount(3, $records);}- public function test_saveconfig_clears_family_filter_on_blank_submit()+ public function test_saveconfig_clears_family_filter_when_nothing_selected(){- $adapter = $this->configuredAdapter(productFamilies: 'Mac,iPhone');+ $this->configuredAdapter(productFamilies: ['Mac', 'iPhone']);+ $instance = SyncAdapterInstance::where('slug', 'apple_business_manager')->firstOrFail();- // Simulate an admin re-saving the form with an empty filter- // to switch back to "sync every family."- $request = \Illuminate\Http\Request::create('/', 'POST', [+ // 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' => '',- 'apple_business_manager_product_family_filter' => '',- ]);- $adapter->saveConfig($request);+ ]));- $stored = SyncAdapterConfig::get(- SyncAdapterInstance::where('slug', 'apple_business_manager')->firstOrFail()->id,- 'product_family_filter',- );- $this->assertSame('', $stored);+ $stored = SyncAdapterConfig::get($instance->id, 'product_family_filter');+ $this->assertSame('[]', $stored);}public function test_survives_mdm_server_map_failure_and_still_yields_records()@@ -268,7 +269,10 @@ class AppleBusinessManagerAdapterTest extends TestCase$this->assertNull($records[0]->extra['abm_mdm_server']);}- private function configuredAdapter(string $mode = 'business', ?string $productFamilies = null): AppleBusinessManagerAdapter+ /**+ * @param array<int, string>|null $productFamilies null = leave the stored filter alone; [] = force to empty+ */+ private function configuredAdapter(string $mode = 'business', ?array $productFamilies = null): AppleBusinessManagerAdapter{$instance = SyncAdapterInstance::where('slug', 'apple_business_manager')->firstOrFail();SyncAdapterConfig::put($instance->id, 'mode', $mode);@@ -276,7 +280,7 @@ class AppleBusinessManagerAdapterTest extends TestCaseSyncAdapterConfig::put($instance->id, 'key_id', 'stub-key-id');SyncAdapterConfig::put($instance->id, 'private_key', Crypt::encrypt($this->privateKeyPem));if ($productFamilies !== null) {- SyncAdapterConfig::put($instance->id, 'product_family_filter', $productFamilies);+ SyncAdapterConfig::put($instance->id, 'product_family_filter', json_encode($productFamilies));}return new AppleBusinessManagerAdapter($instance->fresh());diff --git a/tests/Feature/SyncAdapters/AppleBusinessManager/ModelImageEnrichmentTest.php b/tests/Feature/SyncAdapters/AppleBusinessManager/ModelImageEnrichmentTest.phpnew file mode 100644index 0000000000..0b5d9cfc43--- /dev/null+++ b/tests/Feature/SyncAdapters/AppleBusinessManager/ModelImageEnrichmentTest.php@@ -0,0 +1,236 @@+<?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 Illuminate\Support\Facades\Storage;+use Tests\TestCase;++/**+ * Coverage for the ABM model-image enrichment path. Fetches from+ * appledb.dev when the toggle is on, respects existing images on+ * model + category, and no-ops entirely when the toggle is off.+ */+class ModelImageEnrichmentTest 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;++ Storage::fake('public');+ }++ public function test_pull_backfills_model_image_when_toggle_is_on_and_model_lacks_one()+ {+ $adapter = $this->configuredAdapter(pullImages: true);+ // Pre-create the model so backfill has something to update.+ $category = Category::factory()->assetLaptopCategory()->create(['image' => null]);+ $model = AssetModel::factory()->create([+ 'name' => 'MacBook Pro (14-inch, M4, 2024)',+ 'image' => null,+ 'category_id' => $category->id,+ ]);++ $this->fakeAppleDbAndAbm();++ foreach ($adapter->pull() as $record) {+ SyncHostFromAdapter::run($record);+ }++ $model->refresh();+ $this->assertNotNull($model->image);+ Storage::disk('public')->assertExists('models/'.$model->image);+ }++ public function test_pull_does_not_touch_existing_model_image()+ {+ $adapter = $this->configuredAdapter(pullImages: true);+ $model = AssetModel::factory()->create([+ 'name' => 'MacBook Pro (14-inch, M4, 2024)',+ 'image' => 'admin-uploaded.png',+ ]);++ $this->fakeAppleDbAndAbm();++ foreach ($adapter->pull() as $record) {+ SyncHostFromAdapter::run($record);+ }++ $model->refresh();+ $this->assertSame('admin-uploaded.png', $model->image);+ }++ public function test_pull_does_not_touch_model_when_category_already_has_image()+ {+ $adapter = $this->configuredAdapter(pullImages: true);+ $category = Category::factory()->assetLaptopCategory()->create(['image' => 'category-image.png']);+ $model = AssetModel::factory()->create([+ 'name' => 'MacBook Pro (14-inch, M4, 2024)',+ 'image' => null,+ 'category_id' => $category->id,+ ]);++ $this->fakeAppleDbAndAbm();++ foreach ($adapter->pull() as $record) {+ SyncHostFromAdapter::run($record);+ }++ $model->refresh();+ $this->assertNull($model->image);+ }++ public function test_pull_skips_appledb_calls_entirely_when_toggle_is_off()+ {+ $adapter = $this->configuredAdapter(pullImages: false);++ $this->fakeAppleDbAndAbm();++ foreach ($adapter->pull() as $record) {+ SyncHostFromAdapter::run($record);+ }++ Http::assertNotSent(fn ($request) => str_contains($request->url(), 'appledb.dev'));+ }++ public function test_pull_survives_appledb_outage()+ {+ $adapter = $this->configuredAdapter(pullImages: true);+ $model = AssetModel::factory()->create([+ 'name' => 'MacBook Pro (14-inch, M4, 2024)',+ 'image' => null,+ ]);++ 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/*' => Http::response(['error' => 'boom'], 503),+ ]);++ foreach ($adapter->pull() as $record) {+ SyncHostFromAdapter::run($record);+ }++ $model->refresh();+ // No image populated, but sync completed without throwing.+ $this->assertNull($model->image);+ }++ public function test_pull_only_fetches_once_per_hardware_model_across_many_devices()+ {+ $adapter = $this->configuredAdapter(pullImages: true);+ AssetModel::factory()->create([+ 'name' => 'MacBook Pro (14-inch, M4, 2024)',+ 'image' => null,+ ]);++ 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' => array_map(+ fn (int $i) => $this->deviceWithMarketingName(id: 'guid-'.$i),+ range(1, 5),+ ),+ ]),+ 'api.appledb.dev/device/MacBookPro18,3.json' => Http::response([+ 'imageKey' => 'macbook-pro-14-m4',+ 'colors' => [['key' => 'silver']],+ ]),+ 'img.appledb.dev/*' => Http::response(str_repeat("\x89PNG\r\n\x1a\n", 4)),+ ]);++ foreach ($adapter->pull() as $record) {+ SyncHostFromAdapter::run($record);+ }++ // Even with 5 devices sharing the same hardwareModel, we hit+ // appledb.dev exactly once (info + image).+ $infoCount = 0;+ $imgCount = 0;+ Http::assertSent(function ($request) use (&$infoCount, &$imgCount) {+ if (str_contains($request->url(), 'api.appledb.dev')) {+ $infoCount++;+ }+ if (str_contains($request->url(), 'img.appledb.dev')) {+ $imgCount++;+ }++ return true;+ });+ $this->assertSame(1, $infoCount);+ $this->assertSame(1, $imgCount);+ }++ private function fakeAppleDbAndAbm(): void+ {+ 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/MacBookPro18,3.json' => Http::response([+ 'imageKey' => 'macbook-pro-14-m4',+ 'colors' => [['key' => 'silver'], ['key' => 'space-black']],+ ]),+ 'img.appledb.dev/*' => Http::response(str_repeat("\x89PNG\r\n\x1a\n", 4)),+ ]);+ }++ /**+ * @return array<string, mixed>+ */+ private function deviceWithMarketingName(string $id = 'abm-guid-1'): array+ {+ return [+ 'id' => $id,+ 'attributes' => [+ 'serialNumber' => 'C02SN-'.$id,+ 'partNumber' => 'MK1E3LL/A',+ 'productType' => 'MacBookPro18,3',+ 'deviceModel' => 'MacBook Pro (14-inch, M4, 2024)',+ 'productFamily' => 'Mac',+ 'color' => 'silver',+ ],+ ];+ }++ private function configuredAdapter(bool $pullImages): AppleBusinessManagerAdapter+ {+ $instance = SyncAdapterInstance::where('slug', 'apple_business_manager')->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));+ SyncAdapterConfig::put($instance->id, 'pull_model_images', $pullImages ? '1' : '');+ // Route the marketing name to native:model so the framework+ // uses it as the AssetModel::name (which the pre-created+ // model in each test is named after).+ SyncAdapterConfig::put($instance->id, 'mapping.abm_model_marketing_name', 'native:model');++ return new AppleBusinessManagerAdapter($instance->fresh());+ }+}