@@ -25,30 +25,30 @@
{{ assignment.schedule.name }}
- {% if assignment.user %}{{ assignment.user.name }}{% else %}Unassigned{% endif %}
+ {% if assignment.user %}{{ assignment.user.name }}{% else %}Sem atribuição{% endif %}
{% if assignment.id in my_assignment_ids and day >= today %}
{% if assignment.id in open_swap_assignment_ids %}
-
Change requested
+
Troca pedida
{% else %}
- Request change
+ Pedir troca
{% endif %}
diff --git a/app/templates/login.html b/app/templates/login.html
index c98fcc4..f352066 100644
--- a/app/templates/login.html
+++ b/app/templates/login.html
@@ -1,21 +1,21 @@
{% extends "base.html" %}
-{% block title %}Sign in · {{ settings.app_name }}{% endblock %}
+{% block title %}Entrar · {{ settings.app_name }}{% endblock %}
{% block content %}
- Sign in
- Use your rota username and password.
+ Entrar
+ Use o seu utilizador e a sua palavra-passe da escala.
{% endblock %}
diff --git a/app/templates/schedule.html b/app/templates/schedule.html
index e9b561d..3bb5886 100644
--- a/app/templates/schedule.html
+++ b/app/templates/schedule.html
@@ -4,7 +4,7 @@
{% set schedule = card.schedule %}
-
Schedules
+
Escalas
{{ schedule.name }}
{{ card.kind_label }}{% if schedule.label_time %} · {{ schedule.label_time }}{% endif %}
@@ -12,27 +12,27 @@
{% if card.kind == 'rotation' %}
- Next dates
+ Próximas datas
{{ card.dates | join(' · ') }}
- Rotation order
+ Ordem da rotação
{% for name in card.rotation_names %}
- {{ name }}
- {% else %}- No members yet.
{% endfor %}
+ {% else %}- Ainda não há membros.
{% endfor %}
{% else %}
- The same every month: one person for each day of the month.
- Pattern
+ Igual todos os meses: uma pessoa para cada dia do mês.
+ Padrão
{% for day, person_name in card.pattern %}
- {{ day }} {{ person_name }}
- {% else %}- Nobody set yet.
{% endfor %}
+ {% else %}- Ainda não há ninguém definido.
{% endfor %}
{% endif %}
{% if cards | length > 1 %}
- Other schedules
+ Outras escalas
{% for other in cards %}
{% if other.schedule.id != schedule.id %}
@@ -44,6 +44,6 @@
{% endif %}
{% if not current_user %}
-
+
{% endif %}
-{% endblock %}
\ No newline at end of file
+{% endblock %}
diff --git a/app/templates/schedules.html b/app/templates/schedules.html
index 29627f3..c29a14a 100644
--- a/app/templates/schedules.html
+++ b/app/templates/schedules.html
@@ -1,7 +1,7 @@
{% extends "base.html" %}
-{% block title %}Schedules · {{ settings.app_name }}{% endblock %}
+{% block title %}Escalas · {{ settings.app_name }}{% endblock %}
{% block content %}
-
Schedules
The night schedule repeats every month. Saturday lunch and Sunday lunch are separate rotations that never share an order.
+
{% for card in cards %}
@@ -10,19 +10,19 @@
{{ card.schedule.name }}
{{ card.kind_label }}{% if card.schedule.label_time %} · {{ card.schedule.label_time }}{% endif %}
-
Open schedule
+
Abrir escala
{% if card.kind == 'rotation' %}
-
Next dates
+
Próximas datas
{{ card.dates | join(' · ') }}
-
{{ card.rotation_names | length }} in the rotation.
+
{{ card.rotation_names | length }} pessoa(s) na rotação.
{% endif %}
{% else %}
-
No schedules are published yet.
+
Ainda não há escalas publicadas.
{% endfor %}
{% if not current_user %}
-
+
{% endif %}
-{% endblock %}
\ No newline at end of file
+{% endblock %}
diff --git a/app/templates/swaps.html b/app/templates/swaps.html
index ede5bae..6770e2e 100644
--- a/app/templates/swaps.html
+++ b/app/templates/swaps.html
@@ -1,7 +1,7 @@
{% extends "base.html" %}
{% block content %}
-
Change requests
People can volunteer for an open assignment or accept a request sent directly to them.
+
Pedidos de troca
Qualquer pessoa pode assumir um turno aberto ou aceitar um pedido enviado diretamente para si.
@@ -9,48 +9,48 @@
-
{{ swap.assignment.date.strftime('%A, %d %B %Y') }}
+
{{ swap.assignment.date|dia_longo }}
{{ swap.assignment.schedule.name }}
-
{{ swap.requester.name }} requested a change{% if swap.target_user %} with {{ swap.target_user.name }}{% else %} and opened it to anyone{% endif %}.
+
{{ swap.requester.name }} pediu uma troca{% if swap.target_user %} a {{ swap.target_user.name }}{% else %} e deixou-a aberta a toda a gente{% endif %}.
{% if swap.message %}
{{ swap.message }}
{% endif %}
- {% if swap.accepted_by %}
Accepted by {{ swap.accepted_by.name }}.
{% endif %}
+ {% if swap.accepted_by %}
Aceite por {{ swap.accepted_by.name }}.
{% endif %}
-
{{ swap.status.replace('_', ' ') }}
+
{{ swap.status|estado }}
{% if swap.status == 'open' and swap.requester_id != current_user.id and (swap.target_user_id is none or swap.target_user_id == current_user.id) %}
{% endif %}
{% if swap.status == 'open' and swap.target_user_id == current_user.id %}
{% endif %}
{% if swap.requester_id == current_user.id and swap.status in ['open', 'pending_approval'] %}
{% endif %}
{% if current_user.is_admin and swap.status == 'pending_approval' %}
{% endif %}
{% else %}
-
No change requests yet.
+
Ainda não há pedidos de troca.
{% endfor %}
{% endblock %}
diff --git a/app/web.py b/app/web.py
index 05cbe02..19361f4 100644
--- a/app/web.py
+++ b/app/web.py
@@ -20,6 +20,13 @@ from .models import (
SwapRequest,
User,
)
+from .i18n import (
+ day_numeric,
+ day_numeric_long,
+ day_short,
+ month_name,
+ weekday_names,
+)
from .notifications import send_email_notification, send_many
from .scheduling import assignments_by_date, ensure_month_assignments, month_bounds, rotation_user_for_date
from .security import hash_password, new_csrf_token, verify_password
@@ -41,14 +48,14 @@ def _current_user(request: Request, db: Session) -> User | None:
def _require_user(request: Request, db: Session) -> User:
user = _current_user(request, db)
if not user or not user.is_active:
- raise HTTPException(status_code=401, detail="Login required")
+ raise HTTPException(status_code=401, detail="É necessário iniciar sessão")
return user
def _require_admin(request: Request, db: Session) -> User:
user = _require_user(request, db)
if not user.is_admin:
- raise HTTPException(status_code=403, detail="Administrator access required")
+ raise HTTPException(status_code=403, detail="É necessária a permissão de administrador")
return user
@@ -63,7 +70,7 @@ def _csrf(request: Request) -> str:
def _check_csrf(request: Request, token: str) -> None:
expected = request.session.get("csrf")
if not expected or token != expected:
- raise HTTPException(status_code=400, detail="Invalid CSRF token")
+ raise HTTPException(status_code=400, detail="Token CSRF inválido")
def _flash(request: Request, message: str, level: str = "info") -> None:
@@ -86,14 +93,10 @@ def _parse_month(year: int | None, month: int | None) -> tuple[int, int]:
y = year or today.year
m = month or today.month
if m < 1 or m > 12 or y < 2000 or y > 2100:
- raise HTTPException(status_code=400, detail="Invalid month")
+ raise HTTPException(status_code=400, detail="Mês inválido")
return y, m
-def _weekday_labels(weekdays: set[int]) -> str:
- return ", ".join(calendar.day_name[d] for d in sorted(weekdays))
-
-
ALL_WEEKDAYS = frozenset(range(7))
@@ -103,7 +106,7 @@ def _next_dates(weekdays: set[int], count: int = 6) -> list[str]:
day = today
while len(labels) < count:
if day.weekday() in weekdays:
- labels.append(f"{day.strftime('%a')} {day.day} {day.strftime('%b')}")
+ labels.append(day_short(day))
day += timedelta(days=1)
return labels
@@ -112,12 +115,12 @@ def _schedule_card(schedule: Schedule, db: Session | None = None) -> dict:
weekdays = schedule.weekday_set
fixed = schedule.schedule_type != "rotation" and weekdays == ALL_WEEKDAYS
if fixed:
- kind_label = "Every day · repeats every month"
- weekday_label = "Every day"
+ kind_label = "Todos os dias · repete todos os meses"
+ weekday_label = "Todos os dias"
dates: list[str] = []
else:
- weekday_label = _weekday_labels(weekdays)
- kind_label = f"Rotating · {weekday_label}"
+ weekday_label = weekday_names(weekdays)
+ kind_label = f"Rotação · {weekday_label}"
dates = _next_dates(weekdays)
pattern: list[tuple[int, str]] = []
if fixed and db is not None:
@@ -146,7 +149,7 @@ def _schedule_card(schedule: Schedule, db: Session | None = None) -> dict:
def _schedule_groups(schedules: Sequence[Schedule], db: Session | None = None) -> list[dict]:
cards = [_schedule_card(schedule, db) for schedule in schedules]
# Every rotation is independent: Saturday and Sunday lunch never share an order.
- return sorted(cards, key=lambda card: (card["kind"] != "fixed", card["weekday_label"] != "Every day"))
+ return sorted(cards, key=lambda card: (card["kind"] != "fixed", card["weekday_label"] != "Todos os dias"))
def _active_schedules(db: Session) -> list[Schedule]:
@@ -173,7 +176,7 @@ def _all_schedules(db: Session) -> list[Schedule]:
def _get_schedule(db: Session, schedule_id: int) -> Schedule:
schedule = db.get(Schedule, schedule_id)
if not schedule:
- raise HTTPException(status_code=404, detail="Schedule not found")
+ raise HTTPException(status_code=404, detail="Escala não encontrada")
return schedule
@@ -216,10 +219,10 @@ def login(
_check_csrf(request, csrf_token)
user = db.scalar(select(User).where(func.lower(User.username) == username.strip().lower()))
if not user or not user.is_active or not user.can_login or not verify_password(password, user.password_hash):
- _flash(request, "Invalid username or password.", "error")
+ _flash(request, "Nome de utilizador ou palavra-passe inválidos.", "error")
return _redirect("/login")
request.session["user_id"] = user.id
- _flash(request, f"Welcome, {user.name}.")
+ _flash(request, f"Bem-vindo(a), {user.name}.")
return _redirect("/")
@@ -244,7 +247,7 @@ def public_schedules(request: Request, db: Session = Depends(get_db)):
def public_schedule(schedule_id: int, request: Request, db: Session = Depends(get_db)):
schedule = _get_schedule(db, schedule_id)
if not schedule.is_active:
- raise HTTPException(status_code=404, detail="Schedule not found")
+ raise HTTPException(status_code=404, detail="Escala não encontrada")
return request.app.state.templates.TemplateResponse(
request=request,
name="schedule.html",
@@ -287,7 +290,7 @@ def dashboard(
db,
year=year,
month=month,
- month_name=calendar.month_name[month],
+ month_name=month_name(month),
month_days=[(date(year, month, d), grouped.get(date(year, month, d), [])) for d in range(1, calendar.monthrange(year, month)[1] + 1)],
grouped=grouped,
my_assignment_ids=my_assignment_ids,
@@ -345,9 +348,9 @@ def create_swap(
.options(selectinload(Assignment.schedule), selectinload(Assignment.user))
)
if not assignment or assignment.user_id != user.id:
- raise HTTPException(status_code=403, detail="You can only offer your own assignment")
+ raise HTTPException(status_code=403, detail="Só pode oferecer o seu próprio turno")
if assignment.date < date.today():
- raise HTTPException(status_code=400, detail="Past assignments cannot be changed")
+ raise HTTPException(status_code=400, detail="Turnos passados não podem ser alterados")
existing = db.scalar(
select(SwapRequest.id).where(
@@ -356,14 +359,14 @@ def create_swap(
)
)
if existing:
- _flash(request, "There is already an active change request for this assignment.", "error")
+ _flash(request, "Já existe um pedido de troca ativo para este turno.", "error")
return _redirect("/swaps")
target = None
if target_user_id.strip():
target = db.get(User, int(target_user_id))
if not target or not target.is_active or target.id == user.id:
- raise HTTPException(status_code=400, detail="Invalid target user")
+ raise HTTPException(status_code=400, detail="Destinatário inválido")
swap = SwapRequest(
assignment_id=assignment.id,
@@ -375,12 +378,12 @@ def create_swap(
db.add(swap)
db.commit()
- subject = f"Bar rota change request: {assignment.date:%d %b} – {assignment.schedule.name}"
+ subject = f"Pedido de troca de turno: {day_short(assignment.date)} – {assignment.schedule.name}"
body = (
- f"{user.name} is asking for someone to take their {assignment.schedule.name} assignment "
- f"on {assignment.date:%A, %d %B %Y}.\n\n"
+ f"{user.name} pede que alguém assuma o turno de {assignment.schedule.name} "
+ f"a {day_numeric_long(assignment.date)}.\n\n"
f"{message.strip()}\n\n"
- f"Open the rota: {settings.normalized_base_url}/swaps"
+ f"Abrir a escala: {settings.normalized_base_url}/swaps"
)
if target:
send_email_notification(db, target, "swap_requested", subject, body)
@@ -390,7 +393,7 @@ def create_swap(
).all()
send_many(db, candidates, "swap_requested", subject, body)
- _flash(request, "Change request created.")
+ _flash(request, "Pedido de troca criado.")
return _redirect("/swaps")
@@ -409,15 +412,15 @@ def accept_swap(
.options(selectinload(SwapRequest.assignment).selectinload(Assignment.schedule), selectinload(SwapRequest.requester))
)
if not swap or swap.status != "open":
- raise HTTPException(status_code=400, detail="This request is no longer open")
+ raise HTTPException(status_code=400, detail="Este pedido já não está aberto")
if swap.requester_id == user.id:
- raise HTTPException(status_code=400, detail="You cannot accept your own request")
+ raise HTTPException(status_code=400, detail="Não pode aceitar o seu próprio pedido")
if swap.target_user_id is not None and swap.target_user_id != user.id:
- raise HTTPException(status_code=403, detail="This request is for another user")
+ raise HTTPException(status_code=403, detail="Este pedido é para outra pessoa")
if swap.assignment.user_id != swap.requester_id:
swap.status = "cancelled"
db.commit()
- raise HTTPException(status_code=409, detail="The assignment has already changed")
+ raise HTTPException(status_code=409, detail="O turno já foi alterado")
swap.accepted_by_id = user.id
if swap.assignment.schedule.requires_manager_approval:
@@ -428,18 +431,18 @@ def accept_swap(
db,
admins,
"swap_needs_approval",
- "Bar rota change needs approval",
- f"{user.name} accepted {swap.requester.name}'s {swap.assignment.schedule.name} assignment "
- f"for {swap.assignment.date:%d %B %Y}. Approve it at {settings.normalized_base_url}/swaps",
+ "Uma troca de turno precisa de aprovação",
+ f"{user.name} aceitou o turno de {swap.assignment.schedule.name} pedido por {swap.requester.name} "
+ f"para {day_numeric_long(swap.assignment.date)}. Aprove em {settings.normalized_base_url}/swaps",
)
send_email_notification(
db,
swap.requester,
"swap_accepted",
- "Your rota change was accepted",
- f"{user.name} accepted your request. It is now waiting for manager approval.",
+ "A sua troca de turno foi aceite",
+ f"{user.name} aceitou o seu pedido. Está agora à espera da aprovação da gestão.",
)
- _flash(request, "Accepted. Waiting for manager approval.")
+ _flash(request, "Aceite. A aguardar aprovação da gestão.")
else:
swap.assignment.user_id = user.id
swap.assignment.source = "swap"
@@ -449,17 +452,17 @@ def accept_swap(
db,
swap.requester,
"swap_approved",
- "Your rota change is confirmed",
- f"{user.name} will take {swap.assignment.schedule.name} on {swap.assignment.date:%d %B %Y}.",
+ "A sua troca de turno está confirmada",
+ f"{user.name} fica com o turno de {swap.assignment.schedule.name} a {day_numeric_long(swap.assignment.date)}.",
)
send_email_notification(
db,
user,
"swap_approved",
- "Rota assignment confirmed",
- f"You are now assigned to {swap.assignment.schedule.name} on {swap.assignment.date:%d %B %Y}.",
+ "Turno confirmado",
+ f"A partir de agora está atribuído ao turno de {swap.assignment.schedule.name} a {day_numeric_long(swap.assignment.date)}.",
)
- _flash(request, "Assignment transferred to you.")
+ _flash(request, "O turno foi transferido para si.")
return _redirect("/swaps")
@@ -478,19 +481,19 @@ def reject_swap(
.options(selectinload(SwapRequest.requester))
)
if not swap or swap.status != "open":
- raise HTTPException(status_code=400, detail="This request is no longer open")
+ raise HTTPException(status_code=400, detail="Este pedido já não está aberto")
if swap.target_user_id != user.id:
- raise HTTPException(status_code=403, detail="Only the requested user can reject this request")
+ raise HTTPException(status_code=403, detail="Só a pessoa destinatária pode recusar este pedido")
swap.status = "rejected"
db.commit()
send_email_notification(
db,
swap.requester,
"swap_rejected",
- "Rota change request declined",
- f"{user.name} declined your rota change request.",
+ "Pedido de troca recusado",
+ f"{user.name} recusou o seu pedido de troca.",
)
- _flash(request, "Request declined.")
+ _flash(request, "Pedido recusado.")
return _redirect("/swaps")
@@ -505,10 +508,10 @@ def cancel_swap(
user = _require_user(request, db)
swap = db.get(SwapRequest, swap_id)
if not swap or swap.requester_id != user.id or swap.status not in {"open", "pending_approval"}:
- raise HTTPException(status_code=403, detail="Cannot cancel this request")
+ raise HTTPException(status_code=403, detail="Não é possível cancelar este pedido")
swap.status = "cancelled"
db.commit()
- _flash(request, "Request cancelled.")
+ _flash(request, "Pedido cancelado.")
return _redirect("/swaps")
@@ -531,23 +534,23 @@ def approve_swap(
)
)
if not swap or swap.status != "pending_approval" or not swap.accepted_by:
- raise HTTPException(status_code=400, detail="Request is not ready for approval")
+ raise HTTPException(status_code=400, detail="O pedido ainda não está pronto a ser aprovado")
if swap.assignment.user_id != swap.requester_id:
swap.status = "cancelled"
db.commit()
- raise HTTPException(status_code=409, detail="The assignment has already changed")
+ raise HTTPException(status_code=409, detail="O turno já foi alterado")
swap.assignment.user_id = swap.accepted_by_id
swap.assignment.source = "swap"
swap.status = "approved"
db.commit()
- subject = "Rota change approved"
+ subject = "Troca de turno aprovada"
body = (
- f"The change for {swap.assignment.schedule.name} on {swap.assignment.date:%d %B %Y} was approved. "
- f"{swap.accepted_by.name} is now assigned."
+ f"A troca de {swap.assignment.schedule.name} a {day_numeric_long(swap.assignment.date)} foi aprovada. "
+ f"{swap.accepted_by.name} ficou com o turno."
)
send_many(db, [swap.requester, swap.accepted_by], "swap_approved", subject, body)
- _flash(request, "Change approved and schedule updated.")
+ _flash(request, "Troca aprovada e escala atualizada.")
return _redirect("/swaps")
@@ -566,12 +569,12 @@ def admin_reject_swap(
.options(selectinload(SwapRequest.requester), selectinload(SwapRequest.accepted_by))
)
if not swap or swap.status != "pending_approval":
- raise HTTPException(status_code=400, detail="Request is not awaiting approval")
+ raise HTTPException(status_code=400, detail="O pedido não está à espera de aprovação")
swap.status = "rejected"
db.commit()
users = [u for u in [swap.requester, swap.accepted_by] if u]
- send_many(db, users, "swap_rejected", "Rota change not approved", "The manager did not approve the requested rota change.")
- _flash(request, "Change rejected.")
+ send_many(db, users, "swap_rejected", "Troca de turno não aprovada", "A gestão não aprovou a troca de turno pedida.")
+ _flash(request, "Troca recusada.")
return _redirect("/swaps")
@@ -605,13 +608,13 @@ def admin_create_user(
email_value = email.strip().lower() or None
password_value = password or None
if bool(username_value) != bool(password_value):
- _flash(request, "Set both a username and a password, or leave both blank.", "error")
+ _flash(request, "Defina o nome de utilizador e a palavra-passe, ou deixe ambos vazios.", "error")
return _redirect("/admin/users")
if username_value and db.scalar(select(User.id).where(User.username == username_value)):
- _flash(request, "Username already exists.", "error")
+ _flash(request, "Esse nome de utilizador já existe.", "error")
return _redirect("/admin/users")
if email_value and db.scalar(select(User.id).where(User.email == email_value)):
- _flash(request, "Email address already exists.", "error")
+ _flash(request, "Esse endereço de e-mail já existe.", "error")
return _redirect("/admin/users")
try:
password_hash = hash_password(password_value) if password_value else None
@@ -631,7 +634,7 @@ def admin_create_user(
)
)
db.commit()
- _flash(request, "User created.")
+ _flash(request, "Pessoa criada.")
return _redirect("/admin/users")
@@ -654,24 +657,24 @@ def admin_update_user(
admin = _require_admin(request, db)
user = db.get(User, user_id)
if not user:
- raise HTTPException(status_code=404, detail="User not found")
+ raise HTTPException(status_code=404, detail="Pessoa não encontrada")
email_value = email.strip().lower() or None
duplicate = db.scalar(select(User.id).where(User.email == email_value, User.id != user.id)) if email_value else None
if duplicate:
- _flash(request, "That email address is already in use.", "error")
+ _flash(request, "Esse endereço de e-mail já está a ser usado.", "error")
return _redirect("/admin/users")
username_value = username.strip().lower() or None
password_value = new_password.strip() or None
if username_value:
if user.password_hash is None and password_value is None:
- _flash(request, "Set a new password to give this person a login.", "error")
+ _flash(request, "Defina uma palavra-passe para esta pessoa poder iniciar sessão.", "error")
return _redirect("/admin/users")
if db.scalar(select(User.id).where(User.username == username_value, User.id != user.id)):
- _flash(request, "That username is already in use.", "error")
+ _flash(request, "Esse nome de utilizador já está a ser usado.", "error")
return _redirect("/admin/users")
elif password_value and user.id == admin.id:
- _flash(request, "Add a username before setting a password for your own account.", "error")
+ _flash(request, "Defina um nome de utilizador antes de definir a palavra-passe da sua conta.", "error")
return _redirect("/admin/users")
try:
@@ -693,7 +696,7 @@ def admin_update_user(
if user.id != admin.id:
user.is_admin = bool(is_admin)
db.commit()
- _flash(request, "User updated.")
+ _flash(request, "Pessoa atualizada.")
return _redirect("/admin/users")
@@ -741,7 +744,7 @@ def admin_schedule(
pattern=_pattern_map(db, schedule),
year=year,
month=month,
- month_name=calendar.month_name[month],
+ month_name=month_name(month),
prev=prev,
nxt=nxt,
generate_after=date(year, month, 1) - timedelta(days=1),
@@ -768,7 +771,7 @@ async def admin_schedule_pattern(
_check_csrf(request, str(form.get("csrf_token", "")))
schedule = _get_schedule(db, schedule_id)
if schedule.schedule_type == "rotation":
- raise HTTPException(status_code=400, detail="Rotations use their own order, not a month pattern")
+ raise HTTPException(status_code=400, detail="As rotações usam a sua própria ordem, não um padrão mensal")
users_by_id = {u.id for u in db.scalars(select(User).where(User.is_active.is_(True))).all()}
existing = {
@@ -796,8 +799,9 @@ async def admin_schedule_pattern(
touched = _apply_pattern_to_open_rows(db, schedule)
_flash(
request,
- f"Saved the repeating night pattern ({saved} change(s)). "
- f"Updated {touched} unassigned night(s) in this month and the next; nights already assigned were left alone.",
+ f"Padrão de noites guardado ({saved} alteração(ões)). "
+ f"Foram atualizados {touched} turno(s) sem atribuição neste mês e no próximo; "
+ f"as noites já atribuídas foram mantidas.",
)
return _redirect(f"/admin/schedules/{schedule.id}")
@@ -843,11 +847,11 @@ def admin_schedule_settings(
_require_admin(request, db)
schedule = db.get(Schedule, schedule_id)
if not schedule:
- raise HTTPException(status_code=404, detail="Schedule not found")
+ raise HTTPException(status_code=404, detail="Escala não encontrada")
schedule.requires_manager_approval = bool(requires_manager_approval)
schedule.is_active = bool(is_active)
db.commit()
- _flash(request, "Schedule settings saved.")
+ _flash(request, "Definições da escala guardadas.")
return _redirect(f"/admin/schedules/{schedule.id}")
@@ -864,7 +868,7 @@ def admin_rotation_add(
schedule = db.get(Schedule, schedule_id)
user = db.get(User, user_id)
if not schedule or schedule.schedule_type != "rotation" or not user or not user.is_active:
- raise HTTPException(status_code=400, detail="Invalid rotation member")
+ raise HTTPException(status_code=400, detail="Membro da rotação inválido")
exists = db.scalar(
select(RotationMember.id).where(
RotationMember.schedule_id == schedule.id,
@@ -872,14 +876,14 @@ def admin_rotation_add(
)
)
if exists:
- _flash(request, "That person is already in this rotation.", "error")
+ _flash(request, "Essa pessoa já está nesta rotação.", "error")
return _redirect(f"/admin/schedules/{schedule.id}#rotation-order")
max_position = db.scalar(
select(func.max(RotationMember.position)).where(RotationMember.schedule_id == schedule.id)
) or 0
db.add(RotationMember(schedule_id=schedule.id, user_id=user.id, position=max_position + 1))
db.commit()
- _flash(request, "Rotation member added.")
+ _flash(request, "Membro adicionado à rotação.")
return _redirect(f"/admin/schedules/{schedule.id}#rotation-order")
@@ -894,7 +898,7 @@ def admin_rotation_remove(
_require_admin(request, db)
member = db.get(RotationMember, member_id)
if not member:
- raise HTTPException(status_code=404, detail="Rotation member not found")
+ raise HTTPException(status_code=404, detail="Membro da rotação não encontrado")
schedule_id = member.schedule_id
db.delete(member)
db.commit()
@@ -904,7 +908,7 @@ def admin_rotation_remove(
for idx, row in enumerate(members, start=1):
row.position = idx
db.commit()
- _flash(request, "Rotation member removed.")
+ _flash(request, "Membro removido da rotação.")
return _redirect(f"/admin/schedules/{schedule_id}")
@@ -920,7 +924,7 @@ def admin_rotation_move(
_require_admin(request, db)
member = db.get(RotationMember, member_id)
if not member or direction not in {"up", "down"}:
- raise HTTPException(status_code=400, detail="Invalid move")
+ raise HTTPException(status_code=400, detail="Movimento inválido")
target_position = member.position - 1 if direction == "up" else member.position + 1
other = db.scalar(
select(RotationMember).where(
@@ -1015,7 +1019,7 @@ async def admin_schedule_assignments(
month = int(form.get("month", date.today().month))
assignments = [row for row in _month_assignments(db, year, month) if row.schedule_id == schedule.id]
changed = _save_assignments(db, assignments, form)
- _flash(request, f"Saved {changed} assignment change(s).")
+ _flash(request, f"Foram guardadas {changed} alteração(ões) de turno.")
return _redirect(f"/admin/schedules/{schedule.id}?year={year}&month={month}")
@@ -1088,11 +1092,12 @@ def admin_apply_rotation(
_check_csrf(request, csrf_token)
schedule = _get_schedule(db, schedule_id)
if schedule.schedule_type != "rotation":
- raise HTTPException(status_code=400, detail="This schedule does not use a rotation")
+ raise HTTPException(status_code=400, detail="Esta escala não usa rotação")
year, month = _parse_month(year, month)
created, changed = _generate_rotation_range(db, schedule, *month_bounds(year, month))
- _flash(request, f"Applied rotation for {calendar.month_name[month]} {year}: "
- f"created {created} shift(s), updated {changed} assignment(s). Manual assignments and swaps were kept.")
+ _flash(request, f"Rotação aplicada em {month_name(month)} de {year}: "
+ f"{created} turno(s) criado(s), {changed} turno(s) atualizado(s). "
+ f"As atribuições manuais e as trocas foram mantidas.")
return _redirect(f"/admin/schedules/{schedule.id}?year={year}&month={month}")
@@ -1109,13 +1114,14 @@ def admin_generate_after(
_check_csrf(request, csrf_token)
schedule = _get_schedule(db, schedule_id)
if schedule.schedule_type != "rotation":
- raise HTTPException(status_code=400, detail="This schedule does not use a rotation")
+ raise HTTPException(status_code=400, detail="Esta escala não usa rotação")
if after_date < date(1999, 12, 31) or through_date > date(2100, 12, 31) or through_date <= after_date:
- raise HTTPException(status_code=400, detail="Choose an end date after the reference date, within 2000–2100")
+ raise HTTPException(status_code=400, detail="Escolha uma data final posterior à data de referência, entre 2000 e 2100")
first = after_date + timedelta(days=1)
created, changed = _generate_rotation_range(db, schedule, first, through_date)
- _flash(request, f"Generated shifts after {after_date:%d %b %Y} through {through_date:%d %b %Y}: "
- f"created {created} shift(s), updated {changed} assignment(s). Manual assignments and swaps were kept.")
+ _flash(request, f"Turnos gerados de {day_numeric(after_date)} a {day_numeric(through_date)}: "
+ f"{created} turno(s) criado(s), {changed} turno(s) atualizado(s). "
+ f"As atribuições manuais e as trocas foram mantidas.")
return _redirect(f"/admin/schedules/{schedule.id}?year={first.year}&month={first.month}")
@@ -1132,14 +1138,14 @@ def admin_assignment_regenerate(
_check_csrf(request, csrf_token)
schedule = _get_schedule(db, schedule_id)
if schedule.schedule_type != "rotation":
- raise HTTPException(status_code=400, detail="This schedule does not use a rotation")
+ raise HTTPException(status_code=400, detail="Esta escala não usa rotação")
assignment = db.get(Assignment, assignment_id)
if assignment is None or assignment.schedule_id != schedule.id:
- raise HTTPException(status_code=404, detail="Assignment not found")
+ raise HTTPException(status_code=404, detail="Turno não encontrado")
if assignment.date.weekday() not in schedule.weekday_set:
- raise HTTPException(status_code=400, detail="This date does not match the schedule")
+ raise HTTPException(status_code=400, detail="Esta data não corresponde à escala")
_apply_rotation_to_rows(db, schedule, [assignment])
- _flash(request, "Assignment regenerated using the next person after the previous shift's assignee.")
+ _flash(request, "Turno recalculado com a pessoa a seguir à responsável pelo turno anterior.")
return _redirect(f"/admin/schedules/{schedule.id}?year={assignment.date.year}&month={assignment.date.month}")
diff --git a/docs/DOMAIN.md b/docs/DOMAIN.md
index 6e0448d..1990943 100644
--- a/docs/DOMAIN.md
+++ b/docs/DOMAIN.md
@@ -8,7 +8,9 @@ This distinction is intentional: editing a rotation must not retroactively chang
## Seeded schedules
-### Night
+Seeded names are Portuguese (`Noite`, `Almoço de sábado`, `Almoço de domingo`); the slugs stay `night`, `saturday-lunch` and `sunday-lunch`.
+
+### Night (`Noite`)
- Exists every day (`Monday` through `Sunday`).
- Type: `fixed`.
@@ -17,14 +19,14 @@ This distinction is intentional: editing a rotation must not retroactively chang
- There is no per-month configuration for Night: the same pattern is used every month.
- Existing assignments are never rewritten by a pattern change; they keep the person they already had.
-### Saturday Lunch
+### Saturday Lunch (`Almoço de sábado`)
- Saturdays only.
- Type: `rotation`.
- Has its own ordered member list.
- Continues after the previous assigned person's position in the rotation, including across month boundaries. The anchor date is the fallback when there is no usable previous assignee.
-### Sunday Lunch
+### Sunday Lunch (`Almoço de domingo`)
- Sundays only.
- Type: `rotation`.
diff --git a/tests/test_admin_schedule_assignments.py b/tests/test_admin_schedule_assignments.py
index dc9dda9..c0cbb5a 100644
--- a/tests/test_admin_schedule_assignments.py
+++ b/tests/test_admin_schedule_assignments.py
@@ -44,16 +44,16 @@ def client(db):
def seed(db):
night = Schedule(
- name="Night",
+ name="Noite",
slug="night",
schedule_type="fixed",
weekdays="0,1,2,3,4,5,6",
- label_time="Night",
+ label_time="Noite",
requires_manager_approval=True,
is_active=True,
)
sat = Schedule(
- name="Saturday Lunch",
+ name="Almoço de sábado",
slug="saturday-lunch",
schedule_type="rotation",
weekdays="5",
@@ -63,7 +63,7 @@ def seed(db):
rotation_anchor_date=date(2026, 1, 3),
)
sun = Schedule(
- name="Sunday Lunch",
+ name="Almoço de domingo",
slug="sunday-lunch",
schedule_type="rotation",
weekdays="6",
@@ -120,8 +120,8 @@ def test_night_page_is_a_single_repeating_pattern_with_no_month_picker(client, d
for day in range(1, 32):
assert f'name="day_{day}"' in page
- assert "Save pattern" in page
- assert "Repeating every month" in page
+ assert "Guardar padrão" in page
+ assert "Repete todos os meses" in page
assert "Previous" not in page
assert "Next →" not in page
assert f"year={YEAR}" not in page
@@ -249,8 +249,8 @@ def test_saturday_page_only_shows_saturdays(client, db):
page = client.get(f"/admin/schedules/{sat.id}?year={YEAR}&month={MONTH}").text
assert page.count("assignment_") == len([d for d in range(1, 32) if date(2026, 10, d).weekday() == 5])
- assert "Sunday Lunch" in page # listed under other schedules
- assert "Save October" in page
+ assert "Almoço de domingo" in page # listed under other schedules
+ assert "Guardar Outubro" in page
def test_month_page_redirects_to_the_schedules_hub(client, db):
@@ -404,16 +404,16 @@ def test_rotation_controls_render_regenerate_for_every_row_as_separate_forms(cli
swapped.source = "swap"
db.commit()
page = client.get(f"/admin/schedules/{sat.id}?year={YEAR}&month={MONTH}").text
- assert "Apply rotation to October" in page
- assert page.count(">Regenerate") == 5
+ assert "Aplicar rotação em Outubro" in page
+ assert page.count(">Recalcular") == 5
assert f'form="regenerate-{row.id}"' in page
assert f'form="regenerate-{swapped.id}"' in page
assert f'action="/admin/schedules/{sat.id}/assignments/{row.id}/regenerate"' in page
- assert page.index(f'id="regenerate-{row.id}"') > page.index("Save October")
- assert "Generate after date" in page
+ assert page.index(f'id="regenerate-{row.id}"') > page.index("Guardar Outubro")
+ assert "Gerar depois da data" in page
assert 'name="after_date" value="2026-09-30"' in page
assert 'name="through_date" value="2026-10-31"' in page
- assert "Apply rotation" not in client.get(f"/admin/schedules/{night.id}").text
+ assert "Aplicar rotação" not in client.get(f"/admin/schedules/{night.id}").text
def test_rotation_actions_reject_invalid_schedule_row_and_month(client, db):
diff --git a/tests/test_bootstrap.py b/tests/test_bootstrap.py
index 410e728..8427baa 100644
--- a/tests/test_bootstrap.py
+++ b/tests/test_bootstrap.py
@@ -14,3 +14,17 @@ def test_bootstrap_creates_three_expected_schedules(monkeypatch):
ensure_initial_data(db)
slugs = set(db.scalars(select(Schedule.slug)).all())
assert {"night", "saturday-lunch", "sunday-lunch"}.issubset(slugs)
+
+
+def test_seeded_schedules_are_named_in_portuguese(monkeypatch):
+ engine = create_engine("sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool)
+ Base.metadata.create_all(engine)
+ with Session(engine) as db:
+ ensure_initial_data(db)
+ names = {
+ slug: name
+ for slug, name in db.execute(select(Schedule.slug, Schedule.name)).all()
+ }
+ assert names["night"] == "Noite"
+ assert names["saturday-lunch"] == "Almoço de sábado"
+ assert names["sunday-lunch"] == "Almoço de domingo"
diff --git a/tests/test_i18n.py b/tests/test_i18n.py
new file mode 100644
index 0000000..e756631
--- /dev/null
+++ b/tests/test_i18n.py
@@ -0,0 +1,49 @@
+from datetime import date, datetime
+
+from app.i18n import (
+ MONTHS,
+ day_long,
+ day_numeric,
+ day_numeric_long,
+ day_short,
+ event_type_label,
+ moment,
+ month_name,
+ notification_status_label,
+ source_label,
+ swap_status_label,
+ weekday_name,
+ weekday_names,
+)
+
+
+def test_month_and_weekday_names_are_european_portuguese():
+ assert month_name(1) == "Janeiro"
+ assert month_name(8) == "Agosto"
+ assert MONTHS[0] == "Janeiro"
+ assert weekday_name(5) == "Sábado"
+ assert weekday_name(0) == "Segunda-feira"
+ assert weekday_name(5, short=True) == "Sáb"
+ assert weekday_names({5, 6}) == "Sábado e Domingo"
+ assert weekday_names({0, 1, 2, 3, 4, 5, 6}) == (
+ "Segunda-feira, Terça-feira, Quarta-feira, Quinta-feira, Sexta-feira, Sábado e Domingo"
+ )
+
+
+def test_dates_are_formatted_the_portuguese_way():
+ saturday = date(2026, 1, 3)
+ assert day_short(saturday) == "sáb 03 jan"
+ assert day_long(saturday) == "Sábado, 3 de janeiro de 2026"
+ assert day_numeric(saturday) == "03/01/2026"
+ assert day_numeric_long(saturday) == "3 de janeiro de 2026"
+ assert moment(datetime(2026, 1, 3, 21, 45)) == "03/01/2026 21:45"
+
+
+def test_stored_enum_values_are_translated_for_display():
+ assert source_label("generated") == "automático"
+ assert source_label("manual") == "manual"
+ assert source_label("swap") == "troca"
+ assert source_label("something-new") == "something-new"
+ assert swap_status_label("pending_approval") == "aguarda aprovação"
+ assert notification_status_label("skipped") == "ignorado"
+ assert event_type_label("shift_reminder") == "Lembrete de turno"
diff --git a/tests/test_public_schedules.py b/tests/test_public_schedules.py
index 55026a7..a89c8aa 100644
--- a/tests/test_public_schedules.py
+++ b/tests/test_public_schedules.py
@@ -9,6 +9,7 @@ from sqlalchemy.pool import StaticPool
from app.database import Base, get_db
from app.main import app
+from app.i18n import day_short, month_name, weekday_name
from app.models import RotationMember, Schedule, User
from app.security import hash_password
@@ -86,9 +87,9 @@ def login(client: TestClient, username: str, password: str) -> str:
def seed_schedules(db):
- night = add_schedule(db, name="Night", slug="night", schedule_type="fixed", weekdays="0,1,2,3,4,5,6", label_time="Night")
- sat = add_schedule(db, name="Saturday Lunch", slug="sat")
- sun = add_schedule(db, name="Sunday Lunch", slug="sun", weekdays="6")
+ night = add_schedule(db, name="Noite", slug="night", schedule_type="fixed", weekdays="0,1,2,3,4,5,6", label_time="Noite")
+ sat = add_schedule(db, name="Almoço de sábado", slug="sat")
+ sun = add_schedule(db, name="Almoço de domingo", slug="sun", weekdays="6")
ana = add_person(db, "Ana")
bruno = add_person(db, "Bruno")
add_rotation_member(db, sat, ana, 0)
@@ -104,8 +105,8 @@ def test_public_schedules_page_is_open_to_anonymous_visitors(client, db):
response = client.get("/schedules", follow_redirects=False)
assert response.status_code == 200
- assert "Saturday Lunch" in response.text
- assert "Sunday Lunch" in response.text
+ assert "Almoço de sábado" in response.text
+ assert "Almoço de domingo" in response.text
def test_rota_is_the_landing_page_for_signed_out_visitors(client, db):
@@ -115,9 +116,9 @@ def test_rota_is_the_landing_page_for_signed_out_visitors(client, db):
assert ">Rota" in page
assert '
' in page
+ assert month_name(today.month) in page
+ assert day_short(today) not in page # the rota shows the weekday, not the full date
+ assert f'{weekday_name(today.weekday(), short=True)}' in page
+ assert "Sem atribuição" in page
+ assert "Escalas" in page
+
+
def test_admin_schedules_page_separates_the_three_schedule_types(client, db):
night, sat, sun = seed_schedules(db)
db.add(
@@ -271,9 +285,9 @@ def test_admin_schedules_page_separates_the_three_schedule_types(client, db):
assert f'href="/admin/schedules/{schedule.id}"' in hub
assert "weekdays" not in hub
- assert "Rotation order" not in client.get(f"/admin/schedules/{night.id}").text
- assert "Rotation order" in client.get(f"/admin/schedules/{sat.id}").text
- assert "Rotation order" in client.get(f"/admin/schedules/{sun.id}").text
+ assert "Ordem da rotação" not in client.get(f"/admin/schedules/{night.id}").text
+ assert "Ordem da rotação" in client.get(f"/admin/schedules/{sat.id}").text
+ assert "Ordem da rotação" in client.get(f"/admin/schedules/{sun.id}").text
def test_rotation_edits_return_to_the_schedule_page(client, db):
diff --git a/tests/test_users.py b/tests/test_users.py
index 0146994..60016dd 100644
--- a/tests/test_users.py
+++ b/tests/test_users.py
@@ -86,7 +86,7 @@ def test_person_can_be_created_without_login(client, db, admin):
login(client, "admin", "admin-password")
page = add_person(client, name="Rota Only")
assert "Rota Only" in page
- assert "no login" in page
+ assert "sem login" in page
assert usernames(db) == ["admin", None]
assert db.scalar(select(User).where(User.name == "Rota Only")).can_login is False
@@ -95,7 +95,7 @@ def test_person_can_be_created_without_login(client, db, admin):
def test_username_and_password_must_be_set_together(client, db, admin, fields):
login(client, "admin", "admin-password")
page = add_person(client, name="Halfway", **fields)
- assert "Set both a username and a password" in page
+ assert "Defina o nome de utilizador e a palavra-passe" in page
assert usernames(db) == ["admin"]
assert db.scalar(select(User).where(User.name == "Halfway")) is None
@@ -111,14 +111,14 @@ def test_person_without_credentials_cannot_sign_in(client, db, admin):
)
db.commit()
- assert "Invalid username or password" in login(client, " ", "a-secure-password")
+ assert "Nome de utilizador ou palavra-passe inválidos" in login(client, " ", "a-secure-password")
assert client.get("/swaps", follow_redirects=False).status_code == 401
def test_username_without_password_cannot_sign_in(client, db, admin):
db.add(User(name="Rota Only", username="rotarota", password_hash=None, is_active=True))
db.commit()
- assert "Invalid username or password" in login(client, "rotarota", "a-secure-password")
+ assert "Nome de utilizador ou palavra-passe inválidos" in login(client, "rotarota", "a-secure-password")
def test_admin_can_give_and_remove_a_login(client, db, admin):
@@ -127,7 +127,7 @@ def test_admin_can_give_and_remove_a_login(client, db, admin):
person = db.scalar(select(User).where(User.name == "Rota Only"))
page = update_person(client, person.id, name="Rota Only", username="rotarota")
- assert "Set a new password to give this person a login." in page
+ assert "Defina uma palavra-passe para esta pessoa poder iniciar sessão." in page
assert db.get(User, person.id).can_login is False
update_person(
@@ -140,11 +140,11 @@ def test_admin_can_give_and_remove_a_login(client, db, admin):
assert db.get(User, person.id).can_login is True
client.post("/logout", data={"csrf_token": csrf(client, "/")})
- assert "Welcome, Rota Only." in login(client, "rotarota", "a-secure-password")
+ assert "Bem-vindo(a), Rota Only." in login(client, "rotarota", "a-secure-password")
login(client, "admin", "admin-password")
page = update_person(client, person.id, name="Rota Only")
- assert "User updated." in page
+ assert "Pessoa atualizada." in page
assert db.get(User, person.id).can_login is False
@@ -156,14 +156,14 @@ def test_username_must_stay_unique(client, db, admin):
page = update_person(
client, person.id, name="Rota Only", username="admin", new_password="a-secure-password"
)
- assert "That username is already in use." in page
+ assert "Esse nome de utilizador já está a ser usado." in page
assert db.get(User, person.id).can_login is False
def test_admin_cannot_remove_their_own_login(client, db, admin):
login(client, "admin", "admin-password")
page = update_person(client, admin.id, name="Admin", new_password="another-password")
- assert "Add a username before setting a password for your own account." in page
+ assert "Defina um nome de utilizador antes de definir a palavra-passe da sua conta." in page
assert db.get(User, admin.id).can_login is True
@@ -173,6 +173,6 @@ def test_signed_in_home_is_the_rota_and_nav_has_no_rota_link(client, db, admin):
nav = client.get("/admin/users").text
assert 'Rota' not in nav
- assert '
Schedules' in nav
- assert '
Changes' in nav
+ assert '
Escalas' in nav
+ assert '
Trocas' in nav
assert 'href="/"' in nav # the brand stays the home link for signed-in members