Repository navigation
fix(staff): keep the project screen on a background scope reload #143
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
Closed
maxidragon
wants to merge
5
commits into
develop
from
fix/time-tracking-access-request-survives-scope-reload
Closed
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
fa22c91
fix(staff): keep the project screen on a background scope reload
maxidragon 0153fb0
fix(staff): keep the screen only while the scope first settles
maxidragon 83c5c69
fix(staff): narrow the resolved-screen ref before reading it
maxidragon 405427b
fix(staff): decide on the loader from the load being replaced
maxidragon 63df8fd
test(staff): pin the board's guard state across the first scope settle
maxidragon File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
143 changes: 143 additions & 0 deletions
143
...ackend/staff/time-tracking/projects/[id]/__tests__/page.accessRequestScopeReload.test.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,143 @@ | ||
| /** | ||
| * @jest-environment jsdom | ||
| */ | ||
| // The organization switcher settles its scope shortly after mount, which bumps | ||
| // the scope version from 0 and reloads the project. When that reload lands after | ||
| // the user has requested access, it must not fall back to the full-page loader: | ||
| // that unmounts the guard state and resets "Request sent" to an enabled "Request | ||
| // access", inviting a second request for one already sent. A switch between two | ||
| // known scopes is different — nothing loaded for the old scope may stay up. | ||
| import * as React from 'react' | ||
| import { act, fireEvent, render, screen, waitFor } from '@testing-library/react' | ||
| import { apiCall, apiCallOrThrow } from '@open-mercato/ui/backend/utils/apiCall' | ||
| import TimesheetProjectDetailPage from '../page' | ||
|
|
||
| const PROJECT_ID = '11111111-1111-4111-8111-111111111111' | ||
|
|
||
| let mockScopeVersion = 0 | ||
| let holdProjectLoads = false | ||
| const heldProjectLoads: Array<() => void> = [] | ||
|
|
||
| const mockTranslate = (key: string, fallback?: string) => fallback ?? key | ||
|
|
||
| jest.mock('@open-mercato/shared/lib/i18n/context', () => ({ useT: () => mockTranslate })) | ||
|
|
||
| jest.mock('@open-mercato/shared/lib/frontend/useOrganizationScope', () => ({ | ||
| useOrganizationScopeVersion: () => mockScopeVersion, | ||
| })) | ||
|
|
||
| jest.mock('next/navigation', () => ({ | ||
| useRouter: () => ({ push: jest.fn(), replace: jest.fn() }), | ||
| usePathname: () => `/backend/staff/time-tracking/projects/${PROJECT_ID}`, | ||
| useSearchParams: () => new URLSearchParams(), | ||
| })) | ||
|
|
||
| jest.mock('@open-mercato/ui/backend/FlashMessages', () => ({ flash: jest.fn() })) | ||
|
|
||
| jest.mock('@open-mercato/ui/backend/injection/useGuardedMutation', () => ({ | ||
| useGuardedMutation: () => ({ | ||
| runMutation: async ({ operation }: { operation: () => Promise<unknown> }) => operation(), | ||
| retryLastMutation: async () => true, | ||
| }), | ||
| })) | ||
|
|
||
| jest.mock('@open-mercato/ui/backend/confirm-dialog', () => ({ | ||
| useConfirmDialog: () => ({ confirm: jest.fn(async () => true), ConfirmDialogElement: null }), | ||
| })) | ||
|
|
||
| jest.mock('@open-mercato/ui/backend/utils/apiCall', () => ({ | ||
| apiCall: jest.fn(), | ||
| apiCallOrThrow: jest.fn(), | ||
| readApiResultOrThrow: jest.fn(), | ||
| withScopedApiRequestHeaders: jest.fn( | ||
| async (_headers: Record<string, string>, run: () => Promise<unknown>) => run(), | ||
| ), | ||
| })) | ||
|
|
||
| jest.mock('@open-mercato/ui/backend/charts', () => ({ | ||
| KpiCard: ({ label }: { label: React.ReactNode }) => <div>{label}</div>, | ||
| Sparkline: () => null, | ||
| })) | ||
|
|
||
| jest.mock('../../../../../../lib/time-tracking-ui/ProjectTeamDrawer', () => ({ | ||
| ProjectTeamDrawer: () => null, | ||
| })) | ||
|
|
||
| const apiCallMock = apiCall as unknown as jest.Mock | ||
| const apiCallOrThrowMock = apiCallOrThrow as unknown as jest.Mock | ||
|
|
||
| function projectRequests(): unknown[][] { | ||
| return apiCallMock.mock.calls.filter(([url]) => String(url).startsWith('/api/staff/timesheets/time-projects?')) | ||
| } | ||
|
|
||
| beforeEach(() => { | ||
| jest.clearAllMocks() | ||
| mockScopeVersion = 0 | ||
| holdProjectLoads = false | ||
| heldProjectLoads.length = 0 | ||
| apiCallMock.mockImplementation(async (url: string) => { | ||
| if (url.startsWith('/api/staff/timesheets/time-projects?')) { | ||
| if (holdProjectLoads) await new Promise<void>((resolve) => { heldProjectLoads.push(resolve) }) | ||
| return { ok: false, status: 404, result: { error: 'Not found', reason: 'no_project_access' }, response: {} } | ||
| } | ||
| return { ok: true, status: 200, result: { items: [], granted: [] }, response: {} } | ||
| }) | ||
| apiCallOrThrowMock.mockResolvedValue({ ok: true, status: 200, result: { ok: true }, response: {} }) | ||
| }) | ||
|
|
||
| async function renderAndRequestAccess() { | ||
| const view = render(<TimesheetProjectDetailPage params={{ id: PROJECT_ID }} />) | ||
| const requestButton = await screen.findByRole('button', { name: 'Request access' }) | ||
| await act(async () => { fireEvent.click(requestButton) }) | ||
| expect((await screen.findByRole('button', { name: 'Request sent' })).hasAttribute('disabled')).toBe(true) | ||
| expect(projectRequests()).toHaveLength(1) | ||
| return view | ||
| } | ||
|
|
||
| describe('project detail — access request survives a scope reload', () => { | ||
| it('keeps "Request sent" after the organization scope settles', async () => { | ||
| const view = await renderAndRequestAccess() | ||
|
|
||
| mockScopeVersion = 1 | ||
| view.rerender(<TimesheetProjectDetailPage params={{ id: PROJECT_ID }} />) | ||
|
|
||
| await waitFor(() => expect(projectRequests()).toHaveLength(2)) | ||
| expect(screen.queryByText('Loading project...')).toBeNull() | ||
| await act(async () => { await Promise.resolve() }) | ||
| expect(screen.getByRole('button', { name: 'Request sent' }).hasAttribute('disabled')).toBe(true) | ||
| expect(apiCallOrThrowMock).toHaveBeenCalledTimes(1) | ||
| }) | ||
|
|
||
| it('reloads through the loader when switching between two known scopes', async () => { | ||
| mockScopeVersion = 1 | ||
| const view = await renderAndRequestAccess() | ||
|
|
||
| mockScopeVersion = 2 | ||
| view.rerender(<TimesheetProjectDetailPage params={{ id: PROJECT_ID }} />) | ||
|
|
||
| expect(screen.getByText('Loading project...')).toBeTruthy() | ||
| expect(screen.queryByRole('button', { name: 'Request sent' })).toBeNull() | ||
| await waitFor(() => expect(projectRequests()).toHaveLength(2)) | ||
| expect(await screen.findByRole('button', { name: 'Request access' })).toBeTruthy() | ||
| }) | ||
|
|
||
| it('reloads through the loader when a second switch cancels the first settlement', async () => { | ||
| const view = await renderAndRequestAccess() | ||
| holdProjectLoads = true | ||
|
|
||
| mockScopeVersion = 1 | ||
| view.rerender(<TimesheetProjectDetailPage params={{ id: PROJECT_ID }} />) | ||
| await waitFor(() => expect(projectRequests()).toHaveLength(2)) | ||
| expect(screen.getByRole('button', { name: 'Request sent' })).toBeTruthy() | ||
|
|
||
| mockScopeVersion = 2 | ||
| view.rerender(<TimesheetProjectDetailPage params={{ id: PROJECT_ID }} />) | ||
|
|
||
| expect(screen.getByText('Loading project...')).toBeTruthy() | ||
| expect(screen.queryByRole('button', { name: 'Request sent' })).toBeNull() | ||
|
|
||
| holdProjectLoads = false | ||
| await act(async () => { heldProjectLoads.splice(0).forEach((release) => release()) }) | ||
| expect(await screen.findByRole('button', { name: 'Request access' })).toBeTruthy() | ||
| }) | ||
| }) |
107 changes: 107 additions & 0 deletions
107
.../staff/time-tracking/projects/[id]/board/__tests__/page.accessRequestScopeReload.test.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,107 @@ | ||
| /** | ||
| * @jest-environment jsdom | ||
| */ | ||
| // The board keys its project query on the scope version, so the organization | ||
| // switcher settling the scope (version 0 → 1) re-keys it. For a caller without | ||
| // access the previous answer is `null`, and the guard state only survives the | ||
| // re-key because react-query treats `null` placeholder data as data: were the | ||
| // placeholder dropped (or the denial answered with `undefined`), the board would | ||
| // fall back to its loader and reset "Request sent" to an enabled "Request access". | ||
| // A switch between two known scopes must still go through the loader. | ||
| import * as React from 'react' | ||
| import { act, fireEvent, render, screen, waitFor } from '@testing-library/react' | ||
| import { QueryClient, QueryClientProvider } from '@tanstack/react-query' | ||
| import { apiCall, apiCallOrThrow } from '@open-mercato/ui/backend/utils/apiCall' | ||
| import ProjectBoardPage from '../page' | ||
|
|
||
| const PROJECT_ID = '11111111-1111-4111-8111-111111111111' | ||
|
|
||
| let mockScopeVersion = 0 | ||
|
|
||
| const mockTranslate = (key: string, fallback?: string) => fallback ?? key | ||
|
|
||
| jest.mock('@open-mercato/shared/lib/i18n/context', () => ({ useT: () => mockTranslate })) | ||
|
|
||
| jest.mock('@open-mercato/shared/lib/frontend/useOrganizationScope', () => ({ | ||
| useOrganizationScopeVersion: () => mockScopeVersion, | ||
| })) | ||
|
|
||
| jest.mock('@open-mercato/ui/backend/FlashMessages', () => ({ flash: jest.fn() })) | ||
|
|
||
| jest.mock('@open-mercato/ui/backend/injection/useGuardedMutation', () => ({ | ||
| useGuardedMutation: () => ({ | ||
| runMutation: async ({ operation }: { operation: () => Promise<unknown> }) => operation(), | ||
| retryLastMutation: async () => true, | ||
| }), | ||
| })) | ||
|
|
||
| jest.mock('@open-mercato/ui/backend/utils/apiCall', () => ({ | ||
| apiCall: jest.fn(), | ||
| apiCallOrThrow: jest.fn(), | ||
| })) | ||
|
|
||
| jest.mock('../../../../../../../lib/time-tracking-ui/TaskBoardScreen', () => ({ | ||
| TaskBoardScreen: () => <div data-testid="task-board-screen" />, | ||
| })) | ||
|
|
||
| const apiCallMock = apiCall as unknown as jest.Mock | ||
| const apiCallOrThrowMock = apiCallOrThrow as unknown as jest.Mock | ||
|
|
||
| function projectRequests(): unknown[][] { | ||
| return apiCallMock.mock.calls.filter(([url]) => String(url).startsWith('/api/staff/timesheets/time-projects?')) | ||
| } | ||
|
|
||
| beforeEach(() => { | ||
| jest.clearAllMocks() | ||
| mockScopeVersion = 0 | ||
| apiCallMock.mockResolvedValue({ | ||
| ok: false, | ||
| status: 404, | ||
| result: { error: 'Not found', reason: 'no_project_access' }, | ||
| response: {}, | ||
| }) | ||
| apiCallOrThrowMock.mockResolvedValue({ ok: true, status: 200, result: { ok: true }, response: {} }) | ||
| }) | ||
|
|
||
| async function renderAndRequestAccess() { | ||
| const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }) | ||
| const page = () => ( | ||
| <QueryClientProvider client={queryClient}> | ||
| <ProjectBoardPage params={{ id: PROJECT_ID }} /> | ||
| </QueryClientProvider> | ||
| ) | ||
| const view = render(page()) | ||
| const requestButton = await screen.findByRole('button', { name: 'Request access' }) | ||
| await act(async () => { fireEvent.click(requestButton) }) | ||
| expect((await screen.findByRole('button', { name: 'Request sent' })).hasAttribute('disabled')).toBe(true) | ||
| expect(projectRequests()).toHaveLength(1) | ||
| return { rerender: () => view.rerender(page()) } | ||
| } | ||
|
|
||
| describe('project board — access request survives a scope reload', () => { | ||
| it('keeps "Request sent" after the organization scope settles', async () => { | ||
| const view = await renderAndRequestAccess() | ||
|
|
||
| mockScopeVersion = 1 | ||
| view.rerender() | ||
|
|
||
| expect(screen.queryByText('Loading the board…')).toBeNull() | ||
| await waitFor(() => expect(projectRequests()).toHaveLength(2)) | ||
| await act(async () => { await Promise.resolve() }) | ||
| expect(screen.getByRole('button', { name: 'Request sent' }).hasAttribute('disabled')).toBe(true) | ||
| expect(apiCallOrThrowMock).toHaveBeenCalledTimes(1) | ||
| }) | ||
|
|
||
| it('reloads through the loader when switching between two known scopes', async () => { | ||
| mockScopeVersion = 1 | ||
| const view = await renderAndRequestAccess() | ||
|
|
||
| mockScopeVersion = 2 | ||
| view.rerender() | ||
|
|
||
| expect(screen.getByText('Loading the board…')).toBeTruthy() | ||
| expect(screen.queryByRole('button', { name: 'Request sent' })).toBeNull() | ||
| await waitFor(() => expect(projectRequests()).toHaveLength(2)) | ||
| expect(await screen.findByRole('button', { name: 'Request access' })).toBeTruthy() | ||
| }) | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.