diff --git a/apps/board/board.py b/apps/board/board.py index b37fbf0..1313a37 100644 --- a/apps/board/board.py +++ b/apps/board/board.py @@ -22,7 +22,8 @@ from . import auth, uploads from .db import get_db from . import titles from .render import excerpt, to_html -from .security import admin_required, is_at_least, login_required +from .security import (admin_required, is_at_least, login_required, + moderator_required) bp = Blueprint("board", __name__) @@ -35,6 +36,13 @@ def is_admin() -> bool: return is_at_least(g.member["role"], "admin") +def may_pin() -> bool: + """Deciding what the association reads first is curation, which is a + moderator's whole job. Locking a thread is not, and asks for an admin — + see `set_state`.""" + return is_at_least(g.member["role"], "moderator") + + def may_delete(row) -> bool: return is_admin() or row["author_id"] == g.member["id"] @@ -153,7 +161,7 @@ def threads(): -- free to return them in either order — and did, differently on -- different pages of the same list. Every ordering in this app now -- ends in the primary key for that reason. - ORDER BY t.pinned DESC, t.created_at DESC, t.id DESC + ORDER BY t.pinned DESC, t.pinned_at DESC, t.created_at DESC, t.id DESC LIMIT ? OFFSET ?""", (PER_PAGE + 1, (page - 1) * PER_PAGE), ).fetchall() @@ -163,6 +171,7 @@ def threads(): shown = rows[:PER_PAGE] return render_template("threads.html", threads=shown, page=page, has_next=has_next, excerpt=excerpt, + may_pin=may_pin(), reactions=reactions_for_threads([t["id"] for t in shown])) @@ -186,7 +195,7 @@ def thread(thread_id: int): return render_template("thread.html", thread=row, author=author, comments=comments, body_html=to_html(row["body_md"]), to_html=to_html, may_edit=may_edit, may_delete=may_delete, - is_admin=is_admin(), + is_admin=is_admin(), may_pin=may_pin(), thread_images=uploads.for_threads([thread_id]).get(thread_id, []), comment_images=uploads.for_comments([c["id"] for c in comments]), reactions=reactions_for_threads([thread_id]), @@ -370,14 +379,36 @@ def react(): @bp.route("/tema//estado", methods=["POST"]) -@admin_required +@moderator_required def set_state(thread_id: int): + """Pinning and locking, which are not the same authority. + + A moderator decides what the association reads first — that is curation, + and it is the whole of their job. Closing a conversation is not: it stops + named people saying anything more to each other, which is power over + people, and this codebase keeps those two apart everywhere else (see + `security.py`'s ladder). So the decorator admits a moderator and locking + asks again. + """ _thread_or_404(thread_id) field = request.form.get("field") if field not in ("pinned", "locked"): abort(400, "Campo desconocido.") + if field == "locked" and not is_admin(): + abort(403) value = 1 if request.form.get("value") == "1" else 0 # `field` is checked against a fixed pair above, so it never carries # anything a member typed into the statement. get_db().execute(f"UPDATE threads SET {field} = ? WHERE id = ?", (value, thread_id)) - return redirect(url_for("board.thread", thread_id=thread_id)) + if field == "pinned": + # When, not only whether: several threads can be pinned and the newest + # pin goes on top, so the moment is the order. Cleared on unpinning so + # that pinning again puts it where a new pin belongs rather than where + # the old one was. + get_db().execute( + "UPDATE threads SET pinned_at = CASE WHEN ? THEN datetime('now') END" + " WHERE id = ?", (value, thread_id)) + # Back where it was pressed — the wall as well as the thread page now — + # through the same open-redirect check the login form's `next` gets. + return redirect(auth.safe_next(request.form.get("back") or + url_for("board.thread", thread_id=thread_id))) diff --git a/apps/board/content.py b/apps/board/content.py index 2f49a21..d3a5253 100644 --- a/apps/board/content.py +++ b/apps/board/content.py @@ -244,6 +244,15 @@ def frontmatter_for(collection: str, form: dict) -> dict: # the mind of anybody reading the file. if form.get("ai_generated"): fields["ai_generated"] = True + # The moment it was pinned, and only when it is. One key carrying both the + # flag and the order: several posts can be pinned and the newest pin goes + # first, so `{{ if .Params.pinned }}` still reads as a yes/no while + # `sort … "Params.pinned" "desc"` puts them in the right order with nothing + # else to keep in step. Written as a string rather than a timestamp scalar + # so that a file saved twice does not alternate between the two shapes. + if form.get("pinned"): + fields["pinned"] = (str(form.get("pinned_at") or "") + or datetime.now().isoformat(timespec="seconds")) return fields @@ -259,14 +268,14 @@ def _cache_write(path: str, sha: str, fm: dict) -> None: get_db().execute( """INSERT INTO content_cache (path, sha, title, date, generated, image, event_date, event_time, event_location, - ai_generated) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + ai_generated, pinned) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(path) DO UPDATE SET sha = excluded.sha, title = excluded.title, date = excluded.date, generated = excluded.generated, image = excluded.image, event_date = excluded.event_date, event_time = excluded.event_time, event_location = excluded.event_location, - ai_generated = excluded.ai_generated, + ai_generated = excluded.ai_generated, pinned = excluded.pinned, updated_at = datetime('now')""", (path, sha, str(fm.get("title", "")), str(fm.get("date", "")), 1 if fm.get("translated_from") else 0, @@ -280,7 +289,11 @@ def _cache_write(path: str, sha: str, fm: dict) -> None: # every page view to find out when they are. str(fm.get("event_date", "") or ""), str(fm.get("event_time", "") or ""), str(fm.get("event_location", "") or ""), - 1 if fm.get("ai_generated") else 0), + 1 if fm.get("ai_generated") else 0, + # When it was pinned, or '' — the same copy of the frontmatter, so the + # editor's own list can put the pinned ones first without re-reading + # every file to find out which they are. + str(fm.get("pinned", "") or "")), ) @@ -309,6 +322,7 @@ def listing(collection: str) -> list[dict]: "title": row["title"] or name, "date": row["date"], "ai_generated": bool(row["ai_generated"]), + "pinned": row["pinned"], "event_date": row["event_date"] or "", "event_time": row["event_time"] or "", "event_location": row["event_location"] or "", @@ -320,7 +334,8 @@ def listing(collection: str) -> list[dict]: # as likely to be chronological as not. The editor stamps the clock now # (`stamp`), and the filename is left as the last resort for the posts # written before it did. - items.sort(key=lambda item: (item["date"], item["name"]), reverse=True) + items.sort(key=lambda item: (item["pinned"], item["date"], item["name"]), + reverse=True) return items @@ -424,6 +439,11 @@ def _read_form(collection: str) -> tuple[dict, str, list[str]]: # frontmatter rather than in a database, because the file in the # repository is the record of what was published. "ai_generated": request.form.get("ai_generated") == "on", + # And when it was pinned, carried through untouched, so that editing a + # pinned post does not count as pinning it again and move it above + # everything pinned since. + "pinned": request.form.get("pinned") == "on", + "pinned_at": request.form.get("pinned_at", "").strip(), "author": author, "author_url": author_url, "parent": parent, "weight": weight, "faq": faq, "image_alt": image_alt, @@ -668,6 +688,8 @@ def edit(collection: str, name: str): # correction quietly removes — which is the whole failure the # byline below was given its comment for. "ai_generated": bool(fm.get("ai_generated")), + "pinned": bool(fm.get("pinned")), + "pinned_at": str(fm.get("pinned", "") or ""), # Carried through the form untouched. Correcting a typo in somebody # else's post must not re-sign it with the name of whoever is # fixing it — the same rule the board has about editing other @@ -736,6 +758,47 @@ def delete(collection: str, name: str): return redirect(url_for("content.index", collection=collection)) +@bp.route("/contenido//fijar/", methods=["POST"]) +@moderator_required +def pin(collection: str, name: str): + """Pin or unpin from the list, without opening the post. + + The same write as saving the form — the file in the repository is the + record and there is no second store that could disagree with it — but + reached in one press from the screen where you can see what is pinned and + what is not, because deciding what the site leads with means looking at + the list rather than opening each post to find out. + + The whole document is rebuilt rather than patched: the frontmatter is YAML, + and a regular expression over somebody's prose is how a post loses its body. + """ + meta = _collection_or_404(collection) + name = _name_or_404(name) + path = f"{meta['folder']}/{name}" + wanted = request.form.get("value") == "1" + try: + text, sha = gitea.read_file(path, gitea.content_token()) + fm, body = split_frontmatter(text) + if fm.get("translated_from"): + abort(400, "Ese archivo lo genera la traducción automática.") + if bool(fm.get("pinned")) != wanted: + if wanted: + fm["pinned"] = datetime.now().isoformat(timespec="seconds") + else: + fm.pop("pinned", None) + title = fm.get("title", name) + gitea.write_file( + path, build_document(fm, body).encode("utf-8"), + f"content: {'fijar' if wanted else 'dejar de fijar'} «{title}»", + gitea.content_token(), sha=sha, member=g.member) + except gitea.GiteaError as exc: + flash(str(exc), "error") + return redirect(url_for("content.index", collection=collection)) + + flash("Fijado arriba." if wanted else "Ya no está fijado.", "ok") + return redirect(url_for("content.index", collection=collection)) + + @bp.route("/contenido//vista-previa", methods=["POST"]) @moderator_required def preview(collection: str): diff --git a/apps/board/home.py b/apps/board/home.py index 77df890..078c1f9 100644 --- a/apps/board/home.py +++ b/apps/board/home.py @@ -35,13 +35,15 @@ BODY_MAX = 100_000 def index(): db = get_db() threads = db.execute( - """SELECT t.id, t.title, t.body_md, t.created_at, m.display_name AS author, + """SELECT t.id, t.title, t.body_md, t.created_at, t.pinned, + m.display_name AS author, m.gitea_login AS author_login, m.profile_published AS author_published, (SELECT COUNT(*) FROM comments c WHERE c.thread_id = t.id AND c.deleted_at IS NULL) AS replies FROM threads t JOIN members m ON m.id = t.author_id WHERE t.deleted_at IS NULL - ORDER BY t.pinned DESC, t.created_at DESC, t.id DESC LIMIT ?""", + ORDER BY t.pinned DESC, t.pinned_at DESC, t.created_at DESC, t.id DESC + LIMIT ?""", (RECENT,), ).fetchall() diff --git a/apps/board/migrations.py b/apps/board/migrations.py index fcbc6c0..8b1d4db 100644 --- a/apps/board/migrations.py +++ b/apps/board/migrations.py @@ -364,6 +364,49 @@ def _room_to_say_a_machine_wrote_it(db: sqlite3.Connection) -> None: "INTEGER NOT NULL DEFAULT 0") +def _room_to_say_what_goes_first(db: sqlite3.Connection) -> None: + """When a post was pinned, which is also the order the pinned ones sit in. + + Two plain ADD COLUMNs, and both hold a moment rather than a flag. That is + the design: «several pins, newest pin first» needs an order, and a + timestamp is both the order and the answer to "is this pinned", so there is + no second column to keep in step with the first. + + `threads.pinned` has been in the schema since the board shipped and stays — + it is what the wall's index is on, and folding two columns into one would + be a table rebuild for tidiness. `pinned_at` sits beside it and is NULL for + anything pinned before this step, which sorts those below the ones pinned + since. Nothing is pinned today, so that costs nothing and says the truth: + we do not know when. + + `content_cache.pinned` is only the copy of the post's own frontmatter that + lets the editor's list sort without re-reading every file from the git + server. The file in the repository is the record. + """ + for table, column, kind in ( + ("threads", "pinned_at", "TEXT"), + ("content_cache", "pinned", "TEXT NOT NULL DEFAULT ''")): + existing = _columns(db, table) + if existing and column not in existing: + db.execute(f"ALTER TABLE {table} ADD COLUMN {column} {kind}") + + # And the wall's index, which now names the new column — `CREATE INDEX IF + # NOT EXISTS` in schema.sql leaves an index that already exists exactly as + # it is, so without this a server that has been running keeps the old + # definition forever while a fresh install gets the new one. Nothing breaks + # either way; the two just stop being the same system, which is how a + # difference nobody can see becomes a bug nobody can reproduce. + # Every column it names, because the oldest databases this runner has to + # cross predate some of them and a step that assumes the table it is + # looking at is the current one is a step that fails on the one server it + # was written for. + if {"pinned", "pinned_at", "created_at", "deleted_at"} <= _columns(db, "threads"): + db.execute("DROP INDEX IF EXISTS threads_live") + db.execute("CREATE INDEX threads_live" + " ON threads(pinned DESC, pinned_at DESC, created_at DESC, id DESC)" + " WHERE deleted_at IS NULL") + + # (number, description, function). The number is the value written to # user_version once the step succeeds. STEPS = [ @@ -377,6 +420,7 @@ STEPS = [ (8, "room for the identity, a typeface and the media library", _room_for_identity_and_a_typeface), (9, "a post can say a machine wrote it", _room_to_say_a_machine_wrote_it), + (10, "a post can be pinned to the top", _room_to_say_what_goes_first), ] diff --git a/apps/board/schema.sql b/apps/board/schema.sql index aa07b31..ccca9cd 100644 --- a/apps/board/schema.sql +++ b/apps/board/schema.sql @@ -53,6 +53,10 @@ CREATE TABLE IF NOT EXISTS threads ( created_at TEXT NOT NULL DEFAULT (datetime('now')), edited_at TEXT, pinned INTEGER NOT NULL DEFAULT 0 CHECK (pinned IN (0, 1)), + -- When it was pinned, which is also the order the pinned ones sit in: several + -- can be pinned at once and the newest pin goes first. NULL for anything + -- pinned before this column existed, which sorts those below. + pinned_at TEXT, locked INTEGER NOT NULL DEFAULT 0 CHECK (locked IN (0, 1)), -- Said out loud where the post is read. The association's own words and a -- machine's are both welcome here; which is which is not the reader's job @@ -64,7 +68,8 @@ CREATE TABLE IF NOT EXISTS threads ( ); CREATE INDEX IF NOT EXISTS threads_live - ON threads(pinned DESC, created_at DESC) WHERE deleted_at IS NULL; + ON threads(pinned DESC, pinned_at DESC, created_at DESC, id DESC) + WHERE deleted_at IS NULL; CREATE TABLE IF NOT EXISTS comments ( id INTEGER PRIMARY KEY, @@ -210,6 +215,10 @@ CREATE TABLE IF NOT EXISTS content_cache ( -- it without re-reading every file from the git server. The file is the -- record; this is the cache. ai_generated INTEGER NOT NULL DEFAULT 0 CHECK (ai_generated IN (0, 1)), + -- The same copy of the frontmatter, for the pin: the moment it was pinned, + -- or '' when it is not. A moment rather than a flag because several posts + -- can be pinned and the newest pin goes first, so the value is the order. + pinned TEXT NOT NULL DEFAULT '', updated_at TEXT NOT NULL DEFAULT (datetime('now')) ); diff --git a/apps/board/templates/_pin.html b/apps/board/templates/_pin.html new file mode 100644 index 0000000..b93e3d6 --- /dev/null +++ b/apps/board/templates/_pin.html @@ -0,0 +1,16 @@ +{# Fijar / No fijar, for a thread on the wall or on its own page. + + A form rather than a link, because it changes something and a GET that + changes something is a thing a prefetching browser will do on its own. It + carries where it was pressed so pinning from the wall comes back to the + wall, and the handler puts that through the same open-redirect check as the + login form. #} +{% macro pin(thread, back) %} +
+ + + + + +
+{% endmacro %} diff --git a/apps/board/templates/content_form.html b/apps/board/templates/content_form.html index 23ef155..b28ef4d 100644 --- a/apps/board/templates/content_form.html +++ b/apps/board/templates/content_form.html @@ -159,6 +159,17 @@ Contenido generado con IA + {#- The same switch for the pin, next to it. The moment it was pinned + rides along in the hidden field so that saving a correction does + not count as pinning it again and carry it above everything pinned + since. -#} + + + {#- Beside Cancelar and shaped like it: both are things you press in this row, and a bare link wedged between two buttons reads as unfinished. -#} +
diff --git a/apps/board/templates/home.html b/apps/board/templates/home.html index 9f7abc2..728c884 100644 --- a/apps/board/templates/home.html +++ b/apps/board/templates/home.html @@ -52,6 +52,9 @@ {% endif %} {% for t in threads %}

+ {# This panel orders by the pin like the wall does, so it has to say + which one is pinned or the order looks arbitrary from here. #} + {% if t.pinned %}Fijado {% endif %} {{ t.title }} {{ person(t.author, t.author_login) }} · {{ t.replies }} respuesta{{ '' if t.replies == 1 else 's' }}

diff --git a/apps/board/templates/thread.html b/apps/board/templates/thread.html index 71edc60..06398e6 100644 --- a/apps/board/templates/thread.html +++ b/apps/board/templates/thread.html @@ -2,6 +2,7 @@ {% from "_person.html" import person %} {% from "_reaction.html" import reaction %} {% from "_attachments.html" import attachments %} +{% from "_pin.html" import pin %} {% block title %}{{ thread.title }}{% endblock %} {% block main %} @@ -30,13 +31,12 @@
{% endif %} + {# Pinning is curation and a moderator does it; closing a conversation + stops named people talking to each other and is an admin's. #} + {% if may_pin %} + {{ pin(thread, url_for('board.thread', thread_id=thread.id)) }} + {% endif %} {% if is_admin %} -
- - - - -
diff --git a/apps/board/templates/threads.html b/apps/board/templates/threads.html index a55595f..5b5215e 100644 --- a/apps/board/templates/threads.html +++ b/apps/board/templates/threads.html @@ -1,6 +1,7 @@ {% extends "base.html" %} {% from "_person.html" import person %} {% from "_reaction.html" import reaction %} +{% from "_pin.html" import pin %} {% block title %}Muro{% endblock %} {% block main %} @@ -30,6 +31,10 @@
{{ reaction('thread', t.id, reactions.get(t.id), url_for('board.threads', page=page)) }} {{ t.replies }} respuesta{{ '' if t.replies == 1 else 's' }} + {# From here as well as from the thread page: deciding what the wall + leads with means looking at the wall, not opening each thread to + find out what is on it. #} + {% if may_pin %}{{ pin(t, url_for('board.threads', page=page)) }}{% endif %}
{% endfor %} diff --git a/apps/board/tests/test_board.py b/apps/board/tests/test_board.py index 74e94e8..8f2ed8d 100644 --- a/apps/board/tests/test_board.py +++ b/apps/board/tests/test_board.py @@ -87,12 +87,86 @@ def test_a_closed_thread_refuses_replies(client, db, post, thread, make_member, assert count == 0 -def test_only_admins_pin(client, post, thread, make_member, sign_in): +def test_a_plain_member_cannot_pin(client, post, thread, make_member, sign_in): sign_in(make_member("maria")) assert post(f"/comunidad/tema/{thread['id']}/estado", {"field": "pinned", "value": "1"}).status_code == 403 +def test_a_moderator_pins_but_does_not_lock(client, post, thread, make_member, + sign_in, db): + """The two ride the same route and are not the same authority. Deciding + what the association reads first is curation, which is the whole of a + moderator's job; closing a conversation stops named people saying anything + more to each other, and that is an admin's.""" + sign_in(make_member("modera", role="moderator")) + + assert post(f"/comunidad/tema/{thread['id']}/estado", + {"field": "pinned", "value": "1"}).status_code in (302, 303) + row = db.execute("SELECT pinned, pinned_at FROM threads WHERE id = ?", + (thread["id"],)).fetchone() + assert row["pinned"] == 1 and row["pinned_at"] + + assert post(f"/comunidad/tema/{thread['id']}/estado", + {"field": "locked", "value": "1"}).status_code == 403 + assert db.execute("SELECT locked FROM threads WHERE id = ?", + (thread["id"],)).fetchone()["locked"] == 0 + + +def test_unpinning_forgets_when_it_was_pinned(client, post, thread, make_member, + sign_in, db): + """Otherwise pinning it again would put it back where the old pin was, + rather than at the top where a new pin belongs.""" + sign_in(make_member("modera", role="moderator")) + post(f"/comunidad/tema/{thread['id']}/estado", {"field": "pinned", "value": "1"}) + post(f"/comunidad/tema/{thread['id']}/estado", {"field": "pinned", "value": "0"}) + + row = db.execute("SELECT pinned, pinned_at FROM threads WHERE id = ?", + (thread["id"],)).fetchone() + assert row["pinned"] == 0 and row["pinned_at"] is None + + +def test_a_pinned_thread_leads_the_wall_and_inicio(client, post, make_member, + sign_in, db): + """Both lists, because they are the same rows and used to disagree: the + wall ordered by the pin and Inicio's panel did not.""" + author = make_member("escribe") + sign_in(author) + for title in ("Lo primero", "Lo segundo", "Lo tercero"): + post("/comunidad/nuevo", {"title": title, "body": "Texto."}) + old = db.execute("SELECT id FROM threads ORDER BY id LIMIT 1").fetchone()["id"] + + sign_in(make_member("modera", role="moderator")) + post(f"/comunidad/tema/{old}/estado", {"field": "pinned", "value": "1"}) + + for url in ("/comunidad/muro", "/comunidad/"): + page = client.get(url).get_data(as_text=True) + assert page.index("Lo primero") < page.index("Lo tercero"), url + + +def test_the_newest_pin_goes_above_an_older_one(client, post, make_member, + sign_in, db): + """Several pins at once, newest pin first — which is why the column holds + the moment rather than a 1.""" + author = make_member("escribe") + sign_in(author) + post("/comunidad/nuevo", {"title": "Fijado hace rato", "body": "Texto."}) + post("/comunidad/nuevo", {"title": "Fijado ahora", "body": "Texto."}) + first, second = [r["id"] for r in + db.execute("SELECT id FROM threads ORDER BY id")] + + sign_in(make_member("modera", role="moderator")) + post(f"/comunidad/tema/{first}/estado", {"field": "pinned", "value": "1"}) + # `datetime('now')` has one-second resolution, so the two pins would + # otherwise land in the same second and the order would be the fallback. + db.execute("UPDATE threads SET pinned_at = '2026-01-01 00:00:00' WHERE id = ?", + (first,)) + post(f"/comunidad/tema/{second}/estado", {"field": "pinned", "value": "1"}) + + page = client.get("/comunidad/muro").get_data(as_text=True) + assert page.index("Fijado ahora") < page.index("Fijado hace rato") + + def test_the_state_field_is_not_a_way_into_the_query(client, post, thread, make_member, sign_in): """`field` is interpolated into the UPDATE, so it is checked against a fixed pair first. This asserts the check, not the interpolation.""" diff --git a/apps/board/tests/test_content.py b/apps/board/tests/test_content.py index 19ba852..c949a3b 100644 --- a/apps/board/tests/test_content.py +++ b/apps/board/tests/test_content.py @@ -703,6 +703,101 @@ def test_the_disclosure_is_not_one_of_the_keys_translation_rewrites(repo, editor assert "ai_generated" not in translate.TRANSLATED_KEYS +# --- what the site leads with --------------------------------------------- + +def test_a_pinned_post_carries_the_moment_it_was_pinned(repo, editor, post): + """One key for both the flag and the order. Several posts can be pinned and + the newest pin goes first, so the value has to say when — and it is written + only when it is true, like the IA disclosure, so no post carries a line + reading `pinned: false` for somebody to wonder about.""" + publish(post, pinned="on") + path, = repo.files + fm, _ = translate.split_frontmatter(repo.files[path].decode()) + assert isinstance(fm["pinned"], str) and fm["pinned"].startswith("20") + + publish(post, title="Sin fijar", pinned="") + other = [p for p in repo.files if p != path][0] + fm, _ = translate.split_frontmatter(repo.files[other].decode()) + assert "pinned" not in fm + + +def test_editing_a_pinned_post_does_not_count_as_pinning_it_again(repo, editor, post): + """Otherwise fixing a typo would carry it above everything pinned since, + which is the same shape of bug as the publication date and lands in the + same place.""" + publish(post, pinned="on") + path, = repo.files + before, _ = translate.split_frontmatter(repo.files[path].decode()) + + post(f"/comunidad/contenido/post/editar/{path.rsplit('/', 1)[1]}", + {"title": "Sabores del barrio", "body": "Corregido.", "date": "2026-09-25", + "pinned": "on", "pinned_at": before["pinned"], + "sha": repo._sha(repo.files[path])}) + + after, _ = translate.split_frontmatter(repo.files[path].decode()) + assert after["pinned"] == before["pinned"] + + +def test_the_pin_survives_an_edit_that_says_nothing_about_it(repo, editor, post, client): + """The form loads it back the way it was left. A flag read into the form + but not written out again is a flag that one correction quietly removes.""" + publish(post, pinned="on") + path, = repo.files + name = path.rsplit("/", 1)[1] + page = client.get(f"/comunidad/contenido/post/editar/{name}").get_data(as_text=True) + assert 'name="pinned" checked' in page.replace(' >', '>') + + +def test_pinning_from_the_list_commits_without_opening_the_post(repo, editor, post): + publish(post) + path, = repo.files + name = path.rsplit("/", 1)[1] + + post(f"/comunidad/contenido/post/fijar/{name}", {"value": "1"}) + fm, body = translate.split_frontmatter(repo.files[path].decode()) + assert fm["pinned"] and body.strip() == "Texto del artículo." + + post(f"/comunidad/contenido/post/fijar/{name}", {"value": "0"}) + fm, body = translate.split_frontmatter(repo.files[path].decode()) + assert "pinned" not in fm and body.strip() == "Texto del artículo." + + +def test_a_plain_member_cannot_pin_a_post(repo, post, make_member, sign_in): + sign_in(make_member("maria")) + assert post("/comunidad/contenido/post/fijar/cualquiera.es.md", + {"value": "1"}).status_code == 403 + + +def test_a_moderator_can_pin_a_post(repo, post, make_member, sign_in): + """Curating what the public reads is the whole of a moderator's job, and + `COLLECTIONS["post"]["role"]` has said so since the queue was built.""" + sign_in(make_member("modera", role="moderator")) + publish(post) + path, = repo.files + response = post(f"/comunidad/contenido/post/fijar/{path.rsplit('/', 1)[1]}", + {"value": "1"}) + assert response.status_code in (302, 303) + fm, _ = translate.split_frontmatter(repo.files[path].decode()) + assert fm["pinned"] + + +def test_the_pin_is_not_one_of_the_keys_translation_rewrites(repo, editor, post): + """A pinned post is pinned in German too. `translate_file` copies the whole + frontmatter and rewrites only TRANSLATED_KEYS, so this needs no change to + the pipeline — asserted against the real list, because a key quietly added + to it would send a timestamp through a translation engine.""" + publish(post, pinned="on") + assert "pinned" not in translate.TRANSLATED_KEYS + + +def test_the_pinned_post_is_first_in_the_editors_list(repo, editor, post, client): + publish(post, title="Un aviso viejo", date="2026-01-05", pinned="on") + publish(post, title="Algo de ayer", date="2026-09-25") + + page = client.get("/comunidad/contenido/post").get_data(as_text=True) + assert page.index("Un aviso viejo") < page.index("Algo de ayer") + + # --- a post nobody titled ------------------------------------------------- def test_an_untitled_post_is_named_when_it_is_published(repo, editor, post): diff --git a/apps/board/tests/test_migrations.py b/apps/board/tests/test_migrations.py index 7efbecb..e5eb1a0 100644 --- a/apps/board/tests/test_migrations.py +++ b/apps/board/tests/test_migrations.py @@ -487,3 +487,62 @@ def test_step_nine_gives_every_post_somewhere_to_say_a_machine_wrote_it(tmp_path assert db.execute("PRAGMA user_version").fetchone()[0] == max( number for number, _, _ in migrations.STEPS) db.close() + + +def test_step_ten_gives_a_post_somewhere_to_say_when_it_was_pinned(tmp_path): + """Two plain ADD COLUMNs, and the rows around them untouched. + + Both hold a moment rather than a flag, because several posts can be pinned + and the newest pin goes first — so the value is the order, and there is no + second column to keep in step with the first. `threads.pinned` is the + exception and stays: it has been in the schema since the board shipped and + is what the wall's index is on. + """ + from apps.board.app import create_app + from apps.board.db import connect + + path = str(tmp_path / "board.db") + create_app({"SECRET_KEY": "x", "DB_PATH": path, "OWNER_LOGIN": "salvador", + "UPLOAD_DIR": str(tmp_path / "uploads"), "TESTING": True}) + + db = connect(path) + member = db.execute("SELECT id FROM members WHERE role = 'superadmin'").fetchone()["id"] + db.execute("INSERT INTO threads (author_id, title, body_md, pinned)" + " VALUES (?, 'Fijado hace tiempo', 'Texto.', 1)", (member,)) + db.execute("""INSERT INTO content_cache (path, sha, title, date) + VALUES ('content/post/2026-01-01-algo.es.md', 'abc', 'Algo', '2026-01-01')""") + # Wind it back to a server that has been running since before this phase. + # The index has to go first — SQLite refuses to drop a column one names, + # which is the same reason the step has to recreate it rather than leave it + # to `CREATE INDEX IF NOT EXISTS`. + db.execute("DROP INDEX threads_live") + db.execute("CREATE INDEX threads_live ON threads(pinned DESC, created_at DESC)" + " WHERE deleted_at IS NULL") + db.execute("ALTER TABLE threads DROP COLUMN pinned_at") + db.execute("ALTER TABLE content_cache DROP COLUMN pinned") + db.execute("PRAGMA user_version = 9") + db.commit() + db.close() + + create_app({"SECRET_KEY": "x", "DB_PATH": path, "OWNER_LOGIN": "salvador", + "UPLOAD_DIR": str(tmp_path / "uploads"), "TESTING": True}) + + db = connect(path) + assert "pinned_at" in {row[1] for row in db.execute("PRAGMA table_info(threads)")} + assert "pinned" in {row[1] for row in db.execute("PRAGMA table_info(content_cache)")} + # A thread pinned before this step keeps its pin and gains no moment: we do + # not know when, and NULL says so rather than inventing a time that would + # put it above everything pinned since. + row = db.execute("SELECT title, pinned, pinned_at FROM threads").fetchone() + assert row["title"] == "Fijado hace tiempo" + assert row["pinned"] == 1 and row["pinned_at"] is None + assert db.execute("SELECT pinned FROM content_cache").fetchone()["pinned"] == "" + # And the index is the new one. `CREATE INDEX IF NOT EXISTS` would have + # left the old definition standing on a server that had been running, + # so a fresh install and an upgraded one would have quietly diverged. + index = db.execute("SELECT sql FROM sqlite_master WHERE name = 'threads_live'" + ).fetchone()["sql"] + assert "pinned_at" in index + assert db.execute("PRAGMA user_version").fetchone()[0] == max( + number for number, _, _ in migrations.STEPS) + db.close() diff --git a/docs/server-setup.md b/docs/server-setup.md index 21c2939..af7d516 100644 --- a/docs/server-setup.md +++ b/docs/server-setup.md @@ -1297,6 +1297,45 @@ This is also the shape the EU AI Act's Article 50 asks for — telling people wh they are reading machine-generated material — which is worth knowing for whoever installs this for the second organisation. +### 11.17c Fijar: what the site and the wall lead with + +**Moderators and above can pin.** Deciding what the association reads first is +curation, which is the whole of a moderator's job — `COLLECTIONS["post"]["role"]` +has said so since the queue was built, and `board.set_state` now agrees. +**Locking a thread still asks for an admin**: it stops named people saying +anything more to each other, and that is power over people rather than over +content. The two ride one route and the handler asks twice. + +**Several posts can be pinned at once, and the newest pin goes first.** The +stored value is therefore a *moment* rather than a flag, in both halves: + +| | Where | What is stored | +|---|---|---| +| Public post | its own frontmatter, `pinned: '2026-10-13T12:00:00'`, written only when pinned | plus a copy in `content_cache.pinned`, so the editor's list can sort without re-reading every file from the git server | +| Wall thread | `threads.pinned` (the flag, since the board shipped) and `threads.pinned_at` | cleared on unpinning, so pinning again puts it where a new pin belongs | + +One key carrying both the flag and the order means `{{ if .Params.pinned }}` +still reads as a yes/no while `sort … "Params.pinned" "desc"` puts them in the +right order, with no second field to keep in step. `scripts/translate.py` +copies the whole frontmatter and rewrites only `TRANSLATED_KEYS`, so a pinned +post is pinned in German and Portuguese for free — asserted against the real +list rather than assumed. + +**Two ways to pin a public post**: the *Fijar arriba* switch beside *Publicar* +in the editor, and a one-press *Fijar* in the *Contenido* list. Both commit — +the file in the repository is the record and there is no second store that +could disagree with it — and the list one exists because deciding what the site +leads with means looking at the list rather than opening each post to find out +what is on it. On the wall the same button is on the thread page and on each +card. + +**Migration 10** adds the two columns and **recreates `threads_live`**, the +wall's index, because it now names `pinned_at`. `CREATE INDEX IF NOT EXISTS` in +`schema.sql` leaves an index that already exists exactly as it is, so without +that a server that has been running would keep the old definition forever while +a fresh install got the new one. Nothing breaks either way — which is the +problem: the two stop being the same system, invisibly. + ### 11.18 Marca: the superadministrator owns the look *Gestión* → **Marca**, admins only. Colours, a logo and a favicon for both diff --git a/themes/vienalatina/assets/css/main.css b/themes/vienalatina/assets/css/main.css index 196e7d5..848e4a4 100644 --- a/themes/vienalatina/assets/css/main.css +++ b/themes/vienalatina/assets/css/main.css @@ -4151,6 +4151,22 @@ a.notif-card__message:hover { vertical-align: middle; } +/* Fijado. The same pill, in the brand colour rather than in grey: the IA one + is a disclosure and recedes, this one is the association saying «read this + first» and should carry the weight of having been chosen. */ +.tag-pin { + display: inline-block; + padding: 2px 8px; + border: 1px solid var(--brand, #c0391c); + border-radius: 999px; + background: var(--brand-softer, #fdf1ee); + color: var(--brand-dark, #90290f); + font-size: 0.72rem; + font-weight: 700; + letter-spacing: 0.02em; + vertical-align: middle; +} + /* --- sharing ------------------------------------------------------------ * * A tinted strip rather than six bare icons: the row has to be noticed to be diff --git a/themes/vienalatina/layouts/_default/list.html b/themes/vienalatina/layouts/_default/list.html index 8704689..d68ff95 100644 --- a/themes/vienalatina/layouts/_default/list.html +++ b/themes/vienalatina/layouts/_default/list.html @@ -8,6 +8,7 @@
{{ if .Params.ai_generated }}{{ partial "t.html" (dict "key" "ai" "lang" .Site.Language.Lang) }}{{ end }} + {{ if .Params.pinned }}{{ partial "t.html" (dict "key" "pinned" "lang" .Site.Language.Lang) }}{{ end }}

{{ .Title }}

{{ .Description | default (.Summary | plainify | truncate 200) }}

diff --git a/themes/vienalatina/layouts/_default/single.html b/themes/vienalatina/layouts/_default/single.html index 8f84b19..b2d1fb2 100644 --- a/themes/vienalatina/layouts/_default/single.html +++ b/themes/vienalatina/layouts/_default/single.html @@ -35,6 +35,9 @@ {{ if .Params.ai_generated }} {{ partial "t.html" (dict "key" "ai" "lang" .Site.Language.Lang) }} {{ end }} + {{/* And whether somebody put it at the top on purpose, so a reader + arriving from the home page knows why it was first. */}} + {{ if .Params.pinned }}{{ partial "t.html" (dict "key" "pinned" "lang" .Site.Language.Lang) }}{{ end }} diff --git a/themes/vienalatina/layouts/index.html b/themes/vienalatina/layouts/index.html index becbd2e..2476fd5 100644 --- a/themes/vienalatina/layouts/index.html +++ b/themes/vienalatina/layouts/index.html @@ -6,6 +6,7 @@
{{ if .Params.ai_generated }}{{ partial "t.html" (dict "key" "ai" "lang" .Site.Language.Lang) }}{{ end }} + {{ if .Params.pinned }}{{ partial "t.html" (dict "key" "pinned" "lang" .Site.Language.Lang) }}{{ end }}

{{ .Title }}

{{ .Description | default (.Summary | plainify | truncate 200) }}

diff --git a/themes/vienalatina/layouts/partials/posts-ordered.html b/themes/vienalatina/layouts/partials/posts-ordered.html index 1b9a1a0..5c73337 100644 --- a/themes/vienalatina/layouts/partials/posts-ordered.html +++ b/themes/vienalatina/layouts/partials/posts-ordered.html @@ -19,5 +19,13 @@ `first N` applied to the result slices something already ordered. Applied to the input it would slice first and sort afterwards, which is how a pinned post falls off the end of its own list. + + The pinned ones go on top, newest pin first. `pinned` holds the moment it + was pinned rather than `true`, so one key is both the flag and the order — + there is no second field to keep in step with the first. Two sorts appended + rather than one multi-key sort, so this does not depend on Hugo's sort being + stable. */}} -{{ return (sort . "Date" "desc") }} +{{ $pinned := where . "Params.pinned" "!=" nil }} +{{ $rest := where . "Params.pinned" nil }} +{{ return (append (sort $rest "Date" "desc") (sort $pinned "Params.pinned" "desc")) }} diff --git a/themes/vienalatina/layouts/partials/t.html b/themes/vienalatina/layouts/partials/t.html index 00cb4d4..c489a8f 100644 --- a/themes/vienalatina/layouts/partials/t.html +++ b/themes/vienalatina/layouts/partials/t.html @@ -19,6 +19,7 @@ "noevents" (dict "es" "No hay nada en este mes." "de" "In diesem Monat ist nichts geplant." "pt-br" "Nada marcado neste mês.") "allevents" (dict "es" "Todos los eventos" "de" "Alle Termine" "pt-br" "Todos os eventos") "ai" (dict "es" "Generado con IA" "de" "Mit KI erstellt" "pt-br" "Gerado com IA") + "pinned" (dict "es" "Fijado" "de" "Angeheftet" "pt-br" "Fixado") "share" (dict "es" "Compartir" "de" "Teilen" "pt-br" "Compartilhar") "copylink" (dict "es" "Copiar enlace" "de" "Link kopieren" "pt-br" "Copiar link") "copied" (dict "es" "Enlace copiado" "de" "Link kopiert" "pt-br" "Link copiado")