From 26520bb81bb159464e9d8f51ef597053b75570f7 Mon Sep 17 00:00:00 2001 From: lowicz Date: Thu, 3 Dec 2026 01:09:42 +0100 Subject: [PATCH 1/5] =?UTF-8?q?feat(availability):=20warn=20when=20leave?= =?UTF-8?q?=20or=20"nie=20mog=C4=99"=20leaves=20a=20role=20without=20reser?= =?UTF-8?q?ve?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit One read counts, per day and role, the people qualified for the role who have neither "nie mogę" nor leave that day, against how many the day needs: one for PRIMARY, one for SECONDARY, two different people for the pair and, on a working day, one for the 11-19 shift. As many left as needed is "bez rezerwy", fewer cannot be staffed. A day speaks only when an entry brought it there, and people eligible for no role are not counted. - Saving an entry that blocks duty is never refused. Its answer gains the days it leaves a role the person can take without reserve, with who else is on leave then and whether a schedule covers the day; the calendar shows it as a neutral notice under the month, until the next stroke or its Undo. - Coordinators and admins get the same count in the calendar payload, from today on, as chips above the matrix on "Teraz" and on "Grafik": a warning for no reserve, an alarm for a missing person, days in a row as one chip that opens the first of them. Members are not sent the count, like eligibility. Docs in both languages. --- backend/contracts/openapi.json | 95 ++++++++++- .../src/oncall/domain/availability/models.py | 15 ++ .../oncall/domain/availability/use_cases.py | 46 +++++- backend/src/oncall/domain/calendar/models.py | 4 + .../src/oncall/domain/calendar/use_cases.py | 25 ++- backend/src/oncall/domain/staffing.py | 79 ++++++++++ .../src/oncall/presentation/availability.py | 29 +++- backend/src/oncall/presentation/calendar.py | 3 + backend/src/oncall/presentation/staffing.py | 19 +++ backend/src/oncall/routes/availability.py | 8 +- backend/src/oncall/routes/calendar.py | 4 +- .../domain/test_availability_use_cases.py | 93 ++++++++++- backend/tests/domain/test_staffing.py | 128 +++++++++++++++ backend/tests/test_staffing_reserve.py | 149 ++++++++++++++++++ docs/en/uzytkownik/dostepnosc.md | 11 ++ docs/en/uzytkownik/dyzury.md | 25 ++- docs/uzytkownik/dostepnosc.md | 10 ++ docs/uzytkownik/dyzury.md | 24 ++- .../docs-pl-uzytkownik-dyzury.html | 23 ++- frontend/src/api.ts | 21 +++ .../src/components/CalendarMatrix.test.tsx | 38 +++++ frontend/src/components/CalendarMatrix.tsx | 26 ++- frontend/src/i18n/en/mine.ts | 9 ++ frontend/src/i18n/en/schedule.ts | 3 + frontend/src/i18n/pl/mine.ts | 15 +- frontend/src/i18n/pl/schedule.ts | 5 + frontend/src/lib/calendar.test.ts | 27 ++++ frontend/src/lib/calendar.ts | 17 +- frontend/src/screens/Mine.test.tsx | 75 +++++++++ frontend/src/screens/Mine.tsx | 33 +++- frontend/src/screens/Schedule.tsx | 4 +- 31 files changed, 1031 insertions(+), 32 deletions(-) create mode 100644 backend/src/oncall/domain/staffing.py create mode 100644 backend/src/oncall/presentation/staffing.py create mode 100644 backend/tests/domain/test_staffing.py create mode 100644 backend/tests/test_staffing_reserve.py 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..fce98188 --- /dev/null +++ b/backend/src/oncall/domain/staffing.py @@ -0,0 +1,79 @@ +"""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 that an entry leaves with no reserve. + People eligible for none of the roles are not counted, and a team this + small with everyone available has nothing to say about entries.""" + 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) + if away and available <= needed: + 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; the pair speaks for its two roles + when it is at least as badly off as either, otherwise each role speaks for + itself. The 11-19 shift needs one person on a working day, who may be on + call as well.""" + 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 and all(pair[0].short >= row.short for row in rows): + rows = pair + if is_working_day(day, holidays): + rows += _counts(people, day, [(AssignmentRole.late_shift,)], 1) + result += rows + 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..31306c0d --- /dev/null +++ b/backend/tests/domain/test_staffing.py @@ -0,0 +1,128 @@ +"""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_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..81396cb1 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,30 @@ 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`. + +- 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..35ecbcc3 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,29 @@ 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`. + +- 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..a0ca95b4 100644 --- a/frontend/scripts/__snapshots__/docs-pl-uzytkownik-dyzury.html +++ b/frontend/scripts/__snapshots__/docs-pl-uzytkownik-dyzury.html @@ -122,7 +122,8 @@

Teraz

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 Grafik i tym samym pasem kontrolek w nagłówku sekcji: długość 2 / 4 / 8 @@ -318,9 +319,27 @@

Ryzyka w zakresie

„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.

+ +

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: 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() + + const chips = await within(await screen.findByRole('list', { name: 'Ryzyka w zakresie' })).findAllByRole('button', { name: /rezerwy|brakuje/ }) + expect(chips.map((chip) => [chip.childNodes[1].textContent, chip.classList.contains('chip-bad') ? 'bad' : 'warn'])).toEqual([ + ['9 – 10 wrz: PRIMARY i SECONDARY bez rezerwy (2 osoby)', 'warn'], + ['10 wrz: 11–19 bez rezerwy (1 osoba)', 'warn'], + ['12 wrz: brakuje osoby do SECONDARY', 'bad'], + ['13 wrz: brakuje 2 osób do PRIMARY i SECONDARY', 'bad'], + ]) + expect(chips[0]).toHaveClass('chip-warn') + expect(chips[2]).toHaveAccessibleDescription('Pokaż pierwszy z tych dni') + // The week is staffed all the same: the count is about who is left, not who holds what. + expect(within(riskRow()).getByText('Pełna obsada w całym zakresie')).toBeInTheDocument() + + fireEvent.click(chips[2]) + expect(await screen.findByRole('dialog', { name: /^sob 12-09-2026/ })).toBeInTheDocument() + }) + + it('keeps those chips on the full schedule, which draws no other risk', async () => { + vi.spyOn(api, 'calendar').mockResolvedValue(week({ assignments: [], staffing: [left('2026-09-09', PAIR, 2, 2)] })) + renderScreen() + + const row = await screen.findByRole('list', { name: 'Ryzyka w zakresie' }) + expect(within(row).getAllByRole('listitem')).toHaveLength(1) + expect(within(row).getByRole('button', { name: '9 wrz: PRIMARY i SECONDARY bez rezerwy (2 osoby)' })).toHaveClass('chip-warn') + }) + it('opens the first gap in the day list too', async () => { vi.spyOn(api, 'calendar').mockResolvedValue(week({ assignments: covered(DATES.slice(0, 6)) })) renderScreen() diff --git a/frontend/src/components/CalendarMatrix.tsx b/frontend/src/components/CalendarMatrix.tsx index c141477a..0bb08198 100644 --- a/frontend/src/components/CalendarMatrix.tsx +++ b/frontend/src/components/CalendarMatrix.tsx @@ -20,6 +20,7 @@ import { monthGroups, orderMembers, slotOf, + staffingRuns, startsWeek, } from '../lib/calendar' import { locale, messages, useMessages } from '../i18n' @@ -113,7 +114,8 @@ export function CalendarMatrix({ * function receives whether the range has loaded, how many people it holds, * how many of them have a duty in it and the first day without full coverage. */ heading?: ReactNode | ((summary: MatrixSummary) => ReactNode) - /** The "Teraz" screen carries the risk chips; the full schedule does not. */ + /** The "Teraz" screen carries the risk chips; the full schedule only those + * that say which roles are left with no reserve. */ showRisks?: boolean }) { const queryClient = useQueryClient() @@ -229,6 +231,9 @@ export function CalendarMatrix({ // Runs when the conflicts change; the rest is read as it is then. // eslint-disable-next-line react-hooks/exhaustive-deps }, [dutyConflicts]) + // The roles that entries leave with no reserve or short of people: the + // server counts them for coordinators only, and from today on. + const staffing = useMemo(() => staffingRuns(data?.staffing ?? []), [data]) const gapDates = useMemo(() => new Set(gaps.map((gap) => gap.service_date)), [gaps]) const dayByDate = useMemo(() => new Map((data?.days ?? []).map((day) => [day.service_date, day])), [data]) // What the cells and the inspector read, looked up instead of searched for @@ -356,7 +361,7 @@ export function CalendarMatrix({ ? data?.assignments.find((item) => item.service_date === selected.day.service_date && item.assignee_name === displayName)?.role : undefined - const riskChips = data && showRisks && (gaps.length > 0 || (canCoordinate && dutyConflicts.length > 0) || publishedGaps.length === 0) + const riskChips = data && (staffing.length > 0 || showRisks) return ( <> @@ -364,7 +369,7 @@ export function CalendarMatrix({ {/* Only the staffable kind is a jump target; jumping to a day nobody can fix was the trap behind HGH-02. */} - {publishedGaps.length > 0 && ( + {showRisks && publishedGaps.length > 0 && ( jumpToDate(data.days, publishedGaps[0].service_date)} title={t.risks.showFirstGap}> {t.risks.gapDays(publishedGaps.length)} {' · '} @@ -372,17 +377,26 @@ export function CalendarMatrix({ {publishedGaps.length > 3 ? '…' : ''} )} - {outsideGaps.length > 0 && ( + {showRisks && outsideGaps.length > 0 && ( {t.risks.outsideDays(outsideGaps.length)} )} - {canCoordinate && dutyConflicts.length > 0 && ( + {showRisks && canCoordinate && dutyConflicts.length > 0 && ( jumpToDate(data.days, dutyConflicts[0].service_date)} title={t.risks.showFirstConflict}> {t.risks.conflictDuties(dutyConflicts.every((item) => item.kind === dutyConflicts[0].kind) ? dutyConflicts[0].kind : 'both', dutyConflicts.length)} )} - {gaps.length === 0 && (!canCoordinate || dutyConflicts.length === 0) && ( + {staffing.map((run) => { + const range = formatRange(run.service_date, run.ends_on) + const roles = roleList(run.roles) + return ( + jumpToDate(data.days, run.service_date)} title={t.risks.showStaffingDay}> + {run.available < run.needed ? t.risks.shortOfPeople(range, roles, run.needed - run.available) : t.risks.noReserve(range, roles, run.available)} + + ) + })} + {showRisks && gaps.length === 0 && (!canCoordinate || dutyConflicts.length === 0) && ( {t.risks.fullCoverage} )} diff --git a/frontend/src/i18n/en/mine.ts b/frontend/src/i18n/en/mine.ts index c3967f03..b9a4da8c 100644 --- a/frontend/src/i18n/en/mine.ts +++ b/frontend/src/i18n/en/mine.ts @@ -116,6 +116,15 @@ export const mine: Messages['mine'] = { bodyFor: (name: string) => `The generator may then assign a duty to ${name}.`, add: 'Add the weekend to the leave', }, + staffing: { + when: (range: string, alsoOnLeave: string[]) => (alsoOnLeave.length === 0 + ? `${range}:` + : `${range}: ${alsoOnLeave.join(', ')} ${alsoOnLeave.length === 1 ? 'is' : 'are'} on leave too.`), + noReserve: (roles: string, people: number) => `That leaves ${pluralEn(people, ['person', 'people'])} for ${roles}, with no reserve.`, + short: (roles: string, missing: number) => (missing === 1 ? `${roles} is then one person short.` : `${roles} is then ${missing} people short.`), + unscheduled: (days: number, roles: string, people: number) => `The schedule for ${days === 1 ? 'this day' : 'these days'} is not laid out yet. The generator will have ${pluralEn(people, ['person', 'people'])} for ${roles}.`, + coordinatorsSee: 'Coordinators see this in the schedule.', + }, past: { coordinator: 'Leave can also be added, or removed with the eraser, for past days, up to 12 months back. Other entries only from today.', member: 'Days that have passed are corrected by a coordinator.', diff --git a/frontend/src/i18n/en/schedule.ts b/frontend/src/i18n/en/schedule.ts index 774fc001..5461e6dd 100644 --- a/frontend/src/i18n/en/schedule.ts +++ b/frontend/src/i18n/en/schedule.ts @@ -92,6 +92,9 @@ export const schedule: Messages['schedule'] = { return entry === 'both' ? `${duties} despite “unavailable” or leave` : `${duties} despite “unavailable”` }, fullCoverage: 'Full coverage across the whole range', + noReserve: (range: string, roles: string, people: number) => `${range}: ${roles} with no reserve (${pluralEn(people, ['person', 'people'])})`, + shortOfPeople: (range: string, roles: string, missing: number) => `${range}: ${missing === 1 ? 'one person' : `${missing} people`} short for ${roles}`, + showStaffingDay: 'Show the first of these days', }, loading: 'Loading the schedule…', empty: { diff --git a/frontend/src/i18n/pl/mine.ts b/frontend/src/i18n/pl/mine.ts index be0f8a12..15f3871f 100644 --- a/frontend/src/i18n/pl/mine.ts +++ b/frontend/src/i18n/pl/mine.ts @@ -1,5 +1,5 @@ import type { CollidingEntries } from '../../lib/calendar' -import { pluralPl } from '../../lib/plural' +import { pluralFormPl, pluralPl } from '../../lib/plural' /** The member's own screen (`src/screens/Mine.tsx`): duties, the availability calendar, points, swaps, the ICS feeds. */ export const mine = { @@ -129,6 +129,19 @@ export const mine = { bodyFor: (name: string) => `Generator może wtedy przydzielić dyżur: ${name}.`, add: 'Dodaj weekend do urlopu', }, + /** After a save that leaves roles with exactly as many qualified people + * as the days need, or with fewer: a notice, never a refusal. */ + staffing: { + /** The days, and who else is on leave then. */ + when: (range: string, alsoOnLeave: string[]) => (alsoOnLeave.length === 0 + ? `${range}:` + : `${range} urlop ${alsoOnLeave.length === 1 ? 'ma' : 'mają'} też ${alsoOnLeave.join(', ')}.`), + noReserve: (roles: string, people: number) => `Do ${roles} ${pluralFormPl(people, ['zostaje', 'zostają', 'zostaje'])} wtedy ${pluralPl(people, ['osoba', 'osoby', 'osób'])}, bez rezerwy.`, + short: (roles: string, missing: number) => (missing === 1 ? `Do ${roles} brakuje wtedy osoby.` : `Do ${roles} brakuje wtedy ${missing} osób.`), + /** Days no schedule covers yet: the count is what the generator will have. */ + unscheduled: (days: number, roles: string, people: number) => `${days === 1 ? 'Grafik na ten dzień' : 'Grafik na te dni'} nie jest jeszcze ułożony. Generator będzie miał ${pluralPl(people, ['osobę', 'osoby', 'osób'])} na ${roles}.`, + coordinatorsSee: 'Koordynatorzy widzą to w grafiku.', + }, /** Days that have passed: closed, except for a leave a coordinator or an * admin writes or clears after the fact. */ past: { diff --git a/frontend/src/i18n/pl/schedule.ts b/frontend/src/i18n/pl/schedule.ts index fedfb30d..0867379d 100644 --- a/frontend/src/i18n/pl/schedule.ts +++ b/frontend/src/i18n/pl/schedule.ts @@ -106,6 +106,11 @@ export const schedule = { return entry === 'both' ? `${duties} mimo „nie mogę” lub urlopu` : `${duties} mimo „nie mogę”` }, fullCoverage: 'Pełna obsada w całym zakresie', + /** Roles that "nie mogę" and leave entries leave with exactly as many + * qualified people as the days need, or with fewer. */ + noReserve: (range: string, roles: string, people: number) => `${range}: ${roles} bez rezerwy (${pluralPl(people, ['osoba', 'osoby', 'osób'])})`, + shortOfPeople: (range: string, roles: string, missing: number) => `${range}: ${missing === 1 ? 'brakuje osoby' : `brakuje ${missing} osób`} do ${roles}`, + showStaffingDay: 'Pokaż pierwszy z tych dni', }, loading: 'Wczytywanie grafiku…', empty: { diff --git a/frontend/src/lib/calendar.test.ts b/frontend/src/lib/calendar.test.ts index 2294e5e2..2e707a0d 100644 --- a/frontend/src/lib/calendar.test.ts +++ b/frontend/src/lib/calendar.test.ts @@ -16,6 +16,7 @@ import { lateShiftLink, staffChanges, staffingCandidates, + staffingRuns, startsWeek, } from './calendar' @@ -565,3 +566,29 @@ describe('staffChanges', () => { expect(staffChanges(calendar, '2026-09-02', ['primary'])).toEqual([{ role: 'primary', from: null, restoreTo: null }]) }) }) + +describe('staffingRuns', () => { + const pair = (service_date: string, available = 2) => ({ service_date, roles: ['primary' as const, 'secondary' as const], available, needed: 2 }) + const shift = (service_date: string) => ({ service_date, roles: ['late_shift' as const], available: 1, needed: 1 }) + + it('joins days in a row that say the same about the same roles', () => { + const runs = staffingRuns([pair('2026-12-10'), shift('2026-12-10'), pair('2026-12-11'), pair('2026-12-12', 1), pair('2026-12-14')]) + + expect(runs.map((run) => [run.service_date, run.ends_on, run.roles.join('+'), run.available])).toEqual([ + ['2026-12-10', '2026-12-11', 'primary+secondary', 2], + ['2026-12-10', '2026-12-10', 'late_shift', 1], + // One person fewer is another fact; a day's break ends a run. + ['2026-12-12', '2026-12-12', 'primary+secondary', 1], + ['2026-12-14', '2026-12-14', 'primary+secondary', 2], + ]) + }) + + it('parts a run where the days differ in what the caller reads beside the count', () => { + const rows = [{ ...pair('2026-12-10'), scheduled: true }, { ...pair('2026-12-11'), scheduled: false }, { ...pair('2026-12-12'), scheduled: false }] + + expect(staffingRuns(rows, (row) => String(row.scheduled)).map((run) => [run.service_date, run.ends_on, run.scheduled])).toEqual([ + ['2026-12-10', '2026-12-10', true], + ['2026-12-11', '2026-12-12', false], + ]) + }) +}) diff --git a/frontend/src/lib/calendar.ts b/frontend/src/lib/calendar.ts index a9367f5a..22cdb707 100644 --- a/frontend/src/lib/calendar.ts +++ b/frontend/src/lib/calendar.ts @@ -1,5 +1,5 @@ -import { Assignment, AssignmentRole, AvailabilityKind, CalendarData, LateShiftAnchor } from '../api' -import { formatMonth, isMonday, monthsShort } from './dates' +import { Assignment, AssignmentRole, AvailabilityKind, CalendarData, LateShiftAnchor, Staffing } from '../api' +import { addDays, formatMonth, isMonday, monthsShort } from './dates' import { messages } from '../i18n/messages' /** Roles that must be staffed every single day. The 11-19 shift is working-days @@ -28,6 +28,19 @@ export function groupByKey(items: readonly T[], key: (item: T) => string): Ma return groups } +/** Days in a row that say the same about the same roles, joined into one + * run from `service_date` to `ends_on`, earliest first. `alike` adds what + * else the days of a run must share. */ +export function staffingRuns(rows: readonly T[], alike: (row: T) => string = () => ''): Array { + const same = groupByKey(rows, (row) => `${row.roles}|${row.available}|${row.needed}|${alike(row)}`) + return [...same.values()].flatMap((days) => days.reduce>((runs, row) => { + const last = runs.at(-1) + if (last && addDays(last.ends_on, 1) === row.service_date) last.ends_on = row.service_date + else runs.push({ ...row, ends_on: row.service_date }) + return runs + }, [])).sort((a, b) => a.service_date.localeCompare(b.service_date)) +} + /** Each person's duties of a day under `date|name`, in role order whatever * order the payload came in, so every cell prints its marks the same way. */ export function assignmentsByCell>(assignments: readonly T[]): Map { diff --git a/frontend/src/screens/Mine.test.tsx b/frontend/src/screens/Mine.test.tsx index ae170c70..02628642 100644 --- a/frontend/src/screens/Mine.test.tsx +++ b/frontend/src/screens/Mine.test.tsx @@ -1789,6 +1789,81 @@ describe('MineScreen leave', () => { expect(screen.queryByText(weekendHint)).not.toBeInTheDocument() }) + it('says after a save which roles it leaves with no reserve, without refusing it', async () => { + stub() + const undo = vi.spyOn(api, 'undoAvailabilityRange').mockResolvedValue(undefined) + const replace = saving() + const pair = { roles: ['primary' as const, 'secondary' as const], needed: 2 } + replace.mockImplementationOnce(async (input: AvailabilityRangeInput) => ({ + ...entry('leave', input.starts_on, input.ends_on), + staffing: [ + { service_date: '2026-09-22', ...pair, available: 2, scheduled: true, also_on_leave: ['Marek Nowak'] }, + { service_date: '2026-09-23', ...pair, available: 2, scheduled: true, also_on_leave: ['Marek Nowak'] }, + { service_date: '2026-09-24', ...pair, available: 1, scheduled: true, also_on_leave: ['Marek Nowak', 'Piotr Lis'] }, + { service_date: '2026-09-24', roles: ['late_shift' as const], needed: 1, available: 1, scheduled: true, also_on_leave: [] }, + { service_date: '2026-09-25', ...pair, available: 0, scheduled: true, also_on_leave: [] }, + { service_date: '2026-09-26', ...pair, available: 2, scheduled: false, also_on_leave: [] }, + { service_date: '2026-09-27', ...pair, available: 2, scheduled: false, also_on_leave: [] }, + { service_date: '2026-09-28', roles: ['secondary' as const], needed: 1, available: 1, scheduled: false, also_on_leave: [] }, + ], + })) + renderScreen() + await idleCalendar() + + fireEvent.click(screen.getByRole('radio', { name: 'urlop' })) + paintRange(/wt 22-09-2026/, /pon 28-09-2026/) + + const notice = (await screen.findByText('Koordynatorzy widzą to w grafiku.')).closest('.box') as HTMLElement + expect(notice).toHaveAttribute('role', 'status') + expect(notice).toHaveClass('box-sig') + // The saved fact first, then one line per run of days that read alike. + expect([...notice.children].map((line) => line.textContent)).toEqual([ + 'Zapisano: 22 – 28 wrz „urlop”', + '22 – 23 wrz urlop ma też Marek Nowak. Do PRIMARY i SECONDARY zostają wtedy 2 osoby, bez rezerwy.', + 'czw 24 wrz urlop mają też Marek Nowak, Piotr Lis. Do PRIMARY i SECONDARY brakuje wtedy osoby.', + 'czw 24 wrz: Do 11–19 zostaje wtedy 1 osoba, bez rezerwy.', + 'pt 25 wrz: Do PRIMARY i SECONDARY brakuje wtedy 2 osób.', + '26 – 27 wrz: Grafik na te dni nie jest jeszcze ułożony. Generator będzie miał 2 osoby na PRIMARY i SECONDARY.', + 'pon 28 wrz: Grafik na ten dzień nie jest jeszcze ułożony. Generator będzie miał 1 osobę na SECONDARY.', + 'Koordynatorzy widzą to w grafiku.', + ]) + + // The Undo of that stroke takes the notice with it. + fireEvent.click(await screen.findByRole('button', { name: 'Cofnij' })) + await waitFor(() => expect(undo).toHaveBeenCalled()) + await waitFor(() => expect(screen.queryByText('Koordynatorzy widzą to w grafiku.')).not.toBeInTheDocument()) + }) + + it('drops the notice with the next stroke and keeps it to the person it is about', async () => { + stub() + vi.spyOn(api, 'team').mockResolvedValue(TEAM) + vi.spyOn(api, 'availability').mockResolvedValue([]) + vi.spyOn(api, 'memberAvailability').mockResolvedValue([]) + const staffing = [{ service_date: '2026-09-22', roles: ['primary' as const, 'secondary' as const], needed: 2, available: 2, scheduled: true, also_on_leave: [] }] + const replace = vi.spyOn(api, 'replaceMemberAvailabilityRange') + .mockImplementation(async () => null) + .mockImplementationOnce(async (_member, input) => ({ ...entry('unavailable', input.starts_on, input.ends_on), staffing })) + renderScreen() + const person = await screen.findByRole('combobox', { name: 'Osoba' }) + const beata = (await screen.findByRole('option', { name: 'Beata Lis' })).getAttribute('value') + fireEvent.change(person, { target: { value: beata } }) + await idleCalendar() + + fireEvent.click(cell(/wt 22-09-2026/)) + const notice = (await screen.findByText('Koordynatorzy widzą to w grafiku.')).closest('.box') as HTMLElement + expect(notice).toHaveTextContent('Zapisano: wt 22 wrz „nie mogę”wt 22 wrz: Do PRIMARY i SECONDARY zostają wtedy 2 osoby, bez rezerwy.') + + // It is about Beata's days: the coordinator's own calendar does not carry it. + fireEvent.change(person, { target: { value: '' } }) + await waitFor(() => expect(screen.queryByText('Koordynatorzy widzą to w grafiku.')).not.toBeInTheDocument()) + fireEvent.change(person, { target: { value: beata } }) + expect(await screen.findByText('Koordynatorzy widzą to w grafiku.')).toBeInTheDocument() + + fireEvent.click(cell(/śr 23-09-2026/)) + await waitFor(() => expect(replace).toHaveBeenCalledTimes(2)) + await waitFor(() => expect(screen.queryByText('Koordynatorzy widzą to w grafiku.')).not.toBeInTheDocument()) + }) + it('says that duties handed over stay where they are when a leave is erased', async () => { stub() saving([entry('leave', '2026-09-21', '2026-09-25', 'wyjazd')]) diff --git a/frontend/src/screens/Mine.tsx b/frontend/src/screens/Mine.tsx index 6abc856c..b8cc512b 100644 --- a/frontend/src/screens/Mine.tsx +++ b/frontend/src/screens/Mine.tsx @@ -10,6 +10,7 @@ import { CalendarData, FeedToken, FeedTokenCreated, + StaffingNote, SwapRequest, UserRole, api, @@ -17,7 +18,7 @@ import { import { messages, useMessages } from '../i18n' import { meKey } from '../session' import { isPolishPhone, phoneText } from '../lib/phone' -import { blocksDuty } from '../lib/calendar' +import { blocksDuty, staffingRuns } from '../lib/calendar' import { availabilityCodes, availabilityLabels, availabilityTone, firstName, roleLabels, swapStatusLabels } from '../lib/labels' import { roleLabels as accountRoleLabels } from '../lib/nav' import { DEVIATION_SCALE, deviationWords, monthlyTotals, totalBalance } from '../lib/fairness' @@ -533,7 +534,7 @@ function AvailabilitySection({ role, hasTeamMember, displayName, month, onStepMo target: string onTarget: (target: string) => void }) { - const { mine: m, common } = useMessages() + const { mine: m, common, schedule } = useMessages() const t = m.availability const reasonOf = m.calendar.reason const roleWords = roleLabels() @@ -596,6 +597,9 @@ function AvailabilitySection({ role, hasTeamMember, displayName, month, onStepMo // The leave saved by the last stroke, until the next stroke or its Undo: // what it changes and the weekends it leaves open are said below the calendar. const [paintedLeave, setPaintedLeave] = useState(null) + // The roles the last stroke leaves with no reserve, as the server counted + // them when it saved: a notice until the next stroke or its Undo. + const [staffing, setStaffing] = useState<{ command: PaintCommand; rows: StaffingNote[] } | null>(null) const config = usePublicConfig() const save = (command: PaintCommand) => { const input: AvailabilityRangeInput = { @@ -622,7 +626,10 @@ function AvailabilitySection({ role, hasTeamMember, displayName, month, onStepMo mutationFn: ({ command }) => (command.member ? api.undoMemberAvailabilityRange(command.member, command.undoId) : api.undoAvailabilityRange(command.undoId)), - onSuccess: (_result, { command }) => setPaintedLeave((leave) => (leave?.undoId === command.undoId ? null : leave)), + onSuccess: (_result, { command }) => { + setPaintedLeave((leave) => (leave?.undoId === command.undoId ? null : leave)) + setStaffing((notice) => (notice?.command.undoId === command.undoId ? null : notice)) + }, onSettled: (_result, _error, { command }) => reload(command), }) const paint = useMutation({ @@ -660,8 +667,9 @@ function AvailabilitySection({ role, hasTeamMember, displayName, month, onStepMo if (command.brush === 'leave' && error instanceof ApiError && error.status === 409) setRefusal({ member: command.member, range, reason: error.message }) else toast.error(t.notSaved(range), { description: error.message }) }, - onSettled: (_result, error, command) => { + onSettled: (saved, error, command) => { setPaintedLeave(!error && command.brush === 'leave' ? command : null) + setStaffing(saved?.staffing?.length ? { command, rows: saved.staffing } : null) return reload(command) }, }) @@ -680,6 +688,7 @@ function AvailabilitySection({ role, hasTeamMember, displayName, month, onStepMo if (kind === 'leave') closeIntro() setRefusal(null) setPaintedLeave(null) + setStaffing(null) paint.mutate({ member, startsOn, @@ -875,6 +884,22 @@ function AvailabilitySection({ role, hasTeamMember, displayName, month, onStepMo )} + {staffing?.command.member === member && ( + + {/* One line per run of days that say the same: who else is on leave, and how many people are left. */} + {staffingRuns(staffing.rows, (row) => `${row.scheduled}|${row.also_on_leave}`).map((run) => { + const roles = schedule.staffChange.roleList(run.roles.map((item) => roleWords[item])) + let left = t.staffing.unscheduled(daysBetween(run.service_date, run.ends_on) + 1, roles, run.available) + if (run.scheduled) left = run.available < run.needed ? t.staffing.short(roles, run.needed - run.available) : t.staffing.noReserve(roles, run.available) + return ( +

+ {t.staffing.when(rangeText(run.service_date, run.ends_on), run.also_on_leave)} {left} +
+ ) + })} +
{t.staffing.coordinatorsSee}
+ + )} )} diff --git a/frontend/src/screens/Schedule.tsx b/frontend/src/screens/Schedule.tsx index aa112a7a..b5b84b93 100644 --- a/frontend/src/screens/Schedule.tsx +++ b/frontend/src/screens/Schedule.tsx @@ -40,8 +40,8 @@ function zoomOf(query: URLSearchParams, range: CalendarRange | null): MatrixZoom } /** - * The full schedule: the same matrix as on "Teraz" without the risk row, - * over any range, two to eight weeks per screen, as a matrix or a day list, + * The full schedule: the same matrix as on "Teraz" with no risk chips but + * those of roles left without reserve, over any range, two to eight weeks per screen, as a matrix or a day list, * with the day inspector. The start, the zoom, the "only on duty" filter and * the view live in the URL (`grafik?od=2026-09-14&zoom=8&tylko=z-dyzurem&widok=lista`) * so a view survives a refresh and can be sent as a link; an older link with `od` and From af6bc481d9905b6fdf38f60cd476bc83876b9afb Mon Sep 17 00:00:00 2001 From: lowicz Date: Thu, 3 Dec 2026 01:17:43 +0100 Subject: [PATCH 2/5] no-mistakes(review): name each role when only one of the pair is short --- backend/src/oncall/domain/staffing.py | 25 ++++++++--------- backend/tests/domain/test_staffing.py | 28 +++++++++++++++++++ docs/en/uzytkownik/dyzury.md | 3 +- docs/uzytkownik/dyzury.md | 3 +- .../docs-pl-uzytkownik-dyzury.html | 3 +- 5 files changed, 46 insertions(+), 16 deletions(-) diff --git a/backend/src/oncall/domain/staffing.py b/backend/src/oncall/domain/staffing.py index fce98188..2db592b9 100644 --- a/backend/src/oncall/domain/staffing.py +++ b/backend/src/oncall/domain/staffing.py @@ -38,9 +38,8 @@ def _counts( role_sets: Iterable[tuple[AssignmentRole, ...]], needed: int, ) -> list[Staffing]: - """The count for each set of roles that an entry leaves with no reserve. - People eligible for none of the roles are not counted, and a team this - small with everyone available has nothing to say about entries.""" + """The count for each set of roles. People eligible for none of the roles + are not counted.""" rows = [] for roles in role_sets: qualified = [ @@ -48,8 +47,7 @@ def _counts( ] away = tuple(member for member in qualified if member.is_unavailable(day)) available = len(qualified) - len(away) - if away and available <= needed: - rows.append(Staffing(day, roles, available, needed, away)) + rows.append(Staffing(day, roles, available, needed, away)) return rows @@ -60,20 +58,21 @@ def staffing_without_reserve( 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; the pair speaks for its two roles - when it is at least as badly off as either, otherwise each role speaks for - itself. The 11-19 shift needs one person on a working day, who may be on - call as well.""" + 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 and all(pair[0].short >= row.short for row in rows): - rows = pair + [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 += rows + result += [row for row in rows if row.away and row.available <= row.needed] return result diff --git a/backend/tests/domain/test_staffing.py b/backend/tests/domain/test_staffing.py index 31306c0d..5cda6c08 100644 --- a/backend/tests/domain/test_staffing.py +++ b/backend/tests/domain/test_staffing.py @@ -82,6 +82,34 @@ def test_the_pair_is_not_named_when_one_of_its_roles_is_worse_off() -> None: 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), diff --git a/docs/en/uzytkownik/dyzury.md b/docs/en/uzytkownik/dyzury.md index 81396cb1..333be2a9 100644 --- a/docs/en/uzytkownik/dyzury.md +++ b/docs/en/uzytkownik/dyzury.md @@ -233,7 +233,8 @@ 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`. +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 diff --git a/docs/uzytkownik/dyzury.md b/docs/uzytkownik/dyzury.md index 35ecbcc3..af5f7ae2 100644 --- a/docs/uzytkownik/dyzury.md +++ b/docs/uzytkownik/dyzury.md @@ -224,7 +224,8 @@ 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`. +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ść diff --git a/frontend/scripts/__snapshots__/docs-pl-uzytkownik-dyzury.html b/frontend/scripts/__snapshots__/docs-pl-uzytkownik-dyzury.html index a0ca95b4..daaa2b43 100644 --- a/frontend/scripts/__snapshots__/docs-pl-uzytkownik-dyzury.html +++ b/frontend/scripts/__snapshots__/docs-pl-uzytkownik-dyzury.html @@ -327,7 +327,8 @@

Ryzyka w zakresie

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.

+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.