Skip to content

A free open source IT asset/license management system

Improved custom http adapter UI field mapping, adding more logging

snipe1c10186a648f
diff --git a/app/Console/Commands/PullInventory.php b/app/Console/Commands/PullInventory.php
index 009c1fce1d..5c4bd0aca5 100644
--- a/app/Console/Commands/PullInventory.php
+++ b/app/Console/Commands/PullInventory.php
@@ -5,6 +5,7 @@ namespace App\Console\Commands;
use App\Models\SyncAdapterInstance;
use App\SyncAdapters\SyncAdapter;
use Illuminate\Console\Command;
+use Illuminate\Support\Facades\Log;
use Throwable;
class PullInventory extends Command
@@ -111,18 +112,21 @@ class PullInventory extends Command
$seen = 0;
$errors = 0;
+ Log::channel('sync-adapters')->info("{$slug} sync starting (CLI)");
+
try {
foreach ($adapter->pull() as $record) {
try {
SyncAdapter::syncFromRecord($record);
$seen++;
} catch (Throwable $e) {
- // A single bad record shouldn't take down the run.
- // Log the offending host and keep going.
$errors++;
$sourceId = $record->sourceId;
$message = $e->getMessage();
+ // A single bad record shouldn't take down the run.
+ // Log the offending host and keep going.
$this->warn("Failed to sync host {$sourceId}: {$message}");
+ Log::channel('sync-adapters')->warning("{$slug} sync: failed to upsert host {$sourceId}: {$message}");
}
}
} catch (Throwable $e) {
@@ -134,6 +138,9 @@ class PullInventory extends Command
$elapsed = self::formatElapsed($startedAt);
$this->error("{$slug} {$abortSummary} ({$elapsed})");
+ Log::channel('sync-adapters')->warning("{$slug} sync aborted after {$seen} record(s), {$errors} error(s), elapsed {$elapsed}: {$message}", [
+ 'exception' => $e,
+ ]);
$rows[] = [$slug, 'Aborted', $seen, $errors, $elapsed];
return self::FAILURE;
@@ -149,8 +156,11 @@ class PullInventory extends Command
$instance->last_sync_result = $result;
$instance->save();
+ $elapsed = self::formatElapsed($startedAt);
+ Log::channel('sync-adapters')->info("{$slug} sync complete: {$seen} record(s) processed, {$errors} error(s), elapsed {$elapsed}");
+
$status = $errors > 0 ? 'Errors' : 'OK';
- $rows[] = [$slug, $status, $seen, $errors, self::formatElapsed($startedAt)];
+ $rows[] = [$slug, $status, $seen, $errors, $elapsed];
return $errors > 0 ? self::FAILURE : self::SUCCESS;
}
diff --git a/app/Http/Controllers/SettingsController.php b/app/Http/Controllers/SettingsController.php
index e93f9a8de7..25ffe4258a 100644
--- a/app/Http/Controllers/SettingsController.php
+++ b/app/Http/Controllers/SettingsController.php
@@ -680,7 +680,7 @@ class SettingsController extends Controller
}
}
- if (!$wasLabel2Enabled && $request->boolean('label2_enable')) {
+ if (! $wasLabel2Enabled && $request->boolean('label2_enable')) {
$setting->label2_title = $setting->qr_text;
}
@@ -1099,6 +1099,9 @@ class SettingsController extends Controller
$seen = 0;
$errors = 0;
+ $startedAt = microtime(true);
+
+ Log::channel('sync-adapters')->info("{$instance->slug} sync starting (UI)");
try {
foreach ($adapter->pull() as $record) {
@@ -1107,7 +1110,7 @@ class SettingsController extends Controller
$seen++;
} catch (\Throwable $e) {
$errors++;
- \Log::channel('sync-adapters')->warning(sprintf(
+ Log::channel('sync-adapters')->warning(sprintf(
'%s sync: failed to upsert host %s: %s',
$instance->slug,
$record->sourceId,
@@ -1124,7 +1127,7 @@ class SettingsController extends Controller
// message on 4xx/5xx, and internal error pages regularly
// contain sensitive info we don't want to bounce into the
// admin's browser.
- \Log::channel('sync-adapters')->warning(sprintf('%s sync aborted: %s', $instance->slug, $e->getMessage()), [
+ Log::channel('sync-adapters')->warning(sprintf('%s sync aborted: %s', $instance->slug, $e->getMessage()), [
'exception' => $e,
]);
@@ -1147,6 +1150,9 @@ class SettingsController extends Controller
$instance->last_sync_result = $result;
$instance->save();
+ $elapsed = number_format(microtime(true) - $startedAt, 1);
+ Log::channel('sync-adapters')->info("{$instance->slug} sync complete: {$seen} record(s) processed, {$errors} error(s), elapsed {$elapsed}s");
+
// at least one seen, no errors -> success (green)
// at least one seen, some errors -> warning (orange, admin should check log)
// nothing seen at all, at least one error -> error (red)
@@ -1243,7 +1249,7 @@ class SettingsController extends Controller
? mb_substr($body, 0, 2048).'…'
: $body;
}
- \Log::channel('sync-adapters')->warning(sprintf(
+ Log::channel('sync-adapters')->warning(sprintf(
'%s push: asset %d failed: %s',
$row->source,
$asset->id,
@@ -1253,7 +1259,7 @@ class SettingsController extends Controller
}
});
} catch (\Throwable $e) {
- \Log::channel('sync-adapters')->warning(
+ Log::channel('sync-adapters')->warning(
sprintf('%s push aborted: %s', $instance->slug, $e->getMessage()),
['exception' => $e],
);
@@ -1464,7 +1470,7 @@ class SettingsController extends Controller
try {
$groups = $adapter->fetchGroups();
} catch (\Throwable $e) {
- \Log::channel('sync-adapters')->warning(
+ Log::channel('sync-adapters')->warning(
sprintf('%s refresh-groups aborted: %s', $instance->slug, $e->getMessage()),
['exception' => $e],
);
@@ -1515,7 +1521,7 @@ class SettingsController extends Controller
try {
$fields = $adapter->fetchVendorCustomFields();
} catch (\Throwable $e) {
- \Log::channel('sync-adapters')->warning(
+ Log::channel('sync-adapters')->warning(
sprintf('%s refresh-custom-fields aborted: %s', $instance->slug, $e->getMessage()),
['exception' => $e],
);
diff --git a/app/Rules/CustomHttpExtrasJsonRule.php b/app/Rules/CustomHttpExtrasJsonRule.php
deleted file mode 100644
index a57d3e6ef9..0000000000
--- a/app/Rules/CustomHttpExtrasJsonRule.php
+++ /dev/null
@@ -1,61 +0,0 @@
-<?php
-
-namespace App\Rules;
-
-use Closure;
-use Illuminate\Contracts\Validation\ValidationRule;
-
-/**
- * Validate the Custom HTTP adapter's Custom Extras JSON blob. Blank
- * is fine (no extras configured). Otherwise the value must parse as
- * a JSON array whose entries are objects containing at least the
- * required `key` and `path` string keys.
- */
-class CustomHttpExtrasJsonRule implements ValidationRule
-{
- public function validate(string $attribute, mixed $value, Closure $fail): void
- {
- if ($value === null || $value === '' || (is_string($value) && trim($value) === '')) {
- return;
- }
-
- if (!is_string($value)) {
- $fail(trans('validation.custom_http_extras_json.not_json'));
-
- return;
- }
-
- $decoded = json_decode($value, true);
- if (json_last_error() !== JSON_ERROR_NONE) {
- $fail(trans('validation.custom_http_extras_json.not_json', [
- 'error' => json_last_error_msg(),
- ]));
-
- return;
- }
-
- if (!is_array($decoded)) {
- $fail(trans('validation.custom_http_extras_json.not_array'));
-
- return;
- }
-
- foreach ($decoded as $index => $entry) {
- if (!is_array($entry)) {
- $fail(trans('validation.custom_http_extras_json.entry_not_object', ['index' => $index]));
-
- return;
- }
- foreach (['key', 'path'] as $requiredKey) {
- if (!array_key_exists($requiredKey, $entry) || !is_string($entry[$requiredKey]) || trim($entry[$requiredKey]) === '') {
- $fail(trans('validation.custom_http_extras_json.missing_field', [
- 'index' => $index,
- 'field' => $requiredKey,
- ]));
-
- return;
- }
- }
- }
- }
-}
diff --git a/app/SyncAdapters/AppleBusinessManager/AppleBusinessManagerAdapter.php b/app/SyncAdapters/AppleBusinessManager/AppleBusinessManagerAdapter.php
index 55981ca3d8..1d45e0a01a 100644
--- a/app/SyncAdapters/AppleBusinessManager/AppleBusinessManagerAdapter.php
+++ b/app/SyncAdapters/AppleBusinessManager/AppleBusinessManagerAdapter.php
@@ -7,6 +7,7 @@ use App\SyncAdapters\HostInventoryRecord;
use App\SyncAdapters\SyncAdapter;
use Carbon\Carbon;
use Illuminate\Support\Arr;
+use Illuminate\Support\Facades\Log;
/**
* Apple Business Manager (ABM) / Apple School Manager (ASM) adapter.
@@ -358,7 +359,7 @@ class AppleBusinessManagerAdapter extends SyncAdapter
try {
$deviceToServer = $client->deviceToMdmServerMap();
} catch (\Throwable $e) {
- \Log::channel('sync-adapters')->warning(sprintf(
+ Log::channel('sync-adapters')->warning(sprintf(
'%s mdm-server map fetch failed: %s',
$this->name(),
$e->getMessage(),
@@ -391,7 +392,7 @@ class AppleBusinessManagerAdapter extends SyncAdapter
}
}
} catch (\Throwable $e) {
- \Log::channel('sync-adapters')->warning(sprintf(
+ Log::channel('sync-adapters')->warning(sprintf(
'%s mdmDevices list fetch failed: %s',
$this->name(),
$e->getMessage(),
@@ -472,7 +473,7 @@ class AppleBusinessManagerAdapter extends SyncAdapter
: $record->hardwareModel;
if ($modelName === null || $modelName === '') {
- \Log::channel('sync-adapters')->info(sprintf(
+ Log::channel('sync-adapters')->info(sprintf(
'%s image skip for device %s: no model name resolvable (hardwareModel and abm_model_marketing_name both blank)',
$this->name(),
$record->sourceId,
@@ -488,7 +489,7 @@ class AppleBusinessManagerAdapter extends SyncAdapter
$productType = $record->extra['abm_product_type'] ?? null;
if (! is_string($productType) || $productType === '') {
- \Log::channel('sync-adapters')->info(sprintf(
+ Log::channel('sync-adapters')->info(sprintf(
'%s image skip for model "%s": ABM did not return a productType, nothing to look up on appledb.dev',
$this->name(),
$modelName,
@@ -502,7 +503,7 @@ class AppleBusinessManagerAdapter extends SyncAdapter
->first();
if ($existing !== null && ! empty($existing->image)) {
- \Log::channel('sync-adapters')->info(sprintf(
+ Log::channel('sync-adapters')->info(sprintf(
'%s image skip for model "%s": model already has an image (%s)',
$this->name(),
$modelName,
@@ -515,7 +516,7 @@ class AppleBusinessManagerAdapter extends SyncAdapter
$color = $record->extra['abm_color'] ?? null;
$filename = AppleDBImageFetcher::fetch($productType, is_string($color) ? $color : null);
if ($filename === null) {
- \Log::channel('sync-adapters')->info(sprintf(
+ Log::channel('sync-adapters')->info(sprintf(
'%s image skip for model "%s" (productType=%s): appledb.dev returned no usable image',
$this->name(),
$modelName,
@@ -533,7 +534,7 @@ class AppleBusinessManagerAdapter extends SyncAdapter
// models/ by the fetcher, so the next sync will find the
// model row and only need to set model.image (no
// re-download).
- \Log::channel('sync-adapters')->info(sprintf(
+ Log::channel('sync-adapters')->info(sprintf(
'%s image staged for model "%s" (productType=%s, file=%s): AssetModel row not yet created, image will be assigned on the next sync',
$this->name(),
$modelName,
@@ -547,7 +548,7 @@ class AppleBusinessManagerAdapter extends SyncAdapter
$existing->image = $filename;
$existing->save();
- \Log::channel('sync-adapters')->info(sprintf(
+ Log::channel('sync-adapters')->info(sprintf(
'%s image assigned to model "%s" (productType=%s, file=%s)',
$this->name(),
$modelName,
@@ -667,7 +668,7 @@ class AppleBusinessManagerAdapter extends SyncAdapter
try {
$coverages = $client->deviceAppleCareCoverage($record->sourceId);
} catch (\Throwable $e) {
- \Log::channel('sync-adapters')->warning(sprintf(
+ Log::channel('sync-adapters')->warning(sprintf(
'%s applecare fetch failed for device %s: %s',
$this->name(),
$record->sourceId,
@@ -724,7 +725,7 @@ class AppleBusinessManagerAdapter extends SyncAdapter
try {
$status = $client->deviceActivationLockStatus($record->sourceId);
} catch (\Throwable $e) {
- \Log::channel('sync-adapters')->warning(sprintf(
+ Log::channel('sync-adapters')->warning(sprintf(
'%s activation lock fetch failed for device %s: %s',
$this->name(),
$record->sourceId,
@@ -810,7 +811,7 @@ class AppleBusinessManagerAdapter extends SyncAdapter
try {
$detail = $client->mdmDeviceDetails($record->hardwareSerial);
} catch (\Throwable $e) {
- \Log::channel('sync-adapters')->warning(sprintf(
+ Log::channel('sync-adapters')->warning(sprintf(
'%s mdmDevice detail fetch failed for device %s: %s',
$this->name(),
$record->sourceId,
diff --git a/app/SyncAdapters/CustomHttp/CustomHttpAdapter.php b/app/SyncAdapters/CustomHttp/CustomHttpAdapter.php
index d04228103a..041243bc86 100644
--- a/app/SyncAdapters/CustomHttp/CustomHttpAdapter.php
+++ b/app/SyncAdapters/CustomHttp/CustomHttpAdapter.php
@@ -3,6 +3,7 @@
namespace App\SyncAdapters\CustomHttp;
use App\Models\Asset;
+use App\Models\SyncAdapterConfig;
use App\SyncAdapters\HostInventoryRecord;
use App\SyncAdapters\PushableAdapter;
use App\SyncAdapters\SyncAdapter;
@@ -54,9 +55,9 @@ class CustomHttpAdapter extends SyncAdapter implements PushableAdapter
*
* @return array<string, string>
*/
- private static function fieldPathOptions(): array
+ private function fieldPathOptions(): array
{
- return [
+ $options = [
'hostname' => trans('admin/settings/sync_adapters.field_hostname'),
'serial' => trans('admin/settings/sync_adapters.field_serial'),
'asset_tag' => trans('admin/settings/sync_adapters.field_asset_tag'),
@@ -70,6 +71,22 @@ class CustomHttpAdapter extends SyncAdapter implements PushableAdapter
'assigned_user_email' => trans('admin/settings/sync_adapters.field_assigned_user_email'),
'assigned_user_name' => trans('admin/settings/sync_adapters.field_assigned_user_name'),
];
+
+ // Extra destination slots for admins whose vendor exposes
+ // per-device metadata that lands in native Asset columns
+ // rather than a HostInventoryRecord field.
+ $options['native:notes'] = trans('admin/settings/sync_adapters.target_native_notes');
+ $options['native:purchase_date'] = \App\SyncAdapters\MappingTargets::labelFor('native:purchase_date');
+ $options['native:order_number'] = \App\SyncAdapters\MappingTargets::labelFor('native:order_number');
+
+ // Custom field destinations. Text and textarea-shaped fields
+ // land here so admins can route vendor blobs to whatever
+ // custom field they've defined on the fieldset.
+ foreach (\App\Models\CustomField::whereIn('element', ['text', 'textarea', 'markdown-textarea'])->orderBy('name')->get() as $cf) {
+ $options['custom:'.$cf->id] = trans('admin/settings/sync_adapters.target_custom_prefix').': '.$cf->name;
+ }
+
+ return $options;
}
public static function typeLabel(): string
@@ -269,18 +286,9 @@ class CustomHttpAdapter extends SyncAdapter implements PushableAdapter
'label' => trans('admin/settings/sync_adapters.custom_field_paths_label'),
'type' => 'field_map',
'required' => false,
- 'options' => self::fieldPathOptions(),
+ 'options' => $this->fieldPathOptions(),
'help' => trans('admin/settings/sync_adapters.custom_field_paths_help'),
],
- [
- 'key' => 'extras_definition',
- 'label' => trans('admin/settings/sync_adapters.label_custom_extras_json'),
- 'type' => 'textarea',
- 'required' => false,
- 'section' => 'extras',
- 'placeholder' => '[{"key": "vendor_tag", "label": "Vendor Tag", "path": "tags.asset_tag"}]',
- 'help' => trans('admin/settings/sync_adapters.custom_extras_definition_help'),
- ],
];
}
@@ -344,10 +352,6 @@ class CustomHttpAdapter extends SyncAdapter implements PushableAdapter
'title' => trans('admin/settings/sync_adapters.custom_section_pagination_title'),
'help' => trans('admin/settings/sync_adapters.custom_section_pagination_help'),
],
- 'extras' => [
- 'title' => trans('admin/settings/sync_adapters.custom_section_extras_title'),
- 'help' => trans('admin/settings/sync_adapters.custom_section_extras_help'),
- ],
'push' => [
'title' => trans('admin/settings/sync_adapters.custom_section_push_title'),
'help' => trans('admin/settings/sync_adapters.custom_section_push_help'),
@@ -356,37 +360,63 @@ class CustomHttpAdapter extends SyncAdapter implements PushableAdapter
}
/**
- * Extend the base validation rules with the Custom-Extras JSON
- * shape check. Blank passes through, malformed JSON or missing
- * key/path per entry surfaces the reason instead of silently
- * dropping every entry the way the runtime parser does.
+ * The unified Vendor Response Paths widget lets admins target
+ * custom fields and native columns directly. Each such entry
+ * needs a mapping.<key> = <key> self-routing config so the
+ * framework's applyExtraFieldMappings loop routes the extracted
+ * value to its target. Discovery reads the stored field_paths
+ * JSON blob and returns each custom:/native: destination as an
+ * extra key. Standard HostInventoryRecord field destinations
+ * (hostname, serial, etc.) are handled by the base framework, so
+ * they don't appear here.
*/
- public function validationRules(): array
+ public function extraFields(): array
{
- $rules = parent::validationRules();
- $rules[$this->instance->slug.'_extras_definition'] = [
- 'nullable',
- 'string',
- new \App\Rules\CustomHttpExtrasJsonRule,
- ];
+ $out = [];
+ foreach ($this->fieldPathMap() as $destination => $path) {
+ if ($path === '') {
+ continue;
+ }
+ if (! str_starts_with($destination, 'custom:') && ! str_starts_with($destination, 'native:')) {
+ continue;
+ }
+ $out[$destination] = ['label' => $destination, 'admin_defined' => true];
+ }
- return $rules;
+ return $out;
}
/**
- * Admin-defined extras. Reads the extras_definition JSON blob
- * on this instance and exposes each entry as an extra field the
- * framework's mapping UI can route to a Snipe-IT custom field or
- * a native column.
+ * After the base saveConfig persists field_paths + directions,
+ * make sure every custom:/native: destination has a self-routing
+ * mapping.<key> = <key> config so the framework's extras loop
+ * writes each extracted value to its target at sync time. Cheap
+ * to re-persist on every save because the values are stable.
*/
- public function extraFields(): array
+ public function saveConfig(\Illuminate\Http\Request $request): void
{
- $out = [];
- foreach ($this->extrasDefinition() as $extra) {
- $out[$extra['key']] = ['label' => $extra['label']];
- }
+ parent::saveConfig($request);
- return $out;
+ $slug = $this->instance->slug;
+ $postedDirections = (array) $request->input($slug.'_direction', []);
+ foreach (array_keys($this->fieldPathMap()) as $destination) {
+ if (! str_starts_with($destination, 'custom:') && ! str_starts_with($destination, 'native:')) {
+ continue;
+ }
+ SyncAdapterConfig::put($this->instance->id, 'mapping.'.$destination, $destination);
+
+ // Parent's persistFieldDirections dropped these because
+ // validMappingFields didn't yet include the destination
+ // key on a first save (extraFields() only picks them up
+ // once mapping.<key> is stored). Persist here so per-row
+ // direction from the widget survives the first save.
+ if (isset($postedDirections[$destination])) {
+ $direction = (string) $postedDirections[$destination];
+ if (in_array($direction, ['pull', 'push', 'both', 'skip'], true)) {
+ SyncAdapterConfig::put($this->instance->id, 'direction.'.$destination, $direction);
+ }
+ }
+ }
}
/**
@@ -593,6 +623,24 @@ class CustomHttpAdapter extends SyncAdapter implements PushableAdapter
return;
}
+ // Track null rates per configured dot-path across every
+ // record processed. Paths that return null on 100% of
+ // records are almost always typos or renamed vendor fields.
+ // dotPathGet returns null silently on miss, so without an
+ // end-of-run summary these mistakes hide until an admin
+ // notices the destination column is empty on every asset.
+ $configuredPaths = [];
+ foreach ($fieldPaths as $destination => $path) {
+ if ($path !== '' && $destination !== 'source_id') {
+ $configuredPaths[$destination] = $path;
+ }
+ }
+ foreach ($extras as $extra) {
+ $configuredPaths[$extra['key']] = $extra['path'];
+ }
+ $pathStats = array_fill_keys(array_keys($configuredPaths), 0);
+ $recordCount = 0;
+
$globalIndex = 0;
foreach ($this->paginate() as $records) {
foreach ($records as $record) {
@@ -613,10 +661,50 @@ class CustomHttpAdapter extends SyncAdapter implements PushableAdapter
continue;
}
+ $recordCount++;
+ foreach ($configuredPaths as $destination => $path) {
+ if (self::dotPathGet($record, $path) === null) {
+ $pathStats[$destination]++;
+ }
+ }
yield $normalized;
$globalIndex++;
}
}
+
+ $this->logAlwaysNullPaths($configuredPaths, $pathStats, $recordCount);
+ }
+
+ /**
+ * Emit a sync-adapters-log warning listing every configured
+ * dot-path that returned null on every record we saw. Fires only
+ * when we actually processed records so an empty vendor response
+ * doesn't get mis-flagged as a typo.
+ *
+ * @param array<string, string> $configuredPaths destination => dot-path
+ * @param array<string, int> $pathStats destination => null-count
+ */
+ private function logAlwaysNullPaths(array $configuredPaths, array $pathStats, int $recordCount): void
+ {
+ if ($recordCount === 0) {
+ return;
+ }
+
+ $missing = [];
+ foreach ($pathStats as $destination => $nullCount) {
+ if ($nullCount === $recordCount) {
+ $missing[] = $destination.' → '.$configuredPaths[$destination];
+ }
+ }
+ if ($missing === []) {
+ return;
+ }
+
+ $adapter = $this->name();
+ $list = implode(', ', $missing);
+ Log::channel('sync-adapters')->warning(
+ "{$adapter} pull: processed {$recordCount} record(s), but these Vendor Response Paths returned no data on any record (typo or wrong path?): {$list}"
+ );
}
/**
@@ -942,7 +1030,7 @@ class CustomHttpAdapter extends SyncAdapter implements PushableAdapter
*/
private function fieldPathMap(): array
{
- $baseline = array_fill_keys(array_keys(self::fieldPathOptions()), '');
+ $baseline = array_fill_keys(array_keys($this->fieldPathOptions()), '');
// source_id lives outside the repeater as its own required
// input, so merge it in here to give a uniform
// $map['source_id'] lookup.
@@ -959,7 +1047,17 @@ class CustomHttpAdapter extends SyncAdapter implements PushableAdapter
}
foreach ($decoded as $key => $value) {
- if (is_string($key) && array_key_exists($key, $baseline) && is_string($value)) {
+ if (! is_string($key) || ! is_string($value)) {
+ continue;
+ }
+ // Standard fields and current custom/native destinations
+ // pass the baseline check. Admin-added custom:/native:
+ // entries whose target has since been deleted from
+ // Snipe-IT still deserialize so extraFields() can surface
+ // the orphan and the admin can clean up.
+ if (array_key_exists($key, $baseline)
+ || str_starts_with($key, 'custom:')
+ || str_starts_with($key, 'native:')) {
$baseline[$key] = $value;
}
}
@@ -968,33 +1066,29 @@ class CustomHttpAdapter extends SyncAdapter implements PushableAdapter
}
/**
- * Parse the extras JSON blob into a validated list. Non-array
- * entries and entries missing key/path are dropped silently so a
- * partially-malformed blob still yields the rest.
+ * List of admin-defined extras for the pull-time normalize() to
+ * iterate. Since path is the mapping key on Custom HTTP (the
+ * admin-extras-picker rebuild removed the separate key/label
+ * fields), each entry's key IS its path. Discovery mirrors
+ * extraFields(): walk stored field_paths, keep only custom: /
+ * native: destinations that actually have a non-empty dot-path.
*
* @return array<int, array{key: string, label: string, path: string}>
*/
private function extrasDefinition(): array
{
- $raw = $this->safeCredential('extras_definition');
- if (trim($raw) === '') {
- return [];
- }
-
- $decoded = json_decode($raw, true);
- if (! is_array($decoded)) {
- return [];
- }
-
$out = [];
- foreach ($decoded as $entry) {
- if (! is_array($entry) || ! isset($entry['key'], $entry['path'])) {
+ foreach ($this->fieldPathMap() as $destination => $path) {
+ if ($path === '') {
+ continue;
+ }
+ if (! str_starts_with($destination, 'custom:') && ! str_starts_with($destination, 'native:')) {
continue;
}
$out[] = [
- 'key' => (string) $entry['key'],
- 'label' => (string) ($entry['label'] ?? $entry['key']),
- 'path' => (string) $entry['path'],
+ 'key' => $destination,
+ 'label' => $destination,
+ 'path' => $path,
];
}
diff --git a/app/SyncAdapters/KaseyaVsa10/KaseyaVsa10Adapter.php b/app/SyncAdapters/KaseyaVsa10/KaseyaVsa10Adapter.php
index e5a89ed012..7fc3b7db4a 100644
--- a/app/SyncAdapters/KaseyaVsa10/KaseyaVsa10Adapter.php
+++ b/app/SyncAdapters/KaseyaVsa10/KaseyaVsa10Adapter.php
@@ -6,6 +6,7 @@ use App\SyncAdapters\HostInventoryRecord;
use App\SyncAdapters\SyncAdapter;
use Carbon\Carbon;
use Illuminate\Support\Arr;
+use Illuminate\Support\Facades\Log;
/**
* Kaseya VSA 10 (formerly Kaseya X, product code "vsax") adapter.
@@ -256,7 +257,7 @@ class KaseyaVsa10Adapter extends SyncAdapter
try {
$values = $client->deviceCustomFieldValues($record->sourceId);
} catch (\Throwable $e) {
- \Log::channel('sync-adapters')->warning(sprintf(
+ Log::channel('sync-adapters')->warning(sprintf(
'%s customfields fetch failed for device %s: %s',
$this->name(),
$record->sourceId,
diff --git a/app/SyncAdapters/SyncAdapter.php b/app/SyncAdapters/SyncAdapter.php
index 99fe65e2fb..cf72074f15 100644
--- a/app/SyncAdapters/SyncAdapter.php
+++ b/app/SyncAdapters/SyncAdapter.php
@@ -9,6 +9,7 @@ use App\Models\SyncAdapterInstance;
use App\Rules\ExternalUrl;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Crypt;
+use Illuminate\Support\Facades\Log;
/**
* The single base class every host-inventory adapter extends. Owns
@@ -515,11 +516,15 @@ abstract class SyncAdapter
// Field-map repeater: assoc array of {field_key: path}.
// Empty submissions overwrite as {} so a deliberate
- // "clear everything" from the UI sticks. Blank path
- // values within the array are dropped so a mistakenly
- // added empty row doesn't roundtrip.
+ // "clear everything".
if ($type === 'field_map') {
$values = (array) $request->input($fieldName, []);
+ $pending = (array) $request->input($fieldName.'_pending', []);
+ $pendingKey = is_string($pending['key'] ?? null) ? trim($pending['key']) : '';
+ $pendingValue = is_string($pending['value'] ?? null) ? trim($pending['value']) : '';
+ if ($pendingKey !== '' && $pendingValue !== '') {
+ $values[$pendingKey] = $pendingValue;
+ }
$values = array_filter(
$values,
fn ($v, $k) => is_string($k) && $k !== '' && is_string($v) && trim($v) !== '',
@@ -702,12 +707,34 @@ abstract class SyncAdapter
*/
private function persistFieldMappings(Request $request, string $slug, array $validFields): void
{
- foreach ((array) $request->input($slug.'_mapping', []) as $field => $target) {
+ $posted = (array) $request->input($slug.'_mapping', []);
+
+ // The mapping-picker widget's picker row submits its unfinished
+ // pair under <slug>_mapping_pending[key|value] so admins can
+ // save without clicking the + button first. Fold it into the
+ // posted array before save.
+ $pending = (array) $request->input($slug.'_mapping_pending', []);
+ $pendingKey = is_string($pending['key'] ?? null) ? trim($pending['key']) : '';
+ $pendingValue = is_string($pending['value'] ?? null) ? trim($pending['value']) : '';
+ if ($pendingKey !== '' && $pendingValue !== '' && ! array_key_exists($pendingKey, $posted)) {
+ $posted[$pendingKey] = $pendingValue;
+ }
+
+ foreach ($posted as $field => $target) {
if (! in_array($field, $validFields, true)) {
continue;
}
SyncAdapterConfig::put($this->instance->id, 'mapping.'.$field, (string) $target);
}
+
+ // Extras use the mapping-picker widget, which submits only for
+ // rows the admin left mapped. Removing a row = the row's key
+ // is absent from POST.
+ foreach (array_keys($this->extraFields()) as $extraKey) {
+ if (! array_key_exists($extraKey, $posted)) {
+ SyncAdapterConfig::forget($this->instance->id, 'mapping.'.$extraKey);
+ }
+ }
}
/**
@@ -715,16 +742,35 @@ abstract class SyncAdapter
* target column stored above so admins can flip direction without
* re-picking the target. Only meaningful for adapters that
* implement PushableAdapter. For pull-only adapters the form
- * doesn't render the direction column and this loop is a no-op.
- * Value 'pull' is the default and doesn't need storing, but writing
- * it explicitly keeps the round-trip behavior predictable for
- * admins reading raw config.
+ * doesn't render the direction column, and the default is always pull.
*
* @param array<int, string> $validFields
*/
private function persistFieldDirections(Request $request, string $slug, array $validFields): void
{
- foreach ((array) $request->input($slug.'_direction', []) as $field => $direction) {
+ $posted = (array) $request->input($slug.'_direction', []);
+
+ // Widgets' picker rows submit their unfinished pair under
+ // <slug>_<map_key>_pending[key|value] so admins can save
+ // without clicking + to commit the row first.
+ $pairedMapKeys = [$slug.'_mapping_pending'];
+ foreach ($this->settingsSchema() as $field) {
+ if (($field['type'] ?? '') === 'field_map') {
+ $pairedMapKeys[] = $slug.'_'.$field['key'].'_pending';
+ }
+ }
+ $directionPending = (array) $request->input($slug.'_direction_pending', []);
+ $pendingDir = is_string($directionPending['value'] ?? null) ? trim($directionPending['value']) : '';
+ foreach ($pairedMapKeys as $pendingField) {
+ $pairedPending = (array) $request->input($pendingField, []);
+ $pendingKey = is_string($pairedPending['key'] ?? null) ? trim($pairedPending['key']) : '';
+ $pendingValue = is_string($pairedPending['value'] ?? null) ? trim($pairedPending['value']) : '';
+ if ($pendingKey !== '' && $pendingValue !== '' && $pendingDir !== '' && ! array_key_exists($pendingKey, $posted)) {
+ $posted[$pendingKey] = $pendingDir;
+ }
+ }
+
+ foreach ($posted as $field => $direction) {
if (! in_array($field, $validFields, true)) {
continue;
}
@@ -733,6 +779,16 @@ abstract class SyncAdapter
}
SyncAdapterConfig::put($this->instance->id, 'direction.'.$field, (string) $direction);
}
+
+ // Same forget-on-omit rule as persistFieldMappings for extras:
+ // rows removed via the mapping-picker widget are absent from
+ // POST, and their direction needs clearing so it doesn't
+ // linger on the next sync if the extra gets re-added.
+ foreach (array_keys($this->extraFields()) as $extraKey) {
+ if (! array_key_exists($extraKey, $posted)) {
+ SyncAdapterConfig::forget($this->instance->id, 'direction.'.$extraKey);
+ }
+ }
}
/**
@@ -892,7 +948,7 @@ abstract class SyncAdapter
$written = $touched !== [] ? $touched : array_keys($payload);
if ($this->isPushDryRun()) {
- \Illuminate\Support\Facades\Log::channel('sync-adapters')->info(sprintf(
+ 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),
@@ -905,7 +961,7 @@ abstract class SyncAdapter
$this->dispatchPush($externalSource, $payload);
- \Illuminate\Support\Facades\Log::channel('sync-adapters')->info(sprintf(
+ Log::channel('sync-adapters')->info(sprintf(
'%s push: updated %s device %s [%s]',
$this->name(),
static::typeLabel(),
diff --git a/config/logging.php b/config/logging.php
index e64e6fce49..3d71f1386d 100644
--- a/config/logging.php
+++ b/config/logging.php
@@ -124,7 +124,6 @@ $config = [
'driver' => 'single',
'path' => storage_path('logs/sync-adapters.log'),
'level' => env('LOG_LEVEL', 'info'),
- 'days' => 30,
],
'rollbar' => [
diff --git a/resources/lang/en-US/admin/settings/sync_adapters.php b/resources/lang/en-US/admin/settings/sync_adapters.php
index f6edb2a341..390acf8838 100644
--- a/resources/lang/en-US/admin/settings/sync_adapters.php
+++ b/resources/lang/en-US/admin/settings/sync_adapters.php
@@ -209,13 +209,13 @@ return [
'custom_pagination_page_start_help' => 'The number to use for the first page. Defaults to <code>1</code>. Set to <code>0</code> for APIs that number pages from zero.',
'custom_pagination_next_path_help' => 'Dot-path into the response body pointing at the absolute URL of the next page, e.g. <code>links.next</code> or <code>meta.next_page_url</code>. When the path resolves to blank or missing, pagination stops.',
'custom_field_paths_label' => 'Vendor Response Paths',
- 'custom_field_paths_help' => 'This section tells the adapter WHERE to find each field in your vendor\'s JSON response. Pick a Snipe-IT field, type the dot-path where your API returns that value in one record (e.g. <code>hardware.serial</code>), then click Add. Which Snipe-IT column each value is synces to, and whether it flows pull / push / both, is configured in the field-mapping section further down.',
+ 'custom_field_paths_help' => 'Map each Snipe-IT destination (standard field, custom field, or native column) to the dot-path where its value lives inside one record of your vendor\'s JSON response. Pick a destination, enter its dot-path (e.g. <code>hardware.serial</code>), pick a direction (pull / push / both), then Add.',
'field_map_column_field' => 'Snipe-IT Field',
'field_map_column_path' => 'Vendor Dot-Path',
+ 'field_map_column_direction' => 'Direction',
'field_map_empty' => 'No fields mapped yet.',
'field_map_pick_field' => 'Pick a field',
'field_map_new_path' => 'Dot-path (e.g. hardware.serial)',
- 'custom_extras_definition_help' => 'Optional. JSON array declaring additional vendor fields you want available in the mapping table below. Format: <code>[{"key": "vendor_field", "label": "Human Label", "path": "dot.path.to.value"}]</code>. Each entry appears in the extras list where you can route it to a custom field or a native column.',
'custom_push_method_help' => 'HTTP method the adapter uses when pushing updates back to your API. Defaults to <code>PATCH</code>.',
'custom_push_path_help' => 'Path appended to the Base URL when pushing. Supports the <code>{external_id}</code> placeholder, which is replaced with the vendor-side device id recorded during the last pull for each asset. Leave blank to hit the Base URL directly (useful when your API accepts the id in the request body instead of the URL). To disable push entirely, set Push HTTP Method to <code>Disabled</code>.',
'custom_push_notes_target_help' => 'Optional. Dot-path in the outgoing payload where the composed Push Notes template value should be synced to, e.g. <code>metadata.notes</code>. Leave blank if you are not using composed notes.',
@@ -227,15 +227,23 @@ return [
'custom_section_pull_help' => 'Where the adapter fetches records from and how it locates them inside the JSON response.',
'custom_section_pagination_title' => 'Pagination',
'custom_section_pagination_help' => 'How the adapter walks past the first page of results. Choose <code>None</code> for single-page endpoints.',
- 'custom_section_extras_title' => 'Custom Extras',
- 'custom_section_extras_help' => 'Additional vendor fields not covered by the standard Snipe-IT mapping. Configuration for each extra field is done in the mapping section further down.',
'custom_section_push_title' => 'Push Endpoint',
'custom_section_push_help' => 'How the adapter writes updates back to your API. Set Push HTTP Method to <code>Disabled</code> to keep this instance pull-only.',
'custom_url_prefix_base_url_placeholder' => 'Base URL:',
// Extras / mapping section wrappers
'extra_fields_section_title' => ':type-specific fields',
- 'extra_fields_section_intro' => 'Additional vendor fields that don\'t have a corresponding Snipe-IT field. These can be mapped to custom fields or native Snipe-IT columns in the field-mapping section below. Boolean values can be mapped to checkbox-type custom fields, text fields can be mapped to text-type custom fields.',
+ 'extra_fields_section_intro' => 'Additional vendor fields that don\'t have a corresponding Snipe-IT field. Add a row per vendor field you want to sync and pick wheich field it maps to. Boolean values can be mapped to checkbox-type custom fields, text fields can be mapped to text-type custom fields.',
+
+ // Mapping-picker widget (extras section repeater)
+ 'mapping_picker_col_field' => 'Vendor Field',
+ 'mapping_picker_col_target' => 'Snipe-IT Target',
+ 'mapping_picker_col_direction' => 'Direction',
+ 'mapping_picker_empty' => 'No vendor fields mapped yet. Pick a field below to add one.',
+ 'mapping_picker_pick_extra' => 'Pick a vendor field',
+ 'mapping_picker_pick_target' => 'Pick a target',
+
+ // Admin-defined extras picker (Custom HTTP)
/*
|--------------------------------------------------------------------------
@@ -322,7 +330,6 @@ return [
'label_page_query_parameter' => 'Page Query Parameter',
'label_first_page_number' => 'First Page Number',
'label_next_page_url_path' => 'Next Page URL Path',
- 'label_custom_extras_json' => 'Custom Extras (JSON)',
'label_access_token' => 'Access Token',
'label_tenant_id' => 'Tenant ID',
'label_tenant_code' => 'Tenant Code',
diff --git a/resources/views/blade/input/field-map.blade.php b/resources/views/blade/input/field-map.blade.php
index ebfab27bee..03591b7719 100644
--- a/resources/views/blade/input/field-map.blade.php
+++ b/resources/views/blade/input/field-map.blade.php
@@ -1,31 +1,27 @@
-{{-- Repeater-style picker for building a {snipe_field: vendor_path}
- mapping. Renders one row per already-configured entry (label +
- editable dot-path input + remove button), plus a picker row
- below (dropdown of remaining options + input + Add button).
- Values submit as $name[$snipeFieldKey]=$path so the server sees
- an associative array on save.
-
- Widget is self-contained: inline jQuery IIFE, no snipeit.js
- changes required. Multiple instances on one page each get a
- unique data-field-map-widget id so the handlers don't cross-
- wire. --}}
@props([
'name',
'options' => [],
'stored' => [],
+ 'direction_name' => null,
+ 'direction_options' => [],
+ 'stored_directions' => [],
])
@php
$widgetId = 'field-map-'.\Illuminate\Support\Str::random(8);
$availableOptions = collect($options)->except(array_keys($stored))->all();
+ $showDirection = $direction_name !== null && ! empty($direction_options);
@endphp
<div class="field-map-widget" data-field-map-widget="{{ $widgetId }}">
<table class="table table-condensed" style="margin-bottom: 8px;">
<thead>
<tr>
- <th style="width: 35%">{{ trans('admin/settings/sync_adapters.field_map_column_field') }}</th>
+ <th style="width: 30%">{{ trans('admin/settings/sync_adapters.field_map_column_field') }}</th>
<th>{{ trans('admin/settings/sync_adapters.field_map_column_path') }}</th>
+ @if ($showDirection)
+ <th style="width: 20%">{{ trans('admin/settings/sync_adapters.field_map_column_direction') }}</th>
+ @endif
<th style="width: 60px"></th>
</tr>
</thead>
@@ -42,6 +38,21 @@
aria-label="{{ $options[$storedKey] ?? $storedKey }} dot-path"
>
</td>
+ @if ($showDirection)
+ <td>
+ <select
+ name="{{ $direction_name }}[{{ $storedKey }}]"
+ class="select2 field-map-row-direction"
+ style="width: 100%"
+ data-minimum-results-for-search="Infinity"
+ aria-label="{{ $options[$storedKey] ?? $storedKey }} direction"
+ >
+ @foreach ($direction_options as $dirValue => $dirLabel)
+ <option value="{{ $dirValue }}" @if ((string) $dirValue === (string) ($stored_directions[$storedKey] ?? 'pull')) selected @endif>{{ $dirLabel }}</option>
+ @endforeach
+ </select>
+ </td>
+ @endif
<td>
<button
type="button"
@@ -54,23 +65,18 @@
</tr>
@endforeach
<tr class="field-map-empty" @if (count($stored) > 0) hidden @endif>
- <td colspan="3" class="text-muted text-center">
+ <td colspan="{{ $showDirection ? 4 : 3 }}" class="text-muted text-center">
<em>{{ trans('admin/settings/sync_adapters.field_map_empty') }}</em>
</td>
</tr>
</tbody>
<tfoot>
- {{-- Picker row lives inside the same table so its three
- cells inherit the header's column widths (35% / auto
- / 60px). Puts the select where the "Snipe-IT Field"
- label is, the new-value input where the "Vendor Dot-
- Path" input is, and the Add button in the same slot
- as the row remove buttons. --}}
<tr class="field-map-picker-row">
<td>
<label class="sr-only" for="{{ $widgetId }}-picker">{{ trans('admin/settings/sync_adapters.field_map_pick_field') }}</label>
<select
id="{{ $widgetId }}-picker"
+ name="{{ $name }}_pending[key]"
class="select2 field-map-picker"
style="width: 100%"
data-placeholder="{{ trans('admin/settings/sync_adapters.field_map_pick_field') }}"
@@ -85,16 +91,33 @@
<label class="sr-only" for="{{ $widgetId }}-value">{{ trans('admin/settings/sync_adapters.field_map_new_path') }}</label>
<input
id="{{ $widgetId }}-value"
+ name="{{ $name }}_pending[value]"
type="text"
class="form-control field-map-new-value"
placeholder="{{ trans('admin/settings/sync_adapters.field_map_new_path') }}"
>
</td>
+ @if ($showDirection)
+ <td>
+ <select
+ id="{{ $widgetId }}-direction"
+ name="{{ $direction_name }}_pending[value]"
+ class="select2 field-map-new-direction"
+ style="width: 100%"
+ data-minimum-results-for-search="Infinity"
+ >
+ @foreach ($direction_options as $dirValue => $dirLabel)
+ <option value="{{ $dirValue }}" @if ($dirValue === 'pull') selected @endif>{{ $dirLabel }}</option>
+ @endforeach
+ </select>
+ </td>
+ @endif
<td>
<button
type="button"
class="btn btn-primary field-map-add"
aria-label="{{ trans('button.add') }}"
+ disabled
>
<x-icon type="create" />
</button>
@@ -110,6 +133,13 @@
<td>
<input type="text" name="{{ $name }}[__KEY__]" value="__VALUE__" class="form-control" aria-label="__LABEL__ dot-path">
</td>
+ @if ($showDirection)
+ <td>
+ <select name="{{ $direction_name }}[__KEY__]" class="select2 field-map-row-direction" style="width: 100%" data-minimum-results-for-search="Infinity" aria-label="__LABEL__ direction">
+ __DIRECTION_OPTIONS__
+ </select>
+ </td>
+ @endif
<td>
<button type="button" class="btn btn-danger field-map-remove" aria-label="{{ trans('button.delete') }}">
<i class="fa fa-times" aria-hidden="true"></i>
@@ -119,10 +149,6 @@
</script>
<script>
-// Defer to DOMContentLoaded so jQuery ($) is defined. Inline scripts
-// mid-body run before the tail-of-body <script src="jquery"> loads,
-// so referencing $ at parse time throws ReferenceError. Vanilla JS
-// wrapper here, jQuery inside.
document.addEventListener('DOMContentLoaded', function () {
var widgetId = @json($widgetId);
var $widget = $('[data-field-map-widget="' + widgetId + '"]');
@@ -132,12 +158,26 @@ document.addEventListener('DOMContentLoaded', function () {
var $empty = $widget.find('.field-map-empty');
var $picker = $widget.find('.field-map-picker');
var $newValue = $widget.find('.field-map-new-value');
+ var $newDirection = $widget.find('.field-map-new-direction');
var $addBtn = $widget.find('.field-map-add');
var template = $('[data-field-map-template="' + widgetId + '"]').html();
+ var directionOptionsMap = @json((object) $direction_options);
+
+ function initSelect2($el, opts) {
+ if ($el.hasClass('select2-hidden-accessible')) {
+ $el.select2('destroy');
+ }
+ $el.select2(opts || {});
+ }
+
+ function destroySelect2($el) {
+ if ($el.hasClass('select2-hidden-accessible')) {
+ $el.select2('destroy');
+ }
+ }
function refreshEmptyState() {
var hasRows = $rows.find('tr:not(.field-map-empty)').length > 0;
- $empty.attr('hidden', hasRows ? '' : null);
if (hasRows) { $empty.attr('hidden', ''); } else { $empty.removeAttr('hidden'); }
}
@@ -149,44 +189,106 @@ document.addEventListener('DOMContentLoaded', function () {
.replace(/"/g, '&quot;');
}
- // Check for dirty when vendor mapped fields change. This is needed because the
- // field-map widget is not a form input itself, but it does change the
- // values of inputs inside it.
+ function optionsHtml(map, selected) {
+ var html = '';
+ for (var value in map) {
+ if (!Object.prototype.hasOwnProperty.call(map, value)) {
+ continue;
+ }
+ var sel = String(value) === String(selected) ? ' selected' : '';
+ html += '<option value="' + encode(value) + '"' + sel + '>' + encode(map[value]) + '</option>';
+ }
+ return html;
+ }
+
function notifyFormOfStructuralChange() {
$widget[0].dispatchEvent(new Event('input', {bubbles: true}));
}
- $addBtn.on('click', function () {
+ function commitPickerRow() {
var key = $picker.val();
if (!key) { return; }
+ var value = $newValue.val();
+ if (value.trim() === '') {
+ return;
+ }
var $selected = $picker.find('option:selected');
var label = $selected.text();
- var value = $newValue.val();
+ var direction = $newDirection.length ? $newDirection.val() : 'pull';
var html = template
.split('__KEY__').join(encode(key))
- .split('__LABEL__').join(encode(label))
- .split('__VALUE__').join(encode(value));
+ .split('__LABEL__').join(encode(label)).split('__VALUE__').join(encode(value)).split('__DIRECTION_OPTIONS__').join(optionsHtml(directionOptionsMap, direction));
- $empty.before(html);
+ var $newRow = $(html);
+ $empty.before($newRow);
+ $newRow.find('.field-map-row-direction').each(function () {
+ initSelect2($(this), {minimumResultsForSearch: Infinity});
+ });
$selected.remove();
- $picker.val('').trigger('change'); // trigger('change') refreshes the select2 display after the option was pulled
+ $picker.val('').trigger('change');
$newValue.val('');
+ if ($newDirection.length) {
+ $newDirection.val('pull').trigger('change');
+ }
refreshEmptyState();
+ refreshAddEnabled();
notifyFormOfStructuralChange();
+ }
+
+ $addBtn.on('click', commitPickerRow);
+
+ // Auto-commit the picker row into a real table row as soon as
+ // both fields have content. Firing on picker change catches the
+ // "typed path first, then picked destination" order. Firing on
+ // path blur catches the "picked destination first, then typed
+ // path" order. Committing produces a visible row so admins
+ // abandon by clicking × on that row, same UX as any existing
+ // row, instead of hunting for hidden state.
+ $picker.on('change.autoCommit', function () {
+ if ($picker.val() && $newValue.val().trim() !== '') {
+ commitPickerRow();
+ }
+ });
+ $newValue.on('blur.autoCommit', function () {
+ if ($picker.val() && $newValue.val().trim() !== '') {
+ commitPickerRow();
+ }
});
$rows.on('click', '.field-map-remove', function () {
var $row = $(this).closest('tr');
var key = $row.data('field-key');
var label = $row.find('td:first').text().trim();
+ destroySelect2($row.find('.field-map-row-direction'));
$row.remove();
$picker.append($('<option>').val(key).text(label));
- $picker.trigger('change'); // re-render select2 with the restored option
+ $picker.trigger('change');
refreshEmptyState();
notifyFormOfStructuralChange();
});
+ // Initialize select2 on rendered rows and picker inputs.
+ initSelect2($picker, {
+ placeholder: @json((string) trans('admin/settings/sync_adapters.field_map_pick_field')),
+ allowClear: true,
+ });
+ if ($newDirection.length) {
+ initSelect2($newDirection, {minimumResultsForSearch: Infinity});
+ }
+ $rows.find('.field-map-row-direction').each(function () {
+ initSelect2($(this), {minimumResultsForSearch: Infinity});
+ });
+
+ function refreshAddEnabled() {
+ var ok = !!$picker.val() && $newValue.val().trim() !== '';
+ $addBtn.prop('disabled', !ok);
+ }
+
+ $picker.on('change', refreshAddEnabled);
+ $newValue.on('input change', refreshAddEnabled);
+
refreshEmptyState();
+ refreshAddEnabled();
});
</script>
diff --git a/resources/views/blade/input/mapping-picker.blade.php b/resources/views/blade/input/mapping-picker.blade.php
new file mode 100644
index 0000000000..28128c0f2d
--- /dev/null
+++ b/resources/views/blade/input/mapping-picker.blade.php
@@ -0,0 +1,392 @@
+@props([
+ 'name',
+ 'direction_name' => null,
+ 'entries' => [],
+ 'direction_options' => [],
+ 'supports_push' => false,
+ 'locked' => false,
+ 'add_label' => null,
+ 'empty_label' => null,
+ 'pick_extra_label' => null,
+ 'pick_target_label' => null,
+])
+
+@php
+ $widgetId = 'mapping-picker-'.\Illuminate\Support\Str::random(8);
+ $mapped = collect($entries)->filter(fn ($e) => ! empty($e['stored_target']) && $e['stored_target'] !== 'skip');
+ $unmapped = collect($entries)->reject(fn ($e) => ! empty($e['stored_target']) && $e['stored_target'] !== 'skip');
+ $showDirection = $supports_push && $direction_name !== null;
+ $addLabel = $add_label ?: trans('button.add');
+ $emptyLabel = $empty_label ?: trans('admin/settings/sync_adapters.mapping_picker_empty');
+ $pickExtraLabel = $pick_extra_label ?: trans('admin/settings/sync_adapters.mapping_picker_pick_extra');
+ $pickTargetLabel = $pick_target_label ?: trans('admin/settings/sync_adapters.mapping_picker_pick_target');
+@endphp
+
+<div class="mapping-picker-widget" data-mapping-picker-widget="{{ $widgetId }}">
+ <table class="table table-condensed" style="margin-bottom: 8px;">
+ <thead>
+ <tr>
+ <th style="width: 25%">{{ trans('admin/settings/sync_adapters.mapping_picker_col_field') }}</th>
+ <th>{{ trans('admin/settings/sync_adapters.mapping_picker_col_target') }}</th>
+ @if ($showDirection)
+ <th style="width: 20%">{{ trans('admin/settings/sync_adapters.mapping_picker_col_direction') }}</th>
+ @endif
+ <th style="width: 60px"></th>
+ </tr>
+ </thead>
+ <tbody class="mapping-picker-rows">
+ @foreach ($mapped as $key => $entry)
+ <tr data-field-key="{{ $key }}">
+ <td>{{ $entry['label'] }}</td>
+ <td>
+ <select
+ name="{{ $name }}[{{ $key }}]"
+ class="select2 mapping-picker-row-target"
+ style="width: 100%"
+ @if ($locked) disabled @endif
+ aria-label="{{ $entry['label'] }} {{ trans('admin/settings/sync_adapters.mapping_picker_col_target') }}"
+ >
+ @foreach ($entry['target_options'] as $optionValue => $optionLabel)
+ <option value="{{ $optionValue }}" @if ((string) $optionValue === (string) $entry['stored_target']) selected @endif>{{ $optionLabel }}</option>
+ @endforeach
+ </select>
+ </td>
+ @if ($showDirection)
+ <td>
+ <select
+ name="{{ $direction_name }}[{{ $key }}]"
+ class="select2 mapping-picker-row-direction"
+ style="width: 100%"
+ data-minimum-results-for-search="Infinity"
+ @if ($locked) disabled @endif
+ aria-label="{{ $entry['label'] }} {{ trans('admin/settings/sync_adapters.mapping_picker_col_direction') }}"
+ >
+ @foreach ($direction_options as $dirValue => $dirLabel)
+ <option value="{{ $dirValue }}" @if ((string) $dirValue === (string) ($entry['stored_direction'] ?? 'pull')) selected @endif>{{ $dirLabel }}</option>
+ @endforeach
+ </select>
+ </td>
+ @endif
+ <td>
+ <button
+ type="button"
+ class="btn btn-danger mapping-picker-remove"
+ aria-label="{{ trans('button.delete') }}"
+ @if ($locked) disabled @endif
+ >
+ <x-icon type="x" />
+ </button>
+ </td>
+ </tr>
+ @endforeach
+ <tr class="mapping-picker-empty" @if ($mapped->count() > 0) hidden @endif>
+ <td colspan="{{ $showDirection ? 4 : 3 }}" class="text-muted text-center">
+ <em>{{ $emptyLabel }}</em>
+ </td>
+ </tr>
+ </tbody>
+ <tfoot>
+ <tr class="mapping-picker-picker-row">
+ <td>
+ <label class="sr-only" for="{{ $widgetId }}-picker">{{ $pickExtraLabel }}</label>
+ <select
+ id="{{ $widgetId }}-picker"
+ name="{{ $name }}_pending[key]"
+ class="select2 mapping-picker-picker"
+ style="width: 100%"
+ data-placeholder="{{ $pickExtraLabel }}"
+ @if ($locked) disabled @endif
+ >
+ <option value=""></option>
+ @foreach ($unmapped as $key => $entry)
+ <option
+ value="{{ $key }}"
+ data-label="{{ $entry['label'] }}"
+ data-target-options="{{ json_encode($entry['target_options']) }}"
+ >{{ $entry['label'] }}</option>
+ @endforeach
+ </select>
+ </td>
+ <td>
+ <label class="sr-only" for="{{ $widgetId }}-target">{{ $pickTargetLabel }}</label>
+ <select
+ id="{{ $widgetId }}-target"
+ name="{{ $name }}_pending[value]"
+ class="select2 mapping-picker-new-target"
+ style="width: 100%"
+ data-placeholder="{{ $pickTargetLabel }}"
+ disabled
+ >
+ <option value=""></option>
+ </select>
+ </td>
+ @if ($showDirection)
+ <td>
+ <select
+ id="{{ $widgetId }}-direction"
+ name="{{ $direction_name }}_pending[value]"
+ class="select2 mapping-picker-new-direction"
+ style="width: 100%"
+ data-minimum-results-for-search="Infinity"
+ @if ($locked) disabled @endif
+ >
+ @foreach ($direction_options as $dirValue => $dirLabel)
+ <option value="{{ $dirValue }}" @if ($dirValue === 'pull') selected @endif>{{ $dirLabel }}</option>
+ @endforeach
+ </select>
+ </td>
+ @endif
+ <td>
+ <button
+ type="button"
+ class="btn btn-primary mapping-picker-add"
+ aria-label="{{ $addLabel }}"
+ disabled
+ >
+ <x-icon type="create" />
+ </button>
+ </td>
+ </tr>
+ </tfoot>
+ </table>
+</div>
+
+<script type="text/template" data-mapping-picker-template="{{ $widgetId }}">
+ <tr data-field-key="__KEY__">
+ <td>__LABEL__</td>
+ <td>
+ <select name="{{ $name }}[__KEY__]" class="select2 mapping-picker-row-target" style="width: 100%" aria-label="__LABEL__ target">
+ __TARGET_OPTIONS__
+ </select>
+ </td>
+ @if ($showDirection)
+ <td>
+ <select name="{{ $direction_name }}[__KEY__]" class="select2 mapping-picker-row-direction" style="width: 100%" data-minimum-results-for-search="Infinity" aria-label="__LABEL__ direction">
+ __DIRECTION_OPTIONS__
+ </select>
+ </td>
+ @endif
+ <td>
+ <button type="button" class="btn btn-danger mapping-picker-remove" aria-label="{{ trans('button.delete') }}">
+ <i class="fa fa-times" aria-hidden="true"></i>
+ </button>
+ </td>
+ </tr>
+</script>
+
+<script>
+document.addEventListener('DOMContentLoaded', function () {
+ var widgetId = @json($widgetId);
+ var $widget = $('[data-mapping-picker-widget="' + widgetId + '"]');
+ if ($widget.length === 0) { return; }
+
+ var $rows = $widget.find('.mapping-picker-rows');
+ var $empty = $widget.find('.mapping-picker-empty');
+ var $picker = $widget.find('.mapping-picker-picker');
+ var $newTarget = $widget.find('.mapping-picker-new-target');
+ var $newDirection = $widget.find('.mapping-picker-new-direction');
+ var $addBtn = $widget.find('.mapping-picker-add');
+ var template = $('[data-mapping-picker-template="' + widgetId + '"]').html();
+
+ // snipeit.js auto-inits .select2 elements at DOMContentLoaded, but
+ // dynamic add/remove of rows means the selects inside the template
+ // need explicit init/destroy so the widget doesn't leave hidden
+ // shadow selects behind after removals.
+ function initSelect2($el, extraOpts) {
+ var opts = extraOpts || {};
+ if ($el.hasClass('select2-hidden-accessible')) {
+ $el.select2('destroy');
+ }
+ $el.select2(opts);
+ }
+
+ function destroySelect2($el) {
+ if ($el.hasClass('select2-hidden-accessible')) {
+ $el.select2('destroy');
+ }
+ }
+
+ function encode(s) {
+ return String(s)
+ .replace(/&/g, '&amp;')
+ .replace(/</g, '&lt;')
+ .replace(/>/g, '&gt;')
+ .replace(/"/g, '&quot;');
+ }
+
+ function refreshEmptyState() {
+ var hasRows = $rows.find('tr:not(.mapping-picker-empty)').length > 0;
+ if (hasRows) { $empty.attr('hidden', ''); } else { $empty.removeAttr('hidden'); }
+ }
+
+ function optionsHtml(map, selected) {
+ var html = '';
+ for (var value in map) {
+ if (!Object.prototype.hasOwnProperty.call(map, value)) { continue; }
+ var sel = String(value) === String(selected) ? ' selected' : '';
+ html += '<option value="' + encode(value) + '"' + sel + '>' + encode(map[value]) + '</option>';
+ }
+ return html;
+ }
+
+ function notifyFormOfStructuralChange() {
+ $widget[0].dispatchEvent(new Event('input', {bubbles: true}));
+ }
+
+ function refreshAddButtonState() {
+ var key = $picker.val();
+ var target = $newTarget.val();
+ if (key && target) {
+ $addBtn.removeAttr('disabled');
+ } else {
+ $addBtn.attr('disabled', 'disabled');
+ }
+ }
+
+ function readTargetOptionsFromPicker() {
+ var $selected = $picker.find('option:selected');
+ var raw = $selected.attr('data-target-options');
+ if (!raw) { return null; }
+ try { return JSON.parse(raw); } catch (e) { return null; }
+ }
+
+ $picker.on('change', function () {
+ var options = readTargetOptionsFromPicker();
+ destroySelect2($newTarget);
+ $newTarget.empty();
+ if (options === null) {
+ $newTarget.append('<option value=""></option>').attr('disabled', 'disabled');
+ } else {
+ $newTarget.append('<option value=""></option>');
+ for (var value in options) {
+ if (value === 'skip') { continue; } // skip is not a valid mapped target
+ if (!Object.prototype.hasOwnProperty.call(options, value)) { continue; }
+ $newTarget.append('<option value="' + encode(value) + '">' + encode(options[value]) + '</option>');
+ }
+ $newTarget.removeAttr('disabled');
+ }
+ initSelect2($newTarget, {placeholder: @json((string) $pickTargetLabel), allowClear: true});
+ refreshAddButtonState();
+ });
+
+ function commitPickerRow() {
+ var key = $picker.val();
+ var target = $newTarget.val();
+ var direction = $newDirection.length ? $newDirection.val() : 'pull';
+ if (!key || !target) { return; }
+
+ var $selected = $picker.find('option:selected');
+ var label = $selected.attr('data-label') || $selected.text();
+ var optionsMap = readTargetOptionsFromPicker() || {};
+
+ var targetOptions = '';
+ for (var v in optionsMap) {
+ if (!Object.prototype.hasOwnProperty.call(optionsMap, v)) { continue; }
+ if (v === 'skip') { continue; }
+ var sel = String(v) === String(target) ? ' selected' : '';
+ targetOptions += '<option value="' + encode(v) + '"' + sel + '>' + encode(optionsMap[v]) + '</option>';
+ }
+
+ var directionOptions = @json((object) $direction_options);
+ var directionOptionsHtml = optionsHtml(directionOptions, direction);
+
+ var html = template
+ .split('__KEY__').join(encode(key))
+ .split('__LABEL__').join(encode(label))
+ .split('__TARGET_OPTIONS__').join(targetOptions)
+ .split('__DIRECTION_OPTIONS__').join(directionOptionsHtml);
+
+ var $newRow = $(html);
+ $empty.before($newRow);
+ // Init select2 on the freshly inserted row's target and
+ // direction selects so their styling matches the initially-
+ // server-rendered rows.
+ $newRow.find('.mapping-picker-row-target').each(function () {
+ initSelect2($(this));
+ });
+ $newRow.find('.mapping-picker-row-direction').each(function () {
+ initSelect2($(this), {minimumResultsForSearch: Infinity});
+ });
+ $selected.remove();
+ $picker.val('').trigger('change');
+ destroySelect2($newTarget);
+ $newTarget.empty().append('<option value=""></option>').attr('disabled', 'disabled');
+ initSelect2($newTarget, {placeholder: @json((string) $pickTargetLabel), allowClear: true});
+ if ($newDirection.length) { $newDirection.val('pull').trigger('change'); }
+ refreshEmptyState();
+ refreshAddButtonState();
+ notifyFormOfStructuralChange();
+ }
+
+ // Auto-commit the picker row into a real table row as soon as
+ // both fields have content. Committing produces a visible row so
+ // admins abandon by clicking × on that row, same UX as any
+ // existing row.
+ $newTarget.on('change', function () {
+ refreshAddButtonState();
+ if ($picker.val() && $newTarget.val()) {
+ commitPickerRow();
+ }
+ });
+
+ $addBtn.on('click', commitPickerRow);
+
+ $rows.on('click', '.mapping-picker-remove', function () {
+ var $row = $(this).closest('tr');
+ var key = $row.data('field-key');
+ var label = $row.find('td:first').text().trim();
+
+ // Destroy select2 on the row's selects before removing the DOM
+ // node so we don't leak select2's hidden shadow elements.
+ destroySelect2($row.find('.mapping-picker-row-target'));
+ destroySelect2($row.find('.mapping-picker-row-direction'));
+
+ // Reconstruct the target-options data attribute so re-adding
+ // the extra rebuilds the target dropdown with the right options.
+ var optionsMap = {};
+ $row.find('.mapping-picker-row-target option').each(function () {
+ optionsMap[$(this).val()] = $(this).text();
+ });
+ // Preserve the "skip" option in the data-target-options set
+ // even though it isn't rendered on the row-side target select.
+ // The picker JS strips it out when repopulating the new-row
+ // dropdown, so keeping it here keeps the shape consistent
+ // with the server-rendered picker options.
+ if (!optionsMap.hasOwnProperty('skip')) {
+ optionsMap = Object.assign({skip: 'Skip'}, optionsMap);
+ }
+
+ $row.remove();
+ $picker.append(
+ $('<option>')
+ .val(key)
+ .text(label)
+ .attr('data-label', label)
+ .attr('data-target-options', JSON.stringify(optionsMap))
+ );
+ $picker.trigger('change');
+ refreshEmptyState();
+ notifyFormOfStructuralChange();
+ });
+
+ // Explicit init of the picker-row target + direction and every
+ // server-rendered row's selects. snipeit.js does auto-init on
+ // .select2, but running it here means the widget stays correct
+ // when snipeit.js's timing isn't perfectly ordered against this
+ // widget's inline script.
+ initSelect2($picker, {placeholder: @json((string) $pickExtraLabel), allowClear: true});
+ initSelect2($newTarget, {placeholder: @json((string) $pickTargetLabel), allowClear: true});
+ if ($newDirection.length) {
+ initSelect2($newDirection, {minimumResultsForSearch: Infinity});
+ }
+ $rows.find('.mapping-picker-row-target').each(function () {
+ initSelect2($(this));
+ });
+ $rows.find('.mapping-picker-row-direction').each(function () {
+ initSelect2($(this), {minimumResultsForSearch: Infinity});
+ });
+
+ refreshEmptyState();
+ refreshAddButtonState();
+});
+</script>
diff --git a/resources/views/blade/sync-adapter/form.blade.php b/resources/views/blade/sync-adapter/form.blade.php
index f3c0bf320e..c27c18a105 100644
--- a/resources/views/blade/sync-adapter/form.blade.php
+++ b/resources/views/blade/sync-adapter/form.blade.php
@@ -286,40 +286,6 @@
/>
</fieldset>
- {{-- Any type: field_map entries from the adapter's credential
- schema render here in their own fieldset. Keeps them
- grouped alongside the standard mapping controls below and
- out of the credential-input section above, since they
- define WHERE fields live in the vendor payload rather than
- auth credentials. --}}
- @foreach ($adapter->settingsSchema() as $fmField)
- @if (($fmField['type'] ?? '') === 'field_map')
- @php
- $fmName = $slug.'_'.$fmField['key'];
- $fmStored = $adapter->credentialForDisplay($fmField['key']);
- $fmMap = is_string($fmStored) && $fmStored !== ''
- ? (json_decode($fmStored, true) ?: [])
- : [];
- $fmMap = old($fmName, is_array($fmMap) ? $fmMap : []);
- $fmMap = is_array($fmMap) ? $fmMap : [];
- @endphp
- <fieldset>
- <x-form.legend icon="tip" help_text="{!! $fmField['help'] ?? '' !!}">
- {{ $fmField['label'] }}
- </x-form.legend>
- <div class="form-group">
- <div class="col-md-8 col-md-offset-3">
- <x-input.field-map
- :name="$fmName"
- :options="$fmField['options'] ?? []"
- :stored="$fmMap"
- />
- </div>
- </div>
- </fieldset>
- @endif
- @endforeach
-
{{-- Push dry-run only shows for adapters that actually support
push. Turning it on makes push() log the payload instead of
sending, so admins can verify their config end-to-end against
@@ -432,84 +398,90 @@
</x-form.row>
@endforeach
- @php
- $extraFields = $adapter->extraFields();
- @endphp
+ </fieldset>
+
+ @php
+ $extraFields = $adapter->extraFields();
+ // Precompute entries for the mapping-picker widget (extras
+ // section on adapters that declare adapter-owned extras).
+ // Entry shapes supported:
+ // 'literal label string'
+ // ['label' => 'literal string', 'type' => 'text|boolean', 'admin_defined' => bool]
+ // ['label_key' => 'admin/settings/sync_adapters.extra_foo', 'type' => ..., 'admin_defined' => ...]
+ // label_key entries auto-resolve through trans() with
+ // ':vendor' bound to the adapter's typeLabel so per-vendor
+ // labels share one translation string.
+ $extraEntries = [];
+ foreach ($extraFields as $extraKey => $extraEntry) {
+ if (is_array($extraEntry) && isset($extraEntry['label_key'])) {
+ $extraLabel = trans($extraEntry['label_key'], ['vendor' => $adapter::typeLabel()]);
+ } elseif (is_array($extraEntry)) {
+ $extraLabel = $extraEntry['label'] ?? $extraKey;
+ } else {
+ $extraLabel = $extraEntry;
+ }
+ $extraType = (is_array($extraEntry) && isset($extraEntry['type'])) ? $extraEntry['type'] : 'text';
+ $extraAdminDefined = is_array($extraEntry) && ! empty($extraEntry['admin_defined']);
+ $extraEntries[$extraKey] = [
+ 'label' => $extraLabel,
+ 'target_options' => \App\SyncAdapters\MappingTargets::optionsForExtra($extraType, $extraAdminDefined),
+ 'stored_target' => $adapter->mappingFor($extraKey),
+ 'stored_direction' => $adapter->directionFor($extraKey),
+ ];
+ }
+ @endphp
+
+ @foreach ($adapter->settingsSchema() as $fmField)
+ @if (($fmField['type'] ?? '') === 'field_map')
+ @php
+ $fmName = $slug.'_'.$fmField['key'];
+ $fmStored = $adapter->credentialForDisplay($fmField['key']);
+ $fmMap = is_string($fmStored) && $fmStored !== ''
+ ? (json_decode($fmStored, true) ?: [])
+ : [];
+ $fmMap = old($fmName, is_array($fmMap) ? $fmMap : []);
+ $fmMap = is_array($fmMap) ? $fmMap : [];
+ // Load stored per-row direction values so the widget's
+ // dropdowns pre-select the correct value. Framework's
+ // direction.<key> storage is the single source of
+ // truth, shared with the standard mapping loop above.
+ $fmDirections = [];
+ foreach (array_keys($fmMap) as $fmKey) {
+ $fmDirections[$fmKey] = $adapter->directionFor($fmKey);
+ }
+ @endphp
+ <fieldset>
+ <x-form.legend icon="tip" help_text="{!! $fmField['help'] ?? '' !!}">
+ {{ $fmField['label'] }}
+ </x-form.legend>
+ <x-input.field-map
+ :name="$fmName"
+ :options="$fmField['options'] ?? []"
+ :stored="$fmMap"
+ :direction_name="$supportsPush ? $slug . '_direction' : null"
+ :direction_options="$supportsPush ? $directionOptions : []"
+ :stored_directions="$fmDirections"
+ />
+ </fieldset>
+ @endif
+ @endforeach
- @if (! empty($extraFields))
+ @if (! empty($extraFields))
+ <fieldset>
<x-form.legend icon="tip" help_text="{{ trans('admin/settings/sync_adapters.extra_fields_section_intro') }}">
{{ trans('admin/settings/sync_adapters.extra_fields_section_title', ['type' => $adapter::typeLabel()]) }}
</x-form.legend>
- @foreach ($extraFields as $extraKey => $extraEntry)
- @php
- // Entry shapes accepted:
- // 'literal label string'
- // ['label' => 'literal string', 'type' => 'text|boolean', 'admin_defined' => true|false]
- // ['label_key' => 'admin/settings/sync_adapters.extra_foo', 'type' => ..., 'admin_defined' => ...]
- // label_key entries auto-resolve through trans()
- // with ':vendor' bound to the adapter's typeLabel
- // so per-vendor labels ("Fleet Team", "Jamf UDID")
- // share one translation string.
- if (is_array($extraEntry) && isset($extraEntry['label_key'])) {
- $extraLabel = trans($extraEntry['label_key'], ['vendor' => $adapter::typeLabel()]);
- } elseif (is_array($extraEntry)) {
- $extraLabel = $extraEntry['label'] ?? $extraKey;
- } else {
- $extraLabel = $extraEntry;
- }
- $extraType = (is_array($extraEntry) && isset($extraEntry['type'])) ? $extraEntry['type'] : 'text';
- $extraAdminDefined = is_array($extraEntry) && ! empty($extraEntry['admin_defined']);
- @endphp
- <x-form.row
- :label="$extraLabel"
- :name="$slug . '_mapping_' . $extraKey"
- input_div_class="col-md-8"
- >
- <x-slot:input>
- @if ($supportsPush)
- {{-- Same two-column shape as the standard
- fields above so admins can pick a
- target column AND a direction per
- extra. Framework already respects
- directionFor() on extras via
- pushDirectedFields(), but the UI was
- only exposing the target dropdown. --}}
- <div class="row">
- <div class="col-md-8">
- <x-input.select
- :name="$slug . '_mapping[' . $extraKey . ']'"
- :options="\App\SyncAdapters\MappingTargets::optionsForExtra($extraType, $extraAdminDefined)"
- :selected="$adapter->mappingFor($extraKey)"
- style="width: 100%"
- :disabled="$locked"
- />
- </div>
- <div class="col-md-4">
- <x-input.select
- :name="$slug . '_direction[' . $extraKey . ']'"
- :options="$directionOptions"
- :selected="$adapter->directionFor($extraKey)"
- style="width: 100%"
- data-minimum-results-for-search="Infinity"
- :disabled="$locked"
- />
- </div>
- </div>
- @else
- <x-input.select
- :name="$slug . '_mapping[' . $extraKey . ']'"
- :options="\App\SyncAdapters\MappingTargets::optionsForExtra($extraType, $extraAdminDefined)"
- :selected="$adapter->mappingFor($extraKey)"
- style="width: 100%"
- :disabled="$locked"
- />
- @endif
- </x-slot:input>
- </x-form.row>
- @endforeach
- @endif
- </fieldset>
+ <x-input.mapping-picker
+ :name="$slug . '_mapping'"
+ :direction_name="$supportsPush ? $slug . '_direction' : null"
+ :entries="$extraEntries"
+ :direction_options="$directionOptions"
+ :supports_push="$supportsPush"
+ :locked="$locked"
+ />
+ </fieldset>
+ @endif
{{-- Composed notes fieldset. Renders a multi-field notes blob
from Snipe-IT (asset_tag + status + assigned user + custom
diff --git a/tests/Feature/SyncAdapters/AppleBusinessManager/AppleBusinessManagerAdapterTest.php b/tests/Feature/SyncAdapters/AppleBusinessManager/AppleBusinessManagerAdapterTest.php
index 10c0379a21..c526d3c959 100644
--- a/tests/Feature/SyncAdapters/AppleBusinessManager/AppleBusinessManagerAdapterTest.php
+++ b/tests/Feature/SyncAdapters/AppleBusinessManager/AppleBusinessManagerAdapterTest.php
@@ -272,6 +272,45 @@ class AppleBusinessManagerAdapterTest extends TestCase
$this->assertSame('[]', $stored);
}
+ public function test_saveconfig_persists_widget_picker_row_without_click_add()
+ {
+ // The mapping-picker widget's picker row submits its
+ // unfinished pair under <slug>_mapping_pending[key|value]
+ // and its direction under <slug>_direction_pending[value] so
+ // admins can save the form without clicking + first.
+ $this->configuredAdapter();
+ $instance = SyncAdapterInstance::where('slug', 'abm')->firstOrFail();
+
+ $adapter = new AppleBusinessManagerAdapter($instance->fresh());
+ $adapter->saveConfig(\Illuminate\Http\Request::create('/', 'POST', [
+ 'abm_url' => '',
+ 'abm_mapping_pending' => ['key' => 'abm_product_family', 'value' => 'custom:7'],
+ 'abm_direction_pending' => ['value' => 'pull'],
+ ]));
+
+ $this->assertSame('custom:7', SyncAdapterConfig::get($instance->id, 'mapping.abm_product_family'));
+ $this->assertSame('pull', SyncAdapterConfig::get($instance->id, 'direction.abm_product_family'));
+ }
+
+ public function test_saveconfig_skips_incomplete_mapping_picker_row()
+ {
+ // If the admin picks a source but hasn't chosen a target, the
+ // pair is unfinished. Save shouldn't persist a half-mapping
+ // and shouldn't strand a direction.
+ $this->configuredAdapter();
+ $instance = SyncAdapterInstance::where('slug', 'abm')->firstOrFail();
+
+ $adapter = new AppleBusinessManagerAdapter($instance->fresh());
+ $adapter->saveConfig(\Illuminate\Http\Request::create('/', 'POST', [
+ 'abm_url' => '',
+ 'abm_mapping_pending' => ['key' => 'abm_product_family', 'value' => ''],
+ 'abm_direction_pending' => ['value' => 'pull'],
+ ]));
+
+ $this->assertNull(SyncAdapterConfig::get($instance->id, 'mapping.abm_product_family'));
+ $this->assertNull(SyncAdapterConfig::get($instance->id, 'direction.abm_product_family'));
+ }
+
public function test_survives_mdm_server_map_failure_and_still_yields_records()
{
$adapter = $this->configuredAdapter();
diff --git a/tests/Feature/SyncAdapters/CustomHttp/CustomHttpAdapterTest.php b/tests/Feature/SyncAdapters/CustomHttp/CustomHttpAdapterTest.php
index 6c78b0b751..fede4598bf 100644
--- a/tests/Feature/SyncAdapters/CustomHttp/CustomHttpAdapterTest.php
+++ b/tests/Feature/SyncAdapters/CustomHttp/CustomHttpAdapterTest.php
@@ -11,6 +11,8 @@ use App\SyncAdapters\CustomHttp\CustomHttpAdapter;
use App\SyncAdapters\PushableAdapter;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Http;
+use Illuminate\Support\Facades\Log;
+use Mockery;
use Tests\TestCase;
class CustomHttpAdapterTest extends TestCase
@@ -161,14 +163,22 @@ class CustomHttpAdapterTest extends TestCase
Http::assertSent(fn ($request) => ! $request->hasHeader('Authorization'));
}
- public function test_extras_definition_emits_extra_fields_and_populates_them()
+ public function test_custom_field_destinations_in_field_paths_route_values_through_extras()
{
+ // Under the unified Vendor Response Paths widget, admins pick
+ // a custom-field destination directly in the field-map picker
+ // and give it a dot-path. field_paths JSON stores the pair,
+ // extraFields() derives from those custom: entries, and the
+ // adapter's saveConfig hook writes mapping.<custom:X> = <same>
+ // so the framework routes each extracted value.
$adapter = $this->configuredAdapter([
'field_source_id' => 'id',
- 'extras_definition' => json_encode([
- ['key' => 'vendor_tag', 'label' => 'Vendor Asset Tag', 'path' => 'tags.asset_tag'],
- ['key' => 'vendor_room', 'label' => 'Vendor Room', 'path' => 'location.room'],
+ 'field_paths' => json_encode([
+ 'custom:5' => 'tags.asset_tag',
+ 'custom:6' => 'location.room',
]),
+ 'mapping.custom:5' => 'custom:5',
+ 'mapping.custom:6' => 'custom:6',
]);
Http::fake([
@@ -181,16 +191,171 @@ class CustomHttpAdapterTest extends TestCase
]),
]);
- // Both metadata AND value must round-trip through extraFields()
- // and normalize().
$this->assertSame(
- ['vendor_tag' => ['label' => 'Vendor Asset Tag'], 'vendor_room' => ['label' => 'Vendor Room']],
+ [
+ 'custom:5' => ['label' => 'custom:5', 'admin_defined' => true],
+ 'custom:6' => ['label' => 'custom:6', 'admin_defined' => true],
+ ],
$adapter->extraFields(),
);
$records = iterator_to_array($adapter->pull());
- $this->assertSame('ACME-123', $records[0]->extra['vendor_tag']);
- $this->assertSame('Server Room A', $records[0]->extra['vendor_room']);
+ $this->assertSame('ACME-123', $records[0]->extra['custom:5']);
+ $this->assertSame('Server Room A', $records[0]->extra['custom:6']);
+ }
+
+ public function test_saveconfig_persists_widget_picker_row_without_click_add()
+ {
+ $adapter = $this->configuredAdapter([]);
+ $slug = $adapter->name();
+ $instance = SyncAdapterInstance::where('slug', $slug)->firstOrFail();
+
+ $adapter->saveConfig(\Illuminate\Http\Request::create('/', 'POST', [
+ $slug . '_url' => 'https://vendor.example/api',
+ $slug . '_source_id_path' => 'id',
+ $slug . '_field_paths' => [],
+ $slug . '_field_paths_pending' => ['key' => 'hostname', 'value' => 'device.name'],
+ $slug . '_direction_pending' => ['value' => 'push'],
+ ]));
+
+ $stored = json_decode(SyncAdapterConfig::get($instance->id, 'field_paths'), true);
+ $this->assertSame(['hostname' => 'device.name'], $stored);
+ $this->assertSame('push', SyncAdapterConfig::get($instance->id, 'direction.hostname'));
+ }
+
+ public function test_saveconfig_persists_picker_row_for_custom_field_destination()
+ {
+ // Same save-without-click path, but the picker row targets a
+ // custom-field destination. The unified widget lets admins
+ // choose custom:X directly, and CustomHttp's saveConfig
+ // override writes the self-routing mapping so the framework
+ // routes the extracted value at sync time.
+ $adapter = $this->configuredAdapter([]);
+ $slug = $adapter->name();
+ $instance = SyncAdapterInstance::where('slug', $slug)->firstOrFail();
+
+ $adapter->saveConfig(\Illuminate\Http\Request::create('/', 'POST', [
+ $slug . '_url' => 'https://vendor.example/api',
+ $slug . '_source_id_path' => 'id',
+ $slug . '_field_paths' => [],
+ $slug . '_field_paths_pending' => ['key' => 'custom:9', 'value' => 'location.room'],
+ $slug . '_direction_pending' => ['value' => 'pull'],
+ ]));
+
+ $stored = json_decode(SyncAdapterConfig::get($instance->id, 'field_paths'), true);
+ $this->assertSame(['custom:9' => 'location.room'], $stored);
+ $this->assertSame('custom:9', SyncAdapterConfig::get($instance->id, 'mapping.custom:9'));
+ $this->assertSame('pull', SyncAdapterConfig::get($instance->id, 'direction.custom:9'));
+ }
+
+ public function test_saveconfig_skips_incomplete_picker_row()
+ {
+ // Half-filled picker rows (destination picked but path empty,
+ // or vice versa) submit without both values. Base save drops
+ // them so the admin doesn't get a mystery blank entry after
+ // hitting Save on an unfinished form.
+ $adapter = $this->configuredAdapter([]);
+ $slug = $adapter->name();
+ $instance = SyncAdapterInstance::where('slug', $slug)->firstOrFail();
+
+ $adapter->saveConfig(\Illuminate\Http\Request::create('/', 'POST', [
+ $slug . '_url' => 'https://vendor.example/api',
+ $slug . '_source_id_path' => 'id',
+ $slug . '_field_paths' => [],
+ $slug . '_field_paths_pending' => ['key' => 'hostname', 'value' => ''],
+ $slug . '_direction_pending' => ['value' => 'push'],
+ ]));
+
+ $stored = json_decode(SyncAdapterConfig::get($instance->id, 'field_paths'), true);
+ $this->assertSame([], $stored);
+ $this->assertNull(SyncAdapterConfig::get($instance->id, 'direction.hostname'));
+ }
+
+ public function test_pull_warns_when_configured_path_returns_null_on_every_record()
+ {
+ // A dot-path that returns null on every record is almost
+ // always a typo or a stale/renamed vendor
+ // field.
+ $adapter = $this->configuredAdapter([
+ 'field_source_id' => 'id',
+ 'field_hostname' => 'name',
+ 'field_serial' => 'blargh.not_a_real_field',
+ ]);
+
+ Http::fake([
+ 'vendor.example/*' => Http::response([
+ ['id' => 'dev-1', 'name' => 'host-a'],
+ ['id' => 'dev-2', 'name' => 'host-b'],
+ ]),
+ ]);
+
+ $captured = [];
+ $channel = Mockery::mock();
+ $channel->shouldReceive('warning')->andReturnUsing(function ($msg) use (&$captured) {
+ $captured[] = $msg;
+ });
+ $channel->shouldReceive('info');
+ Log::shouldReceive('channel')->with('sync-adapters')->andReturn($channel);
+
+ iterator_to_array($adapter->pull());
+
+ $matches = array_filter($captured, fn($m) => str_contains($m, 'blargh.not_a_real_field') && str_contains($m, 'serial'));
+ $this->assertNotEmpty($matches, 'Expected an always-null summary warning naming the offending path. Captured: ' . json_encode($captured));
+ }
+
+ public function test_pull_does_not_warn_when_path_resolves_on_at_least_one_record()
+ {
+ // A path that misses on some records but hits on others is
+ // a normal partial-field scenario (optional vendor data), not
+ // a config error. No warning should fire.
+ $adapter = $this->configuredAdapter([
+ 'field_source_id' => 'id',
+ 'field_hostname' => 'name',
+ ]);
+
+ Http::fake([
+ 'vendor.example/*' => Http::response([
+ ['id' => 'dev-1', 'name' => 'host-a'],
+ ['id' => 'dev-2'],
+ ]),
+ ]);
+
+ $captured = [];
+ $channel = Mockery::mock();
+ $channel->shouldReceive('warning')->andReturnUsing(function ($msg) use (&$captured) {
+ $captured[] = $msg;
+ });
+ $channel->shouldReceive('info');
+ Log::shouldReceive('channel')->with('sync-adapters')->andReturn($channel);
+
+ iterator_to_array($adapter->pull());
+
+ $this->assertEmpty($captured, 'No warning expected when the path resolves on at least one record. Captured: ' . json_encode($captured));
+ }
+
+ public function test_pull_does_not_warn_on_empty_vendor_response()
+ {
+ // With zero records processed we can't tell whether a path
+ // is a typo or the vendor just returned nothing, so the
+ // warning shouldn't fire.
+ $adapter = $this->configuredAdapter([
+ 'field_source_id' => 'id',
+ 'field_hostname' => 'blargh.not_a_valid_field',
+ ]);
+
+ Http::fake(['vendor.example/*' => Http::response([])]);
+
+ $captured = [];
+ $channel = Mockery::mock();
+ $channel->shouldReceive('warning')->andReturnUsing(function ($msg) use (&$captured) {
+ $captured[] = $msg;
+ });
+ $channel->shouldReceive('info');
+ Log::shouldReceive('channel')->with('sync-adapters')->andReturn($channel);
+
+ iterator_to_array($adapter->pull());
+
+ $this->assertEmpty($captured);
}
public function test_missing_dot_path_leaves_field_null_without_throwing()
@@ -419,16 +584,6 @@ class CustomHttpAdapterTest extends TestCase
iterator_to_array($adapter->pull());
}
- public function test_malformed_extras_json_is_ignored()
- {
- $adapter = $this->configuredAdapter([
- 'field_source_id' => 'id',
- 'extras_definition' => 'not valid json {{{',
- ]);
-
- $this->assertSame([], $adapter->extraFields());
- }
-
public function test_html_escaped_string_values_are_decoded_on_ingest()
{
// Some APIs (Snipe-IT's own /api/v1/hardware is one) run
@@ -438,11 +593,12 @@ class CustomHttpAdapterTest extends TestCase
// round-tripping the entity into the asset table.
$adapter = $this->configuredAdapter([
'field_source_id' => 'id',
- 'field_hostname' => 'name',
- 'field_model' => 'model',
- 'extras_definition' => json_encode([
- ['key' => 'vendor_notes', 'label' => 'Vendor Notes', 'path' => 'notes'],
+ 'field_paths' => json_encode([
+ 'hostname' => 'name',
+ 'model' => 'model',
+ 'custom:5' => 'notes',
]),
+ 'mapping.custom:5' => 'custom:5',
]);
Http::fake([
@@ -460,7 +616,7 @@ class CustomHttpAdapterTest extends TestCase
$this->assertSame('wksn & friends', $records[0]->hostname);
$this->assertSame("MacBook Pro 13\" '16", $records[0]->hardwareModel);
- $this->assertSame('Ampersand: A & B', $records[0]->extra['vendor_notes']);
+ $this->assertSame('Ampersand: A & B', $records[0]->extra['custom:5']);
}
public function test_last_seen_string_parses_to_carbon()
@@ -709,13 +865,7 @@ class CustomHttpAdapterTest extends TestCase
// Anything not in this set is stored plaintext.
$secretKeys = ['bearer_token', 'basic_password', 'api_key_value'];
- // Shim: field-map storage collapsed 12 individual field_*
- // credential keys into a single field_paths JSON blob, and
- // source_id was hoisted to its own standalone credential
- // (source_id_path) to keep the required identifier visible
- // rather than buried in the picker. Tests pre-date those
- // refactors and still write the old shape for readability,
- // so translate here.
+
if (array_key_exists('field_source_id', $config)) {
SyncAdapterConfig::put($instance->id, 'source_id_path', (string) $config['field_source_id']);
unset($config['field_source_id']);
@@ -742,10 +892,7 @@ class CustomHttpAdapterTest extends TestCase
}
}
// Shim: canPush() now gates on push_method rather than
- // push_path. Existing tests set push_path without specifying
- // a method (default was PATCH before, disabled after). If a
- // test provided push_path without a push_method, default to
- // PATCH so those assertions keep passing without rewrites.
+ // push_path.
if (array_key_exists('push_path', $config) && ! array_key_exists('push_method', $config)) {
$config['push_method'] = 'PATCH';
}
diff --git a/tests/Feature/SyncAdapters/ExtraFieldMappingTest.php b/tests/Feature/SyncAdapters/ExtraFieldMappingTest.php
index 5840de77bc..56c1ec27be 100644
--- a/tests/Feature/SyncAdapters/ExtraFieldMappingTest.php
+++ b/tests/Feature/SyncAdapters/ExtraFieldMappingTest.php
@@ -13,16 +13,6 @@ use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Http;
use Tests\TestCase;
-/**
- * Coverage for the extra-field mapping flow: adapters declare
- * vendor-specific extra keys via extraFields(), admin maps each to a
- * custom field, and SyncAdapter writes the (stringified) value
- * onto the asset's dynamic column.
- *
- * Fleet is the workhorse here because its normalize() emits a mix of
- * scalar (fleet_team, fleet_uuid, fleet_status) and array
- * (fleet_labels) values, exercising the stringifier for both shapes.
- */
class ExtraFieldMappingTest extends TestCase
{
protected function setUp(): void
@@ -345,13 +335,13 @@ class ExtraFieldMappingTest extends TestCase
$this->assertArrayHasKey('fleet_status', $extras);
}
- public function test_settings_page_renders_extra_field_dropdowns_for_adapter_that_declares_them()
+ public function test_settings_page_renders_extra_field_picker_for_adapter_that_declares_them()
{
// Side-effect factory create. The custom field is a fixture that
- // has to exist on the DB for the settings page to render it as an
- // extras-mapping target. The returned instance isn't referenced
- // by name; the assertion just checks the field's name string
- // shows up in the rendered HTML.
+ // has to exist on the DB for the settings page to render it as
+ // an extras-mapping target. The returned instance isn't
+ // referenced by name. The assertion just checks the field's
+ // name string shows up in the rendered HTML.
CustomField::factory()->create(['element' => 'text', 'name' => 'Team Assignment']);
$html = $this->actingAs(\App\Models\User::factory()->superuser()->create())
@@ -359,10 +349,14 @@ class ExtraFieldMappingTest extends TestCase
->assertOk()
->getContent();
- // Rows for each Fleet extra field appear on the page.
- $this->assertStringContainsString('fleet_mapping[fleet_team]', $html);
- $this->assertStringContainsString('fleet_mapping[fleet_labels]', $html);
- // Custom field is offered as a target for extras.
+ // Each unmapped Fleet extra shows up as a picker option carrying
+ // its key as the value and its resolved label as the option text
+ // (mapping-picker widget replaced the one-row-per-extra @foreach).
+ $this->assertStringContainsString('value="fleet_team"', $html);
+ $this->assertStringContainsString('value="fleet_labels"', $html);
+ // Custom field is offered as a target inside each option's
+ // data-target-options JSON. The custom field's name shows up
+ // literally in that JSON.
$this->assertStringContainsString('Team Assignment', $html);
}
diff --git a/tests/Unit/Rules/CustomHttpExtrasJsonRuleTest.php b/tests/Unit/Rules/CustomHttpExtrasJsonRuleTest.php
deleted file mode 100644
index dead9f5639..0000000000
--- a/tests/Unit/Rules/CustomHttpExtrasJsonRuleTest.php
+++ /dev/null
@@ -1,90 +0,0 @@
-<?php
-
-namespace Tests\Unit\Rules;
-
-use App\Rules\CustomHttpExtrasJsonRule;
-use Illuminate\Support\Facades\Validator;
-use Tests\TestCase;
-
-
-class CustomHttpExtrasJsonRuleTest extends TestCase
-{
- public function test_empty_string_passes()
- {
- $this->assertTrue($this->validate(''));
- }
-
- public function test_null_passes()
- {
- $this->assertTrue($this->validate(null));
- }
-
- public function test_whitespace_only_passes()
- {
- $this->assertTrue($this->validate(" \n "));
- }
-
- public function test_valid_json_array_of_complete_entries_passes()
- {
- $this->assertTrue($this->validate(json_encode([
- ['key' => 'vendor_tag', 'label' => 'Vendor Tag', 'path' => 'tags.asset_tag'],
- ['key' => 'vendor_room', 'label' => 'Vendor Room', 'path' => 'location.room'],
- ])));
- }
-
- public function test_entry_without_label_passes_since_label_is_optional()
- {
- // key and path are required, but label falls back to key at read time.
- $this->assertTrue($this->validate(json_encode([
- ['key' => 'vendor_tag', 'path' => 'tags.asset_tag'],
- ])));
- }
-
- public function test_malformed_json_fails()
- {
- // Exactly what bit the user: object followed by a bare number
- // with no comma. json_decode returns null with a syntax error.
- $this->assertFalse($this->validate(
- '[{"key": "vendor_field", "label": "Human Label", "path": "dot.path.to.value"} 90]'
- ));
- }
-
- public function test_not_an_array_fails()
- {
- $this->assertFalse($this->validate('{"key": "one"}'));
- }
-
- public function test_entry_not_an_object_fails()
- {
- $this->assertFalse($this->validate(json_encode(['just a string', 'another'])));
- }
-
- public function test_entry_missing_key_fails()
- {
- $this->assertFalse($this->validate(json_encode([
- ['label' => 'Missing Key', 'path' => 'tags.a'],
- ])));
- }
-
- public function test_entry_missing_path_fails()
- {
- $this->assertFalse($this->validate(json_encode([
- ['key' => 'vendor_tag', 'label' => 'Missing Path'],
- ])));
- }
-
- public function test_entry_with_blank_key_fails()
- {
- $this->assertFalse($this->validate(json_encode([
- ['key' => ' ', 'path' => 'tags.a'],
- ])));
- }
-
- private function validate(?string $value): bool
- {
- return Validator::make(
- ['blob' => $value],
- ['blob' => ['nullable', new CustomHttpExtrasJsonRule]],
- )->passes();
- }
-}