A free open source IT asset/license management system
Fixed #19884 - added aplpe category mapping
snipe697295c687d0
diff --git a/app/SyncAdapters/Mosyle/MosyleAdapter.php b/app/SyncAdapters/Mosyle/MosyleAdapter.phpindex 9c61f0b385..99d46cd1ee 100644--- a/app/SyncAdapters/Mosyle/MosyleAdapter.php+++ b/app/SyncAdapters/Mosyle/MosyleAdapter.php@@ -24,6 +24,26 @@ use Illuminate\Support\Facades\Log;*/class MosyleAdapter extends SyncAdapter implements PushableAdapter{+ /**+ * Per-category-selector config keys -> friendly display name. Same+ * split pattern as ABM: Mosyle's device_type is a four-value enum+ * (mac / ios / tvos / visionos) but admins usually want MacBook vs.+ * iMac/Mini/Studio/Pro in separate Snipe-IT categories, and iPhone+ * vs. iPad in separate ones too. categoryConfigKeyForRecord()+ * encodes the device_type + model prefix mapping below. Issue+ * #19884.+ *+ * @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_vision' => 'Apple Vision',+ ];+public static function typeLabel(): string{// Mosyle Manager and Mosyle Business are different products@@ -51,7 +71,7 @@ class MosyleAdapter extends SyncAdapter implements PushableAdapterpublic function settingsSchema(): array{- return [+ $schema = [['key' => 'access_token','label' => trans('admin/settings/sync_adapters.label_access_token'),@@ -70,6 +90,114 @@ class MosyleAdapter extends SyncAdapter implements PushableAdapter'help' => trans('admin/settings/sync_adapters.mosyle_password_help'),],];++ // Per-family category overrides. Mirrors the ABM pattern (which+ // uses the same Apple product-family vocabulary). Translation+ // keys are shared across both adapters because the strings are+ // adapter-neutral and the FOSS translator community pays the+ // cost of every new key. Empty selection falls back to+ // default_category_id.+ 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,+ 'section' => 'categories',+ 'help' => trans('admin/settings/sync_adapters.abm_category_family_help', ['family' => $displayName]),+ ];+ }++ return $schema;+ }++ public function settingsSections(): array+ {+ return [+ 'categories' => [+ 'title' => trans('admin/settings/sync_adapters.abm_section_categories_title'),+ ],+ ];+ }++ /**+ * Route each record to a per-family category when the admin+ * configured one. Falls through to defaultCategoryId() when the+ * device_type / model prefix doesn't match a configured selector,+ * matching the ABM adapter's 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. Mosyle's+ * device_type is coarser than Apple's productFamily (ios covers+ * both iPhone and iPad), so the mapping splits on the hardwareModel+ * prefix in addition to the device_type. mac devices split into+ * laptop (MacBook*) vs. desktop (iMac / Mac mini / Mac Studio /+ * Mac Pro), matching the ABM split.+ *+ * Returns null when the device_type is unrecognized OR when the+ * model prefix doesn't match a known split, so the framework falls+ * back to defaultCategoryId() rather than saving under an arbitrary+ * bucket.+ */+ private static function categoryConfigKeyForRecord(HostInventoryRecord $record): ?string+ {+ $deviceType = $record->extra['mosyle_device_type'] ?? null;+ if (! is_string($deviceType)) {+ return null;+ }+ $model = $record->hardwareModel ?? '';++ if ($deviceType === 'mac') {+ if ($model === '') {+ return null;+ }+ if (str_starts_with($model, 'MacBook')) {+ return 'category_id_mac_laptop';+ }+ foreach (['iMac', 'Mac mini', 'Mac Studio', 'Mac Pro'] as $desktopPrefix) {+ if (str_starts_with($model, $desktopPrefix)) {+ return 'category_id_mac_desktop';+ }+ }++ return null;+ }++ if ($deviceType === 'ios') {+ if ($model === '') {+ return null;+ }+ if (str_starts_with($model, 'iPhone')) {+ return 'category_id_iphone';+ }+ if (str_starts_with($model, 'iPad')) {+ return 'category_id_ipad';+ }++ return null;+ }++ return match ($deviceType) {+ 'tvos' => 'category_id_appletv',+ 'visionos' => 'category_id_vision',+ default => null,+ };}public function extraFields(): arraydiff --git a/tests/Feature/SyncAdapters/Mosyle/PerFamilyCategoryRoutingTest.php b/tests/Feature/SyncAdapters/Mosyle/PerFamilyCategoryRoutingTest.phpnew file mode 100644index 0000000000..683d6eb345--- /dev/null+++ b/tests/Feature/SyncAdapters/Mosyle/PerFamilyCategoryRoutingTest.php@@ -0,0 +1,188 @@+<?php++namespace Tests\Feature\SyncAdapters\Mosyle;++use App\Models\AssetModel;+use App\Models\Category;+use App\Models\Statuslabel;+use App\Models\SyncAdapterConfig;+use App\Models\SyncAdapterInstance;+use App\SyncAdapters\Mosyle\MosyleAdapter;+use App\SyncAdapters\SyncAdapter;+use Illuminate\Support\Facades\Crypt;+use Illuminate\Support\Facades\Http;+use Tests\TestCase;++/**+ * Coverage for the Mosyle adapter's per-device-type category routing+ * (issue #19884). Mosyle Manager's device_type is a four-value enum+ * (mac / ios / tvos / visionos) plus a model-prefix split so admins+ * get MacBook vs. iMac/Mini/Studio/Pro and iPhone vs. iPad as+ * separate category selectors. Mirrors the ABM adapter's pattern.+ */+class PerFamilyCategoryRoutingTest extends TestCase+{+ protected function setUp(): void+ {+ parent::setUp();+ Statuslabel::factory()->rtd()->create();+ }++ 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,+ ]);++ $this->fakeMosyleWithDevices([+ // Only the ios OS endpoint returns anything. The other+ // mac/tvos/visionos queries return empty pages.+ 'ios' => [$this->mosyleDevice(udid: 'uuid-ipad', model: 'iPad Air', deviceType: 'ios')],+ ]);++ foreach ($adapter->pull() as $record) {+ SyncAdapter::syncFromRecord($record);+ }++ $model = AssetModel::where('name', 'iPad Air')->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,+ ]);++ $this->fakeMosyleWithDevices([+ 'mac' => [$this->mosyleDevice(udid: 'uuid-mbp', model: 'MacBook Pro', deviceType: 'mac')],+ ]);++ foreach ($adapter->pull() as $record) {+ SyncAdapter::syncFromRecord($record);+ }++ $model = AssetModel::where('name', 'MacBook Pro')->firstOrFail();+ $this->assertSame($laptop->id, $model->category_id);+ }++ public function test_imac_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,+ ]);++ $this->fakeMosyleWithDevices([+ 'mac' => [$this->mosyleDevice(udid: 'uuid-imac', model: 'iMac', deviceType: 'mac')],+ ]);++ foreach ($adapter->pull() as $record) {+ SyncAdapter::syncFromRecord($record);+ }++ $model = AssetModel::where('name', 'iMac')->firstOrFail();+ $this->assertSame($desktop->id, $model->category_id);+ }++ public function test_apple_tv_falls_back_to_default_when_no_override_set()+ {+ $default = Category::factory()->assetTabletCategory()->create();+ $adapter = $this->configuredAdapter([+ 'default_category_id' => $default->id,+ // No category_id_appletv override. Adapter has no opinion,+ // framework uses defaultCategoryId.+ ]);++ $this->fakeMosyleWithDevices([+ 'tvos' => [$this->mosyleDevice(udid: 'uuid-atv', model: 'Apple TV 4K', deviceType: 'tvos')],+ ]);++ foreach ($adapter->pull() as $record) {+ SyncAdapter::syncFromRecord($record);+ }++ $model = AssetModel::where('name', 'Apple TV 4K')->firstOrFail();+ $this->assertSame($default->id, $model->category_id);+ }++ /**+ * Build an Http::fake() that returns the given devices for the+ * matching Mosyle OS and empty pages for every other OS. Mosyle's+ * /listdevices is called once per OS (mac, ios, tvos, visionos),+ * each paginated until an empty page terminates the loop.+ *+ * @param array<string, list<array<string, mixed>>> $devicesByOs+ */+ private function fakeMosyleWithDevices(array $devicesByOs): void+ {+ $osOrder = ['mac', 'ios', 'tvos', 'visionos'];+ $sequence = Http::sequence();+ foreach ($osOrder as $os) {+ if (! empty($devicesByOs[$os] ?? [])) {+ $sequence->push($this->devicesResponse($devicesByOs[$os]));+ }+ // Empty terminating page for every OS.+ $sequence->push($this->devicesResponse([]));+ }++ Http::fake([+ '*/login' => Http::response(null, 200, ['Authorization' => 'Bearer fake-jwt']),+ '*/listdevices' => $sequence,+ ]);+ }++ private function configuredAdapter(array $extraConfig = []): MosyleAdapter+ {+ $instance = SyncAdapterInstance::where('slug', 'mosyle')->firstOrFail();+ SyncAdapterConfig::put($instance->id, 'url', 'https://managerapi.mosyle.com/v2');+ SyncAdapterConfig::put($instance->id, 'access_token', Crypt::encrypt('fake-access-token'));+ SyncAdapterConfig::put($instance->id, 'email', '[email protected]');+ SyncAdapterConfig::put($instance->id, 'password', Crypt::encrypt('fake-password'));++ foreach ($extraConfig as $key => $value) {+ SyncAdapterConfig::put($instance->id, $key, $value);+ }++ return new MosyleAdapter($instance->fresh());+ }++ /**+ * @return array<string, mixed>+ */+ private function devicesResponse(array $devices): array+ {+ return [+ 'status' => 'OK',+ 'response' => [+ 'devices' => $devices,+ 'rows' => (string) count($devices),+ 'page_size' => 200,+ 'page' => 1,+ ],+ ];+ }++ /**+ * @return array<string, mixed>+ */+ private function mosyleDevice(string $udid, string $model, string $deviceType, string $name = 'device'): array+ {+ return [+ 'deviceudid' => $udid,+ 'device_name' => $name,+ 'device_model_name' => $model,+ 'serial_number' => 'SN-'.$udid,+ 'device_type' => $deviceType,+ 'is_supervised' => true,+ ];+ }+}