#!/usr/bin/env bash
# Cart abandonment ROI
# What the abandonment recovery actually earned, by channel, over any window. The number to bring to a renewal conversation.
#
# Category : Revenue
# Safety   : read only
# Uses     : reports run
# Returns  : Recovered bookings and revenue attributed to abandonment recovery.
#
# 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/#cart-abandon-roi

# Abandonment recovery. Money fields are integer cents.
set -euo pipefail
FROM=${1:-$(date -u -v-90d +%F 2>/dev/null || date -u -d "-90 days" +%F)}
TO=${2:-$(date -u +%F)}

R=$(sendsquared reports run cart_abandon_conversion --from "$FROM" --to "$TO")
N=$(jq '.data | length' <<<"$R")

echo "window: $FROM to $TO"
if [ "$N" -eq 0 ]; then
  echo "no cart abandonment data in this window."
  echo "if you expect some, check the cart_abandon trigger is live:"
  echo "  sendsquared workflows list | jq -r '.data[] | select(.trigger_type==\"cart_abandon\") | .name'"
  exit 0
fi
jq -r '.data[] | to_entries | map("  \(.key): \(.value)") | .[]' <<<"$R"
