Compare commits
6 Commits
feature/mc
...
a91a8e9dfa
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a91a8e9dfa | ||
|
|
fb94745588 | ||
|
|
8eddbed00b | ||
|
|
e83d247cf9 | ||
|
|
88866f73e6 | ||
| ca521000bf |
251
.agents/skills/feature-planning/SKILL.md
Normal file
251
.agents/skills/feature-planning/SKILL.md
Normal file
@@ -0,0 +1,251 @@
|
||||
# Feature Planning Skill
|
||||
|
||||
This skill provides a structured workflow for implementing new features in the TimeTracker project. Use this skill when the user requests a new feature or significant functionality change.
|
||||
|
||||
## Workflow Overview
|
||||
|
||||
```
|
||||
1. Requirements Discovery (iterative)
|
||||
└── Clarify edge cases, acceptance criteria, constraints
|
||||
|
||||
2. Feature Plan Creation
|
||||
└── docs/features/{feature-name}.md
|
||||
|
||||
3. Implementation
|
||||
└── Use plan as single source of truth
|
||||
```
|
||||
|
||||
## Phase 1: Requirements Discovery
|
||||
|
||||
**Goal:** Understand exactly what needs to be built before writing any code.
|
||||
|
||||
### Questions to Ask
|
||||
|
||||
Ask targeted questions to clarify:
|
||||
|
||||
#### Core Functionality
|
||||
- What is the primary purpose of this feature?
|
||||
- What user problem does it solve?
|
||||
- How should users interact with this feature?
|
||||
|
||||
#### Data & API
|
||||
- What new data needs to be stored?
|
||||
- What existing data structures are affected?
|
||||
- What API endpoints are needed (if any)?
|
||||
|
||||
#### User Interface
|
||||
- Where in the UI should this feature appear?
|
||||
- What views or components are needed?
|
||||
- What user interactions are required?
|
||||
|
||||
#### Edge Cases
|
||||
- What happens when inputs are invalid?
|
||||
- How should errors be handled?
|
||||
- What are the boundary conditions?
|
||||
- Are there any race conditions to consider?
|
||||
|
||||
#### Constraints
|
||||
- Are there performance requirements?
|
||||
- Any security considerations?
|
||||
- Browser/device compatibility?
|
||||
- Integration with existing features?
|
||||
|
||||
### Iteration Process
|
||||
|
||||
1. **Initial Questions** — Ask 3-5 focused questions based on the feature description
|
||||
2. **Wait for Answers** — Let the programmer respond
|
||||
3. **Follow-up Questions** — Dig deeper based on responses
|
||||
4. **Confirm Understanding** — Summarize your understanding and ask for confirmation
|
||||
5. **Iterate** — Repeat until requirements are clear
|
||||
|
||||
### Example Question Flow
|
||||
|
||||
```
|
||||
User: "Add the ability to export time entries to CSV"
|
||||
|
||||
Agent: "Before I start planning, I have a few questions:
|
||||
|
||||
1. Should the export include all entries or only filtered entries (if filters are active)?
|
||||
2. What columns should be included in the CSV? (date, duration, project, client, description?)
|
||||
3. Should the CSV include break minutes and net duration, or just total time?
|
||||
4. Is there a date range limit, or can users export all historical data?
|
||||
5. Should the export be triggered from the Time Entries page, or from a separate Export page?"
|
||||
```
|
||||
|
||||
## Phase 2: Feature Plan
|
||||
|
||||
**Goal:** Create a comprehensive plan document before implementation.
|
||||
|
||||
### Plan Location
|
||||
|
||||
Create the plan at: `docs/features/{feature-name}.md`
|
||||
|
||||
Use kebab-case for the filename (e.g., `csv-export.md`, `dark-mode.md`).
|
||||
|
||||
### Plan Template
|
||||
|
||||
```markdown
|
||||
# Feature: {Feature Name}
|
||||
|
||||
## Overview
|
||||
|
||||
Brief description of what this feature does and why it's needed.
|
||||
|
||||
## Requirements
|
||||
|
||||
### Functional Requirements
|
||||
- Requirement 1
|
||||
- Requirement 2
|
||||
- Requirement 3
|
||||
|
||||
### Non-Functional Requirements
|
||||
- Performance: ...
|
||||
- Security: ...
|
||||
- Usability: ...
|
||||
|
||||
### Constraints
|
||||
- Constraint 1
|
||||
- Constraint 2
|
||||
|
||||
## Technical Approach
|
||||
|
||||
### Architecture Decisions
|
||||
- Decision 1 and rationale
|
||||
- Decision 2 and rationale
|
||||
|
||||
### Database Changes
|
||||
- New tables/columns
|
||||
- Migrations needed
|
||||
- Data migration strategy (if any)
|
||||
|
||||
### API Changes
|
||||
- New endpoints
|
||||
- Modified endpoints
|
||||
- Request/response formats
|
||||
|
||||
### Frontend Changes
|
||||
- New components
|
||||
- Modified components
|
||||
- State management approach
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
1. **Step 1: Backend - Database**
|
||||
- Create migration
|
||||
- Update Prisma schema
|
||||
- Regenerate client
|
||||
|
||||
2. **Step 2: Backend - Service**
|
||||
- Add service methods
|
||||
- Add validation schemas
|
||||
|
||||
3. **Step 3: Backend - Routes**
|
||||
- Create route handlers
|
||||
- Add middleware
|
||||
|
||||
4. **Step 4: Frontend - API Client**
|
||||
- Add API functions
|
||||
|
||||
5. **Step 5: Frontend - Components**
|
||||
- Create/update components
|
||||
- Add to routes if needed
|
||||
|
||||
6. **Step 6: Testing**
|
||||
- Manual testing steps
|
||||
- Edge case verification
|
||||
|
||||
## File Changes
|
||||
|
||||
### New Files
|
||||
- `backend/src/services/export.service.ts`
|
||||
- `frontend/src/hooks/useExport.ts`
|
||||
|
||||
### Modified Files
|
||||
- `backend/src/routes/timeEntry.routes.ts` — Add export endpoint
|
||||
- `frontend/src/pages/TimeEntriesPage.tsx` — Add export button
|
||||
- `frontend/src/api/timeEntries.ts` — Add export function
|
||||
|
||||
### Database
|
||||
- No changes required (or specify migration)
|
||||
|
||||
## Edge Cases
|
||||
|
||||
| Case | Handling |
|
||||
|------|----------|
|
||||
| No entries match filter | Show empty state, export empty CSV with headers |
|
||||
| Very large export (>10k entries) | Stream response, show progress indicator |
|
||||
| User cancels export mid-stream | Gracefully close connection |
|
||||
| Invalid date range | Return 400 error with clear message |
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
### Manual Testing
|
||||
1. Navigate to Time Entries page
|
||||
2. Apply date filter
|
||||
3. Click Export button
|
||||
4. Verify CSV downloads with correct data
|
||||
5. Open CSV and verify format
|
||||
|
||||
### Edge Case Testing
|
||||
1. Export with no entries
|
||||
2. Export with 1000+ entries
|
||||
3. Export with special characters in descriptions
|
||||
4. Export while timer is running
|
||||
|
||||
## Open Questions
|
||||
|
||||
- [ ] Question 1 (to be resolved during implementation)
|
||||
- [ ] Question 2
|
||||
```
|
||||
|
||||
### Plan Review
|
||||
|
||||
After creating the plan:
|
||||
|
||||
1. Present the plan to the programmer
|
||||
2. Ask for feedback and approval
|
||||
3. Make requested changes
|
||||
4. Get final approval before proceeding to implementation
|
||||
|
||||
## Phase 3: Implementation
|
||||
|
||||
**Goal:** Implement the feature exactly as planned.
|
||||
|
||||
### Rules
|
||||
|
||||
1. **Read the plan first** — Start by reading the full plan file
|
||||
2. **Follow the plan** — Implement step by step as outlined
|
||||
3. **Update if needed** — If implementation differs from plan, update the plan file
|
||||
4. **Document changes** — After completion, update relevant documentation
|
||||
|
||||
### Implementation Checklist
|
||||
|
||||
- [ ] Read `docs/features/{feature-name}.md`
|
||||
- [ ] Implement database changes (if any)
|
||||
- [ ] Implement backend service logic
|
||||
- [ ] Implement backend routes
|
||||
- [ ] Implement frontend API client
|
||||
- [ ] Implement frontend components
|
||||
- [ ] Run linting: `npm run lint`
|
||||
- [ ] Manual testing
|
||||
- [ ] Update plan if implementation differs
|
||||
- [ ] Update `project.md` if requirements changed
|
||||
- [ ] Update `README.md` if API changed
|
||||
- [ ] Update `AGENTS.md` if patterns changed
|
||||
|
||||
## Quick Reference
|
||||
|
||||
### Commands
|
||||
- Frontend lint: `npm run lint` (in `frontend/`)
|
||||
- Backend build: `npm run build` (in `backend/`)
|
||||
- DB migration: `npm run db:migrate` (in `backend/`)
|
||||
- DB generate: `npm run db:generate` (in `backend/`)
|
||||
|
||||
### File Locations
|
||||
- Backend routes: `backend/src/routes/`
|
||||
- Backend services: `backend/src/services/`
|
||||
- Backend schemas: `backend/src/schemas/`
|
||||
- Frontend pages: `frontend/src/pages/`
|
||||
- Frontend hooks: `frontend/src/hooks/`
|
||||
- Frontend API: `frontend/src/api/`
|
||||
- Feature plans: `docs/features/`
|
||||
92
AGENTS.md
92
AGENTS.md
@@ -1,6 +1,6 @@
|
||||
# AGENTS.md — Codebase Guide for AI Coding Agents
|
||||
|
||||
This document describes the structure, conventions, and commands for the `vibe_coding_timetracker` monorepo. Read it in full before making changes.
|
||||
This document describes the structure, conventions, and commands for the `vibe_coding_timetracker` monorepo. **Read it in full before making changes.**
|
||||
|
||||
## Repository Structure
|
||||
|
||||
@@ -18,17 +18,103 @@ This document describes the structure, conventions, and commands for the `vibe_c
|
||||
├── backend/ # Express REST API (TypeScript + Prisma + PostgreSQL)
|
||||
│ └── src/
|
||||
│ ├── auth/ # OIDC + JWT logic
|
||||
│ ├── config/ # Configuration constants
|
||||
│ ├── errors/ # AppError subclasses
|
||||
│ ├── middleware/# Express middlewares
|
||||
│ ├── prisma/ # Prisma client singleton
|
||||
│ ├── routes/ # Express routers (xxx.routes.ts)
|
||||
│ ├── schemas/ # Zod validation schemas
|
||||
│ └── services/ # Business logic classes (xxx.service.ts)
|
||||
│ ├── services/ # Business logic classes (xxx.service.ts)
|
||||
│ ├── types/ # TypeScript interfaces
|
||||
│ └── utils/ # Utility functions
|
||||
├── ios/ # Native iOS app (Swift/Xcode)
|
||||
├── timetracker-chart/ # Helm chart for Kubernetes deployment
|
||||
├── helm/ # Helm chart for Kubernetes deployment
|
||||
└── docker-compose.yml
|
||||
```
|
||||
|
||||
## AI Agent Workflow
|
||||
|
||||
### Before Making Changes
|
||||
1. Read this file completely
|
||||
2. Read `project.md` for feature requirements
|
||||
3. Read `README.md` for setup instructions
|
||||
4. Understand the specific task or feature request
|
||||
|
||||
### During Development
|
||||
1. Follow all code conventions in this document
|
||||
2. Write clean, maintainable code
|
||||
3. Add inline comments only when necessary for clarity
|
||||
4. Run linting before completing: `npm run lint`
|
||||
|
||||
### After Making Changes
|
||||
**Always update documentation.** See [Documentation Maintenance](#documentation-maintenance).
|
||||
|
||||
## Feature Development Workflow
|
||||
|
||||
**For new features, AI agents MUST follow this process before writing any code.**
|
||||
|
||||
### Phase 1: Requirements Discovery
|
||||
1. Ask clarifying questions about the feature request
|
||||
2. Identify edge cases, constraints, and acceptance criteria
|
||||
3. Confirm understanding with the programmer
|
||||
4. Iterate until requirements are clear
|
||||
|
||||
### Phase 2: Feature Plan
|
||||
1. Create `docs/features/{feature-name}.md` with the feature plan
|
||||
2. Include: overview, requirements, technical approach, file changes, edge cases, testing
|
||||
3. Present plan for review
|
||||
4. Iterate until approved by the programmer
|
||||
|
||||
### Phase 3: Implementation
|
||||
1. Use the approved plan as the single source of truth
|
||||
2. Implement step by step following the plan
|
||||
3. Update the plan if implementation differs
|
||||
4. Update documentation after completion
|
||||
|
||||
**See the `feature-planning` skill for detailed workflow and templates.**
|
||||
|
||||
## Documentation Maintenance
|
||||
|
||||
**Every code change requires a documentation review.** When you modify the codebase, check whether documentation needs updating.
|
||||
|
||||
### Documentation Files and Their Purposes
|
||||
|
||||
| File | Purpose | Update When |
|
||||
|------|---------|-------------|
|
||||
| `AGENTS.md` | Code conventions, commands, architecture patterns | Changing conventions, adding new patterns, modifying architecture |
|
||||
| `README.md` | Setup instructions, API reference, features list | Adding endpoints, changing environment variables, adding features |
|
||||
| `project.md` | Requirements, data model, functional specifications | Modifying business logic, adding entities, changing validation rules |
|
||||
|
||||
### Update Rules
|
||||
|
||||
#### Update `AGENTS.md` When:
|
||||
- Adding a new coding pattern or convention
|
||||
- Changing the project structure (new directories, reorganization)
|
||||
- Adding or modifying build/lint/test commands
|
||||
- Introducing a new architectural pattern
|
||||
- Changing state management or error handling approaches
|
||||
|
||||
#### Update `README.md` When:
|
||||
- Adding, removing, or modifying API endpoints
|
||||
- Changing environment variables or configuration
|
||||
- Adding new features visible to users
|
||||
- Modifying setup or installation steps
|
||||
- Changing the technology stack
|
||||
|
||||
#### Update `project.md` When:
|
||||
- Adding or modifying business requirements
|
||||
- Changing the data model or relationships
|
||||
- Adding new validation rules
|
||||
- Modifying functional specifications
|
||||
- Updating security or non-functional requirements
|
||||
|
||||
### Documentation Format Rules
|
||||
- Use Markdown formatting
|
||||
- Keep entries concise and actionable
|
||||
- Match the existing tone and style
|
||||
- Use code blocks for commands and code examples
|
||||
- Maintain alphabetical or logical ordering in lists
|
||||
|
||||
## Build, Lint, and Dev Commands
|
||||
|
||||
### Frontend (`frontend/`)
|
||||
|
||||
39
DOCS.md
Normal file
39
DOCS.md
Normal file
@@ -0,0 +1,39 @@
|
||||
# Documentation Guide
|
||||
|
||||
## Documentation Files
|
||||
|
||||
| File | Purpose | When to Update |
|
||||
|------|---------|----------------|
|
||||
| `AGENTS.md` | Code conventions, commands, architecture, AI agent workflow | Adding patterns, changing conventions, modifying structure, updating agent workflow |
|
||||
| `README.md` | Setup instructions, API reference, features list | New endpoints, config changes, new features, technology stack changes |
|
||||
| `project.md` | Requirements, data model, functional specifications | Business logic changes, new entities, validation rules, UI requirements |
|
||||
| `DOCS.md` | Documentation standards and index | Documentation process changes, new documentation files |
|
||||
| `docs/features/*.md` | Feature implementation plans | Created during feature development, updated if implementation differs |
|
||||
|
||||
## AI Agent Skills
|
||||
|
||||
| Skill | Purpose | When to Use |
|
||||
|-------|---------|-------------|
|
||||
| `feature-planning` | Structured workflow for new features | When implementing new features or significant functionality changes |
|
||||
|
||||
## Documentation Standards
|
||||
|
||||
- Use Markdown formatting
|
||||
- Keep entries concise and actionable
|
||||
- Use code blocks for commands and examples
|
||||
- Match existing tone and style
|
||||
- Maintain logical ordering in lists
|
||||
|
||||
## Maintenance Rules
|
||||
|
||||
### AI Agents Must Update Documentation When:
|
||||
1. Adding new code patterns or conventions
|
||||
2. Modifying API endpoints or configuration
|
||||
3. Changing business logic or data models
|
||||
4. Adding new features or entities
|
||||
|
||||
### Review Checklist
|
||||
- [ ] Documentation reflects code changes
|
||||
- [ ] Examples are accurate and tested
|
||||
- [ ] Formatting is consistent
|
||||
- [ ] No outdated information remains
|
||||
25
README.md
25
README.md
@@ -10,6 +10,10 @@ A multi-user web application for tracking time spent working on projects. Users
|
||||
- **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
|
||||
- **Statistics** - View aggregated time tracking data by project and client
|
||||
- **Client Targets** - Set hourly targets per client with weekly/monthly periods
|
||||
- **API Keys** - Generate API keys for external tools and AI agents
|
||||
- **MCP Integration** - Model Context Protocol endpoint for AI agent access
|
||||
- **Responsive UI** - Works on desktop and mobile
|
||||
|
||||
## Architecture
|
||||
@@ -125,6 +129,27 @@ APP_URL="http://localhost:5173"
|
||||
- `POST /api/timer/start` - Start timer
|
||||
- `PUT /api/timer` - Update timer (set project)
|
||||
- `POST /api/timer/stop` - Stop timer (creates entry)
|
||||
- `POST /api/timer/cancel` - Cancel timer without saving
|
||||
|
||||
### Client Targets
|
||||
|
||||
- `GET /api/client-targets` - List targets with balance
|
||||
- `POST /api/client-targets` - Create target
|
||||
- `PUT /api/client-targets/:id` - Update target
|
||||
- `DELETE /api/client-targets/:id` - Delete target
|
||||
- `POST /api/client-targets/:id/corrections` - Add correction
|
||||
- `DELETE /api/client-targets/:id/corrections/:correctionId` - Delete correction
|
||||
|
||||
### API Keys
|
||||
|
||||
- `GET /api/api-keys` - List API keys
|
||||
- `POST /api/api-keys` - Create API key
|
||||
- `DELETE /api/api-keys/:id` - Revoke API key
|
||||
|
||||
### MCP (Model Context Protocol)
|
||||
|
||||
- `GET /mcp` - SSE stream for server-initiated messages
|
||||
- `POST /mcp` - JSON-RPC requests (tool invocations)
|
||||
|
||||
## Data Model
|
||||
|
||||
|
||||
@@ -1,285 +0,0 @@
|
||||
# Client Targets v2 — Feature Requirements
|
||||
|
||||
## Overview
|
||||
|
||||
This document defines the requirements for the second iteration of the Client Targets feature. The main additions are:
|
||||
|
||||
- Targets can be set on a **weekly or monthly** period.
|
||||
- Each target defines a **fixed weekly working-day pattern** (e.g. Mon + Wed).
|
||||
- The balance for the **current period** is calculated proportionally based on elapsed working days, so the user can see at any point in time whether they are ahead or behind.
|
||||
- The **start date** can be any calendar day (no longer restricted to Mondays).
|
||||
- Manual **balance corrections** are preserved and continue to work as before.
|
||||
|
||||
---
|
||||
|
||||
## 1. Target Configuration
|
||||
|
||||
| Field | Type | Constraints |
|
||||
|---|---|---|
|
||||
| `periodType` | `WEEKLY \| MONTHLY` | Required |
|
||||
| `weeklyOrMonthlyHours` | positive float, ≤ 168 | Required; represents hours per week or per month |
|
||||
| `workingDays` | array of day names | At least one of `MON TUE WED THU FRI SAT SUN`; fixed repeating pattern |
|
||||
| `startDate` | `YYYY-MM-DD` | Any calendar day; no longer restricted to Mondays |
|
||||
| `clientId` | UUID | Must belong to the authenticated user |
|
||||
|
||||
**One active target per client** — the unique `(userId, clientId)` constraint is preserved. To change period type, hours, or working days the user creates a new target with a new `startDate`; the old target is soft-deleted. History from the old target is retained as-is and is no longer recalculated.
|
||||
|
||||
---
|
||||
|
||||
## 2. Period Definitions
|
||||
|
||||
| `periodType` | Period start | Period end |
|
||||
|---|---|---|
|
||||
| `WEEKLY` | Monday 00:00 of the calendar week | Sunday 23:59 of that same calendar week |
|
||||
| `MONTHLY` | 1st of the calendar month 00:00 | Last day of the calendar month 23:59 |
|
||||
|
||||
---
|
||||
|
||||
## 3. Balance Calculation — Overview
|
||||
|
||||
The total balance is the **sum of individual period balances** from the period containing `startDate` up to and including the **current period** (the period that contains today).
|
||||
|
||||
Each period is classified as either **completed** or **ongoing**.
|
||||
|
||||
```
|
||||
total_balance_seconds = SUM( balance_seconds ) over all periods
|
||||
```
|
||||
|
||||
Positive = overtime. Negative = undertime.
|
||||
|
||||
---
|
||||
|
||||
## 4. Completed Period Balance
|
||||
|
||||
A period is **completed** when its end date is strictly before today.
|
||||
|
||||
```
|
||||
balance = tracked_hours + correction_hours - period_target_hours
|
||||
```
|
||||
|
||||
- `period_target_hours` — see §5 (pro-ration) for the first period; full `weeklyOrMonthlyHours` for all subsequent periods.
|
||||
- `tracked_hours` — sum of all time entries for this client whose date falls within `[period_start, period_end]`.
|
||||
- `correction_hours` — sum of manual corrections whose `date` falls within `[period_start, period_end]`.
|
||||
|
||||
No working-day logic is applied to completed periods. The target is simply the (optionally pro-rated) hours for that period.
|
||||
|
||||
---
|
||||
|
||||
## 5. First Period Pro-ration
|
||||
|
||||
If `startDate` does not fall on the natural first day of a period (Monday for weekly, 1st for monthly), the target hours for that first period are pro-rated by calendar days.
|
||||
|
||||
### Monthly
|
||||
|
||||
```
|
||||
full_period_days = total calendar days in that month
|
||||
remaining_days = (last day of month) − startDate + 1 // inclusive
|
||||
period_target_hours = (remaining_days / full_period_days) × weeklyOrMonthlyHours
|
||||
```
|
||||
|
||||
**Example:** startDate = Jan 25, target = 40 h/month, January has 31 days.
|
||||
`remaining_days = 7`, `period_target_hours = (7 / 31) × 40 = 9.032 h`
|
||||
|
||||
### Weekly
|
||||
|
||||
```
|
||||
full_period_days = 7
|
||||
remaining_days = Sunday of that calendar week − startDate + 1 // inclusive
|
||||
period_target_hours = (remaining_days / 7) × weeklyOrMonthlyHours
|
||||
```
|
||||
|
||||
**Example:** startDate = Wednesday, target = 40 h/week.
|
||||
`remaining_days = 5 (Wed–Sun)`, `period_target_hours = (5 / 7) × 40 = 28.571 h`
|
||||
|
||||
All periods after the first use the full `weeklyOrMonthlyHours`.
|
||||
|
||||
---
|
||||
|
||||
## 6. Ongoing Period Balance (Current Period)
|
||||
|
||||
The current period is **ongoing** when today falls within it. The balance reflects how the user is doing *so far* — future working days within the current period are not considered.
|
||||
|
||||
### Step 1 — Period target hours
|
||||
|
||||
Apply §5 if this is the first period; otherwise use full `weeklyOrMonthlyHours`.
|
||||
|
||||
### Step 2 — Daily rate
|
||||
|
||||
```
|
||||
working_days_in_period = COUNT of days in [period_start, period_end]
|
||||
that match the working day pattern
|
||||
daily_rate_hours = period_target_hours / working_days_in_period
|
||||
```
|
||||
|
||||
The rate is fixed at the start of the period and does not change as time passes.
|
||||
|
||||
### Step 3 — Elapsed working days
|
||||
|
||||
```
|
||||
elapsed_working_days = COUNT of days in [period_start, TODAY] (both inclusive)
|
||||
that match the working day pattern
|
||||
```
|
||||
|
||||
- If today matches the working day pattern, it is counted as a **full** elapsed working day.
|
||||
- If today does not match the working day pattern, it is not counted.
|
||||
|
||||
### Step 4 — Expected hours so far
|
||||
|
||||
```
|
||||
expected_hours = elapsed_working_days × daily_rate_hours
|
||||
```
|
||||
|
||||
### Step 5 — Balance
|
||||
|
||||
```
|
||||
tracked_hours = SUM of time entries for this client in [period_start, today]
|
||||
correction_hours = SUM of manual corrections whose date ∈ [period_start, today]
|
||||
balance = tracked_hours + correction_hours − expected_hours
|
||||
```
|
||||
|
||||
### Worked example
|
||||
|
||||
> Target: 40 h/month. Working days: Mon + Wed.
|
||||
> Current month has 4 Mondays and 4 Wednesdays → `working_days_in_period = 8`.
|
||||
> `daily_rate_hours = 40 / 8 = 5 h`.
|
||||
> 3 working days have elapsed → `expected_hours = 15 h`.
|
||||
> Tracked so far: 13 h, no corrections.
|
||||
> `balance = 13 − 15 = −2 h` (2 hours behind).
|
||||
|
||||
---
|
||||
|
||||
## 7. Manual Balance Corrections
|
||||
|
||||
| Field | Type | Constraints |
|
||||
|---|---|---|
|
||||
| `date` | `YYYY-MM-DD` | Must be ≥ `startDate`; not more than one period in the future |
|
||||
| `hours` | signed float | Positive = extra credit (reduces deficit). Negative = reduces tracked credit |
|
||||
| `description` | string | Optional, max 255 chars |
|
||||
|
||||
- The system automatically assigns a correction to the period that contains its `date`.
|
||||
- Corrections in **completed periods** are included in the completed period formula (§4).
|
||||
- Corrections in the **ongoing period** are included in the ongoing balance formula (§6).
|
||||
- Corrections in a **future period** (not yet started) are stored and will be applied when that period becomes active.
|
||||
- A correction whose `date` is before `startDate` is rejected with a validation error.
|
||||
|
||||
---
|
||||
|
||||
## 8. Edge Cases
|
||||
|
||||
| Scenario | Behaviour |
|
||||
|---|---|
|
||||
| `startDate` = 1st of month / Monday | No pro-ration; `period_target_hours = weeklyOrMonthlyHours` |
|
||||
| `startDate` = last day of period | `remaining_days = 1`; target is heavily reduced (e.g. 1/31 × hours) |
|
||||
| Working pattern has no matches in the partial first period | `elapsed_working_days = 0`; `expected_hours = 0`; balance = `tracked + corrections` |
|
||||
| Current period has zero elapsed working days | `expected_hours = 0`; balance = `tracked + corrections` (cannot divide by zero — guard required) |
|
||||
| `working_days_in_period = 0` | Impossible by validation (at least one day required), but system must guard: treat as `daily_rate_hours = 0` |
|
||||
| Today is not a working day | `elapsed_working_days` does not include today |
|
||||
| Correction date before `startDate` | Rejected with a validation error |
|
||||
| Correction date in future period | Accepted and stored; applied when that period is ongoing or completed |
|
||||
| User changes working days or period type | Must create a new target with a new `startDate`; old target history is frozen |
|
||||
| Two periods with the same client exist (old soft-deleted, new active) | Only the active target's periods contribute to the displayed balance |
|
||||
| A month with only partial working day coverage (e.g. all Mondays are public holidays) | No automatic holiday handling; user adds manual corrections to compensate |
|
||||
|
||||
---
|
||||
|
||||
## 9. Data Model Changes
|
||||
|
||||
### `ClientTarget` table — additions / changes
|
||||
|
||||
| Column | Change | Notes |
|
||||
|---|---|---|
|
||||
| `period_type` | **Add** | Enum: `WEEKLY`, `MONTHLY` |
|
||||
| `working_days` | **Add** | Array/bitmask of day names: `MON TUE WED THU FRI SAT SUN` |
|
||||
| `start_date` | **Modify** | Remove "must be Monday" validation constraint |
|
||||
| `weekly_hours` | **Rename** | → `target_hours` (represents hours per week or per month depending on `period_type`) |
|
||||
|
||||
### `BalanceCorrection` table — no structural changes
|
||||
|
||||
Date-to-period assignment is computed at query time, not stored.
|
||||
|
||||
---
|
||||
|
||||
## 10. API Changes
|
||||
|
||||
### `ClientTargetWithBalance` response shape
|
||||
|
||||
```typescript
|
||||
interface ClientTargetWithBalance {
|
||||
id: string
|
||||
clientId: string
|
||||
clientName: string
|
||||
userId: string
|
||||
periodType: "weekly" | "monthly"
|
||||
targetHours: number // renamed from weeklyHours
|
||||
workingDays: string[] // e.g. ["MON", "WED"]
|
||||
startDate: string // YYYY-MM-DD
|
||||
createdAt: string
|
||||
updatedAt: string
|
||||
corrections: BalanceCorrection[]
|
||||
totalBalanceSeconds: number // running total across all periods
|
||||
currentPeriodTrackedSeconds: number // replaces currentWeekTrackedSeconds
|
||||
currentPeriodTargetSeconds: number // replaces currentWeekTargetSeconds
|
||||
periods: PeriodBalance[] // replaces weeks[]
|
||||
}
|
||||
|
||||
interface PeriodBalance {
|
||||
periodStart: string // YYYY-MM-DD (Monday or 1st of month)
|
||||
periodEnd: string // YYYY-MM-DD (Sunday or last of month)
|
||||
targetHours: number // pro-rated for first period
|
||||
trackedSeconds: number
|
||||
correctionHours: number
|
||||
balanceSeconds: number
|
||||
isOngoing: boolean
|
||||
// only present when isOngoing = true
|
||||
dailyRateHours?: number
|
||||
workingDaysInPeriod?: number
|
||||
elapsedWorkingDays?: number
|
||||
expectedHours?: number
|
||||
}
|
||||
```
|
||||
|
||||
### Endpoint changes
|
||||
|
||||
| Method | Path | Change |
|
||||
|---|---|---|
|
||||
| `POST /client-targets` | Create | Accepts `periodType`, `workingDays`, `targetHours`; `startDate` unconstrained |
|
||||
| `PUT /client-targets/:id` | Update | Accepts same new fields |
|
||||
| `GET /client-targets` | List | Returns updated `ClientTargetWithBalance` shape |
|
||||
| `POST /client-targets/:id/corrections` | Add correction | No change to signature |
|
||||
| `DELETE /client-targets/:id/corrections/:corrId` | Delete correction | No change |
|
||||
|
||||
### Zod schema changes
|
||||
|
||||
- `CreateClientTargetSchema` / `UpdateClientTargetSchema`:
|
||||
- Add `periodType: z.enum(["weekly", "monthly"])`
|
||||
- Add `workingDays: z.array(z.enum(["MON","TUE","WED","THU","FRI","SAT","SUN"])).min(1)`
|
||||
- Rename `weeklyHours` → `targetHours`
|
||||
- Remove Monday-only regex constraint from `startDate`
|
||||
|
||||
---
|
||||
|
||||
## 11. Frontend Changes
|
||||
|
||||
### Types (`frontend/src/types/index.ts`)
|
||||
- `ClientTargetWithBalance` — add `periodType`, `workingDays`, `targetHours`; replace `weeks` → `periods: PeriodBalance[]`; replace `currentWeek*` → `currentPeriod*`
|
||||
- Add `PeriodBalance` interface
|
||||
- `CreateClientTargetInput` / `UpdateClientTargetInput` — same field additions
|
||||
|
||||
### Hook (`frontend/src/hooks/useClientTargets.ts`)
|
||||
- No structural changes; mutations pass through new fields
|
||||
|
||||
### API client (`frontend/src/api/clientTargets.ts`)
|
||||
- No structural changes; payload shapes updated
|
||||
|
||||
### `ClientsPage` — `ClientTargetPanel`
|
||||
- Working day selector (checkboxes: Mon–Sun, at least one required)
|
||||
- Period type selector (Weekly / Monthly)
|
||||
- Label for hours input updates dynamically: "Hours/week" or "Hours/month"
|
||||
- Start date picker: free date input (no week-picker)
|
||||
- Balance display: label changes from "this week" to "this week" or "this month" based on `periodType`
|
||||
- Expanded period list replaces the expanded week list
|
||||
|
||||
### `DashboardPage`
|
||||
- "Weekly Targets" widget renamed to "Targets"
|
||||
- "This week" label becomes "This week" / "This month" dynamically
|
||||
- `currentWeek*` fields replaced with `currentPeriod*`
|
||||
0
docs/features/.gitkeep
Normal file
0
docs/features/.gitkeep
Normal file
131
docs/features/timer-breaks.md
Normal file
131
docs/features/timer-breaks.md
Normal file
@@ -0,0 +1,131 @@
|
||||
# Feature: Timer Breaks (Pause During Work)
|
||||
|
||||
## Overview
|
||||
Allow users to take breaks while a timer is running. When on break, elapsed time is frozen and break time is tracked. When resumed, break time accumulates and is subtracted from the displayed work time.
|
||||
|
||||
## User Experience
|
||||
|
||||
### Timer States
|
||||
1. **Running** — normal state, elapsed time ticking
|
||||
2. **On Break** — elapsed time frozen, break time ticking, Stop/Cancel buttons disabled
|
||||
3. **Stopped** — no timer active
|
||||
|
||||
### UI Changes (TimerWidget)
|
||||
- Add a **"Break"** button (amber, `Pause` icon) next to Stop when timer is running
|
||||
- When on break:
|
||||
- Change pulsing dot color from red to amber
|
||||
- Elapsed time frozen at net work time
|
||||
- Show break time below: `Break: Xm XXs` (live-ticking)
|
||||
- Replace "Break" button with **"Resume"** button (green, `Play` icon)
|
||||
- **Disable** Stop and Cancel buttons (tooltip: "Resume before stopping")
|
||||
|
||||
### Duration Calculations
|
||||
- **Work time (displayed):** `now - startTime - totalBreakSeconds`
|
||||
- Where `totalBreakSeconds = (breakMinutes * 60) + (now - breakStart if on break)`
|
||||
- When on break: frozen at `(breakStart - startTime - breakMinutes * 60)`
|
||||
- **Break time (displayed):** `breakMinutes * 60 + (now - breakStart if on break)`
|
||||
|
||||
## Implementation
|
||||
|
||||
### 1. Database Schema (`backend/prisma/schema.prisma`)
|
||||
Add two fields to `OngoingTimer`:
|
||||
```prisma
|
||||
model OngoingTimer {
|
||||
// ... existing fields ...
|
||||
breakMinutes Int @default(0) @map("break_minutes")
|
||||
breakStart DateTime? @map("break_start") @db.Timestamptz()
|
||||
}
|
||||
```
|
||||
Run: `npx prisma migrate dev --name add_timer_break_fields`
|
||||
|
||||
### 2. Backend Service (`backend/src/services/timer.service.ts`)
|
||||
|
||||
**New method `startBreak(userId)`:**
|
||||
- Get ongoing timer, throw `NotFoundError` if none
|
||||
- Check `timer.breakStart` is null (not already on break), throw `BadRequestError` if on break
|
||||
- Update: `breakStart = new Date()`
|
||||
- Return updated timer
|
||||
|
||||
**New method `endBreak(userId)`:**
|
||||
- Get ongoing timer, throw `NotFoundError` if none
|
||||
- Check `timer.breakStart` is not null, throw `BadRequestError` if not on break
|
||||
- Calculate additional break minutes: `Math.floor((now - breakStart) / 60000)`
|
||||
- Update: `breakMinutes += additionalMinutes`, `breakStart = null`
|
||||
- Return updated timer
|
||||
|
||||
**Modify `stop(userId)`:**
|
||||
- Before creating time entry, check `timer.breakStart` is null — throw `BadRequestError("Cannot stop timer while on break")` if break is active
|
||||
- When creating `TimeEntry`, set `breakMinutes: timer.breakMinutes`
|
||||
|
||||
**Modify `cancel(userId)`:**
|
||||
- Check `timer.breakStart` is null — throw `BadRequestError("Cannot cancel timer while on break")` if break is active
|
||||
|
||||
### 3. Backend Routes (`backend/src/routes/timer.routes.ts`)
|
||||
Add two new routes (both require auth, no body validation):
|
||||
```
|
||||
POST /api/timer/break → timerService.startBreak(userId)
|
||||
POST /api/timer/resume → timerService.endBreak(userId)
|
||||
```
|
||||
|
||||
### 4. MCP Tools (`backend/src/routes/mcp.routes.ts`)
|
||||
Add two MCP tools: `pause_timer` and `resume_timer`.
|
||||
|
||||
### 5. Frontend Types (`frontend/src/types/index.ts`)
|
||||
Update `OngoingTimer` interface:
|
||||
```typescript
|
||||
export interface OngoingTimer {
|
||||
// ... existing fields ...
|
||||
breakMinutes: number;
|
||||
breakStart: string | null;
|
||||
}
|
||||
```
|
||||
|
||||
### 6. Frontend API (`frontend/src/api/timer.ts`)
|
||||
Add two methods:
|
||||
```typescript
|
||||
startBreak: async (): Promise<OngoingTimer> => { ... }
|
||||
endBreak: async (): Promise<OngoingTimer> => { ... }
|
||||
```
|
||||
|
||||
### 7. Frontend TimerContext (`frontend/src/contexts/TimerContext.tsx`)
|
||||
- Add `breakSeconds` state (live-updating, similar to `elapsedSeconds`)
|
||||
- Expose `isOnBreak` derived boolean (`ongoingTimer?.breakStart !== null`)
|
||||
- Update elapsed time calculation:
|
||||
- Running: `(now - startTime) - (breakMinutes * 60) - (now - breakStart if on break)`
|
||||
- On break: `(breakStart - startTime) - (breakMinutes * 60)` (frozen)
|
||||
- Break seconds: `(breakMinutes * 60) + (now - breakStart if on break)`
|
||||
- Add `startBreak()` and `endBreak()` callbacks
|
||||
- Expose `breakSeconds` and `isOnBreak` in context value
|
||||
|
||||
### 8. Frontend TimerWidget (`frontend/src/components/TimerWidget.tsx`)
|
||||
- Import `Pause` icon from lucide-react
|
||||
- Add Break/Resume button between project selector and Stop button
|
||||
- Show break time display when `breakSeconds > 0` or `isOnBreak`
|
||||
- Change dot color to amber when on break
|
||||
- Disable Stop/Cancel when on break with tooltip
|
||||
|
||||
## Files to Modify (in order)
|
||||
|
||||
| # | File | Change |
|
||||
|---|------|--------|
|
||||
| 1 | `backend/prisma/schema.prisma` | Add `breakMinutes`, `breakStart` to `OngoingTimer` |
|
||||
| 2 | `backend/src/services/timer.service.ts` | Add `startBreak()`, `endBreak()`, modify `stop()` and `cancel()` |
|
||||
| 3 | `backend/src/routes/timer.routes.ts` | Add `/break` and `/resume` routes |
|
||||
| 4 | `backend/src/routes/mcp.routes.ts` | Add `pause_timer` and `resume_timer` MCP tools |
|
||||
| 5 | `frontend/src/types/index.ts` | Add `breakMinutes`, `breakStart` to `OngoingTimer` |
|
||||
| 6 | `frontend/src/api/timer.ts` | Add `startBreak()`, `endBreak()` API methods |
|
||||
| 7 | `frontend/src/contexts/TimerContext.tsx` | Add break state, `breakSeconds`, `isOnBreak`, break methods |
|
||||
| 8 | `frontend/src/components/TimerWidget.tsx` | Add break UI (button, display, disabled states) |
|
||||
|
||||
## Edge Cases
|
||||
- Break start must be after timer start (always true since break is clicked after start)
|
||||
- Break duration naturally cannot exceed work duration (breakStart > startTime)
|
||||
- On stop: reject if break is active (user must resume first)
|
||||
- On cancel: reject if break is active (user must resume first)
|
||||
- Break minutes accumulate across multiple break/resume cycles
|
||||
- Timer refetch (every 60s) will sync break state from server
|
||||
|
||||
## Verification
|
||||
- Run `npm run lint` in both `frontend/` and `backend/`
|
||||
- Run `npm run build` in both `frontend/` and `backend/`
|
||||
- Manual testing: start timer → break → verify elapsed frozen, break ticking → resume → verify break added to total → stop → verify time entry has correct breakMinutes
|
||||
98
project.md
98
project.md
@@ -40,16 +40,22 @@ A multi-user web application for tracking time spent working on projects. Users
|
||||
| **Project** | A project belonging to a client | User, belongs to one Client |
|
||||
| **TimeEntry** | A completed time tracking record | User (explicit), belongs to one Project |
|
||||
| **OngoingTimer** | An active timer while tracking is in progress | User (explicit), belongs to one Project (optional) |
|
||||
| **ClientTarget** | Hourly target for a client per period | User, belongs to one Client |
|
||||
| **BalanceCorrection** | Manual hour adjustment for a target | Belongs to one ClientTarget |
|
||||
| **ApiKey** | API key for external tool access | User |
|
||||
|
||||
### Relationships
|
||||
|
||||
```
|
||||
User
|
||||
├── Client (one-to-many)
|
||||
│ └── Project (one-to-many)
|
||||
│ └── TimeEntry (one-to-many, explicit user reference)
|
||||
│ ├── Project (one-to-many)
|
||||
│ │ └── TimeEntry (one-to-many, explicit user reference)
|
||||
│ └── ClientTarget (one-to-one per client)
|
||||
│ └── BalanceCorrection (one-to-many)
|
||||
│
|
||||
└── OngoingTimer (zero-or-one, explicit user reference)
|
||||
├── OngoingTimer (zero-or-one, explicit user reference)
|
||||
└── ApiKey (one-to-many)
|
||||
```
|
||||
|
||||
**Important**: Both `TimeEntry` and `OngoingTimer` have explicit references to the user who created them. This is distinct from the project's ownership and is required for future extensibility (see Future Extensibility section).
|
||||
@@ -127,10 +133,72 @@ User
|
||||
- Start time
|
||||
- End time
|
||||
- Project
|
||||
- Optional fields:
|
||||
- Break minutes (deducted from total duration)
|
||||
- Description (notes about the work)
|
||||
- The entry is validated against overlap rules before saving
|
||||
|
||||
---
|
||||
|
||||
### 6. Statistics
|
||||
|
||||
- User can view aggregated time tracking statistics
|
||||
- Filters available:
|
||||
- Date range (start/end)
|
||||
- Client
|
||||
- Project
|
||||
- Statistics display:
|
||||
- Total working time
|
||||
- Entry count
|
||||
- Breakdown by project (with color indicators)
|
||||
- Breakdown by client
|
||||
|
||||
---
|
||||
|
||||
### 7. Client Targets
|
||||
|
||||
- User can set hourly targets per client
|
||||
- Target configuration:
|
||||
- Target hours per period
|
||||
- Period type (weekly or monthly)
|
||||
- Working days (e.g., MON-FRI)
|
||||
- Start date
|
||||
- Balance tracking:
|
||||
- Shows current balance vs target
|
||||
- Supports manual corrections (e.g., holidays, overtime carry-over)
|
||||
- Only one target per client allowed
|
||||
|
||||
---
|
||||
|
||||
### 8. API Keys
|
||||
|
||||
- User can generate API keys for external tool access
|
||||
- API key properties:
|
||||
- Name (for identification)
|
||||
- Prefix (first characters shown for identification)
|
||||
- Last used timestamp
|
||||
- Security:
|
||||
- Raw key shown only once at creation
|
||||
- Key is hashed (SHA-256) before storage
|
||||
- Keys can be revoked (deleted)
|
||||
|
||||
---
|
||||
|
||||
### 9. MCP Integration
|
||||
|
||||
- Model Context Protocol endpoint for AI agent access
|
||||
- Stateless operation (no session persistence)
|
||||
- Tools exposed:
|
||||
- Client CRUD operations
|
||||
- Project CRUD operations
|
||||
- Time entry CRUD operations
|
||||
- Timer start/stop/cancel
|
||||
- Client target management
|
||||
- Statistics queries
|
||||
- Authentication via API keys
|
||||
|
||||
---
|
||||
|
||||
## API Endpoints (Suggested)
|
||||
|
||||
### Authentication
|
||||
@@ -165,8 +233,29 @@ User
|
||||
- `POST /api/timer/start` — Start timer (creates OngoingTimer)
|
||||
- `PUT /api/timer` — Update ongoing timer (e.g., set project)
|
||||
- `POST /api/timer/stop` — Stop timer (converts to TimeEntry)
|
||||
- `POST /api/timer/cancel` — Cancel timer without saving
|
||||
- `GET /api/timer` — Get current ongoing timer (if any)
|
||||
|
||||
### Client Targets
|
||||
|
||||
- `GET /api/client-targets` — List targets with computed balance
|
||||
- `POST /api/client-targets` — Create a target
|
||||
- `PUT /api/client-targets/{id}` — Update a target
|
||||
- `DELETE /api/client-targets/{id}` — Delete a target
|
||||
- `POST /api/client-targets/{id}/corrections` — Add a correction
|
||||
- `DELETE /api/client-targets/{id}/corrections/{correctionId}` — Delete a correction
|
||||
|
||||
### API Keys
|
||||
|
||||
- `GET /api/api-keys` — List user's API keys
|
||||
- `POST /api/api-keys` — Create a new API key
|
||||
- `DELETE /api/api-keys/{id}` — Revoke an API key
|
||||
|
||||
### MCP (Model Context Protocol)
|
||||
|
||||
- `GET /mcp` — SSE stream for server-initiated messages
|
||||
- `POST /mcp` — JSON-RPC requests (tool invocations)
|
||||
|
||||
---
|
||||
|
||||
## UI Requirements
|
||||
@@ -183,6 +272,9 @@ User
|
||||
- **Dashboard**: Overview with active timer widget and recent entries
|
||||
- **Time Entries**: List/calendar view of all entries with filters (date range, client, project)
|
||||
- **Clients & Projects**: Management interface for clients and projects
|
||||
- **Statistics**: Aggregated time data with filters and breakdowns
|
||||
- **API Keys**: Create and manage API keys for external access
|
||||
- **Client Targets**: Set and monitor hourly targets per client
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
set -euo pipefail
|
||||
|
||||
REGISTRY="git.simon-franken.de"
|
||||
CHART_DIR="timetracker-chart"
|
||||
CHART_DIR="helm"
|
||||
|
||||
# Load .env file if present (values do not override existing env variables)
|
||||
if [[ -f ".env" ]]; then
|
||||
|
||||
Reference in New Issue
Block a user