A free open source IT asset/license management system
Added tests
snipe44eed065518b
diff --git a/app/Services/AppleDb/AppleDbEnrichment.php b/app/Services/AppleDb/AppleDbEnrichment.phpnew file mode 100644index 0000000000..32a1102f6d--- /dev/null+++ b/app/Services/AppleDb/AppleDbEnrichment.php@@ -0,0 +1,335 @@+<?php++namespace App\Services\AppleDb;++use App\Enums\FileStorage;+use Carbon\CarbonImmutable;+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;++/**+ * Lookup service for appledb.dev, a community-maintained catalog of+ * Apple hardware keyed by hardware-identifier strings ("Mac16,10",+ * "iPhone16,2", etc). Returns an AppleDbRecord with any-or-all of+ * image, marketing name, release date, and manufacturer-declared+ * obsolete date populated.+ *+ * Called from sync adapters (ABM today, more to follow) and from the+ * Models screen's bulk-enrich action. Not sync-coupled: anywhere a+ * productType string is available, this service can turn it into an+ * AppleDbRecord.+ *+ * Everything fails soft: upstream unavailability, unknown productType,+ * malformed JSON, image download failure, disk write failure all+ * return null (or null fields) and log a warning. Callers never+ * abort on a miss, enrichment is cosmetic + supplementary.+ *+ * 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 AppleDbEnrichment+{+ private const INFO_HOST = 'https://api.appledb.dev';++ private const IMAGE_HOST = 'https://img.appledb.dev';++ private const REQUEST_TIMEOUT_SECONDS = 10;++ /**+ * Per-process cache of the raw AppleDB device info payload, keyed+ * by productType. Hit by both canonicalIdentity() (called from an+ * adapter's normalize to feed framework-level identity matching)+ * and lookup() (called later in pull() for image + date backfill),+ * so a 500-device pull sharing a handful of model identifiers makes+ * one HTTP info call per identifier rather than one per device per+ * phase.+ *+ * Null-valued entries are cached too: an identifier that returned+ * no catalog entry on first ask stays null for the rest of the+ * process, so a bad productType does not retry the network every+ * time it is encountered.+ *+ * @var array<string, array<string, mixed>|null>+ */+ private static array $deviceInfoCache = [];++ /**+ * Resolve a productType into an AppleDbRecord. Returns null when+ * the catalog has no entry for the identifier (or the fetch+ * fails outright). A non-null record may still have null fields:+ * the catalog may know the image but not the obsolete date, or+ * vice versa.+ *+ * $colorHint lets callers pass the vendor-reported device color+ * 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 lookup(string $productType, ?string $colorHint = null): ?AppleDbRecord+ {+ if ($productType === '') {+ return null;+ }++ $device = self::fetchDeviceInfoCached($productType);+ if ($device === null) {+ return null;+ }++ $imageFilename = self::resolveImageFilename($productType, $device, $colorHint);+ $marketingName = isset($device['name']) && is_string($device['name']) && $device['name'] !== ''+ ? $device['name']+ : null;++ return new AppleDbRecord(+ imageFilename: $imageFilename,+ marketingName: $marketingName,+ modelNumber: self::firstModelNumber($device['model'] ?? null),+ releaseDate: self::parseDate($device['released'] ?? null),+ discontinuedDate: self::parseDate($device['discontinued'] ?? null),+ );+ }++ /**+ * Lightweight lookup for the two values the sync framework needs+ * at model find-or-create time: the AppleDB canonical marketing+ * name and the Apple regulatory number. No image handling, no+ * date parsing. Called from each Apple-capable adapter's+ * normalize() so the record can carry identity hints into+ * resolveModelIdByName.+ *+ * Returns null when the productType has no catalog entry (which+ * also caches the miss, so a bad identifier does not retry the+ * network on every device that shares it).+ */+ public static function canonicalIdentity(string $productType): ?AppleDbRecord+ {+ if ($productType === '') {+ return null;+ }++ $device = self::fetchDeviceInfoCached($productType);+ if ($device === null) {+ return null;+ }++ $marketingName = isset($device['name']) && is_string($device['name']) && $device['name'] !== ''+ ? $device['name']+ : null;++ return new AppleDbRecord(+ marketingName: $marketingName,+ modelNumber: self::firstModelNumber($device['model'] ?? null),+ );+ }++ /**+ * AppleDB stores the Apple regulatory numbers as an array (one+ * entry per region variant, e.g. ['A2442'] or ['A2779', 'A2780',+ * 'A2881', 'A2882']). We take the first entry and let admins+ * override from the UI when a multi-region install needs a+ * specific variant.+ */+ private static function firstModelNumber(mixed $models): ?string+ {+ if (! is_array($models) || $models === []) {+ return null;+ }++ $first = $models[0] ?? null;++ return is_string($first) && $first !== '' ? $first : null;+ }++ private static function parseDate(mixed $value): ?CarbonImmutable+ {+ if (! is_string($value) || $value === '') {+ return null;+ }++ try {+ return CarbonImmutable::parse($value);+ } catch (\Exception $e) {+ return null;+ }+ }++ /**+ * Stable filename per (productType, colorKey) pair. Hash keeps+ * the filename short and safe regardless of what characters live+ * in the vendor strings. Exposed so tests + callers that already+ * know the color can predict the filename without re-deriving+ * the hash scheme.+ */+ public static function filenameFor(string $productType, string $colorKey): string+ {+ return 'appledb-'.substr(hash('sha1', $productType.'|'.$colorKey), 0, 16).'.png';+ }++ /**+ * @param array<string, mixed> $device+ */+ private static function resolveImageFilename(string $productType, array $device, ?string $colorHint): ?string+ {+ $imageKey = $device['imageKey'] ?? null;+ $colors = $device['colors'] ?? [];+ if (! is_string($imageKey) || $imageKey === '' || ! is_array($colors) || $colors === []) {+ Log::channel('sync-adapters')->info("appledb.dev entry for productType {$productType} is missing imageKey or colors, skipping image");++ return null;+ }++ $colorKey = self::pickColorKey($colors, $colorHint);+ if ($colorKey === null) {+ Log::channel('sync-adapters')->info("appledb.dev entry for productType {$productType} has no usable colorKey, skipping image");++ return null;+ }++ return self::downloadAndStore($productType, $imageKey, $colorKey);+ }++ /**+ * Reset the per-process device info cache. Tests reach for this+ * when they want adjacent Http::fake runs to start from scratch+ * (otherwise the first run's device info persists into the next+ * run's static state and later fakes get ignored).+ */+ public static function clearCache(): void+ {+ self::$deviceInfoCache = [];+ }++ /**+ * @return array<string, mixed>|null+ */+ private static function fetchDeviceInfoCached(string $productType): ?array+ {+ if (array_key_exists($productType, self::$deviceInfoCache)) {+ return self::$deviceInfoCache[$productType];+ }++ $device = self::fetchDeviceInfo($productType);+ self::$deviceInfoCache[$productType] = $device;++ return $device;+ }++ /**+ * @return array<string, mixed>|null+ */+ private static function fetchDeviceInfo(string $productType): ?array+ {+ try {+ $response = Http::withOptions(['allow_redirects' => false])+ ->timeout(self::REQUEST_TIMEOUT_SECONDS)+ ->acceptJson()+ ->get(self::INFO_HOST.'/device/'.rawurlencode($productType).'.json');+ } catch (ConnectionException|RequestException $e) {+ Log::channel('sync-adapters')->warning("appledb.dev device-info fetch failed for {$productType}: {$e->getMessage()}");++ return null;+ }++ if (! $response->successful()) {+ $status = $response->status();+ Log::channel('sync-adapters')->info("appledb.dev has no catalog entry for productType {$productType} (status {$status}), skipping image");++ 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 = FileStorage::Models->publicPath().$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 {+ $url = self::IMAGE_HOST.'/device@main/'.rawurlencode($imageKey).'/'.rawurlencode($colorKey).'.png';+ $response = Http::withOptions(['allow_redirects' => false])+ ->timeout(self::REQUEST_TIMEOUT_SECONDS)+ ->get($url);+ } catch (ConnectionException|RequestException $e) {+ Log::channel('sync-adapters')->warning("appledb.dev image download failed for {$productType} ({$colorKey}): {$e->getMessage()}");++ return null;+ }++ if (! $response->successful()) {+ $status = $response->status();+ Log::channel('sync-adapters')->info("appledb.dev image CDN returned {$status} for {$productType} ({$colorKey}), skipping image");++ return null;+ }++ $bytes = $response->body();+ if ($bytes === '') {+ Log::channel('sync-adapters')->info("appledb.dev image CDN returned empty body for {$productType} ({$colorKey}), skipping image");++ return null;+ }++ $ok = Storage::disk('public')->put($relativePath, $bytes);+ if (! $ok) {+ Log::channel('sync-adapters')->warning("appledb.dev image write failed for {$productType} ({$colorKey}): Storage::put returned false");++ return null;+ }++ Log::channel('sync-adapters')->info("appledb.dev image saved for productType {$productType} (color={$colorKey}, file={$filename})");++ return $filename;+ }+}diff --git a/app/Services/AppleDb/AppleDbRecord.php b/app/Services/AppleDb/AppleDbRecord.phpnew file mode 100644index 0000000000..af2bc73582--- /dev/null+++ b/app/Services/AppleDb/AppleDbRecord.php@@ -0,0 +1,28 @@+<?php++namespace App\Services\AppleDb;++use Carbon\CarbonInterface;++/**+ * Enrichment payload returned by AppleDbEnrichment::lookup(). Every+ * field is nullable because the upstream catalog may know some+ * attributes about a given productType and not others (new releases+ * are typically imageless for a few weeks, obsolescence dates are+ * only populated once Apple formally classifies a model as vintage+ * or obsolete, etc).+ *+ * imageFilename is the filename portion of a PNG already saved under+ * the public disk at models/, keyed by (productType, colorKey). The+ * caller assigns this to AssetModel::image.+ */+readonly class AppleDbRecord+{+ public function __construct(+ public ?string $imageFilename = null,+ public ?string $marketingName = null,+ public ?string $modelNumber = null,+ public ?CarbonInterface $releaseDate = null,+ public ?CarbonInterface $discontinuedDate = null,+ ) {}+}diff --git a/tests/Feature/SyncAdapters/Addigy/AddigyAppleDbEnrichmentTest.php b/tests/Feature/SyncAdapters/Addigy/AddigyAppleDbEnrichmentTest.phpnew file mode 100644index 0000000000..ffa657b9d1--- /dev/null+++ b/tests/Feature/SyncAdapters/Addigy/AddigyAppleDbEnrichmentTest.php@@ -0,0 +1,148 @@+<?php++namespace Tests\Feature\SyncAdapters\Addigy;++use App\Models\AssetModel;+use App\Models\Statuslabel;+use App\Models\SyncAdapterConfig;+use App\Models\SyncAdapterInstance;+use App\Services\AppleDb\AppleDbEnrichment;+use App\SyncAdapters\Addigy\AddigyAdapter;+use App\SyncAdapters\SyncAdapter;+use Illuminate\Support\Facades\Crypt;+use Illuminate\Support\Facades\Http;+use Illuminate\Support\Facades\Storage;+use Tests\TestCase;++/**+ * Coverage for Addigy's AppleDB enrichment path. Addigy's v2 API is+ * fact-request shaped: the client lists the fact identifiers it+ * wants on every POST /devices call, and the response is a facts+ * map. The AppleDB-shape identifier lives in the `product_name`+ * fact per Addigy's device-facts catalog.+ */+class AddigyAppleDbEnrichmentTest extends TestCase+{+ protected function setUp(): void+ {+ parent::setUp();+ Statuslabel::factory()->rtd()->create();+ Storage::fake('public');+ AppleDbEnrichment::clearCache();+ }++ public function test_pull_backfills_model_fields_from_appledb_using_product_name_fact()+ {+ $adapter = $this->configuredAdapter(enrichmentEnabled: true);+ $model = AssetModel::factory()->create([+ 'name' => 'MacBook Pro',+ 'image' => null,+ 'model_number' => null,+ 'mfg_marketing_name' => null,+ 'mfg_release_date' => null,+ 'mfg_discontinued_date' => null,+ ]);++ $this->fakeAddigyAndAppleDb();++ foreach ($adapter->pull() as $record) {+ SyncAdapter::syncFromRecord($record);+ }++ $model->refresh();+ $this->assertSame('MacBook Pro (14-inch, M4, 2024)', $model->mfg_marketing_name);+ $this->assertSame('A3123', $model->model_number);+ $this->assertSame('2024-11-08', $model->mfg_release_date?->toDateString());+ }++ public function test_pull_skips_appledb_entirely_when_toggle_is_off()+ {+ $adapter = $this->configuredAdapter(enrichmentEnabled: false);+ $this->fakeAddigyAndAppleDb();++ foreach ($adapter->pull() as $record) {+ SyncAdapter::syncFromRecord($record);+ }++ Http::assertNotSent(fn ($request) => str_contains($request->url(), 'appledb.dev'));+ }++ public function test_new_mappable_fact_values_land_on_record_extras()+ {+ $adapter = $this->configuredAdapter(enrichmentEnabled: false);+ $this->fakeAddigyAndAppleDb();++ $records = iterator_to_array($adapter->pull());++ $this->assertSame('24A5309e', $records[0]->extra['addigy_build_version']);+ $this->assertSame('UDID-ADDIGY-1', $records[0]->extra['addigy_udid']);+ $this->assertTrue($records[0]->extra['addigy_has_mdm']);+ $this->assertTrue($records[0]->extra['addigy_filevault_enabled']);+ $this->assertFalse($records[0]->extra['addigy_firewall_enabled']);+ $this->assertSame('16', $records[0]->extra['addigy_total_memory_gb']);+ $this->assertSame('500', $records[0]->extra['addigy_disk_total_space_gb']);+ $this->assertSame('250', $records[0]->extra['addigy_disk_free_space_gb']);+ $this->assertSame('2029-01-15', $records[0]->extra['addigy_warranty_expiration_date']);+ }++ public function test_appledb_extras_carry_values_when_toggle_is_on()+ {+ $adapter = $this->configuredAdapter(enrichmentEnabled: true);+ $this->fakeAddigyAndAppleDb();++ $records = iterator_to_array($adapter->pull());++ $this->assertSame('MacBook Pro (14-inch, M4, 2024)', $records[0]->extra['appledb_marketing_name']);+ $this->assertSame('A3123', $records[0]->extra['appledb_model_number']);+ $this->assertSame('MacBookPro18,3', $records[0]->extra['addigy_product_name']);+ }++ private function fakeAddigyAndAppleDb(): void+ {+ Http::fake([+ '*api.addigy.com/api/v2/devices*' => Http::response([+ 'items' => [+ [+ 'agentid' => 'addigy-1',+ 'orgid' => 'org-test',+ 'audit_date' => '2026-01-15T10:00:00Z',+ 'facts' => [+ 'device_name' => ['type' => 'string', 'value' => 'mac-01'],+ 'device_model_name' => ['type' => 'string', 'value' => 'MacBook Pro'],+ 'product_name' => ['type' => 'string', 'value' => 'MacBookPro18,3'],+ 'serial_number' => ['type' => 'string', 'value' => 'ADG-1'],+ 'build_version' => ['type' => 'string', 'value' => '24A5309e'],+ 'udid' => ['type' => 'string', 'value' => 'UDID-ADDIGY-1'],+ 'has_mdm' => ['type' => 'bool', 'value' => true],+ 'filevault_enabled' => ['type' => 'bool', 'value' => true],+ 'firewall_enabled' => ['type' => 'bool', 'value' => false],+ 'total_memory_gb' => ['type' => 'string', 'value' => '16'],+ 'disk_total_space_gb' => ['type' => 'string', 'value' => '500'],+ 'disk_free_space_gb' => ['type' => 'string', 'value' => '250'],+ 'warranty_expiration_date' => ['type' => 'string', 'value' => '2029-01-15'],+ ],+ ],+ ],+ 'metadata' => ['total' => 1],+ ]),+ 'api.appledb.dev/device/*' => Http::response([+ 'name' => 'MacBook Pro (14-inch, M4, 2024)',+ 'released' => '2024-11-08',+ 'discontinued' => '2026-03-05',+ 'model' => ['A3123'],+ 'imageKey' => 'macbook-pro-14-m4',+ 'colors' => [['key' => 'silver']],+ ]),+ 'img.appledb.dev/*' => Http::response(str_repeat("\x89PNG\r\n\x1a\n", 4)),+ ]);+ }++ private function configuredAdapter(bool $enrichmentEnabled): AddigyAdapter+ {+ $instance = SyncAdapterInstance::where('slug', 'addigy')->firstOrFail();+ SyncAdapterConfig::put($instance->id, 'api_key', Crypt::encrypt('fake-addigy-api-key'));+ SyncAdapterConfig::put($instance->id, 'use_appledb_enrichment', $enrichmentEnabled ? '1' : '');++ return new AddigyAdapter($instance->fresh());+ }+}diff --git a/tests/Feature/SyncAdapters/AppleBusinessManager/ModelImageEnrichmentTest.php b/tests/Feature/SyncAdapters/AppleBusinessManager/ModelImageEnrichmentTest.phpindex 4e1a61f123..a80c00b7df 100644--- a/tests/Feature/SyncAdapters/AppleBusinessManager/ModelImageEnrichmentTest.php+++ b/tests/Feature/SyncAdapters/AppleBusinessManager/ModelImageEnrichmentTest.php@@ -28,6 +28,7 @@ class ModelImageEnrichmentTest extends TestCase{parent::setUp();Statuslabel::factory()->rtd()->create();+ AppleDbEnrichment::clearCache();$key = openssl_pkey_new(['private_key_type' => OPENSSL_KEYTYPE_EC,@@ -66,6 +67,10 @@ class ModelImageEnrichmentTest extends TestCasepublic function test_pull_does_not_touch_existing_model_image(){$adapter = $this->configuredAdapter(pullImages: true);+ // Represent a real admin-uploaded image: the file lives on+ // the public disk, so the enrichment flow's "replace stale"+ // check leaves it alone.+ Storage::disk('public')->put('models/admin-uploaded.png', 'png-bytes');$model = AssetModel::factory()->create(['name' => 'MacBook Pro (14-inch, M4, 2024)','image' => 'admin-uploaded.png',@@ -234,12 +239,13 @@ class ModelImageEnrichmentTest extends TestCase$this->assertSame(1, $imgCount);}- public function test_pull_backfills_marketing_name_release_date_and_discontinued_date()+ public function test_pull_backfills_marketing_name_release_date_discontinued_date_and_model_number(){$adapter = $this->configuredAdapter(pullImages: true);$model = AssetModel::factory()->create(['name' => 'MacBook Pro (14-inch, M4, 2024)','image' => null,+ 'model_number' => null,'mfg_marketing_name' => null,'mfg_release_date' => null,'mfg_discontinued_date' => null,@@ -253,6 +259,7 @@ class ModelImageEnrichmentTest extends TestCase$model->refresh();$this->assertSame('MacBook Pro (14-inch, M4, 2024)', $model->mfg_marketing_name);+ $this->assertSame('A3123', $model->model_number);$this->assertSame('2024-11-08', $model->mfg_release_date?->toDateString());$this->assertSame('2026-03-05', $model->mfg_discontinued_date?->toDateString());}@@ -284,10 +291,13 @@ class ModelImageEnrichmentTest extends TestCasepublic function test_pull_skips_appledb_entirely_when_image_and_all_mfg_fields_are_set(){+ // Fully-populated row short-circuits the whole appledb.dev path. The row's own stamped mfg_marketing_name + model_number already serve any future cross-adapter OR match, so no network call is worth making.$adapter = $this->configuredAdapter(pullImages: true);+ Storage::disk('public')->put('models/admin-uploaded.png', 'png-bytes');AssetModel::factory()->create(['name' => 'MacBook Pro (14-inch, M4, 2024)','image' => 'admin-uploaded.png',+ 'model_number' => 'A1234','mfg_marketing_name' => 'Admin name','mfg_release_date' => '2020-01-01','mfg_discontinued_date' => '2022-02-02',@@ -302,6 +312,27 @@ class ModelImageEnrichmentTest extends TestCaseHttp::assertNotSent(fn ($request) => str_contains($request->url(), 'appledb.dev'));}+ public function test_pull_replaces_image_reference_when_the_referenced_file_is_missing_from_the_public_disk()+ {+ $adapter = $this->configuredAdapter(pullImages: true);+ $model = AssetModel::factory()->create([+ 'name' => 'MacBook Pro (14-inch, M4, 2024)',+ // Stale reference, left behind by a prior filesystem driver or an older release. The file is NOT on the public disk.+ 'image' => 'orphaned-ref.png',+ ]);++ $this->fakeAppleDbAndAbm();++ foreach ($adapter->pull() as $record) {+ SyncAdapter::syncFromRecord($record);+ }++ $model->refresh();+ $this->assertNotSame('orphaned-ref.png', $model->image);+ $this->assertNotNull($model->image);+ Storage::disk('public')->assertExists('models/'.$model->image);+ }+public function test_pull_partially_backfills_only_the_empty_mfg_fields(){$adapter = $this->configuredAdapter(pullImages: true);@@ -339,6 +370,7 @@ class ModelImageEnrichmentTest extends TestCase'name' => 'MacBook Pro (14-inch, M4, 2024)','released' => '2024-11-08','discontinued' => '2026-03-05',+ 'model' => ['A3123'],'imageKey' => 'macbook-pro-14-m4','colors' => [['key' => 'silver'], ['key' => 'space-black']],]),diff --git a/tests/Feature/SyncAdapters/CrossAdapterIdentityTest.php b/tests/Feature/SyncAdapters/CrossAdapterIdentityTest.phpnew file mode 100644index 0000000000..62c55923a6--- /dev/null+++ b/tests/Feature/SyncAdapters/CrossAdapterIdentityTest.php@@ -0,0 +1,172 @@+<?php++namespace Tests\Feature\SyncAdapters;++use App\Models\AssetModel;+use App\Models\Statuslabel;+use App\Models\SyncAdapterConfig;+use App\Models\SyncAdapterInstance;+use App\Services\AppleDb\AppleDbEnrichment;+use App\SyncAdapters\Fleet\FleetAdapter;+use App\SyncAdapters\SyncAdapter;+use Illuminate\Support\Facades\Crypt;+use Illuminate\Support\Facades\Http;+use Illuminate\Support\Facades\Storage;+use Tests\TestCase;++/**+ * Cross-adapter identity dedup. ABM reports Apple's long marketing+ * name (e.g. "MacBook Pro (14-inch, M4, 2024)"), Fleet reports the+ * shorter osquery-emitted name ("MacBook Pro") for the same physical+ * hardware. Without the shared canonical identity, each adapter+ * would create its own AssetModel row and admins would be left with+ * duplicates to merge manually.+ *+ * The resolver uses the record's canonicalMarketingName + canonical+ * ModelNumber (populated by AppleDB enrichment during normalize())+ * to pick up the existing row even when the adapter's own+ * $modelName string differs from what's stored.+ */+class CrossAdapterIdentityTest extends TestCase+{+ protected function setUp(): void+ {+ parent::setUp();+ Statuslabel::factory()->rtd()->create();+ Storage::fake('public');+ AppleDbEnrichment::clearCache();+ }++ public function test_fleet_sync_reuses_an_existing_model_created_under_abms_longer_marketing_name()+ {+ // Pre-state: ABM already synced this hardware, leaving an+ // AssetModel with the long marketing name as its name,+ // mfg_marketing_name stamped with the AppleDB canonical, and+ // model_number stamped with Apple's regulatory number. The+ // canonical values are what Fleet's enrichment will converge+ // on when it looks the same productType up.+ $existing = AssetModel::factory()->create([+ 'name' => 'MacBook Pro (14-inch, M4, 2024)',+ 'mfg_marketing_name' => 'MacBook Pro (14-inch, M4, 2024)',+ 'model_number' => 'A3123',+ ]);++ $adapter = $this->configuredFleetAdapter(enrichmentEnabled: true);++ Http::fake([+ '*/api/latest/fleet/hosts*' => Http::response(['hosts' => [+ [+ 'id' => 1,+ 'hostname' => 'mac-01',+ 'hardware_model' => 'MacBookPro18,3',+ 'hardware_marketing_name' => 'MacBook Pro',+ 'hardware_vendor' => 'Apple Inc.',+ 'hardware_serial' => 'C02MAC01',+ 'platform' => 'darwin',+ 'uuid' => 'fleet-mac-01',+ ],+ ]]),+ 'api.appledb.dev/device/*' => Http::response([+ 'name' => 'MacBook Pro (14-inch, M4, 2024)',+ 'released' => '2024-11-08',+ 'discontinued' => '2026-03-05',+ 'model' => ['A3123'],+ '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) {+ SyncAdapter::syncFromRecord($record);+ }++ $this->assertSame(1, AssetModel::query()->count());+ $assetModel = AssetModel::query()->first();+ $this->assertSame($existing->id, $assetModel->id);+ // Fleet did not rename the row to its own shorter marketing name.+ $this->assertSame('MacBook Pro (14-inch, M4, 2024)', $assetModel->name);+ }++ public function test_first_fleet_sync_stamps_canonical_values_on_new_model_row()+ {+ $adapter = $this->configuredFleetAdapter(enrichmentEnabled: true);++ Http::fake([+ '*/api/latest/fleet/hosts*' => Http::response(['hosts' => [+ [+ 'id' => 1,+ 'hostname' => 'mac-01',+ 'hardware_model' => 'MacBookPro18,3',+ 'hardware_marketing_name' => 'MacBook Pro',+ 'hardware_vendor' => 'Apple Inc.',+ 'hardware_serial' => 'C02MAC01',+ 'platform' => 'darwin',+ 'uuid' => 'fleet-mac-01',+ ],+ ]]),+ 'api.appledb.dev/device/*' => Http::response([+ 'name' => 'MacBook Pro (14-inch, M4, 2024)',+ 'released' => '2024-11-08',+ 'discontinued' => '2026-03-05',+ 'model' => ['A3123'],+ '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) {+ SyncAdapter::syncFromRecord($record);+ }++ $this->assertSame(1, AssetModel::query()->count());+ $model = AssetModel::query()->first();+ // Fleet's own marketing name is used as the AssetModel name per the adapter's mapping. Canonical values are stamped alongside so a later ABM sync finds this row via the OR match.+ $this->assertSame('MacBook Pro', $model->name);+ $this->assertSame('MacBook Pro (14-inch, M4, 2024)', $model->mfg_marketing_name);+ $this->assertSame('A3123', $model->model_number);+ }++ public function test_resolver_falls_back_to_name_match_when_canonical_values_are_absent()+ {+ // Non-Apple hosts never carry canonical values (adapter's isAppleHost gate skips the lookup). Framework must still find existing models by exact name match as it has always done.+ $existing = AssetModel::factory()->create([+ 'name' => 'ThinkPad X1 Carbon',+ ]);++ $adapter = $this->configuredFleetAdapter(enrichmentEnabled: true);++ Http::fake([+ '*/api/latest/fleet/hosts*' => Http::response(['hosts' => [+ [+ 'id' => 2,+ 'hostname' => 'linux-01',+ 'hardware_model' => 'ThinkPad X1 Carbon',+ 'hardware_vendor' => 'Lenovo',+ 'hardware_serial' => 'LNV1',+ 'platform' => 'linux',+ 'uuid' => 'fleet-linux-01',+ ],+ ]]),+ ]);++ foreach ($adapter->pull() as $record) {+ SyncAdapter::syncFromRecord($record);+ }++ $this->assertSame(1, AssetModel::query()->count());+ $this->assertSame($existing->id, AssetModel::query()->first()->id);+ }++ private function configuredFleetAdapter(bool $enrichmentEnabled): FleetAdapter+ {+ $instance = SyncAdapterInstance::where('slug', 'fleet')->firstOrFail();+ SyncAdapterConfig::put($instance->id, 'url', 'https://fleet.example.test');+ SyncAdapterConfig::put($instance->id, 'token', Crypt::encrypt('fake-token'));+ SyncAdapterConfig::put($instance->id, 'use_appledb_enrichment', $enrichmentEnabled ? '1' : '');+ SyncAdapterConfig::put($instance->id, 'mapping.fleet_model_marketing_name', 'native:model');++ return new FleetAdapter($instance->fresh());+ }+}diff --git a/tests/Feature/SyncAdapters/Fleet/FleetAppleDbEnrichmentTest.php b/tests/Feature/SyncAdapters/Fleet/FleetAppleDbEnrichmentTest.phpnew file mode 100644index 0000000000..3ebebf0b9f--- /dev/null+++ b/tests/Feature/SyncAdapters/Fleet/FleetAppleDbEnrichmentTest.php@@ -0,0 +1,247 @@+<?php++namespace Tests\Feature\SyncAdapters\Fleet;++use App\Models\AssetModel;+use App\Models\Statuslabel;+use App\Models\SyncAdapterConfig;+use App\Models\SyncAdapterInstance;+use App\Services\AppleDb\AppleDbEnrichment;+use App\SyncAdapters\Fleet\FleetAdapter;+use App\SyncAdapters\SyncAdapter;+use Illuminate\Support\Facades\Crypt;+use Illuminate\Support\Facades\Http;+use Illuminate\Support\Facades\Storage;+use Tests\TestCase;++class FleetAppleDbEnrichmentTest extends TestCase+{+ protected function setUp(): void+ {+ parent::setUp();+ Statuslabel::factory()->rtd()->create();+ Storage::fake('public');+ AppleDbEnrichment::clearCache();+ }++ public function test_pull_backfills_apple_model_fields_from_appledb()+ {+ $adapter = $this->configuredAdapter(enrichmentEnabled: true);+ $model = AssetModel::factory()->create([+ 'name' => 'MacBook Pro (14-inch, M4, 2024)',+ 'image' => null,+ 'model_number' => null,+ 'mfg_marketing_name' => null,+ 'mfg_release_date' => null,+ 'mfg_discontinued_date' => null,+ ]);++ $this->fakeFleetAndAppleDb([$this->appleHost(id: 1)]);++ foreach ($adapter->pull() as $record) {+ SyncAdapter::syncFromRecord($record);+ }++ $model->refresh();+ $this->assertSame('MacBook Pro (14-inch, M4, 2024)', $model->mfg_marketing_name);+ $this->assertSame('A3123', $model->model_number);+ $this->assertSame('2024-11-08', $model->mfg_release_date?->toDateString());+ $this->assertSame('2026-03-05', $model->mfg_discontinued_date?->toDateString());+ $this->assertNotNull($model->image);+ Storage::disk('public')->assertExists('models/'.$model->image);+ }++ public function test_pull_skips_appledb_calls_entirely_when_toggle_is_off()+ {+ $adapter = $this->configuredAdapter(enrichmentEnabled: false);++ $this->fakeFleetAndAppleDb([$this->appleHost(id: 1)]);++ foreach ($adapter->pull() as $record) {+ SyncAdapter::syncFromRecord($record);+ }++ Http::assertNotSent(fn ($request) => str_contains($request->url(), 'appledb.dev'));+ }++ public function test_pull_skips_appledb_for_non_apple_hosts_even_when_toggle_is_on()+ {+ $adapter = $this->configuredAdapter(enrichmentEnabled: true);++ $this->fakeFleetAndAppleDb([+ $this->linuxHost(id: 1),+ $this->windowsHost(id: 2),+ ]);++ foreach ($adapter->pull() as $record) {+ SyncAdapter::syncFromRecord($record);+ }++ Http::assertNotSent(fn ($request) => str_contains($request->url(), 'appledb.dev'));+ }++ public function test_record_extras_carry_appledb_values_for_custom_field_mapping()+ {+ // AppleDB values flow through HostInventoryRecord::$extra so admins can map any of them to a custom field on the asset (e.g. "Original Release Date" column admins can sort by in asset reports).+ $adapter = $this->configuredAdapter(enrichmentEnabled: true);++ $this->fakeFleetAndAppleDb([$this->appleHost(id: 1)]);++ $records = iterator_to_array($adapter->pull());++ $this->assertCount(1, $records);+ $this->assertSame('MacBook Pro (14-inch, M4, 2024)', $records[0]->extra['appledb_marketing_name']);+ $this->assertSame('A3123', $records[0]->extra['appledb_model_number']);+ $this->assertSame('2024-11-08', $records[0]->extra['appledb_release_date']);+ $this->assertSame('2026-03-05', $records[0]->extra['appledb_discontinued_date']);+ }++ public function test_record_extras_appledb_values_null_when_toggle_is_off()+ {+ $adapter = $this->configuredAdapter(enrichmentEnabled: false);++ $this->fakeFleetAndAppleDb([$this->appleHost(id: 1)]);++ $records = iterator_to_array($adapter->pull());++ $this->assertNull($records[0]->extra['appledb_marketing_name']);+ $this->assertNull($records[0]->extra['appledb_model_number']);+ $this->assertNull($records[0]->extra['appledb_release_date']);+ $this->assertNull($records[0]->extra['appledb_discontinued_date']);+ }++ public function test_extra_fields_declaration_hides_appledb_keys_when_toggle_is_off()+ {+ $enabled = $this->configuredAdapter(enrichmentEnabled: true);+ $this->assertArrayHasKey('appledb_marketing_name', $enabled->extraFields());+ $this->assertArrayHasKey('appledb_release_date', $enabled->extraFields());+ $this->assertArrayHasKey('appledb_discontinued_date', $enabled->extraFields());++ $disabled = $this->configuredAdapter(enrichmentEnabled: false);+ $this->assertArrayNotHasKey('appledb_marketing_name', $disabled->extraFields());+ $this->assertArrayNotHasKey('appledb_release_date', $disabled->extraFields());+ $this->assertArrayNotHasKey('appledb_discontinued_date', $disabled->extraFields());+ }++ public function test_record_extras_appledb_values_null_for_non_apple_hosts()+ {+ $adapter = $this->configuredAdapter(enrichmentEnabled: true);++ $this->fakeFleetAndAppleDb([$this->linuxHost(id: 1)]);++ $records = iterator_to_array($adapter->pull());++ $this->assertNull($records[0]->extra['appledb_marketing_name']);+ $this->assertNull($records[0]->extra['appledb_model_number']);+ $this->assertNull($records[0]->extra['appledb_release_date']);+ $this->assertNull($records[0]->extra['appledb_discontinued_date']);+ }++ public function test_pull_only_hits_appledb_once_per_apple_hardware_model()+ {+ $adapter = $this->configuredAdapter(enrichmentEnabled: true);+ AssetModel::factory()->create([+ 'name' => 'MacBook Pro (14-inch, M4, 2024)',+ 'image' => null,+ ]);++ $this->fakeFleetAndAppleDb(array_map(+ fn (int $i) => $this->appleHost(id: $i),+ range(1, 5),+ ));++ foreach ($adapter->pull() as $record) {+ SyncAdapter::syncFromRecord($record);+ }++ $infoCount = 0;+ Http::assertSent(function ($request) use (&$infoCount) {+ if (str_contains($request->url(), 'api.appledb.dev')) {+ $infoCount++;+ }++ return true;+ });+ $this->assertSame(1, $infoCount);+ }++ /**+ * @param array<int, array<string, mixed>> $hosts+ */+ private function fakeFleetAndAppleDb(array $hosts): void+ {+ Http::fake([+ '*/api/latest/fleet/hosts*' => Http::response(['hosts' => $hosts]),+ 'api.appledb.dev/device/*' => Http::response([+ 'name' => 'MacBook Pro (14-inch, M4, 2024)',+ 'released' => '2024-11-08',+ 'discontinued' => '2026-03-05',+ 'model' => ['A3123'],+ 'imageKey' => 'macbook-pro-14-m4',+ 'colors' => [['key' => 'silver']],+ ]),+ 'img.appledb.dev/*' => Http::response(str_repeat("\x89PNG\r\n\x1a\n", 4)),+ ]);+ }++ /**+ * @return array<string, mixed>+ */+ private function appleHost(int $id): array+ {+ return [+ 'id' => $id,+ 'hostname' => 'mac-'.$id,+ 'hardware_model' => 'MacBookPro18,3',+ 'hardware_marketing_name' => 'MacBook Pro (14-inch, M4, 2024)',+ 'hardware_vendor' => 'Apple Inc.',+ 'hardware_serial' => 'C02MAC'.$id,+ 'platform' => 'darwin',+ 'uuid' => 'fleet-mac-'.$id,+ ];+ }++ /**+ * @return array<string, mixed>+ */+ private function linuxHost(int $id): array+ {+ return [+ 'id' => $id,+ 'hostname' => 'linux-'.$id,+ 'hardware_model' => 'ThinkPad X1 Carbon',+ 'hardware_vendor' => 'Lenovo',+ 'hardware_serial' => 'LN'.$id,+ 'platform' => 'linux',+ 'uuid' => 'fleet-linux-'.$id,+ ];+ }++ /**+ * @return array<string, mixed>+ */+ private function windowsHost(int $id): array+ {+ return [+ 'id' => $id,+ 'hostname' => 'win-'.$id,+ 'hardware_model' => 'Surface Laptop 5',+ 'hardware_vendor' => 'Microsoft Corporation',+ 'hardware_serial' => 'MS'.$id,+ 'platform' => 'windows',+ 'uuid' => 'fleet-win-'.$id,+ ];+ }++ private function configuredAdapter(bool $enrichmentEnabled): FleetAdapter+ {+ $instance = SyncAdapterInstance::where('slug', 'fleet')->firstOrFail();+ SyncAdapterConfig::put($instance->id, 'url', 'https://fleet.example.test');+ SyncAdapterConfig::put($instance->id, 'token', Crypt::encrypt('fake-token'));+ SyncAdapterConfig::put($instance->id, 'use_appledb_enrichment', $enrichmentEnabled ? '1' : '');+ // Route the Fleet marketing name to native:model so the AssetModel's name mirrors how the enrichment flow resolves it.+ SyncAdapterConfig::put($instance->id, 'mapping.fleet_model_marketing_name', 'native:model');++ return new FleetAdapter($instance->fresh());+ }+}diff --git a/tests/Feature/SyncAdapters/Jamf/JamfAppleDbEnrichmentTest.php b/tests/Feature/SyncAdapters/Jamf/JamfAppleDbEnrichmentTest.phpnew file mode 100644index 0000000000..cf291b6cfe--- /dev/null+++ b/tests/Feature/SyncAdapters/Jamf/JamfAppleDbEnrichmentTest.php@@ -0,0 +1,169 @@+<?php++namespace Tests\Feature\SyncAdapters\Jamf;++use App\Models\AssetModel;+use App\Models\Statuslabel;+use App\Models\SyncAdapterConfig;+use App\Models\SyncAdapterInstance;+use App\Services\AppleDb\AppleDbEnrichment;+use App\SyncAdapters\Jamf\JamfAdapter;+use App\SyncAdapters\SyncAdapter;+use Illuminate\Support\Facades\Crypt;+use Illuminate\Support\Facades\Http;+use Illuminate\Support\Facades\Storage;+use Tests\TestCase;++class JamfAppleDbEnrichmentTest extends TestCase+{+ protected function setUp(): void+ {+ parent::setUp();+ Statuslabel::factory()->rtd()->create();+ Storage::fake('public');+ AppleDbEnrichment::clearCache();+ }++ public function test_pull_backfills_computer_model_fields_from_appledb()+ {+ $adapter = $this->configuredAdapter(enrichmentEnabled: true);+ $model = AssetModel::factory()->create([+ 'name' => 'MacBook Pro',+ 'image' => null,+ 'model_number' => null,+ 'mfg_marketing_name' => null,+ 'mfg_release_date' => null,+ 'mfg_discontinued_date' => null,+ ]);++ $this->fakeJamfAndAppleDb(computers: [[+ 'id' => '42',+ 'udid' => 'jamf-udid-42',+ 'general' => ['name' => 'host', 'lastContactTime' => null, 'lastEnrolledDate' => null],+ 'hardware' => [+ 'make' => 'Apple',+ 'model' => 'MacBook Pro',+ 'modelIdentifier' => 'MacBookPro18,3',+ 'serialNumber' => 'C02-42',+ ],+ 'operatingSystem' => ['name' => 'macOS', 'version' => '15.0'],+ ]]);++ foreach ($adapter->pull() as $record) {+ SyncAdapter::syncFromRecord($record);+ }++ $model->refresh();+ $this->assertSame('MacBook Pro (14-inch, M4, 2024)', $model->mfg_marketing_name);+ $this->assertSame('A3123', $model->model_number);+ $this->assertSame('2024-11-08', $model->mfg_release_date?->toDateString());+ $this->assertSame('2026-03-05', $model->mfg_discontinued_date?->toDateString());+ $this->assertNotNull($model->image);+ }++ public function test_pull_skips_appledb_calls_entirely_when_toggle_is_off()+ {+ $adapter = $this->configuredAdapter(enrichmentEnabled: false);++ $this->fakeJamfAndAppleDb(computers: [[+ 'id' => '42',+ 'udid' => 'jamf-udid-42',+ 'general' => ['name' => 'host', 'lastContactTime' => null, 'lastEnrolledDate' => null],+ 'hardware' => [+ 'make' => 'Apple',+ 'model' => 'MacBook Pro',+ 'modelIdentifier' => 'MacBookPro18,3',+ 'serialNumber' => 'C02-42',+ ],+ 'operatingSystem' => ['name' => 'macOS', 'version' => '15.0'],+ ]]);++ foreach ($adapter->pull() as $record) {+ SyncAdapter::syncFromRecord($record);+ }++ Http::assertNotSent(fn ($request) => str_contains($request->url(), 'appledb.dev'));+ }++ public function test_mobile_devices_also_resolve_canonical_identity()+ {+ $adapter = $this->configuredAdapter(enrichmentEnabled: true, includeMobile: true);++ $this->fakeJamfAndAppleDb(+ computers: [],+ mobile: [[+ 'id' => '7',+ 'name' => 'ipad-7',+ 'udid' => 'jamf-mobile-udid-7',+ 'serialNumber' => 'IPAD-7',+ 'assetTag' => null,+ 'model' => 'iPad',+ 'modelIdentifier' => 'iPad13,2',+ 'deviceType' => 'ios',+ 'osType' => 'iPadOS',+ 'osVersion' => '18.0',+ 'wifiMacAddress' => null,+ 'ipAddress' => null,+ 'lastInventoryUpdateTimestamp' => null,+ 'managed' => true,+ 'supervised' => false,+ 'location' => ['username' => null, 'emailAddress' => null],+ 'site' => null,+ ]],+ );++ foreach ($adapter->pull() as $record) {+ SyncAdapter::syncFromRecord($record);+ }++ $model = AssetModel::query()->where('name', 'iPad')->first();+ $this->assertNotNull($model);+ $this->assertSame('MacBook Pro (14-inch, M4, 2024)', $model->mfg_marketing_name);+ $this->assertSame('A3123', $model->model_number);+ }++ /**+ * @param array<int, array<string, mixed>> $computers+ * @param array<int, array<string, mixed>> $mobile+ */+ private function fakeJamfAndAppleDb(array $computers, array $mobile = []): void+ {+ Http::fake([+ 'example.jamfcloud.com/api/oauth/token' => Http::response([+ 'access_token' => 'fake-token',+ 'token_type' => 'Bearer',+ 'expires_in' => 3600,+ ]),+ 'example.jamfcloud.com/api/v1/computers-inventory*' => Http::response([+ 'totalCount' => count($computers),+ 'results' => $computers,+ ]),+ 'example.jamfcloud.com/api/v2/mobile-devices*' => Http::response([+ 'totalCount' => count($mobile),+ 'results' => $mobile,+ ]),+ 'example.jamfcloud.com/api/v1/sites' => Http::response([]),+ 'api.appledb.dev/device/*' => Http::response([+ 'name' => 'MacBook Pro (14-inch, M4, 2024)',+ 'released' => '2024-11-08',+ 'discontinued' => '2026-03-05',+ 'model' => ['A3123'],+ 'imageKey' => 'macbook-pro-14-m4',+ 'colors' => [['key' => 'silver']],+ ]),+ 'img.appledb.dev/*' => Http::response(str_repeat("\x89PNG\r\n\x1a\n", 4)),+ ]);+ }++ private function configuredAdapter(bool $enrichmentEnabled, bool $includeMobile = false): JamfAdapter+ {+ $instance = SyncAdapterInstance::where('slug', 'jamf')->firstOrFail();+ SyncAdapterConfig::put($instance->id, 'url', 'https://example.jamfcloud.com');+ SyncAdapterConfig::put($instance->id, 'client_id', Crypt::encrypt('fake-jamf-client-id'));+ SyncAdapterConfig::put($instance->id, 'client_secret', Crypt::encrypt('fake-jamf-client-secret'));+ SyncAdapterConfig::put($instance->id, 'include_mobile_devices', $includeMobile ? '1' : '0');+ SyncAdapterConfig::put($instance->id, 'use_appledb_enrichment', $enrichmentEnabled ? '1' : '');++ return new JamfAdapter($instance->fresh());+ }+}diff --git a/tests/Feature/SyncAdapters/JamfSchool/JamfSchoolAppleDbEnrichmentTest.php b/tests/Feature/SyncAdapters/JamfSchool/JamfSchoolAppleDbEnrichmentTest.phpnew file mode 100644index 0000000000..0eeb085d91--- /dev/null+++ b/tests/Feature/SyncAdapters/JamfSchool/JamfSchoolAppleDbEnrichmentTest.php@@ -0,0 +1,127 @@+<?php++namespace Tests\Feature\SyncAdapters\JamfSchool;++use App\Models\AssetModel;+use App\Models\Statuslabel;+use App\Models\SyncAdapterConfig;+use App\Models\SyncAdapterInstance;+use App\Services\AppleDb\AppleDbEnrichment;+use App\SyncAdapters\JamfSchool\JamfSchoolAdapter;+use App\SyncAdapters\SyncAdapter;+use Illuminate\Support\Facades\Crypt;+use Illuminate\Support\Facades\Http;+use Illuminate\Support\Facades\Storage;+use Tests\TestCase;++class JamfSchoolAppleDbEnrichmentTest extends TestCase+{+ protected function setUp(): void+ {+ parent::setUp();+ Statuslabel::factory()->rtd()->create();+ Storage::fake('public');+ AppleDbEnrichment::clearCache();+ }++ public function test_pull_backfills_model_fields_from_appledb()+ {+ $adapter = $this->configuredAdapter(enrichmentEnabled: true);+ $model = AssetModel::factory()->create([+ 'name' => 'iPad',+ 'image' => null,+ 'model_number' => null,+ 'mfg_marketing_name' => null,+ 'mfg_release_date' => null,+ 'mfg_discontinued_date' => null,+ ]);++ $this->fakeJamfSchoolAndAppleDb();++ foreach ($adapter->pull() as $record) {+ SyncAdapter::syncFromRecord($record);+ }++ $model->refresh();+ $this->assertSame('iPad Pro (11-inch, 4th generation)', $model->mfg_marketing_name);+ $this->assertSame('A2759', $model->model_number);+ $this->assertSame('2022-10-26', $model->mfg_release_date?->toDateString());+ $this->assertNotNull($model->image);+ }++ public function test_pull_skips_appledb_entirely_when_toggle_is_off()+ {+ $adapter = $this->configuredAdapter(enrichmentEnabled: false);+ $this->fakeJamfSchoolAndAppleDb();++ foreach ($adapter->pull() as $record) {+ SyncAdapter::syncFromRecord($record);+ }++ Http::assertNotSent(fn ($request) => str_contains($request->url(), 'appledb.dev'));+ }++ public function test_record_extras_carry_appledb_values_when_toggle_is_on()+ {+ $adapter = $this->configuredAdapter(enrichmentEnabled: true);+ $this->fakeJamfSchoolAndAppleDb();++ $records = iterator_to_array($adapter->pull());++ $this->assertSame('iPad Pro (11-inch, 4th generation)', $records[0]->extra['appledb_marketing_name']);+ $this->assertSame('A2759', $records[0]->extra['appledb_model_number']);+ $this->assertSame('2022-10-26', $records[0]->extra['appledb_release_date']);+ }++ public function test_extra_fields_declaration_hides_appledb_keys_when_toggle_is_off()+ {+ $disabled = $this->configuredAdapter(enrichmentEnabled: false);+ $this->assertArrayNotHasKey('appledb_marketing_name', $disabled->extraFields());++ $enabled = $this->configuredAdapter(enrichmentEnabled: true);+ $this->assertArrayHasKey('appledb_marketing_name', $enabled->extraFields());+ }++ private function fakeJamfSchoolAndAppleDb(): void+ {+ Http::fake([+ '*/devices*' => Http::response([+ 'count' => 1,+ 'devices' => [[+ 'UDID' => 'edu-udid-7',+ 'name' => 'ipad-lab',+ 'serialNumber' => 'JS-7',+ 'model' => [+ 'name' => 'iPad',+ 'identifier' => 'iPad14,3',+ ],+ 'os' => ['prefix' => 'iPadOS', 'version' => '17.0'],+ 'networkInformation' => ['WiFiMAC' => null, 'IPAddress' => null],+ 'lastCheckin' => null,+ 'isSupervised' => true,+ 'assetTag' => null,+ 'locationId' => 1,+ ]],+ ]),+ 'api.appledb.dev/device/*' => Http::response([+ 'name' => 'iPad Pro (11-inch, 4th generation)',+ 'released' => '2022-10-26',+ 'model' => ['A2759'],+ 'imageKey' => 'ipad-pro-11-m2',+ 'colors' => [['key' => 'silver']],+ ]),+ 'img.appledb.dev/*' => Http::response(str_repeat("\x89PNG\r\n\x1a\n", 4)),+ ]);+ }++ private function configuredAdapter(bool $enrichmentEnabled): JamfSchoolAdapter+ {+ $instance = SyncAdapterInstance::where('slug', 'jamf_school')->firstOrFail();+ SyncAdapterConfig::put($instance->id, 'url', 'https://example.jamfcloud.com/api');+ SyncAdapterConfig::put($instance->id, 'network_id', 'school-network-id');+ SyncAdapterConfig::put($instance->id, 'api_key', Crypt::encrypt('fake-jamf-school-key'));+ SyncAdapterConfig::put($instance->id, 'use_appledb_enrichment', $enrichmentEnabled ? '1' : '');++ return new JamfSchoolAdapter($instance->fresh());+ }+}diff --git a/tests/Feature/SyncAdapters/Kandji/KandjiAppleDbEnrichmentTest.php b/tests/Feature/SyncAdapters/Kandji/KandjiAppleDbEnrichmentTest.phpnew file mode 100644index 0000000000..253b33ccd4--- /dev/null+++ b/tests/Feature/SyncAdapters/Kandji/KandjiAppleDbEnrichmentTest.php@@ -0,0 +1,146 @@+<?php++namespace Tests\Feature\SyncAdapters\Kandji;++use App\Models\AssetModel;+use App\Models\Statuslabel;+use App\Models\SyncAdapterConfig;+use App\Models\SyncAdapterInstance;+use App\Services\AppleDb\AppleDbEnrichment;+use App\SyncAdapters\Kandji\KandjiAdapter;+use App\SyncAdapters\SyncAdapter;+use Illuminate\Support\Facades\Crypt;+use Illuminate\Support\Facades\Http;+use Illuminate\Support\Facades\Storage;+use Tests\TestCase;++class KandjiAppleDbEnrichmentTest extends TestCase+{+ protected function setUp(): void+ {+ parent::setUp();+ Statuslabel::factory()->rtd()->create();+ Storage::fake('public');+ AppleDbEnrichment::clearCache();+ }++ public function test_pull_backfills_model_fields_from_appledb_via_details_endpoint()+ {+ $adapter = $this->configuredAdapter(enrichmentEnabled: true);+ $model = AssetModel::factory()->create([+ 'name' => 'MacBook Pro',+ 'image' => null,+ 'model_number' => null,+ 'mfg_marketing_name' => null,+ 'mfg_release_date' => null,+ 'mfg_discontinued_date' => null,+ ]);++ $this->fakeKandjiAndAppleDb();++ foreach ($adapter->pull() as $record) {+ SyncAdapter::syncFromRecord($record);+ }++ $model->refresh();+ $this->assertSame('MacBook Pro (14-inch, M4, 2024)', $model->mfg_marketing_name);+ $this->assertSame('A3123', $model->model_number);+ $this->assertSame('2024-11-08', $model->mfg_release_date?->toDateString());+ $this->assertSame('2026-03-05', $model->mfg_discontinued_date?->toDateString());+ }++ public function test_pull_skips_detail_fetches_entirely_when_toggle_is_off()+ {+ $adapter = $this->configuredAdapter(enrichmentEnabled: false);+ $this->fakeKandjiAndAppleDb();++ foreach ($adapter->pull() as $record) {+ SyncAdapter::syncFromRecord($record);+ }++ Http::assertNotSent(fn ($request) => str_contains($request->url(), '/details'));+ Http::assertNotSent(fn ($request) => str_contains($request->url(), 'appledb.dev'));+ }++ public function test_record_extras_carry_appledb_values_and_kandji_identifier()+ {+ $adapter = $this->configuredAdapter(enrichmentEnabled: true);+ $this->fakeKandjiAndAppleDb();++ $records = iterator_to_array($adapter->pull());++ $this->assertSame('MacBookPro18,3', $records[0]->extra['kandji_model_identifier']);+ $this->assertSame('MacBook Pro (14-inch, M4, 2024)', $records[0]->extra['appledb_marketing_name']);+ $this->assertSame('A3123', $records[0]->extra['appledb_model_number']);+ }++ public function test_detail_fetch_failure_leaves_identifier_null_without_aborting_the_pull()+ {+ $adapter = $this->configuredAdapter(enrichmentEnabled: true);++ Http::fake([+ '*/api/v1/devices*/details' => Http::response([], 500),+ '*/api/v1/devices*' => Http::response([[+ 'device_id' => 'kandji-1',+ 'device_name' => 'mac-01',+ 'model' => 'MacBook Pro',+ 'serial_number' => 'KJ-1',+ 'platform' => 'Mac',+ 'os_version' => '15.0',+ 'last_check_in' => null,+ 'asset_tag' => null,+ 'assigned_blueprint_id' => null,+ 'mdm_enabled' => true,+ ]]),+ 'api.appledb.dev/*' => Http::response([]),+ ]);++ $records = iterator_to_array($adapter->pull());++ $this->assertCount(1, $records);+ $this->assertNull($records[0]->extra['kandji_model_identifier']);+ }++ private function fakeKandjiAndAppleDb(): void+ {+ Http::fake([+ '*/api/v1/devices/kandji-1/details' => Http::response([+ 'hardware_overview' => [+ 'model' => 'MacBook Pro (14-inch, M4, 2024)',+ 'model_identifier' => 'MacBookPro18,3',+ ],+ ]),+ '*/api/v1/devices*' => Http::response([[+ 'device_id' => 'kandji-1',+ 'device_name' => 'mac-01',+ 'model' => 'MacBook Pro',+ 'serial_number' => 'KJ-1',+ 'platform' => 'Mac',+ 'os_version' => '15.0',+ 'last_check_in' => null,+ 'asset_tag' => null,+ 'assigned_blueprint_id' => null,+ 'mdm_enabled' => true,+ ]]),+ 'api.appledb.dev/device/*' => Http::response([+ 'name' => 'MacBook Pro (14-inch, M4, 2024)',+ 'released' => '2024-11-08',+ 'discontinued' => '2026-03-05',+ 'model' => ['A3123'],+ 'imageKey' => 'macbook-pro-14-m4',+ 'colors' => [['key' => 'silver']],+ ]),+ 'img.appledb.dev/*' => Http::response(str_repeat("\x89PNG\r\n\x1a\n", 4)),+ ]);+ }++ private function configuredAdapter(bool $enrichmentEnabled): KandjiAdapter+ {+ $instance = SyncAdapterInstance::where('slug', 'kandji')->firstOrFail();+ SyncAdapterConfig::put($instance->id, 'url', 'https://example.api.kandji.io');+ SyncAdapterConfig::put($instance->id, 'token', Crypt::encrypt('fake-kandji-token'));+ SyncAdapterConfig::put($instance->id, 'use_appledb_enrichment', $enrichmentEnabled ? '1' : '');++ return new KandjiAdapter($instance->fresh());+ }+}