-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebhookController.js
More file actions
490 lines (422 loc) · 12.7 KB
/
webhookController.js
File metadata and controls
490 lines (422 loc) · 12.7 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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
/**
* Webhook Controller
* Handles webhook events for integration with external systems
*/
const Webhook = require('../models/Webhook');
const Transaction = require('../models/Transaction');
const { syncBankTransactions } = require('../services/bookkeeping/reconciliationService');
const { applyCategorizationRules } = require('../services/bookkeeping/categorizationService');
const { syncInvoices } = require('../services/bookkeeping/invoiceService');
const { syncPayments } = require('../services/bookkeeping/paymentService');
const { detectAnomalies } = require('../services/analysis/anomalyService');
const { detectCashFlowIssues } = require('../services/analysis/cashFlowService');
const logger = require('../utils/logger');
const { successResponse, errorResponse } = require('../utils/response');
const crypto = require('crypto');
const axios = require('axios');
/**
* Register a new webhook
* @param {Object} req - Express request object
* @param {Object} res - Express response object
*/
const registerWebhook = async (req, res) => {
try {
const { userId, tenantId } = req.user;
const { name, description, event, url, headers } = req.body;
if (!name || !event || !url) {
return errorResponse(res, 'Name, event, and URL are required', 400);
}
// Create webhook
const webhook = await Webhook.create({
userId,
tenantId,
name,
description,
event,
url,
headers: headers || {},
isActive: true
});
logger.info(`Registered webhook ${webhook.id} for event ${event}`);
return successResponse(res, {
message: 'Webhook registered successfully',
webhook: {
id: webhook.id,
name: webhook.name,
event: webhook.event,
url: webhook.url,
secret: webhook.secret
}
});
} catch (error) {
logger.error('Error in registerWebhook:', error);
return errorResponse(res, error.message, 500);
}
};
/**
* List registered webhooks
* @param {Object} req - Express request object
* @param {Object} res - Express response object
*/
const listWebhooks = async (req, res) => {
try {
const { userId, tenantId } = req.user;
const webhooks = await Webhook.findAll({
where: {
userId,
tenantId
},
attributes: ['id', 'name', 'description', 'event', 'url', 'isActive', 'lastTriggeredAt', 'successCount', 'failureCount']
});
return successResponse(res, webhooks);
} catch (error) {
logger.error('Error in listWebhooks:', error);
return errorResponse(res, error.message, 500);
}
};
/**
* Update webhook
* @param {Object} req - Express request object
* @param {Object} res - Express response object
*/
const updateWebhook = async (req, res) => {
try {
const { userId, tenantId } = req.user;
const { webhookId } = req.params;
const { name, description, event, url, headers, isActive } = req.body;
// Find webhook
const webhook = await Webhook.findOne({
where: {
id: webhookId,
userId,
tenantId
}
});
if (!webhook) {
return errorResponse(res, 'Webhook not found', 404);
}
// Update webhook
await webhook.update({
name: name || webhook.name,
description: description !== undefined ? description : webhook.description,
event: event || webhook.event,
url: url || webhook.url,
headers: headers || webhook.headers,
isActive: isActive !== undefined ? isActive : webhook.isActive
});
logger.info(`Updated webhook ${webhookId}`);
return successResponse(res, {
message: 'Webhook updated successfully',
webhook: {
id: webhook.id,
name: webhook.name,
event: webhook.event,
url: webhook.url,
isActive: webhook.isActive
}
});
} catch (error) {
logger.error('Error in updateWebhook:', error);
return errorResponse(res, error.message, 500);
}
};
/**
* Delete webhook
* @param {Object} req - Express request object
* @param {Object} res - Express response object
*/
const deleteWebhook = async (req, res) => {
try {
const { userId, tenantId } = req.user;
const { webhookId } = req.params;
// Find webhook
const webhook = await Webhook.findOne({
where: {
id: webhookId,
userId,
tenantId
}
});
if (!webhook) {
return errorResponse(res, 'Webhook not found', 404);
}
// Delete webhook
await webhook.destroy();
logger.info(`Deleted webhook ${webhookId}`);
return successResponse(res, {
message: 'Webhook deleted successfully'
});
} catch (error) {
logger.error('Error in deleteWebhook:', error);
return errorResponse(res, error.message, 500);
}
};
/**
* Regenerate webhook secret
* @param {Object} req - Express request object
* @param {Object} res - Express response object
*/
const regenerateWebhookSecret = async (req, res) => {
try {
const { userId, tenantId } = req.user;
const { webhookId } = req.params;
// Find webhook
const webhook = await Webhook.findOne({
where: {
id: webhookId,
userId,
tenantId
}
});
if (!webhook) {
return errorResponse(res, 'Webhook not found', 404);
}
// Generate new secret
const newSecret = crypto.randomBytes(32).toString('hex');
// Update webhook
await webhook.update({
secret: newSecret
});
logger.info(`Regenerated secret for webhook ${webhookId}`);
return successResponse(res, {
message: 'Webhook secret regenerated successfully',
webhook: {
id: webhook.id,
name: webhook.name,
secret: newSecret
}
});
} catch (error) {
logger.error('Error in regenerateWebhookSecret:', error);
return errorResponse(res, error.message, 500);
}
};
/**
* Handle Xero webhook events
* @param {Object} req - Express request object
* @param {Object} res - Express response object
*/
const handleXeroWebhook = async (req, res) => {
try {
// Verify Xero webhook signature
const xeroSignature = req.headers['x-xero-signature'];
if (!xeroSignature) {
logger.warn('Missing Xero webhook signature');
return errorResponse(res, 'Missing signature', 401);
}
// TODO: Implement proper signature verification
// This would require the webhook secret from Xero
// Process webhook event
const event = req.body;
if (!event || !event.events) {
return errorResponse(res, 'Invalid event format', 400);
}
// Process each event
for (const eventItem of event.events) {
await processXeroEvent(eventItem);
}
return successResponse(res, {
message: 'Webhook processed successfully'
});
} catch (error) {
logger.error('Error in handleXeroWebhook:', error);
return errorResponse(res, error.message, 500);
}
};
/**
* Process Xero event
* @param {Object} event - Xero event object
*/
const processXeroEvent = async (event) => {
try {
const { tenantId, eventType, resourceId } = event;
logger.info(`Processing Xero event: ${eventType} for tenant ${tenantId}`);
// Find users with this tenant
const users = await User.findAll({
include: [{
model: XeroTenant,
where: {
tenantId: tenantId
}
}]
});
if (users.length === 0) {
logger.warn(`No users found for tenant ${tenantId}`);
return;
}
// Process event for each user
for (const user of users) {
const userId = user.id;
switch (eventType) {
case 'INVOICE_CREATED':
case 'INVOICE_UPDATED':
await syncInvoices(userId, tenantId, { days: 7 });
break;
case 'PAYMENT_CREATED':
await syncPayments(userId, tenantId, { days: 7 });
break;
case 'BANK_TRANSACTION_CREATED':
case 'BANK_TRANSACTION_UPDATED':
await syncBankTransactions(userId, tenantId, { days: 7 });
await applyCategorizationRules(userId, tenantId);
break;
default:
logger.info(`Unhandled event type: ${eventType}`);
}
// Trigger user webhooks
await triggerUserWebhooks(userId, tenantId, eventType, {
eventType,
resourceId,
tenantId
});
}
} catch (error) {
logger.error('Error in processXeroEvent:', error);
throw error;
}
};
/**
* Trigger user webhooks
* @param {string} userId - User ID
* @param {string} tenantId - Tenant ID
* @param {string} eventType - Event type
* @param {Object} payload - Event payload
*/
const triggerUserWebhooks = async (userId, tenantId, eventType, payload) => {
try {
// Find matching webhooks
const webhooks = await Webhook.findAll({
where: {
userId,
tenantId,
event: eventType,
isActive: true
}
});
if (webhooks.length === 0) {
return;
}
logger.info(`Triggering ${webhooks.length} webhooks for event ${eventType}`);
// Trigger each webhook
for (const webhook of webhooks) {
try {
// Generate signature
const signature = generateWebhookSignature(payload, webhook.secret);
// Prepare headers
const headers = {
'Content-Type': 'application/json',
'X-Webhook-Signature': signature,
...webhook.headers
};
// Send webhook
const response = await axios.post(webhook.url, payload, { headers });
// Update webhook stats
await webhook.update({
lastTriggeredAt: new Date(),
successCount: webhook.successCount + 1
});
logger.info(`Webhook ${webhook.id} triggered successfully`);
} catch (error) {
// Update webhook stats
await webhook.update({
lastTriggeredAt: new Date(),
failureCount: webhook.failureCount + 1,
lastError: error.message
});
logger.error(`Error triggering webhook ${webhook.id}:`, error);
}
}
} catch (error) {
logger.error('Error in triggerUserWebhooks:', error);
throw error;
}
};
/**
* Generate webhook signature
* @param {Object} payload - Webhook payload
* @param {string} secret - Webhook secret
* @returns {string} Signature
*/
const generateWebhookSignature = (payload, secret) => {
const hmac = crypto.createHmac('sha256', secret);
hmac.update(JSON.stringify(payload));
return hmac.digest('hex');
};
/**
* Manually trigger webhook for testing
* @param {Object} req - Express request object
* @param {Object} res - Express response object
*/
const testWebhook = async (req, res) => {
try {
const { userId, tenantId } = req.user;
const { webhookId } = req.params;
const { payload } = req.body;
// Find webhook
const webhook = await Webhook.findOne({
where: {
id: webhookId,
userId,
tenantId
}
});
if (!webhook) {
return errorResponse(res, 'Webhook not found', 404);
}
// Generate test payload if not provided
const testPayload = payload || {
event: webhook.event,
timestamp: new Date().toISOString(),
tenantId,
test: true
};
// Generate signature
const signature = generateWebhookSignature(testPayload, webhook.secret);
// Prepare headers
const headers = {
'Content-Type': 'application/json',
'X-Webhook-Signature': signature,
...webhook.headers
};
// Send webhook
const response = await axios.post(webhook.url, testPayload, { headers });
// Update webhook stats
await webhook.update({
lastTriggeredAt: new Date(),
successCount: webhook.successCount + 1
});
logger.info(`Test webhook ${webhookId} triggered successfully`);
return successResponse(res, {
message: 'Test webhook triggered successfully',
status: response.status,
statusText: response.statusText
});
} catch (error) {
logger.error('Error in testWebhook:', error);
// Update webhook stats if webhook exists
if (req.params.webhookId) {
try {
const webhook = await Webhook.findByPk(req.params.webhookId);
if (webhook) {
await webhook.update({
lastTriggeredAt: new Date(),
failureCount: webhook.failureCount + 1,
lastError: error.message
});
}
} catch (updateError) {
logger.error('Error updating webhook stats:', updateError);
}
}
return errorResponse(res, error.message, 500);
}
};
module.exports = {
registerWebhook,
listWebhooks,
updateWebhook,
deleteWebhook,
regenerateWebhookSecret,
handleXeroWebhook,
testWebhook
};