diff --git a/backend/contracts/openapi.json b/backend/contracts/openapi.json index 9d63ebc9..25d176bb 100644 --- a/backend/contracts/openapi.json +++ b/backend/contracts/openapi.json @@ -572,6 +572,13 @@ ], "title": "Note" }, + "staffing": { + "items": { + "$ref": "#/components/schemas/StaffingNoteResponse" + }, + "title": "Staffing", + "type": "array" + }, "starts_on": { "format": "date", "title": "Starts On", @@ -1285,6 +1292,13 @@ "title": "Members", "type": "array" }, + "staffing": { + "items": { + "$ref": "#/components/schemas/StaffingResponse" + }, + "title": "Staffing", + "type": "array" + }, "starts_on": { "format": "date", "title": "Starts On", @@ -1303,7 +1317,8 @@ "team_has_members", "assignments", "availability", - "leaves" + "leaves", + "staffing" ], "title": "CalendarResponse", "type": "object" @@ -4426,6 +4441,84 @@ "title": "ShareSessionInfo", "type": "object" }, + "StaffingNoteResponse": { + "properties": { + "also_on_leave": { + "items": { + "type": "string" + }, + "title": "Also On Leave", + "type": "array" + }, + "available": { + "title": "Available", + "type": "integer" + }, + "needed": { + "title": "Needed", + "type": "integer" + }, + "roles": { + "items": { + "$ref": "#/components/schemas/AssignmentRole" + }, + "title": "Roles", + "type": "array" + }, + "scheduled": { + "title": "Scheduled", + "type": "boolean" + }, + "service_date": { + "format": "date", + "title": "Service Date", + "type": "string" + } + }, + "required": [ + "service_date", + "roles", + "available", + "needed", + "scheduled", + "also_on_leave" + ], + "title": "StaffingNoteResponse", + "type": "object" + }, + "StaffingResponse": { + "description": "Roles that entries leave with exactly as many people as the day needs\n(no reserve) or with fewer (they cannot be staffed).", + "properties": { + "available": { + "title": "Available", + "type": "integer" + }, + "needed": { + "title": "Needed", + "type": "integer" + }, + "roles": { + "items": { + "$ref": "#/components/schemas/AssignmentRole" + }, + "title": "Roles", + "type": "array" + }, + "service_date": { + "format": "date", + "title": "Service Date", + "type": "string" + } + }, + "required": [ + "service_date", + "roles", + "available", + "needed" + ], + "title": "StaffingResponse", + "type": "object" + }, "SwapAcknowledgementRequest": { "additionalProperties": false, "description": "The optional body of an acceptance or an approval.", diff --git a/backend/src/oncall/domain/availability/models.py b/backend/src/oncall/domain/availability/models.py index 29350aa0..c2527131 100644 --- a/backend/src/oncall/domain/availability/models.py +++ b/backend/src/oncall/domain/availability/models.py @@ -3,6 +3,7 @@ from datetime import date, datetime from oncall.domain.roster import Duty +from oncall.domain.staffing import Staffing from oncall.domain.team import Actor, Member from oncall.domain.vocabulary import AvailabilityKind @@ -135,6 +136,19 @@ class RangeSnapshot: entries: tuple[NewAvailabilityEntry, ...] +@dataclass(frozen=True) +class StaffingNote: + """A day on which the entry just saved is one of those that leave roles + with no reserve. It is told to whoever saved it; it never refuses the + entry.""" + + staffing: Staffing + #: Whether a schedule already covers the day, or the generator has yet to fill it. + scheduled: bool + #: The others counted away that day who are on leave, by name. + also_on_leave: tuple[str, ...] + + @dataclass(frozen=True) class AvailabilityDeclared: entry: AvailabilityEntry @@ -144,6 +158,7 @@ class AvailabilityDeclared: #: remove them. duty_conflicts: tuple[Duty, ...] warning: str | None + staffing: tuple[StaffingNote, ...] = () @dataclass(frozen=True) diff --git a/backend/src/oncall/domain/availability/use_cases.py b/backend/src/oncall/domain/availability/use_cases.py index e5f7a254..41ee3c4b 100644 --- a/backend/src/oncall/domain/availability/use_cases.py +++ b/backend/src/oncall/domain/availability/use_cases.py @@ -29,12 +29,14 @@ MemberRef, NewAvailabilityEntry, RangeSnapshot, + StaffingNote, ) from oncall.domain.availability.ports import AvailabilityReadPorts, AvailabilityWritePorts from oncall.domain.clock import business_today from oncall.domain.errors import NotATeamMember from oncall.domain.ports import TeamDirectory -from oncall.domain.team import Actor, Member +from oncall.domain.staffing import staffing_without_reserve +from oncall.domain.team import Actor, AvailabilityPeriod, Member from oncall.domain.vocabulary import AssignmentRole, AvailabilityKind from oncall.fairness import window from oncall.i18n import translate @@ -88,6 +90,41 @@ def _validate_range( _refuse_closed_days(starts_on, today, kind=kind, actor=actor) +async def _staffing_notes( + member: Member, + entry: NewAvailabilityEntry, + today: date, + scheduled: set[date], + team: TeamDirectory, +) -> tuple[StaffingNote, ...]: + """The days from today on which the new entry is one of those that leave + a role with no reserve.""" + absent = replace( + member, availability=(AvailabilityPeriod(entry.kind, entry.starts_on, entry.ends_on),) + ) + colleagues = await team.colleagues_of(member.id) + return tuple( + StaffingNote( + staffing=row, + scheduled=row.service_date in scheduled, + also_on_leave=tuple( + person.display_name + for person in row.away + if person != absent + and any( + item.kind == AvailabilityKind.leave + and item.starts_on <= row.service_date <= item.ends_on + for item in person.availability + ) + ), + ) + for row in staffing_without_reserve( + [absent, *colleagues], max(entry.starts_on, today), entry.ends_on + ) + if absent in row.away + ) + + async def declare_availability( declaration: AvailabilityDeclaration, ports: AvailabilityWritePorts, @@ -122,8 +159,10 @@ async def declare_availability( # A duty on a day that has passed was served: nobody can take it over any # more, so it is never a collision to announce, and a leave is refused there. duty_conflicts = [] + scheduled: set[date] = set() if declaration.kind.blocks_duty: duties = await ports.roster.duties_in_force(declaration.starts_on, declaration.ends_on) + scheduled = {duty.service_date for duty in duties.values()} held = [duty for duty in duties.values() if duty.held_by(member.id, member.display_name)] served = {duty.slot for duty in held if duty.service_date < today} if served and declaration.kind == AvailabilityKind.leave: @@ -164,6 +203,11 @@ async def declare_availability( on_behalf=on_behalf, duty_conflicts=tuple(duty_conflicts), warning=warning, + staffing=( + await _staffing_notes(member, new_entry, today, scheduled, ports.team) + if declaration.kind.blocks_duty + else () + ), ) diff --git a/backend/src/oncall/domain/calendar/models.py b/backend/src/oncall/domain/calendar/models.py index f8dd15ff..f8f8b988 100644 --- a/backend/src/oncall/domain/calendar/models.py +++ b/backend/src/oncall/domain/calendar/models.py @@ -5,6 +5,7 @@ from oncall.domain.clock import business_date from oncall.domain.roster import Duty +from oncall.domain.staffing import Staffing from oncall.domain.team import Actor, RolePeriod from oncall.domain.vocabulary import ( AvailabilityKind, @@ -177,6 +178,9 @@ class CalendarMatrix: duties: list[CalendarDuty] availability: list[MemberAvailability] leaves: list[MemberLeave] + #: The days from today on that entries leave with no reserve for a role; + #: for coordinators only, like eligibility. + staffing: list[Staffing] @dataclass(frozen=True) diff --git a/backend/src/oncall/domain/calendar/use_cases.py b/backend/src/oncall/domain/calendar/use_cases.py index cb6cd870..2bc16068 100644 --- a/backend/src/oncall/domain/calendar/use_cases.py +++ b/backend/src/oncall/domain/calendar/use_cases.py @@ -32,6 +32,8 @@ ) from oncall.domain.calendar.ports import CalendarPorts from oncall.domain.roster import Duty +from oncall.domain.staffing import staffing_without_reserve +from oncall.domain.team import AvailabilityPeriod, Member from oncall.domain.vocabulary import AssignmentRole, AvailabilityKind from oncall.workdays import polish_holiday_names, polish_holidays, polish_working_days @@ -96,8 +98,24 @@ async def delete_event(event_id: uuid.UUID, ports: CalendarPorts) -> None: await ports.events.remove(event.id) +def _rotation_member(member: CalendarMember) -> Member: + """The member as the rotation's rules read one.""" + return Member( + id=member.id, + display_name=member.display_name, + user_id=member.user_id, + active_from=member.active_from, + active_until=member.active_until, + eligibility=member.eligibility, + availability=tuple( + AvailabilityPeriod(entry.kind, entry.starts_on, entry.ends_on) + for entry in member.availability + ), + ) + + async def calendar_matrix( - audience: Audience, starts_on: date, ends_on: date, ports: CalendarPorts + audience: Audience, starts_on: date, ends_on: date, ports: CalendarPorts, *, today: date ) -> CalendarMatrix: duration = (ends_on - starts_on).days if duration < 0 or duration > MAX_RANGE_DAYS - 1: @@ -177,6 +195,11 @@ async def calendar_matrix( duties=duties, availability=availability, leaves=await _leaves(readable, in_force.values(), starts_on, ends_on, ports), + staffing=staffing_without_reserve( + map(_rotation_member, members), max(starts_on, today), ends_on + ) + if coordinates + else [], ) diff --git a/backend/src/oncall/domain/staffing.py b/backend/src/oncall/domain/staffing.py new file mode 100644 index 00000000..2db592b9 --- /dev/null +++ b/backend/src/oncall/domain/staffing.py @@ -0,0 +1,78 @@ +"""Who is left to take each role on a day, once entries that block duty are counted. + +The count a coordinator can check by hand: the people qualified for a role +who have neither "unavailable" nor leave that day, against the people the day +needs. It reads the entries only, never the schedule, so it says the same +about a day already published and a day the generator has yet to fill. +""" + +from collections.abc import Iterable +from dataclasses import dataclass +from datetime import date, timedelta + +from oncall.domain.team import Member +from oncall.domain.vocabulary import ONCALL_ROLES, AssignmentRole +from oncall.workdays import is_working_day, polish_holidays + + +@dataclass(frozen=True) +class Staffing: + """The people who can still take these roles on a day, and how many the + day needs: as many is no reserve, fewer cannot be staffed.""" + + service_date: date + roles: tuple[AssignmentRole, ...] + available: int + needed: int + #: The people qualified for the roles whose entry keeps them off duty that day. + away: tuple[Member, ...] + + @property + def short(self) -> bool: + return self.available < self.needed + + +def _counts( + members: Iterable[Member], + day: date, + role_sets: Iterable[tuple[AssignmentRole, ...]], + needed: int, +) -> list[Staffing]: + """The count for each set of roles. People eligible for none of the roles + are not counted.""" + rows = [] + for roles in role_sets: + qualified = [ + member for member in members if any(member.is_eligible(role, day) for role in roles) + ] + away = tuple(member for member in qualified if member.is_unavailable(day)) + available = len(qualified) - len(away) + rows.append(Staffing(day, roles, available, needed, away)) + return rows + + +def staffing_without_reserve( + members: Iterable[Member], starts_on: date, ends_on: date +) -> list[Staffing]: + """The days and roles of the range that entries leave with no reserve or + short of people, by day. + + A day needs one person for each on-call role and two different people for + the pair, as the generator requires; a pair with no reserve speaks for its + two roles unless exactly one of them is short, otherwise each role speaks + for itself. The 11-19 shift needs one person on a working day, who may be + on call as well. A day with everyone available has nothing to say, however + small the team.""" + people = list(members) + holidays = polish_holidays(starts_on, ends_on) + result: list[Staffing] = [] + for offset in range((ends_on - starts_on).days + 1): + day = starts_on + timedelta(days=offset) + rows = _counts(people, day, [(role,) for role in ONCALL_ROLES], 1) + [pair] = _counts(people, day, [ONCALL_ROLES], 2) + if pair.available <= pair.needed and sum(row.short for row in rows) != 1: + rows = [pair] + if is_working_day(day, holidays): + rows += _counts(people, day, [(AssignmentRole.late_shift,)], 1) + result += [row for row in rows if row.away and row.available <= row.needed] + return result diff --git a/backend/src/oncall/presentation/availability.py b/backend/src/oncall/presentation/availability.py index 12660b74..ab28e3d5 100644 --- a/backend/src/oncall/presentation/availability.py +++ b/backend/src/oncall/presentation/availability.py @@ -6,10 +6,11 @@ from pydantic import BaseModel, ConfigDict, Field, model_validator -from oncall.domain.availability.models import AvailabilityEntry +from oncall.domain.availability.models import AvailabilityEntry, StaffingNote from oncall.domain.team import Member from oncall.domain.vocabulary import AvailabilityKind from oncall.i18n import translate +from oncall.presentation.staffing import StaffingResponse class _AvailabilityRange(BaseModel): @@ -39,6 +40,13 @@ class AvailabilityRangeReplace(_AvailabilityRange): undo_id: uuid.UUID | None = None +class StaffingNoteResponse(StaffingResponse): + #: Whether a schedule already covers the day. + scheduled: bool + #: The others away that day who are on leave. + also_on_leave: list[str] + + class AvailabilityResponse(BaseModel): model_config = ConfigDict(from_attributes=True) @@ -50,10 +58,16 @@ class AvailabilityResponse(BaseModel): created_at: datetime warning: str | None = None created_by_name: str | None = None + #: The days this entry leaves a role with no reserve: a notice for whoever + #: saved it, never a refusal. + staffing: list[StaffingNoteResponse] = Field(default_factory=list) def availability_response( - entry: AvailabilityEntry, member: Member, warning: str | None = None + entry: AvailabilityEntry, + member: Member, + warning: str | None = None, + staffing: tuple[StaffingNote, ...] = (), ) -> AvailabilityResponse: """Translate a domain entry into the established HTTP representation.""" return AvailabilityResponse( @@ -65,4 +79,15 @@ def availability_response( created_at=entry.created_at, warning=warning, created_by_name=entry.filed_for(member), + staffing=[ + StaffingNoteResponse( + service_date=note.staffing.service_date, + roles=list(note.staffing.roles), + available=note.staffing.available, + needed=note.staffing.needed, + scheduled=note.scheduled, + also_on_leave=list(note.also_on_leave), + ) + for note in staffing + ], ) diff --git a/backend/src/oncall/presentation/calendar.py b/backend/src/oncall/presentation/calendar.py index a5257c08..45d2393a 100644 --- a/backend/src/oncall/presentation/calendar.py +++ b/backend/src/oncall/presentation/calendar.py @@ -8,6 +8,7 @@ from oncall.domain.calendar.models import CalendarMatrix from oncall.domain.vocabulary import AssignmentRole, AvailabilityKind, CalendarEventColor from oncall.i18n import translate +from oncall.presentation.staffing import StaffingResponse class CalendarEventRef(BaseModel): @@ -118,6 +119,7 @@ class CalendarResponse(BaseModel): assignments: list[CalendarAssignmentResponse] availability: list[CalendarAvailabilityResponse] leaves: list[CalendarLeaveResponse] + staffing: list[StaffingResponse] def calendar_response(matrix: CalendarMatrix) -> CalendarResponse: @@ -197,4 +199,5 @@ def calendar_response(matrix: CalendarMatrix) -> CalendarResponse: ) for leave in matrix.leaves ], + staffing=[StaffingResponse.model_validate(row) for row in matrix.staffing], ) diff --git a/backend/src/oncall/presentation/staffing.py b/backend/src/oncall/presentation/staffing.py new file mode 100644 index 00000000..dd0e40f2 --- /dev/null +++ b/backend/src/oncall/presentation/staffing.py @@ -0,0 +1,19 @@ +"""HTTP contract for the count of people left to take a role on a day.""" + +from datetime import date + +from pydantic import BaseModel, ConfigDict + +from oncall.domain.vocabulary import AssignmentRole + + +class StaffingResponse(BaseModel): + """Roles that entries leave with exactly as many people as the day needs + (no reserve) or with fewer (they cannot be staffed).""" + + model_config = ConfigDict(from_attributes=True) + + service_date: date + roles: list[AssignmentRole] + available: int + needed: int diff --git a/backend/src/oncall/routes/availability.py b/backend/src/oncall/routes/availability.py index fa7cc3a5..cbfad334 100644 --- a/backend/src/oncall/routes/availability.py +++ b/backend/src/oncall/routes/availability.py @@ -88,7 +88,9 @@ async def _create( ), ports, ) - return availability_response(declared.entry, declared.member, declared.warning) + return availability_response( + declared.entry, declared.member, declared.warning, declared.staffing + ) async def _replace_range( @@ -112,7 +114,9 @@ async def _replace_range( ) if declared is None: return None - return availability_response(declared.entry, declared.member, declared.warning) + return availability_response( + declared.entry, declared.member, declared.warning, declared.staffing + ) async def _undo_range( diff --git a/backend/src/oncall/routes/calendar.py b/backend/src/oncall/routes/calendar.py index 95cacb2f..c03defd3 100644 --- a/backend/src/oncall/routes/calendar.py +++ b/backend/src/oncall/routes/calendar.py @@ -14,7 +14,7 @@ from oncall.domain.calendar import errors as calendar_errors from oncall.domain.calendar import use_cases as calendar_use_cases from oncall.domain.calendar.models import CalendarEventChange, NewCalendarEvent -from oncall.domain.clock import utc_now +from oncall.domain.clock import business_today, utc_now from oncall.domain.forwarding import use_cases as forwarding_use_cases from oncall.domain.overrides import errors as override_errors from oncall.domain.overrides import use_cases as override_use_cases @@ -134,7 +134,7 @@ async def calendar_matrix( ) -> CalendarResponse: with calendar_errors_as_http(): matrix = await calendar_use_cases.calendar_matrix( - audience_of(principal), starts_on, ends_on, ports + audience_of(principal), starts_on, ends_on, ports, today=business_today() ) return calendar_response(matrix) diff --git a/backend/tests/domain/test_availability_use_cases.py b/backend/tests/domain/test_availability_use_cases.py index 4949ca04..19033408 100644 --- a/backend/tests/domain/test_availability_use_cases.py +++ b/backend/tests/domain/test_availability_use_cases.py @@ -22,8 +22,8 @@ withdraw_availability, ) from oncall.domain.errors import NotATeamMember -from oncall.domain.team import Actor -from oncall.domain.vocabulary import AssignmentRole, AvailabilityKind, UserRole +from oncall.domain.team import Actor, AvailabilityPeriod +from oncall.domain.vocabulary import ONCALL_ROLES, AssignmentRole, AvailabilityKind, UserRole from tests.domain.fakes import World, member DAY = date(2030, 3, 13) @@ -531,3 +531,92 @@ async def test_listing_resolves_whose_entries_are_read(world) -> None: ) assert result.member == world.anna assert len(result.entries) == 1 + + +def leave_of(name: str, starts_on: date, ends_on: date, kind=AvailabilityKind.leave): + return member(name, availability=[AvailabilityPeriod(kind, starts_on, ends_on)]) + + +def notes(declared) -> list[tuple]: + return [ + ( + note.staffing.service_date, + note.staffing.roles, + note.staffing.available, + note.staffing.needed, + note.scheduled, + note.also_on_leave, + ) + for note in declared.staffing + ] + + +async def test_a_leave_that_leaves_no_reserve_is_told_to_whoever_saved_it(world) -> None: + """Anna and Marek away: Ola and Piotr are the pair, with nobody to spare.""" + world.team.add(leave_of("Marek", DAY, DAY + timedelta(days=1))) + ola = world.team.add(member("Ola")) + world.team.add(member("Piotr")) + # A schedule covers the first day only; the second is the generator's still. + world.roster.assign(DAY, AssignmentRole.primary, ola) + + declared = await declare(world, own(world), OwnMember(), AvailabilityKind.leave) + + # On the third day Marek is back and three people are left. + assert notes(declared) == [ + (DAY, ONCALL_ROLES, 2, 2, True, ("Marek",)), + (DAY + timedelta(days=1), ONCALL_ROLES, 2, 2, False, ("Marek",)), + ] + assert declared.warning is None + + +async def test_a_colleague_who_is_unavailable_is_counted_but_not_named(world) -> None: + world.team.add(leave_of("Marek", DAY, DAY, AvailabilityKind.unavailable)) + world.team.add(member("Ola")) + + declared = await declare( + world, world.coordinator, MemberById(world.anna.id), AvailabilityKind.unavailable + ) + + assert notes(declared)[:2] == [ + (DAY, ONCALL_ROLES, 1, 2, False, ()), + (DAY, (AssignmentRole.late_shift,), 1, 1, False, ()), + ] + + +async def test_a_wish_leaves_everyone_available(world) -> None: + world.team.add(leave_of("Marek", DAY, DAY)) + + declared = await declare(world, own(world), OwnMember(), AvailabilityKind.prefer_not) + + assert declared.staffing == () + + +async def test_days_that_have_passed_are_not_counted(world) -> None: + world.team.add(leave_of("Marek", TODAY - timedelta(days=2), TODAY)) + + declared = await declare( + world, + world.coordinator, + MemberById(world.anna.id), + AvailabilityKind.leave, + starts_on=TODAY - timedelta(days=2), + ends_on=TODAY, + ) + + assert {note.staffing.service_date for note in declared.staffing} == {TODAY} + + +async def test_a_role_the_member_cannot_take_is_not_theirs_to_hear_about(world) -> None: + """Zofia only works the 11-19: the pair is short without her doing.""" + zofia = world.team.add(member("Zofia", roles=[AssignmentRole.late_shift])) + world.team.add(leave_of("Marek", DAY, DAY)) + + declared = await declare( + world, + Actor(zofia.user_id, "Zofia", UserRole.member), + OwnMember(), + AvailabilityKind.leave, + ends_on=DAY, + ) + + assert notes(declared) == [(DAY, (AssignmentRole.late_shift,), 1, 1, False, ("Marek",))] diff --git a/backend/tests/domain/test_staffing.py b/backend/tests/domain/test_staffing.py new file mode 100644 index 00000000..5cda6c08 --- /dev/null +++ b/backend/tests/domain/test_staffing.py @@ -0,0 +1,156 @@ +"""Who is left to take each role on a day: the count behind the overlap warning. + +Per day and role, the people qualified who have neither "unavailable" nor +leave, against the people the day needs. As many is no reserve, fewer cannot +be staffed, and a day says nothing unless an entry is what brought it there. +""" + +from datetime import date + +from oncall.domain.staffing import staffing_without_reserve +from oncall.domain.team import AvailabilityPeriod +from oncall.domain.vocabulary import ONCALL_ROLES, AssignmentRole, AvailabilityKind +from tests.domain.fakes import member + +#: A Wednesday, and the Saturday after it. +DAY = date(2030, 3, 13) +SATURDAY = date(2030, 3, 16) +PRIMARY = (AssignmentRole.primary,) +SECONDARY = (AssignmentRole.secondary,) +LATE_SHIFT = (AssignmentRole.late_shift,) + + +def on_leave(name: str, **kwargs): + return member( + name, availability=[AvailabilityPeriod(AvailabilityKind.leave, DAY, DAY)], **kwargs + ) + + +def counts(team, day: date = DAY) -> list[tuple]: + return [ + (row.roles, row.available, row.needed) for row in staffing_without_reserve(team, day, day) + ] + + +def test_a_day_with_everyone_available_says_nothing_however_small_the_team() -> None: + assert counts([member("Anna"), member("Beata")]) == [] + + +def test_two_people_left_for_the_pair_is_no_reserve() -> None: + marek = on_leave("Marek") + ola = member("Ola", unavailable=[DAY]) + + [row] = staffing_without_reserve([member("Anna"), marek, ola, member("Piotr")], DAY, DAY) + + # "Unavailable" counts like leave; two people still cover the 11-19 with one to spare. + assert (row.service_date, row.roles, row.available, row.needed) == (DAY, ONCALL_ROLES, 2, 2) + assert row.away == (marek, ola) + assert row.short is False + + +def test_one_person_left_cannot_staff_the_pair_and_is_the_last_for_the_shift() -> None: + team = [member("Anna"), on_leave("Marek"), on_leave("Ola"), on_leave("Piotr")] + + assert counts(team) == [(ONCALL_ROLES, 1, 2), (LATE_SHIFT, 1, 1)] + + +def test_nobody_left_is_two_people_short_for_the_pair() -> None: + assert counts([on_leave("Anna"), on_leave("Marek")]) == [ + (ONCALL_ROLES, 0, 2), + (LATE_SHIFT, 0, 1), + ] + + +def test_a_role_nobody_can_take_speaks_for_itself() -> None: + """Three people still cover the pair, so only PRIMARY is named.""" + team = [ + on_leave("Anna", roles=PRIMARY), + *(member(name, roles=SECONDARY) for name in ("Beata", "Celina", "Daria")), + ] + + assert counts(team) == [(PRIMARY, 0, 1)] + + +def test_the_pair_is_not_named_when_one_of_its_roles_is_worse_off() -> None: + """Two people are left for the pair, but both can only take SECONDARY.""" + team = [ + on_leave("Anna", roles=PRIMARY), + member("Beata", roles=SECONDARY), + member("Celina", roles=SECONDARY), + ] + + assert counts(team) == [(PRIMARY, 0, 1)] + + +def test_the_pair_is_not_named_when_its_other_role_is_covered() -> None: + """One person is left for the pair, and SECONDARY is not what is missing.""" + team = [on_leave("Anna", roles=PRIMARY), member("Beata", roles=SECONDARY)] + + assert counts(team) == [(PRIMARY, 0, 1)] + + +def test_a_short_role_and_one_with_no_reserve_each_speak_for_themselves() -> None: + celina = on_leave("Celina", roles=SECONDARY) + team = [ + on_leave("Anna", roles=PRIMARY), + on_leave("Beata", roles=PRIMARY), + celina, + member("Daria", roles=SECONDARY), + ] + + assert counts(team) == [(PRIMARY, 0, 1), (SECONDARY, 1, 1)] + assert [ + row.roles for row in staffing_without_reserve(team, DAY, DAY) if celina in row.away + ] == [SECONDARY] + + +def test_a_role_nobody_is_qualified_for_is_not_put_down_to_entries() -> None: + team = [on_leave("Anna", roles=SECONDARY), member("Beata", roles=SECONDARY)] + + assert counts(team) == [(SECONDARY, 1, 1)] + + +def test_the_last_person_for_one_role_is_no_reserve_for_that_role() -> None: + team = [ + on_leave("Anna", roles=PRIMARY), + member("Beata", roles=PRIMARY), + *(member(name, roles=SECONDARY) for name in ("Celina", "Daria")), + ] + + assert counts(team) == [(PRIMARY, 1, 1)] + + +def test_the_shift_is_counted_on_working_days_only_and_days_come_in_order() -> None: + team = [ + member("Anna", roles=LATE_SHIFT), + member( + "Beata", + roles=LATE_SHIFT, + availability=[AvailabilityPeriod(AvailabilityKind.leave, DAY, SATURDAY)], + ), + ] + + rows = staffing_without_reserve(team, DAY, SATURDAY) + + # Wednesday to Friday; the weekend has no 11-19. + assert [(row.service_date.day, row.roles, row.available) for row in rows] == [ + (13, LATE_SHIFT, 1), + (14, LATE_SHIFT, 1), + (15, LATE_SHIFT, 1), + ] + + +def test_a_person_qualified_for_no_role_is_not_counted() -> None: + assert counts([member("Anna"), member("Beata"), on_leave("Celina", roles=())]) == [] + + +def test_a_wish_is_not_an_absence() -> None: + wishes = [ + member(name, availability=[AvailabilityPeriod(kind, DAY, DAY)]) + for name, kind in ( + ("Anna", AvailabilityKind.prefer_not), + ("Beata", AvailabilityKind.prefer), + ) + ] + + assert counts(wishes) == [] diff --git a/backend/tests/test_staffing_reserve.py b/backend/tests/test_staffing_reserve.py new file mode 100644 index 00000000..6c3ea377 --- /dev/null +++ b/backend/tests/test_staffing_reserve.py @@ -0,0 +1,149 @@ +"""The overlap warning: roles that leave or "unavailable" leave without reserve. + +Whoever saves the entry is told in the answer, and is never refused; the +coordinators read the same count in the calendar, from today on. +""" + +from datetime import date + +import pytest +from httpx import AsyncClient +from sqlalchemy.ext.asyncio import AsyncSession + +from oncall.domain.vocabulary import AvailabilityKind, UserRole +from oncall.infrastructure.sqlalchemy.availability_model import Availability +from tests.conftest import create_member, create_published_schedule, create_user, login + +pytestmark = pytest.mark.usefixtures("frozen_clock") + +PAIR = ["primary", "secondary"] + + +async def _team(db: AsyncSession) -> None: + """Anna, Beata and the coordinator Celina take every role. Today is + Tuesday 15 September 2026; Beata is on leave from Monday to Friday, and + the schedule is published for that week.""" + for username, role in ( + ("anna", UserRole.member), + ("beata", UserRole.member), + ("celina", UserRole.coordinator), + ): + user = await create_user(db, username, role=role) + member = await create_member( + db, user, display_name=username.title(), active_from=date(2026, 1, 1) + ) + if username == "beata": + db.add( + Availability( + member_id=member.id, + kind=AvailabilityKind.leave, + starts_on=date(2026, 9, 14), + ends_on=date(2026, 9, 18), + ) + ) + await db.commit() + await create_published_schedule( + db, starts_on=date(2026, 9, 14), days=5, primary=["Celina"], secondary=["Beata"] + ) + + +def _row(day: int, roles: list[str], available: int, needed: int, **more) -> dict: + return { + "service_date": f"2026-09-{day}", + "roles": roles, + "available": available, + "needed": needed, + **more, + } + + +async def _paint(client: AsyncClient, path: str, kind: str = "leave"): + """Thursday to Monday.""" + response = await client.put( + f"/api/v1/availability/{path}/range", + json={"kind": kind, "starts_on": "2026-09-17", "ends_on": "2026-09-21"}, + ) + assert response.status_code == 200, response.text + return response.json() + + +async def test_saving_a_leave_answers_with_the_days_it_leaves_without_reserve(client, db) -> None: + await _team(db) + await login(client, "anna") + + saved = await _paint(client, "me") + + with_beata = {"scheduled": True, "also_on_leave": ["Beata"]} + weekend = {"scheduled": False, "also_on_leave": []} + assert saved["kind"] == "leave" + assert saved["staffing"] == [ + # Only Celina is left: one short for the pair, the last for the 11-19. + _row(17, PAIR, 1, 2, **with_beata), + _row(17, ["late_shift"], 1, 1, **with_beata), + _row(18, PAIR, 1, 2, **with_beata), + _row(18, ["late_shift"], 1, 1, **with_beata), + # Beata is back: two people for the pair, which nobody has scheduled yet. + _row(19, PAIR, 2, 2, **weekend), + _row(20, PAIR, 2, 2, **weekend), + _row(21, PAIR, 2, 2, **weekend), + ] + + +async def test_an_entry_on_behalf_and_a_wish_answer_alike(client, db) -> None: + await _team(db) + await login(client, "celina") + anna = (await client.get("/api/v1/team")).json()[0] + + on_behalf = await _paint(client, f"members/{anna['id']}", "unavailable") + wish = await _paint(client, "me", "prefer_not") + + assert [row["service_date"] for row in on_behalf["staffing"][:2]] == ["2026-09-17"] * 2 + assert wish["staffing"] == [] + + +async def test_a_single_entry_is_answered_with_the_same_notice(client, db) -> None: + await _team(db) + await login(client, "anna") + + response = await client.post( + "/api/v1/availability/me", + json={"kind": "unavailable", "starts_on": "2026-09-19", "ends_on": "2026-09-19"}, + ) + + assert response.status_code == 201, response.text + assert response.json()["staffing"] == [_row(19, PAIR, 2, 2, scheduled=False, also_on_leave=[])] + + +async def _staffing(client: AsyncClient, username: str) -> list[dict]: + await login(client, username) + response = await client.get( + "/api/v1/calendar", params={"starts_on": "2026-09-10", "ends_on": "2026-09-22"} + ) + assert response.status_code == 200, response.text + return response.json()["staffing"] + + +async def test_the_calendar_gives_coordinators_the_count_from_today_on(client, db) -> None: + await _team(db) + await login(client, "anna") + await _paint(client, "me") + + # Monday the 14th has passed; on the 22nd everyone is back. + assert await _staffing(client, "celina") == [ + _row(15, PAIR, 2, 2), + _row(16, PAIR, 2, 2), + _row(17, PAIR, 1, 2), + _row(17, ["late_shift"], 1, 1), + _row(18, PAIR, 1, 2), + _row(18, ["late_shift"], 1, 1), + _row(19, PAIR, 2, 2), + _row(20, PAIR, 2, 2), + _row(21, PAIR, 2, 2), + ] + + +async def test_the_count_is_not_given_to_members(client, db) -> None: + """Who is qualified for what is the coordinators' to read.""" + await _team(db) + + assert await _staffing(client, "anna") == [] diff --git a/docs/en/uzytkownik/dostepnosc.md b/docs/en/uzytkownik/dostepnosc.md index f870e390..31d0e599 100644 --- a/docs/en/uzytkownik/dostepnosc.md +++ b/docs/en/uzytkownik/dostepnosc.md @@ -101,6 +101,17 @@ is not covered by the leave”, because the generator may assign a duty then. The **Add the weekend to the leave** button extends the leave by those two days. +Leave and “unavailable” are always saved, also when they leave a role with +too few people. If on some day a role you are eligible for is left with +exactly as many people as needed, or fewer, a notice under the calendar says +so, for example “10 – 11 Dec: Marek Nowak is on leave too. That leaves 2 +people for PRIMARY and SECONDARY, with no reserve. Coordinators see this in +the schedule.” For days whose schedule is not laid out yet, the notice says +how many people the generator will have. There is nothing you have to do: +the coordinators have those days on the Now and Schedule screens. How the +application counts people is described in +[Risks in the range](dyzury.md#risks-in-the-range). + ### What each mode means - **Unavailable** - a **hard** rule. The generator will not assign you a duty diff --git a/docs/en/uzytkownik/dyzury.md b/docs/en/uzytkownik/dyzury.md index 08bf1bb0..333be2a9 100644 --- a/docs/en/uzytkownik/dyzury.md +++ b/docs/en/uzytkownik/dyzury.md @@ -25,7 +25,8 @@ a range starting the day after the end of the published schedule. Under the header is a row of risk badges, about the visible range only: days without full coverage, days outside the published range and, for a -coordinator, duties of people who are on leave or “Unavailable” that day. A +coordinator, duties of people who are on leave or “Unavailable” that day, and +the roles that leave and “Unavailable” leave with too few people. A badge that leads to a day ends in an arrow. Below is the **Next 4 weeks** section with the same matrix as on the Schedule @@ -223,10 +224,31 @@ outside the published range, duties of people who are on leave or by people on leave”; clicking jumps to the first such day), or **Full coverage** when everything is fine. Narrowing the view cannot hide an active conflict without this message. The -Schedule shows the same matrix without the risk row; days without coverage +Schedule shows the same matrix without these badges; days without coverage are marked in red in the column header and in the day panel there, and the section header gives their number with a link to the first. +Above the matrix, on the Now screen and on the Schedule, a coordinator and an +administrator also see the reserve badges. For every day from today on the +application counts the people eligible for a role who have neither leave nor +“Unavailable” that day, and compares them with how many the day needs: one +for `PRIMARY`, one for `SECONDARY`, two different people for those two roles +together and, on a working day, one for `11–19`. If only one of `PRIMARY` +and `SECONDARY` is short of people, each of the two is judged separately. + +- Exactly as many people are left as needed: a warning, for example “10 – 11 + Dec: PRIMARY and SECONDARY with no reserve (2 people)”. One more absence + and the day cannot be staffed. +- Fewer are left: an alarm, for example “24 Dec: one person short for + SECONDARY”. + +Days in a row with the same result are one badge, and clicking it opens the +first of them; the day panel shows who is on leave or “Unavailable” then. +Only entries count: a day on which everyone is available has no badge even +in a small team, and a person eligible for no role is not counted. The result +is the same for days with a published schedule and for days the generator has +yet to lay out. + ### Day details Clicking a cell (or `Enter` on the selected cell) opens the day panel: the diff --git a/docs/uzytkownik/dostepnosc.md b/docs/uzytkownik/dostepnosc.md index eb452d9c..f57f12a5 100644 --- a/docs/uzytkownik/dostepnosc.md +++ b/docs/uzytkownik/dostepnosc.md @@ -96,6 +96,16 @@ piątek albo zaczyna w poniedziałek, pod kalendarzem jest podpowiedź „Weeken 12 – 13 gru nie jest objęty urlopem”, bo generator może wtedy przydzielić dyżur. Przycisk **Dodaj weekend do urlopu** wydłuża urlop o te dwa dni. +Urlop i „nie mogę” zapisują się zawsze, także wtedy, gdy przez nie do roli +zostaje za mało osób. Jeśli w któryś dzień do roli, do której masz +uprawnienia, zostaje dokładnie tyle osób, ile trzeba, albo mniej, pod +kalendarzem jest informacja, na przykład „10 – 11 gru urlop ma też Marek +Nowak. Do PRIMARY i SECONDARY zostają wtedy 2 osoby, bez rezerwy. +Koordynatorzy widzą to w grafiku.” Dla dni, na które grafik nie jest jeszcze +ułożony, informacja mówi, ile osób będzie miał generator. Nie musisz nic +robić: to koordynatorzy mają te dni na ekranach Teraz i Grafik. Jak aplikacja +liczy osoby, opisuje sekcja [Ryzyka w zakresie](dyzury.md#ryzyka-w-zakresie). + ### Co znaczy który tryb - **Nie mogę** - reguła **twarda**. Generator nie przydzieli Ci dyżuru w tym diff --git a/docs/uzytkownik/dyzury.md b/docs/uzytkownik/dyzury.md index bc56f184..af5f7ae2 100644 --- a/docs/uzytkownik/dyzury.md +++ b/docs/uzytkownik/dyzury.md @@ -23,7 +23,8 @@ po końcu opublikowanego grafiku. Pod nagłówkiem jest rząd znaczników ryzyka, tylko o widocznym zakresie: dni bez pełnej obsady, dni poza opublikowanym zakresem i, dla koordynatora, -dyżury osób, które mają tego dnia urlop albo „nie mogę”. Znacznik, który +dyżury osób, które mają tego dnia urlop albo „nie mogę”, oraz role, do +których urlopy i „nie mogę” zostawiają za mało osób. Znacznik, który prowadzi do dnia, kończy się strzałką. Niżej jest sekcja **Najbliższe 4 tygodnie** z tą samą macierzą co na ekranie @@ -214,10 +215,30 @@ dni poza opublikowanym zakresem, dyżury osób, które mają tego dnia urlop alb „nie mogę” (znacznik liczy dyżury, na przykład „4 dyżury osób na urlopie”; kliknięcie przeskakuje do pierwszego takiego dnia) albo **Pełna obsada**, gdy wszystko gra. Zawężenie widoku nie może ukryć aktywnego konfliktu bez tego -komunikatu. Grafik pokazuje tę samą macierz bez rzędu ryzyk; dni bez obsady +komunikatu. Grafik pokazuje tę samą macierz bez tych znaczników; dni bez obsady są w nim zaznaczone na czerwono w nagłówku kolumny i w panelu dnia, a nagłówek sekcji podaje ich liczbę z linkiem do pierwszego. +Koordynator i administrator widzą nad macierzą, na ekranie Teraz i na +Grafiku, także znaczniki rezerwy. Dla każdego dnia od dziś aplikacja liczy +osoby z uprawnieniem do roli, które nie mają tego dnia ani urlopu, ani „nie +mogę”, i porównuje je z tym, ilu osób dzień potrzebuje: jednej do `PRIMARY`, +jednej do `SECONDARY`, dwóch różnych do obu tych ról razem i, w dzień +roboczy, jednej do `11–19`. Jeśli osoby brakuje tylko do jednej z ról +`PRIMARY` i `SECONDARY`, każda z nich jest oceniana osobno. + +- Zostaje dokładnie tyle osób, ile trzeba: ostrzeżenie, na przykład „10 – 11 + gru: PRIMARY i SECONDARY bez rezerwy (2 osoby)”. Jeszcze jedna nieobecność + i dnia nie da się obsadzić. +- Zostaje mniej: alarm, na przykład „24 gru: brakuje osoby do SECONDARY”. + +Kolejne dni z tym samym wynikiem są jednym znacznikiem, a kliknięcie otwiera +pierwszy z nich; kto ma wtedy urlop albo „nie mogę”, pokazuje panel dnia. +Liczą się tylko wpisy: dzień, w który wszyscy są dostępni, nie ma znacznika +nawet w małym zespole, a osoba bez uprawnień do żadnej roli nie jest +liczona. Wynik jest taki sam dla dni z opublikowanym grafikiem i dla dni, +które generator dopiero ułoży. + ### Szczegóły dnia Kliknięcie komórki (albo `Enter` na zaznaczonej komórce) otwiera panel dnia: diff --git a/frontend/scripts/__snapshots__/docs-pl-uzytkownik-dyzury.html b/frontend/scripts/__snapshots__/docs-pl-uzytkownik-dyzury.html index 9834c6f1..daaa2b43 100644 --- a/frontend/scripts/__snapshots__/docs-pl-uzytkownik-dyzury.html +++ b/frontend/scripts/__snapshots__/docs-pl-uzytkownik-dyzury.html @@ -122,7 +122,8 @@
Pod nagłówkiem jest rząd znaczników ryzyka, tylko o widocznym zakresie: dni bez pełnej obsady, dni poza opublikowanym zakresem i, dla koordynatora, -dyżury osób, które mają tego dnia urlop albo „nie mogę”. Znacznik, który +dyżury osób, które mają tego dnia urlop albo „nie mogę”, oraz role, do +których urlopy i „nie mogę” zostawiają za mało osób. Znacznik, który prowadzi do dnia, kończy się strzałką.
Niżej jest sekcja Najbliższe 4 tygodnie z tą samą macierzą co na ekranie Grafik i tym samym pasem kontrolek w nagłówku sekcji: długość 2 / 4 / 8 @@ -318,9 +319,28 @@
Koordynator i administrator widzą nad macierzą, na ekranie Teraz i na
+Grafiku, także znaczniki rezerwy. Dla każdego dnia od dziś aplikacja liczy
+osoby z uprawnieniem do roli, które nie mają tego dnia ani urlopu, ani „nie
+mogę”, i porównuje je z tym, ilu osób dzień potrzebuje: jednej do PRIMARY,
+jednej do SECONDARY, dwóch różnych do obu tych ról razem i, w dzień
+roboczy, jednej do 11–19. Jeśli osoby brakuje tylko do jednej z ról
+PRIMARY i SECONDARY, każda z nich jest oceniana osobno.
Kolejne dni z tym samym wynikiem są jednym znacznikiem, a kliknięcie otwiera +pierwszy z nich; kto ma wtedy urlop albo „nie mogę”, pokazuje panel dnia. +Liczą się tylko wpisy: dzień, w który wszyscy są dostępni, nie ma znacznika +nawet w małym zespole, a osoba bez uprawnień do żadnej roli nie jest +liczona. Wynik jest taki sam dla dni z opublikowanym grafikiem i dla dni, +które generator dopiero ułoży.
Kliknięcie komórki (albo Enter na zaznaczonej komórce) otwiera panel dnia:
obsada każdej roli, wydarzenia kalendarza i zgłoszona dostępność. Po siatce
diff --git a/frontend/src/api.ts b/frontend/src/api.ts
index 30f08c0e..519b7548 100644
--- a/frontend/src/api.ts
+++ b/frontend/src/api.ts
@@ -219,6 +219,23 @@ export interface SwapRequest {
export type AvailabilityKind = 'unavailable' | 'leave' | 'prefer_not' | 'prefer'
+/** Roles that "unavailable" and leave entries leave, on one day, with exactly
+ * as many qualified people as the day needs (no reserve) or with fewer. */
+export interface Staffing {
+ service_date: string
+ roles: AssignmentRole[]
+ available: number
+ needed: number
+}
+
+/** A day of a saved entry that is among those leaving the roles without reserve. */
+export interface StaffingNote extends Staffing {
+ /** Whether a schedule already covers the day. */
+ scheduled: boolean
+ /** The others away that day who are on leave. */
+ also_on_leave: string[]
+}
+
export interface AvailabilityEntry {
id: string
kind: AvailabilityKind
@@ -228,6 +245,8 @@ export interface AvailabilityEntry {
created_at: string
warning?: string | null
created_by_name?: string | null
+ /** In the answer to a save: a notice for whoever saved, never a refusal. */
+ staffing?: StaffingNote[]
}
export interface AvailabilityInput {
@@ -523,6 +542,8 @@ export interface CalendarData {
* the end of the leave, earliest first. */
duties: Array<{ service_date: string; role: AssignmentRole }>
}>
+ /** From today on, for coordinators only: who is qualified is theirs to read. */
+ staffing?: Staffing[]
}
export type ForwardingMode = 'off' | 'dry_run' | 'live'
diff --git a/frontend/src/components/CalendarMatrix.test.tsx b/frontend/src/components/CalendarMatrix.test.tsx
index 3d0f69ee..f36b9382 100644
--- a/frontend/src/components/CalendarMatrix.test.tsx
+++ b/frontend/src/components/CalendarMatrix.test.tsx
@@ -760,6 +760,44 @@ describe('CalendarMatrix risk chips', () => {
expect(screen.queryByRole('list', { name: 'Ryzyka w zakresie' })).not.toBeInTheDocument()
})
+ const PAIR: AssignmentRole[] = ['primary', 'secondary']
+ const left = (service_date: string, roles: AssignmentRole[], available: number, needed: number) => ({ service_date, roles, available, needed })
+
+ it('names the roles that entries leave with no reserve or short of people, a run of days as one chip', async () => {
+ vi.spyOn(api, 'calendar').mockResolvedValue(week({ staffing: [
+ left('2026-09-09', PAIR, 2, 2),
+ left('2026-09-10', PAIR, 2, 2),
+ left('2026-09-10', ['late_shift'], 1, 1),
+ left('2026-09-12', ['secondary'], 0, 1),
+ left('2026-09-13', PAIR, 0, 2),
+ ] }))
+ renderScreen(