feat: 3.0 - Backend API - POST /api/habits (create habit)

This commit is contained in:
Echo
2026-02-10 11:18:48 +00:00
parent fc5ebf2026
commit 3a09e6c51a
2 changed files with 266 additions and 0 deletions

View File

@@ -48,6 +48,8 @@ class TaskBoardHandler(SimpleHTTPRequestHandler):
self.handle_git_commit()
elif self.path == '/api/pdf':
self.handle_pdf_post()
elif self.path == '/api/habits':
self.handle_habits_post()
elif self.path == '/api/workspace/run':
self.handle_workspace_run()
elif self.path == '/api/workspace/stop':
@@ -718,6 +720,66 @@ class TaskBoardHandler(SimpleHTTPRequestHandler):
except Exception as e:
self.send_json({'error': str(e)}, 500)
def handle_habits_post(self):
"""Create a new habit in habits.json."""
try:
# Read POST body
content_length = int(self.headers['Content-Length'])
post_data = self.rfile.read(content_length).decode('utf-8')
data = json.loads(post_data)
# Validate required fields
name = data.get('name', '').strip()
frequency = data.get('frequency', '').strip()
# Validation: name is required
if not name:
self.send_json({'error': 'name is required'}, 400)
return
# Validation: frequency must be daily or weekly
if frequency not in ('daily', 'weekly'):
self.send_json({'error': 'frequency must be daily or weekly'}, 400)
return
# Generate habit ID with millisecond timestamp
from time import time
habit_id = f"habit-{int(time() * 1000)}"
# Create habit object
new_habit = {
'id': habit_id,
'name': name,
'frequency': frequency,
'createdAt': datetime.now().isoformat(),
'completions': []
}
# Read existing habits
habits_file = KANBAN_DIR / 'habits.json'
if habits_file.exists():
try:
habits_data = json.loads(habits_file.read_text(encoding='utf-8'))
except (json.JSONDecodeError, IOError):
habits_data = {'habits': [], 'lastUpdated': datetime.now().isoformat()}
else:
habits_data = {'habits': [], 'lastUpdated': datetime.now().isoformat()}
# Add new habit
habits_data['habits'].append(new_habit)
habits_data['lastUpdated'] = datetime.now().isoformat()
# Write back to file
habits_file.write_text(json.dumps(habits_data, indent=2), encoding='utf-8')
# Return 201 Created with the new habit
self.send_json(new_habit, 201)
except json.JSONDecodeError:
self.send_json({'error': 'Invalid JSON'}, 400)
except Exception as e:
self.send_json({'error': str(e)}, 500)
def handle_files_get(self):
"""List files or get file content."""
from urllib.parse import urlparse, parse_qs