Skip to content

PranavNagrecha/AwesomeSalesforceSkills / skills/admin/business-hours-and-holidays

business-hours-and-holidays

Verified

Use this skill when creating, deploying, or troubleshooting Salesforce Business Hours and Holidays: the calendars that pause Case escalation rules, entitlement milestones, and Apex BusinessHours math outside working hours. Covers the BusinessHoursSettings metadata, the default calendar, per-region calendars, holiday attachment, the Case Business Hours field, and the BusinessHours Apex class. Trigger keywords: business hours, holidays, SLA clock, escalation not pausing, working hours, support hours, milestone timer weekend. NOT for the escalation rule entries themselves — use admin/escalation-rules. NOT for entitlement process design — use admin/entitlements-and-milestones. NOT for Field Service operating hours or shift scheduling — use admin/fsl-scheduling-setup.

scripts/check_business_hours_and_holidays.py

View on GitHub
#!/usr/bin/env python3
"""Checker for Business Hours and Holidays metadata.

Parses ``settings/BusinessHours.settings-meta.xml`` (or ``BusinessHours.settings``
from a retrieved package) and flags the configuration mistakes that make an SLA
clock keep running: no or several default calendars, inactive defaults, holidays
attached to no calendar or to an unknown one, calendars with no weekday window,
a calendar stored as midnight-to-midnight on every day when that calendar is
the org default (the shipped, never-edited 24/7 shape), and one-off holidays
already in the past.

Severity levels
----------------
ERROR  Always fails the check (exit 1): no/duplicate/inactive default calendar,
       missing timeZoneId, a day with only a start or only an end time, a
       calendar with no open day at all, an unattached or misconfigured
       holiday, and the midnight-to-midnight-every-day shape when it belongs
       to the org DEFAULT calendar (``<default>true</default>``) or is named
       literally ``Default`` — i.e. the shipped calendar nobody edited.
WARN   Fails only with ``--strict``: no BusinessHours settings file found
       under the manifest directory at all.
INFO   Never affects the exit code: the same midnight-to-midnight-every-day
       shape on a calendar that is neither the org default nor named
       ``Default`` — a deliberately named always-open calendar (a 24/7
       severity tier is a legitimate, intentional use of this shape).

Stdlib only.

Usage:
    python3 check_business_hours_and_holidays.py --manifest-dir force-app/main/default
    python3 check_business_hours_and_holidays.py --manifest-dir force-app/main/default --strict
"""

from __future__ import annotations

import argparse
import datetime as dt
import sys
import xml.etree.ElementTree as ET
from pathlib import Path

SF_NS = "http://soap.sforce.com/2006/04/metadata"
DAYS = ("monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday")
MIDNIGHT = "00:00:00.000Z"

ERROR = "ERROR"
WARN = "WARN"
INFO = "INFO"
Finding = tuple[str, str]  # (severity, message)


def _tag(local: str) -> str:
    return f"{{{SF_NS}}}{local}"


def _find(parent: ET.Element, name: str) -> ET.Element | None:
    """Namespaced-or-bare child lookup. Never use ``a or b`` on Elements: a leaf
    Element is falsy, which silently discards a found node."""
    el = parent.find(_tag(name))
    return el if el is not None else parent.find(name)


def _findall(parent: ET.Element, name: str) -> list[ET.Element]:
    return parent.findall(_tag(name)) or parent.findall(name)


def _text(parent: ET.Element, name: str) -> str | None:
    el = _find(parent, name)
    return el.text.strip() if el is not None and el.text else None


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        description="Check BusinessHoursSettings metadata for SLA-clock mistakes.",
    )
    parser.add_argument(
        "--manifest-dir",
        default=".",
        help="Root of the Salesforce project or retrieved metadata (default: current directory).",
    )
    parser.add_argument(
        "--today",
        default=None,
        help="Override today's date (YYYY-MM-DD) for the past-holiday check; used by tests.",
    )
    parser.add_argument(
        "--strict",
        action="store_true",
        help="Also fail (exit 1) on WARN findings. Never promotes INFO.",
    )
    return parser.parse_args()


def find_settings_files(root: Path) -> list[Path]:
    results = list(root.rglob("BusinessHours.settings-meta.xml"))
    results += [p for p in root.rglob("BusinessHours.settings") if p.is_file()]
    return results


def check_file(path: Path, today: dt.date) -> list[Finding]:
    issues: list[Finding] = []
    try:
        root = ET.parse(path).getroot()
    except ET.ParseError as exc:
        return [(ERROR, f"{path.name}: XML parse error — {exc}")]

    calendars = _findall(root, "businessHours")
    holidays = _findall(root, "holidays")
    names: list[str] = []
    defaults: list[str] = []

    for cal in calendars:
        name = _text(cal, "name") or "<unnamed>"
        names.append(name)
        active = (_text(cal, "active") or "false").lower() == "true"
        is_default = (_text(cal, "default") or "false").lower() == "true"
        if is_default:
            defaults.append(name)
            if not active:
                issues.append((ERROR, f"{path.name} / calendar '{name}': marked default but inactive."))
        if not _text(cal, "timeZoneId"):
            issues.append((ERROR, f"{path.name} / calendar '{name}': no timeZoneId — windows have no frame."))

        windows = 0
        all_midnight = True
        for day in DAYS:
            start = _text(cal, f"{day}StartTime")
            end = _text(cal, f"{day}EndTime")
            if start or end:
                windows += 1
                if not (start == MIDNIGHT and end == MIDNIGHT):
                    all_midnight = False
                if (start is None) != (end is None):
                    issues.append(
                        (ERROR, f"{path.name} / calendar '{name}': {day} has a start or end time but not both.")
                    )
        if windows == 0:
            issues.append(
                (ERROR, f"{path.name} / calendar '{name}': no day has a window — the calendar is never open.")
            )
        elif windows == 7 and all_midnight:
            # The shape itself (every day 00:00:00.000Z-00:00:00.000Z) is not the
            # problem: it is exactly how a deliberate, named 24/7 severity-tier
            # calendar is stored. The problem is an org's DEFAULT calendar never
            # having been edited off the shipped shape — every consumer with no
            # calendar of its own falls back to it. So this rule is scoped to the
            # default calendar (by <default>true</default> or by the literal
            # shipped name "Default"); any other all-midnight calendar is a
            # non-blocking INFO note, not an ERROR.
            if is_default or name == "Default":
                issues.append(
                    (
                        ERROR,
                        f"{path.name} / calendar '{name}': every day is 00:00:00.000Z to 00:00:00.000Z — "
                        "this is the shipped 24/7 shape; SLA clocks on this calendar never pause.",
                    )
                )
            else:
                issues.append(
                    (
                        INFO,
                        f"{path.name} / always-open calendar '{name}': SLA clocks on it never pause — "
                        "intended for 24/7 severity tiers; confirm it is not attached to entitlements "
                        "that expect business-hour pauses.",
                    )
                )

    if not calendars:
        issues.append((ERROR, f"{path.name}: no businessHours entries found."))
    elif not defaults:
        issues.append(
            (ERROR, f"{path.name}: no calendar is marked default — consumers with no calendar have nothing to fall back to.")
        )
    elif len(defaults) > 1:
        issues.append((ERROR, f"{path.name}: more than one default calendar: {defaults}. Exactly one is allowed."))

    for hol in holidays:
        hname = _text(hol, "name") or "<unnamed>"
        attached = [el.text.strip() for el in _findall(hol, "businessHours") if el.text]
        if not attached:
            issues.append(
                (ERROR, f"{path.name} / holiday '{hname}': attached to no calendar — it suspends nothing.")
            )
        for cal_name in attached:
            if cal_name not in names:
                issues.append(
                    (ERROR, f"{path.name} / holiday '{hname}': attached to unknown calendar '{cal_name}'.")
                )
        recurring = (_text(hol, "isRecurring") or "false").lower() == "true"
        activity = _text(hol, "activityDate")
        start_t, end_t = _text(hol, "startTime"), _text(hol, "endTime")
        if (start_t is None) != (end_t is None):
            issues.append(
                (ERROR, f"{path.name} / holiday '{hname}': startTime and endTime must both be set or both be absent.")
            )
        if not recurring:
            if not activity:
                issues.append((ERROR, f"{path.name} / holiday '{hname}': non-recurring holiday has no activityDate."))
            else:
                try:
                    when = dt.date.fromisoformat(activity[:10])
                    if when < today:
                        issues.append(
                            (
                                ERROR,
                                f"{path.name} / holiday '{hname}': activityDate {activity[:10]} is in the past — "
                                "stale one-off holiday; add next year's date.",
                            )
                        )
                except ValueError:
                    issues.append((ERROR, f"{path.name} / holiday '{hname}': activityDate '{activity}' is not a date."))
        elif not _text(hol, "recurrenceStartDate"):
            issues.append((ERROR, f"{path.name} / holiday '{hname}': recurring holiday has no recurrenceStartDate."))

    return issues


def check_business_hours_and_holidays(manifest_dir: Path, today: dt.date | None = None) -> list[Finding]:
    today = today or dt.date.today()
    if not manifest_dir.exists():
        return [(ERROR, f"Manifest directory not found: {manifest_dir}")]
    files = find_settings_files(manifest_dir)
    if not files:
        return [(WARN, f"No BusinessHours settings file found under {manifest_dir}.")]
    issues: list[Finding] = []
    for f in files:
        issues.extend(check_file(f, today))
    return issues


def main() -> int:
    args = parse_args()
    today = dt.date.fromisoformat(args.today) if args.today else None
    findings = check_business_hours_and_holidays(Path(args.manifest_dir), today)
    if not findings:
        print("No business hours issues found.")
        return 0

    has_error = False
    has_warn = False
    for severity, message in findings:
        print(f"{severity}: {message}")
        if severity == ERROR:
            has_error = True
        elif severity == WARN:
            has_warn = True

    if has_error:
        return 1
    if args.strict and has_warn:
        return 1
    return 0


if __name__ == "__main__":
    sys.exit(main())
writing-skillsobra/superpowersUse when creating new skills, editing existing skills, or verifying skills work before deploymentStars: 323kUpdated Claude CodeCodexVerifiedInstall
xlsxanthropics/skillsUse this skill any time a spreadsheet file is the primary input or output. This means any task where the user wants to: open, read, edit, or fix an existing .xlsx, .xlsm, .xltx, .csv, or .tsv file (e.g., adding columns, computing formulas, formatting, charting, cleaning messy data); create a new spreadsheet from scratch or from other data sources; or convert between tabular file formats. Trigger especially when the user references a spreadsheet file by name or path — even casually (like "the xlsx in my downloads") — and wants something done to it or produced from it. Also trigger for cleaning or restructuring messy tabular data files (malformed rows, misplaced headers, junk data) into proper spreadsheets. The deliverable must be a spreadsheet file. Do NOT trigger when the primary deliverable is a Word document, HTML report, standalone Python script, database pipeline, or Google Sheets API integration, even if tabular data is involved.Stars: 198kUpdated Claude CodeCodexVerifiedInstall
shipping-and-launchaddyosmani/agent-skillsPrepares production launches. Use when preparing to deploy to production, or when asking what needs to be in place before shipping. Use when you need a pre-launch checklist, when setting up monitoring, when planning a staged rollout, or when you need a rollback strategy.Stars: 119kUpdated Claude CodeCodexVerifiedInstall
childhoodthedotmack/claude-memBabysit a shipped release after merge, publication, or deployment. Verify published packages, production behavior, installed plugins, and late CI or user reports until the observation window is clean; use babysit for PR readiness before release.Stars: 118kUpdated Claude CodeCodexVerifiedInstall