Add per-project card statuses and a kanban board

Statuses
- Migration 006: card_statuses table (project-scoped) and cards.status_id, a
  nullable FK with ON DELETE SET NULL. Every new project is seeded with
  "To do" / "Doing" / "Done"; GET /api/projects/{id}/statuses lists them.
- New cards have no status -- they sit in an "inbox" until moved.

Project view
- Full-width and tabbed: "All tasks" (a flat list, sorted by name
  case-insensitively) and "Kanban" (Inbox plus one column per status).
- Drag a card within or between columns to reorder / restatus; the Inbox
  column has its own name + Add form.

Ordering
- Migration 007: `position` is now a dense 0..n-1 rank within a
  (project_id, status_id) column, not a project-wide order. New composite
  index idx_cards_project_status_position; existing rows re-ranked.
- PUT /api/projects/{id}/cards/order takes { status_id, card_ids } and sets one
  column's contents and order, re-parenting moved-in cards and re-packing their
  source column in a single transaction. PATCH status_id appends the card to the
  end of the destination column.

58 phpunit tests pass; the frontend type-checks and builds.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-09-04 13:37:17 +01:00
co-authored by Claude Sonnet 5
parent d9db4a3a30
commit c47c800d01
21 changed files with 1389 additions and 239 deletions
+43 -17
View File
@@ -6,6 +6,7 @@ namespace App\Http\Controllers;
use App\Exception\ApiException;
use App\Repository\CardRepository;
use App\Repository\CardStatusRepository;
use App\Repository\ProjectRepository;
use App\Support\Validator;
use Psr\Http\Message\ResponseInterface as Response;
@@ -22,6 +23,7 @@ final class CardController extends Controller
public function __construct(
private readonly ProjectRepository $projects,
private readonly CardRepository $cards,
private readonly CardStatusRepository $statuses,
) {
}
@@ -82,11 +84,17 @@ final class CardController extends Controller
if ($validator->has('complete')) {
$fields['complete'] = $validator->optionalBool('complete');
}
if ($validator->has('position')) {
$fields['position'] = $validator->optionalInt('position', 0);
if ($validator->has('status_id')) {
$statusId = $validator->nullableInt('status_id', 1);
if ($statusId !== null && !$validator->failed()
&& $this->statuses->findInProject($statusId, $projectId) === null
) {
$validator->add('status_id', 'That status does not belong to this project.');
}
$fields['status_id'] = $statusId;
}
if ($fields === [] && !$validator->failed()) {
$validator->add('text', 'Provide at least one of: text, complete, position.');
$validator->add('text', 'Provide at least one of: text, complete, status_id.');
}
$validator->assert();
@@ -111,29 +119,45 @@ final class CardController extends Controller
/**
* PUT /api/projects/{projectId}/cards/order
*
* Body: { "card_ids": [3, 1, 2] } — every card in the project, exactly once,
* in the desired order. Positions are rewritten to 0..n-1.
* Sets the contents and order of one status column.
*
* Body: { "status_id": 2 | null, "card_ids": [3, 1, 2] } — the cards that
* should make up that column, in order. Positions are rewritten to 0..n-1;
* any card moved in from another column is re-parented and its old column
* re-packed. `status_id` is omitted or null for the inbox.
*/
public function reorder(Request $request, Response $response, array $args): Response
{
$projectId = $this->requireOwnedProjectId($request, $args);
$body = $this->body($request);
$order = $this->body($request)['card_ids'] ?? null;
$statusId = null;
if (array_key_exists('status_id', $body) && $body['status_id'] !== null) {
if (!is_int($body['status_id'])) {
throw new ApiException('status_id must be a status ID or null.', 422);
}
$statusId = $body['status_id'];
if ($this->statuses->findInProject($statusId, $projectId) === null) {
throw new ApiException('That status does not belong to this project.', 422);
}
}
$order = $body['card_ids'] ?? null;
if (!is_array($order) || array_filter($order, static fn ($id) => !is_int($id)) !== []) {
throw new ApiException('card_ids must be an array of card IDs.', 422);
}
/** @var int[] $order */
$expected = $this->cards->idsForProject($projectId);
$given = $order;
sort($given);
sort($expected);
if ($given !== $expected) {
throw new ApiException('card_ids must contain every card in the project exactly once.', 422);
if (count($order) !== count(array_unique($order))) {
throw new ApiException('card_ids must not contain duplicates.', 422);
}
if (array_diff($order, $this->cards->idsForProject($projectId)) !== []) {
throw new ApiException('Every card_id must be a card in this project.', 422);
}
if (array_diff($this->cards->idsInColumn($projectId, $statusId), $order) !== []) {
throw new ApiException('card_ids must include every card already in this column.', 422);
}
$cards = $this->cards->reorder($projectId, $order);
$cards = $this->cards->orderColumn($projectId, $statusId, $order);
$this->projects->touch($projectId);
return $this->json($response, ['cards' => array_map($this->present(...), $cards)]);
@@ -155,7 +179,7 @@ final class CardController extends Controller
/**
* @param array<string, string> $args
* @return array{id: int, project_id: int, text: string, complete: bool, position: int, created_at: string, updated_at: string}
* @return array{id: int, project_id: int, text: string, complete: bool, position: int, status_id: int|null, status: array{id: int, name: string}|null, created_at: string, updated_at: string}
*/
private function requireCard(int $projectId, array $args): array
{
@@ -169,7 +193,7 @@ final class CardController extends Controller
}
/**
* @param array{id: int, project_id: int, text: string, complete: bool, position: int, created_at: string, updated_at: string} $card
* @param array{id: int, project_id: int, text: string, complete: bool, position: int, status_id: int|null, status: array{id: int, name: string}|null, created_at: string, updated_at: string} $card
* @return array<string, mixed>
*/
private function present(array $card): array
@@ -180,6 +204,8 @@ final class CardController extends Controller
'text' => $card['text'],
'complete' => $card['complete'],
'position' => $card['position'],
'status_id' => $card['status_id'],
'status' => $card['status'],
'created_at' => $card['created_at'],
'updated_at' => $card['updated_at'],
];
@@ -0,0 +1,64 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use App\Exception\ApiException;
use App\Repository\CardStatusRepository;
use App\Repository\ProjectRepository;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
/**
* Read-only listing of a project's card statuses. Statuses are seeded when the
* project is created; there is no create/update/delete yet.
*/
final class CardStatusController extends Controller
{
public function __construct(
private readonly ProjectRepository $projects,
private readonly CardStatusRepository $statuses,
) {
}
/**
* GET /api/projects/{projectId}/statuses
*/
public function index(Request $request, Response $response, array $args): Response
{
$projectId = $this->requireOwnedProjectId($request, $args);
return $this->json($response, [
'statuses' => array_map($this->present(...), $this->statuses->allForProject($projectId)),
]);
}
/**
* @param array<string, string> $args
*/
private function requireOwnedProjectId(Request $request, array $args): int
{
$project = $this->projects->findOwnedBy((int) $args['projectId'], $this->user($request)['id']);
if ($project === null) {
throw new ApiException('Project not found.', 404);
}
return $project['id'];
}
/**
* @param array{id: int, project_id: int, name: string, position: int, created_at: string, updated_at: string} $status
* @return array<string, mixed>
*/
private function present(array $status): array
{
return [
'id' => $status['id'],
'project_id' => $status['project_id'],
'name' => $status['name'],
'position' => $status['position'],
];
}
}
+6 -2
View File
@@ -5,6 +5,7 @@ declare(strict_types=1);
namespace App\Http\Controllers;
use App\Exception\ApiException;
use App\Repository\CardStatusRepository;
use App\Repository\ProjectRepository;
use App\Support\Validator;
use Psr\Http\Message\ResponseInterface as Response;
@@ -20,8 +21,10 @@ final class ProjectController extends Controller
private const DESCRIPTION_MAX = 2000;
private const MAX_PROJECTS_PER_OWNER = 100;
public function __construct(private readonly ProjectRepository $projects)
{
public function __construct(
private readonly ProjectRepository $projects,
private readonly CardStatusRepository $statuses,
) {
}
/**
@@ -54,6 +57,7 @@ final class ProjectController extends Controller
}
$project = $this->projects->create($ownerId, $title, $description);
$this->statuses->seedDefaults($project['id']);
return $this->json($response, ['project' => $this->present($project)], 201);
}
+169 -28
View File
@@ -9,24 +9,41 @@ use PDO;
/**
* Data access for the `cards` table.
*
* `position` is a dense 0..n-1 rank *within a column* — the cards sharing a
* (project_id, status_id). The inbox is the column where status_id IS NULL.
*
* @phpstan-type CardStatus array{id: int, name: string}
* @phpstan-type CardRow array{
* id: int, project_id: int, text: string, complete: bool, position: int,
* status_id: int|null, status: CardStatus|null,
* created_at: string, updated_at: string
* }
*/
final class CardRepository
{
private const SELECT = <<<'SQL'
SELECT c.id, c.project_id, c.text, c.complete, c.position, c.status_id,
c.created_at, c.updated_at,
s.name AS status_name
FROM cards c
LEFT JOIN card_statuses s ON s.id = c.status_id
SQL;
public function __construct(private readonly PDO $pdo)
{
}
/**
* Every card in the project, grouped by column (inbox first) and ordered by
* position within each. Consumers that want a different order (e.g. the
* alphabetical "all tasks" list) re-sort client-side.
*
* @return CardRow[]
*/
public function allForProject(int $projectId): array
{
$stmt = $this->pdo->prepare(
'SELECT * FROM cards WHERE project_id = :project ORDER BY position ASC, id ASC'
self::SELECT . ' WHERE c.project_id = :project ORDER BY c.status_id, c.position ASC, c.id ASC'
);
$stmt->execute(['project' => $projectId]);
@@ -38,7 +55,7 @@ final class CardRepository
*/
public function findInProject(int $id, int $projectId): ?array
{
$stmt = $this->pdo->prepare('SELECT * FROM cards WHERE id = :id AND project_id = :project');
$stmt = $this->pdo->prepare(self::SELECT . ' WHERE c.id = :id AND c.project_id = :project');
$stmt->execute(['id' => $id, 'project' => $projectId]);
$row = $stmt->fetch();
@@ -51,7 +68,8 @@ final class CardRepository
*/
public function create(int $projectId, string $text, bool $complete, ?int $position): array
{
$position ??= $this->nextPosition($projectId);
// A new card has no status — it goes to the end of the inbox column.
$position ??= $this->nextPositionInColumn($projectId, null);
$stmt = $this->pdo->prepare(
'INSERT INTO cards (project_id, text, complete, position)
@@ -71,12 +89,22 @@ final class CardRepository
}
/**
* @param array{text?: string, complete?: bool, position?: int} $fields
* Update simple fields, and/or move the card to another column. A status
* change drops the card at the end of the destination column and re-packs
* the one it left. Precise slotting within a column is done via orderColumn().
*
* @param array{text?: string, complete?: bool, status_id?: int|null} $fields
* @return CardRow
*/
public function update(int $id, int $projectId, array $fields): array
{
$sets = ['updated_at = ' . "strftime('%Y-%m-%dT%H:%M:%SZ', 'now')"];
/** @var CardRow $card */
$card = $this->findInProject($id, $projectId);
$movesColumn = array_key_exists('status_id', $fields) && $fields['status_id'] !== $card['status_id'];
$sourceColumn = $card['status_id'];
$sets = ['updated_at = ' . $this->nowExpr()];
$params = ['id' => $id];
if (array_key_exists('text', $fields)) {
@@ -87,18 +115,40 @@ final class CardRepository
$sets[] = 'complete = :complete';
$params['complete'] = $fields['complete'] ? 1 : 0;
}
if (array_key_exists('position', $fields)) {
if (array_key_exists('status_id', $fields)) {
$sets[] = 'status_id = :status_id';
$params['status_id'] = $fields['status_id'];
}
if ($movesColumn) {
$sets[] = 'position = :position';
$params['position'] = $fields['position'];
$params['position'] = $this->nextPositionInColumn($projectId, $fields['status_id']);
}
$stmt = $this->pdo->prepare('UPDATE cards SET ' . implode(', ', $sets) . ' WHERE id = :id');
$stmt->execute($params);
$sql = 'UPDATE cards SET ' . implode(', ', $sets) . ' WHERE id = :id';
/** @var CardRow $card */
$card = $this->findInProject($id, $projectId);
if (!$movesColumn) {
$this->pdo->prepare($sql)->execute($params);
return $card;
/** @var CardRow $updated */
$updated = $this->findInProject($id, $projectId);
return $updated;
}
$this->pdo->beginTransaction();
try {
$this->pdo->prepare($sql)->execute($params);
$this->repack($projectId, $sourceColumn);
$this->pdo->commit();
} catch (\Throwable $e) {
$this->pdo->rollBack();
throw $e;
}
/** @var CardRow $updated */
$updated = $this->findInProject($id, $projectId);
return $updated;
}
public function delete(int $id): void
@@ -107,39 +157,69 @@ final class CardRepository
}
/**
* IDs of every card in the project, in current position order.
* IDs of every card in the project.
*
* @return int[]
*/
public function idsForProject(int $projectId): array
{
$stmt = $this->pdo->prepare(
'SELECT id FROM cards WHERE project_id = :project ORDER BY position ASC, id ASC'
);
$stmt = $this->pdo->prepare('SELECT id FROM cards WHERE project_id = :project');
$stmt->execute(['project' => $projectId]);
return array_map(intval(...), $stmt->fetchAll(PDO::FETCH_COLUMN));
}
/**
* Assign positions 0..n-1 to the given cards in one transaction.
* IDs of the cards currently in one column, in position order.
*
* @param int[] $orderedIds every card id in the project, exactly once
* @return CardRow[] the project's cards in their new order
* @return int[]
*/
public function reorder(int $projectId, array $orderedIds): array
public function idsInColumn(int $projectId, ?int $statusId): array
{
[$match, $params] = $this->columnMatch($statusId);
$stmt = $this->pdo->prepare(
'UPDATE cards SET position = :position,
updated_at = ' . "strftime('%Y-%m-%dT%H:%M:%SZ', 'now')" . '
WHERE id = :id AND project_id = :project'
"SELECT id FROM cards WHERE project_id = :project AND {$match} ORDER BY position ASC, id ASC"
);
$stmt->execute(['project' => $projectId] + $params);
return array_map(intval(...), $stmt->fetchAll(PDO::FETCH_COLUMN));
}
/**
* Set the contents and order of one column. Every id in $orderedIds is moved
* into $statusId at positions 0..n-1; any other column those cards came from
* is re-packed. One transaction.
*
* @param int[] $orderedIds
* @return CardRow[] the project's cards, grouped by column
*/
public function orderColumn(int $projectId, ?int $statusId, array $orderedIds): array
{
$orderedIds = array_values($orderedIds);
$this->pdo->beginTransaction();
try {
foreach (array_values($orderedIds) as $position => $id) {
$stmt->execute(['position' => $position, 'id' => $id, 'project' => $projectId]);
$sourceColumns = $this->columnsOf($projectId, $orderedIds);
$place = $this->pdo->prepare(
'UPDATE cards SET status_id = :status, position = :position, updated_at = ' . $this->nowExpr() . '
WHERE id = :id AND project_id = :project'
);
foreach ($orderedIds as $position => $id) {
$place->execute([
'status' => $statusId,
'position' => $position,
'id' => $id,
'project' => $projectId,
]);
}
foreach ($sourceColumns as $source) {
if ($source !== $statusId) {
$this->repack($projectId, $source);
}
}
$this->pdo->commit();
} catch (\Throwable $e) {
$this->pdo->rollBack();
@@ -149,16 +229,70 @@ final class CardRepository
return $this->allForProject($projectId);
}
private function nextPosition(int $projectId): int
/**
* The distinct status_id values (columns) the given cards currently sit in.
*
* @param int[] $ids
* @return array<int, int|null>
*/
private function columnsOf(int $projectId, array $ids): array
{
if ($ids === []) {
return [];
}
$placeholders = implode(',', array_fill(0, count($ids), '?'));
$stmt = $this->pdo->prepare(
'SELECT COALESCE(MAX(position), -1) + 1 FROM cards WHERE project_id = :project'
"SELECT DISTINCT status_id FROM cards WHERE project_id = ? AND id IN ($placeholders)"
);
$stmt->execute(['project' => $projectId]);
$stmt->execute([$projectId, ...$ids]);
return array_map(
static fn ($value) => $value === null ? null : (int) $value,
$stmt->fetchAll(PDO::FETCH_COLUMN),
);
}
/** Rewrite one column's positions to a dense 0..n-1 in current order. */
private function repack(int $projectId, ?int $statusId): void
{
$ids = $this->idsInColumn($projectId, $statusId);
$update = $this->pdo->prepare('UPDATE cards SET position = :position WHERE id = :id');
foreach ($ids as $position => $id) {
$update->execute(['position' => $position, 'id' => $id]);
}
}
private function nextPositionInColumn(int $projectId, ?int $statusId): int
{
[$match, $params] = $this->columnMatch($statusId);
$stmt = $this->pdo->prepare(
"SELECT COALESCE(MAX(position), -1) + 1 FROM cards WHERE project_id = :project AND {$match}"
);
$stmt->execute(['project' => $projectId] + $params);
return (int) $stmt->fetchColumn();
}
/**
* A WHERE fragment matching one column, since SQLite needs `IS NULL` (not
* `= NULL`) for the inbox.
*
* @return array{0: string, 1: array<string, int>}
*/
private function columnMatch(?int $statusId): array
{
return $statusId === null
? ['status_id IS NULL', []]
: ['status_id = :status', ['status' => $statusId]];
}
private function nowExpr(): string
{
return "strftime('%Y-%m-%dT%H:%M:%SZ', 'now')";
}
/**
* @param array<string, mixed> $row
* @return CardRow
@@ -170,6 +304,13 @@ final class CardRepository
$row['complete'] = (bool) $row['complete'];
$row['position'] = (int) $row['position'];
$statusId = $row['status_id'] === null ? null : (int) $row['status_id'];
$row['status_id'] = $statusId;
$row['status'] = $statusId === null
? null
: ['id' => $statusId, 'name' => (string) $row['status_name']];
unset($row['status_name']);
/** @var CardRow $row */
return $row;
}
+79
View File
@@ -0,0 +1,79 @@
<?php
declare(strict_types=1);
namespace App\Repository;
use PDO;
/**
* Data access for the `card_statuses` table. Statuses belong to a single
* project. There is no CRUD yet — projects are seeded with a fixed set on
* creation and that is the only way rows appear.
*
* @phpstan-type CardStatusRow array{
* id: int, project_id: int, name: string, position: int,
* created_at: string, updated_at: string
* }
*/
final class CardStatusRepository
{
/** The status set created for every new project, in order. */
public const DEFAULTS = ['To do', 'Doing', 'Done'];
public function __construct(private readonly PDO $pdo)
{
}
/**
* @return CardStatusRow[]
*/
public function allForProject(int $projectId): array
{
$stmt = $this->pdo->prepare(
'SELECT * FROM card_statuses WHERE project_id = :project ORDER BY position ASC, id ASC'
);
$stmt->execute(['project' => $projectId]);
return array_map($this->cast(...), $stmt->fetchAll());
}
/**
* @return CardStatusRow|null
*/
public function findInProject(int $id, int $projectId): ?array
{
$stmt = $this->pdo->prepare('SELECT * FROM card_statuses WHERE id = :id AND project_id = :project');
$stmt->execute(['id' => $id, 'project' => $projectId]);
$row = $stmt->fetch();
return $row === false ? null : $this->cast($row);
}
/** Insert the default status set for a freshly created project. */
public function seedDefaults(int $projectId): void
{
$stmt = $this->pdo->prepare(
'INSERT INTO card_statuses (project_id, name, position) VALUES (:project, :name, :position)'
);
foreach (array_values(self::DEFAULTS) as $position => $name) {
$stmt->execute(['project' => $projectId, 'name' => $name, 'position' => $position]);
}
}
/**
* @param array<string, mixed> $row
* @return CardStatusRow
*/
private function cast(array $row): array
{
$row['id'] = (int) $row['id'];
$row['project_id'] = (int) $row['project_id'];
$row['position'] = (int) $row['position'];
/** @var CardStatusRow $row */
return $row;
}
}
+21
View File
@@ -90,6 +90,27 @@ final class Validator
return $value;
}
/**
* An integer (>= $min) or an explicit null. Only meaningful once has()
* has confirmed the field is present; a null return is a valid value.
*/
public function nullableInt(string $field, int $min): ?int
{
if (!$this->has($field) || $this->data[$field] === null) {
return null;
}
$value = $this->data[$field];
if (!is_int($value) || $value < $min) {
$this->errors[$field][] = ucfirst($field) . " must be an integer of at least {$min}, or null.";
return null;
}
return $value;
}
public function add(string $field, string $message): void
{
$this->errors[$field][] = $message;
+14 -3
View File
@@ -7,6 +7,7 @@ use App\Auth\JwtService;
use App\Auth\SessionPayload;
use App\Http\Controllers\AuthController;
use App\Http\Controllers\CardController;
use App\Http\Controllers\CardStatusController;
use App\Http\Controllers\EmailVerificationController;
use App\Http\Controllers\ProjectController;
use App\Http\JsonErrorHandler;
@@ -15,6 +16,7 @@ use App\Mail\LogMailer;
use App\Mail\Mailer;
use App\Mail\PhpMailerMailer;
use App\Repository\CardRepository;
use App\Repository\CardStatusRepository;
use App\Repository\EmailVerificationRepository;
use App\Repository\ProjectRepository;
use App\Repository\UserRepository;
@@ -43,6 +45,7 @@ $errorMiddleware->setDefaultErrorHandler(
$users = new UserRepository($database->pdo());
$projects = new ProjectRepository($database->pdo());
$cards = new CardRepository($database->pdo());
$cardStatuses = new CardStatusRepository($database->pdo());
$verificationTokens = new EmailVerificationRepository($database->pdo());
$jwt = new JwtService($config->jwtSecret, $config->jwtTtl);
$session = new SessionPayload($jwt, $verificationTokens);
@@ -55,8 +58,9 @@ $verifier = new EmailVerifier($verificationTokens, $users, $mailer, $config->app
$authController = new AuthController($users, $session, $verifier);
$emailController = new EmailVerificationController($users, $verificationTokens, $verifier, $session);
$projectController = new ProjectController($projects);
$cardController = new CardController($projects, $cards);
$projectController = new ProjectController($projects, $cardStatuses);
$cardController = new CardController($projects, $cards, $cardStatuses);
$cardStatusController = new CardStatusController($projects, $cardStatuses);
$authMiddleware = new AuthMiddleware($jwt, $users);
// --- Routes ---------------------------------------------------------------
@@ -66,6 +70,7 @@ $app->group('/api', function (RouteCollectorProxy $group) use (
$emailController,
$projectController,
$cardController,
$cardStatusController,
$authMiddleware,
) {
$group->get('/health', function (Request $request, Response $response): Response {
@@ -82,13 +87,19 @@ $app->group('/api', function (RouteCollectorProxy $group) use (
$group->post('/email/verification', [$emailController, 'resend'])->add($authMiddleware);
$group->post('/email/change', [$emailController, 'requestChange'])->add($authMiddleware);
$group->group('/projects', function (RouteCollectorProxy $projects) use ($projectController, $cardController) {
$group->group('/projects', function (RouteCollectorProxy $projects) use (
$projectController,
$cardController,
$cardStatusController,
) {
$projects->get('', [$projectController, 'index']);
$projects->post('', [$projectController, 'store']);
$projects->get('/{projectId:[0-9]+}', [$projectController, 'show']);
$projects->patch('/{projectId:[0-9]+}', [$projectController, 'update']);
$projects->delete('/{projectId:[0-9]+}', [$projectController, 'destroy']);
$projects->get('/{projectId:[0-9]+}/statuses', [$cardStatusController, 'index']);
$projects->get('/{projectId:[0-9]+}/cards', [$cardController, 'index']);
$projects->post('/{projectId:[0-9]+}/cards', [$cardController, 'store']);
$projects->put('/{projectId:[0-9]+}/cards/order', [$cardController, 'reorder']);