From 3a12d56f8b460973a823eb4e79b0048e43728a18 Mon Sep 17 00:00:00 2001 From: Joren de Graaf Date: Thu, 22 Oct 2026 10:24:33 +0200 Subject: [PATCH] latest changes --- codex-usage.py | 240 ++++++++++++++++++ dashboard/codex_usage.py | 85 +++++++ dashboard/registry.py | 1 + dashboard/static/dashboard/builder.js | 20 +- dashboard/static/dashboard/codex_usage.css | 1 + dashboard/static/dashboard/codex_usage.js | 26 ++ dashboard/templates/dashboard/index.html | 5 +- .../dashboard/widgets/_codex_usage_panel.html | 5 + .../dashboard/widgets/codex_usage.html | 6 + dashboard/tests.py | 31 +++ dashboard/urls.py | 3 +- dashboard/views.py | 7 + docs/card-attachments.md | 2 +- docs/codex-usage-widget.md | 9 + docs/project-board.md | 19 ++ mcp_server/server.py | 27 +- projects/migrations/0007_projectmovekey.py | 30 +++ projects/models.py | 11 + projects/services.py | 97 ++++++- projects/static/projects/board_mobile.css | 7 + projects/static/projects/card_detail.css | 6 + projects/static/projects/card_move.css | 1 + projects/static/projects/card_move.js | 47 ++++ projects/static/projects/project_list.css | 5 + projects/templates/projects/_board.html | 3 +- .../templates/projects/_project_list.html | 12 +- projects/templates/projects/board.html | 159 ++++++++---- projects/templates/projects/card.html | 57 ++++- projects/templates/projects/list.html | 17 +- projects/test_oauth_mcp.py | 42 ++- projects/tests.py | 215 +++++++++++++++- projects/urls.py | 1 + projects/views.py | 78 +++++- 33 files changed, 1179 insertions(+), 96 deletions(-) create mode 100644 codex-usage.py create mode 100644 dashboard/codex_usage.py create mode 100644 dashboard/static/dashboard/codex_usage.css create mode 100644 dashboard/static/dashboard/codex_usage.js create mode 100644 dashboard/templates/dashboard/widgets/_codex_usage_panel.html create mode 100644 dashboard/templates/dashboard/widgets/codex_usage.html create mode 100644 docs/codex-usage-widget.md create mode 100644 docs/project-board.md create mode 100644 projects/migrations/0007_projectmovekey.py create mode 100644 projects/static/projects/board_mobile.css create mode 100644 projects/static/projects/card_detail.css create mode 100644 projects/static/projects/card_move.css create mode 100644 projects/static/projects/card_move.js create mode 100644 projects/static/projects/project_list.css diff --git a/codex-usage.py b/codex-usage.py new file mode 100644 index 0000000..3580fc3 --- /dev/null +++ b/codex-usage.py @@ -0,0 +1,240 @@ +#!/usr/bin/env python3 +"""Portable, dependency-free Codex usage display (Python 3.8+).""" + +import argparse +import datetime as dt +import json +import math +import os +import tempfile +import hashlib +import shutil +import sys +import time +import urllib.error +import urllib.parse +import urllib.request + + +def clean(value): + # Never allow API text to inject terminal control sequences. + return "".join(c for c in str(value) if c.isprintable()) + + +def timestamp(value): + try: + if isinstance(value, str): + result = dt.datetime.fromisoformat(value.replace("Z", "+00:00")) + else: + result = dt.datetime.fromtimestamp(value, dt.timezone.utc) + return result.astimezone().strftime("%d %b %H:%M %Z") + except (ValueError, TypeError, OverflowError, OSError): + return "unknown" + + +def window_line(label, window, width): + if not isinstance(window, dict): + return [label + ": unavailable"] + used = window.get("usedPercent") + if isinstance(used, (int, float)) and not isinstance(used, bool) and math.isfinite(used): + used = max(0, min(100, used)) + size = max(5, min(30, width - 40)) + filled = round(size * used / 100) + bar = "#" * filled + "-" * (size - filled) + summary = "{} [{}] {:g}% used / {:g}% left".format(label, bar, used, 100 - used) + else: + summary = label + ": usage unknown" + reset = window.get("resetsAt") + countdown = "" + if isinstance(reset, (int, float)) and math.isfinite(reset): + seconds = max(0, int(reset - time.time())) + hours, minutes = divmod(seconds // 60, 60) + countdown = " (in {}h {:02d}m)".format(hours, minutes) if seconds else " (awaiting fresh poll)" + return [summary, " Reset: " + timestamp(reset) + countdown] + + +def render(data, failure, width): + lines = ["CODEX USAGE", ""] + if failure: + lines += ["OFFLINE - " + failure, "Showing last successful response" if data else "No usage data yet", ""] + if data: + stale = data.get("stale") or data.get("status") != "ok" or bool(failure) + raw = data.get("raw") or {} + if not isinstance(raw, dict): + raw = {} + allowed = raw.get("ordinaryUsageAllowed") + lines += ["State: {} | Allowed: {}".format("STALE" if stale else "OK", {True: "yes", False: "no"}.get(allowed, "unknown")), + "Last server poll: " + timestamp(data.get("last_checked")), ""] + buckets = raw.get("rateLimitsByLimitId") + if not isinstance(buckets, dict) or not buckets: + buckets = {"codex": raw.get("rateLimits")} + for name, bucket in list(buckets.items())[:20]: + if not isinstance(bucket, dict): + continue + lines.append("{} | Plan: {}".format(clean(name), clean(bucket.get("planType") or "unknown"))) + for key in ("primary", "secondary"): + window = bucket.get(key) + duration = window.get("windowDurationMins") if isinstance(window, dict) else None + label = {300: "5-hour", 10080: "Weekly"}.get(duration, "{} min".format(duration) if duration else key.title()) + lines.extend(window_line(label, window, width)) + credits = bucket.get("credits") + if isinstance(credits, dict): + lines.append("Credits: " + ("unlimited" if credits.get("unlimited") else clean(credits.get("balance", "unknown")))) + lines.append("") + lines.append("Display: {} | Ctrl-C to quit".format(time.strftime("%H:%M:%S"))) + return [clean(line)[:width] for line in lines] + + +def fetch(url, timeout=5): + request = urllib.request.Request(url, headers={"Accept": "application/json"}) + try: + response = urllib.request.urlopen(request, timeout=timeout) + except urllib.error.HTTPError as exc: + if exc.code != 503: + raise + response = exc + with response: + body = response.read(1024 * 1024 + 1) + if len(body) > 1024 * 1024: + raise ValueError("response exceeds 1 MiB") + data = json.loads(body) + if not isinstance(data, dict) or data.get("service") != "codex": + raise ValueError("endpoint did not return Codex usage data") + return data + + +def cache_path(url): + digest = hashlib.sha256(url.encode("utf-8")).hexdigest()[:16] + return os.path.join(tempfile.gettempdir(), "codex-usage-{}-{}.json".format(os.getuid(), digest)) + + +def cached_fetch(url, ttl, timeout): + path = cache_path(url) + cached = None + try: + info = os.lstat(path) + if info.st_uid == os.getuid() and info.st_mode & 0o077 == 0 and info.st_size <= 1024 * 1024: + with open(path, "r") as stream: + cached = json.load(stream) + if (not isinstance(cached, dict) or not isinstance(cached.get("data"), dict) + or not isinstance(cached.get("fetched_at"), (int, float))): + cached = None + except (OSError, ValueError, TypeError): + pass + if cached and 0 <= time.time() - cached["fetched_at"] < ttl: + return cached["data"], None + try: + data = fetch(url, timeout) + if data.get("status") == "unavailable": + return cached["data"] if cached else None, "offline" + fd, temporary = tempfile.mkstemp(prefix=".codex-usage-", dir=tempfile.gettempdir()) + try: + with os.fdopen(fd, "w") as stream: + json.dump({"fetched_at": time.time(), "data": data}, stream) + os.replace(temporary, path) + finally: + if os.path.exists(temporary): + os.unlink(temporary) + return data, None + except (urllib.error.URLError, OSError, ValueError, TimeoutError): + return cached["data"] if cached else None, "offline" + + +def tmux_line(data, failure, compact=True, width=30): + if failure or not data: + return "C OFFLINE" if compact or width < 22 else "CODEX OFFLINE" + if data.get("stale") or data.get("status") != "ok": + return "C STALE" if compact or width < 22 else "CODEX STALE" + raw = data.get("raw") + if not isinstance(raw, dict): + return "C STALE" if compact or width < 22 else "CODEX STALE" + buckets = raw.get("rateLimitsByLimitId") + if not isinstance(buckets, dict) or not buckets: + buckets = {"codex": raw.get("rateLimits")} + values = {} + for bucket in list(buckets.values())[:20]: + if not isinstance(bucket, dict): + continue + for key in ("primary", "secondary"): + window = bucket.get(key) + if not isinstance(window, dict): + continue + duration = window.get("windowDurationMins") + used = window.get("usedPercent") + if isinstance(used, (int, float)) and not isinstance(used, bool) and math.isfinite(used): + if duration == 300: + values.setdefault("5h", round(max(0, min(100, 100 - used)))) + elif duration == 10080: + values.setdefault("W", round(max(0, min(100, 100 - used)))) + if not values: + return "C STALE" if compact or width < 22 else "CODEX STALE" + short = compact or width < 30 + prefix = "C" if short else "CODEX" + parts = [prefix] + if "5h" in values: + parts.append(("" if short else "5h ") + "{}%".format(values["5h"])) + if "W" in values: + parts.append("W {}%".format(values["W"])) + return " ".join(parts)[:width] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--url", default=os.environ.get("CODEX_USAGE_URL", "http://127.0.0.1:3100"), help="server base URL or full /api/usage URL (env: CODEX_USAGE_URL)") + parser.add_argument("--interval", type=float, default=10, help="display fetch interval in seconds (default: 10)") + parser.add_argument("--once", action="store_true", help="print once without terminal controls") + parser.add_argument("--tmux", action="store_true", help="print one compact status-bar line") + parser.add_argument("--compact", action="store_true", help="use short status labels") + parser.add_argument("--width", type=int, default=30, help="maximum tmux output width (default: 30)") + parser.add_argument("--cache-ttl", type=float, default=45, help="cache lifetime in seconds (default: 45)") + args = parser.parse_args() + if not math.isfinite(args.interval) or args.interval < 1: + parser.error("--interval must be at least 1 second") + if args.width < 8 or not math.isfinite(args.cache_ttl) or args.cache_ttl < 0: + parser.error("--width must be at least 8 and --cache-ttl must be nonnegative") + url = args.url.rstrip("/") + parsed = urllib.parse.urlsplit(url) + if parsed.scheme not in ("http", "https") or not parsed.hostname or parsed.query or parsed.fragment or parsed.username: + parser.error("--url must be an HTTP(S) URL without credentials, query or fragment") + if not parsed.path or parsed.path == "/": + url += "/api/usage" + if args.tmux: + data, failure = cached_fetch(url, args.cache_ttl, 2) + print(tmux_line(data, failure, True, args.width)) + return 1 if failure else 0 + interactive = sys.stdout.isatty() and os.environ.get("TERM") != "dumb" and not args.once + data, failure = None, None + if interactive: + sys.stdout.write("\033[?1049h\033[?25l") + try: + while True: + failure = None + try: + received, cache_failure = cached_fetch(url, 0, 5) + if cache_failure: + raise ValueError("usage API unavailable") + if received.get("status") == "unavailable": + failure = "server has no successful usage snapshot" + else: + data = received + except (urllib.error.URLError, OSError, ValueError, TimeoutError): + failure = "cannot fetch usage; check endpoint, network and service" + width, height = shutil.get_terminal_size((80, 24)) + lines = render(data, failure, width) + if interactive: + sys.stdout.write("\033[H\033[2J") + lines = lines[:max(1, height - 1)] + print("\n".join(lines), flush=True) + if args.once: + return 1 if failure else 0 + time.sleep(args.interval) + except KeyboardInterrupt: + return 0 + finally: + if interactive: + sys.stdout.write("\033[?25h\033[?1049l") + sys.stdout.flush() + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/dashboard/codex_usage.py b/dashboard/codex_usage.py new file mode 100644 index 0000000..7fbe3eb --- /dev/null +++ b/dashboard/codex_usage.py @@ -0,0 +1,85 @@ +"""Server-side adapter for the local Codex usage service.""" + +import json +import math +import os +import urllib.error +import urllib.request +from datetime import datetime, timezone + +from django.core.cache import caches + + +URL = os.environ.get("DASHBOARD_CODEX_USAGE_URL", "http://192.168.1.122:3100/api/usage") +CACHE = caches["weather"] +FRESH_SECONDS = 45 +STALE_SECONDS = 15 * 60 + + +def _percentage(value): + if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value): + return None + return round(max(0, min(100, 100 - value))) + + +def _time(value): + if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value): + return None + try: + return datetime.fromtimestamp(value, timezone.utc) + except (ValueError, OverflowError, OSError): + return None + + +def _display(data): + if not isinstance(data, dict) or data.get("service") != "codex": + raise ValueError("Unexpected usage response") + raw = data.get("raw") + if not isinstance(raw, dict): + raise ValueError("Usage details unavailable") + buckets = raw.get("rateLimitsByLimitId") + if not isinstance(buckets, dict) or not buckets: + buckets = {"codex": raw.get("rateLimits")} + windows = [] + for name, bucket in list(buckets.items())[:10]: + if not isinstance(bucket, dict): + continue + for key in ("primary", "secondary"): + window = bucket.get(key) + if not isinstance(window, dict): + continue + duration = window.get("windowDurationMins") + title = {300: "5 hours", 10080: "Weekly"}.get(duration, f"{duration} min" if type(duration) is int and 0 < duration < 100000 else key.title()) + windows.append({ + "title": title, + "remaining": _percentage(window.get("usedPercent")), + "reset": _time(window.get("resetsAt")), + "bucket": str(name)[:32], + }) + checked = data.get("last_checked") + try: + checked = datetime.fromisoformat(checked.replace("Z", "+00:00")) if isinstance(checked, str) else None + except ValueError: + checked = None + return {"windows": windows, "checked": checked, "stale": bool(data.get("stale") or data.get("status") != "ok"), "allowed": raw.get("ordinaryUsageAllowed") is True} + + +def get_usage(): + cached = CACHE.get("codex-usage:v1") + if cached and cached.get("fresh"): + return cached["display"] + try: + request = urllib.request.Request(URL, headers={"Accept": "application/json"}) + with urllib.request.urlopen(request, timeout=5) as response: + body = response.read(1024 * 1024 + 1) + if len(body) > 1024 * 1024: + raise ValueError("Usage response too large") + display = _display(json.loads(body)) + if display["stale"] and cached: + raise ValueError("Usage service returned stale data") + CACHE.set("codex-usage:v1", {"display": display, "fresh": True}, FRESH_SECONDS) + CACHE.set("codex-usage:last-good", display, STALE_SECONDS) + return display + except (urllib.error.URLError, OSError, ValueError, TypeError, json.JSONDecodeError): + previous = CACHE.get("codex-usage:last-good") + return {**previous, "stale": True} if previous else None diff --git a/dashboard/registry.py b/dashboard/registry.py index ac0e234..87c11e4 100644 --- a/dashboard/registry.py +++ b/dashboard/registry.py @@ -20,5 +20,6 @@ WIDGETS = { WidgetType("shortcuts", "Shortcuts", "Links to useful pages", "bi-grid", "dashboard/widgets/shortcuts.html"), WidgetType("open_meteo", "Weather forecast", "Current weather and hourly outlook from Open-Meteo", "bi-cloud-sun", "dashboard/widgets/open_meteo.html", 2), WidgetType("buienradar", "Rain radar", "Netherlands radar and local rain forecast from Buienradar", "bi-cloud-rain", "dashboard/widgets/buienradar.html", 2), + WidgetType("codex_usage", "Codex usage", "Remaining five-hour and weekly capacity", "bi-speedometer2", "dashboard/widgets/codex_usage.html", 2), ) } diff --git a/dashboard/static/dashboard/builder.js b/dashboard/static/dashboard/builder.js index 0cf51f9..8e2c30c 100644 --- a/dashboard/static/dashboard/builder.js +++ b/dashboard/static/dashboard/builder.js @@ -20,20 +20,24 @@ indicator.className = 'widget-drop-indicator'; indicator.setAttribute('aria-hidden', 'true'); grid.append(indicator); - const icons = { welcome: 'bi-sun', notes: 'bi-sticky', shortcuts: 'bi-grid', open_meteo: 'bi-cloud-sun', buienradar: 'bi-cloud-rain' }; - const titles = { welcome: 'Welcome', notes: 'Quick notes', shortcuts: 'Shortcuts', open_meteo: 'Weather forecast', buienradar: 'Rain radar' }; - const spans = { welcome: 2, notes: 1, shortcuts: 1, open_meteo: 2, buienradar: 2 }; - const multiple = { welcome: false, notes: true, shortcuts: false, open_meteo: false, buienradar: false }; + const icons = { welcome: 'bi-sun', notes: 'bi-sticky', shortcuts: 'bi-grid', open_meteo: 'bi-cloud-sun', buienradar: 'bi-cloud-rain', codex_usage: 'bi-speedometer2' }; + const titles = { welcome: 'Welcome', notes: 'Quick notes', shortcuts: 'Shortcuts', open_meteo: 'Weather forecast', buienradar: 'Rain radar', codex_usage: 'Codex usage' }; + const spans = { welcome: 2, notes: 1, shortcuts: 1, open_meteo: 2, buienradar: 2, codex_usage: 2 }; + const multiple = { welcome: false, notes: true, shortcuts: false, open_meteo: false, buienradar: false, codex_usage: false }; function setStatus(message, error = false) { status.textContent = message; status.classList.toggle('error', error); } + function widgetCards(root) { + if (!root || typeof root.querySelectorAll !== 'function') return []; + return root.matches?.('.widget-card') ? [root] : [...root.querySelectorAll('.widget-card')]; + } function cards() { return [...grid.querySelectorAll(':scope > .widget-card')]; } function updateEmpty() { document.querySelector('#empty-layout').hidden = cards().length > 0; } function markDirty() { dirty = true; setStatus('Unsaved layout changes'); updateEmpty(); } function mount(root) { - const targets = root.matches?.('.widget-card') ? [root] : [...root.querySelectorAll('.widget-card')]; + const targets = widgetCards(root); targets.forEach(card => { if (lifecycle.has(card)) return; const controller = new AbortController(); @@ -43,13 +47,13 @@ markDirty(); }, { signal: controller.signal }); } - const widgetCleanup = card.dataset.widgetType === 'open_meteo' ? window.DashboardOpenMeteo?.mount(card) : card.dataset.widgetType === 'buienradar' ? window.DashboardBuienradar?.mount(card) : null; + const widgetCleanup = card.dataset.widgetType === 'open_meteo' ? window.DashboardOpenMeteo?.mount(card) : card.dataset.widgetType === 'buienradar' ? window.DashboardBuienradar?.mount(card) : card.dataset.widgetType === 'codex_usage' ? window.DashboardCodexUsage?.mount(card) : null; lifecycle.set(card, () => { controller.abort(); widgetCleanup?.(); }); card.dispatchEvent(new CustomEvent('dashboard:widget-mounted', { bubbles: true })); }); } function unmount(root) { - const targets = root.matches?.('.widget-card') ? [root] : [...root.querySelectorAll('.widget-card')]; + const targets = widgetCards(root); targets.forEach(card => { lifecycle.get(card)?.(); lifecycle.delete(card); card.dispatchEvent(new CustomEvent('dashboard:widget-unmounted', { bubbles: true })); }); } document.addEventListener('htmx:beforeCleanupElement', event => unmount(event.detail.elt)); @@ -103,7 +107,7 @@ } function widgetMarkup(type) { const icon = icons[type], title = titles[type]; - const body = type === 'open_meteo' ? document.querySelector('#open-meteo-widget-template').innerHTML : type === 'buienradar' ? document.querySelector('#buienradar-widget-template').innerHTML : type === 'notes' ? '

Add a note in widget settings.

' : type === 'welcome' ? '

Welcome to your dashboard. Arrange the cards to fit your day.

This is a placeholder widget. Live data widgets will be added separately.

' : ''; + const body = type === 'open_meteo' ? document.querySelector('#open-meteo-widget-template').innerHTML : type === 'buienradar' ? document.querySelector('#buienradar-widget-template').innerHTML : type === 'codex_usage' ? document.querySelector('#codex-usage-widget-template').innerHTML : type === 'notes' ? '

Add a note in widget settings.

' : type === 'welcome' ? '

Welcome to your dashboard. Arrange the cards to fit your day.

This is a placeholder widget. Live data widgets will be added separately.

' : ''; return `

${title}

${body}
`; } function add(type, before = null) { diff --git a/dashboard/static/dashboard/codex_usage.css b/dashboard/static/dashboard/codex_usage.css new file mode 100644 index 0000000..c50d86c --- /dev/null +++ b/dashboard/static/dashboard/codex_usage.css @@ -0,0 +1 @@ +.codex-usage{min-width:0}.codex-usage-top,.codex-usage-footer{display:flex;justify-content:space-between;align-items:center;gap:12px}.codex-usage-top{margin-bottom:18px}.codex-usage-state{display:inline-flex;align-items:center;gap:7px;font-size:12px;font-weight:700;color:var(--accent)}.codex-usage-state:before{content:"";width:7px;height:7px;border-radius:50%;background:currentColor}.codex-usage-state.is-stale,.codex-usage-state.is-limited{color:var(--text-secondary)}.codex-usage-state.is-error{color:var(--negative)}.codex-usage-checked,.codex-usage-reset,.codex-usage-footer,.codex-usage-note{font-size:12px;color:var(--text-secondary)}.codex-usage-gauges{display:grid;grid-template-columns:repeat(auto-fit,minmax(145px,1fr));gap:20px}.codex-usage-window{display:flex;flex-direction:column;align-items:center;gap:4px;text-align:center;padding:12px;border-radius:var(--radius-md);background:var(--surface-secondary)}.codex-usage-ring{width:116px;aspect-ratio:1;border-radius:50%;display:grid;place-items:center;background:conic-gradient(var(--accent) var(--usage-progress,0%),var(--border) 0);margin-bottom:5px}.codex-usage-ring-inner{width:88px;aspect-ratio:1;border-radius:50%;display:flex;flex-direction:column;align-items:center;justify-content:center;background:var(--surface-secondary);color:var(--text)}.codex-usage-ring-inner strong{font-size:26px;line-height:1.1}.codex-usage-ring-inner small{font-size:11px;color:var(--text-secondary)}.codex-usage-label{font-size:13px;color:var(--text)}.codex-usage-reset{line-height:1.4}.codex-usage-note{margin:14px 0 0!important}.codex-usage-footer{border-top:1px solid var(--border);margin:16px 0 0!important;padding-top:10px}.codex-usage-panel[aria-busy="true"]{opacity:.75}@media(max-width:420px){.codex-usage-gauges{grid-template-columns:repeat(2,minmax(0,1fr));gap:8px}.codex-usage-window{padding:10px 4px}.codex-usage-ring{width:96px}.codex-usage-ring-inner{width:73px}.codex-usage-ring-inner strong{font-size:22px}} diff --git a/dashboard/static/dashboard/codex_usage.js b/dashboard/static/dashboard/codex_usage.js new file mode 100644 index 0000000..cd3288b --- /dev/null +++ b/dashboard/static/dashboard/codex_usage.js @@ -0,0 +1,26 @@ +(() => { + window.DashboardCodexUsage = { + mount(card) { + const root = card.querySelector('[data-codex-usage]'); + if (!root) return () => {}; + const panel = root.querySelector('.codex-usage-panel'); + const next = root.querySelector('[data-next-refresh]'); + const controller = new AbortController(); + let due = Date.now() + 60000; + function updateTimes() { + next.dateTime = new Date(due).toISOString(); + next.textContent = new Date(due).toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' }); + panel.querySelectorAll('time[datetime]').forEach(time => { + const date = new Date(time.dateTime); + if (!Number.isNaN(date.getTime())) time.textContent = date.toLocaleString([], { day: 'numeric', month: 'short', hour: 'numeric', minute: '2-digit' }); + }); + } + panel.addEventListener('htmx:beforeRequest', () => { panel.setAttribute('aria-busy', 'true'); }, { signal: controller.signal }); + panel.addEventListener('htmx:afterRequest', () => { panel.setAttribute('aria-busy', 'false'); }, { signal: controller.signal }); + panel.addEventListener('htmx:afterSwap', () => { due = Date.now() + 60000; updateTimes(); }, { signal: controller.signal }); + updateTimes(); + window.htmx?.process(panel); + return () => { controller.abort(); }; + }, + }; +})(); diff --git a/dashboard/templates/dashboard/index.html b/dashboard/templates/dashboard/index.html index 1063ef3..351f964 100644 --- a/dashboard/templates/dashboard/index.html +++ b/dashboard/templates/dashboard/index.html @@ -1,4 +1,4 @@ -{% extends 'core/base.html' %}{% load static %}{% block content %} +{% extends 'core/base.html' %}{% load static %}{% block content %}
YOUR WORKSPACE

{{ title }}.

Make this space your own with a few useful widgets.

Layout saved
OverviewPersonal
@@ -8,7 +8,8 @@

This page is empty. Choose Edit layout, then add a widget.

+ {{ catalogue|length|json_script:"widget-count" }} - + {% endblock %} diff --git a/dashboard/templates/dashboard/widgets/_codex_usage_panel.html b/dashboard/templates/dashboard/widgets/_codex_usage_panel.html new file mode 100644 index 0000000..89e4bce --- /dev/null +++ b/dashboard/templates/dashboard/widgets/_codex_usage_panel.html @@ -0,0 +1,5 @@ +{% if usage %} +
{% if usage.stale %}Stale data{% elif not usage.allowed %}Usage limited{% else %}Live usage{% endif %}{% if usage.checked %}Checked {% endif %}
+{% if usage.windows %}
{% for window in usage.windows %}
{{ window.title }}{% if window.reset %}Resets {% else %}Reset time unavailable{% endif %}
{% endfor %}
{% else %}

No usage windows available.

{% endif %} +{% if usage.stale %}

Showing the last available snapshot. The next refresh will retry.

{% endif %} +{% else %}

Usage is unavailable right now. The next refresh will retry.

{% endif %} diff --git a/dashboard/templates/dashboard/widgets/codex_usage.html b/dashboard/templates/dashboard/widgets/codex_usage.html new file mode 100644 index 0000000..f9a5eb9 --- /dev/null +++ b/dashboard/templates/dashboard/widgets/codex_usage.html @@ -0,0 +1,6 @@ +{% load static %}
+
+

Loading usage…

+
+ +
diff --git a/dashboard/tests.py b/dashboard/tests.py index a80580b..3ce1490 100644 --- a/dashboard/tests.py +++ b/dashboard/tests.py @@ -14,6 +14,7 @@ from .models import DashboardLayout from .views import validate_widgets from .weather import ForecastUnavailable, coordinates, get_forecast from .buienradar import RainUnavailable, get_rain, parse_forecast +from .codex_usage import _display, get_usage class DashboardTests(TestCase): @@ -130,6 +131,36 @@ class DashboardTests(TestCase): def test_buienradar_stale_fallback(self): cache = caches["weather"] cache.clear() + + def test_codex_usage_registry_and_private_panel(self): + from .registry import WIDGETS + self.assertIn("codex_usage", WIDGETS) + item = {"id": str(uuid.uuid4()), "type": "codex_usage", "span": 2, "settings": {}, "visible": True} + self.assertEqual(validate_widgets([item])[0]["type"], "codex_usage") + with self.assertRaises(ValueError): + validate_widgets([item, {**item, "id": str(uuid.uuid4())}]) + url = reverse("dashboard:codex_usage") + self.assertEqual(self.client.get(url).status_code, 302) + self.client.force_login(self.one) + with patch("dashboard.views.get_usage", return_value={"windows": [{"title": "5 hours", "remaining": 17, "reset": None, "bucket": "codex"}], "checked": None, "stale": False, "allowed": True}): + response = self.client.get(url) + self.assertContains(response, "17%") + self.assertContains(response, "Reset time unavailable") + + def test_codex_usage_normalizes_live_shape_and_stale_cache(self): + raw = {"service": "codex", "status": "ok", "last_checked": "2026-10-21T22:56:50.106Z", "raw": {"ordinaryUsageAllowed": True, "accountId": "private", "rateLimitsByLimitId": {"codex": {"primary": {"usedPercent": 83, "windowDurationMins": 300, "resetsAt": 1792625545}, "secondary": {"usedPercent": 60, "windowDurationMins": 10080, "resetsAt": 1793101162}}}}} + display = _display(raw) + self.assertEqual([window["remaining"] for window in display["windows"]], [17, 40]) + self.assertNotIn("private", str(display)) + cache = caches["weather"] + cache.delete("codex-usage:v1") + cache.delete("codex-usage:last-good") + cache.set("codex-usage:last-good", display, 60) + with patch("dashboard.codex_usage.urllib.request.urlopen", side_effect=OSError("offline")): + fallback = get_usage() + self.assertTrue(fallback["stale"]) + self.assertEqual(fallback["windows"][0]["remaining"], 17) + cache.delete("codex-usage:last-good") key = hashlib.sha256(b"buienradar:v1:52.96:5.92").hexdigest() cache.set(f"stale:{key}", {"points": [{"time": "2026-10-14T23:55:00+02:00", "mm_per_hour": 0, "label": "None"}], "fetched_at": "2026-10-14T21:55:00+00:00"}, 60) with patch("dashboard.buienradar.request_rain", side_effect=OSError("offline")): diff --git a/dashboard/urls.py b/dashboard/urls.py index 2c577fa..e84b468 100644 --- a/dashboard/urls.py +++ b/dashboard/urls.py @@ -4,8 +4,9 @@ from . import views app_name = "dashboard" urlpatterns = [ path("", views.index, name="index"), - path("dashboard//", views.page, name="page"), path("dashboard//layout/", views.layout_api, name="layout"), path("dashboard/weather/open-meteo/", views.open_meteo_api, name="open_meteo"), path("dashboard/weather/buienradar/", views.buienradar_api, name="buienradar"), + path("dashboard/codex-usage/", views.codex_usage_panel, name="codex_usage"), + path("dashboard//", views.page, name="page"), ] diff --git a/dashboard/views.py b/dashboard/views.py index a540940..baf92f3 100644 --- a/dashboard/views.py +++ b/dashboard/views.py @@ -12,6 +12,7 @@ from .models import DashboardLayout from .registry import WIDGETS from .weather import ForecastUnavailable, get_forecast from .buienradar import RainUnavailable, get_rain +from .codex_usage import get_usage PAGES = {"overview": "Overview", "personal": "Personal"} @@ -120,3 +121,9 @@ def buienradar_api(request): except RainUnavailable as exc: return JsonResponse({"error": str(exc)}, status=503) return JsonResponse(rain) + + +@login_required +@require_http_methods(["GET"]) +def codex_usage_panel(request): + return render(request, "dashboard/widgets/_codex_usage_panel.html", {"usage": get_usage()}) diff --git a/docs/card-attachments.md b/docs/card-attachments.md index f9cb1fa..9df367c 100644 --- a/docs/card-attachments.md +++ b/docs/card-attachments.md @@ -1,6 +1,6 @@ # Card and progress-note attachments -Attachments are stored as private files with metadata in `CardAttachment`. A file belongs to one card, and optionally one `CardComment` progress note on that card. Moving a card keeps its files. Deleting a note or card cascades to its attachment records and removes stored files. Explicit deletion also removes the bytes. Files are snapshots; `source_path` and `source_commit` record provenance but do not cause automatic refresh. +Attachments are stored as private files with metadata in `CardAttachment`. A file belongs to one card, and optionally one `CardComment` progress note on that card. Moving a card between project boards keeps the same card and comment records, so its files and progress-note files remain attached and accessible to destination project members. Deleting a note or card cascades to its attachment records and removes stored files. Explicit deletion also removes the bytes. Files are snapshots; `source_path` and `source_commit` record provenance but do not cause automatic refresh. ## Configuration diff --git a/docs/codex-usage-widget.md b/docs/codex-usage-widget.md new file mode 100644 index 0000000..a333bf6 --- /dev/null +++ b/docs/codex-usage-widget.md @@ -0,0 +1,9 @@ +# Codex usage widget + +Add **Codex usage** from the dashboard widget catalogue. The card shows remaining capacity in circular gauges for each usage window returned by the service, plus each window's reset time. Times are converted to the browser's local timezone. The footer shows the next scheduled refresh time. + +The authenticated Django endpoint `dashboard/codex-usage/` requests `http://192.168.1.122:3100/api/usage` by default. Set `DASHBOARD_CODEX_USAGE_URL` on the Django server to override it. The browser receives only normalized display fields; the upstream account ID and full response stay server-side. The service response is cached for 45 seconds in the shared file cache. The browser polls the HTML partial with HTMX every 60 seconds while the widget is mounted. + +If the service fails, the last successful display remains available for up to 15 minutes and is visibly marked stale. After that, the card shows an unavailable state. A response explicitly marked stale is also labeled. The widget never guesses missing percentages or reset times. Removing the card stops its HTMX polling with the DOM element; adding it again starts a new poll. + +The dashboard template adds a version query to the widget stylesheet and scripts, including `builder.js`. This forces browsers with an older cached widget catalogue script to load the current type registry and Add handler after deployment. diff --git a/docs/project-board.md b/docs/project-board.md new file mode 100644 index 0000000..eec0502 --- /dev/null +++ b/docs/project-board.md @@ -0,0 +1,19 @@ +# Project board + +The project board is a Django page backed by the existing project, card, and activity records. The responsive header shows repository metadata, completion progress, and permission-gated project actions. Completion uses active cards and safely reports zero percent when the project has no active cards. + +Search and the filter sheet keep their state in GET parameters (`q`, `priority`, `card_type`, `column`, `assignee`, `tag`, and `archived`). Filter changes refresh the board through HTMX; a normal GET remains available. Archived cards are a separate toggle. Project access is resolved by `services.project_for`, while edit controls are shown only to the owner and project editors. + +Columns scroll horizontally on narrow screens and snap into view. Cards retain SortableJS drag behavior for pointer and touch users, and keep column and ordering controls as keyboard alternatives. The project activity panel shows the latest three events in human-readable form and can expand to older events. The shared five-destination mobile navigation remains the source for mobile app navigation. + +Styles live in `projects/static/projects/board_mobile.css` and use the shared theme variables. No database schema or new client dependency is required. + +## Projects index + +The authenticated Projects index lists only projects available to the current user. Active and archived views, search across project and card content, and pagination remain query-driven. Search responses can replace the project-card list through HTMX. Each project card shows total cards, active-card completion, repository access, and links to its board and documentation. Counts are calculated from existing project and card records; they do not require additional stored fields. + +## Card detail + +Selecting a card opens a responsive detail page with the Markdown description, raw Markdown disclosure, card properties, attachments, progress notes, and the full activity history. The page uses the same theme variables and mobile navigation. Edit, archive/restore, uploads, note creation, and cross-project moves are limited to project owners and editors; viewers can read the card and its history. + +The card action menu can move a card to another active project the current editor may edit. Its accessible confirmation dialog selects an active destination column, defaulting to that project's default column. The move keeps the card UUID and URL, card timestamps, description, revisions, comments, attachments, and activity history. It maps tags to same-named destination tags and clears unmatched tags; an assignee without destination access is cleared. Both outcomes appear in the success message. The move is one transaction, checks the submitted card revision, adds a revision, records source and destination activity, and rejects archived projects, invalid columns, stale forms, and inaccessible destinations. The MCP `cards_move_project` tool calls the same service, requires a destination project UUID and expected revision, and supports an optional idempotency key. The existing `cards_move` tool continues to move a card within its current project. diff --git a/mcp_server/server.py b/mcp_server/server.py index 9a2ff13..a5be206 100644 --- a/mcp_server/server.py +++ b/mcp_server/server.py @@ -541,6 +541,30 @@ def create_server(): return _card_data(services.move_card(user, _card(user, card_id, write=True), Column.objects.get(pk=UUID(column_id)), position, origin='mcp')) return await sync_to_async(lambda: _safe(run))() + @server.tool(structured_output=True, description='Move a card to another editable project. Requires the destination project UUID and expected_revision; optionally choose an active destination column and provide an idempotency key. Preserves the card UUID, notes, files, and history; returns warnings if tags or assignee must be cleared.') + async def cards_move_project(card_id: str, target_project: str, expected_revision: int, + target_column_id: str | None = None, + idempotency_key: str | None = None) -> dict[str, Any]: + def run(): + user = _actor('projects:write') + card = _card(user, card_id, write=True) + try: + project_id = UUID(target_project) + except (ValueError, TypeError, AttributeError): + raise ValidationError('target_project must be a project UUID.') + target = services.project_for(user, project_id, write=True) + column = None + if target_column_id: + try: + column = Column.objects.get(pk=UUID(target_column_id)) + except (Column.DoesNotExist, ValueError, TypeError, AttributeError): + raise ValidationError('Destination column is unavailable.') + moved, result = services.move_card_to_project( + user, card, target, target_column=column, expected_revision=expected_revision, + idempotency_key=idempotency_key, origin='mcp') + return {**_card_data(moved), 'move': result} + return await sync_to_async(lambda: _safe(run))() + @server.tool(structured_output=True, description='Reorder a card within its current column using a zero-based position.') async def cards_reorder(card_id: str, position: int) -> dict[str, Any]: def run(): @@ -712,7 +736,8 @@ def create_server(): async def system_capabilities() -> dict[str, Any]: _actor() return {'scopes': ['projects:read', 'projects:write'], 'max_page_size': 100, 'version': '0.3', - 'transport': 'streamable_http', 'documentation': ['docs_list', 'docs_search', 'docs_read', 'docs_history', 'docs_diff']} + 'transport': 'streamable_http', 'documentation': ['docs_list', 'docs_search', 'docs_read', 'docs_history', 'docs_diff'], + 'card_moves': {'same_project': 'cards_move', 'between_projects': 'cards_move_project'}} return server diff --git a/projects/migrations/0007_projectmovekey.py b/projects/migrations/0007_projectmovekey.py new file mode 100644 index 0000000..e64e96b --- /dev/null +++ b/projects/migrations/0007_projectmovekey.py @@ -0,0 +1,30 @@ +# Generated by Django 6.1.2 on 2026-10-22 01:16 + +import django.db.models.deletion +from django.conf import settings +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('projects', '0006_documentationsync_projectdocument'), + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.CreateModel( + name='ProjectMoveKey', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('key', models.CharField(max_length=128)), + ('payload_hash', models.CharField(max_length=64)), + ('result', models.JSONField()), + ('created_at', models.DateTimeField(auto_now_add=True)), + ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), + ], + options={ + 'constraints': [models.UniqueConstraint(fields=('user', 'key'), name='unique_project_move_key')], + }, + ), + ] diff --git a/projects/models.py b/projects/models.py index 5319e0a..0ce5f7d 100644 --- a/projects/models.py +++ b/projects/models.py @@ -215,6 +215,17 @@ class BulkUpdateKey(models.Model): constraints = [models.UniqueConstraint(fields=['user', 'key'], name='unique_bulk_update_key')] +class ProjectMoveKey(models.Model): + user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) + key = models.CharField(max_length=128) + payload_hash = models.CharField(max_length=64) + result = models.JSONField() + created_at = models.DateTimeField(auto_now_add=True) + + class Meta: + constraints = [models.UniqueConstraint(fields=['user', 'key'], name='unique_project_move_key')] + + class Activity(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='activity') card = models.ForeignKey(Card, null=True, blank=True, on_delete=models.CASCADE, related_name='activity') diff --git a/projects/services.py b/projects/services.py index df71155..fcda840 100644 --- a/projects/services.py +++ b/projects/services.py @@ -8,7 +8,7 @@ from django.core.validators import URLValidator from django.shortcuts import get_object_or_404 from django.utils import timezone from django.utils.text import slugify -from .models import Activity, Board, BulkUpdateKey, Card, CardRevision, Column, CreationKey, Membership, Project, Tag +from .models import Activity, Board, BulkUpdateKey, Card, CardRevision, Column, CreationKey, Membership, Project, ProjectMoveKey, Tag class RevisionConflict(Exception): @@ -145,6 +145,101 @@ def move_card(user, card, column, position=None, origin='web', record_revision=T return card +@transaction.atomic +def move_card_to_project(user, card, target_project, *, target_column=None, expected_revision, + idempotency_key=None, origin='web'): + """Move a card between editable projects without replacing its identity or children.""" + if idempotency_key: + if len(idempotency_key) > 128: + raise ValidationError('Idempotency key is too long.') + payload = json.dumps({'card': str(card.pk), 'target_project': str(target_project.pk), + 'target_column': str(target_column.pk) if target_column else None, + 'expected_revision': int(expected_revision)}, sort_keys=True) + payload_hash = hashlib.sha256(payload.encode()).hexdigest() + user.__class__.objects.select_for_update().get(pk=user.pk) + existing = ProjectMoveKey.objects.select_for_update().filter(user=user, key=idempotency_key).first() + if existing: + if existing.payload_hash != payload_hash: + raise ValidationError('Idempotency key was already used with different move details.') + current = Card.objects.select_for_update().select_related('project').get(pk=card.pk) + project_for(user, current.project_id, write=True) + if current.project_id != target_project.pk: + raise ValidationError('The original move is no longer available to replay.') + return current, existing.result + + card = Card.objects.select_for_update().select_related('project', 'column').get(pk=card.pk) + source = project_for(user, card.project_id, write=True) + target_project = project_for(user, target_project.pk, write=True) + if source.pk == target_project.pk: + raise ValidationError('Choose a different project. Use the column move for this project.') + if source.archived or target_project.archived: + raise ValidationError('Cards cannot be moved from or into an archived project.') + if card.revision != int(expected_revision): + raise RevisionConflict(card.revision) + if target_column is None: + active_columns = target_project.board.columns.filter(archived=False) + target_column = active_columns.filter(is_default=True).first() or active_columns.first() + if (target_column is None or target_column.board_id != target_project.board.pk or target_column.archived): + raise ValidationError('Column is not available in the destination project.') + + warnings = [] + if card.assignee_id and card.assignee_id != target_project.owner_id and not Membership.objects.filter(project=target_project, user_id=card.assignee_id).exists(): + warnings.append(f"Assignee {card.assignee.get_full_name() or card.assignee.username} was cleared because they do not have access to the destination project.") + card.assignee = None + + old_tags = list(card.tags.all()) + target_tags = list(Tag.objects.filter(project=target_project).order_by('pk')) + tags_by_name = {tag.name.casefold(): tag for tag in target_tags} + mapped_tags = [] + for tag in old_tags: + match = tags_by_name.get(tag.name.casefold()) + if match: + mapped_tags.append(match) + else: + warnings.append(f"Tag “{tag.name}” was cleared because it does not exist in the destination project.") + + old_column_id = card.column_id + old_column_name = card.column.name + original_updated_at = card.updated_at + siblings = list(Card.objects.filter(column=target_column, archived=False).exclude(pk=card.pk).order_by('position', 'created_at')) + card.project = target_project + card.column = target_column + card.position = len(siblings) + card.completed_at = timezone.now() if target_column.is_done else None + card.revision += 1 + card.full_clean() + card.save(update_fields=['project', 'column', 'position', 'completed_at', 'revision', 'assignee']) + card.updated_at = original_updated_at + card.tags.set(mapped_tags) + for index, sibling in enumerate(Card.objects.filter(column_id=old_column_id, archived=False).order_by('position', 'created_at')): + if sibling.position != index: + sibling.position = index + sibling.save(update_fields=['position']) + for index, sibling in enumerate(siblings): + if sibling.position != index: + sibling.position = index + sibling.save(update_fields=['position']) + + # The card's prior activity follows its stable UUID into the destination. + Activity.objects.filter(card=card).update(project=target_project) + CardRevision.objects.create(card=card, revision=card.revision, markdown=card.description_markdown, actor=user) + detail = {'from_project': str(source.pk), 'from_column': str(old_column_id), + 'from_column_name': old_column_name, 'to_project': str(target_project.pk), + 'to_column': str(target_column.pk), 'to_column_name': target_column.name} + Activity.objects.create(project=source, actor=user, action='card.moved_project_out', + detail={'card_id': str(card.pk), 'title': card.title, **detail}, origin=origin) + Activity.objects.create(project=target_project, card=card, actor=user, action='card.moved_project', + detail=detail, origin=origin) + result = {'source_project_id': str(source.pk), 'source_project_name': source.name, + 'source_column_id': str(old_column_id), + 'target_project_id': str(target_project.pk), 'target_column_id': str(target_column.pk), + 'target_project_name': target_project.name, 'target_column_name': target_column.name, + 'revision': card.revision, 'url': f'/projects/cards/{card.pk}/', 'warnings': warnings} + if idempotency_key: + ProjectMoveKey.objects.create(user=user, key=idempotency_key, payload_hash=payload_hash, result=result) + return card, result + + @transaction.atomic def set_default(user, column): project_for(user, column.board.project_id, write=True) diff --git a/projects/static/projects/board_mobile.css b/projects/static/projects/board_mobile.css new file mode 100644 index 0000000..2ccffd2 --- /dev/null +++ b/projects/static/projects/board_mobile.css @@ -0,0 +1,7 @@ +.project-board-page{--board-gap:1rem;max-width:1480px;margin:0 auto;color:var(--text);padding-bottom:1.25rem}.project-board-header{display:flex;justify-content:space-between;align-items:flex-end;gap:1.25rem;margin-bottom:1.2rem}.project-board-heading{min-width:0;flex:1}.project-back-link{display:inline-flex;align-items:center;gap:.45rem;color:var(--text-secondary);font-size:.88rem;font-weight:600;text-decoration:none;min-height:44px}.project-back-link:hover{color:var(--accent)}.project-title-row{display:flex;align-items:flex-start;justify-content:space-between;gap:.75rem}.project-title-row h1{font-size:clamp(1.6rem,3vw,2.1rem);font-weight:800;line-height:1.15;overflow-wrap:anywhere;margin:0 0 .3rem}.project-repo-link{display:inline-flex;align-items:center;gap:.35rem;color:var(--text-secondary);font-size:.85rem}.project-description{max-width:68ch;color:var(--text-secondary);font-size:.92rem;margin:.55rem 0}.project-header-actions{display:flex;gap:.55rem;align-items:center;flex-wrap:wrap}.project-header-actions .btn{min-height:44px;display:inline-flex;align-items:center;justify-content:center;gap:.4rem}.project-new-card{font-weight:700}.project-progress{max-width:26rem;margin-top:.85rem}.project-progress-copy{display:flex;gap:.45rem;align-items:baseline;font-size:.83rem;margin-bottom:.35rem}.project-progress-copy strong{font-weight:800}.project-progress-copy span{color:var(--text-secondary)}.project-progress-track{height:7px;background:var(--surface-secondary);border-radius:99px;overflow:hidden}.project-progress-track span{height:100%;display:block;border-radius:inherit;background:var(--positive,var(--accent));transition:width .2s ease}.project-priority-summary{display:flex;flex-wrap:wrap;gap:.5rem;margin-bottom:1rem}.project-priority-summary>span{display:inline-flex;align-items:center;gap:.4rem;padding:.42rem .65rem;border:1px solid var(--border);border-radius:999px;background:var(--surface);font-size:.79rem;color:var(--text-secondary)}.project-priority-summary strong{color:var(--text)}.priority-dot{width:.48rem;height:.48rem;border-radius:50%;background:var(--text-muted)}.priority-high{background:var(--negative,#c44)}.priority-medium{background:var(--warning,#c90)}.priority-low{background:var(--positive,#39865e)}.project-board-filters{display:grid;grid-template-columns:minmax(12rem,1fr) auto auto;gap:.6rem;align-items:center;margin-bottom:.75rem}.project-search{position:relative;display:block}.project-search>i{position:absolute;left:.85rem;top:50%;transform:translateY(-50%);color:var(--text-muted);pointer-events:none}.project-search input{height:46px;padding-left:2.55rem;border-radius:.7rem}.project-filter-open{min-height:46px;display:inline-flex;align-items:center;gap:.45rem}.project-filter-count{display:inline-grid;place-items:center;min-width:1.35rem;height:1.35rem;padding:0 .25rem;border-radius:99px;background:var(--accent);color:var(--surface);font-size:.72rem;font-weight:800}.project-archived-toggle{display:flex;align-items:center;gap:.5rem;min-height:44px;color:var(--text-secondary);font-size:.83rem;white-space:nowrap}.project-archived-toggle .form-check-input{margin:0;width:1.1rem;height:1.1rem}.project-filter-sheet[hidden]{display:none}.project-filter-sheet{position:fixed;inset:0;z-index:1090;display:grid;grid-template-columns:1fr min(27rem,100%);align-items:stretch}.project-filter-scrim{grid-column:1;grid-row:1;background:rgba(8,15,11,.55);border:0}.project-filter-panel{grid-column:2;grid-row:1;display:flex;flex-direction:column;gap:.85rem;overflow-y:auto;padding:1.2rem;background:var(--surface);color:var(--text);border-left:1px solid var(--border);box-shadow:-12px 0 36px rgba(0,0,0,.15);padding-bottom:calc(1.2rem + env(safe-area-inset-bottom))}.project-filter-heading{display:flex;align-items:center;justify-content:space-between;padding-bottom:.7rem;border-bottom:1px solid var(--border)}.project-filter-heading h2{font-size:1.2rem;font-weight:800;margin:0}.project-filter-close{width:44px;height:44px;border:0;border-radius:50%;background:var(--surface-secondary);color:var(--text);font-size:1rem}.project-filter-field{display:grid;gap:.35rem;color:var(--text-secondary);font-weight:700;font-size:.82rem}.project-filter-field .form-select{min-height:44px}.project-filter-footer{display:flex;justify-content:space-between;align-items:center;margin-top:auto;padding-top:.7rem;border-top:1px solid var(--border)}.project-filter-footer .btn{min-height:44px}.project-loading{display:block;min-height:1.2rem;color:var(--text-muted);font-size:.8rem}.project-bulk-toolbar{display:flex;flex-wrap:wrap;align-items:center;gap:.5rem;margin:.25rem 0 .7rem;color:var(--text-secondary);font-size:.84rem}.project-board-section{min-width:0}.project-board-section #kanban-columns{scroll-snap-type:x proximity;overscroll-behavior-inline:contain;scrollbar-width:thin;padding-bottom:.5rem}.project-board-section #kanban-columns>section{scroll-snap-align:start;border-color:var(--border);background:var(--surface)}.project-board-section #kanban-columns .card-header{min-height:3.2rem}.project-board-section #kanban-columns .card-body[data-column]{overflow-y:auto;max-height:min(68vh,48rem)}.project-board-section #kanban-columns article.card{background:var(--surface);border-color:var(--border);scroll-snap-align:start}.project-board-section #kanban-columns article .card-body{padding:.9rem}.project-board-section #kanban-columns article a{overflow-wrap:anywhere}.project-board-section #kanban-columns .form-select{min-height:40px}.project-board-section #kanban-columns button,.project-board-section #kanban-columns a.btn{min-height:40px}.project-board-management{display:flex;gap:.5rem;margin-top:.75rem}.project-board-management .btn{min-height:42px}.project-activity{margin-top:1.75rem;padding:1.1rem 1.2rem;border:1px solid var(--border);border-radius:1rem;background:var(--surface)}.project-section-heading{display:flex;justify-content:space-between;align-items:flex-end;gap:1rem}.project-section-heading h2{font-size:1.1rem;font-weight:800;margin:0}.project-section-heading>a{min-height:44px;display:inline-flex;align-items:center;font-weight:700}.project-section-eyebrow{font-size:.68rem;font-weight:800;letter-spacing:.13em;color:var(--accent);margin:0 0 .25rem}.project-activity-list{list-style:none;margin:.9rem 0 0;padding:0}.project-activity-list li{display:grid;grid-template-columns:2rem minmax(0,1fr);gap:.7rem;position:relative;padding:0 0 1rem}.project-activity-list li:not(:last-child):before{content:"";position:absolute;left:.97rem;top:2rem;bottom:.15rem;border-left:1px solid var(--border)}.project-activity-marker{position:relative;z-index:1;display:grid;place-items:center;width:2rem;height:2rem;border:1px solid var(--border);border-radius:50%;background:var(--surface-secondary);color:var(--accent)}.project-activity-list p{margin:.1rem 0 .2rem;font-size:.88rem;line-height:1.4}.project-activity-list p a{font-weight:700}.project-activity-list small{display:block;color:var(--text-muted);font-size:.77rem}.project-activity-empty{margin:.8rem 0 0;color:var(--text-secondary)}.project-all-activity{margin-top:.25rem;border-top:1px solid var(--border);padding-top:.55rem}.project-all-activity summary{min-height:44px;display:flex;align-items:center;color:var(--accent);font-weight:700;cursor:pointer}.project-all-activity .project-activity-list{margin-top:.65rem}.project-board-page :focus-visible{outline:3px solid var(--focus,#43785e);outline-offset:2px}.project-board-page a,.project-board-page button,.project-board-page summary{touch-action:manipulation} +@media(max-width:760px){.project-board-page{padding-bottom:calc(5.7rem + env(safe-area-inset-bottom))}.project-board-header{display:block;margin-bottom:.9rem}.project-title-row h1{font-size:1.65rem}.project-description{font-size:.86rem}.project-header-actions{display:grid;grid-template-columns:1fr;margin-top:.75rem}.project-header-actions .btn{width:100%}.project-docs-link{order:2}.project-progress{margin-top:.7rem}.project-priority-summary{gap:.4rem;margin-bottom:.75rem}.project-priority-summary>span{padding:.38rem .55rem;font-size:.75rem}.project-board-filters{grid-template-columns:minmax(0,1fr) auto;gap:.5rem}.project-search{grid-column:1/-1}.project-search input{height:48px}.project-archived-toggle{grid-column:1/-1;white-space:normal}.project-filter-sheet{grid-template-columns:1fr;align-items:end}.project-filter-scrim{grid-column:1;grid-row:1}.project-filter-panel{grid-column:1;grid-row:1;max-height:min(82dvh,42rem);border:1px solid var(--border);border-radius:1.1rem 1.1rem 0 0;box-shadow:0 -12px 36px rgba(0,0,0,.18);padding:1rem 1rem calc(1rem + env(safe-area-inset-bottom))}.project-board-section #kanban-columns{margin-right:-1rem;padding-right:1rem;scroll-padding-inline:.1rem}.project-board-section #kanban-columns>section{width:min(82vw,19rem)!important}.project-board-section #kanban-columns .card-body[data-column]{max-height:55vh}.project-activity{padding:1rem;margin-top:1.2rem}.project-activity-list li{grid-template-columns:1.9rem minmax(0,1fr)}.project-activity-marker{width:1.9rem;height:1.9rem}.project-activity-list li:not(:last-child):before{left:.92rem;top:1.9rem}.project-board-management{display:grid;grid-template-columns:1fr 1fr}.project-board-management .btn{padding-inline:.45rem;font-size:.82rem}} +@media(max-width:360px){.project-title-row h1{font-size:1.48rem}.project-header-actions{grid-template-columns:1fr}.project-priority-summary>span{font-size:.7rem;padding:.35rem .45rem}.project-filter-open{padding-inline:.65rem}.project-board-section #kanban-columns>section{width:calc(100vw - 2rem)!important}.project-activity{padding:.85rem}.project-board-management{grid-template-columns:1fr}} +@media(prefers-reduced-motion:reduce){.project-progress-track span{transition:none}} +.project-board-scroll-hint{display:none;color:var(--text-muted);font-size:.76rem;margin:0 0 .35rem}.project-column-empty{color:var(--text-muted);font-size:.84rem;padding:.4rem} +@media(max-width:760px){.project-board-scroll-hint{display:block}} +.project-actions-menu{position:relative;flex:none}.project-actions-menu>summary{list-style:none;display:grid;place-items:center;width:44px;height:44px;border:1px solid var(--border);border-radius:.65rem;background:var(--surface);color:var(--text);cursor:pointer;font-size:1.2rem}.project-actions-menu>summary::-webkit-details-marker{display:none}.project-actions-popover{position:absolute;z-index:20;right:0;top:calc(100% + .35rem);min-width:10rem;padding:.35rem;border:1px solid var(--border);border-radius:.7rem;background:var(--surface);box-shadow:0 8px 24px rgba(0,0,0,.14)}.project-actions-popover a,.project-actions-popover button{display:flex;width:100%;min-height:44px;align-items:center;padding:.55rem .65rem;border:0;border-radius:.45rem;background:transparent;color:var(--text);text-align:left;text-decoration:none;font:inherit;font-size:.88rem}.project-actions-popover a:hover,.project-actions-popover button:hover{background:var(--surface-secondary)}.project-actions-popover form{margin:0}.project-filter-count[hidden]{display:none} diff --git a/projects/static/projects/card_detail.css b/projects/static/projects/card_detail.css new file mode 100644 index 0000000..8ebf023 --- /dev/null +++ b/projects/static/projects/card_detail.css @@ -0,0 +1,6 @@ +.project-card-page{max-width:1280px;margin:0 auto;padding-bottom:1.25rem;color:var(--text)}.project-card-breadcrumb{display:flex;align-items:center;gap:.55rem;min-height:44px;margin-bottom:1rem;color:var(--text-muted);font-size:.84rem}.project-card-breadcrumb a{display:inline-flex;align-items:center;gap:.45rem;min-height:44px;color:var(--text-secondary);font-weight:700;text-decoration:none}.project-card-breadcrumb a:hover{color:var(--accent)}.project-card-breadcrumb>[aria-current=page]{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--text)}.project-card-archived{display:flex;align-items:center;gap:.5rem;padding:.7rem .9rem;border:1px solid var(--warning,#b77716);border-radius:.7rem;background:color-mix(in srgb,var(--warning,#b77716) 10%,var(--surface));color:var(--text);font-size:.86rem}.project-card-header{display:flex;justify-content:space-between;align-items:flex-start;gap:1rem;margin-bottom:1.15rem}.project-card-heading{min-width:0}.project-card-eyebrow{margin:0 0 .35rem;color:var(--accent);font-size:.67rem;font-weight:800;letter-spacing:.14em;text-transform:uppercase}.project-card-heading h1{font-size:clamp(1.6rem,3vw,2.25rem);font-weight:800;line-height:1.15;overflow-wrap:anywhere;margin:0 0 .75rem}.project-card-badges{display:flex;flex-wrap:wrap;gap:.45rem}.project-card-badge{display:inline-flex;align-items:center;gap:.35rem;min-height:32px;padding:.35rem .65rem;border:1px solid var(--border);border-radius:99px;background:var(--surface);color:var(--text-secondary);font-size:.78rem;font-weight:650}.project-card-badge.priority-high{color:var(--negative,#a33);border-color:color-mix(in srgb,var(--negative,#a33) 35%,var(--border))}.project-card-badge.priority-medium{color:var(--warning,#875700);border-color:color-mix(in srgb,var(--warning,#875700) 35%,var(--border))}.project-card-badge.priority-low{color:var(--positive,#28734c);border-color:color-mix(in srgb,var(--positive,#28734c) 35%,var(--border))}.project-card-badge.blocked{color:var(--negative,#a33)}.project-card-actions{position:relative;flex:none}.project-card-actions>summary{list-style:none;display:grid;place-items:center;width:46px;height:46px;border:1px solid var(--border);border-radius:.7rem;background:var(--surface);color:var(--text);cursor:pointer;font-size:1.25rem}.project-card-actions>summary::-webkit-details-marker{display:none}.project-card-actions-menu{position:absolute;z-index:20;right:0;top:calc(100% + .35rem);min-width:12rem;padding:.35rem;border:1px solid var(--border);border-radius:.75rem;background:var(--surface);box-shadow:0 8px 24px rgba(0,0,0,.14)}.project-card-actions-menu a,.project-card-actions-menu button{display:flex;align-items:center;gap:.55rem;width:100%;min-height:44px;padding:.55rem .7rem;border:0;border-radius:.45rem;background:transparent;color:var(--text);text-align:left;text-decoration:none;font:inherit;font-size:.88rem}.project-card-actions-menu a:hover,.project-card-actions-menu button:hover{background:var(--surface-secondary)}.project-card-actions-menu button.danger{color:var(--negative,#a33)}.project-card-actions-menu form{margin:0}.project-card-layout{display:grid;grid-template-columns:minmax(0,1.7fr) minmax(17rem,.8fr);gap:1rem;align-items:start}.project-card-main,.project-card-sidebar{display:grid;gap:1rem;min-width:0}.project-detail-panel,.project-note-card{min-width:0;padding:1.2rem;border:1px solid var(--border);border-radius:1rem;background:var(--surface);color:var(--text);box-shadow:var(--shadow,0 4px 18px rgba(0,0,0,.04))}.project-detail-heading{display:flex;justify-content:space-between;align-items:center;gap:1rem;margin-bottom:.9rem}.project-detail-heading h2{margin:0;font-size:1.08rem;font-weight:800}.project-updated{color:var(--text-muted);font-size:.77rem;white-space:nowrap}.project-card-markdown{font-size:.97rem;line-height:1.75;overflow-wrap:anywhere}.project-card-markdown>:first-child{margin-top:0}.project-card-markdown>:last-child{margin-bottom:0}.project-card-markdown pre,.project-raw-markdown pre{max-width:100%;overflow:auto;padding:1rem;border:1px solid var(--border);border-radius:.7rem;background:var(--surface-secondary);color:var(--text);white-space:pre}.project-card-markdown img{max-width:100%;height:auto}.project-raw-markdown{margin-top:1rem;border-top:1px solid var(--border);padding-top:.75rem}.project-raw-markdown summary{display:flex;align-items:center;gap:.45rem;min-height:44px;color:var(--text-secondary);font-size:.86rem;font-weight:700;cursor:pointer}.project-raw-markdown pre{margin:.6rem 0 0;max-height:28rem;font-size:.8rem}.project-empty-state{margin:.25rem 0;color:var(--text-muted);font-size:.9rem}.project-card-notes{display:grid;gap:.85rem}.project-card-notes>.project-detail-heading{margin:0}.project-count{display:inline-grid;place-items:center;min-width:1.45rem;height:1.45rem;padding:0 .3rem;border-radius:99px;background:var(--surface-secondary);color:var(--text-secondary);font-size:.72rem;font-weight:800;vertical-align:middle}.project-note-form{display:grid;gap:.55rem;padding:1rem;border:1px solid var(--border);border-radius:.85rem;background:var(--surface)}.project-note-form label,.project-upload-form label{color:var(--text-secondary);font-size:.83rem;font-weight:750}.project-note-form textarea{min-height:6rem;resize:vertical}.project-note-submit{display:flex;justify-content:space-between;align-items:center;gap:.7rem}.project-note-submit small{color:var(--text-muted);font-size:.75rem}.project-note-submit .btn{min-height:44px}.project-note-list{display:grid;gap:.75rem}.project-note-card{padding:1rem}.project-note-card>header{display:flex;align-items:center;gap:.65rem}.project-note-avatar{display:grid;place-items:center;width:2.25rem;height:2.25rem;border-radius:50%;background:var(--surface-secondary);color:var(--accent);font-weight:800}.project-note-card>header strong,.project-note-card>header time{display:block}.project-note-card>header strong{font-size:.86rem}.project-note-card>header time{margin-top:.1rem;color:var(--text-muted);font-size:.76rem}.project-note-body{margin:.85rem 0;line-height:1.65;overflow-wrap:anywhere}.project-note-files-title{margin:1rem 0 .45rem;color:var(--text-secondary);font-size:.82rem;font-weight:800}.project-upload-form{display:flex;flex-wrap:wrap;align-items:center;gap:.55rem;margin-top:.75rem;padding-top:.75rem;border-top:1px solid var(--border)}.project-upload-form label{display:flex;align-items:center;gap:.35rem;flex-basis:100%;min-height:36px;margin:0}.project-upload-form input[type=file]{min-width:0;flex:1}.project-upload-form button{min-height:42px}.project-upload-form [role=status]{flex-basis:100%;color:var(--text-muted);font-size:.78rem}.project-card-sidebar .project-detail-heading{margin-bottom:.6rem}.project-properties dl{margin:0}.project-properties dl>div{display:grid;grid-template-columns:minmax(5rem,.8fr) minmax(0,1.2fr);gap:.5rem;padding:.62rem 0;border-top:1px solid var(--border)}.project-properties dt{color:var(--text-muted);font-size:.8rem;font-weight:600}.project-properties dd{display:flex;flex-wrap:wrap;align-items:center;gap:.35rem;margin:0;color:var(--text);font-size:.83rem;font-weight:700;overflow-wrap:anywhere}.project-property-dot{width:.55rem;height:.55rem;border-radius:50%;background:var(--text-muted)}.project-property-dot.priority-high{background:var(--negative,#a33)}.project-property-dot.priority-medium{background:var(--warning,#875700)}.project-property-dot.priority-low{background:var(--positive,#28734c)}.project-properties .project-tags-row{display:block}.project-properties .project-tags-row dd{margin-top:.35rem}.project-tag{padding:.25rem .5rem;border-radius:99px;background:var(--surface-secondary);color:var(--text-secondary);font-size:.73rem}.project-blocked-reason{margin-top:.65rem;padding:.75rem;border-radius:.65rem;background:var(--surface-secondary);font-size:.83rem}.project-blocked-reason strong{color:var(--negative,#a33)}.project-blocked-reason p{margin:.35rem 0 0;overflow-wrap:anywhere}.project-card-files .attachment-list,.project-card-files ul{padding:0}.project-card-files ul>li{align-items:flex-start!important;background:var(--surface);border-color:var(--border)!important}.project-card-files ul>li>a:first-child{overflow-wrap:anywhere}.project-card-files ul>li small{color:var(--text-muted)!important}.project-card-history{padding:0;overflow:hidden}.project-card-history>summary{display:flex;align-items:center;justify-content:space-between;gap:.5rem;min-height:58px;padding:.8rem 1.1rem;list-style:none;cursor:pointer;font-weight:800}.project-card-history>summary::-webkit-details-marker{display:none}.project-card-history>summary>span:first-child{display:flex;align-items:center;gap:.55rem}.project-history-list{list-style:none;margin:0;padding:0 1.1rem 1rem}.project-history-list li{padding:.7rem 0;border-top:1px solid var(--border)}.project-history-list p{margin:0 0 .25rem;font-size:.84rem;font-weight:700}.project-history-list small{color:var(--text-muted);font-size:.75rem}.project-card-page :focus-visible{outline:3px solid var(--focus,#43785e);outline-offset:2px}.project-card-page button,.project-card-page a,.project-card-page summary{touch-action:manipulation} +@media(max-width:1000px){.project-card-layout{grid-template-columns:minmax(0,1.35fr) minmax(15rem,.8fr);gap:.8rem}.project-detail-panel{padding:1rem}} +@media(max-width:760px){.project-card-page{padding-bottom:calc(5.7rem + env(safe-area-inset-bottom))}.project-card-breadcrumb{margin-bottom:.55rem}.project-card-header{gap:.5rem;margin-bottom:.9rem}.project-card-heading h1{font-size:1.65rem}.project-card-badges{gap:.35rem}.project-card-badge{min-height:36px;padding:.35rem .55rem;font-size:.74rem}.project-card-actions>summary{width:44px;height:44px}.project-card-layout{grid-template-columns:minmax(0,1fr);gap:.8rem}.project-card-main,.project-card-sidebar{gap:.8rem}.project-card-sidebar{grid-row:2}.project-detail-panel{padding:.95rem}.project-detail-heading{align-items:flex-start}.project-updated{white-space:normal;text-align:right}.project-upload-form{display:grid;grid-template-columns:minmax(0,1fr) auto}.project-upload-form label,.project-upload-form [role=status],.project-upload-form progress{grid-column:1/-1}.project-upload-form input[type=file]{width:100%;grid-column:1/-1}.project-upload-form button{grid-column:1/-1;width:100%}.project-properties dl>div{grid-template-columns:minmax(5.5rem,.8fr) minmax(0,1.2fr)}.project-note-submit{align-items:flex-start;flex-direction:column}.project-note-submit .btn{width:100%}.project-card-files ul>li{display:grid!important;grid-template-columns:minmax(0,1fr) auto}.project-card-files ul>li>*{min-width:0}.project-card-files ul>li small,.project-card-files ul>li details{grid-column:1/-1}.project-card-files ul>li form{grid-column:2;grid-row:1}.project-card-files ul>li form button{min-height:40px}.project-card-history>summary{min-height:54px}} +@media(max-width:360px){.project-card-heading h1{font-size:1.45rem}.project-card-badge{font-size:.7rem;padding-inline:.45rem}.project-card-breadcrumb{font-size:.78rem}.project-note-card,.project-detail-panel{padding:.8rem}.project-properties dl>div{grid-template-columns:5rem minmax(0,1fr)}} +@media(prefers-reduced-motion:reduce){.project-card-page *{scroll-behavior:auto!important}} +.project-card-actions-menu button[data-open-move-dialog]{width:100%;display:flex;align-items:center;gap:.65rem;border:0;background:transparent;color:inherit;text-align:left;padding:.65rem .8rem;font:inherit;cursor:pointer}.project-card-actions-menu button[data-open-move-dialog]:hover{background:var(--surface-secondary)}.project-card-actions-menu button:disabled{opacity:.55;cursor:not-allowed}.project-move-dialog{width:min(34rem,calc(100vw - 2rem));max-height:calc(100vh - 2rem);border:1px solid var(--border);border-radius:1rem;padding:1.4rem;background:var(--surface);color:var(--text);box-shadow:var(--shadow,0 1rem 4rem #12221940)}.project-move-dialog::backdrop{background:#14211980;backdrop-filter:blur(2px)}.project-move-dialog form{display:grid;gap:.8rem}.project-move-dialog-heading{display:flex;justify-content:space-between;align-items:flex-start;margin-bottom:.35rem}.project-move-dialog-heading h2{font-size:1.35rem;margin:0}.project-move-close{border:0;background:transparent;font-size:1.7rem;line-height:1;padding:.15rem .45rem;color:inherit}.project-move-dialog label{font-weight:650}.project-move-confirmation{padding:.8rem;border-radius:.7rem;background:var(--surface-secondary);margin:.25rem 0}.project-move-dialog-actions{display:flex;justify-content:flex-end;gap:.6rem;margin-top:.25rem}.project-move-dialog :focus-visible{outline:3px solid var(--focus,#43785e);outline-offset:2px}@media(prefers-reduced-motion:reduce){.project-move-dialog::backdrop{backdrop-filter:none}} diff --git a/projects/static/projects/card_move.css b/projects/static/projects/card_move.css new file mode 100644 index 0000000..4ac9c1a --- /dev/null +++ b/projects/static/projects/card_move.css @@ -0,0 +1 @@ +.project-card-messages{margin:0 0 1rem}.project-card-message{margin:0;padding:.8rem 1rem;border-radius:.7rem;background:var(--surface);color:var(--text);border:1px solid var(--border)}.project-card-message.success{border-color:var(--accent);background:color-mix(in srgb,var(--accent) 10%,var(--surface))}.project-card-message.error{border-color:var(--danger,#b42318)}.project-card-actions-menu .project-move-unavailable{display:block;padding:.65rem .8rem;color:var(--text-muted);font-size:.8rem} diff --git a/projects/static/projects/card_move.js b/projects/static/projects/card_move.js new file mode 100644 index 0000000..4c667ea --- /dev/null +++ b/projects/static/projects/card_move.js @@ -0,0 +1,47 @@ +(() => { + const dialog = document.querySelector('[data-project-move-dialog]'); + if (!dialog || dialog.dataset.initialized) return; + dialog.dataset.initialized = 'true'; + const projectSelect = dialog.querySelector('[data-move-project]'); + const columnSelect = dialog.querySelector('[data-move-column]'); + const confirmation = dialog.querySelector('[data-move-confirmation]'); + const form = dialog.querySelector('[data-project-move-form]'); + const opener = document.querySelector('[data-open-move-dialog]'); + const source = document.querySelector('.project-card-heading .project-card-eyebrow')?.textContent.trim() || 'this project'; + + const update = () => { + if (!projectSelect || !columnSelect) return; + const selectedProject = projectSelect.selectedOptions[0]; + const projectId = selectedProject.value; + const defaultId = selectedProject.dataset.defaultColumn; + const defaultName = selectedProject.dataset.defaultName; + for (const option of columnSelect.options) { + const visible = !option.dataset.projectId || option.dataset.projectId === projectId; + option.hidden = !visible; + option.disabled = !visible; + } + const requested = [...columnSelect.options].find(option => option.value === defaultId); + if (requested) columnSelect.value = requested.value; + else columnSelect.value = ''; + const chosen = columnSelect.selectedOptions[0]; + const columnName = chosen?.value ? chosen.textContent.split(' · ').slice(1).join(' · ').replace(/ \(default\)$/, '') : defaultName; + confirmation.textContent = `Move this card from ${source} to ${selectedProject.textContent} · ${columnName}? Its notes, files, and history will move with it.`; + }; + + opener?.addEventListener('click', () => { + update(); + dialog.showModal(); + }); + dialog.querySelectorAll('[data-close-move-dialog]').forEach(button => button.addEventListener('click', () => dialog.close())); + dialog.addEventListener('close', () => opener?.focus()); + projectSelect?.addEventListener('change', update); + columnSelect?.addEventListener('change', update); + form?.addEventListener('submit', () => { + const submit = form.querySelector('[data-move-submit]'); + if (submit) { + submit.disabled = true; + submit.textContent = 'Moving…'; + } + }); + update(); +})(); diff --git a/projects/static/projects/project_list.css b/projects/static/projects/project_list.css new file mode 100644 index 0000000..9dd7f49 --- /dev/null +++ b/projects/static/projects/project_list.css @@ -0,0 +1,5 @@ +.projects-index{max-width:1380px;margin:0 auto;padding-bottom:1rem;color:var(--text)}.projects-index-header{display:flex;justify-content:space-between;align-items:flex-end;gap:1rem;margin-bottom:1.2rem}.projects-index-eyebrow{margin:0 0 .35rem;color:var(--accent);font-size:.67rem;font-weight:800;letter-spacing:.14em}.projects-index-header h1{margin:0;font-size:clamp(1.8rem,3vw,2.35rem);font-weight:800}.projects-index-intro{margin:.4rem 0 0;color:var(--text-secondary);font-size:.92rem}.projects-new-button{min-height:46px;display:inline-flex;align-items:center;justify-content:center;gap:.4rem;font-weight:700;white-space:nowrap}.projects-view-tabs{display:flex;gap:.4rem;border-bottom:1px solid var(--border);margin-bottom:1rem}.projects-view-tabs a{display:inline-flex;align-items:center;justify-content:center;gap:.45rem;min-height:46px;padding:.45rem .8rem;border-bottom:2px solid transparent;color:var(--text-secondary);font-size:.86rem;font-weight:700;text-decoration:none}.projects-view-tabs a[aria-current=page]{border-color:var(--accent);color:var(--accent)}.projects-search-form{display:flex;align-items:center;gap:.6rem;margin-bottom:1rem}.projects-search-box{position:relative;display:block;flex:1}.projects-search-box>i{position:absolute;left:.9rem;top:50%;transform:translateY(-50%);color:var(--text-muted);pointer-events:none}.projects-search-box input{height:48px;padding-left:2.65rem;border-radius:.75rem}.projects-clear-search{display:inline-flex;align-items:center;justify-content:center;gap:.4rem;min-height:44px}.projects-search-form .htmx-indicator{position:absolute;clip:rect(0 0 0 0)}.projects-card-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:1rem}.project-index-card{display:flex;flex-direction:column;min-width:0;min-height:17rem;padding:1.15rem;border:1px solid var(--border);border-radius:1rem;background:var(--surface);color:var(--text);box-shadow:var(--shadow,0 4px 18px rgba(0,0,0,.04));transition:transform .15s ease,border-color .15s ease}.project-index-card:hover{transform:translateY(-2px);border-color:var(--accent)}.project-index-card.is-archived{background:var(--surface-secondary)}.project-index-card-top{display:flex;align-items:center;justify-content:space-between;margin-bottom:.85rem}.project-index-icon,.projects-empty-icon{display:grid;place-items:center;width:2.5rem;height:2.5rem;border-radius:.8rem;background:var(--surface-secondary);color:var(--accent);font-size:1.15rem}.project-archived-badge{display:inline-flex;align-items:center;gap:.35rem;padding:.35rem .55rem;border:1px solid var(--border);border-radius:99px;color:var(--text-muted);font-size:.72rem;font-weight:750}.project-index-card h2{margin:0 0 .45rem;font-size:1.12rem;font-weight:800;line-height:1.3;overflow-wrap:anywhere}.project-index-card h2 a{color:var(--text);text-decoration:none}.project-index-card h2 a:hover{color:var(--accent)}.project-index-description{min-height:2.7rem;margin:0;color:var(--text-secondary);font-size:.84rem;line-height:1.55;overflow-wrap:anywhere}.project-index-progress{margin-top:auto;padding-top:1rem}.project-index-progress-copy{display:flex;justify-content:space-between;align-items:baseline;gap:.5rem;margin-bottom:.4rem;color:var(--text-secondary);font-size:.76rem}.project-index-progress-copy strong{color:var(--text);font-size:.79rem}.project-index-progress-track{height:6px;border-radius:99px;background:var(--surface-secondary);overflow:hidden}.project-index-progress-track span{display:block;height:100%;border-radius:inherit;background:var(--positive,var(--accent))}.project-index-meta{display:flex;flex-wrap:wrap;justify-content:space-between;gap:.55rem;margin-top:.85rem;padding-top:.7rem;border-top:1px solid var(--border);color:var(--text-muted);font-size:.76rem}.project-index-meta span,.project-index-meta a{display:inline-flex;align-items:center;gap:.35rem}.project-index-meta a{color:var(--text-secondary);text-decoration:none}.project-index-meta a:hover{color:var(--accent)}.project-index-actions{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:.5rem;margin-top:.9rem}.project-index-actions .btn{min-height:44px;display:inline-flex;align-items:center;justify-content:center;gap:.4rem}.project-index-actions .btn-outline-secondary{min-width:4.4rem}.projects-empty-state{display:grid;justify-items:center;align-content:center;min-height:18rem;padding:2rem 1rem;border:1px dashed var(--border);border-radius:1rem;background:var(--surface);text-align:center}.projects-empty-icon{width:3.2rem;height:3.2rem;margin-bottom:.9rem;font-size:1.45rem}.projects-empty-state h2{margin:0;font-size:1.15rem;font-weight:800}.projects-empty-state p{max-width:35rem;margin:.45rem 0 1rem;color:var(--text-secondary);font-size:.88rem}.projects-empty-state .btn{min-height:44px}.projects-pagination{display:grid;grid-template-columns:1fr auto 1fr;align-items:center;gap:.7rem;margin-top:1rem;color:var(--text-secondary);font-size:.84rem}.projects-pagination>.btn{display:inline-flex;align-items:center;justify-content:center;gap:.35rem;min-height:44px}.projects-pagination>.btn:last-child{justify-self:end}.projects-index :focus-visible{outline:3px solid var(--focus,#43785e);outline-offset:2px}.projects-index a,.projects-index button{touch-action:manipulation} +@media(max-width:1050px){.projects-card-grid{grid-template-columns:repeat(2,minmax(0,1fr))}} +@media(max-width:760px){.projects-index{padding-bottom:calc(5.7rem + env(safe-area-inset-bottom))}.projects-index-header{align-items:flex-start}.projects-index-header h1{font-size:1.8rem}.projects-index-intro{max-width:25rem;font-size:.85rem}.projects-new-button{min-height:44px;padding-inline:.75rem}.projects-view-tabs a{flex:1}.projects-search-form{align-items:stretch}.projects-search-box input{height:48px}.projects-card-grid{grid-template-columns:minmax(0,1fr);gap:.75rem}.project-index-card{min-height:0;padding:1rem}.project-index-description{min-height:0}.project-index-progress{margin-top:.7rem;padding-top:.8rem}.project-index-actions{margin-top:.8rem}.projects-empty-state{min-height:15rem;padding:1.5rem 1rem}.projects-pagination{grid-template-columns:1fr auto 1fr}} +@media(max-width:360px){.projects-index-header{gap:.5rem}.projects-index-header h1{font-size:1.55rem}.projects-index-intro{font-size:.78rem}.projects-new-button{padding-inline:.55rem;font-size:.82rem}.projects-view-tabs a{padding-inline:.45rem;font-size:.8rem}.projects-search-form{gap:.4rem}.projects-clear-search{padding-inline:.6rem}.project-index-card{padding:.85rem}.projects-pagination{font-size:.75rem;gap:.3rem}.projects-pagination .btn{padding-inline:.5rem}} +@media(prefers-reduced-motion:reduce){.project-index-card{transition:none}} diff --git a/projects/templates/projects/_board.html b/projects/templates/projects/_board.html index 4e51de3..2efe99d 100644 --- a/projects/templates/projects/_board.html +++ b/projects/templates/projects/_board.html @@ -1,4 +1,4 @@ -
+
{% for column in columns %}
@@ -31,6 +31,7 @@
{% endfor %} + {% if not column.visible_cards %}

{% if show_archived %}No archived cards in this column.{% else %}No cards in this column yet.{% endif %}

{% endif %}
{% endfor %} diff --git a/projects/templates/projects/_project_list.html b/projects/templates/projects/_project_list.html index 46fde1d..4a74e93 100644 --- a/projects/templates/projects/_project_list.html +++ b/projects/templates/projects/_project_list.html @@ -1 +1,11 @@ -
{% for project in projects %}

{{ project.name }}

{{ project.description|truncatechars:180 }}

{{ project.card_count }} cards
Browse documentation{% if project.git_repository_url %}Repository{% endif %}
{% empty %}

No projects found.

{% endfor %}
{% if page_obj.has_other_pages %}{% endif %} +{% if projects %}
+ {% for project in projects %}
+
{% if project.archived %} Archived{% endif %}
+

{{ project.name }}

+

{{ project.description|default:'No project description yet.'|truncatechars:180 }}

+
{{ project.done_card_count }} of {{ project.active_card_count }} active cards done{{ project.progress_percent }}%
+
{{ project.card_count }} card{{ project.card_count|pluralize }}{% if project.git_repository_url %} Repository{% endif %}
+ +
{% endfor %} +
{% else %}

{% if query %}No matching projects{% elif show_archived %}No archived projects{% else %}No projects yet{% endif %}

{% if query %}Try a different project or card search.{% elif show_archived %}Archived projects will appear here.{% else %}Create a project to start organizing cards and specifications.{% endif %}

{% if not query and not show_archived %} New project{% endif %}
{% endif %} +{% if page_obj.has_other_pages %}{% endif %} diff --git a/projects/templates/projects/board.html b/projects/templates/projects/board.html index 6f3ba44..4172684 100644 --- a/projects/templates/projects/board.html +++ b/projects/templates/projects/board.html @@ -1,59 +1,112 @@ {% extends 'core/base.html' %} +{% load static %} +{% block extra_head %}{% endblock %} {% block content %} -
-
All projects

{{ project.name }}

{{ project.description }}

{% if project.git_repository_url %}Repository{% endif %}

{{ done_count }} of {{ total_count }} cards done

-
- Browse documentation - {% if can_edit %}Edit project{% if project.archived %}
{% csrf_token %}
{% else %}
{% csrf_token %}
New card{% endif %}{% endif %} -
+
+
+
+ All projects +

{{ project.name }}

{% if project.git_repository_url %} Repository{% endif %}
+ {% if can_edit %}
Project actions
Edit project{% if project.archived %}
{% csrf_token %}
{% else %}
{% csrf_token %}
{% endif %}
{% endif %} +
+ {% if project.description %}

{{ project.description }}

{% endif %} +
{{ done_count }} / {{ total_count }}cards complete
+
+
{% if can_edit and not project.archived %} New card{% endif %} Browse documentation
+
+ +
{% for label,count in priority_counts %}{{ label }} {{ count }}{% endfor %}
+ + + Updating cards… + {% if can_edit and not show_archived %}
0 cards selected
{% endif %} +

On narrow screens, scroll horizontally to see more columns. Use the move controls on each card to move it without dragging.

{% if columns|length > 1 %}{% endif %}
{% include 'projects/_board.html' %}
+ {% if can_edit %}{% endif %} + +

UPDATES

Recent activity

{% if older_activity %}View all{% endif %}
+ {% if recent_activity %}
    {% for event in recent_activity %}
  1. {% if event.card %}{{ event.card.title }} {{ event.display_action }}{% else %}{{ event.display_action }}{% endif %}

    {% if event.actor %}{{ event.actor }}{% else %}A former member{% endif %} ·
  2. {% endfor %}
+ {% if older_activity %}
View all activity ({{ older_activity|length }} older events)
    {% for event in older_activity %}
  1. {% if event.card %}{{ event.card.title }} {{ event.display_action }}{% else %}{{ event.display_action }}{% endif %}

    {% if event.actor %}{{ event.actor }}{% else %}A former member{% endif %} ·
  2. {% endfor %}
{% endif %} + {% else %}

No activity yet. Updates will appear here.

{% endif %} +
-
{% for label,count in priority_counts %}{{ label }}: {{ count }} open{% endfor %}
- -Searching… -{% if can_edit and not show_archived %}
0 cards selected
{% endif %} -
{% include 'projects/_board.html' %}
-{% if can_edit %}Add column -Add tag{% endif %} -

Recent activity

    {% for event in recent_activity %}
  • {{ event.created_at }} · {{ event.action }}{% if event.actor %} by {{ event.actor }}{% endif %}
  • {% empty %}
  • No activity yet.
  • {% endfor %}
- -{% if can_edit %} - - {% csrf_token %} -{% endif %} + +{% if can_edit %}{% endif %} + {% endblock %} diff --git a/projects/templates/projects/card.html b/projects/templates/projects/card.html index b7463a8..c56200b 100644 --- a/projects/templates/projects/card.html +++ b/projects/templates/projects/card.html @@ -1,18 +1,47 @@ {% extends 'core/base.html' %}{% load project_markdown static %} +{% block extra_head %}{% endblock %} {% block content %} -← {{ card.project.name }} -

{{ card.title }}

{% if can_edit %}
Edit {% if card.archived %}
{% csrf_token %}
{% else %}
{% csrf_token %}
{% endif %}
{% endif %}
-

{{ card.get_priority_display }} {{ card.column.name }} · {{ card.get_card_type_display }} · Revision {{ card.revision }}

-
{{ card.description_markdown|safe_markdown }}
-
Raw Markdown
{{ card.description_markdown }}
-

Card files

-{% include 'projects/_attachment_list.html' with files=card_files %} -{% if can_edit %}
{% csrf_token %}
{% endif %}
-

Progress notes

-{% for comment in comments %}
{{ comment.author }} · {{ comment.created_at }}

{{ comment.body|linebreaksbr }}

Files on this progress note

-{% include 'projects/_attachment_list.html' with files=comment.attachments.all %} -{% if can_edit %}
{% csrf_token %}
{% endif %}
{% endfor %} -{% if can_edit %}
{% csrf_token %}
{% endif %} -

History

    {% for event in card.activity.all %}
  • {{ event.created_at }} · {{ event.action }} by {{ event.actor }}
  • {% endfor %}
+
+ {% if messages %}
{% for message in messages %}

{{ message }}

{% endfor %}
{% endif %} + + {% if card.archived %}

This card is archived.

{% endif %} +
+

{{ card.project.name }}

{{ card.title }}

{{ card.get_priority_display }} priority{{ card.column.name }}{{ card.get_card_type_display }}Revision {{ card.revision }}{% if card.is_blocked %}Blocked{% endif %}
+ {% if can_edit %}
Card actions
Edit card{% if destination_options %}{% else %}No other editable projects are available.{% endif %}{% if card.archived %}
{% csrf_token %}
{% else %}
{% csrf_token %}
{% endif %}
{% endif %} +
+ + {% if can_edit %}
{% csrf_token %}

MOVE CARD

Move to another project

+ {% if destination_options %}

This moves the card from {{ card.project.name }} to the selected project.

{% else %}

No other active projects are available for you to edit.

{% endif %}
{% endif %} + +
+
+

CARD DETAILS

Description

Updated {{ card.updated_at|timesince }} ago
+ {% if card.description_markdown %}
{{ card.description_markdown|safe_markdown }}
{% else %}

No description has been added to this card.

{% endif %} +
View raw Markdown
{{ card.description_markdown }}
+
+ +

DISCUSSION

Progress notes {{ comments|length }}

+ {% if can_edit %}
{% csrf_token %}
Notes are visible to project members.
{% endif %} +
{% for comment in comments %}
{{ comment.author }}

{{ comment.body|linebreaksbr }}

Files on this progress note

{% include 'projects/_attachment_list.html' with files=comment.attachments.all %} + {% if can_edit %}
{% csrf_token %}
{% endif %} +
{% empty %}

No progress notes yet.

{% endfor %}
+
+
+ + +
+
+{% if can_edit and destination_options %}{% endif %} {% endblock %} diff --git a/projects/templates/projects/list.html b/projects/templates/projects/list.html index 3a61600..8c318f9 100644 --- a/projects/templates/projects/list.html +++ b/projects/templates/projects/list.html @@ -1 +1,16 @@ -{% extends 'core/base.html' %}{% block content %}

Projects

Boards and specifications across your workspace.

New project

Active · Archived

{% include 'projects/_project_list.html' %}
{% endblock %} +{% extends 'core/base.html' %}{% load static %} +{% block extra_head %}{% endblock %} +{% block content %} +
+

WORKSPACE

Projects

Boards and specifications across your workspace.

New project
+ + +
{% include 'projects/_project_list.html' %}
+
+ +{% endblock %} diff --git a/projects/test_oauth_mcp.py b/projects/test_oauth_mcp.py index 69047c1..d632102 100644 --- a/projects/test_oauth_mcp.py +++ b/projects/test_oauth_mcp.py @@ -1,10 +1,12 @@ import base64 import hashlib import json +import asyncio +import os from urllib.parse import parse_qs, urlparse from django.contrib.auth import get_user_model -from django.test import TestCase, Client as DjangoClient +from django.test import TestCase, TransactionTestCase, Client as DjangoClient from django.conf import settings from asgiref.sync import async_to_sync from unittest.mock import patch @@ -58,6 +60,13 @@ class OAuthMcpTests(TestCase): project = create_project(self.user, name='Private') self.assertEqual(self.client.get(f'/projects/{project.pk}/').status_code, 302) + def test_cross_project_move_tool_is_registered_with_revision_and_uuid_contract(self): + tool = create_server()._tool_manager.get_tool('cards_move_project') + self.assertIn('another editable project', tool.description) + self.assertEqual(set(tool.parameters['required']), {'card_id', 'target_project', 'expected_revision'}) + self.assertIn('idempotency_key', tool.parameters['properties']) + + def test_client_registration_requires_authenticated_user_and_csrf(self): metadata = {'client_name': 'Private test client', 'redirect_uris': ['https://client.example/callback'], 'grant_types': ['authorization_code', 'refresh_token'], 'token_endpoint_auth_method': 'none'} @@ -90,3 +99,34 @@ class OAuthMcpTests(TestCase): with patch('mcp_server.server.get_access_token', return_value=read): with self.assertRaises(ToolError): async_to_sync(server.call_tool)('cards_set_priority', {'card_id': card['id'], 'priority': 'high', 'expected_revision': 1}) + + +class CrossProjectMoveMcpTests(TransactionTestCase): + def test_cross_project_move_mcp_handler_returns_same_move_result(self): + user = get_user_model().objects.create_user('move-mcp-user', password='test-password') + source = create_project(user, name='MCP source') + destination = create_project(user, name='MCP destination') + from .services import create_card + card = create_card(user, source, title='Move through MCP') + server = create_server() + tool = server._tool_manager.get_tool('cards_move_project') + + class InlineAwaitable: + def __init__(self, function): + self.function = function + + async def __call__(self): + return self.function() + + with patch('mcp_server.server._actor', return_value=user), \ + patch('mcp_server.server.sync_to_async', side_effect=lambda function: InlineAwaitable(function)), \ + patch.dict(os.environ, {'DJANGO_ALLOW_ASYNC_UNSAFE': 'true'}): + data = asyncio.run(tool.fn(card_id=str(card.pk), target_project=str(destination.pk), + target_column_id=str(destination.board.columns.get(is_default=True).pk), + expected_revision=card.revision)) + card.refresh_from_db() + self.assertEqual(data['id'], str(card.pk)) + self.assertEqual(data['project_id'], str(destination.pk)) + self.assertEqual(data['revision'], 2) + self.assertEqual(data['move']['source_project_id'], str(source.pk)) + self.assertEqual(data['move']['target_column_id'], str(card.column_id)) diff --git a/projects/tests.py b/projects/tests.py index 9f27eec..82ba878 100644 --- a/projects/tests.py +++ b/projects/tests.py @@ -1,14 +1,14 @@ from django.contrib.auth import get_user_model -from django.test import TestCase, override_settings +from django.test import TestCase, Client, override_settings from django.core.exceptions import ValidationError from django.urls import reverse -from django.http import HttpResponse +from django.http import HttpResponse, Http404 from django.utils import timezone from unittest.mock import patch -from .models import Activity, Card, CardRevision, Membership, Profile +from .models import Activity, Card, CardRevision, CardComment, CardAttachment, Column, Membership, Profile, Tag from .forms import ProfileForm from .middleware import ProfileTimezoneMiddleware -from .services import RevisionConflict, bulk_update_cards, card_for, create_card, create_project, move_card, update_card, update_column +from .services import RevisionConflict, bulk_update_cards, card_for, create_card, create_project, move_card, move_card_to_project, update_card, update_column class ProjectWorkflowTests(TestCase): @@ -46,17 +46,220 @@ class ProjectWorkflowTests(TestCase): card.refresh_from_db() self.assertIsNotNone(card.completed_at) + def test_cross_project_move_preserves_identity_and_children_and_maps_project_data(self): + destination = create_project(self.owner, name='Destination') + card = create_card(self.owner, self.project, title='Keep me', markdown='# Keep this') + source_sibling = create_card(self.owner, self.project, title='Source sibling') + destination_sibling = create_card(self.owner, destination, title='Destination sibling') + original_updated_at = card.updated_at + card.assignee = self.other + card.save(update_fields=['assignee']) + Membership.objects.create(project=destination, user=self.other, role='viewer') + comment = CardComment.objects.create(card=card, author=self.owner, body='Progress note') + attachment = CardAttachment.objects.create(card=card, comment=comment, file='card-attachments/test.txt', + original_filename='test.txt', title='Source file', mime_type='text/plain', byte_size=4, sha256='a' * 64) + source_tag = Tag.objects.create(project=self.project, name='Roadmap') + target_tag = Tag.objects.create(project=destination, name='roadmap') + card.tags.add(source_tag) + old_activity = card.activity.first() + destination_column = destination.board.columns.get(is_default=True) + + moved, result = move_card_to_project(self.owner, card, destination, + target_column=destination_column, expected_revision=card.revision, idempotency_key='move-preserve') + + moved.refresh_from_db() + self.assertEqual(moved.pk, card.pk) + self.assertEqual(moved.project_id, destination.pk) + self.assertEqual(moved.column_id, destination_column.pk) + self.assertEqual(moved.position, 1) + source_sibling.refresh_from_db() + self.assertEqual(source_sibling.position, 0) + destination_sibling.refresh_from_db() + self.assertEqual(destination_sibling.position, 0) + self.assertEqual(moved.revision, card.revision + 1) + self.assertEqual(moved.description_markdown, '# Keep this') + self.assertEqual(moved.updated_at, original_updated_at) + self.assertEqual(moved.assignee_id, self.other.pk) + self.assertEqual(list(moved.revisions.order_by('revision').values_list('revision', flat=True)), [1, 2]) + self.assertEqual(list(moved.tags.all()), [target_tag]) + self.assertEqual(moved.comments.get(pk=comment.pk).body, 'Progress note') + self.assertEqual(moved.attachments.get(pk=attachment.pk).file.name, 'card-attachments/test.txt') + old_activity.refresh_from_db() + self.assertEqual(old_activity.project_id, destination.pk) + self.assertTrue(moved.activity.filter(action='card.moved_project').exists()) + source_event = Activity.objects.get(project=self.project, action='card.moved_project_out') + self.assertEqual(source_event.detail['card_id'], str(card.pk)) + self.assertEqual(result['source_project_id'], str(self.project.pk)) + self.assertEqual(result['revision'], moved.revision) + + def test_cross_project_move_clears_invalid_assignee_and_tags_with_warnings(self): + destination = create_project(self.owner, name='Destination') + card = create_card(self.owner, self.project, title='Transfer') + card.assignee = self.other + card.save(update_fields=['assignee']) + tag = Tag.objects.create(project=self.project, name='Only here') + card.tags.add(tag) + moved, result = move_card_to_project(self.owner, card, destination, expected_revision=card.revision) + self.assertIsNone(moved.assignee_id) + self.assertFalse(moved.tags.exists()) + self.assertEqual(len(result['warnings']), 2) + + def test_cross_project_move_validates_access_column_revision_and_idempotency(self): + destination = create_project(self.owner, name='Destination') + private_destination = create_project(self.other, name='Private destination') + archived_destination = create_project(self.owner, name='Archived destination') + archived_destination.archived = True + archived_destination.save(update_fields=['archived']) + card = create_card(self.owner, self.project, title='Transfer') + foreign_column = private_destination.board.columns.get(is_default=True) + with self.assertRaises(ValidationError): + move_card_to_project(self.owner, card, destination, target_column=foreign_column, expected_revision=1) + with self.assertRaises(RevisionConflict): + move_card_to_project(self.owner, card, destination, expected_revision=0) + with self.assertRaises(Http404): + move_card_to_project(self.owner, card, private_destination, expected_revision=1) + with self.assertRaises(ValidationError): + move_card_to_project(self.owner, card, archived_destination, expected_revision=1) + moved, _ = move_card_to_project(self.owner, card, destination, expected_revision=1, idempotency_key='retry-1') + replay, result = move_card_to_project(self.owner, card, destination, expected_revision=1, idempotency_key='retry-1') + self.assertEqual(replay.pk, moved.pk) + self.assertEqual(result['revision'], moved.revision) + with self.assertRaises(ValidationError): + move_card_to_project(self.owner, card, private_destination, expected_revision=1, idempotency_key='retry-1') + + def test_cross_project_move_ui_requires_csrf_and_shows_success_or_stale_feedback(self): + destination = create_project(self.owner, name='Destination') + card = create_card(self.owner, self.project, title='Transfer') + browser = Client(enforce_csrf_checks=True) + browser.force_login(self.owner) + detail = browser.get(reverse('projects:card', args=[card.pk])) + self.assertContains(detail, 'Move to project') + self.assertContains(detail, 'Destination') + csrf = browser.cookies['csrftoken'].value + move_url = reverse('projects:card_move_project', args=[card.pk]) + payload = {'target_project_id': str(destination.pk), 'target_column_id': '', + 'expected_revision': str(card.revision), 'idempotency_key': 'web-move-1'} + self.assertEqual(browser.post(move_url, payload).status_code, 403) + stale = browser.post(move_url, {**payload, 'expected_revision': '0', 'idempotency_key': 'web-stale'}, HTTP_X_CSRFTOKEN=csrf) + self.assertEqual(stale.status_code, 302) + stale_detail = browser.get(reverse('projects:card', args=[card.pk])) + self.assertContains(stale_detail, 'This card changed before it could be moved.') + response = browser.post(move_url, payload, HTTP_X_CSRFTOKEN=csrf) + self.assertEqual(response.status_code, 302) + self.assertEqual(response['Location'], reverse('projects:card', args=[card.pk])) + self.assertEqual(Card.objects.get(pk=card.pk).project_id, destination.pk) + self.assertContains(browser.get(reverse('projects:card', args=[card.pk])), 'Moved “Transfer” from BoomCast to Destination.') + + def test_cross_project_move_rolls_back_when_revision_creation_fails(self): + destination = create_project(self.owner, name='Destination') + card = create_card(self.owner, self.project, title='Transfer') + with patch.object(CardRevision.objects, 'create', side_effect=RuntimeError('revision store unavailable')): + with self.assertRaises(RuntimeError): + move_card_to_project(self.owner, card, destination, expected_revision=card.revision) + card.refresh_from_db() + self.assertEqual(card.project_id, self.project.pk) + self.assertEqual(card.revision, 1) + self.assertFalse(Activity.objects.filter(action='card.moved_project_out').exists()) + def test_board_filters_and_escaped_markdown(self): card = create_card(self.owner, self.project, title='Danger', markdown='\n\n# Safe') self.client.force_login(self.owner) response = self.client.get(reverse('projects:board', args=[self.project.pk]), {'priority': 'medium'}) - self.assertContains(response, 'Danger') + visible = [card for column in response.context['columns'] for card in column.visible_cards] + self.assertEqual([item.pk for item in visible], [card.pk]) response = self.client.get(reverse('projects:board', args=[self.project.pk]), {'priority': 'high'}) - self.assertNotContains(response, 'Danger') + visible = [item for column in response.context['columns'] for item in column.visible_cards] + self.assertEqual(visible, []) response = self.client.get(reverse('projects:card', args=[card.pk])) self.assertNotContains(response, '', html=False) self.assertContains(response, '

Safe

', html=False) + def test_board_archive_filter_and_mobile_filter_sheet(self): + active = create_card(self.owner, self.project, title='Active card') + archived = create_card(self.owner, self.project, title='Archived card') + archived.archived = True + archived.save(update_fields=['archived']) + self.client.force_login(self.owner) + response = self.client.get(reverse('projects:board', args=[self.project.pk])) + visible = [card for column in response.context['columns'] for card in column.visible_cards] + self.assertEqual([card.pk for card in visible], [active.pk]) + self.assertContains(response, 'role="dialog"') + self.assertContains(response, 'Show archived cards') + response = self.client.get(reverse('projects:board', args=[self.project.pk]), {'archived': '1'}) + visible = [card for column in response.context['columns'] for card in column.visible_cards] + self.assertEqual([card.pk for card in visible], [archived.pk]) + + def test_board_progress_is_zero_safe_and_activity_is_human_readable(self): + self.client.force_login(self.owner) + response = self.client.get(reverse('projects:board', args=[self.project.pk])) + self.assertEqual(response.context['progress_percent'], 0) + self.assertContains(response, '0 / 0') + card = create_card(self.owner, self.project, title='Timeline card') + for index in range(5): + Activity.objects.create(project=self.project, card=card, actor=self.owner, + action='card.moved', detail={'sequence': index}) + response = self.client.get(reverse('projects:board', args=[self.project.pk])) + self.assertEqual(len(response.context['recent_activity']), 3) + self.assertGreater(len(response.context['older_activity']), 0) + self.assertContains(response, 'moved a card') + self.assertContains(response, 'View all') + + def test_card_detail_uses_responsive_layout_and_readable_history(self): + card = create_card(self.owner, self.project, title='Detail view card', markdown='# Description\n\nCard detail text.') + self.client.force_login(self.owner) + response = self.client.get(reverse('projects:card', args=[card.pk])) + self.assertEqual(response.status_code, 200) + self.assertContains(response, 'projects/card_detail.css') + self.assertContains(response, 'Description') + self.assertContains(response, 'Card info') + self.assertContains(response, 'Progress notes') + self.assertContains(response, 'View raw Markdown') + self.assertContains(response, 'created this card') + self.assertContains(response, 'Edit card') + self.assertContains(response, 'Add a progress note') + + def test_card_detail_preserves_viewer_read_only_permissions(self): + card = create_card(self.owner, self.project, title='Viewer detail card', markdown='Readable for the team.') + Membership.objects.create(project=self.project, user=self.other, role='viewer') + self.client.force_login(self.other) + response = self.client.get(reverse('projects:card', args=[card.pk])) + self.assertContains(response, 'Readable for the team.') + self.assertContains(response, 'Card info') + self.assertNotContains(response, 'Edit card') + self.assertNotContains(response, 'Add a progress note') + self.assertNotContains(response, 'Add card files') + + def test_projects_index_preserves_search_access_and_archived_view(self): + finished = create_card(self.owner, self.project, title='Searchable milestone') + move_card(self.owner, finished, self.project.board.columns.get(is_done=True)) + archived_card = create_card(self.owner, self.project, title='Old milestone') + archived_card.archived = True + archived_card.save(update_fields=['archived']) + private_project = create_project(self.other, name='Private workspace') + self.client.force_login(self.owner) + url = reverse('projects:list') + response = self.client.get(url) + self.assertContains(response, 'projects/project_list.css') + self.assertContains(response, 'BoomCast') + self.assertNotContains(response, 'Private workspace') + project = next(item for item in response.context['projects'] if item.pk == self.project.pk) + self.assertEqual(project.card_count, 2) + self.assertEqual(project.active_card_count, 1) + self.assertEqual(project.done_card_count, 1) + self.assertEqual(project.progress_percent, 100) + response = self.client.get(url, {'q': 'Searchable'}) + self.assertContains(response, 'BoomCast') + self.assertContains(response, 'Open board') + response = self.client.get(url, {'q': 'Searchable'}, HTTP_HX_REQUEST='true') + self.assertContains(response, 'BoomCast') + self.assertEqual(response.context['query'], 'Searchable') + self.project.archived = True + self.project.save(update_fields=['archived']) + response = self.client.get(url, {'archived': '1'}) + self.assertContains(response, 'Archived') + self.assertContains(response, 'BoomCast') + self.assertNotContains(response, 'Private workspace') + def test_completion_flag_updates_existing_cards(self): card = create_card(self.owner, self.project, title='Complete later') column = card.column diff --git a/projects/urls.py b/projects/urls.py index 9009240..391e68a 100644 --- a/projects/urls.py +++ b/projects/urls.py @@ -27,6 +27,7 @@ urlpatterns = [ path('cards//', views.card_detail, name='card'), path('cards//edit/', views.card_edit, name='card_edit'), path('cards//move/', views.card_move, name='card_move'), + path('cards//move-project/', views.card_move_project, name='card_move_project'), path('cards//comment/', views.card_comment, name='card_comment'), path('cards//attachments/', views.attachment_upload, name='attachment_upload'), path('attachments//download/', views.attachment_download, name='attachment_download'), diff --git a/projects/views.py b/projects/views.py index 80cfc83..a1f8588 100644 --- a/projects/views.py +++ b/projects/views.py @@ -1,5 +1,6 @@ from django.contrib.auth.decorators import login_required from django.contrib.auth import get_user_model +from django.contrib import messages from django.contrib.auth.views import LoginView from django.core.cache import cache from django.core import signing @@ -20,7 +21,7 @@ from django.utils import timezone from django.conf import settings from oauth2_provider.models import get_access_token_model, revoke_access_token from .forms import CardForm, ColumnForm, ProfileForm, ProjectForm, TagForm -from .models import Activity, Card, CardComment, CardAttachment, Column, Profile, Membership, Tag +from .models import Activity, Card, CardComment, CardAttachment, Column, Profile, Membership, Tag, Project from . import services from . import attachments from . import documentation @@ -30,6 +31,21 @@ from .models import DocumentationSync, ProjectDocument from urllib.parse import quote +ACTIVITY_ACTION_LABELS = { + 'project.created': 'created the project', 'card.created': 'created a card', + 'card.updated': 'updated a card', 'card.moved': 'moved a card', + 'card.moved_project': 'moved this card to another project', + 'card.moved_project_out': 'moved a card to another project', + 'card.assigned': 'changed a card assignment', 'card.tags_changed': 'updated card tags', + 'card.bulk_updated': 'updated a card', 'column.updated': 'updated a column', + 'attachment.added': 'added an attachment', 'attachment.deleted': 'removed an attachment', +} + + +def activity_display_action(action): + return ACTIVITY_ACTION_LABELS.get(action, action.replace('.', ' ').replace('_', ' ')) + + class ThrottledLoginView(LoginView): template_name = 'projects/login.html' @@ -62,8 +78,14 @@ def project_list(request): projects = services.accessible(request.user).filter(archived=show_archived) if query: projects = projects.filter(Q(name__icontains=query) | Q(description__icontains=query) | Q(cards__title__icontains=query) | Q(cards__description_markdown__icontains=query) | Q(tag__name__icontains=query)).distinct() - projects = projects.annotate(card_count=Count('cards', distinct=True)).order_by('name') + projects = projects.annotate( + card_count=Count('cards', distinct=True), + active_card_count=Count('cards', filter=Q(cards__archived=False), distinct=True), + done_card_count=Count('cards', filter=Q(cards__archived=False, cards__column__is_done=True), distinct=True), + ).order_by('name') page_obj = Paginator(projects, 12).get_page(request.GET.get('page')) + for project in page_obj: + project.progress_percent = round(project.done_card_count * 100 / project.active_card_count) if project.active_card_count else 0 filters = request.GET.copy(); filters.pop('page', None) template = 'projects/_project_list.html' if request.headers.get('HX-Request') else 'projects/list.html' return render(request, template, {'projects': page_obj, 'page_obj': page_obj, 'filters_query': filters.urlencode(), 'query': query, 'show_archived': show_archived, 'section': 'projects', 'title': 'Projects'}) @@ -133,8 +155,14 @@ def board(request, project_id): column.active_count = Card.objects.filter(column=column, archived=False).count() assignable_ids = [project.owner_id, *project.memberships.values_list('user_id', flat=True)] active_cards = Card.objects.filter(project=project, archived=False) - context = {'project': project, 'columns': columns, 'page_obj': page_obj, 'filters_query': filters.urlencode(), 'query': query, 'title': project.name, 'section': 'projects', 'card_count': len(cards), 'total_count': active_cards.count(), 'done_count': active_cards.filter(column__is_done=True).count(), 'priority_counts': [(label, active_cards.filter(priority=value, column__is_done=False).count()) for value, label in Card.PRIORITY], 'recent_activity': Activity.objects.filter(project=project).select_related('actor')[:5], 'selected_priority': request.GET.get('priority', ''), 'selected_type': request.GET.get('card_type', ''), 'selected_assignee': request.GET.get('assignee', ''), 'selected_tag': request.GET.get('tag', ''), 'selected_column': request.GET.get('column', ''), 'show_archived': show_archived, 'tags': Tag.objects.filter(project=project).order_by('name'), 'assignable': get_user_model().objects.filter(pk__in=assignable_ids).order_by('username'), 'card_types': Card.TYPE, 'can_edit': can_edit} - template = 'projects/_board.html' if request.headers.get('HX-Request') else 'projects/board.html' + is_htmx = bool(request.headers.get('HX-Request')) + all_activity = [] if is_htmx else list(Activity.objects.filter(project=project).select_related('actor', 'card')) + for event in all_activity: + event.display_action = activity_display_action(event.action) + done_count = active_cards.filter(column__is_done=True).count() + total_count = active_cards.count() + context = {'project': project, 'columns': columns, 'page_obj': page_obj, 'filters_query': filters.urlencode(), 'query': query, 'title': project.name, 'section': 'projects', 'card_count': len(cards), 'total_count': total_count, 'done_count': done_count, 'progress_percent': round(done_count * 100 / total_count) if total_count else 0, 'priority_counts': [(label, active_cards.filter(priority=value, column__is_done=False).count()) for value, label in Card.PRIORITY], 'recent_activity': all_activity[:3], 'older_activity': all_activity[3:], 'selected_priority': request.GET.get('priority', ''), 'selected_type': request.GET.get('card_type', ''), 'selected_assignee': request.GET.get('assignee', ''), 'selected_tag': request.GET.get('tag', ''), 'selected_column': request.GET.get('column', ''), 'show_archived': show_archived, 'active_filter_count': sum(bool(request.GET.get(key)) for key in ('priority', 'card_type', 'column', 'assignee', 'tag')), 'tags': Tag.objects.filter(project=project).order_by('name'), 'assignable': get_user_model().objects.filter(pk__in=assignable_ids).order_by('username'), 'card_types': Card.TYPE, 'can_edit': can_edit} + template = 'projects/_board.html' if is_htmx else 'projects/board.html' return render(request, template, context) @@ -204,11 +232,51 @@ def card_create(request, project_id): def card_detail(request, card_id): card = services.card_for(request.user, card_id) can_edit = card.project.owner_id == request.user.pk or Membership.objects.filter(project=card.project, user=request.user, role='editor').exists() - return render(request, 'projects/card.html', {'card': card, 'can_edit': can_edit, 'title': card.title, 'section': 'projects', + history = card.activity.select_related('actor').all() + for event in history: + event.display_action = activity_display_action(event.action).replace('a card', 'this card') + destinations = Project.objects.filter(archived=False).filter(Q(owner=request.user) | Q(memberships__user=request.user, memberships__role='editor')).exclude(pk=card.project_id).distinct().select_related('board').order_by('name') if can_edit else Project.objects.none() + destination_options = [] + for project in destinations: + columns = list(project.board.columns.filter(archived=False).order_by('position')) + if not columns: + continue + default_column = next((column for column in columns if column.is_default), columns[0]) + destination_options.append({'project': project, 'columns': columns, + 'default_column': default_column}) + return render(request, 'projects/card.html', {'card': card, 'can_edit': can_edit, 'title': card.title, 'section': 'projects', 'history': history, + 'destination_options': destination_options, 'move_idempotency_key': uuid.uuid4(), 'card_files': card.attachments.filter(comment__isnull=True).select_related('uploaded_by'), 'comments': card.comments.prefetch_related('attachments').select_related('author').order_by('created_at')}) +@login_required +@require_POST +def card_move_project(request, card_id): + card = services.card_for(request.user, card_id, write=True) + try: + target_id = uuid.UUID(request.POST.get('target_project_id', '')) + target_project = services.project_for(request.user, target_id, write=True) + column_id = request.POST.get('target_column_id') or None + target_column = get_object_or_404(Column, pk=column_id) if column_id else None + moved, result = services.move_card_to_project( + request.user, card, target_project, target_column=target_column, + expected_revision=request.POST.get('expected_revision'), + idempotency_key=request.POST.get('idempotency_key') or None, + ) + except services.RevisionConflict as conflict: + messages.error(request, f'This card changed before it could be moved. Current revision: {conflict.current}. Reload the card and try again.') + return redirect('projects:card', card_id=card.pk) + except (ValueError, TypeError, ValidationError) as exc: + messages.error(request, '; '.join(exc.messages) if isinstance(exc, ValidationError) else 'The card could not be moved. Reload the card and try again.') + return redirect('projects:card', card_id=card.pk) + message = f'Moved “{moved.title}” from {result["source_project_name"]} to {result["target_project_name"]}.' + if result['warnings']: + message += ' ' + ' '.join(result['warnings']) + messages.success(request, message) + return redirect('projects:card', card_id=moved.pk) + + @login_required @require_POST def attachment_upload(request, card_id):