Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/escalate via ivr #2818

Merged
merged 16 commits into from
Mar 10, 2023
Merged
5 changes: 3 additions & 2 deletions engine/backend.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,8 @@ func newBackend(db *sql.DB) (*backend, error) {
id,
alert_id,
service_id,
contact_method_id
contact_method_id,
created_at
FROM outgoing_messages
WHERE id = $1
`),
Expand All @@ -60,7 +61,7 @@ func (b *backend) FindOne(ctx context.Context, id string) (*callback, error) {
var alertID sql.NullInt64
var serviceID sql.NullString
var cmID sql.NullString
err = b.findOne.QueryRowContext(ctx, id).Scan(&c.ID, &alertID, &serviceID, &cmID)
err = b.findOne.QueryRowContext(ctx, id).Scan(&c.ID, &alertID, &serviceID, &cmID, &c.CreatedAt)
if err != nil {
return nil, err
}
Expand Down
3 changes: 3 additions & 0 deletions engine/callback.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package engine

import (
"time"

"github.com/target/goalert/validation/validate"

"github.com/google/uuid"
Expand All @@ -11,6 +13,7 @@ type callback struct {
AlertID int
ServiceID string
ContactMethodID string
CreatedAt time.Time
}

func (c callback) Normalize() (*callback, error) {
Expand Down
12 changes: 12 additions & 0 deletions engine/engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -323,6 +323,12 @@ func (p *Engine) ReceiveSubject(ctx context.Context, providerID, subjectID, call
newStatus = alert.StatusActive
case notification.ResultResolve:
newStatus = alert.StatusClosed
case notification.ResultEscalate:
err = p.a.EscalateAsOf(ctx, cb.AlertID, cb.CreatedAt)
if err != nil {
return fmt.Errorf("escalate alert: %w", err)
}
return nil
default:
return errors.New("unknown result type")
}
Expand Down Expand Up @@ -376,6 +382,12 @@ func (p *Engine) Receive(ctx context.Context, callbackID string, result notifica
newStatus = alert.StatusActive
case notification.ResultResolve:
newStatus = alert.StatusClosed
case notification.ResultEscalate:
err = p.a.EscalateAsOf(ctx, cb.AlertID, cb.CreatedAt)
if err != nil {
return fmt.Errorf("escalate alert: %w", err)
}
return nil
default:
return errors.New("unknown result type")
}
Expand Down
1 change: 1 addition & 0 deletions notification/result.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,5 @@ type Result int
const (
ResultAcknowledge Result = iota
ResultResolve
ResultEscalate
)
5 changes: 3 additions & 2 deletions notification/result_string.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion notification/twilio/alertsms.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ var alertTempl = template.Must(template.New("alertSMS").Parse(`Alert #{{.AlertID
{{.Link}}{{end}}
{{- if .Code}}

Reply '{{.Code}}a' to ack, '{{.Code}}c' to close.{{end}}`))
Reply '{{.Code}}a' to ack, '{{.Code}}e' to escalate, '{{.Code}}c' to close.{{end}}`))

var bundleTempl = template.Must(template.New("alertBundleSMS").Parse(`Svc '{{.ServiceName}}': {{.Count}} unacked alert{{if gt .Count 1}}s{{end}}

Expand Down
12 changes: 6 additions & 6 deletions notification/twilio/alertsms_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ func TestSMS_RenderAlert(t *testing.T) {

https://example.com/alerts/123

Reply '1a' to ack, '1c' to close.`,
Reply '1a' to ack, '1e' to escalate, '1c' to close.`,
)

check("no-reply-code",
Expand All @@ -86,7 +86,7 @@ https://example.com/alerts/123`,
1,
`Alert #123: Testing

Reply '1a' to ack, '1c' to close.`,
Reply '1a' to ack, '1e' to escalate, '1c' to close.`,
)

check("no-link-or-reply-code",
Expand All @@ -106,11 +106,11 @@ Reply '1a' to ack, '1c' to close.`,
},
"https://example.com/alerts/123",
1,
`Alert #123: Testing with a really really obnoxiously long message that will be need to be tru
`Alert #123: Testing with a really really obnoxiously long message that will

https://example.com/alerts/123

Reply '1a' to ack, '1c' to close.`,
Reply '1a' to ack, '1e' to escalate, '1c' to close.`,
)

check("truncate-long-id",
Expand All @@ -120,11 +120,11 @@ Reply '1a' to ack, '1c' to close.`,
},
"https://example.com/alerts/123",
1,
`Alert #123456789: Testing with a really really obnoxiously long message that will be need to
`Alert #123456789: Testing with a really really obnoxiously long message tha

https://example.com/alerts/123

Reply '1a' to ack, '1c' to close.`,
Reply '1a' to ack, '1e' to escalate, '1c' to close.`,
)

check("message-too-long",
Expand Down
21 changes: 18 additions & 3 deletions notification/twilio/sms.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package twilio
import (
"context"
"database/sql"
stderrors "errors"
"fmt"
"net/http"
"net/url"
Expand All @@ -17,15 +18,16 @@ import (
"github.com/target/goalert/permission"
"github.com/target/goalert/retry"
"github.com/target/goalert/util/log"
"github.com/target/goalert/validation"
"github.com/ttacon/libphonenumber"

"github.com/pkg/errors"
)

var (
lastReplyRx = regexp.MustCompile(`^'?\s*(c|close|a|ack[a-z]*)\s*'?$`)
shortReplyRx = regexp.MustCompile(`^'?\s*([0-9]+)\s*(c|a)\s*'?$`)
alertReplyRx = regexp.MustCompile(`^'?\s*(c|close|a|ack[a-z]*)\s*#?\s*([0-9]+)\s*'?$`)
lastReplyRx = regexp.MustCompile(`^'?\s*(c|close|a|e|ack[a-z]*)\s*'?$`)
shortReplyRx = regexp.MustCompile(`^'?\s*([0-9]+)\s*(c|a|e)\s*'?$`)
alertReplyRx = regexp.MustCompile(`^'?\s*(c|close|e|a|ack[a-z]*)\s*#?\s*([0-9]+)\s*'?$`)

svcReplyRx = regexp.MustCompile(`^'?\s*([0-9]+)\s*(cc|aa)\s*'?$`)
)
Expand Down Expand Up @@ -303,13 +305,17 @@ func (s *SMS) ServeMessage(w http.ResponseWriter, req *http.Request) {
if m := lastReplyRx.FindStringSubmatch(body); len(m) == 2 {
if strings.HasPrefix(m[1], "a") {
result = notification.ResultAcknowledge
} else if strings.HasPrefix(m[1], "e") {
result = notification.ResultEscalate
} else {
result = notification.ResultResolve
}
lookupFn = func() (*codeInfo, error) { return s.b.LookupByCode(ctx, from, 0) }
} else if m := shortReplyRx.FindStringSubmatch(body); len(m) == 3 {
if strings.HasPrefix(m[2], "a") {
result = notification.ResultAcknowledge
} else if strings.HasPrefix(m[2], "e") {
result = notification.ResultEscalate
} else {
result = notification.ResultResolve
}
Expand All @@ -323,6 +329,8 @@ func (s *SMS) ServeMessage(w http.ResponseWriter, req *http.Request) {
} else if m := alertReplyRx.FindStringSubmatch(body); len(m) == 3 {
if strings.HasPrefix(m[1], "a") {
result = notification.ResultAcknowledge
} else if strings.HasPrefix(m[1], "e") {
result = notification.ResultEscalate
} else {
result = notification.ResultResolve
}
Expand All @@ -337,6 +345,8 @@ func (s *SMS) ServeMessage(w http.ResponseWriter, req *http.Request) {
isSvc = true
if strings.HasPrefix(m[2], "a") {
result = notification.ResultAcknowledge
} else if strings.HasPrefix(m[2], "e") {
result = notification.ResultEscalate
} else {
result = notification.ResultResolve
}
Expand All @@ -359,6 +369,8 @@ func (s *SMS) ServeMessage(w http.ResponseWriter, req *http.Request) {
var prefix string
if result == notification.ResultAcknowledge {
prefix = "Acknowledged"
} else if result == notification.ResultEscalate {
prefix = "Escalation requested"
} else {
prefix = "Closed"
}
Expand Down Expand Up @@ -390,6 +402,9 @@ func (s *SMS) ServeMessage(w http.ResponseWriter, req *http.Request) {
} else if alert.IsAlreadyAcknowledged(err) {
nonSystemErr = true
msg = fmt.Sprintf("Alert #%d already acknowledged", alert.AlertID(err))
} else if validation.IsClientError(err) {
respond(true, "Error: "+stderrors.Unwrap(err).Error())
return
}

if nonSystemErr {
Expand Down
4 changes: 4 additions & 0 deletions notification/twilio/twiml.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ const (
optionCancel
optionConfirmStop
optionAck
optionEscalate
optionClose
optionAckAll
optionCloseAll
Expand All @@ -81,6 +82,9 @@ func (t *twiMLResponse) AddOptions(options ...menuOption) {
case optionAck:
t.expectResponse = true
t.Sayf("To acknowledge, press %s.", digitAck)
case optionEscalate:
t.expectResponse = true
t.Sayf("To escalate, press %s.", digitEscalate)
case optionClose:
t.expectResponse = true
t.Sayf("To close, press %s.", digitClose)
Expand Down
30 changes: 30 additions & 0 deletions notification/twilio/twiml_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,36 @@ func TestTwiMLResponse(t *testing.T) {
<prosody rate="slow">To repeat this message, press star.</prosody>
</Say>
</Gather>
</Response>`, string(data))
})
t.Run("esc test", func(t *testing.T) {
var mockConfig config.Config
ctx := mockConfig.Context(context.Background())
rec := httptest.NewRecorder()

r := newTwiMLResponse(ctx, rec)
r.Say("Hello")
r.AddOptions(optionEscalate)
r.Gather("http://example.com")

resp := rec.Result()
assert.Equal(t, http.StatusOK, resp.StatusCode)
assert.Contains(t, resp.Header.Get("Content-Type"), "application/xml")
data, err := io.ReadAll(resp.Body)
assert.NoError(t, err)
assert.Equal(t, `<?xml version="1.0" encoding="UTF-8"?>
<Response>
<Gather numDigits="1" timeout="10" action="http://example.com">
<Say>
<prosody rate="slow">Hello</prosody>
</Say>
<Say>
<prosody rate="slow">To escalate, press 5.</prosody>
</Say>
<Say>
<prosody rate="slow">To repeat this message, press star.</prosody>
</Say>
</Gather>
</Response>`, string(data))
})
}
16 changes: 13 additions & 3 deletions notification/twilio/voice.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"database/sql"
"encoding/base64"
stderrors "errors"
"fmt"
"math"
"net/http"
Expand All @@ -20,6 +21,7 @@ import (
"github.com/target/goalert/permission"
"github.com/target/goalert/retry"
"github.com/target/goalert/util/log"
"github.com/target/goalert/validation"
"github.com/ttacon/libphonenumber"
)

Expand Down Expand Up @@ -52,6 +54,7 @@ const (
digitConfirm = "3"
digitOldAck = "8"
digitOldClose = "9"
digitEscalate = "5"
sayRepeat = "star"
)

Expand Down Expand Up @@ -94,6 +97,10 @@ func voiceErrorMessage(ctx context.Context, err error) (string, error) {
if alert.IsAlreadyAcknowledged(err) {
return "Alert is already acknowledged.", nil
}
if validation.IsClientError(err) {
return "Error: " + stderrors.Unwrap(err).Error(), nil
}

// Error is something else.
return "System error. Please visit the dashboard.", err
}
Expand Down Expand Up @@ -286,7 +293,6 @@ func (v *Voice) ServeStatusCallback(w http.ResponseWriter, req *http.Request) {
// log and continue
log.Log(ctx, err)
}

}

type call struct {
Expand Down Expand Up @@ -483,6 +489,7 @@ func (v *Voice) ServeTest(w http.ResponseWriter, req *http.Request) {
return
}
}

func (v *Voice) ServeVerify(w http.ResponseWriter, req *http.Request) {
if disabled(w, req) {
return
Expand Down Expand Up @@ -587,7 +594,7 @@ func (v *Voice) ServeAlert(w http.ResponseWriter, req *http.Request) {
if call.Q.Get(msgParamBundle) == "1" {
resp.AddOptions(optionAckAll, optionCloseAll)
} else {
resp.AddOptions(optionAck, optionClose)
resp.AddOptions(optionAck, optionEscalate, optionClose)
}
resp.AddOptions(optionStop)
resp.Gather(v.callbackURL(ctx, call.Q, CallTypeAlert))
Expand All @@ -598,12 +605,15 @@ func (v *Voice) ServeAlert(w http.ResponseWriter, req *http.Request) {
resp.Redirect(v.callbackURL(ctx, call.Q, CallTypeStop))
return

case digitAck, digitClose: // Acknowledge and Close cases
case digitAck, digitClose, digitEscalate: // Acknowledge , Escalate and Close cases
var result notification.Result
var msg string
if call.Digits == digitClose {
result = notification.ResultResolve
msg = "Closed"
} else if call.Digits == digitEscalate {
result = notification.ResultEscalate
msg = "Escalation requested"
} else {
result = notification.ResultAcknowledge
msg = "Acknowledged"
Expand Down