From 5e8ee5ad20efb149a1e23fc9288a250ffe2a877a Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 3 Oct 2026 09:53:54 +0000 Subject: [PATCH] Two calendars: one for everybody, one for the members MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit **Public events are posts.** A new Evento category brings three fields with it — event_date, event_time, event_location — and the first is required, because a post's own `date` is when it was announced and an event announced three weeks early would otherwise land in the agenda on the wrong day. Members propose events through the same queue as everything else, and the date survives approval untouched: the event the member described is the event that gets published. An event's page leads with the day, the time and the place before the title, shows its picture full width, and offers "añadir a mi calendario" — a real .ics beside the page, generated because the editor writes `outputs: ["HTML", "ics"]` into an event's frontmatter and nothing else asks for that format. It carries Event structured data as well as the BlogPosting it already had, which is what puts a date beside the result in a search listing. /page/agenda/ is a month grid per month, every month from the first event to the last built at build time, with a script that shows one and moves between them. That arrangement is the point: with JavaScript off every month is on the page as a list, with it on nothing is fetched to change months, and the month it opens on is the reader's rather than the one the site was built in. Hugo exposes no AddDate, so the length of a month is a table plus the leap rule and the first weekday falls out of formatting the date — it looks like something simpler was missed, and it is not. **The private calendar** is a sixth section: rows in SQLite, written by admins, read by every member, never published. It shows the public events too, marked, so a member has one place to look rather than two — they come from the content_cache the editor's listing already fills, which is why migration 5 adds three columns to it and to submissions. The grid is Python's own calendar.Calendar: no date arithmetic of mine anywhere in it. Two things the tests found on the way: gitea.py let `requests`' own exceptions through. They inherit from OSError, not from GiteaError, so the calendar's careful "keep working while the git server is down" would have been defeated by a refused connection — the page would have 500ed instead. Every transport failure is now a GiteaError, raised at the one place that touches the wire. This is the third bug of exactly that shape in this module. An admin's erasure clears events.created_by rather than reassigning it. The meeting still happens after they leave; the event belongs to the association. 509 tests pass, and the site builds with Hugo 0.135.0 under the pipeline's own --panicOnWarning. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01NizVpJ2dwzCbjCrTLCjeHn --- apps/board/app.py | 5 +- apps/board/content.py | 121 ++++++- apps/board/events.py | 329 ++++++++++++++++++ apps/board/gitea.py | 25 +- apps/board/home.py | 1 + apps/board/members.py | 8 +- apps/board/migrations.py | 27 ++ apps/board/schema.sql | 33 ++ apps/board/static/board.css | 73 ++++ apps/board/submissions.py | 32 +- apps/board/templates/base.html | 1 + apps/board/templates/calendar.html | 68 ++++ apps/board/templates/content_form.html | 24 ++ apps/board/templates/event.html | 41 +++ apps/board/templates/event_form.html | 50 +++ apps/board/templates/submission_form.html | 24 ++ apps/board/tests/test_content.py | 76 ++++ apps/board/tests/test_events.py | 231 ++++++++++++ apps/board/tests/test_migrations.py | 5 + apps/board/tests/test_navigation.py | 3 +- apps/board/tests/test_submissions.py | 30 ++ config.yaml | 8 + content/page/agenda.es.md | 11 + docs/server-setup.md | 34 ++ scripts/translate.py | 3 + themes/vienalatina/assets/css/main.css | 130 +++++++ themes/vienalatina/assets/js/agenda.js | 52 +++ .../vienalatina/layouts/_default/single.html | 31 +- .../vienalatina/layouts/_default/single.ics | 40 +++ themes/vienalatina/layouts/page/agenda.html | 101 ++++++ .../layouts/partials/month-name.html | 12 + .../layouts/partials/seo-head.html | 30 ++ themes/vienalatina/layouts/partials/t.html | 27 ++ 33 files changed, 1658 insertions(+), 28 deletions(-) create mode 100644 apps/board/events.py create mode 100644 apps/board/templates/calendar.html create mode 100644 apps/board/templates/event.html create mode 100644 apps/board/templates/event_form.html create mode 100644 apps/board/tests/test_events.py create mode 100644 content/page/agenda.es.md create mode 100644 themes/vienalatina/assets/js/agenda.js create mode 100644 themes/vienalatina/layouts/_default/single.ics create mode 100644 themes/vienalatina/layouts/page/agenda.html create mode 100644 themes/vienalatina/layouts/partials/month-name.html create mode 100644 themes/vienalatina/layouts/partials/t.html diff --git a/apps/board/app.py b/apps/board/app.py index 07c719a..bdb1a09 100644 --- a/apps/board/app.py +++ b/apps/board/app.py @@ -94,11 +94,12 @@ def create_app(overrides: dict | None = None) -> Flask: # restart, which is a confusing way to find out the variable is unset. raise RuntimeError("BOARD_SECRET_KEY is required (generate one with `openssl rand -hex 32`).") - from . import (auth, board, content, home, members, messages, profiles, - submissions, uploads) + from . import (auth, board, content, events, home, members, messages, + profiles, submissions, uploads) app.register_blueprint(auth.bp, url_prefix=URL_PREFIX) app.register_blueprint(home.bp, url_prefix=URL_PREFIX) app.register_blueprint(submissions.bp, url_prefix=URL_PREFIX) + app.register_blueprint(events.bp, url_prefix=URL_PREFIX) app.register_blueprint(members.bp, url_prefix=URL_PREFIX) app.register_blueprint(content.bp, url_prefix=URL_PREFIX) app.register_blueprint(uploads.bp, url_prefix=URL_PREFIX) diff --git a/apps/board/content.py b/apps/board/content.py index 3680b54..79ff3a8 100644 --- a/apps/board/content.py +++ b/apps/board/content.py @@ -59,7 +59,12 @@ COLLECTIONS = { }, } -CATEGORIES = ["Turismo", "Cultura", "Gastronomía", "Comunidad", "Comercio"] +# The one category that changes what a post *is* rather than what it is about: +# tick it and the post needs a date of its own, appears in the agenda, renders +# with the date and the place at the top, and offers an .ics. +EVENT_CATEGORY = "Evento" + +CATEGORIES = ["Evento", "Turismo", "Cultura", "Gastronomía", "Comunidad", "Comercio"] UPLOAD_FOLDER = "static/uploads" @@ -80,6 +85,10 @@ AUTHOR_URL = re.compile(r"^/[A-Za-z0-9][A-Za-z0-9._-]{0,38}$") # names when it hangs under it. PAGE_BASENAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,80}$") +# 24-hour, because every reader of this site is in one city and half of them +# learned to read a clock in a country that writes it this way. +EVENT_TIME = re.compile(r"^([01][0-9]|2[0-3]):[0-5][0-9]$") + # --- the contract with translate.py -------------------------------------- @@ -129,6 +138,16 @@ def frontmatter_for(collection: str, form: dict) -> dict: fields["faq"] = form["faq"] if form.get("image_alt"): fields["image_alt"] = form["image_alt"] + if collection == "post" and form.get("event_date"): + fields["event_date"] = form["event_date"] + if form.get("event_time"): + fields["event_time"] = form["event_time"] + if form.get("event_location"): + fields["event_location"] = form["event_location"] + # Hugo builds one output per format listed here, so only an event gets + # an .ics file beside its page. Written by this code and never by a + # person: it is a build instruction, not something to explain in a form. + fields["outputs"] = ["HTML", "ics"] if collection == "post": if form["categories"]: fields["categories"] = form["categories"] @@ -162,14 +181,22 @@ def _cache_read(path: str, sha: str): def _cache_write(path: str, sha: str, fm: dict) -> None: get_db().execute( - """INSERT INTO content_cache (path, sha, title, date, categories, generated) - VALUES (?, ?, ?, ?, ?, ?) + """INSERT INTO content_cache (path, sha, title, date, categories, generated, + event_date, event_time, event_location) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(path) DO UPDATE SET sha = excluded.sha, title = excluded.title, date = excluded.date, categories = excluded.categories, generated = excluded.generated, + event_date = excluded.event_date, event_time = excluded.event_time, + event_location = excluded.event_location, updated_at = datetime('now')""", (path, sha, str(fm.get("title", "")), str(fm.get("date", "")), - ", ".join(fm.get("categories") or []), 1 if fm.get("translated_from") else 0), + ", ".join(fm.get("categories") or []), 1 if fm.get("translated_from") else 0, + # Cached for the private calendar, which shows public events beside the + # internal ones and would otherwise read every post's frontmatter on + # 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 "")), ) @@ -197,6 +224,9 @@ def listing(collection: str) -> list[dict]: "name": name, "path": path, "sha": sha, "title": row["title"] or name, "date": row["date"], "categories": row["categories"], + "event_date": row["event_date"] or "", + "event_time": row["event_time"] or "", + "event_location": row["event_location"] or "", }) items.sort(key=lambda item: (item["date"], item["name"]), reverse=True) @@ -247,11 +277,6 @@ def _read_form(collection: str) -> tuple[dict, str, list[str]]: categories = [c for c in request.form.getlist("categories") if c in CATEGORIES] - # Carried through the form as hidden fields, the way the date and the image - # path are: they belong to the document being edited, not to whoever is - # editing it, so saving a correction must not re-sign the post. Checked on - # the way back in because a hidden field is only a convention — the URL has - # to be a path on this site and nothing else. # 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 # three languages — and the menu is built from these, not from a list in @@ -269,9 +294,19 @@ def _read_form(collection: str) -> tuple[dict, str, list[str]]: # separator is dropped rather than published half-formed. They are rendered # on the page and as FAQPage structured data, which is the shape an answer # engine quotes most readily. + # When a post is an event, it has a date of its own. The post's `date` above + # is when it was announced — often weeks earlier, and the thing Hugo sorts + # the blog by — so the two cannot be the same field. + event = read_event_fields(request.form, categories, errors) + faq = clean_faq(request.form.get("faq", "")) image_alt = request.form.get("image_alt", "").strip()[:200] + # Carried through the form as hidden fields, the way the date and the image + # path are: they belong to the document being edited, not to whoever is + # editing it, so saving a correction must not re-sign the post. Checked on + # the way back in because a hidden field is only a convention — the URL has + # to be a path on this site and nothing else. author = request.form.get("author", "").strip()[:80] author_url = request.form.get("author_url", "").strip() if author_url and not AUTHOR_URL.match(author_url): @@ -294,6 +329,7 @@ def _read_form(collection: str) -> tuple[dict, str, list[str]]: "author": author, "author_url": author_url, "parent": parent, "weight": weight, "faq": faq, "image_alt": image_alt, + **event, } return fields, body, errors @@ -332,6 +368,40 @@ def commit_picture(data: bytes, filename: str, author=None) -> str: return f"/uploads/{name}" +def read_event_fields(form, categories: list[str], errors: list[str]) -> dict: + """The three fields that come with the Evento category. + + Shared by the editor and by a member's proposal, so a post written by a + moderator and one approved from the queue carry the same frontmatter. The + date is required and the other two are not: an event with no time is an + all-day event, and one with no place is a mistake somebody can fix later + rather than a reason to refuse the whole post. + + Returns empty strings when the category is absent, so an ordinary article + never carries empty event lines in its frontmatter. + """ + if EVENT_CATEGORY not in categories: + return {"event_date": "", "event_time": "", "event_location": ""} + + raw = form.get("event_date", "").strip() + try: + event_date = datetime.strptime(raw, "%Y-%m-%d").date().isoformat() + except ValueError: + event_date = "" + errors.append("Un evento necesita fecha, con el formato AAAA-MM-DD.") + + event_time = form.get("event_time", "").strip() + if event_time and not EVENT_TIME.match(event_time): + event_time = "" + errors.append("La hora debe ser HH:MM, de 00:00 a 23:59.") + + return { + "event_date": event_date, + "event_time": event_time, + "event_location": form.get("event_location", "").strip()[:200], + } + + def clean_faq(raw: str) -> list[str]: """`pregunta|respuesta` per line, kept only when both halves are there. @@ -492,6 +562,9 @@ def edit(collection: str, name: str): "weight": fm.get("weight", ""), "faq": "\n".join(fm.get("faq") or []), "image_alt": fm.get("image_alt", ""), + "event_date": str(fm.get("event_date", "") or ""), + "event_time": str(fm.get("event_time", "") or ""), + "event_location": fm.get("event_location", ""), } return render_template("content_form.html", collection=collection, meta=meta, categories=CATEGORIES, item={"name": name, "sha": sha}, @@ -562,6 +635,36 @@ def preview(collection: str): preview_html=to_html(body)) +def public_events() -> list[dict]: + """The published events, for the private calendar to show beside its own. + + Reads the same cache the editor's listing fills, so this costs one directory + request and nothing more for files that have not changed. The permalink is + rebuilt from the filename rather than stored: `YYYY-MM-DD-slug.es.md` is the + contract translate.py and Hugo's `permalinks` both already rely on. + """ + events = [] + for item in listing("post"): + if not item["event_date"]: + continue + # `2026-10-24-feria.es.md` → /2026/10/24/feria/, the shape config.yaml's + # `permalinks` sets for this section. + parts = item["name"].removesuffix(".es.md").split("-", 3) + if len(parts) == 4 and parts[0].isdigit(): + url = f"/{parts[0]}/{parts[1]}/{parts[2]}/{parts[3]}/" + else: + url = "" + events.append({ + "title": item["title"], + "starts_on": item["event_date"], + "starts_at": item["event_time"], + "location": item["event_location"], + "url": url, + "public": True, + }) + return events + + def possible_parents(collection: str, exclude: str = "") -> list[dict]: """The pages a page may hang under, for the select in the form. diff --git a/apps/board/events.py b/apps/board/events.py new file mode 100644 index 0000000..067bcde --- /dev/null +++ b/apps/board/events.py @@ -0,0 +1,329 @@ +"""The private calendar. + +What the association is doing and when, for the people inside: a meeting, a +rehearsal, a visit somewhere. Admins write them, every member reads them, and +nothing here is ever published — no Open Graph, no sitemap, nothing written to +/var/www. That is the whole difference between this and a post in the Evento +category, and it is why the two live in different places rather than behind a +flag on one. + +**The public events appear here too**, marked as public and linking to the site, +because a member should have one place to look rather than two. They come from +`content.public_events`, which reads the cache the editor's listing already +fills — so a month view costs one directory request to the git server, not one +per post. When that server cannot be reached the private events still render and +the page says the public ones are missing, rather than failing whole. + +The month grid is built with Python's own `calendar` module. There is no +JavaScript here and no date arithmetic of mine to get wrong: the standard +library has known which day of the week the first of the month falls on since +1991. +""" + +from __future__ import annotations + +import calendar +import re +from datetime import date, datetime + +from flask import (Blueprint, Response, abort, flash, g, redirect, + render_template, request, url_for) + +from . import content, gitea, uploads +from .db import get_db +from .render import to_html +from .security import admin_required, login_required + +bp = Blueprint("events", __name__) + +TITLE_MAX = 140 +BODY_MAX = 20_000 +LOCATION_MAX = 200 + +MONTH = re.compile(r"^(\d{4})-(0[1-9]|1[0-2])$") +TIME = re.compile(r"^([01][0-9]|2[0-3]):[0-5][0-9]$") + +MONTH_NAMES = ["enero", "febrero", "marzo", "abril", "mayo", "junio", "julio", + "agosto", "septiembre", "octubre", "noviembre", "diciembre"] +WEEKDAYS = ["lun", "mar", "mié", "jue", "vie", "sáb", "dom"] + + +def month_label(year: int, month: int) -> str: + return f"{MONTH_NAMES[month - 1]} {year}" + + +def shift(year: int, month: int, by: int) -> tuple[int, int]: + """The month `by` months away. Written out rather than reached for a + library: twelve months is modular arithmetic, and dateutil is a dependency.""" + index = (year * 12 + month - 1) + by + return index // 12, index % 12 + 1 + + +def _requested_month() -> tuple[int, int]: + """`?mes=2026-10`, or the month we are in. A malformed one is today's rather + than a 400: a calendar that refuses to draw because a query string was + mistyped is worse than one that shows now.""" + match = MONTH.match(request.args.get("mes", "")) + if match: + return int(match.group(1)), int(match.group(2)) + today = date.today() + return today.year, today.month + + +def private_events(first: str, last: str) -> list[dict]: + rows = get_db().execute( + """SELECT e.*, m.display_name AS author + FROM events e LEFT JOIN members m ON m.id = e.created_by + WHERE e.starts_on BETWEEN ? AND ? + ORDER BY e.starts_on, COALESCE(e.starts_at, '99:99')""", + (first, last), + ).fetchall() + return [{ + "id": row["id"], + "title": row["title"], + "starts_on": row["starts_on"], + "starts_at": row["starts_at"] or "", + "location": row["location"] or "", + "url": url_for("events.show", event_id=row["id"]), + "public": False, + } for row in rows] + + +@bp.route("/calendario") +@login_required +def month(): + year, number = _requested_month() + days_in_month = calendar.monthrange(year, number)[1] + first = f"{year:04d}-{number:02d}-01" + last = f"{year:04d}-{number:02d}-{days_in_month:02d}" + + events = private_events(first, last) + + # The public ones, from the site. A git server that is unreachable must not + # take the private calendar down with it — it is the half that only exists + # here. + public_missing = False + try: + events += [item for item in content.public_events() + if first <= item["starts_on"] <= last] + except gitea.GiteaError: + public_missing = True + + by_day: dict[int, list] = {} + for item in sorted(events, key=lambda e: (e["starts_on"], e["starts_at"] or "99:99")): + by_day.setdefault(int(item["starts_on"][8:10]), []).append(item) + + previous_year, previous_month = shift(year, number, -1) + next_year, next_month = shift(year, number, 1) + today = date.today() + + return render_template( + "calendar.html", + weeks=calendar.Calendar(firstweekday=0).monthdayscalendar(year, number), + weekdays=WEEKDAYS, + by_day=by_day, + label=month_label(year, number), + month_key=f"{year:04d}-{number:02d}", + previous=f"{previous_year:04d}-{previous_month:02d}", + next=f"{next_year:04d}-{next_month:02d}", + this_month=f"{today.year:04d}-{today.month:02d}", + today=today.day if (today.year, today.month) == (year, number) else 0, + public_missing=public_missing, + may_edit=g.member["role"] in ("owner", "admin"), + ) + + +@bp.route("/calendario/") +@login_required +def show(event_id: int): + row = _load(event_id) + return render_template("event.html", event=row, + body_html=to_html(row["body_md"] or ""), + when=_spoken_date(row["starts_on"]), + may_edit=g.member["role"] in ("owner", "admin")) + + +@bp.route("/calendario/.ics") +@login_required +def ics(event_id: int): + """The same courtesy the public events get, behind the login. + + Hand-written rather than through a library for the same reason the rest of + this app is: it is fifteen lines of a format that has not changed since + 1998, and the alternative is a dependency to track for them. + """ + row = _load(event_id) + start = row["starts_on"].replace("-", "") + if row["starts_at"]: + when = f"DTSTART;TZID=Europe/Vienna:{start}T{row['starts_at'].replace(':', '')}00" + else: + when = f"DTSTART;VALUE=DATE:{start}" + + def escaped(text: str) -> str: + return re.sub(r"([,;\\])", r"\\\1", (text or "").replace("\n", " ")) + + lines = [ + "BEGIN:VCALENDAR", "VERSION:2.0", + "PRODID:-//Viena Latina//calendario//ES", "CALSCALE:GREGORIAN", + "BEGIN:VEVENT", + # Stable and unique, so adding it twice updates one entry rather than + # making two. + f"UID:evento-{row['id']}@vienalatina.com", + f"DTSTAMP:{datetime.utcnow().strftime('%Y%m%dT%H%M%SZ')}", + when, + f"SUMMARY:{escaped(row['title'])}", + ] + if row["location"]: + lines.append(f"LOCATION:{escaped(row['location'])}") + if row["body_md"]: + lines.append(f"DESCRIPTION:{escaped(row['body_md'])[:500]}") + lines += ["END:VEVENT", "END:VCALENDAR"] + + return Response( + "\r\n".join(lines) + "\r\n", + mimetype="text/calendar", + headers={"Content-Disposition": + f'attachment; filename="evento-{row["id"]}.ics"'}, + ) + + +# --- writing them, which only admins do ----------------------------------- + +@bp.route("/calendario/nuevo", methods=["GET", "POST"]) +@admin_required +def new(): + if request.method == "GET": + return render_template("event_form.html", event=None, + suggested=request.args.get("dia", "")) + + fields, errors = _read_form() + if errors: + return _back(None, fields, errors) + + photo_name = _store_picture() + cursor = get_db().execute( + """INSERT INTO events (title, body_md, starts_on, starts_at, location, + photo_name, created_by) + VALUES (?, ?, ?, ?, ?, ?, ?)""", + (fields["title"], fields["body"], fields["starts_on"], fields["starts_at"], + fields["location"], photo_name, g.member["id"]), + ) + flash("Evento añadido al calendario.", "ok") + return redirect(url_for("events.show", event_id=cursor.lastrowid)) + + +@bp.route("/calendario//editar", methods=["GET", "POST"]) +@admin_required +def edit(event_id: int): + row = _load(event_id) + if request.method == "GET": + return render_template("event_form.html", event=row, suggested="") + + fields, errors = _read_form() + if errors: + return _back(row, fields, errors) + + photo_name = row["photo_name"] + staged = _store_picture() + if staged: + if photo_name: + uploads.remove(photo_name) + photo_name = staged + + get_db().execute( + """UPDATE events SET title = ?, body_md = ?, starts_on = ?, starts_at = ?, + location = ?, photo_name = ?, updated_at = datetime('now') + WHERE id = ?""", + (fields["title"], fields["body"], fields["starts_on"], fields["starts_at"], + fields["location"], photo_name, event_id), + ) + flash("Evento actualizado.", "ok") + return redirect(url_for("events.show", event_id=event_id)) + + +@bp.route("/calendario//eliminar", methods=["POST"]) +@admin_required +def delete(event_id: int): + row = _load(event_id) + get_db().execute("DELETE FROM events WHERE id = ?", (event_id,)) + if row["photo_name"]: + uploads.remove(row["photo_name"]) + flash(f"«{row['title']}» ya no está en el calendario.", "ok") + return redirect(url_for("events.month", mes=row["starts_on"][:7])) + + +@bp.route("/calendario/foto/") +@login_required +def photo(stored_name: str): + """Behind the login, like the calendar it belongs to.""" + if not uploads.STORED_NAME.match(stored_name): + abort(404) + row = get_db().execute( + "SELECT 1 FROM events WHERE photo_name = ?", (stored_name,)).fetchone() + if row is None: + abort(404) + from flask import send_from_directory + return send_from_directory(uploads.directory(), stored_name) + + +# --- helpers -------------------------------------------------------------- + +def _load(event_id: int): + row = get_db().execute("SELECT * FROM events WHERE id = ?", (event_id,)).fetchone() + if row is None: + abort(404) + return row + + +def _spoken_date(stamp: str) -> str: + when = datetime.strptime(stamp, "%Y-%m-%d").date() + return f"{when.day} de {MONTH_NAMES[when.month - 1]} de {when.year}" + + +def _read_form() -> tuple[dict, list[str]]: + errors = [] + fields = { + "title": request.form.get("title", "").strip()[:TITLE_MAX], + "body": request.form.get("body", "").strip()[:BODY_MAX], + "location": request.form.get("location", "").strip()[:LOCATION_MAX], + "starts_on": "", + "starts_at": "", + } + if not fields["title"]: + errors.append("El evento necesita un título.") + + try: + fields["starts_on"] = datetime.strptime( + request.form.get("starts_on", "").strip(), "%Y-%m-%d").date().isoformat() + except ValueError: + errors.append("La fecha debe tener el formato AAAA-MM-DD.") + + at = request.form.get("starts_at", "").strip() + if at and not TIME.match(at): + errors.append("La hora debe ser HH:MM, de 00:00 a 23:59.") + else: + fields["starts_at"] = at or None + + return fields, errors + + +def _store_picture(): + """One picture, on disk beside the rest, with no `attachments` row — the same + arrangement a profile photo and a proposal's picture already use.""" + try: + staged = uploads.stage(request.files.getlist("picture")) + except uploads.RejectedUpload as exc: + flash(str(exc), "error") + return None + if not staged: + return None + item = staged[0] + uploads.directory().joinpath(item["stored_name"]).write_bytes(item["data"]) + return item["stored_name"] + + +def _back(event, fields, errors): + for message in errors: + flash(message, "error") + return render_template("event_form.html", event=event, fields=fields, + suggested=""), 400 diff --git a/apps/board/gitea.py b/apps/board/gitea.py index 82bcd44..aff9bc2 100644 --- a/apps/board/gitea.py +++ b/apps/board/gitea.py @@ -218,12 +218,25 @@ def _content_request(method: str, url: str, token: str, **kwargs): Hence the message: the thing to check is the token's scope, and it should say so on the screen rather than in a traceback nobody reads. """ - response = requests.request( - method, url, - headers={"Authorization": f"Bearer {token}"}, - timeout=TIMEOUT, - **kwargs, - ) + try: + response = requests.request( + method, url, + headers={"Authorization": f"Bearer {token}"}, + timeout=TIMEOUT, + **kwargs, + ) + except requests.RequestException as exc: + # The network is a failure mode of this module, not of its callers. + # `requests` raises its own exceptions, which inherit from OSError and so + # are not GiteaError — so a caller that handles GiteaError carefully, as + # the calendar does to keep working while the git server is down, would + # still have been taken out by a refused connection. Translated here, at + # the one place that touches the wire. + current_app.logger.warning("gitea unreachable: %s", exc) + raise GiteaError( + "No se pudo contactar con el servidor de git. Vuelve a intentarlo " + "en un momento." + ) from exc if response.status_code in (401, 403): raise GiteaError( "El servidor de git rechazó el token del editor. Comprueba que " diff --git a/apps/board/home.py b/apps/board/home.py index 40f149f..4328da1 100644 --- a/apps/board/home.py +++ b/apps/board/home.py @@ -124,6 +124,7 @@ def session_state(): {"label": "Muro", "url": url_for("board.threads")}, {"label": "Privados", "url": url_for("messages.inbox")}, {"label": "Publicaciones", "url": url_for("submissions.index")}, + {"label": "Calendario", "url": url_for("events.month")}, ] if g.member["role"] in ("owner", "admin"): sections.append({"label": "Gestión", "url": url_for("home.gestion")}) diff --git a/apps/board/members.py b/apps/board/members.py index d535bfb..5998273 100644 --- a/apps/board/members.py +++ b/apps/board/members.py @@ -108,7 +108,13 @@ REASSIGNED_ON_ERASE = { # Removing the picture itself means deleting the post it is attached to. ("attachments", "uploaded_by"), } -CLEARED_ON_ERASE = {("members", "created_by")} +CLEARED_ON_ERASE = { + ("members", "created_by"), + # An event in the private calendar belongs to the association, not to the + # admin who typed it in: the meeting still happens after they leave, so the + # row stays and the name goes. + ("events", "created_by"), +} # Private correspondence is not reassigned to the tombstone, it goes. A thread # outlives its author because other people replied and the conversation would diff --git a/apps/board/migrations.py b/apps/board/migrations.py index 986322b..29447a4 100644 --- a/apps/board/migrations.py +++ b/apps/board/migrations.py @@ -206,6 +206,32 @@ def _members_can_moderate(db: sqlite3.Connection) -> None: if broken: raise RuntimeError(f"migration left dangling references: {broken}") +def _rooms_for_a_date_of_its_own(db: sqlite3.Connection) -> None: + """Somewhere to keep an event's date, in the two tables that already exist. + + Plain ADD COLUMNs, nothing like the rebuilds in steps 1 and 4 — neither + table has a CHECK in the way. + + `submissions` needs them because a member can propose an event, and the date + has to survive in the queue until a moderator approves it. `content_cache` + needs them because the private calendar shows public events beside internal + ones, and reading every post's frontmatter on every page view to find their + dates is exactly what that cache exists to avoid. + """ + for table in ("submissions", "content_cache"): + existing = _columns(db, table) + if not existing: + # No such table in this database. `init_db` runs schema.sql before + # these steps, so on a real server both tables are always there; + # skipping rather than failing keeps a step from depending on how + # much of the schema a given database happens to have, which is the + # property that lets these run against any vintage. + continue + for column in ("event_date", "event_time", "event_location"): + if column not in existing: + db.execute(f"ALTER TABLE {table} ADD COLUMN {column} TEXT") + + # (number, description, function). The number is the value written to # user_version once the step succeeds. STEPS = [ @@ -213,6 +239,7 @@ STEPS = [ (2, "members keep their own password", _members_own_their_passwords), (3, "members can have a public page", _members_get_a_public_page), (4, "members can be moderators", _members_can_moderate), + (5, "events carry a date of their own", _rooms_for_a_date_of_its_own), ] diff --git a/apps/board/schema.sql b/apps/board/schema.sql index ade97ad..3df8ef6 100644 --- a/apps/board/schema.sql +++ b/apps/board/schema.sql @@ -246,6 +246,12 @@ CREATE TABLE IF NOT EXISTS submissions ( body_md TEXT NOT NULL, description TEXT NOT NULL DEFAULT '', categories TEXT NOT NULL DEFAULT '', -- comma-separated, as content_cache + -- Set only when the proposal carries the Evento category. The event's own + -- date, which is not the day it is published: a member announcing a concert + -- three weeks out is the normal case. + event_date TEXT, + event_time TEXT, + event_location TEXT, photo_name TEXT, state TEXT NOT NULL DEFAULT 'pending' CHECK (state IN ('pending', 'approved', 'rejected')), @@ -292,3 +298,30 @@ CREATE UNIQUE INDEX IF NOT EXISTS reactions_one_per_thread ON reactions(member_id, thread_id) WHERE thread_id IS NOT NULL; CREATE UNIQUE INDEX IF NOT EXISTS reactions_one_per_comment ON reactions(member_id, comment_id) WHERE comment_id IS NOT NULL; + +-- The private calendar. +-- +-- Events the association puts on for its members: a meeting, a rehearsal, a +-- visit somewhere. Written by admins, read by every member, and never published +-- — nothing here reaches /var/www, the sitemap or a share card, which is the +-- difference between this table and a post with the Evento category. +-- +-- `starts_on` and `starts_at` are kept apart rather than as one timestamp +-- because an event with no time is an ordinary thing ("the whole Saturday") and +-- a timestamp cannot say so without inventing midnight. +CREATE TABLE IF NOT EXISTS events ( + id INTEGER PRIMARY KEY, + title TEXT NOT NULL, + body_md TEXT NOT NULL DEFAULT '', + starts_on TEXT NOT NULL, -- YYYY-MM-DD + starts_at TEXT, -- HH:MM, or null for all day + location TEXT NOT NULL DEFAULT '', + photo_name TEXT, + -- Cleared rather than reassigned when that member is erased: the event + -- belongs to the association, not to whoever typed it in. + created_by INTEGER REFERENCES members(id), + created_at TEXT NOT NULL DEFAULT (datetime('now')), + updated_at TEXT +); + +CREATE INDEX IF NOT EXISTS events_month ON events(starts_on); diff --git a/apps/board/static/board.css b/apps/board/static/board.css index 4d3f819..ce39279 100644 --- a/apps/board/static/board.css +++ b/apps/board/static/board.css @@ -611,3 +611,76 @@ input[type="file"] { color: var(--subtle); overflow-wrap: anywhere; } + +/* --- the private calendar ---------------------------------------------- */ + +.cal-bar { + display: flex; + align-items: center; + justify-content: space-between; + gap: 1rem; + margin-bottom: 0.35rem; +} +.cal-bar__today { text-align: center; margin: 0 0 1rem; } + +.cal { + width: 100%; + border-collapse: collapse; + table-layout: fixed; +} +.cal th { + padding: 0.4rem; + font-size: 0.72rem; + text-transform: uppercase; + letter-spacing: 0.04em; + color: var(--muted); + text-align: left; +} +.cal__day, .cal__pad { + vertical-align: top; + height: 92px; + padding: 0.35rem; + border: 1px solid var(--border-light); + border-radius: var(--radius-sm); + background: var(--surface); + font-size: 0.8rem; +} +.cal__pad { background: transparent; border-color: transparent; } +.cal__day--today { border-color: var(--brand); background: var(--brand-softer); } +.cal__number { color: var(--subtle); font-weight: 700; } + +.cal__event { + display: block; + margin-top: 0.25rem; + color: var(--brand-dark); + text-decoration: none; + line-height: 1.3; +} +.cal__event:hover { text-decoration: underline; } +.cal__event time { font-weight: 700; } +/* A public event is the association speaking to everybody; an internal one is + not. The distinction has to survive a glance. */ +.cal__event--public { color: var(--muted); } + +.cal__add { + display: none; + float: right; + color: var(--subtle); + text-decoration: none; + font-weight: 700; +} +.cal__day:hover .cal__add { display: inline; } +.cal__add:hover { color: var(--brand); } + +.event-facts p { margin: 0 0 0.25rem; } + +/* Seven columns of nothing is what a month grid is on a phone. */ +@media (max-width: 640px) { + .cal, .cal tbody, .cal tr, .cal td { display: block; width: auto; } + .cal thead { display: none; } + .cal__pad { display: none; } + .cal__day { height: auto; margin-bottom: 0.4rem; } + .cal__day:not(:has(.cal__event)) { display: none; } + .cal__number { display: inline-block; margin-right: 0.5rem; } + .cal__add { display: inline; } +} diff --git a/apps/board/submissions.py b/apps/board/submissions.py index e8152d4..e575549 100644 --- a/apps/board/submissions.py +++ b/apps/board/submissions.py @@ -92,14 +92,18 @@ def _read_proposal() -> tuple[dict, list[str]]: """The same fields the editor asks for, minus the ones only a publisher decides: the date is the day it is approved, and `manual_translation` is a pipeline switch, not something to explain to a member.""" + categories = [c for c in request.form.getlist("categories") + if c in content.CATEGORIES] + errors = [] fields = { "title": request.form.get("title", "").strip()[:TITLE_MAX], "body": request.form.get("body", "").strip()[:BODY_MAX], "description": request.form.get("description", "").strip()[:300], - "categories": [c for c in request.form.getlist("categories") - if c in content.CATEGORIES], + "categories": categories, + # The same three fields the editor asks for, read by the same function: + # a member's event and a moderator's have to produce the same post. + **content.read_event_fields(request.form, categories, errors), } - errors = [] if not fields["title"]: errors.append("El título no puede estar vacío.") if not fields["body"]: @@ -175,10 +179,12 @@ def propose(): photo_name = _store_picture(staged) get_db().execute( """INSERT INTO submissions - (author_id, title, body_md, description, categories, photo_name) - VALUES (?, ?, ?, ?, ?, ?)""", + (author_id, title, body_md, description, categories, photo_name, + event_date, event_time, event_location) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)""", (g.member["id"], fields["title"], fields["body"], fields["description"], - ", ".join(fields["categories"]), photo_name), + ", ".join(fields["categories"]), photo_name, + fields["event_date"], fields["event_time"], fields["event_location"]), ) flash("Enviado. Un moderador lo leerá antes de publicarlo.", "ok") return redirect(url_for("submissions.index")) @@ -217,6 +223,9 @@ def edit(submission_id: int): "description": row["description"], "categories": [c.strip() for c in (row["categories"] or "").split(",") if c.strip()], + "event_date": row["event_date"] or "", + "event_time": row["event_time"] or "", + "event_location": row["event_location"] or "", }) fields, errors = _read_proposal() @@ -238,12 +247,14 @@ def edit(submission_id: int): get_db().execute( """UPDATE submissions SET title = ?, body_md = ?, description = ?, categories = ?, - photo_name = ?, state = 'pending', note = NULL, + photo_name = ?, event_date = ?, event_time = ?, + event_location = ?, state = 'pending', note = NULL, reviewed_by = NULL, reviewed_at = NULL, updated_at = datetime('now') WHERE id = ?""", (fields["title"], fields["body"], fields["description"], - ", ".join(fields["categories"]), photo_name, submission_id), + ", ".join(fields["categories"]), photo_name, fields["event_date"], + fields["event_time"], fields["event_location"], submission_id), ) # Back to pending on every edit, including one made after a rejection: a # rejected post that has been rewritten is waiting again, and leaving it @@ -313,6 +324,11 @@ def approve(submission_id: int): "description": row["description"], "image": "", "manual_translation": False, + # Straight through: the event the member described is the event that + # gets published, with its own date rather than today's. + "event_date": row["event_date"] or "", + "event_time": row["event_time"] or "", + "event_location": row["event_location"] or "", } # Read the picture before the try, and catch only the error that means what # it says. The first version wrapped everything in `except OSError`, which diff --git a/apps/board/templates/base.html b/apps/board/templates/base.html index 67507f4..100544d 100644 --- a/apps/board/templates/base.html +++ b/apps/board/templates/base.html @@ -53,6 +53,7 @@ anybody else the function returns 0 and nothing is drawn. #} Publicaciones{% set waiting = pending_review() %}{% if waiting %} {{ waiting }}{% endif %} +
  • Calendario
  • {% if g.member.role in ('owner', 'admin') %}
  • Gestión
  • {% endif %} diff --git a/apps/board/templates/calendar.html b/apps/board/templates/calendar.html new file mode 100644 index 0000000..8e89cd0 --- /dev/null +++ b/apps/board/templates/calendar.html @@ -0,0 +1,68 @@ +{% extends "base.html" %} +{% block title %}Calendario{% endblock %} + +{% block main %} +
    +

    Calendario

    + {% if may_edit %} + Añadir evento + {% endif %} +
    + +{% if public_missing %} +

    + No se pudo leer la agenda pública del servidor de git, así que aquí abajo + faltan los eventos del sitio. Los internos están todos. +

    +{% endif %} + + +

    + Ir a este mes +

    + + + + {% for day in weekdays %}{% endfor %} + + + {% for week in weeks %} + + {% for day in week %} + {# calendar.monthdayscalendar pads the first and last weeks with + zeroes, which are days belonging to the neighbouring months. #} + {% if day == 0 %} + + {% else %} + + {% endif %} + {% endfor %} + + {% endfor %} + +
    {{ day }}
    + {{ day }} + {% for item in by_day.get(day, []) %} + + {% if item.starts_at %} {% endif %}{{ item.title }} + {% if item.public %}público{% endif %} + + {% endfor %} + {% if may_edit %} + {# The day is carried into the form, so adding something to the + 24th starts with the 24th already filled in. #} + + + {% endif %} +
    + +

    + Los eventos marcados público están en + vienalatina.com y los ve cualquiera. Los demás sólo se ven desde aquí. +

    +{% endblock %} diff --git a/apps/board/templates/content_form.html b/apps/board/templates/content_form.html index 53ec107..edb306e 100644 --- a/apps/board/templates/content_form.html +++ b/apps/board/templates/content_form.html @@ -77,6 +77,30 @@ {% endfor %} + {# An event's own date, which is not the day the post goes up. Shown whenever + a post can be written: ticking Evento above is what makes these required, + checked on the server rather than hidden and shown with a script. #} +
    + Si es un evento +

    + Marca Evento arriba y rellena al menos la fecha. El + evento aparecerá en la agenda del sitio y se podrá añadir al + calendario del móvil. +

    + + + + + + +

    Déjala vacía si dura todo el día.

    + + + +

    Dónde es: el sitio, la calle, el barrio.

    +
    +

    diff --git a/apps/board/templates/event.html b/apps/board/templates/event.html new file mode 100644 index 0000000..f40a705 --- /dev/null +++ b/apps/board/templates/event.html @@ -0,0 +1,41 @@ +{% extends "base.html" %} +{% block title %}{{ event.title }}{% endblock %} + +{% block main %} +

    +

    {{ event.title }}

    + Volver al calendario +
    + +
    +
    +

    {{ when }}{% if event.starts_at %} · {{ event.starts_at }}{% endif %}

    + {% if event.location %}

    {{ event.location }}

    {% endif %} +
    + + {% if event.photo_name %} + {{ event.title }} + {% endif %} + + {% if event.body_md %}
    {{ body_html }}
    {% endif %} + +
    + Añadir a mi calendario + {% if may_edit %} + Editar +
    + + +
    + {% endif %} +
    +
    + +

    + Este evento sólo se ve desde el área de miembros. Para anunciar algo a todo + el mundo, usa Publicaciones + con la categoría «Evento». +

    +{% endblock %} diff --git a/apps/board/templates/event_form.html b/apps/board/templates/event_form.html new file mode 100644 index 0000000..05c2038 --- /dev/null +++ b/apps/board/templates/event_form.html @@ -0,0 +1,50 @@ +{% extends "base.html" %} +{% block title %}{{ 'Editar evento' if event else 'Nuevo evento' }}{% endblock %} + +{% set f = fields or event %} + +{% block main %} +
    +

    {{ 'Editar evento' if event else 'Nuevo evento' }}

    +
    + +

    + Esto va al calendario de la comunidad, que sólo ven los miembros. No sale al + sitio público ni se comparte fuera. +

    + +
    + + + + + + + + + + +

    Déjala vacía si dura todo el día.

    + + + + + + + + + + {% if event and event.photo_name %} +

    Ya tiene una. Subir otra la reemplaza.

    + {% endif %} + +
    + + Cancelar +
    +
    +{% endblock %} diff --git a/apps/board/templates/submission_form.html b/apps/board/templates/submission_form.html index 2b5a985..72928b2 100644 --- a/apps/board/templates/submission_form.html +++ b/apps/board/templates/submission_form.html @@ -35,6 +35,30 @@ {% endfor %} + {# An event's own date, which is not the day the post goes up. Shown whenever + a post can be written: ticking Evento above is what makes these required, + checked on the server rather than hidden and shown with a script. #} +
    + Si es un evento +

    + Marca Evento arriba y rellena al menos la fecha. El + evento aparecerá en la agenda del sitio y se podrá añadir al + calendario del móvil. +

    + + + + + + +

    Déjala vacía si dura todo el día.

    + + + +

    Dónde es: el sitio, la calle, el barrio.

    +
    + diff --git a/apps/board/tests/test_content.py b/apps/board/tests/test_content.py index 582d470..083a628 100644 --- a/apps/board/tests/test_content.py +++ b/apps/board/tests/test_content.py @@ -599,3 +599,79 @@ def test_a_parent_that_has_been_deleted_is_kept_and_named(repo, editor, client): assert 'value="borrada" selected' in body assert "no encontrada" in body + + +# --- events, which are posts with a date of their own --------------------- + +def test_an_event_carries_its_own_date_and_an_ics(repo, editor, post): + """The post's `date` is when it was announced; `event_date` is when it + happens, and the two are weeks apart in the normal case.""" + import yaml + post("/comunidad/contenido/post/nuevo", + {"title": "Feria de otoño", "body": "Ven.", "date": "2026-10-03", + "categories": ["Evento", "Comunidad"], "event_date": "2026-10-24", + "event_time": "18:30", "event_location": "Plaza de Ottakring"}) + + path, = repo.files + front = yaml.safe_load(repo.files[path].decode().split("---")[1]) + assert front["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" + # Hugo builds an .ics only for pages that ask for one. + assert front["outputs"] == ["HTML", "ics"] + + +def test_the_evento_category_without_a_date_is_refused(repo, editor, post): + response = post("/comunidad/contenido/post/nuevo", + {"title": "Algún día", "body": "Texto.", "date": "2026-10-03", + "categories": ["Evento"]}) + + assert response.status_code == 400 + assert "necesita fecha" in response.get_data(as_text=True) + assert repo.files == {} + + +def test_a_nonsense_hour_is_refused(repo, editor, post): + response = post("/comunidad/contenido/post/nuevo", + {"title": "Feria", "body": "Texto.", "date": "2026-10-03", + "categories": ["Evento"], "event_date": "2026-10-24", + "event_time": "25:99"}) + + assert response.status_code == 400 + assert repo.files == {} + + +def test_an_ordinary_post_carries_no_event_lines(repo, editor, post): + """Rather than three empty keys for somebody to wonder about.""" + import yaml + post("/comunidad/contenido/post/nuevo", + {"title": "Un artículo", "body": "Texto.", "date": "2026-10-03", + "categories": ["Cultura"], "event_date": "2026-10-24"}) + + path, = repo.files + front = yaml.safe_load(repo.files[path].decode().split("---")[1]) + for key in ("event_date", "event_time", "event_location", "outputs"): + assert key not in front, key + + +def test_an_event_keeps_its_date_when_edited(repo, editor, post, client): + import yaml + repo.files["content/post/2026-10-03-feria.es.md"] = ( + "---\ntitle: Feria\ndate: 2026-10-03\nlang: es\nmanual_translation: false\n" + "event_date: '2026-10-24'\nevent_time: '18:30'\n" + "event_location: La plaza\ncategories:\n- Evento\n---\n\nVen.\n").encode("utf-8") + + body = client.get("/comunidad/contenido/post/editar/2026-10-03-feria.es.md").get_data(as_text=True) + assert 'value="2026-10-24"' in body + assert 'value="18:30"' in body + + post("/comunidad/contenido/post/editar/2026-10-03-feria.es.md", + {"title": "Feria", "body": "Ven pronto.", "date": "2026-10-03", + "categories": ["Evento"], "event_date": "2026-10-24", + "event_time": "18:30", "event_location": "La plaza", + "sha": repo._sha(repo.files["content/post/2026-10-03-feria.es.md"])}) + + front = yaml.safe_load( + repo.files["content/post/2026-10-03-feria.es.md"].decode().split("---")[1]) + assert front["event_date"] == "2026-10-24" diff --git a/apps/board/tests/test_events.py b/apps/board/tests/test_events.py new file mode 100644 index 0000000..686158e --- /dev/null +++ b/apps/board/tests/test_events.py @@ -0,0 +1,231 @@ +"""Two calendars that must not be confused with each other. + +The public one is posts with the Evento category: published, translated, +indexed, shareable. The private one is rows in this database: admins write them, +members read them, and nothing about them reaches the public site. Most of what +is worth testing here is that boundary, and the handful of date rules that are +easy to get subtly wrong and hard to notice. +""" + +from __future__ import annotations + +from datetime import date + +import pytest + +from apps.board import events, gitea + + +@pytest.fixture +def quiet_gitea(monkeypatch): + """The private calendar asks the git server for the published events. These + tests are about the private half, so it answers with nothing.""" + monkeypatch.setattr(gitea, "list_directory", lambda *a, **k: []) + + +@pytest.fixture +def an_event(post, owner_id, sign_in, quiet_gitea): + def _add(title="Asamblea", starts_on="2026-10-24", **extra): + sign_in(owner_id) + data = {"title": title, "starts_on": starts_on} + data.update(extra) + post("/comunidad/calendario/nuevo", data) + return title + return _add + + +# --- who writes, who reads ------------------------------------------------ + +def test_an_admin_adds_an_event_and_every_member_sees_it( + client, an_event, make_member, sign_in): + an_event() + + sign_in(make_member("maria")) + page = client.get("/comunidad/calendario?mes=2026-10").get_data(as_text=True) + + assert "Asamblea" in page + assert "cal__add" not in page # no + on the days + assert "Añadir evento" not in page # and no button + + +def test_a_member_cannot_reach_the_form_or_the_handler(client, post, make_member, sign_in): + sign_in(make_member("maria")) + + assert client.get("/comunidad/calendario/nuevo").status_code == 403 + assert post("/comunidad/calendario/nuevo", + {"title": "Mío", "starts_on": "2026-10-24"}).status_code == 403 + + +def test_a_moderator_cannot_either(client, make_member, sign_in): + """Moderating what the public reads is not the same as putting something in + the association's diary.""" + sign_in(make_member("luisa", role="moderator")) + assert client.get("/comunidad/calendario/nuevo").status_code == 403 + + +def test_the_calendar_itself_is_behind_the_login(client): + response = client.get("/comunidad/calendario") + assert response.status_code == 302 + assert "/login" in response.headers["Location"] + + +# --- the month ----------------------------------------------------------- + +def test_the_month_shows_its_own_events_and_not_the_neighbours( + client, an_event, owner_id, sign_in): + an_event("Asamblea", "2026-10-24") + an_event("Ensayo", "2026-11-03") + + sign_in(owner_id) + october = client.get("/comunidad/calendario?mes=2026-10").get_data(as_text=True) + + assert "Asamblea" in october + assert "Ensayo" not in october + + +def test_the_arrows_cross_the_year(client, an_event, owner_id, sign_in): + sign_in(owner_id) + page = client.get("/comunidad/calendario?mes=2026-12").get_data(as_text=True) + + assert "mes=2027-01" in page + assert "mes=2026-11" in page + + +def test_shifting_months_wraps_properly(): + assert events.shift(2026, 12, 1) == (2027, 1) + assert events.shift(2026, 1, -1) == (2025, 12) + assert events.shift(2026, 6, 0) == (2026, 6) + + +def test_a_mistyped_month_shows_today_rather_than_an_error( + client, owner_id, sign_in, quiet_gitea): + """A calendar that refuses to draw because a query string was mistyped is + worse than one that shows now.""" + sign_in(owner_id) + today = date.today() + + page = client.get("/comunidad/calendario?mes=pumpkin") + + assert page.status_code == 200 + assert events.month_label(today.year, today.month) in page.get_data(as_text=True) + + +def test_february_in_a_leap_year_has_twenty_nine_days(client, owner_id, sign_in, quiet_gitea): + sign_in(owner_id) + page = client.get("/comunidad/calendario?mes=2028-02").get_data(as_text=True) + assert ">29<" in page + assert ">30<" not in page + + +# --- what the git server does to this ------------------------------------ + +def test_the_private_events_survive_a_git_server_that_is_down( + client, post, owner_id, sign_in, monkeypatch): + """The half that only exists here must not be taken down by the half that + does not. A refused connection reaches this module as a GiteaError because + gitea.py translates it — before that it was a bare OSError and this page + would have 500ed.""" + import requests + sign_in(owner_id) + post("/comunidad/calendario/nuevo", {"title": "Asamblea", "starts_on": "2026-10-24"}) + + def refuse(*args, **kwargs): + raise requests.ConnectionError("nobody home") + monkeypatch.setattr(gitea.requests, "request", refuse) + + page = client.get("/comunidad/calendario?mes=2026-10") + + assert page.status_code == 200 + body = page.get_data(as_text=True) + assert "Asamblea" in body + assert "faltan los eventos del sitio" in body + + +# --- the .ics ------------------------------------------------------------- + +def test_the_ics_is_a_calendar_a_phone_understands(client, an_event, owner_id, sign_in): + an_event("Asamblea", "2026-10-24", starts_at="19:00", + location="Local de la asociación") + sign_in(owner_id) + + response = client.get("/comunidad/calendario/1.ics") + + assert response.mimetype == "text/calendar" + body = response.get_data(as_text=True) + assert body.startswith("BEGIN:VCALENDAR\r\n") + assert body.endswith("END:VCALENDAR\r\n") + assert "DTSTART;TZID=Europe/Vienna:20261024T190000" in body + assert "SUMMARY:Asamblea" in body + assert "UID:evento-1@vienalatina.com" in body # stable, so re-adding updates + + +def test_an_event_with_no_time_lasts_the_whole_day(client, an_event, owner_id, sign_in): + """VALUE=DATE rather than inventing midnight, which is how a calendar shows + it as a band across the top of the day.""" + an_event("Jornada", "2026-10-24") + sign_in(owner_id) + + body = client.get("/comunidad/calendario/1.ics").get_data(as_text=True) + + assert "DTSTART;VALUE=DATE:20261024" in body + + +def test_a_comma_in_the_place_is_escaped(client, an_event, owner_id, sign_in): + """An unescaped comma in LOCATION makes the rest of the line a second + value, and the address arrives truncated.""" + an_event("Asamblea", "2026-10-24", location="Plaza de Ottakring, junto al mercado") + sign_in(owner_id) + + body = client.get("/comunidad/calendario/1.ics").get_data(as_text=True) + + assert "LOCATION:Plaza de Ottakring\\, junto al mercado" in body + + +def test_the_ics_needs_a_session(client, an_event): + an_event() + # The fixture had to sign in to create it; this is about the visitor who + # finds the URL afterwards. + with client.session_transaction() as session: + session.clear() + + response = client.get("/comunidad/calendario/1.ics") + + assert response.status_code == 302 + assert "/login" in response.headers["Location"] + + +# --- refusals ------------------------------------------------------------- + +def test_an_event_without_a_date_is_refused(client, db, post, owner_id, sign_in, quiet_gitea): + sign_in(owner_id) + + response = post("/comunidad/calendario/nuevo", {"title": "Algún día"}) + + assert response.status_code == 400 + assert db.execute("SELECT COUNT(*) AS n FROM events").fetchone()["n"] == 0 + + +def test_a_nonsense_time_is_refused(client, db, post, owner_id, sign_in, quiet_gitea): + sign_in(owner_id) + + post("/comunidad/calendario/nuevo", + {"title": "Asamblea", "starts_on": "2026-10-24", "starts_at": "25:99"}) + + assert db.execute("SELECT COUNT(*) AS n FROM events").fetchone()["n"] == 0 + + +# --- erasure -------------------------------------------------------------- + +def test_erasing_the_admin_leaves_the_event_standing( + db, post, an_event, owner_id, make_member, sign_in, quiet_gitea): + """The meeting still happens after they leave: the event belongs to the + association, so the row stays and the name goes.""" + admin = make_member("admina", role="admin") + sign_in(admin) + post("/comunidad/calendario/nuevo", {"title": "Asamblea", "starts_on": "2026-10-24"}) + + sign_in(owner_id) + post(f"/comunidad/miembros/{admin}/eliminar") + + row = db.execute("SELECT title, created_by FROM events").fetchone() + assert (row["title"], row["created_by"]) == ("Asamblea", None) diff --git a/apps/board/tests/test_migrations.py b/apps/board/tests/test_migrations.py index 19f7153..ad2f22a 100644 --- a/apps/board/tests/test_migrations.py +++ b/apps/board/tests/test_migrations.py @@ -302,6 +302,11 @@ def test_the_app_starts_against_a_database_from_before_all_this(tmp_path): assert (kept["stored_name"], kept["thread_id"], kept["bytes"]) == ( "foto-abc123abc123.jpg", 1, 2048) + # Step 5: somewhere to keep an event's own date, in both tables. + for table in ("submissions", "content_cache"): + columns = {row[1] for row in db.execute(f"PRAGMA table_info({table})")} + assert {"event_date", "event_time", "event_location"} <= columns, table + # Step 4: the role list is wider, the one-owner rule survived the rebuild, # and nothing that pointed at a member row lost its target. db.execute("INSERT INTO members (gitea_login, display_name, role) " diff --git a/apps/board/tests/test_navigation.py b/apps/board/tests/test_navigation.py index ebe80c8..7e6f82d 100644 --- a/apps/board/tests/test_navigation.py +++ b/apps/board/tests/test_navigation.py @@ -23,6 +23,7 @@ SECTIONS = { "Muro": "/comunidad/muro", "Privados": "/comunidad/privados", "Publicaciones": "/comunidad/publicaciones", + "Calendario": "/comunidad/calendario", } ADMIN_ONLY = {"Gestión": "/comunidad/gestion"} @@ -175,7 +176,7 @@ def test_a_member_gets_their_name_and_their_sections(client, make_member, sign_i assert state["signed_in"] is True assert state["name"] == "Maria" assert [s["label"] for s in state["sections"]] == [ - "Inicio", "Muro", "Privados", "Publicaciones"] + "Inicio", "Muro", "Privados", "Publicaciones", "Calendario"] assert state["csrf"] # the bar renders a real logout form diff --git a/apps/board/tests/test_submissions.py b/apps/board/tests/test_submissions.py index 13cf9cb..894e086 100644 --- a/apps/board/tests/test_submissions.py +++ b/apps/board/tests/test_submissions.py @@ -469,3 +469,33 @@ def test_an_approved_post_is_signed_by_the_member_not_the_moderator( assert front["author"] == "Maria" assert front["author_url"] == "/maria" assert repo.authors == [{"name": "Maria", "email": "maria@example.com"}] + + +def test_a_member_can_propose_an_event_and_it_keeps_its_date( + repo, db, post, maria, luisa, sign_in): + """Same form, same queue, same approval — and the event that reaches the + site is the one the member described, dated when it happens.""" + import yaml + sign_in(maria) + propose(post, categories=["Evento"], event_date="2026-11-07", + event_time="20:00", event_location="Sala Ottakring") + submission_id = only_submission(db)["id"] + + sign_in(luisa) + post(f"/comunidad/publicaciones/{submission_id}/aprobar") + + path, = repo.files + front = yaml.safe_load(repo.files[path].decode().split("---")[1]) + assert front["event_date"] == "2026-11-07" + assert front["event_time"] == "20:00" + assert front["event_location"] == "Sala Ottakring" + assert front["author"] == "Maria" + + +def test_an_event_proposal_without_a_date_is_refused(db, post, maria, sign_in): + sign_in(maria) + + response = propose(post, categories=["Evento"]) + + assert response.status_code == 400 + assert db.execute("SELECT COUNT(*) AS n FROM submissions").fetchone()["n"] == 0 diff --git a/config.yaml b/config.yaml index 43bfa72..2052eb3 100644 --- a/config.yaml +++ b/config.yaml @@ -103,6 +103,14 @@ outputFormats: mediaType: "text/plain" baseName: "llms" isPlainText: true + # One .ics beside an event's page, so "añadir a mi calendario" is a link and + # not an instruction. Only pages whose frontmatter lists this output generate + # one, and the editor writes that line for a post in the Evento category — + # see apps/board/content.py. + ics: + mediaType: "text/calendar" + baseName: "index" + isPlainText: true outputs: home: ["HTML", "RSS", "llms"] diff --git a/content/page/agenda.es.md b/content/page/agenda.es.md new file mode 100644 index 0000000..79f4a71 --- /dev/null +++ b/content/page/agenda.es.md @@ -0,0 +1,11 @@ +--- +title: Agenda +lang: es +layout: agenda +weight: 4 +manual_translation: false +description: Todo lo que organiza la comunidad latinoamericana en Viena, mes a mes. +--- + +Lo que viene: ferias, charlas, conciertos y encuentros. Cada evento se puede +añadir al calendario del móvil desde su propia página. diff --git a/docs/server-setup.md b/docs/server-setup.md index 1f66c68..e9dd032 100644 --- a/docs/server-setup.md +++ b/docs/server-setup.md @@ -902,6 +902,40 @@ WordPress: hover and `:focus-within`, inline on a phone, no script. Only *Inicio* and *Comunidad* remain in `config.yaml`. Weight under 5 puts a menu entry before the pages, 5 or more after them. +### 11.15b Two calendars + +**Public events are posts** in the **Evento** category, with three fields of +their own: `event_date`, `event_time` and `event_location`. The post's own `date` +is when it was announced — usually weeks earlier, and what Hugo sorts the blog by +— so the event's date cannot be the same field. Ticking Evento without a date is +refused. Members can propose events exactly as they propose anything else, and a +moderator approves them. + +An event's page leads with the day, the time and the place, shows its picture +full width, and offers **Añadir a mi calendario**: a `.ics` beside the page, +generated because the editor writes `outputs: ["HTML", "ics"]` into an event's +frontmatter. It also carries `Event` structured data, which is what puts a date +beside the result in a search listing. + +`vienalatina.com/page/agenda/` is a month grid per month, from the first event to +the last, built at build time. `assets/js/agenda.js` shows one and moves between +them — so with JavaScript off every month is on the page as a list, and with it +on, moving months costs no request and starts on the month the *reader* is in +rather than the month the site was built in. + +**The private calendar** is `/comunidad/calendario`: rows in SQLite, written by +admins, read by every member, never published. It shows the public events too, +marked, so a member has one place to look; those come from the `content_cache` +that the editor's listing already fills, which is why **migration 5** adds three +columns to it and to `submissions`. If the git server is unreachable the private +events still render and the page says so — `gitea.py` now turns a refused +connection into a `GiteaError` rather than letting `requests`' own exception +through, which is what made that possible. + +The month grid is Python's `calendar.Calendar`; there is no date arithmetic of +ours anywhere in it. Erasing an admin clears `events.created_by` and leaves the +event standing: the meeting still happens after they leave. + ### 11.16 Sharing, SEO and answer engines `partials/seo-head.html` was already emitting hreflang, Open Graph, a Twitter diff --git a/scripts/translate.py b/scripts/translate.py index 179f246..8839dad 100644 --- a/scripts/translate.py +++ b/scripts/translate.py @@ -60,6 +60,9 @@ CONTENT_DIR = REPO_ROOT / "content" # Frontmatter strings translated alongside the body. Note `categories` is # deliberately absent: the taxonomy terms stay Spanish in every language, or # Hugo would fork the taxonomy per language. +# `event_location` is deliberately absent: an address is how somebody finds the +# place, and a translated street or venue name is worse than an untranslated one. +# `event_date` and `event_time` are data, not prose. TRANSLATED_KEYS = ("title", "description", "image_alt") # `faq` is a list of "question|answer" lines, so it cannot go through the loop diff --git a/themes/vienalatina/assets/css/main.css b/themes/vienalatina/assets/css/main.css index f1d20ad..bafc19d 100644 --- a/themes/vienalatina/assets/css/main.css +++ b/themes/vienalatina/assets/css/main.css @@ -3816,3 +3816,133 @@ a.notif-card__message:hover { font: inherit; cursor: pointer; } + +/* --- an event, and the agenda ------------------------------------------ */ + +/* The three things somebody needs before they read a word. */ +.event-card { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 20px; + margin: 20px 0 24px; + padding: 16px 20px; + background: var(--brand-softer, #fdf1ed); + border: 1px solid var(--brand-soft, #fbe2db); + border-radius: var(--radius-xl, 18px); +} + +.event-card__date { + display: flex; + flex-direction: column; + align-items: center; + line-height: 1.05; + color: var(--brand, #c0391c); +} + +.event-card__day { font-size: 2.4rem; font-weight: 800; } +.event-card__month { font-size: 0.95rem; font-weight: 700; } +.event-card__year { font-size: 0.8rem; opacity: 0.75; } + +.event-card__facts { margin: 0; flex: 1 1 200px; } +.event-card__facts dt { + font-size: 0.72rem; + text-transform: uppercase; + letter-spacing: 0.06em; + color: var(--muted, #5c3d37); +} +.event-card__facts dd { margin: 0 0 8px; font-weight: 600; } +.event-card__facts dd:last-child { margin-bottom: 0; } + +.event-card__add { + display: inline-block; + padding: 8px 16px; + border-radius: 999px; + background: var(--brand, #c0391c); + color: #fff; + font-size: 0.86rem; + font-weight: 700; + text-decoration: none; +} +.event-card__add:hover { background: var(--brand-dark, #9a2a0f); color: #fff; } + +/* An event's picture carries the page rather than illustrating it. */ +.article-single__cover--hero { + width: 100%; + max-height: 420px; + object-fit: cover; + border-radius: var(--radius-lg, 12px); +} + +.agenda__intro { color: var(--muted, #5c3d37); margin-bottom: 16px; } + +.agenda__bar { + display: flex; + align-items: center; + justify-content: center; + gap: 16px; + margin: 16px 0; +} + +.agenda__move { + width: 40px; + height: 40px; + border-radius: 50%; + border: 1px solid var(--border-light, #e0cec8); + background: var(--surface, #fff); + color: var(--brand, #c0391c); + font-size: 1.1rem; + cursor: pointer; +} +.agenda__move:hover:not(:disabled) { border-color: var(--brand, #c0391c); } +.agenda__move:disabled { opacity: 0.35; cursor: default; } +.agenda__current { font-size: 1.05rem; min-width: 10rem; text-align: center; } + +/* Until agenda.js runs, every month is visible and the controls would lie + about which one is showing — so the bar appears only once it has. */ +.agenda__bar { display: none; } +.has-agenda-script .agenda__bar { display: flex; } +.has-agenda-script .agenda__heading { display: none; } + +.agenda__grid { + display: grid; + grid-template-columns: repeat(7, 1fr); + gap: 4px; + list-style: none; + margin: 0 0 24px; + padding: 0; +} + +.agenda__day, .agenda__pad { + min-height: 92px; + padding: 6px; + border: 1px solid var(--border-light, #e0cec8); + border-radius: var(--radius-sm, 5px); + background: var(--surface, #fff); + font-size: 0.8rem; +} +.agenda__pad { background: transparent; border-color: transparent; } +.agenda__number { color: var(--subtle, #9a7870); font-weight: 700; } +.agenda__day--busy { background: var(--brand-softer, #fdf1ed); border-color: var(--brand-soft, #fbe2db); } + +.agenda__event { + display: block; + margin-top: 4px; + color: var(--brand-dark, #9a2a0f); + text-decoration: none; + line-height: 1.3; +} +.agenda__event time { font-weight: 700; } +.agenda__event:hover { text-decoration: underline; } + +.agenda__empty { text-align: center; margin: -12px 0 24px; } + +/* A seven-column grid on a phone is seven columns of nothing. Below 640px the + month becomes a list of the days that have something in them. */ +@media (max-width: 640px) { + .agenda__grid { display: block; } + .agenda__pad { display: none; } + .agenda__day { display: none; min-height: 0; margin-bottom: 6px; } + .agenda__day--busy { display: block; } + .agenda__number { display: inline-block; margin-right: 8px; } +} diff --git a/themes/vienalatina/assets/js/agenda.js b/themes/vienalatina/assets/js/agenda.js new file mode 100644 index 0000000..2672649 --- /dev/null +++ b/themes/vienalatina/assets/js/agenda.js @@ -0,0 +1,52 @@ +// Which month the agenda is showing. +// +// Every month is already on the page — the layout builds them all — so this +// only decides which one is visible and moves between them. Three consequences +// worth keeping: a reader with no JavaScript sees every month stacked instead of +// a blank page, moving months makes no request, and the month it starts on is +// decided here rather than when the site was built, so it is right however long +// ago that was. +(function () { + "use strict"; + + var months = [].slice.call(document.querySelectorAll(".agenda__month")); + if (months.length === 0) return; + + var label = document.querySelector("[data-agenda-label]"); + var buttons = [].slice.call(document.querySelectorAll("[data-agenda-move]")); + var keys = months.map(function (section) { return section.dataset.month; }); + + // The month the reader is in, or the nearest one the page has. + var now = new Date(); + var current = now.getFullYear() + "-" + ("0" + (now.getMonth() + 1)).slice(-2); + var index = keys.indexOf(current); + if (index === -1) { + index = 0; + for (var i = 0; i < keys.length; i++) { + if (keys[i] <= current) index = i; + } + } + + function show(next) { + index = Math.max(0, Math.min(months.length - 1, next)); + months.forEach(function (section, i) { + section.hidden = i !== index; + }); + if (label) label.textContent = months[index].dataset.label; + buttons.forEach(function (button) { + var step = parseInt(button.dataset.agendaMove, 10); + button.disabled = index + step < 0 || index + step > months.length - 1; + }); + } + + buttons.forEach(function (button) { + button.addEventListener("click", function () { + show(index + parseInt(button.dataset.agendaMove, 10)); + }); + }); + + // Only now: until this runs the page is the no-JavaScript version, every + // month visible, which is what a crawler and a reader without scripts get. + document.documentElement.classList.add("has-agenda-script"); + show(index); +})(); diff --git a/themes/vienalatina/layouts/_default/single.html b/themes/vienalatina/layouts/_default/single.html index 896f008..b3810d0 100644 --- a/themes/vienalatina/layouts/_default/single.html +++ b/themes/vienalatina/layouts/_default/single.html @@ -36,12 +36,41 @@

    {{ .Title }}

    + {{/* An event leads with the three things somebody needs before they read + a word: when, what time, and where. Everything else on the page is + the same article it would otherwise be. */}} + {{ with .Params.event_date }} + {{ $when := . | time.AsTime }} + + {{ end }} + {{ with .Description }}

    {{ . }}

    {{ end }} {{ with .Params.image }} - + {{ $.Params.image_alt | default $.Title }} {{ end }}
    diff --git a/themes/vienalatina/layouts/_default/single.ics b/themes/vienalatina/layouts/_default/single.ics new file mode 100644 index 0000000..60fa6da --- /dev/null +++ b/themes/vienalatina/layouts/_default/single.ics @@ -0,0 +1,40 @@ +{{- /* One event, as a file a calendar app understands. + + RFC 5545 in fifteen lines. The things that actually matter here: + + * CRLF line endings. The spec says so and some readers are strict about + it; Hugo writes what this template contains, so the \r is explicit. + * UID has to be stable and unique — the permalink is both, and re-adding + an event updates the entry instead of duplicating it. + * Times are written with a TZID of Europe/Vienna rather than converted to + UTC. Every event here happens in one city, and a local time that stays + local survives a daylight-saving change the way a converted one does + not. + * An event with no time is a whole day: VALUE=DATE, which is how a + calendar shows it as a band across the top instead of inventing + midnight. */ -}} +{{- $date := .Params.event_date | time.AsTime -}} +{{- $stamp := now.UTC.Format "20060102T150405Z" -}} +BEGIN:VCALENDAR{{ printf "\r" }} +VERSION:2.0{{ printf "\r" }} +PRODID:-//{{ .Site.Title }}//agenda//ES{{ printf "\r" }} +CALSCALE:GREGORIAN{{ printf "\r" }} +METHOD:PUBLISH{{ printf "\r" }} +BEGIN:VEVENT{{ printf "\r" }} +UID:{{ .Permalink }}{{ printf "\r" }} +DTSTAMP:{{ $stamp }}{{ printf "\r" }} +{{ with .Params.event_time -}} +DTSTART;TZID=Europe/Vienna:{{ $date.Format "20060102" }}T{{ replace . ":" "" }}00{{ printf "\r" }} +{{ else -}} +DTSTART;VALUE=DATE:{{ $date.Format "20060102" }}{{ printf "\r" }} +{{ end -}} +SUMMARY:{{ .Title | plainify | replaceRE "[,;\\\\]" "\\${0}" }}{{ printf "\r" }} +{{ with .Params.event_location -}} +LOCATION:{{ . | plainify | replaceRE "[,;\\\\]" "\\${0}" }}{{ printf "\r" }} +{{ end -}} +{{ with .Description -}} +DESCRIPTION:{{ . | plainify | replaceRE "[,;\\\\]" "\\${0}" }}{{ printf "\r" }} +{{ end -}} +URL:{{ .Permalink }}{{ printf "\r" }} +END:VEVENT{{ printf "\r" }} +END:VCALENDAR{{ printf "\r" }} diff --git a/themes/vienalatina/layouts/page/agenda.html b/themes/vienalatina/layouts/page/agenda.html new file mode 100644 index 0000000..1ea5f92 --- /dev/null +++ b/themes/vienalatina/layouts/page/agenda.html @@ -0,0 +1,101 @@ +{{/* The public agenda: one grid per month, all of them built here. + + Every month between the first event and the last is rendered, plus the + current one, and assets/js/agenda.js shows one at a time. Two things fall + out of building them all rather than fetching a month at a time: + + * **With JavaScript off, every month is on the page**, stacked, each under + its own heading. Nothing is hidden from a reader who has no script, and + nothing is hidden from a crawler either. + * Moving between months is instant and makes no request. + + The weekday arithmetic is the awkward part, because Hugo exposes no + AddDate: the length of a month comes from a table plus a leap-year check, + and the weekday of the first falls out of formatting that date. It looks + like something simpler was missed, and it is not. */}} +{{ define "main" }} +{{ $lang := .Site.Language.Lang }} +{{ $events := where (where .Site.RegularPages "Section" "post") "Params.event_date" "!=" nil }} + +{{/* The span to render: from the earliest event to the latest, and always + including the month the site was built in, so an empty agenda still shows + the reader where they are. */}} +{{ $months := slice }} +{{ range $events }}{{ $months = $months | append (substr .Params.event_date 0 7) }}{{ end }} +{{ $months = $months | append (now.Format "2006-01") }} +{{ $months = sort (uniq $months) }} +{{ $from := index $months 0 }} +{{ $to := index $months (sub (len $months) 1) }} + +{{/* Expanded so a month with nothing in it can still be visited. */}} +{{ $span := slice }} +{{ range $y := seq (int (substr $from 0 4)) (int (substr $to 0 4)) }} +{{ range $m := seq 1 12 }} +{{ $key := printf "%04d-%02d" $y $m }} +{{ if and (ge $key $from) (le $key $to) }}{{ $span = $span | append $key }}{{ end }} +{{ end }} +{{ end }} + +{{ $script := resources.Get "js/agenda.js" | minify | fingerprint }} + + +
    +

    {{ .Title }}

    + {{ with .Content }}
    {{ . }}
    {{ end }} + + + + {{ range $key := $span }} + {{ $year := int (substr $key 0 4) }} + {{ $month := int (substr $key 5 2) }} + {{ $firstDay := printf "%s-01" $key }} + + {{/* Days in the month: a table, with February decided by the leap rule — + every four years, not every hundred, except every four hundred. */}} + {{ $lengths := slice 31 28 31 30 31 30 31 31 30 31 30 31 }} + {{ $days := index $lengths (sub $month 1) }} + {{ if eq $month 2 }} + {{ if or (and (eq (mod $year 4) 0) (ne (mod $year 100) 0)) (eq (mod $year 400) 0) }} + {{ $days = 29 }} + {{ end }} + {{ end }} + + {{/* Monday first, as in Austria and most of Latin America. Go names the + weekday; this turns the name into a column offset. */}} + {{ $offsets := dict "Mon" 0 "Tue" 1 "Wed" 2 "Thu" 3 "Fri" 4 "Sat" 5 "Sun" 6 }} + {{ $lead := index $offsets (($firstDay | time.AsTime).Format "Mon") }} + +
    +

    {{ partial "month-name.html" (dict "month" $month "lang" $lang) }} {{ $year }}

    + +
      + {{ 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 }} +
    1. + {{ $day }} + {{ range $onThisDay }} + + {{ with .Params.event_time }} {{ end }}{{ .Title }} + + {{ end }} +
    2. + {{ end }} +
    + + {{ $inMonth := where (where $events "Params.event_date" "ge" (printf "%s-01" $key)) "Params.event_date" "le" (printf "%s-31" $key) }} + {{ if not $inMonth }} +

    {{ partial "t.html" (dict "key" "noevents" "lang" $lang) }}

    + {{ end }} +
    + {{ end }} +
    +{{ end }} diff --git a/themes/vienalatina/layouts/partials/month-name.html b/themes/vienalatina/layouts/partials/month-name.html new file mode 100644 index 0000000..7a1fcaf --- /dev/null +++ b/themes/vienalatina/layouts/partials/month-name.html @@ -0,0 +1,12 @@ +{{- /* The month in the page's own language. + + Hugo's time.Format follows the site's language only when the translation + tables are installed, and this theme ships no i18n files — three languages, + twelve words each, is a table rather than a dependency. */ -}} +{{- $names := dict + "es" (slice "enero" "febrero" "marzo" "abril" "mayo" "junio" "julio" "agosto" "septiembre" "octubre" "noviembre" "diciembre") + "de" (slice "Januar" "Februar" "März" "April" "Mai" "Juni" "Juli" "August" "September" "Oktober" "November" "Dezember") + "pt-br" (slice "janeiro" "fevereiro" "março" "abril" "maio" "junho" "julho" "agosto" "setembro" "outubro" "novembro" "dezembro") +-}} +{{- $table := index $names .lang | default (index $names "es") -}} +{{- index $table (sub (int .month) 1) -}} diff --git a/themes/vienalatina/layouts/partials/seo-head.html b/themes/vienalatina/layouts/partials/seo-head.html index 5c6177b..e369517 100644 --- a/themes/vienalatina/layouts/partials/seo-head.html +++ b/themes/vienalatina/layouts/partials/seo-head.html @@ -85,6 +85,36 @@ {{ partial "breadcrumbs-schema.html" . }} {{ partial "faq-schema.html" . }} +{{/* An event is also an Event. This is what puts a date next to the result in a + search listing, and what an answer engine reads when somebody asks what is + on in Vienna this weekend — the article alone says none of it in a form a + machine can use. */}} +{{ with .Params.event_date }} +{{ $when := . | time.AsTime }} +{{ $start := $when.Format "2006-01-02" }} +{{ with $.Params.event_time }}{{ $start = printf "%sT%s:00" $start . }}{{ end }} +{{ $event := dict + "@context" "https://schema.org" + "@type" "Event" + "name" $.Title + "startDate" $start + "url" $.Permalink + "inLanguage" $.Site.Language.LanguageCode + "eventAttendanceMode" "https://schema.org/OfflineEventAttendanceMode" + "eventStatus" "https://schema.org/EventScheduled" + "organizer" (dict "@type" "Organization" "name" $.Site.Title "url" $.Site.Home.Permalink) +}} +{{ with $desc }}{{ $event = merge $event (dict "description" .) }}{{ end }} +{{ with $image }}{{ $event = merge $event (dict "image" .) }}{{ end }} +{{ with $.Params.event_location }} +{{ $event = merge $event (dict "location" (dict + "@type" "Place" + "name" . + "address" (dict "@type" "PostalAddress" "addressLocality" "Wien" "addressCountry" "AT"))) }} +{{ end }} + +{{ end }} + {{ else if .IsHome }} {{/* ---- Home ---- */}} diff --git a/themes/vienalatina/layouts/partials/t.html b/themes/vienalatina/layouts/partials/t.html new file mode 100644 index 0000000..e00b7a9 --- /dev/null +++ b/themes/vienalatina/layouts/partials/t.html @@ -0,0 +1,27 @@ +{{- /* The handful of words the templates themselves say. + + Everything else on this site is content and arrives already translated by + the pipeline. These are the labels around it — "Lugar", "Hoy" — and there + are eleven of them, which is a table rather than a reason to install i18n + files and a translation workflow for the theme. + + Usage: {{ partial "t.html" (dict "key" "place" "lang" .Site.Language.Lang) }} + An unknown key returns itself, so a typo is visible on the page instead of + rendering as nothing. */ -}} +{{- $words := dict + "time" (dict "es" "Hora" "de" "Uhrzeit" "pt-br" "Hora") + "place" (dict "es" "Lugar" "de" "Ort" "pt-br" "Local") + "add" (dict "es" "Añadir a mi calendario" "de" "Zum Kalender hinzufügen" "pt-br" "Adicionar ao meu calendário") + "agenda" (dict "es" "Agenda" "de" "Termine" "pt-br" "Agenda") + "today" (dict "es" "Hoy" "de" "Heute" "pt-br" "Hoje") + "previous" (dict "es" "Mes anterior" "de" "Voriger Monat" "pt-br" "Mês anterior") + "next" (dict "es" "Mes siguiente" "de" "Nächster Monat" "pt-br" "Próximo mês") + "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") +-}} +{{- $entry := index $words .key -}} +{{- if $entry -}} +{{- index $entry .lang | default (index $entry "es") -}} +{{- else -}} +{{- .key -}} +{{- end -}}