Archon/archon-ui-main/src/features/projects/tasks/hooks/tests/useTaskQueries.test.ts
DIY Smart Code c45842f0bb
feat: decouple task priority from task order (#652)
* feat: decouple task priority from task order

This implements a dedicated priority system that operates independently
from the existing task_order system, allowing users to set task priority
without affecting visual drag-and-drop positioning.

## Changes Made

### Database
- Add priority column to archon_tasks table with enum type (critical, high, medium, low)
- Create database migration with safe enum handling and data backfill
- Add proper indexing for performance

### Backend
- Update UpdateTaskRequest to include priority field
- Add priority validation in TaskService with enum checking
- Include priority field in task list responses and ETag generation
- Fix cache invalidation for priority updates

### Frontend
- Update TaskPriority type from "urgent" to "critical" for consistency
- Add changePriority method to useTaskActions hook
- Update TaskCard to use direct priority field instead of task_order conversion
- Update TaskEditModal priority form to use direct priority values
- Fix TaskPriorityComponent to use correct priority enum values
- Update buildTaskUpdates to include priority field changes
- Add priority field to Task interface as required field
- Update test fixtures to include priority field

## Key Features
-  Users can change task priority without affecting drag-and-drop order
-  Users can drag tasks to reorder without changing priority level
-  Priority persists correctly in database with dedicated column
-  All existing priority functionality continues working identically
-  Cache invalidation works properly for priority changes
-  Both TaskCard priority button and TaskEditModal priority work

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* feat: add priority column to complete_setup.sql for fresh installations

- Add task_priority enum type (low, medium, high, critical)
- Add priority column to archon_tasks table with default 'medium'
- Add index for priority column performance
- Add documentation comment for priority field

This ensures fresh installations include the priority system without
needing to run the separate migration.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* fix: include priority field in task creation payload

When creating new tasks via TaskEditModal, the buildCreateRequest function
was not including the priority field, causing new tasks to fall back to
the database default ('medium') instead of respecting the user's selected
priority in the modal.

Added priority: localTask.priority || 'medium' to ensure the user's
chosen priority is sent to the API during task creation.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* feat: make priority migration safe and idempotent

Replaced destructive DROP TYPE CASCADE with safe migration patterns:

- Use DO blocks with EXCEPTION handling for enum and column creation
- Prevent conflicts with complete_setup.sql for fresh installations
- Enhanced backfill logic to preserve user-modified priorities
- Only update tasks that haven't been modified (updated_at = created_at)
- Add comprehensive error handling with informative notices
- Migration can now be run multiple times safely

This ensures the migration works for both existing installations
(incremental migration) and fresh installations (complete_setup.sql)
without data loss or conflicts.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* feat: enforce NOT NULL constraint on priority column

Data integrity improvements:

Migration (add_priority_column_to_tasks.sql):
- Add column as nullable first with DEFAULT 'medium'
- Update any NULL values to 'medium'
- Set NOT NULL constraint to enforce application invariants
- Safe handling for existing columns with proper constraint checking

Complete Setup (complete_setup.sql):
- Priority column now DEFAULT 'medium' NOT NULL for fresh installations
- Ensures consistency between migration and fresh install paths

Both paths now enforce priority field as required, matching the
frontend Task interface where priority is a required field.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* feat: add priority support to task creation API

Complete priority support for task creation:

API Routes (projects_api.py):
- Add priority field to CreateTaskRequest Pydantic model
- Pass request.priority to TaskService.create_task call

Task Service (task_service.py):
- Add priority parameter to create_task method signature
- Add priority validation using existing validate_priority method
- Include priority field in database INSERT task_data
- Include priority field in API response task object

This ensures that new tasks created via TaskEditModal respect the
user's selected priority instead of falling back to database default.

Validation ensures only valid priority values (low, medium, high, critical)
are accepted and stored in the database.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* feat: implement clean slate priority migration (no backward compatibility)

Remove all task_order to priority mapping logic for true decoupling:

- All existing tasks get 'medium' priority (clean slate)
- No complex CASE logic or task_order relationships
- Users explicitly set priorities as needed after migration
- Truly independent priority and visual ordering systems
- Simpler, safer migration with no coupling logic

This approach prioritizes clean architecture over preserving
implied user intentions from the old coupled system.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor: rename TaskPriority.tsx to TaskPriorityComponent.tsx for consistency

- Renamed file to match the exported component name
- Updated import in index.ts barrel export
- Maintains consistency with other component naming patterns

---------

Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Rasmus Widing <rasmus.widing@gmail.com>
2025-09-17 13:44:25 +03:00

216 lines
6.3 KiB
TypeScript

import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { renderHook, waitFor } from "@testing-library/react";
import React from "react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { Task } from "../../types";
import { taskKeys, useCreateTask, useProjectTasks } from "../useTaskQueries";
// Mock the services
vi.mock("../../services", () => ({
taskService: {
getTasksByProject: vi.fn(),
createTask: vi.fn(),
updateTask: vi.fn(),
deleteTask: vi.fn(),
},
}));
// Create stable toast mock
const showToastMock = vi.fn();
// Mock the toast hook
vi.mock("../../../../ui/hooks/useToast", () => ({
useToast: () => ({
showToast: showToastMock,
}),
}));
// Mock smart polling
vi.mock("../../../../ui/hooks", () => ({
useSmartPolling: () => ({
refetchInterval: 5000,
isPaused: false,
}),
}));
// Test wrapper with QueryClient
const createWrapper = () => {
const queryClient = new QueryClient({
defaultOptions: {
queries: { retry: false },
mutations: { retry: false },
},
});
return ({ children }: { children: React.ReactNode }) =>
React.createElement(QueryClientProvider, { client: queryClient }, children);
};
describe("useTaskQueries", () => {
beforeEach(() => {
vi.clearAllMocks();
showToastMock.mockClear();
});
describe("taskKeys", () => {
it("should generate correct query keys", () => {
expect(taskKeys.all("project-123")).toEqual(["projects", "project-123", "tasks"]);
});
});
describe("useProjectTasks", () => {
it("should fetch tasks for a project", async () => {
const mockTasks: Task[] = [
{
id: "task-1",
project_id: "project-123",
title: "Test Task",
description: "Test Description",
status: "todo",
assignee: "User",
task_order: 100,
priority: "medium",
created_at: "2024-01-01T00:00:00Z",
updated_at: "2024-01-01T00:00:00Z",
},
];
const { taskService } = await import("../../services");
vi.mocked(taskService.getTasksByProject).mockResolvedValue(mockTasks);
const { result } = renderHook(() => useProjectTasks("project-123"), {
wrapper: createWrapper(),
});
await waitFor(() => {
expect(result.current.isSuccess).toBe(true);
expect(result.current.data).toEqual(mockTasks);
});
expect(taskService.getTasksByProject).toHaveBeenCalledWith("project-123");
});
it("should not fetch tasks when projectId is undefined", () => {
const { result } = renderHook(() => useProjectTasks(undefined), {
wrapper: createWrapper(),
});
expect(result.current.isLoading).toBe(false);
expect(result.current.isFetching).toBe(false);
expect(result.current.data).toBeUndefined();
});
it("should respect enabled flag", () => {
const { result } = renderHook(() => useProjectTasks("project-123", false), {
wrapper: createWrapper(),
});
expect(result.current.isLoading).toBe(false);
expect(result.current.isFetching).toBe(false);
expect(result.current.data).toBeUndefined();
});
});
describe("useCreateTask", () => {
it("should optimistically add task and replace with server response", async () => {
const newTask: Task = {
id: "real-task-id",
project_id: "project-123",
title: "New Task",
description: "New Description",
status: "todo",
assignee: "User",
task_order: 100,
priority: "medium",
created_at: "2024-01-01T00:00:00Z",
updated_at: "2024-01-01T00:00:00Z",
};
const { taskService } = await import("../../services");
vi.mocked(taskService.createTask).mockResolvedValue(newTask);
const wrapper = createWrapper();
const { result } = renderHook(() => useCreateTask(), { wrapper });
await result.current.mutateAsync({
project_id: "project-123",
title: "New Task",
description: "New Description",
status: "todo",
assignee: "User",
});
await waitFor(() => {
expect(result.current.isSuccess).toBe(true);
expect(taskService.createTask).toHaveBeenCalledWith({
project_id: "project-123",
title: "New Task",
description: "New Description",
status: "todo",
assignee: "User",
});
});
});
it("should provide default values for optional fields", async () => {
const newTask: Task = {
id: "real-task-id",
project_id: "project-123",
title: "Minimal Task",
description: "",
status: "todo",
assignee: "User",
task_order: 100,
priority: "medium",
created_at: "2024-01-01T00:00:00Z",
updated_at: "2024-01-01T00:00:00Z",
};
const { taskService } = await import("../../services");
vi.mocked(taskService.createTask).mockResolvedValue(newTask);
const wrapper = createWrapper();
const { result } = renderHook(() => useCreateTask(), { wrapper });
await result.current.mutateAsync({
project_id: "project-123",
title: "Minimal Task",
description: "",
});
await waitFor(() => {
expect(result.current.isSuccess).toBe(true);
});
// Verify the service was called with the minimal payload
// The service/backend handles providing defaults, not the hook
expect(taskService.createTask).toHaveBeenCalledWith({
project_id: "project-123",
title: "Minimal Task",
description: "",
});
});
it("should rollback on error", async () => {
const { taskService } = await import("../../services");
vi.mocked(taskService.createTask).mockRejectedValue(new Error("Network error"));
const wrapper = createWrapper();
const { result } = renderHook(() => useCreateTask(), { wrapper });
await expect(
result.current.mutateAsync({
project_id: "project-123",
title: "Failed Task",
description: "This will fail",
}),
).rejects.toThrow("Network error");
// Verify error feedback was shown to user
await waitFor(() => {
expect(showToastMock).toHaveBeenCalledWith(expect.stringContaining("Failed to create task"), "error");
});
});
});
});