diff --git a/apps/board/board.py b/apps/board/board.py index 469a689..b37fbf0 100644 --- a/apps/board/board.py +++ b/apps/board/board.py @@ -147,7 +147,13 @@ def threads(): 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 + -- `id` last, and it is not decoration. `created_at` is + -- `datetime('now')`, which has one-second resolution, so two + -- threads written in the same second compared equal and SQLite was + -- 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 LIMIT ? OFFSET ?""", (PER_PAGE + 1, (page - 1) * PER_PAGE), ).fetchall() @@ -174,7 +180,7 @@ def thread(thread_id: int): m.gitea_login AS author_login, m.profile_published AS author_published FROM comments c JOIN members m ON m.id = c.author_id WHERE c.thread_id = ? AND c.deleted_at IS NULL - ORDER BY c.created_at""", + ORDER BY c.created_at, c.id""", (thread_id,), ).fetchall() return render_template("thread.html", thread=row, author=author, diff --git a/apps/board/content.py b/apps/board/content.py index 5abb5fd..2f49a21 100644 --- a/apps/board/content.py +++ b/apps/board/content.py @@ -25,6 +25,7 @@ import secrets import unicodedata from datetime import date as date_type from datetime import datetime +from datetime import time as time_type import yaml from flask import (Blueprint, abort, current_app, flash, g, redirect, @@ -142,10 +143,61 @@ def build_document(fields: dict, body: str) -> str: return f"---\n{front}---\n\n{body.strip()}\n" +def as_datetime(value): + """Whatever a `date:` turned out to be — a date, a datetime, a string — + as a datetime, or None if it is none of those.""" + if isinstance(value, datetime): + return value + if isinstance(value, date_type): + return datetime.combine(value, time_type()) + try: + return datetime.fromisoformat(str(value).strip()) + except (TypeError, ValueError): + return None + + +def date_input(value) -> str: + """The `YYYY-MM-DD` an `` accepts. A datetime handed to + one straight is not a value it understands, and the browser answers by + showing an empty field — silently, which is the failure this exists to + stop.""" + moment = as_datetime(value) + return f"{moment:%Y-%m-%d}" if moment else "" + + +def stamp(when, original=None) -> datetime: + """The post's date, with the clock attached. + + Hugo sorts the blog by this field and a bare `date: 2026-07-31` makes every + post published that day byte-identical in it — so Hugo falls through to its + next key, the title, and the day comes out alphabetised. Permanently: a + rebuild does not change it, because nothing about the files changed. That + is the whole of "the posts are not in the order they were written". + + The day is still the one whoever is publishing chose, and the URL still + carries only the day. The time is the tiebreak, which is why it is the + clock at the moment of publication rather than anything cleverer. + + `original` is what the file already said. An edit keeps it verbatim as long + as the day has not moved — otherwise correcting a typo would carry a + year-old post to the top of the home page. + """ + chosen = as_datetime(when) or datetime.now() + before = as_datetime(original) + if before and before.date() == chosen.date() and before.time() != time_type(): + return before + now = datetime.now() + return chosen.replace(hour=now.hour, minute=now.minute, second=now.second, + microsecond=0) + + def frontmatter_for(collection: str, form: dict) -> dict: fields = {"title": form["title"]} if COLLECTIONS[collection]["dated"]: - fields["date"] = form["date"] + # Every path that writes a post comes through here — the editor, an + # edit, and a moderator approving a proposal — so this is the one place + # the clock has to be attached. + fields["date"] = stamp(form["date"], form.get("date_stamped")) fields["lang"] = "es" fields["manual_translation"] = form["manual_translation"] if collection == "page": @@ -262,6 +314,12 @@ def listing(collection: str) -> list[dict]: "event_location": row["event_location"] or "", }) + # Newest first, by the whole of the date. That used to be a day and nothing + # else, so everything published on one day tied and fell through to the + # filename — which under `reverse` is descending-alphabetical slug order, + # 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) return items @@ -307,6 +365,10 @@ def _read_form(collection: str) -> tuple[dict, str, list[str]]: when = datetime.strptime(raw_date, "%Y-%m-%d").date() except ValueError: errors.append("La fecha debe tener el formato AAAA-MM-DD.") + # What the file already said, carried through the form untouched so that + # `stamp()` can keep the publication time when only the text changed. A + # date field is a day and nothing else; this is the rest of it. + stamped = request.form.get("date_stamped", "").strip() # A page's place in the menu. `parent` is another page's basename — the one # translate.py uses to pair siblings, so a parent chosen once holds in all @@ -354,6 +416,7 @@ def _read_form(collection: str) -> tuple[dict, str, list[str]]: fields = { "title": title, "date": when, + "date_stamped": stamped, "date_input": raw_date, "description": request.form.get("description", "").strip(), "image": image, "manual_translation": request.form.get("manual_translation") == "on", @@ -588,9 +651,15 @@ def edit(collection: str, name: str): "error") return redirect(url_for("content.index", collection=collection)) + published = as_datetime(fm.get("date")) fields = { "title": fm.get("title", ""), "date": fm.get("date"), + # The day for the date field, and the whole of it for the hidden + # one, so an edit that does not move the day keeps the publication + # time the post already had. + "date_input": date_input(fm.get("date")), + "date_stamped": published.isoformat() if published else "", "description": fm.get("description", ""), "image": fm.get("image", ""), "manual_translation": bool(fm.get("manual_translation")), diff --git a/apps/board/home.py b/apps/board/home.py index ce7e458..77df890 100644 --- a/apps/board/home.py +++ b/apps/board/home.py @@ -41,7 +41,7 @@ def index(): 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.created_at DESC LIMIT ?""", + ORDER BY t.pinned DESC, t.created_at DESC, t.id DESC LIMIT ?""", (RECENT,), ).fetchall() @@ -62,13 +62,16 @@ def index(): JOIN conversation_members theirs ON theirs.conversation_id = c.id AND theirs.member_id != :me JOIN members other ON other.id = theirs.member_id - ORDER BY last_at DESC NULLS LAST LIMIT :limit""", + ORDER BY last_at DESC NULLS LAST, c.id DESC LIMIT :limit""", {"me": g.member["id"], "limit": RECENT}, ).fetchall() mine = db.execute( """SELECT id, title, state, note FROM submissions - WHERE author_id = ? ORDER BY created_at DESC LIMIT ?""", + WHERE author_id = ? + ORDER BY CASE state WHEN 'pending' THEN 0 ELSE 1 END, + created_at DESC, id DESC + LIMIT ?""", (g.member["id"], RECENT), ).fetchall() @@ -82,7 +85,7 @@ def index(): m.profile_published AS author_published FROM submissions s JOIN members m ON m.id = s.author_id WHERE s.state = 'pending' AND s.author_id != ? - ORDER BY s.created_at LIMIT ?""", + ORDER BY s.created_at, s.id LIMIT ?""", (g.member["id"], RECENT), ).fetchall() diff --git a/apps/board/messages.py b/apps/board/messages.py index 19ac6f7..2bdadcc 100644 --- a/apps/board/messages.py +++ b/apps/board/messages.py @@ -146,7 +146,7 @@ def history(other_id: int) -> dict: a.profile_published AS author_published FROM messages m JOIN members a ON a.id = m.author_id WHERE m.conversation_id = ? AND m.deleted_at IS NULL - ORDER BY m.created_at""", + ORDER BY m.created_at, m.id""", (conversation_id,), ).fetchall() db.execute( diff --git a/apps/board/submissions.py b/apps/board/submissions.py index 8ba1941..2fc7b1f 100644 --- a/apps/board/submissions.py +++ b/apps/board/submissions.py @@ -132,7 +132,8 @@ def index(): db = get_db() mine = db.execute( """SELECT * FROM submissions WHERE author_id = ? - ORDER BY CASE state WHEN 'pending' THEN 0 ELSE 1 END, created_at DESC""", + ORDER BY CASE state WHEN 'pending' THEN 0 ELSE 1 END, + created_at DESC, id DESC""", (g.member["id"],), ).fetchall() queue = [] @@ -143,7 +144,7 @@ def index(): m.profile_published AS author_published FROM submissions s JOIN members m ON m.id = s.author_id WHERE s.state = 'pending' AND s.author_id != ? - ORDER BY s.created_at""", + ORDER BY s.created_at, s.id""", (g.member["id"],), ).fetchall() return render_template("submissions.html", mine=mine, queue=queue, diff --git a/apps/board/templates/content_form.html b/apps/board/templates/content_form.html index 10f4e3a..23ef155 100644 --- a/apps/board/templates/content_form.html +++ b/apps/board/templates/content_form.html @@ -34,7 +34,12 @@ {% if meta.dated %} - + + {#- The publication time the post already carries. Hugo sorts the blog by + the whole of it and a date field is only a day, so without this, saving + a corrected typo would restamp the clock and carry a year-old post to + the top of the home page. -#} + {% endif %} {% if collection == 'page' %} diff --git a/apps/board/tests/test_content.py b/apps/board/tests/test_content.py index 6cb9dad..19ba852 100644 --- a/apps/board/tests/test_content.py +++ b/apps/board/tests/test_content.py @@ -12,6 +12,8 @@ from __future__ import annotations import importlib.util import io import sys +from datetime import date as date_type +from datetime import datetime from pathlib import Path import pytest @@ -566,7 +568,8 @@ def test_an_event_carries_its_own_date_and_an_ics(repo, editor, post): path, = repo.files front = yaml.safe_load(repo.files[path].decode().split("---")[1]) - assert front["date"].isoformat() == "2026-10-03" + # The day the writer chose, and the clock attached to it — see `stamp`. + assert front["date"].date().isoformat() == "2026-10-03" assert front["event_date"] == "2026-10-24" assert front["event_time"] == "18:30" assert front["event_location"] == "Plaza de Ottakring" @@ -758,3 +761,82 @@ def test_a_post_still_needs_a_body(repo, editor, post): response = publish(post, title="", body="") assert not repo.files assert "cuerpo no puede estar vacío" in response.get_data(as_text=True) + + +# --- the order the site reads them in ------------------------------------- + +def test_two_posts_published_on_one_day_do_not_have_the_same_date( + repo, editor, post): + """The bug behind «the posts are not in the order they were written». + + `date: 2026-09-25` with no clock is byte-identical for everything published + that day, so Hugo falls through its sort keys to the title and the day + comes out alphabetised — permanently, because a rebuild changes nothing + about the files. The day is still the one the writer chose; the time is + only what breaks the tie. + """ + publish(post, title="Zutano llega tarde", date="2026-09-25") + publish(post, title="Abc va primero", date="2026-09-25") + + dates = {} + for path, blob in repo.files.items(): + fm, _ = translate.split_frontmatter(blob.decode()) + dates[path] = fm["date"] + + assert len(dates) == 2 + for path, when in dates.items(): + assert isinstance(when, datetime), f"{path} carries a bare date: {when!r}" + assert when.date() == date_type(2026, 9, 25) + # And the URL still carries only the day, so nothing anybody linked moves. + assert sorted(repo.files) == [ + "content/post/2026-09-25-abc-va-primero.es.md", + "content/post/2026-09-25-zutano-llega-tarde.es.md", + ] + + +def test_the_newest_post_is_first_in_the_editors_own_list(repo, editor, post, client): + """Contenido sorted on the same date-only string, with the filename as the + tiebreak — and `reverse=True` reverses the filename too, so the day came + out in descending-alphabetical slug order.""" + publish(post, title="Abc se publica primero", date="2026-09-25") + publish(post, title="Zutano se publica después", date="2026-09-25") + + page = client.get("/comunidad/contenido/post").get_data(as_text=True) + assert page.index("Zutano se publica después") < page.index("Abc se publica primero") + + +def test_correcting_a_post_does_not_move_it_to_the_top(repo, editor, post): + """An edit keeps the publication time the file already carried, as long as + the day has not moved. Without that, fixing a typo in a year-old post would + restamp it with today's clock and carry it up the page.""" + publish(post, title="Una nota de hace tiempo", date="2026-09-25") + path, = repo.files + before, _ = translate.split_frontmatter(repo.files[path].decode()) + + post(f"/comunidad/contenido/post/editar/{path.rsplit('/', 1)[1]}", + {"title": "Una nota de hace tiempo", "body": "Corregida.", + "date": "2026-09-25", "date_stamped": before["date"].isoformat(), + "sha": repo._sha(repo.files[path])}) + + after, _ = translate.split_frontmatter(repo.files[path].decode()) + assert after["date"] == before["date"] + + +def test_moving_a_post_to_another_day_restamps_it(repo, editor, post): + """The other half: a date deliberately changed is a date changed, and the + clock that goes with it is the one it is being published at now.""" + publish(post, title="Se adelanta", date="2026-09-25") + path, = repo.files + before, _ = translate.split_frontmatter(repo.files[path].decode()) + + post(f"/comunidad/contenido/post/editar/{path.rsplit('/', 1)[1]}", + {"title": "Se adelanta", "body": "Texto.", "date": "2026-10-01", + "date_stamped": before["date"].isoformat(), + "sha": repo._sha(repo.files[path])}) + + # An edit writes back to the file it opened — the filename keeps the day it + # was created with, and always has. The date Hugo sorts and builds the URL + # from is the one in the frontmatter, and that is the one that moves. + after, _ = translate.split_frontmatter(repo.files[path].decode()) + assert after["date"].date() == date_type(2026, 10, 1) + assert after["date"] != before["date"] diff --git a/docs/server-setup.md b/docs/server-setup.md index 0719e20..21c2939 100644 --- a/docs/server-setup.md +++ b/docs/server-setup.md @@ -1034,6 +1034,50 @@ Only *Inicio* remains in `config.yaml`. Weight under 5 puts a menu entry before the pages, 5 or more after them. *Comunidad* used to be the entry at weight 9 and is a button in the bar now — see §11.19. +### 11.15c Strict reverse-chronological order, in both halves + +Posts came out in the wrong order on the public site and in the editor, from two +different causes that look like one bug. + +**On the site: the editor wrote a day with no clock.** `date: 2026-07-31` is +byte-identical for everything published that day, so Hugo fell through its sort +keys — weight, date, linktitle, filepath — and the day came out **alphabetised +by title**. Permanently: a rebuild changes nothing about the files. None of the +four post feeds applied an explicit sort either, so all four inherited it. + +Both halves are fixed, and both are needed — a sort cannot break a tie: + +- `apps/board/content.py`'s **`stamp()`** attaches the clock at the moment of + publication, in `frontmatter_for`, which every publishing path goes through + (the editor, an edit, a moderator approving a proposal). The day is still + whoever publishes chose and the URL still carries only the day, so nothing + anybody linked to moves. **An edit keeps the time the file already had** as + long as the day has not changed — otherwise correcting a typo would carry a + year-old post to the top of the home page. That is what the hidden + `date_stamped` field in `content_form.html` is for. +- **`partials/posts-ordered.html`** returns the order, and the home page, the + section list, `llms.txt` and the `BlogPosting` block in `seo-head.html` all + call it. `first N` is applied to its result, never to its input: slicing + before sorting is how a post falls off the end of its own list. + +Posts written before this keep their bare date and tie with each other, which +is right — the time they were published is not recoverable. Saving one attaches +a clock. + +**In the members area: no ordering had a tiebreak.** `created_at` is +`datetime('now')`, which has one-second resolution, so two rows written in the +same second compared equal and SQLite returned them in whatever order it liked +— differently on different pages of the same list. Every ordering now ends in +the primary key. `activity.py` had it already and was the model. + +Two disagreements went with it: Inicio's wall panel now orders by `pinned` like +the wall itself, and its own-submissions panel uses the same state ranking +*Publicaciones* does. The two moderation queues stay **oldest-first** on +purpose: a queue is not a feed, and work waiting to be done is FIFO. + +The public agenda also sorts a day's events by `event_time`, which the private +calendar has done since it was written. + ### 11.15b Two calendars **Public events are posts carrying an `event_date`**, with two more fields of diff --git a/themes/vienalatina/layouts/_default/list.html b/themes/vienalatina/layouts/_default/list.html index c6aa30e..8704689 100644 --- a/themes/vienalatina/layouts/_default/list.html +++ b/themes/vienalatina/layouts/_default/list.html @@ -3,7 +3,7 @@

{{ .Title }}

- {{ range .Pages }} + {{ range partial "posts-ordered.html" .Pages }}
diff --git a/themes/vienalatina/layouts/index.html b/themes/vienalatina/layouts/index.html index 0c85b66..becbd2e 100644 --- a/themes/vienalatina/layouts/index.html +++ b/themes/vienalatina/layouts/index.html @@ -1,7 +1,7 @@ {{/* Home: feed of recent articles in the current language. */}} {{ define "main" }}
- {{ range first 20 (where .Site.RegularPages "Section" "post") }} + {{ range first 20 (partial "posts-ordered.html" (where .Site.RegularPages "Section" "post")) }}
diff --git a/themes/vienalatina/layouts/index.llms.txt b/themes/vienalatina/layouts/index.llms.txt index bc82ef3..5429f58 100644 --- a/themes/vienalatina/layouts/index.llms.txt +++ b/themes/vienalatina/layouts/index.llms.txt @@ -13,6 +13,6 @@ This site publishes in Spanish. Every article has server-rendered German (/de/) {{ end }} ## Recent articles -{{ range first 50 (where .Site.RegularPages "Section" "post") -}} +{{ range first 50 (partial "posts-ordered.html" (where .Site.RegularPages "Section" "post")) -}} - [{{ .Title }}]({{ .Permalink }}): {{ .Description | default (.Summary | plainify | truncate 200) }} {{ end -}} diff --git a/themes/vienalatina/layouts/page/agenda.html b/themes/vienalatina/layouts/page/agenda.html index 67af9ba..6fc7c7c 100644 --- a/themes/vienalatina/layouts/page/agenda.html +++ b/themes/vienalatina/layouts/page/agenda.html @@ -79,7 +79,14 @@ {{ if gt $lead 0 }}{{ range seq $lead }}{{ end }}{{ end }} {{ range $day := seq 1 $days }} {{ $date := printf "%s-%02d" $key $day }} - {{ $onThisDay := where $events "Params.event_date" $date }} + {{/* By the hour, so two things on one day read in the order they + happen rather than in the order they were announced. The + private calendar has sorted this way since it was written + (apps/board/events.py: `ORDER BY starts_on, COALESCE(starts_at, + '99:99')`), and the two show the same events to the same + people. An event with no time sorts first here, which is right: + all day begins before the evening does. */}} + {{ $onThisDay := sort (where $events "Params.event_date" $date) "Params.event_time" }} {{/* The column a day falls in is its weekday, Monday first — the same arithmetic the padding above is made of. On a phone the grid becomes one day per row, where a column position says diff --git a/themes/vienalatina/layouts/partials/posts-ordered.html b/themes/vienalatina/layouts/partials/posts-ordered.html new file mode 100644 index 0000000..1b9a1a0 --- /dev/null +++ b/themes/vienalatina/layouts/partials/posts-ordered.html @@ -0,0 +1,23 @@ +{{/* + The order every list of posts on this site is in, in one place. + + Call it with the pages and range over what comes back: + + {{ range first 20 (partial "posts-ordered.html" (where site.RegularPages "Section" "post")) }} + {{ range partial "posts-ordered.html" .Pages }} + + Four lists used to range over the pages with no sort at all and lean on + Hugo's default, which is weight, then date, then linktitle, then filepath. + That is fine until two posts share a date — and until this phase the editor + wrote `date: 2026-07-31` with no clock, so every post published on one day + was identical in it and Hugo fell through to the title. A day came out + alphabetised, permanently, because nothing about the files changed on a + rebuild. The editor stamps the time now (apps/board/content.py, `stamp`), + and this is the other half: the order is stated rather than inherited, so a + weight somebody adds by hand cannot quietly reorder the home page. + + `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. +*/}} +{{ return (sort . "Date" "desc") }} diff --git a/themes/vienalatina/layouts/partials/seo-head.html b/themes/vienalatina/layouts/partials/seo-head.html index b546d78..2978d69 100644 --- a/themes/vienalatina/layouts/partials/seo-head.html +++ b/themes/vienalatina/layouts/partials/seo-head.html @@ -205,7 +205,7 @@ {{ with .Site.Params.sameAs }}{{ $org = merge $org (dict "sameAs" .) }}{{ end }} -{{ $posts := first 10 (where .Site.RegularPages "Section" "post") }} +{{ $posts := first 10 (partial "posts-ordered.html" (where .Site.RegularPages "Section" "post")) }} {{ $blogPost := slice }} {{ range $posts }} {{ $entry := dict