Compare commits
6 Commits
bd0ac0d95b
...
dev
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1c4cdf042c | ||
|
|
2ee75f719b | ||
|
|
c6ed57342c | ||
|
|
5d5cec048f | ||
| 01e594b941 | |||
|
|
3fc90063b4 |
4
.gitignore
vendored
4
.gitignore
vendored
@@ -41,3 +41,7 @@ Thumbs.db
|
||||
|
||||
# Docker
|
||||
docker-compose.override.yml
|
||||
|
||||
#dev stuff
|
||||
/.claude/
|
||||
/.vscode/
|
||||
160
ARCHIVE_FEATURE_README.md
Normal file
160
ARCHIVE_FEATURE_README.md
Normal file
@@ -0,0 +1,160 @@
|
||||
# Project Archive Feature
|
||||
|
||||
## Overview
|
||||
|
||||
The Break It Down (BIT) application now supports archiving projects! This helps you organize your workspace by hiding completed or inactive projects from the main view while keeping them accessible.
|
||||
|
||||
## Features Added
|
||||
|
||||
### 1. **Archive Status**
|
||||
- Projects can be marked as archived or active
|
||||
- Archived projects are kept in the database but hidden from the default view
|
||||
- All tasks and data are preserved when archiving
|
||||
|
||||
### 2. **Tab Navigation**
|
||||
The main Projects page now has three tabs:
|
||||
- **Active** (default) - Shows only non-archived projects
|
||||
- **Archived** - Shows only archived projects
|
||||
- **All** - Shows all projects regardless of archive status
|
||||
|
||||
### 3. **Quick Actions**
|
||||
Each project card now has two action buttons:
|
||||
- **Archive/Unarchive** (📦/↩️) - Toggle archive status
|
||||
- **Delete** (🗑️) - Permanently delete the project
|
||||
|
||||
### 4. **Visual Indicators**
|
||||
- Archived projects appear with reduced opacity and gray border
|
||||
- "(archived)" label appears next to archived project names
|
||||
- Context-aware empty state messages
|
||||
|
||||
## Database Changes
|
||||
|
||||
A new column has been added to the `projects` table:
|
||||
- `is_archived` (BOOLEAN) - Defaults to `False` for new projects
|
||||
|
||||
## Installation & Migration
|
||||
|
||||
### For New Installations
|
||||
No action needed! The database will be created with the correct schema automatically.
|
||||
|
||||
### For Existing Databases
|
||||
|
||||
If you have an existing Break It Down database, run the migration script:
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
python3 migrate_add_is_archived.py
|
||||
```
|
||||
|
||||
This will add the `is_archived` column to your existing projects table and set all existing projects to `is_archived=False`.
|
||||
|
||||
### Restart the Backend
|
||||
|
||||
After migration, restart the backend server to load the updated models:
|
||||
|
||||
```bash
|
||||
# Stop the current backend process
|
||||
pkill -f "uvicorn.*backend.main:app"
|
||||
|
||||
# Start the backend again
|
||||
cd /path/to/break-it-down
|
||||
uvicorn backend.main:app --host 0.0.0.0 --port 8001
|
||||
```
|
||||
|
||||
Or if using Docker:
|
||||
```bash
|
||||
docker-compose restart backend
|
||||
```
|
||||
|
||||
## API Changes
|
||||
|
||||
### Updated Endpoint: GET /api/projects
|
||||
|
||||
New optional query parameter:
|
||||
- `archived` (boolean, optional) - Filter projects by archive status
|
||||
- `archived=false` - Returns only active projects
|
||||
- `archived=true` - Returns only archived projects
|
||||
- No parameter - Returns all projects
|
||||
|
||||
Examples:
|
||||
```bash
|
||||
# Get active projects
|
||||
GET /api/projects?archived=false
|
||||
|
||||
# Get archived projects
|
||||
GET /api/projects?archived=true
|
||||
|
||||
# Get all projects
|
||||
GET /api/projects
|
||||
```
|
||||
|
||||
### Updated Endpoint: PUT /api/projects/{id}
|
||||
|
||||
New field in request body:
|
||||
```json
|
||||
{
|
||||
"name": "Project Name", // optional
|
||||
"description": "Description", // optional
|
||||
"statuses": [...], // optional
|
||||
"is_archived": true // optional - new!
|
||||
}
|
||||
```
|
||||
|
||||
### New API Helper Functions
|
||||
|
||||
The frontend API client now includes:
|
||||
- `archiveProject(id)` - Archive a project
|
||||
- `unarchiveProject(id)` - Unarchive a project
|
||||
|
||||
## File Changes Summary
|
||||
|
||||
### Backend
|
||||
- `backend/app/models.py` - Added `is_archived` Boolean column to Project model
|
||||
- `backend/app/schemas.py` - Updated ProjectUpdate and Project schemas
|
||||
- `backend/app/main.py` - Added `archived` query parameter to list_projects endpoint
|
||||
- `backend/app/crud.py` - Updated get_projects to support archive filtering
|
||||
- `backend/migrate_add_is_archived.py` - Migration script (new file)
|
||||
|
||||
### Frontend
|
||||
- `frontend/src/pages/ProjectList.jsx` - Added tabs, archive buttons, and filtering logic
|
||||
- `frontend/src/utils/api.js` - Added archive/unarchive functions and updated getProjects
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### Archive a Project
|
||||
1. Go to the Projects page
|
||||
2. Click the archive icon (📦) on any project card
|
||||
3. The project disappears from the Active view
|
||||
4. Switch to the "Archived" tab to see it
|
||||
|
||||
### Unarchive a Project
|
||||
1. Switch to the "Archived" tab
|
||||
2. Click the unarchive icon (↩️) on the project card
|
||||
3. The project returns to the Active view
|
||||
|
||||
### View All Projects
|
||||
Click the "All" tab to see both active and archived projects together.
|
||||
|
||||
## Status vs Archive
|
||||
|
||||
**Important distinction:**
|
||||
- **Task Status** (backlog, in_progress, on_hold, done) - Applied to individual tasks within a project
|
||||
- **Project Archive** - Applied to entire projects to organize your workspace
|
||||
|
||||
The existing task status "on_hold" is still useful for pausing work on specific tasks, while archiving is for entire projects you want to hide from your main view.
|
||||
|
||||
## Backward Compatibility
|
||||
|
||||
All changes are backward compatible:
|
||||
- Existing projects will default to `is_archived=false` (active)
|
||||
- Old API calls without the `archived` parameter still work (returns all projects)
|
||||
- The frontend gracefully handles projects with or without the archive field
|
||||
|
||||
## Future Enhancements
|
||||
|
||||
Potential additions:
|
||||
- Archive date tracking
|
||||
- Bulk archive operations
|
||||
- Archive projects from the ProjectSettings modal
|
||||
- Auto-archive projects after X days of inactivity
|
||||
- Project status badges (active, archived, on-hold, completed)
|
||||
10
CHANGELOG.md
10
CHANGELOG.md
@@ -1,11 +1,11 @@
|
||||
# Changelog
|
||||
|
||||
All notable changes to TESSERACT will be documented in this file.
|
||||
All notable changes to Break It Down (BIT) will be documented in this file.
|
||||
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
||||
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## [0.1.6] - 2025-01-25
|
||||
## [0.1.6] - 2025-11-25
|
||||
|
||||
### Added
|
||||
- **Dynamic Status Management System**
|
||||
@@ -69,7 +69,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
- Helper functions for status formatting and color coding
|
||||
- Prop drilling of projectStatuses through component hierarchy
|
||||
|
||||
## [0.1.5] - 2025-01-XX
|
||||
## [0.1.5] - 2025-11-22
|
||||
|
||||
### Added
|
||||
- **Nested Kanban View** - Major feature implementation
|
||||
@@ -238,9 +238,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
## Project Information
|
||||
|
||||
**TESSERACT** - Task Decomposition Engine
|
||||
**Break It Down (BIT)** - Task Decomposition Engine
|
||||
A self-hosted web application for managing deeply nested todo trees with advanced time tracking and project planning capabilities.
|
||||
|
||||
**Repository**: https://github.com/serversdwn/tesseract
|
||||
**Repository**: https://github.com/serversdwn/break-it-down
|
||||
**License**: MIT
|
||||
**Author**: serversdwn
|
||||
|
||||
25
README.md
25
README.md
@@ -1,4 +1,4 @@
|
||||
# TESSERACT
|
||||
# Break It Down - BIT
|
||||
|
||||
**Task Decomposition Engine** - A self-hosted web application for managing deeply nested todo trees with advanced time tracking and project planning capabilities.
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
|
||||
## Overview
|
||||
|
||||
TESSERACT is designed for complex project management where tasks naturally decompose into hierarchical structures. Whether you're breaking down software projects, research tasks, or multi-phase initiatives, TESSERACT helps you visualize, track, and manage work at any level of granularity.
|
||||
Break It Down is designed for complex project management where tasks naturally decompose into hierarchical structures. Whether you're breaking down software projects, research tasks, or multi-phase initiatives, BIT helps you visualize, track, and manage work at any level of granularity.
|
||||
|
||||
### Key Features
|
||||
|
||||
@@ -33,7 +33,6 @@ TESSERACT is designed for complex project management where tasks naturally decom
|
||||
- **LLM Integration**: Import JSON task trees generated by AI assistants
|
||||
- **Real-Time Search**: Find tasks across projects with filtering
|
||||
- **Self-Hosted**: Full data ownership and privacy
|
||||
- **Dark Cyberpunk UI**: Orange-accented dark theme optimized for focus
|
||||
|
||||
## Tech Stack
|
||||
|
||||
@@ -55,8 +54,8 @@ TESSERACT is designed for complex project management where tasks naturally decom
|
||||
|
||||
1. **Clone the repository**
|
||||
```bash
|
||||
git clone https://github.com/serversdwn/tesseract.git
|
||||
cd tesseract
|
||||
git clone https://github.com/serversdwn/break-it-down.git
|
||||
cd break-it-down
|
||||
```
|
||||
|
||||
2. **Start the application**
|
||||
@@ -166,7 +165,7 @@ The Kanban board displays tasks in a nested hierarchy while maintaining status-b
|
||||
|
||||
### Understanding Time Estimates
|
||||
|
||||
TESSERACT uses **leaf-based time calculation** for accurate project planning:
|
||||
Break It Down uses **leaf-based time calculation** for accurate project planning:
|
||||
|
||||
- **Leaf Tasks** (no subtasks): Display shows their own time estimate
|
||||
- **Parent Tasks** (have subtasks): Display shows sum of ALL descendant leaf tasks
|
||||
@@ -202,7 +201,7 @@ Remaining work: 3h 30m (not 10h!)
|
||||
|
||||
### JSON Import
|
||||
|
||||
TESSERACT can import task hierarchies from JSON files, making it perfect for LLM-generated project breakdowns.
|
||||
Break It Down can import task hierarchies from JSON files, making it perfect for LLM-generated project breakdowns.
|
||||
|
||||
1. Click "Import JSON" on a project
|
||||
2. Upload a file matching this structure:
|
||||
@@ -307,7 +306,7 @@ tasks
|
||||
### Project Structure
|
||||
|
||||
```
|
||||
tesseract/
|
||||
break-it-down/
|
||||
├─ backend/
|
||||
│ ├─ app/
|
||||
│ │ ├─ main.py # FastAPI application
|
||||
@@ -370,10 +369,10 @@ Frontend will be available at `http://localhost:5173` (Vite default)
|
||||
**Backup:**
|
||||
```bash
|
||||
# Docker
|
||||
docker cp tesseract-backend:/app/tesseract.db ./backup.db
|
||||
docker cp bit-backend:/app/bit.db ./backup.db
|
||||
|
||||
# Local
|
||||
cp backend/tesseract.db ./backup.db
|
||||
cp backend/bit.db ./backup.db
|
||||
```
|
||||
|
||||
**Schema Changes:**
|
||||
@@ -456,8 +455,8 @@ MIT License - see LICENSE file for details
|
||||
|
||||
## Support
|
||||
|
||||
- **Issues**: https://github.com/serversdwn/tesseract/issues
|
||||
- **Discussions**: https://github.com/serversdwn/tesseract/discussions
|
||||
- **Issues**: https://github.com/serversdwn/break-it-down/issues
|
||||
- **Discussions**: https://github.com/serversdwn/break-it-down/discussions
|
||||
|
||||
## Acknowledgments
|
||||
|
||||
@@ -467,4 +466,4 @@ MIT License - see LICENSE file for details
|
||||
|
||||
---
|
||||
|
||||
**TESSERACT** - Decompose complexity, achieve clarity.
|
||||
**Break It Down (BIT)** - Decompose complexity, achieve clarity.
|
||||
|
||||
244
SYSTEMSPEC_v0.2.0.md
Normal file
244
SYSTEMSPEC_v0.2.0.md
Normal file
@@ -0,0 +1,244 @@
|
||||
# Break It Down (BIT)
|
||||
|
||||
# SYSTEM SPECIFICATION
|
||||
|
||||
## Version: v0.2.0
|
||||
|
||||
## Feature Theme: Campaign Mode + Entropy Engine + Project Wizard
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
# 1. Overview
|
||||
|
||||
v0.2.0 introduces **Campaign Mode**, an operations layer on top of
|
||||
Break-It-Down's planning engine.
|
||||
|
||||
BIT remains the HQ planning system (tree + kanban). Campaign Mode is the
|
||||
execution layer focused on:
|
||||
|
||||
- Low-friction session starts
|
||||
- Visual progress (photo proof)
|
||||
- Entropy-based decay for recurring physical spaces
|
||||
- Gentle nudges to trigger action
|
||||
- A fast project-building Wizard
|
||||
|
||||
The goal is to reduce startup friction and help users act without
|
||||
overthinking.
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
# 2. Core Architectural Principles
|
||||
|
||||
1. Existing planning functionality must remain unchanged for standard
|
||||
projects.
|
||||
2. Campaign functionality activates only when
|
||||
`project_mode == "entropy_space"`.
|
||||
3. Planning (HQ) and Execution (Campaign) are separate UI routes.
|
||||
4. Session start must require no pre-forms.
|
||||
5. Entropy simulation must feel like physics, not guilt.
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
# 3. New Core Concepts
|
||||
|
||||
## 3.1 Project Modes
|
||||
|
||||
Add enum to projects:
|
||||
|
||||
- `standard` (default, existing behavior)
|
||||
- `entropy_space` (physical space / territory model)
|
||||
|
||||
Future modes may include: - `pipeline_chores` - `deep_work`
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
## 3.2 Campaign Types
|
||||
|
||||
Only meaningful when `project_mode == "entropy_space"`:
|
||||
|
||||
- `finite` --- one-off liberation (garage purge)
|
||||
- `background` --- ongoing maintenance (bathroom, kitchen)
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
## 3.3 Zones (v1 Implementation)
|
||||
|
||||
In `entropy_space` projects:
|
||||
|
||||
- Top-level tasks (`parent_task_id IS NULL`)
|
||||
- `is_zone = true`
|
||||
|
||||
No separate zones table in v0.2.0.
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
## 3.4 Work Sessions
|
||||
|
||||
Generic sessions stored in backend. Campaign UI refers to them as
|
||||
"Strikes".
|
||||
|
||||
Session kinds:
|
||||
|
||||
- `strike`
|
||||
- `pomodoro` (future)
|
||||
- `run` (future)
|
||||
- `freeform`
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
# 4. Database Schema Changes
|
||||
|
||||
## 4.1 Projects Table Additions
|
||||
|
||||
project_mode TEXT NOT NULL DEFAULT 'standard'
|
||||
campaign_type TEXT NULL
|
||||
campaign_active BOOLEAN NOT NULL DEFAULT 0
|
||||
|
||||
nudge_enabled BOOLEAN NOT NULL DEFAULT 0
|
||||
nudge_window_start TEXT NULL
|
||||
nudge_window_end TEXT NULL
|
||||
nudge_min_interval_minutes INTEGER NULL
|
||||
nudge_max_per_day INTEGER NULL
|
||||
|
||||
photo_proof_enabled BOOLEAN NOT NULL DEFAULT 0
|
||||
default_session_kind TEXT NOT NULL DEFAULT 'freeform'
|
||||
default_session_minutes INTEGER NOT NULL DEFAULT 12
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
## 4.2 Tasks Table Additions (Zones Only)
|
||||
|
||||
is_zone BOOLEAN NOT NULL DEFAULT 0
|
||||
|
||||
stability_base INTEGER NULL
|
||||
decay_rate_per_day REAL NULL
|
||||
last_stability_update_at DATETIME NULL
|
||||
last_strike_at DATETIME NULL
|
||||
|
||||
zone_preset TEXT NULL
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
## 4.3 New Table: work_sessions
|
||||
|
||||
id INTEGER PRIMARY KEY
|
||||
project_id INTEGER NOT NULL
|
||||
task_id INTEGER NULL
|
||||
kind TEXT NOT NULL
|
||||
started_at DATETIME NOT NULL
|
||||
ended_at DATETIME NULL
|
||||
duration_seconds INTEGER NULL
|
||||
note TEXT NULL
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
## 4.4 New Table: session_photos
|
||||
|
||||
id INTEGER PRIMARY KEY
|
||||
session_id INTEGER NOT NULL
|
||||
phase TEXT NOT NULL -- 'before' or 'after'
|
||||
path TEXT NOT NULL
|
||||
taken_at DATETIME NOT NULL
|
||||
|
||||
Images stored in Docker volume under:
|
||||
|
||||
/data/photos/{project_id}/{session_id}/...
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
# 5. Entropy Engine (v1)
|
||||
|
||||
## 5.1 Stability Model
|
||||
|
||||
Fields used: - stability_base - last_stability_update_at -
|
||||
decay_rate_per_day
|
||||
|
||||
Derived:
|
||||
|
||||
days_elapsed = (now - last_stability_update_at)
|
||||
stability_now = max(0, stability_base - decay_rate_per_day * days_elapsed)
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
## 5.2 Strike Effect
|
||||
|
||||
On strike completion:
|
||||
|
||||
Option A (fixed):
|
||||
|
||||
boost = 20
|
||||
|
||||
Option B (duration-based):
|
||||
|
||||
boost = clamp(10, 35, round(duration_minutes * 1.5))
|
||||
|
||||
Update:
|
||||
|
||||
stability_base = min(100, stability_now + boost)
|
||||
last_stability_update_at = now
|
||||
last_strike_at = now
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
## 5.3 Stability Color Mapping
|
||||
|
||||
- 80--100 → green
|
||||
- 55--79 → yellow
|
||||
- 30--54 → orange
|
||||
- 0--29 → red
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
# 6. API Additions
|
||||
|
||||
## Campaign
|
||||
|
||||
POST /api/projects/{id}/launch_campaign
|
||||
GET /api/projects/{id}/zones
|
||||
|
||||
## Sessions
|
||||
|
||||
POST /api/sessions/start
|
||||
POST /api/sessions/{id}/stop
|
||||
GET /api/projects/{id}/sessions
|
||||
|
||||
## Photos
|
||||
|
||||
POST /api/sessions/{id}/photos
|
||||
GET /api/sessions/{id}/photos
|
||||
|
||||
## Wizard
|
||||
|
||||
POST /api/wizard/build_project
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
# 7. Frontend Routes
|
||||
|
||||
/projects
|
||||
/projects/:id
|
||||
/projects/:id/campaign
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
# 8. Build Phases
|
||||
|
||||
Phase 0: Core campaign + stability\
|
||||
Phase 1: Photo proof + compare slider\
|
||||
Phase 2: Nudges\
|
||||
Phase 3: Hex grid expansion
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
# 9. Success Criteria
|
||||
|
||||
- Wizard creates entropy project in \<30 seconds\
|
||||
- Strike starts in 1 tap\
|
||||
- Stability increases after strike\
|
||||
- Stability decreases over time\
|
||||
- No regression in standard projects
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
**Break It Down v0.2.0**\
|
||||
Planning in HQ. Liberation on the front lines.
|
||||
@@ -1,8 +1,8 @@
|
||||
# Database Configuration
|
||||
DATABASE_URL=sqlite:///./tesseract.db
|
||||
DATABASE_URL=sqlite:///./bit.db
|
||||
|
||||
# API Configuration
|
||||
API_TITLE=Tesseract - Nested Todo Tree API
|
||||
API_TITLE=Break It Down (BIT) - Nested Todo Tree API
|
||||
API_DESCRIPTION=API for managing deeply nested todo trees
|
||||
API_VERSION=1.0.0
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
from sqlalchemy.orm import Session, joinedload
|
||||
from sqlalchemy import func
|
||||
from typing import List, Optional
|
||||
from datetime import datetime, timedelta
|
||||
from . import models, schemas
|
||||
|
||||
|
||||
@@ -21,8 +23,14 @@ def get_project(db: Session, project_id: int) -> Optional[models.Project]:
|
||||
return db.query(models.Project).filter(models.Project.id == project_id).first()
|
||||
|
||||
|
||||
def get_projects(db: Session, skip: int = 0, limit: int = 100) -> List[models.Project]:
|
||||
return db.query(models.Project).offset(skip).limit(limit).all()
|
||||
def get_projects(db: Session, skip: int = 0, limit: int = 100, archived: Optional[bool] = None) -> List[models.Project]:
|
||||
query = db.query(models.Project)
|
||||
|
||||
# Filter by archive status if specified
|
||||
if archived is not None:
|
||||
query = query.filter(models.Project.is_archived == archived)
|
||||
|
||||
return query.offset(skip).limit(limit).all()
|
||||
|
||||
|
||||
def update_project(
|
||||
@@ -180,3 +188,66 @@ def get_tasks_by_status(db: Session, project_id: int, status: str) -> List[model
|
||||
models.Task.project_id == project_id,
|
||||
models.Task.status == status
|
||||
).all()
|
||||
|
||||
|
||||
# TimeLog CRUD
|
||||
def create_time_log(db: Session, task_id: int, time_log: schemas.TimeLogCreate) -> models.TimeLog:
|
||||
db_log = models.TimeLog(
|
||||
task_id=task_id,
|
||||
minutes=time_log.minutes,
|
||||
note=time_log.note,
|
||||
session_type=time_log.session_type,
|
||||
)
|
||||
db.add(db_log)
|
||||
db.commit()
|
||||
db.refresh(db_log)
|
||||
return db_log
|
||||
|
||||
|
||||
def get_time_logs_by_task(db: Session, task_id: int) -> List[models.TimeLog]:
|
||||
return db.query(models.TimeLog).filter(
|
||||
models.TimeLog.task_id == task_id
|
||||
).order_by(models.TimeLog.logged_at.desc()).all()
|
||||
|
||||
|
||||
def get_project_time_summary(db: Session, project_id: int) -> dict:
|
||||
"""Aggregate time logged across all tasks in a project"""
|
||||
project = get_project(db, project_id)
|
||||
|
||||
# Get all task IDs in this project
|
||||
task_ids = db.query(models.Task.id).filter(
|
||||
models.Task.project_id == project_id
|
||||
).subquery()
|
||||
|
||||
# Total minutes logged
|
||||
total = db.query(func.sum(models.TimeLog.minutes)).filter(
|
||||
models.TimeLog.task_id.in_(task_ids)
|
||||
).scalar() or 0
|
||||
|
||||
# Pomodoro minutes
|
||||
pomodoro = db.query(func.sum(models.TimeLog.minutes)).filter(
|
||||
models.TimeLog.task_id.in_(task_ids),
|
||||
models.TimeLog.session_type == "pomodoro"
|
||||
).scalar() or 0
|
||||
|
||||
# Manual minutes
|
||||
manual = db.query(func.sum(models.TimeLog.minutes)).filter(
|
||||
models.TimeLog.task_id.in_(task_ids),
|
||||
models.TimeLog.session_type == "manual"
|
||||
).scalar() or 0
|
||||
|
||||
# Weekly minutes (past 7 days)
|
||||
week_ago = datetime.utcnow() - timedelta(days=7)
|
||||
weekly = db.query(func.sum(models.TimeLog.minutes)).filter(
|
||||
models.TimeLog.task_id.in_(task_ids),
|
||||
models.TimeLog.logged_at >= week_ago
|
||||
).scalar() or 0
|
||||
|
||||
return {
|
||||
"total_minutes": total,
|
||||
"pomodoro_minutes": pomodoro,
|
||||
"manual_minutes": manual,
|
||||
"weekly_minutes": weekly,
|
||||
"weekly_hours_goal": project.weekly_hours_goal if project else None,
|
||||
"total_hours_goal": project.total_hours_goal if project else None,
|
||||
}
|
||||
|
||||
@@ -30,9 +30,14 @@ app.add_middleware(
|
||||
# ========== PROJECT ENDPOINTS ==========
|
||||
|
||||
@app.get("/api/projects", response_model=List[schemas.Project])
|
||||
def list_projects(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
|
||||
"""List all projects"""
|
||||
return crud.get_projects(db, skip=skip, limit=limit)
|
||||
def list_projects(
|
||||
skip: int = 0,
|
||||
limit: int = 100,
|
||||
archived: Optional[bool] = None,
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""List all projects with optional archive filter"""
|
||||
return crud.get_projects(db, skip=skip, limit=limit, archived=archived)
|
||||
|
||||
|
||||
@app.post("/api/projects", response_model=schemas.Project, status_code=201)
|
||||
@@ -154,6 +159,32 @@ def delete_task(task_id: int, db: Session = Depends(get_db)):
|
||||
return None
|
||||
|
||||
|
||||
# ========== TIME LOG ENDPOINTS ==========
|
||||
|
||||
@app.post("/api/tasks/{task_id}/time-logs", response_model=schemas.TimeLog, status_code=201)
|
||||
def log_time(task_id: int, time_log: schemas.TimeLogCreate, db: Session = Depends(get_db)):
|
||||
"""Log time spent on a task"""
|
||||
if not crud.get_task(db, task_id):
|
||||
raise HTTPException(status_code=404, detail="Task not found")
|
||||
return crud.create_time_log(db, task_id, time_log)
|
||||
|
||||
|
||||
@app.get("/api/tasks/{task_id}/time-logs", response_model=List[schemas.TimeLog])
|
||||
def get_time_logs(task_id: int, db: Session = Depends(get_db)):
|
||||
"""Get all time logs for a task"""
|
||||
if not crud.get_task(db, task_id):
|
||||
raise HTTPException(status_code=404, detail="Task not found")
|
||||
return crud.get_time_logs_by_task(db, task_id)
|
||||
|
||||
|
||||
@app.get("/api/projects/{project_id}/time-summary", response_model=schemas.ProjectTimeSummary)
|
||||
def get_project_time_summary(project_id: int, db: Session = Depends(get_db)):
|
||||
"""Get aggregated time statistics for a project"""
|
||||
if not crud.get_project(db, project_id):
|
||||
raise HTTPException(status_code=404, detail="Project not found")
|
||||
return crud.get_project_time_summary(db, project_id)
|
||||
|
||||
|
||||
# ========== SEARCH ENDPOINT ==========
|
||||
|
||||
@app.get("/api/search", response_model=List[schemas.Task])
|
||||
@@ -314,6 +345,6 @@ def root():
|
||||
"""API health check"""
|
||||
return {
|
||||
"status": "online",
|
||||
"message": "Tesseract API - Nested Todo Tree Manager",
|
||||
"message": "Break It Down (BIT) API",
|
||||
"docs": "/docs"
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from sqlalchemy import Column, Integer, String, Text, DateTime, ForeignKey, JSON
|
||||
from sqlalchemy import Column, Integer, String, Text, DateTime, ForeignKey, JSON, Boolean
|
||||
from sqlalchemy.orm import relationship
|
||||
from datetime import datetime
|
||||
from .database import Base
|
||||
@@ -15,6 +15,12 @@ class Project(Base):
|
||||
name = Column(String(255), nullable=False)
|
||||
description = Column(Text, nullable=True)
|
||||
statuses = Column(JSON, nullable=False, default=DEFAULT_STATUSES)
|
||||
is_archived = Column(Boolean, default=False, nullable=False)
|
||||
category = Column(String(100), nullable=True)
|
||||
weekly_hours_goal = Column(Integer, nullable=True) # stored in minutes
|
||||
total_hours_goal = Column(Integer, nullable=True) # stored in minutes
|
||||
pomodoro_work_minutes = Column(Integer, nullable=True, default=25)
|
||||
pomodoro_break_minutes = Column(Integer, nullable=True, default=5)
|
||||
created_at = Column(DateTime, default=datetime.utcnow)
|
||||
updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
@@ -39,3 +45,17 @@ class Task(Base):
|
||||
|
||||
project = relationship("Project", back_populates="tasks")
|
||||
parent = relationship("Task", remote_side=[id], backref="subtasks")
|
||||
time_logs = relationship("TimeLog", back_populates="task", cascade="all, delete-orphan")
|
||||
|
||||
|
||||
class TimeLog(Base):
|
||||
__tablename__ = "time_logs"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
task_id = Column(Integer, ForeignKey("tasks.id"), nullable=False)
|
||||
minutes = Column(Integer, nullable=False)
|
||||
note = Column(Text, nullable=True)
|
||||
session_type = Column(String(50), default="manual") # 'pomodoro' | 'manual'
|
||||
logged_at = Column(DateTime, default=datetime.utcnow)
|
||||
|
||||
task = relationship("Task", back_populates="time_logs")
|
||||
|
||||
@@ -54,17 +54,34 @@ class ProjectBase(BaseModel):
|
||||
|
||||
class ProjectCreate(ProjectBase):
|
||||
statuses: Optional[List[str]] = None
|
||||
category: Optional[str] = None
|
||||
weekly_hours_goal: Optional[int] = None
|
||||
total_hours_goal: Optional[int] = None
|
||||
pomodoro_work_minutes: Optional[int] = None
|
||||
pomodoro_break_minutes: Optional[int] = None
|
||||
|
||||
|
||||
class ProjectUpdate(BaseModel):
|
||||
name: Optional[str] = None
|
||||
description: Optional[str] = None
|
||||
statuses: Optional[List[str]] = None
|
||||
is_archived: Optional[bool] = None
|
||||
category: Optional[str] = None
|
||||
weekly_hours_goal: Optional[int] = None
|
||||
total_hours_goal: Optional[int] = None
|
||||
pomodoro_work_minutes: Optional[int] = None
|
||||
pomodoro_break_minutes: Optional[int] = None
|
||||
|
||||
|
||||
class Project(ProjectBase):
|
||||
id: int
|
||||
statuses: List[str]
|
||||
is_archived: bool
|
||||
category: Optional[str] = None
|
||||
weekly_hours_goal: Optional[int] = None
|
||||
total_hours_goal: Optional[int] = None
|
||||
pomodoro_work_minutes: Optional[int] = None
|
||||
pomodoro_break_minutes: Optional[int] = None
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
@@ -103,3 +120,30 @@ class ImportResult(BaseModel):
|
||||
project_id: int
|
||||
project_name: str
|
||||
tasks_created: int
|
||||
|
||||
|
||||
# TimeLog Schemas
|
||||
class TimeLogCreate(BaseModel):
|
||||
minutes: int
|
||||
note: Optional[str] = None
|
||||
session_type: str = "manual" # 'pomodoro' | 'manual'
|
||||
|
||||
|
||||
class TimeLog(BaseModel):
|
||||
id: int
|
||||
task_id: int
|
||||
minutes: int
|
||||
note: Optional[str] = None
|
||||
session_type: str
|
||||
logged_at: datetime
|
||||
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
|
||||
class ProjectTimeSummary(BaseModel):
|
||||
total_minutes: int
|
||||
pomodoro_minutes: int
|
||||
manual_minutes: int
|
||||
weekly_minutes: int
|
||||
weekly_hours_goal: Optional[int] = None
|
||||
total_hours_goal: Optional[int] = None
|
||||
|
||||
@@ -6,10 +6,10 @@ class Settings(BaseSettings):
|
||||
"""Application settings loaded from environment variables"""
|
||||
|
||||
# Database Configuration
|
||||
database_url: str = "sqlite:///./tesseract.db"
|
||||
database_url: str = "sqlite:///./bit.db"
|
||||
|
||||
# API Configuration
|
||||
api_title: str = "Tesseract - Nested Todo Tree API"
|
||||
api_title: str = "Break It Down (BIT) - Nested Todo Tree API"
|
||||
api_description: str = "API for managing deeply nested todo trees"
|
||||
api_version: str = "1.0.0"
|
||||
|
||||
|
||||
37
backend/migrate_add_is_archived.py
Normal file
37
backend/migrate_add_is_archived.py
Normal file
@@ -0,0 +1,37 @@
|
||||
"""
|
||||
Migration script to add is_archived column to existing projects.
|
||||
Run this once if you have an existing database.
|
||||
"""
|
||||
import sqlite3
|
||||
import os
|
||||
|
||||
# Get the database path
|
||||
db_path = os.path.join(os.path.dirname(__file__), 'bit.db')
|
||||
|
||||
if not os.path.exists(db_path):
|
||||
print(f"Database not found at {db_path}")
|
||||
print("No migration needed - new database will be created with the correct schema.")
|
||||
exit(0)
|
||||
|
||||
# Connect to the database
|
||||
conn = sqlite3.connect(db_path)
|
||||
cursor = conn.cursor()
|
||||
|
||||
try:
|
||||
# Check if the column already exists
|
||||
cursor.execute("PRAGMA table_info(projects)")
|
||||
columns = [column[1] for column in cursor.fetchall()]
|
||||
|
||||
if 'is_archived' in columns:
|
||||
print("Column 'is_archived' already exists. Migration not needed.")
|
||||
else:
|
||||
# Add the is_archived column
|
||||
cursor.execute("ALTER TABLE projects ADD COLUMN is_archived BOOLEAN NOT NULL DEFAULT 0")
|
||||
conn.commit()
|
||||
print("Successfully added 'is_archived' column to projects table.")
|
||||
print("All existing projects have been set to is_archived=False (0).")
|
||||
except Exception as e:
|
||||
print(f"Error during migration: {e}")
|
||||
conn.rollback()
|
||||
finally:
|
||||
conn.close()
|
||||
42
backend/migrate_add_project_goals.py
Normal file
42
backend/migrate_add_project_goals.py
Normal file
@@ -0,0 +1,42 @@
|
||||
"""
|
||||
Migration script to add time goals, category, and pomodoro settings to projects table.
|
||||
Run this once if you have an existing database.
|
||||
"""
|
||||
import sqlite3
|
||||
import os
|
||||
|
||||
db_path = os.path.join(os.path.dirname(__file__), 'bit.db')
|
||||
|
||||
if not os.path.exists(db_path):
|
||||
print("No migration needed - new database will be created with the correct schema.")
|
||||
exit(0)
|
||||
|
||||
conn = sqlite3.connect(db_path)
|
||||
cursor = conn.cursor()
|
||||
|
||||
try:
|
||||
cursor.execute("PRAGMA table_info(projects)")
|
||||
columns = [column[1] for column in cursor.fetchall()]
|
||||
|
||||
new_columns = [
|
||||
("category", "TEXT DEFAULT NULL"),
|
||||
("weekly_hours_goal", "INTEGER DEFAULT NULL"),
|
||||
("total_hours_goal", "INTEGER DEFAULT NULL"),
|
||||
("pomodoro_work_minutes", "INTEGER DEFAULT 25"),
|
||||
("pomodoro_break_minutes", "INTEGER DEFAULT 5"),
|
||||
]
|
||||
|
||||
for col_name, col_def in new_columns:
|
||||
if col_name in columns:
|
||||
print(f"Column '{col_name}' already exists. Skipping.")
|
||||
else:
|
||||
cursor.execute(f"ALTER TABLE projects ADD COLUMN {col_name} {col_def}")
|
||||
print(f"Successfully added '{col_name}'.")
|
||||
|
||||
conn.commit()
|
||||
print("Migration complete.")
|
||||
except Exception as e:
|
||||
print(f"Error during migration: {e}")
|
||||
conn.rollback()
|
||||
finally:
|
||||
conn.close()
|
||||
@@ -10,7 +10,7 @@ DEFAULT_STATUSES = ["backlog", "in_progress", "on_hold", "done"]
|
||||
|
||||
def migrate():
|
||||
# Connect to the database
|
||||
conn = sqlite3.connect('tesseract.db')
|
||||
conn = sqlite3.connect('bit.db')
|
||||
cursor = conn.cursor()
|
||||
|
||||
try:
|
||||
|
||||
34
backend/migrate_add_time_logs.py
Normal file
34
backend/migrate_add_time_logs.py
Normal file
@@ -0,0 +1,34 @@
|
||||
"""
|
||||
Migration script to create the time_logs table.
|
||||
Run this once if you have an existing database.
|
||||
"""
|
||||
import sqlite3
|
||||
import os
|
||||
|
||||
db_path = os.path.join(os.path.dirname(__file__), 'bit.db')
|
||||
|
||||
if not os.path.exists(db_path):
|
||||
print("No migration needed - new database will be created with the correct schema.")
|
||||
exit(0)
|
||||
|
||||
conn = sqlite3.connect(db_path)
|
||||
cursor = conn.cursor()
|
||||
|
||||
try:
|
||||
cursor.execute("""
|
||||
CREATE TABLE IF NOT EXISTS time_logs (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
task_id INTEGER NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
|
||||
minutes INTEGER NOT NULL,
|
||||
note TEXT,
|
||||
session_type TEXT DEFAULT 'manual',
|
||||
logged_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
""")
|
||||
conn.commit()
|
||||
print("Successfully created 'time_logs' table (or it already existed).")
|
||||
except Exception as e:
|
||||
print(f"Error during migration: {e}")
|
||||
conn.rollback()
|
||||
finally:
|
||||
conn.close()
|
||||
@@ -3,12 +3,12 @@ services:
|
||||
build:
|
||||
context: ./backend
|
||||
dockerfile: Dockerfile
|
||||
container_name: tesseract-backend
|
||||
container_name: bit-backend
|
||||
ports:
|
||||
- "8002:8002"
|
||||
volumes:
|
||||
- ./backend/app:/app/app
|
||||
- tesseract-db:/app
|
||||
- bit-db:/app
|
||||
env_file:
|
||||
- ./backend/.env
|
||||
environment:
|
||||
@@ -19,7 +19,7 @@ services:
|
||||
build:
|
||||
context: ./frontend
|
||||
dockerfile: Dockerfile
|
||||
container_name: tesseract-frontend
|
||||
container_name: bit-frontend
|
||||
ports:
|
||||
- "3002:80"
|
||||
env_file:
|
||||
@@ -29,4 +29,4 @@ services:
|
||||
restart: unless-stopped
|
||||
|
||||
volumes:
|
||||
tesseract-db:
|
||||
bit-db:
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
<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>Tesseract - Task Decomposition Engine</title>
|
||||
<title>BIT - Break It Down</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
|
||||
4
frontend/package-lock.json
generated
4
frontend/package-lock.json
generated
@@ -1,11 +1,11 @@
|
||||
{
|
||||
"name": "tesseract-frontend",
|
||||
"name": "bit-frontend",
|
||||
"version": "1.0.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "tesseract-frontend",
|
||||
"name": "bit-frontend",
|
||||
"version": "1.0.0",
|
||||
"dependencies": {
|
||||
"lucide-react": "^0.303.0",
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"name": "tesseract-frontend",
|
||||
"name": "bit-frontend",
|
||||
"private": true,
|
||||
"version": "1.0.0",
|
||||
"type": "module",
|
||||
|
||||
@@ -2,32 +2,38 @@ import { Routes, Route } from 'react-router-dom'
|
||||
import ProjectList from './pages/ProjectList'
|
||||
import ProjectView from './pages/ProjectView'
|
||||
import SearchBar from './components/SearchBar'
|
||||
import { PomodoroProvider } from './context/PomodoroContext'
|
||||
import PomodoroWidget from './components/PomodoroWidget'
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<div className="min-h-screen bg-cyber-dark">
|
||||
<header className="border-b border-cyber-orange/30 bg-cyber-darkest">
|
||||
<div className="container mx-auto px-4 py-4">
|
||||
<div className="flex justify-between items-center">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-cyber-orange">
|
||||
TESSERACT
|
||||
<span className="ml-3 text-sm text-gray-500">Task Decomposition Engine</span>
|
||||
<span className="ml-2 text-xs text-gray-600">v{import.meta.env.VITE_APP_VERSION || '0.1.6'}</span>
|
||||
</h1>
|
||||
<PomodoroProvider>
|
||||
<div className="min-h-screen bg-cyber-dark">
|
||||
<header className="border-b border-cyber-orange/30 bg-cyber-darkest">
|
||||
<div className="container mx-auto px-4 py-4">
|
||||
<div className="flex justify-between items-center">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-cyber-orange">
|
||||
BIT
|
||||
<span className="ml-3 text-sm text-gray-500">Break It Down</span>
|
||||
<span className="ml-2 text-xs text-gray-600">v{import.meta.env.VITE_APP_VERSION || '0.1.6'}</span>
|
||||
</h1>
|
||||
</div>
|
||||
<SearchBar />
|
||||
</div>
|
||||
<SearchBar />
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
</header>
|
||||
|
||||
<main className="container mx-auto px-4 py-8">
|
||||
<Routes>
|
||||
<Route path="/" element={<ProjectList />} />
|
||||
<Route path="/project/:projectId" element={<ProjectView />} />
|
||||
</Routes>
|
||||
</main>
|
||||
</div>
|
||||
<main className="container mx-auto px-4 py-8">
|
||||
<Routes>
|
||||
<Route path="/" element={<ProjectList />} />
|
||||
<Route path="/project/:projectId" element={<ProjectView />} />
|
||||
</Routes>
|
||||
</main>
|
||||
|
||||
<PomodoroWidget />
|
||||
</div>
|
||||
</PomodoroProvider>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { Plus, Check, X, Flag, Clock, ChevronDown, ChevronRight, ChevronsDown, ChevronsUp } from 'lucide-react'
|
||||
import { Plus, Check, X, Flag, Clock, ChevronDown, ChevronRight, ChevronsDown, ChevronsUp, Timer } from 'lucide-react'
|
||||
import {
|
||||
getProjectTasks,
|
||||
createTask,
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
import { formatTimeWithTotal } from '../utils/format'
|
||||
import TaskMenu from './TaskMenu'
|
||||
import TaskForm from './TaskForm'
|
||||
import { usePomodoro } from '../context/PomodoroContext'
|
||||
|
||||
// Helper to format status label
|
||||
const formatStatusLabel = (status) => {
|
||||
@@ -69,10 +70,12 @@ function hasDescendantsInStatus(taskId, allTasks, status) {
|
||||
return getDescendantsInStatus(taskId, allTasks, status).length > 0
|
||||
}
|
||||
|
||||
function TaskCard({ task, allTasks, onUpdate, onDragStart, isParent, columnStatus, expandedCards, setExpandedCards, projectStatuses, projectId }) {
|
||||
function TaskCard({ task, allTasks, onUpdate, onDragStart, isParent, columnStatus, expandedCards, setExpandedCards, projectStatuses, projectId, pomodoroSettings }) {
|
||||
const [isEditing, setIsEditing] = useState(false)
|
||||
const [editTitle, setEditTitle] = useState(task.title)
|
||||
const [showAddSubtask, setShowAddSubtask] = useState(false)
|
||||
const { startPomodoro, activeTask, phase } = usePomodoro()
|
||||
const isActiveTimer = activeTask?.id === task.id && phase !== 'idle'
|
||||
|
||||
// Use global expanded state
|
||||
const isExpanded = expandedCards[task.id] || false
|
||||
@@ -234,6 +237,20 @@ function TaskCard({ task, allTasks, onUpdate, onDragStart, isParent, columnStatu
|
||||
</div>
|
||||
|
||||
<div className="flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
startPomodoro(
|
||||
{ id: task.id, title: task.title, estimatedMinutes: task.estimated_minutes },
|
||||
pomodoroSettings?.workMinutes || 25,
|
||||
pomodoroSettings?.breakMinutes || 5
|
||||
)
|
||||
}}
|
||||
className={`p-1 transition-colors ${isActiveTimer ? 'text-cyber-orange' : 'text-gray-400 hover:text-cyber-orange'}`}
|
||||
title={isActiveTimer ? 'Timer running' : 'Start Pomodoro'}
|
||||
>
|
||||
<Timer size={14} />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setShowAddSubtask(true)}
|
||||
className="text-cyber-orange hover:text-cyber-orange-bright p-1"
|
||||
@@ -283,6 +300,7 @@ function TaskCard({ task, allTasks, onUpdate, onDragStart, isParent, columnStatu
|
||||
setExpandedCards={setExpandedCards}
|
||||
projectStatuses={projectStatuses}
|
||||
projectId={projectId}
|
||||
pomodoroSettings={pomodoroSettings}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
@@ -291,7 +309,7 @@ function TaskCard({ task, allTasks, onUpdate, onDragStart, isParent, columnStatu
|
||||
)
|
||||
}
|
||||
|
||||
function KanbanColumn({ status, allTasks, projectId, onUpdate, onDrop, onDragOver, expandedCards, setExpandedCards, projectStatuses }) {
|
||||
function KanbanColumn({ status, allTasks, projectId, onUpdate, onDrop, onDragOver, expandedCards, setExpandedCards, projectStatuses, pomodoroSettings }) {
|
||||
const [showAddTask, setShowAddTask] = useState(false)
|
||||
|
||||
const handleAddTask = async (taskData) => {
|
||||
@@ -384,6 +402,7 @@ function KanbanColumn({ status, allTasks, projectId, onUpdate, onDrop, onDragOve
|
||||
setExpandedCards={setExpandedCards}
|
||||
projectStatuses={projectStatuses}
|
||||
projectId={projectId}
|
||||
pomodoroSettings={pomodoroSettings}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
@@ -400,6 +419,10 @@ function KanbanView({ projectId, project }) {
|
||||
|
||||
// Get statuses from project, or use defaults
|
||||
const statuses = project?.statuses || ['backlog', 'in_progress', 'on_hold', 'done']
|
||||
const pomodoroSettings = {
|
||||
workMinutes: project?.pomodoro_work_minutes || 25,
|
||||
breakMinutes: project?.pomodoro_break_minutes || 5,
|
||||
}
|
||||
const statusesWithMeta = statuses.map(status => ({
|
||||
key: status,
|
||||
label: formatStatusLabel(status),
|
||||
@@ -507,6 +530,7 @@ function KanbanView({ projectId, project }) {
|
||||
expandedCards={expandedCards}
|
||||
setExpandedCards={setExpandedCards}
|
||||
projectStatuses={statuses}
|
||||
pomodoroSettings={pomodoroSettings}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
134
frontend/src/components/PomodoroWidget.jsx
Normal file
134
frontend/src/components/PomodoroWidget.jsx
Normal file
@@ -0,0 +1,134 @@
|
||||
import { X, Pause, Play, Square, SkipForward } from 'lucide-react'
|
||||
import { usePomodoro } from '../context/PomodoroContext'
|
||||
|
||||
function formatCountdown(seconds) {
|
||||
const m = Math.floor(seconds / 60)
|
||||
const s = seconds % 60
|
||||
return `${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`
|
||||
}
|
||||
|
||||
export default function PomodoroWidget() {
|
||||
const { activeTask, phase, secondsLeft, sessionCount, workMinutes, breakMinutes, pause, resume, stop, skipBreak } = usePomodoro()
|
||||
|
||||
if (phase === 'idle') return null
|
||||
|
||||
const isBreak = phase === 'break'
|
||||
const isPaused = phase === 'paused'
|
||||
|
||||
const totalSecs = isBreak ? breakMinutes * 60 : workMinutes * 60
|
||||
const progress = totalSecs > 0 ? (totalSecs - secondsLeft) / totalSecs : 0
|
||||
|
||||
const phaseLabel = isBreak ? '☕ BREAK' : '🍅 WORK'
|
||||
const phaseColor = isBreak ? 'text-green-400' : 'text-cyber-orange'
|
||||
const borderColor = isBreak ? 'border-green-500/50' : 'border-cyber-orange/50'
|
||||
|
||||
return (
|
||||
<div className={`fixed bottom-4 right-4 z-50 w-72 bg-cyber-darkest border ${borderColor} rounded-lg shadow-cyber-lg`}>
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between px-4 pt-3 pb-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className={`text-xs font-bold tracking-wider ${phaseColor}`}>
|
||||
{phaseLabel}
|
||||
{!isBreak && sessionCount > 0 && (
|
||||
<span className="ml-2 text-gray-500 font-normal">#{sessionCount + 1}</span>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
<button
|
||||
onClick={stop}
|
||||
className="text-gray-500 hover:text-gray-300 transition-colors"
|
||||
title="Stop and close"
|
||||
>
|
||||
<X size={16} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Task name */}
|
||||
{activeTask && !isBreak && (
|
||||
<div className="px-4 pb-1">
|
||||
<p className="text-sm text-gray-300 truncate" title={activeTask.title}>
|
||||
{activeTask.title}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Timer display */}
|
||||
<div className="px-4 py-2 text-center">
|
||||
<span className={`text-4xl font-mono font-bold tabular-nums ${isPaused ? 'text-gray-500' : phaseColor}`}>
|
||||
{formatCountdown(secondsLeft)}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Progress bar */}
|
||||
<div className="px-4 pb-2">
|
||||
<div className="h-1 bg-cyber-darker rounded-full overflow-hidden">
|
||||
<div
|
||||
className={`h-full rounded-full transition-all duration-1000 ${isBreak ? 'bg-green-500' : 'bg-cyber-orange'}`}
|
||||
style={{ width: `${progress * 100}%` }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Controls */}
|
||||
<div className="flex gap-2 px-4 pb-3">
|
||||
{isBreak ? (
|
||||
<>
|
||||
<button
|
||||
onClick={skipBreak}
|
||||
className="flex-1 flex items-center justify-center gap-1 px-3 py-1.5 text-xs bg-cyber-darker border border-cyber-orange/30 text-gray-300 rounded hover:border-cyber-orange/60 hover:text-gray-100 transition-colors"
|
||||
>
|
||||
<SkipForward size={13} />
|
||||
Skip Break
|
||||
</button>
|
||||
<button
|
||||
onClick={stop}
|
||||
className="flex items-center justify-center gap-1 px-3 py-1.5 text-xs bg-cyber-darker border border-red-500/30 text-red-400 rounded hover:border-red-500/60 transition-colors"
|
||||
>
|
||||
<Square size={13} />
|
||||
Stop
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
{isPaused ? (
|
||||
<button
|
||||
onClick={resume}
|
||||
className="flex-1 flex items-center justify-center gap-1 px-3 py-1.5 text-xs bg-cyber-orange/20 border border-cyber-orange text-cyber-orange rounded hover:bg-cyber-orange/30 transition-colors"
|
||||
>
|
||||
<Play size={13} />
|
||||
Resume
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
onClick={pause}
|
||||
className="flex-1 flex items-center justify-center gap-1 px-3 py-1.5 text-xs bg-cyber-darker border border-cyber-orange/30 text-gray-300 rounded hover:border-cyber-orange/60 hover:text-gray-100 transition-colors"
|
||||
>
|
||||
<Pause size={13} />
|
||||
Pause
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
onClick={stop}
|
||||
className="flex items-center justify-center gap-1 px-3 py-1.5 text-xs bg-cyber-darker border border-red-500/30 text-red-400 rounded hover:border-red-500/60 transition-colors"
|
||||
>
|
||||
<Square size={13} />
|
||||
Stop
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Session count dots */}
|
||||
{sessionCount > 0 && (
|
||||
<div className="flex justify-center gap-1 pb-3">
|
||||
{Array.from({ length: Math.min(sessionCount, 8) }).map((_, i) => (
|
||||
<div key={i} className="w-1.5 h-1.5 rounded-full bg-cyber-orange/60" />
|
||||
))}
|
||||
{sessionCount > 8 && (
|
||||
<span className="text-xs text-gray-500 ml-1">+{sessionCount - 8}</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -11,6 +11,23 @@ function ProjectSettings({ project, onClose, onUpdate }) {
|
||||
const [taskCounts, setTaskCounts] = useState({})
|
||||
const [deleteWarning, setDeleteWarning] = useState(null)
|
||||
|
||||
// Time & Goals fields
|
||||
const [category, setCategory] = useState(project.category || '')
|
||||
const [weeklyGoalHours, setWeeklyGoalHours] = useState(
|
||||
project.weekly_hours_goal ? Math.floor(project.weekly_hours_goal / 60) : ''
|
||||
)
|
||||
const [weeklyGoalMins, setWeeklyGoalMins] = useState(
|
||||
project.weekly_hours_goal ? project.weekly_hours_goal % 60 : ''
|
||||
)
|
||||
const [totalGoalHours, setTotalGoalHours] = useState(
|
||||
project.total_hours_goal ? Math.floor(project.total_hours_goal / 60) : ''
|
||||
)
|
||||
const [totalGoalMins, setTotalGoalMins] = useState(
|
||||
project.total_hours_goal ? project.total_hours_goal % 60 : ''
|
||||
)
|
||||
const [pomodoroWork, setPomodoroWork] = useState(project.pomodoro_work_minutes || 25)
|
||||
const [pomodoroBreak, setPomodoroBreak] = useState(project.pomodoro_break_minutes || 5)
|
||||
|
||||
useEffect(() => {
|
||||
loadTaskCounts()
|
||||
}, [])
|
||||
@@ -120,8 +137,20 @@ function ProjectSettings({ project, onClose, onUpdate }) {
|
||||
return
|
||||
}
|
||||
|
||||
const weeklyMinutes =
|
||||
(parseInt(weeklyGoalHours) || 0) * 60 + (parseInt(weeklyGoalMins) || 0)
|
||||
const totalMinutes =
|
||||
(parseInt(totalGoalHours) || 0) * 60 + (parseInt(totalGoalMins) || 0)
|
||||
|
||||
try {
|
||||
await updateProject(project.id, { statuses })
|
||||
await updateProject(project.id, {
|
||||
statuses,
|
||||
category: category.trim() || null,
|
||||
weekly_hours_goal: weeklyMinutes > 0 ? weeklyMinutes : null,
|
||||
total_hours_goal: totalMinutes > 0 ? totalMinutes : null,
|
||||
pomodoro_work_minutes: parseInt(pomodoroWork) || 25,
|
||||
pomodoro_break_minutes: parseInt(pomodoroBreak) || 5,
|
||||
})
|
||||
onUpdate()
|
||||
onClose()
|
||||
} catch (err) {
|
||||
@@ -247,6 +276,106 @@ function ProjectSettings({ project, onClose, onUpdate }) {
|
||||
Add Status
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Time & Goals */}
|
||||
<div className="mt-6 pt-6 border-t border-cyber-orange/20">
|
||||
<h3 className="text-lg font-semibold text-gray-200 mb-4">Time & Goals</h3>
|
||||
|
||||
<div className="space-y-4">
|
||||
{/* Category */}
|
||||
<div>
|
||||
<label className="block text-sm text-gray-400 mb-1">Category</label>
|
||||
<input
|
||||
type="text"
|
||||
value={category}
|
||||
onChange={(e) => setCategory(e.target.value)}
|
||||
placeholder="e.g. home, programming, hobby"
|
||||
className="w-full px-3 py-2 bg-cyber-darker border border-cyber-orange/30 rounded text-gray-100 text-sm focus:outline-none focus:border-cyber-orange"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Weekly goal */}
|
||||
<div>
|
||||
<label className="block text-sm text-gray-400 mb-1">Weekly Time Goal</label>
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="number"
|
||||
min="0"
|
||||
value={weeklyGoalHours}
|
||||
onChange={(e) => setWeeklyGoalHours(e.target.value)}
|
||||
placeholder="0"
|
||||
className="w-20 px-3 py-2 bg-cyber-darker border border-cyber-orange/30 rounded text-gray-100 text-sm focus:outline-none focus:border-cyber-orange"
|
||||
/>
|
||||
<span className="text-gray-500 text-sm">hr</span>
|
||||
<input
|
||||
type="number"
|
||||
min="0"
|
||||
max="59"
|
||||
value={weeklyGoalMins}
|
||||
onChange={(e) => setWeeklyGoalMins(e.target.value)}
|
||||
placeholder="0"
|
||||
className="w-20 px-3 py-2 bg-cyber-darker border border-cyber-orange/30 rounded text-gray-100 text-sm focus:outline-none focus:border-cyber-orange"
|
||||
/>
|
||||
<span className="text-gray-500 text-sm">min / week</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Total budget */}
|
||||
<div>
|
||||
<label className="block text-sm text-gray-400 mb-1">Total Time Budget</label>
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="number"
|
||||
min="0"
|
||||
value={totalGoalHours}
|
||||
onChange={(e) => setTotalGoalHours(e.target.value)}
|
||||
placeholder="0"
|
||||
className="w-20 px-3 py-2 bg-cyber-darker border border-cyber-orange/30 rounded text-gray-100 text-sm focus:outline-none focus:border-cyber-orange"
|
||||
/>
|
||||
<span className="text-gray-500 text-sm">hr</span>
|
||||
<input
|
||||
type="number"
|
||||
min="0"
|
||||
max="59"
|
||||
value={totalGoalMins}
|
||||
onChange={(e) => setTotalGoalMins(e.target.value)}
|
||||
placeholder="0"
|
||||
className="w-20 px-3 py-2 bg-cyber-darker border border-cyber-orange/30 rounded text-gray-100 text-sm focus:outline-none focus:border-cyber-orange"
|
||||
/>
|
||||
<span className="text-gray-500 text-sm">min total</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Pomodoro settings */}
|
||||
<div>
|
||||
<label className="block text-sm text-gray-400 mb-1">Pomodoro Settings</label>
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="number"
|
||||
min="1"
|
||||
max="120"
|
||||
value={pomodoroWork}
|
||||
onChange={(e) => setPomodoroWork(e.target.value)}
|
||||
className="w-16 px-2 py-2 bg-cyber-darker border border-cyber-orange/30 rounded text-gray-100 text-sm focus:outline-none focus:border-cyber-orange text-center"
|
||||
/>
|
||||
<span className="text-gray-500 text-sm">min work</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="number"
|
||||
min="0"
|
||||
max="60"
|
||||
value={pomodoroBreak}
|
||||
onChange={(e) => setPomodoroBreak(e.target.value)}
|
||||
className="w-16 px-2 py-2 bg-cyber-darker border border-cyber-orange/30 rounded text-gray-100 text-sm focus:outline-none focus:border-cyber-orange text-center"
|
||||
/>
|
||||
<span className="text-gray-500 text-sm">min break</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Footer */}
|
||||
|
||||
@@ -6,7 +6,8 @@ import {
|
||||
Check,
|
||||
X,
|
||||
Flag,
|
||||
Clock
|
||||
Clock,
|
||||
Timer
|
||||
} from 'lucide-react'
|
||||
import {
|
||||
getProjectTaskTree,
|
||||
@@ -17,6 +18,7 @@ import {
|
||||
import { formatTimeWithTotal } from '../utils/format'
|
||||
import TaskMenu from './TaskMenu'
|
||||
import TaskForm from './TaskForm'
|
||||
import { usePomodoro } from '../context/PomodoroContext'
|
||||
|
||||
// Helper to format status label
|
||||
const formatStatusLabel = (status) => {
|
||||
@@ -44,12 +46,14 @@ const FLAG_COLORS = {
|
||||
pink: 'bg-pink-500'
|
||||
}
|
||||
|
||||
function TaskNode({ task, projectId, onUpdate, level = 0, projectStatuses }) {
|
||||
function TaskNode({ task, projectId, onUpdate, level = 0, projectStatuses, pomodoroSettings }) {
|
||||
const [isExpanded, setIsExpanded] = useState(true)
|
||||
const [isEditing, setIsEditing] = useState(false)
|
||||
const [editTitle, setEditTitle] = useState(task.title)
|
||||
const [editStatus, setEditStatus] = useState(task.status)
|
||||
const [showAddSubtask, setShowAddSubtask] = useState(false)
|
||||
const { startPomodoro, activeTask, phase } = usePomodoro()
|
||||
const isActiveTimer = activeTask?.id === task.id && phase !== 'idle'
|
||||
|
||||
const hasSubtasks = task.subtasks && task.subtasks.length > 0
|
||||
|
||||
@@ -200,6 +204,20 @@ function TaskNode({ task, projectId, onUpdate, level = 0, projectStatuses }) {
|
||||
|
||||
{/* Actions */}
|
||||
<div className="flex gap-2 opacity-0 group-hover:opacity-100 transition-opacity">
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
startPomodoro(
|
||||
{ id: task.id, title: task.title, estimatedMinutes: task.estimated_minutes },
|
||||
pomodoroSettings?.workMinutes || 25,
|
||||
pomodoroSettings?.breakMinutes || 5
|
||||
)
|
||||
}}
|
||||
className={`transition-colors ${isActiveTimer ? 'text-cyber-orange' : 'text-gray-400 hover:text-cyber-orange'}`}
|
||||
title={isActiveTimer ? 'Timer running' : 'Start Pomodoro'}
|
||||
>
|
||||
<Timer size={16} />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setShowAddSubtask(true)}
|
||||
className="text-cyber-orange hover:text-cyber-orange-bright"
|
||||
@@ -242,6 +260,7 @@ function TaskNode({ task, projectId, onUpdate, level = 0, projectStatuses }) {
|
||||
onUpdate={onUpdate}
|
||||
level={level + 1}
|
||||
projectStatuses={projectStatuses}
|
||||
pomodoroSettings={pomodoroSettings}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
@@ -252,6 +271,10 @@ function TaskNode({ task, projectId, onUpdate, level = 0, projectStatuses }) {
|
||||
|
||||
function TreeView({ projectId, project }) {
|
||||
const projectStatuses = project?.statuses || ['backlog', 'in_progress', 'on_hold', 'done']
|
||||
const pomodoroSettings = {
|
||||
workMinutes: project?.pomodoro_work_minutes || 25,
|
||||
breakMinutes: project?.pomodoro_break_minutes || 5,
|
||||
}
|
||||
const [tasks, setTasks] = useState([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState('')
|
||||
@@ -338,6 +361,7 @@ function TreeView({ projectId, project }) {
|
||||
projectId={projectId}
|
||||
onUpdate={loadTasks}
|
||||
projectStatuses={projectStatuses}
|
||||
pomodoroSettings={pomodoroSettings}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
204
frontend/src/context/PomodoroContext.jsx
Normal file
204
frontend/src/context/PomodoroContext.jsx
Normal file
@@ -0,0 +1,204 @@
|
||||
import { createContext, useContext, useState, useEffect, useRef, useCallback } from 'react'
|
||||
import { logTime } from '../utils/api'
|
||||
|
||||
const PomodoroContext = createContext(null)
|
||||
|
||||
export function PomodoroProvider({ children }) {
|
||||
const [activeTask, setActiveTask] = useState(null) // { id, title, estimatedMinutes }
|
||||
const [phase, setPhase] = useState('idle') // 'idle' | 'work' | 'break' | 'paused'
|
||||
const [secondsLeft, setSecondsLeft] = useState(0)
|
||||
const [sessionCount, setSessionCount] = useState(0)
|
||||
const [workMinutes, setWorkMinutes] = useState(25)
|
||||
const [breakMinutes, setBreakMinutes] = useState(5)
|
||||
const [pausedPhase, setPausedPhase] = useState(null) // which phase we paused from
|
||||
const [secondsWhenPaused, setSecondsWhenPaused] = useState(0)
|
||||
|
||||
// Track how many seconds actually elapsed in the current work session
|
||||
// (for partial sessions when user stops early)
|
||||
const elapsedWorkSeconds = useRef(0)
|
||||
const intervalRef = useRef(null)
|
||||
|
||||
const playBeep = useCallback((frequency = 440, duration = 0.4) => {
|
||||
try {
|
||||
const ctx = new AudioContext()
|
||||
const osc = ctx.createOscillator()
|
||||
const gain = ctx.createGain()
|
||||
osc.connect(gain)
|
||||
gain.connect(ctx.destination)
|
||||
osc.frequency.value = frequency
|
||||
gain.gain.setValueAtTime(0.3, ctx.currentTime)
|
||||
gain.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + duration)
|
||||
osc.start(ctx.currentTime)
|
||||
osc.stop(ctx.currentTime + duration)
|
||||
} catch (e) {
|
||||
// AudioContext not available (e.g. in tests)
|
||||
}
|
||||
}, [])
|
||||
|
||||
const sendNotification = useCallback((title, body) => {
|
||||
if (typeof Notification !== 'undefined' && Notification.permission === 'granted') {
|
||||
new Notification(title, { body, icon: '/vite.svg' })
|
||||
}
|
||||
}, [])
|
||||
|
||||
const requestNotificationPermission = useCallback(() => {
|
||||
if (typeof Notification !== 'undefined' && Notification.permission === 'default') {
|
||||
Notification.requestPermission()
|
||||
}
|
||||
}, [])
|
||||
|
||||
const autoLogCompletedSession = useCallback(async (taskId, minutes, sessionType) => {
|
||||
if (minutes <= 0) return
|
||||
try {
|
||||
await logTime(taskId, { minutes, session_type: sessionType })
|
||||
} catch (e) {
|
||||
console.error('Failed to auto-log time:', e)
|
||||
}
|
||||
}, [])
|
||||
|
||||
// Tick logic — runs every second when active
|
||||
useEffect(() => {
|
||||
if (phase !== 'work' && phase !== 'break') {
|
||||
clearInterval(intervalRef.current)
|
||||
return
|
||||
}
|
||||
|
||||
intervalRef.current = setInterval(() => {
|
||||
setSecondsLeft(prev => {
|
||||
if (prev <= 1) {
|
||||
// Time's up
|
||||
clearInterval(intervalRef.current)
|
||||
|
||||
if (phase === 'work') {
|
||||
// Auto-log the completed pomodoro
|
||||
autoLogCompletedSession(
|
||||
activeTask.id,
|
||||
workMinutes,
|
||||
'pomodoro'
|
||||
)
|
||||
elapsedWorkSeconds.current = 0
|
||||
|
||||
// Play double beep + notification
|
||||
playBeep(523, 0.3)
|
||||
setTimeout(() => playBeep(659, 0.4), 350)
|
||||
sendNotification('BIT — Pomodoro done!', `Time for a break. Session ${sessionCount + 1} complete.`)
|
||||
|
||||
setSessionCount(c => c + 1)
|
||||
|
||||
if (breakMinutes > 0) {
|
||||
setPhase('break')
|
||||
return breakMinutes * 60
|
||||
} else {
|
||||
// No break configured — go straight back to work
|
||||
setPhase('work')
|
||||
return workMinutes * 60
|
||||
}
|
||||
} else {
|
||||
// Break over
|
||||
playBeep(440, 0.3)
|
||||
setTimeout(() => playBeep(523, 0.4), 350)
|
||||
sendNotification('BIT — Break over!', 'Ready for the next pomodoro?')
|
||||
setPhase('work')
|
||||
return workMinutes * 60
|
||||
}
|
||||
}
|
||||
|
||||
if (phase === 'work') {
|
||||
elapsedWorkSeconds.current += 1
|
||||
}
|
||||
|
||||
return prev - 1
|
||||
})
|
||||
}, 1000)
|
||||
|
||||
return () => clearInterval(intervalRef.current)
|
||||
}, [phase, activeTask, workMinutes, breakMinutes, sessionCount, autoLogCompletedSession, playBeep, sendNotification])
|
||||
|
||||
const startPomodoro = useCallback((task, workMins = 25, breakMins = 5) => {
|
||||
// If a session is active, log partial time first
|
||||
if (phase === 'work' && activeTask && elapsedWorkSeconds.current > 0) {
|
||||
const partialMinutes = Math.round(elapsedWorkSeconds.current / 60)
|
||||
if (partialMinutes > 0) {
|
||||
autoLogCompletedSession(activeTask.id, partialMinutes, 'pomodoro')
|
||||
}
|
||||
}
|
||||
|
||||
clearInterval(intervalRef.current)
|
||||
elapsedWorkSeconds.current = 0
|
||||
|
||||
requestNotificationPermission()
|
||||
|
||||
setActiveTask(task)
|
||||
setWorkMinutes(workMins)
|
||||
setBreakMinutes(breakMins)
|
||||
setSessionCount(0)
|
||||
setPhase('work')
|
||||
setSecondsLeft(workMins * 60)
|
||||
}, [phase, activeTask, autoLogCompletedSession, requestNotificationPermission])
|
||||
|
||||
const pause = useCallback(() => {
|
||||
if (phase !== 'work' && phase !== 'break') return
|
||||
clearInterval(intervalRef.current)
|
||||
setPausedPhase(phase)
|
||||
setSecondsWhenPaused(secondsLeft)
|
||||
setPhase('paused')
|
||||
}, [phase, secondsLeft])
|
||||
|
||||
const resume = useCallback(() => {
|
||||
if (phase !== 'paused') return
|
||||
setPhase(pausedPhase)
|
||||
setSecondsLeft(secondsWhenPaused)
|
||||
}, [phase, pausedPhase, secondsWhenPaused])
|
||||
|
||||
const stop = useCallback(async () => {
|
||||
clearInterval(intervalRef.current)
|
||||
|
||||
// Log partial work time if we were mid-session
|
||||
const currentPhase = phase === 'paused' ? pausedPhase : phase
|
||||
if (currentPhase === 'work' && activeTask && elapsedWorkSeconds.current > 0) {
|
||||
const partialMinutes = Math.round(elapsedWorkSeconds.current / 60)
|
||||
if (partialMinutes > 0) {
|
||||
await autoLogCompletedSession(activeTask.id, partialMinutes, 'pomodoro')
|
||||
}
|
||||
}
|
||||
|
||||
elapsedWorkSeconds.current = 0
|
||||
setActiveTask(null)
|
||||
setPhase('idle')
|
||||
setSecondsLeft(0)
|
||||
setSessionCount(0)
|
||||
setPausedPhase(null)
|
||||
}, [phase, pausedPhase, activeTask, autoLogCompletedSession])
|
||||
|
||||
const skipBreak = useCallback(() => {
|
||||
if (phase !== 'break') return
|
||||
clearInterval(intervalRef.current)
|
||||
setPhase('work')
|
||||
setSecondsLeft(workMinutes * 60)
|
||||
elapsedWorkSeconds.current = 0
|
||||
}, [phase, workMinutes])
|
||||
|
||||
return (
|
||||
<PomodoroContext.Provider value={{
|
||||
activeTask,
|
||||
phase,
|
||||
secondsLeft,
|
||||
sessionCount,
|
||||
workMinutes,
|
||||
breakMinutes,
|
||||
startPomodoro,
|
||||
pause,
|
||||
resume,
|
||||
stop,
|
||||
skipBreak,
|
||||
}}>
|
||||
{children}
|
||||
</PomodoroContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
export function usePomodoro() {
|
||||
const ctx = useContext(PomodoroContext)
|
||||
if (!ctx) throw new Error('usePomodoro must be used inside PomodoroProvider')
|
||||
return ctx
|
||||
}
|
||||
@@ -1,10 +1,12 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { Plus, Upload, Trash2 } from 'lucide-react'
|
||||
import { getProjects, createProject, deleteProject, importJSON } from '../utils/api'
|
||||
import { Plus, Upload, Trash2, Archive, ArchiveRestore, Clock } from 'lucide-react'
|
||||
import { getProjects, createProject, deleteProject, importJSON, archiveProject, unarchiveProject, getProjectTimeSummary } from '../utils/api'
|
||||
import { formatTime } from '../utils/format'
|
||||
|
||||
function ProjectList() {
|
||||
const [projects, setProjects] = useState([])
|
||||
const [timeSummaries, setTimeSummaries] = useState({})
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [showCreateModal, setShowCreateModal] = useState(false)
|
||||
const [showImportModal, setShowImportModal] = useState(false)
|
||||
@@ -12,16 +14,36 @@ function ProjectList() {
|
||||
const [newProjectDesc, setNewProjectDesc] = useState('')
|
||||
const [importJSON_Text, setImportJSONText] = useState('')
|
||||
const [error, setError] = useState('')
|
||||
const [activeTab, setActiveTab] = useState('active') // 'active', 'archived', 'all'
|
||||
const [activeCategory, setActiveCategory] = useState(null)
|
||||
const navigate = useNavigate()
|
||||
|
||||
useEffect(() => {
|
||||
loadProjects()
|
||||
}, [])
|
||||
}, [activeTab])
|
||||
|
||||
const loadProjects = async () => {
|
||||
try {
|
||||
const data = await getProjects()
|
||||
setLoading(true)
|
||||
let archivedFilter = null
|
||||
if (activeTab === 'active') archivedFilter = false
|
||||
if (activeTab === 'archived') archivedFilter = true
|
||||
|
||||
const data = await getProjects(archivedFilter)
|
||||
setProjects(data)
|
||||
|
||||
// Fetch time summaries in parallel for all projects
|
||||
const summaryEntries = await Promise.all(
|
||||
data.map(async (p) => {
|
||||
try {
|
||||
const summary = await getProjectTimeSummary(p.id)
|
||||
return [p.id, summary]
|
||||
} catch {
|
||||
return [p.id, null]
|
||||
}
|
||||
})
|
||||
)
|
||||
setTimeSummaries(Object.fromEntries(summaryEntries))
|
||||
} catch (err) {
|
||||
setError(err.message)
|
||||
} finally {
|
||||
@@ -72,13 +94,33 @@ function ProjectList() {
|
||||
}
|
||||
}
|
||||
|
||||
const handleArchiveProject = async (projectId, e) => {
|
||||
e.stopPropagation()
|
||||
try {
|
||||
await archiveProject(projectId)
|
||||
setProjects(projects.filter(p => p.id !== projectId))
|
||||
} catch (err) {
|
||||
setError(err.message)
|
||||
}
|
||||
}
|
||||
|
||||
const handleUnarchiveProject = async (projectId, e) => {
|
||||
e.stopPropagation()
|
||||
try {
|
||||
await unarchiveProject(projectId)
|
||||
setProjects(projects.filter(p => p.id !== projectId))
|
||||
} catch (err) {
|
||||
setError(err.message)
|
||||
}
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return <div className="text-center text-gray-400 py-12">Loading...</div>
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="flex justify-between items-center mb-8">
|
||||
<div className="flex justify-between items-center mb-6">
|
||||
<h2 className="text-3xl font-bold text-gray-100">Projects</h2>
|
||||
<div className="flex gap-3">
|
||||
<button
|
||||
@@ -98,44 +140,215 @@ function ProjectList() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Category filter */}
|
||||
{(() => {
|
||||
const categories = [...new Set(projects.map(p => p.category).filter(Boolean))].sort()
|
||||
if (categories.length === 0) return null
|
||||
return (
|
||||
<div className="flex gap-2 flex-wrap mb-4">
|
||||
<button
|
||||
onClick={() => setActiveCategory(null)}
|
||||
className={`px-3 py-1 text-sm rounded-full border transition-colors ${
|
||||
activeCategory === null
|
||||
? 'bg-cyber-orange/20 border-cyber-orange text-cyber-orange'
|
||||
: 'border-cyber-orange/30 text-gray-400 hover:border-cyber-orange/60'
|
||||
}`}
|
||||
>
|
||||
All
|
||||
</button>
|
||||
{categories.map(cat => (
|
||||
<button
|
||||
key={cat}
|
||||
onClick={() => setActiveCategory(activeCategory === cat ? null : cat)}
|
||||
className={`px-3 py-1 text-sm rounded-full border transition-colors ${
|
||||
activeCategory === cat
|
||||
? 'bg-cyber-orange/20 border-cyber-orange text-cyber-orange'
|
||||
: 'border-cyber-orange/30 text-gray-400 hover:border-cyber-orange/60'
|
||||
}`}
|
||||
>
|
||||
{cat}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
})()}
|
||||
|
||||
{/* Tabs */}
|
||||
<div className="flex gap-1 mb-6 border-b border-cyber-orange/20">
|
||||
<button
|
||||
onClick={() => setActiveTab('active')}
|
||||
className={`px-4 py-2 font-medium transition-colors ${
|
||||
activeTab === 'active'
|
||||
? 'text-cyber-orange border-b-2 border-cyber-orange'
|
||||
: 'text-gray-400 hover:text-gray-200'
|
||||
}`}
|
||||
>
|
||||
Active
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setActiveTab('archived')}
|
||||
className={`px-4 py-2 font-medium transition-colors ${
|
||||
activeTab === 'archived'
|
||||
? 'text-cyber-orange border-b-2 border-cyber-orange'
|
||||
: 'text-gray-400 hover:text-gray-200'
|
||||
}`}
|
||||
>
|
||||
Archived
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setActiveTab('all')}
|
||||
className={`px-4 py-2 font-medium transition-colors ${
|
||||
activeTab === 'all'
|
||||
? 'text-cyber-orange border-b-2 border-cyber-orange'
|
||||
: 'text-gray-400 hover:text-gray-200'
|
||||
}`}
|
||||
>
|
||||
All
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="mb-4 p-4 bg-red-900/30 border border-red-500/50 rounded text-red-300">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{projects.length === 0 ? (
|
||||
<div className="text-center py-16 text-gray-500">
|
||||
<p className="text-xl mb-2">No projects yet</p>
|
||||
<p className="text-sm">Create a new project or import from JSON</p>
|
||||
</div>
|
||||
) : (
|
||||
{(() => {
|
||||
const visibleProjects = activeCategory
|
||||
? projects.filter(p => p.category === activeCategory)
|
||||
: projects
|
||||
if (visibleProjects.length === 0) return (
|
||||
<div className="text-center py-16 text-gray-500">
|
||||
<p className="text-xl mb-2">
|
||||
{activeTab === 'archived' ? 'No archived projects' : 'No projects yet'}
|
||||
</p>
|
||||
<p className="text-sm">
|
||||
{activeTab === 'archived'
|
||||
? 'Archive projects to keep them out of your active workspace'
|
||||
: 'Create a new project or import from JSON'}
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
return null
|
||||
})()}
|
||||
{projects.length > 0 && (
|
||||
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
|
||||
{projects.map(project => (
|
||||
<div
|
||||
key={project.id}
|
||||
onClick={() => navigate(`/project/${project.id}`)}
|
||||
className="p-6 bg-cyber-darkest border border-cyber-orange/30 rounded-lg hover:border-cyber-orange hover:shadow-cyber transition-all cursor-pointer group"
|
||||
>
|
||||
<div className="flex justify-between items-start mb-2">
|
||||
<h3 className="text-xl font-semibold text-gray-100 group-hover:text-cyber-orange transition-colors">
|
||||
{project.name}
|
||||
</h3>
|
||||
<button
|
||||
onClick={(e) => handleDeleteProject(project.id, e)}
|
||||
className="text-gray-600 hover:text-red-400 transition-colors"
|
||||
>
|
||||
<Trash2 size={18} />
|
||||
</button>
|
||||
{(activeCategory ? projects.filter(p => p.category === activeCategory) : projects).map(project => {
|
||||
const summary = timeSummaries[project.id]
|
||||
const weeklyPct = summary && summary.weekly_hours_goal
|
||||
? Math.min(100, Math.round((summary.weekly_minutes / summary.weekly_hours_goal) * 100))
|
||||
: null
|
||||
const totalPct = summary && summary.total_hours_goal
|
||||
? Math.min(100, Math.round((summary.total_minutes / summary.total_hours_goal) * 100))
|
||||
: null
|
||||
|
||||
return (
|
||||
<div
|
||||
key={project.id}
|
||||
onClick={() => navigate(`/project/${project.id}`)}
|
||||
className={`p-6 bg-cyber-darkest border rounded-lg hover:border-cyber-orange hover:shadow-cyber transition-all cursor-pointer group ${
|
||||
project.is_archived
|
||||
? 'border-gray-700 opacity-75'
|
||||
: 'border-cyber-orange/30'
|
||||
}`}
|
||||
>
|
||||
<div className="flex justify-between items-start mb-2">
|
||||
<h3 className="text-xl font-semibold text-gray-100 group-hover:text-cyber-orange transition-colors">
|
||||
{project.name}
|
||||
{project.is_archived && (
|
||||
<span className="ml-2 text-xs text-gray-500">(archived)</span>
|
||||
)}
|
||||
</h3>
|
||||
<div className="flex gap-2">
|
||||
{project.is_archived ? (
|
||||
<button
|
||||
onClick={(e) => handleUnarchiveProject(project.id, e)}
|
||||
className="text-gray-600 hover:text-cyber-orange transition-colors"
|
||||
title="Unarchive project"
|
||||
>
|
||||
<ArchiveRestore size={18} />
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
onClick={(e) => handleArchiveProject(project.id, e)}
|
||||
className="text-gray-600 hover:text-yellow-400 transition-colors"
|
||||
title="Archive project"
|
||||
>
|
||||
<Archive size={18} />
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
onClick={(e) => handleDeleteProject(project.id, e)}
|
||||
className="text-gray-600 hover:text-red-400 transition-colors"
|
||||
title="Delete project"
|
||||
>
|
||||
<Trash2 size={18} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Category badge */}
|
||||
{project.category && (
|
||||
<span className="inline-block px-2 py-0.5 text-xs bg-cyber-orange/10 text-cyber-orange/70 border border-cyber-orange/20 rounded-full mb-2">
|
||||
{project.category}
|
||||
</span>
|
||||
)}
|
||||
|
||||
{project.description && (
|
||||
<p className="text-gray-400 text-sm line-clamp-2">{project.description}</p>
|
||||
)}
|
||||
|
||||
{/* Time summary */}
|
||||
{summary && summary.total_minutes > 0 && (
|
||||
<div className="mt-3 space-y-2">
|
||||
<div className="flex items-center gap-2 text-xs text-gray-500">
|
||||
<Clock size={11} />
|
||||
<span>{formatTime(summary.total_minutes)} logged total</span>
|
||||
{summary.weekly_minutes > 0 && (
|
||||
<span className="text-gray-600">· {formatTime(summary.weekly_minutes)} this week</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Weekly goal bar */}
|
||||
{weeklyPct !== null && (
|
||||
<div>
|
||||
<div className="flex justify-between text-xs text-gray-600 mb-0.5">
|
||||
<span>Weekly goal</span>
|
||||
<span>{weeklyPct}%</span>
|
||||
</div>
|
||||
<div className="h-1.5 bg-cyber-darker rounded-full overflow-hidden">
|
||||
<div
|
||||
className={`h-full rounded-full transition-all ${weeklyPct >= 100 ? 'bg-green-500' : 'bg-cyber-orange'}`}
|
||||
style={{ width: `${weeklyPct}%` }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Total budget bar */}
|
||||
{totalPct !== null && (
|
||||
<div>
|
||||
<div className="flex justify-between text-xs text-gray-600 mb-0.5">
|
||||
<span>Total budget</span>
|
||||
<span>{totalPct}%</span>
|
||||
</div>
|
||||
<div className="h-1.5 bg-cyber-darker rounded-full overflow-hidden">
|
||||
<div
|
||||
className={`h-full rounded-full transition-all ${totalPct >= 100 ? 'bg-red-500' : 'bg-cyber-orange/60'}`}
|
||||
style={{ width: `${totalPct}%` }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<p className="text-xs text-gray-600 mt-3">
|
||||
Created {new Date(project.created_at).toLocaleDateString()}
|
||||
</p>
|
||||
</div>
|
||||
{project.description && (
|
||||
<p className="text-gray-400 text-sm line-clamp-2">{project.description}</p>
|
||||
)}
|
||||
<p className="text-xs text-gray-600 mt-3">
|
||||
Created {new Date(project.created_at).toLocaleDateString()}
|
||||
</p>
|
||||
</div>
|
||||
))}
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
||||
@@ -22,7 +22,14 @@ async function fetchAPI(endpoint, options = {}) {
|
||||
}
|
||||
|
||||
// Projects
|
||||
export const getProjects = () => fetchAPI('/projects');
|
||||
export const getProjects = (archived = null) => {
|
||||
const params = new URLSearchParams();
|
||||
if (archived !== null) {
|
||||
params.append('archived', archived);
|
||||
}
|
||||
const queryString = params.toString();
|
||||
return fetchAPI(`/projects${queryString ? `?${queryString}` : ''}`);
|
||||
};
|
||||
export const getProject = (id) => fetchAPI(`/projects/${id}`);
|
||||
export const createProject = (data) => fetchAPI('/projects', {
|
||||
method: 'POST',
|
||||
@@ -33,6 +40,8 @@ export const updateProject = (id, data) => fetchAPI(`/projects/${id}`, {
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
export const deleteProject = (id) => fetchAPI(`/projects/${id}`, { method: 'DELETE' });
|
||||
export const archiveProject = (id) => updateProject(id, { is_archived: true });
|
||||
export const unarchiveProject = (id) => updateProject(id, { is_archived: false });
|
||||
|
||||
// Tasks
|
||||
export const getProjectTasks = (projectId) => fetchAPI(`/projects/${projectId}/tasks`);
|
||||
@@ -57,6 +66,14 @@ export const importJSON = (data) => fetchAPI('/import-json', {
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
|
||||
// Time Logs
|
||||
export const logTime = (taskId, data) => fetchAPI(`/tasks/${taskId}/time-logs`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
export const getTimeLogs = (taskId) => fetchAPI(`/tasks/${taskId}/time-logs`);
|
||||
export const getProjectTimeSummary = (projectId) => fetchAPI(`/projects/${projectId}/time-summary`);
|
||||
|
||||
// Search
|
||||
export const searchTasks = (query, projectIds = null) => {
|
||||
const params = new URLSearchParams({ query });
|
||||
|
||||
511
v0_2_0-build-spec.md
Normal file
511
v0_2_0-build-spec.md
Normal file
@@ -0,0 +1,511 @@
|
||||
Break It Down (BIT) — Campaign Mode + Entropy + Wizard Build Spec
|
||||
0) Product idea in one sentence
|
||||
|
||||
BIT is the planning HQ (deep task decomposition). You can “Launch Campaign” on a project to switch into a low-friction operations mode that nudges you, runs timeboxed sessions, captures before/after photos, and visualizes “entropy” creeping back into recurring home zones via a strategy-game-style stability map.
|
||||
|
||||
1) Non-negotiable design principles
|
||||
|
||||
“Start a session” must be 1 tap from Campaign view. No forms before action.
|
||||
|
||||
Entropy features only apply to projects in entropy_space mode; standard projects remain unchanged.
|
||||
|
||||
Planning (Tree/Kanban) and Doing (Campaign) are separate routes and separate UI skins.
|
||||
|
||||
Wizard must generate “good enough” structure in <30 seconds and optionally auto-start the first session.
|
||||
|
||||
2) Core Concepts & Modes
|
||||
2.1 Project Modes (enum)
|
||||
|
||||
standard: current BIT behavior (Tree + Kanban).
|
||||
|
||||
entropy_space: physical-space / recurring maintenance / territory reclaiming.
|
||||
|
||||
(future) pipeline_chores: chores with stages/recurrence (laundry/dishes).
|
||||
|
||||
(future) deep_work: focus sessions (pomodoro defaults).
|
||||
|
||||
2.2 Campaign Types (enum)
|
||||
|
||||
finite: one-off liberation (garage purge). Optional/slow entropy decay.
|
||||
|
||||
background: ongoing maintenance (bathroom/kitchen). Entropy decay enabled.
|
||||
|
||||
2.3 Zone (v1 implementation)
|
||||
|
||||
In entropy_space projects, a Zone is a top-level task (parent_task_id IS NULL).
|
||||
|
||||
2.4 Session (generic), with “Strike” as a label
|
||||
|
||||
Backend stores generic sessions. Campaign UI calls them “strikes” for entropy projects.
|
||||
|
||||
Session kinds (enum):
|
||||
|
||||
strike (entropy_space)
|
||||
|
||||
pomodoro (future deep_work)
|
||||
|
||||
run (future pipeline chores)
|
||||
|
||||
freeform (optional)
|
||||
|
||||
3) User Flows
|
||||
3.1 HQ Planning Flow (existing, with additions)
|
||||
|
||||
Create project (standard or via Wizard).
|
||||
|
||||
In entropy projects, create top-level “zones” + subtasks.
|
||||
|
||||
Hit Launch Campaign button → opens Campaign route.
|
||||
|
||||
3.2 Campaign Operations Flow (new)
|
||||
|
||||
Campaign view shows only:
|
||||
|
||||
Zone cards (stability color + bar + last worked)
|
||||
|
||||
Recommended micro-missions
|
||||
|
||||
Big Start Strike button per zone
|
||||
|
||||
Flow:
|
||||
|
||||
Tap “Start Strike” on a Zone (1 tap)
|
||||
|
||||
Timer begins immediately (default length buttons: 8 / 12 / 25 min)
|
||||
|
||||
Optional prompt: “Snap BEFORE?” (default enabled for entropy_space)
|
||||
|
||||
End Strike → prompt “Snap AFTER”
|
||||
|
||||
Immediately show Before/After compare slider (dopamine)
|
||||
|
||||
Save: session record + optional quick note
|
||||
|
||||
Zone stability increases; decay continues over time
|
||||
|
||||
3.3 Wizard Flow (new)
|
||||
|
||||
Goal: generate project + zones + micro-missions + defaults quickly.
|
||||
|
||||
Wizard inputs:
|
||||
|
||||
Area template (Garage / Bathroom / Kitchen / Whole House / Office)
|
||||
|
||||
Campaign type (Finite vs Background)
|
||||
|
||||
Intensity (Light / Normal / Disaster)
|
||||
|
||||
Nudge window (e.g. 9am–9pm) + max nudges/day
|
||||
|
||||
Default strike buttons (8/12/25 or 10/20/30)
|
||||
|
||||
Wizard outputs:
|
||||
|
||||
Project with project_mode=entropy_space
|
||||
|
||||
Top-level zone tasks
|
||||
|
||||
Subtasks (micro-missions)
|
||||
|
||||
Decay defaults per zone (background campaigns)
|
||||
|
||||
Option: auto-launch campaign and auto-start first strike
|
||||
|
||||
4) Data Model Changes (SQLite + SQLAlchemy)
|
||||
4.1 projects table additions
|
||||
|
||||
project_mode TEXT NOT NULL DEFAULT 'standard'
|
||||
|
||||
campaign_type TEXT NULL (only meaningful if project_mode=entropy_space)
|
||||
|
||||
campaign_active BOOLEAN NOT NULL DEFAULT 0
|
||||
|
||||
nudge_enabled BOOLEAN NOT NULL DEFAULT 0
|
||||
|
||||
nudge_window_start TEXT NULL (HH:MM)
|
||||
|
||||
nudge_window_end TEXT NULL
|
||||
|
||||
nudge_min_interval_minutes INTEGER NULL
|
||||
|
||||
nudge_max_per_day INTEGER NULL
|
||||
|
||||
photo_proof_enabled BOOLEAN NOT NULL DEFAULT 0
|
||||
|
||||
default_session_kind TEXT NOT NULL DEFAULT 'freeform'
|
||||
|
||||
default_session_minutes INTEGER NOT NULL DEFAULT 12
|
||||
|
||||
Notes:
|
||||
|
||||
Keep these nullable/ignored for standard projects.
|
||||
|
||||
Don’t add auth/user tables yet unless you already have them.
|
||||
|
||||
4.2 tasks table additions (only used for entropy zones in v1)
|
||||
|
||||
stability_base INTEGER NULL (stored “as of last_update”; 0–100)
|
||||
|
||||
decay_rate_per_day REAL NULL
|
||||
|
||||
last_stability_update_at DATETIME NULL
|
||||
|
||||
last_strike_at DATETIME NULL
|
||||
|
||||
is_zone BOOLEAN NOT NULL DEFAULT 0 (set true for top-level zone tasks in entropy projects; keeps logic explicit)
|
||||
|
||||
(optional) zone_preset TEXT NULL (bathroom/kitchen/garage for defaults)
|
||||
|
||||
4.3 New table: work_sessions
|
||||
|
||||
id PK
|
||||
|
||||
project_id FK
|
||||
|
||||
task_id FK NULL (zone task)
|
||||
|
||||
kind TEXT NOT NULL
|
||||
|
||||
started_at DATETIME NOT NULL
|
||||
|
||||
ended_at DATETIME NULL
|
||||
|
||||
duration_seconds INTEGER NULL (set on stop)
|
||||
|
||||
note TEXT NULL
|
||||
|
||||
4.4 New table: session_photos
|
||||
|
||||
id PK
|
||||
|
||||
session_id FK
|
||||
|
||||
phase TEXT NOT NULL (‘before’, ‘after’)
|
||||
|
||||
path TEXT NOT NULL
|
||||
|
||||
taken_at DATETIME NOT NULL
|
||||
|
||||
(optional) width, height, hash
|
||||
|
||||
4.5 Storage for images
|
||||
|
||||
Store files on disk in a Docker volume: /data/photos/...
|
||||
|
||||
DB stores only paths/keys
|
||||
|
||||
Provide /api/media/... endpoint to serve images (or configure nginx static)
|
||||
|
||||
5) Entropy / Stability Logic (v1)
|
||||
5.1 Stability computation approach
|
||||
|
||||
Zones track stability via a base value plus decay since last update.
|
||||
|
||||
Fields used:
|
||||
|
||||
stability_base
|
||||
|
||||
last_stability_update_at
|
||||
|
||||
decay_rate_per_day
|
||||
|
||||
Derived:
|
||||
|
||||
stability_now = max(0, stability_base - decay_rate_per_day * days_elapsed)
|
||||
|
||||
On “strike completed”:
|
||||
|
||||
compute stability_now
|
||||
|
||||
apply boost: stability_base = min(100, stability_now + boost)
|
||||
|
||||
set last_stability_update_at = now
|
||||
|
||||
set last_strike_at = now
|
||||
|
||||
Boost rule (v1 simple):
|
||||
|
||||
boost = 20 for any completed strike
|
||||
OR
|
||||
|
||||
boost = clamp(10, 35, round(duration_minutes * 1.5))
|
||||
|
||||
Pick one (fixed boost is easiest to reason about).
|
||||
|
||||
5.2 Color mapping (no raw numbers by default)
|
||||
|
||||
80–100: green
|
||||
|
||||
55–79: yellow
|
||||
|
||||
30–54: orange
|
||||
|
||||
0–29: red
|
||||
|
||||
5.3 Nudges (v1 simple scheduler)
|
||||
|
||||
A background job runs every X minutes (or on app open for v0):
|
||||
|
||||
For each entropy_space project with nudge_enabled:
|
||||
|
||||
for each zone:
|
||||
|
||||
compute stability_now
|
||||
|
||||
if stability_now <= threshold AND not nudged too recently AND within time window:
|
||||
|
||||
create “nudge event” (v0: show in UI inbox; v1: web push/email)
|
||||
|
||||
Start with in-app “Nudge Inbox” so you don’t need push infra immediately.
|
||||
|
||||
6) API Spec (FastAPI)
|
||||
6.1 Projects
|
||||
|
||||
POST /api/projects (add project_mode + campaign settings fields)
|
||||
|
||||
PUT /api/projects/{id} (update campaign settings and campaign_active)
|
||||
|
||||
POST /api/projects/{id}/launch_campaign (sets campaign_active true; returns campaign URL)
|
||||
|
||||
6.2 Tasks
|
||||
|
||||
Existing endpoints unchanged, but:
|
||||
|
||||
POST /api/tasks should allow is_zone, decay_rate_per_day, etc. when project_mode=entropy_space.
|
||||
|
||||
New:
|
||||
|
||||
GET /api/projects/{id}/zones → list top-level zone tasks with computed stability_now and color
|
||||
|
||||
6.3 Sessions
|
||||
|
||||
POST /api/sessions/start
|
||||
|
||||
body: {project_id, task_id?, kind?, planned_minutes?}
|
||||
|
||||
returns: {session_id, started_at}
|
||||
|
||||
POST /api/sessions/{id}/stop
|
||||
|
||||
body: {note?}
|
||||
|
||||
server sets ended_at + duration_seconds; updates zone stability if task_id references a zone
|
||||
|
||||
GET /api/projects/{id}/sessions (filters by kind/date optional)
|
||||
|
||||
GET /api/tasks/{id}/sessions
|
||||
|
||||
6.4 Photos
|
||||
|
||||
POST /api/sessions/{id}/photos (multipart: file + phase)
|
||||
|
||||
GET /api/sessions/{id}/photos → returns URLs/paths
|
||||
|
||||
(optional) GET /api/media/{path} or nginx static mapping
|
||||
|
||||
6.5 Wizard
|
||||
|
||||
POST /api/wizard/build_project
|
||||
|
||||
input: {template_id, intensity, campaign_type, nudge_settings, strike_defaults, auto_launch, auto_start}
|
||||
|
||||
output: {project_id, campaign_url, session_id?}
|
||||
|
||||
7) Frontend Spec (React + Tailwind)
|
||||
7.1 Routes
|
||||
|
||||
/projects (existing)
|
||||
|
||||
/projects/:id (HQ planning view: Tree/Kanban)
|
||||
|
||||
/projects/:id/campaign (Campaign view)
|
||||
|
||||
7.2 Campaign View Components
|
||||
|
||||
CampaignHeader
|
||||
|
||||
project name
|
||||
|
||||
“Back to HQ” link
|
||||
|
||||
campaign settings shortcut
|
||||
|
||||
ZoneGrid
|
||||
|
||||
list of ZoneCards
|
||||
|
||||
ZoneCard
|
||||
|
||||
zone name
|
||||
|
||||
stability bar (color only)
|
||||
|
||||
“Start Strike” button
|
||||
|
||||
quick duration buttons (8/12/25)
|
||||
|
||||
last strike text (“3d ago”)
|
||||
|
||||
recommended micro-missions (top 1–3 subtasks)
|
||||
|
||||
StrikeModal (or full-screen on mobile)
|
||||
|
||||
timer running
|
||||
|
||||
optional “Snap Before”
|
||||
|
||||
“End Strike”
|
||||
|
||||
PhotoCapture
|
||||
|
||||
file input / camera capture on mobile
|
||||
|
||||
BeforeAfterCompare
|
||||
|
||||
slider compare (immediate reward)
|
||||
|
||||
NudgeInbox (v0 notifications)
|
||||
|
||||
list of pending nudges; tap takes you to zone
|
||||
|
||||
7.3 Wizard UI
|
||||
|
||||
NewProjectWizard
|
||||
|
||||
choose template card
|
||||
|
||||
choose campaign type + intensity
|
||||
|
||||
choose nudge window + max/day
|
||||
|
||||
review zones generated (editable list)
|
||||
|
||||
“Create + Launch Campaign” button
|
||||
|
||||
8) Templates (Wizard v1)
|
||||
|
||||
Store templates as JSON files in repo (e.g. backend/app/templates/*.json) or in frontend.
|
||||
|
||||
Template structure (conceptual):
|
||||
|
||||
project: name, description, mode=entropy_space
|
||||
|
||||
zones: list with zone_preset, default_decay, starter_subtasks (micro-missions)
|
||||
|
||||
intensity_modifiers: disaster adds extra subtasks + higher starting entropy or lower initial stability
|
||||
|
||||
Starter templates:
|
||||
|
||||
Garage (finite default)
|
||||
|
||||
Bathroom (background default)
|
||||
|
||||
Kitchen (background default)
|
||||
|
||||
Whole House Reset (finite, multiple zones)
|
||||
|
||||
Office/Desk (background or finite selectable)
|
||||
|
||||
9) Phased Build (so you actually ship it)
|
||||
Phase 0: “Usable Tonight”
|
||||
|
||||
Add project_mode + campaign route
|
||||
|
||||
Zones list with stability bar (computed simply)
|
||||
|
||||
Start/stop session (strike) updates stability
|
||||
|
||||
No photos yet, no nudges
|
||||
|
||||
Phase 1: “Dopamine Injector”
|
||||
|
||||
Before/after photos tied to sessions
|
||||
|
||||
Compare slider immediately after session
|
||||
|
||||
Campaign view defaults for entropy projects
|
||||
|
||||
Phase 2: “Gentle Push”
|
||||
|
||||
Nudge Inbox + simple scheduler (no push)
|
||||
|
||||
Nudge thresholds + per-project window settings
|
||||
|
||||
Phase 3: “Grand Strategy”
|
||||
|
||||
Optional hex-grid visualization (C)
|
||||
|
||||
Zone tiles table + aggregation
|
||||
|
||||
Light “liberation” progress summary per project
|
||||
|
||||
Phase 4: “AI Wizard”
|
||||
|
||||
Replace/augment templates with LLM-generated breakdowns
|
||||
|
||||
Maintain wizard output contract (same JSON schema)
|
||||
|
||||
10) Codex Work Instructions (copy/paste to Codex)
|
||||
Prompt 1 — Backend schema + models
|
||||
|
||||
“Implement Phase 0 backend changes for Break-It-Down:
|
||||
|
||||
Add fields to projects and tasks as specified (project_mode, campaign fields; zone stability fields).
|
||||
|
||||
Add new tables work_sessions and session_photos.
|
||||
|
||||
Update SQLAlchemy models and Pydantic schemas.
|
||||
|
||||
Add endpoints: /api/projects/{id}/zones, /api/sessions/start, /api/sessions/{id}/stop.
|
||||
|
||||
Implement stability calculation and strike boost on stop.
|
||||
|
||||
Ensure existing endpoints still work for standard projects.
|
||||
|
||||
Provide migration approach for SQLite (simple ‘ALTER TABLE’ + create tables).”
|
||||
|
||||
Prompt 2 — Campaign frontend (Phase 0)
|
||||
|
||||
“Implement Campaign view route /projects/:id/campaign:
|
||||
|
||||
Fetch zones via /api/projects/{id}/zones
|
||||
|
||||
Render ZoneCards with stability bar color mapping.
|
||||
|
||||
Add Start Strike flow (start session, timer UI, stop session).
|
||||
|
||||
Ensure 1-tap Start Strike from ZoneCard starts session immediately.
|
||||
|
||||
Keep HQ view unchanged.”
|
||||
|
||||
Prompt 3 — Photos + compare (Phase 1)
|
||||
|
||||
“Add session photo upload and compare slider:
|
||||
|
||||
Backend: /api/sessions/{id}/photos multipart upload; store files under /data/photos with unique paths; return URLs.
|
||||
|
||||
Frontend: After stopping strike, prompt for after photo; show before/after compare slider.
|
||||
|
||||
Add optional before photo prompt at strike start.
|
||||
|
||||
Make it mobile-friendly (use capture attribute).”
|
||||
|
||||
Prompt 4 — Wizard (Phase 1–2)
|
||||
|
||||
“Add New Project Wizard:
|
||||
|
||||
Use local JSON templates to generate project + zones + subtasks.
|
||||
|
||||
Implement backend endpoint /api/wizard/build_project that creates project and tasks from template.
|
||||
|
||||
Wizard should optionally auto-launch campaign and auto-start first strike.”
|
||||
|
||||
Prompt 5 — Nudges (Phase 2)
|
||||
|
||||
“Implement in-app Nudges:
|
||||
|
||||
Backend job that evaluates stability and writes nudge events to DB.
|
||||
|
||||
Frontend Nudge Inbox list and click-through to zone.
|
||||
|
||||
Respect per-project windows, min interval, max/day.”
|
||||
Reference in New Issue
Block a user