Skip to content

A free open source IT asset/license management system

Omg codacy

snipec8ba9f049b94
diff --git a/app/Http/Controllers/Api/UnacceptedAcceptancesController.php b/app/Http/Controllers/Api/UnacceptedAcceptancesController.php
index f88784540e..efdc9df0ce 100644
--- a/app/Http/Controllers/Api/UnacceptedAcceptancesController.php
+++ b/app/Http/Controllers/Api/UnacceptedAcceptancesController.php
@@ -6,29 +6,18 @@ use App\Console\Commands\SendAcceptanceReminder;
use App\Helpers\Helper;
use App\Http\Controllers\Controller;
use App\Http\Transformers\AcceptancesTransformer;
-use App\Models\Accessory;
-use App\Models\Asset;
use App\Models\CheckoutAcceptance;
-use App\Models\Component;
-use App\Models\Consumable;
-use App\Models\License;
-use App\Models\LicenseSeat;
use App\Notifications\UnacceptedAssetReminderNotification;
-use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
-use Illuminate\Support\Facades\Gate;
/**
* JSON endpoint powering /unaccepted-acceptances (via
* UnacceptedAcceptancesController's Blade view).
*
- * Scoping is DB-level, not post-hoc: whereHasMorph narrows to the
- * checkoutable types the caller can view AND lets each type's own
- * CompanyableScope / CompanyableChildScope apply its FMCS + location
- * filtering during the join. The paginated count and the page rows
- * reflect the same viewer-permissioned set, so no cross-company
- * totals leak via `total`.
+ * Query scoping, morph eager-loading, and the per-row FMCS filter
+ * live on CheckoutAcceptanceQueryBuilder::visibleToCurrentUser so
+ * the controller stays thin and the scoping decisions have one home.
*/
class UnacceptedAcceptancesController extends Controller
{
@@ -36,32 +25,8 @@ class UnacceptedAcceptancesController extends Controller
{
$this->authorize('canCheckoutAtLeastOneItemType');
- // Pre-filter the morph types to just those this caller can
- // view. Types they can't view are excluded from the query
- // entirely, preventing even a type-shape leak.
- $viewableTypes = array_filter(
- [Asset::class, LicenseSeat::class, Accessory::class, Component::class, Consumable::class],
- fn (string $type) => Gate::allows('view', $type === LicenseSeat::class ? License::class : $type),
- );
-
- if ($viewableTypes === []) {
- return (new AcceptancesTransformer)->transformAcceptances(collect(), 0);
- }
-
$query = CheckoutAcceptance::pending()
- ->with([
- 'checkoutable' => function (MorphTo $morphTo) {
- $morphTo->withTrashed()->morphWith([
- Asset::class => ['model.category', 'assignedTo', 'company'],
- Accessory::class => ['category', 'checkouts', 'company'],
- LicenseSeat::class => ['user', 'license.company', 'license.category'],
- Component::class => ['assignedTo', 'category', 'company'],
- Consumable::class => ['category', 'company'],
- ]);
- },
- 'assignedTo' => fn ($q) => $q->withTrashed(),
- ])
- ->whereHasMorph('checkoutable', $viewableTypes)
+ ->visibleToCurrentUser()
->orderByDesc('checkout_acceptances.created_at');
if ($request->boolean('deleted')) {
@@ -90,7 +55,9 @@ class UnacceptedAcceptancesController extends Controller
/**
* Send reminder emails to users with unaccepted items. No `ids`
* supplied: delegates to snipeit:acceptance-reminder so the
- * send-all shape is identical to the console command
+ * send-all shape is identical to the console command. With ids:
+ * routes through UnacceptedAssetReminderNotification::dispatchForAcceptanceIds
+ * which dedupes by assignee and surfaces a skip tally.
*/
public function sendReminders(Request $request): JsonResponse
{
@@ -117,55 +84,17 @@ class UnacceptedAcceptancesController extends Controller
);
}
- $acceptancesByAssignee = CheckoutAcceptance::pending()
- ->whereIn('id', $ids)
- ->with(['assignedTo' => fn ($q) => $q->withTrashed()])
- ->get()
- ->filter(fn (CheckoutAcceptance $a) => $a->assignedTo && $a->isAccessibleToCurrentUser())
- ->groupBy(fn (CheckoutAcceptance $a) => $a->assignedTo->id);
-
- $sent = 0;
- $skipped = [
- 'no_email' => 0,
- 'none_pending' => 0,
- ];
- // Any id in the request that didn't survive the pending +
- // FMCS filter above falls out as not_found. Tracked here so
- // the response can tell the caller how many of their ids
- // never reached the dispatch loop.
- $notFound = count($ids) - $acceptancesByAssignee->sum(fn ($g) => $g->count());
-
- foreach ($acceptancesByAssignee as $group) {
- /** @var CheckoutAcceptance $first */
- $first = $group->first();
- $assignee = $first->assignedTo;
-
- if (empty($assignee->email) || $assignee->activated == '0') {
- $skipped['no_email']++;
-
- continue;
- }
-
- $pending = $assignee->getAssignedItemsWithPendingAcceptance();
- if ($pending->isEmpty()) {
- $skipped['none_pending']++;
-
- continue;
- }
-
- $assignee->notify(new UnacceptedAssetReminderNotification($first, $pending->count()));
- $sent++;
- }
+ $result = UnacceptedAssetReminderNotification::dispatchForAcceptanceIds($ids);
return response()->json(
Helper::formatStandardApiResponse(
'success',
[
'mode' => 'ids',
- 'sent' => $sent,
- 'skipped' => $skipped + ['not_found_or_fmcs' => max(0, $notFound)],
+ 'sent' => $result['sent'],
+ 'skipped' => $result['skipped'],
],
- trans_choice('admin/reports/general.reminder_sent_count', $sent, ['count' => $sent]),
+ trans_choice('admin/reports/general.reminder_sent_count', $result['sent'], ['count' => $result['sent']]),
),
);
}
diff --git a/app/Http/Transformers/AcceptancesTransformer.php b/app/Http/Transformers/AcceptancesTransformer.php
index b055612f4f..57b3c3d9bb 100644
--- a/app/Http/Transformers/AcceptancesTransformer.php
+++ b/app/Http/Transformers/AcceptancesTransformer.php
@@ -153,13 +153,11 @@ class AcceptancesTransformer
*/
private static function resolveCategory($item): ?array
{
- if ($item instanceof Asset) {
- $category = $item->model?->category;
- } elseif ($item instanceof LicenseSeat) {
- $category = $item->license?->category;
- } else {
- $category = $item->category ?? null;
- }
+ $category = match (true) {
+ $item instanceof Asset => $item->model?->category,
+ $item instanceof LicenseSeat => $item->license?->category,
+ default => $item->category ?? null,
+ };
return $category ? [
'id' => (int) $category->id,
diff --git a/app/Models/Builders/CheckoutAcceptanceQueryBuilder.php b/app/Models/Builders/CheckoutAcceptanceQueryBuilder.php
index 00147aec3b..f0fedbf6ed 100644
--- a/app/Models/Builders/CheckoutAcceptanceQueryBuilder.php
+++ b/app/Models/Builders/CheckoutAcceptanceQueryBuilder.php
@@ -2,9 +2,17 @@
namespace App\Models\Builders;
+use App\Models\Accessory;
+use App\Models\Asset;
use App\Models\CheckoutAcceptance;
+use App\Models\Component;
+use App\Models\Consumable;
+use App\Models\License;
+use App\Models\LicenseSeat;
use App\Models\User;
use Illuminate\Database\Eloquent\Builder;
+use Illuminate\Database\Eloquent\Relations\MorphTo;
+use Illuminate\Support\Facades\Gate;
/**
* @template TModel of CheckoutAcceptance
@@ -27,4 +35,49 @@ class CheckoutAcceptanceQueryBuilder extends Builder
{
return $this->whereNull('accepted_at')->whereNotNull('declined_at');
}
+
+ /**
+ * Narrows to acceptances whose checkoutable the current viewer
+ * can `view` AND can see per FMCS. Pre-filters the morph types
+ * so types the caller can't view are excluded from the query
+ * entirely (no type-shape leak), and whereHasMorph lets each
+ * concrete type apply its own CompanyableScope /
+ * CompanyableChildScope during the join. The whole page body
+ * reflects the viewer-permissioned set, including total count.
+ *
+ * Eager-loads enough of each checkoutable to render the
+ * acceptance list (model, category, company, assignee) without
+ * N+1-ing on the transformer.
+ */
+ public function visibleToCurrentUser(): self
+ {
+ $viewableTypes = array_filter(
+ [Asset::class, LicenseSeat::class, Accessory::class, Component::class, Consumable::class],
+ fn (string $type) => Gate::allows('view', $type === LicenseSeat::class ? License::class : $type),
+ );
+
+ if ($viewableTypes === []) {
+ // whereIn against an empty array produces an empty
+ // result without short-circuiting the builder chain,
+ // so downstream ->get() / ->orderBy() still work. Portable
+ // across MySQL / MariaDB / SQLite without the whereRaw
+ // escape hatch.
+ return $this->whereIn('id', []);
+ }
+
+ return $this
+ ->with([
+ 'checkoutable' => function (MorphTo $morphTo) {
+ $morphTo->withTrashed()->morphWith([
+ Asset::class => ['model.category', 'assignedTo', 'company'],
+ Accessory::class => ['category', 'checkouts', 'company'],
+ LicenseSeat::class => ['user', 'license.company', 'license.category'],
+ Component::class => ['assignedTo', 'category', 'company'],
+ Consumable::class => ['category', 'company'],
+ ]);
+ },
+ 'assignedTo' => fn ($q) => $q->withTrashed(),
+ ])
+ ->whereHasMorph('checkoutable', $viewableTypes);
+ }
}
diff --git a/app/Notifications/UnacceptedAssetReminderNotification.php b/app/Notifications/UnacceptedAssetReminderNotification.php
index 6320412fec..66b8a5ab12 100644
--- a/app/Notifications/UnacceptedAssetReminderNotification.php
+++ b/app/Notifications/UnacceptedAssetReminderNotification.php
@@ -47,4 +47,62 @@ class UnacceptedAssetReminderNotification extends Notification
'accept_url' => route('account.accept'),
]);
}
+
+ /**
+ * Shared dispatch loop for a set of acceptance ids. Dedupes by
+ * assignee (five selected acceptances for one user = one
+ * notification with count=5), skips assignees without an email
+ * or who've been deactivated, and surfaces a per-reason skip
+ * tally so the API response can show the admin what happened.
+ *
+ * @param array<int> $acceptanceIds
+ * @return array{sent: int, skipped: array<string, int>}
+ */
+ public static function dispatchForAcceptanceIds(array $acceptanceIds): array
+ {
+ $acceptancesByAssignee = CheckoutAcceptance::pending()
+ ->whereIn('id', $acceptanceIds)
+ ->with(['assignedTo' => fn ($q) => $q->withTrashed()])
+ ->get()
+ ->filter(fn (CheckoutAcceptance $a) => $a->assignedTo && $a->isAccessibleToCurrentUser())
+ ->groupBy(fn (CheckoutAcceptance $a) => $a->assignedTo->id);
+
+ $sent = 0;
+ $skipped = [
+ 'no_email' => 0,
+ 'none_pending' => 0,
+ // Any id in the request that didn't survive the pending
+ // + FMCS filter above falls out as not_found. Tracked
+ // here so the response can tell the caller how many of
+ // their ids never reached the dispatch loop.
+ 'not_found_or_fmcs' => max(0, count($acceptanceIds) - $acceptancesByAssignee->sum(fn ($g) => $g->count())),
+ ];
+
+ foreach ($acceptancesByAssignee as $group) {
+ /** @var CheckoutAcceptance $first */
+ $first = $group->first();
+ $assignee = $first->assignedTo;
+
+ if (empty($assignee->email) || $assignee->activated == '0') {
+ $skipped['no_email']++;
+
+ continue;
+ }
+
+ $pending = $assignee->getAssignedItemsWithPendingAcceptance();
+ if ($pending->isEmpty()) {
+ $skipped['none_pending']++;
+
+ continue;
+ }
+
+ $assignee->notify(new self($first, $pending->count()));
+ $sent++;
+ }
+
+ return [
+ 'sent' => $sent,
+ 'skipped' => $skipped,
+ ];
+ }
}
diff --git a/app/Presenters/CheckoutAcceptancePresenter.php b/app/Presenters/CheckoutAcceptancePresenter.php
index 0f3ea12058..cd06d58544 100644
--- a/app/Presenters/CheckoutAcceptancePresenter.php
+++ b/app/Presenters/CheckoutAcceptancePresenter.php
@@ -8,10 +8,12 @@ class CheckoutAcceptancePresenter extends Presenter
{
$showingDeleted = request('deleted') === 'deleted';
- $layout = [];
+ $columns = [];
+ // Pending-only view carries the bulk-select checkbox. Trashed
+ // rows have no bulk-eligible action so the column drops out.
if (! $showingDeleted) {
- $layout[] = [
+ $columns[] = [
'field' => 'checkbox',
'scope' => 'col',
'checkbox' => true,
@@ -22,116 +24,116 @@ class CheckoutAcceptancePresenter extends Presenter
];
}
- $layout = array_merge($layout, [
- [
- 'field' => 'created_at',
- 'scope' => 'col',
- 'searchable' => false,
- 'sortable' => true,
- 'title' => trans('general.date'),
- 'visible' => true,
- 'formatter' => 'dateDisplayFormatter',
- ], [
- 'field' => 'company.name',
- 'scope' => 'col',
- 'searchable' => true,
- 'sortable' => true,
- 'switchable' => true,
- 'visible' => true,
- 'title' => trans('general.company'),
- ], [
- 'field' => 'category.name',
- 'scope' => 'col',
- 'searchable' => true,
- 'sortable' => true,
- 'switchable' => true,
- 'visible' => true,
- 'title' => trans('general.category'),
- ], [
- 'field' => 'model.name',
- 'scope' => 'col',
- 'searchable' => true,
- 'sortable' => true,
- 'switchable' => true,
- 'visible' => true,
- 'title' => trans('admin/hardware/form.model'),
- ], [
- // The item being accepted. polymorphicItemFormatter
- // keys off item.type to pick the icon + destination
- // path, so this column renders consistently with the
- // activity report (same icon per morph type, same
- // deleted strikethrough, same viewable fallback).
- 'field' => 'item',
- 'scope' => 'col',
- 'searchable' => true,
- 'sortable' => true,
- 'title' => trans('general.name'),
- 'visible' => true,
- 'formatter' => 'polymorphicItemFormatter',
- ], [
- 'field' => 'asset_tag',
- 'scope' => 'col',
- 'searchable' => true,
- 'sortable' => true,
- 'switchable' => true,
- 'visible' => true,
- 'title' => trans('admin/hardware/table.asset_tag'),
- ], [
- // Assignee (always a user on checkout_acceptances).
- // Same shared formatter so the user icon + link come
- // for free.
- 'field' => 'target',
- 'scope' => 'col',
- 'searchable' => true,
- 'sortable' => false,
- 'title' => trans('admin/hardware/table.checkoutto'),
- 'visible' => true,
- 'formatter' => 'polymorphicItemFormatter',
- ], [
- // Admin who did the checkout, resolved via the matching
- // action_log row. Rendered through the shared formatter
- // so it reads the same way as every other user cell.
- 'field' => 'checked_out_by',
- 'scope' => 'col',
- 'searchable' => true,
- 'sortable' => false,
- 'switchable' => true,
- 'visible' => true,
- 'title' => trans('general.created_by'),
- 'formatter' => 'polymorphicItemFormatter',
- ],
- ]);
+ $columns[] = [
+ 'field' => 'created_at',
+ 'scope' => 'col',
+ 'searchable' => false,
+ 'sortable' => true,
+ 'title' => trans('general.date'),
+ 'visible' => true,
+ 'formatter' => 'dateDisplayFormatter',
+ ];
- // The pending-only view carries the Actions column (reminder /
- // delete) and omits deleted_at (always null). The deleted
- // view swaps those: nothing to do on a trashed row, but the
- // operator wants to see when it was deleted.
- if ($showingDeleted) {
- $layout[] = [
- 'field' => 'deleted_at',
- 'scope' => 'col',
- 'searchable' => false,
- 'sortable' => true,
- 'switchable' => true,
- 'visible' => true,
- 'title' => trans('general.deleted_at'),
- 'formatter' => 'dateDisplayFormatter',
- ];
- } else {
- $layout[] = [
- 'field' => 'actions',
- 'scope' => 'col',
- 'searchable' => false,
- 'sortable' => false,
- 'switchable' => false,
- 'title' => trans('button.actions'),
- 'visible' => true,
- 'formatter' => 'acceptanceActionsFormatter',
- 'printIgnore' => true,
- 'class' => 'hidden-print text-nowrap',
- ];
- }
+ $columns[] = [
+ 'field' => 'company.name',
+ 'scope' => 'col',
+ 'searchable' => true,
+ 'sortable' => true,
+ 'switchable' => true,
+ 'visible' => true,
+ 'title' => trans('general.company'),
+ ];
+
+ $columns[] = [
+ 'field' => 'category.name',
+ 'scope' => 'col',
+ 'searchable' => true,
+ 'sortable' => true,
+ 'switchable' => true,
+ 'visible' => true,
+ 'title' => trans('general.category'),
+ ];
+
+ $columns[] = [
+ 'field' => 'model.name',
+ 'scope' => 'col',
+ 'searchable' => true,
+ 'sortable' => true,
+ 'switchable' => true,
+ 'visible' => true,
+ 'title' => trans('admin/hardware/form.model'),
+ ];
+
+ // Item / target / checked_out_by all render through the shared
+ // polymorphicItemFormatter, which reads value.type to pick the
+ // per-morph-type icon + destination path. Keeps per-type
+ // rendering out of this file.
+ $columns[] = [
+ 'field' => 'item',
+ 'scope' => 'col',
+ 'searchable' => true,
+ 'sortable' => true,
+ 'title' => trans('general.name'),
+ 'visible' => true,
+ 'formatter' => 'polymorphicItemFormatter',
+ ];
+
+ $columns[] = [
+ 'field' => 'asset_tag',
+ 'scope' => 'col',
+ 'searchable' => true,
+ 'sortable' => true,
+ 'switchable' => true,
+ 'visible' => true,
+ 'title' => trans('admin/hardware/table.asset_tag'),
+ ];
+
+ $columns[] = [
+ 'field' => 'target',
+ 'scope' => 'col',
+ 'searchable' => true,
+ 'sortable' => false,
+ 'title' => trans('admin/hardware/table.checkoutto'),
+ 'visible' => true,
+ 'formatter' => 'polymorphicItemFormatter',
+ ];
+
+ $columns[] = [
+ 'field' => 'checked_out_by',
+ 'scope' => 'col',
+ 'searchable' => true,
+ 'sortable' => false,
+ 'switchable' => true,
+ 'visible' => true,
+ 'title' => trans('general.created_by'),
+ 'formatter' => 'polymorphicItemFormatter',
+ ];
+
+ // Pending view ends with the Actions column (reminder / delete).
+ // Deleted view swaps it for the Deleted At timestamp since
+ // nothing's actionable on a trashed row.
+ $columns[] = $showingDeleted ? [
+ 'field' => 'deleted_at',
+ 'scope' => 'col',
+ 'searchable' => false,
+ 'sortable' => true,
+ 'switchable' => true,
+ 'visible' => true,
+ 'title' => trans('general.deleted_at'),
+ 'formatter' => 'dateDisplayFormatter',
+ ] : [
+ 'field' => 'actions',
+ 'scope' => 'col',
+ 'searchable' => false,
+ 'sortable' => false,
+ 'switchable' => false,
+ 'title' => trans('button.actions'),
+ 'visible' => true,
+ 'formatter' => 'acceptanceActionsFormatter',
+ 'printIgnore' => true,
+ 'class' => 'hidden-print text-nowrap',
+ ];
- return json_encode($layout);
+ return json_encode($columns);
}
}