Skip to content

Improvement of Task filtering status #3140

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jun 20, 2025
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,8 @@
isYesterday,
} from 'date-fns';
import { useEffect, useRef, useState } from 'react';
import { moveTask } from '@/lib/task-helper';
import { toast } from '@tuturuuu/ui/hooks/use-toast';

Check warning on line 62 in apps/web/src/app/[locale]/(dashboard)/[wsId]/tasks/boards/[boardId]/task.tsx

View check run for this annotation

Codecov / codecov/patch

apps/web/src/app/[locale]/(dashboard)/[wsId]/tasks/boards/[boardId]/task.tsx#L61-L62

Added lines #L61 - L62 were not covered by tests

export interface Task extends TaskType {}

Expand All @@ -67,6 +69,7 @@
taskList?: TaskList;
isOverlay?: boolean;
onUpdate?: () => void;
availableLists?: TaskList[]; // Optional: pass from parent to avoid redundant API calls

Check warning on line 72 in apps/web/src/app/[locale]/(dashboard)/[wsId]/tasks/boards/[boardId]/task.tsx

View check run for this annotation

Codecov / codecov/patch

apps/web/src/app/[locale]/(dashboard)/[wsId]/tasks/boards/[boardId]/task.tsx#L72

Added line #L72 was not covered by tests
}

export function TaskCard({
Expand All @@ -75,6 +78,7 @@
taskList,
isOverlay,
onUpdate,
availableLists: propAvailableLists,

Check warning on line 81 in apps/web/src/app/[locale]/(dashboard)/[wsId]/tasks/boards/[boardId]/task.tsx

View check run for this annotation

Codecov / codecov/patch

apps/web/src/app/[locale]/(dashboard)/[wsId]/tasks/boards/[boardId]/task.tsx#L81

Added line #L81 was not covered by tests
}: Props) {
const [isLoading, setIsLoading] = useState(false);
const [isHovered, setIsHovered] = useState(false);
Expand All @@ -91,8 +95,13 @@
const updateTaskMutation = useUpdateTask(boardId);
const deleteTaskMutation = useDeleteTask(boardId);

// Fetch available task lists for the board
// Fetch available task lists for the board (only if not provided as prop)

Check warning on line 98 in apps/web/src/app/[locale]/(dashboard)/[wsId]/tasks/boards/[boardId]/task.tsx

View check run for this annotation

Codecov / codecov/patch

apps/web/src/app/[locale]/(dashboard)/[wsId]/tasks/boards/[boardId]/task.tsx#L98

Added line #L98 was not covered by tests
useEffect(() => {
if (propAvailableLists) {
setAvailableLists(propAvailableLists);
return;
}

Check warning on line 104 in apps/web/src/app/[locale]/(dashboard)/[wsId]/tasks/boards/[boardId]/task.tsx

View check run for this annotation

Codecov / codecov/patch

apps/web/src/app/[locale]/(dashboard)/[wsId]/tasks/boards/[boardId]/task.tsx#L100-L104

Added lines #L100 - L104 were not covered by tests
const fetchTaskLists = async () => {
const supabase = createClient();
const { data, error } = await supabase
Expand All @@ -109,7 +118,7 @@
};

fetchTaskLists();
}, [boardId]);
}, [boardId, propAvailableLists]);

Check warning on line 121 in apps/web/src/app/[locale]/(dashboard)/[wsId]/tasks/boards/[boardId]/task.tsx

View check run for this annotation

Codecov / codecov/patch

apps/web/src/app/[locale]/(dashboard)/[wsId]/tasks/boards/[boardId]/task.tsx#L121

Added line #L121 was not covered by tests

// Find the first list with 'done' or 'closed' status
const getTargetCompletionList = () => {
Expand Down Expand Up @@ -244,22 +253,24 @@
if (!targetCompletionList || !onUpdate) return;

setIsLoading(true);
updateTaskMutation.mutate(
{
taskId: task.id,
updates: {
list_id: targetCompletionList.id,
archived: true, // Also mark as archived when moving to completion
},
},
{
onSettled: () => {
setIsLoading(false);
setMenuOpen(false);
onUpdate();
},
}
);

// Use the standard moveTask function to ensure consistent logic
const supabase = createClient();
try {
await moveTask(supabase, task.id, targetCompletionList.id);
// Manually invalidate queries since we're not using the mutation hook
onUpdate();
} catch (error) {
console.error('Failed to move task to completion:', error);
toast({
title: 'Error',
description: 'Failed to complete task. Please try again.',
variant: 'destructive',
});
} finally {
setIsLoading(false);
setMenuOpen(false);
}

Check warning on line 273 in apps/web/src/app/[locale]/(dashboard)/[wsId]/tasks/boards/[boardId]/task.tsx

View check run for this annotation

Codecov / codecov/patch

apps/web/src/app/[locale]/(dashboard)/[wsId]/tasks/boards/[boardId]/task.tsx#L256-L273

Added lines #L256 - L273 were not covered by tests
}

async function handleDelete() {
Expand Down
31 changes: 25 additions & 6 deletions apps/web/src/app/api/v1/workspaces/[wsId]/tasks/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,17 @@
interface TaskListData {
id: string;
name: string | null;
// Task list status: 'not_started' | 'active' | 'done' | 'closed'
// Used to determine task availability for time tracking
status: string | null;

Check warning on line 19 in apps/web/src/app/api/v1/workspaces/[wsId]/tasks/route.ts

View check run for this annotation

Codecov / codecov/patch

apps/web/src/app/api/v1/workspaces/[wsId]/tasks/route.ts#L17-L19

Added lines #L17 - L19 were not covered by tests
workspace_boards: {
id: string;
name: string | null;
ws_id: string;
} | null;
}

interface RawTaskData {
interface TaskData {

Check warning on line 27 in apps/web/src/app/api/v1/workspaces/[wsId]/tasks/route.ts

View check run for this annotation

Codecov / codecov/patch

apps/web/src/app/api/v1/workspaces/[wsId]/tasks/route.ts#L27

Added line #L27 was not covered by tests
id: string;
name: string;
description: string | null;
Expand All @@ -31,6 +34,7 @@
end_date: string | null;
created_at: string | null;
list_id: string;
archived: boolean | null;

Check warning on line 37 in apps/web/src/app/api/v1/workspaces/[wsId]/tasks/route.ts

View check run for this annotation

Codecov / codecov/patch

apps/web/src/app/api/v1/workspaces/[wsId]/tasks/route.ts#L37

Added line #L37 was not covered by tests
task_lists: TaskListData | null;
assignees?: TaskAssigneeData[];
}
Expand Down Expand Up @@ -86,6 +90,9 @@
Number.isFinite(parsedOffset) && parsedOffset >= 0 ? parsedOffset : 0;
const boardId = url.searchParams.get('boardId');
const listId = url.searchParams.get('listId');

// Check if this is a request for time tracking (indicated by limit=100 and no specific filters)
const isTimeTrackingRequest = limit === 100 && !boardId && !listId;

Check warning on line 95 in apps/web/src/app/api/v1/workspaces/[wsId]/tasks/route.ts

View check run for this annotation

Codecov / codecov/patch

apps/web/src/app/api/v1/workspaces/[wsId]/tasks/route.ts#L93-L95

Added lines #L93 - L95 were not covered by tests

// Build the query for fetching tasks with assignee information
let query = supabase
Expand All @@ -101,9 +108,11 @@
end_date,
created_at,
list_id,
archived,

Check warning on line 111 in apps/web/src/app/api/v1/workspaces/[wsId]/tasks/route.ts

View check run for this annotation

Codecov / codecov/patch

apps/web/src/app/api/v1/workspaces/[wsId]/tasks/route.ts#L111

Added line #L111 was not covered by tests
task_lists!inner (
id,
name,
status,

Check warning on line 115 in apps/web/src/app/api/v1/workspaces/[wsId]/tasks/route.ts

View check run for this annotation

Codecov / codecov/patch

apps/web/src/app/api/v1/workspaces/[wsId]/tasks/route.ts#L115

Added line #L115 was not covered by tests
board_id,
workspace_boards!inner (
id,
Expand All @@ -123,6 +132,14 @@
.eq('task_lists.workspace_boards.ws_id', wsId)
.eq('deleted', false);

// IMPORTANT: If this is for time tracking, apply the same filters as the server-side helper
if (isTimeTrackingRequest) {
query = query
.eq('archived', false) // Only non-archived tasks
.in('task_lists.status', ['not_started', 'active']) // Only from active lists
.eq('task_lists.deleted', false); // Ensure list is not deleted
}

Check warning on line 142 in apps/web/src/app/api/v1/workspaces/[wsId]/tasks/route.ts

View check run for this annotation

Codecov / codecov/patch

apps/web/src/app/api/v1/workspaces/[wsId]/tasks/route.ts#L135-L142

Added lines #L135 - L142 were not covered by tests
// Apply filters based on query parameters
if (listId) {
query = query.eq('list_id', listId);
Expand All @@ -142,7 +159,7 @@

// Transform the data to match the expected WorkspaceTask format
const tasks =
data?.map((task: RawTaskData) => ({
data?.map((task: TaskData) => ({

Check warning on line 162 in apps/web/src/app/api/v1/workspaces/[wsId]/tasks/route.ts

View check run for this annotation

Codecov / codecov/patch

apps/web/src/app/api/v1/workspaces/[wsId]/tasks/route.ts#L162

Added line #L162 was not covered by tests
id: task.id,
name: task.name,
description: task.description,
Expand All @@ -152,20 +169,22 @@
end_date: task.end_date,
created_at: task.created_at,
list_id: task.list_id,
archived: task.archived,

Check warning on line 172 in apps/web/src/app/api/v1/workspaces/[wsId]/tasks/route.ts

View check run for this annotation

Codecov / codecov/patch

apps/web/src/app/api/v1/workspaces/[wsId]/tasks/route.ts#L172

Added line #L172 was not covered by tests
// Add board information for context
board_name: task.task_lists?.workspace_boards?.name,
list_name: task.task_lists?.name,
list_status: task.task_lists?.status,

Check warning on line 176 in apps/web/src/app/api/v1/workspaces/[wsId]/tasks/route.ts

View check run for this annotation

Codecov / codecov/patch

apps/web/src/app/api/v1/workspaces/[wsId]/tasks/route.ts#L176

Added line #L176 was not covered by tests
// Add assignee information
assignees: [
...(task.assignees ?? [])
.map((a) => a.user)
.filter((u): u is NonNullable<typeof u> => !!u?.id)
.reduce((uniqueUsers, user) => {
.map((a: any) => a.user)
.filter((u: any) => !!u?.id)
.reduce((uniqueUsers: Map<string, any>, user: any) => {

Check warning on line 182 in apps/web/src/app/api/v1/workspaces/[wsId]/tasks/route.ts

View check run for this annotation

Codecov / codecov/patch

apps/web/src/app/api/v1/workspaces/[wsId]/tasks/route.ts#L180-L182

Added lines #L180 - L182 were not covered by tests
if (!uniqueUsers.has(user.id)) {
uniqueUsers.set(user.id, user);
}
return uniqueUsers;
}, new Map<string, NonNullable<typeof task.assignees>[0]['user']>())
}, new Map())

Check warning on line 187 in apps/web/src/app/api/v1/workspaces/[wsId]/tasks/route.ts

View check run for this annotation

Codecov / codecov/patch

apps/web/src/app/api/v1/workspaces/[wsId]/tasks/route.ts#L187

Added line #L187 was not covered by tests
.values(),
],
// Add helper field to identify if current user is assigned
Expand Down
72 changes: 30 additions & 42 deletions apps/web/src/lib/task-helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -143,13 +143,32 @@
return data as Task;
}

// Utility function to transform and deduplicate assignees
export function transformAssignees(assignees: any[]): any[] {
return assignees
?.map((a: any) => a.user)
.filter(
(user: any, index: number, self: any[]) =>
user?.id &&
self.findIndex((u: any) => u.id === user.id) === index
) || [];
}

Check warning on line 155 in apps/web/src/lib/task-helper.ts

View check run for this annotation

Codecov / codecov/patch

apps/web/src/lib/task-helper.ts#L147-L155

Added lines #L147 - L155 were not covered by tests

// Utility function to invalidate all task-related caches consistently
export function invalidateTaskCaches(queryClient: any, boardId?: string) {
if (boardId) {
queryClient.invalidateQueries({ queryKey: ['tasks', boardId] });
queryClient.invalidateQueries({ queryKey: ['task_lists', boardId] });
}

Check warning on line 162 in apps/web/src/lib/task-helper.ts

View check run for this annotation

Codecov / codecov/patch

apps/web/src/lib/task-helper.ts#L158-L162

Added lines #L158 - L162 were not covered by tests
// Always invalidate time tracker since task availability affects it
queryClient.invalidateQueries({ queryKey: ['time-tracking-data'] });
}

Check warning on line 165 in apps/web/src/lib/task-helper.ts

View check run for this annotation

Codecov / codecov/patch

apps/web/src/lib/task-helper.ts#L164-L165

Added lines #L164 - L165 were not covered by tests

export async function moveTask(
supabase: SupabaseClient,
taskId: string,
newListId: string
) {
console.log('🔄 Starting moveTask:', { taskId, newListId });

// First, get the target list to check its status
const { data: targetList, error: listError } = await supabase
.from('task_lists')
Expand All @@ -162,17 +181,12 @@
throw listError;
}

console.log('✅ Target list found:', targetList);

// Determine if task should be marked as archived based on list status
// Determine task completion status based on list status
// - not_started, active: task is available for work (archived = false)
// - done, closed: task is completed/archived (archived = true)
const shouldArchive =
targetList.status === 'done' || targetList.status === 'closed';

console.log('📝 Task completion status will be:', {
shouldArchive,
reason: `List status is "${targetList.status}"`,
});

const { data, error } = await supabase
.from('tasks')
.update({
Expand All @@ -199,23 +213,10 @@
throw error;
}

console.log('✅ Task moved successfully in database:', {
taskId: data.id,
newListId: data.list_id,
archived: data.archived,
});

// Transform the nested assignees data
const transformedTask = {
...data,
assignees: data.assignees
?.map((a: any) => a.user)
.filter(
(user: any, index: number, self: any[]) =>
user &&
user.id &&
self.findIndex((u: any) => u.id === user.id) === index
),
assignees: transformAssignees(data.assignees),

Check warning on line 219 in apps/web/src/lib/task-helper.ts

View check run for this annotation

Codecov / codecov/patch

apps/web/src/lib/task-helper.ts#L219

Added line #L219 was not covered by tests
};

return transformedTask as Task;
Expand Down Expand Up @@ -484,17 +485,10 @@
taskId: string;
newListId: string;
}) => {
console.log('🚀 useMoveTask mutation called:', {
taskId,
newListId,
boardId,
});
const supabase = createClient();
return moveTask(supabase, taskId, newListId);
},
onMutate: async ({ taskId, newListId }) => {
console.log('🔄 useMoveTask onMutate:', { taskId, newListId });

// Cancel any outgoing refetches
await queryClient.cancelQueries({ queryKey: ['tasks', boardId] });

Expand All @@ -514,9 +508,7 @@

return { previousTasks };
},
onError: (err, variables, context) => {
console.error('❌ useMoveTask onError:', err, variables);

onError: (err, _variables, context) => {

Check warning on line 511 in apps/web/src/lib/task-helper.ts

View check run for this annotation

Codecov / codecov/patch

apps/web/src/lib/task-helper.ts#L511

Added line #L511 was not covered by tests
// Rollback optimistic update on error
if (context?.previousTasks) {
queryClient.setQueryData(['tasks', boardId], context.previousTasks);
Expand All @@ -529,9 +521,7 @@
variant: 'destructive',
});
},
onSuccess: (updatedTask, variables) => {
console.log('✅ useMoveTask onSuccess:', { updatedTask, variables });

onSuccess: (updatedTask, _variables) => {

Check warning on line 524 in apps/web/src/lib/task-helper.ts

View check run for this annotation

Codecov / codecov/patch

apps/web/src/lib/task-helper.ts#L524

Added line #L524 was not covered by tests
// Update the cache with the server response
queryClient.setQueryData(
['tasks', boardId],
Expand All @@ -543,11 +533,9 @@
}
);
},
onSettled: (data, error, variables) => {
console.log('🏁 useMoveTask onSettled:', { data, error, variables });

// Ensure data consistency
queryClient.invalidateQueries({ queryKey: ['tasks', boardId] });
onSettled: (_data, _error, _variables) => {

Check warning on line 536 in apps/web/src/lib/task-helper.ts

View check run for this annotation

Codecov / codecov/patch

apps/web/src/lib/task-helper.ts#L536

Added line #L536 was not covered by tests
// Ensure data consistency across all task-related caches
invalidateTaskCaches(queryClient, boardId);

Check warning on line 538 in apps/web/src/lib/task-helper.ts

View check run for this annotation

Codecov / codecov/patch

apps/web/src/lib/task-helper.ts#L538

Added line #L538 was not covered by tests
},
});
}
Expand Down
Loading
Loading