diff --git a/app/templates/admin_schedule.html b/app/templates/admin_schedule.html index 4f030d1..7aa5f92 100644 --- a/app/templates/admin_schedule.html +++ b/app/templates/admin_schedule.html @@ -31,23 +31,16 @@ -

Cada turno automático é dado à próxima pessoa ativa a seguir à responsável pelo turno anterior desta escala, com retorno ao início da rotação. Aplicar a rotação mantém as atribuições manuais e as trocas concluídas. Recalcular substitui a atribuição de uma data, incluindo uma atribuição manual ou uma troca. Uma rotação vazia deixa os turnos automáticos sem atribuição.

-
- - - - -
-

Cria os turnos em falta e atualiza as atribuições automáticas depois da data de referência, até à data final (inclusive). As atribuições manuais e as trocas concluídas são mantidas e usadas como referência.

+
- - +
-

Deixa sem atribuição os turnos automáticos a partir do início do mês e ano escolhidos, nesse mês e em todos os seguintes. Nenhum turno é apagado e as atribuições manuais e as trocas concluídas são mantidas. Use-o antes de aplicar a rotação de novo, para recalcular tudo a partir de um ponto.

+

Deixa sem atribuição os turnos automáticos do mês e ano escolhidos e de todos os seguintes. Nenhum turno é apagado e as atribuições manuais e as trocas concluídas são mantidas. Use Limpar turnos antes de Aplicar rotação, para recalcular tudo a partir de um ponto.

@@ -112,9 +105,9 @@ {% for name in months %}{% endfor %} - +
-

Atualiza os turnos automáticos já existentes a partir do início do mês e ano escolhidos, em todos os meses seguintes, para refletirem o padrão acima. Use isto depois de corrigir o padrão. As atribuições manuais e as trocas concluídas são mantidas, os dias sem pessoa no padrão ficam como estão e nenhum turno é criado.

+

Atualiza os turnos automáticos já existentes do mês e ano escolhidos e de todos os seguintes, para refletirem o padrão guardado acima. As atribuições manuais e as trocas concluídas são mantidas, os dias sem pessoa no padrão ficam como estão e nenhum turno é criado.

{% endif %} diff --git a/app/templates/admin_schedules.html b/app/templates/admin_schedules.html index e303327..7458f78 100644 --- a/app/templates/admin_schedules.html +++ b/app/templates/admin_schedules.html @@ -7,12 +7,6 @@ Atribuir por dia -
-

Calendário da rota

-

Um link para partilhar com a equipa, com os turnos de toda a gente, para adicionar a qualquer calendário. Cada pessoa tem também o seu feed só com os turnos dela.

-

{{ calendar_feed_url }}

- Subscrever o calendário do bar -
{% for card in cards %} {% set schedule = card.schedule %} diff --git a/app/web.py b/app/web.py index b40e256..28c5341 100644 --- a/app/web.py +++ b/app/web.py @@ -1320,8 +1320,6 @@ def admin_schedule( month_name=month_name(month), prev=prev, nxt=nxt, - generate_after=date(year, month, 1) - timedelta(days=1), - generate_through=month_bounds(year, month)[1], ), ) @@ -1936,30 +1934,6 @@ def admin_apply_rotation( return _redirect(f"/admin/schedules/{schedule.id}?year={year}&month={month}") -@router.post("/admin/schedules/{schedule_id}/generate-after") -def admin_generate_after( - schedule_id: int, - request: Request, - after_date: date = Form(...), - through_date: date = Form(...), - csrf_token: str = Form(...), - db: Session = Depends(get_db), -): - _require_admin(request, db) - _check_csrf(request, csrf_token) - schedule = _get_schedule(db, schedule_id) - if schedule.schedule_type != "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="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"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}") - - @router.post("/admin/schedules/{schedule_id}/assignments/{assignment_id}/regenerate") @router.post("/admin/schedules/{schedule_id}/assignments/{assignment_id}/use-rotation") def admin_assignment_regenerate( diff --git a/docs/DOMAIN.md b/docs/DOMAIN.md index 806f849..7168590 100644 --- a/docs/DOMAIN.md +++ b/docs/DOMAIN.md @@ -32,7 +32,7 @@ Every start copies the SQLite file aside before anything else runs, using SQLite - Generation fills a missing assignment with the person configured for that day of the month. Days 29 to 31 only apply to months that have them. - 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. -- An administrator can explicitly **Apply pattern from** a chosen month and year on `/admin/schedules/`. It rewrites every existing `generated` night from the first day of that month onwards, in that month and every later one, to match the current pattern. It is the explicit way to push a corrected pattern onto shifts that already have a person. Assignment IDs, notes and completed request history are kept, `manual` assignments and completed swaps are preserved, days with nobody in the pattern are left as they are, and no assignment is ever created. Open and pending change requests on a rewritten shift are cancelled and the new and previous people are notified. +- An administrator can explicitly **Aplicar padrão** from a chosen month and year on `/admin/schedules/`. It rewrites every existing `generated` night from the first day of that month onwards, in that month and every later one, to match the current pattern. It is the explicit way to push a corrected pattern onto shifts that already have a person. Assignment IDs, notes and completed request history are kept, `manual` assignments and completed swaps are preserved, days with nobody in the pattern are left as they are, and no assignment is ever created. Open and pending change requests on a rewritten shift are cancelled and the new and previous people are notified. ### Saturday Lunch (`Almoço - Sábados`) @@ -63,9 +63,9 @@ An administrator can explicitly **Apply rotation** on a lunch schedule's month p Every assignment on a lunch schedule page has a **Regenerate** button. An administrator can explicitly regenerate any assignment, including an automatic assignment, manual override, or completed swap. It immediately recalculates that date from the current rotation and its source becomes `generated`; if there are no active rotation members, it becomes unassigned. These actions preserve assignment IDs, notes, and completed request history. If ownership changes, open or pending-approval change requests for the assignment are cancelled, and assignment-change notifications are attempted after saving. -**Generate after date** fills missing shifts and recalculates automatic assignments in that schedule strictly after the selected reference date, through an explicit end date (inclusive). The range can span multiple months. Assignments on or before the reference date and after the end date are not edited. Manual assignments and completed swaps within the range are preserved and supply references for later dates. The default range covers the displayed month. -**Clear month and following** empties the `generated` shifts of a lunch schedule from the first day of a chosen month and year onwards, in that month and every later one, so they read as unassigned. No shift is deleted: rows keep their IDs, notes, source and completed request history, and stay `generated`, so **Apply rotation** or **Generate after date** fills them again. Manual assignments and completed swaps are never emptied. Open and pending change requests on an emptied shift are cancelled and the previous person is notified. Use it to force a recalculation from a known point instead of relying on the shifts that already exist. + +**Limpar turnos** empties the `generated` shifts of a lunch schedule from the first day of a chosen month and year onwards, in that month and every later one, so they read as unassigned. No shift is deleted: rows keep their IDs, notes, source and completed request history, and stay `generated`, so **Aplicar rotação** fills them again. Manual assignments and completed swaps are never emptied. Open and pending change requests on an emptied shift are cancelled and the previous person is notified. Use it to force a recalculation from a known point instead of relying on the shifts that already exist. ## People and logins diff --git a/tests/test_admin_schedule_assignments.py b/tests/test_admin_schedule_assignments.py index 622e708..f314c52 100644 --- a/tests/test_admin_schedule_assignments.py +++ b/tests/test_admin_schedule_assignments.py @@ -770,9 +770,6 @@ def test_rotation_controls_render_regenerate_for_every_row_as_separate_forms(cli 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("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 "Aplicar rotação" not in client.get(f"/admin/schedules/{night.id}").text @@ -890,109 +887,6 @@ def test_regenerate_replaces_any_assignment_source_and_retains_history(client, d assert (current.user_id, current.source) == expected -def test_generate_after_date_spans_months_with_exclusive_start_and_inclusive_end(client, db): - _, sat, _, ana, bruno, admin = seed(db) - token = sign_in(client) - ensure_month_assignments(db, YEAR, MONTH) - reference = assignment_on(db, sat, date(YEAR, MONTH, 31)) - reference.user_id, reference.source = ana.id, "manual" - outdated = Assignment(schedule_id=sat.id, date=date(YEAR, 11, 7), user_id=ana.id, source="generated") - swapped = Assignment(schedule_id=sat.id, date=date(YEAR, 11, 14), user_id=bruno.id, source="swap") - later = Assignment(schedule_id=sat.id, date=date(YEAR, 11, 28), user_id=admin.id, source="generated") - db.add_all([outdated, swapped, later]) - db.flush() - stale = SwapRequest(assignment_id=outdated.id, requester_id=ana.id, status="pending_approval") - db.add(stale) - db.commit() - untouched = {row.id: (row.user_id, row.source) for row in db.scalars(select(Assignment)).all() - if row.id != outdated.id} - - response = client.post(f"/admin/schedules/{sat.id}/generate-after", data={ - "csrf_token": token, "after_date": "2026-10-31", "through_date": "2026-11-21", - }, follow_redirects=False) - assert response.status_code == 303 - assert response.headers["location"] == f"/admin/schedules/{sat.id}?year=2026&month=11" - db.expire_all() - assert (outdated.user_id, outdated.source) == (bruno.id, "generated") - generated = assignment_on(db, sat, date(YEAR, 11, 21)) - assert (generated.user_id, generated.source) == (ana.id, "generated") - assert stale.status == "cancelled" - for assignment_id, expected in untouched.items(): - row = db.get(Assignment, assignment_id) - assert (row.user_id, row.source) == expected - november = db.scalars(select(Assignment).where( - Assignment.date >= date(YEAR, 11, 1), Assignment.date <= date(YEAR, 11, 30) - )).all() - assert len(november) == 4 - assert all(row.schedule_id == sat.id for row in november) - before_repeat = [(r.id, r.user_id, r.source) for r in november] - log_count = len(db.scalars(select(NotificationLog)).all()) - client.post(f"/admin/schedules/{sat.id}/generate-after", data={ - "csrf_token": token, "after_date": "2026-10-31", "through_date": "2026-11-21", - }, follow_redirects=False) - db.expire_all() - assert [(r.id, r.user_id, r.source) for r in november] == before_repeat - assert len(db.scalars(select(NotificationLog)).all()) == log_count - - -def test_generate_after_date_fills_multiple_months_in_order(client, db): - _, sat, _, ana, bruno, _ = seed(db) - token = sign_in(client) - ensure_month_assignments(db, YEAR, MONTH) - reference = assignment_on(db, sat, date(YEAR, MONTH, 31)) - reference.user_id = bruno.id - db.commit() - response = client.post(f"/admin/schedules/{sat.id}/generate-after", data={ - "csrf_token": token, "after_date": "2026-10-31", "through_date": "2026-12-05", - }, follow_redirects=False) - assert response.status_code == 303 - rows = db.scalars(select(Assignment).where(Assignment.date > date(YEAR, MONTH, 31)).order_by(Assignment.date)).all() - assert [r.date for r in rows] == [date(YEAR, 11, day) for day in (7, 14, 21, 28)] + [date(YEAR, 12, 5)] - assert [r.user_id for r in rows] == [ana.id, bruno.id, ana.id, bruno.id, ana.id] - assert all(r.schedule_id == sat.id and r.source == "generated" for r in rows) - - -@pytest.mark.parametrize("after_date,through_date,status", [ - ("2026-10-31", "2026-10-31", 400), - ("2026-10-31", "2026-10-01", 400), - ("1999-12-30", "2026-10-31", 400), - ("2026-10-31", "2101-01-01", 400), - ("not-a-date", "2026-10-31", 422), - ("2026-10-31", "2026-11-31", 422), -]) -def test_generate_after_rejects_invalid_ranges_without_editing_data(client, db, after_date, through_date, status): - _, sat, _, _, _, _ = seed(db) - token = sign_in(client) - snapshot = [(r.id, r.user_id, r.source) for r in db.scalars(select(Assignment)).all()] - assert client.post(f"/admin/schedules/{sat.id}/generate-after", data={ - "csrf_token": token, "after_date": after_date, "through_date": through_date, - }).status_code == status - assert [(r.id, r.user_id, r.source) for r in db.scalars(select(Assignment)).all()] == snapshot - - -@pytest.mark.parametrize("action", ["regenerate", "generate-after"]) -def test_new_generation_controls_require_admin_and_csrf(client, db, action): - night, sat, _, _, _, _ = seed(db) - ensure_month_assignments(db, YEAR, MONTH) - row = assignment_on(db, sat, date(YEAR, MONTH, 3)) - member = User(name="Member", username="member", password_hash=hash_password("member-password"), is_active=True) - db.add(member) - db.commit() - url = f"/admin/schedules/{sat.id}/assignments/{row.id}/regenerate" if action == "regenerate" else ( - f"/admin/schedules/{sat.id}/generate-after" - ) - data = {"csrf_token": "invalid", "after_date": "2026-10-31", "through_date": "2026-11-21"} - assert client.post(url, data=data).status_code == 401 - token = sign_in(client) - assert client.post(url, data=data).status_code == 400 - if action == "generate-after": - assert client.post(f"/admin/schedules/{night.id}/generate-after", data={**data, "csrf_token": token}).status_code == 400 - client.post("/logout", data={"csrf_token": token}) - token = CSRF_RE.search(client.get("/login").text).group(1) - client.post("/login", data={"username": "member", "password": "member-password", "csrf_token": token}) - assert client.post(url, data={**data, "csrf_token": token}).status_code == 403 - - def upcoming_of(db, schedule: Schedule, exclude: int | None = None) -> int: row = db.scalar( select(Assignment)