Skip to content

A free open source IT asset/license management system

Added Apple Business Manager adapter

snipe881144f595dd
diff --git a/app/SyncAdapters/AdapterRegistry.php b/app/SyncAdapters/AdapterRegistry.php
index 896098cee2..0d3f09f4cc 100644
--- a/app/SyncAdapters/AdapterRegistry.php
+++ b/app/SyncAdapters/AdapterRegistry.php
@@ -4,12 +4,14 @@ namespace App\SyncAdapters;
use App\Models\SyncAdapterInstance;
use App\SyncAdapters\Addigy\AddigyAdapter;
+use App\SyncAdapters\AppleBusinessManager\AppleBusinessManagerAdapter;
use App\SyncAdapters\Fleet\FleetAdapter;
use App\SyncAdapters\Intune\IntuneAdapter;
use App\SyncAdapters\Jamf\JamfAdapter;
use App\SyncAdapters\JamfSchool\JamfSchoolAdapter;
use App\SyncAdapters\JumpCloud\JumpCloudAdapter;
use App\SyncAdapters\Kandji\KandjiAdapter;
+use App\SyncAdapters\KaseyaVsa10\KaseyaVsa10Adapter;
use App\SyncAdapters\MerakiSystemsManager\MerakiSystemsManagerAdapter;
use App\SyncAdapters\Mosyle\MosyleAdapter;
use App\SyncAdapters\NinjaOne\NinjaOneAdapter;
@@ -36,10 +38,12 @@ class AdapterRegistry
private const TYPES = [
'fleet' => FleetAdapter::class,
'addigy' => AddigyAdapter::class,
+ 'apple_business_manager' => AppleBusinessManagerAdapter::class,
'intune' => IntuneAdapter::class,
'jamf' => JamfAdapter::class,
'jamf_school' => JamfSchoolAdapter::class,
'kandji' => KandjiAdapter::class,
+ 'kaseya_vsa10' => KaseyaVsa10Adapter::class,
'meraki_sm' => MerakiSystemsManagerAdapter::class,
'mosyle' => MosyleAdapter::class,
'ninjaone' => NinjaOneAdapter::class,
diff --git a/app/SyncAdapters/AppleBusinessManager/AppleBusinessManagerAdapter.php b/app/SyncAdapters/AppleBusinessManager/AppleBusinessManagerAdapter.php
new file mode 100644
index 0000000000..6d2fbbd1ef
--- /dev/null
+++ b/app/SyncAdapters/AppleBusinessManager/AppleBusinessManagerAdapter.php
@@ -0,0 +1,457 @@
+<?php
+
+namespace App\SyncAdapters\AppleBusinessManager;
+
+use App\Models\SyncAdapterConfig;
+use App\SyncAdapters\HostInventoryRecord;
+use App\SyncAdapters\Support\ConfigurableAdapter;
+use Carbon\Carbon;
+use Illuminate\Http\Request;
+use Illuminate\Support\Arr;
+
+/**
+ * Apple Business Manager (ABM) / Apple School Manager (ASM) adapter.
+ * Pulls the master device roster from Apple's org-devices API using
+ * JWT client-assertion auth (ES256, signed with an EC P-256 private
+ * key downloaded from Apple's admin console).
+ *
+ * ABM is a purchase-registration portal, not a runtime inventory.
+ * Devices show up here as soon as they're bought via an
+ * Apple-integrated reseller, before enrollment, before OS install.
+ * That means hostname, OS version, last-seen, and MAC address are
+ * null in every record: those become populated later once the device
+ * enrolls in an MDM (Jamf, Kandji, Mosyle, Intune, etc). The point of
+ * the ABM adapter is to pre-populate Snipe-IT with the authoritative
+ * "we own this serial" list before an MDM enrolls it, or to pick up
+ * devices the MDM never sees (spares, decommissioned, in-transit).
+ *
+ * Groups: ABM has Organizations/Sites concepts, but the device record
+ * doesn't expose an org-scoped foreign key today. Group scoping is
+ * off. If admins want per-Snipe-IT-company routing, they run one
+ * adapter instance per company for now.
+ *
+ * Push: not implemented. Apple's write endpoints (device metadata,
+ * MDM server assignment) are outside Snipe-IT's authoritative scope.
+ */
+class AppleBusinessManagerAdapter extends ConfigurableAdapter
+{
+ public static function typeLabel(): string
+ {
+ return 'Apple Business Manager';
+ }
+
+ public function baseUrlPlaceholder(): ?string
+ {
+ // ABM/ASM base URLs are host-fixed per mode (business or
+ // school), so we don't expose a URL field. The mode selection
+ // in the credential schema controls host + scope.
+ return null;
+ }
+
+ public function credentialSchema(): array
+ {
+ return [
+ [
+ 'key' => 'mode',
+ 'label' => 'Portal',
+ 'help' => trans('admin/settings/sync_adapters.abm_mode_help'),
+ ],
+ [
+ 'key' => 'client_id',
+ 'label' => 'Client ID',
+ 'help' => trans('admin/settings/sync_adapters.abm_client_id_help'),
+ ],
+ [
+ 'key' => 'key_id',
+ 'label' => 'Key ID',
+ 'help' => trans('admin/settings/sync_adapters.abm_key_id_help'),
+ ],
+ [
+ 'key' => 'private_key',
+ 'label' => 'Private Key (PEM)',
+ 'secret' => true,
+ 'help' => trans('admin/settings/sync_adapters.abm_private_key_help'),
+ ],
+ [
+ 'key' => 'product_family_filter',
+ 'label' => 'Product Families',
+ 'required' => false,
+ 'help' => trans('admin/settings/sync_adapters.abm_product_family_filter_help'),
+ ],
+ ];
+ }
+
+ public function extraFields(): array
+ {
+ return [
+ 'abm_product_family' => ['label_key' => 'admin/settings/sync_adapters.extra_product_family'],
+ 'abm_model_marketing_name' => ['label_key' => 'admin/settings/sync_adapters.extra_model_marketing_name'],
+ 'abm_product_type' => ['label_key' => 'admin/settings/sync_adapters.extra_product_type'],
+ 'abm_part_number' => ['label_key' => 'admin/settings/sync_adapters.extra_part_number'],
+ 'abm_color' => ['label_key' => 'admin/settings/sync_adapters.extra_color'],
+ 'abm_order_number' => ['label_key' => 'admin/settings/sync_adapters.extra_order_number'],
+ 'abm_order_date' => ['label_key' => 'admin/settings/sync_adapters.extra_order_date'],
+ 'abm_purchase_source_type' => ['label_key' => 'admin/settings/sync_adapters.extra_purchase_source_type'],
+ 'abm_purchase_source_id' => ['label_key' => 'admin/settings/sync_adapters.extra_purchase_source_id'],
+ 'abm_mdm_server' => ['label_key' => 'admin/settings/sync_adapters.extra_mdm_server'],
+ 'abm_applecare_agreement_number' => ['label_key' => 'admin/settings/sync_adapters.extra_applecare_agreement_number'],
+ 'abm_applecare_status' => ['label_key' => 'admin/settings/sync_adapters.extra_applecare_status'],
+ 'abm_applecare_payment_type' => ['label_key' => 'admin/settings/sync_adapters.extra_applecare_payment_type'],
+ 'abm_applecare_start_date' => ['label_key' => 'admin/settings/sync_adapters.extra_applecare_start_date'],
+ 'abm_applecare_end_date' => ['label_key' => 'admin/settings/sync_adapters.extra_applecare_end_date'],
+ 'abm_applecare_description' => ['label_key' => 'admin/settings/sync_adapters.extra_applecare_description'],
+ 'abm_applecare_is_canceled' => ['label_key' => 'admin/settings/sync_adapters.extra_applecare_is_canceled', 'type' => 'boolean'],
+ 'abm_applecare_is_renewable' => ['label_key' => 'admin/settings/sync_adapters.extra_applecare_is_renewable', 'type' => 'boolean'],
+ ];
+ }
+
+ /**
+ * 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(
+ clientId: $this->credential('client_id'),
+ keyId: $this->credential('key_id'),
+ privateKeyPem: $this->credential('private_key'),
+ mode: $this->resolvedMode(),
+ );
+
+ // Build the device-to-MDM-server map up front so normalize()
+ // can attach each device's assigned server name without a
+ // per-device API call. Best-effort: failures leave the map
+ // empty and every asset just gets a null abm_mdm_server.
+ $deviceToServer = [];
+ try {
+ $deviceToServer = $client->deviceToMdmServerMap();
+ } catch (\Throwable $e) {
+ \Log::channel('sync-adapters')->warning(sprintf(
+ '%s mdm-server map fetch failed: %s',
+ $this->name(),
+ $e->getMessage(),
+ ));
+ }
+
+ // Only fetch AppleCare coverage per device when at least one
+ // applecare extra field is mapped. Fetching AppleCare adds an
+ // API call per device, so admins who don't care about
+ // warranty tracking skip the cost entirely.
+ $enrichWithAppleCare = $this->hasMappedAppleCareFields();
+
+ // Allowed product families (lower-cased for comparison).
+ // Empty means "all families".
+ $allowedFamilies = $this->allowedProductFamilies();
+
+ foreach ($client->devices() as $device) {
+ $family = strtolower((string) ($device['attributes']['productFamily'] ?? ''));
+ if ($allowedFamilies !== [] && ! in_array($family, $allowedFamilies, true)) {
+ continue;
+ }
+ $record = $this->normalize($device, $deviceToServer);
+ if ($enrichWithAppleCare) {
+ $record = $this->enrichRecordWithAppleCare($record, $client);
+ }
+ 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.
+ *
+ * @return array<int, string>
+ */
+ private function allowedProductFamilies(): array
+ {
+ try {
+ $raw = $this->credential('product_family_filter');
+ } catch (\Throwable) {
+ return [];
+ }
+
+ if ($raw === '') {
+ return [];
+ }
+
+ $parts = preg_split('/[,\s]+/', strtolower($raw)) ?: [];
+
+ return array_values(array_filter(array_map('trim', $parts), fn ($p) => $p !== ''));
+ }
+
+ /**
+ * Whether at least one AppleCare-shaped extra has a non-skip
+ * mapping stored. Gates the per-device AppleCare fetch in pull()
+ * so admins who don't map any AppleCare field don't pay for the
+ * enrichment.
+ */
+ private function hasMappedAppleCareFields(): bool
+ {
+ foreach (array_keys($this->extraFields()) as $key) {
+ if (! str_starts_with($key, 'abm_applecare_')) {
+ continue;
+ }
+ $target = $this->mappingFor($key);
+ if ($target !== '' && $target !== 'skip') {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * Fetch AppleCare coverage for one asset, pick the most relevant
+ * plan, and merge its fields into the record's extras. On empty
+ * or failed responses we just return the un-enriched record so
+ * the sync doesn't stall on transient AppleCare-endpoint issues.
+ */
+ private function enrichRecordWithAppleCare(HostInventoryRecord $record, AppleBusinessManagerClient $client): HostInventoryRecord
+ {
+ try {
+ $coverages = $client->deviceAppleCareCoverage($record->sourceId);
+ } catch (\Throwable $e) {
+ \Log::channel('sync-adapters')->warning(sprintf(
+ '%s applecare fetch failed for device %s: %s',
+ $this->name(),
+ $record->sourceId,
+ $e->getMessage(),
+ ));
+
+ return $record;
+ }
+
+ $best = self::pickBestCoverage($coverages);
+ if ($best === null) {
+ return $record;
+ }
+
+ $extra = $record->extra;
+ $extra['abm_applecare_agreement_number'] = $best['agreementNumber'] ?? null;
+ $extra['abm_applecare_status'] = self::titleCase($best['status'] ?? null);
+ $extra['abm_applecare_payment_type'] = self::titleCase($best['paymentType'] ?? null);
+ $extra['abm_applecare_start_date'] = self::parseOrderDate($best['startDateTime'] ?? null);
+ $extra['abm_applecare_end_date'] = self::parseOrderDate($best['endDateTime'] ?? null);
+ $extra['abm_applecare_description'] = $best['description'] ?? null;
+ $extra['abm_applecare_is_canceled'] = $best['isCanceled'] ?? null;
+ $extra['abm_applecare_is_renewable'] = $best['isRenewable'] ?? null;
+
+ return new HostInventoryRecord(
+ sourceKey: $record->sourceKey,
+ sourceId: $record->sourceId,
+ hostname: $record->hostname,
+ hardwareSerial: $record->hardwareSerial,
+ hardwareModel: $record->hardwareModel,
+ manufacturer: $record->manufacturer,
+ primaryMac: $record->primaryMac,
+ primaryIp: $record->primaryIp,
+ os: $record->os,
+ osVersion: $record->osVersion,
+ lastSeen: $record->lastSeen,
+ assetTag: $record->assetTag,
+ assignedUserEmail: $record->assignedUserEmail,
+ assignedUserName: $record->assignedUserName,
+ vendorGroupId: $record->vendorGroupId,
+ extra: $extra,
+ );
+ }
+
+ /**
+ * Pick the most relevant AppleCare coverage plan for a device.
+ * A device can carry multiple overlapping plans (renewals,
+ * add-ons, prior canceled ones). Ranking mirrors axm2snipe's
+ * approach so an org migrating from that tool sees the same
+ * coverage on each asset:
+ * 1. ACTIVE status beats INACTIVE
+ * 2. PAID_UP_FRONT payment type beats subscription / none
+ * 3. Later endDateTime wins the final tiebreaker
+ *
+ * Returns the winning attributes array, or null when the list is
+ * empty / every entry lacks attributes.
+ *
+ * @param array<int, array<string, mixed>> $coverages
+ * @return array<string, mixed>|null
+ */
+ private static function pickBestCoverage(array $coverages): ?array
+ {
+ $best = null;
+ foreach ($coverages as $coverage) {
+ $attrs = $coverage['attributes'] ?? null;
+ if (! is_array($attrs)) {
+ continue;
+ }
+ if ($best === null) {
+ $best = $attrs;
+
+ continue;
+ }
+ if (self::coverageIsBetter($attrs, $best)) {
+ $best = $attrs;
+ }
+ }
+
+ return $best;
+ }
+
+ /**
+ * Ordering predicate for two AppleCare coverage attribute maps.
+ * See pickBestCoverage() for the ranking rules.
+ *
+ * @param array<string, mixed> $candidate
+ * @param array<string, mixed> $current
+ */
+ private static function coverageIsBetter(array $candidate, array $current): bool
+ {
+ $candidateActive = ($candidate['status'] ?? '') === 'ACTIVE';
+ $currentActive = ($current['status'] ?? '') === 'ACTIVE';
+ if ($candidateActive !== $currentActive) {
+ return $candidateActive;
+ }
+
+ $candidatePaid = ($candidate['paymentType'] ?? '') === 'PAID_UP_FRONT';
+ $currentPaid = ($current['paymentType'] ?? '') === 'PAID_UP_FRONT';
+ if ($candidatePaid !== $currentPaid) {
+ return $candidatePaid;
+ }
+
+ $candidateEnd = $candidate['endDateTime'] ?? null;
+ $currentEnd = $current['endDateTime'] ?? null;
+ if (! is_string($candidateEnd) || ! is_string($currentEnd)) {
+ return false;
+ }
+
+ return Carbon::parse($candidateEnd)->greaterThan(Carbon::parse($currentEnd));
+ }
+
+ /**
+ * Convert an ABM device row into the normalized record shape.
+ * ABM's device `id` is a stable GUID and is what we key
+ * asset_external_sources on. Manufacturer is hard-coded to
+ * "Apple" since every ABM device is by definition Apple hardware
+ * and the payload doesn't carry the string.
+ *
+ * @param array<string, mixed> $device
+ * @param array<string, string> $deviceToServer
+ */
+ private function normalize(array $device, array $deviceToServer): HostInventoryRecord
+ {
+ $attrs = $device['attributes'] ?? [];
+ $id = (string) ($device['id'] ?? '');
+
+ return new HostInventoryRecord(
+ sourceKey: $this->name(),
+ sourceId: $id,
+ // ABM is pre-provisioning, so hostname doesn't exist here.
+ // Downstream shell-asset creation names the row after the
+ // synthetic sourceKey + sourceId until admins rename it
+ // or an MDM adapter joins in and provides a real hostname.
+ hostname: null,
+ hardwareSerial: Arr::get($attrs, 'serialNumber'),
+ // ABM provides three model-adjacent strings, exposed as
+ // extras below so admins can pick which one flows to
+ // native:model via the mapping UI:
+ // - deviceModel: marketing name ("MacBook Pro
+ // (14-inch, M1 Pro/Max, 2021)"), which matches Fleet's
+ // hardware_marketing_name for cross-adapter
+ // convergence
+ // - productType: hardware identifier ("MacBookPro18,3")
+ // - partNumber: Apple's SKU ("MK1E3LL/A")
+ // Default hardwareModel is partNumber because it's
+ // always populated and unique per SKU. Admins mapping
+ // abm_marketing_name to native:model gets the friendly
+ // Fleet-compatible shape instead.
+ hardwareModel: Arr::get($attrs, 'partNumber'),
+ manufacturer: 'Apple',
+ primaryMac: null,
+ primaryIp: null,
+ os: null,
+ osVersion: null,
+ lastSeen: null,
+ assignedUserEmail: null,
+ assignedUserName: null,
+ vendorGroupId: null,
+ extra: [
+ 'abm_product_family' => Arr::get($attrs, 'productFamily'),
+ 'abm_model_marketing_name' => Arr::get($attrs, 'deviceModel'),
+ 'abm_product_type' => Arr::get($attrs, 'productType'),
+ 'abm_part_number' => Arr::get($attrs, 'partNumber'),
+ 'abm_color' => self::titleCase(Arr::get($attrs, 'color')),
+ 'abm_order_number' => Arr::get($attrs, 'orderNumber'),
+ 'abm_order_date' => self::parseOrderDate(Arr::get($attrs, 'orderDateTime')),
+ 'abm_purchase_source_type' => Arr::get($attrs, 'purchaseSourceType'),
+ 'abm_purchase_source_id' => Arr::get($attrs, 'purchaseSourceId'),
+ 'abm_mdm_server' => $deviceToServer[$id] ?? null,
+ ],
+ );
+ }
+
+ /**
+ * Which mode we're operating in: 'business' or 'school'. Stored
+ * plain-text as a credential value so credentialSchema() renders
+ * a normal text input. Anything other than 'school' resolves to
+ * 'business' (the safer default that keeps admins from typoing
+ * their way into the wrong host).
+ */
+ private function resolvedMode(): string
+ {
+ try {
+ $stored = strtolower(trim($this->credential('mode')));
+ } catch (\Throwable) {
+ return 'business';
+ }
+
+ return $stored === 'school' ? 'school' : 'business';
+ }
+
+ /**
+ * Title-case a color string ("SPACEBLACK" -> "Spaceblack") so
+ * downstream custom fields aren't stuck with the vendor's
+ * upper-case constants. Passes through null unchanged so
+ * empty-guards on custom-field writes still fire.
+ */
+ private static function titleCase(?string $value): ?string
+ {
+ if ($value === null || $value === '') {
+ return $value;
+ }
+
+ return ucwords(strtolower($value));
+ }
+
+ /**
+ * ABM emits orderDateTime as ISO 8601 with fractional seconds and
+ * a trailing Z. Format to YYYY-MM-DD for admins who route this
+ * to a date-typed custom field.
+ */
+ private static function parseOrderDate(mixed $value): ?string
+ {
+ if ($value === null || $value === '') {
+ return null;
+ }
+
+ try {
+ return Carbon::parse($value)->toDateString();
+ } catch (\Throwable) {
+ return null;
+ }
+ }
+}
diff --git a/app/SyncAdapters/AppleBusinessManager/AppleBusinessManagerClient.php b/app/SyncAdapters/AppleBusinessManager/AppleBusinessManagerClient.php
new file mode 100644
index 0000000000..e5702bc4bb
--- /dev/null
+++ b/app/SyncAdapters/AppleBusinessManager/AppleBusinessManagerClient.php
@@ -0,0 +1,226 @@
+<?php
+
+namespace App\SyncAdapters\AppleBusinessManager;
+
+use Firebase\JWT\JWT;
+use Illuminate\Http\Client\PendingRequest;
+use Illuminate\Support\Facades\Http;
+use Illuminate\Support\Str;
+
+/**
+ * Thin wrapper around Apple Business Manager (ABM) and Apple School
+ * Manager (ASM) REST APIs. Both products share the same endpoint shape
+ * and JWT client-assertion auth model. Only the base host differs
+ * (api-business.apple.com vs api-school.apple.com). The mode toggle in
+ * the adapter's credential schema picks which host + scope to use.
+ *
+ * Auth model: Apple issues an OAuth application (Settings > API in the
+ * ABM/ASM console) as a Client ID + Key ID + downloaded EC P-256
+ * private key (.pem). This client signs a JWT client-assertion with
+ * ES256, exchanges it at account.apple.com for a short-lived bearer,
+ * and caches that bearer for the life of the sync run.
+ *
+ * Pagination: /v1/orgDevices uses `limit` + `cursor` for forward
+ * paging. `Meta.Paging.Total` gives the total record count when the
+ * caller wants to size progress reporting.
+ */
+class AppleBusinessManagerClient
+{
+ private const APPLE_AUDIENCE = 'https://account.apple.com/auth/oauth2/v2/token';
+
+ private const APPLE_TOKEN_ENDPOINT = 'https://account.apple.com/auth/oauth2/v2/token';
+
+ private ?string $accessToken = null;
+
+ /**
+ * @param 'business'|'school' $mode
+ */
+ public function __construct(
+ private readonly string $clientId,
+ private readonly string $keyId,
+ private readonly string $privateKeyPem,
+ private readonly string $mode = 'business',
+ ) {}
+
+ /**
+ * Iterate every device in the org. Devices come back with an
+ * `Attributes` object carrying SerialNumber, PartNumber,
+ * ProductFamily, Color, OrderNumber, OrderDateTime, and other
+ * pre-provisioning fields. Hostnames / OS versions / last-seen
+ * are NOT here (ABM is a purchase-registration portal, not a
+ * runtime inventory), so downstream mapping leaves those null.
+ *
+ * @return iterable<int, array<string, mixed>>
+ */
+ public function devices(int $pageSize = 100): iterable
+ {
+ $cursor = null;
+
+ do {
+ $params = ['limit' => $pageSize];
+ if (is_string($cursor)) {
+ $params['cursor'] = $cursor;
+ }
+
+ $response = $this->request()
+ ->get('/v1/orgDevices', $params)
+ ->throw()
+ ->json();
+
+ $devices = $response['data'] ?? [];
+ foreach ($devices as $device) {
+ yield $device;
+ }
+
+ $cursor = $response['links']['next'] ?? null;
+ } while (is_string($cursor) && $cursor !== '');
+ }
+
+ /**
+ * Fetch every AppleCare coverage plan for a single device. Apple
+ * returns an array (a device can carry multiple overlapping plans
+ * for various renewals / extensions), so callers pick the best
+ * one for their purposes. Each entry has an attributes object
+ * with agreementNumber, startDateTime, endDateTime, status,
+ * paymentType, isCanceled, isRenewable, description.
+ *
+ * @return array<int, array<string, mixed>>
+ */
+ public function deviceAppleCareCoverage(string $deviceId): array
+ {
+ $response = $this->request()
+ ->get('/v1/orgDevices/'.$deviceId.'/appleCareCoverage')
+ ->throw()
+ ->json();
+
+ return $response['data'] ?? [];
+ }
+
+ /**
+ * Build a device-id -> MDM server name map by walking every MDM
+ * server's device linkages. Devices unassigned to any MDM server
+ * simply aren't in the returned map, so a `?? ''` fallback at the
+ * adapter side keeps normalize() clean. Called once per sync run.
+ *
+ * @return array<string, string>
+ */
+ public function deviceToMdmServerMap(): array
+ {
+ $servers = $this->request()
+ ->get('/v1/mdmServers')
+ ->throw()
+ ->json();
+
+ $serverNames = [];
+ foreach ($servers['data'] ?? [] as $server) {
+ $id = $server['id'] ?? null;
+ $name = $server['attributes']['serverName'] ?? null;
+ if (is_string($id) && is_string($name)) {
+ $serverNames[$id] = $name;
+ }
+ }
+
+ $deviceToServer = [];
+ foreach ($serverNames as $serverId => $serverName) {
+ $cursor = null;
+ do {
+ $params = ['limit' => 1000];
+ if (is_string($cursor)) {
+ $params['cursor'] = $cursor;
+ }
+ $response = $this->request()
+ ->get('/v1/mdmServers/'.$serverId.'/relationships/devices', $params)
+ ->throw()
+ ->json();
+
+ foreach ($response['data'] ?? [] as $linkage) {
+ $deviceId = $linkage['id'] ?? null;
+ if (is_string($deviceId)) {
+ $deviceToServer[$deviceId] = $serverName;
+ }
+ }
+
+ $cursor = $response['links']['next'] ?? null;
+ } while (is_string($cursor) && $cursor !== '');
+ }
+
+ return $deviceToServer;
+ }
+
+ /**
+ * Base HTTP client with resolved bearer token. Retries on 429 with
+ * exponential backoff. Apple's rate limit is generous but bursts
+ * during a full org pull can trip it briefly.
+ */
+ private function request(): PendingRequest
+ {
+ return Http::baseUrl($this->apiBaseUrl())
+ ->withToken($this->bearer())
+ ->acceptJson()
+ ->timeout(30)
+ ->retry(3, 500, fn (\Exception $e) => $e instanceof \Illuminate\Http\Client\ConnectionException
+ || ($e instanceof \Illuminate\Http\Client\RequestException && $e->response->status() === 429));
+ }
+
+ /**
+ * Exchange a signed JWT client-assertion for a bearer token.
+ * Tokens are short-lived (~1 hour) and cached on this instance so
+ * a full sync doesn't retrigger auth per request. Failures throw
+ * up to the sync runner and land in the sync-adapters log.
+ */
+ private function bearer(): string
+ {
+ if ($this->accessToken !== null) {
+ return $this->accessToken;
+ }
+
+ $assertion = $this->buildClientAssertion();
+
+ $response = Http::asForm()
+ ->timeout(30)
+ ->post(self::APPLE_TOKEN_ENDPOINT, [
+ 'grant_type' => 'client_credentials',
+ 'client_id' => $this->clientId,
+ 'client_assertion_type' => 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer',
+ 'client_assertion' => $assertion,
+ 'scope' => $this->tokenScope(),
+ ])
+ ->throw()
+ ->json();
+
+ return $this->accessToken = (string) ($response['access_token'] ?? '');
+ }
+
+ /**
+ * Sign an ES256 JWT client-assertion. Apple requires 180-day max
+ * expiration. We use 5 minutes, which is more than enough for the
+ * single token exchange this triggers. jti keeps replay windows
+ * closed even under a rotating fleet of sync processes.
+ */
+ private function buildClientAssertion(): string
+ {
+ $now = time();
+ $payload = [
+ 'sub' => $this->clientId,
+ 'aud' => self::APPLE_AUDIENCE,
+ 'iss' => $this->clientId,
+ 'iat' => $now,
+ 'exp' => $now + 300,
+ 'jti' => (string) Str::uuid(),
+ ];
+
+ return JWT::encode($payload, $this->privateKeyPem, 'ES256', $this->keyId);
+ }
+
+ private function apiBaseUrl(): string
+ {
+ return $this->mode === 'school'
+ ? 'https://api-school.apple.com'
+ : 'https://api-business.apple.com';
+ }
+
+ private function tokenScope(): string
+ {
+ return $this->mode === 'school' ? 'school.api' : 'business.api';
+ }
+}
diff --git a/database/migrations/2026_09_09_130000_seed_apple_business_manager_adapter_instance.php b/database/migrations/2026_09_09_130000_seed_apple_business_manager_adapter_instance.php
new file mode 100644
index 0000000000..d8fa90e8b7
--- /dev/null
+++ b/database/migrations/2026_09_09_130000_seed_apple_business_manager_adapter_instance.php
@@ -0,0 +1,33 @@
+<?php
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Support\Facades\DB;
+
+return new class extends Migration
+{
+ public function up(): void
+ {
+ if (DB::table('sync_adapter_instances')->where('slug', 'apple_business_manager')->exists()) {
+ return;
+ }
+
+ $now = now();
+ DB::table('sync_adapter_instances')->insert([
+ 'slug' => 'apple_business_manager',
+ 'adapter_type' => 'apple_business_manager',
+ 'label' => 'Apple Business Manager',
+ 'active' => false,
+ 'built_in' => true,
+ 'created_at' => $now,
+ 'updated_at' => $now,
+ ]);
+ }
+
+ public function down(): void
+ {
+ DB::table('sync_adapter_instances')
+ ->where('slug', 'apple_business_manager')
+ ->where('built_in', true)
+ ->delete();
+ }
+};
diff --git a/tests/Feature/SyncAdapters/AppleBusinessManager/AppleBusinessManagerAdapterTest.php b/tests/Feature/SyncAdapters/AppleBusinessManager/AppleBusinessManagerAdapterTest.php
new file mode 100644
index 0000000000..f7b5445a44
--- /dev/null
+++ b/tests/Feature/SyncAdapters/AppleBusinessManager/AppleBusinessManagerAdapterTest.php
@@ -0,0 +1,283 @@
+<?php
+
+namespace Tests\Feature\SyncAdapters\AppleBusinessManager;
+
+use App\Models\Statuslabel;
+use App\Models\SyncAdapterConfig;
+use App\Models\SyncAdapterInstance;
+use App\SyncAdapters\AppleBusinessManager\AppleBusinessManagerAdapter;
+use Illuminate\Support\Facades\Crypt;
+use Illuminate\Support\Facades\Http;
+use Tests\TestCase;
+
+/**
+ * End-to-end coverage for the Apple Business Manager adapter.
+ * Generates a fresh EC P-256 keypair at test time so the JWT
+ * signing path runs unmocked, and fakes Apple's token endpoint
+ * plus /v1/orgDevices and /v1/mdmServers so the extraction logic
+ * is exercised without any actual network calls.
+ */
+class AppleBusinessManagerAdapterTest 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',
+ ]);
+ openssl_pkey_export($key, $pem);
+ $this->privateKeyPem = $pem;
+ }
+
+ public function test_pulls_devices_and_extracts_apple_specific_fields()
+ {
+ $adapter = $this->configuredAdapter();
+
+ Http::fake([
+ 'account.apple.com/*' => Http::response(['access_token' => 'stub-bearer', 'expires_in' => 3600]),
+ 'api-business.apple.com/v1/mdmServers' => Http::response(['data' => []]),
+ 'api-business.apple.com/v1/orgDevices*' => Http::response([
+ 'data' => [
+ [
+ 'id' => 'abm-guid-1',
+ 'attributes' => [
+ 'serialNumber' => 'C02XL1234567',
+ 'partNumber' => 'MK1E3LL/A',
+ 'productFamily' => 'Mac',
+ 'color' => 'SPACEBLACK',
+ 'orderNumber' => 'W1234567',
+ 'orderDateTime' => '2025-08-15T14:22:00.000Z',
+ 'purchaseSourceType' => 'AppleCustomer',
+ 'purchaseSourceId' => 'DEP12345',
+ ],
+ ],
+ ],
+ ]),
+ ]);
+
+ $records = iterator_to_array($adapter->pull());
+ $this->assertCount(1, $records);
+
+ $record = $records[0];
+ $this->assertSame('apple_business_manager', $record->sourceKey);
+ $this->assertSame('abm-guid-1', $record->sourceId);
+ $this->assertSame('C02XL1234567', $record->hardwareSerial);
+ // Default hardwareModel is partNumber (always populated per
+ // ABM device). Marketing name (deviceModel) flows via the
+ // abm_marketing_name extra so admins can route it to
+ // native:model instead when they prefer the friendly shape.
+ $this->assertSame('MK1E3LL/A', $record->hardwareModel);
+ $this->assertSame('Apple', $record->manufacturer);
+ $this->assertNull($record->hostname);
+ $this->assertNull($record->os);
+ $this->assertSame('Mac', $record->extra['abm_product_family']);
+ $this->assertSame('Spaceblack', $record->extra['abm_color']);
+ $this->assertSame('W1234567', $record->extra['abm_order_number']);
+ $this->assertSame('2025-08-15', $record->extra['abm_order_date']);
+ $this->assertSame('AppleCustomer', $record->extra['abm_purchase_source_type']);
+ }
+
+ public function test_merges_mdm_server_name_from_linkages()
+ {
+ $adapter = $this->configuredAdapter();
+
+ Http::fake([
+ 'account.apple.com/*' => Http::response(['access_token' => 'stub-bearer']),
+ 'api-business.apple.com/v1/mdmServers' => Http::response([
+ 'data' => [
+ ['id' => 'server-A', 'attributes' => ['serverName' => 'Jamf Prod']],
+ ['id' => 'server-B', 'attributes' => ['serverName' => 'Kandji Loaner Fleet']],
+ ],
+ ]),
+ 'api-business.apple.com/v1/mdmServers/server-A/relationships/devices*' => Http::response([
+ 'data' => [['id' => 'device-1'], ['id' => 'device-2']],
+ ]),
+ 'api-business.apple.com/v1/mdmServers/server-B/relationships/devices*' => Http::response([
+ 'data' => [['id' => 'device-3']],
+ ]),
+ 'api-business.apple.com/v1/orgDevices*' => Http::response([
+ 'data' => [
+ ['id' => 'device-1', 'attributes' => ['serialNumber' => 'SN1', 'partNumber' => 'MK1', 'productFamily' => 'Mac']],
+ ['id' => 'device-3', 'attributes' => ['serialNumber' => 'SN3', 'partNumber' => 'MK3', 'productFamily' => 'iPhone']],
+ ['id' => 'device-99', 'attributes' => ['serialNumber' => 'SN99', 'partNumber' => 'MK99', 'productFamily' => 'iPad']],
+ ],
+ ]),
+ ]);
+
+ $records = iterator_to_array($adapter->pull());
+
+ $byId = collect($records)->keyBy('sourceId');
+ $this->assertSame('Jamf Prod', $byId['device-1']->extra['abm_mdm_server']);
+ $this->assertSame('Kandji Loaner Fleet', $byId['device-3']->extra['abm_mdm_server']);
+ $this->assertNull($byId['device-99']->extra['abm_mdm_server']);
+ }
+
+ public function test_school_mode_targets_school_host()
+ {
+ $adapter = $this->configuredAdapter('school');
+
+ Http::fake([
+ 'account.apple.com/*' => Http::response(['access_token' => 'stub-bearer']),
+ 'api-school.apple.com/v1/mdmServers' => Http::response(['data' => []]),
+ 'api-school.apple.com/v1/orgDevices*' => Http::response(['data' => []]),
+ ]);
+
+ iterator_to_array($adapter->pull());
+
+ Http::assertSent(fn ($request) => str_starts_with($request->url(), 'https://api-school.apple.com/'));
+ Http::assertNotSent(fn ($request) => str_starts_with($request->url(), 'https://api-business.apple.com/'));
+ }
+
+ public function test_token_exchange_sends_signed_jwt_client_assertion()
+ {
+ $adapter = $this->configuredAdapter();
+
+ Http::fake([
+ 'account.apple.com/*' => Http::response(['access_token' => 'stub-bearer']),
+ 'api-business.apple.com/*' => Http::response(['data' => []]),
+ ]);
+
+ iterator_to_array($adapter->pull());
+
+ Http::assertSent(function ($request) {
+ if (! str_contains($request->url(), 'account.apple.com')) {
+ return false;
+ }
+ $body = $request->body();
+ // Body is form-encoded; check the assertion fields are present
+ // and the JWT is well-formed (three base64url segments).
+ if (! str_contains($body, 'client_assertion_type=urn')) {
+ return false;
+ }
+ preg_match('/client_assertion=([^&]+)/', $body, $m);
+ if (! isset($m[1])) {
+ return false;
+ }
+ $parts = explode('.', urldecode($m[1]));
+
+ return count($parts) === 3;
+ });
+ }
+
+ public function test_product_family_filter_limits_pulled_devices()
+ {
+ $adapter = $this->configuredAdapter(productFamilies: 'Mac, iPad');
+
+ Http::fake([
+ 'account.apple.com/*' => Http::response(['access_token' => 'stub-bearer']),
+ 'api-business.apple.com/v1/mdmServers' => Http::response(['data' => []]),
+ 'api-business.apple.com/v1/orgDevices*' => Http::response([
+ 'data' => [
+ ['id' => 'g-mac', 'attributes' => ['serialNumber' => 'MACSN', 'partNumber' => 'MK1', 'productFamily' => 'Mac']],
+ ['id' => 'g-iphone', 'attributes' => ['serialNumber' => 'IPSN', 'partNumber' => 'IP1', 'productFamily' => 'iPhone']],
+ ['id' => 'g-ipad', 'attributes' => ['serialNumber' => 'IPADSN', 'partNumber' => 'IPD1', 'productFamily' => 'iPad']],
+ ['id' => 'g-watch', 'attributes' => ['serialNumber' => 'WSN', 'partNumber' => 'WT1', 'productFamily' => 'Watch']],
+ ],
+ ]),
+ ]);
+
+ $records = iterator_to_array($adapter->pull());
+ $ids = array_map(fn ($r) => $r->sourceId, $records);
+ sort($ids);
+ $this->assertSame(['g-ipad', 'g-mac'], $ids);
+ }
+
+ public function test_product_family_filter_is_case_insensitive()
+ {
+ $adapter = $this->configuredAdapter(productFamilies: 'MAC');
+
+ Http::fake([
+ 'account.apple.com/*' => Http::response(['access_token' => 'stub-bearer']),
+ 'api-business.apple.com/v1/mdmServers' => Http::response(['data' => []]),
+ 'api-business.apple.com/v1/orgDevices*' => Http::response([
+ 'data' => [
+ ['id' => 'g-mac', 'attributes' => ['serialNumber' => 'S1', 'partNumber' => 'M1', 'productFamily' => 'Mac']],
+ ['id' => 'g-phone', 'attributes' => ['serialNumber' => 'S2', 'partNumber' => 'P1', 'productFamily' => 'iPhone']],
+ ],
+ ]),
+ ]);
+
+ $records = iterator_to_array($adapter->pull());
+ $this->assertCount(1, $records);
+ $this->assertSame('g-mac', $records[0]->sourceId);
+ }
+
+ public function test_blank_product_family_filter_passes_every_device_through()
+ {
+ $adapter = $this->configuredAdapter(productFamilies: '');
+
+ Http::fake([
+ 'account.apple.com/*' => Http::response(['access_token' => 'stub-bearer']),
+ 'api-business.apple.com/v1/mdmServers' => Http::response(['data' => []]),
+ 'api-business.apple.com/v1/orgDevices*' => Http::response([
+ 'data' => [
+ ['id' => 'g-1', 'attributes' => ['serialNumber' => 'S1', 'partNumber' => 'P1', 'productFamily' => 'Mac']],
+ ['id' => 'g-2', 'attributes' => ['serialNumber' => 'S2', 'partNumber' => 'P2', 'productFamily' => 'iPhone']],
+ ['id' => 'g-3', 'attributes' => ['serialNumber' => 'S3', 'partNumber' => 'P3', 'productFamily' => 'Vision']],
+ ],
+ ]),
+ ]);
+
+ $records = iterator_to_array($adapter->pull());
+ $this->assertCount(3, $records);
+ }
+
+ public function test_saveconfig_clears_family_filter_on_blank_submit()
+ {
+ $adapter = $this->configuredAdapter(productFamilies: 'Mac,iPhone');
+
+ // Simulate an admin re-saving the form with an empty filter
+ // to switch back to "sync every family."
+ $request = \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);
+ }
+
+ public function test_survives_mdm_server_map_failure_and_still_yields_records()
+ {
+ $adapter = $this->configuredAdapter();
+
+ Http::fake([
+ 'account.apple.com/*' => Http::response(['access_token' => 'stub-bearer']),
+ 'api-business.apple.com/v1/mdmServers' => Http::response(['error' => 'boom'], 500),
+ 'api-business.apple.com/v1/orgDevices*' => Http::response([
+ 'data' => [
+ ['id' => 'guid-x', 'attributes' => ['serialNumber' => 'SNX', 'partNumber' => 'MKX', 'productFamily' => 'Mac']],
+ ],
+ ]),
+ ]);
+
+ $records = iterator_to_array($adapter->pull());
+
+ // Record still comes through; mdm_server just null.
+ $this->assertCount(1, $records);
+ $this->assertNull($records[0]->extra['abm_mdm_server']);
+ }
+
+ private function configuredAdapter(string $mode = 'business', ?string $productFamilies = null): AppleBusinessManagerAdapter
+ {
+ $instance = SyncAdapterInstance::where('slug', 'apple_business_manager')->firstOrFail();
+ SyncAdapterConfig::put($instance->id, 'mode', $mode);
+ SyncAdapterConfig::put($instance->id, 'client_id', 'stub-client-id');
+ SyncAdapterConfig::put($instance->id, 'key_id', 'stub-key-id');
+ SyncAdapterConfig::put($instance->id, 'private_key', Crypt::encrypt($this->privateKeyPem));
+ if ($productFamilies !== null) {
+ SyncAdapterConfig::put($instance->id, 'product_family_filter', $productFamilies);
+ }
+
+ return new AppleBusinessManagerAdapter($instance->fresh());
+ }
+}
diff --git a/tests/Feature/SyncAdapters/AppleBusinessManager/AppleCareEnrichmentTest.php b/tests/Feature/SyncAdapters/AppleBusinessManager/AppleCareEnrichmentTest.php
new file mode 100644
index 0000000000..baf2f12c4f
--- /dev/null
+++ b/tests/Feature/SyncAdapters/AppleBusinessManager/AppleCareEnrichmentTest.php
@@ -0,0 +1,284 @@
+<?php
+
+namespace Tests\Feature\SyncAdapters\AppleBusinessManager;
+
+use App\Models\CustomField;
+use App\Models\Statuslabel;
+use App\Models\SyncAdapterConfig;
+use App\Models\SyncAdapterInstance;
+use App\SyncAdapters\AppleBusinessManager\AppleBusinessManagerAdapter;
+use Illuminate\Support\Facades\Crypt;
+use Illuminate\Support\Facades\Http;
+use Tests\TestCase;
+
+/**
+ * Coverage for the ABM AppleCare enrichment path. Fetching AppleCare
+ * per device adds an API call per asset, so we gate it on at least one
+ * AppleCare extra being mapped to a target. Additional coverage:
+ * - the ACTIVE > PAID_UP_FRONT > later-end selection order
+ * - failure survival (transient AppleCare outage still yields a record)
+ * - date normalization to YYYY-MM-DD
+ */
+class AppleCareEnrichmentTest 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',
+ ]);
+ openssl_pkey_export($key, $pem);
+ $this->privateKeyPem = $pem;
+ }
+
+ public function test_pull_enriches_with_applecare_when_a_field_is_mapped()
+ {
+ $customField = CustomField::factory()->create(['element' => 'text', 'name' => 'Warranty End']);
+ $adapter = $this->configuredAdapter();
+
+ $instance = SyncAdapterInstance::where('slug', 'apple_business_manager')->firstOrFail();
+ SyncAdapterConfig::put($instance->id, 'mapping.abm_applecare_end_date', 'custom:'.$customField->id);
+
+ Http::fake([
+ 'account.apple.com/*' => Http::response(['access_token' => 'stub-bearer']),
+ 'api-business.apple.com/v1/mdmServers' => Http::response(['data' => []]),
+ 'api-business.apple.com/v1/orgDevices/abm-guid-a/appleCareCoverage' => Http::response([
+ 'data' => [[
+ 'id' => 'ac-1',
+ 'type' => 'appleCareCoverage',
+ 'attributes' => [
+ 'agreementNumber' => 'AC-987',
+ 'status' => 'ACTIVE',
+ 'paymentType' => 'PAID_UP_FRONT',
+ 'startDateTime' => '2025-08-15T14:22:00Z',
+ 'endDateTime' => '2028-08-15T14:22:00Z',
+ 'description' => 'AppleCare+ for MacBook Pro',
+ 'isCanceled' => false,
+ 'isRenewable' => true,
+ ],
+ ]],
+ ]),
+ 'api-business.apple.com/v1/orgDevices*' => Http::response([
+ 'data' => [$this->minimalAbmDevice('abm-guid-a')],
+ ]),
+ ]);
+
+ $record = iterator_to_array($adapter->pull())[0];
+
+ $this->assertSame('AC-987', $record->extra['abm_applecare_agreement_number']);
+ $this->assertSame('Active', $record->extra['abm_applecare_status']);
+ $this->assertSame('Paid_up_front', $record->extra['abm_applecare_payment_type']);
+ $this->assertSame('2025-08-15', $record->extra['abm_applecare_start_date']);
+ $this->assertSame('2028-08-15', $record->extra['abm_applecare_end_date']);
+ $this->assertSame('AppleCare+ for MacBook Pro', $record->extra['abm_applecare_description']);
+ $this->assertFalse($record->extra['abm_applecare_is_canceled']);
+ $this->assertTrue($record->extra['abm_applecare_is_renewable']);
+ }
+
+ public function test_pull_skips_applecare_fetch_when_no_field_is_mapped()
+ {
+ $adapter = $this->configuredAdapter();
+
+ 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/*/appleCareCoverage' => Http::response(
+ ['error' => 'unreachable'],
+ 500,
+ ),
+ 'api-business.apple.com/v1/orgDevices*' => Http::response([
+ 'data' => [$this->minimalAbmDevice('abm-guid-b')],
+ ]),
+ ]);
+
+ iterator_to_array($adapter->pull());
+
+ Http::assertNotSent(fn ($request) => str_contains($request->url(), '/appleCareCoverage'));
+ }
+
+ public function test_pull_selects_active_over_inactive_coverage()
+ {
+ $customField = CustomField::factory()->create(['element' => 'text', 'name' => 'Warranty']);
+ $adapter = $this->configuredAdapter();
+
+ $instance = SyncAdapterInstance::where('slug', 'apple_business_manager')->firstOrFail();
+ SyncAdapterConfig::put($instance->id, 'mapping.abm_applecare_agreement_number', 'custom:'.$customField->id);
+
+ Http::fake([
+ 'account.apple.com/*' => Http::response(['access_token' => 'stub-bearer']),
+ 'api-business.apple.com/v1/mdmServers' => Http::response(['data' => []]),
+ 'api-business.apple.com/v1/orgDevices/dev-1/appleCareCoverage' => Http::response([
+ 'data' => [
+ ['attributes' => [
+ 'agreementNumber' => 'INACTIVE-EXPIRED',
+ 'status' => 'INACTIVE',
+ 'paymentType' => 'PAID_UP_FRONT',
+ 'endDateTime' => '2030-01-01T00:00:00Z',
+ ]],
+ ['attributes' => [
+ 'agreementNumber' => 'ACTIVE-WINS',
+ 'status' => 'ACTIVE',
+ 'paymentType' => 'SUBSCRIPTION',
+ 'endDateTime' => '2026-01-01T00:00:00Z',
+ ]],
+ ],
+ ]),
+ 'api-business.apple.com/v1/orgDevices*' => Http::response([
+ 'data' => [$this->minimalAbmDevice('dev-1')],
+ ]),
+ ]);
+
+ $record = iterator_to_array($adapter->pull())[0];
+ // Active wins over inactive even though inactive has a
+ // later end date and a paid-up-front payment.
+ $this->assertSame('ACTIVE-WINS', $record->extra['abm_applecare_agreement_number']);
+ }
+
+ public function test_pull_prefers_paid_up_front_when_both_active()
+ {
+ $customField = CustomField::factory()->create(['element' => 'text', 'name' => 'Warranty']);
+ $adapter = $this->configuredAdapter();
+
+ $instance = SyncAdapterInstance::where('slug', 'apple_business_manager')->firstOrFail();
+ SyncAdapterConfig::put($instance->id, 'mapping.abm_applecare_agreement_number', 'custom:'.$customField->id);
+
+ Http::fake([
+ 'account.apple.com/*' => Http::response(['access_token' => 'stub-bearer']),
+ 'api-business.apple.com/v1/mdmServers' => Http::response(['data' => []]),
+ 'api-business.apple.com/v1/orgDevices/dev-2/appleCareCoverage' => Http::response([
+ 'data' => [
+ ['attributes' => [
+ 'agreementNumber' => 'SUB-1',
+ 'status' => 'ACTIVE',
+ 'paymentType' => 'SUBSCRIPTION',
+ 'endDateTime' => '2030-01-01T00:00:00Z',
+ ]],
+ ['attributes' => [
+ 'agreementNumber' => 'PAID-WINS',
+ 'status' => 'ACTIVE',
+ 'paymentType' => 'PAID_UP_FRONT',
+ 'endDateTime' => '2027-01-01T00:00:00Z',
+ ]],
+ ],
+ ]),
+ 'api-business.apple.com/v1/orgDevices*' => Http::response([
+ 'data' => [$this->minimalAbmDevice('dev-2')],
+ ]),
+ ]);
+
+ $record = iterator_to_array($adapter->pull())[0];
+ $this->assertSame('PAID-WINS', $record->extra['abm_applecare_agreement_number']);
+ }
+
+ public function test_pull_falls_through_to_later_end_date_when_active_and_payment_tie()
+ {
+ $customField = CustomField::factory()->create(['element' => 'text', 'name' => 'Warranty']);
+ $adapter = $this->configuredAdapter();
+
+ $instance = SyncAdapterInstance::where('slug', 'apple_business_manager')->firstOrFail();
+ SyncAdapterConfig::put($instance->id, 'mapping.abm_applecare_agreement_number', 'custom:'.$customField->id);
+
+ Http::fake([
+ 'account.apple.com/*' => Http::response(['access_token' => 'stub-bearer']),
+ 'api-business.apple.com/v1/mdmServers' => Http::response(['data' => []]),
+ 'api-business.apple.com/v1/orgDevices/dev-3/appleCareCoverage' => Http::response([
+ 'data' => [
+ ['attributes' => [
+ 'agreementNumber' => 'EARLY',
+ 'status' => 'ACTIVE',
+ 'paymentType' => 'PAID_UP_FRONT',
+ 'endDateTime' => '2026-01-01T00:00:00Z',
+ ]],
+ ['attributes' => [
+ 'agreementNumber' => 'LATE-WINS',
+ 'status' => 'ACTIVE',
+ 'paymentType' => 'PAID_UP_FRONT',
+ 'endDateTime' => '2029-06-15T00:00:00Z',
+ ]],
+ ],
+ ]),
+ 'api-business.apple.com/v1/orgDevices*' => Http::response([
+ 'data' => [$this->minimalAbmDevice('dev-3')],
+ ]),
+ ]);
+
+ $record = iterator_to_array($adapter->pull())[0];
+ $this->assertSame('LATE-WINS', $record->extra['abm_applecare_agreement_number']);
+ }
+
+ public function test_pull_survives_applecare_endpoint_failure()
+ {
+ $customField = CustomField::factory()->create(['element' => 'text', 'name' => 'Warranty']);
+ $adapter = $this->configuredAdapter();
+
+ $instance = SyncAdapterInstance::where('slug', 'apple_business_manager')->firstOrFail();
+ SyncAdapterConfig::put($instance->id, 'mapping.abm_applecare_end_date', 'custom:'.$customField->id);
+
+ Http::fake([
+ 'account.apple.com/*' => Http::response(['access_token' => 'stub-bearer']),
+ 'api-business.apple.com/v1/mdmServers' => Http::response(['data' => []]),
+ 'api-business.apple.com/v1/orgDevices/*/appleCareCoverage' => Http::response(['error' => 'boom'], 503),
+ 'api-business.apple.com/v1/orgDevices*' => Http::response([
+ 'data' => [$this->minimalAbmDevice('dev-fail')],
+ ]),
+ ]);
+
+ $records = iterator_to_array($adapter->pull());
+
+ // Record still yields; the applecare fields just stay absent.
+ $this->assertCount(1, $records);
+ $this->assertArrayNotHasKey('abm_applecare_end_date', $records[0]->extra);
+ }
+
+ public function test_empty_applecare_data_leaves_extras_untouched()
+ {
+ $customField = CustomField::factory()->create(['element' => 'text', 'name' => 'Warranty']);
+ $adapter = $this->configuredAdapter();
+
+ $instance = SyncAdapterInstance::where('slug', 'apple_business_manager')->firstOrFail();
+ SyncAdapterConfig::put($instance->id, 'mapping.abm_applecare_end_date', 'custom:'.$customField->id);
+
+ Http::fake([
+ 'account.apple.com/*' => Http::response(['access_token' => 'stub-bearer']),
+ 'api-business.apple.com/v1/mdmServers' => Http::response(['data' => []]),
+ 'api-business.apple.com/v1/orgDevices/*/appleCareCoverage' => Http::response(['data' => []]),
+ 'api-business.apple.com/v1/orgDevices*' => Http::response([
+ 'data' => [$this->minimalAbmDevice('dev-no-ac')],
+ ]),
+ ]);
+
+ $record = iterator_to_array($adapter->pull())[0];
+ $this->assertArrayNotHasKey('abm_applecare_end_date', $record->extra);
+ }
+
+ private function configuredAdapter(): 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));
+
+ return new AppleBusinessManagerAdapter($instance->fresh());
+ }
+
+ /**
+ * @return array<string, mixed>
+ */
+ private function minimalAbmDevice(string $id): array
+ {
+ return [
+ 'id' => $id,
+ 'attributes' => [
+ 'serialNumber' => 'SN-'.$id,
+ 'partNumber' => 'MK1E3LL/A',
+ 'productFamily' => 'Mac',
+ ],
+ ];
+ }
+}