-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
171 lines (139 loc) · 5.53 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
export async function setupPlugin({ config, global, cache }) {
console.info(`Setting up the plugin`)
let baseUrl = `https://${config.hostName}.zendesk.com/`
global.token = Buffer.from(`${config.userEmail}/token:${config.zendeskApiKey}`).toString('base64')
global.baseTicketUrl = baseUrl + 'api/v2/tickets.json?sort_order=desc&sort_by=id'
global.fetchUserUrl = baseUrl + 'api/v2/users'
global.options = {
headers: {
Authorization: `Basic ${global.token}`,
'Content-Type': 'application/json',
},
}
const authenticationResponse = await fetchWithRetry(global.baseTicketUrl, global.options)
if (!statusOk(authenticationResponse)) {
throw new Error(`Unable to access ZenDesk API's for ${config.hostName}`)
} else {
console.info(`Initial setup with ZenDesk for ${config.hostName} successful`)
}
global.triggeringEvents = (config.triggeringEvents || '').split(',').map((v) => v.trim())
global.emailDomainsToIgnore = (config.ignoredEmails || '').split(',').map((v) => v.trim())
}
export const jobs = {
pushUserDataToZendesk: async (request, { storage, global, cache }) => {
const userId = await storage.get(request.email, null)
if (userId) {
const url = global.fetchUserUrl
global.options.body = JSON.stringify({
user: {
user_fields: { [request.event.event]: `${request.event.sent_at}` },
},
})
const result = await fetchWithRetry(`${url}/${userId}`, global.options, 'PUT')
}
},
}
async function fetchUserIdentity(requesterId, global, storage) {
const userResult = await fetchWithRetry(`${global.fetchUserUrl}/${requesterId}`, global.options)
const user = await userResult.json()
// posthog.capture(user.user.email, { $set_once: { zendeskId: user.user.id } });
await storage.set(user.user.email, user.user.id)
return user.user.email
}
async function fetchAllTickets(global, storage, cache) {
let allTickets = [null]
let index = 1
while (allTickets.length > 0) {
const finalUrl = `${global.baseTicketUrl}&page=${index}`
const allTicketData = await fetchWithRetry(finalUrl, global.options)
index += 1
allTickets = await allTicketData.json()
allTickets = allTickets.tickets
if (allTickets.length === 0) {
break
}
///saves storage space
for (let ticket of allTickets) {
const customerRecordExists = await storage.get(ticket.id, null)
if (!customerRecordExists) {
await storage.set(ticket.id, true)
} else {
break
}
const emailId = await fetchUserIdentity(ticket.requester_id, global, storage)
const ticketObjectToSave = {
ticketId: ticket.id,
created_at: ticket.created_at,
updated_at: ticket.updated_at,
type: ticket.type,
subject: ticket.raw_subject,
description: ticket.description,
priority: ticket.priority,
status: ticket.status,
recipient: ticket.recipient,
requester_id: ticket.requester_id,
submitter_id: ticket.submitter_id,
assignee_id: ticket.assignee_id,
organization_id: ticket.organization_id,
group_id: ticket.group_id,
is_public: ticket.is_public,
due_at: ticket.due_at,
ticket_form_id: ticket.ticket_form_id,
brand_id: ticket.brand_id,
}
posthog.capture('zendesk_ticket', {
distinct_id: emailId,
$set: { zendeskId: ticketObjectToSave.requester_id },
...ticketObjectToSave,
})
}
}
}
export async function onEvent(event, { jobs, config, global, storage }) {
if (global.triggeringEvents.includes(event.event)) {
const email = getEmailFromEvent(event)
if (email) {
if (global.emailDomainsToIgnore.includes(email.split('@')[1])) {
return
}
const request = {
email: email,
event: event,
}
await jobs.pushUserDataToZendesk(request).runNow()
}
}
}
function getEmailFromEvent(event) {
if (isEmail(event.distinct_id)) {
return event.distinct_id
} else if (event['$set'] && Object.keys(event['$set']).includes('email')) {
if (isEmail(event['$set']['email'])) {
return event['$set']['email']
}
} else if (event['properties'] && Object.keys(event['properties']).includes('email')) {
if (isEmail(event['properties']['email'])) {
return event['properties']['email']
}
}
return null
}
export async function runEveryMinute({ global, storage, cache }) {
const allTickets = await fetchAllTickets(global, storage, cache)
}
function isEmail(email) {
const re =
/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
return re.test(String(email).toLowerCase())
}
function statusOk(res) {
return String(res.status)[0] === '2'
}
async function fetchWithRetry(url, options = {}, method = 'GET') {
try {
const res = await fetch(url, { method: method, ...options })
return res
} catch (e) {
throw new RetryError(e.toString())
}
}