-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathemail-handler.js
More file actions
302 lines (255 loc) · 8.45 KB
/
Copy pathemail-handler.js
File metadata and controls
302 lines (255 loc) · 8.45 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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
// email-handler.js — Email processing workflow for tax documents
// Handles incoming emails with attachments and processes them automatically
import { createDocumentProcessor } from './document-processor.js';
/**
* Email processing result
* @typedef {Object} EmailProcessingResult
* @property {boolean} success - Whether processing succeeded
* @property {string} emailSubject - Email subject line
* @property {string} emailFrom - Email sender
* @property {Date} receivedAt - When email was received
* @property {Array} processedDocuments - Array of processed document results
* @property {Array} failedAttachments - Array of failed attachment names
* @property {string} summary - Processing summary
*/
/**
* EmailProcessor class for handling incoming email processing
*/
export class EmailProcessor {
constructor() {
this.documentProcessor = null;
this.maxAttachmentSize = 10 * 1024 * 1024; // 10MB
this.supportedFormats = ['.pdf', '.jpg', '.jpeg', '.png', '.txt'];
}
/**
* Initialize the email processor
*/
async initialize() {
this.documentProcessor = await createDocumentProcessor();
}
/**
* Extract attachments from an email
* @param {object} email - Email object with attachments
* @returns {Array<File>} - Array of attachment files
*/
extractAttachments(email) {
if (!email.attachments || email.attachments.length === 0) {
return [];
}
const validAttachments = [];
for (const attachment of email.attachments) {
// Check file size
if (attachment.size > this.maxAttachmentSize) {
console.warn(`Attachment ${attachment.name} exceeds max size (10MB)`);
continue;
}
// Check file format
const hasValidExtension = this.supportedFormats.some((ext) =>
attachment.name.toLowerCase().endsWith(ext)
);
if (!hasValidExtension) {
console.warn(`Attachment ${attachment.name} has unsupported format`);
continue;
}
validAttachments.push(attachment);
}
return validAttachments;
}
/**
* Extract text from email body
* @param {object} email - Email object
* @returns {string} - Email body text
*/
extractEmailBodyText(email) {
// Try to get plain text version first
if (email.textBody) {
return email.textBody;
}
// Fall back to HTML body (strip tags)
if (email.htmlBody) {
// Basic HTML tag removal
return email.htmlBody
.replace(/<[^>]*>/g, ' ')
.replace(/\s+/g, ' ')
.trim();
}
return '';
}
/**
* Process text from email body
* @param {string} text - Email body text
* @returns {object|null} - Processing result or null if no valid data
*/
processEmailBody(text) {
// Only process if text looks like it contains tax document data
if (!text || text.length < 50) return null;
// Check if text contains any document-like patterns
const hasDocumentPatterns =
/(?:Box|Case)\s+(?:14|A|16)|Employment\s+Income|Gross\s+Fares?|Total|Receipt/i.test(text);
if (!hasDocumentPatterns) return null;
return this.documentProcessor.processText(text);
}
/**
* Process a single incoming email
* @param {object} email - Email object
* @returns {Promise<EmailProcessingResult>}
*/
async processIncomingEmail(email) {
if (!this.documentProcessor) {
await this.initialize();
}
const results = [];
const failedAttachments = [];
// Step 1: Process attachments
const attachments = this.extractAttachments(email);
for (const attachment of attachments) {
try {
const result = await this.documentProcessor.processDocument(attachment);
results.push(result);
} catch (error) {
failedAttachments.push({
name: attachment.name,
error: error.message,
});
}
}
// Step 2: Try to extract data from email body
const bodyText = this.extractEmailBodyText(email);
const bodyResult = this.processEmailBody(bodyText);
if (bodyResult && bodyResult.success) {
results.push(bodyResult);
}
// Step 3: Generate summary
const summary = this.generateEmailSummary(results, failedAttachments);
return {
success: results.length > 0,
emailSubject: email.subject || 'No subject',
emailFrom: email.from || 'Unknown sender',
receivedAt: email.receivedAt || new Date(),
processedDocuments: results,
failedAttachments,
summary,
};
}
/**
* Generate a summary report of email processing
* @param {Array} results - Processing results
* @param {Array} failedAttachments - Failed attachments
* @returns {string} - Summary text
*/
generateEmailSummary(results, failedAttachments) {
let summary = '📧 Email Processing Summary\n\n';
if (results.length === 0) {
summary += '❌ No valid documents were processed.\n';
if (failedAttachments.length > 0) {
summary += `\nFailed attachments (${failedAttachments.length}):\n`;
failedAttachments.forEach((att) => {
summary += ` - ${att.name}: ${att.error}\n`;
});
}
return summary;
}
summary += `✅ Successfully processed ${results.length} document(s):\n\n`;
results.forEach((result, index) => {
summary += `${index + 1}. ${result.documentType}\n`;
if (result.fileName) {
summary += ` File: ${result.fileName}\n`;
}
if (result.validation.confidenceScore) {
summary += ` Confidence: ${result.validation.confidenceScore}%\n`;
}
if (result.extractedData) {
const dataPoints = Object.keys(result.extractedData).length;
summary += ` Extracted ${dataPoints} field(s)\n`;
}
if (result.validation.warnings.length > 0) {
summary += ` ⚠️ ${result.validation.warnings.length} warning(s)\n`;
}
summary += '\n';
});
if (failedAttachments.length > 0) {
summary += `\n⚠️ Failed to process ${failedAttachments.length} attachment(s):\n`;
failedAttachments.forEach((att) => {
summary += ` - ${att.name}\n`;
});
}
return summary;
}
/**
* Generate an email response with processing results
* @param {EmailProcessingResult} result - Email processing result
* @returns {object} - Email response object
*/
generateEmailResponse(result) {
const subject = `Re: ${result.emailSubject} - Processing Complete`;
let body = `Thank you for submitting your tax documents!\n\n`;
body += result.summary;
body += '\n---\n';
body += 'TaxSyncForDrivers Automated Document Processing\n';
body += 'This is an automated response. Please do not reply to this email.\n';
return {
to: result.emailFrom,
subject,
body,
isSuccess: result.success,
};
}
/**
* Clean up resources
*/
async cleanup() {
if (this.documentProcessor) {
await this.documentProcessor.cleanup();
}
}
}
/**
* Create and initialize an email processor
* @returns {Promise<EmailProcessor>}
*/
export async function createEmailProcessor() {
const processor = new EmailProcessor();
await processor.initialize();
return processor;
}
/**
* Webhook handler for incoming emails (e.g., from n8n)
* @param {object} webhookPayload - Webhook payload from email service
* @returns {Promise<object>} - Processing result
*/
export async function handleEmailWebhook(webhookPayload) {
const processor = new EmailProcessor();
await processor.initialize();
try {
// Parse webhook payload into email format
const email = {
from: webhookPayload.from || webhookPayload.sender,
subject: webhookPayload.subject,
textBody: webhookPayload.text || webhookPayload.body,
htmlBody: webhookPayload.html,
attachments: webhookPayload.attachments || [],
receivedAt: new Date(webhookPayload.receivedAt || Date.now()),
};
const result = await processor.processIncomingEmail(email);
// Generate response email
const response = processor.generateEmailResponse(result);
return {
success: true,
processingResult: result,
emailResponse: response,
};
} catch (error) {
return {
success: false,
error: error.message,
emailResponse: {
to: webhookPayload.from,
subject: 'Document Processing Failed',
body: `We encountered an error processing your documents: ${error.message}\n\nPlease try again or contact support.`,
isSuccess: false,
},
};
} finally {
await processor.cleanup();
}
}