Skip to content

A free open source IT asset/license management system

Fixed order number badge

snipece94a4c9d5d2
diff --git a/app/Http/Controllers/Api/OrderItemsController.php b/app/Http/Controllers/Api/OrderItemsController.php
index 6ddb9cc85c..9d5a510012 100644
--- a/app/Http/Controllers/Api/OrderItemsController.php
+++ b/app/Http/Controllers/Api/OrderItemsController.php
@@ -113,7 +113,14 @@ class OrderItemsController extends Controller
// Orders tab shows purchases only. Corrections / consumption
// events (zero or negative-qty OrderItems) belong in the
// item's history tab, not on the "Orders" list.
- ->where('order_items.qty', '>', 0);
+ ->where('order_items.qty', '>', 0)
+ // Drop rows whose parent Order has no order_number. Those
+ // are initial-inventory anchors (writeInitialOrderIfStocked)
+ // or seeded placeholders without a real acquisition
+ // reference. Including them makes the Orders tab show
+ // rows that look blank to the admin and inflates the
+ // tab badge past what the user considers a real order.
+ ->whereHas('order', fn ($q) => $q->whereNotNull('order_number'));
}
private function applyScopeFilters(Builder $query, Request $request): void
diff --git a/app/Http/Controllers/Components/BulkComponentsController.php b/app/Http/Controllers/Components/BulkComponentsController.php
index 1afa39b825..92147d6c36 100644
--- a/app/Http/Controllers/Components/BulkComponentsController.php
+++ b/app/Http/Controllers/Components/BulkComponentsController.php
@@ -45,7 +45,15 @@ class BulkComponentsController extends Controller
->with('error', trans('admin/components/message.bulk.no_components_selected'));
}
- $components = Component::whereIn('id', $request->input('ids'))->get();
+ // Restore acts on soft-deleted rows, so widen the lookup with
+ // withTrashed for that branch only. The CompanyableScope still
+ // applies via the auto-scope on Component, so cross-tenant ids
+ // continue to drop.
+ $query = Component::whereIn('id', $request->input('ids'));
+ if ($request->input('bulk_actions') === 'restore') {
+ $query->withTrashed();
+ }
+ $components = $query->get();
if ($components->isEmpty()) {
return redirect()->route('components.index')
@@ -55,6 +63,7 @@ class BulkComponentsController extends Controller
return match ($request->input('bulk_actions')) {
'edit' => $this->showEdit($components),
'delete' => $this->showDelete($components),
+ 'restore' => $this->doRestore($components),
default => redirect()->route('components.index')
->with('error', trans('admin/components/message.bulk.no_action_selected')),
};
@@ -230,4 +239,47 @@ class BulkComponentsController extends Controller
'ids' => $components->pluck('id')->all(),
]);
}
+
+ /**
+ * Bulk-restore handler. Restore is non-destructive, so there's no
+ * confirm view: iterate the selection, call ->restore(), redirect
+ * back to the Deleted index with a summary. Per-row Gate::allows
+ * `delete` keeps restore on the delete-tier auth bar (matches
+ * postRestore + AssetModelsController).
+ */
+ protected function doRestore($components): RedirectResponse
+ {
+ $this->authorize('delete', Component::class);
+
+ $restored = 0;
+ $errors = [];
+
+ foreach ($components as $component) {
+ if (! Gate::allows('delete', $component)) {
+ $errors[] = trans('general.unauthorized');
+
+ continue;
+ }
+
+ if ($component->deleted_at === null) {
+ // Already live. Skip without erroring so a stale
+ // selection doesn't blow up the whole batch.
+ continue;
+ }
+
+ if ($component->restore()) {
+ $restored++;
+ }
+ }
+
+ $redirect = redirect()->route('components.index', ['status' => 'Deleted']);
+
+ if (count($errors) > 0 && $restored === 0) {
+ return $redirect->with('multi_error_messages', $errors);
+ }
+
+ return $redirect
+ ->with('success', trans_choice('admin/components/message.bulk.restore.success', $restored, ['count' => $restored]))
+ ->with('multi_error_messages', $errors ?: null);
+ }
}
diff --git a/app/Http/Controllers/Components/ComponentCheckinController.php b/app/Http/Controllers/Components/ComponentCheckinController.php
index 5160b449dc..23fefc28a2 100644
--- a/app/Http/Controllers/Components/ComponentCheckinController.php
+++ b/app/Http/Controllers/Components/ComponentCheckinController.php
@@ -129,6 +129,9 @@ class ComponentCheckinController extends Controller
*/
public function bulkCheckinSelected(Request $request): RedirectResponse
{
+
+ $this->authorize('checkin', Component::class);
+
$pivotIds = array_filter((array) $request->input('ids', []));
if (empty($pivotIds)) {
@@ -149,7 +152,13 @@ class ComponentCheckinController extends Controller
->whereIn('component_id', Component::query()->select('id'))
->get();
- $count = 0;
+ // Count returned ROWS and total UNITS separately. Each pivot
+ // carries an assigned_qty, so "3 rows checked in" might really
+ // mean "3 rows totaling 25 units back in inventory." The
+ // success message surfaces both so the operator can reconcile
+ // against what they expected to return.
+ $rowCount = 0;
+ $unitCount = 0;
foreach ($assignments as $assignment) {
$component = $assignment->component;
if (!$component || !Gate::allows('checkin', $component)) {
@@ -161,6 +170,7 @@ class ComponentCheckinController extends Controller
// Asset directly by its pivot column. withTrashed so a
// soft-deleted asset doesn't break the checkin event.
$asset = Asset::withTrashed()->find($assignment->asset_id);
+ $qty = (int) $assignment->assigned_qty;
if ($assignment->delete()) {
event(new CheckoutableCheckedIn(
@@ -170,11 +180,15 @@ class ComponentCheckinController extends Controller
null,
Carbon::now(),
));
- $count++;
+ $rowCount++;
+ $unitCount += $qty;
}
}
return redirect()->back()
- ->with('success', trans_choice('admin/components/message.bulk.checkin_selected.success', $count, ['count' => $count]));
+ ->with('success', trans_choice('admin/components/message.bulk.checkin_selected.success', $rowCount, [
+ 'count' => $rowCount,
+ 'unit_count' => $unitCount,
+ ]));
}
}
diff --git a/app/Http/Controllers/Components/ComponentsController.php b/app/Http/Controllers/Components/ComponentsController.php
index 6c08018ba8..2842352778 100644
--- a/app/Http/Controllers/Components/ComponentsController.php
+++ b/app/Http/Controllers/Components/ComponentsController.php
@@ -233,6 +233,30 @@ class ComponentsController extends Controller
return redirect()->route('components.index')->with('success', trans('admin/components/message.delete.success'));
}
+ /**
+ * Restore a soft-deleted component.
+ */
+ public function postRestore($id): RedirectResponse
+ {
+ if ($component = Component::withTrashed()->find($id)) {
+
+ $this->authorize('delete', $component);
+
+ if ($component->deleted_at == '') {
+ return redirect()->back()->with('error', trans('general.not_deleted', ['item_type' => trans('general.component')]));
+ }
+
+ if ($component->restore()) {
+ return redirect()->route('components.show', $component)
+ ->with('success', trans('admin/components/message.restore.success'));
+ }
+
+ return redirect()->back()->with('error', trans('general.could_not_restore', ['item_type' => trans('general.component'), 'error' => $component->getErrors()->first()]));
+ }
+
+ return redirect()->route('components.index')->with('error', trans('admin/components/message.does_not_exist'));
+ }
+
/**
* Return a view to display component information.
*
diff --git a/app/Http/Transformers/ComponentsTransformer.php b/app/Http/Transformers/ComponentsTransformer.php
index 1eba033017..562a02d3ce 100644
--- a/app/Http/Transformers/ComponentsTransformer.php
+++ b/app/Http/Transformers/ComponentsTransformer.php
@@ -84,6 +84,7 @@ class ComponentsTransformer
] : null,
'created_at' => Helper::getFormattedDateObject($component->created_at, 'datetime'),
'updated_at' => Helper::getFormattedDateObject($component->updated_at, 'datetime'),
+ 'deleted_at' => Helper::getFormattedDateObject($component->deleted_at, 'datetime'),
'user_can_checkout' => ($component->numRemaining() > 0) ? 1 : 0,
];
@@ -97,17 +98,26 @@ class ComponentsTransformer
$permissions_array = [];
$permissions_array['assigned_to_self'] = $userHasOpenRequest;
+ // Soft-deleted rows surface in the "Deleted" index view with
+ // their write-ish actions rendered disabled, not hidden, by
+ // the per-row formatter. Keep the policy-gated flags true so
+ // the disabled stand-ins render. The formatter inspects
+ // row.deleted_at to flip them to their disabled state.
+ $isDeleted = $component->deleted_at !== null;
$canUpdate = Gate::allows('update', $component);
$canDelete = $component->isDeletable();
$permissions_array['available_actions'] = [
'checkout' => Gate::allows('checkout', $component),
'checkin' => Gate::allows('checkin', $component),
- 'update' => $canUpdate,
+ 'update' => $canUpdate && ! $isDeleted,
'adjust_quantity' => $canUpdate,
+ // Cloning a deleted component is explicitly allowed. It
+ // produces a brand-new row and leaves the deleted parent
+ // untouched, so it's safe as a restore-and-tweak shortcut.
'clone' => Gate::allows('clone', $component),
'delete' => $canDelete,
- 'request' => (bool) $component->requestable && ! $userHasOpenRequest,
+ 'request' => (bool) $component->requestable && ! $isDeleted && ! $userHasOpenRequest,
'cancel' => (bool) $component->requestable && $userHasOpenRequest,
// Dropdown-action gating: the bulk-actions dropdown asks
// "can this row take THIS action?" and disables the
@@ -116,8 +126,16 @@ class ComponentsTransformer
// in partials/bootstrap-table). Keys must match the
// bulk_actions dropdown values on the components index.
'bulk_selectable' => [
- 'edit' => $canUpdate,
- 'delete' => $canDelete,
+ // Edit and Delete only make sense for live rows. On
+ // soft-deleted rows the bulk-actions dropdown offers
+ // Restore instead, so flip both off here to keep the
+ // dropdown's auto-uncheck guard honest.
+ 'edit' => $canUpdate && ! $isDeleted,
+ 'delete' => $canDelete && ! $isDeleted,
+ // Restore is only meaningful on the Deleted index.
+ // Treating it as a delete-tier action (same policy
+ // choice as postRestore / AssetModelsController).
+ 'restore' => $isDeleted && Gate::allows('delete', $component),
],
];
$array += $permissions_array;
diff --git a/app/Models/Traits/HasOrders.php b/app/Models/Traits/HasOrders.php
index 117a19ca30..d438a74352 100644
--- a/app/Models/Traits/HasOrders.php
+++ b/app/Models/Traits/HasOrders.php
@@ -75,11 +75,11 @@ trait HasOrders
/**
* Count of distinct Orders this item has been *purchased* on. Feeds
- * the info-panel's "Total Orders" row and the Orders-tab badge.
- * Filters to lines with positive qty so corrections / consumption
- * events (0- or negative-qty OrderItems) don't inflate the count —
- * those aren't purchases, and treating them as such was misleading
- * when a lifecycle had more corrections than actual acquisitions.
+ * the info-panel's "Total Orders" row. Filters to lines with
+ * positive qty so corrections / consumption events (0- or
+ * negative-qty OrderItems) don't inflate the count. Those aren't
+ * purchases, and treating them as such was misleading when a
+ * lifecycle had more corrections than actual acquisitions.
* DISTINCT because one Order can carry multiple positive lines for
* the same item under staggered receipts.
*/
@@ -91,6 +91,29 @@ trait HasOrders
->count('orders.id');
}
+ /**
+ * Row count that the Orders-tab API endpoint will return for this
+ * item. Used by the tab badge so the number next to "Orders"
+ * matches the row count of the table underneath. ordersCount
+ * (distinct Orders) is wrong for this specific surface because
+ * one Order can produce multiple table rows via multi-line
+ * acquisitions, and HasManyThrough's inner join + Order's own
+ * SoftDeletes scope can diverge from the API's leftJoin shape.
+ *
+ * Mirrors the filters applied by OrderItemsController::index,
+ * which excludes OrderItems whose parent Order has no order
+ * number. Those are the initial-inventory anchors written by
+ * writeInitialOrderIfStocked and shouldn't surface as "orders"
+ * in the admin UI alongside real acquisition records.
+ */
+ public function orderItemsCount(): int
+ {
+ return (int) $this->orderItems()
+ ->where('qty', '>', 0)
+ ->whereHas('order', fn ($q) => $q->whereNotNull('order_number'))
+ ->count();
+ }
+
/**
* Prefill context for the adjust-quantity modal and the info-panel's
* "last" fields. Prefers the most recent Order/OrderItem when one
diff --git a/app/Observers/ComponentObserver.php b/app/Observers/ComponentObserver.php
index d16f1b0b90..9ce1e51067 100644
--- a/app/Observers/ComponentObserver.php
+++ b/app/Observers/ComponentObserver.php
@@ -18,6 +18,16 @@ class ComponentObserver
$changed = [];
foreach ($component->getRawOriginal() as $key => $value) {
+ // SoftDeletes drives the delete + restore flows through
+ // save(), which fires `updated` with deleted_at as the
+ // changed field. The `deleting`/`restored` observers log
+ // those actions directly, so excluding deleted_at here
+ // keeps us from double-logging ("delete" plus an "update"
+ // row that only shows the deleted_at diff).
+ if ($key === 'deleted_at') {
+ continue;
+ }
+
// Check and see if the value changed
if ($component->getRawOriginal()[$key] != $component->getAttributes()[$key]) {
$changed[$key]['old'] = $component->getRawOriginal()[$key];
diff --git a/app/Presenters/ComponentPresenter.php b/app/Presenters/ComponentPresenter.php
index 210fbdbcab..10d388074b 100644
--- a/app/Presenters/ComponentPresenter.php
+++ b/app/Presenters/ComponentPresenter.php
@@ -8,11 +8,14 @@ namespace App\Presenters;
class ComponentPresenter extends Presenter
{
/**
- * Json Column Layout for bootstrap table
+ * JSON column layout for bootstrap-table.
*
+ * @param bool $showDeletedAt Make the deleted_at column visible
+ * by default. Passed from the Deleted-index view so admins
+ * see when each row was deleted. Still switchable elsewhere.
* @return string
*/
- public static function dataTableLayout()
+ public static function dataTableLayout(bool $showDeletedAt = false)
{
$layout = [
[
@@ -228,6 +231,15 @@ class ComponentPresenter extends Presenter
'visible' => false,
'title' => trans('general.updated_at'),
'formatter' => 'dateDisplayFormatter',
+ ], [
+ 'field' => 'deleted_at',
+ 'scope' => 'col',
+ 'searchable' => false,
+ 'sortable' => true,
+ 'switchable' => true,
+ 'visible' => $showDeletedAt,
+ 'title' => trans('general.deleted_at'),
+ 'formatter' => 'dateDisplayFormatter',
],
];
diff --git a/resources/lang/en-US/admin/components/message.php b/resources/lang/en-US/admin/components/message.php
index b836dee2ac..755a4321c6 100644
--- a/resources/lang/en-US/admin/components/message.php
+++ b/resources/lang/en-US/admin/components/message.php
@@ -14,6 +14,11 @@ return [
'success' => 'Component updated successfully.',
],
+ 'restore' => [
+ 'error' => 'Component was not restored, please try again',
+ 'success' => 'Component restored successfully.',
+ ],
+
'delete' => [
'confirm' => 'Are you sure you wish to delete this component?',
'error' => 'There was an issue deleting the component. Please try again.',
@@ -46,9 +51,13 @@ return [
'partial_success' => ':count component was deleted. See errors below for the rest.|:count components were deleted. See errors below for the rest.',
],
+ 'restore' => [
+ 'success' => ':count component was restored.|:count components were restored.',
+ ],
+
'checkin_selected' => [
'no_rows_selected' => 'No checked-out components were selected.',
- 'success' => ':count checked-out component was returned.|:count checked-out components were returned.',
+ 'success' => ':unit_count unit returned across :count checkout.|:unit_count units returned across :count checkouts.',
],
],
diff --git a/resources/lang/en-US/general.php b/resources/lang/en-US/general.php
index 8e10f0b6e6..82210dff93 100644
--- a/resources/lang/en-US/general.php
+++ b/resources/lang/en-US/general.php
@@ -56,6 +56,7 @@ return [
'assets_checked_in_count' => 'assets checked in',
'assets_checked_out_count' => 'assets checked out',
'asset_deleted_warning' => 'This asset has been deleted. You must restore it before you can assign it to someone.',
+ 'component_deleted_warning' => 'This component has been deleted. You must restore it before you can check it out again.',
'assigned_date' => 'Date Assigned',
'assigned_to' => 'Assigned to :name',
'assigned_quantity' => 'Assigned Quantity',
@@ -646,6 +647,7 @@ return [
'modal_confirm_generic' => 'Are you sure?',
'cannot_be_deleted' => 'This item cannot be deleted',
'cannot_be_edited' => 'This item cannot be edited.',
+ 'cannot_be_checked_out' => 'This item cannot be checked out.',
'undeployable_tooltip' => 'This item cannot be checked out. Check the quantity remaining.',
'serial_number' => 'Serial Number',
'item_notes' => ':item Notes',
diff --git a/resources/views/accessories/view.blade.php b/resources/views/accessories/view.blade.php
index 261a287150..3a63ea29be 100644
--- a/resources/views/accessories/view.blade.php
+++ b/resources/views/accessories/view.blade.php
@@ -26,7 +26,7 @@
<x-slot:tabnav>
<x-tabs.checkedout-tab :item="$accessory" count="{{ $accessory->checkouts_count }}" />
<x-tabs.files-tab :item="$accessory" count="{{ $accessory->uploads()->count() }}"/>
- <x-tabs.orders-tab count="{{ $accessory->ordersCount() }}"/>
+ <x-tabs.orders-tab count="{{ $accessory->orderItemsCount() }}"/>
<x-tabs.history-tab count="{{ $accessory->history()->count() }}" :model="$accessory"/>
<x-tabs.upload-tab :item="$accessory"/>
</x-slot:tabnav>
diff --git a/resources/views/blade/button/restore.blade.php b/resources/views/blade/button/restore.blade.php
index 0b9f4b4305..f6130dbd5f 100644
--- a/resources/views/blade/button/restore.blade.php
+++ b/resources/views/blade/button/restore.blade.php
@@ -7,7 +7,11 @@
@can('update', $item)
@if ($item->deleted_at!='')
<!-- start restore button component -->
- <form method="POST" action="{{ $route }}" class="inline">
+ {{-- Pull-right on the form matches the delete button's
+ alignment, so swapping delete↔restore between live and
+ soft-deleted views keeps the destructive-action slot in
+ the same spot in the info-panel. --}}
+ <form method="POST" action="{{ $route }}" class="inline pull-right">
@csrf
<button class="btn btn-sm btn-warning hidden-print{{ $wide == 'true' ? ' btn-block btn-social' : '' }}" data-tooltip="true" data-placement="top" data-title="{{ trans('general.restore') }}">
<x-icon type="restore" class="fa-fw" />
diff --git a/resources/views/blade/info-panel/index.blade.php b/resources/views/blade/info-panel/index.blade.php
index 1402b3b681..978c0b5e3b 100644
--- a/resources/views/blade/info-panel/index.blade.php
+++ b/resources/views/blade/info-panel/index.blade.php
@@ -219,10 +219,10 @@
<x-info-element>
<x-icon type="cost" class="fa-fw" title="{{ trans('general.total_cost') }}"/>
{{ trans('general.total_cost') }}
- <span class="pull-right">
- {{ $currency !== '' ? $currency : $snipeSettings->default_currency }}
+ {{ $currency !== '' ? $currency : $snipeSettings->default_currency }}
+ <x-copy-to-clipboard copy_what="total_cost" class="pull-right">
{{ Helper::formatCurrencyOutput($totalsByCurrency[$currency]) }}
- </span>
+ </x-copy-to-clipboard>
</x-info-element>
@elseif (count($totalsByCurrency) > 1)
<x-info-element>
diff --git a/resources/views/blade/table/bulk-components.blade.php b/resources/views/blade/table/bulk-components.blade.php
index 029890a816..31ce4d5e20 100644
--- a/resources/views/blade/table/bulk-components.blade.php
+++ b/resources/views/blade/table/bulk-components.blade.php
@@ -4,8 +4,12 @@
:action_route="route('components.bulkedit.show')"
model_name="component"
:actions="array_filter([
- 'edit' => Gate::allows('update', \App\Models\Component::class) ? ['label' => trans('general.bulk_edit')] : null,
- 'delete' => Gate::allows('delete', \App\Models\Component::class) ? ['label' => trans('general.delete')] : null,
+ 'edit' => (request('status') !== 'Deleted' && Gate::allows('update', \App\Models\Component::class))
+ ? ['label' => trans('general.bulk_edit')] : null,
+ 'delete' => (request('status') !== 'Deleted' && Gate::allows('delete', \App\Models\Component::class))
+ ? ['label' => trans('general.delete')] : null,
+ 'restore' => (request('status') === 'Deleted' && Gate::allows('delete', \App\Models\Component::class))
+ ? ['label' => trans('general.restore')] : null,
])"
/>
@endif
diff --git a/resources/views/components/index.blade.php b/resources/views/components/index.blade.php
index 813f2ab040..ef3c01e055 100644
--- a/resources/views/components/index.blade.php
+++ b/resources/views/components/index.blade.php
@@ -19,7 +19,10 @@
@section('content')
<x-container>
<x-box name="components" sr_only_title>
- <x-table.components :route="route('api.components.index', ['status' => e(request('status'))])" />
+ <x-table.components
+ :route="route('api.components.index', ['status' => e(request('status'))])"
+ :presenter="\App\Presenters\ComponentPresenter::dataTableLayout(request('status') === 'Deleted')"
+ />
</x-box>
</x-container>
@can('update', \App\Models\Component::class)
diff --git a/resources/views/components/view.blade.php b/resources/views/components/view.blade.php
index 38aec64656..ddb73e2ce1 100644
--- a/resources/views/components/view.blade.php
+++ b/resources/views/components/view.blade.php
@@ -13,6 +13,14 @@
@section('content')
<x-container columns="2">
+ @if ($snipe_component->deleted_at != '')
+ <div class="col-md-12">
+ <x-callout type="warning" icon="warning" live="assertive">
+ {{ trans('general.component_deleted_warning') }}
+ </x-callout>
+ </div>
+ @endif
+
<x-page-column class="col-md-9 main-panel">
<x-tabs>
<x-slot:tabnav>
@@ -25,9 +33,11 @@
/>
<x-tabs.files-tab :item="$snipe_component" count="{{ $snipe_component->uploads()->count() }}"/>
- <x-tabs.orders-tab count="{{ $snipe_component->ordersCount() }}"/>
+ <x-tabs.orders-tab count="{{ $snipe_component->orderItemsCount() }}"/>
<x-tabs.history-tab count="{{ $snipe_component->history()->count() }}" :model="$snipe_component"/>
- <x-tabs.upload-tab :item="$snipe_component"/>
+ @if ($snipe_component->deleted_at == '')
+ <x-tabs.upload-tab :item="$snipe_component"/>
+ @endif
</x-slot:tabnav>
@@ -83,27 +93,63 @@
<x-info-panel :infoPanelObj="$snipe_component" img_path="{{ app('components_upload_url') }}" :qr_code_url="route('qr_code/common', ['object_type' => 'components', 'id' => $snipe_component->id])">
<x-slot:buttons>
- <x-button.edit :item="$snipe_component" :route="route('components.edit', $snipe_component->id)"/>
- <x-button.clone :item="$snipe_component" :route="route('components.clone.create', $snipe_component->id)"/>
- <x-button.checkout :item="$snipe_component" :route="route('components.checkout.show', $snipe_component->id)" />
- @can('update', $snipe_component)
- @php $lastOrder = $snipe_component->lastOrderDefaults(); @endphp
- <button type="button"
- class="btn btn-sm btn-primary adjust-quantity {{ $snipe_component->archived ? 'disabled' : '' }}"
- data-tooltip="true"
- title="{{ $snipe_component->archived ? trans('admin/components/general.archived_component') : trans('general.adjust_quantity') }}"
- @disabled($snipe_component->archived)
- data-adjust-url="{{ route('components.adjust-quantity', $snipe_component) }}"
- data-item-name="{{ e($snipe_component->name) }}"
- data-available="{{ (int) $snipe_component->numRemaining() }}"
- @if ($lastOrder && $lastOrder['unit_cost'] !== null) data-last-unit-cost="{{ $lastOrder['unit_cost'] }}" @endif
- @if ($lastOrder && $lastOrder['currency'] !== null) data-last-currency="{{ e($lastOrder['currency']) }}" @endif
- >
- <x-icon type="plus-minus" class="fa-fw" />
- <span class="sr-only">{{ trans('general.adjust_quantity') }}</span>
- </button>
- @endcan
- <x-button.delete :item="$snipe_component" />
+ @if ($snipe_component->deleted_at != '')
+ {{-- Soft-deleted: keep every action visually
+ present but non-interactive so admins see
+ what's unavailable while viewing the
+ restorable record. x-button.edit hides
+ itself on deleted rows, so render disabled
+ stand-ins inline. --}}
+ @can('update', $snipe_component)
+ <a href="#" class="btn btn-sm btn-warning hidden-print disabled" data-tooltip="true" data-placement="top" data-title="{{ trans('general.component_deleted_warning') }}">
+ <x-icon type="edit" class="fa-fw" />
+ </a>
+ @endcan
+ {{-- Clone works on deleted items so admins
+ can spin up a replacement row without
+ restoring the original. Component gets
+ the normal active clone affordance. --}}
+ <x-button.clone :item="$snipe_component" :route="route('components.clone.create', $snipe_component->id)"/>
+ @can('checkout', $snipe_component)
+ <button type="button" class="btn btn-sm bg-maroon hidden-print disabled" data-tooltip="true" data-placement="top" data-title="{{ trans('general.component_deleted_warning') }}" disabled>
+ <x-icon type="checkout" class="fa-fw" />
+ </button>
+ @endcan
+ @can('update', $snipe_component)
+ <button type="button" class="btn btn-sm btn-primary adjust-quantity disabled" data-tooltip="true" data-placement="top" data-title="{{ trans('general.component_deleted_warning') }}" disabled>
+ <x-icon type="plus-minus" class="fa-fw" />
+ <span class="sr-only">{{ trans('general.adjust_quantity') }}</span>
+ </button>
+ @endcan
+ <x-button.restore :item="$snipe_component" :route="route('components.restore', ['componentID' => $snipe_component->id])" />
+ @else
+ <x-button.edit :item="$snipe_component" :route="route('components.edit', $snipe_component->id)"/>
+ <x-button.clone :item="$snipe_component" :route="route('components.clone.create', $snipe_component->id)"/>
+ <x-button.checkout :item="$snipe_component" :route="route('components.checkout.show', $snipe_component->id)" />
+ @can('update', $snipe_component)
+ @php
+ $lastOrder = $snipe_component->lastOrderDefaults();
+ $adjustDisabledReason = $snipe_component->archived
+ ? trans('admin/components/general.archived_component')
+ : null;
+ @endphp
+ <button type="button"
+ class="btn btn-sm btn-primary adjust-quantity {{ $adjustDisabledReason ? 'disabled' : '' }}"
+ data-tooltip="true"
+ title="{{ $adjustDisabledReason ?? trans('general.adjust_quantity') }}"
+ @disabled($adjustDisabledReason !== null)
+ data-adjust-url="{{ route('components.adjust-quantity', $snipe_component) }}"
+ data-item-name="{{ e($snipe_component->name) }}"
+ data-available="{{ (int) $snipe_component->numRemaining() }}"
+ @if ($lastOrder && $lastOrder['unit_cost'] !== null) data-last-unit-cost="{{ $lastOrder['unit_cost'] }}" @endif
+ @if ($lastOrder && $lastOrder['currency'] !== null) data-last-currency="{{ e($lastOrder['currency']) }}" @endif
+ >
+ <x-icon type="plus-minus" class="fa-fw" />
+ <span class="sr-only">{{ trans('general.adjust_quantity') }}</span>
+ </button>
+ @endcan
+ <x-button.delete :item="$snipe_component" />
+ @endif
</x-slot:buttons>
</x-info-panel>
@@ -116,13 +162,15 @@
@section('moar_scripts')
- @can('files', $snipe_component)
- <x-modals.upload-file item-type="components" :item-id="$snipe_component->id" />
- @endcan
-
- @can('update', $snipe_component)
- <x-modals.adjust-quantity />
- @endcan
+ @if ($snipe_component->deleted_at == '')
+ @can('files', $snipe_component)
+ <x-modals.upload-file item-type="components" :item-id="$snipe_component->id" />
+ @endcan
+
+ @can('update', $snipe_component)
+ <x-modals.adjust-quantity />
+ @endcan
+ @endif
@include ('partials.bootstrap-table', ['exportFile' => 'component' . $snipe_component->name . '-export', 'search' => false])
@endsection
diff --git a/resources/views/partials/bootstrap-table.blade.php b/resources/views/partials/bootstrap-table.blade.php
index b46a6a78db..3b8243e441 100644
--- a/resources/views/partials/bootstrap-table.blade.php
+++ b/resources/views/partials/bootstrap-table.blade.php
@@ -2696,13 +2696,18 @@
// for retired inventory rather than wondering where it
// went.
if ((row.available_actions) && (row.available_actions.adjust_quantity === true)) {
+ var adjustDeleted = !!row.deleted_at;
+ var adjustDisabled = adjustDeleted || row.archived === true;
+ var adjustReason = adjustDeleted
+ ? '{{ trans('general.component_deleted_warning') }}'
+ : '{{ trans('admin/components/general.archived_component') }}';
actions += window.renderAdjustQuantityButton({
dest: dest,
id: row.id,
name: row.name || '',
available: row.remaining,
- disabled: row.archived === true,
- disabledReason: '{{ trans('admin/components/general.archived_component') }}',
+ disabled: adjustDisabled,
+ disabledReason: adjustReason,
}) + '&nbsp;';
}
@@ -3226,6 +3231,15 @@
// the /{destination}/{id}/checkin/{backto?} route.
var backto = row.checkin_backto ? '/' + row.checkin_backto : '';
+ // Soft-deleted rows render a disabled checkout stand-in
+ // instead of the active link so the Deleted-index view
+ // keeps the control visible but inert. row.deleted_at is
+ // populated by the transformer whenever the model uses
+ // SoftDeletes.
+ if (row.deleted_at && (row.available_actions.checkout == true)) {
+ return '<span data-tooltip="true" title="{{ trans('general.cannot_be_checked_out') }}"><a class="btn btn-sm bg-maroon btn-checkout disabled">{{ trans('general.checkout') }}</a></span>';
+ }
+
// The user is allowed to check items out, AND the item is deployable
if ((row.available_actions.checkout == true) && (row.user_can_checkout == true) && ((!row.asset_id) && (!row.assigned_to))) {
diff --git a/routes/web/components.php b/routes/web/components.php
index c341662582..367c70ac64 100644
--- a/routes/web/components.php
+++ b/routes/web/components.php
@@ -48,13 +48,19 @@ Route::group(['prefix' => 'components', 'middleware' => ['auth']], function () {
Route::get('{component}/clone',
[Components\ComponentsController::class, 'getClone']
)->where('component', '[0-9]+')
- ->name('components.clone.create');
+ ->name('components.clone.create')
+ ->withTrashed();
Route::post('{component}/adjust-quantity',
[Components\ComponentsController::class, 'adjustQuantity']
)->where('component', '[0-9]+')
->name('components.adjust-quantity');
+ Route::post('{componentID}/restore',
+ [Components\ComponentsController::class, 'postRestore']
+ )->where('componentID', '[0-9]+')
+ ->name('components.restore');
+
// Bulk-fulfill queue for this component. Distinct from the
// sibling user-target bulk-fulfill routes (accessories/
// consumables/licenses) because component checkouts target an
@@ -102,4 +108,4 @@ Route::group(['prefix' => 'components', 'middleware' => ['auth']], function () {
Route::resource('components', Components\ComponentsController::class, [
'middleware' => ['auth'],
'parameters' => ['component' => 'component_id'],
-]);
+])->withTrashed(['show']);
diff --git a/tests/Feature/Components/Api/ComponentIndexDeletedActionsTest.php b/tests/Feature/Components/Api/ComponentIndexDeletedActionsTest.php
new file mode 100644
index 0000000000..d0a463f669
--- /dev/null
+++ b/tests/Feature/Components/Api/ComponentIndexDeletedActionsTest.php
@@ -0,0 +1,109 @@
+<?php
+
+namespace Tests\Feature\Components\Api;
+
+use App\Models\Component;
+use App\Models\User;
+use Tests\TestCase;
+
+/**
+ * The per-row action buttons on the Deleted index are purely driven by
+ * available_actions flags in the transformer payload (the shared
+ * genericActionsFormatter inspects row.deleted_at + available_actions
+ * to decide between active, disabled, and restore renderings).
+ *
+ * Pin the transformer's deleted-row shape so a future transformer
+ * refactor can't silently flip edit/adjust-quantity/checkout from
+ * disabled-but-visible back to active, or drop the restore flag that
+ * swaps the trash button out for restore.
+ */
+class ComponentIndexDeletedActionsTest extends TestCase
+{
+ private function rowFor(Component $component): array
+ {
+ $response = $this->actingAsForApi(User::factory()->superuser()->create())
+ ->getJson(route('api.components.index', ['status' => 'Deleted']))
+ ->assertOk();
+
+ $row = collect($response->json('rows'))->firstWhere('id', $component->id);
+ $this->assertNotNull($row, "deleted component {$component->id} should appear in Deleted index");
+
+ return $row;
+ }
+
+ public function test_deleted_row_blocks_update_and_delete_and_request(): void
+ {
+ $component = Component::factory()->create();
+ $component->delete();
+
+ $row = $this->rowFor($component);
+ $this->assertFalse($row['available_actions']['update']);
+ $this->assertFalse($row['available_actions']['delete']);
+ $this->assertFalse($row['available_actions']['request']);
+ }
+
+ public function test_deleted_row_keeps_adjust_quantity_true_so_formatter_renders_disabled(): void
+ {
+ // adjust_quantity stays policy-true even for deleted rows so
+ // the generic formatter renders a visible-but-disabled plus-
+ // minus button (driven off row.deleted_at). Flipping this to
+ // false would hide the button entirely, which is NOT what we
+ // want on the Deleted index.
+ $component = Component::factory()->create();
+ $component->delete();
+
+ $this->assertTrue($this->rowFor($component)['available_actions']['adjust_quantity']);
+ }
+
+ public function test_deleted_row_keeps_checkout_true_so_formatter_renders_disabled(): void
+ {
+ // Same rationale as adjust_quantity: keep the flag policy-
+ // true, let the InOut formatter inspect row.deleted_at and
+ // render a disabled checkout stand-in.
+ $component = Component::factory()->create();
+ $component->delete();
+
+ $this->assertTrue($this->rowFor($component)['available_actions']['checkout']);
+ }
+
+ public function test_deleted_row_keeps_clone_available(): void
+ {
+ // Cloning a deleted component is explicitly allowed as a
+ // restore-and-tweak shortcut: the clone produces a brand-new
+ // row and leaves the deleted parent untouched.
+ $component = Component::factory()->create();
+ $component->delete();
+
+ $this->assertTrue($this->rowFor($component)['available_actions']['clone']);
+ }
+
+ public function test_deleted_row_exposes_bulk_selectable_restore(): void
+ {
+ // The Deleted index's bulk-actions dropdown offers Restore
+ // instead of Edit/Delete. The dropdown's auto-uncheck guard
+ // (applyActionDependentRowStyling) reads bulk_selectable.restore
+ // to decide whether a row can participate in the restore batch.
+ $component = Component::factory()->create();
+ $component->delete();
+
+ $bulk = $this->rowFor($component)['available_actions']['bulk_selectable'];
+ $this->assertTrue($bulk['restore']);
+ $this->assertFalse($bulk['edit']);
+ $this->assertFalse($bulk['delete']);
+ }
+
+ public function test_live_row_does_not_expose_restore_bulk_selectable(): void
+ {
+ $component = Component::factory()->create();
+
+ $this->settings->set(['show_archived_in_list' => 1]);
+
+ $response = $this->actingAsForApi(User::factory()->superuser()->create())
+ ->getJson(route('api.components.index'))
+ ->assertOk();
+
+ $row = collect($response->json('rows'))->firstWhere('id', $component->id);
+ $this->assertNotNull($row);
+ $this->assertFalse($row['available_actions']['bulk_selectable']['restore']);
+ }
+}
diff --git a/tests/Feature/Components/ComponentDeleteLoggingTest.php b/tests/Feature/Components/ComponentDeleteLoggingTest.php
new file mode 100644
index 0000000000..02a3b002a6
--- /dev/null
+++ b/tests/Feature/Components/ComponentDeleteLoggingTest.php
@@ -0,0 +1,59 @@
+<?php
+
+namespace Tests\Feature\Components;
+
+use App\Models\Actionlog;
+use App\Models\Component;
+use App\Models\User;
+use Tests\TestCase;
+
+/**
+ * Regression pin for the double-log on soft-delete: SoftDeletes
+ * routes the delete flow through save(), which fires `updated`
+ * alongside `deleting`. The observer's `updated` hook used to log a
+ * generic "update" entry with just the deleted_at diff, producing a
+ * phantom audit row next to the real "delete" entry. Observer now
+ * skips deleted_at in the changed-field scan.
+ */
+class ComponentDeleteLoggingTest extends TestCase
+{
+ public function test_soft_delete_writes_only_a_single_delete_log_entry(): void
+ {
+ $this->actingAs(User::factory()->superuser()->create());
+
+ $component = Component::factory()->create();
+
+ $logsBefore = Actionlog::where('item_type', Component::class)
+ ->where('item_id', $component->id)
+ ->count();
+
+ $component->delete();
+
+ $logsAfter = Actionlog::where('item_type', Component::class)
+ ->where('item_id', $component->id)
+ ->orderBy('id')
+ ->get();
+
+ $this->assertCount($logsBefore + 1, $logsAfter, 'soft-delete should write exactly one new action_log row');
+ $this->assertSame('delete', $logsAfter->last()->action_type);
+ }
+
+ public function test_regular_update_still_logs_an_update_entry(): void
+ {
+ // Pin that stripping deleted_at from the diff didn't accidentally
+ // disable all update logging.
+ $this->actingAs(User::factory()->superuser()->create());
+
+ $component = Component::factory()->create();
+ $component->name = 'Renamed';
+ $component->save();
+
+ $this->assertTrue(
+ Actionlog::where('item_type', Component::class)
+ ->where('item_id', $component->id)
+ ->where('action_type', 'update')
+ ->exists(),
+ 'a plain update should still log an "update" row',
+ );
+ }
+}
diff --git a/tests/Feature/Components/Ui/BulkCheckinComponentsTest.php b/tests/Feature/Components/Ui/BulkCheckinComponentsTest.php
index 12731f7880..4bbb5b9503 100644
--- a/tests/Feature/Components/Ui/BulkCheckinComponentsTest.php
+++ b/tests/Feature/Components/Ui/BulkCheckinComponentsTest.php
@@ -34,7 +34,7 @@ class BulkCheckinComponentsTest extends TestCase
$this->actingAs(User::factory()->viewComponents()->create())
->post(route('components.bulkcheckin.selected'), ['ids' => [$pivotId]])
- ->assertRedirect();
+ ->assertForbidden();
$this->assertDatabaseHas('components_assets', ['id' => $pivotId]);
}
@@ -73,6 +73,46 @@ class BulkCheckinComponentsTest extends TestCase
->assertSessionHas('warning');
}
+ public function test_success_message_reports_total_units_not_just_pivot_rows(): void
+ {
+ // Regression: a pivot row can represent many units via
+ // assigned_qty, so "3 rows checked in" might really mean
+ // 25 units returned. The success message must surface the
+ // units total, not just the row count. Pin so a refactor
+ // can't quietly drop the per-row qty sum.
+ $component = Component::factory()->create(['qty' => 50]);
+
+ $pivotA = $this->attachCheckout($component, Asset::factory()->create(), 4);
+ $pivotB = $this->attachCheckout($component, Asset::factory()->create(), 11);
+ $pivotC = $this->attachCheckout($component, Asset::factory()->create(), 7);
+
+ $this->actingAs(User::factory()->superuser()->create())
+ ->post(route('components.bulkcheckin.selected'), ['ids' => [$pivotA, $pivotB, $pivotC]])
+ ->assertRedirect()
+ ->assertSessionHas('success', trans_choice(
+ 'admin/components/message.bulk.checkin_selected.success',
+ 3,
+ ['count' => 3, 'unit_count' => 22],
+ ));
+ }
+
+ public function test_success_message_handles_single_unit_single_row(): void
+ {
+ // Covers the singular side of the trans_choice branch for the
+ // simplest checkin: one row, one unit.
+ $component = Component::factory()->create(['qty' => 5]);
+ $pivot = $this->attachCheckout($component, Asset::factory()->create(), 1);
+
+ $this->actingAs(User::factory()->superuser()->create())
+ ->post(route('components.bulkcheckin.selected'), ['ids' => [$pivot]])
+ ->assertRedirect()
+ ->assertSessionHas('success', trans_choice(
+ 'admin/components/message.bulk.checkin_selected.success',
+ 1,
+ ['count' => 1, 'unit_count' => 1],
+ ));
+ }
+
public function test_unknown_pivot_ids_are_silently_skipped(): void
{
// Mirrors the LicenseCheckinController flow: stale pivot ids
diff --git a/tests/Feature/Components/Ui/OrdersTabBadgeTest.php b/tests/Feature/Components/Ui/OrdersTabBadgeTest.php
new file mode 100644
index 0000000000..a597b2c77d
--- /dev/null
+++ b/tests/Feature/Components/Ui/OrdersTabBadgeTest.php
@@ -0,0 +1,111 @@
+<?php
+
+namespace Tests\Feature\Components\Ui;
+
+use App\Models\Component;
+use App\Models\Order;
+use App\Models\OrderItem;
+use App\Models\User;
+use Tests\TestCase;
+
+/**
+ * Regression pin: the Orders-tab badge used to call ordersCount
+ * (distinct Orders through HasManyThrough) while the tab's table
+ * API returned OrderItems. One Order with multiple positive-qty
+ * lines produced badge=1 but table=N rows. The badge now mirrors
+ * the API's own filter via orderItemsCount, including the "parent
+ * Order must have a non-null order_number" filter that keeps
+ * initial-inventory anchors (writeInitialOrderIfStocked) from
+ * surfacing in the Orders UI.
+ */
+class OrdersTabBadgeTest extends TestCase
+{
+ public function test_badge_counts_order_items_not_distinct_orders(): void
+ {
+ $component = Component::factory()->create();
+
+ // One Order carries three positive-qty lines against the
+ // same component. ordersCount would say 1, since it counts
+ // distinct Orders. The API returns 3 rows, so the badge
+ // must say 3.
+ $order = Order::create(['order_number' => 'ORD-SAMEORDER']);
+ foreach (range(1, 3) as $_) {
+ OrderItem::create([
+ 'order_id' => $order->id,
+ 'item_type' => Component::class,
+ 'item_id' => $component->id,
+ 'qty' => 1,
+ ]);
+ }
+
+ $this->assertSame(3, $component->orderItemsCount());
+ }
+
+ public function test_badge_excludes_zero_and_negative_qty_lines(): void
+ {
+ // Corrections / consumption events ride on OrderItems with
+ // zero or negative qty and are shown on the History tab, not
+ // Orders. Must not inflate the Orders-tab badge.
+ $component = Component::factory()->create();
+ $order = Order::create(['order_number' => 'ORD-MIXEDQTY']);
+
+ OrderItem::create([
+ 'order_id' => $order->id,
+ 'item_type' => Component::class,
+ 'item_id' => $component->id,
+ 'qty' => 5,
+ ]);
+ OrderItem::create([
+ 'order_id' => $order->id,
+ 'item_type' => Component::class,
+ 'item_id' => $component->id,
+ 'qty' => 0,
+ ]);
+ OrderItem::create([
+ 'order_id' => $order->id,
+ 'item_type' => Component::class,
+ 'item_id' => $component->id,
+ 'qty' => -2,
+ ]);
+
+ $this->assertSame(1, $component->orderItemsCount());
+ }
+
+ public function test_badge_excludes_initial_inventory_anchor(): void
+ {
+ // writeInitialOrderIfStocked writes an Order with
+ // order_number=null + one positive-qty OrderItem whenever
+ // a Component is created with qty > 0. That anchor shouldn't
+ // count toward the Orders-tab badge or surface in the table,
+ // because admins think of "orders" as named acquisitions.
+ $component = Component::factory()->create();
+
+ $this->assertSame(0, $component->orderItemsCount());
+ }
+
+ public function test_badge_matches_api_row_count(): void
+ {
+ $component = Component::factory()->create();
+ $order = Order::create(['order_number' => 'ORD-APIMATCH']);
+
+ foreach (range(1, 2) as $_) {
+ OrderItem::create([
+ 'order_id' => $order->id,
+ 'item_type' => Component::class,
+ 'item_id' => $component->id,
+ 'qty' => 4,
+ ]);
+ }
+
+ $apiRows = $this->actingAsForApi(User::factory()->superuser()->create())
+ ->getJson(route('api.order-items.index', [
+ 'item_type' => Component::class,
+ 'item_id' => $component->id,
+ ]))
+ ->assertOk()
+ ->json('rows');
+
+ $this->assertSame(count($apiRows), $component->orderItemsCount());
+ $this->assertSame(2, $component->orderItemsCount());
+ }
+}
diff --git a/tests/Feature/Components/Ui/RestoreComponentTest.php b/tests/Feature/Components/Ui/RestoreComponentTest.php
new file mode 100644
index 0000000000..3e771c7d0f
--- /dev/null
+++ b/tests/Feature/Components/Ui/RestoreComponentTest.php
@@ -0,0 +1,151 @@
+<?php
+
+namespace Tests\Feature\Components\Ui;
+
+use App\Models\Company;
+use App\Models\Component;
+use App\Models\User;
+use Tests\TestCase;
+
+class RestoreComponentTest extends TestCase
+{
+ public function test_single_restore_requires_delete_permission(): void
+ {
+ $component = Component::factory()->create();
+ $component->delete();
+
+ $this->actingAs(User::factory()->viewComponents()->create())
+ ->post(route('components.restore', ['componentID' => $component->id]))
+ ->assertForbidden();
+
+ $this->assertNotNull($component->fresh()->deleted_at);
+ }
+
+ public function test_single_restore_brings_component_back(): void
+ {
+ $component = Component::factory()->create();
+ $component->delete();
+
+ $this->actingAs(User::factory()->superuser()->create())
+ ->post(route('components.restore', ['componentID' => $component->id]))
+ ->assertRedirect(route('components.show', $component));
+
+ $this->assertNull($component->fresh()->deleted_at);
+ }
+
+ public function test_single_restore_rejects_already_live_component(): void
+ {
+ $component = Component::factory()->create();
+
+ $this->actingAs(User::factory()->superuser()->create())
+ ->post(route('components.restore', ['componentID' => $component->id]))
+ ->assertRedirect()
+ ->assertSessionHas('error');
+
+ $this->assertNull($component->fresh()->deleted_at);
+ }
+
+ public function test_single_restore_rejects_unknown_id(): void
+ {
+ $this->actingAs(User::factory()->superuser()->create())
+ ->post(route('components.restore', ['componentID' => 999999]))
+ ->assertRedirect(route('components.index'))
+ ->assertSessionHas('error');
+ }
+
+ public function test_single_restore_blocks_cross_company_under_fmcs(): void
+ {
+ // postRestore now authorizes against the instance, so the
+ // policy's before() hook runs the FMCS cross-tenant check.
+ // Pin against the pre-fix behavior where class-level authorize
+ // skipped that guard.
+ $this->settings->enableMultipleFullCompanySupport();
+
+ [$companyA, $companyB] = Company::factory()->count(2)->create();
+ $actor = $companyA->users()->save(User::factory()->deleteComponents()->viewComponents()->make());
+ $foreign = Component::factory()->for($companyB)->create();
+ $foreign->delete();
+
+ $this->actingAs($actor)
+ ->post(route('components.restore', ['componentID' => $foreign->id]))
+ ->assertRedirect();
+
+ $this->assertNotNull($foreign->fresh()->deleted_at);
+ }
+
+ public function test_bulk_restore_requires_delete_permission(): void
+ {
+ $component = Component::factory()->create();
+ $component->delete();
+
+ $this->actingAs(User::factory()->viewComponents()->create())
+ ->post(route('components.bulkedit.show'), [
+ 'ids' => [$component->id],
+ 'bulk_actions' => 'restore',
+ ])
+ ->assertForbidden();
+
+ $this->assertNotNull($component->fresh()->deleted_at);
+ }
+
+ public function test_bulk_restore_brings_selected_components_back(): void
+ {
+ $one = Component::factory()->create();
+ $two = Component::factory()->create();
+ $one->delete();
+ $two->delete();
+
+ $this->actingAs(User::factory()->superuser()->create())
+ ->post(route('components.bulkedit.show'), [
+ 'ids' => [$one->id, $two->id],
+ 'bulk_actions' => 'restore',
+ ])
+ ->assertRedirect(route('components.index', ['status' => 'Deleted']))
+ ->assertSessionHas('success');
+
+ $this->assertNull($one->fresh()->deleted_at);
+ $this->assertNull($two->fresh()->deleted_at);
+ }
+
+ public function test_bulk_restore_skips_live_rows_without_error(): void
+ {
+ // Stale selection: one row is already live. The restore
+ // dispatcher silently skips live rows so the deleted ones
+ // still succeed. Pin so a future refactor can't tighten this
+ // into a hard failure that blocks the batch.
+ $deleted = Component::factory()->create();
+ $deleted->delete();
+
+ $live = Component::factory()->create();
+
+ $this->actingAs(User::factory()->superuser()->create())
+ ->post(route('components.bulkedit.show'), [
+ 'ids' => [$deleted->id, $live->id],
+ 'bulk_actions' => 'restore',
+ ])
+ ->assertRedirect(route('components.index', ['status' => 'Deleted']))
+ ->assertSessionHas('success');
+
+ $this->assertNull($deleted->fresh()->deleted_at);
+ $this->assertNull($live->fresh()->deleted_at);
+ }
+
+ public function test_bulk_restore_blocks_cross_company_under_fmcs(): void
+ {
+ $this->settings->enableMultipleFullCompanySupport();
+
+ [$companyA, $companyB] = Company::factory()->count(2)->create();
+ $actor = $companyA->users()->save(User::factory()->editComponents()->deleteComponents()->viewComponents()->make());
+ $foreign = Component::factory()->for($companyB)->create();
+ $foreign->delete();
+
+ $this->actingAs($actor)
+ ->post(route('components.bulkedit.show'), [
+ 'ids' => [$foreign->id],
+ 'bulk_actions' => 'restore',
+ ])
+ ->assertRedirect();
+
+ $this->assertNotNull($foreign->fresh()->deleted_at);
+ }
+}
diff --git a/tests/Feature/Components/Ui/SoftDeletedComponentViewTest.php b/tests/Feature/Components/Ui/SoftDeletedComponentViewTest.php
new file mode 100644
index 0000000000..4906cebe22
--- /dev/null
+++ b/tests/Feature/Components/Ui/SoftDeletedComponentViewTest.php
@@ -0,0 +1,95 @@
+<?php
+
+namespace Tests\Feature\Components\Ui;
+
+use App\Models\Component;
+use App\Models\User;
+use Tests\TestCase;
+
+class SoftDeletedComponentViewTest extends TestCase
+{
+ public function test_show_page_loads_for_soft_deleted_component(): void
+ {
+ // Resource route uses ->withTrashed(['show']) so route-model
+ // binding resolves soft-deleted components on the show path.
+ // Without that, clicking a row from /components?status=Deleted
+ // 404s before the controller runs.
+ $component = Component::factory()->create();
+ $component->delete();
+
+ $this->actingAs(User::factory()->superuser()->create())
+ ->get(route('components.show', $component))
+ ->assertOk();
+ }
+
+ public function test_show_page_renders_deleted_warning_banner(): void
+ {
+ $component = Component::factory()->create();
+ $component->delete();
+
+ $this->actingAs(User::factory()->superuser()->create())
+ ->get(route('components.show', $component))
+ ->assertOk()
+ ->assertSeeText(trans('general.component_deleted_warning'));
+ }
+
+ public function test_live_show_page_does_not_render_deleted_banner(): void
+ {
+ $component = Component::factory()->create();
+
+ $this->actingAs(User::factory()->superuser()->create())
+ ->get(route('components.show', $component))
+ ->assertOk()
+ ->assertDontSeeText(trans('general.component_deleted_warning'));
+ }
+
+ public function test_clone_route_resolves_soft_deleted_component(): void
+ {
+ // Clone works on deleted parents (restore-and-tweak shortcut).
+ // Needs ->withTrashed() on the clone route to let route-model
+ // binding find the parent.
+ $component = Component::factory()->create();
+ $component->delete();
+
+ $this->actingAs(User::factory()->superuser()->create())
+ ->get(route('components.clone.create', $component->id))
+ ->assertOk();
+ }
+
+ public function test_adjust_quantity_endpoint_does_not_touch_soft_deleted(): void
+ {
+ // Belt-and-braces: the view disables the adjust-quantity
+ // button on deleted rows, and the endpoint uses standard
+ // route-model binding (no withTrashed), so a direct POST
+ // to /components/{deleted-id}/adjust-quantity can't bump qty
+ // on a deleted parent. Pin on the quantity staying put rather
+ // than the specific HTTP status so a future validation /
+ // route-model-binding refactor can shift the response code
+ // without weakening the actual guard.
+ $component = Component::factory()->create(['qty' => 5]);
+ $component->delete();
+
+ $this->actingAs(User::factory()->superuser()->create())
+ ->post(route('components.adjust-quantity', ['component' => $component->id]), [
+ 'amount' => 1,
+ 'adjustment_type' => 'increase',
+ 'purchase_date' => now()->toDateString(),
+ ]);
+
+ $this->assertSame(5, (int) $component->fresh()->qty);
+ }
+
+ public function test_checkout_endpoint_blocks_soft_deleted(): void
+ {
+ // The checkout controller does its own Component::find lookup
+ // (not route-model binding) which auto-applies the soft-delete
+ // scope and returns null. Pin so stock-depleting checkouts
+ // can't fire on a deleted parent.
+ $component = Component::factory()->create();
+ $component->delete();
+
+ $this->actingAs(User::factory()->superuser()->create())
+ ->get(route('components.checkout.show', ['componentID' => $component->id]))
+ ->assertRedirect(route('components.index'));
+ }
+}