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
21 changes: 20 additions & 1 deletion backend/src/oncall/domain/calendar/models.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import uuid
from collections.abc import Iterable
from dataclasses import dataclass
from datetime import date, datetime
from datetime import date, datetime, timedelta
from typing import Any

from oncall.domain.clock import business_date
Expand Down Expand Up @@ -106,6 +107,17 @@ def backfilled_on(self) -> date | None:
return None


def leave_runs(entries: Iterable[tuple[date, date]]) -> list[tuple[date, date]]:
"""One member's leave entries, those on consecutive days joined into one."""
runs: list[tuple[date, date]] = []
for first, last in sorted(entries):
if runs and runs[-1][1] + timedelta(days=1) == first:
runs[-1] = (runs[-1][0], last)
else:
runs.append((first, last))
return runs


@dataclass(frozen=True)
class CalendarMember:
id: uuid.UUID
Expand All @@ -116,6 +128,13 @@ class CalendarMember:
eligibility: tuple[RolePeriod, ...]
availability: tuple[AvailabilityNote, ...]

def leave_runs(self) -> list[tuple[date, date]]:
return leave_runs(
(entry.starts_on, entry.ends_on)
for entry in self.availability
if entry.kind == AvailabilityKind.leave
)


@dataclass(frozen=True)
class CalendarDay:
Expand Down
19 changes: 2 additions & 17 deletions backend/src/oncall/domain/calendar/use_cases.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
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.domain.vocabulary import AssignmentRole
from oncall.workdays import polish_holiday_names, polish_holidays, polish_working_days


Expand Down Expand Up @@ -215,7 +215,7 @@ async def _leaves(
found = [
(member, first, last)
for member in members
for first, last in _leave_runs(member)
for first, last in member.leave_runs()
if first <= ends_on and last >= starts_on
]
duties = list(in_range)
Expand All @@ -242,21 +242,6 @@ async def _leaves(
]


def _leave_runs(member: CalendarMember) -> list[tuple[date, date]]:
"""The member's leave entries, those on consecutive days joined into one."""
runs: list[tuple[date, date]] = []
for first, last in sorted(
(entry.starts_on, entry.ends_on)
for entry in member.availability
if entry.kind == AvailabilityKind.leave
):
if runs and runs[-1][1] + timedelta(days=1) == first:
runs[-1] = (runs[-1][0], last)
else:
runs.append((first, last))
return runs


async def dashboard(
audience: Audience,
starts_on: date | None,
Expand Down
86 changes: 80 additions & 6 deletions backend/src/oncall/domain/digest.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,29 @@
digest of its own, so nobody is written to on one. A role nobody holds is said
to be a gap rather than left out, and days no schedule in force reaches are
all gaps and still sent: those are the days a coordinator most needs the mail.

A duty whose holder has a leave entry on its day is one nobody took over. The
digest says so on that duty's line, and names who is on leave on the day it is
sent and the duties such people still hold in the seven days after it.
"""

import uuid
from collections import defaultdict
from collections.abc import Iterable
from dataclasses import dataclass
from datetime import date, datetime, timedelta
from enum import StrEnum
from typing import Protocol

from oncall.domain.calendar.models import leave_runs
from oncall.domain.ports import PublishedRoster
from oncall.domain.roster import Duty
from oncall.domain.vocabulary import AssignmentRole
from oncall.workdays import is_polish_working_day, next_working_day

#: How far past the day it is sent the digest reads the duties of people on leave.
LEAVE_HORIZON = timedelta(days=7)


class Gap(StrEnum):
"""Why a role has nobody on a day, in the words the mail says it in."""
Expand All @@ -37,6 +49,8 @@ class DayDuties:
#: In the order a day's roles are read in: PRIMARY, SECONDARY, 11–19. Each
#: with the name of whoever holds it, or why nobody does.
holders: tuple[tuple[AssignmentRole, str | Gap], ...]
#: The roles whose holder has a leave entry on this day.
held_on_leave: frozenset[AssignmentRole] = frozenset()


@dataclass(frozen=True)
Expand All @@ -45,6 +59,12 @@ class DutyDigest:

#: The working day it is sent on, then the days off that follow it.
days: tuple[DayDuties, ...]
#: Who is on leave on the day it is sent, by name, each with the last day
#: of that leave.
on_leave: tuple[tuple[str, date], ...] = ()
#: The duties of the seven days after that day whose holder is on leave
#: then: day, role and name, in the order they are read in.
leave_duties: tuple[tuple[date, AssignmentRole, str], ...] = ()

@property
def sent_on(self) -> date:
Expand All @@ -58,17 +78,52 @@ async def send(self, digest: DutyDigest) -> int:
...


class DigestTeam(Protocol):
async def leave_entries(
self, starts_on: date, ends_on: date, holding: Iterable[uuid.UUID]
) -> list[tuple[uuid.UUID, str, date, date]]:
"""The leave entries that end on `starts_on` or later, also those past
`ends_on`, of members active in the range and anyone holding a duty in
it: member, name, first and last day, by name."""
...


@dataclass(frozen=True)
class DigestPorts:
roster: PublishedRoster
team: DigestTeam
recipients: DigestRecipients


async def digest_for(working_day: date, roster: PublishedRoster) -> DutyDigest:
async def digest_for(working_day: date, ports: DigestPorts) -> DutyDigest:
"""The digest of a working day, read from the duties in force: that day
and every day before the next working one."""
and every day before the next working one, with the leaves that touch
them and the seven days after that day."""
following = next_working_day(working_day)
duties = await roster.duties_in_force(working_day, following - timedelta(days=1))
last_day = max(following - timedelta(days=1), working_day + LEAVE_HORIZON)
duties = await ports.roster.duties_in_force(working_day, last_day)
entries = await ports.team.leave_entries(
working_day,
last_day,
{duty.member_id for duty in duties.values() if duty.member_id is not None},
)
by_member: defaultdict[tuple[uuid.UUID, str], list[tuple[date, date]]] = defaultdict(list)
for member_id, name, first, last in entries:
by_member[member_id, name].append((first, last))
leaves = [
(member_id, name, first, last)
for (member_id, name), ranges in by_member.items()
for first, last in leave_runs(ranges)
]

def on_leave(duty: Duty) -> bool:
return any(
first <= duty.service_date <= last and duty.held_by(member_id, name)
for member_id, name, first, last in leaves
)

held_on_leave = {slot for slot, duty in duties.items() if on_leave(duty)}
week_ahead = [working_day + timedelta(days=offset + 1) for offset in range(LEAVE_HORIZON.days)]
days = []
for offset in range((following - working_day).days):
day = working_day + timedelta(days=offset)
Expand All @@ -81,8 +136,27 @@ async def digest_for(working_day: date, roster: PublishedRoster) -> DutyDigest:
holders.append((role, Gap.day_off))
else:
holders.append((role, Gap.unstaffed))
days.append(DayDuties(day=day, holders=tuple(holders)))
return DutyDigest(days=tuple(days))
days.append(
DayDuties(
day=day,
holders=tuple(holders),
held_on_leave=frozenset(
role for role in AssignmentRole if (day, role) in held_on_leave
),
)
)
return DutyDigest(
days=tuple(days),
on_leave=tuple(
(name, last) for _, name, first, last in leaves if first <= working_day <= last
),
leave_duties=tuple(
(day, role, duties[day, role].assignee_name)
for day in week_ahead
for role in AssignmentRole
if (day, role) in held_on_leave
),
)


async def send_daily_digest(now_local: datetime, digest_hour: int, ports: DigestPorts) -> int:
Expand All @@ -94,4 +168,4 @@ async def send_daily_digest(now_local: datetime, digest_hour: int, ports: Digest
today = now_local.date()
if now_local.hour < digest_hour or not is_polish_working_day(today):
return 0
return await ports.recipients.send(await digest_for(today, ports.roster))
return await ports.recipients.send(await digest_for(today, ports))
42 changes: 33 additions & 9 deletions backend/src/oncall/infrastructure/sqlalchemy/calendar.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from collections.abc import Iterable
from datetime import date

from sqlalchemy import select
from sqlalchemy import ColumnElement, and_, select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import joinedload, selectinload

Expand Down Expand Up @@ -113,6 +113,17 @@ async def event_deleted(self, event: CalendarEvent) -> None:
)


def _active_or_holding(
starts_on: date, ends_on: date, holding: Iterable[uuid.UUID]
) -> ColumnElement[bool]:
return and_(
TeamMember.active_from <= ends_on,
TeamMember.active_until.is_(None)
| (TeamMember.active_until >= starts_on)
| TeamMember.id.in_(set(holding)),
)


class SqlAlchemyCalendarRoster:
def __init__(self, session: AsyncSession) -> None:
self._session = session
Expand All @@ -126,14 +137,7 @@ async def members_for_range(
joinedload(TeamMember.availability).joinedload(Availability.created_by),
joinedload(TeamMember.eligibility),
)
.where(
TeamMember.active_from <= ends_on,
(
TeamMember.active_until.is_(None)
| (TeamMember.active_until >= starts_on)
| TeamMember.id.in_(set(holding))
),
)
.where(_active_or_holding(starts_on, ends_on, holding))
.order_by(TeamMember.display_name)
)
return [
Expand Down Expand Up @@ -161,6 +165,26 @@ async def members_for_range(
for row in rows.unique()
]

async def leave_entries(
self, starts_on: date, ends_on: date, holding: Iterable[uuid.UUID]
) -> list[tuple[uuid.UUID, str, date, date]]:
rows = await self._session.execute(
select(
TeamMember.id,
TeamMember.display_name,
Availability.starts_on,
Availability.ends_on,
)
.join(Availability, Availability.member_id == TeamMember.id)
.where(
Availability.kind == AvailabilityKind.leave,
Availability.ends_on >= starts_on,
_active_or_holding(starts_on, ends_on, holding),
)
.order_by(TeamMember.display_name)
)
return [(member_id, name, first, last) for member_id, name, first, last in rows]

async def on_leave(self, member_ids: Iterable[uuid.UUID], day: date) -> set[uuid.UUID]:
rows = await self._session.scalars(
select(Availability.member_id).where(
Expand Down
5 changes: 4 additions & 1 deletion backend/src/oncall/infrastructure/sqlalchemy/digest.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from sqlalchemy.ext.asyncio import AsyncSession

from oncall.domain.digest import DigestPorts, DutyDigest
from oncall.infrastructure.sqlalchemy.calendar import SqlAlchemyCalendarRoster
from oncall.infrastructure.sqlalchemy.roster import SqlAlchemyPublishedRoster
from oncall.notifications.triggers import enqueue_duty_digest

Expand All @@ -17,5 +18,7 @@ async def send(self, digest: DutyDigest) -> int:

def digest_ports(session: AsyncSession) -> DigestPorts:
return DigestPorts(
roster=SqlAlchemyPublishedRoster(session), recipients=SqlAlchemyDigestRecipients(session)
roster=SqlAlchemyPublishedRoster(session),
team=SqlAlchemyCalendarRoster(session),
recipients=SqlAlchemyDigestRecipients(session),
)
Loading