2026-04-07 18:09:19 -04:00
|
|
|
|
"""Lambda handler — posts the weekly on-call schedule and previous week's pay summary
|
2026-04-07 18:54:19 -04:00
|
|
|
|
to Slack every Monday at 7am ET, and emails the pay summary to payroll."""
|
2026-04-03 18:32:32 -04:00
|
|
|
|
|
|
|
|
|
|
import logging
|
|
|
|
|
|
import os
|
|
|
|
|
|
from datetime import datetime, timedelta
|
2026-04-07 18:59:52 -04:00
|
|
|
|
from decimal import Decimal
|
2026-04-03 18:32:32 -04:00
|
|
|
|
from zoneinfo import ZoneInfo
|
|
|
|
|
|
|
|
|
|
|
|
import boto3
|
|
|
|
|
|
from slack_sdk import WebClient
|
|
|
|
|
|
|
2026-08-29 20:52:28 +00:00
|
|
|
|
import shared.sentry_init # noqa: F401
|
Merge ring-scheduler-3cx and resolve all open issues (#62)
* Add arm64, log retention, and compliance fixes
- Set arm64 architecture globally for all Lambda functions
- Add explicit CloudWatch log groups with 60-day retention
- Add missing WeeklyPostFunctionArn to stack outputs
- Add Dependabot assignees for both ecosystems
- Add samconfig.toml.example for onboarding
* Restructure src/ to per-function layout with shared Layer
Move from flat src/ to per-function directories:
- src/slack-bot/ — Slack Bolt Lambda handler
- src/weekly-post/ — Monday schedule + pay post
- src/roster-sync/ — Daily 3CX roster sync
- src/shared/ — Lambda Layer with schedule, blocks, three_cx_client
Each function has its own requirements.txt and CodeUri. Shared
modules are deployed as a SAM Layer (afterhours-shared) importable
as `from shared.X import Y`.
* Migrate secrets from SSM Parameter Store to Secrets Manager
- Slack bot token and signing secret now read from Secrets Manager
- 3CX credentials (domain, client-id, client-secret) moved to
Secrets Manager under afterhours-shift-manager/3cx-* prefix
- Channel ID is now a non-secret CloudFormation parameter (ShiftChannel)
- Add shared secrets.py helper for Secrets Manager reads
- Remove SSM and KMS IAM policies, add secretsmanager:GetSecretValue
* Merge ring-scheduler-3cx as 4th Lambda function
- Add afterhours-ring-scheduler Lambda with 4 EventBridge rules
(daily 8am EST/EDT + weekend 5pm EST/EDT) for 3CX ring group
routing updates
- Extract shared ring_scheduler.py module for direct ring group
updates from both the scheduled Lambda and the Slack bot
- Replace cross-Lambda invoke with direct update_ring_group() call
in the Slack bot — eliminates lambda:InvokeFunction dependency
- Use RingGroup API (correct) instead of Queue API (was wrong in
the original ring-scheduler repo)
- Eliminate YAML config fallback — DynamoDB is the sole schedule
source
- Add RingGroupNumber CloudFormation parameter
* Add schedule post live-update and old post deletion (#40, #41)
- Store schedule message timestamp in DynamoDB (SCHEDULE_POST record)
- Delete previous week's schedule post before posting the new one
- Live-update the schedule post via chat_update after any
pick/drop/swap/button-pickup so it always reflects current state
* Disallow past shifts and add day/night labels (#43, #42)
- Reject /oncall pick and /oncall drop for past dates
- Show ephemeral error when stale pickup buttons are clicked
- Hide pickup buttons for dates in the past
- Add explicit "Day (8am-5pm)" and "Night (5pm-8am)" labels to
schedule lines, pickup buttons, and shift change notifications
* Add admin slash commands for shift and roster management (#39)
- /oncall admin override <date> <ext> — assign a shift
- /oncall admin open <date> — mark shift as open
- /oncall admin clear <date> — remove override, revert to weekly
- /oncall admin roster add/remove/rename — manage roster entries
- Admin access gated by admin_users list in DynamoDB CONFIG
- Help message shows admin commands for admin users
* Update README for merged architecture and new features
* Switch from RingGroup API to Queue API at extension 801
The 3CX routing was changed from ring group 800 to queue 801 in a
previous PR on ring-scheduler-3cx. Updates all callers and the SAM
template parameter default accordingly.
* Pass SAM parameter overrides in deploy workflow
* Fix review findings: IAM, routing guards, past-date check, roster safety
- Ring scheduler: use DynamoDBCrudPolicy (resolve_shift needs Query)
- Button pickup: update 3CX for active shift type, not just night
- Pick/drop/swap commands: only update 3CX when shift type is active
- Swap command: add missing past-date guard
- add_roster_entry: reject if extension already exists
- Apply ruff formatting
* Add error handling to ring scheduler 3CX call
* Fix weekend day shift commands and admin 3CX routing
- Add _find_employee_shift() to check both day/night on weekends
- Drop/swap now correctly find and operate on weekend day shifts
- Pick finds first available shift type on weekends
- Admin override/open/clear update 3CX for same-day active shifts
* Fix dependabot directories and admin weekend shift handling
Dependabot now scans per-function requirement directories instead
of the repo root. Admin override/open/clear commands accept an
optional day/night parameter for weekend day shift management.
* Fix weekend day shift active window to 8am-5pm
Before midnight-8am on weekends incorrectly reported the day shift
as active when the previous night shift is still running.
* Show shift type label for both weekend shifts in notifications
Night shift notifications on weekends were missing the type label,
making them ambiguous. Also fix schedule post text fallback to use
this_monday instead of now for the start date.
* Extract determine_shift_type into shared layer
Eliminates duplicated weekend day/night boundary logic between
the ring scheduler and Slack bot Lambdas.
* Fix weekly schedule fallback start date
Co-authored-by: Adam Moussa <amoussa1229@users.noreply.github.com>
* Include weekend shift type in command confirmations
Co-authored-by: Adam Moussa <amoussa1229@users.noreply.github.com>
* Apply ruff formatting to app.py
* Only show day/night shift labels on weekends in schedule display
Weekday shifts are always night — the label was redundant clutter.
* Deduplicate 3CX forwarding payload and add shift type to pick command
Extract _update_forwarding helper in ThreeCXClient to share the
payload between queue and ring group methods. Add optional day/night
argument to /oncall pick so users can target a specific weekend shift.
* Consolidate WEEKEND_DAYS and fix weekday pickup button labels
Import WEEKEND_DAYS from shared.schedule instead of redefining in
blocks.py and weekly-post/app.py. Gate pickup button day/night
labels on weekends only, matching all other display surfaces.
---------
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Adam Moussa <amoussa1229@users.noreply.github.com>
2026-05-12 19:55:39 -04:00
|
|
|
|
from shared.blocks import build_pay_summary_blocks, build_week_schedule
|
|
|
|
|
|
from shared.schedule import FALLBACK_EXTENSION, WEEKEND_DAYS, ShiftSchedule
|
|
|
|
|
|
from shared.secrets import get_secret
|
2026-04-03 18:32:32 -04:00
|
|
|
|
|
|
|
|
|
|
logger = logging.getLogger()
|
|
|
|
|
|
logger.setLevel(logging.INFO)
|
|
|
|
|
|
|
|
|
|
|
|
EASTERN = ZoneInfo("America/New_York")
|
|
|
|
|
|
|
2026-05-08 15:46:51 -04:00
|
|
|
|
DAY_ORDER = [
|
|
|
|
|
|
"Monday",
|
|
|
|
|
|
"Tuesday",
|
|
|
|
|
|
"Wednesday",
|
|
|
|
|
|
"Thursday",
|
|
|
|
|
|
"Friday",
|
|
|
|
|
|
"Saturday",
|
|
|
|
|
|
"Sunday",
|
|
|
|
|
|
]
|
2026-04-07 18:09:19 -04:00
|
|
|
|
|
|
|
|
|
|
|
2026-06-17 11:14:29 -04:00
|
|
|
|
def _record_pay_line(
|
|
|
|
|
|
breakdown, totals, *, date, day_label, name, ext, effective, base_rate, is_holiday
|
|
|
|
|
|
):
|
|
|
|
|
|
"""Append a single breakdown line and roll it into per-employee totals.
|
|
|
|
|
|
|
|
|
|
|
|
``effective`` is the dollar value actually earned for this one shift
|
|
|
|
|
|
(base_rate * multiplier for holidays, base_rate otherwise). To stay
|
|
|
|
|
|
compatible with the existing Slack ``build_pay_summary_blocks`` consumer —
|
|
|
|
|
|
which treats ``rate`` as the already-multiplied per-shift pay — the line's
|
|
|
|
|
|
``rate`` is set to ``effective``; ``base_rate`` is preserved separately and
|
|
|
|
|
|
``amount`` mirrors ``effective``. All money is stored as ``Decimal``.
|
|
|
|
|
|
"""
|
|
|
|
|
|
line = {
|
|
|
|
|
|
"date": date.strftime("%Y-%m-%d"),
|
|
|
|
|
|
"date_label": date.strftime("%b %-d"),
|
|
|
|
|
|
"day": day_label,
|
|
|
|
|
|
"name": name,
|
|
|
|
|
|
"extension": ext,
|
|
|
|
|
|
"rate": Decimal(str(effective)),
|
|
|
|
|
|
"base_rate": Decimal(str(base_rate)),
|
|
|
|
|
|
"amount": Decimal(str(effective)),
|
|
|
|
|
|
}
|
|
|
|
|
|
breakdown.append(line)
|
2026-04-07 18:22:56 -04:00
|
|
|
|
|
|
|
|
|
|
if name not in totals:
|
2026-05-08 15:46:51 -04:00
|
|
|
|
totals[name] = {
|
|
|
|
|
|
"shifts": 0,
|
|
|
|
|
|
"total": Decimal("0"),
|
|
|
|
|
|
"extension": ext,
|
2026-06-17 11:14:29 -04:00
|
|
|
|
"rate": Decimal(str(base_rate)),
|
|
|
|
|
|
"holiday_shifts": 0,
|
2026-05-08 15:46:51 -04:00
|
|
|
|
}
|
2026-04-07 18:22:56 -04:00
|
|
|
|
totals[name]["shifts"] += 1
|
2026-06-17 11:14:29 -04:00
|
|
|
|
totals[name]["total"] += Decimal(str(effective))
|
|
|
|
|
|
if is_holiday:
|
|
|
|
|
|
totals[name]["holiday_shifts"] = totals[name].get("holiday_shifts", 0) + 1
|
|
|
|
|
|
return line
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _add_shift_to_pay(schedule, breakdown, totals, date, day_name, shift_type="night"):
|
|
|
|
|
|
"""Resolve a shift and add it to the pay breakdown if assigned.
|
|
|
|
|
|
|
|
|
|
|
|
Holidays are day-only, multi-assignee shifts paid at base_rate * multiplier;
|
|
|
|
|
|
every assignee gets a distinct breakdown line tagged with the holiday
|
|
|
|
|
|
multiplier and label. Regular shifts have a single assignee at multiplier 1.
|
|
|
|
|
|
"""
|
|
|
|
|
|
date_str = date.strftime("%Y-%m-%d")
|
|
|
|
|
|
ctx = schedule.get_shift_context(date_str, day_name, shift_type)
|
|
|
|
|
|
|
|
|
|
|
|
assignees = ctx.get("assignees") or []
|
|
|
|
|
|
if not assignees:
|
|
|
|
|
|
return
|
|
|
|
|
|
|
|
|
|
|
|
label_suffix = " (Day)" if shift_type == "day" else ""
|
|
|
|
|
|
day_label = f"{day_name[:3]}{label_suffix}"
|
|
|
|
|
|
|
|
|
|
|
|
if ctx["kind"] == "holiday":
|
|
|
|
|
|
multiplier = Decimal(str(ctx.get("multiplier", 1)))
|
|
|
|
|
|
holiday_label = ctx.get("label", "")
|
|
|
|
|
|
for assignee in assignees:
|
|
|
|
|
|
ext = assignee["extension"]
|
|
|
|
|
|
name = assignee["name"]
|
|
|
|
|
|
if ext == FALLBACK_EXTENSION:
|
|
|
|
|
|
continue
|
|
|
|
|
|
base_rate = Decimal(str(schedule.get_shift_rate(ext)))
|
|
|
|
|
|
effective = base_rate * multiplier
|
|
|
|
|
|
line = _record_pay_line(
|
|
|
|
|
|
breakdown,
|
|
|
|
|
|
totals,
|
|
|
|
|
|
date=date,
|
|
|
|
|
|
day_label=day_label,
|
|
|
|
|
|
name=name,
|
|
|
|
|
|
ext=ext,
|
|
|
|
|
|
effective=effective,
|
|
|
|
|
|
base_rate=base_rate,
|
|
|
|
|
|
is_holiday=True,
|
|
|
|
|
|
)
|
|
|
|
|
|
line["multiplier"] = Decimal(str(multiplier))
|
|
|
|
|
|
line["is_holiday"] = True
|
|
|
|
|
|
line["holiday_label"] = holiday_label
|
|
|
|
|
|
return
|
|
|
|
|
|
|
|
|
|
|
|
# Regular (override/weekly) shift — single assignee.
|
|
|
|
|
|
assignee = assignees[0]
|
|
|
|
|
|
ext = assignee["extension"]
|
|
|
|
|
|
name = assignee["name"]
|
|
|
|
|
|
if ext == FALLBACK_EXTENSION:
|
|
|
|
|
|
return
|
|
|
|
|
|
|
|
|
|
|
|
rate = Decimal(str(schedule.get_shift_rate(ext)))
|
|
|
|
|
|
_record_pay_line(
|
|
|
|
|
|
breakdown,
|
|
|
|
|
|
totals,
|
|
|
|
|
|
date=date,
|
|
|
|
|
|
day_label=day_label,
|
|
|
|
|
|
name=name,
|
|
|
|
|
|
ext=ext,
|
|
|
|
|
|
effective=rate,
|
|
|
|
|
|
base_rate=rate,
|
|
|
|
|
|
is_holiday=False,
|
|
|
|
|
|
)
|
2026-04-07 18:22:56 -04:00
|
|
|
|
|
|
|
|
|
|
|
2026-04-07 18:09:19 -04:00
|
|
|
|
def _calculate_weekly_pay(schedule: ShiftSchedule, week_start: datetime) -> dict:
|
|
|
|
|
|
"""Calculate pay for a Mon–Sun week. Returns pay record dict."""
|
2026-04-07 18:12:32 -04:00
|
|
|
|
default_rate = schedule.get_shift_rate()
|
2026-04-07 18:09:19 -04:00
|
|
|
|
breakdown = []
|
|
|
|
|
|
totals = {}
|
|
|
|
|
|
|
|
|
|
|
|
for i in range(7):
|
|
|
|
|
|
date = week_start + timedelta(days=i)
|
|
|
|
|
|
day_name = DAY_ORDER[i]
|
2026-06-17 11:14:29 -04:00
|
|
|
|
date_str = date.strftime("%Y-%m-%d")
|
2026-04-07 18:22:56 -04:00
|
|
|
|
|
2026-06-17 11:14:29 -04:00
|
|
|
|
# Day shifts (8am–5pm) exist on weekends and on holidays. Holidays are
|
|
|
|
|
|
# day-only and may land on a weekday, so check the day shift whenever a
|
|
|
|
|
|
# holiday record exists for the date, not just on weekend days.
|
|
|
|
|
|
if day_name in WEEKEND_DAYS or schedule.get_holiday(date_str):
|
2026-04-07 18:22:56 -04:00
|
|
|
|
_add_shift_to_pay(schedule, breakdown, totals, date, day_name, "day")
|
|
|
|
|
|
|
|
|
|
|
|
# After-hours (night) shift
|
|
|
|
|
|
_add_shift_to_pay(schedule, breakdown, totals, date, day_name, "night")
|
2026-04-07 18:09:19 -04:00
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
|
"week_start": week_start.strftime("%Y-%m-%d"),
|
2026-04-07 18:12:32 -04:00
|
|
|
|
"default_rate": str(default_rate),
|
2026-04-07 18:09:19 -04:00
|
|
|
|
"breakdown": breakdown,
|
|
|
|
|
|
"totals": totals,
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-04-03 18:32:32 -04:00
|
|
|
|
|
2026-04-07 18:54:19 -04:00
|
|
|
|
def _build_pay_email_html(week_label: str, pay_record: dict) -> str:
|
2026-06-17 11:14:29 -04:00
|
|
|
|
"""Build an HTML email body for the weekly pay summary.
|
|
|
|
|
|
|
|
|
|
|
|
Holiday shifts are rendered distinctly: a per-shift breakdown section
|
|
|
|
|
|
highlights holiday rows (shaded, showing the multiplier and label) and the
|
|
|
|
|
|
totals table flags any employee who worked a holiday during the week.
|
|
|
|
|
|
"""
|
|
|
|
|
|
breakdown = pay_record.get("breakdown", [])
|
|
|
|
|
|
totals = pay_record.get("totals", {})
|
|
|
|
|
|
|
|
|
|
|
|
holiday_names = {line["name"] for line in breakdown if line.get("is_holiday")}
|
|
|
|
|
|
|
2026-04-07 18:54:19 -04:00
|
|
|
|
totals_rows = ""
|
2026-06-17 11:14:29 -04:00
|
|
|
|
for name, info in sorted(totals.items()):
|
|
|
|
|
|
holiday_tag = (
|
|
|
|
|
|
' <span style="color:#b8860b;">★ holiday</span>'
|
|
|
|
|
|
if name in holiday_names
|
|
|
|
|
|
else ""
|
|
|
|
|
|
)
|
2026-04-07 18:54:19 -04:00
|
|
|
|
totals_rows += (
|
2026-06-17 11:14:29 -04:00
|
|
|
|
f"<tr><td>{name}{holiday_tag}</td>"
|
2026-04-07 18:54:19 -04:00
|
|
|
|
f"<td>${info.get('rate', 0):.2f}</td><td><strong>${info['total']:.2f}</strong></td></tr>\n"
|
|
|
|
|
|
)
|
|
|
|
|
|
|
2026-06-17 11:14:29 -04:00
|
|
|
|
breakdown_rows = ""
|
|
|
|
|
|
for line in breakdown:
|
|
|
|
|
|
if line.get("is_holiday"):
|
|
|
|
|
|
mult = line.get("multiplier", Decimal("1"))
|
|
|
|
|
|
label = line.get("holiday_label", "") or "Holiday"
|
|
|
|
|
|
base = line.get("base_rate", line["rate"])
|
|
|
|
|
|
row_style = ' style="background:#fff8e1;"'
|
|
|
|
|
|
detail = f"{label} — ${base:.2f} × {mult:.2f}x"
|
|
|
|
|
|
else:
|
|
|
|
|
|
row_style = ""
|
|
|
|
|
|
detail = f"${line['rate']:.2f}"
|
|
|
|
|
|
breakdown_rows += (
|
|
|
|
|
|
f"<tr{row_style}><td>{line['date_label']}</td>"
|
|
|
|
|
|
f"<td>{line['day']}</td>"
|
|
|
|
|
|
f"<td>{line['name']}</td>"
|
|
|
|
|
|
f"<td>{detail}</td>"
|
|
|
|
|
|
f"<td><strong>${line['amount']:.2f}</strong></td></tr>\n"
|
|
|
|
|
|
)
|
|
|
|
|
|
|
2026-04-07 18:54:19 -04:00
|
|
|
|
return f"""<html>
|
|
|
|
|
|
<body style="font-family: Arial, sans-serif; color: #333;">
|
2026-04-07 19:07:44 -04:00
|
|
|
|
<h2>Bonus Pay Summary — {week_label}</h2>
|
2026-04-07 18:54:19 -04:00
|
|
|
|
|
|
|
|
|
|
<table border="1" cellpadding="6" cellspacing="0" style="border-collapse: collapse;">
|
2026-04-08 13:22:28 -04:00
|
|
|
|
<tr style="background: #f0f0f0;"><th>Name</th><th>Rate</th><th>Total</th></tr>
|
2026-04-07 18:54:19 -04:00
|
|
|
|
{totals_rows}</table>
|
|
|
|
|
|
|
2026-06-17 11:14:29 -04:00
|
|
|
|
<h3>Shift Breakdown</h3>
|
|
|
|
|
|
<table border="1" cellpadding="6" cellspacing="0" style="border-collapse: collapse;">
|
|
|
|
|
|
<tr style="background: #f0f0f0;"><th>Date</th><th>Day</th><th>Name</th><th>Detail</th><th>Amount</th></tr>
|
|
|
|
|
|
{breakdown_rows}</table>
|
|
|
|
|
|
<p style="color: #888; font-size: 12px;">Holiday shifts are shaded and paid at the listed multiplier.</p>
|
|
|
|
|
|
|
2026-04-08 13:22:28 -04:00
|
|
|
|
<p style="color: #888; font-size: 12px;">This is an automated report from Sea Haven Industries.</p>
|
2026-04-07 18:54:19 -04:00
|
|
|
|
</body>
|
|
|
|
|
|
</html>"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _send_pay_email(week_label: str, pay_record: dict) -> None:
|
|
|
|
|
|
"""Send the weekly pay summary email via SES."""
|
|
|
|
|
|
sender = os.environ.get("SES_SENDER", "noreply@seahaven.com")
|
|
|
|
|
|
recipients = os.environ.get("PAYROLL_RECIPIENTS", "").split(",")
|
|
|
|
|
|
recipients = [r.strip() for r in recipients if r.strip()]
|
|
|
|
|
|
|
|
|
|
|
|
if not recipients:
|
|
|
|
|
|
logger.warning("No PAYROLL_RECIPIENTS configured — skipping email")
|
|
|
|
|
|
return
|
|
|
|
|
|
|
|
|
|
|
|
ses = boto3.client("ses")
|
|
|
|
|
|
html_body = _build_pay_email_html(week_label, pay_record)
|
|
|
|
|
|
|
|
|
|
|
|
ses.send_email(
|
|
|
|
|
|
Source=sender,
|
|
|
|
|
|
Destination={"ToAddresses": recipients},
|
|
|
|
|
|
Message={
|
2026-04-07 19:07:44 -04:00
|
|
|
|
"Subject": {"Data": f"Bonus Pay Summary — {week_label}"},
|
2026-04-07 18:54:19 -04:00
|
|
|
|
"Body": {"Html": {"Data": html_body}},
|
|
|
|
|
|
},
|
|
|
|
|
|
)
|
|
|
|
|
|
logger.info("Sent pay email to %s", recipients)
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-04-03 18:32:32 -04:00
|
|
|
|
def handler(event, context):
|
|
|
|
|
|
now = datetime.now(EASTERN)
|
|
|
|
|
|
|
|
|
|
|
|
# DST guard — same pattern as the 3CX scheduler
|
2026-04-07 18:58:03 -04:00
|
|
|
|
force = event.get("force", False)
|
|
|
|
|
|
if not force and now.hour != 7:
|
2026-05-08 15:46:51 -04:00
|
|
|
|
logger.info(
|
|
|
|
|
|
"ET hour is %d, not 7am — skipping (wrong DST rule fired)", now.hour
|
|
|
|
|
|
)
|
2026-04-03 18:32:32 -04:00
|
|
|
|
return {"skipped": True}
|
|
|
|
|
|
|
Merge ring-scheduler-3cx and resolve all open issues (#62)
* Add arm64, log retention, and compliance fixes
- Set arm64 architecture globally for all Lambda functions
- Add explicit CloudWatch log groups with 60-day retention
- Add missing WeeklyPostFunctionArn to stack outputs
- Add Dependabot assignees for both ecosystems
- Add samconfig.toml.example for onboarding
* Restructure src/ to per-function layout with shared Layer
Move from flat src/ to per-function directories:
- src/slack-bot/ — Slack Bolt Lambda handler
- src/weekly-post/ — Monday schedule + pay post
- src/roster-sync/ — Daily 3CX roster sync
- src/shared/ — Lambda Layer with schedule, blocks, three_cx_client
Each function has its own requirements.txt and CodeUri. Shared
modules are deployed as a SAM Layer (afterhours-shared) importable
as `from shared.X import Y`.
* Migrate secrets from SSM Parameter Store to Secrets Manager
- Slack bot token and signing secret now read from Secrets Manager
- 3CX credentials (domain, client-id, client-secret) moved to
Secrets Manager under afterhours-shift-manager/3cx-* prefix
- Channel ID is now a non-secret CloudFormation parameter (ShiftChannel)
- Add shared secrets.py helper for Secrets Manager reads
- Remove SSM and KMS IAM policies, add secretsmanager:GetSecretValue
* Merge ring-scheduler-3cx as 4th Lambda function
- Add afterhours-ring-scheduler Lambda with 4 EventBridge rules
(daily 8am EST/EDT + weekend 5pm EST/EDT) for 3CX ring group
routing updates
- Extract shared ring_scheduler.py module for direct ring group
updates from both the scheduled Lambda and the Slack bot
- Replace cross-Lambda invoke with direct update_ring_group() call
in the Slack bot — eliminates lambda:InvokeFunction dependency
- Use RingGroup API (correct) instead of Queue API (was wrong in
the original ring-scheduler repo)
- Eliminate YAML config fallback — DynamoDB is the sole schedule
source
- Add RingGroupNumber CloudFormation parameter
* Add schedule post live-update and old post deletion (#40, #41)
- Store schedule message timestamp in DynamoDB (SCHEDULE_POST record)
- Delete previous week's schedule post before posting the new one
- Live-update the schedule post via chat_update after any
pick/drop/swap/button-pickup so it always reflects current state
* Disallow past shifts and add day/night labels (#43, #42)
- Reject /oncall pick and /oncall drop for past dates
- Show ephemeral error when stale pickup buttons are clicked
- Hide pickup buttons for dates in the past
- Add explicit "Day (8am-5pm)" and "Night (5pm-8am)" labels to
schedule lines, pickup buttons, and shift change notifications
* Add admin slash commands for shift and roster management (#39)
- /oncall admin override <date> <ext> — assign a shift
- /oncall admin open <date> — mark shift as open
- /oncall admin clear <date> — remove override, revert to weekly
- /oncall admin roster add/remove/rename — manage roster entries
- Admin access gated by admin_users list in DynamoDB CONFIG
- Help message shows admin commands for admin users
* Update README for merged architecture and new features
* Switch from RingGroup API to Queue API at extension 801
The 3CX routing was changed from ring group 800 to queue 801 in a
previous PR on ring-scheduler-3cx. Updates all callers and the SAM
template parameter default accordingly.
* Pass SAM parameter overrides in deploy workflow
* Fix review findings: IAM, routing guards, past-date check, roster safety
- Ring scheduler: use DynamoDBCrudPolicy (resolve_shift needs Query)
- Button pickup: update 3CX for active shift type, not just night
- Pick/drop/swap commands: only update 3CX when shift type is active
- Swap command: add missing past-date guard
- add_roster_entry: reject if extension already exists
- Apply ruff formatting
* Add error handling to ring scheduler 3CX call
* Fix weekend day shift commands and admin 3CX routing
- Add _find_employee_shift() to check both day/night on weekends
- Drop/swap now correctly find and operate on weekend day shifts
- Pick finds first available shift type on weekends
- Admin override/open/clear update 3CX for same-day active shifts
* Fix dependabot directories and admin weekend shift handling
Dependabot now scans per-function requirement directories instead
of the repo root. Admin override/open/clear commands accept an
optional day/night parameter for weekend day shift management.
* Fix weekend day shift active window to 8am-5pm
Before midnight-8am on weekends incorrectly reported the day shift
as active when the previous night shift is still running.
* Show shift type label for both weekend shifts in notifications
Night shift notifications on weekends were missing the type label,
making them ambiguous. Also fix schedule post text fallback to use
this_monday instead of now for the start date.
* Extract determine_shift_type into shared layer
Eliminates duplicated weekend day/night boundary logic between
the ring scheduler and Slack bot Lambdas.
* Fix weekly schedule fallback start date
Co-authored-by: Adam Moussa <amoussa1229@users.noreply.github.com>
* Include weekend shift type in command confirmations
Co-authored-by: Adam Moussa <amoussa1229@users.noreply.github.com>
* Apply ruff formatting to app.py
* Only show day/night shift labels on weekends in schedule display
Weekday shifts are always night — the label was redundant clutter.
* Deduplicate 3CX forwarding payload and add shift type to pick command
Extract _update_forwarding helper in ThreeCXClient to share the
payload between queue and ring group methods. Add optional day/night
argument to /oncall pick so users can target a specific weekend shift.
* Consolidate WEEKEND_DAYS and fix weekday pickup button labels
Import WEEKEND_DAYS from shared.schedule instead of redefining in
blocks.py and weekly-post/app.py. Gate pickup button day/night
labels on weekends only, matching all other display surfaces.
---------
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Adam Moussa <amoussa1229@users.noreply.github.com>
2026-05-12 19:55:39 -04:00
|
|
|
|
bot_token = get_secret(os.environ["SLACK_BOT_TOKEN_SECRET"])
|
|
|
|
|
|
channel_id = os.environ["SHIFT_CHANNEL"]
|
2026-04-03 18:32:32 -04:00
|
|
|
|
|
|
|
|
|
|
schedule = ShiftSchedule()
|
|
|
|
|
|
slack = WebClient(token=bot_token)
|
|
|
|
|
|
|
2026-04-07 18:09:19 -04:00
|
|
|
|
# --- 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)
|
|
|
|
|
|
|
2026-04-07 19:07:44 -04:00
|
|
|
|
pay_dm_user = os.environ.get("PAY_REPORT_USER")
|
|
|
|
|
|
|
2026-04-07 18:09:19 -04:00
|
|
|
|
if pay_record["breakdown"]:
|
|
|
|
|
|
week_key = prev_monday.strftime("%Y-%m-%d")
|
|
|
|
|
|
schedule.save_pay_record(week_key, pay_record)
|
|
|
|
|
|
|
|
|
|
|
|
prev_sunday = prev_monday + timedelta(days=6)
|
2026-05-08 15:46:51 -04:00
|
|
|
|
week_label = (
|
|
|
|
|
|
f"{prev_monday.strftime('%b %-d')} to {prev_sunday.strftime('%b %-d')}"
|
|
|
|
|
|
)
|
2026-04-07 18:09:19 -04:00
|
|
|
|
pay_blocks = build_pay_summary_blocks(
|
2026-04-07 18:12:32 -04:00
|
|
|
|
week_label, pay_record["breakdown"], pay_record["totals"]
|
2026-04-07 18:09:19 -04:00
|
|
|
|
)
|
2026-04-07 19:07:44 -04:00
|
|
|
|
|
|
|
|
|
|
# DM pay report to designated user instead of channel
|
|
|
|
|
|
if pay_dm_user:
|
|
|
|
|
|
slack.chat_postMessage(
|
|
|
|
|
|
channel=pay_dm_user,
|
|
|
|
|
|
blocks=pay_blocks,
|
|
|
|
|
|
text=f"After-Hours Pay — {week_label}",
|
|
|
|
|
|
)
|
2026-05-08 15:46:51 -04:00
|
|
|
|
logger.info(
|
|
|
|
|
|
"Sent pay summary DM to %s for week of %s", pay_dm_user, week_key
|
|
|
|
|
|
)
|
2026-04-07 19:07:44 -04:00
|
|
|
|
else:
|
|
|
|
|
|
logger.warning("PAY_REPORT_USER not set — skipping Slack pay summary")
|
2026-04-07 18:09:19 -04:00
|
|
|
|
|
2026-06-15 13:24:32 -04:00
|
|
|
|
# Email pay summary to payroll. Isolated so a delivery failure (e.g.
|
|
|
|
|
|
# an SES permission/identity issue) can never abort the rest of the
|
|
|
|
|
|
# handler — the Slack schedule post below must still go out.
|
|
|
|
|
|
try:
|
|
|
|
|
|
_send_pay_email(week_label, pay_record)
|
|
|
|
|
|
except Exception:
|
|
|
|
|
|
logger.exception(
|
|
|
|
|
|
"Failed to send pay summary email to payroll for week of %s",
|
|
|
|
|
|
week_key,
|
|
|
|
|
|
)
|
2026-04-07 18:54:19 -04:00
|
|
|
|
|
2026-04-08 13:36:34 -04:00
|
|
|
|
# --- Two-week schedule (always starts on Monday of this week) ---
|
|
|
|
|
|
this_monday = now - timedelta(days=now.weekday())
|
2026-06-27 15:45:01 -04:00
|
|
|
|
week_start = this_monday.strftime("%Y-%m-%d")
|
2026-04-08 13:36:34 -04:00
|
|
|
|
blocks = build_week_schedule(schedule, start_date=this_monday)
|
2026-04-03 18:32:32 -04:00
|
|
|
|
|
2026-04-08 13:36:34 -04:00
|
|
|
|
end_date = this_monday + timedelta(days=13)
|
2026-06-27 15:45:01 -04:00
|
|
|
|
fallback_text = (
|
|
|
|
|
|
f"After-Hours Schedule — {this_monday.strftime('%b %-d')} "
|
|
|
|
|
|
f"to {end_date.strftime('%b %-d')}"
|
2026-04-03 18:32:32 -04:00
|
|
|
|
)
|
|
|
|
|
|
|
2026-07-10 16:36:47 -04:00
|
|
|
|
# Delete the previous week's schedule post + repost a fresh one so the
|
|
|
|
|
|
# message lands at the bottom of the channel every Monday. The activity
|
|
|
|
|
|
# bump (handle_channel_message) handles in-week bottom-stickiness; this
|
|
|
|
|
|
# ensures the rollover itself re-places the post at the bottom.
|
2026-06-27 15:45:01 -04:00
|
|
|
|
old_post = schedule.get_schedule_post(channel_id)
|
|
|
|
|
|
if old_post and old_post.get("message_ts"):
|
|
|
|
|
|
try:
|
2026-07-10 16:36:47 -04:00
|
|
|
|
slack.chat_delete(channel=channel_id, ts=old_post["message_ts"])
|
2026-06-27 15:45:01 -04:00
|
|
|
|
logger.info(
|
2026-07-10 16:36:47 -04:00
|
|
|
|
"Deleted previous schedule post %s for weekly rollover",
|
|
|
|
|
|
old_post["message_ts"],
|
2026-06-27 15:45:01 -04:00
|
|
|
|
)
|
|
|
|
|
|
except Exception:
|
|
|
|
|
|
logger.warning(
|
2026-07-10 16:36:47 -04:00
|
|
|
|
"Could not delete old schedule post for rollover; continuing",
|
|
|
|
|
|
exc_info=True,
|
2026-06-27 15:45:01 -04:00
|
|
|
|
)
|
|
|
|
|
|
|
2026-07-10 16:36:47 -04:00
|
|
|
|
result = slack.chat_postMessage(
|
|
|
|
|
|
channel=channel_id, blocks=blocks, text=fallback_text
|
|
|
|
|
|
)
|
|
|
|
|
|
message_ts = result["ts"]
|
|
|
|
|
|
logger.info(
|
|
|
|
|
|
"Posted new weekly schedule to channel %s (ts=%s)", channel_id, message_ts
|
|
|
|
|
|
)
|
2026-06-27 15:45:01 -04:00
|
|
|
|
|
2026-07-10 16:36:47 -04:00
|
|
|
|
# Persist the new ts immediately. If the write fails after the post has
|
|
|
|
|
|
# already landed, roll the fresh message back before letting the error
|
|
|
|
|
|
# propagate — an async retry would otherwise read the stale (already
|
|
|
|
|
|
# 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)
|
|
|
|
|
|
except Exception:
|
|
|
|
|
|
logger.warning(
|
|
|
|
|
|
"Failed to persist schedule post %s; rolling it back to avoid an "
|
|
|
|
|
|
"orphaned duplicate on retry",
|
|
|
|
|
|
message_ts,
|
|
|
|
|
|
exc_info=True,
|
|
|
|
|
|
)
|
|
|
|
|
|
try:
|
|
|
|
|
|
slack.chat_delete(channel=channel_id, ts=message_ts)
|
|
|
|
|
|
except Exception:
|
|
|
|
|
|
logger.warning(
|
|
|
|
|
|
"Could not roll back orphaned schedule post %s",
|
|
|
|
|
|
message_ts,
|
|
|
|
|
|
exc_info=True,
|
|
|
|
|
|
)
|
|
|
|
|
|
raise
|
2026-05-08 15:46:51 -04:00
|
|
|
|
return {
|
|
|
|
|
|
"posted": True,
|
|
|
|
|
|
"channel": channel_id,
|
2026-06-27 15:45:01 -04:00
|
|
|
|
"message_ts": message_ts,
|
2026-05-08 15:46:51 -04:00
|
|
|
|
"pay_calculated": bool(pay_record["breakdown"]),
|
|
|
|
|
|
}
|