Skip to content

A free open source IT asset/license management system

Mirror behavior in API

snipe5aa9458044d5
diff --git a/app/Http/Controllers/Api/AccessoriesController.php b/app/Http/Controllers/Api/AccessoriesController.php
index fe7f7c105b..6f917b1feb 100644
--- a/app/Http/Controllers/Api/AccessoriesController.php
+++ b/app/Http/Controllers/Api/AccessoriesController.php
@@ -5,6 +5,7 @@ namespace App\Http\Controllers\Api;
use App\Events\CheckoutableCheckedIn;
use App\Events\CheckoutableCheckedOut;
use App\Helpers\Helper;
+use App\Http\Controllers\Accessories\BulkAccessoriesController;
use App\Http\Controllers\Controller;
use App\Http\Requests\AccessoryCheckoutRequest;
use App\Http\Requests\AdjustQuantityRequest;
@@ -25,6 +26,8 @@ use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB;
+use Illuminate\Support\Facades\Gate;
+use Illuminate\Validation\ValidationException;
class AccessoriesController extends Controller
{
@@ -400,10 +403,19 @@ class AccessoriesController extends Controller
{
$this->authorize('delete', Accessory::class);
$accessory = Accessory::withCount('checkouts as checkouts_count')->findOrFail($id);
- $this->authorize($accessory);
-
- if ($accessory->checkouts_count > 0) {
- return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/accessories/general.delete_disabled')));
+ $this->authorize('delete', $accessory);
+
+ // Mirror the web + bulk paths. Active checkouts block destroy
+ // the same way they block archive.
+ if (! $accessory->isDeletable()) {
+ return response()->json(Helper::formatStandardApiResponse(
+ 'error',
+ null,
+ trans('general.bulk_delete_associations.assoc_checkouts_no_count', [
+ 'item_name' => $accessory->name,
+ 'item' => trans('general.accessory'),
+ ]),
+ ), 422);
}
$accessory->delete();
@@ -411,6 +423,236 @@ class AccessoriesController extends Controller
return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/accessories/message.delete.success')));
}
+ /**
+ * Restore a soft-deleted accessory. API parity for the web
+ * AccessoriesController::postRestore endpoint.
+ */
+ public function restore($id): JsonResponse
+ {
+ $this->authorize('delete', Accessory::class);
+ $accessory = Accessory::withTrashed()->findOrFail($id);
+ $this->authorize('delete', $accessory);
+
+ if ($accessory->deleted_at === null) {
+ return response()->json(Helper::formatStandardApiResponse(
+ 'error',
+ null,
+ trans('general.not_deleted', ['item_type' => trans('general.accessory')]),
+ ), 422);
+ }
+
+ if (! $accessory->restore()) {
+ return response()->json(Helper::formatStandardApiResponse(
+ 'error',
+ null,
+ trans('general.could_not_restore', ['item_type' => trans('general.accessory'), 'error' => $accessory->getErrors()->first()]),
+ ), 422);
+ }
+
+ return response()->json(Helper::formatStandardApiResponse(
+ 'success',
+ null,
+ trans('admin/accessories/message.restore.success'),
+ ));
+ }
+
+ /**
+ * Flip archived off. API parity for the web
+ * AccessoriesController::postUnarchive endpoint.
+ */
+ public function unarchive(Accessory $accessory): JsonResponse
+ {
+ $this->authorize('update', $accessory);
+
+ if (! $accessory->archived) {
+ return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/accessories/message.update.success')));
+ }
+
+ $accessory->archived = false;
+ if (! $accessory->save()) {
+ return response()->json(Helper::formatStandardApiResponse('error', null, $accessory->getErrors()), 422);
+ }
+
+ return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/accessories/message.update.success')));
+ }
+
+ /**
+ * Bulk edit. Mirror of BulkAccessoriesController::update.
+ * Returns JSON instead of a flash redirect, otherwise identical
+ * semantics: writes only non-blank fields, routes company_id
+ * through FMCS, supports null_{field}=1 opt-in null-outs, per-row
+ * Gate check, surfaces partial-success detail in the payload.
+ */
+ public function bulkEdit(Request $request): JsonResponse
+ {
+ $this->authorize('update', Accessory::class);
+
+ if (! $request->filled('ids')) {
+ return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/accessories/message.bulk.no_accessories_selected')), 422);
+ }
+
+ $accessories = Accessory::whereIn('id', $request->input('ids'))->get();
+ if ($accessories->isEmpty()) {
+ return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/accessories/message.bulk.no_accessories_selected')), 422);
+ }
+
+ $updateData = [];
+ foreach (BulkAccessoriesController::EDITABLE_FIELDS as $field) {
+ if (! $request->has($field)) {
+ continue;
+ }
+ $value = $request->input($field);
+ if ($value === '' || $value === null) {
+ continue;
+ }
+ $updateData[$field] = $value;
+ }
+
+ if (array_key_exists('company_id', $updateData)) {
+ try {
+ $updateData['company_id'] = Company::getIdForCurrentUser($updateData['company_id']);
+ } catch (ValidationException $e) {
+ return response()->json(Helper::formatStandardApiResponse('error', null, $e->errors()), 422);
+ }
+ }
+
+ foreach (['category_id', 'company_id', 'manufacturer_id', 'location_id', 'default_supplier_id', 'min_amt'] as $field) {
+ if ($request->boolean('null_'.$field)) {
+ if ($field === 'category_id') {
+ continue;
+ }
+ $updateData[$field] = null;
+ }
+ }
+
+ if (empty($updateData)) {
+ return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/accessories/message.bulk.no_fields_updated')), 422);
+ }
+
+ $authorized = $accessories->filter(fn (Accessory $a) => Gate::allows('update', $a));
+ $skipped = $accessories->count() - $authorized->count();
+
+ $updated = 0;
+ $failed_rows = [];
+ foreach ($authorized as $accessory) {
+ $accessory->fill($updateData);
+ if ($accessory->save()) {
+ $updated++;
+
+ continue;
+ }
+ $failed_rows[] = $accessory->name.': '.$accessory->getErrors()->first();
+ }
+
+ $failed = count($failed_rows);
+ $payload = ['updated' => $updated, 'skipped_unauthorized' => $skipped, 'failed_rows' => $failed_rows];
+
+ if ($updated === 0 && $failed > 0) {
+ return response()->json(Helper::formatStandardApiResponse(
+ 'error',
+ $payload,
+ trans_choice('admin/accessories/message.bulk.update.none_updated', $failed, ['count' => $failed]),
+ ), 422);
+ }
+
+ return response()->json(Helper::formatStandardApiResponse(
+ 'success',
+ $payload,
+ trans_choice('admin/accessories/message.bulk.update.success', $updated, ['count' => $updated]),
+ ));
+ }
+
+ /**
+ * Bulk soft-delete. Per-row isDeletable + Gate check mirror the
+ * web controller.
+ */
+ public function bulkDestroy(Request $request): JsonResponse
+ {
+ $this->authorize('delete', Accessory::class);
+
+ $errors = [];
+ $success_count = 0;
+
+ foreach ((array) $request->input('ids', []) as $id) {
+ $accessory = Accessory::find($id);
+ if (is_null($accessory)) {
+ $errors[] = trans('admin/accessories/message.does_not_exist', ['id' => $id]);
+
+ continue;
+ }
+
+ if (! Gate::allows('delete', $accessory)) {
+ $errors[] = trans('general.unauthorized');
+
+ continue;
+ }
+
+ $accessory->loadCount('checkouts as checkouts_count');
+ if (! $accessory->isDeletable()) {
+ $errors[] = trans('general.bulk_delete_associations.assoc_checkouts_no_count', [
+ 'item_name' => $accessory->name,
+ 'item' => trans('general.accessory'),
+ ]);
+
+ continue;
+ }
+
+ $accessory->delete();
+ $success_count++;
+ }
+
+ $payload = ['deleted' => $success_count, 'errors' => $errors];
+ $message = $success_count > 0
+ ? trans_choice('admin/accessories/message.delete.bulk_success', $success_count, ['count' => $success_count])
+ : trans('admin/accessories/message.bulk.no_accessories_selected');
+
+ return response()->json(
+ Helper::formatStandardApiResponse($success_count > 0 ? 'success' : 'error', $payload, $message),
+ $success_count > 0 ? 200 : 422,
+ );
+ }
+
+ /**
+ * Bulk restore. Already-live rows are skipped without erroring so
+ * a stale selection doesn't blow up the whole batch.
+ */
+ public function bulkRestore(Request $request): JsonResponse
+ {
+ $this->authorize('delete', Accessory::class);
+
+ $ids = (array) $request->input('ids', []);
+ if ($ids === []) {
+ return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/accessories/message.bulk.no_accessories_selected')), 422);
+ }
+
+ $accessories = Accessory::withTrashed()->whereIn('id', $ids)->get();
+
+ $restored = 0;
+ $errors = [];
+
+ foreach ($accessories as $accessory) {
+ if (! Gate::allows('delete', $accessory)) {
+ $errors[] = trans('general.unauthorized');
+
+ continue;
+ }
+
+ if ($accessory->deleted_at === null) {
+ continue;
+ }
+
+ if ($accessory->restore()) {
+ $restored++;
+ }
+ }
+
+ return response()->json(Helper::formatStandardApiResponse(
+ $restored > 0 ? 'success' : 'error',
+ ['restored' => $restored, 'errors' => $errors],
+ trans_choice('admin/accessories/message.bulk.restore.success', $restored, ['count' => $restored]),
+ ), $restored > 0 ? 200 : 422);
+ }
+
/**
* Save the Accessory checkout information.
*
diff --git a/app/Http/Controllers/Api/ComponentsController.php b/app/Http/Controllers/Api/ComponentsController.php
index f7db8232e9..52f4ad3c0e 100644
--- a/app/Http/Controllers/Api/ComponentsController.php
+++ b/app/Http/Controllers/Api/ComponentsController.php
@@ -5,6 +5,7 @@ namespace App\Http\Controllers\Api;
use App\Events\CheckoutableCheckedIn;
use App\Exceptions\MissingLogTarget;
use App\Helpers\Helper;
+use App\Http\Controllers\Components\BulkComponentsController;
use App\Http\Controllers\Controller;
use App\Http\Requests\AdjustQuantityRequest;
use App\Http\Requests\ImageUploadRequest;
@@ -24,6 +25,7 @@ use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
+use Illuminate\Validation\ValidationException;
class ComponentsController extends Controller
{
@@ -336,8 +338,19 @@ class ComponentsController extends Controller
$component = Component::findOrFail($id);
$this->authorize('delete', $component);
- if ($component->numCheckedOut() > 0) {
- return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/components/message.delete.error_qty')));
+ // Mirror the web + bulk paths. Active checkouts block destroy
+ // the same way they block archive. numCheckedOut() reads
+ // sum_unconstrained_assets. Load it first to avoid a per-row query.
+ $component->loadSum('unconstrainedAssets as sum_unconstrained_assets', 'components_assets.assigned_qty');
+ if (! $component->isDeletable()) {
+ return response()->json(Helper::formatStandardApiResponse(
+ 'error',
+ null,
+ trans('general.bulk_delete_associations.assoc_checkouts_no_count', [
+ 'item_name' => $component->name,
+ 'item' => trans('general.component'),
+ ]),
+ ), 422);
}
$component->delete();
@@ -345,6 +358,238 @@ class ComponentsController extends Controller
return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/components/message.delete.success')));
}
+ /**
+ * Restore a soft-deleted component. API parity for the web
+ * ComponentsController::postRestore endpoint.
+ */
+ public function restore($id): JsonResponse
+ {
+ $this->authorize('delete', Component::class);
+ $component = Component::withTrashed()->findOrFail($id);
+ $this->authorize('delete', $component);
+
+ if ($component->deleted_at === null) {
+ return response()->json(Helper::formatStandardApiResponse(
+ 'error',
+ null,
+ trans('general.not_deleted', ['item_type' => trans('general.component')]),
+ ), 422);
+ }
+
+ if (! $component->restore()) {
+ return response()->json(Helper::formatStandardApiResponse(
+ 'error',
+ null,
+ trans('general.could_not_restore', ['item_type' => trans('general.component'), 'error' => $component->getErrors()->first()]),
+ ), 422);
+ }
+
+ return response()->json(Helper::formatStandardApiResponse(
+ 'success',
+ null,
+ trans('admin/components/message.restore.success'),
+ ));
+ }
+
+ /**
+ * Flip archived off. API parity for the web
+ * ComponentsController::postUnarchive endpoint.
+ */
+ public function unarchive(Component $component): JsonResponse
+ {
+ $this->authorize('update', $component);
+
+ if (! $component->archived) {
+ return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/components/message.update.success')));
+ }
+
+ $component->archived = false;
+ if (! $component->save()) {
+ return response()->json(Helper::formatStandardApiResponse('error', null, $component->getErrors()), 422);
+ }
+
+ return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/components/message.update.success')));
+ }
+
+ /**
+ * Bulk edit. Mirror of BulkComponentsController::update.
+ * Returns JSON instead of a flash redirect, otherwise identical
+ * semantics: writes only non-blank fields, routes company_id
+ * through FMCS, supports null_{field}=1 opt-in null-outs, per-row
+ * Gate check, surfaces partial-success detail in the payload.
+ */
+ public function bulkEdit(Request $request): JsonResponse
+ {
+ $this->authorize('update', Component::class);
+
+ if (! $request->filled('ids')) {
+ return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/components/message.bulk.no_components_selected')), 422);
+ }
+
+ $components = Component::whereIn('id', $request->input('ids'))->get();
+ if ($components->isEmpty()) {
+ return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/components/message.bulk.no_components_selected')), 422);
+ }
+
+ $updateData = [];
+ foreach (BulkComponentsController::EDITABLE_FIELDS as $field) {
+ if (! $request->has($field)) {
+ continue;
+ }
+ $value = $request->input($field);
+ if ($value === '' || $value === null) {
+ continue;
+ }
+ $updateData[$field] = $value;
+ }
+
+ if (array_key_exists('company_id', $updateData)) {
+ try {
+ $updateData['company_id'] = Company::getIdForCurrentUser($updateData['company_id']);
+ } catch (ValidationException $e) {
+ return response()->json(Helper::formatStandardApiResponse('error', null, $e->errors()), 422);
+ }
+ }
+
+ foreach (['category_id', 'company_id', 'manufacturer_id', 'location_id', 'default_supplier_id', 'min_amt'] as $field) {
+ if ($request->boolean('null_'.$field)) {
+ if ($field === 'category_id') {
+ continue;
+ }
+ $updateData[$field] = null;
+ }
+ }
+
+ if (empty($updateData)) {
+ return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/components/message.bulk.no_fields_updated')), 422);
+ }
+
+ $authorized = $components->filter(fn (Component $c) => Gate::allows('update', $c));
+ $skipped = $components->count() - $authorized->count();
+
+ $updated = 0;
+ $failed_rows = [];
+ foreach ($authorized as $component) {
+ $component->fill($updateData);
+ if ($component->save()) {
+ $updated++;
+
+ continue;
+ }
+ $failed_rows[] = $component->name.': '.$component->getErrors()->first();
+ }
+
+ $failed = count($failed_rows);
+ $payload = ['updated' => $updated, 'skipped_unauthorized' => $skipped, 'failed_rows' => $failed_rows];
+
+ if ($updated === 0 && $failed > 0) {
+ return response()->json(Helper::formatStandardApiResponse(
+ 'error',
+ $payload,
+ trans_choice('admin/components/message.bulk.update.none_updated', $failed, ['count' => $failed]),
+ ), 422);
+ }
+
+ return response()->json(Helper::formatStandardApiResponse(
+ 'success',
+ $payload,
+ trans_choice('admin/components/message.bulk.update.success', $updated, ['count' => $updated]),
+ ));
+ }
+
+ /**
+ * Bulk soft-delete. Per-row isDeletable + Gate check mirror the
+ * web controller.
+ */
+ public function bulkDestroy(Request $request): JsonResponse
+ {
+ $this->authorize('delete', Component::class);
+
+ $errors = [];
+ $success_count = 0;
+
+ foreach ((array) $request->input('ids', []) as $id) {
+ $component = Component::find($id);
+ if (is_null($component)) {
+ $errors[] = trans('admin/components/message.does_not_exist', ['id' => $id]);
+
+ continue;
+ }
+
+ if (! Gate::allows('delete', $component)) {
+ $errors[] = trans('general.unauthorized');
+
+ continue;
+ }
+
+ // numCheckedOut() reads sum_unconstrained_assets. Load it
+ // first so isDeletable() does not fire a per-row sub-query.
+ $component->loadSum('unconstrainedAssets as sum_unconstrained_assets', 'components_assets.assigned_qty');
+ if (! $component->isDeletable()) {
+ $errors[] = trans('general.bulk_delete_associations.assoc_checkouts_no_count', [
+ 'item_name' => $component->name,
+ 'item' => trans('general.component'),
+ ]);
+
+ continue;
+ }
+
+ $component->delete();
+ $success_count++;
+ }
+
+ $payload = ['deleted' => $success_count, 'errors' => $errors];
+ $message = $success_count > 0
+ ? trans_choice('admin/components/message.bulk.delete.success', $success_count, ['count' => $success_count])
+ : trans('admin/components/message.bulk.no_components_selected');
+
+ return response()->json(
+ Helper::formatStandardApiResponse($success_count > 0 ? 'success' : 'error', $payload, $message),
+ $success_count > 0 ? 200 : 422,
+ );
+ }
+
+ /**
+ * Bulk restore. Already-live rows are skipped without erroring so
+ * a stale selection doesn't blow up the whole batch.
+ */
+ public function bulkRestore(Request $request): JsonResponse
+ {
+ $this->authorize('delete', Component::class);
+
+ $ids = (array) $request->input('ids', []);
+ if ($ids === []) {
+ return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/components/message.bulk.no_components_selected')), 422);
+ }
+
+ $components = Component::withTrashed()->whereIn('id', $ids)->get();
+
+ $restored = 0;
+ $errors = [];
+
+ foreach ($components as $component) {
+ if (! Gate::allows('delete', $component)) {
+ $errors[] = trans('general.unauthorized');
+
+ continue;
+ }
+
+ if ($component->deleted_at === null) {
+ continue;
+ }
+
+ if ($component->restore()) {
+ $restored++;
+ }
+ }
+
+ return response()->json(Helper::formatStandardApiResponse(
+ $restored > 0 ? 'success' : 'error',
+ ['restored' => $restored, 'errors' => $errors],
+ trans_choice('admin/components/message.bulk.restore.success', $restored, ['count' => $restored]),
+ ), $restored > 0 ? 200 : 422);
+ }
+
/**
* Display all assets attached to a component
*
diff --git a/app/Http/Controllers/Api/ConsumablesController.php b/app/Http/Controllers/Api/ConsumablesController.php
index 2173150d2b..785a8c4175 100644
--- a/app/Http/Controllers/Api/ConsumablesController.php
+++ b/app/Http/Controllers/Api/ConsumablesController.php
@@ -4,6 +4,7 @@ namespace App\Http\Controllers\Api;
use App\Events\CheckoutableCheckedOut;
use App\Helpers\Helper;
+use App\Http\Controllers\Consumables\BulkConsumablesController;
use App\Http\Controllers\Controller;
use App\Http\Requests\AdjustQuantityRequest;
use App\Http\Requests\FilterRequest;
@@ -13,14 +14,18 @@ use App\Http\Traits\HandlesAdjustQuantity;
use App\Http\Transformers\ActionlogsTransformer;
use App\Http\Transformers\ConsumablesTransformer;
use App\Http\Transformers\SelectlistTransformer;
+use App\Models\Actionlog;
use App\Models\Company;
use App\Models\Consumable;
+use App\Models\ConsumableAssignment;
use App\Models\Setting;
use App\Models\User;
use DomainException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
+use Illuminate\Support\Facades\Gate;
+use Illuminate\Validation\ValidationException;
class ConsumablesController extends Controller
{
@@ -38,8 +43,12 @@ class ConsumablesController extends Controller
$this->authorize('index', Consumable::class);
// See ComponentsController for the orderItems.order.supplier eager-load rationale.
+ // consumables_users_count feeds the stockroom-remaining math (qty minus total ever
+ // distributed, unchanged by mark-consumed). outstanding_assignments_count feeds
+ // isDeletable() and the archive guard so neither fires a per-row count query.
$consumables = Consumable::with('company', 'location', 'category', 'defaultSupplier', 'manufacturer', 'orderItems.order.supplier')
- ->withCount('users as consumables_users_count');
+ ->withCount('users as consumables_users_count')
+ ->withCount('outstandingAssignments as outstanding_assignments_count');
// This array is what determines which fields should be allowed to be sorted on ON the table itself.
// These must match a column on the consumables table directly.
@@ -68,6 +77,19 @@ class ConsumablesController extends Controller
'manufacturer',
];
+ // Archived / soft-deleted scope.
+ switch ($request->input('status')) {
+ case 'Archived':
+ $consumables->archived();
+ break;
+ case 'Deleted':
+ $consumables->onlyTrashed();
+ break;
+ default:
+ $consumables->consumablesForShow();
+ break;
+ }
+
// This invokes the Searchable model trait scopeTextSearch and will handle input by search or by advanced search filter
if ($request->filled('filter') || $request->filled('search')) {
$consumables->TextSearch($request->input('filter') ? $request->input('filter') : $request->input('search'));
@@ -77,6 +99,14 @@ class ConsumablesController extends Controller
$consumables->where('consumables.name', '=', $request->input('name'));
}
+ if ($request->input('requestable') == 'true') {
+ $consumables->where('consumables.requestable', '=', '1');
+ }
+
+ if ($request->input('archived') == 'true') {
+ $consumables->archived();
+ }
+
if ($request->filled('company_id')) {
// expand_company_hierarchy=1 opts the company show-page tabs into the
// parent/child rollup so a child shows items inherited from its parent.
@@ -298,11 +328,79 @@ class ConsumablesController extends Controller
$this->authorize('delete', Consumable::class);
$consumable = Consumable::findOrFail($id);
$this->authorize('delete', $consumable);
+
+ // Mirror the web + bulk paths. Outstanding distributions
+ // block destroy the same way they block archive.
+ $consumable->loadCount('outstandingAssignments as outstanding_assignments_count');
+ if (! $consumable->isDeletable()) {
+ return response()->json(Helper::formatStandardApiResponse(
+ 'error',
+ null,
+ trans('general.bulk_delete_associations.assoc_checkouts_no_count', [
+ 'item_name' => $consumable->name,
+ 'item' => trans('general.consumable'),
+ ]),
+ ), 422);
+ }
+
$consumable->delete();
return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/consumables/message.delete.success')));
}
+ /**
+ * Restore a soft-deleted consumable. API parity for the web
+ * ConsumablesController::postRestore endpoint.
+ */
+ public function restore($id): JsonResponse
+ {
+ $this->authorize('delete', Consumable::class);
+ $consumable = Consumable::withTrashed()->findOrFail($id);
+ $this->authorize('delete', $consumable);
+
+ if ($consumable->deleted_at === null) {
+ return response()->json(Helper::formatStandardApiResponse(
+ 'error',
+ null,
+ trans('general.not_deleted', ['item_type' => trans('general.consumable')]),
+ ), 422);
+ }
+
+ if (! $consumable->restore()) {
+ return response()->json(Helper::formatStandardApiResponse(
+ 'error',
+ null,
+ trans('general.could_not_restore', ['item_type' => trans('general.consumable'), 'error' => $consumable->getErrors()->first()]),
+ ), 422);
+ }
+
+ return response()->json(Helper::formatStandardApiResponse(
+ 'success',
+ null,
+ trans('admin/consumables/message.restore.success'),
+ ));
+ }
+
+ /**
+ * Flip archived off. API parity for the web
+ * ConsumablesController::postUnarchive endpoint.
+ */
+ public function unarchive(Consumable $consumable): JsonResponse
+ {
+ $this->authorize('update', $consumable);
+
+ if (! $consumable->archived) {
+ return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/consumables/message.update.success')));
+ }
+
+ $consumable->archived = false;
+ if (! $consumable->save()) {
+ return response()->json(Helper::formatStandardApiResponse('error', null, $consumable->getErrors()), 422);
+ }
+
+ return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/consumables/message.update.success')));
+ }
+
/**
* Returns a JSON response containing details on the users associated with this consumable.
*
@@ -315,8 +413,12 @@ class ConsumablesController extends Controller
*/
public function getDataView($consumableId): array
{
+ // Only outstanding pivot rows surface on the Assigned tab.
+ // Rows marked consumed drop out of the checkouts view because
+ // they are no longer "currently distributed." The audit trail
+ // for each consume still lives on the item's History tab.
$consumable = Consumable::with(['consumableAssignments' => function ($query) {
- $query->orderBy($query->getModel()->getTable().'.created_at', 'DESC');
+ $query->outstanding()->orderBy($query->getModel()->getTable().'.created_at', 'DESC');
},
'consumableAssignments.adminuser' => function ($query) {},
'consumableAssignments.user' => function ($query) {},
@@ -328,8 +430,12 @@ class ConsumablesController extends Controller
$this->authorize('view', Consumable::class);
$rows = [];
+ $canConsume = Gate::allows('checkout', $consumable);
+
foreach ($consumable->consumableAssignments as $consumable_assignment) {
$rows[] = [
+ 'id' => (int) $consumable_assignment->id,
+ 'consumable_id' => (int) $consumable_assignment->consumable_id,
'avatar' => ($consumable_assignment->user) ? e($consumable_assignment->user->present()->gravatar) : '',
'user' => ($consumable_assignment->user) ? [
'id' => (int) $consumable_assignment->user->id,
@@ -341,13 +447,16 @@ class ConsumablesController extends Controller
'id' => (int) $consumable_assignment->adminuser->id,
'name' => e($consumable_assignment->adminuser->display_name),
] : null,
+ 'available_actions' => [
+ 'consume' => $canConsume,
+ 'bulk_selectable' => [
+ 'consume' => $canConsume,
+ ],
+ ],
];
}
- $consumableCount = $consumable->users->count();
- $data = ['total' => $consumableCount, 'rows' => $rows];
-
- return $data;
+ return ['total' => count($rows), 'rows' => $rows];
}
/**
@@ -508,6 +617,7 @@ class ConsumablesController extends Controller
{
$query = Consumable::with('category', 'location', 'company', 'manufacturer', 'requests')
->withCount('users as consumables_users_count')
+ ->withCount('outstandingAssignments as outstanding_assignments_count')
->Requestable();
if ($request->filled('search')) {
@@ -525,4 +635,266 @@ class ConsumablesController extends Controller
return (new ConsumablesTransformer)->transformRequestedConsumables($rows, $total);
}
+
+ /**
+ * Mark one pivot row consumed. API parity for the web
+ * ConsumableCheckoutController::consume endpoint. One-way: an
+ * already-consumed row no-ops.
+ */
+ public function consume(Consumable $consumable, ConsumableAssignment $assignment): JsonResponse
+ {
+ $this->authorize('checkout', $consumable);
+
+ if ($assignment->consumable_id !== $consumable->id) {
+ return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/consumables/message.does_not_exist')), 404);
+ }
+
+ if ($assignment->isConsumed()) {
+ return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/consumables/message.consumed.already')));
+ }
+
+ $assignment->consumed_at = now();
+ if (! $assignment->save()) {
+ return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/consumables/message.consumed.error')), 422);
+ }
+
+ $this->writeConsumeLog($consumable, $assignment);
+
+ return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/consumables/message.consumed.success')));
+ }
+
+ /**
+ * Bulk mark pivot rows consumed. Mixed-parent submissions are
+ * rejected because the show-page flow guarantees a single parent
+ * and the API honors that invariant too.
+ */
+ public function bulkConsume(Request $request): JsonResponse
+ {
+ $pivotIds = (array) $request->input('ids', []);
+ if ($pivotIds === []) {
+ return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/consumables/message.consumed.no_rows_selected')), 422);
+ }
+
+ $assignments = ConsumableAssignment::with('consumable')
+ ->whereIn('id', $pivotIds)
+ ->whereNull('consumed_at')
+ ->get();
+
+ if ($assignments->isEmpty()) {
+ return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/consumables/message.consumed.no_rows_selected')), 422);
+ }
+
+ $consumableIds = $assignments->pluck('consumable_id')->unique();
+ if ($consumableIds->count() !== 1) {
+ return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/consumables/message.consumed.no_rows_selected')), 422);
+ }
+
+ $consumable = $assignments->first()->consumable;
+ $this->authorize('checkout', $consumable);
+
+ $now = now();
+ $consumed = 0;
+ foreach ($assignments as $assignment) {
+ $assignment->consumed_at = $now;
+ if ($assignment->save()) {
+ $consumed++;
+ $this->writeConsumeLog($consumable, $assignment);
+ }
+ }
+
+ return response()->json(Helper::formatStandardApiResponse(
+ 'success',
+ ['consumed' => $consumed],
+ trans_choice('admin/consumables/message.consumed.bulk_success', $consumed, ['count' => $consumed]),
+ ));
+ }
+
+ /**
+ * Bulk edit. Mirror of BulkConsumablesController::update.
+ * Returns JSON instead of a flash redirect, otherwise identical
+ * semantics: writes only non-blank fields, routes company_id
+ * through FMCS, supports null_{field}=1 opt-in null-outs, per-row
+ * Gate check, surfaces partial-success detail in the payload.
+ */
+ public function bulkEdit(Request $request): JsonResponse
+ {
+ $this->authorize('update', Consumable::class);
+
+ if (! $request->filled('ids')) {
+ return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/consumables/message.bulk.no_consumables_selected')), 422);
+ }
+
+ $consumables = Consumable::whereIn('id', $request->input('ids'))->get();
+ if ($consumables->isEmpty()) {
+ return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/consumables/message.bulk.no_consumables_selected')), 422);
+ }
+
+ $updateData = [];
+ foreach (BulkConsumablesController::EDITABLE_FIELDS as $field) {
+ if (! $request->has($field)) {
+ continue;
+ }
+ $value = $request->input($field);
+ if ($value === '' || $value === null) {
+ continue;
+ }
+ $updateData[$field] = $value;
+ }
+
+ if (array_key_exists('company_id', $updateData)) {
+ try {
+ $updateData['company_id'] = Company::getIdForCurrentUser($updateData['company_id']);
+ } catch (ValidationException $e) {
+ return response()->json(Helper::formatStandardApiResponse('error', null, $e->errors()), 422);
+ }
+ }
+
+ foreach (['category_id', 'company_id', 'manufacturer_id', 'location_id', 'default_supplier_id', 'min_amt'] as $field) {
+ if ($request->boolean('null_'.$field)) {
+ if ($field === 'category_id') {
+ continue;
+ }
+ $updateData[$field] = null;
+ }
+ }
+
+ if (empty($updateData)) {
+ return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/consumables/message.bulk.no_fields_updated')), 422);
+ }
+
+ $authorized = $consumables->filter(fn (Consumable $c) => Gate::allows('update', $c));
+ $skipped = $consumables->count() - $authorized->count();
+
+ $updated = 0;
+ $failed_rows = [];
+ foreach ($authorized as $consumable) {
+ $consumable->fill($updateData);
+ if ($consumable->save()) {
+ $updated++;
+
+ continue;
+ }
+ $failed_rows[] = $consumable->name.': '.$consumable->getErrors()->first();
+ }
+
+ $failed = count($failed_rows);
+ $payload = ['updated' => $updated, 'skipped_unauthorized' => $skipped, 'failed_rows' => $failed_rows];
+
+ if ($updated === 0 && $failed > 0) {
+ return response()->json(Helper::formatStandardApiResponse(
+ 'error',
+ $payload,
+ trans_choice('admin/consumables/message.bulk.update.none_updated', $failed, ['count' => $failed]),
+ ), 422);
+ }
+
+ return response()->json(Helper::formatStandardApiResponse(
+ 'success',
+ $payload,
+ trans_choice('admin/consumables/message.bulk.update.success', $updated, ['count' => $updated]),
+ ));
+ }
+
+ /**
+ * Bulk soft-delete. Per-row isDeletable + Gate check mirror the
+ * web controller.
+ */
+ public function bulkDestroy(Request $request): JsonResponse
+ {
+ $this->authorize('delete', Consumable::class);
+
+ $errors = [];
+ $success_count = 0;
+
+ foreach ((array) $request->input('ids', []) as $id) {
+ $consumable = Consumable::find($id);
+ if (is_null($consumable)) {
+ $errors[] = trans('admin/consumables/message.does_not_exist', ['id' => $id]);
+
+ continue;
+ }
+
+ if (! Gate::allows('delete', $consumable)) {
+ $errors[] = trans('general.unauthorized');
+
+ continue;
+ }
+
+ $consumable->loadCount('outstandingAssignments as outstanding_assignments_count');
+ if (! $consumable->isDeletable()) {
+ $errors[] = trans('general.bulk_delete_associations.assoc_checkouts_no_count', [
+ 'item_name' => $consumable->name,
+ 'item' => trans('general.consumable'),
+ ]);
+
+ continue;
+ }
+
+ $consumable->delete();
+ $success_count++;
+ }
+
+ $payload = ['deleted' => $success_count, 'errors' => $errors];
+ $message = $success_count > 0
+ ? trans_choice('admin/consumables/message.delete.bulk_success', $success_count, ['count' => $success_count])
+ : trans('admin/consumables/message.bulk.no_consumables_selected');
+
+ return response()->json(
+ Helper::formatStandardApiResponse($success_count > 0 ? 'success' : 'error', $payload, $message),
+ $success_count > 0 ? 200 : 422,
+ );
+ }
+
+ /**
+ * Bulk restore. Already-live rows are skipped without erroring so
+ * a stale selection doesn't blow up the whole batch.
+ */
+ public function bulkRestore(Request $request): JsonResponse
+ {
+ $this->authorize('delete', Consumable::class);
+
+ $ids = (array) $request->input('ids', []);
+ if ($ids === []) {
+ return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/consumables/message.bulk.no_consumables_selected')), 422);
+ }
+
+ $consumables = Consumable::withTrashed()->whereIn('id', $ids)->get();
+
+ $restored = 0;
+ $errors = [];
+
+ foreach ($consumables as $consumable) {
+ if (! Gate::allows('delete', $consumable)) {
+ $errors[] = trans('general.unauthorized');
+
+ continue;
+ }
+
+ if ($consumable->deleted_at === null) {
+ continue;
+ }
+
+ if ($consumable->restore()) {
+ $restored++;
+ }
+ }
+
+ return response()->json(Helper::formatStandardApiResponse(
+ $restored > 0 ? 'success' : 'error',
+ ['restored' => $restored, 'errors' => $errors],
+ trans_choice('admin/consumables/message.bulk.restore.success', $restored, ['count' => $restored]),
+ ), $restored > 0 ? 200 : 422);
+ }
+
+ private function writeConsumeLog(Consumable $consumable, ConsumableAssignment $assignment): void
+ {
+ $log = new Actionlog;
+ $log->item_type = Consumable::class;
+ $log->item_id = $consumable->id;
+ $log->target_type = User::class;
+ $log->target_id = $assignment->assigned_to;
+ $log->created_at = date('Y-m-d H:i:s');
+ $log->created_by = auth()->id();
+ $log->logaction('consumed');
+ }
}
diff --git a/app/Http/Controllers/Consumables/BulkConsumablesController.php b/app/Http/Controllers/Consumables/BulkConsumablesController.php
new file mode 100644
index 0000000000..a28ed9d078
--- /dev/null
+++ b/app/Http/Controllers/Consumables/BulkConsumablesController.php
@@ -0,0 +1,310 @@
+<?php
+
+namespace App\Http\Controllers\Consumables;
+
+use App\Http\Controllers\Controller;
+use App\Models\Company;
+use App\Models\Consumable;
+use Illuminate\Contracts\View\View;
+use Illuminate\Http\RedirectResponse;
+use Illuminate\Http\Request;
+use Illuminate\Support\Facades\Gate;
+use Illuminate\Validation\ValidationException;
+
+class BulkConsumablesController extends Controller
+{
+ /**
+ * Fields admins may bulk-write across the selected rows. Mirrors
+ * BulkComponentsController::EDITABLE_FIELDS. qty / supplier_id /
+ * purchase_date / purchase_cost are quantity-adjustment territory
+ * and stay out of bulk edit.
+ *
+ * @var array<int, string>
+ */
+ public const EDITABLE_FIELDS = [
+ 'category_id',
+ 'company_id',
+ 'manufacturer_id',
+ 'location_id',
+ 'default_supplier_id',
+ 'min_amt',
+ 'requestable',
+ 'archived',
+ ];
+
+ /**
+ * Dispatcher. The index POSTs here with ids[] + bulk_actions, and
+ * we route to the edit-form view, the delete-confirm view, or
+ * the restore handler.
+ */
+ public function edit(Request $request): View|RedirectResponse
+ {
+ $this->authorize('view', Consumable::class);
+
+ if (! $request->filled('ids')) {
+ return redirect()->route('consumables.index')
+ ->with('error', trans('admin/consumables/message.bulk.no_consumables_selected'));
+ }
+
+ // Restore acts on soft-deleted rows, so widen the lookup with
+ // withTrashed for that branch only.
+ $query = Consumable::whereIn('id', $request->input('ids'));
+ if ($request->input('bulk_actions') === 'restore') {
+ $query->withTrashed();
+ }
+ $consumables = $query->get();
+
+ if ($consumables->isEmpty()) {
+ return redirect()->route('consumables.index')
+ ->with('error', trans('admin/consumables/message.bulk.no_consumables_selected'));
+ }
+
+ return match ($request->input('bulk_actions')) {
+ 'edit' => $this->showEdit($consumables),
+ 'delete' => $this->showDelete($consumables),
+ 'restore' => $this->doRestore($consumables),
+ default => redirect()->route('consumables.index')
+ ->with('error', trans('admin/consumables/message.bulk.no_action_selected')),
+ };
+ }
+
+ /**
+ * Apply the bulk-edit form. Each editable field is written only
+ * when the admin provided a value (empty fields are left alone),
+ * so admins can tweak just the fields they care about without
+ * flattening everything else to blank.
+ */
+ public function update(Request $request): RedirectResponse
+ {
+ $this->authorize('update', Consumable::class);
+
+ if (! $request->filled('ids')) {
+ return redirect()->route('consumables.index')
+ ->with('error', trans('admin/consumables/message.bulk.no_consumables_selected'));
+ }
+
+ $consumables = Consumable::whereIn('id', $request->input('ids'))->get();
+
+ if ($consumables->isEmpty()) {
+ return redirect()->route('consumables.index')
+ ->with('error', trans('admin/consumables/message.bulk.no_consumables_selected'));
+ }
+
+ $updateData = [];
+ foreach (self::EDITABLE_FIELDS as $field) {
+ if (! $request->has($field)) {
+ continue;
+ }
+
+ $value = $request->input($field);
+
+ // Treat blank selects / cleared text inputs as "don't touch".
+ if ($value === '' || $value === null) {
+ continue;
+ }
+
+ $updateData[$field] = $value;
+ }
+
+ // Route company_id through getIdForCurrentUser so a non-superuser
+ // can't hand-craft a POST that writes a cross-tenant company_id
+ // across the selection. Matches BulkComponentsController's shape.
+ if (array_key_exists('company_id', $updateData)) {
+ try {
+ $updateData['company_id'] = Company::getIdForCurrentUser($updateData['company_id']);
+ } catch (ValidationException $e) {
+ return redirect()->route('consumables.index')
+ ->withErrors($e->errors())
+ ->with('error', trans('general.unauthorized'));
+ }
+ }
+
+ // Opt-in null-outs via null_{field}=1 checkboxes.
+ foreach (['category_id', 'company_id', 'manufacturer_id', 'location_id', 'default_supplier_id', 'min_amt'] as $field) {
+ if ($request->boolean('null_'.$field)) {
+ if ($field === 'category_id') {
+ continue;
+ }
+ $updateData[$field] = null;
+ }
+ }
+
+ if (empty($updateData)) {
+ return redirect()->route('consumables.index')
+ ->with('warning', trans('admin/consumables/message.bulk.no_fields_updated'));
+ }
+
+ $authorized = $consumables->filter(fn (Consumable $c) => Gate::allows('update', $c));
+ $skipped = $consumables->count() - $authorized->count();
+
+ $updated = 0;
+ $failed_rows = [];
+ foreach ($authorized as $consumable) {
+ $consumable->fill($updateData);
+ if ($consumable->save()) {
+ $updated++;
+
+ continue;
+ }
+ $failed_rows[] = $consumable->name.': '.$consumable->getErrors()->first();
+ }
+
+ $failed = count($failed_rows);
+ $redirect = redirect()->route('consumables.index');
+
+ if ($failed > 0) {
+ $redirect->with('multi_error_messages', $failed_rows);
+ }
+
+ // All target rows rejected by validation. Don't dress a zero-row
+ // update up as a success - the model errors tell the real story.
+ if ($updated === 0 && $failed > 0) {
+ return $redirect->with('error', trans_choice(
+ 'admin/consumables/message.bulk.update.none_updated',
+ $failed,
+ ['count' => $failed]
+ ));
+ }
+
+ $message = trans_choice('admin/consumables/message.bulk.update.success', $updated, ['count' => $updated]);
+
+ if ($skipped > 0) {
+ $message .= ' '.trans('admin/consumables/message.bulk.skipped_unauthorized', ['count' => $skipped]);
+ }
+
+ return $failed > 0
+ ? $redirect->with('warning', $message)
+ : $redirect->with('success', $message);
+ }
+
+ public function destroy(Request $request)
+ {
+ $this->authorize('delete', Consumable::class);
+
+ $errors = [];
+ $success_count = 0;
+
+ foreach ((array) $request->input('ids', []) as $id) {
+ // Consumable uses CompanyableTrait, so Consumable::find() is
+ // filtered by CompanyableScope. Cross-company rows return
+ // null and fall into the "does_not_exist" bucket without
+ // ever reaching authorization.
+ $consumable = Consumable::find($id);
+ if (is_null($consumable)) {
+ $errors[] = trans('admin/consumables/message.does_not_exist', ['id' => $id]);
+
+ continue;
+ }
+
+ // Per-row auth as belt-and-braces on top of the query scope.
+ // Catches FMCS mismatches that a superuser scope-bypass could
+ // let through, plus any future policy tightening (e.g. per-role
+ // company-based delete gating).
+ if (! Gate::allows('delete', $consumable)) {
+ $errors[] = trans('general.unauthorized');
+
+ continue;
+ }
+
+ $consumable->loadCount('outstandingAssignments as outstanding_assignments_count');
+ if (! $consumable->isDeletable()) {
+ $errors[] = trans('general.bulk_delete_associations.assoc_checkouts_no_count', [
+ 'item_name' => $consumable->name,
+ 'item' => trans('general.consumable'),
+ ]);
+
+ continue;
+ }
+
+ // Note: the image file is deliberately preserved across this
+ // soft-delete. Snipe-IT's `snipeit:purge` command permanently
+ // removes it later when the row is force-deleted. Keeping
+ // the file here means a restored soft-deleted row still has
+ // its image.
+ $consumable->delete();
+ $success_count++;
+ }
+
+ if (count($errors) > 0) {
+ if ($success_count > 0) {
+ return redirect()->route('consumables.index')
+ ->with('success', trans_choice('admin/consumables/message.delete.partial_success', $success_count, ['count' => $success_count]))
+ ->with('multi_error_messages', $errors);
+ }
+
+ return redirect()->route('consumables.index')->with('multi_error_messages', $errors);
+ }
+
+ return redirect()->route('consumables.index')
+ ->with('success', trans_choice('admin/consumables/message.delete.bulk_success', $success_count, ['count' => $success_count]));
+ }
+
+ protected function showEdit($consumables): View
+ {
+ $this->authorize('update', Consumable::class);
+
+ return view('consumables.bulk-edit', [
+ 'consumables' => $consumables,
+ 'ids' => $consumables->pluck('id')->all(),
+ ]);
+ }
+
+ protected function showDelete($consumables): View
+ {
+ $this->authorize('delete', Consumable::class);
+
+ // Load outstanding_assignments_count so the view's isDeletable()
+ // check can distinguish "no outstanding units, safe to delete"
+ // from "has unconsumed distributions, show X instead of a
+ // checkbox." Without this, isDeletable() falls back to a
+ // per-row count query.
+ $consumables->loadCount('outstandingAssignments as outstanding_assignments_count');
+
+ return view('consumables.bulk-delete', [
+ 'consumables' => $consumables,
+ 'ids' => $consumables->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).
+ */
+ protected function doRestore($consumables): RedirectResponse
+ {
+ $this->authorize('delete', Consumable::class);
+
+ $restored = 0;
+ $errors = [];
+
+ foreach ($consumables as $consumable) {
+ if (! Gate::allows('delete', $consumable)) {
+ $errors[] = trans('general.unauthorized');
+
+ continue;
+ }
+
+ if ($consumable->deleted_at === null) {
+ // Already live. Skip silently.
+ continue;
+ }
+
+ if ($consumable->restore()) {
+ $restored++;
+ }
+ }
+
+ $redirect = redirect()->route('consumables.index', ['status' => 'Deleted']);
+
+ if (count($errors) > 0 && $restored === 0) {
+ return $redirect->with('multi_error_messages', $errors);
+ }
+
+ return $redirect
+ ->with('success', trans_choice('admin/consumables/message.bulk.restore.success', $restored, ['count' => $restored]))
+ ->with('multi_error_messages', $errors ?: null);
+ }
+}
diff --git a/app/Http/Controllers/Consumables/ConsumableCheckoutController.php b/app/Http/Controllers/Consumables/ConsumableCheckoutController.php
index f75ca89870..625de6ccab 100644
--- a/app/Http/Controllers/Consumables/ConsumableCheckoutController.php
+++ b/app/Http/Controllers/Consumables/ConsumableCheckoutController.php
@@ -6,9 +6,11 @@ use App\Actions\Acceptances\CreateCheckoutAcceptanceAction;
use App\Events\CheckoutableCheckedOut;
use App\Helpers\Helper;
use App\Http\Controllers\Controller;
+use App\Models\Actionlog;
use App\Models\CheckoutAcceptance;
use App\Models\CheckoutRequest;
use App\Models\Consumable;
+use App\Models\ConsumableAssignment;
use App\Models\User;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Contracts\View\View;
@@ -375,4 +377,134 @@ class ConsumableCheckoutController extends Controller
->with($fulfilled > 0 ? 'success' : 'warning', $summary)
->with('multi_error_messages', $errors);
}
+
+ /**
+ * Mark a single consumable_users pivot row as consumed. One-way:
+ * once set, consumed_at never clears, so an already-consumed row
+ * no-op redirects. Gated on consumables.checkout per the design
+ * decision to let the same permission that distributes units also
+ * close them out. Writes an audit-log entry so the lifecycle shows
+ * up in the item's history tab.
+ */
+ public function consume(Consumable $consumable, ConsumableAssignment $assignment): RedirectResponse
+ {
+ $this->authorize('checkout', $consumable);
+
+ if ($assignment->consumable_id !== $consumable->id) {
+ abort(404);
+ }
+
+ if ($assignment->isConsumed()) {
+ return redirect()->route('consumables.show', $consumable)
+ ->with('warning', trans('admin/consumables/message.consumed.already'));
+ }
+
+ $assignment->consumed_at = now();
+ if (! $assignment->save()) {
+ return redirect()->route('consumables.show', $consumable)
+ ->with('error', trans('admin/consumables/message.consumed.error'));
+ }
+
+ $this->writeConsumeLog($consumable, $assignment);
+
+ return redirect()->route('consumables.show', $consumable)
+ ->with('success', trans('admin/consumables/message.consumed.success'));
+ }
+
+ /**
+ * Confirmation view for marking several pivot rows consumed at
+ * once. The POST comes from the bootstrap-table bulk-actions
+ * dropdown on the consumable show page's assigned tab. Already-
+ * consumed rows and cross-consumable rows are filtered out here
+ * so the confirmation page only lists valid targets.
+ */
+ public function bulkConsumeShow(Request $request): View|RedirectResponse
+ {
+ $pivotIds = (array) $request->input('ids', []);
+ if ($pivotIds === []) {
+ return redirect()->back()
+ ->with('error', trans('admin/consumables/message.consumed.no_rows_selected'));
+ }
+
+ $assignments = ConsumableAssignment::with('consumable', 'user')
+ ->whereIn('id', $pivotIds)
+ ->whereNull('consumed_at')
+ ->get();
+
+ if ($assignments->isEmpty()) {
+ return redirect()->back()
+ ->with('error', trans('admin/consumables/message.consumed.no_rows_selected'));
+ }
+
+ // Every row has to belong to the same parent consumable since
+ // this flow runs off the show page's assigned tab. Mixed-parent
+ // submissions are a sign the UI was tampered with, so bail.
+ $consumableIds = $assignments->pluck('consumable_id')->unique();
+ if ($consumableIds->count() !== 1) {
+ return redirect()->back()
+ ->with('error', trans('admin/consumables/message.consumed.no_rows_selected'));
+ }
+
+ $consumable = $assignments->first()->consumable;
+ $this->authorize('checkout', $consumable);
+
+ return view('consumables.bulk-consume', [
+ 'consumable' => $consumable,
+ 'assignments' => $assignments,
+ 'ids' => $assignments->pluck('id')->all(),
+ ]);
+ }
+
+ public function bulkConsumeStore(Request $request): RedirectResponse
+ {
+ $pivotIds = (array) $request->input('ids', []);
+ if ($pivotIds === []) {
+ return redirect()->route('consumables.index')
+ ->with('error', trans('admin/consumables/message.consumed.no_rows_selected'));
+ }
+
+ $assignments = ConsumableAssignment::with('consumable')
+ ->whereIn('id', $pivotIds)
+ ->whereNull('consumed_at')
+ ->get();
+
+ if ($assignments->isEmpty()) {
+ return redirect()->route('consumables.index')
+ ->with('error', trans('admin/consumables/message.consumed.no_rows_selected'));
+ }
+
+ $consumableIds = $assignments->pluck('consumable_id')->unique();
+ if ($consumableIds->count() !== 1) {
+ return redirect()->route('consumables.index')
+ ->with('error', trans('admin/consumables/message.consumed.no_rows_selected'));
+ }
+
+ $consumable = $assignments->first()->consumable;
+ $this->authorize('checkout', $consumable);
+
+ $now = now();
+ $consumed = 0;
+ foreach ($assignments as $assignment) {
+ $assignment->consumed_at = $now;
+ if ($assignment->save()) {
+ $consumed++;
+ $this->writeConsumeLog($consumable, $assignment);
+ }
+ }
+
+ return redirect()->route('consumables.show', $consumable)
+ ->with('success', trans_choice('admin/consumables/message.consumed.bulk_success', $consumed, ['count' => $consumed]));
+ }
+
+ private function writeConsumeLog(Consumable $consumable, ConsumableAssignment $assignment): void
+ {
+ $log = new Actionlog;
+ $log->item_type = Consumable::class;
+ $log->item_id = $consumable->id;
+ $log->target_type = User::class;
+ $log->target_id = $assignment->assigned_to;
+ $log->created_at = date('Y-m-d H:i:s');
+ $log->created_by = auth()->id();
+ $log->logaction('consumed');
+ }
}
diff --git a/app/Http/Controllers/Consumables/ConsumablesController.php b/app/Http/Controllers/Consumables/ConsumablesController.php
index d7691a8ce0..08012bc540 100644
--- a/app/Http/Controllers/Consumables/ConsumablesController.php
+++ b/app/Http/Controllers/Consumables/ConsumablesController.php
@@ -61,7 +61,8 @@ class ConsumablesController extends Controller
$this->authorize('create', Consumable::class);
return view('consumables.edit')->with('category_type', 'consumable')
- ->with('item', new Consumable);
+ ->with('item', new Consumable)
+ ->with('pendingRequestCount', 0);
}
/**
@@ -98,8 +99,9 @@ class ConsumablesController extends Controller
// absence to false so the flag really flips off. The setter
// normalizes the truthy branch.
$consumable->requestable = $request->input('requestable', false);
+ $consumable->archived = $request->input('archived', 0);
// Seed the template supplier from the initial-acquisition
- // supplier on the create form; editable afterwards.
+ // supplier on the create form, editable afterwards.
$consumable->default_supplier_id = $request->input('default_supplier_id', $request->input('supplier_id'));
if ($request->has('use_cloned_image')) {
@@ -148,7 +150,8 @@ class ConsumablesController extends Controller
return view('consumables/edit')
->with('item', $consumable)
- ->with('category_type', 'consumable');
+ ->with('category_type', 'consumable')
+ ->with('pendingRequestCount', $consumable->openRequests()->count());
}
@@ -188,9 +191,10 @@ class ConsumablesController extends Controller
// controller for the parent-as-template rationale.
$consumable->default_supplier_id = $request->input('default_supplier_id');
$consumable->notes = $request->input('notes');
- // Unchecked checkbox is omitted from the POST body; coerce
+ // Unchecked checkbox is omitted from the POST body. Coerce
// absence to false so unchecking really turns the flag off.
$consumable->requestable = $request->input('requestable', false);
+ $consumable->archived = $request->input('archived', 0);
$consumable = $request->handleImages($consumable);
@@ -230,6 +234,55 @@ class ConsumablesController extends Controller
return redirect()->route('consumables.index')->with('success', trans('admin/consumables/message.delete.success'));
}
+ /**
+ * Restore a soft-deleted consumable. Mirrors AccessoriesController::postRestore
+ * (restoring is a delete-tier action across the project).
+ */
+ public function postRestore($id): RedirectResponse
+ {
+ if ($consumable = Consumable::withTrashed()->find($id)) {
+ // Per-instance authorize so the policy's before() hook runs
+ // its FMCS isCurrentUserHasAccess check against the actual
+ // row, not just the class.
+ $this->authorize('delete', $consumable);
+
+ if ($consumable->deleted_at == '') {
+ return redirect()->back()->with('error', trans('general.not_deleted', ['item_type' => trans('general.consumable')]));
+ }
+
+ if ($consumable->restore()) {
+ return redirect()->route('consumables.show', $consumable)
+ ->with('success', trans('admin/consumables/message.restore.success'));
+ }
+
+ return redirect()->back()->with('error', trans('general.could_not_restore', ['item_type' => trans('general.consumable'), 'error' => $consumable->getErrors()->first()]));
+ }
+
+ return redirect()->route('consumables.index')->with('error', trans('admin/consumables/message.does_not_exist'));
+ }
+
+ /**
+ * Flip a consumable back to live inventory. Mirrors postRestore's
+ * auth shape so unarchiving goes through the same per-instance
+ * authorize path as restore from soft-delete.
+ */
+ public function postUnarchive(Consumable $consumable): RedirectResponse
+ {
+ $this->authorize('update', $consumable);
+
+ if (! $consumable->archived) {
+ return redirect()->back()->with('error', trans('admin/consumables/message.does_not_exist'));
+ }
+
+ $consumable->archived = false;
+
+ if ($consumable->save()) {
+ return redirect()->back()->with('success', trans('general.unarchive_success', ['item_type' => trans('general.consumable')]));
+ }
+
+ return redirect()->back()->withErrors($consumable->getErrors());
+ }
+
/**
* Return a view to display component information.
*
@@ -244,7 +297,13 @@ class ConsumablesController extends Controller
*/
public function show(Consumable $consumable)
{
- $consumable = Consumable::withCount('users as users_consumables')->find($consumable->id);
+ // Route-model binding resolves soft-deleted rows via
+ // withTrashed(['show']) on the resource route, so re-fetch
+ // with withTrashed() as well. Without it the show page 404s
+ // for admins following a link from the Deleted index view.
+ $consumable = Consumable::withTrashed()
+ ->withCount('users as users_consumables')
+ ->find($consumable->id);
$this->authorize($consumable);
return view('consumables/view', compact('consumable'));
@@ -268,7 +327,8 @@ class ConsumablesController extends Controller
return view('consumables/edit')
->with('cloned_model', $consumable_to_close)
- ->with('item', $consumable);
+ ->with('item', $consumable)
+ ->with('pendingRequestCount', 0);
}
/**