A free open source IT asset/license management system
Only override push payload when we need to (multi-endpoint adapters)
snipeb3beba47a186
diff --git a/app/SyncAdapters/CustomHttp/CustomHttpAdapter.php b/app/SyncAdapters/CustomHttp/CustomHttpAdapter.phpindex 0b566dba9e..d7da0953dd 100644--- a/app/SyncAdapters/CustomHttp/CustomHttpAdapter.php+++ b/app/SyncAdapters/CustomHttp/CustomHttpAdapter.php@@ -476,7 +476,7 @@ class CustomHttpAdapter extends SyncAdapter implements PushableAdapter** @return array{0: array<string, mixed>, 1: array<int, string>}*/- private function buildPushPayload(Asset $asset): array+ protected function buildPushPayload(Asset $asset): array{$payload = [];$touched = [];diff --git a/app/SyncAdapters/Jamf/JamfAdapter.php b/app/SyncAdapters/Jamf/JamfAdapter.phpindex 932b421fd7..3ae69e1eb9 100644--- a/app/SyncAdapters/Jamf/JamfAdapter.php+++ b/app/SyncAdapters/Jamf/JamfAdapter.php@@ -8,7 +8,6 @@ use App\SyncAdapters\PushableAdapter;use App\SyncAdapters\SyncAdapter;use Carbon\Carbon;use Illuminate\Support\Arr;-use Illuminate\Support\Facades\Log;/*** Jamf Pro adapter. Pulls computer inventory via the Jamf Pro API and@@ -168,11 +167,14 @@ class JamfAdapter extends SyncAdapter implements PushableAdapter*/public function push(Asset $asset, array $changedFields = []): bool{- $externalSource = $this->pushPrologue($asset, $changedFields);- if ($externalSource === null) {- return false;- }+ return $this->pushViaSinglePayload($asset, $changedFields);+ }+ /**+ * @return array{0: array<string, mixed>, 1: array<int, string>}+ */+ protected function buildPushPayload(Asset $asset): array+ {$payload = [];$touched = [];foreach ($this->pushDirectedFields() as $field) {@@ -190,34 +192,16 @@ class JamfAdapter extends SyncAdapter implements PushableAdapter$touched[] = $path;}- $this->applyComposedNotesToPayload($asset, $payload, $touched);-- if ($payload === []) {- return false;- }-- if ($this->isPushDryRun()) {- Log::channel('sync-adapters')->info(sprintf(- '%s push [dry-run]: would PATCH Jamf computer %s with %s',- $this->name(),- $externalSource->external_id,- json_encode($payload, JSON_UNESCAPED_SLASHES),- ));-- return true;- }+ return [$payload, $touched];+ }+ /**+ * @param array<string, mixed> $payload+ */+ protected function dispatchPush(\App\Models\AssetExternalSource $externalSource, array $payload): void+ {$client = new JamfClient(baseUrl: $this->url(), token: $this->credential('token'));$client->updateComputerDetail($externalSource->external_id, $payload);-- Log::channel('sync-adapters')->info(sprintf(- '%s push: updated Jamf computer %s at paths [%s]',- $this->name(),- $externalSource->external_id,- implode(', ', $touched),- ));-- return true;}/**diff --git a/app/SyncAdapters/Kandji/KandjiAdapter.php b/app/SyncAdapters/Kandji/KandjiAdapter.phpindex 1981c8d82d..4c688d3007 100644--- a/app/SyncAdapters/Kandji/KandjiAdapter.php+++ b/app/SyncAdapters/Kandji/KandjiAdapter.php@@ -161,25 +161,24 @@ class KandjiAdapter extends SyncAdapter implements PushableAdapter}/**- * Push Snipe-IT-authoritative fields to the vendor. Filters the- * asset's fields down to those marked 'push' in the mapping table- * for this instance, serializes them into Kandji's field-name- * shape, and PATCHes the device.- *- * Silently no-ops when the asset has never been synced from this- * instance (no asset_external_sources row -> no vendor device id- * to write against) or when nothing on the mapping is directed- * 'push'.+ * Push Snipe-IT-authoritative fields to Kandji. Delegates to the+ * base template, which runs the prologue guards, splices composed+ * notes, handles the dry-run branch, and writes the success log+ * line. Kandji provides the vendor-shape payload and the vendor+ * dispatch call via the two hooks below.** @param array<int, string> $changedFields*/public function push(Asset $asset, array $changedFields = []): bool{- $externalSource = $this->pushPrologue($asset, $changedFields);- if ($externalSource === null) {- return false;- }+ return $this->pushViaSinglePayload($asset, $changedFields);+ }+ /**+ * @return array{0: array<string, mixed>, 1: array<int, string>}+ */+ protected function buildPushPayload(Asset $asset): array+ {$payload = [];foreach ($this->pushDirectedFields() as $field) {$mapped = self::sourceFieldToKandjiField($field);@@ -195,43 +194,16 @@ class KandjiAdapter extends SyncAdapter implements PushableAdapter$payload[$mapped] = $value;}- // Composed notes merge into the same payload so admins can- // push both an asset_tag AND a composed notes blob in a- // single API call.- $this->applyComposedNotesToPayload($asset, $payload);-- if ($payload === []) {- return false;- }-- // Dry-run: log the payload we WOULD send and return without- // hitting Kandji. Lets admins verify their config end-to-end- // (mapping resolution, direction, credential wiring, external_id- // lookup) without a real API call. Dry-run counts as a push- // attempt from the controller's POV so the flash reflects- // that admins actually did the thing they clicked.- if ($this->isPushDryRun()) {- Log::channel('sync-adapters')->info(sprintf(- '%s push [dry-run]: would PATCH Kandji device %s with %s',- $this->name(),- $externalSource->external_id,- json_encode($payload, JSON_UNESCAPED_SLASHES),- ));-- return true;- }+ return [$payload, []];+ }+ /**+ * @param array<string, mixed> $payload+ */+ protected function dispatchPush(\App\Models\AssetExternalSource $externalSource, array $payload): void+ {$client = new KandjiClient(baseUrl: $this->url(), token: $this->credential('token'));$client->updateDevice($externalSource->external_id, $payload);-- Log::channel('sync-adapters')->info(sprintf(- '%s push: updated Kandji device %s with fields [%s]',- $this->name(),- $externalSource->external_id,- implode(', ', array_keys($payload)),- ));-- return true;}/**diff --git a/app/SyncAdapters/NinjaOne/NinjaOneAdapter.php b/app/SyncAdapters/NinjaOne/NinjaOneAdapter.phpindex 077f4915c2..38b58ce38d 100644--- a/app/SyncAdapters/NinjaOne/NinjaOneAdapter.php+++ b/app/SyncAdapters/NinjaOne/NinjaOneAdapter.php@@ -177,19 +177,23 @@ class NinjaOneAdapter extends SyncAdapter implements PushableAdapter* doesn't expose a top-level asset_tag column, so the admin must* pre-create a custom field in the NinjaOne dashboard and put its* name in the "Asset Tag Custom Field Name" schema slot. If the- * slot is blank, push silently no-ops (nothing to write to).- * If the slot has a name but no such field exists in NinjaOne,- * NinjaOne returns a 4xx and the error surfaces in the log.+ * slot is blank, buildPushPayload returns empty and the template+ * short-circuits. If the slot has a name but no such field exists+ * in NinjaOne, NinjaOne returns a 4xx and the error surfaces via+ * the controller's outer catch.** @param array<int, string> $changedFields*/public function push(Asset $asset, array $changedFields = []): bool{- $externalSource = $this->pushPrologue($asset, $changedFields);- if ($externalSource === null) {- return false;- }+ return $this->pushViaSinglePayload($asset, $changedFields);+ }+ /**+ * @return array{0: array<string, mixed>, 1: array<int, string>}+ */+ protected function buildPushPayload(Asset $asset): array+ {$customFieldName = $this->credentialOrNull('asset_tag_custom_field');if ($customFieldName === null || $customFieldName === '') {Log::channel('sync-adapters')->info(sprintf(@@ -198,66 +202,31 @@ class NinjaOneAdapter extends SyncAdapter implements PushableAdapter$asset->id,));- return false;+ return [[], []];}- $payload = $this->buildCustomFieldPayload($asset, $customFieldName);- if ($payload === []) {- return false;+ $payload = [];+ $value = in_array('asset_tag', $this->pushDirectedFields(), true)+ ? $this->assetValueForSourceField($asset, 'asset_tag')+ : null;+ if ($value !== null && $value !== '') {+ $payload[$customFieldName] = $value;}- if ($this->isPushDryRun()) {- Log::channel('sync-adapters')->info(sprintf(- '%s push [dry-run]: would PATCH Ninja device %s custom-fields %s',- $this->name(),- $externalSource->external_id,- json_encode($payload, JSON_UNESCAPED_SLASHES),- ));-- return true;- }+ return [$payload, []];+ }+ /**+ * @param array<string, mixed> $payload+ */+ protected function dispatchPush(\App\Models\AssetExternalSource $externalSource, array $payload): void+ {$client = new NinjaOneClient(baseUrl: $this->url(),clientId: $this->credential('client_id'),clientSecret: $this->credential('client_secret'),);$client->updateDeviceCustomFields($externalSource->external_id, $payload);-- Log::channel('sync-adapters')->info(sprintf(- '%s push: updated Ninja device %s custom field "%s"',- $this->name(),- $externalSource->external_id,- $customFieldName,- ));-- return true;- }-- /**- * Assemble the /custom-fields PATCH payload. Ninja accepts- * multiple field name / value pairs in one request, so asset_tag- * and the composed-notes target get merged when both are- * configured. Admin sets the notes-target field via the composed-- * notes fieldset override. Nothing is defaulted because Ninja- * has no built-in notes concept for us to guess.- *- * @return array<string, mixed>- */- private function buildCustomFieldPayload(Asset $asset, string $assetTagFieldName): array- {- $payload = [];-- $value = in_array('asset_tag', $this->pushDirectedFields(), true)- ? $this->assetValueForSourceField($asset, 'asset_tag')- : null;- if ($value !== null && $value !== '') {- $payload[$assetTagFieldName] = $value;- }-- $this->applyComposedNotesToPayload($asset, $payload);-- return $payload;}/**diff --git a/app/SyncAdapters/SyncAdapter.php b/app/SyncAdapters/SyncAdapter.phpindex ae09f65f6c..960daaeaac 100644--- a/app/SyncAdapters/SyncAdapter.php+++ b/app/SyncAdapters/SyncAdapter.php@@ -840,6 +840,96 @@ abstract class SyncAdapter};}+ /**+ * Standard push() implementation for single-endpoint adapters. An+ * adapter whose push() writes one payload to one endpoint (Kandji,+ * Jamf, NinjaOne) overrides two hooks (buildPushPayload,+ * dispatchPush) and delegates push() to this template.+ *+ * Adapters with split-endpoint pushes (Mosyle posts asset_tag and+ * notes to separate operations, Workspace ONE splits device fields+ * from Custom Attributes) implement push() directly and don't call+ * this. CustomHttp also implements push() directly because its+ * dry-run log and dispatch depend on admin-configured HTTP method+ * and endpoint that the template can't parameterize.+ *+ * Success and dry-run log lines use typeLabel() plus the flat+ * $touched list (falling back to array_keys($payload) when the+ * adapter builds a flat-keyed payload and doesn't populate+ * $touched). Adapters wanting vendor-specific log wording override+ * push() directly instead of using the template.+ *+ * @param array<int, string> $changedFields+ */+ protected function pushViaSinglePayload(Asset $asset, array $changedFields): bool+ {+ $externalSource = $this->pushPrologue($asset, $changedFields);+ if ($externalSource === null) {+ return false;+ }++ [$payload, $touched] = $this->buildPushPayload($asset);+ $this->applyComposedNotesToPayload($asset, $payload, $touched);++ if ($payload === []) {+ return false;+ }++ $written = $touched !== [] ? $touched : array_keys($payload);++ if ($this->isPushDryRun()) {+ \Illuminate\Support\Facades\Log::channel('sync-adapters')->info(sprintf(+ '%s push [dry-run]: would send %s to %s device %s',+ $this->name(),+ json_encode($payload, JSON_UNESCAPED_SLASHES),+ static::typeLabel(),+ $externalSource->external_id,+ ));++ return true;+ }++ $this->dispatchPush($externalSource, $payload);++ \Illuminate\Support\Facades\Log::channel('sync-adapters')->info(sprintf(+ '%s push: updated %s device %s [%s]',+ $this->name(),+ static::typeLabel(),+ $externalSource->external_id,+ implode(', ', $written),+ ));++ return true;+ }++ /**+ * Build the outgoing vendor payload for pushViaSinglePayload().+ * Adapters that call pushViaSinglePayload() override this to+ * return their payload and the flat list of dot-paths / keys that+ * were written (for the post-push audit log). Empty payload signals+ * "nothing to send" and the template short-circuits.+ *+ * @return array{0: array<string, mixed>, 1: array<int, string>}+ */+ protected function buildPushPayload(Asset $asset): array+ {+ throw new \LogicException(static::class.' calls pushViaSinglePayload() but does not override buildPushPayload().');+ }++ /**+ * Fire the vendor HTTP call for pushViaSinglePayload(). Adapters+ * that call pushViaSinglePayload() override this. Failures throw+ * (the outer controller catches and renders a red-flash summary,+ * matching the pull path). No return value: presence of the call+ * is enough, the template logs success on its own.+ *+ * @param array<string, mixed> $payload+ */+ protected function dispatchPush(\App\Models\AssetExternalSource $externalSource, array $payload): void+ {+ throw new \LogicException(static::class.' calls pushViaSinglePayload() but does not override dispatchPush().');+ }+/*** Shared prologue for every PushableAdapter::push() implementation.* Runs the three identical guards each adapter's push() started withdiff --git a/tests/Feature/SyncAdapters/CustomHttp/CustomHttpAdapterTest.php b/tests/Feature/SyncAdapters/CustomHttp/CustomHttpAdapterTest.phpindex 22d48455b7..6c78b0b751 100644--- a/tests/Feature/SyncAdapters/CustomHttp/CustomHttpAdapterTest.php+++ b/tests/Feature/SyncAdapters/CustomHttp/CustomHttpAdapterTest.php@@ -400,19 +400,23 @@ class CustomHttpAdapterTest extends TestCase$this->assertSame(1, $callCount, 'None-style must issue exactly one HTTP call.');}- public function test_http_failure_fails_soft_and_yields_nothing()- {- // Vendor 500 must not crash the sync run. Adapter logs a- // warning and returns an empty iterable so the framework's- // orchestrator moves on.+ public function test_http_failure_propagates_so_controller_shows_error()+ {+ // Vendor 5xx / auth failure must propagate rather than get+ // swallowed. Prior behavior returned an empty iterable, which+ // the controller flashed as a warm-fuzzy "Synced 0 host(s), 0+ // error(s)" success. Now the exception bubbles to the+ // controller's outer catch, which flashes a red error with+ // the sanitized vendor summary.$adapter = $this->configuredAdapter(['field_source_id' => 'id',]);Http::fake(['vendor.example/*' => Http::response(['error' => 'boom'], 500)]);- $records = iterator_to_array($adapter->pull());- $this->assertSame([], $records);+ $this->expectException(\Illuminate\Http\Client\RequestException::class);++ iterator_to_array($adapter->pull());}public function test_malformed_extras_json_is_ignored()