Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
95 changes: 94 additions & 1 deletion backend/contracts/openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -572,6 +572,13 @@
],
"title": "Note"
},
"staffing": {
"items": {
"$ref": "#/components/schemas/StaffingNoteResponse"
},
"title": "Staffing",
"type": "array"
},
"starts_on": {
"format": "date",
"title": "Starts On",
Expand Down Expand Up @@ -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",
Expand All @@ -1303,7 +1317,8 @@
"team_has_members",
"assignments",
"availability",
"leaves"
"leaves",
"staffing"
],
"title": "CalendarResponse",
"type": "object"
Expand Down Expand Up @@ -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.",
Expand Down
15 changes: 15 additions & 0 deletions backend/src/oncall/domain/availability/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand All @@ -144,6 +158,7 @@ class AvailabilityDeclared:
#: remove them.
duty_conflicts: tuple[Duty, ...]
warning: str | None
staffing: tuple[StaffingNote, ...] = ()


@dataclass(frozen=True)
Expand Down
46 changes: 45 additions & 1 deletion backend/src/oncall/domain/availability/use_cases.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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 ()
),
)


Expand Down
4 changes: 4 additions & 0 deletions backend/src/oncall/domain/calendar/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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)
Expand Down
25 changes: 24 additions & 1 deletion backend/src/oncall/domain/calendar/use_cases.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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 [],
)


Expand Down
78 changes: 78 additions & 0 deletions backend/src/oncall/domain/staffing.py
Original file line number Diff line number Diff line change
@@ -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
Loading