ParamsParser) -> str:
"""Show single Todo of ?id=."""
id_ = params.get_int_or_none('id')
- if id_ is None:
- raise NotFoundException('Todo of ID not found.')
todo = Todo.by_id(conn, id_)
- return self.server.jinja.get_template('todo.html').render(todo=todo)
+ candidates = Todo.by_date(conn, todo.day.date)
+ return self.server.jinja.get_template('todo.html').render(
+ todo=todo, candidates=candidates)
def do_GET_process(self, conn: DatabaseConnection,
params: ParamsParser) -> str:
postvars = parse_qs(self.rfile.read(length).decode(),
keep_blank_values=True, strict_parsing=True)
form_data = PostvarsParser(postvars)
- if site in ('day', 'process'):
+ if site in ('day', 'process', 'todo'):
getattr(self, f'do_POST_{site}')(conn, params, form_data)
conn.commit()
else:
todo = Todo(None, process, False, day)
todo.save(conn)
+ def do_POST_todo(self, conn: DatabaseConnection, params: ParamsParser,
+ form_data: PostvarsParser) -> None:
+ """Update Todo and its children."""
+ id_ = params.get_int_or_none('id')
+ todo = Todo.by_id(conn, id_)
+ child_id = form_data.get_int_or_none('adopt')
+ if child_id is not None:
+ child = Todo.by_id(conn, child_id)
+ todo.add_child(child)
+ todo.save(conn)
+
def do_POST_process(self, conn: DatabaseConnection, params: ParamsParser,
form_data: PostvarsParser) -> None:
"""Update or insert Process of ?id= and fields defined in postvars."""
from plomtask.db import DatabaseConnection
from plomtask.days import Day
from plomtask.processes import Process
-from plomtask.exceptions import NotFoundException
+from plomtask.exceptions import (NotFoundException, BadFormatException,
+ HandledException)
class Todo:
self.process = process
self.is_done = is_done
self.day = day
+ self.children: list[Todo] = []
@classmethod
def from_table_row(cls, db_conn: DatabaseConnection, row: Row) -> Todo:
return todo
@classmethod
- def by_id(cls, db_conn: DatabaseConnection, id_: int) -> Todo:
- """Get Todo of .id_=id_ – from DB cache if possible."""
+ def by_id(cls, db_conn: DatabaseConnection, id_: int | None) -> Todo:
+ """Get Todo of .id_=id_ and children (from DB cache if possible)."""
if id_ in db_conn.cached_todos.keys():
todo = db_conn.cached_todos[id_]
- assert isinstance(todo, Todo)
- return todo
- for row in db_conn.exec('SELECT * FROM todos WHERE id = ?', (id_,)):
- return cls.from_table_row(db_conn, row)
- raise NotFoundException(f'Todo of ID not found: {id_}')
+ else:
+ todo = None
+ for row in db_conn.exec('SELECT * FROM todos WHERE id = ?',
+ (id_,)):
+ todo = cls.from_table_row(db_conn, row)
+ break
+ if todo is None:
+ raise NotFoundException(f'Todo of ID not found: {id_}')
+ for row in db_conn.exec('SELECT child FROM todo_children '
+ 'WHERE parent = ?', (id_,)):
+ todo.children += [cls.by_id(db_conn, row[0])]
+ assert isinstance(todo, Todo)
+ return todo
@classmethod
def by_date(cls, db_conn: DatabaseConnection, date: str) -> list[Todo]:
todos += [cls.by_id(db_conn, row[0])]
return todos
+ def add_child(self, child: Todo) -> None:
+ """Add child to self.children, guard against recursion"""
+ def walk_steps(node: Todo) -> None:
+ if node.id_ == self.id_:
+ raise BadFormatException('bad child choice causes recursion')
+ for child in node.children:
+ walk_steps(child)
+ if self.id_ is None:
+ raise HandledException('Can only add children to saved Todos.')
+ if child.id_ is None:
+ raise HandledException('Can only add saved children to Todos.')
+ if child in self.children:
+ raise BadFormatException('cannot adopt same child twice')
+ walk_steps(child)
+ self.children += [child]
+
def save(self, db_conn: DatabaseConnection) -> None:
- """Write self to DB and its cache."""
+ """Write self and children to DB and its cache."""
if self.process.id_ is None:
raise NotFoundException('Process of Todo without ID (not saved?)')
cursor = db_conn.exec('REPLACE INTO todos VALUES (?,?,?,?)',
self.id_ = cursor.lastrowid
assert self.id_ is not None
db_conn.cached_todos[self.id_] = self
+ db_conn.exec('DELETE FROM todo_children WHERE parent = ?',
+ (self.id_,))
+ for child in self.children:
+ db_conn.exec('INSERT INTO todo_children VALUES (?, ?)',
+ (self.id_, child.id_))
CREATE TABLE processes (
id INTEGER PRIMARY KEY
);
+CREATE TABLE todo_children (
+ parent INTEGER NOT NULL,
+ child INTEGER NOT NULL,
+ PRIMARY KEY (parent, child),
+ FOREIGN KEY (parent) REFERENCES todos(id),
+ FOREIGN KEY (child) REFERENCES todos(id)
+);
CREATE TABLE todos (
id INTEGER PRIMARY KEY,
process_id INTEGER NOT NULL,
{% extends 'base.html' %}
+{% macro todo_with_children(todo, indent) %}
+<li>{% for i in range(indent) %}+{% endfor %}<a href="todo?id={{todo.id_}}">{{todo.process.title.newest|e}}</a>
+{% for child in todo.children %}
+{{ todo_with_children(child, indent+1) }}
+{% endfor %}
+{% endmacro %}
+
{% block content %}
<h3>{{day.date}} / {{day.weekday}}</h3>
<p>
</form>
<ul>
{% for todo in todos %}
-<li><a href="todo?id={{todo.id_}}">{{todo.process.title.newest|e}}</a>
+{{ todo_with_children(todo, 0) }}
{% endfor %}
</ul>
{% endblock %}
from plomtask.todos import Todo
from plomtask.days import Day
from plomtask.processes import Process
-from plomtask.exceptions import NotFoundException
+from plomtask.exceptions import (NotFoundException, BadFormatException,
+ HandledException)
class TestsWithDB(TestCaseWithDB):
self.assertEqual(Todo.by_date(self.db_conn, day2.date), [])
self.assertEqual(Todo.by_date(self.db_conn, 'foo'), [])
+ def test_Todo_children(self) -> None:
+ """Test Todo.children relations."""
+ day = Day('2024-01-01')
+ process = Process(None)
+ process.save_without_steps(self.db_conn)
+ todo_1 = Todo(None, process, False, day)
+ todo_2 = Todo(None, process, False, day)
+ with self.assertRaises(HandledException):
+ todo_1.add_child(todo_2)
+ todo_1.save(self.db_conn)
+ with self.assertRaises(HandledException):
+ todo_1.add_child(todo_2)
+ todo_2.save(self.db_conn)
+ todo_1.add_child(todo_2)
+ todo_1.save(self.db_conn)
+ todo_retrieved = Todo.by_id(self.db_conn, todo_1.id_)
+ self.assertEqual(todo_retrieved.children, [todo_2])
+ with self.assertRaises(BadFormatException):
+ todo_2.add_child(todo_1)
+
def test_Todo_singularity(self) -> None:
"""Test pointers made for single object keep pointing to it."""
day = Day('2024-01-01')
class TestsWithServer(TestCaseWithServer):
"""Tests against our HTTP server/handler (and database)."""
- def test_do_POST_todo(self) -> None:
+ def test_do_POST_day(self) -> None:
"""Test Todo posting of POST /day."""
form_data = {'title': '', 'description': '', 'effort': 1}
self.check_post(form_data, '/process?id=', 302, '/')
self.assertEqual(todo1.process.id_, process2.id_)
self.assertEqual(todo1.is_done, False)
+ def test_do_POST_todo(self) -> None:
+ """Test POST /todo."""
+ form_data = {'title': '', 'description': '', 'effort': 1}
+ self.check_post(form_data, '/process', 302, '/')
+ form_data = {'comment': '', 'new_todo': 1}
+ self.check_post(form_data, '/day?date=2024-01-01', 302, '/')
+ form_data = {}
+ self.check_post(form_data, '/todo=', 404)
+ self.check_post(form_data, '/todo?id=', 404)
+ self.check_post(form_data, '/todo?id=FOO', 400)
+ self.check_post(form_data, '/todo?id=0', 404)
+ self.check_post(form_data, '/todo?id=1', 302, '/')
+ todo1 = Todo.by_date(self.db_conn, '2024-01-01')[0]
+ self.assertEqual(todo1.children, [])
+ form_data = {'adopt': 'foo'}
+ self.check_post(form_data, '/todo?id=1', 400)
+ form_data = {'adopt': 1}
+ self.check_post(form_data, '/todo?id=1', 400)
+ form_data = {'adopt': 2}
+ self.check_post(form_data, '/todo?id=1', 404)
+ form_data = {'comment': '', 'new_todo': 1}
+ self.check_post(form_data, '/day?date=2024-01-01', 302, '/')
+ form_data = {'adopt': 2}
+ self.check_post(form_data, '/todo?id=1', 302, '/')
+ self.db_conn.cached_todos = {}
+ todo1 = Todo.by_date(self.db_conn, '2024-01-01')[0]
+ todo2 = Todo.by_date(self.db_conn, '2024-01-01')[1]
+ self.assertEqual(todo1.children, [todo2])
+ self.check_post(form_data, '/todo?id=1', 400, '/')
+
def test_do_GET_todo(self) -> None:
"""Test GET /todo response codes."""
form_data = {'title': '', 'description': '', 'effort': 1}