#!/usr/bin/env bash
# Abandoned call triage
# Every caller who hung up before an agent picked up yesterday, turned into a task assigned to whoever owns callbacks. Missed calls during peak season are lost bookings.
#
# Category : Operations
# Safety   : WRITES DATA, read before running
# Uses     : reports run, tasks create
# Returns  : One task per abandoned call, attached to the contact where one is known.
#
# 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/#abandoned-call-triage

# Yesterday's abandoned calls -> callback tasks.
set -euo pipefail
DAY=${1:-$(date -u -v-1d +%F 2>/dev/null || date -u -d "-1 day" +%F)}
AGENT=${2:?pass the agent to assign callbacks to (id, name or email)}

CALLS=$(sendsquared reports run --type call_abandonment_detail --from "$DAY" --to "$DAY")

jq -r '.data[] | [ (.contactId // ""), (.callerNumber // .fromNumber // ""), (.waitSeconds // 0) ] | @tsv' <<<"$CALLS" \
| while IFS=$'\t' read -r CONTACT NUMBER WAIT; do
    sendsquared tasks create \
      --label "Call back $NUMBER" \
      --description "Abandoned after ${WAIT}s waiting on $DAY." \
      --due "$(date -u +%F)" \
      --agent "$AGENT" \
      ${CONTACT:+--contact "$CONTACT"} \
      --output quiet
    echo "task queued for $NUMBER (waited ${WAIT}s)"
  done
