feat: improve calendar sharing

This commit is contained in:
jfmcarreira committed 2026-10-07 00:25:09 +01:00
1 parent 0bc800a971
commit 675c3a661c
6 files changed
+113 -16

No files matched your search

+17
View File
@@ -73,6 +73,23 @@ docker compose down
Stopping the service leaves the host data directory intact.
## Add shifts to a phone's calendar
Sign in, open **Calendário** from the rota, and choose your team's calendar
(administrators can also choose **Rota completa**):
- **iPhone / Apple Calendar** opens the native subscription confirmation.
- **Google Calendar / Android** opens Google Calendar on the web. Google requires
its desktop interface to add subscriptions: request the desktop site in your phone's
browser, or add it on a computer, then enable the calendar in the mobile app.
- **Outlook** opens the web subscription screen; use the same account as the mobile app.
- **Copiar endereço** supplies the feed URL for another app or manual setup.
The page includes step-by-step instructions for each platform. Subscribe by URL
rather than importing a downloaded `.ics` file so future changes appear automatically.
Providers control refresh timing; updates may take several hours. Google and Outlook
need an Internet-accessible feed address.
## Run tests
From the repository root, run one command:
+12
View File
@@ -70,6 +70,16 @@ input:focus,select:focus,button:focus-visible,a:focus-visible,summary:focus-visi
.flash{padding:12px 14px;border-radius:9px;margin-bottom:18px;background:var(--brand-soft);border-left:4px solid var(--brand)}
.flash.error{background:#f8e8e8;color:#7d2525;border-left-color:var(--danger)}
.calendar-list{display:flex;flex-direction:column;gap:8px;padding-bottom:35px}
.calendar-subscribe-actions{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:8px;margin:14px 0}
.calendar-subscribe-actions .button{display:flex;align-items:center;justify-content:center;text-align:center;min-height:48px}
.calendar-feed label{display:block;margin-bottom:6px;font-size:.9rem;font-weight:600}
.calendar-url-row{display:flex;align-items:center;flex-wrap:wrap;gap:8px}
.calendar-url-row input{flex:1 1 260px;min-width:0}
.calendar-copy-status{min-height:1.45em;margin:8px 0 0;font-size:.9rem}
.calendar-help details+details{margin-top:8px}
.calendar-help summary{padding:10px 0;min-height:44px}
.calendar-help ol{padding-left:24px;margin-top:4px}
.calendar-help li+li{margin-top:8px}
.day-card{display:grid;grid-template-columns:74px 1fr;overflow:hidden}
.day-card.today{outline:2px solid var(--brand);outline-offset:1px}
.day-label{padding:14px;text-align:center;border-right:1px solid var(--line);display:flex;flex-direction:column;background:#fffafa}
@@ -114,6 +124,8 @@ th{font-size:.8rem;text-transform:uppercase;color:var(--muted);background:#fff7f
.nav{order:3;width:100%;padding-bottom:4px}
.account{margin-left:auto}
.form-grid{grid-template-columns:1fr}
.calendar-subscribe-actions{grid-template-columns:1fr}
.calendar-url-row button{width:100%;min-height:44px}
.day-card{grid-template-columns:58px 1fr}
.day-label{padding:10px 7px}
.assignment{align-items:flex-start;flex-direction:column}
+1
View File
@@ -43,6 +43,7 @@
<section class="panel">
<h2>Calendário da equipa</h2>
<p class="muted">Um único endereço com a rota completa, para qualquer calendário.</p>
<p><a class="button secondary" href="{{ app_path('/calendar') }}">Adicionar ao calendário do telemóvel</a></p>
<div class="inline-form">
<input type="text" readonly value="{{ calendar_feed_url }}" aria-label="Endereço do calendário da equipa">
<button class="secondary" type="button" data-copy="{{ calendar_feed_url }}">Copiar</button>
+72 -15
View File
@@ -5,38 +5,95 @@
<div>
<p class="eyebrow"><a href="{{ app_path('/') }}">Rota</a></p>
<h1>Calendário</h1>
<p class="muted">Adiciona o endereço ao Google Calendar, Apple Calendar ou Outlook. O calendário atualiza-se sozinho, não é preciso repetir o processo.</p>
<p class="muted">Os teus turnos na app de calendário do telemóvel. Subscreve uma vez: as alterações à rota aparecem automaticamente, quando a app atualizar o calendário.</p>
</div>
</div>
<div class="stack gap-lg">
{% for feed in feeds %}
<section class="panel">
<section class="panel calendar-feed">
<h2>{{ feed.title }}</h2>
<div class="inline-form">
<input type="text" readonly value="{{ feed.url }}" aria-label="Endereço do calendário">
<button class="secondary" type="button" data-copy="{{ feed.url }}">Copiar</button>
<a class="button secondary" href="webcal://{{ feed.url.split('//')[-1] }}">Subscrever</a>
<div class="calendar-subscribe-actions" aria-label="Adicionar {{ feed.title }}">
<a class="button primary" href="{{ feed.webcal_url }}">iPhone / Apple Calendar</a>
<a class="button secondary" href="{{ feed.google_url }}" target="_blank" rel="noopener noreferrer">Google Calendar / Android</a>
<a class="button secondary" href="{{ feed.outlook_url }}" target="_blank" rel="noopener noreferrer">Outlook</a>
</div>
<p class="muted">No iPhone, confirma a subscrição na app Calendário. No Google e Outlook, adiciona pelo navegador à conta que usas no telemóvel. <a href="#calendar-help">Ver os passos</a>.</p>
<label for="calendar-url-{{ loop.index }}">Endereço para subscrever noutra app</label>
<div class="calendar-url-row">
<input id="calendar-url-{{ loop.index }}" type="text" readonly value="{{ feed.url }}" inputmode="url" autocapitalize="off" spellcheck="false">
<button class="secondary" type="button" data-copy="{{ feed.url }}">Copiar endereço</button>
</div>
<p class="calendar-copy-status muted" role="status" data-copy-status></p>
</section>
{% else %}
<div class="empty">Ainda não tens uma equipa ativa com calendário.</div>
{% endfor %}
</div>
<section class="panel calendar-help top-space" id="calendar-help">
<h2>Como adicionar no telemóvel</h2>
<details>
<summary>iPhone / iPad — Apple Calendar</summary>
<ol>
<li>Toca em <strong>iPhone / Apple Calendar</strong> no calendário que queres adicionar.</li>
<li>Permite abrir a app Calendário e confirma <strong>Subscrever</strong>.</li>
<li>Se o botão não abrir a app, copia o endereço. Na app Calendário, abre <strong>Calendários → Adicionar calendário → Adicionar calendário de assinatura</strong> e cola-o.</li>
</ol>
</details>
<details>
<summary>Android / Google Calendar</summary>
<ol>
<li>Toca em <strong>Google Calendar / Android</strong> e entra na conta Google que usas no telemóvel.</li>
<li>O Google exige a versão para computador para adicionar subscrições. No navegador do telemóvel, ativa <strong>Site para computador</strong>; se não conseguires, abre esta página num computador.</li>
<li>Confirma a adição. Se não aparecer essa opção, copia o endereço e, no Google Calendar, escolhe <strong>Outros calendários → + → A partir de URL</strong>, cola-o e adiciona o calendário.</li>
<li>Na app Google Calendar, abre o menu e ativa o novo calendário. Se não aparecer, verifica as definições de sincronização.</li>
</ol>
</details>
<details>
<summary>Outlook</summary>
<ol>
<li>Toca em <strong>Outlook</strong> e entra na conta que usas na app.</li>
<li>Confirma a subscrição no Outlook na Web. Se necessário, usa <strong>Adicionar calendário → Subscrever a partir da Web</strong> e cola o endereço copiado.</li>
<li>Na app Outlook, seleciona o novo calendário nessa conta. Se a versão móvel não mostrar a opção de subscrever, usa o navegador em modo computador.</li>
</ol>
</details>
<p class="muted">Escolhe uma subscrição por endereço, em vez de importar um ficheiro .ics, para receber futuras alterações. A atualização depende da app e pode demorar algumas horas. Para Google e Outlook, o endereço tem de estar acessível pela Internet.</p>
</section>
<script>
// Copy the address without leaving the page; falls back to selecting the field.
// Clipboard permissions can fail even on HTTPS; keep a mobile-friendly fallback.
document.querySelectorAll("[data-copy]").forEach(function (button) {
button.addEventListener("click", function () {
button.addEventListener("click", async function () {
var url = button.dataset.copy;
var field = button.parentElement.querySelector("input");
var status = button.closest(".calendar-feed").querySelector("[data-copy-status]");
var copied = false;
if (navigator.clipboard && window.isSecureContext) {
navigator.clipboard.writeText(url);
button.textContent = "Copiado";
setTimeout(function () { button.textContent = "Copiar"; }, 1500);
return;
try {
await navigator.clipboard.writeText(url);
copied = true;
} catch (error) {
// Fall through to selection/copy when clipboard access is denied.
}
}
if (!copied) {
field.focus();
field.select();
field.setSelectionRange(0, field.value.length);
try {
copied = document.execCommand("copy");
} catch (error) {
// The selected field still supports the phone's native Copy action.
}
}
if (copied) {
button.textContent = "Copiado";
status.textContent = "Endereço copiado. Cola-o na tua app de calendário.";
setTimeout(function () { button.textContent = "Copiar endereço"; }, 2000);
} else {
status.textContent = "Endereço selecionado. Toque no campo e escolha «Copiar».";
}
field.focus();
field.select();
button.textContent = "Copie com Ctrl+C";
});
});
</script>
+9
View File
@@ -4,6 +4,7 @@ import calendar
from collections.abc import Sequence
import secrets
from datetime import date, datetime, time, timedelta
from urllib.parse import urlencode
from fastapi import APIRouter, Depends, Form, HTTPException, Request
from fastapi.responses import HTMLResponse, RedirectResponse, Response
@@ -316,6 +317,14 @@ def calendar_page(request: Request, db: Session = Depends(get_db)):
"url": _shared_calendar_url(request),
}
)
for feed in feeds:
feed["webcal_url"] = "webcal://" + feed["url"].split("://", 1)[-1]
feed["google_url"] = "https://calendar.google.com/calendar/render?" + urlencode(
{"cid": feed["url"]}
)
feed["outlook_url"] = "https://outlook.live.com/calendar/0/addfromweb?" + urlencode(
{"url": feed["url"], "name": feed["title"]}
)
return request.app.state.templates.TemplateResponse(
request=request,
name="calendar.html",
+2 -1
View File
@@ -18,7 +18,8 @@ Every start copies the SQLite file aside before anything else runs, using SQLite
## Calendar feeds
- `/calendar/<token>.ics` is an iCalendar feed anybody can subscribe to from Google Calendar, Apple Calendar or Outlook. Every team has its own token, created the first time someone assigned to it opens `/calendar`, and its feed only carries the shifts assigned to it.
- `/calendar` is the page holding those links: the rota only has a button pointing there, so it keeps showing nothing but who works each day. A user gets one feed per team it is assigned to, each titled `Turnos de <equipa>`. Each address sits in a readonly field with a **Copiar** button (clipboard when the browser allows it, selecting the field otherwise) plus a `webcal://` shortcut.
- `/calendar` is the page holding those links: the rota only has a button pointing there, so it keeps showing nothing but who works each day. A user gets one feed per active team it is assigned to, each titled `Turnos de <equipa>`, plus the whole-rota feed for administrators. Each feed has mobile-sized **iPhone / Apple Calendar**, **Google Calendar / Android**, and **Outlook** actions. Apple opens a `webcal://` subscription; Google and Outlook open web subscription flows with the feed address encoded in the link. The page includes platform-specific instructions, a readonly address field, and **Copiar endereço**, with clipboard-error handling and a native-selection fallback for phones.
- Google does not add URL subscriptions through its mobile app: use its desktop web interface (request the desktop site on the phone, or use a computer), then enable the calendar in the mobile app using the same account. Outlook subscriptions also use its web interface. Subscriptions refresh according to the provider's schedule, rather than instantly; Google and Outlook must be able to fetch the address over the Internet. Importing a downloaded `.ics` file is a snapshot and is not the subscription workflow.
- Administrators also get one shared feed with the whole rota, using the team token in `CALENDAR_TOKEN` (generated on first use and shown on `/admin/schedules`).
- A feed publishes one month back and six months forward. Times carry the bar's timezone (`DTSTART;TZID=Europe/Lisbon:20261017T203000`) and the feed declares it in `X-WR-TIMEZONE` plus a `VTIMEZONE` block with the European summer-time rules (WET/WEST), so every client shows a night at 20:30 and keeps the right offset across the year. The zone comes from `TIMEZONE`; an unknown zone falls back to `Europe/Lisbon`. Times and names are private member data: the token is the only protection, so the shared link goes only to the team.
- Each event title is `<equipa> · <escala> · <horas>` so a list of shifts reads at a glance; a shift without a team keeps `<escala> · <horas>`.