adds statistics

This commit is contained in:
2026-02-16 19:15:23 +01:00
parent 2311cd8265
commit 9206453394
12 changed files with 613 additions and 58 deletions

View File

@@ -1,16 +1,44 @@
import { Router } from 'express';
import { requireAuth } from '../middleware/auth';
import { validateBody, validateParams, validateQuery } from '../middleware/validation';
import { TimeEntryService } from '../services/timeEntry.service';
import { CreateTimeEntrySchema, UpdateTimeEntrySchema, IdSchema, TimeEntryFiltersSchema } from '../schemas';
import type { AuthenticatedRequest } from '../types';
import { Router } from "express";
import { requireAuth } from "../middleware/auth";
import {
validateBody,
validateParams,
validateQuery,
} from "../middleware/validation";
import { TimeEntryService } from "../services/timeEntry.service";
import {
CreateTimeEntrySchema,
UpdateTimeEntrySchema,
IdSchema,
TimeEntryFiltersSchema,
StatisticsFiltersSchema,
} from "../schemas";
import type { AuthenticatedRequest } from "../types";
const router = Router();
const timeEntryService = new TimeEntryService();
// GET /api/time-entries/statistics - Get aggregated statistics
router.get(
"/statistics",
requireAuth,
validateQuery(StatisticsFiltersSchema),
async (req: AuthenticatedRequest, res, next) => {
try {
const stats = await timeEntryService.getStatistics(
req.user!.id,
req.query,
);
res.json(stats);
} catch (error) {
next(error);
}
},
);
// GET /api/time-entries - List user's entries
router.get(
'/',
"/",
requireAuth,
validateQuery(TimeEntryFiltersSchema),
async (req: AuthenticatedRequest, res, next) => {
@@ -20,12 +48,12 @@ router.get(
} catch (error) {
next(error);
}
}
},
);
// POST /api/time-entries - Create entry manually
router.post(
'/',
"/",
requireAuth,
validateBody(CreateTimeEntrySchema),
async (req: AuthenticatedRequest, res, next) => {
@@ -35,28 +63,32 @@ router.post(
} catch (error) {
next(error);
}
}
},
);
// PUT /api/time-entries/:id - Update entry
router.put(
'/:id',
"/:id",
requireAuth,
validateParams(IdSchema),
validateBody(UpdateTimeEntrySchema),
async (req: AuthenticatedRequest, res, next) => {
try {
const entry = await timeEntryService.update(req.params.id, req.user!.id, req.body);
const entry = await timeEntryService.update(
req.params.id,
req.user!.id,
req.body,
);
res.json(entry);
} catch (error) {
next(error);
}
}
},
);
// DELETE /api/time-entries/:id - Delete entry
router.delete(
'/:id',
"/:id",
requireAuth,
validateParams(IdSchema),
async (req: AuthenticatedRequest, res, next) => {
@@ -66,7 +98,7 @@ router.delete(
} catch (error) {
next(error);
}
}
},
);
export default router;

View File

@@ -51,6 +51,13 @@ export const TimeEntryFiltersSchema = z.object({
limit: z.coerce.number().int().min(1).max(100).default(50),
});
export const StatisticsFiltersSchema = z.object({
startDate: z.string().datetime().optional(),
endDate: z.string().datetime().optional(),
projectId: z.string().uuid().optional(),
clientId: z.string().uuid().optional(),
});
export const StartTimerSchema = z.object({
projectId: z.string().uuid().optional(),
});

View File

@@ -1,9 +1,157 @@
import { prisma } from '../prisma/client';
import type { CreateTimeEntryInput, UpdateTimeEntryInput, TimeEntryFilters } from '../types';
import { prisma } from "../prisma/client";
import type {
CreateTimeEntryInput,
UpdateTimeEntryInput,
TimeEntryFilters,
StatisticsFilters,
} from "../types";
export class TimeEntryService {
async getStatistics(userId: string, filters: StatisticsFilters = {}) {
const { startDate, endDate, projectId, clientId } = filters;
const where: {
userId: string;
startTime?: { gte?: Date; lte?: Date };
projectId?: string;
project?: { clientId?: string };
} = { userId };
if (startDate || endDate) {
where.startTime = {};
if (startDate) where.startTime.gte = new Date(startDate);
if (endDate) where.startTime.lte = new Date(endDate);
}
if (projectId) {
where.projectId = projectId;
}
if (clientId) {
where.project = { clientId };
}
const entries = await prisma.timeEntry.findMany({
where,
include: {
project: {
select: {
id: true,
name: true,
color: true,
client: {
select: {
id: true,
name: true,
},
},
},
},
},
});
// Calculate total duration in seconds
const totalSeconds = entries.reduce((total, entry) => {
const startTime = new Date(entry.startTime);
const endTime = new Date(entry.endTime);
return (
total + Math.floor((endTime.getTime() - startTime.getTime()) / 1000)
);
}, 0);
// Calculate by project
const byProject = entries.reduce(
(acc, entry) => {
const projectId = entry.project.id;
const projectName = entry.project.name;
const projectColor = entry.project.color;
const startTime = new Date(entry.startTime);
const endTime = new Date(entry.endTime);
const duration = Math.floor(
(endTime.getTime() - startTime.getTime()) / 1000,
);
if (!acc[projectId]) {
acc[projectId] = {
projectId,
projectName,
projectColor,
totalSeconds: 0,
entryCount: 0,
};
}
acc[projectId].totalSeconds += duration;
acc[projectId].entryCount += 1;
return acc;
},
{} as Record<
string,
{
projectId: string;
projectName: string;
projectColor: string | null;
totalSeconds: number;
entryCount: number;
}
>,
);
// Calculate by client
const byClient = entries.reduce(
(acc, entry) => {
const clientId = entry.project.client.id;
const clientName = entry.project.client.name;
const startTime = new Date(entry.startTime);
const endTime = new Date(entry.endTime);
const duration = Math.floor(
(endTime.getTime() - startTime.getTime()) / 1000,
);
if (!acc[clientId]) {
acc[clientId] = {
clientId,
clientName,
totalSeconds: 0,
entryCount: 0,
};
}
acc[clientId].totalSeconds += duration;
acc[clientId].entryCount += 1;
return acc;
},
{} as Record<
string,
{
clientId: string;
clientName: string;
totalSeconds: number;
entryCount: number;
}
>,
);
return {
totalSeconds,
entryCount: entries.length,
byProject: Object.values(byProject),
byClient: Object.values(byClient),
filters: {
startDate: startDate || null,
endDate: endDate || null,
projectId: projectId || null,
clientId: clientId || null,
},
};
}
async findAll(userId: string, filters: TimeEntryFilters = {}) {
const { startDate, endDate, projectId, clientId, page = 1, limit = 50 } = filters;
const {
startDate,
endDate,
projectId,
clientId,
page = 1,
limit = 50,
} = filters;
const skip = (page - 1) * limit;
const where: {
@@ -30,7 +178,7 @@ export class TimeEntryService {
const [entries, total] = await Promise.all([
prisma.timeEntry.findMany({
where,
orderBy: { startTime: 'desc' },
orderBy: { startTime: "desc" },
skip,
take: limit,
include: {
@@ -90,7 +238,9 @@ export class TimeEntryService {
// Validate end time is after start time
if (endTime <= startTime) {
const error = new Error('End time must be after start time') as Error & { statusCode: number };
const error = new Error("End time must be after start time") as Error & {
statusCode: number;
};
error.statusCode = 400;
throw error;
}
@@ -101,15 +251,23 @@ export class TimeEntryService {
});
if (!project) {
const error = new Error('Project not found') as Error & { statusCode: number };
const error = new Error("Project not found") as Error & {
statusCode: number;
};
error.statusCode = 404;
throw error;
}
// Check for overlapping entries
const hasOverlap = await this.hasOverlappingEntries(userId, startTime, endTime);
const hasOverlap = await this.hasOverlappingEntries(
userId,
startTime,
endTime,
);
if (hasOverlap) {
const error = new Error('This time entry overlaps with an existing entry') as Error & { statusCode: number };
const error = new Error(
"This time entry overlaps with an existing entry",
) as Error & { statusCode: number };
error.statusCode = 400;
throw error;
}
@@ -143,17 +301,23 @@ export class TimeEntryService {
async update(id: string, userId: string, data: UpdateTimeEntryInput) {
const entry = await this.findById(id, userId);
if (!entry) {
const error = new Error('Time entry not found') as Error & { statusCode: number };
const error = new Error("Time entry not found") as Error & {
statusCode: number;
};
error.statusCode = 404;
throw error;
}
const startTime = data.startTime ? new Date(data.startTime) : entry.startTime;
const startTime = data.startTime
? new Date(data.startTime)
: entry.startTime;
const endTime = data.endTime ? new Date(data.endTime) : entry.endTime;
// Validate end time is after start time
if (endTime <= startTime) {
const error = new Error('End time must be after start time') as Error & { statusCode: number };
const error = new Error("End time must be after start time") as Error & {
statusCode: number;
};
error.statusCode = 400;
throw error;
}
@@ -165,16 +329,25 @@ export class TimeEntryService {
});
if (!project) {
const error = new Error('Project not found') as Error & { statusCode: number };
const error = new Error("Project not found") as Error & {
statusCode: number;
};
error.statusCode = 404;
throw error;
}
}
// Check for overlapping entries (excluding this entry)
const hasOverlap = await this.hasOverlappingEntries(userId, startTime, endTime, id);
const hasOverlap = await this.hasOverlappingEntries(
userId,
startTime,
endTime,
id,
);
if (hasOverlap) {
const error = new Error('This time entry overlaps with an existing entry') as Error & { statusCode: number };
const error = new Error(
"This time entry overlaps with an existing entry",
) as Error & { statusCode: number };
error.statusCode = 400;
throw error;
}
@@ -208,7 +381,9 @@ export class TimeEntryService {
async delete(id: string, userId: string) {
const entry = await this.findById(id, userId);
if (!entry) {
const error = new Error('Time entry not found') as Error & { statusCode: number };
const error = new Error("Time entry not found") as Error & {
statusCode: number;
};
error.statusCode = 404;
throw error;
}
@@ -222,7 +397,7 @@ export class TimeEntryService {
userId: string,
startTime: Date,
endTime: Date,
excludeId?: string
excludeId?: string,
): Promise<boolean> {
const where: {
userId: string;

View File

@@ -57,6 +57,13 @@ export interface TimeEntryFilters {
limit?: number;
}
export interface StatisticsFilters {
startDate?: string;
endDate?: string;
projectId?: string;
clientId?: string;
}
export interface StartTimerInput {
projectId?: string;
}

View File

@@ -9,6 +9,7 @@ import { DashboardPage } from "./pages/DashboardPage";
import { TimeEntriesPage } from "./pages/TimeEntriesPage";
import { ClientsPage } from "./pages/ClientsPage";
import { ProjectsPage } from "./pages/ProjectsPage";
import { StatisticsPage } from "./pages/StatisticsPage";
function App() {
return (
@@ -31,6 +32,7 @@ function App() {
<Route path="time-entries" element={<TimeEntriesPage />} />
<Route path="clients" element={<ClientsPage />} />
<Route path="projects" element={<ProjectsPage />} />
<Route path="statistics" element={<StatisticsPage />} />
</Route>
</Routes>
</AuthProvider>

View File

@@ -1,7 +1,8 @@
import axios from "axios";
import type { User } from "@/types";
const AUTH_BASE = import.meta.env.VITE_API_URL + "/auth";
const AUTH_BASE =
(import.meta.env.VITE_API_URL || `${window.location.origin}/api`) + "/auth";
export const authApi = {
login: (): void => {

View File

@@ -1,7 +1,7 @@
import axios, { AxiosError } from "axios";
const apiClient = axios.create({
baseURL: import.meta.env.VITE_API_URL,
baseURL: import.meta.env.VITE_API_URL || `${window.location.origin}/api`,
headers: {
"Content-Type": "application/json",
},

View File

@@ -5,6 +5,8 @@ import type {
CreateTimeEntryInput,
UpdateTimeEntryInput,
TimeEntryFilters,
TimeStatistics,
StatisticsFilters,
} from '@/types';
export const timeEntriesApi = {
@@ -15,6 +17,13 @@ export const timeEntriesApi = {
return data;
},
getStatistics: async (filters?: StatisticsFilters): Promise<TimeStatistics> => {
const { data } = await apiClient.get<TimeStatistics>('/time-entries/statistics', {
params: filters,
});
return data;
},
create: async (input: CreateTimeEntryInput): Promise<TimeEntry> => {
const { data } = await apiClient.post<TimeEntry>('/time-entries', input);
return data;

View File

@@ -1,15 +1,23 @@
import { NavLink } from 'react-router-dom';
import { Clock, List, Briefcase, FolderOpen, LogOut } from 'lucide-react';
import { useAuth } from '@/contexts/AuthContext';
import { NavLink } from "react-router-dom";
import {
Clock,
List,
Briefcase,
FolderOpen,
BarChart3,
LogOut,
} from "lucide-react";
import { useAuth } from "@/contexts/AuthContext";
export function Navbar() {
const { user, logout } = useAuth();
const navItems = [
{ to: '/dashboard', label: 'Dashboard', icon: Clock },
{ to: '/time-entries', label: 'Time Entries', icon: List },
{ to: '/clients', label: 'Clients', icon: Briefcase },
{ to: '/projects', label: 'Projects', icon: FolderOpen },
{ to: "/dashboard", label: "Dashboard", icon: Clock },
{ to: "/time-entries", label: "Time Entries", icon: List },
{ to: "/statistics", label: "Statistics", icon: BarChart3 },
{ to: "/clients", label: "Clients", icon: Briefcase },
{ to: "/projects", label: "Projects", icon: FolderOpen },
];
return (
@@ -19,7 +27,9 @@ export function Navbar() {
<div className="flex">
<div className="flex-shrink-0 flex items-center">
<Clock className="h-8 w-8 text-primary-600" />
<span className="ml-2 text-xl font-bold text-gray-900">TimeTracker</span>
<span className="ml-2 text-xl font-bold text-gray-900">
TimeTracker
</span>
</div>
<div className="hidden sm:ml-8 sm:flex sm:space-x-4">
{navItems.map((item) => (
@@ -29,8 +39,8 @@ export function Navbar() {
className={({ isActive }) =>
`inline-flex items-center px-3 py-2 text-sm font-medium rounded-md transition-colors ${
isActive
? 'text-primary-600 bg-primary-50'
: 'text-gray-600 hover:text-gray-900 hover:bg-gray-50'
? "text-primary-600 bg-primary-50"
: "text-gray-600 hover:text-gray-900 hover:bg-gray-50"
}`
}
>
@@ -63,7 +73,7 @@ export function Navbar() {
to={item.to}
className={({ isActive }) =>
`flex flex-col items-center p-2 text-xs font-medium rounded-md ${
isActive ? 'text-primary-600' : 'text-gray-600'
isActive ? "text-primary-600" : "text-gray-600"
}`
}
>

View File

@@ -1,19 +1,24 @@
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { timeEntriesApi } from '@/api/timeEntries';
import type { CreateTimeEntryInput, UpdateTimeEntryInput, TimeEntryFilters } from '@/types';
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { timeEntriesApi } from "@/api/timeEntries";
import type {
CreateTimeEntryInput,
UpdateTimeEntryInput,
TimeEntryFilters,
StatisticsFilters,
} from "@/types";
export function useTimeEntries(filters?: TimeEntryFilters) {
const queryClient = useQueryClient();
const { data, isLoading, error } = useQuery({
queryKey: ['timeEntries', filters],
queryKey: ["timeEntries", filters],
queryFn: () => timeEntriesApi.getAll(filters),
});
const createTimeEntry = useMutation({
mutationFn: (input: CreateTimeEntryInput) => timeEntriesApi.create(input),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['timeEntries'] });
queryClient.invalidateQueries({ queryKey: ["timeEntries"] });
},
});
@@ -21,14 +26,14 @@ export function useTimeEntries(filters?: TimeEntryFilters) {
mutationFn: ({ id, input }: { id: string; input: UpdateTimeEntryInput }) =>
timeEntriesApi.update(id, input),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['timeEntries'] });
queryClient.invalidateQueries({ queryKey: ["timeEntries"] });
},
});
const deleteTimeEntry = useMutation({
mutationFn: (id: string) => timeEntriesApi.delete(id),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['timeEntries'] });
queryClient.invalidateQueries({ queryKey: ["timeEntries"] });
},
});
@@ -41,3 +46,16 @@ export function useTimeEntries(filters?: TimeEntryFilters) {
deleteTimeEntry,
};
}
export function useStatistics(filters?: StatisticsFilters) {
const { data, isLoading, error } = useQuery({
queryKey: ["statistics", filters],
queryFn: () => timeEntriesApi.getStatistics(filters),
});
return {
data,
isLoading,
error,
};
}

View File

@@ -0,0 +1,259 @@
import { useState } from "react";
import {
BarChart3,
Calendar,
Building2,
FolderOpen,
Clock,
} from "lucide-react";
import { useStatistics } from "@/hooks/useTimeEntries";
import { useClients } from "@/hooks/useClients";
import { useProjects } from "@/hooks/useProjects";
import { formatDuration } from "@/utils/dateUtils";
import type { StatisticsFilters } from "@/types";
export function StatisticsPage() {
const [filters, setFilters] = useState<StatisticsFilters>({});
const { data: statistics, isLoading } = useStatistics(filters);
const { clients } = useClients();
const { projects } = useProjects();
const handleFilterChange = (
key: keyof StatisticsFilters,
value: string | undefined,
) => {
setFilters((prev) => ({
...prev,
[key]: value || undefined,
}));
};
const clearFilters = () => {
setFilters({});
};
return (
<div className="space-y-6">
{/* Page Header */}
<div>
<h1 className="text-2xl font-bold text-gray-900">Statistics</h1>
<p className="mt-1 text-sm text-gray-600">
View your working hours with filters
</p>
</div>
{/* Filters */}
<div className="card">
<div className="flex items-center gap-2 mb-4">
<BarChart3 className="h-5 w-5 text-primary-600" />
<h2 className="text-lg font-semibold text-gray-900">Filters</h2>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
{/* Date Range */}
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
<span className="flex items-center gap-1">
<Calendar className="h-4 w-4" />
From Date
</span>
</label>
<input
type="date"
value={filters.startDate ? filters.startDate.split("T")[0] : ""}
onChange={(e) =>
handleFilterChange(
"startDate",
e.target.value ? `${e.target.value}T00:00:00` : undefined,
)
}
className="input"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
<span className="flex items-center gap-1">
<Calendar className="h-4 w-4" />
To Date
</span>
</label>
<input
type="date"
value={filters.endDate ? filters.endDate.split("T")[0] : ""}
onChange={(e) =>
handleFilterChange(
"endDate",
e.target.value ? `${e.target.value}T23:59:59` : undefined,
)
}
className="input"
/>
</div>
{/* Client Filter */}
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
<span className="flex items-center gap-1">
<Building2 className="h-4 w-4" />
Client
</span>
</label>
<select
value={filters.clientId || ""}
onChange={(e) =>
handleFilterChange("clientId", e.target.value || undefined)
}
className="input"
>
<option value="">All Clients</option>
{clients?.map((client) => (
<option key={client.id} value={client.id}>
{client.name}
</option>
))}
</select>
</div>
{/* Project Filter */}
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
<span className="flex items-center gap-1">
<FolderOpen className="h-4 w-4" />
Project
</span>
</label>
<select
value={filters.projectId || ""}
onChange={(e) =>
handleFilterChange("projectId", e.target.value || undefined)
}
className="input"
>
<option value="">All Projects</option>
{projects?.map((project) => (
<option key={project.id} value={project.id}>
{project.name}
</option>
))}
</select>
</div>
</div>
{/* Clear Filters Button */}
{(filters.startDate ||
filters.endDate ||
filters.clientId ||
filters.projectId) && (
<div className="mt-4">
<button onClick={clearFilters} className="btn btn-secondary">
Clear Filters
</button>
</div>
)}
</div>
{/* Total Hours Display */}
<div className="card bg-gradient-to-br from-primary-50 to-primary-100 border-primary-200">
<div className="flex items-center justify-between">
<div>
<p className="text-sm font-medium text-primary-700">
Total Working Time
</p>
<p className="text-4xl font-bold text-primary-900 mt-1">
{isLoading ? (
<span className="text-2xl">Loading...</span>
) : (
formatDuration(statistics?.totalSeconds || 0)
)}
</p>
</div>
<div className="p-4 bg-primary-200 rounded-full">
<Clock className="h-8 w-8 text-primary-700" />
</div>
</div>
<p className="mt-2 text-sm text-primary-600">
{statistics?.entryCount || 0} time entries
</p>
</div>
{/* Breakdown by Project */}
{statistics && statistics.byProject.length > 0 && (
<div className="card">
<h3 className="text-lg font-semibold text-gray-900 mb-4">
By Project
</h3>
<div className="space-y-3">
{statistics.byProject.map((project) => (
<div
key={project.projectId}
className="flex items-center justify-between p-3 bg-gray-50 rounded-lg"
>
<div className="flex items-center gap-3">
<div
className="w-3 h-3 rounded-full"
style={{
backgroundColor: project.projectColor || "#6b7280",
}}
/>
<span className="font-medium text-gray-900">
{project.projectName}
</span>
<span className="text-sm text-gray-500">
({project.entryCount} entries)
</span>
</div>
<span className="font-mono font-semibold text-gray-900">
{formatDuration(project.totalSeconds)}
</span>
</div>
))}
</div>
</div>
)}
{/* Breakdown by Client */}
{statistics && statistics.byClient.length > 0 && (
<div className="card">
<h3 className="text-lg font-semibold text-gray-900 mb-4">
By Client
</h3>
<div className="space-y-3">
{statistics.byClient.map((client) => (
<div
key={client.clientId}
className="flex items-center justify-between p-3 bg-gray-50 rounded-lg"
>
<div className="flex items-center gap-3">
<Building2 className="h-4 w-4 text-gray-400" />
<span className="font-medium text-gray-900">
{client.clientName}
</span>
<span className="text-sm text-gray-500">
({client.entryCount} entries)
</span>
</div>
<span className="font-mono font-semibold text-gray-900">
{formatDuration(client.totalSeconds)}
</span>
</div>
))}
</div>
</div>
)}
{/* Empty State */}
{!isLoading && statistics && statistics.entryCount === 0 && (
<div className="card text-center py-12">
<BarChart3 className="h-12 w-12 text-gray-300 mx-auto mb-4" />
<h3 className="text-lg font-medium text-gray-900">
No data available
</h3>
<p className="text-gray-500 mt-1">
No time entries found for the selected filters.
</p>
</div>
)}
</div>
);
}

View File

@@ -56,6 +56,41 @@ export interface TimeEntryFilters {
limit?: number;
}
export interface StatisticsFilters {
startDate?: string;
endDate?: string;
projectId?: string;
clientId?: string;
}
export interface ProjectStatistics {
projectId: string;
projectName: string;
projectColor: string | null;
totalSeconds: number;
entryCount: number;
}
export interface ClientStatistics {
clientId: string;
clientName: string;
totalSeconds: number;
entryCount: number;
}
export interface TimeStatistics {
totalSeconds: number;
entryCount: number;
byProject: ProjectStatistics[];
byClient: ClientStatistics[];
filters: {
startDate: string | null;
endDate: string | null;
projectId: string | null;
clientId: string | null;
};
}
export interface PaginatedTimeEntries {
entries: TimeEntry[];
pagination: {