Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
122 changes: 122 additions & 0 deletions src/hooks/chat/__tests__/useConversationHandlers.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { renderHook } from '@testing-library/react';
import { useConversationHandlers } from '../useConversationHandlers';

const mockConversations = vi.hoisted(() => ({
updateConversationStatus: vi.fn(),
updateConversationPriority: vi.fn(),
markAsRead: vi.fn(),
markAsUnread: vi.fn(),
pinConversation: vi.fn(),
unpinConversation: vi.fn(),
archiveConversation: vi.fn(),
unarchiveConversation: vi.fn(),
}));

vi.mock('@/contexts/chat/ChatContext', () => ({
useChatContext: () => ({ conversations: mockConversations }),
}));

vi.mock('@/contexts/PermissionsContext', () => ({
usePermissions: () => ({ can: vi.fn().mockReturnValue(true) }),
}));

vi.mock('sonner', () => ({
toast: { error: vi.fn(), success: vi.fn() },
}));

const baseConversation = { id: 'conv-1', uuid: 'uuid-conv-1', status: 'open' } as any;

describe('useConversationHandlers', () => {
beforeEach(() => {
vi.clearAllMocks();
});

describe('handleMarkAsResolved', () => {
it('calls updateConversationStatus with resolved status', async () => {
mockConversations.updateConversationStatus.mockResolvedValueOnce({});

const { result } = renderHook(() => useConversationHandlers());
await result.current.handleMarkAsResolved(baseConversation);

expect(mockConversations.updateConversationStatus).toHaveBeenCalledWith(
'conv-1',
'resolved',
undefined,
);
});

it('re-throws when updateConversationStatus fails', async () => {
const error = new Error('API error');
mockConversations.updateConversationStatus.mockRejectedValueOnce(error);

const { result } = renderHook(() => useConversationHandlers());

await expect(
result.current.handleMarkAsResolved(baseConversation),
).rejects.toThrow('API error');
});

it('passes onReload callback to updateConversationStatus', async () => {
mockConversations.updateConversationStatus.mockResolvedValueOnce({});
const onReload = vi.fn().mockResolvedValue(undefined);

const { result } = renderHook(() => useConversationHandlers());
await result.current.handleMarkAsResolved(baseConversation, onReload);

expect(mockConversations.updateConversationStatus).toHaveBeenCalledWith(
'conv-1',
'resolved',
onReload,
);
});

it('does not swallow error — caller can gate navigation on success', async () => {
mockConversations.updateConversationStatus.mockRejectedValueOnce(new Error('fail'));

const { result } = renderHook(() => useConversationHandlers());

let threw = false;
try {
await result.current.handleMarkAsResolved(baseConversation);
} catch {
threw = true;
}

expect(threw).toBe(true);
});
});

describe('handleMarkAsResolved — selected vs non-selected (navigation gating)', () => {
it('resolves without throwing when conversation is NOT selected (non-selected path)', async () => {
mockConversations.updateConversationStatus.mockResolvedValueOnce({});

const { result } = renderHook(() => useConversationHandlers());

await expect(
result.current.handleMarkAsResolved(baseConversation),
).resolves.not.toThrow();
});

it('propagates error so Chat.tsx can skip URL navigation on failure', async () => {
mockConversations.updateConversationStatus.mockRejectedValueOnce(new Error('backend fail'));

const { result } = renderHook(() => useConversationHandlers());

const navigateMock = vi.fn();

let navigationCalled = false;
try {
await result.current.handleMarkAsResolved(baseConversation);
navigateMock('/conversations');
navigationCalled = true;
} catch {
// expected — navigation must NOT run
}

expect(navigateMock).not.toHaveBeenCalled();
expect(navigationCalled).toBe(false);
});
});
});
1 change: 1 addition & 0 deletions src/hooks/chat/useConversationHandlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ export const useConversationHandlers = () => {
await conversations.updateConversationStatus(conversation.id, 'resolved', onReload);
} catch (error) {
console.error('❌ Error marking as resolved:', error);
throw error;
}
},
[conversations],
Expand Down
50 changes: 26 additions & 24 deletions src/pages/Customer/Chat/Chat.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -377,11 +377,31 @@ const Chat = () => {
[conversationHandlers],
);

const clearSelectionAndGoToList = useCallback(async () => {
isManualNavigationRef.current = true;
await conversations.selectConversation(null);
setMobileView('list');
setIsContactSidebarOpen(false);
navigate('/conversations', { replace: true });
setTimeout(() => {
isManualNavigationRef.current = false;
}, 100);
}, [conversations, navigate]);

const handleMarkAsResolved = useCallback(
async (conversation: Conversation) => {
await conversationHandlers.handleMarkAsResolved(conversation, reloadCurrentFilters);
const resolvedId = String(conversation.uuid || conversation.id);
try {
await conversationHandlers.handleMarkAsResolved(conversation, reloadCurrentFilters);
const liveSelected = conversations.state.selectedConversationId;
if (liveSelected != null && String(liveSelected) === resolvedId) {
await clearSelectionAndGoToList();
}
} catch {
// error already toasted by updateConversationStatus
}
},
[conversationHandlers, reloadCurrentFilters],
[conversationHandlers, reloadCurrentFilters, conversations, clearSelectionAndGoToList],
);

const handlePostpone = useCallback(
Expand Down Expand Up @@ -496,13 +516,7 @@ const Chat = () => {
await conversations.deleteConversation(String(conversationToDelete.id));
setShowDeleteDialog(false);
setConversationToDelete(null);
setMobileView('list');
setIsContactSidebarOpen(false);
isManualNavigationRef.current = true;
navigate('/conversations', { replace: true });
setTimeout(() => {
isManualNavigationRef.current = false;
}, 100);
await clearSelectionAndGoToList();
} catch (error) {
console.error('Error deleting conversation:', error);
// Error is already handled in the context with toast
Expand Down Expand Up @@ -667,21 +681,9 @@ const Chat = () => {
}, 100);
};

const handleCloseConversation = () => {
// 🔒 MARCAR NAVEGAÇÃO MANUAL para evitar URL sync
isManualNavigationRef.current = true;

conversations.selectConversation(null);
setMobileView('list');
setIsContactSidebarOpen(false); // Fechar sidebar se estiver aberto
// Voltar para a lista geral de conversas
navigate('/conversations', { replace: true });

// 🔒 RESET flag após navegação
setTimeout(() => {
isManualNavigationRef.current = false;
}, 100);
};
const handleCloseConversation = useCallback(async () => {
await clearSelectionAndGoToList();
}, [clearSelectionAndGoToList]);

return (
<ErrorBoundary>
Expand Down
Loading