diff --git a/app/i18n.py b/app/i18n.py index cd5db1d..25ec4a1 100644 --- a/app/i18n.py +++ b/app/i18n.py @@ -62,6 +62,7 @@ SWAP_STATUS_LABELS = { "pending_approval": "aguarda aprovação", "approved": "aprovado", "rejected": "recusado", + "reverted": "revertida", "cancelled": "cancelado", } @@ -77,6 +78,7 @@ EVENT_TYPE_LABELS = { "swap_accepted": "Troca aceite", "swap_approved": "Troca aprovada", "swap_rejected": "Troca recusada", + "swap_reverted": "Troca revertida", "assignment_updated": "Turno atribuído", "assignment_changed": "Turno retirado", "shift_reminder": "Lembrete de turno", diff --git a/app/models.py b/app/models.py index bc95d33..7a9f0c6 100644 --- a/app/models.py +++ b/app/models.py @@ -114,10 +114,16 @@ class Assignment(Base): class SwapRequest(Base): + """A swap is one shift for one shift: `assignment_id` goes to the target and + `target_assignment_id` comes back to the requester.""" + __tablename__ = "swap_requests" id: Mapped[int] = mapped_column(Integer, primary_key=True) assignment_id: Mapped[int] = mapped_column(ForeignKey("assignments.id", ondelete="CASCADE"), nullable=False) + target_assignment_id: Mapped[int | None] = mapped_column( + ForeignKey("assignments.id", ondelete="SET NULL"), nullable=True + ) requester_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"), nullable=False) target_user_id: Mapped[int | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL"), nullable=True) accepted_by_id: Mapped[int | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL"), nullable=True) @@ -126,7 +132,8 @@ class SwapRequest(Base): created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) - assignment: Mapped[Assignment] = relationship() + assignment: Mapped[Assignment] = relationship(foreign_keys=[assignment_id]) + target_assignment: Mapped[Assignment | None] = relationship(foreign_keys=[target_assignment_id]) requester: Mapped[User] = relationship(foreign_keys=[requester_id]) target_user: Mapped[User | None] = relationship(foreign_keys=[target_user_id]) accepted_by: Mapped[User | None] = relationship(foreign_keys=[accepted_by_id]) diff --git a/app/static/app.css b/app/static/app.css index 19855ea..172036f 100644 --- a/app/static/app.css +++ b/app/static/app.css @@ -41,6 +41,7 @@ a{color:var(--brand-dark)} .gap-lg{gap:14px} .top-space{margin-top:18px} .row{display:flex;align-items:center} +.row.end{justify-content:flex-end} .between{justify-content:space-between} .wrap{flex-wrap:wrap} .gap{gap:14px} diff --git a/app/templates/admin_assign.html b/app/templates/admin_assign.html new file mode 100644 index 0000000..b24010a --- /dev/null +++ b/app/templates/admin_assign.html @@ -0,0 +1,57 @@ +{% extends "base.html" %} +{% block title %}Atribuição por dia · {{ settings.app_name }}{% endblock %} +{% block content %} +
+
+

Escalas

+

Atribuição por dia

+

Escolha o dia e a pessoa que fica com cada turno. É uma atribuição direta, não uma troca.

+
+
+ +
+
+ +
+ ← Dia anterior + Hoje + Dia seguinte → +
+ +
+
+

{{ day|dia_longo }}

+ {% for row in shifts %} +
+ + +
+ {{ row.schedule.name }} + {% if row.schedule.label_time %} · {{ row.schedule.label_time }}{% endif %} +
+ {% if row.assignment.user %} + Agora: {{ row.assignment.user.name }} ({{ row.assignment.source|origem }}) + {% else %} + Agora: sem atribuição + {% endif %} +
+
+
+ + +
+
+ {% else %} +
Este dia não tem turnos.
+ {% endfor %} +
+

Atribuir aqui fecha qualquer pedido de troca em aberto sobre esse turno e avisa a nova pessoa e a anterior.

+

«Automático» repõe a pessoa que a escala dá a este dia — a ordem da rotação ou o padrão de noites — e volta a marcar o turno como automático.

+
+{% endblock %} \ No newline at end of file diff --git a/app/templates/admin_schedule.html b/app/templates/admin_schedule.html index d4e3d49..18f5813 100644 --- a/app/templates/admin_schedule.html +++ b/app/templates/admin_schedule.html @@ -107,6 +107,7 @@
{{ item.assignment.date|dia }} · {{ item.assignment.schedule.name }} — pedido por {{ item.requester.name }} + {% if item.target_assignment %}em troca de {{ item.target_assignment.date|dia }}{% endif %} {% if item.target_user %}para {{ item.target_user.name }}{% endif %} {% if item.accepted_by %}, aceite por {{ item.accepted_by.name }}{% endif %} {% if item.message %}
“{{ item.message }}”{% endif %} @@ -116,7 +117,7 @@ + {% if admin_request.accepted_by %} + + {% else %} + + + {% endif %} + +
+ + +
{% else %} -
- Pedir troca -
- - - - -
-
+ Troca pedida {% endif %}
{% endif %} diff --git a/app/templates/swap_new.html b/app/templates/swap_new.html new file mode 100644 index 0000000..00f58cc --- /dev/null +++ b/app/templates/swap_new.html @@ -0,0 +1,45 @@ +{% extends "base.html" %} +{% block title %}Pedir troca · {{ settings.app_name }}{% endblock %} +{% block content %} +
+
+

Trocas

+

Pedir troca

+

Uma troca é entre duas pessoas da mesma escala: cada uma fica com o turno da outra.

+
+
+ ← Anterior + Seguinte → +
+
+ +
+{% for group in groups %} +
+
+

{{ group.schedule.name }}

+ {{ month_name }} {{ year }} +
+
+ + + + +
+
+
+{% else %} +
Não há turnos disponíveis para {{ month_name|lower }} de {{ year }}.
+{% endfor %} +
+{% endblock %} \ No newline at end of file diff --git a/app/templates/swaps.html b/app/templates/swaps.html index 0605b0b..5a90b8c 100644 --- a/app/templates/swaps.html +++ b/app/templates/swaps.html @@ -11,7 +11,9 @@
{{ swap.assignment.date|dia_longo }}

{{ swap.assignment.schedule.name }}

-

{{ 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 %}.

+

{{ swap.requester.name }} passa o turno de {{ swap.assignment.date|dia }} + {%- if swap.target_assignment %} e fica com o de {{ swap.target_assignment.date|dia }}{% endif %} + {%- if swap.target_user %} ({{ swap.target_user.name }}){% endif %}.

{% if swap.message %}

{{ swap.message }}

{% endif %} {% if swap.accepted_by %}

Aceite por {{ swap.accepted_by.name }}.

{% endif %}
@@ -19,16 +21,19 @@
- {% 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) %} + {% set eligible = swap.requester_id != current_user.id and (swap.target_user_id is none or swap.target_user_id == current_user.id) %} + {% set can_accept = swap.status == 'open' and eligible %} + {% set can_decline = swap.status in ['open', 'pending_approval'] and (current_user.is_admin or (swap.status == 'open' and eligible)) %} + {% if can_accept %}
{% endif %} - {% if swap.status == 'open' and swap.target_user_id == current_user.id %} -
+ {% if can_decline %} + - +
{% endif %} {% if swap.requester_id == current_user.id and swap.status in ['open', 'pending_approval'] %} @@ -37,14 +42,21 @@ {% endif %} - {% if current_user.is_admin and swap.status == 'pending_approval' %} -
+ {% if current_user.is_admin and swap.status == 'approved' and swap.target_assignment %} + - +
-
+ {% endif %} + {% if current_user.is_admin and swap.status in ['open', 'pending_approval'] %} + - + {% if swap.accepted_by %} + + {% else %} + + + {% endif %}
{% endif %}
diff --git a/app/web.py b/app/web.py index 0d43ab0..09fb370 100644 --- a/app/web.py +++ b/app/web.py @@ -272,6 +272,7 @@ def dashboard( my_assignment_ids = {a.id for a in assignments if user and a.user_id == user.id} open_swap_assignment_ids = set() + admin_requests: dict[int, SwapRequest] = {} if user: open_swap_assignment_ids = set( db.scalars( @@ -281,7 +282,27 @@ def dashboard( ) ).all() ) + if user and user.is_admin: + # Administrators can settle any request on this month's rota. + admin_requests = { + request.assignment_id: request + for request in db.scalars( + select(SwapRequest) + .where( + SwapRequest.assignment_id.in_([a.id for a in assignments]), + SwapRequest.status.in_(["open", "pending_approval"]), + ) + .options( + selectinload(SwapRequest.assignment).selectinload(Assignment.schedule), + selectinload(SwapRequest.target_assignment).selectinload(Assignment.schedule), + selectinload(SwapRequest.requester), + selectinload(SwapRequest.accepted_by), + ) + .order_by(SwapRequest.created_at) + ).all() + } + today = date.today() return request.app.state.templates.TemplateResponse( request=request, name="dashboard.html", @@ -295,10 +316,13 @@ def dashboard( grouped=grouped, my_assignment_ids=my_assignment_ids, open_swap_assignment_ids=open_swap_assignment_ids, + admin_requests=admin_requests, prev=prev, nxt=nxt, - active_users=db.scalars(select(User).where(User.is_active.is_(True)).order_by(User.name)).all(), - today=date.today(), + schedule_people=_schedule_people_map( + db, {request.assignment.schedule_id for request in admin_requests.values()} + ), + today=today, ), ) @@ -327,76 +351,319 @@ def swaps_page(request: Request, db: Session = Depends(get_db)): return request.app.state.templates.TemplateResponse( request=request, name="swaps.html", - context=_context(request, db, swaps=swaps, today=date.today()), + context=_context( + request, + db, + swaps=swaps, + today=date.today(), + schedule_people=_schedule_people_map( + db, {swap.assignment.schedule_id for swap in swaps} + ), + ), ) +def _schedule_people_ids(db: Session, schedule_id: int) -> set[int]: + """Everyone who works this schedule: its rotation, its pattern or one of its shifts. + + A swap is always one person for one person of the same schedule, so these are + the only people who can be asked or chosen. + """ + ids: set[int] = set() + ids.update( + db.scalars( + select(Assignment.user_id).where( + Assignment.schedule_id == schedule_id, Assignment.user_id.is_not(None) + ) + ).all() + ) + ids.update( + db.scalars( + select(MonthlyPattern.user_id).where( + MonthlyPattern.schedule_id == schedule_id, MonthlyPattern.user_id.is_not(None) + ) + ).all() + ) + ids.update( + db.scalars(select(RotationMember.user_id).where(RotationMember.schedule_id == schedule_id)).all() + ) + return {i for i in ids if i is not None} + + +def _schedule_people(db: Session, schedule_id: int) -> list[User]: + ids = _schedule_people_ids(db, schedule_id) + if not ids: + return [] + return list( + db.scalars( + select(User).where(User.id.in_(ids), User.is_active.is_(True)).order_by(User.name) + ).all() + ) + + +def _schedule_people_map(db: Session, schedule_ids: set[int]) -> dict[int, list[User]]: + """Active people per schedule, for the swap forms: a swap stays inside one schedule.""" + return {schedule_id: _schedule_people(db, schedule_id) for schedule_id in schedule_ids} + + +def _active_request(db: Session, assignment_id: int) -> int | None: + return db.scalar( + select(SwapRequest.id).where( + SwapRequest.assignment_id == assignment_id, + SwapRequest.status.in_(["open", "pending_approval"]), + ) + ) + + +def _swap_side( + db: Session, schedule: Schedule, assignment_id: int | None, *, exclude_user_id: int | None = None +) -> Assignment: + """One side of a swap: an assigned, future shift of the same schedule.""" + assignment = db.get(Assignment, assignment_id) if assignment_id else None + if not assignment: + raise HTTPException(status_code=400, detail="Escolha o turno da outra pessoa") + if assignment.schedule_id != schedule.id: + raise HTTPException(status_code=400, detail="Só pode trocar com quem trabalha nesta escala") + if assignment.user_id is None or assignment.user_id == exclude_user_id: + raise HTTPException(status_code=400, detail="Escolha o turno de outra pessoa") + if assignment.date < date.today(): + raise HTTPException(status_code=400, detail="Turnos passados não podem ser alterados") + if _active_request(db, assignment.id): + raise HTTPException(status_code=400, detail="Esse turno já tem um pedido de troca") + return assignment + + +def _swap_partner(db: Session, schedule: Schedule, user_id: int | None) -> User | None: + """The one person this swap is with: active and working the same schedule.""" + if not user_id: + raise HTTPException(status_code=400, detail="Escolha a pessoa que fica com o turno") + if user_id not in _schedule_people_ids(db, schedule.id): + raise HTTPException( + status_code=400, detail="Só pode trocar com quem trabalha nesta escala" + ) + partner = db.get(User, user_id) + if not partner or not partner.is_active: + raise HTTPException(status_code=400, detail="Pessoa inválida para este turno") + return partner + + +@router.get("/swaps/new", response_class=HTMLResponse) +def new_swap_page( + request: Request, + year: int | None = None, + month: int | None = None, + db: Session = Depends(get_db), +): + """Its own page, so the rota keeps showing only who works each day.""" + user = _require_user(request, db) + year, month = _parse_month(year, month) + assignments = ensure_month_assignments(db, year, month) + taken = set( + db.scalars( + select(SwapRequest.assignment_id).where( + SwapRequest.status.in_(["open", "pending_approval"]) + ) + ).all() + ) + # One person can work several days, so the shift to offer is chosen here, + # and each schedule only offers the people who work that same schedule. + names = {u.id: u.name for u in db.scalars(select(User)).all()} + groups: list[dict] = [] + for schedule in _active_schedules(db): + mine = [ + a for a in assignments + if a.schedule_id == schedule.id + and a.user_id + and (a.user_id == user.id or user.is_admin) + and a.date >= date.today() + and a.id not in taken + ] + theirs = [ + a for a in assignments + if a.schedule_id == schedule.id + and a.user_id + and a.user_id != user.id + and a.date >= date.today() + and a.id not in taken + ] + if not mine or not theirs: + continue + groups.append( + { + "schedule": schedule, + "shifts": [{"id": a.id, "label": f"{day_short(a.date)}"} for a in sorted(mine, key=lambda r: r.date)], + "wanted": [ + { + "id": a.id, + "label": f"{day_short(a.date)} · {names[a.user_id]}", + } + for a in sorted(theirs, key=lambda r: r.date) + ], + } + ) + prev, nxt = _month_nav(year, month) + return request.app.state.templates.TemplateResponse( + request=request, + name="swap_new.html", + context=_context( + request, + db, + year=year, + month=month, + month_name=month_name(month), + prev=prev, + nxt=nxt, + groups=groups, + ), + ) + + +@router.post("/swaps/new") +def create_swap_for_chosen_shift( + request: Request, + assignment_id: int = Form(...), + target_assignment_id: int = Form(...), + message: str = Form(""), + csrf_token: str = Form(...), + db: Session = Depends(get_db), +): + return _create_swap(assignment_id, request, target_assignment_id, message, csrf_token, db) + + @router.post("/assignments/{assignment_id}/swap") def create_swap( assignment_id: int, request: Request, - target_user_id: str = Form(""), + target_assignment_id: int = Form(...), message: str = Form(""), csrf_token: str = Form(...), db: Session = Depends(get_db), +): + return _create_swap(assignment_id, request, target_assignment_id, message, csrf_token, db) + + +def _create_swap( + assignment_id: int, + request: Request, + target_assignment_id: int, + message: str, + csrf_token: str, + db: Session, ): _check_csrf(request, csrf_token) user = _require_user(request, db) - assignment = db.scalar( - select(Assignment) - .where(Assignment.id == assignment_id) - .options(selectinload(Assignment.schedule), selectinload(Assignment.user)) - ) - if not assignment or assignment.user_id != user.id: + assignment = db.get(Assignment, assignment_id) + if not assignment: + raise HTTPException(status_code=404, detail="Turno não encontrado") + # An administrator may open a request for someone else, but the shift stays + # the requester's own so the ownership rule still applies on acceptance. + owner_id = assignment.user_id + if owner_id is None or (owner_id != user.id and not user.is_admin): raise HTTPException(status_code=403, detail="Só pode oferecer o seu próprio turno") + owner = db.get(User, owner_id) if assignment.date < date.today(): raise HTTPException(status_code=400, detail="Turnos passados não podem ser alterados") - - existing = db.scalar( - select(SwapRequest.id).where( - SwapRequest.assignment_id == assignment.id, - SwapRequest.status.in_(["open", "pending_approval"]), - ) - ) - if existing: + if _active_request(db, assignment.id): _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="Destinatário inválido") + # A swap is one shift for one shift, both of the same schedule. + incoming = _swap_side(db, assignment.schedule, target_assignment_id, exclude_user_id=owner.id) + if incoming.id == assignment.id: + raise HTTPException(status_code=400, detail="Escolha outro turno para a troca") + target = db.get(User, incoming.user_id) swap = SwapRequest( assignment_id=assignment.id, - requester_id=user.id, - target_user_id=target.id if target else None, + target_assignment_id=incoming.id, + requester_id=owner.id, + target_user_id=target.id, status="open", message=message.strip() or None, ) db.add(swap) db.commit() - subject = f"Pedido de troca de turno: {day_short(assignment.date)} – {assignment.schedule.name}" + subject = ( + f"Troca de turnos: {day_short(assignment.date)} por {day_short(incoming.date)} " + f"– {assignment.schedule.name}" + ) body = ( - f"{user.name} pede que alguém assuma o turno de {assignment.schedule.name} " - f"a {day_numeric_long(assignment.date)}.\n\n" + f"{owner.name} propõe trocar o turno de {assignment.schedule.name} de " + f"{day_numeric_long(assignment.date)} pelo seu turno de {day_numeric_long(incoming.date)}.\n\n" f"{message.strip()}\n\n" f"Abrir a escala: {settings.normalized_base_url}/swaps" ) - if target: - send_email_notification(db, target, "swap_requested", subject, body) - else: - candidates = db.scalars( - select(User).where(User.is_active.is_(True), User.id != user.id).order_by(User.name) - ).all() - send_many(db, candidates, "swap_requested", subject, body) + send_email_notification(db, target, "swap_requested", subject, body) _flash(request, "Pedido de troca criado.") return _redirect("/swaps") +def _safe_back(request: Request, fallback: str) -> str: + """Return to the rota when the action was started there, never to an arbitrary URL.""" + back = str(request.query_params.get("back") or request.headers.get("referer") or "") + if back.startswith("/") and not back.startswith("//"): + return back.split("#")[0] + return fallback + + +def _reject_swap(db: Session, swap: SwapRequest) -> None: + swap.status = "rejected" + db.commit() + + +def _rejectable(user: User, swap: SwapRequest) -> bool: + """Anyone eligible may decline an open request; admins can also drop a pending one.""" + if user.is_admin: + return True + if swap.status != "open" or swap.requester_id == user.id: + return False + return swap.target_user_id is None or swap.target_user_id == user.id + + +def _swap_ownership_holds(db: Session, swap: SwapRequest) -> bool: + """Both people must still own their own shift, otherwise the swap is void.""" + if swap.assignment.user_id != swap.requester_id: + return False + if swap.target_assignment_id is not None and swap.target_assignment is not None: + if swap.target_assignment.user_id != swap.target_user_id: + return False + return True + + +def _complete_swap(db: Session, swap: SwapRequest, new_user: User) -> None: + """Exchange both shifts and close the request. Ownership must be checked by the caller.""" + swap.assignment.user_id = new_user.id + swap.assignment.source = "swap" + incoming = swap.target_assignment + if incoming is not None: + incoming.user_id = swap.requester_id + incoming.source = "swap" + swap.accepted_by_id = new_user.id + swap.status = "approved" + for other in db.scalars( + select(SwapRequest).where( + SwapRequest.id != swap.id, + SwapRequest.status.in_(["open", "pending_approval"]), + ( + (SwapRequest.assignment_id == swap.assignment_id) + | (SwapRequest.target_assignment_id == swap.assignment_id) + | ( + (SwapRequest.assignment_id.is_not(None)) + & (SwapRequest.assignment_id == swap.target_assignment_id) + ) + | ( + (SwapRequest.target_assignment_id.is_not(None)) + & (SwapRequest.target_assignment_id == swap.target_assignment_id) + ) + ), + ) + ).all(): + other.status = "cancelled" + db.commit() + + @router.post("/swaps/{swap_id}/accept") def accept_swap( swap_id: int, @@ -409,7 +676,11 @@ def accept_swap( swap = db.scalar( select(SwapRequest) .where(SwapRequest.id == swap_id) - .options(selectinload(SwapRequest.assignment).selectinload(Assignment.schedule), selectinload(SwapRequest.requester)) + .options( + selectinload(SwapRequest.assignment).selectinload(Assignment.schedule), + selectinload(SwapRequest.target_assignment).selectinload(Assignment.schedule), + selectinload(SwapRequest.requester), + ) ) if not swap or swap.status != "open": raise HTTPException(status_code=400, detail="Este pedido já não está aberto") @@ -417,7 +688,7 @@ def accept_swap( 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="Este pedido é para outra pessoa") - if swap.assignment.user_id != swap.requester_id: + if not _swap_ownership_holds(db, swap): swap.status = "cancelled" db.commit() raise HTTPException(status_code=409, detail="O turno já foi alterado") @@ -432,8 +703,14 @@ def accept_swap( admins, "swap_needs_approval", "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", + f"{user.name} aceitou a troca de {swap.assignment.schedule.name} de " + f"{day_numeric_long(swap.assignment.date)}" + + ( + f" por {day_numeric_long(swap.target_assignment.date)}" + if swap.target_assignment is not None + else "" + ) + + f", pedida por {swap.requester.name}. Aprove em {settings.normalized_base_url}/swaps", ) send_email_notification( db, @@ -444,25 +721,23 @@ def accept_swap( ) _flash(request, "Aceite. A aguardar aprovação da gestão.") else: - swap.assignment.user_id = user.id - swap.assignment.source = "swap" - swap.status = "approved" - db.commit() - send_email_notification( - db, - swap.requester, - "swap_approved", - "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", - "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, "O turno foi transferido para si.") + _complete_swap(db, swap, user) + incoming = swap.target_assignment + for person, other in ((swap.requester, user), (user, swap.requester)): + send_email_notification( + db, + person, + "swap_approved", + "Troca de turno confirmada", + f"Troca concluída em {swap.assignment.schedule.name}: fica com o turno de " + f"{day_numeric_long(swap.assignment.date)}" + + ( + f" e passa o de {day_numeric_long(incoming.date)} para {other.name}." + if incoming is not None + else "." + ), + ) + _flash(request, "Troca concluída.") return _redirect("/swaps") @@ -480,12 +755,11 @@ def reject_swap( .where(SwapRequest.id == swap_id) .options(selectinload(SwapRequest.requester)) ) - if not swap or swap.status != "open": + if not swap or swap.status not in {"open", "pending_approval"}: 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="Só a pessoa destinatária pode recusar este pedido") - swap.status = "rejected" - db.commit() + if not _rejectable(user, swap): + raise HTTPException(status_code=403, detail="Não pode recusar este pedido") + _reject_swap(db, swap) send_email_notification( db, swap.requester, @@ -494,7 +768,7 @@ def reject_swap( f"{user.name} recusou o seu pedido de troca.", ) _flash(request, "Pedido recusado.") - return _redirect("/swaps") + return _redirect(_safe_back(request, "/swaps")) @router.post("/swaps/{swap_id}/cancel") @@ -519,39 +793,110 @@ def cancel_swap( def approve_swap( swap_id: int, request: Request, + user_id: str = Form(""), csrf_token: str = Form(...), db: Session = Depends(get_db), ): + admin = _require_admin(request, db) _check_csrf(request, csrf_token) - _require_admin(request, db) swap = db.scalar( select(SwapRequest) .where(SwapRequest.id == swap_id) .options( selectinload(SwapRequest.assignment).selectinload(Assignment.schedule), + selectinload(SwapRequest.target_assignment).selectinload(Assignment.schedule), selectinload(SwapRequest.requester), selectinload(SwapRequest.accepted_by), ) ) - if not swap or swap.status != "pending_approval" or not swap.accepted_by: - raise HTTPException(status_code=400, detail="O pedido ainda não está pronto a ser aprovado") - if swap.assignment.user_id != swap.requester_id: + if not swap or swap.status not in {"open", "pending_approval"}: + raise HTTPException(status_code=400, detail="Este pedido já não pode ser aprovado") + if not _swap_ownership_holds(db, swap): swap.status = "cancelled" db.commit() raise HTTPException(status_code=409, detail="O turno já foi alterado") + if swap.assignment.date < date.today(): + raise HTTPException(status_code=400, detail="Turnos passados não podem ser alterados") - swap.assignment.user_id = swap.accepted_by_id - swap.assignment.source = "swap" - swap.status = "approved" - db.commit() + if swap.accepted_by and swap.accepted_by.is_active: + new_user = swap.accepted_by + elif swap.target_user_id and db.get(User, swap.target_user_id).is_active: + new_user = db.get(User, swap.target_user_id) + else: + new_user = _swap_partner(db, swap.assignment.schedule, int(user_id) if user_id.strip() else None) + if new_user.id == swap.requester_id: + raise HTTPException(status_code=400, detail="Escolha outra pessoa para a troca") + + _complete_swap(db, swap, new_user) + incoming = swap.target_assignment subject = "Troca de turno aprovada" body = ( - 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." + f"{admin.name} aprovou a troca de {swap.assignment.schedule.name}: " + f"{new_user.name} fica com o turno de {day_numeric_long(swap.assignment.date)}" + + ( + f" e {swap.requester.name} com o de {day_numeric_long(incoming.date)}." + if incoming is not None + else "." + ) ) - send_many(db, [swap.requester, swap.accepted_by], "swap_approved", subject, body) + send_many(db, [swap.requester, new_user], "swap_approved", subject, body) _flash(request, "Troca aprovada e escala atualizada.") - return _redirect("/swaps") + return _redirect(_safe_back(request, "/swaps")) + + +@router.post("/swaps/{swap_id}/revert") +def revert_swap( + swap_id: int, + request: Request, + csrf_token: str = Form(...), + db: Session = Depends(get_db), +): + """Administrator only: undo an approved swap and give both shifts back.""" + admin = _require_admin(request, db) + _check_csrf(request, csrf_token) + swap = db.scalar( + select(SwapRequest) + .where(SwapRequest.id == swap_id) + .options( + selectinload(SwapRequest.assignment).selectinload(Assignment.schedule), + selectinload(SwapRequest.target_assignment), + selectinload(SwapRequest.requester), + ) + ) + if not swap or swap.target_assignment_id is None: + raise HTTPException(status_code=404, detail="Troca não encontrada") + if swap.status != "approved": + raise HTTPException(status_code=400, detail="Só uma troca aprovada pode ser revertida") + # The shifts must still be the ones the swap produced, or somebody edited them since. + if swap.assignment.user_id != swap.accepted_by_id or ( + swap.target_assignment is not None + and swap.target_assignment.user_id != swap.requester_id + ): + raise HTTPException( + status_code=409, detail="O turno foi alterado depois da troca; reverta com a atribuição por dia" + ) + + incoming = swap.target_assignment + note = f"Revertida a troca #{swap.id} por {admin.name}" + swap.assignment.user_id = swap.requester_id + swap.assignment.source = "manual" + swap.assignment.note = note + incoming.user_id = swap.target_user_id + incoming.source = "manual" + incoming.note = note + swap.status = "reverted" + db.commit() + + subject = "Troca de turno revertida" + body = ( + f"{admin.name} reverteu a troca de {swap.assignment.schedule.name}. " + f"{swap.requester.name} volta a {day_numeric_long(swap.assignment.date)} e " + f"{swap.target_user.name} volta a {day_numeric_long(incoming.date)}.\n\n" + f"Ver a escala: {settings.normalized_base_url}/" + ) + send_many(db, [swap.requester, swap.target_user], "swap_reverted", subject, body) + _flash(request, "Troca revertida: os dois turnos voltaram a quem os tinha.") + return _redirect(_safe_back(request, "/swaps")) @router.post("/swaps/{swap_id}/admin-reject") @@ -561,21 +906,21 @@ def admin_reject_swap( csrf_token: str = Form(...), db: Session = Depends(get_db), ): + admin = _require_admin(request, db) _check_csrf(request, csrf_token) - _require_admin(request, db) swap = db.scalar( select(SwapRequest) .where(SwapRequest.id == swap_id) .options(selectinload(SwapRequest.requester), selectinload(SwapRequest.accepted_by)) ) - if not swap or swap.status != "pending_approval": - raise HTTPException(status_code=400, detail="O pedido não está à espera de aprovação") - swap.status = "rejected" - db.commit() + if not swap or swap.status not in {"open", "pending_approval"}: + raise HTTPException(status_code=400, detail="Este pedido não pode ser recusado") + _reject_swap(db, swap) users = [u for u in [swap.requester, swap.accepted_by] if u] - send_many(db, users, "swap_rejected", "Troca de turno não aprovada", "A gestão não aprovou a troca de turno pedida.") + send_many(db, users, "swap_rejected", "Troca de turno não aprovada", + f"{admin.name} não aprovou a troca de turno pedida.") _flash(request, "Troca recusada.") - return _redirect("/swaps") + return _redirect(_safe_back(request, "/swaps")) @router.get("/admin/users", response_class=HTMLResponse) @@ -801,7 +1146,6 @@ def admin_user_delete( db.execute(delete(RotationMember).where(RotationMember.user_id == user.id)) db.delete(user) db.commit() - _flash(request, f"{user.name} foi removida(o).") return _redirect("/admin/users") @@ -844,6 +1188,7 @@ def admin_schedule( card=_schedule_card(schedule, db), cards=_schedule_groups(_all_schedules(db), db), users=users, + schedule_people=_schedule_people(db, schedule.id), assignments=assignments, swap_requests=_open_swap_requests(db, schedule.id), pattern_days=list(range(1, 32)), @@ -872,6 +1217,7 @@ def _open_swap_requests(db: Session, schedule_id: int) -> list[SwapRequest]: ) .options( selectinload(SwapRequest.assignment).selectinload(Assignment.schedule), + selectinload(SwapRequest.target_assignment).selectinload(Assignment.schedule), selectinload(SwapRequest.requester), selectinload(SwapRequest.target_user), selectinload(SwapRequest.accepted_by), @@ -1098,6 +1444,32 @@ def _save_assignments(db: Session, assignments: Sequence[Assignment], form) -> i return len(changed) +def _default_person(db: Session, schedule: Schedule, day: date) -> User | None: + """Who this shift would have by default: the rotation order or the night pattern.""" + if schedule.schedule_type == "rotation": + return rotation_user_for_date(db, schedule, day) + user_id = _pattern_map(db, schedule).get(day.day) + return db.get(User, user_id) if user_id else None + + +def _set_assignee( + db: Session, assignment: Assignment, new_user: User | None, source: str = "manual" +) -> None: + """Put someone on a shift directly: no change request, and any stale one is closed.""" + assignment.user_id = new_user.id if new_user else None + assignment.user = new_user + assignment.source = source + for swap in db.scalars( + select(SwapRequest).where( + SwapRequest.status.in_(["open", "pending_approval"]), + (SwapRequest.assignment_id == assignment.id) + | (SwapRequest.target_assignment_id == assignment.id), + ) + ).all(): + swap.status = "cancelled" + db.commit() + + def _notify_assignment_changes(db: Session, changed: Sequence[tuple[Assignment, User | None, User | None]]) -> None: for assignment, old_user, new_user in changed: subject = f"Escala atualizada: {day_short(assignment.date)} – {assignment.schedule.name}" @@ -1153,6 +1525,7 @@ def admin_schedule_assign_swap( .where(SwapRequest.id == swap_id) .options( selectinload(SwapRequest.assignment).selectinload(Assignment.schedule), + selectinload(SwapRequest.target_assignment).selectinload(Assignment.schedule), selectinload(SwapRequest.requester), ) ) @@ -1160,13 +1533,13 @@ def admin_schedule_assign_swap( raise HTTPException(status_code=404, detail="Pedido de troca não encontrado") if swap.status not in {"open", "pending_approval"}: raise HTTPException(status_code=400, detail="Este pedido já não está aberto") - new_user = db.get(User, user_id) - if not new_user or not new_user.is_active or new_user.id == swap.requester_id: - raise HTTPException(status_code=400, detail="Pessoa inválida para este turno") + new_user = _swap_partner(db, schedule, user_id) + if new_user.id == swap.requester_id: + raise HTTPException(status_code=400, detail="Escolha outra pessoa para a troca") if swap.assignment.date < date.today(): raise HTTPException(status_code=400, detail="Turnos passados não podem ser alterados") # The request only applies while the person who asked for the change still owns the shift. - if swap.assignment.user_id != swap.requester_id: + if not _swap_ownership_holds(db, swap): swap.status = "cancelled" db.commit() raise HTTPException(status_code=409, detail="O turno já foi alterado") @@ -1187,9 +1560,15 @@ def admin_schedule_assign_swap( subject = "Troca de turno aprovada" body = ( - f"{admin.name} atribuiu o turno de {schedule.name} a {day_numeric_long(swap.assignment.date)} " - f"a {new_user.name}, a pedido de {swap.requester.name}.\n\n" - f"Ver a escala: {settings.normalized_base_url}/" + f"{admin.name} atribuiu o turno de {schedule.name} de " + f"{day_numeric_long(swap.assignment.date)} a {new_user.name}, a pedido de {swap.requester.name}." + + ( + f" Em troca, {swap.requester.name} passa a ter o turno de " + f"{day_numeric_long(swap.target_assignment.date)}." + if swap.target_assignment is not None + else "" + ) + + f"\n\nVer a escala: {settings.normalized_base_url}/" ) send_many(db, [swap.requester, new_user], "swap_approved", subject, body) _flash(request, f"Turno de {day_short(swap.assignment.date)} atribuído a {new_user.name}.") @@ -1346,6 +1725,110 @@ def admin_assignment_regenerate( return _redirect(f"/admin/schedules/{schedule.id}?year={assignment.date.year}&month={assignment.date.month}") +@router.get("/admin/assign", response_class=HTMLResponse) +def admin_assign_day( + request: Request, + on: str | None = None, + db: Session = Depends(get_db), +): + """Pick a day and put someone on one of its shifts. No change request involved. + + `on` is a whole ISO date (`YYYY-MM-DD`), which is what the date input sends. + """ + _require_admin(request, db) + today = date.today() + chosen = today + if on: + try: + chosen = date.fromisoformat(on) + except ValueError: + raise HTTPException(status_code=400, detail="Data inválida") + rows = { + a.schedule_id: a + for a in ensure_month_assignments(db, chosen.year, chosen.month) + if a.date == chosen + } + shifts = [ + { + "schedule": schedule, + "assignment": rows[schedule.id], + "auto": _default_person(db, schedule, chosen), + } + for schedule in _active_schedules(db) + if schedule.id in rows + ] + prev_day = chosen - timedelta(days=1) + next_day = chosen + timedelta(days=1) + return request.app.state.templates.TemplateResponse( + request=request, + name="admin_assign.html", + context=_context( + request, + db, + day=chosen, + shifts=shifts, + users=db.scalars( + select(User).where(User.is_active.is_(True)).order_by(User.name) + ).all(), + prev_day=prev_day, + next_day=next_day, + today=today, + ), + ) + + +@router.post("/admin/assign") +def admin_assign_person( + request: Request, + assignment_id: int = Form(...), + user_id: str = Form(""), + csrf_token: str = Form(...), + db: Session = Depends(get_db), +): + admin = _require_admin(request, db) + _check_csrf(request, csrf_token) + assignment = db.scalar( + select(Assignment) + .where(Assignment.id == assignment_id) + .options(selectinload(Assignment.schedule), selectinload(Assignment.user)) + ) + if not assignment: + raise HTTPException(status_code=404, detail="Turno não encontrado") + if assignment.date.weekday() not in assignment.schedule.weekday_set: + raise HTTPException(status_code=400, detail="Esta data não corresponde à escala") + + choice = user_id.strip() + source = "manual" + new_user = None + if choice == "auto": + source = "generated" + new_user = _default_person(db, assignment.schedule, assignment.date) + elif choice: + new_user = db.get(User, int(choice)) + if not new_user or not new_user.is_active: + raise HTTPException(status_code=400, detail="Pessoa inválida") + if new_user and new_user.id == assignment.user_id and assignment.source == source: + _flash(request, f"{new_user.name} já estava em {day_short(assignment.date)}.") + return _redirect(_assign_day_url(assignment.date)) + + previous_user_id = assignment.user_id + _set_assignee(db, assignment, new_user, source) + previous_user = db.get(User, previous_user_id) if previous_user_id else None + _notify_assignment_changes(db, [(assignment, previous_user, new_user)]) + if new_user is None: + message = f"Turno de {day_short(assignment.date)} sem atribuição." + else: + message = f"{new_user.name} em {day_short(assignment.date)} · {assignment.schedule.name}." + if source == "generated": + message += " (automático)" + _flash(request, message) + return _redirect(_assign_day_url(assignment.date)) + + +def _assign_day_url(day: date) -> str: + return f"/admin/assign?on={day.isoformat()}" + + @router.get("/admin/notifications", response_class=HTMLResponse) def admin_notifications(request: Request, db: Session = Depends(get_db)): _require_admin(request, db) diff --git a/docs/DOMAIN.md b/docs/DOMAIN.md index e5fc383..473d185 100644 --- a/docs/DOMAIN.md +++ b/docs/DOMAIN.md @@ -68,16 +68,24 @@ Every assignment on a lunch schedule page has a **Regenerate** button. An admini `open` → `pending_approval` → `approved` -Other terminal states: `rejected`, `cancelled`. +Other terminal states: `rejected`, `cancelled`, `reverted`. -- A member can offer one of their future/current assignments to a specific active member or to anyone. +- A swap is always **one shift for one shift**: it is created on `/swaps/new` (its own page, so the rota keeps showing only who works each day) and names both shifts. The person giving the first shift is the requester; the person owning the second one is the target. There are no open offers. +- The two shifts must belong to the same schedule. The people of a schedule are the ones in its rotation, in its monthly pattern, or already holding one of its shifts. +- When a swap is approved or accepted, **both** assignments change hands at once: the target takes the requester's shift and the requester takes the target's shift. Both become `swap` and both people are notified. +- One person can work several days in a month, so each side of the exchange is chosen from a list of the month's future shifts, grouped by schedule: the requester picks "O turno que passo" (their own shifts) and "O turno que quero em troca" (someone else's shifts of that schedule). A member only sees their own shifts on the first list; an administrator sees all of them. +- A shift can only be part of one open request at a time, on either side. +- An administrator can open a request for someone else's shift. The request is still recorded against the person who owns the shift, so the ownership rule below keeps working; unassigned and past shifts cannot be requested. +- `/admin/assign` is the day-by-day picker for administrators: pick a day, then put someone on one of its shifts with **Atribuir**. This is a direct assignment, never a change request. It sets the assignment source to `manual`, cancels any open request that involves that shift, and notifies both the new and the previous person. `Sem atribuição` clears it. The date must match one of the schedule's weekdays. - The requester cannot accept their own request. -- A targeted request can only be accepted/rejected by that target. -- An open request can be accepted by any other active member who can sign in. +- Only the person the request names can accept it or decline it. - If the schedule requires manager approval, acceptance moves to `pending_approval`. +- Nobody can decline their own request; the requester cancels it instead. An administrator may decline any `open` or `pending_approval` request. +- An administrator can approve a `pending_approval` request (it goes to whoever accepted it) or an `open` one, choosing another person of the same schedule when there is no named partner. Approval and decline are available both in `/swaps` and on the rota page next to the shift. - Approval transfers the assignment and sets its source to `swap`. -- If the requester no longer owns the assignment, the request must not be applied. -- On a schedule's configuration page, an administrator can complete an `open` or `pending_approval` request on someone's behalf by choosing any other active member. This is the only way a rota-only person gives up or receives a shift. The same ownership rule applies, other open requests for that assignment are cancelled, and the requester and the new person are both notified. Past dates are refused. +- Only an administrator can revert an approved two-sided swap: both shifts go back to the people who had them, their source becomes `manual` (the original source cannot be recovered) and a note records the revert. If either shift changed after the swap, the revert is refused and the day-by-day assignment must be used instead. +- If either person no longer owns their own shift, the request must not be applied and is cancelled. +- On a schedule's configuration page, an administrator can complete an `open` or `pending_approval` request on someone's behalf by choosing another person who works that same schedule. This is the only way a rota-only person gives up or receives a shift. The same ownership rule applies, other open requests for that assignment are cancelled, and the requester and the new person are both notified. Past dates are refused. ## Notifications diff --git a/migrations/versions/57f552c46f7c_swap_names_both_shifts.py b/migrations/versions/57f552c46f7c_swap_names_both_shifts.py new file mode 100644 index 0000000..27083ea --- /dev/null +++ b/migrations/versions/57f552c46f7c_swap_names_both_shifts.py @@ -0,0 +1,38 @@ +"""swap names both shifts + +Revision ID: 57f552c46f7c +Revises: bd2d4bb905b1 +Create Date: 2026-10-06 12:07:24.786067 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision: str = '57f552c46f7c' +down_revision: Union[str, Sequence[str], None] = 'bd2d4bb905b1' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + """Add the second shift of the exchange.""" + with op.batch_alter_table('swap_requests', schema=None) as batch_op: + batch_op.add_column(sa.Column('target_assignment_id', sa.Integer(), nullable=True)) + batch_op.create_foreign_key( + 'fk_swap_requests_target_assignment', + 'assignments', + ['target_assignment_id'], + ['id'], + ondelete='SET NULL', + ) + + +def downgrade() -> None: + """Drop the second shift of the exchange.""" + with op.batch_alter_table('swap_requests', schema=None) as batch_op: + batch_op.drop_constraint('fk_swap_requests_target_assignment', type_='foreignkey') + batch_op.drop_column('target_assignment_id') diff --git a/tests/test_admin_schedule_assignments.py b/tests/test_admin_schedule_assignments.py index 860bac0..f67f94b 100644 --- a/tests/test_admin_schedule_assignments.py +++ b/tests/test_admin_schedule_assignments.py @@ -10,6 +10,7 @@ from sqlalchemy.pool import StaticPool from app.database import Base, get_db from app.main import app from app.models import Assignment, MonthlyPattern, NotificationLog, RotationMember, Schedule, SwapRequest, User +from app.i18n import day_long, day_short from app.scheduling import ensure_month_assignments from app.security import hash_password @@ -632,19 +633,53 @@ def test_new_generation_controls_require_admin_and_csrf(client, db, action): assert client.post(url, data={**data, "csrf_token": token}).status_code == 403 -def _open_request(db, schedule: Schedule, owner: User, target: User | None = None) -> SwapRequest: - ensure_month_assignments(db, YEAR, MONTH) - assignment = db.scalar( - select(Assignment).where( +def upcoming_of(db, schedule: Schedule, exclude: int | None = None) -> int: + row = db.scalar( + select(Assignment) + .where( Assignment.schedule_id == schedule.id, Assignment.date > date.today(), - ).order_by(Assignment.date) + Assignment.id != exclude if exclude else Assignment.id.is_not(None), + ) + .order_by(Assignment.date) ) + assert row is not None + return row.id + + +def _open_request( + db, + schedule: Schedule, + owner: User, + target: User | None = None, + *, + two_sided: bool = True, +) -> SwapRequest: + """An open request: `owner` gives a shift and, by default, gets another one back.""" + ensure_month_assignments(db, YEAR, MONTH) + upcoming = list( + db.scalars( + select(Assignment) + .where(Assignment.schedule_id == schedule.id, Assignment.date > date.today()) + .order_by(Assignment.date) + ).all() + ) + assignment = upcoming[0] assignment.user_id = owner.id + incoming = None + partner = target + if two_sided: + for row in upcoming[1:]: + if row.user_id is not None and (partner is None or row.user_id == partner.id): + incoming = row + break + if incoming is not None and partner is None: + partner = db.get(User, incoming.user_id) swap = SwapRequest( assignment_id=assignment.id, + target_assignment_id=incoming.id if incoming is not None else None, requester_id=owner.id, - target_user_id=target.id if target else None, + target_user_id=partner.id if partner else None, status="open", ) db.add(swap) @@ -657,6 +692,9 @@ def test_admin_completes_a_change_request_on_the_schedule_page(client, db): token = sign_in(client) rota_only = User(name="Rota Only", is_active=True, notify_email=True, email="rota@example.com") db.add(rota_only) + db.flush() + # Rota-only people work the schedule without signing in, so they are part of it. + db.add(RotationMember(schedule_id=sat.id, user_id=rota_only.id, position=2)) db.commit() swap = _open_request(db, sat, ana) @@ -744,3 +782,651 @@ def test_admin_assignment_rejects_bad_input_and_protects_the_route(client, db): client.post("/login", data={"username": "member", "password": "member-password", "csrf_token": token}) token = CSRF_RE.search(client.get("/").text).group(1) assert client.post(url, data={"csrf_token": token, "user_id": bruno.id}).status_code == 403 + + +def test_admin_can_open_a_change_request_for_someone_else(client, db): + _, sat, _, ana, bruno, admin = seed(db) + token = sign_in(client) + row = assignment_on(db, sat, date(YEAR, MONTH, 17)) + row.user_id = ana.id + incoming = assignment_on(db, sat, date(YEAR, MONTH, 24)) + incoming.user_id = bruno.id + db.commit() + + rota = client.get(f"/?year={YEAR}&month={MONTH}").text + assert 'href="/swaps/new?year=2026&month=10"' in rota # the rota only links to the form + page = client.get(f"/swaps/new?year={YEAR}&month={MONTH}").text + assert f'', block) + } + ) + return options + + +def test_the_swap_page_lists_the_shifts_and_the_people_of_each_schedule(client, db): + _, sat, sun, ana, bruno, admin = seed(db) + token = sign_in(client) + ensure_month_assignments(db, YEAR, MONTH) + future = [a for a in db.scalars(select(Assignment)).all() if a.date >= date.today() and a.user_id] + + rota = client.get(f"/?year={YEAR}&month={MONTH}").text + assert 'action="/swaps/new"' not in rota # the rota only shows who works each day + assert f'href="/swaps/new?year={YEAR}&month={MONTH}"' in rota + + page = client.get(f"/swaps/new?year={YEAR}&month={MONTH}").text + listed = _shift_options(page) + # Every future shift of the month an administrator may offer is listed once, with its date. + assert set(listed) == {a.id for a in future} + for assignment in future: + assert listed[assignment.id] == day_short(assignment.date) + + # Ana only appears in the Saturday block, Bruno in Saturday and Sunday. + assert page.count("Ana") >= 1 + saturday = page.split("Almoço - Sábados")[1].split("")[0] + sunday = page.split("Almoço - Domingo")[1].split("")[0] + assert "Ana" in saturday and "Ana" not in sunday + assert "Bruno" in sunday + + # A member only gets their own shifts in the list. + ana.username = "ana" + ana.password_hash = hash_password("ana-password") + db.commit() + client.post("/logout", data={"csrf_token": token}) + token = CSRF_RE.search(client.get("/login").text).group(1) + client.post("/login", data={"username": "ana", "password": "ana-password", "csrf_token": token}) + own = _shift_options(client.get(f"/swaps/new?year={YEAR}&month={MONTH}").text) + assert own + for assignment_id in own: + assert db.get(Assignment, assignment_id).user_id == ana.id + + +def test_a_swap_cannot_cross_schedules(client, db): + night, sat, sun, ana, bruno, admin = seed(db) + token = sign_in(client) + ensure_month_assignments(db, YEAR, MONTH) + saturday = assignment_on(db, sat, date(YEAR, MONTH, 17)) + saturday.user_id = ana.id + bruno_shift = assignment_on(db, sat, date(YEAR, MONTH, 24)) + bruno_shift.user_id = bruno.id + night_row = assignment_on(db, night, date(YEAR, MONTH, 18)) + night_row.user_id = ana.id + db.commit() + page = client.get(f"/swaps/new?year={YEAR}&month={MONTH}").text + token_page = CSRF_RE.search(page).group(1) + + # Bruno works the Saturday rotation but not the night schedule. + response = client.post( + "/swaps/new", + data={ + "csrf_token": token_page, + "assignment_id": saturday.id, + "target_assignment_id": bruno_shift.id, + }, + follow_redirects=False, + ) + assert response.status_code == 303 # a valid Saturday swap + + other = client.post( + "/swaps/new", + data={ + "csrf_token": token_page, + "assignment_id": night_row.id, + "target_assignment_id": bruno_shift.id, + }, + ) + assert other.status_code == 400 + assert db.scalars( + select(SwapRequest).where(SwapRequest.assignment_id == night_row.id) + ).all() == [] + + +def test_approving_a_swap_moves_both_shifts(client, db): + _, sat, _, ana, bruno, admin = seed(db) + token = sign_in(client) + swap = _open_request(db, sat, ana, target=bruno) + given, wanted = swap.assignment_id, swap.target_assignment_id + db.refresh(swap) + assert db.get(Assignment, given).user_id == ana.id + assert db.get(Assignment, wanted).user_id == bruno.id + + client.post(f"/swaps/{swap.id}/approve", data={"csrf_token": token}, follow_redirects=False) + + db.refresh(swap) + assert swap.status == "approved" + assert db.get(Assignment, given).user_id == bruno.id + assert db.get(Assignment, given).source == "swap" + assert db.get(Assignment, wanted).user_id == ana.id + assert db.get(Assignment, wanted).source == "swap" + notified = db.scalars( + select(NotificationLog).where(NotificationLog.event_type == "swap_approved") + ).all() + assert {log.user_id for log in notified} == {ana.id, bruno.id} + + +def test_the_two_shifts_are_only_traded_if_both_are_still_owned(client, db): + _, sat, _, ana, bruno, admin = seed(db) + token = sign_in(client) + swap = _open_request(db, sat, ana, target=bruno) + given, wanted = swap.assignment_id, swap.target_assignment_id + # Someone else takes the shift the requester wanted in return. + db.get(Assignment, wanted).user_id = ana.id + db.commit() + + response = client.post(f"/swaps/{swap.id}/approve", data={"csrf_token": token}) + + assert response.status_code == 409 + db.refresh(swap) + assert swap.status == "cancelled" + assert db.get(Assignment, given).user_id == ana.id + assert db.get(Assignment, wanted).user_id == ana.id + + +def test_creating_a_swap_needs_two_shifts_of_the_same_schedule(client, db): + night, sat, sun, ana, bruno, admin = seed(db) + token = sign_in(client) + ensure_month_assignments(db, YEAR, MONTH) + mine = assignment_on(db, sat, date(YEAR, MONTH, 17)) + mine.user_id = ana.id + other_saturday = assignment_on(db, sat, date(YEAR, MONTH, 24)) + other_saturday.user_id = bruno.id + night_shift = assignment_on(db, night, date(YEAR, MONTH, 19)) + night_shift.user_id = bruno.id + db.commit() + page = client.get(f"/swaps/new?year={YEAR}&month={MONTH}").text + form = {"csrf_token": CSRF_RE.search(page).group(1), "assignment_id": mine.id} + + def post(**extra): + return client.post("/swaps/new", data={**form, **extra}, follow_redirects=False) + + assert post(target_assignment_id=night_shift.id).status_code == 400 # another schedule + assert post(target_assignment_id=mine.id).status_code == 400 # the same shift + assert post().status_code == 422 # both shifts are required + + created = post(target_assignment_id=other_saturday.id) + assert created.status_code == 303, created.status_code + swap = db.scalar(select(SwapRequest).where(SwapRequest.assignment_id == mine.id)) + assert (swap.requester_id, swap.target_user_id, swap.target_assignment_id) == ( + ana.id, + bruno.id, + other_saturday.id, + ) + + # A shift can only be part of one open request at a time. + again = client.post( + "/swaps/new", + data={**form, "target_assignment_id": other_saturday.id}, + follow_redirects=True, + ) + assert "Já existe um pedido de troca ativo" in again.text + assert len(db.scalars(select(SwapRequest).where(SwapRequest.assignment_id == mine.id)).all()) == 1 + assert client.post( + "/swaps/new", + data={**form, "assignment_id": other_saturday.id, "target_assignment_id": mine.id}, + follow_redirects=False, + ).status_code == 400 + + +def test_admin_assigns_someone_to_a_day_without_any_swap(client, db): + night, sat, sun, ana, bruno, admin = seed(db) + token = sign_in(client) + target = date(YEAR, MONTH, 17) # a Saturday + page = client.get(f"/admin/assign?on={target.isoformat()}").text + assert "Atribuição por dia" in page + assert f'name="on" value="{target.isoformat()}"' in page + assert 'this.form.submit()' in page # picking a date applies it straight away + assert "Ver dia" not in page + assert f'href="/admin/assign?on={target.replace(day=16).isoformat()}"' in page + assert day_long(target) in page + night_row = assignment_on(db, night, target) + lunch_row = assignment_on(db, sat, target) + lunch_row.user_id = ana.id + db.commit() + + response = client.post( + "/admin/assign", + data={"csrf_token": token, "assignment_id": lunch_row.id, "user_id": bruno.id}, + follow_redirects=True, + ) + + assert "Bruno em sáb 17 out · Almoço - Sábados" in response.text + db.refresh(lunch_row) + assert lunch_row.user_id == bruno.id + assert lunch_row.source == "manual" + assert db.scalars(select(SwapRequest)).all() == [] # no change request involved + notified = db.scalars( + select(NotificationLog).where(NotificationLog.event_type == "assignment_updated") + ).all() + assert [log.user_id for log in notified] == [bruno.id] + assert db.get(Assignment, night_row.id).user_id in {None, ana.id, bruno.id} + + +def test_assigning_on_the_day_page_replaces_the_person_and_notifies_both(client, db): + _, sat, _, ana, bruno, admin = seed(db) + token = sign_in(client) + row = assignment_on(db, sat, date(YEAR, MONTH, 17)) + row.user_id = ana.id + db.commit() + + client.post( + "/admin/assign", + data={"csrf_token": token, "assignment_id": row.id, "user_id": bruno.id}, + follow_redirects=True, + ) + + db.refresh(row) + assert row.user_id == bruno.id + notified = { + (log.event_type, log.user_id) + for log in db.scalars(select(NotificationLog)).all() + } + assert ("assignment_updated", bruno.id) in notified + assert ("assignment_changed", ana.id) in notified + + # Choosing the same person again is a no-op, and nobody can be left unassigned by accident. + same = client.post( + "/admin/assign", + data={"csrf_token": token, "assignment_id": row.id, "user_id": bruno.id}, + follow_redirects=True, + ) + assert "Bruno já estava em sáb 17 out" in same.text + cleared = client.post( + "/admin/assign", + data={"csrf_token": token, "assignment_id": row.id, "user_id": ""}, + follow_redirects=True, + ) + assert "sem atribuição" in cleared.text + db.refresh(row) + assert row.user_id is None + assert row.source == "manual" + + +def test_assigning_by_day_closes_an_open_request_and_protects_the_route(client, db): + _, sat, _, ana, bruno, admin = seed(db) + token = sign_in(client) + swap = _open_request(db, sat, ana, target=bruno) + row = db.get(Assignment, swap.assignment_id) + + client.post( + "/admin/assign", + data={"csrf_token": token, "assignment_id": row.id, "user_id": bruno.id}, + follow_redirects=False, + ) + + db.refresh(swap) + assert swap.status == "cancelled" + + client.post("/logout", data={"csrf_token": token}) + assert client.post( + "/admin/assign", data={"assignment_id": row.id, "user_id": "", "csrf_token": token} + ).status_code == 401 + token = sign_in(client) + assert client.post("/admin/assign", data={"csrf_token": "invalid", "assignment_id": row.id}).status_code == 400 + assert client.post( + "/admin/assign", data={"csrf_token": token, "assignment_id": 9999, "user_id": ana.id} + ).status_code == 404 + inactive = User(name="Gone", is_active=False, notify_email=False) + db.add(inactive) + db.commit() + assert client.post( + "/admin/assign", data={"csrf_token": token, "assignment_id": row.id, "user_id": inactive.id} + ).status_code == 400 + assert client.get("/admin/assign?on=2026-10-45").status_code == 400 + assert client.get("/admin/assign?on=nao-e-uma-data").status_code == 400 + +def test_the_day_assign_page_is_reachable_from_the_schedules_hub(client, db): + _, sat, _, _, _, _ = seed(db) + sign_in(client) + + hub = client.get("/admin/schedules").text + assert 'Atribuir por dia' in hub + assert 'Atribuir dia' not in client.get("/admin/users").text + assert "Atribuição por dia" in client.get("/admin/assign").text + + +def test_the_day_page_can_reset_a_shift_to_its_default_person(client, db): + night, sat, sun, ana, bruno, admin = seed(db) + token = sign_in(client) + day = date(YEAR, MONTH, 17) # a Saturday + lunch = assignment_on(db, sat, day) + lunch.user_id = ana.id + lunch.source = "manual" + night_row = assignment_on(db, night, day) + night_row.user_id = ana.id + night_row.source = "manual" + db.commit() + db.add(MonthlyPattern(schedule_id=night.id, day_of_month=day.day, user_id=bruno.id)) + db.commit() + + page = client.get(f"/admin/assign?on={day.isoformat()}").text + assert "Automático → " in page + + response = client.post( + "/admin/assign", + data={"csrf_token": token, "assignment_id": lunch.id, "user_id": "auto"}, + follow_redirects=True, + ) + assert "(automático)" in response.text + db.refresh(lunch) + assert lunch.source == "generated" + assert lunch.user_id == bruno.id # the rotation picks Bruno for this date + + client.post( + "/admin/assign", + data={"csrf_token": token, "assignment_id": night_row.id, "user_id": "auto"}, + follow_redirects=True, + ) + db.refresh(night_row) + assert night_row.source == "generated" + assert night_row.user_id == bruno.id # the night pattern wins for the fixed schedule + + +def test_admin_reverts_an_approved_swap(client, db): + _, sat, _, ana, bruno, admin = seed(db) + token = sign_in(client) + swap = _open_request(db, sat, ana, target=bruno) + given, wanted = swap.assignment_id, swap.target_assignment_id + client.post(f"/swaps/{swap.id}/approve", data={"csrf_token": token}, follow_redirects=False) + db.refresh(swap) + assert (db.get(Assignment, given).user_id, db.get(Assignment, wanted).user_id) == (bruno.id, ana.id) + + page = client.get("/swaps").text + assert f'action="/swaps/{swap.id}/revert"' in page + response = client.post( + f"/swaps/{swap.id}/revert", data={"csrf_token": token}, follow_redirects=True + ) + + assert "Troca revertida" in response.text + db.refresh(swap) + assert swap.status == "reverted" + for shift_id, person in ((given, ana), (wanted, bruno)): + row = db.get(Assignment, shift_id) + assert row.user_id == person.id + assert row.source == "manual" + assert "Revertida a troca" in (row.note or "") + notified = db.scalars( + select(NotificationLog).where(NotificationLog.event_type == "swap_reverted") + ).all() + assert {log.user_id for log in notified} == {ana.id, bruno.id} + assert "revertida" in client.get("/swaps").text + + +def test_reverting_is_admin_only_and_only_when_it_still_applies(client, db): + _, sat, _, ana, bruno, admin = seed(db) + token = sign_in(client) + swap = _open_request(db, sat, ana, target=bruno) + given, wanted = swap.assignment_id, swap.target_assignment_id + + # Still open: nothing to revert yet. + assert client.post(f"/swaps/{swap.id}/revert", data={"csrf_token": token}).status_code == 400 + + client.post(f"/swaps/{swap.id}/approve", data={"csrf_token": token}, follow_redirects=False) + db.refresh(swap) + + # Somebody reassigned the shift after the swap: reverting would undo the wrong thing. + db.get(Assignment, wanted).user_id = admin.id + db.commit() + assert client.post(f"/swaps/{swap.id}/revert", data={"csrf_token": token}).status_code == 409 + assert db.get(Assignment, given).user_id == bruno.id + + # A member cannot revert, and a one-sided request has nothing to give back. + client.post("/logout", data={"csrf_token": token}) + bruno.username = "bruno" + bruno.password_hash = hash_password("bruno-password") + db.commit() + member_token = CSRF_RE.search(client.get("/login").text).group(1) + client.post("/login", data={"username": "bruno", "password": "bruno-password", "csrf_token": member_token}) + member_token = CSRF_RE.search(client.get("/swaps").text).group(1) + assert f'action="/swaps/{swap.id}/revert"' not in client.get("/swaps").text + assert client.post( + f"/swaps/{swap.id}/revert", data={"csrf_token": member_token} + ).status_code == 403 + + token = sign_in(client) + assert client.post(f"/swaps/{swap.id}/revert", data={"csrf_token": "invalid"}).status_code == 400 + assert client.post("/swaps/9999/revert", data={"csrf_token": token}).status_code == 404 + legacy = _open_request(db, sat, ana, two_sided=False) + client.post(f"/swaps/{legacy.id}/approve", data={"csrf_token": token, "user_id": bruno.id}, + follow_redirects=False) + db.refresh(legacy) + assert legacy.status == "approved" + assert client.post(f"/swaps/{legacy.id}/revert", data={"csrf_token": token}).status_code == 404 diff --git a/tests/test_migrations.py b/tests/test_migrations.py index db1838e..be3eec5 100644 --- a/tests/test_migrations.py +++ b/tests/test_migrations.py @@ -24,7 +24,7 @@ def test_migrations_produce_the_model_schema(tmp_path, monkeypatch): with engine.connect() as connection: head = connection.execute(text("select version_num from alembic_version")).scalar_one() - assert head == "bd2d4bb905b1" + assert head == "57f552c46f7c" def test_seeded_schedule_names_are_renamed_without_touching_custom_names(tmp_path, monkeypatch): diff --git a/tests/test_users.py b/tests/test_users.py index 72c5e6f..2cd6c63 100644 --- a/tests/test_users.py +++ b/tests/test_users.py @@ -245,7 +245,8 @@ def test_removing_a_person_clears_every_reference(client, db, admin): follow_redirects=True, ) - assert "Rota Only foi removida(o)." in response.text + assert "foi removida" not in response.text + assert "Rota Only" not in response.text assert db.get(User, person.id) is None db.refresh(log) assert log.user_id is None