-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworker.js
More file actions
189 lines (150 loc) · 5.64 KB
/
worker.js
File metadata and controls
189 lines (150 loc) · 5.64 KB
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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
// =============================================================================
// CONFIGURATION - Update these values for your SuperOps instance
// =============================================================================
// Your SuperOps subdomain (e.g., "my.yourcompany.io" or "app.superops.ai")
const SUPEROPS_DOMAIN = "my.limehawk.io";
// Fallback URL when ticket link can't be extracted
const FALLBACK_URL = `https://${SUPEROPS_DOMAIN}`;
// =============================================================================
export default {
async fetch(request, env, ctx) {
return new Response("Email worker - not a web endpoint", { status: 200 });
},
async email(message, env, ctx) {
const subject = message.headers.get("subject") || "";
const rawEmail = await new Response(message.raw).text();
const decoded = decodeEmail(rawEmail);
const bodyStart = decoded.indexOf("<html>");
const body = bodyStart > -1 ? decoded.substring(bodyStart) : decoded;
const isReply = subject.toLowerCase().includes("replied to");
const ticketData = parseTicketData(body, isReply);
const chatPayload = isReply
? buildReplyCard(ticketData)
: buildNewTicketCard(ticketData);
await fetch(env.GCHAT_WEBHOOK, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(chatPayload)
});
}
};
function decodeEmail(raw) {
return raw
.replace(/=\r\n/g, "")
.replace(/=([0-9A-F]{2})/gi, (_, hex) => String.fromCharCode(parseInt(hex, 16)))
.replace(/\r\n/g, "\n");
}
function cleanText(text) {
return text
.replace(/\xA0/g, " ")
.replace(/Â/g, "")
.replace(/\s+/g, " ")
.trim();
}
function parseTicketData(body, isReply) {
return {
ticketId: cleanText(extractAfterLabel(body, "Ticket #:") || extractAfterLabel(body, "ticket #")).replace(/\.$/, ""),
client: cleanText(extractAfterLabel(body, "Client:")),
site: cleanText(extractAfterLabel(body, "Site:")),
subject: cleanText(extractAfterLabel(body, "Subject:")),
ticketUrl: extractUrl(body),
priority: cleanText(extractAfterLabel(body, "Priority:")),
category: cleanText(extractAfterLabel(body, "Category:")),
status: cleanText(extractAfterLabel(body, "Status:")),
requester: cleanText(extractAfterLabel(body, "Requester:")),
description: extractDescription(body),
repliedBy: cleanText(extractAfterLabel(body, "Reply from:")),
replyContent: extractReplyContent(body)
};
}
function extractAfterLabel(text, label) {
const labelIndex = text.toLowerCase().indexOf(label.toLowerCase());
if (labelIndex === -1) return "";
const afterLabel = text.substring(labelIndex + label.length);
const spanMatch = afterLabel.match(/[^>]*>([^<]+)</);
if (spanMatch) {
return spanMatch[1];
}
return "";
}
function extractUrl(text) {
// Build regex from configured domain
const escapedDomain = SUPEROPS_DOMAIN.replace(/\./g, "\\.");
const pattern = new RegExp(`https://${escapedDomain}/#/tickets/\\d+/ticket`);
const match = text.match(pattern);
return match ? match[0] : "";
}
function extractDescription(body) {
const descIndex = body.indexOf("Description:");
if (descIndex === -1) return "";
const afterDesc = body.substring(descIndex);
const divMatch = afterDesc.match(/<div>([^<]+)<\/div>/i);
if (!divMatch) return "";
let content = divMatch[1]
.replace(/ /g, " ")
.replace(/\xA0/g, " ")
.replace(/Â/g, "")
.replace(/\s+/g, " ")
.trim();
if (content.length > 500) {
content = content.substring(0, 500).trim() + "...";
}
return content;
}
function extractReplyContent(body) {
const replyMarker = 'data-value="Reply">';
const replyStart = body.indexOf(replyMarker);
if (replyStart === -1) return "";
let afterReply = body.substring(replyStart + replyMarker.length);
const divMatch = afterReply.match(/<div>\s*([\s\S]*?)\s*<\/div>/i);
if (!divMatch) return "";
let content = divMatch[1]
.replace(/<[^>]+>/g, " ")
.replace(/ /g, " ")
.replace(/\xA0/g, " ")
.replace(/Â/g, "")
.replace(/\s+/g, " ")
.trim();
if (content.length > 500) {
content = content.substring(0, 500).trim() + "...";
}
return content || "No content";
}
function buildNewTicketCard(data) {
const lines = [];
lines.push(`🎫 *New Ticket #${data.ticketId}*`);
lines.push(`*${data.subject || "No subject"}*`);
lines.push("");
if (data.client) lines.push(`🏢 Client: ${data.client}`);
if (data.site) lines.push(`📍 Site: ${data.site}`);
if (data.requester) lines.push(`👤 Requester: ${data.requester}`);
if (data.priority) lines.push(`🚨 Priority: ${data.priority}`);
if (data.category) lines.push(`📂 Category: ${data.category}`);
if (data.description) {
lines.push("");
lines.push(`📝 Description:`);
lines.push(data.description);
}
lines.push("");
lines.push(`🔗 ${data.ticketUrl || FALLBACK_URL}`);
return { text: lines.join("\n") };
}
function buildReplyCard(data) {
const lines = [];
lines.push(`💬 *Ticket Reply #${data.ticketId}*`);
lines.push(`*${data.subject || "No subject"}*`);
lines.push("");
if (data.client) lines.push(`🏢 Client: ${data.client}`);
if (data.site) lines.push(`📍 Site: ${data.site}`);
if (data.requester) lines.push(`👤 Requester: ${data.requester}`);
if (data.priority) lines.push(`🚨 Priority: ${data.priority}`);
if (data.status) lines.push(`📋 Status: ${data.status}`);
if (data.replyContent) {
lines.push("");
lines.push(`💬 ${data.repliedBy || "Reply"}:`);
lines.push(data.replyContent);
}
lines.push("");
lines.push(`🔗 ${data.ticketUrl || FALLBACK_URL}`);
return { text: lines.join("\n") };
}