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
38 changes: 38 additions & 0 deletions __tests__/TimerPage.resume.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { render, screen } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import TimerPage from '../app/timer/page';

// Mock fetch for clients and /api/timer
beforeEach(() => {
global.fetch = jest.fn((url) => {
if (typeof url === 'string' && url.endsWith('/api/timer')) {
return Promise.resolve({ ok: true, json: () => Promise.resolve({ runningEntry: { id: 'entry1', clientId: 'client1', startTime: new Date(Date.now() - 5000).toISOString(), client: { id: 'client1', name: 'Client A', hourlyRate: 50 } } }) });
}
if (typeof url === 'string' && url.endsWith('/api/clients')) {
return Promise.resolve({ ok: true, json: () => Promise.resolve({ clients: [{ id: 'client1', name: 'Client A', hourlyRate: 50 }] }) });
}
return Promise.resolve({ ok: false });
}) as jest.Mock;
});

afterEach(() => {
jest.resetAllMocks();
});

describe('TimerPage resume behavior', () => {
it('resumes UI when runningEntry exists', async () => {
const qc = new QueryClient();
render(
<QueryClientProvider client={qc}>
<TimerPage />
</QueryClientProvider>,
);

// Wait for the timer display to show a non-zero time
const timerDisplay = await screen.findByText(/\d{2}:\d{2}:\d{2}/);
expect(timerDisplay.textContent).not.toBe('00:00:00');

// Ensure Stop button is present (implies running)
expect(await screen.findByText(/stop/i)).toBeInTheDocument();
});
});
49 changes: 49 additions & 0 deletions __tests__/api/timer.get.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { GET } from '../../app/api/timer/route';
import { getServerSession } from 'next-auth';

jest.mock('@/lib/prisma', () => ({
prisma: {
user: { upsert: jest.fn() },
client: { findFirst: jest.fn() },
timeEntry: { findFirst: jest.fn(), create: jest.fn(), update: jest.fn(), findUnique: jest.fn() },
},
}));
jest.mock('next-auth', () => ({ getServerSession: jest.fn() }));

const { prisma: mockPrisma } = jest.requireMock('@/lib/prisma') as {
prisma: {
user: { upsert: jest.Mock };
client: { findFirst: jest.Mock };
timeEntry: { findFirst: jest.Mock; create: jest.Mock; update: jest.Mock; findUnique: jest.Mock };
};
};

describe('GET /api/timer', () => {
beforeEach(() => {
jest.resetAllMocks();
});

it('returns runningEntry when present', async () => {
(getServerSession as jest.Mock).mockResolvedValue({ user: { email: 'test@example.com' } });
mockPrisma.user.upsert.mockResolvedValue({ id: 'user1', email: 'test@example.com' });
mockPrisma.timeEntry.findFirst.mockResolvedValue({ id: 'entry1', clientId: 'client1', startTime: new Date().toISOString(), status: 'RUNNING', client: { id: 'client1', name: 'C' } });

const res = await GET();
const json = await res.json();

expect(json.runningEntry).toBeDefined();
expect(json.runningEntry.status).toBe('RUNNING');
expect(json.runningEntry.client).toBeDefined();
});

it('returns null when no running entry', async () => {
(getServerSession as jest.Mock).mockResolvedValue({ user: { email: 'test@example.com' } });
mockPrisma.user.upsert.mockResolvedValue({ id: 'user1', email: 'test@example.com' });
mockPrisma.timeEntry.findFirst.mockResolvedValue(null);

const res = await GET();
const json = await res.json();

expect(json.runningEntry).toBeNull();
});
});
74 changes: 74 additions & 0 deletions __tests__/api/timer.post.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
// Mock prisma, next-auth, auth and env before importing the route module
jest.mock('@/lib/prisma', () => ({
prisma: {
user: { upsert: jest.fn() },
client: { findFirst: jest.fn() },
timeEntry: { findFirst: jest.fn(), create: jest.fn(), update: jest.fn(), findUnique: jest.fn() },
},
}));
jest.mock('next-auth', () => ({ getServerSession: jest.fn() }));
jest.mock('@/auth', () => ({ authOptions: {} }));
jest.mock('@/lib/env', () => ({ validateEnv: () => {} }));

const { getServerSession } = jest.requireMock('next-auth') as { getServerSession: jest.Mock };
let POST: (req: Request) => Promise<Response>;
beforeAll(async () => {
const mod = await import('../../app/api/timer/route');
POST = mod.POST;
});

const { prisma: mockPrisma } = jest.requireMock('@/lib/prisma') as {
prisma: {
user: { upsert: jest.Mock };
client: { findFirst: jest.Mock };
timeEntry: { findFirst: jest.Mock; create: jest.Mock; update: jest.Mock; findUnique: jest.Mock };
};
};

describe('POST /api/timer', () => {
beforeEach(() => {
jest.resetAllMocks();
});

it('creates a running time entry when none exists', async () => {
// Mock session
(getServerSession as jest.Mock).mockResolvedValue({ user: { email: 'test@example.com', name: 'Test' } });

// Mock upsert user
mockPrisma.user.upsert.mockResolvedValue({ id: 'user1', email: 'test@example.com' });
// Mock client lookup
mockPrisma.client.findFirst.mockResolvedValue({ id: 'client1', userId: 'user1' });
// No existing running entry
mockPrisma.timeEntry.findFirst.mockResolvedValue(null);
// Create returns new entry
mockPrisma.timeEntry.create.mockResolvedValue({ id: 'entry1', startTime: new Date().toISOString(), clientId: 'client1', userId: 'user1', status: 'RUNNING' });

const req = new Request('http://localhost/api/timer', {
method: 'POST',
body: JSON.stringify({ clientId: 'client1', startTime: new Date().toISOString() }),
});

const res = await POST(req as Request);
const json = await res.json();

expect(json.timeEntry).toBeDefined();
expect(json.timeEntry.status).toBe('RUNNING');
});

it('returns 409 when a running timer already exists', async () => {
(getServerSession as jest.Mock).mockResolvedValue({ user: { email: 'test@example.com', name: 'Test' } });
mockPrisma.user.upsert.mockResolvedValue({ id: 'user1', email: 'test@example.com' });
mockPrisma.client.findFirst.mockResolvedValue({ id: 'client1', userId: 'user1' });
mockPrisma.timeEntry.findFirst.mockResolvedValue({ id: 'existing', userId: 'user1', status: 'RUNNING' });

const req = new Request('http://localhost/api/timer', {
method: 'POST',
body: JSON.stringify({ clientId: 'client1', startTime: new Date().toISOString() }),
});

const res = await POST(req as Request);
const json = await res.json();

expect(json.error).toBe('A timer is already running');
});
});
59 changes: 59 additions & 0 deletions __tests__/api/timer.put.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { PUT } from '../../app/api/timer/[id]/route';
import { getServerSession } from 'next-auth';

jest.mock('@/lib/prisma', () => ({
prisma: {
user: { upsert: jest.fn() },
client: { findFirst: jest.fn() },
timeEntry: { findFirst: jest.fn(), create: jest.fn(), update: jest.fn(), findUnique: jest.fn() },
},
}));
jest.mock('next-auth', () => ({ getServerSession: jest.fn() }));

const { prisma: mockPrisma } = jest.requireMock('@/lib/prisma') as {
prisma: {
user: { upsert: jest.Mock };
client: { findFirst: jest.Mock };
timeEntry: { findFirst: jest.Mock; create: jest.Mock; update: jest.Mock; findUnique: jest.Mock };
};
};

describe('PUT /api/timer/:id', () => {
beforeEach(() => {
jest.resetAllMocks();
});

it('completes an existing running entry', async () => {
(getServerSession as jest.Mock).mockResolvedValue({ user: { email: 'test@example.com' } });
mockPrisma.user.upsert.mockResolvedValue({ id: 'user1', email: 'test@example.com' });
mockPrisma.timeEntry.findUnique.mockResolvedValue({ id: 'entry1', userId: 'user1' });
mockPrisma.timeEntry.update.mockResolvedValue({ id: 'entry1', endTime: new Date().toISOString(), status: 'COMPLETED' });

const req = new Request('http://localhost/api/timer/entry1', {
method: 'PUT',
body: JSON.stringify({ endTime: new Date().toISOString() }),
});

const res = await PUT(req as Request, { params: Promise.resolve({ id: 'entry1' }) } as { params: Promise<{ id: string }> });
const json = await res.json();

expect(json.timeEntry).toBeDefined();
expect(json.timeEntry.status).toBe('COMPLETED');
});

it('returns 404 for non-owner or missing entry', async () => {
(getServerSession as jest.Mock).mockResolvedValue({ user: { email: 'test@example.com' } });
mockPrisma.user.upsert.mockResolvedValue({ id: 'user1', email: 'test@example.com' });
mockPrisma.timeEntry.findUnique.mockResolvedValue(null);

const req = new Request('http://localhost/api/timer/doesnotexist', {
method: 'PUT',
body: JSON.stringify({ endTime: new Date().toISOString() }),
});

const res = await PUT(req as Request, { params: Promise.resolve({ id: 'doesnotexist' }) } as { params: Promise<{ id: string }> });
const json = await res.json();

expect(json.error).toBe('Time entry not found');
});
});
12 changes: 8 additions & 4 deletions app/api/timer/[id]/route.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { getServerSession } from 'next-auth';
import { authOptions } from '@/auth';
import { prisma } from '@/lib/prisma';
import { TimeEntryStatus } from '@prisma/client';
import { validateEnv } from '@/lib/env';

export async function PUT(req: Request, { params }: { params: Promise<{ id: string }> }) {
Expand Down Expand Up @@ -29,13 +30,16 @@ export async function PUT(req: Request, { params }: { params: Promise<{ id: stri
},
});

const existing = await prisma.timeEntry.findUnique({ where: { id } });
if (!existing || existing.userId !== user.id) {
return Response.json({ error: 'Time entry not found' }, { status: 404 });
}

const updatedEntry = await prisma.timeEntry.update({
where: {
id,
userId: user.id,
},
where: { id },
data: {
endTime: new Date(endTime),
status: TimeEntryStatus.COMPLETED,
},
});
return Response.json({ timeEntry: updatedEntry });
Expand Down
19 changes: 15 additions & 4 deletions app/api/timer/route.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { getServerSession } from 'next-auth';
import { authOptions } from '@/auth';
import { prisma } from '@/lib/prisma';
import { TimeEntryStatus } from '@prisma/client';
import { validateEnv } from '@/lib/env';

export async function POST(req: Request) {
Expand Down Expand Up @@ -40,13 +41,23 @@ export async function POST(req: Request) {
return Response.json({ error: 'Client not found' }, { status: 404 });
}

// Create time entry
// Ensure there is no other running entry for this user
const existingRunning = await prisma.timeEntry.findFirst({
where: { userId: user.id, status: TimeEntryStatus.RUNNING },
});

if (existingRunning) {
return Response.json({ error: 'A timer is already running' }, { status: 409 });
}

// Create time entry with status RUNNING
const timeEntry = await prisma.timeEntry.create({
data: {
startTime: new Date(startTime),
endTime: endTime ? new Date(endTime) : null,
clientId,
userId: user.id,
status: TimeEntryStatus.RUNNING,
},
});

Expand Down Expand Up @@ -75,16 +86,16 @@ export async function GET() {
},
});

const inProgressEntries = await prisma.timeEntry.findMany({
const runningEntry = await prisma.timeEntry.findFirst({
where: {
userId: user.id,
endTime: null,
status: 'RUNNING',
},
include: {
client: true,
},
});
return Response.json({ inProgressEntries });
return Response.json({ runningEntry });
} catch (error) {
console.error('Error fetching in-progress time entries:', error);
return Response.json({ error: 'Internal server error' }, { status: 500 });
Expand Down
27 changes: 27 additions & 0 deletions app/timer/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,33 @@ export default function TimerPage() {
},
});

// On mount, check for any running entry and resume timer UI
useEffect(() => {
let mounted = true;
(async () => {
try {
const res = await fetch('/api/timer');
if (!res.ok) return;
const data = await res.json();
const entry = data.runningEntry;
if (mounted && entry) {
setSelectedClientId(entry.clientId);
setActiveEntryId(entry.id);
const s = new Date(entry.startTime);
setStartTime(s);
const diff = Math.floor((Date.now() - s.getTime()) / 1000);
setSeconds(Math.max(0, diff));
setIsRunning(true);
}
} catch {
// ignore
}
})();
return () => {
mounted = false;
};
}, []);

useEffect(() => {
let interval: NodeJS.Timeout;

Expand Down
27 changes: 27 additions & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/** @type {import('jest').Config} */
const config = {
testEnvironment: 'jsdom',
testMatch: ['**/__tests__/**/*.[jt]s?(x)', '**/?(*.)+(spec|test).[jt]s?(x)'],
transform: {
'^.+\\.(ts|tsx)$': ['ts-jest', {
tsconfig: {
jsx: 'react-jsx',
paths: {} // disable tsconfig path mapping in ts-jest
}
}],
},
moduleNameMapper: {
'^@/auth$': '<rootDir>/auth.ts', // specific override first
'^@/(.*)$': '<rootDir>/app/$1', // matches tsconfig: @/* -> ./app/*
},
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
collectCoverageFrom: [
'app/**/*.{ts,tsx}',
'components/**/*.{ts,tsx}',
'!**/node_modules/**',
'!**/.next/**',
],
};

module.exports = config;
19 changes: 0 additions & 19 deletions jest.config.ts

This file was deleted.

Loading
Loading