creates application
This commit is contained in:
17
.env.example
Normal file
17
.env.example
Normal file
@@ -0,0 +1,17 @@
|
||||
# Database
|
||||
DATABASE_URL="postgresql://user:password@localhost:5432/timetracker"
|
||||
|
||||
# OIDC Configuration
|
||||
OIDC_ISSUER_URL="https://your-oidc-provider.com"
|
||||
OIDC_CLIENT_ID="your-client-id"
|
||||
OIDC_REDIRECT_URI="http://localhost:3000/auth/callback"
|
||||
|
||||
# Session
|
||||
SESSION_SECRET="your-session-secret-min-32-characters"
|
||||
|
||||
# Server
|
||||
PORT=3001
|
||||
NODE_ENV=development
|
||||
|
||||
# Frontend URL (for CORS)
|
||||
FRONTEND_URL="http://localhost:5173"
|
||||
38
.gitignore
vendored
Normal file
38
.gitignore
vendored
Normal file
@@ -0,0 +1,38 @@
|
||||
# Dependencies
|
||||
node_modules/
|
||||
.pnp
|
||||
.pnp.js
|
||||
|
||||
# Production builds
|
||||
dist/
|
||||
build/
|
||||
|
||||
# Environment files
|
||||
.env
|
||||
.env.local
|
||||
.env.*.local
|
||||
|
||||
# IDE
|
||||
.idea/
|
||||
.vscode/
|
||||
*.swp
|
||||
*.swo
|
||||
|
||||
# OS
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
# Logs
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
logs/
|
||||
*.log
|
||||
|
||||
# Database
|
||||
*.db
|
||||
*.sqlite
|
||||
|
||||
# Prisma
|
||||
prisma/migrations/*/migration.sql
|
||||
!prisma/migrations/migration_lock.toml
|
||||
153
README.md
Normal file
153
README.md
Normal file
@@ -0,0 +1,153 @@
|
||||
# TimeTracker
|
||||
|
||||
A multi-user web application for tracking time spent working on projects. Users authenticate via an external OIDC provider and manage their own clients, projects, and time entries.
|
||||
|
||||
## Features
|
||||
|
||||
- **OIDC Authentication** - Secure login via external OpenID Connect provider with PKCE flow
|
||||
- **Client Management** - Create and manage clients/customers
|
||||
- **Project Management** - Organize work into projects with color coding
|
||||
- **Time Tracking** - Start/stop timer with live elapsed time display
|
||||
- **Manual Entry** - Add time entries manually for past work
|
||||
- **Validation** - Overlap prevention and end-time validation
|
||||
- **Responsive UI** - Works on desktop and mobile
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
|
||||
│ React │────▶│ Express │────▶│ PostgreSQL │
|
||||
│ Frontend │ │ Backend │ │ Database │
|
||||
└─────────────┘ └─────────────┘ └─────────────┘
|
||||
│
|
||||
▼
|
||||
┌─────────────┐
|
||||
│ OIDC │
|
||||
│ Provider │
|
||||
└─────────────┘
|
||||
```
|
||||
|
||||
## Quick Start
|
||||
|
||||
### Prerequisites
|
||||
|
||||
- Node.js 18+
|
||||
- PostgreSQL 14+
|
||||
- An OIDC provider (e.g., Keycloak, Auth0, Okta)
|
||||
|
||||
### 1. Database Setup
|
||||
|
||||
```bash
|
||||
# Create PostgreSQL database
|
||||
createdb timetracker
|
||||
```
|
||||
|
||||
### 2. Backend Setup
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
npm install
|
||||
|
||||
# Copy and configure environment
|
||||
cp ../.env.example .env
|
||||
# Edit .env with your database and OIDC settings
|
||||
|
||||
# Run migrations
|
||||
npx prisma migrate dev
|
||||
|
||||
# Start server
|
||||
npm run dev
|
||||
```
|
||||
|
||||
### 3. Frontend Setup
|
||||
|
||||
```bash
|
||||
cd frontend
|
||||
npm install
|
||||
npm run dev
|
||||
```
|
||||
|
||||
### 4. Environment Variables
|
||||
|
||||
Create `.env` in the backend directory:
|
||||
|
||||
```env
|
||||
# Database
|
||||
DATABASE_URL="postgresql://user:password@localhost:5432/timetracker"
|
||||
|
||||
# OIDC Configuration
|
||||
OIDC_ISSUER_URL="https://your-oidc-provider.com"
|
||||
OIDC_CLIENT_ID="your-client-id"
|
||||
OIDC_REDIRECT_URI="http://localhost:3001/auth/callback"
|
||||
|
||||
# Session
|
||||
SESSION_SECRET="your-secure-session-secret-min-32-chars"
|
||||
|
||||
# Server
|
||||
PORT=3001
|
||||
NODE_ENV=development
|
||||
FRONTEND_URL="http://localhost:5173"
|
||||
```
|
||||
|
||||
## API Endpoints
|
||||
|
||||
### Authentication
|
||||
- `GET /auth/login` - Initiate OIDC login
|
||||
- `GET /auth/callback` - OIDC callback
|
||||
- `POST /auth/logout` - End session
|
||||
- `GET /auth/me` - Get current user
|
||||
|
||||
### Clients
|
||||
- `GET /api/clients` - List clients
|
||||
- `POST /api/clients` - Create client
|
||||
- `PUT /api/clients/:id` - Update client
|
||||
- `DELETE /api/clients/:id` - Delete client
|
||||
|
||||
### Projects
|
||||
- `GET /api/projects` - List projects
|
||||
- `POST /api/projects` - Create project
|
||||
- `PUT /api/projects/:id` - Update project
|
||||
- `DELETE /api/projects/:id` - Delete project
|
||||
|
||||
### Time Entries
|
||||
- `GET /api/time-entries` - List entries (with filters/pagination)
|
||||
- `POST /api/time-entries` - Create entry
|
||||
- `PUT /api/time-entries/:id` - Update entry
|
||||
- `DELETE /api/time-entries/:id` - Delete entry
|
||||
|
||||
### Timer
|
||||
- `GET /api/timer` - Get ongoing timer
|
||||
- `POST /api/timer/start` - Start timer
|
||||
- `PUT /api/timer` - Update timer (set project)
|
||||
- `POST /api/timer/stop` - Stop timer (creates entry)
|
||||
|
||||
## Data Model
|
||||
|
||||
```
|
||||
User (oidc sub)
|
||||
├── Client[]
|
||||
│ └── Project[]
|
||||
│ └── TimeEntry[]
|
||||
└── OngoingTimer (optional)
|
||||
```
|
||||
|
||||
## Technology Stack
|
||||
|
||||
**Backend:**
|
||||
- Node.js + Express
|
||||
- TypeScript
|
||||
- Prisma ORM
|
||||
- PostgreSQL
|
||||
- OpenID Client
|
||||
|
||||
**Frontend:**
|
||||
- React 18
|
||||
- TypeScript
|
||||
- TanStack Query
|
||||
- React Router
|
||||
- Tailwind CSS
|
||||
- date-fns
|
||||
|
||||
## License
|
||||
|
||||
MIT
|
||||
25
backend/Dockerfile
Normal file
25
backend/Dockerfile
Normal file
@@ -0,0 +1,25 @@
|
||||
FROM node:20-alpine
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Copy package files
|
||||
COPY package*.json ./
|
||||
COPY prisma ./prisma/
|
||||
|
||||
# Install dependencies
|
||||
RUN npm ci
|
||||
|
||||
# Generate Prisma client
|
||||
RUN npx prisma generate
|
||||
|
||||
# Copy source code
|
||||
COPY . .
|
||||
|
||||
# Build TypeScript
|
||||
RUN npm run build
|
||||
|
||||
# Expose port
|
||||
EXPOSE 3001
|
||||
|
||||
# Start the application
|
||||
CMD ["sh", "-c", "npx prisma migrate deploy && npm start"]
|
||||
1791
backend/package-lock.json
generated
Normal file
1791
backend/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
30
backend/package.json
Normal file
30
backend/package.json
Normal file
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"name": "timetracker-backend",
|
||||
"version": "1.0.0",
|
||||
"scripts": {
|
||||
"dev": "tsx watch src/index.ts",
|
||||
"build": "tsc",
|
||||
"start": "node dist/index.js",
|
||||
"db:migrate": "prisma migrate dev",
|
||||
"db:generate": "prisma generate",
|
||||
"db:seed": "tsx prisma/seed.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@prisma/client": "^5.7.0",
|
||||
"cors": "^2.8.5",
|
||||
"dotenv": "^16.3.1",
|
||||
"express": "^4.18.2",
|
||||
"express-session": "^1.17.3",
|
||||
"openid-client": "^5.6.1",
|
||||
"zod": "^3.22.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/cors": "^2.8.17",
|
||||
"@types/express": "^4.17.21",
|
||||
"@types/express-session": "^1.17.10",
|
||||
"@types/node": "^20.10.5",
|
||||
"prisma": "^5.7.0",
|
||||
"tsx": "^4.7.0",
|
||||
"typescript": "^5.3.3"
|
||||
}
|
||||
}
|
||||
3
backend/prisma/migrations/migration_lock.toml
Normal file
3
backend/prisma/migrations/migration_lock.toml
Normal file
@@ -0,0 +1,3 @@
|
||||
# Please do not edit this file manually
|
||||
# It should be added in your version-control system (e.g., Git)
|
||||
provider = "postgresql"
|
||||
93
backend/prisma/schema.prisma
Normal file
93
backend/prisma/schema.prisma
Normal file
@@ -0,0 +1,93 @@
|
||||
generator client {
|
||||
provider = "prisma-client-js"
|
||||
}
|
||||
|
||||
datasource db {
|
||||
provider = "postgresql"
|
||||
url = env("DATABASE_URL")
|
||||
}
|
||||
|
||||
model User {
|
||||
id String @id @db.VarChar(255)
|
||||
username String @db.VarChar(255)
|
||||
email String @db.VarChar(255)
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
clients Client[]
|
||||
projects Project[]
|
||||
timeEntries TimeEntry[]
|
||||
ongoingTimer OngoingTimer?
|
||||
|
||||
@@map("users")
|
||||
}
|
||||
|
||||
model Client {
|
||||
id String @id @default(uuid())
|
||||
name String @db.VarChar(255)
|
||||
description String? @db.Text
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
userId String @map("user_id") @db.VarChar(255)
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
projects Project[]
|
||||
|
||||
@@index([userId])
|
||||
@@map("clients")
|
||||
}
|
||||
|
||||
model Project {
|
||||
id String @id @default(uuid())
|
||||
name String @db.VarChar(255)
|
||||
description String? @db.Text
|
||||
color String? @db.VarChar(7) // Hex color code
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
userId String @map("user_id") @db.VarChar(255)
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
clientId String @map("client_id")
|
||||
client Client @relation(fields: [clientId], references: [id], onDelete: Cascade)
|
||||
|
||||
timeEntries TimeEntry[]
|
||||
ongoingTimer OngoingTimer?
|
||||
|
||||
@@index([userId])
|
||||
@@index([clientId])
|
||||
@@map("projects")
|
||||
}
|
||||
|
||||
model TimeEntry {
|
||||
id String @id @default(uuid())
|
||||
startTime DateTime @map("start_time") @db.Timestamptz()
|
||||
endTime DateTime @map("end_time") @db.Timestamptz()
|
||||
description String? @db.Text
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
userId String @map("user_id") @db.VarChar(255)
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
projectId String @map("project_id")
|
||||
project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([userId])
|
||||
@@index([userId, startTime])
|
||||
@@index([projectId])
|
||||
@@map("time_entries")
|
||||
}
|
||||
|
||||
model OngoingTimer {
|
||||
id String @id @default(uuid())
|
||||
startTime DateTime @map("start_time") @db.Timestamptz()
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
userId String @map("user_id") @db.VarChar(255) @unique
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
projectId String? @map("project_id")
|
||||
project Project? @relation(fields: [projectId], references: [id], onDelete: SetNull)
|
||||
|
||||
@@index([userId])
|
||||
@@map("ongoing_timers")
|
||||
}
|
||||
115
backend/src/auth/oidc.ts
Normal file
115
backend/src/auth/oidc.ts
Normal file
@@ -0,0 +1,115 @@
|
||||
import { Issuer, generators, Client, TokenSet } from 'openid-client';
|
||||
import { config } from '../config';
|
||||
import type { AuthenticatedUser } from '../types';
|
||||
|
||||
let oidcClient: Client | null = null;
|
||||
|
||||
export async function initializeOIDC(): Promise<void> {
|
||||
try {
|
||||
const issuer = await Issuer.discover(config.oidc.issuerUrl);
|
||||
|
||||
oidcClient = new issuer.Client({
|
||||
client_id: config.oidc.clientId,
|
||||
redirect_uris: [config.oidc.redirectUri],
|
||||
response_types: ['code'],
|
||||
token_endpoint_auth_method: 'none', // PKCE flow - no client secret
|
||||
});
|
||||
|
||||
console.log('OIDC client initialized');
|
||||
} catch (error) {
|
||||
console.error('Failed to initialize OIDC client:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export function getOIDCClient(): Client {
|
||||
if (!oidcClient) {
|
||||
throw new Error('OIDC client not initialized');
|
||||
}
|
||||
return oidcClient;
|
||||
}
|
||||
|
||||
export interface AuthSession {
|
||||
codeVerifier: string;
|
||||
state: string;
|
||||
nonce: string;
|
||||
}
|
||||
|
||||
export function createAuthSession(): AuthSession {
|
||||
return {
|
||||
codeVerifier: generators.codeVerifier(),
|
||||
state: generators.state(),
|
||||
nonce: generators.nonce(),
|
||||
};
|
||||
}
|
||||
|
||||
export function getAuthorizationUrl(session: AuthSession): string {
|
||||
const client = getOIDCClient();
|
||||
const codeChallenge = generators.codeChallenge(session.codeVerifier);
|
||||
|
||||
return client.authorizationUrl({
|
||||
scope: 'openid profile email',
|
||||
state: session.state,
|
||||
nonce: session.nonce,
|
||||
code_challenge: codeChallenge,
|
||||
code_challenge_method: 'S256',
|
||||
});
|
||||
}
|
||||
|
||||
export async function handleCallback(
|
||||
params: Record<string, string>,
|
||||
session: AuthSession
|
||||
): Promise<TokenSet> {
|
||||
const client = getOIDCClient();
|
||||
|
||||
const tokenSet = await client.callback(
|
||||
config.oidc.redirectUri,
|
||||
params,
|
||||
{
|
||||
code_verifier: session.codeVerifier,
|
||||
state: session.state,
|
||||
nonce: session.nonce,
|
||||
}
|
||||
);
|
||||
|
||||
return tokenSet;
|
||||
}
|
||||
|
||||
export async function getUserInfo(tokenSet: TokenSet): Promise<AuthenticatedUser> {
|
||||
const client = getOIDCClient();
|
||||
|
||||
const claims = tokenSet.claims();
|
||||
|
||||
// Try to get more detailed userinfo if available
|
||||
let userInfo: Record<string, unknown> = {};
|
||||
try {
|
||||
userInfo = await client.userinfo(tokenSet);
|
||||
} catch {
|
||||
// Some providers don't support userinfo endpoint
|
||||
// We'll use the claims from the ID token
|
||||
}
|
||||
|
||||
const id = String(claims.sub);
|
||||
const username = String(userInfo.preferred_username || claims.preferred_username || claims.name || id);
|
||||
const email = String(userInfo.email || claims.email || '');
|
||||
|
||||
if (!email) {
|
||||
throw new Error('Email not provided by OIDC provider');
|
||||
}
|
||||
|
||||
return {
|
||||
id,
|
||||
username,
|
||||
email,
|
||||
};
|
||||
}
|
||||
|
||||
export async function verifyToken(tokenSet: TokenSet): Promise<boolean> {
|
||||
try {
|
||||
const client = getOIDCClient();
|
||||
await client.userinfo(tokenSet);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
47
backend/src/config/index.ts
Normal file
47
backend/src/config/index.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
import dotenv from 'dotenv';
|
||||
import path from 'path';
|
||||
|
||||
dotenv.config({ path: path.resolve(__dirname, '../../.env') });
|
||||
|
||||
export const config = {
|
||||
port: parseInt(process.env.PORT || '3001', 10),
|
||||
nodeEnv: process.env.NODE_ENV || 'development',
|
||||
|
||||
database: {
|
||||
url: process.env.DATABASE_URL || '',
|
||||
},
|
||||
|
||||
oidc: {
|
||||
issuerUrl: process.env.OIDC_ISSUER_URL || '',
|
||||
clientId: process.env.OIDC_CLIENT_ID || '',
|
||||
redirectUri: process.env.OIDC_REDIRECT_URI || 'http://localhost:3001/auth/callback',
|
||||
},
|
||||
|
||||
session: {
|
||||
secret: process.env.SESSION_SECRET || 'default-secret-change-in-production',
|
||||
maxAge: 24 * 60 * 60 * 1000, // 24 hours
|
||||
},
|
||||
|
||||
cors: {
|
||||
origin: process.env.FRONTEND_URL || 'http://localhost:5173',
|
||||
credentials: true,
|
||||
},
|
||||
};
|
||||
|
||||
export function validateConfig(): void {
|
||||
const required = [
|
||||
'DATABASE_URL',
|
||||
'OIDC_ISSUER_URL',
|
||||
'OIDC_CLIENT_ID',
|
||||
];
|
||||
|
||||
for (const key of required) {
|
||||
if (!process.env[key]) {
|
||||
throw new Error(`Missing required environment variable: ${key}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (config.session.secret.length < 32) {
|
||||
console.warn('Warning: SESSION_SECRET should be at least 32 characters for security');
|
||||
}
|
||||
}
|
||||
74
backend/src/index.ts
Normal file
74
backend/src/index.ts
Normal file
@@ -0,0 +1,74 @@
|
||||
import express from 'express';
|
||||
import cors from 'cors';
|
||||
import session from 'express-session';
|
||||
import { config, validateConfig } from './config';
|
||||
import { connectDatabase } from './prisma/client';
|
||||
import { errorHandler, notFoundHandler } from './middleware/errorHandler';
|
||||
|
||||
// Import routes
|
||||
import authRoutes from './routes/auth.routes';
|
||||
import clientRoutes from './routes/client.routes';
|
||||
import projectRoutes from './routes/project.routes';
|
||||
import timeEntryRoutes from './routes/timeEntry.routes';
|
||||
import timerRoutes from './routes/timer.routes';
|
||||
|
||||
async function main() {
|
||||
// Validate configuration
|
||||
validateConfig();
|
||||
|
||||
// Connect to database
|
||||
await connectDatabase();
|
||||
|
||||
const app = express();
|
||||
|
||||
// CORS
|
||||
app.use(cors({
|
||||
origin: config.cors.origin,
|
||||
credentials: true,
|
||||
}));
|
||||
|
||||
// Body parsing
|
||||
app.use(express.json());
|
||||
app.use(express.urlencoded({ extended: true }));
|
||||
|
||||
// Session
|
||||
app.use(session({
|
||||
secret: config.session.secret,
|
||||
resave: false,
|
||||
saveUninitialized: false,
|
||||
name: 'sessionId',
|
||||
cookie: {
|
||||
secure: config.nodeEnv === 'production',
|
||||
httpOnly: true,
|
||||
maxAge: config.session.maxAge,
|
||||
sameSite: config.nodeEnv === 'production' ? 'strict' : 'lax',
|
||||
},
|
||||
}));
|
||||
|
||||
// Health check
|
||||
app.get('/health', (_req, res) => {
|
||||
res.json({ status: 'ok', timestamp: new Date().toISOString() });
|
||||
});
|
||||
|
||||
// Routes
|
||||
app.use('/auth', authRoutes);
|
||||
app.use('/api/clients', clientRoutes);
|
||||
app.use('/api/projects', projectRoutes);
|
||||
app.use('/api/time-entries', timeEntryRoutes);
|
||||
app.use('/api/timer', timerRoutes);
|
||||
|
||||
// Error handling
|
||||
app.use(notFoundHandler);
|
||||
app.use(errorHandler);
|
||||
|
||||
// Start server
|
||||
app.listen(config.port, () => {
|
||||
console.log(`Server running on port ${config.port}`);
|
||||
console.log(`Environment: ${config.nodeEnv}`);
|
||||
});
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
console.error('Failed to start server:', error);
|
||||
process.exit(1);
|
||||
});
|
||||
43
backend/src/middleware/auth.ts
Normal file
43
backend/src/middleware/auth.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
import { Request, Response, NextFunction } from 'express';
|
||||
import { prisma } from '../prisma/client';
|
||||
import type { AuthenticatedRequest, AuthenticatedUser } from '../types';
|
||||
|
||||
export function requireAuth(
|
||||
req: AuthenticatedRequest,
|
||||
res: Response,
|
||||
next: NextFunction
|
||||
): void {
|
||||
if (!req.session?.user) {
|
||||
res.status(401).json({ error: 'Unauthorized' });
|
||||
return;
|
||||
}
|
||||
|
||||
req.user = req.session.user as AuthenticatedUser;
|
||||
next();
|
||||
}
|
||||
|
||||
export function optionalAuth(
|
||||
req: AuthenticatedRequest,
|
||||
res: Response,
|
||||
next: NextFunction
|
||||
): void {
|
||||
if (req.session?.user) {
|
||||
req.user = req.session.user as AuthenticatedUser;
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
export async function syncUser(user: AuthenticatedUser): Promise<void> {
|
||||
await prisma.user.upsert({
|
||||
where: { id: user.id },
|
||||
update: {
|
||||
username: user.username,
|
||||
email: user.email,
|
||||
},
|
||||
create: {
|
||||
id: user.id,
|
||||
username: user.username,
|
||||
email: user.email,
|
||||
},
|
||||
});
|
||||
}
|
||||
54
backend/src/middleware/errorHandler.ts
Normal file
54
backend/src/middleware/errorHandler.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
import { Request, Response, NextFunction } from 'express';
|
||||
import { Prisma } from '@prisma/client';
|
||||
|
||||
export interface ApiError extends Error {
|
||||
statusCode?: number;
|
||||
code?: string;
|
||||
}
|
||||
|
||||
export function errorHandler(
|
||||
err: ApiError,
|
||||
_req: Request,
|
||||
res: Response,
|
||||
_next: NextFunction
|
||||
): void {
|
||||
console.error('Error:', err);
|
||||
|
||||
// Prisma errors
|
||||
if (err instanceof Prisma.PrismaClientKnownRequestError) {
|
||||
switch (err.code) {
|
||||
case 'P2002':
|
||||
res.status(409).json({ error: 'Resource already exists' });
|
||||
return;
|
||||
case 'P2025':
|
||||
res.status(404).json({ error: 'Resource not found' });
|
||||
return;
|
||||
case 'P2003':
|
||||
res.status(400).json({ error: 'Invalid reference to related resource' });
|
||||
return;
|
||||
default:
|
||||
res.status(500).json({ error: 'Database error' });
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (err instanceof Prisma.PrismaClientValidationError) {
|
||||
res.status(400).json({ error: 'Invalid data format' });
|
||||
return;
|
||||
}
|
||||
|
||||
const statusCode = err.statusCode || 500;
|
||||
const message = err.message || 'Internal server error';
|
||||
|
||||
res.status(statusCode).json({
|
||||
error: statusCode === 500 ? 'Internal server error' : message
|
||||
});
|
||||
}
|
||||
|
||||
export function notFoundHandler(
|
||||
_req: Request,
|
||||
res: Response,
|
||||
_next: NextFunction
|
||||
): void {
|
||||
res.status(404).json({ error: 'Endpoint not found' });
|
||||
}
|
||||
51
backend/src/middleware/validation.ts
Normal file
51
backend/src/middleware/validation.ts
Normal file
@@ -0,0 +1,51 @@
|
||||
import { Request, Response, NextFunction } from 'express';
|
||||
import { ZodSchema, ZodError } from 'zod';
|
||||
|
||||
export function validateBody<T>(schema: ZodSchema<T>) {
|
||||
return (req: Request, res: Response, next: NextFunction): void => {
|
||||
try {
|
||||
req.body = schema.parse(req.body);
|
||||
next();
|
||||
} catch (error) {
|
||||
if (error instanceof ZodError) {
|
||||
const errors = error.errors.map(e => ({
|
||||
path: e.path.join('.'),
|
||||
message: e.message,
|
||||
}));
|
||||
res.status(400).json({ error: 'Validation failed', details: errors });
|
||||
return;
|
||||
}
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export function validateParams<T>(schema: ZodSchema<T>) {
|
||||
return (req: Request, res: Response, next: NextFunction): void => {
|
||||
try {
|
||||
req.params = schema.parse(req.params) as typeof req.params;
|
||||
next();
|
||||
} catch (error) {
|
||||
if (error instanceof ZodError) {
|
||||
res.status(400).json({ error: 'Invalid parameters', details: error.errors });
|
||||
return;
|
||||
}
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export function validateQuery<T>(schema: ZodSchema<T>) {
|
||||
return (req: Request, res: Response, next: NextFunction): void => {
|
||||
try {
|
||||
req.query = schema.parse(req.query) as typeof req.query;
|
||||
next();
|
||||
} catch (error) {
|
||||
if (error instanceof ZodError) {
|
||||
res.status(400).json({ error: 'Invalid query parameters', details: error.errors });
|
||||
return;
|
||||
}
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
}
|
||||
25
backend/src/prisma/client.ts
Normal file
25
backend/src/prisma/client.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
|
||||
const globalForPrisma = globalThis as unknown as {
|
||||
prisma: PrismaClient | undefined;
|
||||
};
|
||||
|
||||
export const prisma = globalForPrisma.prisma ?? new PrismaClient();
|
||||
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
globalForPrisma.prisma = prisma;
|
||||
}
|
||||
|
||||
export async function connectDatabase(): Promise<void> {
|
||||
try {
|
||||
await prisma.$connect();
|
||||
console.log('Connected to database');
|
||||
} catch (error) {
|
||||
console.error('Failed to connect to database:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export async function disconnectDatabase(): Promise<void> {
|
||||
await prisma.$disconnect();
|
||||
}
|
||||
86
backend/src/routes/auth.routes.ts
Normal file
86
backend/src/routes/auth.routes.ts
Normal file
@@ -0,0 +1,86 @@
|
||||
import { Router } from 'express';
|
||||
import { initializeOIDC, createAuthSession, getAuthorizationUrl, handleCallback, getUserInfo } from '../auth/oidc';
|
||||
import { syncUser } from '../middleware/auth';
|
||||
import type { AuthenticatedRequest } from '../types';
|
||||
|
||||
const router = Router();
|
||||
|
||||
// Initialize OIDC on first request
|
||||
let oidcInitialized = false;
|
||||
|
||||
async function ensureOIDC() {
|
||||
if (!oidcInitialized) {
|
||||
await initializeOIDC();
|
||||
oidcInitialized = true;
|
||||
}
|
||||
}
|
||||
|
||||
// GET /auth/login - Initiate OIDC login flow
|
||||
router.get('/login', async (req, res) => {
|
||||
try {
|
||||
await ensureOIDC();
|
||||
|
||||
const session = createAuthSession();
|
||||
req.session.oidc = session;
|
||||
|
||||
const authorizationUrl = getAuthorizationUrl(session);
|
||||
res.redirect(authorizationUrl);
|
||||
} catch (error) {
|
||||
console.error('Login error:', error);
|
||||
res.status(500).json({ error: 'Failed to initiate login' });
|
||||
}
|
||||
});
|
||||
|
||||
// GET /auth/callback - OIDC callback handler
|
||||
router.get('/callback', async (req, res) => {
|
||||
try {
|
||||
await ensureOIDC();
|
||||
|
||||
const oidcSession = req.session.oidc;
|
||||
if (!oidcSession) {
|
||||
res.status(400).json({ error: 'Invalid session' });
|
||||
return;
|
||||
}
|
||||
|
||||
const tokenSet = await handleCallback(req.query as Record<string, string>, oidcSession);
|
||||
const user = await getUserInfo(tokenSet);
|
||||
|
||||
// Sync user with database
|
||||
await syncUser(user);
|
||||
|
||||
// Store user in session
|
||||
req.session.user = user;
|
||||
delete req.session.oidc;
|
||||
|
||||
// Redirect to frontend
|
||||
const frontendUrl = process.env.FRONTEND_URL || 'http://localhost:5173';
|
||||
res.redirect(`${frontendUrl}/auth/callback?success=true`);
|
||||
} catch (error) {
|
||||
console.error('Callback error:', error);
|
||||
const frontendUrl = process.env.FRONTEND_URL || 'http://localhost:5173';
|
||||
res.redirect(`${frontendUrl}/auth/callback?error=authentication_failed`);
|
||||
}
|
||||
});
|
||||
|
||||
// POST /auth/logout - End session
|
||||
router.post('/logout', (req: AuthenticatedRequest, res) => {
|
||||
req.session.destroy((err) => {
|
||||
if (err) {
|
||||
res.status(500).json({ error: 'Failed to logout' });
|
||||
return;
|
||||
}
|
||||
res.clearCookie('connect.sid');
|
||||
res.json({ message: 'Logged out successfully' });
|
||||
});
|
||||
});
|
||||
|
||||
// GET /auth/me - Get current user
|
||||
router.get('/me', (req: AuthenticatedRequest, res) => {
|
||||
if (!req.session?.user) {
|
||||
res.status(401).json({ error: 'Not authenticated' });
|
||||
return;
|
||||
}
|
||||
res.json(req.session.user);
|
||||
});
|
||||
|
||||
export default router;
|
||||
67
backend/src/routes/client.routes.ts
Normal file
67
backend/src/routes/client.routes.ts
Normal file
@@ -0,0 +1,67 @@
|
||||
import { Router } from 'express';
|
||||
import { requireAuth } from '../middleware/auth';
|
||||
import { validateBody, validateParams } from '../middleware/validation';
|
||||
import { ClientService } from '../services/client.service';
|
||||
import { CreateClientSchema, UpdateClientSchema, IdSchema } from '../schemas';
|
||||
import type { AuthenticatedRequest } from '../types';
|
||||
|
||||
const router = Router();
|
||||
const clientService = new ClientService();
|
||||
|
||||
// GET /api/clients - List user's clients
|
||||
router.get('/', requireAuth, async (req: AuthenticatedRequest, res, next) => {
|
||||
try {
|
||||
const clients = await clientService.findAll(req.user!.id);
|
||||
res.json(clients);
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
});
|
||||
|
||||
// POST /api/clients - Create client
|
||||
router.post(
|
||||
'/',
|
||||
requireAuth,
|
||||
validateBody(CreateClientSchema),
|
||||
async (req: AuthenticatedRequest, res, next) => {
|
||||
try {
|
||||
const client = await clientService.create(req.user!.id, req.body);
|
||||
res.status(201).json(client);
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// PUT /api/clients/:id - Update client
|
||||
router.put(
|
||||
'/:id',
|
||||
requireAuth,
|
||||
validateParams(IdSchema),
|
||||
validateBody(UpdateClientSchema),
|
||||
async (req: AuthenticatedRequest, res, next) => {
|
||||
try {
|
||||
const client = await clientService.update(req.params.id, req.user!.id, req.body);
|
||||
res.json(client);
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// DELETE /api/clients/:id - Delete client
|
||||
router.delete(
|
||||
'/:id',
|
||||
requireAuth,
|
||||
validateParams(IdSchema),
|
||||
async (req: AuthenticatedRequest, res, next) => {
|
||||
try {
|
||||
await clientService.delete(req.params.id, req.user!.id);
|
||||
res.status(204).send();
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
export default router;
|
||||
78
backend/src/routes/project.routes.ts
Normal file
78
backend/src/routes/project.routes.ts
Normal file
@@ -0,0 +1,78 @@
|
||||
import { Router } from 'express';
|
||||
import { requireAuth } from '../middleware/auth';
|
||||
import { validateBody, validateParams, validateQuery } from '../middleware/validation';
|
||||
import { ProjectService } from '../services/project.service';
|
||||
import { CreateProjectSchema, UpdateProjectSchema, IdSchema } from '../schemas';
|
||||
import { z } from 'zod';
|
||||
import type { AuthenticatedRequest } from '../types';
|
||||
|
||||
const router = Router();
|
||||
const projectService = new ProjectService();
|
||||
|
||||
const QuerySchema = z.object({
|
||||
clientId: z.string().uuid().optional(),
|
||||
});
|
||||
|
||||
// GET /api/projects - List user's projects
|
||||
router.get(
|
||||
'/',
|
||||
requireAuth,
|
||||
validateQuery(QuerySchema),
|
||||
async (req: AuthenticatedRequest, res, next) => {
|
||||
try {
|
||||
const { clientId } = req.query as { clientId?: string };
|
||||
const projects = await projectService.findAll(req.user!.id, clientId);
|
||||
res.json(projects);
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// POST /api/projects - Create project
|
||||
router.post(
|
||||
'/',
|
||||
requireAuth,
|
||||
validateBody(CreateProjectSchema),
|
||||
async (req: AuthenticatedRequest, res, next) => {
|
||||
try {
|
||||
const project = await projectService.create(req.user!.id, req.body);
|
||||
res.status(201).json(project);
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// PUT /api/projects/:id - Update project
|
||||
router.put(
|
||||
'/:id',
|
||||
requireAuth,
|
||||
validateParams(IdSchema),
|
||||
validateBody(UpdateProjectSchema),
|
||||
async (req: AuthenticatedRequest, res, next) => {
|
||||
try {
|
||||
const project = await projectService.update(req.params.id, req.user!.id, req.body);
|
||||
res.json(project);
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// DELETE /api/projects/:id - Delete project
|
||||
router.delete(
|
||||
'/:id',
|
||||
requireAuth,
|
||||
validateParams(IdSchema),
|
||||
async (req: AuthenticatedRequest, res, next) => {
|
||||
try {
|
||||
await projectService.delete(req.params.id, req.user!.id);
|
||||
res.status(204).send();
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
export default router;
|
||||
72
backend/src/routes/timeEntry.routes.ts
Normal file
72
backend/src/routes/timeEntry.routes.ts
Normal file
@@ -0,0 +1,72 @@
|
||||
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';
|
||||
|
||||
const router = Router();
|
||||
const timeEntryService = new TimeEntryService();
|
||||
|
||||
// GET /api/time-entries - List user's entries
|
||||
router.get(
|
||||
'/',
|
||||
requireAuth,
|
||||
validateQuery(TimeEntryFiltersSchema),
|
||||
async (req: AuthenticatedRequest, res, next) => {
|
||||
try {
|
||||
const result = await timeEntryService.findAll(req.user!.id, req.query);
|
||||
res.json(result);
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// POST /api/time-entries - Create entry manually
|
||||
router.post(
|
||||
'/',
|
||||
requireAuth,
|
||||
validateBody(CreateTimeEntrySchema),
|
||||
async (req: AuthenticatedRequest, res, next) => {
|
||||
try {
|
||||
const entry = await timeEntryService.create(req.user!.id, req.body);
|
||||
res.status(201).json(entry);
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// PUT /api/time-entries/:id - Update entry
|
||||
router.put(
|
||||
'/: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);
|
||||
res.json(entry);
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// DELETE /api/time-entries/:id - Delete entry
|
||||
router.delete(
|
||||
'/:id',
|
||||
requireAuth,
|
||||
validateParams(IdSchema),
|
||||
async (req: AuthenticatedRequest, res, next) => {
|
||||
try {
|
||||
await timeEntryService.delete(req.params.id, req.user!.id);
|
||||
res.status(204).send();
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
export default router;
|
||||
66
backend/src/routes/timer.routes.ts
Normal file
66
backend/src/routes/timer.routes.ts
Normal file
@@ -0,0 +1,66 @@
|
||||
import { Router } from 'express';
|
||||
import { requireAuth } from '../middleware/auth';
|
||||
import { validateBody } from '../middleware/validation';
|
||||
import { TimerService } from '../services/timer.service';
|
||||
import { StartTimerSchema, UpdateTimerSchema, StopTimerSchema } from '../schemas';
|
||||
import type { AuthenticatedRequest } from '../types';
|
||||
|
||||
const router = Router();
|
||||
const timerService = new TimerService();
|
||||
|
||||
// GET /api/timer - Get current ongoing timer
|
||||
router.get('/', requireAuth, async (req: AuthenticatedRequest, res, next) => {
|
||||
try {
|
||||
const timer = await timerService.getOngoingTimer(req.user!.id);
|
||||
res.json(timer);
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
});
|
||||
|
||||
// POST /api/timer/start - Start timer
|
||||
router.post(
|
||||
'/start',
|
||||
requireAuth,
|
||||
validateBody(StartTimerSchema),
|
||||
async (req: AuthenticatedRequest, res, next) => {
|
||||
try {
|
||||
const timer = await timerService.start(req.user!.id, req.body);
|
||||
res.status(201).json(timer);
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// PUT /api/timer - Update ongoing timer
|
||||
router.put(
|
||||
'/',
|
||||
requireAuth,
|
||||
validateBody(UpdateTimerSchema),
|
||||
async (req: AuthenticatedRequest, res, next) => {
|
||||
try {
|
||||
const timer = await timerService.update(req.user!.id, req.body);
|
||||
res.json(timer);
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// POST /api/timer/stop - Stop timer
|
||||
router.post(
|
||||
'/stop',
|
||||
requireAuth,
|
||||
validateBody(StopTimerSchema),
|
||||
async (req: AuthenticatedRequest, res, next) => {
|
||||
try {
|
||||
const entry = await timerService.stop(req.user!.id, req.body);
|
||||
res.json(entry);
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
export default router;
|
||||
64
backend/src/schemas/index.ts
Normal file
64
backend/src/schemas/index.ts
Normal file
@@ -0,0 +1,64 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
export const IdSchema = z.object({
|
||||
id: z.string().uuid(),
|
||||
});
|
||||
|
||||
export const CreateClientSchema = z.object({
|
||||
name: z.string().min(1).max(255),
|
||||
description: z.string().max(1000).optional(),
|
||||
});
|
||||
|
||||
export const UpdateClientSchema = z.object({
|
||||
name: z.string().min(1).max(255).optional(),
|
||||
description: z.string().max(1000).optional(),
|
||||
});
|
||||
|
||||
export const CreateProjectSchema = z.object({
|
||||
name: z.string().min(1).max(255),
|
||||
description: z.string().max(1000).optional(),
|
||||
color: z.string().regex(/^#[0-9A-Fa-f]{6}$/).optional(),
|
||||
clientId: z.string().uuid(),
|
||||
});
|
||||
|
||||
export const UpdateProjectSchema = z.object({
|
||||
name: z.string().min(1).max(255).optional(),
|
||||
description: z.string().max(1000).optional(),
|
||||
color: z.string().regex(/^#[0-9A-Fa-f]{6}$/).optional().nullable(),
|
||||
clientId: z.string().uuid().optional(),
|
||||
});
|
||||
|
||||
export const CreateTimeEntrySchema = z.object({
|
||||
startTime: z.string().datetime(),
|
||||
endTime: z.string().datetime(),
|
||||
description: z.string().max(1000).optional(),
|
||||
projectId: z.string().uuid(),
|
||||
});
|
||||
|
||||
export const UpdateTimeEntrySchema = z.object({
|
||||
startTime: z.string().datetime().optional(),
|
||||
endTime: z.string().datetime().optional(),
|
||||
description: z.string().max(1000).optional(),
|
||||
projectId: z.string().uuid().optional(),
|
||||
});
|
||||
|
||||
export const TimeEntryFiltersSchema = z.object({
|
||||
startDate: z.string().datetime().optional(),
|
||||
endDate: z.string().datetime().optional(),
|
||||
projectId: z.string().uuid().optional(),
|
||||
clientId: z.string().uuid().optional(),
|
||||
page: z.coerce.number().int().min(1).default(1),
|
||||
limit: z.coerce.number().int().min(1).max(100).default(50),
|
||||
});
|
||||
|
||||
export const StartTimerSchema = z.object({
|
||||
projectId: z.string().uuid().optional(),
|
||||
});
|
||||
|
||||
export const UpdateTimerSchema = z.object({
|
||||
projectId: z.string().uuid().optional().nullable(),
|
||||
});
|
||||
|
||||
export const StopTimerSchema = z.object({
|
||||
projectId: z.string().uuid().optional(),
|
||||
});
|
||||
53
backend/src/services/client.service.ts
Normal file
53
backend/src/services/client.service.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
import { prisma } from '../prisma/client';
|
||||
import type { CreateClientInput, UpdateClientInput } from '../types';
|
||||
|
||||
export class ClientService {
|
||||
async findAll(userId: string) {
|
||||
return prisma.client.findMany({
|
||||
where: { userId },
|
||||
orderBy: { name: 'asc' },
|
||||
});
|
||||
}
|
||||
|
||||
async findById(id: string, userId: string) {
|
||||
return prisma.client.findFirst({
|
||||
where: { id, userId },
|
||||
});
|
||||
}
|
||||
|
||||
async create(userId: string, data: CreateClientInput) {
|
||||
return prisma.client.create({
|
||||
data: {
|
||||
...data,
|
||||
userId,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async update(id: string, userId: string, data: UpdateClientInput) {
|
||||
const client = await this.findById(id, userId);
|
||||
if (!client) {
|
||||
const error = new Error('Client not found') as Error & { statusCode: number };
|
||||
error.statusCode = 404;
|
||||
throw error;
|
||||
}
|
||||
|
||||
return prisma.client.update({
|
||||
where: { id },
|
||||
data,
|
||||
});
|
||||
}
|
||||
|
||||
async delete(id: string, userId: string) {
|
||||
const client = await this.findById(id, userId);
|
||||
if (!client) {
|
||||
const error = new Error('Client not found') as Error & { statusCode: number };
|
||||
error.statusCode = 404;
|
||||
throw error;
|
||||
}
|
||||
|
||||
await prisma.client.delete({
|
||||
where: { id },
|
||||
});
|
||||
}
|
||||
}
|
||||
121
backend/src/services/project.service.ts
Normal file
121
backend/src/services/project.service.ts
Normal file
@@ -0,0 +1,121 @@
|
||||
import { prisma } from '../prisma/client';
|
||||
|
||||
import type { CreateProjectInput, UpdateProjectInput } from '../types';
|
||||
|
||||
export class ProjectService {
|
||||
async findAll(userId: string, clientId?: string) {
|
||||
return prisma.project.findMany({
|
||||
where: {
|
||||
userId,
|
||||
...(clientId && { clientId }),
|
||||
},
|
||||
orderBy: { name: 'asc' },
|
||||
include: {
|
||||
client: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async findById(id: string, userId: string) {
|
||||
return prisma.project.findFirst({
|
||||
where: { id, userId },
|
||||
include: {
|
||||
client: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async create(userId: string, data: CreateProjectInput) {
|
||||
// Verify the client belongs to the user
|
||||
const client = await prisma.client.findFirst({
|
||||
where: { id: data.clientId, userId },
|
||||
});
|
||||
|
||||
if (!client) {
|
||||
const error = new Error('Client not found or does not belong to user') as Error & { statusCode: number };
|
||||
error.statusCode = 400;
|
||||
throw error;
|
||||
}
|
||||
|
||||
return prisma.project.create({
|
||||
data: {
|
||||
name: data.name,
|
||||
description: data.description,
|
||||
color: data.color,
|
||||
userId,
|
||||
clientId: data.clientId,
|
||||
},
|
||||
include: {
|
||||
client: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async update(id: string, userId: string, data: UpdateProjectInput) {
|
||||
const project = await this.findById(id, userId);
|
||||
if (!project) {
|
||||
const error = new Error('Project not found') as Error & { statusCode: number };
|
||||
error.statusCode = 404;
|
||||
throw error;
|
||||
}
|
||||
|
||||
// If clientId is being updated, verify it belongs to the user
|
||||
if (data.clientId) {
|
||||
const client = await prisma.client.findFirst({
|
||||
where: { id: data.clientId, userId },
|
||||
});
|
||||
|
||||
if (!client) {
|
||||
const error = new Error('Client not found or does not belong to user') as Error & { statusCode: number };
|
||||
error.statusCode = 400;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
return prisma.project.update({
|
||||
where: { id },
|
||||
data: {
|
||||
name: data.name,
|
||||
description: data.description,
|
||||
color: data.color,
|
||||
clientId: data.clientId,
|
||||
},
|
||||
include: {
|
||||
client: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async delete(id: string, userId: string) {
|
||||
const project = await this.findById(id, userId);
|
||||
if (!project) {
|
||||
const error = new Error('Project not found') as Error & { statusCode: number };
|
||||
error.statusCode = 404;
|
||||
throw error;
|
||||
}
|
||||
|
||||
await prisma.project.delete({
|
||||
where: { id },
|
||||
});
|
||||
}
|
||||
}
|
||||
249
backend/src/services/timeEntry.service.ts
Normal file
249
backend/src/services/timeEntry.service.ts
Normal file
@@ -0,0 +1,249 @@
|
||||
import { prisma } from '../prisma/client';
|
||||
import type { CreateTimeEntryInput, UpdateTimeEntryInput, TimeEntryFilters } from '../types';
|
||||
|
||||
export class TimeEntryService {
|
||||
async findAll(userId: string, filters: TimeEntryFilters = {}) {
|
||||
const { startDate, endDate, projectId, clientId, page = 1, limit = 50 } = filters;
|
||||
const skip = (page - 1) * limit;
|
||||
|
||||
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, total] = await Promise.all([
|
||||
prisma.timeEntry.findMany({
|
||||
where,
|
||||
orderBy: { startTime: 'desc' },
|
||||
skip,
|
||||
take: limit,
|
||||
include: {
|
||||
project: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
color: true,
|
||||
client: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
prisma.timeEntry.count({ where }),
|
||||
]);
|
||||
|
||||
return {
|
||||
entries,
|
||||
pagination: {
|
||||
page,
|
||||
limit,
|
||||
total,
|
||||
totalPages: Math.ceil(total / limit),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async findById(id: string, userId: string) {
|
||||
return prisma.timeEntry.findFirst({
|
||||
where: { id, userId },
|
||||
include: {
|
||||
project: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
color: true,
|
||||
client: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async create(userId: string, data: CreateTimeEntryInput) {
|
||||
const startTime = new Date(data.startTime);
|
||||
const endTime = new Date(data.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 };
|
||||
error.statusCode = 400;
|
||||
throw error;
|
||||
}
|
||||
|
||||
// Verify the project belongs to the user
|
||||
const project = await prisma.project.findFirst({
|
||||
where: { id: data.projectId, userId },
|
||||
});
|
||||
|
||||
if (!project) {
|
||||
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);
|
||||
if (hasOverlap) {
|
||||
const error = new Error('This time entry overlaps with an existing entry') as Error & { statusCode: number };
|
||||
error.statusCode = 400;
|
||||
throw error;
|
||||
}
|
||||
|
||||
return prisma.timeEntry.create({
|
||||
data: {
|
||||
startTime,
|
||||
endTime,
|
||||
description: data.description,
|
||||
userId,
|
||||
projectId: data.projectId,
|
||||
},
|
||||
include: {
|
||||
project: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
color: true,
|
||||
client: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
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 };
|
||||
error.statusCode = 404;
|
||||
throw error;
|
||||
}
|
||||
|
||||
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 };
|
||||
error.statusCode = 400;
|
||||
throw error;
|
||||
}
|
||||
|
||||
// If project changed, verify it belongs to the user
|
||||
if (data.projectId && data.projectId !== entry.projectId) {
|
||||
const project = await prisma.project.findFirst({
|
||||
where: { id: data.projectId, userId },
|
||||
});
|
||||
|
||||
if (!project) {
|
||||
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);
|
||||
if (hasOverlap) {
|
||||
const error = new Error('This time entry overlaps with an existing entry') as Error & { statusCode: number };
|
||||
error.statusCode = 400;
|
||||
throw error;
|
||||
}
|
||||
|
||||
return prisma.timeEntry.update({
|
||||
where: { id },
|
||||
data: {
|
||||
startTime,
|
||||
endTime,
|
||||
description: data.description,
|
||||
projectId: data.projectId,
|
||||
},
|
||||
include: {
|
||||
project: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
color: true,
|
||||
client: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
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 };
|
||||
error.statusCode = 404;
|
||||
throw error;
|
||||
}
|
||||
|
||||
await prisma.timeEntry.delete({
|
||||
where: { id },
|
||||
});
|
||||
}
|
||||
|
||||
private async hasOverlappingEntries(
|
||||
userId: string,
|
||||
startTime: Date,
|
||||
endTime: Date,
|
||||
excludeId?: string
|
||||
): Promise<boolean> {
|
||||
const where: {
|
||||
userId: string;
|
||||
id?: { not: string };
|
||||
OR: Array<{
|
||||
startTime?: { lt: Date };
|
||||
endTime?: { gt: Date };
|
||||
}>;
|
||||
} = {
|
||||
userId,
|
||||
OR: [
|
||||
// Entry starts during the new entry
|
||||
{ startTime: { lt: endTime }, endTime: { gt: startTime } },
|
||||
],
|
||||
};
|
||||
|
||||
if (excludeId) {
|
||||
where.id = { not: excludeId };
|
||||
}
|
||||
|
||||
const count = await prisma.timeEntry.count({ where });
|
||||
return count > 0;
|
||||
}
|
||||
}
|
||||
216
backend/src/services/timer.service.ts
Normal file
216
backend/src/services/timer.service.ts
Normal file
@@ -0,0 +1,216 @@
|
||||
import { prisma } from '../prisma/client';
|
||||
import type { StartTimerInput, UpdateTimerInput, StopTimerInput } from '../types';
|
||||
|
||||
export class TimerService {
|
||||
async getOngoingTimer(userId: string) {
|
||||
return prisma.ongoingTimer.findUnique({
|
||||
where: { userId },
|
||||
include: {
|
||||
project: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
color: true,
|
||||
client: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async start(userId: string, data?: StartTimerInput) {
|
||||
// Check if user already has an ongoing timer
|
||||
const existingTimer = await this.getOngoingTimer(userId);
|
||||
if (existingTimer) {
|
||||
const error = new Error('Timer is already running') as Error & { statusCode: number };
|
||||
error.statusCode = 400;
|
||||
throw error;
|
||||
}
|
||||
|
||||
// If projectId provided, verify it belongs to the user
|
||||
let projectId: string | null = null;
|
||||
if (data?.projectId) {
|
||||
const project = await prisma.project.findFirst({
|
||||
where: { id: data.projectId, userId },
|
||||
});
|
||||
|
||||
if (!project) {
|
||||
const error = new Error('Project not found') as Error & { statusCode: number };
|
||||
error.statusCode = 404;
|
||||
throw error;
|
||||
}
|
||||
|
||||
projectId = data.projectId;
|
||||
}
|
||||
|
||||
return prisma.ongoingTimer.create({
|
||||
data: {
|
||||
startTime: new Date(),
|
||||
userId,
|
||||
projectId,
|
||||
},
|
||||
include: {
|
||||
project: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
color: true,
|
||||
client: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async update(userId: string, data: UpdateTimerInput) {
|
||||
const timer = await this.getOngoingTimer(userId);
|
||||
if (!timer) {
|
||||
const error = new Error('No timer is running') as Error & { statusCode: number };
|
||||
error.statusCode = 404;
|
||||
throw error;
|
||||
}
|
||||
|
||||
// If projectId is explicitly null, clear the project
|
||||
// If projectId is a string, verify it belongs to the user
|
||||
let projectId: string | null | undefined = undefined;
|
||||
|
||||
if (data.projectId === null) {
|
||||
projectId = null;
|
||||
} else if (data.projectId) {
|
||||
const project = await prisma.project.findFirst({
|
||||
where: { id: data.projectId, userId },
|
||||
});
|
||||
|
||||
if (!project) {
|
||||
const error = new Error('Project not found') as Error & { statusCode: number };
|
||||
error.statusCode = 404;
|
||||
throw error;
|
||||
}
|
||||
|
||||
projectId = data.projectId;
|
||||
}
|
||||
|
||||
return prisma.ongoingTimer.update({
|
||||
where: { userId },
|
||||
data: projectId !== undefined ? { projectId } : {},
|
||||
include: {
|
||||
project: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
color: true,
|
||||
client: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async stop(userId: string, data?: StopTimerInput) {
|
||||
const timer = await this.getOngoingTimer(userId);
|
||||
if (!timer) {
|
||||
const error = new Error('No timer is running') as Error & { statusCode: number };
|
||||
error.statusCode = 404;
|
||||
throw error;
|
||||
}
|
||||
|
||||
// Determine which project to use
|
||||
let projectId = timer.projectId;
|
||||
|
||||
// If data.projectId is provided, use it instead
|
||||
if (data?.projectId) {
|
||||
const project = await prisma.project.findFirst({
|
||||
where: { id: data.projectId, userId },
|
||||
});
|
||||
|
||||
if (!project) {
|
||||
const error = new Error('Project not found') as Error & { statusCode: number };
|
||||
error.statusCode = 404;
|
||||
throw error;
|
||||
}
|
||||
|
||||
projectId = data.projectId;
|
||||
}
|
||||
|
||||
// If no project is selected, throw error requiring project selection
|
||||
if (!projectId) {
|
||||
const error = new Error('Please select a project before stopping the timer') as Error & { statusCode: number };
|
||||
error.statusCode = 400;
|
||||
throw error;
|
||||
}
|
||||
|
||||
const endTime = new Date();
|
||||
const startTime = timer.startTime;
|
||||
|
||||
// Check for overlapping entries
|
||||
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 };
|
||||
error.statusCode = 400;
|
||||
throw error;
|
||||
}
|
||||
|
||||
// Delete ongoing timer and create time entry in a transaction
|
||||
const result = await prisma.$transaction([
|
||||
prisma.ongoingTimer.delete({
|
||||
where: { userId },
|
||||
}),
|
||||
prisma.timeEntry.create({
|
||||
data: {
|
||||
startTime,
|
||||
endTime,
|
||||
userId,
|
||||
projectId,
|
||||
},
|
||||
include: {
|
||||
project: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
color: true,
|
||||
client: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
return result[1]; // Return the created time entry
|
||||
}
|
||||
|
||||
private async hasOverlappingEntries(
|
||||
userId: string,
|
||||
startTime: Date,
|
||||
endTime: Date
|
||||
): Promise<boolean> {
|
||||
const count = await prisma.timeEntry.count({
|
||||
where: {
|
||||
userId,
|
||||
OR: [
|
||||
{ startTime: { lt: endTime }, endTime: { gt: startTime } },
|
||||
],
|
||||
},
|
||||
});
|
||||
return count > 0;
|
||||
}
|
||||
}
|
||||
70
backend/src/types/index.ts
Normal file
70
backend/src/types/index.ts
Normal file
@@ -0,0 +1,70 @@
|
||||
import { Request } from 'express';
|
||||
|
||||
export interface AuthenticatedUser {
|
||||
id: string;
|
||||
username: string;
|
||||
email: string;
|
||||
}
|
||||
|
||||
export interface AuthenticatedRequest extends Request {
|
||||
user?: AuthenticatedUser;
|
||||
}
|
||||
|
||||
export interface CreateClientInput {
|
||||
name: string;
|
||||
description?: string;
|
||||
}
|
||||
|
||||
export interface UpdateClientInput {
|
||||
name?: string;
|
||||
description?: string;
|
||||
}
|
||||
|
||||
export interface CreateProjectInput {
|
||||
name: string;
|
||||
description?: string;
|
||||
color?: string;
|
||||
clientId: string;
|
||||
}
|
||||
|
||||
export interface UpdateProjectInput {
|
||||
name?: string;
|
||||
description?: string;
|
||||
color?: string;
|
||||
clientId?: string;
|
||||
}
|
||||
|
||||
export interface CreateTimeEntryInput {
|
||||
startTime: string;
|
||||
endTime: string;
|
||||
description?: string;
|
||||
projectId: string;
|
||||
}
|
||||
|
||||
export interface UpdateTimeEntryInput {
|
||||
startTime?: string;
|
||||
endTime?: string;
|
||||
description?: string;
|
||||
projectId?: string;
|
||||
}
|
||||
|
||||
export interface TimeEntryFilters {
|
||||
startDate?: string;
|
||||
endDate?: string;
|
||||
projectId?: string;
|
||||
clientId?: string;
|
||||
page?: number;
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
export interface StartTimerInput {
|
||||
projectId?: string;
|
||||
}
|
||||
|
||||
export interface UpdateTimerInput {
|
||||
projectId?: string | null;
|
||||
}
|
||||
|
||||
export interface StopTimerInput {
|
||||
projectId?: string;
|
||||
}
|
||||
10
backend/src/types/session.d.ts
vendored
Normal file
10
backend/src/types/session.d.ts
vendored
Normal file
@@ -0,0 +1,10 @@
|
||||
import 'express-session';
|
||||
import type { AuthenticatedUser } from './index';
|
||||
import type { AuthSession } from '../auth/oidc';
|
||||
|
||||
declare module 'express-session' {
|
||||
interface SessionData {
|
||||
user?: AuthenticatedUser;
|
||||
oidc?: AuthSession;
|
||||
}
|
||||
}
|
||||
18
backend/tsconfig.json
Normal file
18
backend/tsconfig.json
Normal file
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "Node16",
|
||||
"moduleResolution": "Node16",
|
||||
"lib": ["ES2022"],
|
||||
"outDir": "./dist",
|
||||
"rootDir": "./src",
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"resolveJsonModule": true,
|
||||
"declaration": true
|
||||
},
|
||||
"include": ["src/**/*"],
|
||||
"exclude": ["node_modules", "dist"]
|
||||
}
|
||||
51
docker-compose.yml
Normal file
51
docker-compose.yml
Normal file
@@ -0,0 +1,51 @@
|
||||
version: '3.8'
|
||||
|
||||
services:
|
||||
db:
|
||||
image: postgres:16-alpine
|
||||
environment:
|
||||
POSTGRES_USER: timetracker
|
||||
POSTGRES_PASSWORD: timetracker_password
|
||||
POSTGRES_DB: timetracker
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/data
|
||||
ports:
|
||||
- "5432:5432"
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U timetracker"]
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
|
||||
backend:
|
||||
build:
|
||||
context: ./backend
|
||||
dockerfile: Dockerfile
|
||||
environment:
|
||||
DATABASE_URL: "postgresql://timetracker:timetracker_password@db:5432/timetracker"
|
||||
OIDC_ISSUER_URL: ${OIDC_ISSUER_URL}
|
||||
OIDC_CLIENT_ID: ${OIDC_CLIENT_ID}
|
||||
OIDC_REDIRECT_URI: "http://localhost:3001/auth/callback"
|
||||
SESSION_SECRET: ${SESSION_SECRET}
|
||||
PORT: 3001
|
||||
NODE_ENV: production
|
||||
FRONTEND_URL: "http://localhost:5173"
|
||||
ports:
|
||||
- "3001:3001"
|
||||
depends_on:
|
||||
db:
|
||||
condition: service_healthy
|
||||
|
||||
frontend:
|
||||
build:
|
||||
context: ./frontend
|
||||
dockerfile: Dockerfile
|
||||
environment:
|
||||
VITE_API_URL: "http://localhost:3001"
|
||||
ports:
|
||||
- "5173:80"
|
||||
depends_on:
|
||||
- backend
|
||||
|
||||
volumes:
|
||||
postgres_data:
|
||||
20
frontend/Dockerfile
Normal file
20
frontend/Dockerfile
Normal file
@@ -0,0 +1,20 @@
|
||||
# Build stage
|
||||
FROM node:20-alpine as builder
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY package*.json ./
|
||||
RUN npm ci
|
||||
|
||||
COPY . .
|
||||
RUN npm run build
|
||||
|
||||
# Production stage
|
||||
FROM nginx:alpine
|
||||
|
||||
COPY --from=builder /app/dist /usr/share/nginx/html
|
||||
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||
|
||||
EXPOSE 80
|
||||
|
||||
CMD ["nginx", "-g", "daemon off;"]
|
||||
13
frontend/index.html
Normal file
13
frontend/index.html
Normal file
@@ -0,0 +1,13 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>TimeTracker</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
35
frontend/nginx.conf
Normal file
35
frontend/nginx.conf
Normal file
@@ -0,0 +1,35 @@
|
||||
server {
|
||||
listen 80;
|
||||
server_name localhost;
|
||||
root /usr/share/nginx/html;
|
||||
index index.html;
|
||||
|
||||
location / {
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
|
||||
# Proxy API requests to backend
|
||||
location /api {
|
||||
proxy_pass http://backend:3001;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection 'upgrade';
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_cache_bypass $http_upgrade;
|
||||
}
|
||||
|
||||
location /auth {
|
||||
proxy_pass http://backend:3001;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection 'upgrade';
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_cache_bypass $http_upgrade;
|
||||
}
|
||||
}
|
||||
4531
frontend/package-lock.json
generated
Normal file
4531
frontend/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
38
frontend/package.json
Normal file
38
frontend/package.json
Normal file
@@ -0,0 +1,38 @@
|
||||
{
|
||||
"name": "timetracker-frontend",
|
||||
"private": true,
|
||||
"version": "1.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc && vite build",
|
||||
"preview": "vite preview",
|
||||
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0"
|
||||
},
|
||||
"dependencies": {
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0",
|
||||
"react-router-dom": "^6.21.0",
|
||||
"@tanstack/react-query": "^5.15.0",
|
||||
"axios": "^1.6.2",
|
||||
"date-fns": "^3.0.6",
|
||||
"clsx": "^2.0.0",
|
||||
"tailwind-merge": "^2.2.0",
|
||||
"lucide-react": "^0.304.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/react": "^18.2.43",
|
||||
"@types/react-dom": "^18.2.17",
|
||||
"@typescript-eslint/eslint-plugin": "^6.14.0",
|
||||
"@typescript-eslint/parser": "^6.14.0",
|
||||
"@vitejs/plugin-react": "^4.2.1",
|
||||
"autoprefixer": "^10.4.16",
|
||||
"eslint": "^8.55.0",
|
||||
"eslint-plugin-react-hooks": "^4.6.0",
|
||||
"eslint-plugin-react-refresh": "^0.4.5",
|
||||
"postcss": "^8.4.32",
|
||||
"tailwindcss": "^3.4.0",
|
||||
"typescript": "^5.2.2",
|
||||
"vite": "^5.0.8"
|
||||
}
|
||||
}
|
||||
6
frontend/postcss.config.js
Normal file
6
frontend/postcss.config.js
Normal file
@@ -0,0 +1,6 @@
|
||||
export default {
|
||||
plugins: {
|
||||
tailwindcss: {},
|
||||
autoprefixer: {},
|
||||
},
|
||||
}
|
||||
40
frontend/src/App.tsx
Normal file
40
frontend/src/App.tsx
Normal file
@@ -0,0 +1,40 @@
|
||||
import { Routes, Route, Navigate } from 'react-router-dom';
|
||||
import { AuthProvider } from './contexts/AuthContext';
|
||||
import { TimerProvider } from './contexts/TimerContext';
|
||||
import { Layout } from './components/Layout';
|
||||
import { ProtectedRoute } from './components/ProtectedRoute';
|
||||
import { LoginPage } from './pages/LoginPage';
|
||||
import { AuthCallbackPage } from './pages/AuthCallbackPage';
|
||||
import { DashboardPage } from './pages/DashboardPage';
|
||||
import { TimeEntriesPage } from './pages/TimeEntriesPage';
|
||||
import { ClientsPage } from './pages/ClientsPage';
|
||||
import { ProjectsPage } from './pages/ProjectsPage';
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<AuthProvider>
|
||||
<TimerProvider>
|
||||
<Routes>
|
||||
<Route path="/login" element={<LoginPage />} />
|
||||
<Route path="/auth/callback" element={<AuthCallbackPage />} />
|
||||
<Route
|
||||
path="/"
|
||||
element={
|
||||
<ProtectedRoute>
|
||||
<Layout />
|
||||
</ProtectedRoute>
|
||||
}
|
||||
>
|
||||
<Route index element={<Navigate to="/dashboard" replace />} />
|
||||
<Route path="dashboard" element={<DashboardPage />} />
|
||||
<Route path="time-entries" element={<TimeEntriesPage />} />
|
||||
<Route path="clients" element={<ClientsPage />} />
|
||||
<Route path="projects" element={<ProjectsPage />} />
|
||||
</Route>
|
||||
</Routes>
|
||||
</TimerProvider>
|
||||
</AuthProvider>
|
||||
);
|
||||
}
|
||||
|
||||
export default App;
|
||||
25
frontend/src/api/auth.ts
Normal file
25
frontend/src/api/auth.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
import axios from 'axios';
|
||||
import type { User } from '@/types';
|
||||
|
||||
const AUTH_BASE = '/auth';
|
||||
|
||||
export const authApi = {
|
||||
login: (): void => {
|
||||
window.location.href = `${AUTH_BASE}/login`;
|
||||
},
|
||||
|
||||
logout: async (): Promise<void> => {
|
||||
await axios.post(`${AUTH_BASE}/logout`, {}, { withCredentials: true });
|
||||
},
|
||||
|
||||
getCurrentUser: async (): Promise<User | null> => {
|
||||
try {
|
||||
const { data } = await axios.get<User>(`${AUTH_BASE}/me`, {
|
||||
withCredentials: true,
|
||||
});
|
||||
return data;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
},
|
||||
};
|
||||
26
frontend/src/api/client.ts
Normal file
26
frontend/src/api/client.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
import axios, { AxiosError } from 'axios';
|
||||
|
||||
const apiClient = axios.create({
|
||||
baseURL: '/api',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
withCredentials: true,
|
||||
});
|
||||
|
||||
// Response interceptor for error handling
|
||||
apiClient.interceptors.response.use(
|
||||
(response) => response,
|
||||
(error: AxiosError<{ error?: string; details?: unknown }>) => {
|
||||
if (error.response?.status === 401) {
|
||||
// Redirect to login on 401
|
||||
window.location.href = '/login';
|
||||
return Promise.reject(error);
|
||||
}
|
||||
|
||||
const message = error.response?.data?.error || error.message || 'An error occurred';
|
||||
return Promise.reject(new Error(message));
|
||||
}
|
||||
);
|
||||
|
||||
export default apiClient;
|
||||
23
frontend/src/api/clients.ts
Normal file
23
frontend/src/api/clients.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
import apiClient from './client';
|
||||
import type { Client, CreateClientInput, UpdateClientInput } from '@/types';
|
||||
|
||||
export const clientsApi = {
|
||||
getAll: async (): Promise<Client[]> => {
|
||||
const { data } = await apiClient.get<Client[]>('/clients');
|
||||
return data;
|
||||
},
|
||||
|
||||
create: async (input: CreateClientInput): Promise<Client> => {
|
||||
const { data } = await apiClient.post<Client>('/clients', input);
|
||||
return data;
|
||||
},
|
||||
|
||||
update: async (id: string, input: UpdateClientInput): Promise<Client> => {
|
||||
const { data } = await apiClient.put<Client>(`/clients/${id}`, input);
|
||||
return data;
|
||||
},
|
||||
|
||||
delete: async (id: string): Promise<void> => {
|
||||
await apiClient.delete(`/clients/${id}`);
|
||||
},
|
||||
};
|
||||
25
frontend/src/api/projects.ts
Normal file
25
frontend/src/api/projects.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
import apiClient from './client';
|
||||
import type { Project, CreateProjectInput, UpdateProjectInput } from '@/types';
|
||||
|
||||
export const projectsApi = {
|
||||
getAll: async (clientId?: string): Promise<Project[]> => {
|
||||
const { data } = await apiClient.get<Project[]>('/projects', {
|
||||
params: clientId ? { clientId } : undefined,
|
||||
});
|
||||
return data;
|
||||
},
|
||||
|
||||
create: async (input: CreateProjectInput): Promise<Project> => {
|
||||
const { data } = await apiClient.post<Project>('/projects', input);
|
||||
return data;
|
||||
},
|
||||
|
||||
update: async (id: string, input: UpdateProjectInput): Promise<Project> => {
|
||||
const { data } = await apiClient.put<Project>(`/projects/${id}`, input);
|
||||
return data;
|
||||
},
|
||||
|
||||
delete: async (id: string): Promise<void> => {
|
||||
await apiClient.delete(`/projects/${id}`);
|
||||
},
|
||||
};
|
||||
31
frontend/src/api/timeEntries.ts
Normal file
31
frontend/src/api/timeEntries.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
import apiClient from './client';
|
||||
import type {
|
||||
TimeEntry,
|
||||
PaginatedTimeEntries,
|
||||
CreateTimeEntryInput,
|
||||
UpdateTimeEntryInput,
|
||||
TimeEntryFilters,
|
||||
} from '@/types';
|
||||
|
||||
export const timeEntriesApi = {
|
||||
getAll: async (filters?: TimeEntryFilters): Promise<PaginatedTimeEntries> => {
|
||||
const { data } = await apiClient.get<PaginatedTimeEntries>('/time-entries', {
|
||||
params: filters,
|
||||
});
|
||||
return data;
|
||||
},
|
||||
|
||||
create: async (input: CreateTimeEntryInput): Promise<TimeEntry> => {
|
||||
const { data } = await apiClient.post<TimeEntry>('/time-entries', input);
|
||||
return data;
|
||||
},
|
||||
|
||||
update: async (id: string, input: UpdateTimeEntryInput): Promise<TimeEntry> => {
|
||||
const { data } = await apiClient.put<TimeEntry>(`/time-entries/${id}`, input);
|
||||
return data;
|
||||
},
|
||||
|
||||
delete: async (id: string): Promise<void> => {
|
||||
await apiClient.delete(`/time-entries/${id}`);
|
||||
},
|
||||
};
|
||||
30
frontend/src/api/timer.ts
Normal file
30
frontend/src/api/timer.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import apiClient from './client';
|
||||
import type { OngoingTimer, TimeEntry } from '@/types';
|
||||
|
||||
export const timerApi = {
|
||||
getOngoing: async (): Promise<OngoingTimer | null> => {
|
||||
const { data } = await apiClient.get<OngoingTimer | null>('/timer');
|
||||
return data;
|
||||
},
|
||||
|
||||
start: async (projectId?: string): Promise<OngoingTimer> => {
|
||||
const { data } = await apiClient.post<OngoingTimer>('/timer/start', {
|
||||
projectId,
|
||||
});
|
||||
return data;
|
||||
},
|
||||
|
||||
update: async (projectId?: string | null): Promise<OngoingTimer> => {
|
||||
const { data } = await apiClient.put<OngoingTimer>('/timer', {
|
||||
projectId,
|
||||
});
|
||||
return data;
|
||||
},
|
||||
|
||||
stop: async (projectId?: string): Promise<TimeEntry> => {
|
||||
const { data } = await apiClient.post<TimeEntry>('/timer/stop', {
|
||||
projectId,
|
||||
});
|
||||
return data;
|
||||
},
|
||||
};
|
||||
17
frontend/src/components/Layout.tsx
Normal file
17
frontend/src/components/Layout.tsx
Normal file
@@ -0,0 +1,17 @@
|
||||
import { Outlet } from 'react-router-dom';
|
||||
import { Navbar } from './Navbar';
|
||||
import { TimerWidget } from './TimerWidget';
|
||||
|
||||
export function Layout() {
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50">
|
||||
<Navbar />
|
||||
<main className="pt-4 pb-24 px-4 sm:px-6 lg:px-8">
|
||||
<div className="max-w-7xl mx-auto">
|
||||
<Outlet />
|
||||
</div>
|
||||
</main>
|
||||
<TimerWidget />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
78
frontend/src/components/Navbar.tsx
Normal file
78
frontend/src/components/Navbar.tsx
Normal file
@@ -0,0 +1,78 @@
|
||||
import { NavLink } from 'react-router-dom';
|
||||
import { Clock, List, Briefcase, FolderOpen, 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 },
|
||||
];
|
||||
|
||||
return (
|
||||
<nav className="bg-white shadow-sm border-b border-gray-200">
|
||||
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
|
||||
<div className="flex justify-between h-16">
|
||||
<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>
|
||||
</div>
|
||||
<div className="hidden sm:ml-8 sm:flex sm:space-x-4">
|
||||
{navItems.map((item) => (
|
||||
<NavLink
|
||||
key={item.to}
|
||||
to={item.to}
|
||||
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'
|
||||
}`
|
||||
}
|
||||
>
|
||||
<item.icon className="h-4 w-4 mr-2" />
|
||||
{item.label}
|
||||
</NavLink>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center space-x-4">
|
||||
<span className="text-sm text-gray-600 hidden sm:block">
|
||||
{user?.username}
|
||||
</span>
|
||||
<button
|
||||
onClick={logout}
|
||||
className="inline-flex items-center px-3 py-2 border border-transparent text-sm font-medium rounded-md text-gray-600 hover:text-gray-900 hover:bg-gray-100 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500"
|
||||
>
|
||||
<LogOut className="h-4 w-4 sm:mr-2" />
|
||||
<span className="hidden sm:inline">Logout</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/* Mobile navigation */}
|
||||
<div className="sm:hidden border-t border-gray-200">
|
||||
<div className="flex justify-around py-2">
|
||||
{navItems.map((item) => (
|
||||
<NavLink
|
||||
key={item.to}
|
||||
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'
|
||||
}`
|
||||
}
|
||||
>
|
||||
<item.icon className="h-5 w-5 mb-1" />
|
||||
{item.label}
|
||||
</NavLink>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
24
frontend/src/components/ProtectedRoute.tsx
Normal file
24
frontend/src/components/ProtectedRoute.tsx
Normal file
@@ -0,0 +1,24 @@
|
||||
import { Navigate } from 'react-router-dom';
|
||||
import { useAuth } from '@/contexts/AuthContext';
|
||||
|
||||
interface ProtectedRouteProps {
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
export function ProtectedRoute({ children }: ProtectedRouteProps) {
|
||||
const { isAuthenticated, isLoading } = useAuth();
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center">
|
||||
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary-600"></div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!isAuthenticated) {
|
||||
return <Navigate to="/login" replace />;
|
||||
}
|
||||
|
||||
return <>{children}</>;
|
||||
}
|
||||
163
frontend/src/components/TimerWidget.tsx
Normal file
163
frontend/src/components/TimerWidget.tsx
Normal file
@@ -0,0 +1,163 @@
|
||||
import { useState } from 'react';
|
||||
import { Play, Square, ChevronDown } from 'lucide-react';
|
||||
import { useTimer } from '@/contexts/TimerContext';
|
||||
import { useProjects } from '@/hooks/useProjects';
|
||||
import { formatDuration } from '@/utils/dateUtils';
|
||||
|
||||
export function TimerWidget() {
|
||||
const { ongoingTimer, isLoading, elapsedSeconds, startTimer, stopTimer, updateTimerProject } = useTimer();
|
||||
const { projects } = useProjects();
|
||||
const [showProjectSelect, setShowProjectSelect] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const handleStart = async () => {
|
||||
setError(null);
|
||||
try {
|
||||
await startTimer();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to start timer');
|
||||
}
|
||||
};
|
||||
|
||||
const handleStop = async () => {
|
||||
setError(null);
|
||||
try {
|
||||
await stopTimer();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to stop timer');
|
||||
}
|
||||
};
|
||||
|
||||
const handleProjectChange = async (projectId: string) => {
|
||||
setError(null);
|
||||
try {
|
||||
await updateTimerProject(projectId);
|
||||
setShowProjectSelect(false);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to update project');
|
||||
}
|
||||
};
|
||||
|
||||
const handleClearProject = async () => {
|
||||
setError(null);
|
||||
try {
|
||||
await updateTimerProject(null);
|
||||
setShowProjectSelect(false);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to clear project');
|
||||
}
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="fixed bottom-0 left-0 right-0 bg-white border-t border-gray-200 p-4 shadow-lg">
|
||||
<div className="max-w-7xl mx-auto flex items-center justify-center">
|
||||
<div className="animate-spin rounded-full h-6 w-6 border-b-2 border-primary-600"></div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="fixed bottom-0 left-0 right-0 bg-white border-t border-gray-200 p-4 shadow-lg z-50">
|
||||
<div className="max-w-7xl mx-auto flex items-center justify-between">
|
||||
{ongoingTimer ? (
|
||||
<>
|
||||
{/* Running Timer Display */}
|
||||
<div className="flex items-center space-x-4 flex-1">
|
||||
<div className="flex items-center space-x-2">
|
||||
<div className="w-3 h-3 bg-red-500 rounded-full animate-pulse"></div>
|
||||
<span className="text-2xl font-mono font-bold text-gray-900">
|
||||
{formatDuration(elapsedSeconds)}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Project Selector */}
|
||||
<div className="relative">
|
||||
<button
|
||||
onClick={() => setShowProjectSelect(!showProjectSelect)}
|
||||
className="flex items-center space-x-2 px-3 py-2 bg-gray-100 rounded-lg hover:bg-gray-200 transition-colors"
|
||||
>
|
||||
{ongoingTimer.project ? (
|
||||
<>
|
||||
<div
|
||||
className="w-3 h-3 rounded-full"
|
||||
style={{ backgroundColor: ongoingTimer.project.color || '#6b7280' }}
|
||||
/>
|
||||
<span className="text-sm font-medium text-gray-700">
|
||||
{ongoingTimer.project.name}
|
||||
</span>
|
||||
</>
|
||||
) : (
|
||||
<span className="text-sm font-medium text-gray-500">
|
||||
Select project...
|
||||
</span>
|
||||
)}
|
||||
<ChevronDown className="h-4 w-4 text-gray-500" />
|
||||
</button>
|
||||
|
||||
{showProjectSelect && (
|
||||
<div className="absolute bottom-full left-0 mb-2 w-64 bg-white rounded-lg shadow-lg border border-gray-200 max-h-64 overflow-y-auto">
|
||||
<button
|
||||
onClick={handleClearProject}
|
||||
className="w-full px-4 py-2 text-left text-sm text-gray-500 hover:bg-gray-50 border-b border-gray-100"
|
||||
>
|
||||
No project
|
||||
</button>
|
||||
{projects?.map((project) => (
|
||||
<button
|
||||
key={project.id}
|
||||
onClick={() => handleProjectChange(project.id)}
|
||||
className="w-full px-4 py-2 text-left text-sm hover:bg-gray-50 flex items-center space-x-2"
|
||||
>
|
||||
<div
|
||||
className="w-3 h-3 rounded-full flex-shrink-0"
|
||||
style={{ backgroundColor: project.color || '#6b7280' }}
|
||||
/>
|
||||
<div className="min-w-0">
|
||||
<div className="font-medium text-gray-900 truncate">{project.name}</div>
|
||||
<div className="text-xs text-gray-500 truncate">{project.client.name}</div>
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Stop Button */}
|
||||
<button
|
||||
onClick={handleStop}
|
||||
className="flex items-center space-x-2 px-6 py-3 bg-red-600 text-white rounded-lg font-medium hover:bg-red-700 transition-colors"
|
||||
>
|
||||
<Square className="h-5 w-5 fill-current" />
|
||||
<span>Stop</span>
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
{/* Stopped Timer Display */}
|
||||
<div className="flex items-center space-x-2">
|
||||
<span className="text-gray-500">Ready to track time</span>
|
||||
</div>
|
||||
|
||||
{/* Start Button */}
|
||||
<button
|
||||
onClick={handleStart}
|
||||
className="flex items-center space-x-2 px-6 py-3 bg-primary-600 text-white rounded-lg font-medium hover:bg-primary-700 transition-colors"
|
||||
>
|
||||
<Play className="h-5 w-5 fill-current" />
|
||||
<span>Start</span>
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="max-w-7xl mx-auto mt-2">
|
||||
<p className="text-sm text-red-600">{error}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
69
frontend/src/contexts/AuthContext.tsx
Normal file
69
frontend/src/contexts/AuthContext.tsx
Normal file
@@ -0,0 +1,69 @@
|
||||
import {
|
||||
createContext,
|
||||
useContext,
|
||||
useState,
|
||||
useEffect,
|
||||
useCallback,
|
||||
type ReactNode,
|
||||
} from 'react';
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { authApi } from '@/api/auth';
|
||||
import type { User } from '@/types';
|
||||
|
||||
interface AuthContextType {
|
||||
user: User | null;
|
||||
isLoading: boolean;
|
||||
isAuthenticated: boolean;
|
||||
login: () => void;
|
||||
logout: () => Promise<void>;
|
||||
refetchUser: () => Promise<void>;
|
||||
}
|
||||
|
||||
const AuthContext = createContext<AuthContextType | undefined>(undefined);
|
||||
|
||||
export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const { data: user, isLoading } = useQuery({
|
||||
queryKey: ['currentUser'],
|
||||
queryFn: authApi.getCurrentUser,
|
||||
staleTime: 5 * 60 * 1000, // 5 minutes
|
||||
});
|
||||
|
||||
const login = useCallback(() => {
|
||||
authApi.login();
|
||||
}, []);
|
||||
|
||||
const logout = useCallback(async () => {
|
||||
await authApi.logout();
|
||||
queryClient.setQueryData(['currentUser'], null);
|
||||
queryClient.clear();
|
||||
}, [queryClient]);
|
||||
|
||||
const refetchUser = useCallback(async () => {
|
||||
await queryClient.invalidateQueries({ queryKey: ['currentUser'] });
|
||||
}, [queryClient]);
|
||||
|
||||
return (
|
||||
<AuthContext.Provider
|
||||
value={{
|
||||
user: user ?? null,
|
||||
isLoading,
|
||||
isAuthenticated: !!user,
|
||||
login,
|
||||
logout,
|
||||
refetchUser,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useAuth() {
|
||||
const context = useContext(AuthContext);
|
||||
if (context === undefined) {
|
||||
throw new Error('useAuth must be used within an AuthProvider');
|
||||
}
|
||||
return context;
|
||||
}
|
||||
136
frontend/src/contexts/TimerContext.tsx
Normal file
136
frontend/src/contexts/TimerContext.tsx
Normal file
@@ -0,0 +1,136 @@
|
||||
import {
|
||||
createContext,
|
||||
useContext,
|
||||
useState,
|
||||
useEffect,
|
||||
useCallback,
|
||||
type ReactNode,
|
||||
} from 'react';
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { timerApi } from '@/api/timer';
|
||||
import type { OngoingTimer, TimeEntry } from '@/types';
|
||||
|
||||
interface TimerContextType {
|
||||
ongoingTimer: OngoingTimer | null;
|
||||
isLoading: boolean;
|
||||
elapsedSeconds: number;
|
||||
startTimer: (projectId?: string) => Promise<void>;
|
||||
updateTimerProject: (projectId?: string | null) => Promise<void>;
|
||||
stopTimer: (projectId?: string) => Promise<TimeEntry | null>;
|
||||
}
|
||||
|
||||
const TimerContext = createContext<TimerContextType | undefined>(undefined);
|
||||
|
||||
export function TimerProvider({ children }: { children: ReactNode }) {
|
||||
const queryClient = useQueryClient();
|
||||
const [elapsedSeconds, setElapsedSeconds] = useState(0);
|
||||
const [elapsedInterval, setElapsedInterval] = useState<NodeJS.Timeout | null>(null);
|
||||
|
||||
const { data: ongoingTimer, isLoading } = useQuery({
|
||||
queryKey: ['ongoingTimer'],
|
||||
queryFn: timerApi.getOngoing,
|
||||
refetchInterval: 60000, // Refetch every minute to sync with server
|
||||
});
|
||||
|
||||
// Calculate elapsed time
|
||||
useEffect(() => {
|
||||
if (ongoingTimer) {
|
||||
const startTime = new Date(ongoingTimer.startTime).getTime();
|
||||
const now = Date.now();
|
||||
const initialElapsed = Math.floor((now - startTime) / 1000);
|
||||
setElapsedSeconds(initialElapsed);
|
||||
|
||||
// Start interval to update elapsed time
|
||||
const interval = setInterval(() => {
|
||||
setElapsedSeconds(Math.floor((Date.now() - startTime) / 1000));
|
||||
}, 1000);
|
||||
setElapsedInterval(interval);
|
||||
} else {
|
||||
setElapsedSeconds(0);
|
||||
if (elapsedInterval) {
|
||||
clearInterval(elapsedInterval);
|
||||
setElapsedInterval(null);
|
||||
}
|
||||
}
|
||||
|
||||
return () => {
|
||||
if (elapsedInterval) {
|
||||
clearInterval(elapsedInterval);
|
||||
}
|
||||
};
|
||||
}, [ongoingTimer]);
|
||||
|
||||
// Start timer mutation
|
||||
const startMutation = useMutation({
|
||||
mutationFn: timerApi.start,
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['ongoingTimer'] });
|
||||
},
|
||||
});
|
||||
|
||||
// Update timer mutation
|
||||
const updateMutation = useMutation({
|
||||
mutationFn: timerApi.update,
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['ongoingTimer'] });
|
||||
},
|
||||
});
|
||||
|
||||
// Stop timer mutation
|
||||
const stopMutation = useMutation({
|
||||
mutationFn: timerApi.stop,
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['ongoingTimer'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['timeEntries'] });
|
||||
},
|
||||
});
|
||||
|
||||
const startTimer = useCallback(
|
||||
async (projectId?: string) => {
|
||||
await startMutation.mutateAsync(projectId);
|
||||
},
|
||||
[startMutation]
|
||||
);
|
||||
|
||||
const updateTimerProject = useCallback(
|
||||
async (projectId?: string | null) => {
|
||||
await updateMutation.mutateAsync(projectId);
|
||||
},
|
||||
[updateMutation]
|
||||
);
|
||||
|
||||
const stopTimer = useCallback(
|
||||
async (projectId?: string): Promise<TimeEntry | null> => {
|
||||
try {
|
||||
const entry = await stopMutation.mutateAsync(projectId);
|
||||
return entry;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
},
|
||||
[stopMutation]
|
||||
);
|
||||
|
||||
return (
|
||||
<TimerContext.Provider
|
||||
value={{
|
||||
ongoingTimer: ongoingTimer ?? null,
|
||||
isLoading,
|
||||
elapsedSeconds,
|
||||
startTimer,
|
||||
updateTimerProject,
|
||||
stopTimer,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</TimerContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useTimer() {
|
||||
const context = useContext(TimerContext);
|
||||
if (context === undefined) {
|
||||
throw new Error('useTimer must be used within a TimerProvider');
|
||||
}
|
||||
return context;
|
||||
}
|
||||
45
frontend/src/hooks/useClients.ts
Normal file
45
frontend/src/hooks/useClients.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { clientsApi } from '@/api/clients';
|
||||
import type { CreateClientInput, UpdateClientInput } from '@/types';
|
||||
|
||||
export function useClients() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const { data: clients, isLoading, error } = useQuery({
|
||||
queryKey: ['clients'],
|
||||
queryFn: clientsApi.getAll,
|
||||
});
|
||||
|
||||
const createClient = useMutation({
|
||||
mutationFn: (input: CreateClientInput) => clientsApi.create(input),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['clients'] });
|
||||
},
|
||||
});
|
||||
|
||||
const updateClient = useMutation({
|
||||
mutationFn: ({ id, input }: { id: string; input: UpdateClientInput }) =>
|
||||
clientsApi.update(id, input),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['clients'] });
|
||||
},
|
||||
});
|
||||
|
||||
const deleteClient = useMutation({
|
||||
mutationFn: (id: string) => clientsApi.delete(id),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['clients'] });
|
||||
// Also invalidate projects since they depend on clients
|
||||
queryClient.invalidateQueries({ queryKey: ['projects'] });
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
clients,
|
||||
isLoading,
|
||||
error,
|
||||
createClient,
|
||||
updateClient,
|
||||
deleteClient,
|
||||
};
|
||||
}
|
||||
43
frontend/src/hooks/useProjects.ts
Normal file
43
frontend/src/hooks/useProjects.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { projectsApi } from '@/api/projects';
|
||||
import type { CreateProjectInput, UpdateProjectInput } from '@/types';
|
||||
|
||||
export function useProjects(clientId?: string) {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const { data: projects, isLoading, error } = useQuery({
|
||||
queryKey: ['projects', clientId],
|
||||
queryFn: () => projectsApi.getAll(clientId),
|
||||
});
|
||||
|
||||
const createProject = useMutation({
|
||||
mutationFn: (input: CreateProjectInput) => projectsApi.create(input),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['projects'] });
|
||||
},
|
||||
});
|
||||
|
||||
const updateProject = useMutation({
|
||||
mutationFn: ({ id, input }: { id: string; input: UpdateProjectInput }) =>
|
||||
projectsApi.update(id, input),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['projects'] });
|
||||
},
|
||||
});
|
||||
|
||||
const deleteProject = useMutation({
|
||||
mutationFn: (id: string) => projectsApi.delete(id),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['projects'] });
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
projects,
|
||||
isLoading,
|
||||
error,
|
||||
createProject,
|
||||
updateProject,
|
||||
deleteProject,
|
||||
};
|
||||
}
|
||||
43
frontend/src/hooks/useTimeEntries.ts
Normal file
43
frontend/src/hooks/useTimeEntries.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { timeEntriesApi } from '@/api/timeEntries';
|
||||
import type { CreateTimeEntryInput, UpdateTimeEntryInput, TimeEntryFilters } from '@/types';
|
||||
|
||||
export function useTimeEntries(filters?: TimeEntryFilters) {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const { data, isLoading, error } = useQuery({
|
||||
queryKey: ['timeEntries', filters],
|
||||
queryFn: () => timeEntriesApi.getAll(filters),
|
||||
});
|
||||
|
||||
const createTimeEntry = useMutation({
|
||||
mutationFn: (input: CreateTimeEntryInput) => timeEntriesApi.create(input),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['timeEntries'] });
|
||||
},
|
||||
});
|
||||
|
||||
const updateTimeEntry = useMutation({
|
||||
mutationFn: ({ id, input }: { id: string; input: UpdateTimeEntryInput }) =>
|
||||
timeEntriesApi.update(id, input),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['timeEntries'] });
|
||||
},
|
||||
});
|
||||
|
||||
const deleteTimeEntry = useMutation({
|
||||
mutationFn: (id: string) => timeEntriesApi.delete(id),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['timeEntries'] });
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
data,
|
||||
isLoading,
|
||||
error,
|
||||
createTimeEntry,
|
||||
updateTimeEntry,
|
||||
deleteTimeEntry,
|
||||
};
|
||||
}
|
||||
43
frontend/src/index.css
Normal file
43
frontend/src/index.css
Normal file
@@ -0,0 +1,43 @@
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
@layer base {
|
||||
body {
|
||||
@apply bg-gray-50 text-gray-900;
|
||||
}
|
||||
}
|
||||
|
||||
@layer components {
|
||||
.btn {
|
||||
@apply inline-flex items-center justify-center px-4 py-2 rounded-lg font-medium transition-colors focus:outline-none focus:ring-2 focus:ring-offset-2;
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
@apply btn bg-primary-600 text-white hover:bg-primary-700 focus:ring-primary-500;
|
||||
}
|
||||
|
||||
.btn-secondary {
|
||||
@apply btn bg-gray-200 text-gray-800 hover:bg-gray-300 focus:ring-gray-500;
|
||||
}
|
||||
|
||||
.btn-danger {
|
||||
@apply btn bg-red-600 text-white hover:bg-red-700 focus:ring-red-500;
|
||||
}
|
||||
|
||||
.btn-outline {
|
||||
@apply btn border-2 border-gray-300 text-gray-700 hover:bg-gray-50 focus:ring-gray-500;
|
||||
}
|
||||
|
||||
.input {
|
||||
@apply w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent;
|
||||
}
|
||||
|
||||
.label {
|
||||
@apply block text-sm font-medium text-gray-700 mb-1;
|
||||
}
|
||||
|
||||
.card {
|
||||
@apply bg-white rounded-lg shadow-sm border border-gray-200 p-6;
|
||||
}
|
||||
}
|
||||
25
frontend/src/main.tsx
Normal file
25
frontend/src/main.tsx
Normal file
@@ -0,0 +1,25 @@
|
||||
import React from 'react';
|
||||
import ReactDOM from 'react-dom/client';
|
||||
import { BrowserRouter } from 'react-router-dom';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import App from './App';
|
||||
import './index.css';
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
retry: 1,
|
||||
refetchOnWindowFocus: false,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
ReactDOM.createRoot(document.getElementById('root')!).render(
|
||||
<React.StrictMode>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<BrowserRouter>
|
||||
<App />
|
||||
</BrowserRouter>
|
||||
</QueryClientProvider>
|
||||
</React.StrictMode>
|
||||
);
|
||||
39
frontend/src/pages/AuthCallbackPage.tsx
Normal file
39
frontend/src/pages/AuthCallbackPage.tsx
Normal file
@@ -0,0 +1,39 @@
|
||||
import { useEffect } from 'react';
|
||||
import { useNavigate, useSearchParams } from 'react-router-dom';
|
||||
import { useAuth } from '@/contexts/AuthContext';
|
||||
|
||||
export function AuthCallbackPage() {
|
||||
const navigate = useNavigate();
|
||||
const [searchParams] = useSearchParams();
|
||||
const { refetchUser } = useAuth();
|
||||
|
||||
useEffect(() => {
|
||||
const handleCallback = async () => {
|
||||
const success = searchParams.get('success');
|
||||
const error = searchParams.get('error');
|
||||
|
||||
if (error) {
|
||||
navigate('/login', { replace: true });
|
||||
return;
|
||||
}
|
||||
|
||||
if (success === 'true') {
|
||||
await refetchUser();
|
||||
navigate('/dashboard', { replace: true });
|
||||
} else {
|
||||
navigate('/login', { replace: true });
|
||||
}
|
||||
};
|
||||
|
||||
handleCallback();
|
||||
}, [searchParams, navigate, refetchUser]);
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-gray-50">
|
||||
<div className="text-center">
|
||||
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary-600 mx-auto"></div>
|
||||
<p className="mt-4 text-gray-600">Completing authentication...</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
212
frontend/src/pages/ClientsPage.tsx
Normal file
212
frontend/src/pages/ClientsPage.tsx
Normal file
@@ -0,0 +1,212 @@
|
||||
import { useState } from 'react';
|
||||
import { Plus, Edit2, Trash2, Building2 } from 'lucide-react';
|
||||
import { useClients } from '@/hooks/useClients';
|
||||
import type { Client, CreateClientInput, UpdateClientInput } from '@/types';
|
||||
|
||||
export function ClientsPage() {
|
||||
const { clients, isLoading, createClient, updateClient, deleteClient } = useClients();
|
||||
const [isModalOpen, setIsModalOpen] = useState(false);
|
||||
const [editingClient, setEditingClient] = useState<Client | null>(null);
|
||||
const [formData, setFormData] = useState<CreateClientInput>({ name: '', description: '' });
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const handleOpenModal = (client?: Client) => {
|
||||
if (client) {
|
||||
setEditingClient(client);
|
||||
setFormData({ name: client.name, description: client.description || '' });
|
||||
} else {
|
||||
setEditingClient(null);
|
||||
setFormData({ name: '', description: '' });
|
||||
}
|
||||
setError(null);
|
||||
setIsModalOpen(true);
|
||||
};
|
||||
|
||||
const handleCloseModal = () => {
|
||||
setIsModalOpen(false);
|
||||
setEditingClient(null);
|
||||
setFormData({ name: '', description: '' });
|
||||
setError(null);
|
||||
};
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
|
||||
if (!formData.name.trim()) {
|
||||
setError('Client name is required');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
if (editingClient) {
|
||||
await updateClient.mutateAsync({
|
||||
id: editingClient.id,
|
||||
input: formData as UpdateClientInput,
|
||||
});
|
||||
} else {
|
||||
await createClient.mutateAsync(formData);
|
||||
}
|
||||
handleCloseModal();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to save client');
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async (client: Client) => {
|
||||
if (!confirm(`Are you sure you want to delete "${client.name}"? This will also delete all associated projects and time entries.`)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await deleteClient.mutateAsync(client.id);
|
||||
} catch (err) {
|
||||
alert(err instanceof Error ? err.message : 'Failed to delete client');
|
||||
}
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center h-64">
|
||||
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary-600"></div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Page Header */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900">Clients</h1>
|
||||
<p className="mt-1 text-sm text-gray-600">
|
||||
Manage your clients and customers
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => handleOpenModal()}
|
||||
className="btn-primary"
|
||||
>
|
||||
<Plus className="h-5 w-5 mr-2" />
|
||||
Add Client
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Clients List */}
|
||||
{clients?.length === 0 ? (
|
||||
<div className="card text-center py-12">
|
||||
<Building2 className="h-12 w-12 text-gray-400 mx-auto mb-4" />
|
||||
<h3 className="text-lg font-medium text-gray-900">No clients yet</h3>
|
||||
<p className="mt-1 text-sm text-gray-600">
|
||||
Get started by adding your first client
|
||||
</p>
|
||||
<button
|
||||
onClick={() => handleOpenModal()}
|
||||
className="btn-primary mt-4"
|
||||
>
|
||||
<Plus className="h-5 w-5 mr-2" />
|
||||
Add Client
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
|
||||
{clients?.map((client) => (
|
||||
<div key={client.id} className="card">
|
||||
<div className="flex items-start justify-between">
|
||||
<div className="flex-1 min-w-0">
|
||||
<h3 className="text-lg font-medium text-gray-900 truncate">
|
||||
{client.name}
|
||||
</h3>
|
||||
{client.description && (
|
||||
<p className="mt-1 text-sm text-gray-600 line-clamp-2">
|
||||
{client.description}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex space-x-2 ml-4">
|
||||
<button
|
||||
onClick={() => handleOpenModal(client)}
|
||||
className="p-2 text-gray-400 hover:text-gray-600 rounded-lg hover:bg-gray-100"
|
||||
>
|
||||
<Edit2 className="h-4 w-4" />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleDelete(client)}
|
||||
className="p-2 text-gray-400 hover:text-red-600 rounded-lg hover:bg-red-50"
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Modal */}
|
||||
{isModalOpen && (
|
||||
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
|
||||
<div className="bg-white rounded-lg shadow-xl max-w-md w-full">
|
||||
<div className="px-6 py-4 border-b border-gray-200">
|
||||
<h2 className="text-lg font-semibold text-gray-900">
|
||||
{editingClient ? 'Edit Client' : 'Add Client'}
|
||||
</h2>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit} className="p-6 space-y-4">
|
||||
{error && (
|
||||
<div className="p-3 bg-red-50 text-red-700 rounded-lg text-sm">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div>
|
||||
<label className="label">Client Name</label>
|
||||
<input
|
||||
type="text"
|
||||
value={formData.name}
|
||||
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
|
||||
className="input"
|
||||
placeholder="Enter client name"
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="label">Description (Optional)</label>
|
||||
<textarea
|
||||
value={formData.description}
|
||||
onChange={(e) => setFormData({ ...formData, description: e.target.value })}
|
||||
className="input"
|
||||
rows={3}
|
||||
placeholder="Enter description"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end space-x-3 pt-4">
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleCloseModal}
|
||||
className="btn-secondary"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
className="btn-primary"
|
||||
disabled={createClient.isPending || updateClient.isPending}
|
||||
>
|
||||
{createClient.isPending || updateClient.isPending
|
||||
? 'Saving...'
|
||||
: editingClient
|
||||
? 'Save Changes'
|
||||
: 'Add Client'}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
161
frontend/src/pages/DashboardPage.tsx
Normal file
161
frontend/src/pages/DashboardPage.tsx
Normal file
@@ -0,0 +1,161 @@
|
||||
import { Link } from 'react-router-dom';
|
||||
import { Clock, Calendar, Briefcase, TrendingUp } from 'lucide-react';
|
||||
import { useTimeEntries } from '@/hooks/useTimeEntries';
|
||||
import { formatDate, formatDurationFromDates } from '@/utils/dateUtils';
|
||||
import { startOfDay, endOfDay, format as formatDateFns } from 'date-fns';
|
||||
|
||||
export function DashboardPage() {
|
||||
const today = new Date();
|
||||
const { data: todayEntries } = useTimeEntries({
|
||||
startDate: startOfDay(today).toISOString(),
|
||||
endDate: endOfDay(today).toISOString(),
|
||||
limit: 5,
|
||||
});
|
||||
|
||||
const { data: recentEntries } = useTimeEntries({
|
||||
limit: 10,
|
||||
});
|
||||
|
||||
const totalTodaySeconds = todayEntries?.entries.reduce((total, entry) => {
|
||||
return total + calculateDuration(entry.startTime, entry.endTime);
|
||||
}, 0) || 0;
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Page Header */}
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900">Dashboard</h1>
|
||||
<p className="mt-1 text-sm text-gray-600">
|
||||
Overview of your time tracking activity
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Stats Grid */}
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
|
||||
<StatCard
|
||||
icon={Clock}
|
||||
label="Today"
|
||||
value={formatDuration(totalTodaySeconds)}
|
||||
color="blue"
|
||||
/>
|
||||
<StatCard
|
||||
icon={Calendar}
|
||||
label="Entries Today"
|
||||
value={todayEntries?.entries.length.toString() || '0'}
|
||||
color="green"
|
||||
/>
|
||||
<StatCard
|
||||
icon={Briefcase}
|
||||
label="Active Projects"
|
||||
value={new Set(recentEntries?.entries.map(e => e.projectId)).size.toString() || '0'}
|
||||
color="purple"
|
||||
/>
|
||||
<StatCard
|
||||
icon={TrendingUp}
|
||||
label="Total Entries"
|
||||
value={recentEntries?.pagination.total.toString() || '0'}
|
||||
color="orange"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Recent Activity */}
|
||||
<div className="card">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h2 className="text-lg font-semibold text-gray-900">Recent Activity</h2>
|
||||
<Link
|
||||
to="/time-entries"
|
||||
className="text-sm text-primary-600 hover:text-primary-700"
|
||||
>
|
||||
View all →
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
{recentEntries?.entries.length === 0 ? (
|
||||
<p className="text-gray-500 text-center py-8">
|
||||
No time entries yet. Start tracking time using the timer below.
|
||||
</p>
|
||||
) : (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="min-w-full divide-y divide-gray-200">
|
||||
<thead className="bg-gray-50">
|
||||
<tr>
|
||||
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
|
||||
Project
|
||||
</th>
|
||||
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
|
||||
Date
|
||||
</th>
|
||||
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
|
||||
Duration
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="bg-white divide-y divide-gray-200">
|
||||
{recentEntries?.entries.slice(0, 5).map((entry) => (
|
||||
<tr key={entry.id}>
|
||||
<td className="px-4 py-3 whitespace-nowrap">
|
||||
<div className="flex items-center">
|
||||
<div
|
||||
className="w-3 h-3 rounded-full mr-2"
|
||||
style={{ backgroundColor: entry.project.color || '#6b7280' }}
|
||||
/>
|
||||
<div>
|
||||
<div className="text-sm font-medium text-gray-900">
|
||||
{entry.project.name}
|
||||
</div>
|
||||
<div className="text-xs text-gray-500">
|
||||
{entry.project.client.name}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-4 py-3 whitespace-nowrap text-sm text-gray-500">
|
||||
{formatDate(entry.startTime)}
|
||||
</td>
|
||||
<td className="px-4 py-3 whitespace-nowrap text-sm text-gray-900 font-mono">
|
||||
{formatDurationFromDates(entry.startTime, entry.endTime)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface StatCardProps {
|
||||
icon: React.ElementType;
|
||||
label: string;
|
||||
value: string;
|
||||
color: 'blue' | 'green' | 'purple' | 'orange';
|
||||
}
|
||||
|
||||
function StatCard({ icon: Icon, label, value, color }: StatCardProps) {
|
||||
const colors = {
|
||||
blue: 'bg-blue-50 text-blue-600',
|
||||
green: 'bg-green-50 text-green-600',
|
||||
purple: 'bg-purple-50 text-purple-600',
|
||||
orange: 'bg-orange-50 text-orange-600',
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="card p-4">
|
||||
<div className="flex items-center">
|
||||
<div className={`p-3 rounded-lg ${colors[color]}`}>
|
||||
<Icon className="h-6 w-6" />
|
||||
</div>
|
||||
<div className="ml-4">
|
||||
<p className="text-sm font-medium text-gray-600">{label}</p>
|
||||
<p className="text-2xl font-bold text-gray-900">{value}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function calculateDuration(startTime: string, endTime: string): number {
|
||||
return Math.floor((new Date(endTime).getTime() - new Date(startTime).getTime()) / 1000);
|
||||
}
|
||||
51
frontend/src/pages/LoginPage.tsx
Normal file
51
frontend/src/pages/LoginPage.tsx
Normal file
@@ -0,0 +1,51 @@
|
||||
import { Clock } from 'lucide-react';
|
||||
import { useAuth } from '@/contexts/AuthContext';
|
||||
|
||||
export function LoginPage() {
|
||||
const { login } = useAuth();
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-gray-50">
|
||||
<div className="max-w-md w-full space-y-8 p-8">
|
||||
<div className="text-center">
|
||||
<div className="mx-auto h-16 w-16 bg-primary-100 rounded-full flex items-center justify-center">
|
||||
<Clock className="h-8 w-8 text-primary-600" />
|
||||
</div>
|
||||
<h2 className="mt-6 text-3xl font-bold text-gray-900">TimeTracker</h2>
|
||||
<p className="mt-2 text-sm text-gray-600">
|
||||
Track your time efficiently across multiple projects and clients
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="mt-8">
|
||||
<button
|
||||
onClick={login}
|
||||
className="w-full flex justify-center py-3 px-4 border border-transparent rounded-lg shadow-sm text-sm font-medium text-white bg-primary-600 hover:bg-primary-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500"
|
||||
>
|
||||
Sign in with SSO
|
||||
</button>
|
||||
<p className="mt-4 text-xs text-center text-gray-500">
|
||||
Secure authentication via OpenID Connect
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="mt-8 border-t border-gray-200 pt-8">
|
||||
<div className="grid grid-cols-3 gap-4 text-center">
|
||||
<div>
|
||||
<div className="text-2xl font-bold text-gray-900">Simple</div>
|
||||
<div className="text-xs text-gray-500">Start/Stop Timer</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-2xl font-bold text-gray-900">Organized</div>
|
||||
<div className="text-xs text-gray-500">Clients & Projects</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-2xl font-bold text-gray-900">Detailed</div>
|
||||
<div className="text-xs text-gray-500">Time Reports</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
195
frontend/src/pages/ProjectsPage.tsx
Normal file
195
frontend/src/pages/ProjectsPage.tsx
Normal file
@@ -0,0 +1,195 @@
|
||||
import { useState } from 'react';
|
||||
import { Plus, Edit2, Trash2, FolderOpen } from 'lucide-react';
|
||||
import { useProjects } from '@/hooks/useProjects';
|
||||
import { useClients } from '@/hooks/useClients';
|
||||
import type { Project, CreateProjectInput, UpdateProjectInput } from '@/types';
|
||||
|
||||
const PRESET_COLORS = [
|
||||
'#ef4444', '#f97316', '#f59e0b', '#84cc16', '#22c55e',
|
||||
'#10b981', '#14b8a6', '#06b6d4', '#0ea5e9', '#3b82f6',
|
||||
'#6366f1', '#8b5cf6', '#a855f7', '#d946ef', '#ec4899',
|
||||
'#f43f5e', '#6b7280', '#374151',
|
||||
];
|
||||
|
||||
export function ProjectsPage() {
|
||||
const { projects, isLoading: projectsLoading, createProject, updateProject, deleteProject } = useProjects();
|
||||
const { clients, isLoading: clientsLoading } = useClients();
|
||||
const [isModalOpen, setIsModalOpen] = useState(false);
|
||||
const [editingProject, setEditingProject] = useState<Project | null>(null);
|
||||
const [formData, setFormData] = useState<CreateProjectInput>({
|
||||
name: '',
|
||||
description: '',
|
||||
color: '#3b82f6',
|
||||
clientId: '',
|
||||
});
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const isLoading = projectsLoading || clientsLoading;
|
||||
|
||||
const handleOpenModal = (project?: Project) => {
|
||||
if (project) {
|
||||
setEditingProject(project);
|
||||
setFormData({
|
||||
name: project.name,
|
||||
description: project.description || '',
|
||||
color: project.color || '#3b82f6',
|
||||
clientId: project.clientId,
|
||||
});
|
||||
} else {
|
||||
setEditingProject(null);
|
||||
setFormData({
|
||||
name: '',
|
||||
description: '',
|
||||
color: '#3b82f6',
|
||||
clientId: clients?.[0]?.id || '',
|
||||
});
|
||||
}
|
||||
setError(null);
|
||||
setIsModalOpen(true);
|
||||
};
|
||||
|
||||
const handleCloseModal = () => {
|
||||
setIsModalOpen(false);
|
||||
setEditingProject(null);
|
||||
setFormData({ name: '', description: '', color: '#3b82f6', clientId: '' });
|
||||
setError(null);
|
||||
};
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
|
||||
if (!formData.name.trim()) {
|
||||
setError('Project name is required');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!formData.clientId) {
|
||||
setError('Please select a client');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
if (editingProject) {
|
||||
await updateProject.mutateAsync({
|
||||
id: editingProject.id,
|
||||
input: formData as UpdateProjectInput,
|
||||
});
|
||||
} else {
|
||||
await createProject.mutateAsync(formData);
|
||||
}
|
||||
handleCloseModal();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to save project');
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async (project: Project) => {
|
||||
if (!confirm(`Are you sure you want to delete "${project.name}"?`)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await deleteProject.mutateAsync(project.id);
|
||||
} catch (err) {
|
||||
alert(err instanceof Error ? err.message : 'Failed to delete project');
|
||||
}
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center h-64">
|
||||
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary-600"></div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!clients?.length) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900">Projects</h1>
|
||||
</div>
|
||||
<div className="card text-center py-12">
|
||||
<FolderOpen className="h-12 w-12 text-gray-400 mx-auto mb-4" />
|
||||
<p className="mt-2 text-gray-600">Please create a client first.</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<h1 className="text-2xl font-bold text-gray-900">Projects</h1>
|
||||
<button onClick={() => handleOpenModal()} className="btn-primary">
|
||||
<Plus className="h-5 w-5 mr-2" />
|
||||
Add Project
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
|
||||
{projects?.map((project) => (
|
||||
<div key={project.id} className="card">
|
||||
<div className="flex items-start justify-between">
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center space-x-2">
|
||||
<div className="w-4 h-4 rounded-full" style={{ backgroundColor: project.color || '#6b7280' }} />
|
||||
<h3 className="font-medium text-gray-900 truncate">{project.name}</h3>
|
||||
</div>
|
||||
<p className="mt-1 text-sm text-gray-500">{project.client.name}</p>
|
||||
</div>
|
||||
<div className="flex space-x-1 ml-2">
|
||||
<button onClick={() => handleOpenModal(project)} className="p-1.5 text-gray-400 hover:text-gray-600 rounded">
|
||||
<Edit2 className="h-4 w-4" />
|
||||
</button>
|
||||
<button onClick={() => handleDelete(project)} className="p-1.5 text-gray-400 hover:text-red-600 rounded">
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{isModalOpen && (
|
||||
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
|
||||
<div className="bg-white rounded-lg shadow-xl max-w-md w-full p-6">
|
||||
<h2 className="text-lg font-semibold mb-4">{editingProject ? 'Edit Project' : 'Add Project'}</h2>
|
||||
{error && <div className="mb-4 p-3 bg-red-50 text-red-700 rounded-lg text-sm">{error}</div>}
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div>
|
||||
<label className="label">Project Name</label>
|
||||
<input type="text" value={formData.name} onChange={(e) => setFormData({ ...formData, name: e.target.value })} className="input" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">Client</label>
|
||||
<select value={formData.clientId} onChange={(e) => setFormData({ ...formData, clientId: e.target.value })} className="input">
|
||||
{clients?.map((client) => (
|
||||
<option key={client.id} value={client.id}>{client.name}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">Color</label>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{PRESET_COLORS.map((color) => (
|
||||
<button key={color} type="button" onClick={() => setFormData({ ...formData, color })} className={`w-8 h-8 rounded-full ${formData.color === color ? 'ring-2 ring-offset-2 ring-gray-400' : ''}`} style={{ backgroundColor: color }} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">Description</label>
|
||||
<textarea value={formData.description} onChange={(e) => setFormData({ ...formData, description: e.target.value })} className="input" rows={2} />
|
||||
</div>
|
||||
<div className="flex justify-end space-x-3 pt-2">
|
||||
<button type="button" onClick={handleCloseModal} className="btn-secondary">Cancel</button>
|
||||
<button type="submit" className="btn-primary">{editingProject ? 'Save' : 'Create'}</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
177
frontend/src/pages/TimeEntriesPage.tsx
Normal file
177
frontend/src/pages/TimeEntriesPage.tsx
Normal file
@@ -0,0 +1,177 @@
|
||||
import { useState } from 'react';
|
||||
import { Plus, Edit2, Trash2 } from 'lucide-react';
|
||||
import { useTimeEntries } from '@/hooks/useTimeEntries';
|
||||
import { useProjects } from '@/hooks/useProjects';
|
||||
import { formatDate, formatDurationFromDates, getLocalISOString, toISOTimezone } from '@/utils/dateUtils';
|
||||
import type { TimeEntry, CreateTimeEntryInput, UpdateTimeEntryInput } from '@/types';
|
||||
|
||||
export function TimeEntriesPage() {
|
||||
const { data, isLoading, createTimeEntry, updateTimeEntry, deleteTimeEntry } = useTimeEntries();
|
||||
const { projects } = useProjects();
|
||||
|
||||
const [isModalOpen, setIsModalOpen] = useState(false);
|
||||
const [editingEntry, setEditingEntry] = useState<TimeEntry | null>(null);
|
||||
const [formData, setFormData] = useState<CreateTimeEntryInput>({
|
||||
startTime: '',
|
||||
endTime: '',
|
||||
description: '',
|
||||
projectId: '',
|
||||
});
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const handleOpenModal = (entry?: TimeEntry) => {
|
||||
if (entry) {
|
||||
setEditingEntry(entry);
|
||||
setFormData({
|
||||
startTime: getLocalISOString(new Date(entry.startTime)),
|
||||
endTime: getLocalISOString(new Date(entry.endTime)),
|
||||
description: entry.description || '',
|
||||
projectId: entry.projectId,
|
||||
});
|
||||
} else {
|
||||
setEditingEntry(null);
|
||||
const now = new Date();
|
||||
const oneHourAgo = new Date(now.getTime() - 60 * 60 * 1000);
|
||||
setFormData({
|
||||
startTime: getLocalISOString(oneHourAgo),
|
||||
endTime: getLocalISOString(now),
|
||||
description: '',
|
||||
projectId: projects?.[0]?.id || '',
|
||||
});
|
||||
}
|
||||
setError(null);
|
||||
setIsModalOpen(true);
|
||||
};
|
||||
|
||||
const handleCloseModal = () => {
|
||||
setIsModalOpen(false);
|
||||
setEditingEntry(null);
|
||||
setError(null);
|
||||
};
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
|
||||
if (!formData.projectId) {
|
||||
setError('Please select a project');
|
||||
return;
|
||||
}
|
||||
|
||||
const input = {
|
||||
...formData,
|
||||
startTime: toISOTimezone(formData.startTime),
|
||||
endTime: toISOTimezone(formData.endTime),
|
||||
};
|
||||
|
||||
try {
|
||||
if (editingEntry) {
|
||||
await updateTimeEntry.mutateAsync({ id: editingEntry.id, input: input as UpdateTimeEntryInput });
|
||||
} else {
|
||||
await createTimeEntry.mutateAsync(input);
|
||||
}
|
||||
handleCloseModal();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to save');
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async (entry: TimeEntry) => {
|
||||
if (!confirm('Delete this time entry?')) return;
|
||||
try {
|
||||
await deleteTimeEntry.mutateAsync(entry.id);
|
||||
} catch (err) {
|
||||
alert(err instanceof Error ? err.message : 'Failed to delete');
|
||||
}
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return <div className="flex justify-center h-64 items-center"><div className="animate-spin h-12 w-12 border-b-2 border-primary-600 rounded-full"></div></div>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex justify-between items-center">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900">Time Entries</h1>
|
||||
<p className="text-sm text-gray-600">Manage your tracked time</p>
|
||||
</div>
|
||||
<button onClick={() => handleOpenModal()} className="btn-primary">
|
||||
<Plus className="h-5 w-5 mr-2" /> Add Entry
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="card overflow-hidden">
|
||||
<table className="min-w-full divide-y divide-gray-200">
|
||||
<thead className="bg-gray-50">
|
||||
<tr>
|
||||
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Date</th>
|
||||
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Project</th>
|
||||
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Duration</th>
|
||||
<th className="px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="bg-white divide-y divide-gray-200">
|
||||
{data?.entries.map((entry) => (
|
||||
<tr key={entry.id} className="hover:bg-gray-50">
|
||||
<td className="px-4 py-3 whitespace-nowrap text-sm text-gray-900">{formatDate(entry.startTime)}</td>
|
||||
<td className="px-4 py-3 whitespace-nowrap">
|
||||
<div className="flex items-center">
|
||||
<div className="w-3 h-3 rounded-full mr-2" style={{ backgroundColor: entry.project.color || '#6b7280' }} />
|
||||
<div>
|
||||
<div className="text-sm font-medium text-gray-900">{entry.project.name}</div>
|
||||
<div className="text-xs text-gray-500">{entry.project.client.name}</div>
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-4 py-3 whitespace-nowrap text-sm font-mono text-gray-900">{formatDurationFromDates(entry.startTime, entry.endTime)}</td>
|
||||
<td className="px-4 py-3 whitespace-nowrap text-right">
|
||||
<button onClick={() => handleOpenModal(entry)} className="p-1.5 text-gray-400 hover:text-gray-600 mr-1"><Edit2 className="h-4 w-4" /></button>
|
||||
<button onClick={() => handleDelete(entry)} className="p-1.5 text-gray-400 hover:text-red-600"><Trash2 className="h-4 w-4" /></button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
{data?.entries.length === 0 && (
|
||||
<div className="text-center py-8 text-gray-500">No time entries yet</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{isModalOpen && (
|
||||
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
|
||||
<div className="bg-white rounded-lg shadow-xl max-w-md w-full p-6">
|
||||
<h2 className="text-lg font-semibold mb-4">{editingEntry ? 'Edit Entry' : 'Add Entry'}</h2>
|
||||
{error && <div className="mb-4 p-3 bg-red-50 text-red-700 rounded-lg text-sm">{error}</div>}
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div>
|
||||
<label className="label">Project</label>
|
||||
<select value={formData.projectId} onChange={(e) => setFormData({ ...formData, projectId: e.target.value })} className="input">
|
||||
{projects?.map((p) => <option key={p.id} value={p.id}>{p.name}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label className="label">Start</label>
|
||||
<input type="datetime-local" value={formData.startTime} onChange={(e) => setFormData({ ...formData, startTime: e.target.value })} className="input" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">End</label>
|
||||
<input type="datetime-local" value={formData.endTime} onChange={(e) => setFormData({ ...formData, endTime: e.target.value })} className="input" />
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">Description</label>
|
||||
<textarea value={formData.description} onChange={(e) => setFormData({ ...formData, description: e.target.value })} className="input" rows={2} />
|
||||
</div>
|
||||
<div className="flex justify-end space-x-3 pt-2">
|
||||
<button type="button" onClick={handleCloseModal} className="btn-secondary">Cancel</button>
|
||||
<button type="submit" className="btn-primary">{editingEntry ? 'Save' : 'Create'}</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
105
frontend/src/types/index.ts
Normal file
105
frontend/src/types/index.ts
Normal file
@@ -0,0 +1,105 @@
|
||||
export interface User {
|
||||
id: string;
|
||||
username: string;
|
||||
email: string;
|
||||
}
|
||||
|
||||
export interface Client {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string | null;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface Project {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string | null;
|
||||
color: string | null;
|
||||
clientId: string;
|
||||
client: Pick<Client, 'id' | 'name'>;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface TimeEntry {
|
||||
id: string;
|
||||
startTime: string;
|
||||
endTime: string;
|
||||
description: string | null;
|
||||
projectId: string;
|
||||
project: Pick<Project, 'id' | 'name' | 'color'> & {
|
||||
client: Pick<Client, 'id' | 'name'>;
|
||||
};
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface OngoingTimer {
|
||||
id: string;
|
||||
startTime: string;
|
||||
projectId: string | null;
|
||||
project: (Pick<Project, 'id' | 'name' | 'color'> & {
|
||||
client: Pick<Client, 'id' | 'name'>;
|
||||
}) | null;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface TimeEntryFilters {
|
||||
startDate?: string;
|
||||
endDate?: string;
|
||||
projectId?: string;
|
||||
clientId?: string;
|
||||
page?: number;
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
export interface PaginatedTimeEntries {
|
||||
entries: TimeEntry[];
|
||||
pagination: {
|
||||
page: number;
|
||||
limit: number;
|
||||
total: number;
|
||||
totalPages: number;
|
||||
};
|
||||
}
|
||||
|
||||
export interface CreateClientInput {
|
||||
name: string;
|
||||
description?: string;
|
||||
}
|
||||
|
||||
export interface UpdateClientInput {
|
||||
name?: string;
|
||||
description?: string;
|
||||
}
|
||||
|
||||
export interface CreateProjectInput {
|
||||
name: string;
|
||||
description?: string;
|
||||
color?: string;
|
||||
clientId: string;
|
||||
}
|
||||
|
||||
export interface UpdateProjectInput {
|
||||
name?: string;
|
||||
description?: string;
|
||||
color?: string | null;
|
||||
clientId?: string;
|
||||
}
|
||||
|
||||
export interface CreateTimeEntryInput {
|
||||
startTime: string;
|
||||
endTime: string;
|
||||
description?: string;
|
||||
projectId: string;
|
||||
}
|
||||
|
||||
export interface UpdateTimeEntryInput {
|
||||
startTime?: string;
|
||||
endTime?: string;
|
||||
description?: string;
|
||||
projectId?: string;
|
||||
}
|
||||
54
frontend/src/utils/dateUtils.ts
Normal file
54
frontend/src/utils/dateUtils.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
import { format, parseISO, differenceInSeconds, formatDuration as dateFnsFormatDuration } from 'date-fns';
|
||||
|
||||
export function formatDate(date: string | Date): string {
|
||||
const d = typeof date === 'string' ? parseISO(date) : date;
|
||||
return format(d, 'MMM d, yyyy');
|
||||
}
|
||||
|
||||
export function formatTime(date: string | Date): string {
|
||||
const d = typeof date === 'string' ? parseISO(date) : date;
|
||||
return format(d, 'h:mm a');
|
||||
}
|
||||
|
||||
export function formatDateTime(date: string | Date): string {
|
||||
const d = typeof date === 'string' ? parseISO(date) : date;
|
||||
return format(d, 'MMM d, yyyy h:mm a');
|
||||
}
|
||||
|
||||
export function formatDuration(totalSeconds: number): string {
|
||||
const hours = Math.floor(totalSeconds / 3600);
|
||||
const minutes = Math.floor((totalSeconds % 3600) / 60);
|
||||
const seconds = totalSeconds % 60;
|
||||
|
||||
const parts = [];
|
||||
if (hours > 0) {
|
||||
parts.push(hours.toString().padStart(2, '0'));
|
||||
}
|
||||
parts.push(minutes.toString().padStart(2, '0'));
|
||||
parts.push(seconds.toString().padStart(2, '0'));
|
||||
|
||||
return parts.join(':');
|
||||
}
|
||||
|
||||
export function calculateDuration(startTime: string, endTime: string): number {
|
||||
const start = parseISO(startTime);
|
||||
const end = parseISO(endTime);
|
||||
return differenceInSeconds(end, start);
|
||||
}
|
||||
|
||||
export function formatDurationFromDates(startTime: string, endTime: string): string {
|
||||
const seconds = calculateDuration(startTime, endTime);
|
||||
return formatDuration(seconds);
|
||||
}
|
||||
|
||||
export function getLocalISOString(date: Date = new Date()): string {
|
||||
const timezoneOffset = date.getTimezoneOffset() * 60000;
|
||||
const localISOTime = new Date(date.getTime() - timezoneOffset).toISOString().slice(0, 16);
|
||||
return localISOTime;
|
||||
}
|
||||
|
||||
export function toISOTimezone(dateStr: string): string {
|
||||
// Convert a local datetime input to ISO string with timezone
|
||||
const date = new Date(dateStr);
|
||||
return date.toISOString();
|
||||
}
|
||||
26
frontend/tailwind.config.js
Normal file
26
frontend/tailwind.config.js
Normal file
@@ -0,0 +1,26 @@
|
||||
/** @type {import('tailwindcss').Config} */
|
||||
export default {
|
||||
content: [
|
||||
"./index.html",
|
||||
"./src/**/*.{js,ts,jsx,tsx}",
|
||||
],
|
||||
theme: {
|
||||
extend: {
|
||||
colors: {
|
||||
primary: {
|
||||
50: '#eff6ff',
|
||||
100: '#dbeafe',
|
||||
200: '#bfdbfe',
|
||||
300: '#93c5fd',
|
||||
400: '#60a5fa',
|
||||
500: '#3b82f6',
|
||||
600: '#2563eb',
|
||||
700: '#1d4ed8',
|
||||
800: '#1e40af',
|
||||
900: '#1e3a8a',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
plugins: [],
|
||||
}
|
||||
25
frontend/tsconfig.json
Normal file
25
frontend/tsconfig.json
Normal file
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2020",
|
||||
"useDefineForClassFields": true,
|
||||
"lib": ["ES2020", "DOM", "DOM.Iterable"],
|
||||
"module": "ESNext",
|
||||
"skipLibCheck": true,
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"@/*": ["src/*"]
|
||||
}
|
||||
},
|
||||
"include": ["src"],
|
||||
"references": [{ "path": "./tsconfig.node.json" }]
|
||||
}
|
||||
10
frontend/tsconfig.node.json
Normal file
10
frontend/tsconfig.node.json
Normal file
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"composite": true,
|
||||
"skipLibCheck": true,
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"allowSyntheticDefaultImports": true
|
||||
},
|
||||
"include": ["vite.config.ts"]
|
||||
}
|
||||
25
frontend/vite.config.ts
Normal file
25
frontend/vite.config.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
import { defineConfig } from 'vite';
|
||||
import react from '@vitejs/plugin-react';
|
||||
import path from 'path';
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': path.resolve(__dirname, './src'),
|
||||
},
|
||||
},
|
||||
server: {
|
||||
port: 5173,
|
||||
proxy: {
|
||||
'/api': {
|
||||
target: 'http://localhost:3001',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/auth': {
|
||||
target: 'http://localhost:3001',
|
||||
changeOrigin: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
Reference in New Issue
Block a user