Skip to content

A free open source IT asset/license management system

Assets API: Fixed #18727 and #16883 -

snipe34dafe9eedcb
diff --git a/app/Http/Controllers/Api/AssetsController.php b/app/Http/Controllers/Api/AssetsController.php
index 2f1ced473d..cf41430fd6 100644
--- a/app/Http/Controllers/Api/AssetsController.php
+++ b/app/Http/Controllers/Api/AssetsController.php
@@ -6,10 +6,12 @@ use App\Events\CheckoutableCheckedIn;
use App\Helpers\Helper;
use App\Http\Controllers\Controller;
use App\Http\Requests\AssetCheckoutRequest;
+use App\Http\Requests\BulkUpdateAssetsRequest;
use App\Http\Requests\FilterRequest;
use App\Http\Requests\ImageUploadRequest;
use App\Http\Requests\StoreAssetRequest;
use App\Http\Requests\UpdateAssetRequest;
+use App\Http\Requests\UploadFileRequest;
use App\Http\Traits\MigratesLegacyAssetLocations;
use App\Http\Transformers\ActionlogsTransformer;
use App\Http\Transformers\AssetsTransformer;
@@ -27,7 +29,6 @@ use App\Models\LicenseSeat;
use App\Models\Location;
use App\Models\Setting;
use App\Models\User;
-use App\Observers\AssetObserver;
use App\View\Label;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder;
@@ -786,7 +787,10 @@ class AssetsController extends Controller
}
/**
- * Accepts a POST request to update an asset
+ * Update a single asset. Route-model-binding on {asset} guarantees the
+ * caller is either operating on a real Asset or 404'd at routing.
+ * Response shape is the legacy `{status, messages, payload}` body every
+ * integration already knows.
*
* @author [A. Gianotto] [<[email protected]>]
*
@@ -794,25 +798,172 @@ class AssetsController extends Controller
*/
public function update(UpdateAssetRequest $request, Asset $asset): JsonResponse
{
- $asset->fill($request->validated());
+ $result = $this->applyAssetUpdate($asset, $request);
+
+ return response()->json($this->formatSingleAssetResponse($result));
+ }
+
+ /**
+ * Bulk update: `ids` in the request body names which assets to touch,
+ * every other field is the update payload applied to each of them.
+ * Per-row envelope response so callers can see which ids succeeded and
+ * which failed without looping the endpoint themselves.
+ */
+ public function bulkUpdate(BulkUpdateAssetsRequest $request): JsonResponse
+ {
+ $ids = array_values(array_unique(array_map('intval', (array) $request->input('ids', []))));
+
+ $assets = Asset::whereIn('id', $ids)->get()->keyBy('id');
+
+ $results = [];
+ $success_count = 0;
+ $error_count = 0;
+
+ foreach ($ids as $id) {
+ if (! $assets->has($id)) {
+ $results[] = [
+ 'id' => $id,
+ 'status' => 'error',
+ 'messages' => trans('admin/hardware/message.does_not_exist'),
+ 'payload' => null,
+ ];
+ $error_count++;
+
+ continue;
+ }
+
+ $asset = $assets->get($id);
+
+ // Per-row auth: a caller who can update one asset may not be able
+ // to update another (FMCS, tightened policy). Deny one row rather
+ // than 403ing the whole batch.
+ if (! Gate::allows('update', $asset)) {
+ $results[] = [
+ 'id' => $id,
+ 'status' => 'error',
+ 'messages' => trans('general.unauthorized'),
+ 'payload' => null,
+ ];
+ $error_count++;
+
+ continue;
+ }
+
+ $result = $this->applyAssetUpdate($asset, $request);
+ $row = $this->buildRowResult($id, $result);
+ $results[] = $row;
+
+ $row['status'] === 'success' ? $success_count++ : $error_count++;
+ }
+
+ return response()->json($this->assembleBulkResponse($results, $success_count, $error_count));
+ }
+
+ /**
+ * Turn a single applyAssetUpdate() result into the per-row shape used by the
+ * bulk response. Reuses formatSingleAssetResponse() so the row's payload +
+ * error handling stays byte-identical to the legacy singular response.
+ */
+ private function buildRowResult(int $id, array $result): array
+ {
+ $formatted = $this->formatSingleAssetResponse($result);
+
+ return [
+ 'id' => $id,
+ 'status' => $formatted['status'],
+ 'messages' => $formatted['messages'],
+ 'payload' => $formatted['payload'],
+ ];
+ }
+
+ /**
+ * Compute the overall status + summary message for a batch and return the
+ * full bulk response envelope. Used by bulkUpdate() and by update() when
+ * the caller opts into the bulk shape via `?response=bulk`.
+ */
+ private function assembleBulkResponse(array $results, int $success_count, int $error_count): array
+ {
+ $overall_status = match (true) {
+ $error_count === 0 => 'success',
+ $success_count === 0 => 'error',
+ default => 'partial',
+ };
+
+ $message = match ($overall_status) {
+ 'success' => trans_choice('admin/hardware/message.bulk_update.success', $success_count, ['count' => $success_count]),
+ 'partial' => trans('admin/hardware/message.bulk_update.partial', ['success' => $success_count, 'failed' => $error_count]),
+ 'error' => trans('admin/hardware/message.bulk_update.error'),
+ };
+
+ return [
+ 'status' => $overall_status,
+ 'messages' => $message,
+ 'results' => $results,
+ ];
+ }
+
+ /**
+ * Format an applyAssetUpdate() result into the legacy single-asset API
+ * response body. Used by update() (default shape) and by buildRowResult()
+ * to shape each row of a bulk response.
+ *
+ * Kept as a flat asset payload (not through AssetsTransformer) so the
+ * response continues to match the shape existing integrations rely on.
+ */
+ private function formatSingleAssetResponse(array $result): array
+ {
+ if (! empty($result['error_response_key'])) {
+ return Helper::formatStandardApiResponse('error', null, trans($result['error_response_key']));
+ }
+
+ if (! $result['success']) {
+ return Helper::formatStandardApiResponse('error', null, $result['errors']);
+ }
+
+ return Helper::formatStandardApiResponse('success', $result['asset'], trans($result['message']));
+ }
+
+ /**
+ * Apply a validated UpdateAssetRequest payload to a single Asset.
+ *
+ * Shared between update() and bulkUpdate(), so the transaction, checkout
+ * side-effects, and encrypted-custom-field gating live in one place.
+ * Returns the neutral result shape that formatSingleAssetResponse() /
+ * buildRowResult() turn into the legacy or bulk-envelope response body.
+ *
+ * @return array{
+ * success: bool,
+ * asset: Asset|null,
+ * message: string|null,
+ * errors: mixed,
+ * encrypted_field_warning: bool,
+ * error_response_key: string|null,
+ * }
+ *
+ * `error_response_key` is set for early-exit conditions that need a
+ * specific translation key rather than a validation-errors payload
+ * (e.g. an unresolvable checkout target). Callers translate.
+ */
+ private function applyAssetUpdate(Asset $asset, UpdateAssetRequest $request): array
+ {
+ $validated = $request->validated();
+
+ $asset->fill($validated);
if ($request->has('model_id')) {
- $asset->model()->associate(AssetModel::find($request->validated()['model_id']));
+ $asset->model()->associate(AssetModel::find($validated['model_id']));
}
if ($request->has('company_id')) {
- $asset->company_id = Company::getIdForCurrentUser($request->validated()['company_id']);
+ $asset->company_id = Company::getIdForCurrentUser($validated['company_id']);
}
if ($request->has('rtd_location_id') && ! $request->has('location_id')) {
- $asset->location_id = $request->validated()['rtd_location_id'];
+ $asset->location_id = $validated['rtd_location_id'];
}
if ($request->input('last_audit_date')) {
$asset->last_audit_date = Carbon::parse($request->input('last_audit_date'))->startOfDay()->format('Y-m-d H:i:s');
}
- /**
- * this is here just legacy reasons. Api\AssetController
- * used image_source once to allow encoded image uploads.
- */
+ // Legacy shim: an older release accepted image_source in place of image.
if ($request->has('image_source')) {
$request->offsetSet('image', $request->offsetGet('image_source'));
}
@@ -820,43 +971,58 @@ class AssetsController extends Controller
$asset = $request->handleImages($asset);
$model = $asset->model;
- // Update custom fields
$problems_updating_encrypted_custom_fields = false;
- if (($model) && (isset($model->fieldset))) {
+ if ($model && isset($model->fieldset)) {
foreach ($model->fieldset->fields as $field) {
+ if (! $request->has($field->db_column)) {
+ continue;
+ }
+
$field_val = $request->input($field->db_column, null);
- if ($request->has($field->db_column)) {
- if ($field->element == 'checkbox') {
- if (is_array($field_val)) {
- $field_val = implode(',', $field_val);
- }
- }
- if ($field->field_encrypted == '1') {
- if (Gate::allows('assets.view.encrypted_custom_fields')) {
- $field_val = Crypt::encrypt($field_val);
- } else {
- $problems_updating_encrypted_custom_fields = true;
+ if ($field->element === 'checkbox' && is_array($field_val)) {
+ $field_val = implode(',', $field_val);
+ }
- continue;
- }
+ if ($field->field_encrypted == '1') {
+ if (Gate::allows('assets.view.encrypted_custom_fields')) {
+ $field_val = Crypt::encrypt($field_val);
+ } else {
+ // Skip encrypted-field updates for callers without the
+ // permission, but flag it so the response can nudge them.
+ $problems_updating_encrypted_custom_fields = true;
+
+ continue;
}
- $asset->{$field->db_column} = $field_val;
}
+
+ $asset->{$field->db_column} = $field_val;
}
}
+
$target = $this->resolveCheckoutTargetForAssetMutation($request, $asset->id);
$requestedCheckout = $request->filled('assigned_user') || $request->filled('assigned_asset') || $request->filled('assigned_location');
- if ($requestedCheckout && (! $target)) {
- return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/hardware/message.does_not_exist')));
+ if ($requestedCheckout && ! $target) {
+ return [
+ 'success' => false,
+ 'asset' => null,
+ 'message' => null,
+ 'errors' => null,
+ 'encrypted_field_warning' => false,
+ 'error_response_key' => 'admin/hardware/message.does_not_exist',
+ ];
}
- if ($requestedCheckout) {
- $companyMismatchResponse = $this->checkoutCompanyMismatchResponse($asset, $target);
- if ($companyMismatchResponse) {
- return $companyMismatchResponse;
- }
+ if ($requestedCheckout && ! $asset->canCheckoutTo($target)) {
+ return [
+ 'success' => false,
+ 'asset' => null,
+ 'message' => null,
+ 'errors' => null,
+ 'encrypted_field_warning' => false,
+ 'error_response_key' => 'general.error_user_company',
+ ];
}
$updated = DB::transaction(function () use ($asset, $request, $target, $requestedCheckout): bool {
@@ -865,8 +1031,8 @@ class AssetsController extends Controller
}
if ($requestedCheckout) {
- // Using `->has` preserves the asset name if the name parameter was not included in request.
- $asset_name = request()->has('name') ? request('name') : $asset->name;
+ // Preserve the asset name if the name wasn't in the payload.
+ $asset_name = $request->has('name') ? $request->input('name') : $asset->name;
$location = null;
if ($request->filled('assigned_user')) {
@@ -877,13 +1043,13 @@ class AssetsController extends Controller
$location = $target->id;
}
- // Keep update + optional checkout side effects atomic.
if (! $asset->checkOut($target, auth()->user(), date('Y-m-d H:i:s'), '', 'Checked out on asset update', $asset_name, $location)) {
return false;
}
if ($request->filled('assigned_asset')) {
- Asset::where('assigned_type', Asset::class)->where('assigned_to', $asset->id)
+ Asset::where('assigned_type', Asset::class)
+ ->where('assigned_to', $asset->id)
->update(['location_id' => $target->location_id]);
}
}
@@ -891,26 +1057,37 @@ class AssetsController extends Controller
return true;
});
- if ($updated) {
-
- if ($asset->image) {
- $asset->image = $asset->getImageUrl();
- }
+ if (! $updated) {
+ return [
+ 'success' => false,
+ 'asset' => null,
+ 'message' => null,
+ 'errors' => $asset->getErrors(),
+ 'encrypted_field_warning' => false,
+ 'error_response_key' => null,
+ ];
+ }
- if ($problems_updating_encrypted_custom_fields) {
- return response()->json(Helper::formatStandardApiResponse('success', $asset, trans('admin/hardware/message.update.encrypted_warning')));
- // Below is the *correct* return since it uses the transformer, but we have to use the old, flat return for now until we can update Jamf2Snipe and Kanji2Snipe
- // return response()->json(Helper::formatStandardApiResponse('success', (new AssetsTransformer)->transformAsset($asset), trans('admin/hardware/message.update.encrypted_warning')));
- } else {
- return response()->json(Helper::formatStandardApiResponse('success', $asset, trans('admin/hardware/message.update.success')));
- // Below is the *correct* return since it uses the transformer, but we have to use the old, flat return for now until we can update Jamf2Snipe and Kanji2Snipe
- // / return response()->json(Helper::formatStandardApiResponse('success', (new AssetsTransformer)->transformAsset($asset), trans('admin/hardware/message.update.success')));
- }
+ if ($asset->image) {
+ $asset->image = $asset->getImageUrl();
}
- return response()->json(Helper::formatStandardApiResponse('error', null, $asset->getErrors()), 200);
+ return [
+ 'success' => true,
+ 'asset' => $asset,
+ 'message' => $problems_updating_encrypted_custom_fields
+ ? 'admin/hardware/message.update.encrypted_warning'
+ : 'admin/hardware/message.update.success',
+ 'errors' => null,
+ 'encrypted_field_warning' => $problems_updating_encrypted_custom_fields,
+ 'error_response_key' => null,
+ ];
}
+ /**
+ * Resolve the assignee target from the request payload. Used by
+ * applyAssetUpdate() as well as store() and checkout().
+ */
private function resolveCheckoutTargetForAssetMutation(Request $request, ?int $assetId = null): User|Asset|Location|null
{
if ($request->filled('assigned_user')) {
@@ -928,6 +1105,11 @@ class AssetsController extends Controller
return null;
}
+ /**
+ * Company-mismatch check used by store() and checkout(). applyAssetUpdate()
+ * inlines the equivalent check because it needs to return the neutral
+ * result shape (not a JsonResponse) so the bulk envelope can wrap it.
+ */
private function checkoutCompanyMismatchResponse(Asset $asset, User|Asset|Location $target): ?JsonResponse
{
if (! $asset->canCheckoutTo($target)) {
@@ -1242,10 +1424,115 @@ class AssetsController extends Controller
*
* @since [v4.0]
*/
- public function audit(Request $request, Asset $asset): JsonResponse
+ public function audit(UploadFileRequest $request, ?Asset $asset = null): JsonResponse
+ {
+ $this->authorize('audit', Asset::class);
+
+ // On the legacy route the URL has no {asset} — resolve from the body
+ // via audit_key + audit_by_field (or the fallback asset_tag field).
+ // On the newer route the Asset is bound by RMB, so body-based lookup
+ // is skipped entirely.
+ $resolvedAsset = $asset ?: $this->resolveAuditAssetFromBody($request);
+
+ if (! $resolvedAsset) {
+ return response()->json(Helper::formatStandardApiResponse(
+ 'error',
+ $this->auditFailPayload($request),
+ trans('admin/hardware/message.does_not_exist')
+ ), 200);
+ }
+
+ $result = $this->applyAssetAudit($resolvedAsset, $request);
+
+ return response()->json($this->formatSingleAuditResponse($result));
+ }
+
+ /**
+ * Bulk audit: `ids` in the request body names which assets to audit,
+ * everything else on the request body is the shared audit payload
+ * (note, next_audit_date, location, uploaded image, etc.) applied to
+ * each. Per-row envelope response.
+ */
+ public function bulkAudit(UploadFileRequest $request): JsonResponse
{
$this->authorize('audit', Asset::class);
+ $ids = array_values(array_unique(array_map('intval', (array) $request->input('ids', []))));
+
+ if ($ids === []) {
+ return response()->json([
+ 'status' => 'error',
+ 'messages' => ['ids' => [trans('validation.required', ['attribute' => 'ids'])]],
+ 'results' => [],
+ ]);
+ }
+
+ $assets = Asset::whereIn('id', $ids)->get()->keyBy('id');
+
+ $results = [];
+ $success_count = 0;
+ $error_count = 0;
+
+ foreach ($ids as $id) {
+ if (! $assets->has($id)) {
+ $results[] = [
+ 'id' => $id,
+ 'status' => 'error',
+ 'messages' => trans('admin/hardware/message.does_not_exist'),
+ 'payload' => null,
+ ];
+ $error_count++;
+
+ continue;
+ }
+
+ $asset = $assets->get($id);
+
+ // Per-row FMCS/authorization gate. The class-level authorize()
+ // above is only a coarse "you have assets.audit" check; this
+ // catches FMCS mismatches and any policy tightening that lands
+ // later, surfacing them as row errors rather than a whole 403.
+ if (! Gate::allows('audit', $asset)) {
+ $results[] = [
+ 'id' => $id,
+ 'status' => 'error',
+ 'messages' => trans('general.unauthorized'),
+ 'payload' => null,
+ ];
+ $error_count++;
+
+ continue;
+ }
+
+ $result = $this->applyAssetAudit($asset, $request);
+ $row = $this->buildAuditRowResult($id, $result);
+ $results[] = $row;
+
+ $row['status'] === 'success' ? $success_count++ : $error_count++;
+ }
+
+ return response()->json($this->assembleBulkResponse($results, $success_count, $error_count));
+ }
+
+ /**
+ * Apply an audit to a single Asset.
+ *
+ * Shared between audit() and bulkAudit(), so validation, the observer
+ * bypass, and the logAudit side-effect live in one place. Returns the
+ * neutral result shape that formatSingleAuditResponse() /
+ * buildAuditRowResult() turn into the legacy or bulk-envelope response
+ * body.
+ *
+ * @return array{
+ * success: bool,
+ * asset: Asset|null,
+ * payload: array,
+ * message: string|null,
+ * errors: mixed,
+ * }
+ */
+ private function applyAssetAudit(Asset $asset, UploadFileRequest $request): array
+ {
$settings = Setting::getSettings();
$dt = null;
@@ -1256,130 +1543,182 @@ class AssetsController extends Controller
$audit_by_field = $request->input('audit_by_field', 'asset_tag');
$audit_key = $request->input('audit_key', null);
- // If they have selected to scan by serial, use that
- if (($settings->unique_serial == '1') && ($audit_by_field == 'serial') && ($audit_key)) {
- $asset = Asset::where('serial', '=', trim($audit_key))->first();
+ $originalValues = $asset->getRawOriginal();
- // If they have selected by asset tag, use that
- } elseif (($audit_by_field == 'asset_tag') && ($audit_key)) {
- $asset = Asset::where('asset_tag', '=', trim($audit_key))->first();
+ $asset->next_audit_date = $dt;
- // Allow the asset tag to be passed in the payload (legacy method)
- } elseif ($request->filled('asset_tag')) {
- $asset = Asset::where('asset_tag', '=', $request->input('asset_tag'))->first();
+ if ($request->filled('next_audit_date')) {
+ $asset->next_audit_date = $request->input('next_audit_date');
}
- // If none of the above were selected, fall back to the route-model-binding
- if ($asset) {
+ // "update_location" flag actually writes the location instead of
+ // only recording it in the audit notes.
+ if ($request->input('update_location') == '1') {
+ $asset->location_id = $request->input('location_id');
+ }
- $originalValues = $asset->getRawOriginal();
+ $asset->last_audit_date = date('Y-m-d H:i:s');
- $asset->next_audit_date = $dt;
+ if ($request->input('clear_name') == '1') {
+ $asset->name = null;
+ }
- if ($request->filled('next_audit_date')) {
- $asset->next_audit_date = $request->input('next_audit_date');
- }
+ $payload = [
+ 'id' => $asset->id,
+ 'asset_tag' => e($asset->asset_tag),
+ 'audit_by_field' => e(Str::headline($audit_by_field)),
+ 'audit_key' => e($audit_key),
+ 'note' => $request->filled('note') ? e($request->input('note')) : null,
+ 'status_label' => e($asset->status?->display_name),
+ 'status_type' => $asset->status?->getStatuslabelType(),
+ 'next_audit_date' => Helper::getFormattedDateObject($asset->next_audit_date),
+ ];
- // Check to see if they checked the box to update the physical location,
- // not just note it in the audit notes
- if ($request->input('update_location') == '1') {
- $asset->location_id = $request->input('location_id');
- }
+ if ($asset->model && $asset->model->fieldset) {
+ $payload['custom_fields'] = [];
+ foreach ($asset->model->fieldset->fields as $field) {
+ if ($field->display_audit != '1' || ! $request->has($field->db_column)) {
+ continue;
+ }
- $asset->last_audit_date = date('Y-m-d H:i:s');
+ $value = $request->input($field->db_column);
+ $stored = is_array($value) ? implode(', ', $value) : $value;
+
+ if ($field->field_encrypted == '1') {
+ // Only writers with the encrypted-view permission can
+ // set encrypted fields; other callers get the payload
+ // echo but no persisted change.
+ if (Gate::allows('assets.view.encrypted_custom_fields')) {
+ $asset->{$field->db_column} = Crypt::encrypt($stored);
+ }
+ } else {
+ $asset->{$field->db_column} = $stored;
+ }
- if ($request->input('clear_name') == '1') {
- $asset->name = null;
+ $payload['custom_fields'][$field->db_column] = $value;
}
+ }
- // Set up the payload for re-display in the API response
- $payload = [
- 'id' => $asset->id,
- 'asset_tag' => e($asset->asset_tag),
- 'audit_by_field' => e(Str::headline($audit_by_field)),
- 'audit_key' => e($audit_key),
- 'note' => $request->filled('note') ? e($request->input('note')) : null,
- 'status_label' => e($asset->status?->display_name),
- 'status_type' => $asset->status?->getStatuslabelType(),
- 'next_audit_date' => Helper::getFormattedDateObject($asset->next_audit_date),
- ];
+ // Merge the model-level base rules with the custom-field rules so
+ // uploaded audit data is checked before we bypass the observer below.
+ $asset->setRules($asset->getRules() + $asset->customFieldValidationRules());
- /**
- * Update custom fields in the database.
- * Validation for these fields is handled through the AssetRequest form request
- * $model = AssetModel::find($request->input('model_id'));
- */
- if (($asset->model) && ($asset->model->fieldset)) {
- $payload['custom_fields'] = [];
- foreach ($asset->model->fieldset->fields as $field) {
- if (($field->display_audit == '1') && ($request->has($field->db_column))) {
- if ($field->field_encrypted == '1') {
- if (Gate::allows('assets.view.encrypted_custom_fields')) {
- if (is_array($request->input($field->db_column))) {
- $asset->{$field->db_column} = Crypt::encrypt(implode(', ', $request->input($field->db_column)));
- } else {
- $asset->{$field->db_column} = Crypt::encrypt($request->input($field->db_column));
- }
- }
- } else {
- if (is_array($request->input($field->db_column))) {
- $asset->{$field->db_column} = implode(', ', $request->input($field->db_column));
- } else {
- $asset->{$field->db_column} = $request->input($field->db_column);
- }
- }
- $payload['custom_fields'][$field->db_column] = $request->input($field->db_column);
- }
+ if ($asset->isInvalid()) {
+ return [
+ 'success' => false,
+ 'asset' => $asset,
+ 'payload' => $payload,
+ 'message' => null,
+ 'errors' => $asset->getErrors(),
+ ];
+ }
- }
+ // We save() further down but don't want an "update" log entry (the
+ // observer would emit one because de-normed fields like
+ // next_audit_date change here) in addition to the "audit" log entry
+ // we create below. unsetEventDispatcher() bypasses the observer;
+ // isValid() above already ran the Watson validation manually.
+ //
+ // @see \App\Observers\AssetObserver::updating()
+ // @see \App\Models\Asset::save()
+ $asset->unsetEventDispatcher();
+
+ if ($asset->isValid() && $asset->save()) {
+ // Persist an audit image if the caller uploaded one, matching
+ // the web audit form's behavior. Filename is stored on the
+ // action log so it renders in the audit history.
+ $file_name = null;
+ if ($request->hasFile('image')) {
+ $file_name = $request->handleFile('private_uploads/audits/', 'audit-'.$asset->id, $request->file('image'));
+ $payload['image'] = $file_name;
}
- // Invoke the validation to see if the audit will complete successfully
- $asset->setRules($asset->getRules() + $asset->customFieldValidationRules());
+ $asset->logAudit($request->input('note'), $request->input('location_id'), $file_name, $originalValues);
- // Validate the rest of the data before we turn off the event dispatcher
- if ($asset->isInvalid()) {
- return response()->json(Helper::formatStandardApiResponse('error', $payload, $asset->getErrors()));
- }
+ return [
+ 'success' => true,
+ 'asset' => $asset,
+ 'payload' => $payload,
+ 'message' => 'admin/hardware/message.audit.success',
+ 'errors' => null,
+ ];
+ }
- /**
- * Even though we do a save() further down, we don't want to log this as a "normal" asset update,
- * which would trigger the Asset Observer and would log an asset *update* log entry (because the
- * de-normed fields like next_audit_date on the asset itself will change on save()) *in addition* to
- * the audit log entry we're creating through this controller.
- *
- * To prevent this double-logging (one for update and one for audit), we skip the observer and bypass
- * that de-normed update log entry by using unsetEventDispatcher(), BUT invoking unsetEventDispatcher()
- * will bypass normal model-level validation that's usually handled at the observer)
- *
- * We handle validation on the save() by checking if the asset is valid via the ->isValid() method,
- * which manually invokes Watson Validating to make sure the asset's model is valid.
- *
- * @see AssetObserver::updating()
- * @see Asset::save()
- */
- $asset->unsetEventDispatcher();
-
- /**
- * Invoke Watson Validating to check the asset itself and check to make sure it saved correctly.
- * We have to invoke this manually because of the unsetEventDispatcher() above.)
- */
- if ($asset->isValid() && $asset->save()) {
- $asset->logAudit(request('note'), request('location_id'), null, $originalValues);
-
- return response()->json(Helper::formatStandardApiResponse('success', $payload, trans('admin/hardware/message.audit.success')));
- }
+ return [
+ 'success' => false,
+ 'asset' => $asset,
+ 'payload' => $payload,
+ 'message' => null,
+ 'errors' => $asset->getErrors(),
+ ];
+ }
+
+ /**
+ * Body-based asset lookup for the legacy audit path. Mirrors the pre-
+ * refactor behavior: prefer audit_key + audit_by_field (serial or
+ * asset_tag), fall back to the legacy `asset_tag` field, otherwise
+ * return null so the caller can try the URL-bound id.
+ */
+ private function resolveAuditAssetFromBody(Request $request): ?Asset
+ {
+ $settings = Setting::getSettings();
+ $audit_by_field = $request->input('audit_by_field', 'asset_tag');
+ $audit_key = $request->input('audit_key', null);
+ if ($settings->unique_serial == '1' && $audit_by_field === 'serial' && $audit_key) {
+ return Asset::where('serial', '=', trim($audit_key))->first();
}
- $fail_payload = [
- 'audit_by_field' => e(Str::headline($audit_by_field)),
- 'audit_key' => e($audit_key),
+ if ($audit_by_field === 'asset_tag' && $audit_key) {
+ return Asset::where('asset_tag', '=', trim($audit_key))->first();
+ }
+
+ if ($request->filled('asset_tag')) {
+ return Asset::where('asset_tag', '=', $request->input('asset_tag'))->first();
+ }
+
+ return null;
+ }
+
+ /**
+ * The "no matching asset" fail payload the legacy audit response emits.
+ */
+ private function auditFailPayload(Request $request): array
+ {
+ return [
+ 'audit_by_field' => e(Str::headline($request->input('audit_by_field', 'asset_tag'))),
+ 'audit_key' => e($request->input('audit_key', null)),
];
+ }
- // No matching asset for the asset tag that was passed.
- return response()->json(Helper::formatStandardApiResponse('error', $fail_payload, trans('admin/hardware/message.does_not_exist')), 200);
+ /**
+ * Format an applyAssetAudit() result into the legacy single-asset audit
+ * response body. `payload` here is the audit-specific structure
+ * (asset_tag, audit_by_field, custom_fields, ...) built inside
+ * applyAssetAudit(), NOT the full Asset model.
+ */
+ private function formatSingleAuditResponse(array $result): array
+ {
+ if (! $result['success']) {
+ return Helper::formatStandardApiResponse('error', $result['payload'], $result['errors']);
+ }
+
+ return Helper::formatStandardApiResponse('success', $result['payload'], trans($result['message']));
+ }
+ /**
+ * Turn an applyAssetAudit() result into a per-row bulk-envelope entry.
+ */
+ private function buildAuditRowResult(int $id, array $result): array
+ {
+ $formatted = $this->formatSingleAuditResponse($result);
+
+ return [
+ 'id' => $id,
+ 'status' => $formatted['status'],
+ 'messages' => $formatted['messages'],
+ 'payload' => $formatted['payload'],
+ ];
}
/**
diff --git a/app/Http/Requests/BulkUpdateAssetsRequest.php b/app/Http/Requests/BulkUpdateAssetsRequest.php
new file mode 100644
index 0000000000..b72150bc8f
--- /dev/null
+++ b/app/Http/Requests/BulkUpdateAssetsRequest.php
@@ -0,0 +1,74 @@
+<?php
+
+namespace App\Http\Requests;
+
+use App\Models\Asset;
+use Illuminate\Contracts\Validation\Validator;
+use Illuminate\Http\Exceptions\HttpResponseException;
+use Illuminate\Support\Facades\Gate;
+
+/**
+ * Bulk update: same field rules as UpdateAssetRequest, plus an `ids` array in
+ * the request body naming which assets to update. Per-row authorization
+ * happens in AssetsController::bulkUpdate() because a caller who can update
+ * one asset may not be able to update another (FMCS, policy).
+ */
+class BulkUpdateAssetsRequest extends UpdateAssetRequest
+{
+ public function authorize()
+ {
+ // Coarse gate: caller must have general update permission on the
+ // Asset resource. Per-row permission is checked inside bulkUpdate()
+ // so a single denied asset produces one error row, not a whole 403.
+ return Gate::allows('update', Asset::class);
+ }
+
+ public function rules()
+ {
+ return array_merge(parent::rules(), [
+ 'ids' => ['required', 'array', 'min:1'],
+ 'ids.*' => ['integer'],
+ ]);
+ }
+
+ /**
+ * Bulk endpoint always returns the per-row envelope — for a request-level
+ * validation failure (bad field values, missing ids) we fan the same
+ * error messages out to every id the caller aimed at so downstream code
+ * iterating `results` doesn't need a special "whole payload rejected"
+ * branch.
+ */
+ protected function failedValidation(Validator $validator)
+ {
+ $errorMessages = $validator->errors()->messages();
+ $ids = array_values(array_unique(array_map(
+ 'intval',
+ array_filter((array) $this->input('ids', []), fn ($v) => is_numeric($v))
+ )));
+
+ $results = array_map(fn ($id) => [
+ 'id' => $id,
+ 'status' => 'error',
+ 'messages' => $errorMessages,
+ 'payload' => null,
+ ], $ids);
+
+ throw new HttpResponseException(response()->json([
+ 'status' => 'error',
+ 'messages' => $ids === []
+ ? $errorMessages
+ : trans('admin/hardware/message.bulk_update.error'),
+ 'results' => $results,
+ ]));
+ }
+
+ /**
+ * Bulk can't `Rule::unique->ignore()` N ids simultaneously; per-row
+ * uniqueness collisions are caught by Watson's ValidatingTrait at
+ * save-time and surface as row-level errors in the envelope.
+ */
+ protected function ignoreIdForUnique(): ?int
+ {
+ return null;
+ }
+}
diff --git a/app/Http/Requests/Traits/MayContainCustomFields.php b/app/Http/Requests/Traits/MayContainCustomFields.php
index 2014e10d74..2a781df29d 100644
--- a/app/Http/Requests/Traits/MayContainCustomFields.php
+++ b/app/Http/Requests/Traits/MayContainCustomFields.php
@@ -2,6 +2,7 @@
namespace App\Http\Requests\Traits;
+use App\Models\Asset;
use App\Models\AssetModel;
use App\Models\CustomField;
@@ -17,19 +18,17 @@ trait MayContainCustomFields
$asset_model = AssetModel::find(request()->input('model_id'));
// or if we have it available to route-model-binding
- } elseif ((request()->route('asset') && (request()->route('asset')->model_id))) {
+ } elseif (request()->route('asset') instanceof Asset && request()->route('asset')->model_id) {
$asset_model = AssetModel::find(request()->route('asset')->model_id);
+ } elseif ($this->method() == 'POST') {
+ $asset_model = AssetModel::find($this->model_id);
} else {
-
- if ($this->method() == 'POST') {
- $asset_model = AssetModel::find($this->model_id);
- }
-
- if ($this->method() == 'PATCH' || $this->method() == 'PUT') {
- $asset_model = $this->asset->model;
- }
+ // Bulk update / audit paths (no single {asset} in the URL) — the
+ // model to validate against can't be pinned to one asset, so let
+ // per-row saves surface any bad custom-field values at save time.
+ $asset_model = null;
}
// collect the custom fields in the request
diff --git a/app/Http/Requests/UpdateAssetRequest.php b/app/Http/Requests/UpdateAssetRequest.php
index 74a9a92559..5f5e98a199 100644
--- a/app/Http/Requests/UpdateAssetRequest.php
+++ b/app/Http/Requests/UpdateAssetRequest.php
@@ -48,6 +48,13 @@ class UpdateAssetRequest extends ImageUploadRequest
// route through checkOut() and produce the required audit-log entry).
unset($assetRules['assigned_to'], $assetRules['assigned_type']);
+ // On the singular endpoint we can tell Rule::unique to ignore the
+ // asset being updated. Bulk (BulkUpdateAssetsRequest) overrides this
+ // to null because it would have to ignore N different ids at once,
+ // which Rule::unique->ignore() can't express — collisions on the
+ // bulk path are caught per-row by Watson at save time.
+ $ignoreId = $this->ignoreIdForUnique();
+
$rules = array_merge(
parent::rules(),
$assetRules,
@@ -59,15 +66,25 @@ class UpdateAssetRequest extends ImageUploadRequest
'status_id' => ['integer', 'exists:status_labels,id'],
'asset_tag' => [
'min:1', 'max:255', 'not_array',
- Rule::unique('assets', 'asset_tag')->ignore($this->asset)->withoutTrashed(),
+ Rule::unique('assets', 'asset_tag')->ignore($ignoreId)->withoutTrashed(),
],
'serial' => [
'string', 'max:255', 'not_array',
- $setting->unique_serial == '1' ? Rule::unique('assets', 'serial')->ignore($this->asset)->withoutTrashed() : 'nullable',
+ $setting->unique_serial == '1' ? Rule::unique('assets', 'serial')->ignore($ignoreId)->withoutTrashed() : 'nullable',
],
],
);
return $rules;
}
+
+ /**
+ * ID that Rule::unique should ignore when checking asset_tag / serial. The
+ * singular endpoint has an Asset via route-model-binding; the bulk subclass
+ * has no single id to point at and returns null.
+ */
+ protected function ignoreIdForUnique(): ?int
+ {
+ return $this->asset instanceof Asset ? $this->asset->id : null;
+ }
}
diff --git a/resources/lang/en-US/admin/hardware/message.php b/resources/lang/en-US/admin/hardware/message.php
index d8ae8df62b..f33e37be08 100644
--- a/resources/lang/en-US/admin/hardware/message.php
+++ b/resources/lang/en-US/admin/hardware/message.php
@@ -35,6 +35,12 @@ return [
'assets_do_not_exist_or_are_invalid' => 'Selected assets cannot be updated.',
],
+ 'bulk_update' => [
+ 'success' => 'Asset updated successfully.|:count assets were updated successfully.',
+ 'partial' => ':success asset(s) updated successfully, :failed failed. See the results array for details.',
+ 'error' => 'No assets were updated. See the results array for details.',
+ ],
+
'restore' => [
'error' => 'Asset was not restored, please try again',
'success' => 'Asset restored successfully.',
diff --git a/routes/api.php b/routes/api.php
index 0dee614cea..a7ff098394 100644
--- a/routes/api.php
+++ b/routes/api.php
@@ -535,7 +535,7 @@ Route::group(['prefix' => 'v1', 'middleware' => ['api', 'api-throttle:api']], fu
)->name('api.assets.list-upcoming')
->where(['action' => 'audit|audits|checkins', 'upcoming_status' => 'due|overdue|due-or-overdue']);
- // Legacy URL for audit
+ // Legacy URL for audit (body-based lookup via audit_key/asset_tag).
Route::post('audit',
[
Api\AssetsController::class,
@@ -543,7 +543,17 @@ Route::group(['prefix' => 'v1', 'middleware' => ['api', 'api-throttle:api']], fu
]
)->name('api.asset.audit.legacy');
- // Newer url for audit
+ // Bulk audit: `ids` array in the request body, per-row envelope response.
+ // Declared BEFORE `{asset}/audit` so /hardware/audit/bulk matches this
+ // route instead of being interpreted as {asset}=audit.
+ Route::post('audit/bulk',
+ [
+ Api\AssetsController::class,
+ 'bulkAudit',
+ ]
+ )->name('api.asset.bulk-audit');
+
+ // Single-asset audit. Route-model-binding on {asset}; legacy response shape.
Route::post('{asset}/audit',
[
Api\AssetsController::class,
@@ -596,11 +606,17 @@ Route::group(['prefix' => 'v1', 'middleware' => ['api', 'api-throttle:api']], fu
/** End assigned routes */
});
- // pulling this out of resource route group to begin normalizing for route-model binding.
- // this would probably keep working with the resource route group, but the general practice is for
- // the model name to be the parameter - and i think it's a good differentiation in the code while we convert the others.
- Route::patch('/hardware/{asset}', [Api\AssetsController::class, 'update'])->name('api.assets.update');
- Route::put('/hardware/{asset}', [Api\AssetsController::class, 'update'])->name('api.assets.put-update');
+ // Bulk update: `ids` array in the request body, per-row envelope response.
+ // Declared BEFORE the singular {asset} routes so PATCH /hardware/bulk hits
+ // this handler instead of trying to bind "bulk" as an Asset.
+ Route::patch('/hardware/bulk', [Api\AssetsController::class, 'bulkUpdate'])
+ ->name('api.assets.bulk-update');
+
+ // Single-asset update. Route-model-binding on {asset}, legacy response shape.
+ Route::patch('/hardware/{asset}', [Api\AssetsController::class, 'update'])
+ ->name('api.assets.update');
+ Route::put('/hardware/{asset}', [Api\AssetsController::class, 'update'])
+ ->name('api.assets.put-update');
Route::resource('hardware',
Api\AssetsController::class,
diff --git a/tests/Feature/Assets/Api/AuditAssetTest.php b/tests/Feature/Assets/Api/AuditAssetTest.php
index d60e74630d..592d589c21 100644
--- a/tests/Feature/Assets/Api/AuditAssetTest.php
+++ b/tests/Feature/Assets/Api/AuditAssetTest.php
@@ -2,9 +2,12 @@
namespace Tests\Feature\Assets\Api;
+use App\Models\Actionlog;
use App\Models\Asset;
use App\Models\User;
use Carbon\Carbon;
+use Illuminate\Http\UploadedFile;
+use Illuminate\Support\Facades\Storage;
use PHPUnit\Framework\Attributes\Group;
use Tests\TestCase;
@@ -191,4 +194,51 @@ class AuditAssetTest extends TestCase
$this->assertEquals('My Asset Name', $asset->refresh()->name);
}
+
+ public function test_audit_persists_uploaded_image_and_stamps_filename_on_log()
+ {
+ // Parity with the web audit form: an uploaded `image` on the API
+ // audit request should be saved into private_uploads/audits/ and its
+ // storage-relative filename recorded on the resulting audit log entry.
+ Storage::fake();
+
+ $asset = Asset::factory()->create();
+
+ $response = $this->actingAsForApi(User::factory()->auditAssets()->create())
+ ->post(route('api.asset.audit', $asset->id), [
+ 'note' => 'audit w/ photo',
+ 'image' => UploadedFile::fake()->image('audit.jpg'),
+ ])
+ ->assertOk()
+ ->assertStatusMessageIs('success');
+
+ // Payload echoes back the stored filename.
+ $filename = $response->json('payload.image');
+ $this->assertNotNull($filename);
+ $this->assertStringStartsWith('audit-'.$asset->id.'-', $filename);
+ Storage::assertExists('private_uploads/audits/'.$filename);
+
+ // Filename shows up on the audit log so the audit history view can render it.
+ $log = Actionlog::where('item_id', $asset->id)->where('action_type', 'audit')->first();
+ $this->assertNotNull($log);
+ $this->assertSame($filename, $log->filename);
+ }
+
+ public function test_audit_without_image_does_not_stamp_filename()
+ {
+ Storage::fake();
+
+ $asset = Asset::factory()->create();
+
+ $this->actingAsForApi(User::factory()->auditAssets()->create())
+ ->postJson(route('api.asset.audit', $asset->id), [
+ 'note' => 'no photo',
+ ])
+ ->assertOk()
+ ->assertStatusMessageIs('success');
+
+ $log = Actionlog::where('item_id', $asset->id)->where('action_type', 'audit')->first();
+ $this->assertNotNull($log);
+ $this->assertNull($log->filename);
+ }
}
diff --git a/tests/Feature/Assets/Api/BulkAuditAssetsTest.php b/tests/Feature/Assets/Api/BulkAuditAssetsTest.php
new file mode 100644
index 0000000000..07bc9c6384
--- /dev/null
+++ b/tests/Feature/Assets/Api/BulkAuditAssetsTest.php
@@ -0,0 +1,207 @@
+<?php
+
+namespace Tests\Feature\Assets\Api;
+
+use App\Models\Actionlog;
+use App\Models\Asset;
+use App\Models\Company;
+use App\Models\User;
+use Illuminate\Http\UploadedFile;
+use Illuminate\Support\Facades\Storage;
+use PHPUnit\Framework\Attributes\Group;
+use Tests\TestCase;
+
+/**
+ * Coverage for POST /api/v1/hardware/audit/bulk. `ids` in the request body
+ * names which assets to audit; other body fields (note, next_audit_date,
+ * update_location, image, ...) apply to every one of them. Response is
+ * always the per-row envelope.
+ *
+ * Backward-compat coverage for the singular endpoint (POST
+ * /hardware/{asset}/audit) and the legacy body-based route (POST
+ * /hardware/audit) lives in AuditAssetTest.
+ */
+#[Group('auditing')]
+class BulkAuditAssetsTest extends TestCase
+{
+ private function bulkUrl(): string
+ {
+ return route('api.asset.bulk-audit');
+ }
+
+ public function test_audits_all_assets_and_returns_per_row_envelope()
+ {
+ [$a, $b, $c] = Asset::factory()->count(3)->create();
+ $future = now()->addMonths(4)->toDateString();
+
+ $response = $this->actingAsForApi(User::factory()->auditAssets()->create())
+ ->postJson($this->bulkUrl(), [
+ 'ids' => [$a->id, $b->id, $c->id],
+ 'next_audit_date' => $future,
+ 'note' => 'bulk audit',
+ ])
+ ->assertOk()
+ ->assertJsonPath('status', 'success');
+
+ $results = $response->json('results');
+ $this->assertCount(3, $results);
+
+ foreach ([$a, $b, $c] as $original) {
+ $fresh = $original->fresh();
+ $this->assertEquals($future, $fresh->next_audit_date, "next_audit_date not applied to asset {$original->id}");
+ $this->assertNotNull($fresh->last_audit_date, "last_audit_date not stamped on asset {$original->id}");
+ }
+
+ $this->assertArrayHasKey('id', $results[0]);
+ $this->assertArrayHasKey('status', $results[0]);
+ $this->assertArrayHasKey('messages', $results[0]);
+ $this->assertArrayHasKey('payload', $results[0]);
+ $this->assertSame('success', $results[0]['status']);
+ // asset_tag is HTML-escaped through e() in the payload; compare as strings.
+ $this->assertSame((string) $a->asset_tag, (string) $results[0]['payload']['asset_tag']);
+ }
+
+ public function test_input_order_is_preserved_in_results()
+ {
+ [$a, $b, $c] = Asset::factory()->count(3)->create();
+
+ $response = $this->actingAsForApi(User::factory()->auditAssets()->create())
+ ->postJson($this->bulkUrl(), [
+ 'ids' => [$c->id, $a->id, $b->id],
+ 'note' => 'order check',
+ ])
+ ->assertOk();
+
+ $ids = array_column($response->json('results'), 'id');
+ $this->assertSame([$c->id, $a->id, $b->id], $ids);
+ }
+
+ public function test_nonexistent_id_is_reported_as_row_error()
+ {
+ $a = Asset::factory()->create();
+
+ $response = $this->actingAsForApi(User::factory()->auditAssets()->create())
+ ->postJson($this->bulkUrl(), [
+ 'ids' => [$a->id, 999999],
+ 'note' => 'partial',
+ ])
+ ->assertOk();
+
+ $this->assertSame('partial', $response->json('status'));
+
+ $rows = collect($response->json('results'))->keyBy('id');
+ $this->assertSame('success', $rows[$a->id]['status']);
+ $this->assertSame('error', $rows[999999]['status']);
+ $this->assertNull($rows[999999]['payload']);
+ }
+
+ public function test_all_failures_produce_overall_error_status()
+ {
+ $response = $this->actingAsForApi(User::factory()->auditAssets()->create())
+ ->postJson($this->bulkUrl(), [
+ 'ids' => [999998, 999999],
+ 'note' => 'nothing exists',
+ ])
+ ->assertOk();
+
+ $this->assertSame('error', $response->json('status'));
+ $this->assertCount(2, $response->json('results'));
+
+ foreach ($response->json('results') as $row) {
+ $this->assertSame('error', $row['status']);
+ }
+ }
+
+ public function test_duplicate_ids_are_only_processed_once()
+ {
+ $a = Asset::factory()->create();
+
+ $response = $this->actingAsForApi(User::factory()->auditAssets()->create())
+ ->postJson($this->bulkUrl(), [
+ 'ids' => [$a->id, $a->id, $a->id],
+ 'note' => 'once please',
+ ])
+ ->assertOk();
+
+ $this->assertCount(1, $response->json('results'));
+ $this->assertSame($a->id, $response->json('results.0.id'));
+ }
+
+ public function test_missing_ids_field_is_a_request_level_validation_error()
+ {
+ $response = $this->actingAsForApi(User::factory()->auditAssets()->create())
+ ->postJson($this->bulkUrl(), [
+ 'note' => 'no ids provided',
+ ])
+ ->assertJsonPath('status', 'error');
+
+ $this->assertArrayHasKey('ids', $response->json('messages'));
+ $this->assertSame([], $response->json('results'));
+ }
+
+ public function test_attaches_uploaded_image_to_every_row_audit_log()
+ {
+ // A single `image` on a bulk audit should be stored once per asset
+ // and each asset's audit log entry should reference its own copy —
+ // mirroring the web audit form which associates the uploaded image
+ // with the individual audit.
+ Storage::fake();
+
+ [$a, $b] = Asset::factory()->count(2)->create();
+
+ $response = $this->actingAsForApi(User::factory()->auditAssets()->create())
+ ->post($this->bulkUrl(), [
+ 'ids' => [$a->id, $b->id],
+ 'note' => 'batch w/ photo',
+ 'image' => UploadedFile::fake()->image('audit.jpg'),
+ ])
+ ->assertOk()
+ ->assertJsonPath('status', 'success');
+
+ $rows = collect($response->json('results'))->keyBy('id');
+ foreach ([$a, $b] as $asset) {
+ $filename = $rows[$asset->id]['payload']['image'] ?? null;
+ $this->assertNotNull($filename, "no image filename for asset {$asset->id}");
+ $this->assertStringStartsWith('audit-'.$asset->id.'-', $filename);
+ Storage::assertExists('private_uploads/audits/'.$filename);
+
+ $log = Actionlog::where('item_id', $asset->id)->where('action_type', 'audit')->first();
+ $this->assertSame($filename, $log->filename);
+ }
+ }
+
+ public function test_respects_fmcs_scoping_for_non_superuser()
+ {
+ // FMCS on, caller in company A tries to audit both an A-owned asset
+ // and a B-owned asset. B is hidden by the CompanyableScope on the
+ // Asset::whereIn(...) fetch, so it reports as `does_not_exist` in
+ // the per-row envelope. Then the per-row Gate::allows('audit', $asset)
+ // check inside bulkAudit() acts as belt-and-braces if a future scope
+ // change lets the query see it — the row would surface as
+ // `unauthorized` instead.
+ $this->settings->enableMultipleFullCompanySupport();
+
+ $companyA = Company::factory()->create();
+ $companyB = Company::factory()->create();
+
+ $userA = User::factory()->auditAssets()->create(['company_id' => $companyA->id]);
+ $assetA = Asset::factory()->create(['company_id' => $companyA->id, 'created_by' => $userA->id]);
+ $assetB = Asset::factory()->create(['company_id' => $companyB->id]);
+
+ $response = $this->actingAsForApi($userA)
+ ->postJson($this->bulkUrl(), [
+ 'ids' => [$assetA->id, $assetB->id],
+ 'note' => 'fmcs check',
+ ])
+ ->assertOk();
+
+ $this->assertSame('partial', $response->json('status'));
+
+ $rows = collect($response->json('results'))->keyBy('id');
+ $this->assertSame('success', $rows[$assetA->id]['status']);
+ $this->assertSame('error', $rows[$assetB->id]['status']);
+
+ $this->assertNotNull($assetA->fresh()->last_audit_date);
+ $this->assertNull($assetB->fresh()->last_audit_date);
+ }
+}
diff --git a/tests/Feature/Assets/Api/BulkUpdateAssetsTest.php b/tests/Feature/Assets/Api/BulkUpdateAssetsTest.php
new file mode 100644
index 0000000000..f7c242afd7
--- /dev/null
+++ b/tests/Feature/Assets/Api/BulkUpdateAssetsTest.php
@@ -0,0 +1,206 @@
+<?php
+
+namespace Tests\Feature\Assets\Api;
+
+use App\Models\Asset;
+use App\Models\Company;
+use App\Models\Statuslabel;
+use App\Models\User;
+use Tests\TestCase;
+
+/**
+ * Coverage for PATCH /api/v1/hardware/bulk. `ids` in the request body names
+ * which assets to touch; every other body field is the shared update payload
+ * applied to each. Response is always the per-row envelope:
+ * `{status, messages, results: [ {id, status, messages, payload} ]}`.
+ *
+ * Backward-compat coverage for the singular endpoint (PATCH /hardware/{asset},
+ * legacy `{status, messages, payload}` shape) lives in UpdateAssetTest.
+ */
+class BulkUpdateAssetsTest extends TestCase
+{
+ private function bulkUrl(): string
+ {
+ return route('api.assets.bulk-update');
+ }
+
+ public function test_requires_permission()
+ {
+ $a = Asset::factory()->create();
+ $b = Asset::factory()->create();
+
+ $this->actingAsForApi(User::factory()->create())
+ ->patchJson($this->bulkUrl(), [
+ 'ids' => [$a->id, $b->id],
+ 'name' => 'nope',
+ ])
+ ->assertForbidden();
+ }
+
+ public function test_updates_all_assets_and_returns_per_row_envelope()
+ {
+ [$a, $b, $c] = Asset::factory()->count(3)->create();
+ $status = Statuslabel::factory()->create();
+
+ $response = $this->actingAsForApi(User::factory()->editAssets()->create())
+ ->patchJson($this->bulkUrl(), [
+ 'ids' => [$a->id, $b->id, $c->id],
+ 'status_id' => $status->id,
+ 'notes' => 'bulk updated',
+ ])
+ ->assertOk()
+ ->assertJsonPath('status', 'success');
+
+ $results = $response->json('results');
+ $this->assertCount(3, $results);
+
+ foreach ([$a, $b, $c] as $original) {
+ $fresh = $original->fresh();
+ $this->assertEquals($status->id, $fresh->status_id, "status_id not applied to asset {$original->id}");
+ $this->assertEquals('bulk updated', $fresh->notes, "notes not applied to asset {$original->id}");
+ }
+
+ $this->assertArrayHasKey('id', $results[0]);
+ $this->assertArrayHasKey('status', $results[0]);
+ $this->assertArrayHasKey('messages', $results[0]);
+ $this->assertArrayHasKey('payload', $results[0]);
+ $this->assertSame('success', $results[0]['status']);
+ $this->assertNotNull($results[0]['payload']);
+ }
+
+ public function test_input_order_is_preserved_in_results()
+ {
+ [$a, $b, $c] = Asset::factory()->count(3)->create();
+
+ $response = $this->actingAsForApi(User::factory()->editAssets()->create())
+ ->patchJson($this->bulkUrl(), [
+ 'ids' => [$c->id, $a->id, $b->id],
+ 'notes' => 'order check',
+ ])
+ ->assertOk();
+
+ $ids = array_column($response->json('results'), 'id');
+ $this->assertSame([$c->id, $a->id, $b->id], $ids);
+ }
+
+ public function test_nonexistent_id_is_reported_as_row_error()
+ {
+ $a = Asset::factory()->create();
+
+ $response = $this->actingAsForApi(User::factory()->editAssets()->create())
+ ->patchJson($this->bulkUrl(), [
+ 'ids' => [$a->id, 999999],
+ 'notes' => 'partial',
+ ])
+ ->assertOk();
+
+ $this->assertSame('partial', $response->json('status'));
+
+ $rows = collect($response->json('results'))->keyBy('id');
+ $this->assertSame('success', $rows[$a->id]['status']);
+ $this->assertSame('error', $rows[999999]['status']);
+ $this->assertNull($rows[999999]['payload']);
+ }
+
+ public function test_all_failures_produce_overall_error_status()
+ {
+ $response = $this->actingAsForApi(User::factory()->editAssets()->create())
+ ->patchJson($this->bulkUrl(), [
+ 'ids' => [999998, 999999],
+ 'notes' => 'nothing exists',
+ ])
+ ->assertOk();
+
+ $this->assertSame('error', $response->json('status'));
+ $this->assertCount(2, $response->json('results'));
+
+ foreach ($response->json('results') as $row) {
+ $this->assertSame('error', $row['status']);
+ }
+ }
+
+ public function test_duplicate_ids_are_only_processed_once()
+ {
+ $a = Asset::factory()->create();
+
+ $response = $this->actingAsForApi(User::factory()->editAssets()->create())
+ ->patchJson($this->bulkUrl(), [
+ 'ids' => [$a->id, $a->id, $a->id],
+ 'notes' => 'once please',
+ ])
+ ->assertOk();
+
+ $this->assertCount(1, $response->json('results'));
+ $this->assertSame($a->id, $response->json('results.0.id'));
+ }
+
+ public function test_invalid_field_fans_the_validation_error_out_to_every_row()
+ {
+ // A status_id that references a non-existent status_label fails
+ // request-level validation before any row is attempted, so the
+ // response can't distinguish which ids succeeded vs failed. The
+ // failedValidation() hook on BulkUpdateAssetsRequest emits the
+ // per-row envelope though, with the same error copied onto each id.
+ [$a, $b] = Asset::factory()->count(2)->create();
+
+ $response = $this->actingAsForApi(User::factory()->editAssets()->create())
+ ->patchJson($this->bulkUrl(), [
+ 'ids' => [$a->id, $b->id],
+ 'status_id' => 999999,
+ ])
+ ->assertJsonPath('status', 'error')
+ ->assertJsonCount(2, 'results');
+
+ $rows = collect($response->json('results'))->keyBy('id');
+ foreach ([$a->id, $b->id] as $id) {
+ $this->assertSame('error', $rows[$id]['status']);
+ $this->assertArrayHasKey('status_id', $rows[$id]['messages']);
+ }
+ }
+
+ public function test_missing_ids_field_is_a_request_level_validation_error()
+ {
+ $response = $this->actingAsForApi(User::factory()->editAssets()->create())
+ ->patchJson($this->bulkUrl(), [
+ 'notes' => 'no ids provided',
+ ])
+ ->assertJsonPath('status', 'error');
+
+ // With no `ids`, there are no rows to fan errors onto — messages
+ // carries the raw validator error bag.
+ $this->assertArrayHasKey('ids', $response->json('messages'));
+ $this->assertSame([], $response->json('results'));
+ }
+
+ public function test_respects_fmcs_scoping_for_non_superuser()
+ {
+ // Caller scoped to company A asking to update assets [A-owned, B-owned]
+ // should see the B-owned row surface as `does_not_exist` — the query-level
+ // CompanyableScope hides it from `Asset::whereIn(...)`, so the row falls
+ // into the "no such asset" branch. The A-owned row goes through as normal.
+ $this->settings->enableMultipleFullCompanySupport();
+
+ $companyA = Company::factory()->create();
+ $companyB = Company::factory()->create();
+
+ $userA = User::factory()->editAssets()->create(['company_id' => $companyA->id]);
+ $assetA = Asset::factory()->create(['company_id' => $companyA->id, 'created_by' => $userA->id]);
+ $assetB = Asset::factory()->create(['company_id' => $companyB->id]);
+
+ $response = $this->actingAsForApi($userA)
+ ->patchJson($this->bulkUrl(), [
+ 'ids' => [$assetA->id, $assetB->id],
+ 'notes' => 'fmcs check',
+ ])
+ ->assertOk();
+
+ $this->assertSame('partial', $response->json('status'));
+
+ $rows = collect($response->json('results'))->keyBy('id');
+ $this->assertSame('success', $rows[$assetA->id]['status']);
+ $this->assertSame('error', $rows[$assetB->id]['status']);
+
+ $this->assertSame('fmcs check', $assetA->fresh()->notes);
+ $this->assertNotSame('fmcs check', $assetB->fresh()->notes);
+ }
+}