#!/usr/bin/env bash
# Silent arrivals
# Guests arriving in the next three days who have had no message from you at all. Catches the stays that slipped through a paused automation or a broken template.
#
# Category : Operations
# Safety   : read only
# Uses     : reservations list, contacts timeline
# Returns  : Arrival date, unit, guest and contact id for every silent upcoming stay.
#
# Requires the SendSquared CLI and jq:
#   curl -fsSL https://cli.sendsquared.com/install.sh | bash
#   sendsquared auth login
#
# Free to use and adapt. https://sendsquared.com/cli/scripts/#silent-arrivals

# Upcoming arrivals with no outbound message on the contact.
set -euo pipefail
DAYS=${1:-3}
TODAY=$(date -u +%F)
UNTIL=$(date -u -v+${DAYS}d +%F 2>/dev/null || date -u -d "+${DAYS} days" +%F)

echo "arrivals $TODAY to $UNTIL with nothing sent"
sendsquared reservations list --limit 1000 --sort arrival_date:asc \
| jq -r --arg from "$TODAY" --arg to "$UNTIL" '
    .data[]
    | select(.contact_id != null and (.arrival_date // "") != "")
    | select(.cancelled_at == null)
    | (.arrival_date | split("T")[0]) as $d
    | select($d >= $from and $d <= $to)
    | [ $d, (.unit_type // "-"), ((.pms_first_name // "") + " " + (.pms_last_name // "")), .contact_id ] | @tsv
  ' \
| while IFS=$'\t' read -r ARR UNIT GUEST CONTACT; do
    SENT=$(sendsquared contacts timeline "$CONTACT" 2>/dev/null \
      | jq '[.data[]? | select(.direction == "outbound")] | length')
    if [ "${SENT:-0}" -eq 0 ]; then
      printf "  %-12s %-18s %-26s contact %s\n" "$ARR" "$UNIT" "$GUEST" "$CONTACT"
    fi
  done
echo "done"
