From ade1d83f514b041dabcf66e2a72da79d681929ef Mon Sep 17 00:00:00 2001 From: Manuk Date: Fri, 13 Nov 2026 02:58:18 +0400 Subject: [PATCH 1/3] fix: order lane cells by the board query's order like columns --- docs/content/2.essentials/6.swimlanes.md | 4 + src/Concerns/HasBoardGroupings.php | 69 ++++++++- .../Fixtures/Modern/TestCastGroupedBoard.php | 9 +- tests/Fixtures/Modern/TestGroupedBoard.php | 28 +++- tests/Modern/Feature/GroupingTest.php | 139 ++++++++++++++++++ 5 files changed, 244 insertions(+), 5 deletions(-) diff --git a/docs/content/2.essentials/6.swimlanes.md b/docs/content/2.essentials/6.swimlanes.md index 7786ac09a..916792d7d 100644 --- a/docs/content/2.essentials/6.swimlanes.md +++ b/docs/content/2.essentials/6.swimlanes.md @@ -80,6 +80,10 @@ The header `+` from `createCardAction()` creates a card without knowing the lane - Without `moveUsing()`, the lanes are read-only. Cards move between columns inside their lane, the browser blocks a drop into another lane, and the server refuses it with a message. - The server checks that the card sits in the lane it left, and refuses the move when the board has changed underneath the user. +## Card order + +Cells order their cards by the board query's own `orderBy()` calls first, then by position, the same as columns. A board query with `distinct()` honours only plain `orderBy()` columns of the model's own table that its select list includes, and falls back to position order for any other order. + ## Limits and collapsed columns - A column limit counts the whole column across every lane, and the header is shared. diff --git a/src/Concerns/HasBoardGroupings.php b/src/Concerns/HasBoardGroupings.php index 55c001d2a..c43750ae3 100644 --- a/src/Concerns/HasBoardGroupings.php +++ b/src/Concerns/HasBoardGroupings.php @@ -8,6 +8,7 @@ use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Collection as EloquentCollection; use Illuminate\Database\Eloquent\Model; +use Illuminate\Database\Query\Builder as QueryBuilder; use Illuminate\Support\Facades\DB; use Illuminate\Support\Str; use Relaticle\Flowforge\Grouping; @@ -96,7 +97,11 @@ protected function getLaneRecordsQuery(Lane $lane, int $perCellLimit): ?Builder return null; } - $scoped = $lane->applyQuery($boardQuery)->applyScopes(); + $laneQuery = $lane->applyQuery($boardQuery); + $boardOrders = $laneQuery->getQuery()->orders ?? []; + $boardOrderBindings = $laneQuery->getQuery()->getRawBindings()['order']; + + $scoped = $laneQuery->applyScopes(); $model = $scoped->getModel(); $inner = $scoped->getQuery(); @@ -112,21 +117,26 @@ protected function getLaneRecordsQuery(Lane $lane, int $perCellLimit): ?Builder } } + [$boardOrder, $boardOrderBindings] = $this->compileBoardOrders($inner, $model, $boardOrders, $boardOrderBindings); + if ($inner->distinct) { $inner = $model->newModelQuery()->fromSub($inner, $model->getTable())->getQuery(); } $grammar = $inner->getGrammar(); $partition = $grammar->wrap($this->getColumnIdentifierAttribute()); - $order = collect([$this->getPositionIdentifierAttribute(), $model->getKeyName()]) + $order = collect([$boardOrder]) + ->merge(collect([$this->getPositionIdentifierAttribute(), $model->getKeyName()]) + ->filter() + ->map(fn (string $column): string => $grammar->wrap($model->qualifyColumn($column)))) ->filter() - ->map(fn (string $column): string => $grammar->wrap($model->qualifyColumn($column))) ->implode(', '); if ($inner->columns === null) { $inner->select($model->qualifyColumn('*')); } + $inner->addBinding($boardOrderBindings, 'select'); $inner->addSelect([ DB::raw("row_number() over (partition by {$partition} order by {$order}) as flowforge_cell_row"), DB::raw("count(*) over (partition by {$partition}) as flowforge_cell_total"), @@ -140,6 +150,59 @@ protected function getLaneRecordsQuery(Lane $lane, int $perCellLimit): ?Builder return $outer->setEagerLoads($scoped->getEagerLoads()); } + /** + * @param array> $orders + * @param array $bindings + * @return array{string, array} + */ + protected function compileBoardOrders(QueryBuilder $inner, Model $model, array $orders, array $bindings): array + { + $grammar = $inner->getGrammar(); + $table = $model->getTable(); + $columns = array_filter(array_map($grammar->getValue(...), $inner->columns ?? []), is_string(...)); + $aliases = array_filter(array_map( + fn (string $column): ?string => preg_match('/\sas\s+\W?([\w$]+)\W?\s*$/i', $column, $match) ? $match[1] : null, + $columns, + )); + $selectsOwnColumns = array_intersect(['*', "{$table}.*"], $columns) !== []; + $compiled = []; + + foreach ($orders as $order) { + $column = $order['column'] ?? null; + + if (($order['type'] ?? null) === 'InOrderOf') { + return ['', []]; + } + + if ($inner->distinct) { + $name = is_string($column) && ! isset($order['sql']) ? Str::after($column, "{$table}.") : ''; + + if ($name === '' || str_contains($name, '.') || ! ($selectsOwnColumns || array_intersect([$name, "{$table}.{$name}"], $columns) !== [])) { + return ['', []]; + } + + $compiled[] = $grammar->wrap($model->qualifyColumn($name)) . ' ' . $order['direction']; + + continue; + } + + $sql = isset($order['sql']) + ? $grammar->getValue($order['sql']) + : $grammar->wrap($column) . ' ' . $order['direction']; + $readable = str_replace(['"', '`', '[', ']'], '', $sql); + + foreach ($aliases as $alias) { + if (preg_match('/(?getColumnIdentifierAttribute(); diff --git a/tests/Fixtures/Modern/TestCastGroupedBoard.php b/tests/Fixtures/Modern/TestCastGroupedBoard.php index 2f1c604d9..234e30eab 100644 --- a/tests/Fixtures/Modern/TestCastGroupedBoard.php +++ b/tests/Fixtures/Modern/TestCastGroupedBoard.php @@ -16,6 +16,8 @@ class TestCastGroupedBoard extends BoardPage public bool $distinctJoin = false; + public string $orderShape = 'none'; + public function getEloquentQuery(): Builder { $query = CastTask::query(); @@ -28,7 +30,12 @@ public function getEloquentQuery(): Builder $query->join('task_user', 'task_user.task_id', '=', 'tasks.id')->select('tasks.*')->distinct(); } - return $query; + return match ($this->orderShape) { + 'title_desc' => $query->orderBy('tasks.title', 'desc'), + 'unselected' => $query->orderBy('task_user.user_id', 'desc'), + 'raw' => $query->orderByRaw('lower(tasks.title) desc'), + default => $query, + }; } public function board(Board $board): Board diff --git a/tests/Fixtures/Modern/TestGroupedBoard.php b/tests/Fixtures/Modern/TestGroupedBoard.php index 3c33f70ea..f665f3c4c 100644 --- a/tests/Fixtures/Modern/TestGroupedBoard.php +++ b/tests/Fixtures/Modern/TestGroupedBoard.php @@ -33,6 +33,10 @@ class TestGroupedBoard extends BoardPage public bool $boundHaving = false; + public string $orderShape = 'none'; + + public int $subqueryUserId = 0; + public array $authorizedLanes = []; public function getEloquentQuery(): Builder @@ -43,7 +47,29 @@ public function getEloquentQuery(): Builder $query->groupByRaw('tasks.id, ?', [1])->havingRaw('count(*) > ?', [0]); } - return $query; + return match ($this->orderShape) { + 'title_desc' => $query->orderBy('title', 'desc'), + 'hours_title' => $query->orderBy('estimated_hours', 'desc')->orderBy('title'), + 'bound_raw' => $query + ->select('tasks.*') + ->selectRaw('? as picked', ['picked']) + ->where('tasks.title', '<>', 'Excluded') + ->orderByRaw('case when tasks.title = ? then 0 else 1 end', ['Gamma']), + 'bound_subquery' => $query + ->select('tasks.*') + ->selectRaw('? as picked', ['picked']) + ->where('tasks.title', '<>', 'Excluded') + ->orderBy( + DB::table('task_user') + ->selectRaw('count(*)') + ->whereColumn('task_user.task_id', 'tasks.id') + ->where('task_user.user_id', '<>', $this->subqueryUserId), + 'desc', + ), + 'expression' => $query->orderBy(DB::raw('length(tasks.title)'), 'desc'), + 'alias' => $query->withCount('assignees')->orderBy('assignees_count', 'desc'), + default => $query, + }; } public function board(Board $board): Board diff --git a/tests/Modern/Feature/GroupingTest.php b/tests/Modern/Feature/GroupingTest.php index 1d35a306a..be79b80b3 100644 --- a/tests/Modern/Feature/GroupingTest.php +++ b/tests/Modern/Feature/GroupingTest.php @@ -2,6 +2,7 @@ declare(strict_types=1); +use Illuminate\Database\Eloquent\Builder; use Illuminate\Support\Facades\DB; use Livewire\Livewire; use Relaticle\Flowforge\Exceptions\CardMoveRejectedException; @@ -504,3 +505,141 @@ function cellTitles(array $laneData, string $laneId, string $columnId): array 'medium' => [[]], ]); }); + +function laneCellQuery(string $board, array $props, string $grouping, int $limit): Builder +{ + $instance = Livewire::test($board, $props)->instance()->getBoard(); + $lane = $instance->getLanes($instance->getGrouping($grouping))[0]; + + return (fn () => $this->getLaneRecordsQuery($lane, $limit))->call($instance); +} + +function laneCellTitles(string $board, array $props, int $limit = 10, string $grouping = 'priority'): array +{ + return laneCellQuery($board, $props, $grouping, $limit)->get()->pluck('title')->all(); +} + +test('a lane query with no board order keeps its exact SQL and bindings', function () { + groupedTask('One', 'todo', '1', '65535.0000000000'); + + $plain = laneCellQuery(TestGroupedBoard::class, [], 'priority', 5); + $withCount = laneCellQuery(TestCastGroupedBoard::class, [], 'priority', 5); + + expect($plain->toSql())->toBe('select * from (select "tasks".*, row_number() over (partition by "status" order by "tasks"."order_position", "tasks"."id") as flowforge_cell_row, count(*) over (partition by "status") as flowforge_cell_total from "tasks" where "priority" = ?) as "tasks" where "flowforge_cell_row" <= ? order by "flowforge_cell_row" asc') + ->and($plain->getBindings())->toBe(['1', 5]) + ->and($withCount->toSql())->toBe('select * from (select "tasks".*, (select count(*) from "users" inner join "task_user" on "users"."id" = "task_user"."user_id" where "tasks"."id" = "task_user"."task_id") as "assignees_count", row_number() over (partition by "status" order by "tasks"."order_position", "tasks"."id") as flowforge_cell_row, count(*) over (partition by "status") as flowforge_cell_total from "tasks" where "priority" = ?) as "tasks" where "flowforge_cell_row" <= ? order by "flowforge_cell_row" asc') + ->and($withCount->getBindings())->toBe(['1', 5]); +})->group('pgsql'); + +test('lane cells follow the order of the board query', function () { + groupedTask('Alpha', 'todo', 'low', '65535.0000000000'); + groupedTask('Charlie', 'todo', 'low', '131070.0000000000'); + groupedTask('Bravo', 'todo', 'low', '196605.0000000000'); + + expect(laneCellTitles(TestGroupedBoard::class, ['orderShape' => 'title_desc']))->toBe(['Charlie', 'Bravo', 'Alpha']); +})->group('pgsql'); + +test('lane cells break ties in the board query order by position', function () { + $first = groupedTask('Same', 'todo', 'low', '65535.0000000000'); + $zed = groupedTask('Zed', 'todo', 'low', '98302.0000000000'); + $second = groupedTask('Same', 'todo', 'low', '131070.0000000000'); + + $records = laneCellQuery(TestGroupedBoard::class, ['orderShape' => 'title_desc'], 'priority', 10)->get(); + + expect($records->pluck('id')->all())->toBe([$zed->id, $first->id, $second->id]); +})->group('pgsql'); + +test('lane cells honour several orders on the board query', function () { + groupedTask('Low hours b', 'todo', 'low', '65535.0000000000')->update(['estimated_hours' => 1]); + groupedTask('High hours b', 'todo', 'low', '131070.0000000000')->update(['estimated_hours' => 5]); + groupedTask('High hours a', 'todo', 'low', '196605.0000000000')->update(['estimated_hours' => 5]); + + expect(laneCellTitles(TestGroupedBoard::class, ['orderShape' => 'hours_title'])) + ->toBe(['High hours a', 'High hours b', 'Low hours b']); +})->group('pgsql'); + +test('the cell limit keeps the top cards by the board query order and the total stays full', function () { + groupedTask('Alpha', 'todo', 'low', '65535.0000000000'); + groupedTask('Bravo', 'todo', 'low', '131070.0000000000'); + groupedTask('Charlie', 'todo', 'low', '196605.0000000000'); + groupedTask('Delta', 'todo', 'low', '262140.0000000000'); + + $board = Livewire::test(TestGroupedBoard::class, ['cardsPerCell' => 2, 'orderShape' => 'title_desc'])->instance()->getBoard(); + $cell = $board->getLaneViewData($board->getGrouping('priority'), 10, [])['lanes'][0]['cells']['todo']; + + expect(array_column($cell['items'], 'title'))->toBe(['Delta', 'Charlie']) + ->and($cell['total'])->toBe(4); +})->group('pgsql'); + +test('each cell orders its own cards', function () { + groupedTask('Alpha todo', 'todo', 'low', '65535.0000000000'); + groupedTask('Zulu todo', 'todo', 'low', '131070.0000000000'); + groupedTask('Alpha doing', 'in_progress', 'low', '65535.0000000000'); + groupedTask('Zulu doing', 'in_progress', 'low', '131070.0000000000'); + + $board = Livewire::test(TestGroupedBoard::class, ['cardsPerCell' => 1, 'orderShape' => 'title_desc'])->instance()->getBoard(); + $data = $board->getLaneViewData($board->getGrouping('priority'), 10, []); + + expect(cellTitles($data, 'low', 'todo'))->toBe(['Zulu todo']) + ->and(cellTitles($data, 'low', 'in_progress'))->toBe(['Zulu doing']); +})->group('pgsql'); + +test('an order carrying a binding lands beside the select and where bindings', function () { + groupedTask('Alpha', 'todo', 'low', '65535.0000000000'); + groupedTask('Gamma', 'todo', 'low', '131070.0000000000'); + groupedTask('Beta', 'todo', 'low', '196605.0000000000'); + groupedTask('Excluded', 'todo', 'low', '262140.0000000000'); + + $records = laneCellQuery(TestGroupedBoard::class, ['orderShape' => 'bound_raw'], 'priority', 10)->get(); + + expect($records->pluck('title')->all())->toBe(['Gamma', 'Alpha', 'Beta']) + ->and($records->pluck('picked')->unique()->all())->toBe(['picked']); +})->group('pgsql'); + +test('a subquery order keeps its bindings in place', function () { + $emma = User::factory()->create(); + $marcus = User::factory()->create(); + $third = User::factory()->create(); + groupedTask('One', 'todo', 'low', '65535.0000000000')->assignees()->attach($emma); + groupedTask('Two', 'todo', 'low', '131070.0000000000')->assignees()->attach($marcus); + groupedTask('Three', 'todo', 'low', '196605.0000000000')->assignees()->attach([$marcus->id, $third->id]); + groupedTask('Four', 'todo', 'low', '262140.0000000000'); + groupedTask('Excluded', 'todo', 'low', '327675.0000000000'); + + $records = laneCellQuery(TestGroupedBoard::class, ['orderShape' => 'bound_subquery', 'subqueryUserId' => $emma->id], 'priority', 10)->get(); + + expect($records->pluck('title')->all())->toBe(['Three', 'Two', 'One', 'Four']) + ->and($records->pluck('picked')->unique()->all())->toBe(['picked']); +})->group('pgsql'); + +test('an order on an expression is honoured', function () { + groupedTask('Ab', 'todo', 'low', '65535.0000000000'); + groupedTask('Abcd', 'todo', 'low', '131070.0000000000'); + groupedTask('Abc', 'todo', 'low', '196605.0000000000'); + + expect(laneCellTitles(TestGroupedBoard::class, ['orderShape' => 'expression']))->toBe(['Abcd', 'Abc', 'Ab']); +})->group('pgsql'); + +test('an order on a selected alias falls back to position order', function () { + $emma = User::factory()->create(); + groupedTask('First', 'todo', 'low', '65535.0000000000'); + groupedTask('Second', 'todo', 'low', '131070.0000000000')->assignees()->attach($emma); + + expect(laneCellTitles(TestGroupedBoard::class, ['orderShape' => 'alias']))->toBe(['First', 'Second']); +})->group('pgsql'); + +test('a distinct board query honours an order on a selected column of its own table', function () { + $emma = User::factory()->create(); + groupedTask('Alpha', 'todo', '1', '65535.0000000000')->assignees()->attach($emma); + groupedTask('Bravo', 'todo', '1', '131070.0000000000')->assignees()->attach($emma); + + expect(laneCellTitles(TestCastGroupedBoard::class, ['distinctJoin' => true, 'orderShape' => 'title_desc']))->toBe(['Bravo', 'Alpha']); +}); + +test('a distinct board query falls back to position order for an order its wrapper cannot read', function (string $shape) { + $emma = User::factory()->create(); + groupedTask('Alpha', 'todo', '1', '65535.0000000000')->assignees()->attach($emma); + groupedTask('Bravo', 'todo', '1', '131070.0000000000')->assignees()->attach($emma); + + expect(laneCellTitles(TestCastGroupedBoard::class, ['distinctJoin' => true, 'orderShape' => $shape]))->toBe(['Alpha', 'Bravo']); +})->with(['raw', 'unselected']); From 99b6dec1c4bf66a822ffb6d4d084a5a1e840d716 Mon Sep 17 00:00:00 2001 From: Manuk Date: Fri, 13 Nov 2026 03:08:05 +0400 Subject: [PATCH 2/3] fix: qualify bare lane order columns and detect every select alias --- docs/content/2.essentials/6.swimlanes.md | 6 +- src/Concerns/HasBoardGroupings.php | 79 +++++++++++++++++++--- tests/Fixtures/Modern/TestGroupedBoard.php | 16 +++++ tests/Modern/Feature/GroupingTest.php | 68 +++++++++++++++++-- 4 files changed, 155 insertions(+), 14 deletions(-) diff --git a/docs/content/2.essentials/6.swimlanes.md b/docs/content/2.essentials/6.swimlanes.md index 916792d7d..7f1b4039c 100644 --- a/docs/content/2.essentials/6.swimlanes.md +++ b/docs/content/2.essentials/6.swimlanes.md @@ -82,7 +82,11 @@ The header `+` from `createCardAction()` creates a card without knowing the lane ## Card order -Cells order their cards by the board query's own `orderBy()` calls first, then by position, the same as columns. A board query with `distinct()` honours only plain `orderBy()` columns of the model's own table that its select list includes, and falls back to position order for any other order. +Cells order their cards by the board query's own `orderBy()` calls first, then by position, the same as columns. A bare column name resolves against the model's own table. + +Lanes fall back to position order for the whole query when an order cannot be placed in the ranking: a bare name that is not a column of the model's table (a selected alias such as a `withCount` column), an `inOrderOf()` order, or a raw or expression order that uses a selected alias by name. A raw order that only calls a function with an alias's name, such as `count(*)`, is honoured. A board query with `distinct()` honours only plain `orderBy()` columns of the model's own table that its select list includes, and falls back for any other order. + +While the board query carries an order, a card dragged within a cell is written a position between neighbours that are not in position order. Refuse or ignore reorders inside a cell while the board sorts, the same as for flat columns. ## Limits and collapsed columns diff --git a/src/Concerns/HasBoardGroupings.php b/src/Concerns/HasBoardGroupings.php index c43750ae3..4dec17044 100644 --- a/src/Concerns/HasBoardGroupings.php +++ b/src/Concerns/HasBoardGroupings.php @@ -160,10 +160,6 @@ protected function compileBoardOrders(QueryBuilder $inner, Model $model, array $ $grammar = $inner->getGrammar(); $table = $model->getTable(); $columns = array_filter(array_map($grammar->getValue(...), $inner->columns ?? []), is_string(...)); - $aliases = array_filter(array_map( - fn (string $column): ?string => preg_match('/\sas\s+\W?([\w$]+)\W?\s*$/i', $column, $match) ? $match[1] : null, - $columns, - )); $selectsOwnColumns = array_intersect(['*', "{$table}.*"], $columns) !== []; $compiled = []; @@ -186,15 +182,24 @@ protected function compileBoardOrders(QueryBuilder $inner, Model $model, array $ continue; } + if (is_string($column) && ! isset($order['sql'])) { + $isBare = ! str_contains($column, '.'); + + if ($isBare && ! $this->modelHasColumn($model, $column)) { + return ['', []]; + } + + $compiled[] = $grammar->wrap($isBare ? $model->qualifyColumn($column) : $column) . ' ' . $order['direction']; + + continue; + } + $sql = isset($order['sql']) ? $grammar->getValue($order['sql']) : $grammar->wrap($column) . ' ' . $order['direction']; - $readable = str_replace(['"', '`', '[', ']'], '', $sql); - foreach ($aliases as $alias) { - if (preg_match('/(?mentionsAlias($sql, $this->selectAliases($inner))) { + return ['', []]; } $compiled[] = $sql; @@ -203,6 +208,62 @@ protected function compileBoardOrders(QueryBuilder $inner, Model $model, array $ return [implode(', ', $compiled), $bindings]; } + /** + * @return array + */ + protected function selectAliases(QueryBuilder $query): array + { + $aliases = []; + + foreach ($query->columns ?? [] as $column) { + $items = ['']; + $depth = 0; + $quote = null; + + foreach (str_split((string) $query->getGrammar()->getValue($column)) as $char) { + if ($quote !== null) { + $quote = $char === $quote ? null : $quote; + } elseif (in_array($char, ["'", '"', '`'], true)) { + $quote = $char; + } elseif ($char === '(' || $char === ')') { + $depth += $char === '(' ? 1 : -1; + } elseif ($char === ',' && $depth === 0) { + $items[] = ''; + + continue; + } + + $items[array_key_last($items)] .= $char; + } + + foreach ($items as $item) { + if (preg_match('/\sas\s+(?:"((?:[^"]|"")+)"|`([^`]+)`|\[([^\]]+)\]|([\w$]+))\s*$|\)\s+([\w$]+)\s*$/i', $item, $match)) { + $aliases[] = array_values(array_filter(array_slice($match, 1), fn (string $part): bool => $part !== ''))[0]; + } + } + } + + return $aliases; + } + + /** + * @param array $aliases + */ + protected function mentionsAlias(string $sql, array $aliases): bool + { + $code = preg_replace("/'(?:[^']|'')*'/", "''", $sql) ?? $sql; + + foreach ($aliases as $alias) { + $name = preg_quote($alias, '/'); + + if (preg_match('/(?getColumnIdentifierAttribute(); diff --git a/tests/Fixtures/Modern/TestGroupedBoard.php b/tests/Fixtures/Modern/TestGroupedBoard.php index f665f3c4c..e9ea9be1a 100644 --- a/tests/Fixtures/Modern/TestGroupedBoard.php +++ b/tests/Fixtures/Modern/TestGroupedBoard.php @@ -68,6 +68,22 @@ public function getEloquentQuery(): Builder ), 'expression' => $query->orderBy(DB::raw('length(tasks.title)'), 'desc'), 'alias' => $query->withCount('assignees')->orderBy('assignees_count', 'desc'), + 'joined_latest' => $query->join('users', 'users.id', '=', 'tasks.created_by')->select('tasks.*')->latest(), + 'joined_same_name' => $query->join('task_labels', 'task_labels.task_id', '=', 'tasks.id')->select('tasks.*')->orderBy('id', 'desc'), + 'multi_alias' => $query->select('tasks.*')->selectRaw('length(tasks.title) as cnt, 1 as total')->orderBy('cnt', 'desc'), + 'multi_alias_raw' => $query->select('tasks.*')->selectRaw('length(tasks.title) as cnt, 1 as total')->orderByRaw('cnt desc'), + 'quoted_alias' => $query->select('tasks.*')->selectRaw('length(tasks.title) as "Total Hours"')->orderByRaw('"Total Hours" desc'), + 'function_named_like_alias' => $query + ->select('tasks.*') + ->selectRaw('(select count(*) from task_user where task_user.task_id = tasks.id) as count') + ->orderByRaw('(select count(*) from task_user where task_user.task_id = tasks.id) desc'), + 'literal_named_like_alias' => $query + ->select('tasks.*') + ->selectRaw('1 as picked') + ->orderByRaw("case when tasks.title = 'picked' then 0 else 1 end, tasks.title desc"), + 'from_sub' => $query + ->fromSub(Task::query()->select('tasks.*')->selectRaw('? as picked', ['picked']), 'tasks') + ->orderByRaw('case when tasks.title = ? then 0 else 1 end', ['Gamma']), default => $query, }; } diff --git a/tests/Modern/Feature/GroupingTest.php b/tests/Modern/Feature/GroupingTest.php index be79b80b3..b984ba9c6 100644 --- a/tests/Modern/Feature/GroupingTest.php +++ b/tests/Modern/Feature/GroupingTest.php @@ -540,13 +540,13 @@ function laneCellTitles(string $board, array $props, int $limit = 10, string $gr })->group('pgsql'); test('lane cells break ties in the board query order by position', function () { - $first = groupedTask('Same', 'todo', 'low', '65535.0000000000'); + $later = groupedTask('Same', 'todo', 'low', '131070.0000000000'); $zed = groupedTask('Zed', 'todo', 'low', '98302.0000000000'); - $second = groupedTask('Same', 'todo', 'low', '131070.0000000000'); + $earlier = groupedTask('Same', 'todo', 'low', '65535.0000000000'); $records = laneCellQuery(TestGroupedBoard::class, ['orderShape' => 'title_desc'], 'priority', 10)->get(); - expect($records->pluck('id')->all())->toBe([$zed->id, $first->id, $second->id]); + expect($records->pluck('id')->all())->toBe([$zed->id, $earlier->id, $later->id]); })->group('pgsql'); test('lane cells honour several orders on the board query', function () { @@ -638,8 +638,68 @@ function laneCellTitles(string $board, array $props, int $limit = 10, string $gr test('a distinct board query falls back to position order for an order its wrapper cannot read', function (string $shape) { $emma = User::factory()->create(); + $marcus = User::factory()->create(); groupedTask('Alpha', 'todo', '1', '65535.0000000000')->assignees()->attach($emma); - groupedTask('Bravo', 'todo', '1', '131070.0000000000')->assignees()->attach($emma); + groupedTask('Bravo', 'todo', '1', '131070.0000000000')->assignees()->attach($marcus); expect(laneCellTitles(TestCastGroupedBoard::class, ['distinctJoin' => true, 'orderShape' => $shape]))->toBe(['Alpha', 'Bravo']); })->with(['raw', 'unselected']); + +test('a joined board query ordered by latest orders lane cells newest first', function () { + $author = User::factory()->create(); + foreach (['Oldest' => '2024-01-01', 'Newest' => '2024-03-01', 'Middle' => '2024-02-01'] as $title => $day) { + $task = groupedTask($title, 'todo', 'low', (string) (65535 * (DB::table('tasks')->count() + 1)) . '.0000000000'); + DB::table('tasks')->where('id', $task->id)->update(['created_by' => $author->id, 'created_at' => $day . ' 00:00:00']); + } + + expect(laneCellTitles(TestGroupedBoard::class, ['orderShape' => 'joined_latest']))->toBe(['Newest', 'Middle', 'Oldest']); +})->group('pgsql'); + +test('a bare order column shared with a joined table resolves against the model table', function () { + $first = groupedTask('First', 'todo', 'low', '65535.0000000000'); + $second = groupedTask('Second', 'todo', 'low', '131070.0000000000'); + DB::table('task_labels')->insert([['task_id' => $first->id, 'label' => 'a'], ['task_id' => $second->id, 'label' => 'b']]); + + expect(laneCellTitles(TestGroupedBoard::class, ['orderShape' => 'joined_same_name']))->toBe(['Second', 'First']); +})->group('pgsql'); + +test('an order on one of several selected aliases falls back to position order', function (string $shape) { + groupedTask('Short', 'todo', 'low', '65535.0000000000'); + groupedTask('A longer title', 'todo', 'low', '131070.0000000000'); + + expect(laneCellTitles(TestGroupedBoard::class, ['orderShape' => $shape]))->toBe(['Short', 'A longer title']); +})->with(['multi_alias', 'multi_alias_raw'])->group('pgsql'); + +test('an order on a quoted alias with a space falls back to position order', function () { + groupedTask('Short', 'todo', 'low', '65535.0000000000'); + groupedTask('A longer title', 'todo', 'low', '131070.0000000000'); + + expect(laneCellTitles(TestGroupedBoard::class, ['orderShape' => 'quoted_alias']))->toBe(['Short', 'A longer title']); +})->group('pgsql'); + +test('a raw order calling a function named like a selected alias is honoured', function () { + $emma = User::factory()->create(); + groupedTask('Unassigned', 'todo', 'low', '65535.0000000000'); + groupedTask('Assigned', 'todo', 'low', '131070.0000000000')->assignees()->attach($emma); + + expect(laneCellTitles(TestGroupedBoard::class, ['orderShape' => 'function_named_like_alias']))->toBe(['Assigned', 'Unassigned']); +})->group('pgsql'); + +test('a raw order with a string literal equal to a selected alias is honoured', function () { + groupedTask('Alpha', 'todo', 'low', '65535.0000000000'); + groupedTask('Zulu', 'todo', 'low', '131070.0000000000'); + groupedTask('picked', 'todo', 'low', '196605.0000000000'); + + expect(laneCellTitles(TestGroupedBoard::class, ['orderShape' => 'literal_named_like_alias']))->toBe(['picked', 'Zulu', 'Alpha']); +})->group('pgsql'); + +test('a from-bucket binding and an order binding stay aligned', function () { + groupedTask('Alpha', 'todo', 'low', '65535.0000000000'); + groupedTask('Gamma', 'todo', 'low', '131070.0000000000'); + groupedTask('Beta', 'todo', 'low', '196605.0000000000'); + + $records = laneCellQuery(TestGroupedBoard::class, ['orderShape' => 'from_sub'], 'priority', 10)->get(); + + expect($records->pluck('title')->all())->toBe(['Gamma', 'Alpha', 'Beta']) + ->and($records->pluck('picked')->unique()->all())->toBe(['picked']); +})->group('pgsql'); From 8246dafcfde619ed9f6fc309cc496ea84496e698 Mon Sep 17 00:00:00 2001 From: Manuk Date: Fri, 13 Nov 2026 03:19:48 +0400 Subject: [PATCH 3/3] fix: fall back when a lane order names a shadowed alias --- docs/content/2.essentials/6.swimlanes.md | 2 +- src/Concerns/HasBoardGroupings.php | 2 +- tests/Fixtures/Modern/TestGroupedBoard.php | 1 + tests/Modern/Feature/GroupingTest.php | 7 +++++++ 4 files changed, 10 insertions(+), 2 deletions(-) diff --git a/docs/content/2.essentials/6.swimlanes.md b/docs/content/2.essentials/6.swimlanes.md index 7f1b4039c..838f0f3b8 100644 --- a/docs/content/2.essentials/6.swimlanes.md +++ b/docs/content/2.essentials/6.swimlanes.md @@ -84,7 +84,7 @@ The header `+` from `createCardAction()` creates a card without knowing the lane Cells order their cards by the board query's own `orderBy()` calls first, then by position, the same as columns. A bare column name resolves against the model's own table. -Lanes fall back to position order for the whole query when an order cannot be placed in the ranking: a bare name that is not a column of the model's table (a selected alias such as a `withCount` column), an `inOrderOf()` order, or a raw or expression order that uses a selected alias by name. A raw order that only calls a function with an alias's name, such as `count(*)`, is honoured. A board query with `distinct()` honours only plain `orderBy()` columns of the model's own table that its select list includes, and falls back for any other order. +Lanes fall back to position order for the whole query when an order cannot be placed in the ranking: a bare name that is not a column of the model's table (a selected alias such as a `withCount` column) or that a selected alias shadows, an `inOrderOf()` order, or a raw or expression order that uses a selected alias by name. A raw order that only calls a function with an alias's name, such as `count(*)`, is honoured. A board query with `distinct()` honours only plain `orderBy()` columns of the model's own table that its select list includes, and falls back for any other order. While the board query carries an order, a card dragged within a cell is written a position between neighbours that are not in position order. Refuse or ignore reorders inside a cell while the board sorts, the same as for flat columns. diff --git a/src/Concerns/HasBoardGroupings.php b/src/Concerns/HasBoardGroupings.php index 4dec17044..1f983bebc 100644 --- a/src/Concerns/HasBoardGroupings.php +++ b/src/Concerns/HasBoardGroupings.php @@ -185,7 +185,7 @@ protected function compileBoardOrders(QueryBuilder $inner, Model $model, array $ if (is_string($column) && ! isset($order['sql'])) { $isBare = ! str_contains($column, '.'); - if ($isBare && ! $this->modelHasColumn($model, $column)) { + if ($isBare && (! $this->modelHasColumn($model, $column) || in_array($column, $this->selectAliases($inner), true))) { return ['', []]; } diff --git a/tests/Fixtures/Modern/TestGroupedBoard.php b/tests/Fixtures/Modern/TestGroupedBoard.php index e9ea9be1a..e1bd8ee9f 100644 --- a/tests/Fixtures/Modern/TestGroupedBoard.php +++ b/tests/Fixtures/Modern/TestGroupedBoard.php @@ -72,6 +72,7 @@ public function getEloquentQuery(): Builder 'joined_same_name' => $query->join('task_labels', 'task_labels.task_id', '=', 'tasks.id')->select('tasks.*')->orderBy('id', 'desc'), 'multi_alias' => $query->select('tasks.*')->selectRaw('length(tasks.title) as cnt, 1 as total')->orderBy('cnt', 'desc'), 'multi_alias_raw' => $query->select('tasks.*')->selectRaw('length(tasks.title) as cnt, 1 as total')->orderByRaw('cnt desc'), + 'shadowed_alias' => $query->select('tasks.id', 'tasks.status', 'tasks.priority', 'tasks.order_position')->selectRaw('lower(tasks.title) as title')->orderBy('title', 'desc'), 'quoted_alias' => $query->select('tasks.*')->selectRaw('length(tasks.title) as "Total Hours"')->orderByRaw('"Total Hours" desc'), 'function_named_like_alias' => $query ->select('tasks.*') diff --git a/tests/Modern/Feature/GroupingTest.php b/tests/Modern/Feature/GroupingTest.php index b984ba9c6..4f3c3bb01 100644 --- a/tests/Modern/Feature/GroupingTest.php +++ b/tests/Modern/Feature/GroupingTest.php @@ -703,3 +703,10 @@ function laneCellTitles(string $board, array $props, int $limit = 10, string $gr expect($records->pluck('title')->all())->toBe(['Gamma', 'Alpha', 'Beta']) ->and($records->pluck('picked')->unique()->all())->toBe(['picked']); })->group('pgsql'); + +test('a bare order column shadowed by a selected alias falls back to position order', function () { + groupedTask('Alpha', 'todo', 'low', '65535.0000000000'); + groupedTask('Bravo', 'todo', 'low', '131070.0000000000'); + + expect(laneCellTitles(TestGroupedBoard::class, ['orderShape' => 'shadowed_alias']))->toBe(['alpha', 'bravo']); +})->group('pgsql');