Skip to content
Open
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
9 changes: 9 additions & 0 deletions app/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import NotFound from "./pages/NotFound";
import { Landing } from "./pages/Landing";
import ProtectedRoute from "./components/auth/ProtectedRoute";
import Account from "./pages/Account";
import Jobs from "./pages/Jobs";

const queryClient = new QueryClient({
defaultOptions: {
Expand Down Expand Up @@ -83,6 +84,14 @@ const App = () => (
</ProtectedRoute>
}
/>
<Route
path="jobs"
element={
<ProtectedRoute>
<Jobs />
</ProtectedRoute>
}
/>
<Route
path="account"
element={
Expand Down
163 changes: 163 additions & 0 deletions app/src/__tests__/Jobs.integration.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
import React from 'react';
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import Jobs from '@/pages/Jobs';

const toastMock = jest.fn();
jest.mock('@/hooks/use-toast', () => ({
useToast: () => ({ toast: toastMock }),
}));

jest.mock('@/components/ui/button', () => ({
Button: ({ children, ...props }: React.PropsWithChildren & React.ButtonHTMLAttributes<HTMLButtonElement>) => (
<button {...props}>{children}</button>
),
}));
jest.mock('@/components/ui/input', () => ({
Input: ({ ...props }: React.InputHTMLAttributes<HTMLInputElement>) => <input {...props} />,
}));
jest.mock('@/components/ui/label', () => ({
Label: ({ children, ...props }: React.PropsWithChildren & React.LabelHTMLAttributes<HTMLLabelElement>) => (
<label {...props}>{children}</label>
),
}));
jest.mock('@/components/ui/badge', () => ({
Badge: ({ children, className, ...props }: React.PropsWithChildren & React.HTMLAttributes<HTMLDivElement>) => (
<span className={className} {...props}>{children}</span>
),
}));
jest.mock('@/components/ui/dialog', () => ({
Dialog: ({ children }: React.PropsWithChildren) => <div>{children}</div>,
DialogContent: ({ children }: React.PropsWithChildren) => <div>{children}</div>,
DialogHeader: ({ children }: React.PropsWithChildren) => <div>{children}</div>,
DialogTitle: ({ children }: React.PropsWithChildren) => <div>{children}</div>,
DialogDescription: ({ children }: React.PropsWithChildren) => <div>{children}</div>,
DialogTrigger: ({ children }: React.PropsWithChildren) => <div>{children}</div>,
DialogFooter: ({ children }: React.PropsWithChildren) => <div>{children}</div>,
}));

const listJobsMock = jest.fn();
const createJobMock = jest.fn();
const retryJobMock = jest.fn();
const getJobStatsMock = jest.fn();
const getDeadLetterQueueMock = jest.fn();
jest.mock('@/api/jobs', () => ({
listJobs: (...args: unknown[]) => listJobsMock(...args),
createJob: (...args: unknown[]) => createJobMock(...args),
retryJob: (...args: unknown[]) => retryJobMock(...args),
getJobStats: (...args: unknown[]) => getJobStatsMock(...args),
getDeadLetterQueue: (...args: unknown[]) => getDeadLetterQueueMock(...args),
}));

const SAMPLE_JOB = {
id: 1,
user_id: 1,
name: 'Sync bank data',
job_type: 'DATA_SYNC' as const,
status: 'COMPLETED' as const,
attempts: 1,
max_retries: 5,
last_error: null,
payload: '{"source":"plaid"}',
result: '{"records_synced":42}',
scheduled_at: '2025-01-01T00:00:00',
started_at: '2025-01-01T00:00:01',
completed_at: '2025-01-01T00:00:02',
next_retry_at: null,
created_at: '2025-01-01T00:00:00',
updated_at: '2025-01-01T00:00:02',
};

const FAILED_JOB = {
...SAMPLE_JOB,
id: 2,
name: 'Failed report',
job_type: 'REPORT_GENERATION' as const,
status: 'FAILED' as const,
attempts: 3,
last_error: 'Connection timeout',
completed_at: null,
result: null,
next_retry_at: '2025-01-01T00:01:00',
};

const SAMPLE_STATS = {
pending: 2,
running: 1,
completed: 10,
failed: 3,
dead: 1,
total: 17,
};

describe('Jobs monitor integration', () => {
beforeEach(() => {
jest.clearAllMocks();
listJobsMock.mockResolvedValue({
jobs: [SAMPLE_JOB, FAILED_JOB],
total: 2,
page: 1,
per_page: 20,
});
getJobStatsMock.mockResolvedValue(SAMPLE_STATS);
createJobMock.mockResolvedValue(SAMPLE_JOB);
retryJobMock.mockResolvedValue({ ...FAILED_JOB, status: 'COMPLETED', attempts: 4 });
getDeadLetterQueueMock.mockResolvedValue([]);
});

it('renders page title and stats cards', async () => {
render(<Jobs />);
await waitFor(() => expect(getJobStatsMock).toHaveBeenCalled());
expect(screen.getByText(/background jobs/i)).toBeInTheDocument();
expect(screen.getByText('17')).toBeInTheDocument(); // total
expect(screen.getByText('10')).toBeInTheDocument(); // completed
});

it('renders job list with status badges', async () => {
render(<Jobs />);
await waitFor(() => expect(listJobsMock).toHaveBeenCalled());
expect(screen.getByText('Sync bank data')).toBeInTheDocument();
expect(screen.getByText('Failed report')).toBeInTheDocument();
expect(screen.getByText('Completed')).toBeInTheDocument();
expect(screen.getByText('Failed')).toBeInTheDocument();
});

it('shows retry button for failed jobs', async () => {
render(<Jobs />);
await waitFor(() => expect(listJobsMock).toHaveBeenCalled());
const retryButtons = screen.getAllByRole('button', { name: /retry/i });
expect(retryButtons.length).toBeGreaterThanOrEqual(1);
});

it('retries a failed job', async () => {
render(<Jobs />);
await waitFor(() => expect(listJobsMock).toHaveBeenCalled());
const retryButtons = screen.getAllByRole('button', { name: /retry/i });
await userEvent.click(retryButtons[0]);
await waitFor(() => expect(retryJobMock).toHaveBeenCalledWith(2));
expect(toastMock).toHaveBeenCalledWith(
expect.objectContaining({ title: 'Job retried' }),
);
});

it('shows error message for failed jobs', async () => {
render(<Jobs />);
await waitFor(() => expect(listJobsMock).toHaveBeenCalled());
expect(screen.getByText('Connection timeout')).toBeInTheDocument();
});

it('displays attempt counter', async () => {
render(<Jobs />);
await waitFor(() => expect(listJobsMock).toHaveBeenCalled());
expect(screen.getByText('Attempt 1/5')).toBeInTheDocument();
expect(screen.getByText('Attempt 3/5')).toBeInTheDocument();
});

it('shows empty state when no jobs', async () => {
listJobsMock.mockResolvedValue({ jobs: [], total: 0, page: 1, per_page: 20 });
getJobStatsMock.mockResolvedValue({ ...SAMPLE_STATS, total: 0 });
render(<Jobs />);
await waitFor(() => expect(listJobsMock).toHaveBeenCalled());
expect(screen.getByText(/no jobs found/i)).toBeInTheDocument();
});
});
82 changes: 82 additions & 0 deletions app/src/api/jobs.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import { api } from './client';

export type JobStatus = 'PENDING' | 'RUNNING' | 'COMPLETED' | 'FAILED' | 'DEAD';
export type JobType = 'DATA_SYNC' | 'REPORT_GENERATION' | 'EMAIL_NOTIFICATION';

export type Job = {
id: number;
user_id: number;
name: string;
job_type: JobType;
status: JobStatus;
attempts: number;
max_retries: number;
last_error: string | null;
payload: string | null;
result: string | null;
scheduled_at: string | null;
started_at: string | null;
completed_at: string | null;
next_retry_at: string | null;
created_at: string | null;
updated_at: string | null;
};

export type JobListResponse = {
jobs: Job[];
total: number;
page: number;
per_page: number;
};

export type JobStats = {
pending: number;
running: number;
completed: number;
failed: number;
dead: number;
total: number;
};

export type JobCreate = {
name: string;
job_type: JobType;
payload?: Record<string, unknown>;
max_retries?: number;
scheduled_at?: string;
};

export async function listJobs(params?: {
status?: JobStatus;
job_type?: JobType;
page?: number;
per_page?: number;
}): Promise<JobListResponse> {
const searchParams = new URLSearchParams();
if (params?.status) searchParams.set('status', params.status);
if (params?.job_type) searchParams.set('job_type', params.job_type);
if (params?.page) searchParams.set('page', String(params.page));
if (params?.per_page) searchParams.set('per_page', String(params.per_page));
const qs = searchParams.toString();
return api<JobListResponse>(`/jobs${qs ? `?${qs}` : ''}`);
}

export async function createJob(payload: JobCreate): Promise<Job> {
return api<Job>('/jobs', { method: 'POST', body: payload });
}

export async function getJob(id: number): Promise<Job> {
return api<Job>(`/jobs/${id}`);
}

export async function retryJob(id: number): Promise<Job> {
return api<Job>(`/jobs/${id}/retry`, { method: 'POST' });
}

export async function getJobStats(): Promise<JobStats> {
return api<JobStats>('/jobs/stats');
}

export async function getDeadLetterQueue(): Promise<Job[]> {
return api<Job[]>('/jobs/dead-letter');
}
1 change: 1 addition & 0 deletions app/src/components/layout/Navbar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ const navigation = [
{ name: 'Reminders', href: '/reminders' },
{ name: 'Expenses', href: '/expenses' },
{ name: 'Analytics', href: '/analytics' },
{ name: 'Jobs', href: '/jobs' },
];

export function Navbar() {
Expand Down
Loading