nomadro/apps/api/services/work_svc/store.py
Eric 2b574f7957 Ship native /social/work: Planka-shaped boards + Etherpad pads on FastAPI.
Secondary-dev Next UI with DnD, labels, stopwatch, archive, activity; pads with revisions; README documents pnpm dev:work-api.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-04 01:06:26 +08:00

1092 lines
40 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""
SQLite store — domain shaped after Planka (Project/Board/List/Card) + Etherpad pads.
Secondary-dev reimplementation for Nomadro (not a dump of upstream runtime).
"""
from __future__ import annotations
import json
import sqlite3
import time
import uuid
from pathlib import Path
from typing import Any
from .config import DATA_DIR, DB_PATH
# reuse ebook helper if importable; else local
try:
from ebook_svc.core.sqlite_util import connect as _connect
except Exception: # pragma: no cover
def _connect(path: str | Path, *, timeout: float = 30.0) -> sqlite3.Connection:
p = Path(path)
p.parent.mkdir(parents=True, exist_ok=True)
c = sqlite3.connect(str(p), timeout=timeout)
c.row_factory = sqlite3.Row
c.execute("PRAGMA journal_mode=WAL")
return c
def _now() -> str:
return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
def _id(prefix: str) -> str:
return f"{prefix}_{uuid.uuid4().hex[:10]}"
def _conn() -> sqlite3.Connection:
DATA_DIR.mkdir(parents=True, exist_ok=True)
return _connect(DB_PATH)
def _ensure_column(c: sqlite3.Connection, table: str, column: str, decl: str) -> None:
cols = {r[1] for r in c.execute(f"PRAGMA table_info({table})").fetchall()}
if column not in cols:
c.execute(f"ALTER TABLE {table} ADD COLUMN {column} {decl}")
def init_db() -> None:
with _conn() as c:
c.executescript(
"""
CREATE TABLE IF NOT EXISTS projects (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
description TEXT NOT NULL DEFAULT '',
background_type TEXT DEFAULT 'gradient',
background_gradient TEXT DEFAULT 'ocean-dive',
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS boards (
id TEXT PRIMARY KEY,
project_id TEXT NOT NULL,
name TEXT NOT NULL,
position REAL NOT NULL DEFAULT 0,
default_view TEXT NOT NULL DEFAULT 'kanban',
background_gradient TEXT DEFAULT 'ocean-dive',
show_card_counter INTEGER NOT NULL DEFAULT 1,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
FOREIGN KEY(project_id) REFERENCES projects(id)
);
CREATE TABLE IF NOT EXISTS lists (
id TEXT PRIMARY KEY,
board_id TEXT NOT NULL,
name TEXT NOT NULL,
type TEXT NOT NULL DEFAULT 'active',
position REAL NOT NULL DEFAULT 0,
color TEXT,
FOREIGN KEY(board_id) REFERENCES boards(id)
);
CREATE TABLE IF NOT EXISTS cards (
id TEXT PRIMARY KEY,
list_id TEXT NOT NULL,
board_id TEXT NOT NULL,
name TEXT NOT NULL,
description TEXT NOT NULL DEFAULT '',
type TEXT NOT NULL DEFAULT 'project',
position REAL NOT NULL DEFAULT 0,
due_date TEXT,
is_due_completed INTEGER NOT NULL DEFAULT 0,
stopwatch_json TEXT,
cover_color TEXT,
is_closed INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
FOREIGN KEY(list_id) REFERENCES lists(id),
FOREIGN KEY(board_id) REFERENCES boards(id)
);
CREATE TABLE IF NOT EXISTS attachments (
id TEXT PRIMARY KEY,
card_id TEXT NOT NULL,
name TEXT NOT NULL,
url TEXT NOT NULL,
created_at TEXT NOT NULL,
FOREIGN KEY(card_id) REFERENCES cards(id)
);
CREATE TABLE IF NOT EXISTS pads (
id TEXT PRIMARY KEY,
title TEXT NOT NULL,
text TEXT NOT NULL DEFAULT '',
authors_json TEXT NOT NULL DEFAULT '[]',
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS pad_revisions (
id TEXT PRIMARY KEY,
pad_id TEXT NOT NULL,
author TEXT NOT NULL,
text TEXT NOT NULL,
at TEXT NOT NULL,
FOREIGN KEY(pad_id) REFERENCES pads(id)
);
CREATE TABLE IF NOT EXISTS labels (
id TEXT PRIMARY KEY,
board_id TEXT NOT NULL,
name TEXT,
color TEXT NOT NULL,
position REAL NOT NULL DEFAULT 0,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
FOREIGN KEY(board_id) REFERENCES boards(id)
);
CREATE TABLE IF NOT EXISTS card_labels (
card_id TEXT NOT NULL,
label_id TEXT NOT NULL,
PRIMARY KEY(card_id, label_id),
FOREIGN KEY(card_id) REFERENCES cards(id),
FOREIGN KEY(label_id) REFERENCES labels(id)
);
CREATE TABLE IF NOT EXISTS task_lists (
id TEXT PRIMARY KEY,
card_id TEXT NOT NULL,
name TEXT NOT NULL DEFAULT 'Checklist',
position REAL NOT NULL DEFAULT 0,
FOREIGN KEY(card_id) REFERENCES cards(id)
);
CREATE TABLE IF NOT EXISTS tasks (
id TEXT PRIMARY KEY,
task_list_id TEXT NOT NULL,
name TEXT NOT NULL,
is_completed INTEGER NOT NULL DEFAULT 0,
position REAL NOT NULL DEFAULT 0,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
FOREIGN KEY(task_list_id) REFERENCES task_lists(id)
);
CREATE TABLE IF NOT EXISTS comments (
id TEXT PRIMARY KEY,
card_id TEXT NOT NULL,
author TEXT NOT NULL,
text TEXT NOT NULL,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
FOREIGN KEY(card_id) REFERENCES cards(id)
);
CREATE TABLE IF NOT EXISTS card_members (
card_id TEXT NOT NULL,
name TEXT NOT NULL,
PRIMARY KEY(card_id, name),
FOREIGN KEY(card_id) REFERENCES cards(id)
);
CREATE TABLE IF NOT EXISTS activities (
id TEXT PRIMARY KEY,
board_id TEXT NOT NULL,
card_id TEXT,
actor TEXT NOT NULL DEFAULT 'system',
type TEXT NOT NULL,
data_json TEXT NOT NULL DEFAULT '{}',
created_at TEXT NOT NULL,
FOREIGN KEY(board_id) REFERENCES boards(id)
);
"""
)
# Planka-parity columns for DBs created before this revision
_ensure_column(c, "projects", "background_type", "TEXT DEFAULT 'gradient'")
_ensure_column(c, "projects", "background_gradient", "TEXT DEFAULT 'ocean-dive'")
_ensure_column(c, "boards", "background_gradient", "TEXT DEFAULT 'ocean-dive'")
_ensure_column(c, "boards", "show_card_counter", "INTEGER NOT NULL DEFAULT 1")
_ensure_column(c, "cards", "is_due_completed", "INTEGER NOT NULL DEFAULT 0")
_ensure_column(c, "cards", "stopwatch_json", "TEXT")
_ensure_column(c, "cards", "cover_color", "TEXT")
n = c.execute("SELECT COUNT(*) AS n FROM projects").fetchone()["n"]
if n == 0:
_seed(c)
def _seed(c: sqlite3.Connection) -> None:
t = _now()
pid = _id("proj")
bid = _id("board")
c.execute(
"INSERT INTO projects(id,name,description,background_type,background_gradient,created_at,updated_at) VALUES(?,?,?,?,?,?,?)",
(pid, "Nomadro Remote", "二次开发种子项目(Planka 模型)", "gradient", "ocean-dive", t, t),
)
c.execute(
"INSERT INTO boards(id,project_id,name,position,default_view,background_gradient,show_card_counter,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?,?)",
(bid, pid, "Sprint board", 0, "kanban", "ocean-dive", 1, t, t),
)
lists = [
(_id("list"), "Backlog", "active", 0),
(_id("list"), "Doing", "active", 1),
(_id("list"), "Done", "closed", 2),
(_id("list"), "Archive", "archive", 3),
]
for lid, name, typ, pos in lists:
c.execute(
"INSERT INTO lists(id,board_id,name,type,position) VALUES(?,?,?,?,?)",
(lid, bid, name, typ, pos),
)
c.execute(
"INSERT INTO cards(id,list_id,board_id,name,description,type,position,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?,?)",
(
_id("card"),
lists[1][0],
bid,
"Native Next + FastAPI work module",
"From Planka/Etherpad domain analysis",
"project",
0,
t,
t,
),
)
pad_id = _id("pad")
text = "# Nomadro Pad\n\nEtherpad 模型二次开发 · 修订历史进 FastAPI。\n"
c.execute(
"INSERT INTO pads(id,title,text,authors_json,created_at,updated_at) VALUES(?,?,?,?,?,?)",
(pad_id, "Welcome pad", text, json.dumps(["system"]), t, t),
)
c.execute(
"INSERT INTO pad_revisions(id,pad_id,author,text,at) VALUES(?,?,?,?,?)",
(_id("rev"), pad_id, "system", text, t),
)
def list_projects() -> list[dict[str, Any]]:
with _conn() as c:
rows = c.execute(
"SELECT id,name,description,created_at,updated_at FROM projects ORDER BY updated_at DESC"
).fetchall()
return [dict(r) for r in rows]
def create_project(name: str, description: str = "") -> dict[str, Any]:
t = _now()
pid = _id("proj")
with _conn() as c:
c.execute(
"INSERT INTO projects(id,name,description,background_type,background_gradient,created_at,updated_at) VALUES(?,?,?,?,?,?,?)",
(pid, name.strip() or "Untitled", description.strip(), "gradient", "ocean-dive", t, t),
)
bid = _id("board")
c.execute(
"INSERT INTO boards(id,project_id,name,position,default_view,background_gradient,show_card_counter,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?,?)",
(bid, pid, "Main board", 0, "kanban", "ocean-dive", 1, t, t),
)
for i, (nm, typ) in enumerate(
[
("Backlog", "active"),
("Doing", "active"),
("Done", "closed"),
("Archive", "archive"),
]
):
c.execute(
"INSERT INTO lists(id,board_id,name,type,position) VALUES(?,?,?,?,?)",
(_id("list"), bid, nm, typ, i),
)
return {"id": pid, "name": name, "description": description, "created_at": t, "updated_at": t, "board_id": bid}
def list_boards(project_id: str | None = None) -> list[dict[str, Any]]:
with _conn() as c:
if project_id:
rows = c.execute(
"SELECT id,project_id,name,position,default_view,background_gradient,show_card_counter,created_at,updated_at FROM boards WHERE project_id=? ORDER BY position",
(project_id,),
).fetchall()
else:
rows = c.execute(
"SELECT id,project_id,name,position,default_view,background_gradient,show_card_counter,created_at,updated_at FROM boards ORDER BY updated_at DESC"
).fetchall()
return [dict(r) for r in rows]
def _ensure_board_labels(c: sqlite3.Connection, board_id: str) -> None:
n = c.execute(
"SELECT COUNT(*) AS n FROM labels WHERE board_id=?", (board_id,)
).fetchone()["n"]
if n:
return
t = _now()
defaults = [
("Bug", "berry-red"),
("Feature", "lagoon-blue"),
("Urgent", "pumpkin-orange"),
("Design", "pink-tulip"),
]
for i, (name, color) in enumerate(defaults):
c.execute(
"INSERT INTO labels(id,board_id,name,color,position,created_at,updated_at) VALUES(?,?,?,?,?,?,?)",
(_id("label"), board_id, name, color, i, t, t),
)
def _parse_card_row(r: sqlite3.Row) -> dict[str, Any]:
d = dict(r)
raw = d.pop("stopwatch_json", None)
try:
d["stopwatch"] = json.loads(raw) if raw else None
except Exception:
d["stopwatch"] = None
return d
def get_board(board_id: str) -> dict[str, Any] | None:
with _conn() as c:
b = c.execute(
"SELECT id,project_id,name,position,default_view,background_gradient,show_card_counter,created_at,updated_at FROM boards WHERE id=?",
(board_id,),
).fetchone()
if not b:
return None
_ensure_board_labels(c, board_id)
lists = [
dict(r)
for r in c.execute(
"SELECT id,board_id,name,type,position,color FROM lists WHERE board_id=? ORDER BY position",
(board_id,),
).fetchall()
]
# Ensure archive list exists (Planka ListTypes.ARCHIVE)
if not any(x["type"] == "archive" for x in lists):
pos = max((x["position"] for x in lists), default=-1) + 1
aid = _id("list")
c.execute(
"INSERT INTO lists(id,board_id,name,type,position) VALUES(?,?,?,?,?)",
(aid, board_id, "Archive", "archive", pos),
)
lists.append(
{
"id": aid,
"board_id": board_id,
"name": "Archive",
"type": "archive",
"position": pos,
"color": None,
}
)
cards = [
_parse_card_row(r)
for r in c.execute(
"SELECT id,list_id,board_id,name,description,type,position,due_date,is_due_completed,stopwatch_json,cover_color,is_closed,created_at,updated_at FROM cards WHERE board_id=? ORDER BY position",
(board_id,),
).fetchall()
]
labels = [
dict(r)
for r in c.execute(
"SELECT id,board_id,name,color,position FROM labels WHERE board_id=? ORDER BY position",
(board_id,),
).fetchall()
]
card_ids = [x["id"] for x in cards]
card_labels: list[dict[str, Any]] = []
task_lists: list[dict[str, Any]] = []
tasks: list[dict[str, Any]] = []
comments: list[dict[str, Any]] = []
card_members: list[dict[str, Any]] = []
if card_ids:
qmarks = ",".join("?" * len(card_ids))
card_labels = [
dict(r)
for r in c.execute(
f"SELECT card_id,label_id FROM card_labels WHERE card_id IN ({qmarks})",
card_ids,
).fetchall()
]
task_lists = [
dict(r)
for r in c.execute(
f"SELECT id,card_id,name,position FROM task_lists WHERE card_id IN ({qmarks}) ORDER BY position",
card_ids,
).fetchall()
]
tl_ids = [t["id"] for t in task_lists]
if tl_ids:
tqm = ",".join("?" * len(tl_ids))
tasks = [
dict(r)
for r in c.execute(
f"SELECT id,task_list_id,name,is_completed,position,created_at,updated_at FROM tasks WHERE task_list_id IN ({tqm}) ORDER BY position",
tl_ids,
).fetchall()
]
comments = [
dict(r)
for r in c.execute(
f"SELECT id,card_id,author,text,created_at,updated_at FROM comments WHERE card_id IN ({qmarks}) ORDER BY created_at",
card_ids,
).fetchall()
]
card_members = [
dict(r)
for r in c.execute(
f"SELECT card_id,name FROM card_members WHERE card_id IN ({qmarks})",
card_ids,
).fetchall()
]
attachments: list[dict[str, Any]] = []
if card_ids:
attachments = [
dict(r)
for r in c.execute(
f"SELECT id,card_id,name,url,created_at FROM attachments WHERE card_id IN ({qmarks}) ORDER BY created_at",
card_ids,
).fetchall()
]
activities = [
{
**dict(r),
"data": json.loads(r["data_json"] or "{}"),
}
for r in c.execute(
"SELECT id,board_id,card_id,actor,type,data_json,created_at FROM activities WHERE board_id=? ORDER BY created_at DESC LIMIT 40",
(board_id,),
).fetchall()
]
for a in activities:
a.pop("data_json", None)
out = dict(b)
out["lists"] = lists
out["cards"] = cards
out["labels"] = labels
out["card_labels"] = card_labels
out["task_lists"] = task_lists
out["tasks"] = tasks
out["comments"] = comments
out["card_members"] = card_members
out["attachments"] = attachments
out["activities"] = activities
return out
def _activity(
c: sqlite3.Connection,
board_id: str,
typ: str,
*,
card_id: str | None = None,
actor: str = "system",
data: dict[str, Any] | None = None,
) -> None:
c.execute(
"INSERT INTO activities(id,board_id,card_id,actor,type,data_json,created_at) VALUES(?,?,?,?,?,?,?)",
(
_id("act"),
board_id,
card_id,
actor,
typ,
json.dumps(data or {}),
_now(),
),
)
def create_board(project_id: str, name: str) -> dict[str, Any]:
t = _now()
bid = _id("board")
with _conn() as c:
pos = c.execute(
"SELECT COALESCE(MAX(position),-1)+1 AS p FROM boards WHERE project_id=?",
(project_id,),
).fetchone()["p"]
c.execute(
"INSERT INTO boards(id,project_id,name,position,default_view,background_gradient,show_card_counter,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?,?)",
(bid, project_id, name.strip() or "Board", pos, "kanban", "ocean-dive", 1, t, t),
)
for i, (nm, typ) in enumerate(
[
("Backlog", "active"),
("Doing", "active"),
("Done", "closed"),
("Archive", "archive"),
]
):
c.execute(
"INSERT INTO lists(id,board_id,name,type,position) VALUES(?,?,?,?,?)",
(_id("list"), bid, nm, typ, i),
)
c.execute("UPDATE projects SET updated_at=? WHERE id=?", (t, project_id))
return get_board(bid) # type: ignore
def add_list(board_id: str, name: str, typ: str = "active") -> dict[str, Any] | None:
with _conn() as c:
if not c.execute("SELECT 1 FROM boards WHERE id=?", (board_id,)).fetchone():
return None
pos = c.execute(
"SELECT COALESCE(MAX(position),-1)+1 AS p FROM lists WHERE board_id=?",
(board_id,),
).fetchone()["p"]
lid = _id("list")
c.execute(
"INSERT INTO lists(id,board_id,name,type,position) VALUES(?,?,?,?,?)",
(lid, board_id, name.strip() or "List", typ, pos),
)
c.execute("UPDATE boards SET updated_at=? WHERE id=?", (_now(), board_id))
return get_board(board_id)
def add_card(board_id: str, list_id: str, name: str, description: str = "") -> dict[str, Any] | None:
t = _now()
with _conn() as c:
if not c.execute(
"SELECT 1 FROM lists WHERE id=? AND board_id=?", (list_id, board_id)
).fetchone():
return None
pos = c.execute(
"SELECT COALESCE(MAX(position),-1)+1 AS p FROM cards WHERE list_id=?",
(list_id,),
).fetchone()["p"]
cid = _id("card")
cname = name.strip() or "Card"
c.execute(
"INSERT INTO cards(id,list_id,board_id,name,description,type,position,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?,?)",
(cid, list_id, board_id, cname, description.strip(), "project", pos, t, t),
)
_activity(
c,
board_id,
"createCard",
card_id=cid,
data={"card": {"name": cname}, "listId": list_id},
)
c.execute("UPDATE boards SET updated_at=? WHERE id=?", (t, board_id))
return get_board(board_id)
def update_card(
board_id: str,
card_id: str,
*,
name: str | None = None,
description: str | None = None,
due_date: str | None = None,
clear_due: bool = False,
is_due_completed: bool | None = None,
cover_color: str | None = None,
clear_cover: bool = False,
) -> dict[str, Any] | None:
t = _now()
with _conn() as c:
card = c.execute(
"SELECT * FROM cards WHERE id=? AND board_id=?", (card_id, board_id)
).fetchone()
if not card:
return None
new_name = name.strip() if name is not None else card["name"]
new_desc = description if description is not None else card["description"]
if name is not None and not new_name:
new_name = card["name"]
new_due = card["due_date"]
if clear_due:
new_due = None
elif due_date is not None:
new_due = due_date or None
due_done = (
int(bool(is_due_completed))
if is_due_completed is not None
else card["is_due_completed"]
)
cover = card["cover_color"] if "cover_color" in card.keys() else None
if clear_cover:
cover = None
elif cover_color is not None:
cover = cover_color or None
c.execute(
"UPDATE cards SET name=?, description=?, due_date=?, is_due_completed=?, cover_color=?, updated_at=? WHERE id=?",
(new_name, new_desc or "", new_due, due_done, cover, t, card_id),
)
c.execute("UPDATE boards SET updated_at=? WHERE id=?", (t, board_id))
return get_board(board_id)
def update_board(
board_id: str,
*,
name: str | None = None,
background_gradient: str | None = None,
show_card_counter: bool | None = None,
) -> dict[str, Any] | None:
t = _now()
with _conn() as c:
b = c.execute("SELECT * FROM boards WHERE id=?", (board_id,)).fetchone()
if not b:
return None
new_name = name.strip() if name is not None else b["name"]
if name is not None and not new_name:
new_name = b["name"]
grad = (
background_gradient
if background_gradient is not None
else b["background_gradient"]
)
counter = (
int(bool(show_card_counter))
if show_card_counter is not None
else b["show_card_counter"]
)
c.execute(
"UPDATE boards SET name=?, background_gradient=?, show_card_counter=?, updated_at=? WHERE id=?",
(new_name, grad, counter, t, board_id),
)
return get_board(board_id)
def toggle_stopwatch(board_id: str, card_id: str) -> dict[str, Any] | None:
"""Planka startStopwatch / stopStopwatch parity."""
t = _now()
with _conn() as c:
card = c.execute(
"SELECT * FROM cards WHERE id=? AND board_id=?", (card_id, board_id)
).fetchone()
if not card:
return None
try:
sw = json.loads(card["stopwatch_json"] or "null") or {
"startedAt": None,
"total": 0,
}
except Exception:
sw = {"startedAt": None, "total": 0}
if sw.get("startedAt"):
started = time.strptime(sw["startedAt"], "%Y-%m-%dT%H:%M:%SZ")
elapsed = int(time.mktime(time.gmtime()) - time.mktime(started))
# started was UTC via strptime without tz — use fromisoformat style
try:
from datetime import datetime, timezone
started_dt = datetime.strptime(
sw["startedAt"], "%Y-%m-%dT%H:%M:%SZ"
).replace(tzinfo=timezone.utc)
elapsed = int((datetime.now(timezone.utc) - started_dt).total_seconds())
except Exception:
elapsed = max(0, elapsed)
sw = {"startedAt": None, "total": int(sw.get("total") or 0) + max(0, elapsed)}
else:
sw = {"startedAt": t, "total": int(sw.get("total") or 0)}
c.execute(
"UPDATE cards SET stopwatch_json=?, updated_at=? WHERE id=?",
(json.dumps(sw), t, card_id),
)
c.execute("UPDATE boards SET updated_at=? WHERE id=?", (t, board_id))
return get_board(board_id)
def add_attachment(
board_id: str, card_id: str, name: str, url: str
) -> dict[str, Any] | None:
t = _now()
with _conn() as c:
if not c.execute(
"SELECT 1 FROM cards WHERE id=? AND board_id=?", (card_id, board_id)
).fetchone():
return None
c.execute(
"INSERT INTO attachments(id,card_id,name,url,created_at) VALUES(?,?,?,?,?)",
(
_id("att"),
card_id,
(name or "Link").strip() or "Link",
url.strip(),
t,
),
)
c.execute("UPDATE boards SET updated_at=? WHERE id=?", (t, board_id))
return get_board(board_id)
def delete_attachment(board_id: str, attachment_id: str) -> dict[str, Any] | None:
with _conn() as c:
row = c.execute(
"SELECT a.id, a.card_id FROM attachments a JOIN cards c ON c.id=a.card_id WHERE a.id=? AND c.board_id=?",
(attachment_id, board_id),
).fetchone()
if not row:
return None
c.execute("DELETE FROM attachments WHERE id=?", (attachment_id,))
c.execute("UPDATE boards SET updated_at=? WHERE id=?", (_now(), board_id))
return get_board(board_id)
def archive_card(board_id: str, card_id: str) -> dict[str, Any] | None:
"""Move card into Archive list (Planka moveCurrentCardToArchive)."""
with _conn() as c:
card = c.execute(
"SELECT * FROM cards WHERE id=? AND board_id=?", (card_id, board_id)
).fetchone()
if not card:
return None
arch = c.execute(
"SELECT id FROM lists WHERE board_id=? AND type='archive' ORDER BY position LIMIT 1",
(board_id,),
).fetchone()
if not arch:
return None
list_id = arch["id"]
return move_card(board_id, card_id, list_id, 0)
def move_list(board_id: str, list_id: str, position: int) -> dict[str, Any] | None:
with _conn() as c:
if not c.execute(
"SELECT 1 FROM lists WHERE id=? AND board_id=?", (list_id, board_id)
).fetchone():
return None
others = c.execute(
"SELECT id FROM lists WHERE board_id=? AND id!=? ORDER BY position",
(board_id, list_id),
).fetchall()
ids = [r["id"] for r in others]
pos = max(0, min(int(position), len(ids)))
ids.insert(pos, list_id)
for i, lid in enumerate(ids):
c.execute("UPDATE lists SET position=? WHERE id=?", (i, lid))
c.execute("UPDATE boards SET updated_at=? WHERE id=?", (_now(), board_id))
return get_board(board_id)
def toggle_card_label(board_id: str, card_id: str, label_id: str) -> dict[str, Any] | None:
with _conn() as c:
if not c.execute(
"SELECT 1 FROM cards WHERE id=? AND board_id=?", (card_id, board_id)
).fetchone():
return None
if not c.execute(
"SELECT 1 FROM labels WHERE id=? AND board_id=?", (label_id, board_id)
).fetchone():
return None
hit = c.execute(
"SELECT 1 FROM card_labels WHERE card_id=? AND label_id=?",
(card_id, label_id),
).fetchone()
if hit:
c.execute(
"DELETE FROM card_labels WHERE card_id=? AND label_id=?",
(card_id, label_id),
)
else:
c.execute(
"INSERT INTO card_labels(card_id,label_id) VALUES(?,?)",
(card_id, label_id),
)
c.execute("UPDATE boards SET updated_at=? WHERE id=?", (_now(), board_id))
return get_board(board_id)
def ensure_task_list(card_id: str) -> str:
with _conn() as c:
row = c.execute(
"SELECT id FROM task_lists WHERE card_id=? ORDER BY position LIMIT 1",
(card_id,),
).fetchone()
if row:
return row["id"]
tid = _id("tlist")
c.execute(
"INSERT INTO task_lists(id,card_id,name,position) VALUES(?,?,?,?)",
(tid, card_id, "Checklist", 0),
)
return tid
def add_task(board_id: str, card_id: str, name: str) -> dict[str, Any] | None:
t = _now()
with _conn() as c:
if not c.execute(
"SELECT 1 FROM cards WHERE id=? AND board_id=?", (card_id, board_id)
).fetchone():
return None
tl = ensure_task_list(card_id)
with _conn() as c:
pos = c.execute(
"SELECT COALESCE(MAX(position),-1)+1 AS p FROM tasks WHERE task_list_id=?",
(tl,),
).fetchone()["p"]
c.execute(
"INSERT INTO tasks(id,task_list_id,name,is_completed,position,created_at,updated_at) VALUES(?,?,?,?,?,?,?)",
(_id("task"), tl, name.strip() or "Task", 0, pos, t, t),
)
c.execute("UPDATE boards SET updated_at=? WHERE id=?", (t, board_id))
return get_board(board_id)
def toggle_task(board_id: str, task_id: str) -> dict[str, Any] | None:
t = _now()
with _conn() as c:
task = c.execute("SELECT * FROM tasks WHERE id=?", (task_id,)).fetchone()
if not task:
return None
done = 0 if task["is_completed"] else 1
c.execute(
"UPDATE tasks SET is_completed=?, updated_at=? WHERE id=?",
(done, t, task_id),
)
tl = c.execute(
"SELECT card_id FROM task_lists WHERE id=?", (task["task_list_id"],)
).fetchone()
_activity(
c,
board_id,
"completeTask" if done else "uncompleteTask",
card_id=tl["card_id"] if tl else None,
data={"task": {"id": task_id, "name": task["name"]}},
)
c.execute("UPDATE boards SET updated_at=? WHERE id=?", (t, board_id))
return get_board(board_id)
def add_comment(board_id: str, card_id: str, author: str, text: str) -> dict[str, Any] | None:
t = _now()
with _conn() as c:
if not c.execute(
"SELECT 1 FROM cards WHERE id=? AND board_id=?", (card_id, board_id)
).fetchone():
return None
who = (author or "guest").strip() or "guest"
c.execute(
"INSERT INTO comments(id,card_id,author,text,created_at,updated_at) VALUES(?,?,?,?,?,?)",
(_id("cmt"), card_id, who, text.strip(), t, t),
)
_activity(
c,
board_id,
"comment",
card_id=card_id,
actor=who,
data={"text": text.strip()[:120]},
)
c.execute("UPDATE boards SET updated_at=? WHERE id=?", (t, board_id))
return get_board(board_id)
def update_list(
board_id: str,
list_id: str,
*,
name: str | None = None,
color: str | None = None,
) -> dict[str, Any] | None:
with _conn() as c:
row = c.execute(
"SELECT * FROM lists WHERE id=? AND board_id=?", (list_id, board_id)
).fetchone()
if not row:
return None
new_name = name.strip() if name is not None else row["name"]
if name is not None and not new_name:
new_name = row["name"]
new_color = color if color is not None else row["color"]
c.execute(
"UPDATE lists SET name=?, color=? WHERE id=?",
(new_name, new_color, list_id),
)
c.execute("UPDATE boards SET updated_at=? WHERE id=?", (_now(), board_id))
return get_board(board_id)
def delete_list(board_id: str, list_id: str) -> dict[str, Any] | None:
with _conn() as c:
if not c.execute(
"SELECT 1 FROM lists WHERE id=? AND board_id=?", (list_id, board_id)
).fetchone():
return None
cards = c.execute(
"SELECT id FROM cards WHERE list_id=?", (list_id,)
).fetchall()
for card in cards:
cid = card["id"]
c.execute("DELETE FROM card_labels WHERE card_id=?", (cid,))
c.execute("DELETE FROM card_members WHERE card_id=?", (cid,))
c.execute("DELETE FROM comments WHERE card_id=?", (cid,))
tls = c.execute(
"SELECT id FROM task_lists WHERE card_id=?", (cid,)
).fetchall()
for tl in tls:
c.execute("DELETE FROM tasks WHERE task_list_id=?", (tl["id"],))
c.execute("DELETE FROM task_lists WHERE card_id=?", (cid,))
c.execute("DELETE FROM cards WHERE list_id=?", (list_id,))
c.execute("DELETE FROM lists WHERE id=?", (list_id,))
_activity(c, board_id, "delete_list", data={"list_id": list_id})
c.execute("UPDATE boards SET updated_at=? WHERE id=?", (_now(), board_id))
return get_board(board_id)
def delete_card(board_id: str, card_id: str) -> dict[str, Any] | None:
with _conn() as c:
if not c.execute(
"SELECT 1 FROM cards WHERE id=? AND board_id=?", (card_id, board_id)
).fetchone():
return None
c.execute("DELETE FROM card_labels WHERE card_id=?", (card_id,))
c.execute("DELETE FROM card_members WHERE card_id=?", (card_id,))
c.execute("DELETE FROM comments WHERE card_id=?", (card_id,))
tls = c.execute(
"SELECT id FROM task_lists WHERE card_id=?", (card_id,)
).fetchall()
for tl in tls:
c.execute("DELETE FROM tasks WHERE task_list_id=?", (tl["id"],))
c.execute("DELETE FROM task_lists WHERE card_id=?", (card_id,))
c.execute("DELETE FROM cards WHERE id=?", (card_id,))
_activity(c, board_id, "delete_card", card_id=card_id)
c.execute("UPDATE boards SET updated_at=? WHERE id=?", (_now(), board_id))
return get_board(board_id)
def toggle_card_member(board_id: str, card_id: str, name: str) -> dict[str, Any] | None:
who = (name or "").strip()
if not who:
return None
with _conn() as c:
if not c.execute(
"SELECT 1 FROM cards WHERE id=? AND board_id=?", (card_id, board_id)
).fetchone():
return None
hit = c.execute(
"SELECT 1 FROM card_members WHERE card_id=? AND name=?",
(card_id, who),
).fetchone()
if hit:
c.execute(
"DELETE FROM card_members WHERE card_id=? AND name=?",
(card_id, who),
)
act = "removeMemberFromCard"
else:
c.execute(
"INSERT INTO card_members(card_id,name) VALUES(?,?)",
(card_id, who),
)
act = "addMemberToCard"
_activity(
c,
board_id,
act,
card_id=card_id,
actor=who,
data={"name": who},
)
c.execute("UPDATE boards SET updated_at=? WHERE id=?", (_now(), board_id))
return get_board(board_id)
def move_card(board_id: str, card_id: str, list_id: str, position: int) -> dict[str, Any] | None:
t = _now()
with _conn() as c:
card = c.execute(
"SELECT * FROM cards WHERE id=? AND board_id=?", (card_id, board_id)
).fetchone()
if not card:
return None
if not c.execute(
"SELECT 1 FROM lists WHERE id=? AND board_id=?", (list_id, board_id)
).fetchone():
return None
from_list = card["list_id"]
others = c.execute(
"SELECT id FROM cards WHERE list_id=? AND id!=? ORDER BY position",
(list_id, card_id),
).fetchall()
ids = [r["id"] for r in others]
pos = max(0, min(int(position), len(ids)))
ids.insert(pos, card_id)
c.execute(
"UPDATE cards SET list_id=?, updated_at=? WHERE id=?",
(list_id, t, card_id),
)
for i, cid in enumerate(ids):
c.execute("UPDATE cards SET position=? WHERE id=?", (i, cid))
if from_list != list_id:
rest = c.execute(
"SELECT id FROM cards WHERE list_id=? ORDER BY position", (from_list,)
).fetchall()
for i, r in enumerate(rest):
c.execute("UPDATE cards SET position=? WHERE id=?", (i, r["id"]))
_activity(
c,
board_id,
"moveCard",
card_id=card_id,
data={
"fromList": {"id": from_list},
"toList": {"id": list_id},
"position": position,
},
)
c.execute("UPDATE boards SET updated_at=? WHERE id=?", (t, board_id))
return get_board(board_id)
def list_pads() -> list[dict[str, Any]]:
with _conn() as c:
rows = c.execute(
"SELECT id,title,authors_json,created_at,updated_at FROM pads ORDER BY updated_at DESC"
).fetchall()
out = []
for r in rows:
d = dict(r)
d["authors"] = json.loads(d.pop("authors_json") or "[]")
out.append(d)
return out
def get_pad(pad_id: str) -> dict[str, Any] | None:
with _conn() as c:
p = c.execute(
"SELECT id,title,text,authors_json,created_at,updated_at FROM pads WHERE id=?",
(pad_id,),
).fetchone()
if not p:
return None
revs = [
dict(r)
for r in c.execute(
"SELECT id,author,text,at FROM pad_revisions WHERE pad_id=? ORDER BY at DESC LIMIT 40",
(pad_id,),
).fetchall()
]
d = dict(p)
d["authors"] = json.loads(d.pop("authors_json") or "[]")
d["revisions"] = list(reversed(revs))
return d
def create_pad(title: str, author: str = "guest") -> dict[str, Any]:
t = _now()
pid = _id("pad")
author = (author or "guest").strip() or "guest"
with _conn() as c:
c.execute(
"INSERT INTO pads(id,title,text,authors_json,created_at,updated_at) VALUES(?,?,?,?,?,?)",
(pid, title.strip() or "Untitled", "", json.dumps([author]), t, t),
)
c.execute(
"INSERT INTO pad_revisions(id,pad_id,author,text,at) VALUES(?,?,?,?,?)",
(_id("rev"), pid, author, "", t),
)
return get_pad(pid) # type: ignore
def update_pad(pad_id: str, text: str, author: str = "guest", title: str | None = None) -> dict[str, Any] | None:
t = _now()
author = (author or "guest").strip() or "guest"
with _conn() as c:
p = c.execute("SELECT * FROM pads WHERE id=?", (pad_id,)).fetchone()
if not p:
return None
authors = json.loads(p["authors_json"] or "[]")
if author not in authors:
authors.append(author)
new_title = title.strip() if title and title.strip() else p["title"]
c.execute(
"UPDATE pads SET title=?, text=?, authors_json=?, updated_at=? WHERE id=?",
(new_title, text, json.dumps(authors), t, pad_id),
)
c.execute(
"INSERT INTO pad_revisions(id,pad_id,author,text,at) VALUES(?,?,?,?,?)",
(_id("rev"), pad_id, author, text, t),
)
# trim
old = c.execute(
"SELECT id FROM pad_revisions WHERE pad_id=? ORDER BY at DESC",
(pad_id,),
).fetchall()
for r in old[40:]:
c.execute("DELETE FROM pad_revisions WHERE id=?", (r["id"],))
return get_pad(pad_id)