Merge branch 'release/v2.1.2' of https://github.com/Worklenz/worklenz into test/kanban-order-v1.2.2

This commit is contained in:
shancds
2025-07-15 16:39:35 +05:30
54 changed files with 2700 additions and 540 deletions

View File

@@ -5,6 +5,7 @@ import i18next from 'i18next';
// Components
import ThemeWrapper from './features/theme/ThemeWrapper';
import ModuleErrorBoundary from './components/ModuleErrorBoundary';
// Routes
import router from './app/routes';
@@ -13,6 +14,7 @@ import router from './app/routes';
import { useAppSelector } from './hooks/useAppSelector';
import { initMixpanel } from './utils/mixpanelInit';
import { initializeCsrfToken } from './api/api-client';
import CacheCleanup from './utils/cache-cleanup';
// Types & Constants
import { Language } from './features/i18n/localesSlice';
@@ -113,6 +115,56 @@ const App: React.FC = memo(() => {
};
}, []);
// Global error handlers for module loading issues
useEffect(() => {
const handleUnhandledRejection = (event: PromiseRejectionEvent) => {
const error = event.reason;
// Check if this is a module loading error
if (
error?.message?.includes('Failed to fetch dynamically imported module') ||
error?.message?.includes('Loading chunk') ||
error?.name === 'ChunkLoadError'
) {
console.error('Unhandled module loading error:', error);
event.preventDefault(); // Prevent default browser error handling
// Clear caches and reload
CacheCleanup.clearAllCaches()
.then(() => CacheCleanup.forceReload('/auth/login'))
.catch(() => window.location.reload());
}
};
const handleError = (event: ErrorEvent) => {
const error = event.error;
// Check if this is a module loading error
if (
error?.message?.includes('Failed to fetch dynamically imported module') ||
error?.message?.includes('Loading chunk') ||
error?.name === 'ChunkLoadError'
) {
console.error('Global module loading error:', error);
event.preventDefault(); // Prevent default browser error handling
// Clear caches and reload
CacheCleanup.clearAllCaches()
.then(() => CacheCleanup.forceReload('/auth/login'))
.catch(() => window.location.reload());
}
};
// Add global error handlers
window.addEventListener('unhandledrejection', handleUnhandledRejection);
window.addEventListener('error', handleError);
return () => {
window.removeEventListener('unhandledrejection', handleUnhandledRejection);
window.removeEventListener('error', handleError);
};
}, []);
// Register service worker
useEffect(() => {
registerSW({
@@ -150,12 +202,14 @@ const App: React.FC = memo(() => {
return (
<Suspense fallback={<SuspenseFallback />}>
<ThemeWrapper>
<RouterProvider
router={router}
future={{
v7_startTransition: true,
}}
/>
<ModuleErrorBoundary>
<RouterProvider
router={router}
future={{
v7_startTransition: true,
}}
/>
</ModuleErrorBoundary>
</ThemeWrapper>
</Suspense>
);

View File

@@ -90,6 +90,23 @@ export const SetupGuard = memo(({ children }: GuardProps) => {
SetupGuard.displayName = 'SetupGuard';
// Combined guard for routes that require both authentication and setup completion
export const AuthAndSetupGuard = memo(({ children }: GuardProps) => {
const { isAuthenticated, isSetupComplete, location } = useAuthStatus();
if (!isAuthenticated) {
return <Navigate to="/auth" state={{ from: location }} replace />;
}
if (!isSetupComplete) {
return <Navigate to="/worklenz/setup" />;
}
return <>{children}</>;
});
AuthAndSetupGuard.displayName = 'AuthAndSetupGuard';
// Optimized route wrapping function with Suspense boundaries
const wrapRoutes = (
routes: RouteObject[],
@@ -171,9 +188,11 @@ StaticLicenseExpired.displayName = 'StaticLicenseExpired';
// Create route arrays (moved outside of useMemo to avoid hook violations)
const publicRoutes = [...rootRoutes, ...authRoutes, notFoundRoute];
const protectedMainRoutes = wrapRoutes(mainRoutes, AuthGuard);
// Apply combined guard to main routes that require both auth and setup completion
const protectedMainRoutes = wrapRoutes(mainRoutes, AuthAndSetupGuard);
const adminRoutes = wrapRoutes(reportingRoutes, AdminGuard);
const setupRoutes = wrapRoutes([accountSetupRoute], SetupGuard);
// Setup route should be accessible without setup completion, only requires authentication
const setupRoutes = wrapRoutes([accountSetupRoute], AuthGuard);
// License expiry check function
const withLicenseExpiryCheck = (routes: RouteObject[]): RouteObject[] => {

View File

@@ -39,7 +39,7 @@ const CustomColordLabel = React.forwardRef<HTMLSpanElement, CustomColordLabelPro
<Tooltip title={label.name}>
<span
ref={ref}
className="inline-flex items-center px-2 py-0.5 rounded-sm text-xs font-medium shrink-0 max-w-[120px]"
className="inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium shrink-0 max-w-[100px]"
style={{
backgroundColor,
color: textColor,

View File

@@ -21,8 +21,8 @@ const CustomNumberLabel = React.forwardRef<HTMLSpanElement, CustomNumberLabelPro
<Tooltip title={labelList.join(', ')}>
<span
ref={ref}
className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium text-white cursor-help"
style={{ backgroundColor }}
className="inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium cursor-help"
style={{ backgroundColor, color: 'white' }}
>
{namesString}
</span>

View File

@@ -0,0 +1,110 @@
import React, { Component, ErrorInfo, ReactNode } from 'react';
import { Button, Result } from 'antd';
import CacheCleanup from '@/utils/cache-cleanup';
interface Props {
children: ReactNode;
}
interface State {
hasError: boolean;
error?: Error;
}
class ModuleErrorBoundary extends Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error: Error): State {
// Check if this is a module loading error
const isModuleError =
error.message.includes('Failed to fetch dynamically imported module') ||
error.message.includes('Loading chunk') ||
error.message.includes('Loading CSS chunk') ||
error.name === 'ChunkLoadError';
if (isModuleError) {
return { hasError: true, error };
}
// For other errors, let them bubble up
return { hasError: false };
}
componentDidCatch(error: Error, errorInfo: ErrorInfo) {
console.error('Module Error Boundary caught an error:', error, errorInfo);
// If this is a module loading error, clear caches and reload
if (this.state.hasError) {
this.handleModuleError();
}
}
private async handleModuleError() {
try {
console.log('Handling module loading error - clearing caches...');
// Clear all caches
await CacheCleanup.clearAllCaches();
// Force reload to login page
CacheCleanup.forceReload('/auth/login');
} catch (cacheError) {
console.error('Failed to handle module error:', cacheError);
// Fallback: just reload the page
window.location.reload();
}
}
private handleRetry = async () => {
try {
await CacheCleanup.clearAllCaches();
CacheCleanup.forceReload('/auth/login');
} catch (error) {
console.error('Retry failed:', error);
window.location.reload();
}
};
render() {
if (this.state.hasError) {
return (
<div style={{
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
minHeight: '100vh',
padding: '20px'
}}>
<Result
status="error"
title="Module Loading Error"
subTitle="There was an issue loading the application. This usually happens after updates or during logout."
extra={[
<Button
type="primary"
key="retry"
onClick={this.handleRetry}
loading={false}
>
Retry
</Button>,
<Button
key="reload"
onClick={() => window.location.reload()}
>
Reload Page
</Button>
]}
/>
</div>
);
}
return this.props.children;
}
}
export default ModuleErrorBoundary;

View File

@@ -1,5 +1,5 @@
import React, { startTransition, useEffect, useRef, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useSelector } from 'react-redux';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
@@ -18,6 +18,11 @@ import { IAccountSetupRequest } from '@/types/project-templates/project-template
import { evt_account_setup_template_complete } from '@/shared/worklenz-analytics-events';
import { useMixpanelTracking } from '@/hooks/useMixpanelTracking';
import { createPortal } from 'react-dom';
import { useAppDispatch } from '@/hooks/useAppDispatch';
import { verifyAuthentication } from '@/features/auth/authSlice';
import { setUser } from '@/features/user/userSlice';
import { setSession } from '@/utils/session-helper';
import { IAuthorizeResponse } from '@/types/auth/login.types';
const { Title } = Typography;
@@ -29,7 +34,7 @@ interface Props {
export const ProjectStep: React.FC<Props> = ({ onEnter, styles, isDarkMode = false }) => {
const { t } = useTranslation('account-setup');
const dispatch = useDispatch();
const dispatch = useAppDispatch();
const navigate = useNavigate();
const { trackMixpanelEvent } = useMixpanelTracking();
@@ -69,6 +74,18 @@ export const ProjectStep: React.FC<Props> = ({ onEnter, styles, isDarkMode = fal
if (res.done && res.body.id) {
toggleTemplateSelector(false);
trackMixpanelEvent(evt_account_setup_template_complete);
// Refresh user session to update setup_completed status
try {
const authResponse = await dispatch(verifyAuthentication()).unwrap() as IAuthorizeResponse;
if (authResponse?.authenticated && authResponse?.user) {
setSession(authResponse.user);
dispatch(setUser(authResponse.user));
}
} catch (error) {
logger.error('Failed to refresh user session after template setup completion', error);
}
navigate(`/worklenz/projects/${res.body.id}?tab=tasks-list&pinned_tab=tasks-list`);
}
} catch (error) {

View File

@@ -1,6 +1,5 @@
import { useSocket } from '@/socket/socketContext';
import { ITaskPhase } from '@/types/tasks/taskPhase.types';
import { IProjectTask } from '@/types/project/projectTasksViewModel.types';
import { Select } from 'antd';
import { Form } from 'antd';
@@ -27,12 +26,6 @@ const TaskDrawerPhaseSelector = ({ phases, task }: TaskDrawerPhaseSelectorProps)
phase_id: value,
parent_task: task.parent_task_id || null,
});
// socket?.once(SocketEvents.TASK_PHASE_CHANGE.toString(), () => {
// if(list.getCurrentGroup().value === this.list.GROUP_BY_PHASE_VALUE && this.list.isSubtasksIncluded) {
// this.list.emitRefreshSubtasksIncluded();
// }
// });
};
return (
@@ -41,8 +34,11 @@ const TaskDrawerPhaseSelector = ({ phases, task }: TaskDrawerPhaseSelectorProps)
allowClear
placeholder="Select Phase"
options={phaseMenuItems}
style={{ width: 'fit-content' }}
dropdownStyle={{ width: 'fit-content' }}
styles={{
root: {
width: 'fit-content',
},
}}
onChange={handlePhaseChange}
/>
</Form.Item>

View File

@@ -7,3 +7,28 @@
outline: 1px solid #d9d9d9;
border-radius: 4px;
}
/* Task name display styles */
.task-name-display {
margin: 0;
padding: 2px 8px;
font-size: 16px;
cursor: pointer;
width: 100%;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
min-height: 20px;
line-height: 1.4;
display: flex;
align-items: center;
}
.task-name-display:hover {
background-color: rgba(0, 0, 0, 0.02);
border-radius: 4px;
}
[data-theme='dark'] .task-name-display:hover {
background-color: rgba(255, 255, 255, 0.05);
}

View File

@@ -1,4 +1,4 @@
import { Button, Dropdown, Flex, Input, InputRef, MenuProps } from 'antd';
import { Button, Dropdown, Flex, Input, InputRef, MenuProps, Tooltip } from 'antd';
import React, { ChangeEvent, useEffect, useRef, useState } from 'react';
import { EllipsisOutlined } from '@ant-design/icons';
import { TFunction } from 'i18next';
@@ -21,12 +21,19 @@ import { deleteBoardTask } from '@/features/board/board-slice';
import { deleteTask as deleteKanbanTask, updateEnhancedKanbanSubtask } from '@/features/enhanced-kanban/enhanced-kanban.slice';
import useTabSearchParam from '@/hooks/useTabSearchParam';
import { ITaskViewModel } from '@/types/tasks/task.types';
import TaskHierarchyBreadcrumb from '../task-hierarchy-breadcrumb/task-hierarchy-breadcrumb';
type TaskDrawerHeaderProps = {
inputRef: React.RefObject<InputRef | null>;
t: TFunction;
};
// Utility function to truncate text
const truncateText = (text: string, maxLength: number = 50): string => {
if (!text || text.length <= maxLength) return text;
return `${text.substring(0, maxLength)}...`;
};
const TaskDrawerHeader = ({ inputRef, t }: TaskDrawerHeaderProps) => {
const dispatch = useAppDispatch();
const { socket, connected } = useSocket();
@@ -38,6 +45,9 @@ const TaskDrawerHeader = ({ inputRef, t }: TaskDrawerHeaderProps) => {
const [taskName, setTaskName] = useState<string>(taskFormViewModel?.task?.name ?? '');
const currentSession = useAuthService().getCurrentSession();
// Check if current task is a sub-task
const isSubTask = taskFormViewModel?.task?.is_sub_task || !!taskFormViewModel?.task?.parent_task_id;
useEffect(() => {
setTaskName(taskFormViewModel?.task?.name ?? '');
}, [taskFormViewModel?.task?.name]);
@@ -126,54 +136,57 @@ const TaskDrawerHeader = ({ inputRef, t }: TaskDrawerHeaderProps) => {
// No need for local socket listeners that could interfere with global handlers
};
const displayTaskName = taskName || t('taskHeader.taskNamePlaceholder');
const truncatedTaskName = truncateText(displayTaskName, 50);
const shouldShowTooltip = displayTaskName.length > 50;
return (
<Flex gap={12} align="center" style={{ marginBlockEnd: 6 }}>
<Flex style={{ position: 'relative', width: '100%' }}>
{isEditing ? (
<Input
ref={inputRef}
size="large"
value={taskName}
onChange={e => onTaskNameChange(e)}
onBlur={handleInputBlur}
placeholder={t('taskHeader.taskNamePlaceholder')}
className="task-name-input"
style={{
width: '100%',
border: 'none',
}}
showCount={true}
maxLength={250}
autoFocus
/>
) : (
<p
onClick={() => setIsEditing(true)}
style={{
margin: 0,
padding: '4px 11px',
fontSize: '16px',
cursor: 'pointer',
wordWrap: 'break-word',
overflowWrap: 'break-word',
width: '100%',
}}
>
{taskName || t('taskHeader.taskNamePlaceholder')}
</p>
)}
<div>
{/* Show breadcrumb for sub-tasks */}
{isSubTask && <TaskHierarchyBreadcrumb t={t} />}
<Flex gap={8} align="center" style={{ marginBlockEnd: 2 }}>
<Flex style={{ position: 'relative', width: '100%', alignItems: 'center' }}>
{isEditing ? (
<Input
ref={inputRef}
size="large"
value={taskName}
onChange={e => onTaskNameChange(e)}
onBlur={handleInputBlur}
placeholder={t('taskHeader.taskNamePlaceholder')}
className="task-name-input"
style={{
width: '100%',
border: 'none',
}}
showCount={true}
maxLength={250}
autoFocus
/>
) : (
<Tooltip title={shouldShowTooltip ? displayTaskName : ''} trigger="hover">
<p
onClick={() => setIsEditing(true)}
className="task-name-display"
>
{truncatedTaskName}
</p>
</Tooltip>
)}
</Flex>
<TaskDrawerStatusDropdown
statuses={taskFormViewModel?.statuses ?? []}
task={taskFormViewModel?.task ?? ({} as ITaskViewModel)}
teamId={currentSession?.team_id ?? ''}
/>
<Dropdown overlayClassName={'delete-task-dropdown'} menu={{ items: deletTaskDropdownItems }}>
<Button type="text" icon={<EllipsisOutlined />} />
</Dropdown>
</Flex>
<TaskDrawerStatusDropdown
statuses={taskFormViewModel?.statuses ?? []}
task={taskFormViewModel?.task ?? ({} as ITaskViewModel)}
teamId={currentSession?.team_id ?? ''}
/>
<Dropdown overlayClassName={'delete-task-dropdown'} menu={{ items: deletTaskDropdownItems }}>
<Button type="text" icon={<EllipsisOutlined />} />
</Dropdown>
</Flex>
</div>
);
};

View File

@@ -3,7 +3,7 @@ import Drawer from 'antd/es/drawer';
import { InputRef } from 'antd/es/input';
import { useTranslation } from 'react-i18next';
import { useEffect, useRef, useState } from 'react';
import { PlusOutlined } from '@ant-design/icons';
import { PlusOutlined, CloseOutlined, ArrowLeftOutlined } from '@ant-design/icons';
import { useAppSelector } from '@/hooks/useAppSelector';
import { useAppDispatch } from '@/hooks/useAppDispatch';
@@ -13,6 +13,7 @@ import {
setTaskFormViewModel,
setTaskSubscribers,
setTimeLogEditing,
fetchTask,
} from '@/features/task-drawer/task-drawer.slice';
import './task-drawer.css';
@@ -33,6 +34,7 @@ const TaskDrawer = () => {
const { showTaskDrawer, timeLogEditing } = useAppSelector(state => state.taskDrawerReducer);
const { taskFormViewModel, selectedTaskId } = useAppSelector(state => state.taskDrawerReducer);
const { projectId } = useAppSelector(state => state.projectReducer);
const taskNameInputRef = useRef<InputRef>(null);
const isClosingManually = useRef(false);
@@ -54,6 +56,17 @@ const TaskDrawer = () => {
dispatch(setTaskSubscribers([]));
};
const handleBackToParent = () => {
if (taskFormViewModel?.task?.parent_task_id && projectId) {
// Navigate to parent task
dispatch(setSelectedTaskId(taskFormViewModel.task.parent_task_id));
dispatch(fetchTask({
taskId: taskFormViewModel.task.parent_task_id,
projectId
}));
}
};
const handleOnClose = (
e?: React.MouseEvent<Element, MouseEvent> | React.KeyboardEvent<Element>
) => {
@@ -68,10 +81,8 @@ const TaskDrawer = () => {
if (isClickOutsideDrawer || !taskFormViewModel?.task?.is_sub_task) {
resetTaskState();
} else {
dispatch(setSelectedTaskId(null));
dispatch(setTaskFormViewModel({}));
dispatch(setTaskSubscribers([]));
dispatch(setSelectedTaskId(taskFormViewModel?.task?.parent_task_id || null));
// For sub-tasks, navigate to parent instead of closing
handleBackToParent();
}
// Reset the flag after a short delay
setTimeout(() => {
@@ -205,6 +216,17 @@ const TaskDrawer = () => {
};
};
// Check if current task is a sub-task
const isSubTask = taskFormViewModel?.task?.is_sub_task || !!taskFormViewModel?.task?.parent_task_id;
// Custom close icon based on whether it's a sub-task
const getCloseIcon = () => {
if (isSubTask) {
return <ArrowLeftOutlined />;
}
return <CloseOutlined />;
};
const drawerProps = {
open: showTaskDrawer,
onClose: handleOnClose,
@@ -215,6 +237,7 @@ const TaskDrawer = () => {
footer: renderFooter(),
bodyStyle: getBodyStyle(),
footerStyle: getFooterStyle(),
closeIcon: getCloseIcon(),
};
return (

View File

@@ -0,0 +1,88 @@
.task-hierarchy-breadcrumb {
margin-bottom: 4px;
}
.task-hierarchy-breadcrumb .ant-breadcrumb {
font-size: 14px;
line-height: 1;
}
.task-hierarchy-breadcrumb .ant-breadcrumb-link {
color: inherit;
}
.task-hierarchy-breadcrumb .ant-breadcrumb-separator {
color: #8c8c8c;
margin: 0 4px;
}
/* Dark mode styles */
[data-theme='dark'] .task-hierarchy-breadcrumb .ant-breadcrumb-separator {
color: #595959;
}
/* Back button styles */
.task-hierarchy-breadcrumb .ant-btn-link {
padding: 0;
height: auto;
font-size: 14px;
line-height: 1.3;
max-width: 200px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
display: flex;
align-items: center;
}
.task-hierarchy-breadcrumb .ant-btn-link .anticon {
margin-right: 0; /* Remove default margin */
}
.task-hierarchy-breadcrumb .ant-btn-link:hover {
color: #40a9ff;
}
[data-theme='dark'] .task-hierarchy-breadcrumb .ant-btn-link:hover {
color: #40a9ff;
}
/* Current task name styles */
.task-hierarchy-breadcrumb .current-task-name {
font-size: 14px;
color: #000000d9;
font-weight: 500;
max-width: 200px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
display: inline-block;
line-height: 1.3;
}
[data-theme='dark'] .task-hierarchy-breadcrumb .current-task-name {
color: #ffffffd9;
}
/* Breadcrumb item container */
.task-hierarchy-breadcrumb .ant-breadcrumb-item {
max-width: 220px;
overflow: hidden;
display: flex;
align-items: center;
}
/* Ensure breadcrumb items don't break the layout */
.task-hierarchy-breadcrumb .ant-breadcrumb ol {
display: flex;
flex-wrap: wrap;
align-items: center;
margin: 0;
padding: 0;
}
/* Better alignment for breadcrumb items */
.task-hierarchy-breadcrumb .ant-breadcrumb-item .ant-breadcrumb-link {
display: flex;
align-items: center;
}

View File

@@ -0,0 +1,189 @@
import React, { useState, useEffect } from 'react';
import { Breadcrumb, Button, Typography, Tooltip } from 'antd';
import { HomeOutlined } from '@ant-design/icons';
import { useAppSelector } from '@/hooks/useAppSelector';
import { useAppDispatch } from '@/hooks/useAppDispatch';
import { fetchTask, setSelectedTaskId } from '@/features/task-drawer/task-drawer.slice';
import { tasksApiService } from '@/api/tasks/tasks.api.service';
import { TFunction } from 'i18next';
import './task-hierarchy-breadcrumb.css';
interface TaskHierarchyBreadcrumbProps {
t: TFunction;
onBackClick?: () => void;
}
interface TaskHierarchyItem {
id: string;
name: string;
parent_task_id?: string;
}
// Utility function to truncate text
const truncateText = (text: string, maxLength: number = 25): string => {
if (!text || text.length <= maxLength) return text;
return `${text.substring(0, maxLength)}...`;
};
const TaskHierarchyBreadcrumb: React.FC<TaskHierarchyBreadcrumbProps> = ({ t, onBackClick }) => {
const dispatch = useAppDispatch();
const { taskFormViewModel } = useAppSelector(state => state.taskDrawerReducer);
const { projectId } = useAppSelector(state => state.projectReducer);
const themeMode = useAppSelector(state => state.themeReducer.mode);
const [hierarchyPath, setHierarchyPath] = useState<TaskHierarchyItem[]>([]);
const [loading, setLoading] = useState(false);
const task = taskFormViewModel?.task;
const isSubTask = task?.is_sub_task || !!task?.parent_task_id;
// Recursively fetch the complete hierarchy path
const fetchHierarchyPath = async (currentTaskId: string): Promise<TaskHierarchyItem[]> => {
if (!projectId) return [];
const path: TaskHierarchyItem[] = [];
let taskId = currentTaskId;
// Traverse up the hierarchy until we reach the root
while (taskId) {
try {
const response = await tasksApiService.getFormViewModel(taskId, projectId);
if (response.done && response.body.task) {
const taskData = response.body.task;
path.unshift({
id: taskData.id,
name: taskData.name || '',
parent_task_id: taskData.parent_task_id || undefined
});
// Move to parent task
taskId = taskData.parent_task_id || '';
} else {
break;
}
} catch (error) {
console.error('Error fetching task in hierarchy:', error);
break;
}
}
return path;
};
// Fetch the complete hierarchy when component mounts or task changes
useEffect(() => {
const loadHierarchy = async () => {
if (!isSubTask || !task?.parent_task_id || !projectId) {
setHierarchyPath([]);
return;
}
setLoading(true);
try {
const path = await fetchHierarchyPath(task.parent_task_id);
setHierarchyPath(path);
} catch (error) {
console.error('Error loading task hierarchy:', error);
setHierarchyPath([]);
} finally {
setLoading(false);
}
};
loadHierarchy();
}, [task?.parent_task_id, projectId, isSubTask]);
const handleNavigateToTask = (taskId: string) => {
if (projectId) {
if (onBackClick) {
onBackClick();
}
// Navigate to the selected task
dispatch(setSelectedTaskId(taskId));
dispatch(fetchTask({ taskId, projectId }));
}
};
if (!isSubTask || hierarchyPath.length === 0) {
return null;
}
// Create breadcrumb items from the hierarchy path
const breadcrumbItems = [
// Add all parent tasks in the hierarchy
...hierarchyPath.map((hierarchyTask, index) => {
const truncatedName = truncateText(hierarchyTask.name, 25);
const shouldShowTooltip = hierarchyTask.name.length > 25;
return {
title: (
<Tooltip title={shouldShowTooltip ? hierarchyTask.name : ''} trigger="hover">
<Button
type="link"
icon={index === 0 ? <HomeOutlined /> : undefined}
onClick={() => handleNavigateToTask(hierarchyTask.id)}
style={{
padding: 0,
height: 'auto',
color: themeMode === 'dark' ? '#1890ff' : '#1890ff',
fontSize: '14px',
marginRight: '0px',
maxWidth: '200px',
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
display: 'flex',
alignItems: 'center',
gap: index === 0 ? '6px' : '0px', // Add gap between icon and text for root task
}}
>
{truncatedName}
</Button>
</Tooltip>
),
};
}),
// Add the current task as the last item (non-clickable)
{
title: (() => {
const currentTaskName = task?.name || t('taskHeader.currentTask', 'Current Task');
const truncatedCurrentName = truncateText(currentTaskName, 25);
const shouldShowCurrentTooltip = currentTaskName.length > 25;
return (
<Tooltip title={shouldShowCurrentTooltip ? currentTaskName : ''} trigger="hover">
<Typography.Text
className="current-task-name"
style={{
color: themeMode === 'dark' ? '#ffffffd9' : '#000000d9',
fontSize: '14px',
fontWeight: 500,
maxWidth: '200px',
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
display: 'inline-block',
}}
>
{truncatedCurrentName}
</Typography.Text>
</Tooltip>
);
})(),
},
];
return (
<div className="task-hierarchy-breadcrumb">
{loading ? (
<Typography.Text style={{ color: themeMode === 'dark' ? '#ffffffd9' : '#000000d9' }}>
{t('taskHeader.loadingHierarchy', 'Loading hierarchy...')}
</Typography.Text>
) : (
<Breadcrumb items={breadcrumbItems} />
)}
</div>
);
};
export default TaskHierarchyBreadcrumb;

View File

@@ -9,6 +9,7 @@ import {
KeyboardSensor,
TouchSensor,
closestCenter,
useDroppable,
} from '@dnd-kit/core';
import {
SortableContext,
@@ -67,6 +68,101 @@ import { AddCustomColumnButton, CustomColumnHeader } from './components/CustomCo
import TaskListSkeleton from './components/TaskListSkeleton';
import ConvertToSubtaskDrawer from '@/components/task-list-common/convert-to-subtask-drawer/convert-to-subtask-drawer';
// Empty Group Drop Zone Component
const EmptyGroupDropZone: React.FC<{
groupId: string;
visibleColumns: any[];
t: (key: string) => string;
}> = ({ groupId, visibleColumns, t }) => {
const { setNodeRef, isOver, active } = useDroppable({
id: `empty-group-${groupId}`,
data: {
type: 'group',
groupId: groupId,
isEmpty: true,
},
});
return (
<div
ref={setNodeRef}
className={`relative w-full transition-colors duration-200 ${
isOver && active ? 'bg-blue-50 dark:bg-blue-900/20' : ''
}`}
>
<div className="flex items-center min-w-max px-1 py-6">
{visibleColumns.map((column, index) => {
const emptyColumnStyle = {
width: column.width,
flexShrink: 0,
};
return (
<div
key={`empty-${column.id}`}
className="border-r border-gray-200 dark:border-gray-700"
style={emptyColumnStyle}
/>
);
})}
</div>
<div className="absolute left-4 top-1/2 transform -translate-y-1/2 flex items-center">
<div
className={`text-sm px-4 py-3 rounded-md border shadow-sm transition-colors duration-200 ${
isOver && active
? 'text-blue-600 dark:text-blue-400 bg-blue-50 dark:bg-blue-900/30 border-blue-300 dark:border-blue-600'
: 'text-gray-500 dark:text-gray-400 bg-white dark:bg-gray-900 border-gray-200 dark:border-gray-700'
}`}
>
{isOver && active ? t('dropTaskHere') || 'Drop task here' : t('noTasksInGroup')}
</div>
</div>
{isOver && active && (
<div className="absolute inset-0 border-2 border-dashed border-blue-400 dark:border-blue-500 rounded-md pointer-events-none" />
)}
</div>
);
};
// Placeholder Drop Indicator Component
const PlaceholderDropIndicator: React.FC<{
isVisible: boolean;
visibleColumns: any[];
}> = ({ isVisible, visibleColumns }) => {
if (!isVisible) return null;
return (
<div
className="flex items-center min-w-max px-1 border-2 border-dashed border-blue-400 dark:border-blue-500 bg-blue-50 dark:bg-blue-900/20 rounded-md mx-1 my-1 transition-all duration-200 ease-in-out"
style={{ minWidth: 'max-content', height: '40px' }}
>
{visibleColumns.map((column, index) => {
const columnStyle = {
width: column.width,
flexShrink: 0,
};
return (
<div
key={`placeholder-${column.id}`}
className="flex items-center justify-center h-full"
style={columnStyle}
>
{/* Show "Drop task here" message in the title column */}
{column.id === 'title' && (
<div className="text-xs text-blue-600 dark:text-blue-400 font-medium opacity-75">
Drop task here
</div>
)}
{/* Show subtle placeholder content in other columns */}
{column.id !== 'title' && column.id !== 'dragHandle' && (
<div className="w-full h-4 mx-1 bg-white dark:bg-gray-700 rounded opacity-50" />
)}
</div>
);
})}
</div>
);
};
// Hooks and utilities
import { useTaskSocketHandlers } from '@/hooks/useTaskSocketHandlers';
import { useSocket } from '@/socket/socketContext';
@@ -127,7 +223,7 @@ const TaskListV2Section: React.FC = () => {
);
// Custom hooks
const { activeId, handleDragStart, handleDragOver, handleDragEnd } = useDragAndDrop(
const { activeId, overId, handleDragStart, handleDragOver, handleDragEnd } = useDragAndDrop(
allTasks,
groups
);
@@ -465,31 +561,11 @@ const TaskListV2Section: React.FC = () => {
projectId={urlProjectId || ''}
/>
{isGroupEmpty && !isGroupCollapsed && (
<div className="relative w-full">
<div className="flex items-center min-w-max px-1 py-6">
{visibleColumns.map((column, index) => {
const emptyColumnStyle = {
width: column.width,
flexShrink: 0,
...(column.id === 'labels' && column.width === 'auto'
? { minWidth: '200px', flexGrow: 1 }
: {}),
};
return (
<div
key={`empty-${column.id}`}
className="border-r border-gray-200 dark:border-gray-700"
style={emptyColumnStyle}
/>
);
})}
</div>
<div className="absolute left-4 top-1/2 transform -translate-y-1/2 flex items-center">
<div className="text-sm text-gray-500 dark:text-gray-400 bg-white dark:bg-gray-900 px-4 py-3 rounded-md border border-gray-200 dark:border-gray-700 shadow-sm">
{t('noTasksInGroup')}
</div>
</div>
</div>
<EmptyGroupDropZone
groupId={group.id}
visibleColumns={visibleColumns}
t={t}
/>
)}
</div>
);
@@ -546,12 +622,6 @@ const TaskListV2Section: React.FC = () => {
const columnStyle: ColumnStyle = {
width: column.width,
flexShrink: 0,
...(column.id === 'labels' && column.width === 'auto'
? {
minWidth: '200px',
flexGrow: 1,
}
: {}),
...((column as any).minWidth && { minWidth: (column as any).minWidth }),
...((column as any).maxWidth && { maxWidth: (column as any).maxWidth }),
};
@@ -687,8 +757,9 @@ const TaskListV2Section: React.FC = () => {
{renderGroup(groupIndex)}
{/* Group Tasks */}
{!collapsedGroups.has(group.id) &&
group.tasks.map((task, taskIndex) => {
{!collapsedGroups.has(group.id) && (
group.tasks.length > 0 ? (
group.tasks.map((task, taskIndex) => {
const globalTaskIndex =
virtuosoGroups.slice(0, groupIndex).reduce((sum, g) => sum + g.count, 0) +
taskIndex;
@@ -696,12 +767,41 @@ const TaskListV2Section: React.FC = () => {
// Check if this is the first actual task in the group (not AddTaskRow)
const isFirstTaskInGroup = taskIndex === 0 && !('isAddTaskRow' in task);
// Check if we should show drop indicators
const isTaskBeingDraggedOver = overId === task.id;
const isGroupBeingDraggedOver = overId === group.id;
const isFirstTaskInGroupBeingDraggedOver = isFirstTaskInGroup && isTaskBeingDraggedOver;
return (
<div key={task.id || `add-task-${group.id}-${taskIndex}`}>
{/* Placeholder drop indicator before first task in group */}
{isFirstTaskInGroupBeingDraggedOver && (
<PlaceholderDropIndicator isVisible={true} visibleColumns={visibleColumns} />
)}
{/* Placeholder drop indicator between tasks */}
{isTaskBeingDraggedOver && !isFirstTaskInGroup && (
<PlaceholderDropIndicator isVisible={true} visibleColumns={visibleColumns} />
)}
{renderTask(globalTaskIndex, isFirstTaskInGroup)}
{/* Placeholder drop indicator at end of group when dragging over group */}
{isGroupBeingDraggedOver && taskIndex === group.tasks.length - 1 && (
<PlaceholderDropIndicator isVisible={true} visibleColumns={visibleColumns} />
)}
</div>
);
})}
})
) : (
// Handle empty groups with placeholder drop indicator
overId === group.id && (
<div style={{ minWidth: 'max-content' }}>
<PlaceholderDropIndicator isVisible={true} visibleColumns={visibleColumns} />
</div>
)
)
)}
</div>
))}
</div>
@@ -710,12 +810,12 @@ const TaskListV2Section: React.FC = () => {
</div>
{/* Drag Overlay */}
<DragOverlay dropAnimation={null}>
<DragOverlay dropAnimation={{ duration: 200, easing: 'ease-in-out' }}>
{activeId ? (
<div className="bg-white dark:bg-gray-800 shadow-xl rounded-md border-2 border-blue-400 opacity-95">
<div className="bg-white dark:bg-gray-800 shadow-2xl rounded-lg border-2 border-blue-500 dark:border-blue-400 scale-105">
<div className="px-4 py-3">
<div className="flex items-center gap-3">
<HolderOutlined className="text-blue-500" />
<HolderOutlined className="text-blue-500 dark:text-blue-400" />
<div>
<div className="text-sm font-medium text-gray-900 dark:text-white">
{allTasks.find(task => task.id === activeId)?.name ||

View File

@@ -24,6 +24,7 @@ interface TaskRowProps {
isSubtask?: boolean;
isFirstInGroup?: boolean;
updateTaskCustomColumnValue?: (taskId: string, columnKey: string, value: string) => void;
depth?: number;
}
const TaskRow: React.FC<TaskRowProps> = memo(({
@@ -32,7 +33,8 @@ const TaskRow: React.FC<TaskRowProps> = memo(({
visibleColumns,
isSubtask = false,
isFirstInGroup = false,
updateTaskCustomColumnValue
updateTaskCustomColumnValue,
depth = 0
}) => {
// Get task data and selection state from Redux
const task = useAppSelector(state => selectTaskById(state, taskId));
@@ -107,13 +109,14 @@ const TaskRow: React.FC<TaskRowProps> = memo(({
handleTaskNameEdit,
attributes,
listeners,
depth,
});
// Memoize style object to prevent unnecessary re-renders
const style = useMemo(() => ({
transform: CSS.Transform.toString(transform),
transition,
opacity: isDragging ? 0.5 : 1,
opacity: isDragging ? 0 : 1, // Completely hide the original task while dragging
}), [transform, transition, isDragging]);
return (

View File

@@ -22,6 +22,8 @@ interface TaskRowWithSubtasksProps {
}>;
isFirstInGroup?: boolean;
updateTaskCustomColumnValue?: (taskId: string, columnKey: string, value: string) => void;
depth?: number; // Add depth prop to track nesting level
maxDepth?: number; // Add maxDepth prop to limit nesting
}
interface AddSubtaskRowProps {
@@ -32,14 +34,15 @@ interface AddSubtaskRowProps {
width: string;
isSticky?: boolean;
}>;
onSubtaskAdded: () => void; // Simplified - no rowId needed
rowId: string; // Unique identifier for this add subtask row
autoFocus?: boolean; // Whether this row should auto-focus on mount
isActive?: boolean; // Whether this row should show the input/button
onActivate?: () => void; // Simplified - no rowId needed
onSubtaskAdded: () => void;
rowId: string;
autoFocus?: boolean;
isActive?: boolean;
onActivate?: () => void;
depth?: number; // Add depth prop for proper indentation
}
const AddSubtaskRow: React.FC<AddSubtaskRowProps> = memo(({
const AddSubtaskRow: React.FC<AddSubtaskRowProps> = memo(({
parentTaskId,
projectId,
visibleColumns,
@@ -47,25 +50,20 @@ const AddSubtaskRow: React.FC<AddSubtaskRowProps> = memo(({
rowId,
autoFocus = false,
isActive = true,
onActivate
onActivate,
depth = 0
}) => {
const [isAdding, setIsAdding] = useState(autoFocus);
const { t } = useTranslation('task-list-table');
const [isAdding, setIsAdding] = useState(false);
const [subtaskName, setSubtaskName] = useState('');
const inputRef = useRef<any>(null);
const { socket, connected } = useSocket();
const { t } = useTranslation('task-list-table');
const dispatch = useAppDispatch();
// Get session data for reporter_id and team_id
const { socket, connected } = useSocket();
const currentSession = useAuthService().getCurrentSession();
// Auto-focus when autoFocus prop is true
useEffect(() => {
if (autoFocus && inputRef.current) {
setIsAdding(true);
setTimeout(() => {
inputRef.current?.focus();
}, 100);
inputRef.current.focus();
}
}, [autoFocus]);
@@ -141,11 +139,15 @@ const AddSubtaskRow: React.FC<AddSubtaskRowProps> = memo(({
return (
<div className="flex items-center h-full" style={baseStyle}>
<div className="flex items-center w-full h-full">
{/* Match subtask indentation pattern - tighter spacing */}
<div className="w-4" />
{/* Match subtask indentation pattern - reduced spacing for level 1 */}
<div className="w-2" />
{/* Add additional indentation for deeper levels - increased spacing for level 2+ */}
{Array.from({ length: depth }).map((_, i) => (
<div key={i} className="w-6" />
))}
<div className="w-1" />
{isActive ? (
{isActive ? (
!isAdding ? (
<button
onClick={() => {
@@ -188,7 +190,7 @@ const AddSubtaskRow: React.FC<AddSubtaskRowProps> = memo(({
default:
return <div style={baseStyle} />;
}
}, [isAdding, subtaskName, handleAddSubtask, handleCancel, handleBlur, handleKeyDown, t, isActive, onActivate]);
}, [isAdding, subtaskName, handleAddSubtask, handleCancel, handleBlur, handleKeyDown, t, isActive, onActivate, depth]);
return (
<div className="flex items-center min-w-max px-1 py-0.5 hover:bg-gray-50 dark:hover:bg-gray-800 min-h-[36px] border-b border-gray-200 dark:border-gray-700">
@@ -203,12 +205,42 @@ const AddSubtaskRow: React.FC<AddSubtaskRowProps> = memo(({
AddSubtaskRow.displayName = 'AddSubtaskRow';
// Helper function to get background color based on depth
const getSubtaskBackgroundColor = (depth: number) => {
switch (depth) {
case 1:
return 'bg-gray-50 dark:bg-gray-800/50';
case 2:
return 'bg-blue-50 dark:bg-blue-900/20';
case 3:
return 'bg-green-50 dark:bg-green-900/20';
default:
return 'bg-gray-50 dark:bg-gray-800/50';
}
};
// Helper function to get border color based on depth
const getBorderColor = (depth: number) => {
switch (depth) {
case 1:
return 'border-blue-200 dark:border-blue-700';
case 2:
return 'border-green-200 dark:border-green-700';
case 3:
return 'border-purple-200 dark:border-purple-700';
default:
return 'border-blue-200 dark:border-blue-700';
}
};
const TaskRowWithSubtasks: React.FC<TaskRowWithSubtasksProps> = memo(({
taskId,
projectId,
visibleColumns,
isFirstInGroup = false,
updateTaskCustomColumnValue
updateTaskCustomColumnValue,
depth = 0,
maxDepth = 3
}) => {
const task = useAppSelector(state => selectTaskById(state, taskId));
const isLoadingSubtasks = useAppSelector(state => selectSubtaskLoading(state, taskId));
@@ -223,6 +255,9 @@ const TaskRowWithSubtasks: React.FC<TaskRowWithSubtasksProps> = memo(({
return null;
}
// Don't render subtasks if we've reached the maximum depth
const canHaveSubtasks = depth < maxDepth;
return (
<>
{/* Main task row */}
@@ -232,10 +267,12 @@ const TaskRowWithSubtasks: React.FC<TaskRowWithSubtasksProps> = memo(({
visibleColumns={visibleColumns}
isFirstInGroup={isFirstInGroup}
updateTaskCustomColumnValue={updateTaskCustomColumnValue}
isSubtask={depth > 0}
depth={depth}
/>
{/* Subtasks and add subtask row when expanded */}
{task.show_sub_tasks && (
{canHaveSubtasks && task.show_sub_tasks && (
<>
{/* Show loading skeleton while fetching subtasks */}
{isLoadingSubtasks && (
@@ -244,22 +281,23 @@ const TaskRowWithSubtasks: React.FC<TaskRowWithSubtasksProps> = memo(({
</>
)}
{/* Render existing subtasks when not loading */}
{/* Render existing subtasks when not loading - RECURSIVELY */}
{!isLoadingSubtasks && task.sub_tasks?.map((subtask: Task) => (
<div key={subtask.id} className="bg-gray-50 dark:bg-gray-800/50 border-l-2 border-blue-200 dark:border-blue-700">
<TaskRow
<div key={subtask.id} className={`${getSubtaskBackgroundColor(depth + 1)} border-l-2 ${getBorderColor(depth + 1)}`}>
<TaskRowWithSubtasks
taskId={subtask.id}
projectId={projectId}
visibleColumns={visibleColumns}
isSubtask={true}
updateTaskCustomColumnValue={updateTaskCustomColumnValue}
depth={depth + 1}
maxDepth={maxDepth}
/>
</div>
))}
{/* Add subtask row - only show when not loading */}
{!isLoadingSubtasks && (
<div className="bg-gray-50 dark:bg-gray-800/50 border-l-2 border-blue-200 dark:border-blue-700">
<div className={`${getSubtaskBackgroundColor(depth + 1)} border-l-2 ${getBorderColor(depth + 1)}`}>
<AddSubtaskRow
parentTaskId={taskId}
projectId={projectId}
@@ -267,8 +305,9 @@ const TaskRowWithSubtasks: React.FC<TaskRowWithSubtasksProps> = memo(({
onSubtaskAdded={handleSubtaskAdded}
rowId={`add-subtask-${taskId}`}
autoFocus={false}
isActive={true} // Always show the add subtask row
onActivate={undefined} // Not needed anymore
isActive={true}
onActivate={undefined}
depth={depth + 1}
/>
</div>
)}

View File

@@ -252,10 +252,9 @@ interface LabelsColumnProps {
}
export const LabelsColumn: React.FC<LabelsColumnProps> = memo(({ width, task, labelsAdapter, isDarkMode, visibleColumns }) => {
const labelsColumn = visibleColumns.find(col => col.id === 'labels');
const labelsStyle = {
width,
...(labelsColumn?.width === 'auto' ? { minWidth: '200px', flexGrow: 1 } : {})
flexShrink: 0
};
return (

View File

@@ -24,6 +24,7 @@ interface TitleColumnProps {
onEditTaskName: (editing: boolean) => void;
onTaskNameChange: (name: string) => void;
onTaskNameSave: () => void;
depth?: number;
}
export const TitleColumn: React.FC<TitleColumnProps> = memo(({
@@ -36,7 +37,8 @@ export const TitleColumn: React.FC<TitleColumnProps> = memo(({
taskName,
onEditTaskName,
onTaskNameChange,
onTaskNameSave
onTaskNameSave,
depth = 0
}) => {
const dispatch = useAppDispatch();
const { socket, connected } = useSocket();
@@ -150,11 +152,16 @@ export const TitleColumn: React.FC<TitleColumnProps> = memo(({
/* Normal layout when not editing */
<>
<div className="flex items-center flex-1 min-w-0">
{/* Indentation for subtasks - tighter spacing */}
{isSubtask && <div className="w-4 flex-shrink-0" />}
{/* Indentation for subtasks - reduced spacing for level 1 */}
{isSubtask && <div className="w-2 flex-shrink-0" />}
{/* Expand/Collapse button - only show for parent tasks */}
{!isSubtask && (
{/* Additional indentation for deeper levels - increased spacing for level 2+ */}
{Array.from({ length: depth }).map((_, i) => (
<div key={i} className="w-6 flex-shrink-0" />
))}
{/* Expand/Collapse button - show for any task that can have sub-tasks */}
{depth < 2 && ( // Only show if not at maximum depth (can still have children)
<button
onClick={handleToggleExpansion}
className={`flex h-4 w-4 items-center justify-center rounded-sm text-xs mr-1 hover:border hover:border-blue-500 hover:bg-blue-50 dark:hover:bg-blue-900/20 hover:scale-110 transition-all duration-300 ease-out flex-shrink-0 ${
@@ -175,8 +182,8 @@ export const TitleColumn: React.FC<TitleColumnProps> = memo(({
</button>
)}
{/* Additional indentation for subtasks after the expand button space */}
{isSubtask && <div className="w-2 flex-shrink-0" />}
{/* Additional indentation for subtasks after the expand button space - reduced for level 1 */}
{isSubtask && <div className="w-1 flex-shrink-0" />}
<div className="flex items-center gap-2 flex-1 min-w-0">
{/* Task name with dynamic width */}
@@ -202,8 +209,8 @@ export const TitleColumn: React.FC<TitleColumnProps> = memo(({
{/* Indicators container - flex-shrink-0 to prevent compression */}
<div className="flex items-center gap-1 flex-shrink-0">
{/* Subtask count indicator - only show if count > 0 */}
{!isSubtask && task.sub_tasks_count != null && task.sub_tasks_count > 0 && (
{/* Subtask count indicator - show for any task that can have sub-tasks */}
{depth < 2 && task.sub_tasks_count != null && task.sub_tasks_count > 0 && (
<Tooltip title={t(`indicators.tooltips.subtasks${task.sub_tasks_count === 1 ? '' : '_plural'}`, { count: task.sub_tasks_count })}>
<div className="flex items-center gap-1 px-1.5 py-0.5 bg-blue-50 dark:bg-blue-900/20 rounded text-xs">
<span className="text-blue-600 dark:text-blue-400 font-medium">

View File

@@ -19,10 +19,10 @@ export const BASE_COLUMNS = [
{ id: 'title', label: 'taskColumn', width: '470px', isSticky: true, key: COLUMN_KEYS.NAME },
{ id: 'description', label: 'descriptionColumn', width: '260px', key: COLUMN_KEYS.DESCRIPTION },
{ id: 'progress', label: 'progressColumn', width: '120px', key: COLUMN_KEYS.PROGRESS },
{ id: 'assignees', label: 'assigneesColumn', width: '150px', key: COLUMN_KEYS.ASSIGNEES },
{ id: 'labels', label: 'labelsColumn', width: 'auto', key: COLUMN_KEYS.LABELS },
{ id: 'phase', label: 'phaseColumn', width: '120px', key: COLUMN_KEYS.PHASE },
{ id: 'status', label: 'statusColumn', width: '120px', key: COLUMN_KEYS.STATUS },
{ id: 'assignees', label: 'assigneesColumn', width: '150px', key: COLUMN_KEYS.ASSIGNEES },
{ id: 'labels', label: 'labelsColumn', width: '250px', key: COLUMN_KEYS.LABELS },
{ id: 'phase', label: 'phaseColumn', width: '120px', key: COLUMN_KEYS.PHASE },
{ id: 'priority', label: 'priorityColumn', width: '120px', key: COLUMN_KEYS.PRIORITY },
{ id: 'timeTracking', label: 'timeTrackingColumn', width: '120px', key: COLUMN_KEYS.TIME_TRACKING },
{ id: 'estimation', label: 'estimationColumn', width: '120px', key: COLUMN_KEYS.ESTIMATION },

View File

@@ -1,12 +1,142 @@
import { useState, useCallback } from 'react';
import { DragEndEvent, DragOverEvent, DragStartEvent } from '@dnd-kit/core';
import { useAppDispatch } from '@/hooks/useAppDispatch';
import { reorderTasksInGroup, moveTaskBetweenGroups } from '@/features/task-management/task-management.slice';
import { Task, TaskGroup } from '@/types/task-management.types';
import { useAppSelector } from '@/hooks/useAppSelector';
import { reorderTasksInGroup } from '@/features/task-management/task-management.slice';
import { selectCurrentGrouping } from '@/features/task-management/grouping.slice';
import { Task, TaskGroup, getSortOrderField } from '@/types/task-management.types';
import { useSocket } from '@/socket/socketContext';
import { SocketEvents } from '@/shared/socket-events';
import { useParams } from 'react-router-dom';
import { useAuthService } from '@/hooks/useAuth';
import logger from '@/utils/errorLogger';
export const useDragAndDrop = (allTasks: Task[], groups: TaskGroup[]) => {
const dispatch = useAppDispatch();
const { socket, connected } = useSocket();
const { projectId } = useParams();
const currentGrouping = useAppSelector(selectCurrentGrouping);
const currentSession = useAuthService().getCurrentSession();
const [activeId, setActiveId] = useState<string | null>(null);
const [overId, setOverId] = useState<string | null>(null);
// Helper function to emit socket event for persistence
const emitTaskSortChange = useCallback(
(taskId: string, sourceGroup: TaskGroup, targetGroup: TaskGroup, insertIndex: number) => {
if (!socket || !connected || !projectId) {
logger.warning('Socket not connected or missing project ID');
return;
}
const task = allTasks.find(t => t.id === taskId);
if (!task) {
logger.error('Task not found for socket emission:', taskId);
return;
}
// Get team_id from current session
const teamId = currentSession?.team_id || '';
// Use new bulk update approach - recalculate ALL task orders to prevent duplicates
const taskUpdates: any[] = [];
// Create a copy of all groups and perform the move operation
const updatedGroups = groups.map(group => ({
...group,
taskIds: [...group.taskIds]
}));
// Find the source and target groups in our copy
const sourceGroupCopy = updatedGroups.find(g => g.id === sourceGroup.id)!;
const targetGroupCopy = updatedGroups.find(g => g.id === targetGroup.id)!;
if (sourceGroup.id === targetGroup.id) {
// Same group - reorder within the group
const sourceIndex = sourceGroupCopy.taskIds.indexOf(taskId);
// Remove task from old position
sourceGroupCopy.taskIds.splice(sourceIndex, 1);
// Insert at new position
sourceGroupCopy.taskIds.splice(insertIndex, 0, taskId);
} else {
// Different groups - move task between groups
// Remove from source group
const sourceIndex = sourceGroupCopy.taskIds.indexOf(taskId);
sourceGroupCopy.taskIds.splice(sourceIndex, 1);
// Add to target group
targetGroupCopy.taskIds.splice(insertIndex, 0, taskId);
}
// Now assign sequential sort orders to ALL tasks across ALL groups
let currentSortOrder = 0;
updatedGroups.forEach(group => {
group.taskIds.forEach(id => {
const update: any = {
task_id: id,
sort_order: currentSortOrder
};
// Add group-specific fields for the moved task if it changed groups
if (id === taskId && sourceGroup.id !== targetGroup.id) {
if (currentGrouping === 'status') {
update.status_id = targetGroup.id;
} else if (currentGrouping === 'priority') {
update.priority_id = targetGroup.id;
} else if (currentGrouping === 'phase') {
update.phase_id = targetGroup.id;
}
}
taskUpdates.push(update);
currentSortOrder++;
});
});
const socketData = {
project_id: projectId,
group_by: currentGrouping || 'status',
task_updates: taskUpdates,
from_group: sourceGroup.id,
to_group: targetGroup.id,
task: {
id: task.id,
project_id: projectId,
status: task.status || '',
priority: task.priority || '',
},
team_id: teamId,
};
socket.emit(SocketEvents.TASK_SORT_ORDER_CHANGE.toString(), socketData);
// Also emit the specific grouping field change event for the moved task
if (sourceGroup.id !== targetGroup.id) {
if (currentGrouping === 'phase') {
// Emit phase change event
socket.emit(SocketEvents.TASK_PHASE_CHANGE.toString(), {
task_id: taskId,
phase_id: targetGroup.id,
parent_task: task.parent_task_id || null,
});
} else if (currentGrouping === 'priority') {
// Emit priority change event
socket.emit(SocketEvents.TASK_PRIORITY_CHANGE.toString(), JSON.stringify({
task_id: taskId,
priority_id: targetGroup.id,
team_id: teamId,
}));
} else if (currentGrouping === 'status') {
// Emit status change event
socket.emit(SocketEvents.TASK_STATUS_CHANGE.toString(), JSON.stringify({
task_id: taskId,
status_id: targetGroup.id,
team_id: teamId,
}));
}
}
},
[socket, connected, projectId, allTasks, groups, currentGrouping, currentSession]
);
const handleDragStart = useCallback((event: DragStartEvent) => {
setActiveId(event.active.id as string);
@@ -16,11 +146,17 @@ export const useDragAndDrop = (allTasks: Task[], groups: TaskGroup[]) => {
(event: DragOverEvent) => {
const { active, over } = event;
if (!over) return;
if (!over) {
setOverId(null);
return;
}
const activeId = active.id;
const overId = over.id;
// Set the overId for drop indicators
setOverId(overId as string);
// Find the active task and the item being dragged over
const activeTask = allTasks.find(task => task.id === activeId);
if (!activeTask) return;
@@ -38,15 +174,6 @@ export const useDragAndDrop = (allTasks: Task[], groups: TaskGroup[]) => {
}
if (!activeGroup || !targetGroup) return;
// If dragging to a different group, we need to handle cross-group movement
if (activeGroup.id !== targetGroup.id) {
console.log('Cross-group drag detected:', {
activeTask: activeTask.id,
fromGroup: activeGroup.id,
toGroup: targetGroup.id,
});
}
},
[allTasks, groups]
);
@@ -55,6 +182,7 @@ export const useDragAndDrop = (allTasks: Task[], groups: TaskGroup[]) => {
(event: DragEndEvent) => {
const { active, over } = event;
setActiveId(null);
setOverId(null);
if (!over || active.id === over.id) {
return;
@@ -66,22 +194,27 @@ export const useDragAndDrop = (allTasks: Task[], groups: TaskGroup[]) => {
// Find the active task
const activeTask = allTasks.find(task => task.id === activeId);
if (!activeTask) {
console.error('Active task not found:', activeId);
logger.error('Active task not found:', activeId);
return;
}
// Find the groups
const activeGroup = groups.find(group => group.taskIds.includes(activeTask.id));
if (!activeGroup) {
console.error('Could not find active group for task:', activeId);
logger.error('Could not find active group for task:', activeId);
return;
}
// Check if we're dropping on a task or a group
// Check if we're dropping on a task, group, or empty group
const overTask = allTasks.find(task => task.id === overId);
const overGroup = groups.find(group => group.id === overId);
// Check if dropping on empty group drop zone
const isEmptyGroupDrop = typeof overId === 'string' && overId.startsWith('empty-group-');
const emptyGroupId = isEmptyGroupDrop ? overId.replace('empty-group-', '') : null;
const emptyGroup = emptyGroupId ? groups.find(group => group.id === emptyGroupId) : null;
let targetGroup = overGroup;
let targetGroup = overGroup || emptyGroup;
let insertIndex = 0;
if (overTask) {
@@ -94,27 +227,20 @@ export const useDragAndDrop = (allTasks: Task[], groups: TaskGroup[]) => {
// Dropping on a group (at the end)
targetGroup = overGroup;
insertIndex = targetGroup.taskIds.length;
} else if (emptyGroup) {
// Dropping on an empty group
targetGroup = emptyGroup;
insertIndex = 0; // First position in empty group
}
if (!targetGroup) {
console.error('Could not find target group');
logger.error('Could not find target group');
return;
}
const isCrossGroup = activeGroup.id !== targetGroup.id;
const activeIndex = activeGroup.taskIds.indexOf(activeTask.id);
console.log('Drag operation:', {
activeId,
overId,
activeTask: activeTask.name || activeTask.title,
activeGroup: activeGroup.id,
targetGroup: targetGroup.id,
activeIndex,
insertIndex,
isCrossGroup,
});
if (isCrossGroup) {
// Moving task between groups
console.log('Moving task between groups:', {
@@ -124,16 +250,8 @@ export const useDragAndDrop = (allTasks: Task[], groups: TaskGroup[]) => {
newPosition: insertIndex,
});
// Move task to the target group
dispatch(
moveTaskBetweenGroups({
taskId: activeId as string,
sourceGroupId: activeGroup.id,
targetGroupId: targetGroup.id,
})
);
// Reorder task within target group at drop position
// reorderTasksInGroup handles both same-group and cross-group moves
// No need for separate moveTaskBetweenGroups call
dispatch(
reorderTasksInGroup({
sourceTaskId: activeId as string,
@@ -142,15 +260,10 @@ export const useDragAndDrop = (allTasks: Task[], groups: TaskGroup[]) => {
destinationGroupId: targetGroup.id,
})
);
} else {
// Reordering within the same group
console.log('Reordering task within same group:', {
task: activeTask.name || activeTask.title,
group: activeGroup.title,
from: activeIndex,
to: insertIndex,
});
// Emit socket event for persistence
emitTaskSortChange(activeId as string, activeGroup, targetGroup, insertIndex);
} else {
if (activeIndex !== insertIndex) {
// Reorder task within same group at drop position
dispatch(
@@ -161,14 +274,18 @@ export const useDragAndDrop = (allTasks: Task[], groups: TaskGroup[]) => {
destinationGroupId: activeGroup.id,
})
);
// Emit socket event for persistence
emitTaskSortChange(activeId as string, activeGroup, targetGroup, insertIndex);
}
}
},
[allTasks, groups, dispatch]
[allTasks, groups, dispatch, emitTaskSortChange]
);
return {
activeId,
overId,
handleDragStart,
handleDragOver,
handleDragEnd,

View File

@@ -58,6 +58,9 @@ interface UseTaskRowColumnsProps {
// Drag and drop
attributes: any;
listeners: any;
// Depth for nested subtasks
depth?: number;
}
export const useTaskRowColumns = ({
@@ -84,6 +87,7 @@ export const useTaskRowColumns = ({
handleTaskNameEdit,
attributes,
listeners,
depth = 0,
}: UseTaskRowColumnsProps) => {
const renderColumn = useCallback((columnId: string, width: string, isSticky?: boolean, index?: number) => {
@@ -128,6 +132,7 @@ export const useTaskRowColumns = ({
onEditTaskName={setEditTaskName}
onTaskNameChange={setTaskName}
onTaskNameSave={handleTaskNameSave}
depth={depth}
/>
);

View File

@@ -7,7 +7,7 @@ import {
EntityId,
createSelector,
} from '@reduxjs/toolkit';
import { Task, TaskManagementState, TaskGroup, TaskGrouping } from '@/types/task-management.types';
import { Task, TaskManagementState, TaskGroup, TaskGrouping, getSortOrderField } from '@/types/task-management.types';
import { ITaskListColumn } from '@/types/tasks/taskList.types';
import { RootState } from '@/app/store';
import {
@@ -660,12 +660,12 @@ const taskManagementSlice = createSlice({
const [removed] = newTasks.splice(newTasks.indexOf(sourceTaskId), 1);
newTasks.splice(newTasks.indexOf(destinationTaskId), 0, removed);
group.taskIds = newTasks;
// Update order for affected tasks. Assuming simple reordering affects order.
// This might need more sophisticated logic based on how `order` is used.
// Update order for affected tasks using the appropriate sort field
const sortField = getSortOrderField(state.grouping?.id);
newTasks.forEach((id, index) => {
if (newEntities[id]) {
newEntities[id] = { ...newEntities[id], order: index };
newEntities[id] = { ...newEntities[id], [sortField]: index };
}
});
}
@@ -673,11 +673,11 @@ const taskManagementSlice = createSlice({
// Moving between different groups
const sourceGroup = state.groups.find(g => g.id === sourceGroupId);
const destinationGroup = state.groups.find(g => g.id === destinationGroupId);
if (sourceGroup && destinationGroup) {
// Remove from source group
sourceGroup.taskIds = sourceGroup.taskIds.filter(id => id !== sourceTaskId);
// Add to destination group at the correct position relative to destinationTask
const destinationIndex = destinationGroup.taskIds.indexOf(destinationTaskId);
if (destinationIndex !== -1) {
@@ -685,50 +685,17 @@ const taskManagementSlice = createSlice({
} else {
destinationGroup.taskIds.push(sourceTaskId); // Add to end if destination task not found
}
// Update task's grouping field to reflect new group (e.g., status, priority, phase)
// This assumes the group ID directly corresponds to the task's field value
if (sourceTask) {
let updatedTask = { ...sourceTask };
switch (state.grouping?.id) {
case IGroupBy.STATUS:
updatedTask.status = destinationGroup.id;
break;
case IGroupBy.PRIORITY:
updatedTask.priority = destinationGroup.id;
break;
case IGroupBy.PHASE:
// Handle unmapped group specially
if (destinationGroup.id === 'Unmapped' || destinationGroup.title === 'Unmapped') {
updatedTask.phase = ''; // Clear phase for unmapped group
} else {
updatedTask.phase = destinationGroup.id;
}
break;
case IGroupBy.MEMBERS:
// If moving to a member group, ensure task is assigned to that member
// This assumes the group ID is the member ID
if (!updatedTask.assignees) {
updatedTask.assignees = [];
}
if (!updatedTask.assignees.includes(destinationGroup.id)) {
updatedTask.assignees.push(destinationGroup.id);
}
// If moving from a member group, and the task is no longer in any member group,
// consider removing the assignment (more complex logic might be needed here)
break;
default:
break;
}
newEntities[sourceTaskId] = updatedTask;
}
// Update order for affected tasks in both groups if necessary
// Do NOT update the task's grouping field (priority, phase, status) here.
// This will be handled by the socket event handler after backend confirmation.
// Update order for affected tasks in both groups using the appropriate sort field
const sortField = getSortOrderField(state.grouping?.id);
sourceGroup.taskIds.forEach((id, index) => {
if (newEntities[id]) newEntities[id] = { ...newEntities[id], order: index };
if (newEntities[id]) newEntities[id] = { ...newEntities[id], [sortField]: index };
});
destinationGroup.taskIds.forEach((id, index) => {
if (newEntities[id]) newEntities[id] = { ...newEntities[id], order: index };
if (newEntities[id]) newEntities[id] = { ...newEntities[id], [sortField]: index };
});
}
}
@@ -958,8 +925,26 @@ const taskManagementSlice = createSlice({
.addCase(fetchTasksV3.fulfilled, (state, action) => {
state.loading = false;
const { allTasks, groups, grouping } = action.payload;
tasksAdapter.setAll(state as EntityState<Task, string>, allTasks || []); // Ensure allTasks is an array
state.ids = (allTasks || []).map(task => task.id); // Also update ids
// Preserve existing timer state from old tasks before replacing
const oldTasks = state.entities;
const tasksWithTimers = (allTasks || []).map(task => {
const oldTask = oldTasks[task.id];
if (oldTask?.timeTracking?.activeTimer) {
// Preserve the timer state from the old task
return {
...task,
timeTracking: {
...task.timeTracking,
activeTimer: oldTask.timeTracking.activeTimer
}
};
}
return task;
});
tasksAdapter.setAll(state as EntityState<Task, string>, tasksWithTimers); // Ensure allTasks is an array
state.ids = tasksWithTimers.map(task => task.id); // Also update ids
state.groups = groups;
state.grouping = grouping;
})
@@ -1010,7 +995,7 @@ const taskManagementSlice = createSlice({
order: subtask.sort_order || subtask.order || 0,
parent_task_id: parentTaskId,
is_sub_task: true,
sub_tasks_count: 0,
sub_tasks_count: subtask.sub_tasks_count || 0, // Use actual count from backend
show_sub_tasks: false,
}));

View File

@@ -14,10 +14,10 @@ const DEFAULT_FIELDS: TaskListField[] = [
{ key: 'KEY', label: 'Key', visible: false, order: 1 },
{ key: 'DESCRIPTION', label: 'Description', visible: false, order: 2 },
{ key: 'PROGRESS', label: 'Progress', visible: true, order: 3 },
{ key: 'ASSIGNEES', label: 'Assignees', visible: true, order: 4 },
{ key: 'LABELS', label: 'Labels', visible: true, order: 5 },
{ key: 'PHASE', label: 'Phase', visible: true, order: 6 },
{ key: 'STATUS', label: 'Status', visible: true, order: 7 },
{ key: 'STATUS', label: 'Status', visible: true, order: 4 },
{ key: 'ASSIGNEES', label: 'Assignees', visible: true, order: 5 },
{ key: 'LABELS', label: 'Labels', visible: true, order: 6 },
{ key: 'PHASE', label: 'Phase', visible: true, order: 7 },
{ key: 'PRIORITY', label: 'Priority', visible: true, order: 8 },
{ key: 'TIME_TRACKING', label: 'Time Tracking', visible: true, order: 9 },
{ key: 'ESTIMATION', label: 'Estimation', visible: false, order: 10 },

View File

@@ -33,6 +33,7 @@ import {
updateTaskDescription,
updateSubTasks,
updateTaskProgress,
updateTaskTimeTracking,
} from '@/features/tasks/tasks.slice';
import {
addTask,
@@ -936,6 +937,8 @@ export const useTaskSocketHandlers = () => {
const { task_id, start_time } = typeof data === 'string' ? JSON.parse(data) : data;
if (!task_id) return;
const timerTimestamp = start_time ? (typeof start_time === 'number' ? start_time : parseInt(start_time)) : Date.now();
// Update the task-management slice to include timer state
const currentTask = store.getState().taskManagement.entities[task_id];
if (currentTask) {
@@ -943,13 +946,16 @@ export const useTaskSocketHandlers = () => {
...currentTask,
timeTracking: {
...currentTask.timeTracking,
activeTimer: start_time ? (typeof start_time === 'number' ? start_time : parseInt(start_time)) : Date.now(),
activeTimer: timerTimestamp,
},
updatedAt: new Date().toISOString(),
updated_at: new Date().toISOString(),
};
dispatch(updateTask(updatedTask));
}
// Also update the tasks slice activeTimers to keep both slices in sync
dispatch(updateTaskTimeTracking({ taskId: task_id, timeTracking: timerTimestamp }));
} catch (error) {
logger.error('Error handling timer start event:', error);
}
@@ -975,11 +981,79 @@ export const useTaskSocketHandlers = () => {
};
dispatch(updateTask(updatedTask));
}
// Also update the tasks slice activeTimers to keep both slices in sync
dispatch(updateTaskTimeTracking({ taskId: task_id, timeTracking: null }));
} catch (error) {
logger.error('Error handling timer stop event:', error);
}
}, [dispatch]);
// Handler for task sort order change events
const handleTaskSortOrderChange = useCallback((data: any[]) => {
try {
if (!Array.isArray(data) || data.length === 0) return;
// DEBUG: Log the data received from the backend
console.log('[TASK_SORT_ORDER_CHANGE] Received data:', data);
// Get canonical lists from Redux
const state = store.getState();
const priorityList = state.priorityReducer?.priorities || [];
const phaseList = state.phaseReducer?.phaseList || [];
const statusList = state.taskStatusReducer?.status || [];
// The backend sends an array of tasks with updated sort orders and possibly grouping fields
data.forEach((taskData: any) => {
const currentTask = state.taskManagement.entities[taskData.id];
if (currentTask) {
let updatedTask: Task = {
...currentTask,
order: taskData.sort_order || taskData.current_sort_order || currentTask.order,
updatedAt: new Date().toISOString(),
updated_at: new Date().toISOString(),
};
// Update grouping fields if present
if (typeof taskData.priority_id !== 'undefined') {
const found = priorityList.find(p => p.id === taskData.priority_id);
if (found) {
updatedTask.priority = found.name;
// updatedTask.priority_id = found.id; // Only if Task type has priority_id
} else {
updatedTask.priority = taskData.priority_id || '';
// updatedTask.priority_id = taskData.priority_id;
}
}
if (typeof taskData.phase_id !== 'undefined') {
const found = phaseList.find(p => p.id === taskData.phase_id);
if (found) {
updatedTask.phase = found.name;
// updatedTask.phase_id = found.id; // Only if Task type has phase_id
} else {
updatedTask.phase = taskData.phase_id || '';
// updatedTask.phase_id = taskData.phase_id;
}
}
if (typeof taskData.status_id !== 'undefined') {
const found = statusList.find(s => s.id === taskData.status_id);
if (found) {
updatedTask.status = found.name;
// updatedTask.status_id = found.id; // Only if Task type has status_id
} else {
updatedTask.status = taskData.status_id || '';
// updatedTask.status_id = taskData.status_id;
}
}
dispatch(updateTask(updatedTask));
}
});
} catch (error) {
logger.error('Error handling task sort order change event:', error);
}
}, [dispatch]);
// Register socket event listeners
useEffect(() => {
if (!socket) return;
@@ -1013,6 +1087,7 @@ export const useTaskSocketHandlers = () => {
{ event: SocketEvents.TASK_CUSTOM_COLUMN_UPDATE.toString(), handler: handleCustomColumnUpdate },
{ event: SocketEvents.TASK_TIMER_START.toString(), handler: handleTimerStart },
{ event: SocketEvents.TASK_TIMER_STOP.toString(), handler: handleTimerStop },
{ event: SocketEvents.TASK_SORT_ORDER_CHANGE.toString(), handler: handleTaskSortOrderChange },
];
@@ -1047,6 +1122,7 @@ export const useTaskSocketHandlers = () => {
handleCustomColumnUpdate,
handleTimerStart,
handleTimerStop,
handleTaskSortOrderChange,
]);
};

View File

@@ -50,7 +50,11 @@ export const useTaskTimer = (taskId: string, initialStartTime: number | null) =>
// Timer management effect
useEffect(() => {
if (started && localStarted && reduxStartTime) {
if (started && reduxStartTime) {
// Sync local state with Redux state
if (!localStarted) {
setLocalStarted(true);
}
clearTimerInterval();
timerTick();
intervalRef.current = setInterval(timerTick, 1000);

View File

@@ -0,0 +1,79 @@
import { useEffect, useRef } from 'react';
import { useAppDispatch } from '@/hooks/useAppDispatch';
import { updateTaskTimeTracking } from '@/features/tasks/tasks.slice';
import { updateTask } from '@/features/task-management/task-management.slice';
import { taskTimeLogsApiService } from '@/api/tasks/task-time-logs.api.service';
import { store } from '@/app/store';
import { Task } from '@/types/task-management.types';
import logger from '@/utils/errorLogger';
import moment from 'moment';
export const useTimerInitialization = () => {
const dispatch = useAppDispatch();
const hasInitialized = useRef(false);
useEffect(() => {
const initializeTimers = async () => {
// Prevent duplicate initialization
if (hasInitialized.current) {
return;
}
try {
hasInitialized.current = true;
// Fetch running timers from backend
const response = await taskTimeLogsApiService.getRunningTimers();
if (response && response.done && Array.isArray(response.body)) {
const runningTimers = response.body;
// Update Redux state for each running timer
runningTimers.forEach(timer => {
if (timer.task_id && timer.start_time) {
try {
// Convert start_time to timestamp
const startTime = moment(timer.start_time);
if (startTime.isValid()) {
const timestamp = startTime.valueOf();
// Update the tasks slice activeTimers
dispatch(updateTaskTimeTracking({
taskId: timer.task_id,
timeTracking: timestamp
}));
// Update the task-management slice if the task exists
const currentTask = store.getState().taskManagement.entities[timer.task_id];
if (currentTask) {
const updatedTask: Task = {
...currentTask,
timeTracking: {
...currentTask.timeTracking,
activeTimer: timestamp,
},
updatedAt: new Date().toISOString(),
updated_at: new Date().toISOString(),
};
dispatch(updateTask(updatedTask));
}
}
} catch (error) {
logger.error(`Error initializing timer for task ${timer.task_id}:`, error);
}
}
});
if (runningTimers.length > 0) {
logger.info(`Initialized ${runningTimers.length} running timers from backend`);
}
}
} catch (error) {
logger.error('Error initializing timers from backend:', error);
}
};
// Initialize timers when the hook mounts
initializeTimers();
}, [dispatch]);
};

View File

@@ -1,5 +1,5 @@
import React, { useEffect } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { useSelector } from 'react-redux';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
import { Space, Steps, Button, Typography } from 'antd/es';
@@ -26,6 +26,7 @@ import { validateEmail } from '@/utils/validateEmail';
import { sanitizeInput } from '@/utils/sanitizeInput';
import logo from '@/assets/images/worklenz-light-mode.png';
import logoDark from '@/assets/images/worklenz-dark-mode.png';
import { useAppDispatch } from '@/hooks/useAppDispatch';
import './account-setup.css';
import { IAccountSetupRequest } from '@/types/project-templates/project-templates.types';
@@ -34,7 +35,7 @@ import { profileSettingsApiService } from '@/api/settings/profile/profile-settin
const { Title } = Typography;
const AccountSetup: React.FC = () => {
const dispatch = useDispatch();
const dispatch = useAppDispatch();
const { t } = useTranslation('account-setup');
useDocumentTitle(t('setupYourAccount', 'Account Setup'));
const navigate = useNavigate();
@@ -52,8 +53,7 @@ const AccountSetup: React.FC = () => {
trackMixpanelEvent(evt_account_setup_visit);
const verifyAuthStatus = async () => {
try {
const response = (await dispatch(verifyAuthentication()).unwrap())
.payload as IAuthorizeResponse;
const response = await dispatch(verifyAuthentication()).unwrap() as IAuthorizeResponse;
if (response?.authenticated) {
setSession(response.user);
dispatch(setUser(response.user));
@@ -163,6 +163,18 @@ const AccountSetup: React.FC = () => {
const res = await profileSettingsApiService.setupAccount(model);
if (res.done && res.body.id) {
trackMixpanelEvent(skip ? evt_account_setup_skip_invite : evt_account_setup_complete);
// Refresh user session to update setup_completed status
try {
const authResponse = await dispatch(verifyAuthentication()).unwrap() as IAuthorizeResponse;
if (authResponse?.authenticated && authResponse?.user) {
setSession(authResponse.user);
dispatch(setUser(authResponse.user));
}
} catch (error) {
logger.error('Failed to refresh user session after setup completion', error);
}
navigate(`/worklenz/projects/${res.body.id}?tab=tasks-list&pinned_tab=tasks-list`);
}
} catch (error) {

View File

@@ -5,6 +5,7 @@ import { useTranslation } from 'react-i18next';
import { useAuthService } from '@/hooks/useAuth';
import { useMediaQuery } from 'react-responsive';
import { authApiService } from '@/api/auth/auth.api.service';
import CacheCleanup from '@/utils/cache-cleanup';
const LoggingOutPage = () => {
const navigate = useNavigate();
@@ -14,14 +15,30 @@ const LoggingOutPage = () => {
useEffect(() => {
const logout = async () => {
await auth.signOut();
await authApiService.logout();
setTimeout(() => {
window.location.href = '/';
}, 1500);
try {
// Clear local session
await auth.signOut();
// Call backend logout
await authApiService.logout();
// Clear all caches using the utility
await CacheCleanup.clearAllCaches();
// Force a hard reload to ensure fresh state
setTimeout(() => {
CacheCleanup.forceReload('/auth/login');
}, 1000);
} catch (error) {
console.error('Logout error:', error);
// Fallback: force reload to login page
CacheCleanup.forceReload('/auth/login');
}
};
void logout();
}, [auth, navigate]);
}, [auth]);
const cardStyles = {
width: '100%',

View File

@@ -39,6 +39,7 @@ import { resetState as resetEnhancedKanbanState } from '@/features/enhanced-kanb
import { setProjectId as setInsightsProjectId } from '@/features/projects/insights/project-insights.slice';
import { SuspenseFallback } from '@/components/suspense-fallback/suspense-fallback';
import { useTranslation } from 'react-i18next';
import { useTimerInitialization } from '@/hooks/useTimerInitialization';
// Import critical components synchronously to avoid suspense interruptions
@@ -89,6 +90,9 @@ const ProjectView = React.memo(() => {
const [taskid, setTaskId] = useState<string>(urlParams.taskId);
const [isInitialized, setIsInitialized] = useState(false);
// Initialize timer state from backend when project view loads
useTimerInitialization();
// Update local state when URL params change
useEffect(() => {
setActiveTab(urlParams.tab);

View File

@@ -41,6 +41,10 @@ export interface Task {
has_subscribers?: boolean;
schedule_id?: string | null;
order?: number;
status_sort_order?: number; // Sort order when grouped by status
priority_sort_order?: number; // Sort order when grouped by priority
phase_sort_order?: number; // Sort order when grouped by phase
member_sort_order?: number; // Sort order when grouped by members
reporter?: string; // Reporter field
timeTracking?: { // Time tracking information
logged?: number;
@@ -173,3 +177,21 @@ export interface BulkAction {
value?: any;
taskIds: string[];
}
// Helper function to get the appropriate sort order field based on grouping
export function getSortOrderField(grouping: string | undefined): keyof Task {
switch (grouping) {
case 'status':
return 'status_sort_order';
case 'priority':
return 'priority_sort_order';
case 'phase':
return 'phase_sort_order';
case 'members':
return 'member_sort_order';
case 'general':
return 'order'; // explicit general sorting
default:
return 'status_sort_order'; // Default to status sorting to match backend
}
}

View File

@@ -0,0 +1,163 @@
/**
* Cache cleanup utilities for logout operations
* Handles clearing of various caches to prevent stale data issues
*/
export class CacheCleanup {
/**
* Clear all caches including service worker, browser cache, and storage
*/
static async clearAllCaches(): Promise<void> {
try {
console.log('CacheCleanup: Starting cache clearing process...');
// Clear browser caches
if ('caches' in window) {
const cacheNames = await caches.keys();
console.log('CacheCleanup: Found caches:', cacheNames);
await Promise.all(
cacheNames.map(async cacheName => {
const deleted = await caches.delete(cacheName);
console.log(`CacheCleanup: Deleted cache "${cacheName}":`, deleted);
return deleted;
})
);
console.log('CacheCleanup: Browser caches cleared');
} else {
console.log('CacheCleanup: Cache API not supported');
}
// Clear service worker cache
if ('serviceWorker' in navigator) {
const registration = await navigator.serviceWorker.getRegistration();
if (registration) {
console.log('CacheCleanup: Found service worker registration');
// Send logout message to service worker to clear its caches and unregister
if (registration.active) {
try {
console.log('CacheCleanup: Sending LOGOUT message to service worker...');
await this.sendMessageToServiceWorker('LOGOUT');
console.log('CacheCleanup: LOGOUT message sent successfully');
} catch (error) {
console.warn('CacheCleanup: Failed to send logout message to service worker:', error);
// Fallback: try to clear cache manually
try {
console.log('CacheCleanup: Trying fallback CLEAR_CACHE message...');
await this.sendMessageToServiceWorker('CLEAR_CACHE');
console.log('CacheCleanup: CLEAR_CACHE message sent successfully');
} catch (fallbackError) {
console.warn('CacheCleanup: Failed to clear service worker cache:', fallbackError);
}
}
}
// If service worker is still registered, unregister it
if (registration.active) {
console.log('CacheCleanup: Unregistering service worker...');
await registration.unregister();
console.log('CacheCleanup: Service worker unregistered');
}
} else {
console.log('CacheCleanup: No service worker registration found');
}
} else {
console.log('CacheCleanup: Service Worker not supported');
}
// Clear localStorage and sessionStorage
const localStorageKeys = Object.keys(localStorage);
const sessionStorageKeys = Object.keys(sessionStorage);
console.log('CacheCleanup: Clearing localStorage keys:', localStorageKeys);
console.log('CacheCleanup: Clearing sessionStorage keys:', sessionStorageKeys);
localStorage.clear();
sessionStorage.clear();
console.log('CacheCleanup: Local storage cleared');
console.log('CacheCleanup: Cache clearing process completed successfully');
} catch (error) {
console.error('CacheCleanup: Error clearing caches:', error);
throw error;
}
}
/**
* Send message to service worker
*/
private static async sendMessageToServiceWorker(type: string, payload?: any): Promise<any> {
if (!('serviceWorker' in navigator)) {
throw new Error('Service Worker not supported');
}
const registration = await navigator.serviceWorker.getRegistration();
if (!registration || !registration.active) {
throw new Error('Service Worker not active');
}
return new Promise((resolve, reject) => {
const messageChannel = new MessageChannel();
messageChannel.port1.onmessage = (event) => {
if (event.data.error) {
reject(event.data.error);
} else {
resolve(event.data);
}
};
registration.active!.postMessage(
{ type, payload },
[messageChannel.port2]
);
// Timeout after 5 seconds
setTimeout(() => {
reject(new Error('Service Worker message timeout'));
}, 5000);
});
}
/**
* Force reload the page to ensure fresh state
*/
static forceReload(url: string = '/auth/login'): void {
// Use replace to prevent back button issues
window.location.replace(url);
}
/**
* Clear specific cache types
*/
static async clearSpecificCaches(cacheTypes: string[]): Promise<void> {
if (!('caches' in window)) return;
const cacheNames = await caches.keys();
const cachesToDelete = cacheNames.filter(name =>
cacheTypes.some(type => name.includes(type))
);
await Promise.all(
cachesToDelete.map(cacheName => caches.delete(cacheName))
);
}
/**
* Clear API cache specifically
*/
static async clearAPICache(): Promise<void> {
await this.clearSpecificCaches(['api', 'dynamic']);
}
/**
* Clear static asset cache
*/
static async clearStaticCache(): Promise<void> {
await this.clearSpecificCaches(['static', 'images']);
}
}
export default CacheCleanup;