Skip to content

A free open source IT asset/license management system

Fixed #17288 - better sorting on activity report

snipe9ed4a22a6130
diff --git a/app/Http/Controllers/Api/ReportsController.php b/app/Http/Controllers/Api/ReportsController.php
index 8e2d3bd46d..707a88c765 100644
--- a/app/Http/Controllers/Api/ReportsController.php
+++ b/app/Http/Controllers/Api/ReportsController.php
@@ -58,7 +58,7 @@ class ReportsController extends Controller
// then they shouldn't be able to see the activity log for that item or target,
// but if they have the general activity view permission,
// then they can see all activity logs regardless of the item or target.
-
+
if ((! Gate::allows('activity.view')) && (($targetClass && $request->filled('target_id')) || ($itemClass && $request->filled('item_id')))) {
if ($targetClass && $request->filled('target_id')) {
@@ -160,7 +160,16 @@ class ReportsController extends Controller
$actionlogs->OrderByAssetNextAuditDate($order);
break;
case 'item':
- $actionlogs->OrderByItemName($order);
+ // The audit report (action_type=audit) is asset-only
+ // and keeps the simpler asset-name sort. The general
+ // activity report is polymorphic across every entity
+ // on the install and uses the per-type COALESCE sort.
+ // #17288.
+ if ($request->input('action_type') === 'audit') {
+ $actionlogs->OrderByItemName($order);
+ } else {
+ $actionlogs->OrderByPolymorphicItemName($order);
+ }
break;
default:
$sort = in_array($request->input('sort'), $allowed_columns) ? e($request->input('sort')) : 'action_logs.created_at';
diff --git a/app/Models/Builders/ActionlogQueryBuilder.php b/app/Models/Builders/ActionlogQueryBuilder.php
index aacc3e9a68..07debb1dc9 100644
--- a/app/Models/Builders/ActionlogQueryBuilder.php
+++ b/app/Models/Builders/ActionlogQueryBuilder.php
@@ -2,8 +2,23 @@
namespace App\Models\Builders;
+use App\Models\Accessory;
use App\Models\Actionlog;
use App\Models\Asset;
+use App\Models\AssetModel;
+use App\Models\Category;
+use App\Models\Company;
+use App\Models\Component;
+use App\Models\Consumable;
+use App\Models\Department;
+use App\Models\License;
+use App\Models\LicenseSeat;
+use App\Models\Location;
+use App\Models\Maintenance;
+use App\Models\Manufacturer;
+use App\Models\Setting;
+use App\Models\Supplier;
+use App\Models\User;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\MorphTo;
@@ -67,8 +82,8 @@ class ActionlogQueryBuilder extends Builder
/**
* Item name sort for the audit report (#9430). Only Assets get
* audited, so the action_type=audit filter upstream guarantees
- * item_type=Asset. Fixing truly-polymorphic item sort is a bigger
- * change.
+ * item_type=Asset. For the polymorphic activity report, use
+ * orderByItemTypeAndId instead.
*/
public function orderByItemName(string $order): self
{
@@ -80,4 +95,90 @@ class ActionlogQueryBuilder extends Builder
->addSelect('action_logs.*')
->orderBy('asset_item_sort.name', $order);
}
+
+ /**
+ * This is genuinely awful, but...
+ *
+ * Alphabetical polymorphic item-name sort for the activity report
+ * (#17288). action_logs.item is a polymorphic morphTo across every
+ * entity on the install, so there is no cross-type "name" column
+ * to ORDER BY. This LEFT JOINs each possible item_type table on
+ * (item_id, item_type) and COALESCEs the per-type name expression,
+ * so each row contributes exactly one non-null name value and the
+ * query orders by that merged value.
+ *
+ * Per-type expressions handle the entities whose display name is
+ * not just `name`: Asset falls back to asset_tag when name is
+ * null, User concatenates first_name + last_name when display_name
+ * is empty, LicenseSeat has no name column of its own so a second
+ * JOIN to the parent license surfaces the license name.
+ *
+ * The joins are selective (each ON predicate includes the item_type
+ * match, so a given action_logs row only joins to one child table)
+ * and non-multiplying (one match per row at most), so count() and
+ * pagination behavior are unaffected.
+ */
+ public function orderByPolymorphicItemName(string $order): self
+ {
+ $order = strtolower($order) === 'desc' ? 'desc' : 'asc';
+
+ // Honor name_display_format for the User case so last-first
+ // locales (Hungarian, CJK) sort users the same way the UI
+ // reads them. display_name is user-authored so it ships as-is
+ // regardless of locale. Only the first_name+last_name fallback
+ // flips. #19626.
+ //
+ // NULLIF around display_name mirrors the User model's
+ // display_name accessor, which falls back to the full name when
+ // the stored value is empty. ConvertEmptyStringsToNull turns ''
+ // into null on HTTP writes, but factory, seeder, and import
+ // paths can land an actual '' in the column.
+ $userNameExpr = Setting::getSettings()?->name_display_format === 'last_first'
+ ? "COALESCE(NULLIF(poly_user.display_name, ''), CONCAT(poly_user.last_name, ' ', poly_user.first_name))"
+ : "COALESCE(NULLIF(poly_user.display_name, ''), CONCAT(poly_user.first_name, ' ', poly_user.last_name))";
+
+ $types = [
+ [Accessory::class, 'accessories', 'poly_accessory', 'poly_accessory.name'],
+ [Asset::class, 'assets', 'poly_asset', "COALESCE(NULLIF(poly_asset.name, ''), poly_asset.asset_tag)"],
+ [AssetModel::class, 'models', 'poly_assetmodel', 'poly_assetmodel.name'],
+ [Category::class, 'categories', 'poly_category', 'poly_category.name'],
+ [Company::class, 'companies', 'poly_company', 'poly_company.name'],
+ [Component::class, 'components', 'poly_component', 'poly_component.name'],
+ [Consumable::class, 'consumables', 'poly_consumable', 'poly_consumable.name'],
+ [Department::class, 'departments', 'poly_department', 'poly_department.name'],
+ [License::class, 'licenses', 'poly_license', 'poly_license.name'],
+ [Location::class, 'locations', 'poly_location', 'poly_location.name'],
+ [Maintenance::class, 'maintenances', 'poly_maintenance', 'poly_maintenance.name'],
+ [Manufacturer::class, 'manufacturers', 'poly_manufacturer', 'poly_manufacturer.name'],
+ [Supplier::class, 'suppliers', 'poly_supplier', 'poly_supplier.name'],
+ [User::class, 'users', 'poly_user', $userNameExpr],
+ ];
+
+ $query = $this;
+ $nameExprs = [];
+ foreach ($types as [$classString, $table, $alias, $nameExpr]) {
+ $query = $query->leftJoin($table.' as '.$alias, function ($join) use ($alias, $classString) {
+ $join->on('action_logs.item_id', '=', $alias.'.id')
+ ->where('action_logs.item_type', '=', $classString);
+ });
+ $nameExprs[] = $nameExpr;
+ }
+
+ // LicenseSeat has no name column of its own, so the join lands
+ // on the seat row and a second join surfaces the parent license
+ // name. The ON predicate for the seat join still carries the
+ // item_type gate, so this pair of joins only fires on seat
+ // rows and poly_seat_license.name is null on everything else.
+ $query = $query
+ ->leftJoin('license_seats as poly_license_seat', function ($join) {
+ $join->on('action_logs.item_id', '=', 'poly_license_seat.id')
+ ->where('action_logs.item_type', '=', LicenseSeat::class);
+ })
+ ->leftJoin('licenses as poly_seat_license', 'poly_license_seat.license_id', '=', 'poly_seat_license.id');
+ $nameExprs[] = 'poly_seat_license.name';
+
+ return $query
+ ->addSelect('action_logs.*')
+ ->orderByRaw('COALESCE('.implode(', ', $nameExprs).') '.$order);
+ }
}
diff --git a/tests/Feature/Reporting/ActivityReportTest.php b/tests/Feature/Reporting/ActivityReportTest.php
index d1836cbdd3..d637906caa 100644
--- a/tests/Feature/Reporting/ActivityReportTest.php
+++ b/tests/Feature/Reporting/ActivityReportTest.php
@@ -223,6 +223,103 @@ class ActivityReportTest extends TestCase
->assertStatusMessageIs('error');
}
+ public function test_sort_by_item_on_activity_report_orders_by_polymorphic_item_name()
+ {
+ // Issue #17288. The activity report's `item` column is
+ // polymorphic across every entity on the install. The sort
+ // joins each possible item_type table and COALESCEs their
+ // per-type name expressions so rows order alphabetically by
+ // the displayed item name regardless of type.
+ $actor = User::factory()->superuser()->create();
+
+ $zebra = Asset::factory()->create(['name' => 'Zebra Laptop']);
+ $apple = \App\Models\Component::factory()->create(['name' => 'Apple Keyboard']);
+ $monkey = \App\Models\License::factory()->create(['name' => 'Monkey License']);
+
+ $zebraLog = Actionlog::factory()->create([
+ 'action_type' => 'checkout',
+ 'item_type' => Asset::class,
+ 'item_id' => $zebra->id,
+ ]);
+ $appleLog = Actionlog::factory()->create([
+ 'action_type' => 'checkout',
+ 'item_type' => \App\Models\Component::class,
+ 'item_id' => $apple->id,
+ ]);
+ $monkeyLog = Actionlog::factory()->create([
+ 'action_type' => 'checkout',
+ 'item_type' => \App\Models\License::class,
+ 'item_id' => $monkey->id,
+ ]);
+
+ $ids = collect($this->actingAsForApi($actor)
+ ->getJson(route('api.activity.index', [
+ 'sort' => 'item',
+ 'order' => 'asc',
+ ]))
+ ->assertOk()
+ ->json('rows'))
+ ->pluck('id')
+ ->filter(fn ($id) => in_array($id, [$zebraLog->id, $appleLog->id, $monkeyLog->id]))
+ ->values()
+ ->all();
+
+ $this->assertSame([$appleLog->id, $monkeyLog->id, $zebraLog->id], $ids);
+ }
+
+ public function test_sort_by_item_honors_last_first_name_display_format_for_user_rows()
+ {
+ // On a last-first install (Hungarian, CJK, etc.) the polymorphic
+ // name sort for User rows reads "Doe John" rather than
+ // "John Doe", so a user named John Doe orders alphabetically by
+ // "D" rather than "J". display_name is user-authored so it ships
+ // as-is regardless of locale. #17288 + #19626.
+ $this->settings->set(['name_display_format' => 'last_first']);
+
+ $actor = User::factory()->superuser()->create();
+
+ $john = User::factory()->create([
+ 'first_name' => 'John',
+ 'last_name' => 'Doe',
+ 'display_name' => null,
+ ]);
+ $apple = \App\Models\Component::factory()->create(['name' => 'Apple Keyboard']);
+ $zebra = \App\Models\Component::factory()->create(['name' => 'Zebra Mouse']);
+
+ $userLog = Actionlog::factory()->create([
+ 'action_type' => 'update',
+ 'item_type' => User::class,
+ 'item_id' => $john->id,
+ ]);
+ $appleLog = Actionlog::factory()->create([
+ 'action_type' => 'checkout',
+ 'item_type' => \App\Models\Component::class,
+ 'item_id' => $apple->id,
+ ]);
+ $zebraLog = Actionlog::factory()->create([
+ 'action_type' => 'checkout',
+ 'item_type' => \App\Models\Component::class,
+ 'item_id' => $zebra->id,
+ ]);
+
+ $ids = collect($this->actingAsForApi($actor)
+ ->getJson(route('api.activity.index', [
+ 'sort' => 'item',
+ 'order' => 'asc',
+ ]))
+ ->assertOk()
+ ->json('rows'))
+ ->pluck('id')
+ ->filter(fn ($id) => in_array($id, [$userLog->id, $appleLog->id, $zebraLog->id]))
+ ->values()
+ ->all();
+
+ // Apple Keyboard < Doe John < Zebra Mouse.
+ // Without the last_first flip, the user would sort as "John Doe"
+ // and land between Apple and Zebra at a different position.
+ $this->assertSame([$appleLog->id, $userLog->id, $zebraLog->id], $ids);
+ }
+
public function test_search_matches_target_asset_tag_on_component_checkout()
{
// Component checkouts store item=Component and target=Asset.