feat: add method to reset assignments
This commit is contained in:
1 parent
1d82097af1
commit
0ef61b3231
6 files changed
+530
-4
No files matched your search
+3
-2
@@ -98,7 +98,8 @@ def pattern_user_for_date(db: Session, schedule: Schedule, target: date) -> User
|
||||
return row.user
|
||||
|
||||
|
||||
def _pattern_users(db: Session, schedule: Schedule) -> dict[int, int]:
|
||||
def pattern_users(db: Session, schedule: Schedule) -> dict[int, int]:
|
||||
"""Active person per calendar day of the month, for a `fixed` schedule."""
|
||||
rows = db.scalars(
|
||||
select(MonthlyPattern)
|
||||
.where(MonthlyPattern.schedule_id == schedule.id)
|
||||
@@ -117,7 +118,7 @@ def ensure_month_assignments(db: Session, year: int, month: int) -> list[Assignm
|
||||
|
||||
changed = False
|
||||
for schedule in schedules:
|
||||
patterns = _pattern_users(db, schedule) if schedule.schedule_type == "fixed" else {}
|
||||
patterns = pattern_users(db, schedule) if schedule.schedule_type == "fixed" else {}
|
||||
for day in iter_month_dates(year, month):
|
||||
if day.weekday() not in schedule.weekday_set:
|
||||
continue
|
||||
|
||||
@@ -39,6 +39,15 @@
|
||||
<button class="secondary" type="submit">Gerar depois da data</button>
|
||||
</form>
|
||||
<p class="muted">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.</p>
|
||||
<form method="post" action="{{ app_path('/admin/schedules/' ~ schedule.id ~ '/clear-from') }}" class="inline-form">
|
||||
<input type="hidden" name="csrf_token" value="{{ csrf_token }}">
|
||||
<label>Limpar a partir de<select name="month">
|
||||
{% for name in months %}<option value="{{ loop.index }}" {% if loop.index == month %}selected{% endif %}>{{ name }}</option>{% endfor %}
|
||||
</select></label>
|
||||
<label>de<input type="number" name="year" value="{{ year }}" min="2000" max="2100" required></label>
|
||||
<button class="danger" type="submit">Limpar mês e seguintes</button>
|
||||
</form>
|
||||
<p class="muted">Deixa sem atribuição os turnos <strong>automáticos</strong> 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.</p>
|
||||
<form method="post" action="{{ app_path('/admin/schedules/' ~ schedule.id ~ '/assignments') }}">
|
||||
<input type="hidden" name="csrf_token" value="{{ csrf_token }}">
|
||||
<input type="hidden" name="year" value="{{ year }}"><input type="hidden" name="month" value="{{ month }}">
|
||||
@@ -97,6 +106,15 @@
|
||||
</div>
|
||||
<div class="sticky-actions"><button class="primary" type="submit">Guardar padrão</button></div>
|
||||
</form>
|
||||
<form method="post" action="{{ app_path('/admin/schedules/' ~ schedule.id ~ '/apply-pattern') }}" class="inline-form">
|
||||
<input type="hidden" name="csrf_token" value="{{ csrf_token }}">
|
||||
<label>A partir de<select name="month">
|
||||
{% for name in months %}<option value="{{ loop.index }}" {% if loop.index == month %}selected{% endif %}>{{ name }}</option>{% endfor %}
|
||||
</select></label>
|
||||
<label>de<input type="number" name="year" value="{{ year }}" min="2000" max="2100" required></label>
|
||||
<button class="secondary" type="submit">Aplicar padrão a partir do mês escolhido</button>
|
||||
</form>
|
||||
<p class="muted">Atualiza os turnos <strong>automáticos</strong> 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.</p>
|
||||
</section>
|
||||
{% endif %}
|
||||
|
||||
|
||||
+141
-1
@@ -23,6 +23,7 @@ from .models import (
|
||||
User,
|
||||
)
|
||||
from .i18n import (
|
||||
MONTHS,
|
||||
day_numeric,
|
||||
day_numeric_long,
|
||||
day_short,
|
||||
@@ -31,7 +32,13 @@ from .i18n import (
|
||||
window_label,
|
||||
)
|
||||
from .notifications import send_email_notification, send_many
|
||||
from .scheduling import assignments_by_date, ensure_month_assignments, month_bounds, rotation_user_for_date
|
||||
from .scheduling import (
|
||||
assignments_by_date,
|
||||
ensure_month_assignments,
|
||||
month_bounds,
|
||||
pattern_users,
|
||||
rotation_user_for_date,
|
||||
)
|
||||
from .security import hash_password, new_csrf_token, verify_password
|
||||
|
||||
router = APIRouter()
|
||||
@@ -1307,6 +1314,7 @@ def admin_schedule(
|
||||
swap_requests=_open_swap_requests(db, schedule.id),
|
||||
pattern_days=list(range(1, 32)),
|
||||
pattern=_pattern_map(db, schedule),
|
||||
months=MONTHS,
|
||||
year=year,
|
||||
month=month,
|
||||
month_name=month_name(month),
|
||||
@@ -1422,6 +1430,138 @@ def _apply_pattern_to_open_rows(db: Session, schedule: Schedule) -> int:
|
||||
return touched
|
||||
|
||||
|
||||
def _apply_pattern_forward(db: Session, schedule: Schedule, first: date) -> int:
|
||||
"""Explicit admin edit: push the monthly pattern onto generated assignments from `first` on.
|
||||
|
||||
Never creates or deletes rows, keeps assignment IDs, and preserves manual
|
||||
assignments and completed swaps. A day with nobody in the pattern is left as
|
||||
it is, so an empty pattern entry cannot blank out a shift.
|
||||
"""
|
||||
patterns = pattern_users(db, schedule)
|
||||
if not patterns:
|
||||
return 0
|
||||
rows = db.scalars(
|
||||
select(Assignment)
|
||||
.where(
|
||||
Assignment.schedule_id == schedule.id,
|
||||
Assignment.date >= first,
|
||||
Assignment.source == "generated",
|
||||
)
|
||||
.options(selectinload(Assignment.user), selectinload(Assignment.schedule))
|
||||
.order_by(Assignment.date)
|
||||
).all()
|
||||
changed: list[tuple[Assignment, User | None, User | None]] = []
|
||||
touched = 0
|
||||
for row in rows:
|
||||
user_id = patterns.get(row.date.day)
|
||||
if user_id is None or row.user_id == user_id:
|
||||
continue
|
||||
old_user = db.get(User, row.user_id) if row.user_id is not None else None
|
||||
new_user = db.get(User, user_id)
|
||||
changed.append((row, old_user, new_user))
|
||||
for swap in db.scalars(
|
||||
select(SwapRequest).where(
|
||||
SwapRequest.assignment_id == row.id,
|
||||
SwapRequest.status.in_(["open", "pending_approval"]),
|
||||
)
|
||||
).all():
|
||||
swap.status = "cancelled"
|
||||
row.user_id = user_id
|
||||
row.user = new_user
|
||||
touched += 1
|
||||
if changed:
|
||||
db.commit()
|
||||
_notify_assignment_changes(db, changed)
|
||||
return touched
|
||||
|
||||
|
||||
@router.post("/admin/schedules/{schedule_id}/apply-pattern")
|
||||
def admin_apply_pattern(
|
||||
schedule_id: int,
|
||||
request: Request,
|
||||
year: int = Form(...),
|
||||
month: int = 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 != "fixed":
|
||||
raise HTTPException(status_code=400, detail="Esta escala não usa um padrão mensal")
|
||||
year, month = _parse_month(year, month)
|
||||
first = date(year, month, 1)
|
||||
touched = _apply_pattern_forward(db, schedule, first)
|
||||
_flash(
|
||||
request,
|
||||
f"Padrão aplicado a partir de {day_numeric_long(first)}: {touched} turno(s) atualizado(s). "
|
||||
f"As atribuições manuais e as trocas foram mantidas, e os dias sem pessoa no padrão ficaram como estão.",
|
||||
)
|
||||
return _redirect(f"/admin/schedules/{schedule.id}")
|
||||
|
||||
|
||||
def _clear_assignments_from(db: Session, schedule: Schedule, first: date) -> int:
|
||||
"""Explicit admin edit: leave the shifts from `first` on without an assignee.
|
||||
|
||||
Only `generated` rows are touched, so manual assignments and completed swaps
|
||||
survive. Rows keep their IDs, notes and swap history and stay `generated`, so
|
||||
applying the rotation again fills them.
|
||||
"""
|
||||
rows = db.scalars(
|
||||
select(Assignment)
|
||||
.where(
|
||||
Assignment.schedule_id == schedule.id,
|
||||
Assignment.date >= first,
|
||||
Assignment.source == "generated",
|
||||
Assignment.user_id.is_not(None),
|
||||
)
|
||||
.options(selectinload(Assignment.user), selectinload(Assignment.schedule))
|
||||
.order_by(Assignment.date)
|
||||
).all()
|
||||
changed: list[tuple[Assignment, User | None, User | None]] = []
|
||||
for row in rows:
|
||||
old_user = db.get(User, row.user_id)
|
||||
changed.append((row, old_user, None))
|
||||
for swap in db.scalars(
|
||||
select(SwapRequest).where(
|
||||
SwapRequest.assignment_id == row.id,
|
||||
SwapRequest.status.in_(["open", "pending_approval"]),
|
||||
)
|
||||
).all():
|
||||
swap.status = "cancelled"
|
||||
row.user_id = None
|
||||
row.user = None
|
||||
if changed:
|
||||
db.commit()
|
||||
_notify_assignment_changes(db, changed)
|
||||
return len(changed)
|
||||
|
||||
|
||||
@router.post("/admin/schedules/{schedule_id}/clear-from")
|
||||
def admin_clear_from(
|
||||
schedule_id: int,
|
||||
request: Request,
|
||||
year: int = Form(...),
|
||||
month: int = 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")
|
||||
year, month = _parse_month(year, month)
|
||||
first = date(year, month, 1)
|
||||
cleared = _clear_assignments_from(db, schedule, first)
|
||||
_flash(
|
||||
request,
|
||||
f"Turnos limpos a partir de {day_numeric_long(first)}: {cleared} turno(s) sem atribuição. "
|
||||
f"As atribuições manuais e as trocas foram mantidas. Use Aplicar rotação para os preencher de novo.",
|
||||
)
|
||||
return _redirect(f"/admin/schedules/{schedule.id}?year={year}&month={month}")
|
||||
|
||||
|
||||
@router.post("/admin/schedules/{schedule_id}/settings")
|
||||
def admin_schedule_settings(
|
||||
schedule_id: int,
|
||||
|
||||
@@ -32,6 +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/<night id>`. 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`)
|
||||
|
||||
@@ -64,6 +65,8 @@ Every assignment on a lunch schedule page has a **Regenerate** button. An admini
|
||||
|
||||
**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.
|
||||
|
||||
## People and logins
|
||||
|
||||
- `email` and `phone` are optional.
|
||||
|
||||
@@ -11,7 +11,7 @@ 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.scheduling import ensure_month_assignments, iter_month_dates
|
||||
from app.security import hash_password
|
||||
|
||||
CSRF_RE = re.compile(r'name="csrf_token" value="([^"]+)"')
|
||||
@@ -240,6 +240,369 @@ def test_saving_the_pattern_leaves_assigned_nights_alone(client, db):
|
||||
assert assignment_on(db, night, date.today()).user_id == bruno.id
|
||||
|
||||
|
||||
def apply_pattern(client: TestClient, db, schedule: Schedule, year: int, month: int):
|
||||
token = CSRF_RE.search(client.get(f"/admin/schedules/{schedule.id}").text).group(1)
|
||||
return client.post(
|
||||
f"/admin/schedules/{schedule.id}/apply-pattern",
|
||||
data={"csrf_token": token, "year": year, "month": month},
|
||||
follow_redirects=False,
|
||||
)
|
||||
|
||||
|
||||
def test_applying_the_pattern_forward_rewrites_generated_nights(client, db):
|
||||
night, _, _, ana, bruno, _ = seed(db)
|
||||
sign_in(client)
|
||||
# Nights already exist and were generated from the old pattern.
|
||||
db.add_all(
|
||||
[
|
||||
MonthlyPattern(schedule_id=night.id, day_of_month=3, user_id=ana.id),
|
||||
MonthlyPattern(schedule_id=night.id, day_of_month=4, user_id=ana.id),
|
||||
]
|
||||
)
|
||||
db.commit()
|
||||
ensure_month_assignments(db, 2026, 11)
|
||||
ensure_month_assignments(db, 2026, 12)
|
||||
db.expire_all()
|
||||
assert assignment_on(db, night, date(2026, 11, 3)).user_id == ana.id
|
||||
|
||||
# The administrator corrects the pattern: the 3rd now belongs to Bruno.
|
||||
row = db.scalar(
|
||||
select(MonthlyPattern).where(
|
||||
MonthlyPattern.schedule_id == night.id, MonthlyPattern.day_of_month == 3
|
||||
)
|
||||
)
|
||||
row.user_id = bruno.id
|
||||
db.commit()
|
||||
|
||||
response = apply_pattern(client, db, night, 2026, 11)
|
||||
|
||||
assert response.status_code == 303
|
||||
assert response.headers["location"] == f"/admin/schedules/{night.id}"
|
||||
db.expire_all()
|
||||
# Every following month follows the corrected pattern, not just this one.
|
||||
assert assignment_on(db, night, date(2026, 11, 3)).user_id == bruno.id
|
||||
assert assignment_on(db, night, date(2026, 12, 3)).user_id == bruno.id
|
||||
# A day the administrator did not touch is left as it was.
|
||||
assert assignment_on(db, night, date(2026, 12, 4)).user_id == ana.id
|
||||
|
||||
|
||||
def test_applying_the_pattern_forward_keeps_manual_and_swap_nights(client, db):
|
||||
night, _, _, ana, bruno, _ = seed(db)
|
||||
sign_in(client)
|
||||
db.add(MonthlyPattern(schedule_id=night.id, day_of_month=3, user_id=ana.id))
|
||||
db.add(MonthlyPattern(schedule_id=night.id, day_of_month=4, user_id=ana.id))
|
||||
db.commit()
|
||||
ensure_month_assignments(db, 2026, 11)
|
||||
db.expire_all()
|
||||
|
||||
manual = assignment_on(db, night, date(2026, 11, 3))
|
||||
manual.user_id = bruno.id
|
||||
manual.source = "manual"
|
||||
swapped = assignment_on(db, night, date(2026, 11, 4))
|
||||
swapped.user_id = bruno.id
|
||||
swapped.source = "swap"
|
||||
generated_id = assignment_on(db, night, date(2026, 11, 5)).id
|
||||
db.commit()
|
||||
|
||||
apply_pattern(client, db, night, 2026, 11)
|
||||
|
||||
db.expire_all()
|
||||
assert assignment_on(db, night, date(2026, 11, 3)).user_id == bruno.id
|
||||
assert assignment_on(db, night, date(2026, 11, 3)).source == "manual"
|
||||
assert assignment_on(db, night, date(2026, 11, 4)).user_id == bruno.id
|
||||
assert assignment_on(db, night, date(2026, 11, 4)).source == "swap"
|
||||
# Unrelated generated rows keep their identity and stay unassigned.
|
||||
assert assignment_on(db, night, date(2026, 11, 5)).id == generated_id
|
||||
assert assignment_on(db, night, date(2026, 11, 5)).user_id is None
|
||||
|
||||
|
||||
def test_applying_the_pattern_forward_never_creates_nights(client, db):
|
||||
night, _, _, ana, _, _ = seed(db)
|
||||
sign_in(client)
|
||||
db.add(MonthlyPattern(schedule_id=night.id, day_of_month=3, user_id=ana.id))
|
||||
db.commit()
|
||||
ensure_month_assignments(db, 2026, 11)
|
||||
|
||||
apply_pattern(client, db, night, 2026, 11)
|
||||
|
||||
db.expire_all()
|
||||
assert db.scalar(
|
||||
select(Assignment).where(
|
||||
Assignment.schedule_id == night.id, Assignment.date == date(2026, 12, 3)
|
||||
)
|
||||
) is None
|
||||
|
||||
|
||||
def test_applying_the_pattern_forward_leaves_empty_pattern_days_alone(client, db):
|
||||
night, _, _, ana, bruno, _ = seed(db)
|
||||
sign_in(client)
|
||||
db.add(MonthlyPattern(schedule_id=night.id, day_of_month=3, user_id=ana.id))
|
||||
db.commit()
|
||||
ensure_month_assignments(db, 2026, 11)
|
||||
db.expire_all()
|
||||
untargeted = assignment_on(db, night, date(2026, 11, 6))
|
||||
untargeted.user_id = bruno.id
|
||||
db.commit()
|
||||
|
||||
apply_pattern(client, db, night, 2026, 11)
|
||||
|
||||
db.expire_all()
|
||||
# Day 6 has nobody in the pattern, so the person already there stays.
|
||||
assert assignment_on(db, night, date(2026, 11, 6)).user_id == bruno.id
|
||||
|
||||
|
||||
def test_applying_the_pattern_forward_cancels_open_requests_on_changed_nights(client, db):
|
||||
night, _, _, ana, bruno, _ = seed(db)
|
||||
sign_in(client)
|
||||
db.add(MonthlyPattern(schedule_id=night.id, day_of_month=3, user_id=ana.id))
|
||||
db.commit()
|
||||
ensure_month_assignments(db, 2026, 11)
|
||||
db.expire_all()
|
||||
changed = assignment_on(db, night, date(2026, 11, 3))
|
||||
untouched = assignment_on(db, night, date(2026, 11, 7))
|
||||
changed.user_id = bruno.id
|
||||
db.commit()
|
||||
on_changed = SwapRequest(
|
||||
assignment_id=changed.id, requester_id=bruno.id, target_user_id=ana.id, status="open"
|
||||
)
|
||||
on_untouched = SwapRequest(
|
||||
assignment_id=untouched.id, requester_id=bruno.id, target_user_id=ana.id, status="open"
|
||||
)
|
||||
db.add_all([on_changed, on_untouched])
|
||||
db.commit()
|
||||
changed_id, untouched_id = on_changed.id, on_untouched.id
|
||||
|
||||
apply_pattern(client, db, night, 2026, 11)
|
||||
|
||||
db.expire_all()
|
||||
assert db.get(SwapRequest, changed_id).status == "cancelled"
|
||||
assert db.get(SwapRequest, untouched_id).status == "open"
|
||||
|
||||
|
||||
def test_applying_the_pattern_forward_only_covers_the_selected_month_onwards(client, db):
|
||||
night, _, _, ana, bruno, _ = seed(db)
|
||||
sign_in(client)
|
||||
db.add(MonthlyPattern(schedule_id=night.id, day_of_month=3, user_id=ana.id))
|
||||
db.commit()
|
||||
ensure_month_assignments(db, 2026, 10)
|
||||
ensure_month_assignments(db, 2026, 11)
|
||||
ensure_month_assignments(db, 2026, 12)
|
||||
db.expire_all()
|
||||
for month in (10, 11, 12):
|
||||
row = assignment_on(db, night, date(2026, month, 3))
|
||||
row.user_id = bruno.id
|
||||
db.commit()
|
||||
row = db.scalar(
|
||||
select(MonthlyPattern).where(
|
||||
MonthlyPattern.schedule_id == night.id, MonthlyPattern.day_of_month == 3
|
||||
)
|
||||
)
|
||||
row.user_id = ana.id
|
||||
db.commit()
|
||||
|
||||
apply_pattern(client, db, night, 2026, 11)
|
||||
|
||||
db.expire_all()
|
||||
# October is history and is not touched.
|
||||
assert assignment_on(db, night, date(2026, 10, 3)).user_id == bruno.id
|
||||
assert assignment_on(db, night, date(2026, 11, 3)).user_id == ana.id
|
||||
assert assignment_on(db, night, date(2026, 12, 3)).user_id == ana.id
|
||||
|
||||
|
||||
def test_applying_the_pattern_is_refused_on_a_rotation(client, db):
|
||||
night, sat, _, _, _, _ = seed(db)
|
||||
sign_in(client)
|
||||
before = {
|
||||
row.id: row.user_id
|
||||
for row in db.scalars(select(Assignment).where(Assignment.schedule_id == sat.id)).all()
|
||||
}
|
||||
|
||||
response = apply_pattern(client, db, sat, 2026, 11)
|
||||
|
||||
assert response.status_code == 400
|
||||
db.expire_all()
|
||||
after = {
|
||||
row.id: row.user_id
|
||||
for row in db.scalars(select(Assignment).where(Assignment.schedule_id == sat.id)).all()
|
||||
}
|
||||
assert after == before
|
||||
|
||||
|
||||
def test_applying_the_pattern_requires_an_admin(client, db):
|
||||
night, _, _, ana, _, _ = seed(db)
|
||||
ensure_month_assignments(db, 2026, 11)
|
||||
db.add(MonthlyPattern(schedule_id=night.id, day_of_month=3, user_id=ana.id))
|
||||
db.commit()
|
||||
|
||||
response = client.post(
|
||||
f"/admin/schedules/{night.id}/apply-pattern",
|
||||
data={"csrf_token": "anything", "year": 2026, "month": 11},
|
||||
follow_redirects=False,
|
||||
)
|
||||
|
||||
assert response.status_code == 401
|
||||
db.expire_all()
|
||||
assert assignment_on(db, night, date(2026, 11, 3)).user_id is None
|
||||
|
||||
|
||||
def clear_from(client: TestClient, db, schedule: Schedule, year: int, month: int):
|
||||
token = CSRF_RE.search(client.get(f"/admin/schedules/{schedule.id}").text).group(1)
|
||||
return client.post(
|
||||
f"/admin/schedules/{schedule.id}/clear-from",
|
||||
data={"csrf_token": token, "year": year, "month": month},
|
||||
follow_redirects=False,
|
||||
)
|
||||
|
||||
|
||||
def test_clearing_a_month_empties_that_month_and_the_ones_after(client, db):
|
||||
night, sat, _, ana, bruno, _ = seed(db)
|
||||
sign_in(client)
|
||||
ensure_month_assignments(db, 2026, 10)
|
||||
ensure_month_assignments(db, 2026, 11)
|
||||
ensure_month_assignments(db, 2026, 12)
|
||||
db.expire_all()
|
||||
before = {
|
||||
row.date: (row.id, row.user_id)
|
||||
for row in db.scalars(
|
||||
select(Assignment).where(Assignment.schedule_id == sat.id, Assignment.user_id.is_not(None))
|
||||
).all()
|
||||
}
|
||||
assert before[date(2026, 11, 7)][1] in (ana.id, bruno.id)
|
||||
|
||||
response = clear_from(client, db, sat, 2026, 11)
|
||||
|
||||
assert response.status_code == 303
|
||||
assert response.headers["location"] == f"/admin/schedules/{sat.id}?year=2026&month=11"
|
||||
db.expire_all()
|
||||
# October is untouched.
|
||||
assert assignment_on(db, sat, date(2026, 10, 3)).user_id == before[date(2026, 10, 3)][1]
|
||||
# November and December are emptied but the rows themselves survive.
|
||||
for month in (11, 12):
|
||||
for day in [d for d in iter_month_dates(2026, month) if d.weekday() == 5]:
|
||||
row = assignment_on(db, sat, day)
|
||||
assert row.user_id is None
|
||||
assert row.source == "generated"
|
||||
assert row.id == before[day][0]
|
||||
|
||||
|
||||
def test_clearing_keeps_manual_and_swapped_shifts(client, db):
|
||||
night, sat, _, ana, bruno, _ = seed(db)
|
||||
sign_in(client)
|
||||
ensure_month_assignments(db, 2026, 11)
|
||||
db.expire_all()
|
||||
manual = assignment_on(db, sat, date(2026, 11, 7))
|
||||
manual.user_id = ana.id
|
||||
manual.source = "manual"
|
||||
swapped = assignment_on(db, sat, date(2026, 11, 14))
|
||||
swapped.user_id = bruno.id
|
||||
swapped.source = "swap"
|
||||
db.commit()
|
||||
|
||||
clear_from(client, db, sat, 2026, 11)
|
||||
|
||||
db.expire_all()
|
||||
assert assignment_on(db, sat, date(2026, 11, 7)).user_id == ana.id
|
||||
assert assignment_on(db, sat, date(2026, 11, 7)).source == "manual"
|
||||
assert assignment_on(db, sat, date(2026, 11, 14)).user_id == bruno.id
|
||||
assert assignment_on(db, sat, date(2026, 11, 14)).source == "swap"
|
||||
# The automatic ones around them are gone.
|
||||
assert assignment_on(db, sat, date(2026, 11, 21)).user_id is None
|
||||
assert assignment_on(db, sat, date(2026, 11, 28)).user_id is None
|
||||
|
||||
|
||||
def test_applying_the_rotation_fills_cleared_shifts_again(client, db):
|
||||
night, sat, _, ana, bruno, _ = seed(db)
|
||||
sign_in(client)
|
||||
ensure_month_assignments(db, 2026, 11)
|
||||
db.expire_all()
|
||||
ids = {
|
||||
row.date: row.id
|
||||
for row in db.scalars(select(Assignment).where(Assignment.schedule_id == sat.id)).all()
|
||||
}
|
||||
|
||||
clear_from(client, db, sat, 2026, 11)
|
||||
token = CSRF_RE.search(client.get(f"/admin/schedules/{sat.id}?year=2026&month=11").text).group(1)
|
||||
client.post(
|
||||
f"/admin/schedules/{sat.id}/apply-rotation",
|
||||
data={"csrf_token": token, "year": 2026, "month": 11},
|
||||
follow_redirects=False,
|
||||
)
|
||||
|
||||
db.expire_all()
|
||||
for day in (7, 14, 21, 28):
|
||||
row = assignment_on(db, sat, date(2026, 11, day))
|
||||
assert row.user_id in (ana.id, bruno.id)
|
||||
# Same rows, not new ones.
|
||||
assert row.id == ids[date(2026, 11, day)]
|
||||
|
||||
|
||||
def test_clearing_cancels_open_requests_on_the_shifts_it_empties(client, db):
|
||||
night, sat, _, ana, bruno, _ = seed(db)
|
||||
sign_in(client)
|
||||
ensure_month_assignments(db, 2026, 11)
|
||||
db.expire_all()
|
||||
emptied = assignment_on(db, sat, date(2026, 11, 7))
|
||||
untouched = assignment_on(db, sat, date(2026, 10, 3))
|
||||
on_emptied = SwapRequest(assignment_id=emptied.id, requester_id=ana.id, status="open")
|
||||
on_untouched = SwapRequest(assignment_id=untouched.id, requester_id=ana.id, status="open")
|
||||
db.add_all([on_emptied, on_untouched])
|
||||
db.commit()
|
||||
emptied_id, untouched_id = on_emptied.id, on_untouched.id
|
||||
|
||||
clear_from(client, db, sat, 2026, 11)
|
||||
|
||||
db.expire_all()
|
||||
assert db.get(SwapRequest, emptied_id).status == "cancelled"
|
||||
assert db.get(SwapRequest, untouched_id).status == "open"
|
||||
|
||||
|
||||
def test_clearing_is_refused_on_the_night_schedule(client, db):
|
||||
night, sat, _, ana, _, _ = seed(db)
|
||||
sign_in(client)
|
||||
db.add(MonthlyPattern(schedule_id=night.id, day_of_month=3, user_id=ana.id))
|
||||
db.commit()
|
||||
ensure_month_assignments(db, 2026, 11)
|
||||
db.expire_all()
|
||||
before = {
|
||||
row.date: row.user_id
|
||||
for row in db.scalars(select(Assignment).where(Assignment.schedule_id == night.id)).all()
|
||||
}
|
||||
|
||||
response = clear_from(client, db, night, 2026, 11)
|
||||
|
||||
assert response.status_code == 400
|
||||
db.expire_all()
|
||||
after = {
|
||||
row.date: row.user_id
|
||||
for row in db.scalars(select(Assignment).where(Assignment.schedule_id == night.id)).all()
|
||||
}
|
||||
assert after == before
|
||||
|
||||
|
||||
def test_clearing_requires_an_admin(client, db):
|
||||
night, sat, _, _, _, _ = seed(db)
|
||||
ensure_month_assignments(db, 2026, 11)
|
||||
db.expire_all()
|
||||
before = {
|
||||
row.date: row.user_id
|
||||
for row in db.scalars(select(Assignment).where(Assignment.schedule_id == sat.id)).all()
|
||||
}
|
||||
|
||||
response = client.post(
|
||||
f"/admin/schedules/{sat.id}/clear-from",
|
||||
data={"csrf_token": "anything", "year": 2026, "month": 11},
|
||||
follow_redirects=False,
|
||||
)
|
||||
|
||||
assert response.status_code == 401
|
||||
db.expire_all()
|
||||
after = {
|
||||
row.date: row.user_id
|
||||
for row in db.scalars(select(Assignment).where(Assignment.schedule_id == sat.id)).all()
|
||||
}
|
||||
assert after == before
|
||||
|
||||
|
||||
def test_saturday_page_only_shows_saturdays(client, db):
|
||||
_, sat, _, _, _, _ = seed(db)
|
||||
sign_in(client)
|
||||
|
||||
@@ -3,6 +3,7 @@ from datetime import date, time, timedelta
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.calendar import build_feed
|
||||
from app.config import settings
|
||||
from app.models import Assignment, Schedule, User
|
||||
# the fixtures live next door and are shared by importing them here
|
||||
from app.security import hash_password
|
||||
|
||||
Reference in new issue
Block a user