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

Add Ticket Fields for Zendesk #86

Merged
merged 5 commits into from
Nov 4, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file modified mailroom_test.dump
Binary file not shown.
8 changes: 6 additions & 2 deletions services/tickets/zendesk/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,10 @@ type errorResponse struct {
Description string `json:"description"`
}

func (c *baseClient) get(endpoint string, payload interface{}, response interface{}) (*httpx.Trace, error) {
return c.request("GET", endpoint, payload, response)
}

func (c *baseClient) post(endpoint string, payload interface{}, response interface{}) (*httpx.Trace, error) {
return c.request("POST", endpoint, payload, response)
}
Expand Down Expand Up @@ -225,8 +229,8 @@ func NewPushClient(httpClient *http.Client, httpRetries *httpx.RetryConfig, subd

// FieldValue is a value for the named field
type FieldValue struct {
ID string `json:"id"`
Value string `json:"value"`
ID string `json:"id"`
Value interface{} `json:"value"`
}

// Author see https://developer.zendesk.com/rest_api/docs/support/channel_framework#author-object
Expand Down
67 changes: 65 additions & 2 deletions services/tickets/zendesk/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@ import (
"fmt"
"net/http"
"net/url"
"reflect"
"strings"

"github.com/nyaruka/gocommon/dates"
"github.com/nyaruka/gocommon/httpx"
"github.com/nyaruka/gocommon/jsonx"
"github.com/nyaruka/goflow/flows"
"github.com/nyaruka/goflow/utils"
"github.com/nyaruka/mailroom/core/models"
Expand Down Expand Up @@ -81,7 +83,6 @@ func (s *service) Open(session flows.Session, topic *flows.Topic, body string, a

msg := &ExternalResource{
ExternalID: string(ticket.UUID()), // there's no local msg so use ticket UUID instead
Message: body,
ThreadID: string(ticket.UUID()),
CreatedAt: dates.Now(),
Author: Author{
Expand All @@ -91,10 +92,73 @@ func (s *service) Open(session flows.Session, topic *flows.Topic, body string, a
AllowChannelback: true,
}

var tags []string

fieldsValue := []FieldValue{}
if !strings.HasPrefix(body, "{") {
msg.Message = body
} else {
extra := &struct {
Message string `json:"message"`
Priority string `json:"priority"`
Subject string `json:"subject"`
Description string `json:"description"`
CustomFields []FieldValue `json:"custom_fields"`
Tags []string `json:"tags"`
}{}

err := jsonx.Unmarshal([]byte(body), extra)
if err != nil {
return nil, err
}

v := reflect.ValueOf(extra)
fields := reflect.Indirect(v)
if fields.NumField() > 0 {
for i := 0; i < fields.NumField(); i++ {
if fields.Field(i).Type().Name() == "string" && fields.Field(i).Interface() != "" {
fieldsValue = append(fieldsValue, FieldValue{ID: fields.Type().Field(i).Tag.Get("json"), Value: fields.Field(i).Interface()})
} else if fields.Type().Field(i).Tag.Get("json") == "custom_fields" && fields.Field(i).Interface() != nil {
fieldsValue = append(fieldsValue, FieldValue{ID: fields.Type().Field(i).Tag.Get("json"), Value: fields.Field(i).Interface()})
}
}
msg.Fields = fieldsValue
}

if extra.Message != "" {
msg.Message = extra.Message
} else {
msg.Message = extra.Subject
}

tags = extra.Tags
}

if err := s.push(msg, logHTTP); err != nil {
return nil, err
}

if tags != nil {
trace, err := s.restClient.get("tickets?external_id="+string(ticket.UUID()), nil, nil)
if err != nil {
return nil, err
}
response := &struct {
Tickets []struct {
TicketID int `json:"id"`
} `json:"tickets"`
}{}
err = jsonx.Unmarshal(trace.ResponseBody, response)
if err != nil {
return nil, err
}

_, err = s.restClient.put(fmt.Sprint(response.Tickets[0].TicketID)+"/tags.json", tags, nil)
if err != nil {
return nil, err
}
}

return ticket, nil
}

Expand Down Expand Up @@ -249,7 +313,6 @@ func (s *service) push(msg *ExternalResource, logHTTP flows.HTTPLogCallback) err
// For example https://mybucket.s3.amazonaws.com/attachments/1/01c1/1aa4/01c11aa4-770a-4783.jpg
// is sent to Zendesk as file/1/01c1/1aa4/01c11aa4-770a-4783.jpg
// which it will request as POST https://textit.com/tickets/types/zendesk/file/1/01c1/1aa4/01c11aa4-770a-4783.jpg
//
func (s *service) convertAttachments(attachments []utils.Attachment) ([]string, error) {
prefix := s.rtConfig.S3MediaPrefix
if !strings.HasPrefix(prefix, "/") {
Expand Down
22 changes: 19 additions & 3 deletions services/tickets/zendesk/service_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ import (
"github.com/stretchr/testify/require"
)

const fieldTicket = `{"message":"Cookies","priority":"high","subject":"Where are my cookies?","description":"I want to know where is my cookie.","tags": ["TAG_01","TAG_02"],"custom_fields":[{"id":"21938362","value":"hd_3000"}]}`

func TestOpenAndForward(t *testing.T) {
ctx, rt, _, _ := testsuite.Get()

Expand Down Expand Up @@ -55,6 +57,20 @@ func TestOpenAndForward(t *testing.T) {
]
}`),
},
"https://nyaruka.zendesk.com/api/v2/tickets?external_id=59d74b86-3e2f-4a93-aece-b05d2fdcde0c": {
httpx.NewMockResponse(200, nil, `{
"tickets": [
{
"id": 1234,
"subject": "Where are my cookie?"
}
]}`),
},
"https://nyaruka.zendesk.com/api/v2/1234/tags.json": {
httpx.NewMockResponse(200, nil, `{
"tags": ["TAG_01","TAG_02"]
}`),
},
}))

ticketer := flows.NewTicketer(static.NewTicketer(assets.TicketerUUID(uuids.New()), "Support", "zendesk"))
Expand Down Expand Up @@ -90,16 +106,16 @@ func TestOpenAndForward(t *testing.T) {
defaultTopic := oa.SessionAssets().Topics().FindByName("General")

// try with connection failure
_, err = svc.Open(session, defaultTopic, "Where are my cookies?", nil, logger.Log)
_, err = svc.Open(session, defaultTopic, fieldTicket, nil, logger.Log)
assert.EqualError(t, err, "error pushing message to zendesk: unable to connect to server")

logger = &flows.HTTPLogger{}

ticket, err := svc.Open(session, defaultTopic, "Where are my cookies?", nil, logger.Log)
ticket, err := svc.Open(session, defaultTopic, fieldTicket, nil, logger.Log)
assert.NoError(t, err)
assert.Equal(t, flows.TicketUUID("59d74b86-3e2f-4a93-aece-b05d2fdcde0c"), ticket.UUID())
assert.Equal(t, "General", ticket.Topic().Name())
assert.Equal(t, "Where are my cookies?", ticket.Body())
assert.Equal(t, fieldTicket, ticket.Body())
assert.Equal(t, "", ticket.ExternalID())
assert.Equal(t, 1, len(logger.Logs))
test.AssertSnapshot(t, "open_ticket", logger.Logs[0].Request)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,4 @@ Authorization: Bearer ****************
Content-Type: application/json
Accept-Encoding: gzip

{"instance_push_id":"1234-abcd","request_id":"sesame:1570461700000000000","external_resources":[{"external_id":"ca5607f0-cba8-4c94-9cd5-c4fbc24aa767","message":"It's urgent","thread_id":"59d74b86-3e2f-4a93-aece-b05d2fdcde0c","created_at":"2019-10-07T15:21:39Z","author":{"external_id":"6393abc0-283d-4c9b-a1b3-641a035c34bf","name":"Cathy"},"allow_channelback":true,"file_urls":["file/0123/attachment1.jpg"]}]}
{"instance_push_id":"1234-abcd","request_id":"sesame:1570461704000000000","external_resources":[{"external_id":"ca5607f0-cba8-4c94-9cd5-c4fbc24aa767","message":"It's urgent","thread_id":"59d74b86-3e2f-4a93-aece-b05d2fdcde0c","created_at":"2019-10-07T15:21:43Z","author":{"external_id":"6393abc0-283d-4c9b-a1b3-641a035c34bf","name":"Cathy"},"allow_channelback":true,"file_urls":["file/0123/attachment1.jpg"]}]}
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
POST /api/v2/any_channel/push.json HTTP/1.1
Host: nyaruka.zendesk.com
User-Agent: Go-http-client/1.1
Content-Length: 382
Content-Length: 631
Authorization: Bearer ****************
Content-Type: application/json
Accept-Encoding: gzip

{"instance_push_id":"1234-abcd","request_id":"sesame:1570461696000000000","external_resources":[{"external_id":"59d74b86-3e2f-4a93-aece-b05d2fdcde0c","message":"Where are my cookies?","thread_id":"59d74b86-3e2f-4a93-aece-b05d2fdcde0c","created_at":"2019-10-07T15:21:35Z","author":{"external_id":"5d76d86b-3bb9-4d5a-b822-c9d86f5d8e4f","name":"Ryan Lewis"},"allow_channelback":true}]}
{"instance_push_id":"1234-abcd","request_id":"sesame:1570461696000000000","external_resources":[{"external_id":"59d74b86-3e2f-4a93-aece-b05d2fdcde0c","message":"Cookies","thread_id":"59d74b86-3e2f-4a93-aece-b05d2fdcde0c","created_at":"2019-10-07T15:21:35Z","author":{"external_id":"5d76d86b-3bb9-4d5a-b822-c9d86f5d8e4f","name":"Ryan Lewis"},"allow_channelback":true,"fields":[{"id":"message","value":"Cookies"},{"id":"priority","value":"high"},{"id":"subject","value":"Where are my cookies?"},{"id":"description","value":"I want to know where is my cookie."},{"id":"custom_fields","value":[{"id":"21938362","value":"hd_3000"}]}]}]}