-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathemail-server.js
More file actions
172 lines (150 loc) · 5.19 KB
/
email-server.js
File metadata and controls
172 lines (150 loc) · 5.19 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
// email-server.js — Express server for email webhook processing
// Handles incoming emails via AWS SES and processes tax documents
import express from 'express';
import { handleEmailWebhook } from './email-handler.js';
import { sendProcessingResults, sendErrorNotification } from './email-sender.js';
import { updateUserTaxData } from './tax-integration.js';
const app = express();
const PORT = process.env.PORT || 3000;
// Middleware for parsing JSON and form data
app.use(express.urlencoded({ extended: true, limit: '50mb' }));
app.use(express.json({ limit: '50mb' }));
// TODO: Add rate limiting middleware for production deployment
// Recommended: express-rate-limit package
// Example:
// const rateLimit = require('express-rate-limit');
// const limiter = rateLimit({
// windowMs: 60 * 60 * 1000, // 1 hour
// max: 100, // limit each IP to 100 requests per windowMs
// message: 'Too many requests from this IP, please try again later.'
// });
// app.use('/webhook/', limiter);
/**
* Health check endpoint
*/
app.get('/health', (req, res) => {
res.json({
status: 'ok',
service: 'TaxSync Email Integration',
timestamp: new Date().toISOString(),
});
});
/**
* AWS SES webhook endpoint for incoming emails
* Receives emails sent to notifications@isaloumapps.com
*/
app.post('/webhook/ses', async (req, res) => {
try {
// Extract email data from AWS SES webhook
// AWS SES can send SNS notifications with email data
const emailData = {
from: req.body.from || req.body.sender,
subject: req.body.subject || 'No subject',
textBody: req.body.text || req.body.body || '',
htmlBody: req.body.html || '',
attachments: req.body.attachments || [],
receivedAt: new Date(req.body.receivedAt || Date.now()),
};
console.log(
`📧 Received email from ${emailData.from} with ${emailData.attachments.length} attachment(s)`
);
// Process the email through our handler
const processingResult = await handleEmailWebhook(emailData);
if (processingResult.success) {
// Update user's tax data
const taxUpdates = [];
for (const doc of processingResult.processingResult.processedDocuments) {
try {
const taxUpdate = await updateUserTaxData(emailData.from, doc);
taxUpdates.push(taxUpdate);
} catch (error) {
console.error('Tax update error:', error);
}
}
// Send success email with results
await sendProcessingResults(
emailData.from,
processingResult.processingResult.processedDocuments,
emailData.subject,
taxUpdates
);
} else {
// Send error notification
await sendErrorNotification(
emailData.from,
processingResult.error || 'Unknown error',
emailData.subject
);
}
// Respond to AWS SES webhook
res.status(200).json({ success: true, message: 'Email processed' });
} catch (error) {
console.error('Email processing error:', error);
// Try to notify user about the error
if (req.body.from || req.body.sender) {
try {
await sendErrorNotification(
req.body.from || req.body.sender,
error.message,
req.body.subject || 'Your submission'
);
} catch (sendError) {
console.error('Failed to send error notification:', sendError);
}
}
res.status(500).json({ error: 'Internal server error' });
}
});
/**
* Generic email webhook endpoint (for other email services)
*/
app.post('/webhook/email', async (req, res) => {
try {
const emailData = {
from: req.body.from || req.body.sender,
subject: req.body.subject || 'No subject',
textBody: req.body.text || req.body.body || '',
htmlBody: req.body.html || '',
attachments: req.body.attachments || [],
receivedAt: new Date(req.body.receivedAt || Date.now()),
};
console.log(`📧 Received email from ${emailData.from}`);
const processingResult = await handleEmailWebhook(emailData);
if (processingResult.success) {
const taxUpdates = [];
for (const doc of processingResult.processingResult.processedDocuments) {
try {
const taxUpdate = await updateUserTaxData(emailData.from, doc);
taxUpdates.push(taxUpdate);
} catch (error) {
console.error('Tax update error:', error);
}
}
await sendProcessingResults(
emailData.from,
processingResult.processingResult.processedDocuments,
emailData.subject,
taxUpdates
);
} else {
await sendErrorNotification(emailData.from, processingResult.error, emailData.subject);
}
res.status(200).json({ success: true });
} catch (error) {
console.error('Email webhook error:', error);
res.status(500).json({ error: error.message });
}
});
/**
* Start the server
*/
if (process.env.NODE_ENV !== 'test') {
app.listen(PORT, () => {
console.log(`🚀 TaxSync Email Server running on port ${PORT}`);
console.log(`📧 Webhook endpoints:`);
console.log(` - POST /webhook/ses (for AWS SES integration)`);
console.log(` - POST /webhook/email (generic webhook)`);
console.log(` - GET /health (health check)`);
});
}
export { app };