A free open source IT asset/license management system
Added user consumables API endpoint
snipe919c8b45398c
diff --git a/app/Http/Controllers/Api/UsersController.php b/app/Http/Controllers/Api/UsersController.phpindex 4e8f2b18e7..1a599029e6 100644--- a/app/Http/Controllers/Api/UsersController.php+++ b/app/Http/Controllers/Api/UsersController.php@@ -12,7 +12,6 @@ use App\Http\Requests\SaveUserRequest;use App\Http\Transformers\AccessoriesTransformer;use App\Http\Transformers\ActionlogsTransformer;use App\Http\Transformers\AssetsTransformer;-use App\Http\Transformers\ConsumablesTransformer;use App\Http\Transformers\LicensesTransformer;use App\Http\Transformers\SelectlistTransformer;use App\Http\Transformers\UsersTransformer;@@ -881,13 +880,12 @@ class UsersController extends Controller}/**- * Return JSON containing a list of consumables assigned to a user.+ * Return JSON containing a paginated list of consumable checkouts+ * assigned to a user. One row per consumables_users pivot entry.** @author [A. Gianotto] [<[email protected]>]** @since [v3.0]- *- * @param $userId*/public function consumables(Request $request, $id): array{@@ -895,9 +893,28 @@ class UsersController extends Controller$this->authorize('view', Consumable::class);$user = User::findOrFail($id);$this->authorize('view', $user);- $consumables = $user->consumables;- return (new ConsumablesTransformer)->transformConsumables($consumables, $consumables->count(), $request);+ $query = $user->consumables();++ $total = $query->count();+ $offset = ($request->input('offset') > $total) ? $total : app('api_offset_value');+ $limit = app('api_limit_value');++ $sortColumn = $request->input('sort') === 'name'+ ? 'consumables.name'+ : 'consumables_users.created_at';+ $order = $request->input('order') === 'asc' ? 'asc' : 'desc';++ $consumables = $query+ ->orderBy($sortColumn, $order)+ ->skip($offset)+ ->take($limit)+ ->get();++ $unitCostsById = Consumable::lastUnitCostsFor($consumables);++ return (new UsersTransformer)+ ->transformUserConsumables($consumables, $unitCostsById, $total);}/**diff --git a/app/Http/Transformers/UsersTransformer.php b/app/Http/Transformers/UsersTransformer.phpindex ba975aaea0..222d68ef0b 100644--- a/app/Http/Transformers/UsersTransformer.php+++ b/app/Http/Transformers/UsersTransformer.php@@ -3,6 +3,7 @@namespace App\Http\Transformers;use App\Helpers\Helper;+use App\Models\Consumable;use App\Models\User;use Illuminate\Database\Eloquent\Collection;use Illuminate\Support\Facades\Gate;@@ -231,4 +232,44 @@ class UsersTransformer{return (new DatatablesTransformer)->transformDatatables($users);}++ /**+ * @param Collection<int, Consumable> $consumables+ * @param array<int, string|null> $unitCostsById+ * @return array<string, mixed>+ */+ public function transformUserConsumables(Collection $consumables, array $unitCostsById, int $total): array+ {+ $rows = [];+ foreach ($consumables as $consumable) {+ $rows[] = $this->transformUserConsumableRow($consumable, $unitCostsById);+ }++ return (new DatatablesTransformer)->transformDatatables($rows, $total);+ }++ /**+ * @param array<int, string|null> $unitCostsById+ * @return array<string, mixed>+ */+ private function transformUserConsumableRow(Consumable $consumable, array $unitCostsById): array+ {+ $unitCost = $unitCostsById[$consumable->id] ?? null;+ /** @var \Illuminate\Database\Eloquent\Relations\Pivot $pivot */+ $pivot = $consumable->pivot;++ return [+ 'id' => (int) $pivot->id,+ 'consumable' => [+ 'id' => (int) $consumable->id,+ 'name' => e($consumable->name),+ ],+ 'name' => e($consumable->name),+ 'image' => $consumable->getImageUrl() ?: null,+ 'qty' => 1,+ 'purchase_cost' => Helper::formatCurrencyOutput($unitCost),+ 'created_at' => Helper::getFormattedDateObject($pivot->created_at, 'datetime'),+ 'note' => $pivot->note ? e($pivot->note) : null,+ ];+ }}diff --git a/app/Models/Traits/HasOrders.php b/app/Models/Traits/HasOrders.phpindex 4cbbc16998..117a19ca30 100644--- a/app/Models/Traits/HasOrders.php+++ b/app/Models/Traits/HasOrders.php@@ -139,6 +139,63 @@ trait HasOrders];}+ /**+ * Batch version of lastOrderDefaults()['unit_cost'] for a whole+ * collection of items of the same class. Falls back to each+ * item's default_purchase_cost when it has no order history.+ *+ * @param iterable<int, self> $items+ * @return array<int, string|null> Keyed by item id.+ */+ public static function lastUnitCostsFor(iterable $items): array+ {+ $ids = [];+ $defaults = [];+ foreach ($items as $item) {+ $id = (int) $item->getKey();+ if ($id <= 0) {+ continue;+ }+ $ids[$id] = true;+ if (! array_key_exists($id, $defaults) && $item->default_purchase_cost !== null) {+ $defaults[$id] = (string) $item->default_purchase_cost;+ }+ }+ $ids = array_keys($ids);+ if ($ids === []) {+ return [];+ }++ $latestOrderItemIds = OrderItem::query()+ ->where('item_type', static::class)+ ->whereIn('item_id', $ids)+ ->groupBy('item_id')+ ->select('item_id')+ ->selectRaw('MAX(id) as max_id')+ ->pluck('max_id')+ ->all();++ $prices = [];+ if ($latestOrderItemIds !== []) {+ $prices = OrderItem::query()+ ->whereIn('id', $latestOrderItemIds)+ ->pluck('price', 'item_id')+ ->all();+ }++ $out = [];+ foreach ($ids as $id) {+ if (array_key_exists($id, $prices) && $prices[$id] !== null) {+ $out[$id] = (string) $prices[$id];++ continue;+ }+ $out[$id] = $defaults[$id] ?? null;+ }++ return $out;+ }+/*** Prefill values for the create / clone form's initial-acquisition* fields. Distinct from lastOrderDefaults() because this shapediff --git a/app/Models/User.php b/app/Models/User.phpindex 8c71928864..52a48fde66 100644--- a/app/Models/User.php+++ b/app/Models/User.php@@ -1943,50 +1943,79 @@ class User extends SnipeModel implements AuthenticatableContract, AuthorizableCoreturn $this->locale ?? Setting::getSettings()->locale ?? config('app.locale');}+ protected bool $userTotalCostComputed = false;+public function getUserTotalCost(){- $asset_cost = 0;- $license_cost = 0;- $accessory_cost = 0;- $consumable_cost = 0;- $maintenance_cost = 0;-- foreach ($this->assets as $asset) {- $asset_cost += (float) $asset->purchase_cost;+ if ($this->userTotalCostComputed) {+ return $this;}- $this->asset_cost = $asset_cost;- foreach ($this->licenses as $license) {- $license_cost += (float) $license->purchase_cost;- }- $this->license_cost = $license_cost;-- // Accessory / consumable unit cost tracks the info-panel's "last- // unit cost" so this tally matches the per-item rows in the tab- // tables. lastOrderDefaults() already merges last-Order price- // with the parent's `default_purchase_cost` template value when- // an item has no order history, so nothing to fall back to here.- foreach ($this->accessories as $accessory) {- $accessory_cost += (float) ($accessory->lastOrderDefaults()['unit_cost'] ?? 0);- }- $this->accessory_cost = $accessory_cost;+ $this->asset_cost = (float) $this->assets()->sum('purchase_cost');+ $this->license_cost = (float) $this->licenses()->sum('purchase_cost');+ $this->maintenance_cost = (float) $this->assignedMaintenances()->sum('cost');- foreach ($this->consumables as $consumable) {- $consumable_cost += (float) ($consumable->lastOrderDefaults()['unit_cost'] ?? 0);+ $this->accessory_cost = $this->sumPivotUnitCosts(+ pivotTable: 'accessories_checkout',+ pivotFk: 'accessory_id',+ modelClass: \App\Models\Accessory::class,+ extraWhere: ['assigned_type' => \App\Models\User::class],+ );+ $this->consumable_cost = $this->sumPivotUnitCosts(+ pivotTable: 'consumables_users',+ pivotFk: 'consumable_id',+ modelClass: \App\Models\Consumable::class,+ );++ $this->total_user_cost = $this->asset_cost + $this->accessory_cost + $this->consumable_cost + $this->license_cost + $this->maintenance_cost;++ $this->userTotalCostComputed = true;++ return $this;+ }++ /**+ * Sum (pivot_row_count * last_unit_cost) across every distinct+ * item this user has any pivot rows for.+ *+ * $modelClass must use the HasOrders trait.+ *+ * @param array<string, mixed> $extraWhere additional pivot-side filters (e.g. polymorphic assigned_type)+ */+ private function sumPivotUnitCosts(+ string $pivotTable,+ string $pivotFk,+ string $modelClass,+ array $extraWhere = [],+ ): float {+ $countsByItem = \Illuminate\Support\Facades\DB::table($pivotTable)+ ->where('assigned_to', $this->id);+ foreach ($extraWhere as $column => $value) {+ $countsByItem->where($column, $value);}- $this->consumable_cost = $consumable_cost;+ $countsByItem = $countsByItem+ ->groupBy($pivotFk)+ ->select($pivotFk)+ ->selectRaw('COUNT(*) as pivot_count')+ ->pluck('pivot_count', $pivotFk)+ ->all();- // Maintenances tied to this user as the polymorphic checked_out_to- // target. Summed across open + completed records because the- // user "caused" both.- foreach ($this->assignedMaintenances as $maintenance) {- $maintenance_cost += (float) $maintenance->cost;+ if ($countsByItem === []) {+ return 0.0;}- $this->maintenance_cost = $maintenance_cost;- $this->total_user_cost = $asset_cost + $accessory_cost + $consumable_cost + $license_cost + $maintenance_cost;+ $items = $modelClass::query()+ ->whereIn('id', array_keys($countsByItem))+ ->get(['id', 'default_purchase_cost']);- return $this;+ $unitCosts = $modelClass::lastUnitCostsFor($items);++ $total = 0.0;+ foreach ($countsByItem as $itemId => $count) {+ $total += (float) ($unitCosts[$itemId] ?? 0) * (int) $count;+ }++ return $total;}public function scopeUserLocation($query, $location, $search)diff --git a/app/Presenters/UserPresenter.php b/app/Presenters/UserPresenter.phpindex 61afe2b9eb..2d4288300c 100644--- a/app/Presenters/UserPresenter.php+++ b/app/Presenters/UserPresenter.php@@ -628,4 +628,63 @@ class UserPresenter extends Presenterreturn $this->model->department?->tag_color?? $this->model->company?->color;}++ public static function consumablesDataTableLayout(): string+ {+ $layout = [+ [+ 'field' => 'consumable',+ 'scope' => 'col',+ 'searchable' => true,+ 'sortable' => true,+ 'switchable' => false,+ 'title' => trans('general.name'),+ 'visible' => true,+ 'formatter' => 'consumablesLinkObjFormatter',+ ],+ [+ 'field' => 'qty',+ 'scope' => 'col',+ 'searchable' => false,+ 'sortable' => false,+ 'switchable' => true,+ 'title' => trans('general.qty'),+ 'visible' => true,+ 'footerFormatter' => 'sumFormatter',+ 'class' => 'text-right',+ ],+ [+ 'field' => 'purchase_cost',+ 'scope' => 'col',+ 'searchable' => false,+ 'sortable' => false,+ 'switchable' => true,+ 'title' => trans('general.unit_cost'),+ 'visible' => true,+ 'footerFormatter' => 'sumFormatter',+ 'class' => 'text-right',+ ],+ [+ 'field' => 'created_at',+ 'scope' => 'col',+ 'searchable' => false,+ 'sortable' => true,+ 'switchable' => true,+ 'title' => trans('general.date'),+ 'visible' => true,+ 'formatter' => 'dateDisplayFormatter',+ ],+ [+ 'field' => 'note',+ 'scope' => 'col',+ 'searchable' => true,+ 'sortable' => false,+ 'switchable' => true,+ 'title' => trans('general.notes'),+ 'visible' => true,+ ],+ ];++ return json_encode($layout);+ }}diff --git a/phpstan-baseline.neon b/phpstan-baseline.neonindex 49d583ffee..7dcd32ebd0 100644--- a/phpstan-baseline.neon+++ b/phpstan-baseline.neon@@ -5217,7 +5217,7 @@ parameters:-message: '#^Access to an undefined property App\\Models\\Accessory\:\:\$default_purchase_cost\.$#'identifier: property.notFound- count: 1+ count: 2path: app/Models/Accessory.php-@@ -5553,7 +5553,7 @@ parameters:-message: '#^Access to an undefined property App\\Models\\Asset\:\:\$default_purchase_cost\.$#'identifier: property.notFound- count: 1+ count: 2path: app/Models/Asset.php-@@ -6495,7 +6495,7 @@ parameters:-message: '#^Access to an undefined property App\\Models\\Component\:\:\$default_purchase_cost\.$#'identifier: property.notFound- count: 1+ count: 2path: app/Models/Component.php-@@ -6741,7 +6741,7 @@ parameters:-message: '#^Access to an undefined property App\\Models\\Consumable\:\:\$default_purchase_cost\.$#'identifier: property.notFound- count: 1+ count: 2path: app/Models/Consumable.php-@@ -10379,3 +10379,21 @@ parameters:identifier: arguments.countcount: 1path: routes/web.php++ -+ message: '#^Access to an undefined property App\\Models\\Consumable\:\:\$pivot\.$#'+ identifier: property.notFound+ count: 1+ path: app/Http/Transformers/UsersTransformer.php++ -+ message: '#^Access to an undefined property Illuminate\\Database\\Eloquent\\Relations\\Pivot\:\:\$created_at\.$#'+ identifier: property.notFound+ count: 1+ path: app/Http/Transformers/UsersTransformer.php++ -+ message: '#^Access to an undefined property Illuminate\\Database\\Eloquent\\Relations\\Pivot\:\:\$note\.$#'+ identifier: property.notFound+ count: 1+ path: app/Http/Transformers/UsersTransformer.phpdiff --git a/resources/views/users/view.blade.php b/resources/views/users/view.blade.phpindex e86d2bf3fe..37a8e8c570 100755--- a/resources/views/users/view.blade.php+++ b/resources/views/users/view.blade.php@@ -469,40 +469,15 @@<x-tabs.pane name="consumables" :count="$user->consumables()->count()">@can('view', \App\Models\Consumable::class)- <table- data-cookie-id-table="userConsumableTable"- data-id-table="userConsumableTable"- id="userConsumableTable"- data-buttons="consumableButtons"- data-side-pagination="client"- data-show-footer="true"- data-sort-name="name"- class="table table-striped snipe-table table-hover"- data-export-options='{- "fileName": "export-consumable-{{ str_slug($user->username) }}-{{ date('Y-m-d') }}",- "ignoreColumn": ["actions","image","change","checkbox","checkincheckout","delete","download","icon"]- }'>- <thead>- <tr>- <th scope="col" class="col-md-3">{{ trans('general.name') }}</th>- <th scope="col" class="col-md-2" data-footer-formatter="sumFormatter" data-fieldname="purchase_cost">{{ trans('general.unit_cost') }}</th>- <th scope="col" class="col-md-2">{{ trans('general.date') }}</th>- <th scope="col" class="col-md-5">{{ trans('general.notes') }}</th>- </tr>- </thead>- <tbody>- @foreach ($user->consumables as $consumable)- <tr>- <td>{!! $consumable->present()->nameUrl() !!}</td>- <td>- {!! Helper::formatCurrencyOutput($consumable->lastOrderDefaults()['unit_cost'] ?? null) !!}- </td>- <td>{{ Helper::getFormattedDateObject($consumable->pivot->created_at, 'datetime', false) }}</td>- <td>{{ $consumable->pivot->note }}</td>- </tr>- @endforeach- </tbody>- </table>+ <x-table+ name="userConsumableTable"+ show_column_search="false"+ show_footer="true"+ buttons="consumableButtons"+ api_url="{{ route('api.users.consumableslist', ['user' => $user->id]) }}"+ :presenter="\App\Presenters\UserPresenter::consumablesDataTableLayout()"+ export_filename="export-consumable-{{ str_slug($user->username) }}-{{ date('Y-m-d') }}"+ />@endcan</x-tabs.pane>diff --git a/routes/api.php b/routes/api.phpindex 94bc337527..28bd4944be 100644--- a/routes/api.php+++ b/routes/api.php@@ -1269,6 +1269,13 @@ Route::group(['prefix' => 'v1', 'middleware' => ['api', 'api-throttle:api']], fu])->name('api.users.accessorieslist');+ Route::get('{user}/consumables',+ [+ Api\UsersController::class,+ 'consumables',+ ]+ )->name('api.users.consumableslist');+Route::get('{user}/licenses',[Api\UsersController::class,diff --git a/tests/Feature/Users/Api/UserConsumablesListTest.php b/tests/Feature/Users/Api/UserConsumablesListTest.phpnew file mode 100644index 0000000000..1e6e420937--- /dev/null+++ b/tests/Feature/Users/Api/UserConsumablesListTest.php@@ -0,0 +1,142 @@+<?php++namespace Tests\Feature\Users\Api;++use App\Models\Consumable;+use App\Models\User;+use Illuminate\Support\Facades\DB;+use Tests\TestCase;++/**+ * Coverage for the new api.users.consumableslist endpoint that+ * replaces the server-side @foreach block on users.show. The tab+ * used to render every pivot row inline and call lastOrderDefaults()+ * per row, which N+1'd into a 502 on users with tens of thousands+ * of consumable checkouts. The endpoint paginates + resolves last+ * unit costs in one grouped query.+ */+class UserConsumablesListTest extends TestCase+{+ public function test_endpoint_requires_view_permission(): void+ {+ $user = User::factory()->create();++ $this->actingAsForApi(User::factory()->create())+ ->getJson(route('api.users.consumableslist', ['user' => $user->id]))+ ->assertForbidden();+ }++ public function test_endpoint_returns_one_row_per_pivot_entry(): void+ {+ // Two distinct consumables. First one checked out to the+ // user three separate times so the response has three rows+ // pointing at the same underlying consumable.+ $user = User::factory()->create();+ $pens = Consumable::factory()->create(['name' => 'Pens']);+ $paper = Consumable::factory()->create(['name' => 'Paper']);++ DB::table('consumables_users')->insert([+ ['consumable_id' => $pens->id, 'assigned_to' => $user->id, 'created_at' => now(), 'note' => 'first'],+ ['consumable_id' => $pens->id, 'assigned_to' => $user->id, 'created_at' => now(), 'note' => 'second'],+ ['consumable_id' => $pens->id, 'assigned_to' => $user->id, 'created_at' => now(), 'note' => 'third'],+ ['consumable_id' => $paper->id, 'assigned_to' => $user->id, 'created_at' => now(), 'note' => 'reams'],+ ]);++ $response = $this->actingAsForApi(User::factory()->viewUsers()->viewConsumables()->create())+ ->getJson(route('api.users.consumableslist', ['user' => $user->id]))+ ->assertOk()+ ->json();++ $this->assertSame(4, $response['total']);+ $this->assertCount(4, $response['rows']);+ }++ public function test_endpoint_paginates_and_reports_metadata(): void+ {+ $user = User::factory()->create();+ $consumable = Consumable::factory()->create();+ $rows = array_fill(0, 5, [+ 'consumable_id' => $consumable->id,+ 'assigned_to' => $user->id,+ 'created_at' => now(),+ ]);+ DB::table('consumables_users')->insert($rows);++ $response = $this->actingAsForApi(User::factory()->viewUsers()->viewConsumables()->create())+ ->getJson(route('api.users.consumableslist', ['user' => $user->id, 'limit' => 2, 'page' => 2]))+ ->assertOk()+ ->json();++ $this->assertSame(5, $response['total']);+ $this->assertCount(2, $response['rows']);+ $this->assertSame(2, $response['per_page']);+ $this->assertSame(2, $response['current_page']);+ $this->assertSame(3, $response['total_pages']);+ $this->assertNotNull($response['next_page_url']);+ $this->assertNotNull($response['prev_page_url']);+ }++ public function test_endpoint_resolves_last_unit_cost_in_one_grouped_query(): void+ {+ // Regression test for the reason this endpoint exists at all.+ // A user with N pivot rows would previously issue N per-row+ // queries against order_items to resolve unit_cost. Now+ // OrderItem is touched at most twice regardless of pivot+ // count: once for the MAX(id) GROUP BY, once for the price+ // lookup. lastUnitCostsFor early-returns before the second+ // query when there are no order-item ids on hit, so the+ // "no order history at all" path can even land at once.+ $user = User::factory()->create();+ $consumable = Consumable::factory()->create(['default_purchase_cost' => '0.10']);+ $orderId = DB::table('orders')->insertGetId([+ 'created_at' => now(),+ 'updated_at' => now(),+ ]);+ DB::table('order_items')->insert([+ 'order_id' => $orderId,+ 'item_type' => Consumable::class,+ 'item_id' => $consumable->id,+ 'price' => '0.25',+ 'qty' => 1,+ 'created_at' => now(),+ 'updated_at' => now(),+ ]);++ // 20 pivot rows pointing at the one consumable.+ $rows = array_fill(0, 20, [+ 'consumable_id' => $consumable->id,+ 'assigned_to' => $user->id,+ 'created_at' => now(),+ ]);+ DB::table('consumables_users')->insert($rows);++ DB::enableQueryLog();+ try {+ $response = $this->actingAsForApi(User::factory()->viewUsers()->viewConsumables()->create())+ ->getJson(route('api.users.consumableslist', ['user' => $user->id]))+ ->assertOk()+ ->json();+ } finally {+ $queries = DB::getQueryLog();+ DB::disableQueryLog();+ }++ $orderItemQueries = array_filter(+ $queries,+ fn ($q) => str_contains(strtolower($q['query']), 'order_items'),+ );+ $this->assertLessThanOrEqual(+ 2,+ count($orderItemQueries),+ 'lastUnitCostsFor must hit order_items at most twice regardless of pivot count',+ );++ // Sanity-check the row shape too: 20 rows, all with the+ // resolved price (formatCurrencyOutput of 0.25).+ $this->assertCount(20, $response['rows']);+ foreach ($response['rows'] as $row) {+ $this->assertNotNull($row['purchase_cost']);+ $this->assertSame((int) $consumable->id, $row['consumable']['id']);+ }+ }+}diff --git a/tests/Unit/Models/UserTotalCostTest.php b/tests/Unit/Models/UserTotalCostTest.phpindex ed9c4c4e24..28abc0c01e 100644--- a/tests/Unit/Models/UserTotalCostTest.php+++ b/tests/Unit/Models/UserTotalCostTest.php@@ -2,9 +2,12 @@namespace Tests\Unit\Models;+use App\Models\Accessory;use App\Models\Asset;+use App\Models\Consumable;use App\Models\Maintenance;use App\Models\User;+use Illuminate\Support\Facades\DB;use Tests\TestCase;/**@@ -63,4 +66,124 @@ class UserTotalCostTest extends TestCase$this->assertEqualsWithDelta(0, (float) $totals->maintenance_cost, 0.001);$this->assertEqualsWithDelta(0, (float) $totals->total_user_cost, 0.001);}++ public function test_consumable_cost_multiplies_unit_cost_by_pivot_row_count(): void+ {+ // Regression: the summary panel used to iterate the+ // belongsToMany collection which contains one row per+ // checkout event. A user handed 500 boxes of pens at $0.10+ // must total $50, not $0.10. The DB-aggregate path replaces+ // that foreach so we pin the pivot-count-times-unit-cost+ // math here.+ $user = User::factory()->create();+ $pens = Consumable::factory()->create(['default_purchase_cost' => '0.10']);+ $paper = Consumable::factory()->create(['default_purchase_cost' => '1.50']);++ $rows = [];+ for ($i = 0; $i < 500; $i++) {+ $rows[] = ['consumable_id' => $pens->id, 'assigned_to' => $user->id, 'created_at' => now()];+ }+ for ($i = 0; $i < 3; $i++) {+ $rows[] = ['consumable_id' => $paper->id, 'assigned_to' => $user->id, 'created_at' => now()];+ }+ DB::table('consumables_users')->insert($rows);++ $totals = $user->getUserTotalCost();++ // 500 * $0.10 + 3 * $1.50 = $54.50+ $this->assertEqualsWithDelta(54.50, (float) $totals->consumable_cost, 0.001);+ }++ public function test_summary_computes_without_hitting_order_items_per_pivot_row(): void+ {+ // Regression coverage for the 502-on-huge-user bug. The+ // aggregate must touch order_items at most twice regardless+ // of how many pivot rows the user has.+ $user = User::factory()->create();+ $consumable = Consumable::factory()->create(['default_purchase_cost' => '0.10']);++ $rows = array_fill(0, 100, [+ 'consumable_id' => $consumable->id,+ 'assigned_to' => $user->id,+ 'created_at' => now(),+ ]);+ DB::table('consumables_users')->insert($rows);++ DB::enableQueryLog();+ try {+ $user->getUserTotalCost();+ } finally {+ $queries = DB::getQueryLog();+ DB::disableQueryLog();+ }++ $orderItemQueries = array_filter(+ $queries,+ fn ($q) => str_contains(strtolower($q['query']), 'order_items'),+ );+ $this->assertLessThanOrEqual(+ 2,+ count($orderItemQueries),+ 'getUserTotalCost must resolve unit costs in at most 2 grouped queries, not one per pivot row',+ );+ }++ public function test_repeated_calls_memoize_and_do_not_re_query(): void+ {+ // The Blade show-user page reads $user->getUserTotalCost()+ // seven times. Regression coverage for the memoization guard:+ // the second call must execute zero DB queries.+ $user = User::factory()->create();+ $consumable = Consumable::factory()->create();+ DB::table('consumables_users')->insert([+ ['consumable_id' => $consumable->id, 'assigned_to' => $user->id, 'created_at' => now()],+ ]);++ $user->getUserTotalCost();++ DB::enableQueryLog();+ try {+ $user->getUserTotalCost();+ $user->getUserTotalCost();+ $user->getUserTotalCost();+ } finally {+ $queries = DB::getQueryLog();+ DB::disableQueryLog();+ }++ $this->assertCount(0, $queries, 'Subsequent calls to getUserTotalCost must be memoized');+ }++ public function test_accessory_cost_ignores_pivot_rows_for_other_target_types(): void+ {+ // accessories_checkout is polymorphic (users, assets,+ // locations). The aggregate must filter to+ // assigned_type = User so a device checkout of the same+ // accessory doesn't inflate the user's summary.+ $user = User::factory()->create();+ $accessory = Accessory::factory()->create(['default_purchase_cost' => '5.00']);++ DB::table('accessories_checkout')->insert([+ [+ 'accessory_id' => $accessory->id,+ 'assigned_to' => $user->id,+ 'assigned_type' => User::class,+ 'created_at' => now(),+ ],+ [+ 'accessory_id' => $accessory->id,+ 'assigned_to' => 99_999_999,+ 'assigned_type' => Asset::class,+ 'created_at' => now(),+ ],+ ]);++ $totals = $user->getUserTotalCost();++ // One user pivot row * $5.00. The Asset pivot row must not+ // contribute even though it points at the same accessory+ // and would inflate the sum without the assigned_type+ // filter.+ $this->assertEqualsWithDelta(5.00, (float) $totals->accessory_cost, 0.001);+ }}