mirror of
https://github.com/Sea-Haven-Industries/afterhours-shift-manager.git
synced 2026-09-30 05:33:12 +00:00
feat(schedule): align the work week with Sunday-Saturday payroll (DEV-300) (#282)
* feat(schedule): align the work week with Sunday-Saturday payroll Saturday night stays in the week that ends Saturday, and the first Flex close skips dates already sent. * fix(slack-bot): show the last pay close on Sunday The Monday 7am row for the week that just ended is not written yet, so /oncall pay now falls back to the prior close.
This commit is contained in:
parent
7b5009fb55
commit
470e00affb
16 changed files with 372 additions and 82 deletions
|
|
@ -10,6 +10,14 @@ fine and still supported.
|
|||
|
||||
---
|
||||
|
||||
## v1.17.0 — September 25, 2026
|
||||
|
||||
**The work week now runs Sunday through Saturday, matching payroll.** The Monday
|
||||
7am schedule post and pay summary use that week. A Saturday night shift (5pm
|
||||
Saturday through 8am Sunday) stays in the Saturday week. Sunday day and Sunday
|
||||
night open the next week. The first pay close after this change skips any date
|
||||
already sent to Flex, so that Sunday is not paid twice.
|
||||
|
||||
## v1.16.0 — September 21, 2026
|
||||
|
||||
**After Hours is available in the employee portal, and Slack still works.** Employees
|
||||
|
|
|
|||
10
README.md
10
README.md
|
|
@ -11,6 +11,8 @@ Slack bot for managing after-hours on-call shifts at Sea Haven Industries. Emplo
|
|||
|
||||
A recurring weekly schedule assigns employees to after-hours phone duty. Weekend shifts are split into Day (8am-5pm) and Night (5pm-8am). Any unassigned shift shows as **Available** in Slack with a pickup button. When someone picks up or drops a shift for today, the 3CX queue is updated immediately. Future changes take effect when the ring scheduler runs at 8am daily and 5pm on weekends.
|
||||
|
||||
The work week runs Sunday through Saturday, matching payroll. A Saturday night shift (5pm Saturday through 8am Sunday) stays in the Saturday week. Sunday day and Sunday night open the next week. The Monday 7am post shows the week that started the day before, plus the following week, and the pay summary covers the previous Sunday through Saturday.
|
||||
|
||||
The weekly schedule post is updated live when shifts change, and the previous week's post is automatically deleted when the new one goes out.
|
||||
|
||||
The bot also has an **About** page: open the bot in Slack and click its **Home** tab to see what it does, the full command list, and the latest "What's New" (see [Releases & Versioning](#releases--versioning)).
|
||||
|
|
@ -28,7 +30,7 @@ Employees can do the same pick, drop, swap, and admin work from the internal por
|
|||
| `/oncall swap <date> @person` | Request a swap — the other person gets an Accept/Decline DM and the shift only moves once they accept |
|
||||
| `/oncall register <ext>` | Link your Slack account to your phone extension |
|
||||
| `/oncall roster` | Show all employees and their link status |
|
||||
| `/oncall pay` | Show last week's bonus pay summary |
|
||||
| `/oncall pay` | Show last week's bonus pay summary (Sunday through Saturday) |
|
||||
| `/oncall rate` | Show current shift pay rates |
|
||||
| `/oncall rate default <amount>` | Set the default per-shift rate |
|
||||
| `/oncall rate <ext> <amount>` | Set a per-person shift rate |
|
||||
|
|
@ -74,7 +76,7 @@ Fargate is the live path. These `src/*/app.py` zip sources remain for `scripts/p
|
|||
| Handler | Former trigger | Purpose |
|
||||
|---|---|---|
|
||||
| `afterhours-shift-manager` | API Gateway (POST /slack/events) | Slack bot — handles `/oncall` commands and interactive buttons |
|
||||
| `afterhours-weekly-post` | EventBridge (Monday 7am ET) | Posts weekly schedule to Slack, sends pay report email |
|
||||
| `afterhours-weekly-post` | EventBridge (Monday 7am ET) | Posts the Sunday-Saturday schedule and the previous week's pay summary |
|
||||
| `afterhours-roster-sync` | EventBridge (daily 6am ET) | Syncs employee roster from 3CX |
|
||||
| `afterhours-portal-api` | API Gateway (ANY /api/shifts, ANY /api/shifts/{proxy+}) | Cognito-authenticated employee/admin shift API for the internal portal |
|
||||
| `afterhours-ring-scheduler` | EventBridge (daily 8am ET + weekend 5pm ET) | Updates 3CX queue routing based on who's on shift |
|
||||
|
|
@ -86,7 +88,7 @@ Fargate is the live path. These `src/*/app.py` zip sources remain for `scripts/p
|
|||
src/
|
||||
server/ Flask + gunicorn + SQS worker (Fargate)
|
||||
slack-bot/ Slack Bolt app; leftover zip source for packaging; ships CHANGELOG.md for App Home
|
||||
weekly-post/ Monday schedule + pay post (leftover zip source for packaging)
|
||||
weekly-post/ Monday 7am schedule post and prior Sunday-Saturday pay (leftover zip source)
|
||||
roster-sync/ Daily 3CX roster sync (leftover zip source for packaging)
|
||||
roster-api/ HTTP PUT/DELETE /roster for identity hire/offboard (leftover zip source for packaging)
|
||||
portal-api/ Cognito employee/admin shift API for the internal portal (leftover zip source for packaging)
|
||||
|
|
@ -111,7 +113,7 @@ Single table with `PK` / `SK` keys:
|
|||
| `HOLIDAY` | `<YYYY-MM-DD>` | Holiday day shift (one per date): `slots` (int), `assignees` (MAP keyed by extension — `{"114": {name, claimed_at}}`), `multiplier` (Decimal, defaults to `CONFIG.holiday_multiplier` = 1.5, overridable per holiday), `label`, `created_at`, `created_by`, `activated` (bool), `schedule_names` (list) |
|
||||
| `PICKUP_REQUEST` | `<YYYY-MM-DD>[-DAY]#<ext>` | Pending late-pickup awaiting admin approval: `requester_ext`, `requester_name`, `requester_slack`, `shift_type`, `is_holiday`, `status`, `created_at`, `expires_at` (TTL = shift end) |
|
||||
| `SCHEDULE_POST` | `<channel_id>` | Current schedule message timestamp |
|
||||
| `PAY` | `<YYYY-MM-DD>` | Weekly pay record (Monday date key) |
|
||||
| `PAY` | `<YYYY-MM-DD>` | Weekly pay record (Sunday date key; older rows may use Monday) |
|
||||
| `CONFIG` | `CONFIG` | Settings: shift_rate, fallback_extension, admin_users, `ring_group`, `holiday_multiplier` (default holiday pay multiplier, 1.5), `holiday_queue` (3CX queue repointed during holidays, default 802), `ivr_number` (3CX IVR repointed during holidays, default 800), `captured_ivr_routes` (original IVR routes saved at holiday activation, restored at deactivation) |
|
||||
|
||||
Weekend day-shift rows use a `-DAY` suffix on the SK (e.g. `OVERRIDE` / `2026-04-05-DAY`). The table has TTL enabled on `expires_at` so abandoned pending swaps and pickup requests self-clean.
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import re
|
|||
from datetime import datetime, timedelta
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from shared.schedule import WEEKEND_DAYS
|
||||
from shared.schedule import WEEKEND_DAYS, week_start
|
||||
|
||||
EASTERN = ZoneInfo("America/New_York")
|
||||
|
||||
|
|
@ -116,11 +116,11 @@ def build_week_schedule(schedule, start_date: datetime | None = None) -> list[di
|
|||
|
||||
Args:
|
||||
schedule: ShiftSchedule instance
|
||||
start_date: Monday of the first week to show. Defaults to current week's Monday.
|
||||
start_date: Sunday of the first week to show. Defaults to current week's Sunday.
|
||||
"""
|
||||
now = datetime.now(EASTERN)
|
||||
if start_date is None:
|
||||
start_date = now - timedelta(days=now.weekday()) # Monday of this week
|
||||
start_date = week_start(now)
|
||||
start_date = start_date.replace(hour=0, minute=0, second=0, microsecond=0)
|
||||
|
||||
today_str = now.strftime("%Y-%m-%d")
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ import re
|
|||
from datetime import datetime, timedelta
|
||||
from decimal import Decimal
|
||||
|
||||
from shared.schedule import FALLBACK_EXTENSION, WEEKEND_DAYS, ShiftSchedule
|
||||
from shared.schedule import FALLBACK_EXTENSION, WEEKEND_DAYS, ShiftSchedule, week_start
|
||||
from shared.shift_clock import (
|
||||
EASTERN,
|
||||
holiday_window_active,
|
||||
|
|
@ -101,11 +101,11 @@ def _slot_payload(
|
|||
|
||||
|
||||
def week_range(which: str) -> tuple[datetime, str]:
|
||||
"""Sunday–Saturday window. ``next`` is the following Sunday."""
|
||||
now = datetime.now(EASTERN)
|
||||
this_monday = (now - timedelta(days=now.weekday())).replace(
|
||||
hour=0, minute=0, second=0, microsecond=0
|
||||
)
|
||||
start = this_monday if which != "next" else this_monday + timedelta(days=7)
|
||||
start = week_start(now)
|
||||
if which == "next":
|
||||
start = start + timedelta(days=7)
|
||||
label = "this" if which != "next" else "next"
|
||||
return start, label
|
||||
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ Single-table design:
|
|||
"""
|
||||
|
||||
import os
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timedelta
|
||||
from decimal import Decimal
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
|
|
@ -36,6 +36,21 @@ DEFAULT_HOLIDAY_QUEUE = "802"
|
|||
DEFAULT_IVR_NUMBER = "800"
|
||||
|
||||
|
||||
def week_start(when: datetime) -> datetime:
|
||||
"""Sunday 00:00 Eastern of the Sun–Sat work week that contains ``when``.
|
||||
|
||||
Shifts belong to the week of their start date. A Saturday night shift
|
||||
(5pm Saturday through 8am Sunday) stays in the week that ends Saturday.
|
||||
Sunday day and Sunday night open the next week.
|
||||
"""
|
||||
if when.tzinfo is None:
|
||||
when = when.replace(tzinfo=EASTERN)
|
||||
else:
|
||||
when = when.astimezone(EASTERN)
|
||||
when = when.replace(hour=0, minute=0, second=0, microsecond=0)
|
||||
return when - timedelta(days=(when.weekday() + 1) % 7)
|
||||
|
||||
|
||||
def determine_shift_type(now: datetime | None = None) -> str:
|
||||
"""Return the currently active shift type: 'day' or 'night'.
|
||||
|
||||
|
|
@ -643,12 +658,27 @@ class ShiftSchedule:
|
|||
# ── Pay records ─────────────────────────────────────────────────────
|
||||
|
||||
def get_pay_record(self, week_key: str) -> dict | None:
|
||||
"""Get a pay record by week key (e.g. '2026-04-06')."""
|
||||
"""Get a pay record by week key (the Sunday that opens the week)."""
|
||||
resp = self.table.get_item(Key={"PK": "PAY", "SK": week_key})
|
||||
return resp.get("Item")
|
||||
|
||||
def list_pay_records(self) -> list[dict]:
|
||||
"""Return every PAY row, including legacy Monday-keyed weeks."""
|
||||
items: list[dict] = []
|
||||
kwargs: dict = {"KeyConditionExpression": Key("PK").eq("PAY")}
|
||||
while True:
|
||||
resp = self.table.query(**kwargs)
|
||||
items.extend(resp.get("Items", []))
|
||||
last = resp.get("LastEvaluatedKey")
|
||||
if not last:
|
||||
return items
|
||||
kwargs["ExclusiveStartKey"] = last
|
||||
|
||||
def save_pay_record(self, week_key: str, record: dict) -> None:
|
||||
"""Save a weekly pay summary. week_key is the Monday date string."""
|
||||
"""Save a weekly pay summary. week_key is the Sunday date string.
|
||||
|
||||
Older rows may still be keyed by Monday. New writes use Sunday.
|
||||
"""
|
||||
self.table.put_item(Item={"PK": "PAY", "SK": week_key, **record})
|
||||
|
||||
# ── Config ──────────────────────────────────────────────────────────
|
||||
|
|
|
|||
|
|
@ -19,7 +19,7 @@ from shared.blocks import (
|
|||
build_week_schedule,
|
||||
)
|
||||
from shared.ring_scheduler import update_queue_routing
|
||||
from shared.schedule import FALLBACK_EXTENSION
|
||||
from shared.schedule import FALLBACK_EXTENSION, week_start
|
||||
from shared.secrets import get_secret
|
||||
from shared.shift_clock import is_active_shift_type, is_today
|
||||
from shared.three_cx_client import ThreeCXClient, oauth_client
|
||||
|
|
@ -217,10 +217,10 @@ def delete_holiday_schedules(schedule_names: list[str]) -> None:
|
|||
|
||||
def schedule_fallback_text() -> str:
|
||||
now = datetime.now(EASTERN)
|
||||
this_monday = now - timedelta(days=now.weekday())
|
||||
end_date = this_monday + timedelta(days=13)
|
||||
start = week_start(now)
|
||||
end_date = start + timedelta(days=13)
|
||||
return (
|
||||
f"After-Hours Schedule — {this_monday.strftime('%b %-d')} "
|
||||
f"After-Hours Schedule — {start.strftime('%b %-d')} "
|
||||
f"to {end_date.strftime('%b %-d')}"
|
||||
)
|
||||
|
||||
|
|
|
|||
|
|
@ -10,6 +10,14 @@ fine and still supported.
|
|||
|
||||
---
|
||||
|
||||
## v1.17.0 — September 25, 2026
|
||||
|
||||
**The work week now runs Sunday through Saturday, matching payroll.** The Monday
|
||||
7am schedule post and pay summary use that week. A Saturday night shift (5pm
|
||||
Saturday through 8am Sunday) stays in the Saturday week. Sunday day and Sunday
|
||||
night open the next week. The first pay close after this change skips any date
|
||||
already sent to Flex, so that Sunday is not paid twice.
|
||||
|
||||
## v1.16.0 — September 21, 2026
|
||||
|
||||
**After Hours is available in the employee portal, and Slack still works.** Employees
|
||||
|
|
|
|||
|
|
@ -44,6 +44,7 @@ from shared.schedule import (
|
|||
ExtensionAlreadyRegistered,
|
||||
ShiftSchedule,
|
||||
determine_shift_type,
|
||||
week_start,
|
||||
)
|
||||
from shared.secrets import get_secret
|
||||
from shared.three_cx_client import ThreeCXClient
|
||||
|
|
@ -345,10 +346,10 @@ def _droppable_shifts(schedule, date_str, day_name, employee_ext) -> list[str]:
|
|||
def _schedule_fallback_text() -> str:
|
||||
"""Notification fallback text for the two-week schedule post."""
|
||||
now = datetime.now(EASTERN)
|
||||
this_monday = now - timedelta(days=now.weekday())
|
||||
end_date = this_monday + timedelta(days=13)
|
||||
start = week_start(now)
|
||||
end_date = start + timedelta(days=13)
|
||||
return (
|
||||
f"After-Hours Schedule — {this_monday.strftime('%b %-d')} "
|
||||
f"After-Hours Schedule — {start.strftime('%b %-d')} "
|
||||
f"to {end_date.strftime('%b %-d')}"
|
||||
)
|
||||
|
||||
|
|
@ -641,25 +642,50 @@ def _show_schedule(respond, schedule):
|
|||
|
||||
def _show_next_week(respond, schedule):
|
||||
now = datetime.now(EASTERN)
|
||||
# Jump 2 weeks ahead from this week's Monday
|
||||
this_monday = now - timedelta(days=now.weekday())
|
||||
next_start = this_monday + timedelta(days=14)
|
||||
# The default view is already two weeks, so "next" starts two Sundays ahead.
|
||||
next_start = week_start(now) + timedelta(days=14)
|
||||
blocks = build_week_schedule(schedule, start_date=next_start)
|
||||
respond(blocks=blocks)
|
||||
|
||||
|
||||
def _pay_week_bounds(pay_record: dict) -> tuple[datetime, datetime]:
|
||||
"""Label bounds for a pay record.
|
||||
|
||||
New rows are Sunday–Saturday. A cutover row may store a shorter
|
||||
``window_start``/``window_end``. Legacy rows are Monday–Sunday via
|
||||
``week_start`` plus six days.
|
||||
"""
|
||||
start = datetime.strptime(
|
||||
pay_record.get("window_start") or pay_record["week_start"], "%Y-%m-%d"
|
||||
)
|
||||
if pay_record.get("window_end"):
|
||||
end = datetime.strptime(pay_record["window_end"], "%Y-%m-%d")
|
||||
else:
|
||||
end = start + timedelta(days=6)
|
||||
return start, end
|
||||
|
||||
|
||||
def _show_pay(respond, schedule):
|
||||
now = datetime.now(EASTERN)
|
||||
# Show last completed week's pay (previous Monday–Sunday)
|
||||
this_monday = now - timedelta(days=now.weekday())
|
||||
prev_monday = this_monday - timedelta(days=7)
|
||||
week_key = prev_monday.strftime("%Y-%m-%d")
|
||||
|
||||
pay_record = schedule.get_pay_record(week_key)
|
||||
# The Monday 7am close writes the Sun–Sat week that ended Saturday. On
|
||||
# Sunday, and on Monday before that close, that row is not written yet, so
|
||||
# also try the prior week's Sunday key and the legacy Monday keys.
|
||||
prev_start = week_start(now) - timedelta(days=7)
|
||||
pay_record = None
|
||||
for start in (
|
||||
prev_start,
|
||||
prev_start + timedelta(days=1),
|
||||
prev_start - timedelta(days=7),
|
||||
prev_start - timedelta(days=6),
|
||||
):
|
||||
record = schedule.get_pay_record(start.strftime("%Y-%m-%d"))
|
||||
if record and record.get("breakdown"):
|
||||
pay_record = record
|
||||
break
|
||||
if pay_record and pay_record.get("breakdown"):
|
||||
prev_sunday = prev_monday + timedelta(days=6)
|
||||
label_start, label_end = _pay_week_bounds(pay_record)
|
||||
week_label = (
|
||||
f"{prev_monday.strftime('%b %-d')} to {prev_sunday.strftime('%b %-d')}"
|
||||
f"{label_start.strftime('%b %-d')} to {label_end.strftime('%b %-d')}"
|
||||
)
|
||||
blocks = build_pay_summary_blocks(
|
||||
week_label, pay_record["breakdown"], pay_record["totals"]
|
||||
|
|
@ -667,7 +693,7 @@ def _show_pay(respond, schedule):
|
|||
respond(blocks=blocks)
|
||||
else:
|
||||
respond(
|
||||
text=f"No pay record found for the week of {prev_monday.strftime('%b %-d')}."
|
||||
text=f"No pay record found for the week of {prev_start.strftime('%b %-d')}."
|
||||
)
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
"""Lambda handler — posts the weekly on-call schedule and previous week's pay summary
|
||||
to Slack every Monday at 7am ET, and enqueues after-hours dollars for Flex."""
|
||||
"""Lambda handler — posts the two-week on-call schedule and the previous
|
||||
Sunday–Saturday pay summary to Slack every Monday at 7am ET, and enqueues
|
||||
after-hours dollars for Flex."""
|
||||
|
||||
import json
|
||||
import logging
|
||||
|
|
@ -13,7 +14,7 @@ from slack_sdk import WebClient
|
|||
|
||||
import shared.sentry_init # noqa: F401
|
||||
from shared.blocks import build_pay_summary_blocks, build_week_schedule
|
||||
from shared.schedule import FALLBACK_EXTENSION, WEEKEND_DAYS, ShiftSchedule
|
||||
from shared.schedule import FALLBACK_EXTENSION, WEEKEND_DAYS, ShiftSchedule, week_start
|
||||
from shared.secrets import get_secret
|
||||
|
||||
logger = logging.getLogger()
|
||||
|
|
@ -22,16 +23,6 @@ logger.setLevel(logging.INFO)
|
|||
EASTERN = ZoneInfo("America/New_York")
|
||||
KIND_AFTER_HOURS = "after_hours"
|
||||
|
||||
DAY_ORDER = [
|
||||
"Monday",
|
||||
"Tuesday",
|
||||
"Wednesday",
|
||||
"Thursday",
|
||||
"Friday",
|
||||
"Saturday",
|
||||
"Sunday",
|
||||
]
|
||||
|
||||
|
||||
def _record_pay_line(
|
||||
breakdown, totals, *, date, day_label, name, ext, effective, base_rate, is_holiday
|
||||
|
|
@ -136,15 +127,20 @@ def _add_shift_to_pay(schedule, breakdown, totals, date, day_name, shift_type="n
|
|||
)
|
||||
|
||||
|
||||
def _calculate_weekly_pay(schedule: ShiftSchedule, week_start: datetime) -> dict:
|
||||
"""Calculate pay for a Mon–Sun week. Returns pay record dict."""
|
||||
def _calculate_weekly_pay(schedule: ShiftSchedule, week_start_dt: datetime) -> dict:
|
||||
"""Calculate pay for a Sun–Sat week. Returns pay record dict.
|
||||
|
||||
``week_start_dt`` is the Sunday that opens the week. Each shift is attributed
|
||||
by its start date, so Saturday night stays in this week and the following
|
||||
Sunday does not.
|
||||
"""
|
||||
default_rate = schedule.get_shift_rate()
|
||||
breakdown = []
|
||||
totals = {}
|
||||
|
||||
for i in range(7):
|
||||
date = week_start + timedelta(days=i)
|
||||
day_name = DAY_ORDER[i]
|
||||
date = week_start_dt + timedelta(days=i)
|
||||
day_name = date.strftime("%A")
|
||||
date_str = date.strftime("%Y-%m-%d")
|
||||
|
||||
# Day shifts (8am–5pm) exist on weekends and on holidays. Holidays are
|
||||
|
|
@ -157,17 +153,104 @@ def _calculate_weekly_pay(schedule: ShiftSchedule, week_start: datetime) -> dict
|
|||
_add_shift_to_pay(schedule, breakdown, totals, date, day_name, "night")
|
||||
|
||||
return {
|
||||
"week_start": week_start.strftime("%Y-%m-%d"),
|
||||
"week_start": week_start_dt.strftime("%Y-%m-%d"),
|
||||
"default_rate": str(default_rate),
|
||||
"breakdown": breakdown,
|
||||
"totals": totals,
|
||||
}
|
||||
|
||||
|
||||
def _already_sent_dates(schedule: ShiftSchedule, week_key: str) -> set[str]:
|
||||
"""Dates already included in some other pay row that Flex has received.
|
||||
|
||||
The current week's own row is ignored so a retry can rebuild it.
|
||||
"""
|
||||
sent: set[str] = set()
|
||||
for record in schedule.list_pay_records():
|
||||
if record.get("SK") == week_key:
|
||||
continue
|
||||
if not record.get("checkcomponents_sent"):
|
||||
continue
|
||||
for line in record.get("breakdown") or []:
|
||||
date = line.get("date")
|
||||
if date:
|
||||
sent.add(str(date))
|
||||
return sent
|
||||
|
||||
|
||||
def _rebuild_totals(breakdown: list[dict]) -> dict:
|
||||
totals: dict = {}
|
||||
for line in breakdown:
|
||||
name = line["name"]
|
||||
if name not in totals:
|
||||
totals[name] = {
|
||||
"shifts": 0,
|
||||
"total": Decimal("0"),
|
||||
"extension": line["extension"],
|
||||
"rate": line.get("base_rate", line["rate"]),
|
||||
"holiday_shifts": 0,
|
||||
}
|
||||
totals[name]["shifts"] += 1
|
||||
totals[name]["total"] += Decimal(str(line["amount"]))
|
||||
if line.get("is_holiday"):
|
||||
totals[name]["holiday_shifts"] += 1
|
||||
return totals
|
||||
|
||||
|
||||
def _exclude_sent_dates(
|
||||
schedule: ShiftSchedule, pay_record: dict, week_key: str
|
||||
) -> dict:
|
||||
"""Drop dates Flex already received, and shrink the reported window.
|
||||
|
||||
The PAY key stays the Sunday that opened the computed week. When the
|
||||
leading Sunday (or any other day) was in a sent Monday–Sunday row, the
|
||||
Flex window becomes the remaining span, often Monday–Saturday once.
|
||||
"""
|
||||
sent = _already_sent_dates(schedule, week_key)
|
||||
if not sent:
|
||||
return pay_record
|
||||
start = datetime.strptime(pay_record["week_start"], "%Y-%m-%d").date()
|
||||
kept_days = []
|
||||
omitted = False
|
||||
for offset in range(7):
|
||||
day = start + timedelta(days=offset)
|
||||
if day.isoformat() in sent:
|
||||
omitted = True
|
||||
else:
|
||||
kept_days.append(day)
|
||||
if not omitted:
|
||||
return pay_record
|
||||
pay_record["breakdown"] = [
|
||||
line for line in pay_record["breakdown"] if str(line.get("date")) not in sent
|
||||
]
|
||||
pay_record["totals"] = _rebuild_totals(pay_record["breakdown"])
|
||||
if kept_days and len(kept_days) < 7:
|
||||
pay_record["window_start"] = kept_days[0].isoformat()
|
||||
pay_record["window_end"] = kept_days[-1].isoformat()
|
||||
return pay_record
|
||||
|
||||
|
||||
def _pay_week_label(pay_record: dict) -> str:
|
||||
start = datetime.strptime(
|
||||
pay_record.get("window_start") or pay_record["week_start"], "%Y-%m-%d"
|
||||
)
|
||||
if pay_record.get("window_end"):
|
||||
end = datetime.strptime(pay_record["window_end"], "%Y-%m-%d")
|
||||
else:
|
||||
end = start + timedelta(days=6)
|
||||
return f"{start.strftime('%b %-d')} to {end.strftime('%b %-d')}"
|
||||
|
||||
|
||||
def build_checkcomponents_payload(pay_record: dict) -> dict:
|
||||
"""Sibling dollar lines only. No Flex OAuth, no payPeriodId invention."""
|
||||
week_start = datetime.strptime(pay_record["week_start"], "%Y-%m-%d").date()
|
||||
window_end = week_start + timedelta(days=6)
|
||||
week_start_date = datetime.strptime(pay_record["week_start"], "%Y-%m-%d").date()
|
||||
window_end = week_start_date + timedelta(days=6)
|
||||
if pay_record.get("window_start"):
|
||||
week_start_date = datetime.strptime(
|
||||
pay_record["window_start"], "%Y-%m-%d"
|
||||
).date()
|
||||
if pay_record.get("window_end"):
|
||||
window_end = datetime.strptime(pay_record["window_end"], "%Y-%m-%d").date()
|
||||
lines = []
|
||||
for info in pay_record.get("totals", {}).values():
|
||||
ext = str(info.get("extension") or "").strip()
|
||||
|
|
@ -185,7 +268,7 @@ def build_checkcomponents_payload(pay_record: dict) -> dict:
|
|||
return {
|
||||
"type": "checkcomponents",
|
||||
"kind": KIND_AFTER_HOURS,
|
||||
"windowStart": week_start.isoformat(),
|
||||
"windowStart": week_start_date.isoformat(),
|
||||
"windowEnd": window_end.isoformat(),
|
||||
"lines": lines,
|
||||
}
|
||||
|
|
@ -222,24 +305,22 @@ def handler(event, context):
|
|||
schedule = ShiftSchedule()
|
||||
slack = WebClient(token=bot_token)
|
||||
|
||||
# --- Previous week's pay summary ---
|
||||
prev_monday = now - timedelta(days=7)
|
||||
prev_monday = prev_monday.replace(hour=0, minute=0, second=0, microsecond=0)
|
||||
pay_record = _calculate_weekly_pay(schedule, prev_monday)
|
||||
# --- Previous completed Sun–Sat pay summary ---
|
||||
# Monday 7am is after Saturday night ends (Sunday 8am), so this week is closed.
|
||||
prev_sunday = week_start(now) - timedelta(days=7)
|
||||
pay_record = _calculate_weekly_pay(schedule, prev_sunday)
|
||||
|
||||
pay_dm_user = os.environ.get("PAY_REPORT_USER")
|
||||
|
||||
week_key = prev_monday.strftime("%Y-%m-%d")
|
||||
week_key = prev_sunday.strftime("%Y-%m-%d")
|
||||
pay_record = _exclude_sent_dates(schedule, pay_record, week_key)
|
||||
if pay_record["breakdown"]:
|
||||
existing = schedule.get_pay_record(week_key)
|
||||
if existing and existing.get("checkcomponents_sent"):
|
||||
pay_record["checkcomponents_sent"] = True
|
||||
schedule.save_pay_record(week_key, pay_record)
|
||||
|
||||
prev_sunday = prev_monday + timedelta(days=6)
|
||||
week_label = (
|
||||
f"{prev_monday.strftime('%b %-d')} to {prev_sunday.strftime('%b %-d')}"
|
||||
)
|
||||
week_label = _pay_week_label(pay_record)
|
||||
pay_blocks = build_pay_summary_blocks(
|
||||
week_label, pay_record["breakdown"], pay_record["totals"]
|
||||
)
|
||||
|
|
@ -257,14 +338,14 @@ def handler(event, context):
|
|||
else:
|
||||
logger.warning("PAY_REPORT_USER not set — skipping Slack pay summary")
|
||||
|
||||
# --- Two-week schedule (always starts on Monday of this week) ---
|
||||
this_monday = now - timedelta(days=now.weekday())
|
||||
week_start = this_monday.strftime("%Y-%m-%d")
|
||||
blocks = build_week_schedule(schedule, start_date=this_monday)
|
||||
# --- Two-week schedule (starts on Sunday of this Sun–Sat week) ---
|
||||
this_sunday = week_start(now)
|
||||
schedule_week = this_sunday.strftime("%Y-%m-%d")
|
||||
blocks = build_week_schedule(schedule, start_date=this_sunday)
|
||||
|
||||
end_date = this_monday + timedelta(days=13)
|
||||
end_date = this_sunday + timedelta(days=13)
|
||||
fallback_text = (
|
||||
f"After-Hours Schedule — {this_monday.strftime('%b %-d')} "
|
||||
f"After-Hours Schedule — {this_sunday.strftime('%b %-d')} "
|
||||
f"to {end_date.strftime('%b %-d')}"
|
||||
)
|
||||
|
||||
|
|
@ -300,7 +381,7 @@ def handler(event, context):
|
|||
# deleted) ts, no-op its delete, and post a *second* schedule, orphaning
|
||||
# this one at the bottom of the channel.
|
||||
try:
|
||||
schedule.save_schedule_post(channel_id, message_ts, week_start)
|
||||
schedule.save_schedule_post(channel_id, message_ts, schedule_week)
|
||||
except Exception:
|
||||
logger.warning(
|
||||
"Failed to persist schedule post %s; rolling it back to avoid an "
|
||||
|
|
|
|||
|
|
@ -53,7 +53,7 @@ resource "aws_iam_role_policy" "holiday_scheduler" {
|
|||
locals {
|
||||
job_schedules = {
|
||||
weekly-post = {
|
||||
description = "Post weekly schedule Monday 7am Eastern"
|
||||
description = "Post weekly schedule Monday 7am Eastern; closes the Sun-Sat pay week"
|
||||
schedule = "cron(0 7 ? * MON *)"
|
||||
event = "weekly_post"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -34,6 +34,8 @@ class TestBuildWeekSchedule:
|
|||
blocks = build_week_schedule(schedule)
|
||||
assert blocks[0]["type"] == "header"
|
||||
assert "After-Hours Schedule" in blocks[0]["text"]["text"]
|
||||
# Monday 2026-06-01 belongs to the week that opened Sunday May 31.
|
||||
assert blocks[0]["text"]["text"] == "After-Hours Schedule — May 31 to Jun 13"
|
||||
assert blocks[1]["type"] == "section"
|
||||
|
||||
@freeze_time("2026-06-01 12:00:00")
|
||||
|
|
|
|||
|
|
@ -95,6 +95,7 @@ def test_snapshot_includes_weekday_holiday_day_shift(schedule, seed):
|
|||
)
|
||||
with freezegun.freeze_time("2026-06-08 12:00:00-04:00"):
|
||||
snap = snapshot(schedule, employee)
|
||||
assert snap["weekStart"] == "2026-06-07"
|
||||
wednesday = next(day for day in snap["days"] if day["date"] == "2026-06-10")
|
||||
assert wednesday["slots"][0]["kind"] == "holiday"
|
||||
assert wednesday["slots"][0]["shiftType"] == "day"
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ from shared.schedule import (
|
|||
FALLBACK_EXTENSION,
|
||||
ShiftSchedule,
|
||||
determine_shift_type,
|
||||
week_start,
|
||||
)
|
||||
|
||||
ET = ZoneInfo("America/New_York")
|
||||
|
|
@ -22,6 +23,20 @@ WED = "2026-06-03"
|
|||
HOL = "2026-07-04" # holiday date (a Saturday)
|
||||
|
||||
|
||||
class TestWeekStart:
|
||||
def test_sunday_opens_the_week(self):
|
||||
sunday = datetime(2026, 6, 7, 15, tzinfo=ET)
|
||||
assert week_start(sunday).strftime("%Y-%m-%d") == "2026-06-07"
|
||||
|
||||
def test_monday_belongs_to_the_sunday_before(self):
|
||||
monday = datetime(2026, 6, 8, 8, tzinfo=ET)
|
||||
assert week_start(monday).strftime("%Y-%m-%d") == "2026-06-07"
|
||||
|
||||
def test_saturday_stays_in_the_week_that_started_sunday(self):
|
||||
saturday = datetime(2026, 6, 13, 23, tzinfo=ET)
|
||||
assert week_start(saturday).strftime("%Y-%m-%d") == "2026-06-07"
|
||||
|
||||
|
||||
class TestDetermineShiftType:
|
||||
@pytest.mark.parametrize(
|
||||
"dt,expected",
|
||||
|
|
|
|||
|
|
@ -1,5 +1,7 @@
|
|||
"""Tests for slack-bot module-level helpers."""
|
||||
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from freezegun import freeze_time
|
||||
|
||||
# Monday 2026-06-01 08:00 ET → weekday, active shift is night.
|
||||
|
|
@ -35,6 +37,53 @@ class TestShiftTiming:
|
|||
assert slackbot_app._within_drop_lock("2026-06-02", "night") is True
|
||||
|
||||
|
||||
def _save_pay(schedule, week_key, week_start):
|
||||
schedule.save_pay_record(
|
||||
week_key,
|
||||
{
|
||||
"week_start": week_start,
|
||||
"breakdown": [
|
||||
{
|
||||
"date": week_start,
|
||||
"date_label": "day",
|
||||
"day": "Day",
|
||||
"name": "Alice",
|
||||
"extension": "114",
|
||||
"rate": 50,
|
||||
}
|
||||
],
|
||||
"totals": {
|
||||
"Alice": {
|
||||
"shifts": 1,
|
||||
"total": 50,
|
||||
"extension": "114",
|
||||
"rate": 50,
|
||||
}
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
class TestShowPay:
|
||||
@freeze_time("2026-06-08 12:00:00") # Monday 08:00 ET
|
||||
def test_falls_back_to_legacy_monday_key(self, slackbot_app, schedule):
|
||||
_save_pay(schedule, "2026-06-01", "2026-06-01")
|
||||
respond = MagicMock()
|
||||
slackbot_app._show_pay(respond, schedule)
|
||||
header = respond.call_args.kwargs["blocks"][0]["text"]["text"]
|
||||
assert "Jun 1 to Jun 7" in header
|
||||
|
||||
@freeze_time("2026-06-14 12:00:00") # Sunday 08:00 ET
|
||||
def test_sunday_shows_prior_close_before_monday_job(self, slackbot_app, schedule):
|
||||
# Monday 2026-06-08 saved the week of Sun 2026-05-31. The next close
|
||||
# (Sun 2026-06-07) is not written until Monday 2026-06-15.
|
||||
_save_pay(schedule, "2026-05-31", "2026-05-31")
|
||||
respond = MagicMock()
|
||||
slackbot_app._show_pay(respond, schedule)
|
||||
header = respond.call_args.kwargs["blocks"][0]["text"]["text"]
|
||||
assert "May 31 to Jun 6" in header
|
||||
|
||||
|
||||
class TestIsToday:
|
||||
@freeze_time(MON)
|
||||
def test_true_for_today(self, slackbot_app):
|
||||
|
|
|
|||
|
|
@ -55,21 +55,23 @@ def test_posts_schedule_and_saves_post(weeklypost_app, schedule, seed, slack, en
|
|||
assert result["message_ts"] == "999.000"
|
||||
# The new schedule post was persisted for next week's cleanup.
|
||||
assert schedule.get_schedule_post("C_TEST")["message_ts"] == "999.000"
|
||||
# Monday 2026-06-08 is inside the week that opened Sunday 2026-06-07.
|
||||
assert schedule.get_schedule_post("C_TEST")["week_start"] == "2026-06-07"
|
||||
slack.chat_postMessage.assert_called()
|
||||
sqs.send_message.assert_not_called()
|
||||
|
||||
|
||||
@freeze_time(MON_0800)
|
||||
def test_calculates_and_dms_pay(weeklypost_app, schedule, seed, slack, env, sqs):
|
||||
# Previous week (Mon 2026-06-01) had Alice on the Monday night shift.
|
||||
# Previous Sun–Sat week includes Monday 2026-06-01, Alice's night shift.
|
||||
seed.config(shift_rate="50")
|
||||
seed.weekly("Monday", "114", "Alice")
|
||||
|
||||
result = weeklypost_app.handler({"force": True}, None)
|
||||
|
||||
assert result["pay_calculated"] is True
|
||||
# Pay record saved under previous Monday's key.
|
||||
assert schedule.get_pay_record("2026-06-01") is not None
|
||||
# Pay record saved under the previous Sunday (Sun 2026-05-31 through Sat 2026-06-06).
|
||||
assert schedule.get_pay_record("2026-05-31") is not None
|
||||
# A DM went to the configured pay-report user.
|
||||
dm_calls = [
|
||||
c
|
||||
|
|
@ -81,11 +83,50 @@ def test_calculates_and_dms_pay(weeklypost_app, schedule, seed, slack, env, sqs)
|
|||
body = json.loads(sqs.send_message.call_args.kwargs["MessageBody"])
|
||||
assert body["type"] == "checkcomponents"
|
||||
assert body["kind"] == "after_hours"
|
||||
assert body["windowStart"] == "2026-06-01"
|
||||
assert body["windowEnd"] == "2026-06-07"
|
||||
assert body["windowStart"] == "2026-05-31"
|
||||
assert body["windowEnd"] == "2026-06-06"
|
||||
assert "payPeriodId" not in body
|
||||
assert body["lines"] == [{"extension": "114", "amount": "50.00"}]
|
||||
assert schedule.get_pay_record("2026-06-01")["checkcomponents_sent"] is True
|
||||
assert schedule.get_pay_record("2026-05-31")["checkcomponents_sent"] is True
|
||||
|
||||
|
||||
@freeze_time(MON_0800)
|
||||
def test_cutover_omits_sunday_already_sent(
|
||||
weeklypost_app, schedule, seed, slack, env, sqs
|
||||
):
|
||||
# Last ISO close (Mon 2026-05-25 through Sun 2026-05-31) already sent Sunday.
|
||||
# The new Sun–Sat close must drop that Sunday and report Mon–Sat.
|
||||
seed.config(shift_rate="50")
|
||||
seed.weekly("Monday", "114", "Alice")
|
||||
seed.weekly("Sunday", "114", "Alice", shift_type="day")
|
||||
schedule.save_pay_record(
|
||||
"2026-05-25",
|
||||
{
|
||||
"week_start": "2026-05-25",
|
||||
"checkcomponents_sent": True,
|
||||
"breakdown": [
|
||||
{
|
||||
"date": "2026-05-31",
|
||||
"name": "Alice",
|
||||
"extension": "114",
|
||||
"amount": "50",
|
||||
}
|
||||
],
|
||||
"totals": {},
|
||||
},
|
||||
)
|
||||
|
||||
weeklypost_app.handler({"force": True}, None)
|
||||
|
||||
record = schedule.get_pay_record("2026-05-31")
|
||||
dates = {line["date"] for line in record["breakdown"]}
|
||||
assert dates == {"2026-06-01"}
|
||||
assert record["window_start"] == "2026-06-01"
|
||||
assert record["window_end"] == "2026-06-06"
|
||||
body = json.loads(sqs.send_message.call_args.kwargs["MessageBody"])
|
||||
assert body["windowStart"] == "2026-06-01"
|
||||
assert body["windowEnd"] == "2026-06-06"
|
||||
assert body["lines"] == [{"extension": "114", "amount": "50.00"}]
|
||||
|
||||
|
||||
@freeze_time(MON_0800)
|
||||
|
|
@ -180,7 +221,7 @@ def test_empty_queue_url_skips_checkcomponents(
|
|||
|
||||
assert result["posted"] is True
|
||||
sqs.send_message.assert_not_called()
|
||||
assert "checkcomponents_sent" not in (schedule.get_pay_record("2026-06-01") or {})
|
||||
assert "checkcomponents_sent" not in (schedule.get_pay_record("2026-05-31") or {})
|
||||
|
||||
|
||||
@freeze_time(MON_0800)
|
||||
|
|
@ -199,7 +240,7 @@ def test_save_failure_does_not_enqueue_checkcomponents(
|
|||
weeklypost_app.handler({"force": True}, None)
|
||||
|
||||
sqs.send_message.assert_not_called()
|
||||
assert "checkcomponents_sent" not in (schedule.get_pay_record("2026-06-01") or {})
|
||||
assert "checkcomponents_sent" not in (schedule.get_pay_record("2026-05-31") or {})
|
||||
|
||||
|
||||
@freeze_time(MON_0800)
|
||||
|
|
@ -213,7 +254,7 @@ def test_retry_does_not_resend_checkcomponents(
|
|||
weeklypost_app.handler({"force": True}, None)
|
||||
|
||||
sqs.send_message.assert_called_once()
|
||||
assert schedule.get_pay_record("2026-06-01")["checkcomponents_sent"] is True
|
||||
assert schedule.get_pay_record("2026-05-31")["checkcomponents_sent"] is True
|
||||
|
||||
|
||||
def test_payload_skips_fallback_and_zero(weeklypost_app):
|
||||
|
|
|
|||
|
|
@ -3,8 +3,10 @@
|
|||
from datetime import datetime
|
||||
from decimal import Decimal
|
||||
|
||||
# 2026-06-01 is a Monday — required so DAY_ORDER lines up with real weekdays.
|
||||
# 2026-06-01 is a Monday. Day names come from the date, so a week may start any day.
|
||||
WEEK_START = datetime(2026, 6, 1)
|
||||
# Sunday that opens the week containing Monday 2026-06-01.
|
||||
SUNDAY_WEEK = datetime(2026, 5, 31)
|
||||
|
||||
|
||||
class TestAddShiftToPay:
|
||||
|
|
@ -64,6 +66,31 @@ class TestCalculateWeeklyPay:
|
|||
assert record["totals"]["Alice"]["shifts"] == 2
|
||||
assert record["totals"]["Alice"]["total"] == Decimal("100")
|
||||
|
||||
def test_saturday_night_stays_in_week_ending_saturday(
|
||||
self, weeklypost_app, schedule, seed
|
||||
):
|
||||
# Sat 2026-06-06 night runs into Sunday morning and stays on Saturday.
|
||||
# Sun 2026-06-07 day opens the next week. Sun 2026-05-31 day is this week.
|
||||
seed.config(shift_rate="50")
|
||||
seed.weekly("Saturday", "200", "Alice", shift_type="night")
|
||||
seed.weekly("Sunday", "201", "Bob", shift_type="day")
|
||||
record = weeklypost_app._calculate_weekly_pay(schedule, SUNDAY_WEEK)
|
||||
by_date = {line["date"]: line for line in record["breakdown"]}
|
||||
assert by_date["2026-06-06"]["name"] == "Alice"
|
||||
assert by_date["2026-06-06"]["day"].startswith("Sat")
|
||||
assert by_date["2026-05-31"]["name"] == "Bob"
|
||||
assert "2026-06-07" not in by_date
|
||||
|
||||
def test_sunday_day_opens_the_next_week(self, weeklypost_app, schedule, seed):
|
||||
seed.config(shift_rate="50")
|
||||
seed.weekly("Saturday", "200", "Alice", shift_type="night")
|
||||
seed.weekly("Sunday", "201", "Bob", shift_type="day")
|
||||
record = weeklypost_app._calculate_weekly_pay(schedule, datetime(2026, 6, 7))
|
||||
by_date = {line["date"]: line for line in record["breakdown"]}
|
||||
assert by_date["2026-06-07"]["name"] == "Bob"
|
||||
assert by_date["2026-06-13"]["name"] == "Alice"
|
||||
assert "2026-06-06" not in by_date
|
||||
|
||||
def test_empty_week_has_no_breakdown(self, weeklypost_app, schedule, seed):
|
||||
seed.config(shift_rate="50")
|
||||
record = weeklypost_app._calculate_weekly_pay(schedule, WEEK_START)
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue