-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcustomer-api.js
More file actions
495 lines (428 loc) · 13.8 KB
/
Copy pathcustomer-api.js
File metadata and controls
495 lines (428 loc) · 13.8 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
491
492
493
494
495
/**
* Customer API endpoints for Node-RED integration
* Provides HTTP endpoints for managing customers and conversations
*/
module.exports = function(RED) {
const express = require('express');
const bodyParser = require('body-parser');
const customerDb = require('./customer-db');
// Create a router for our API endpoints
const apiRouter = express.Router();
// Middleware
apiRouter.use(bodyParser.json());
// Authentication middleware (simple API key check)
const authenticate = (req, res, next) => {
const apiKey = req.headers['x-api-key'];
// In production, use a proper API key validation system
// This is just a simple example
if (!apiKey || apiKey !== 'your-secret-api-key') {
return res.status(401).json({
status: 'error',
message: 'Authentication required'
});
}
next();
};
// Enable CORS for all routes
apiRouter.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept, X-API-Key, Authorization');
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
if (req.method === 'OPTIONS') {
return res.sendStatus(200);
}
next();
});
// Customer endpoints
// Get all customers
apiRouter.get('/customers', authenticate, (req, res) => {
try {
const customers = customerDb.getAllCustomers();
res.json({ status: 'success', customers });
} catch (error) {
res.status(500).json({
status: 'error',
message: error.message
});
}
});
// Find customer by ID or email
apiRouter.get('/customers/find', authenticate, (req, res) => {
try {
const identifier = req.query.identifier;
if (!identifier) {
return res.status(400).json({
status: 'error',
message: 'Identifier is required'
});
}
const customer = customerDb.findCustomer(identifier);
if (!customer) {
return res.status(404).json({
status: 'error',
message: 'Customer not found'
});
}
res.json({ status: 'success', customer });
} catch (error) {
res.status(500).json({
status: 'error',
message: error.message
});
}
});
// Create new customer
apiRouter.post('/customers', authenticate, (req, res) => {
try {
const customerData = req.body;
// Check for minimum required data
if (!customerData.email) {
return res.status(400).json({
status: 'error',
message: 'Email is required'
});
}
// Check if customer already exists with this email
const existingCustomer = customerDb.findCustomer(customerData.email);
if (existingCustomer) {
return res.status(409).json({
status: 'error',
message: 'Customer with this email already exists',
customer: existingCustomer
});
}
const customer = customerDb.createCustomer(customerData);
res.status(201).json({ status: 'success', customer });
} catch (error) {
res.status(500).json({
status: 'error',
message: error.message
});
}
});
// Update customer
apiRouter.put('/customers/:id', authenticate, (req, res) => {
try {
const customerId = req.params.id;
const customerData = req.body;
const customer = customerDb.updateCustomer(customerId, customerData);
res.json({ status: 'success', customer });
} catch (error) {
res.status(500).json({
status: 'error',
message: error.message
});
}
});
// Get customer conversations
apiRouter.get('/customers/:id/conversations', authenticate, (req, res) => {
try {
const customerId = req.params.id;
const conversations = customerDb.getCustomerConversations(customerId);
res.json({ status: 'success', conversations });
} catch (error) {
res.status(500).json({
status: 'error',
message: error.message
});
}
});
// Conversation endpoints
// Get conversation by ID
apiRouter.get('/conversations/:id', authenticate, (req, res) => {
try {
const conversationId = req.params.id;
const conversation = customerDb.getConversation(conversationId);
if (!conversation) {
return res.status(404).json({
status: 'error',
message: 'Conversation not found'
});
}
res.json({ status: 'success', conversation });
} catch (error) {
res.status(500).json({
status: 'error',
message: error.message
});
}
});
// Create new conversation
apiRouter.post('/conversations', authenticate, (req, res) => {
try {
const { customerId, initialMessage } = req.body;
if (!customerId) {
return res.status(400).json({
status: 'error',
message: 'Customer ID is required'
});
}
const conversation = customerDb.createConversation(customerId, initialMessage);
res.status(201).json({ status: 'success', conversation });
} catch (error) {
res.status(500).json({
status: 'error',
message: error.message
});
}
});
// Find or create active conversation
apiRouter.post('/conversations/active', authenticate, (req, res) => {
try {
const { customerId, initialMessage } = req.body;
if (!customerId) {
return res.status(400).json({
status: 'error',
message: 'Customer ID is required'
});
}
const conversation = customerDb.findOrCreateConversation(customerId, initialMessage);
res.json({ status: 'success', conversation });
} catch (error) {
res.status(500).json({
status: 'error',
message: error.message
});
}
});
// Add message to conversation
apiRouter.post('/conversations/:id/messages', authenticate, (req, res) => {
try {
const conversationId = req.params.id;
const { content, sender } = req.body;
if (!content) {
return res.status(400).json({
status: 'error',
message: 'Message content is required'
});
}
const message = customerDb.addMessage(conversationId, content, sender);
res.status(201).json({ status: 'success', message });
} catch (error) {
res.status(500).json({
status: 'error',
message: error.message
});
}
});
// Update conversation status
apiRouter.put('/conversations/:id/status', authenticate, (req, res) => {
try {
const conversationId = req.params.id;
const { status } = req.body;
if (!status) {
return res.status(400).json({
status: 'error',
message: 'Status is required'
});
}
const conversation = customerDb.updateConversationStatus(conversationId, status);
res.json({ status: 'success', conversation });
} catch (error) {
res.status(500).json({
status: 'error',
message: error.message
});
}
});
// Update conversation context (for AI)
apiRouter.put('/conversations/:id/context', authenticate, (req, res) => {
try {
const conversationId = req.params.id;
const contextData = req.body;
const conversation = customerDb.updateConversationContext(conversationId, contextData);
res.json({ status: 'success', conversation });
} catch (error) {
res.status(500).json({
status: 'error',
message: error.message
});
}
});
// CRM integration endpoints
// Link customer to CRM
apiRouter.post('/crm/link', authenticate, (req, res) => {
try {
const { customerId, crmId } = req.body;
if (!customerId || !crmId) {
return res.status(400).json({
status: 'error',
message: 'Customer ID and CRM ID are required'
});
}
const customer = customerDb.linkCustomerToCRM(customerId, crmId);
res.json({ status: 'success', customer });
} catch (error) {
res.status(500).json({
status: 'error',
message: error.message
});
}
});
// Export customer data for CRM
apiRouter.get('/crm/export/:customerId', authenticate, (req, res) => {
try {
const customerId = req.params.customerId;
const data = customerDb.exportCustomerData(customerId);
res.json({ status: 'success', data });
} catch (error) {
res.status(500).json({
status: 'error',
message: error.message
});
}
});
// Special endpoint for Node-RED to process a message with context
apiRouter.post('/process', authenticate, async (req, res) => {
try {
const {
message,
customerId,
customerEmail,
customerName,
conversationId
} = req.body;
if (!message) {
return res.status(400).json({
status: 'error',
message: 'Message content is required'
});
}
// Identify or create customer
let customer;
if (customerId) {
customer = customerDb.findCustomer(customerId);
} else if (customerEmail) {
customer = customerDb.findCustomer(customerEmail);
if (!customer) {
// Create new customer
customer = customerDb.createCustomer({
email: customerEmail,
name: customerName || customerEmail.split('@')[0]
});
}
} else {
// Create anonymous customer
customer = customerDb.createCustomer({
name: 'Anonymous User'
});
}
// Find or create conversation
let conversation;
if (conversationId) {
conversation = customerDb.getConversation(conversationId);
if (!conversation) {
conversation = customerDb.createConversation(customer.id, message);
} else {
customerDb.addMessage(conversation.id, message, 'customer');
}
} else {
conversation = customerDb.findOrCreateConversation(customer.id, message);
}
// Extract conversation history for context
const messages = conversation.messages;
const history = messages.map(msg => ({
role: msg.sender === 'customer' ? 'user' : 'assistant',
content: msg.content
}));
// Prepare response
res.json({
status: 'success',
customer,
conversation,
history,
currentMessage: message
});
} catch (error) {
res.status(500).json({
status: 'error',
message: error.message
});
}
});
// Register our router with Node-RED
RED.httpNode.use('/customer-api', apiRouter);
// Create a Node-RED node type for customer management
function CustomerProfileNode(config) {
RED.nodes.createNode(this, config);
const node = this;
node.on('input', function(msg) {
try {
const email = msg.payload.email || msg.customer?.email;
// Skip if no identifying information
if (!email) {
node.send(msg);
return;
}
// Try to find customer
let customer = customerDb.findCustomer(email);
// Create customer if not found
if (!customer) {
customer = customerDb.createCustomer({
email: email,
name: msg.payload.name || msg.customer?.name || email.split('@')[0]
});
}
// Add or update customer in message
msg.customer = customer;
// Find or create active conversation
const message = msg.payload.message || msg.payload;
const conversation = customerDb.findOrCreateConversation(
customer.id,
typeof message === 'string' ? message : null
);
// Add conversation to message
msg.conversation = conversation;
// Add conversation history for AI context
msg.history = conversation.messages.map(msg => ({
role: msg.sender === 'customer' ? 'user' : 'assistant',
content: msg.content
}));
node.send(msg);
} catch (error) {
node.error(`Customer profile error: ${error.message}`, msg);
msg.error = error.message;
node.send(msg);
}
});
}
RED.nodes.registerType("customer-profile", CustomerProfileNode);
// Create a Node-RED node type for recording responses
function RecordResponseNode(config) {
RED.nodes.createNode(this, config);
const node = this;
node.on('input', function(msg) {
try {
// Skip if no conversation
if (!msg.conversation || !msg.conversation.id) {
node.send(msg);
return;
}
// Get the response content
let responseContent;
if (msg.payload.response) {
responseContent = msg.payload.response;
} else if (typeof msg.payload === 'string') {
responseContent = msg.payload;
} else {
responseContent = JSON.stringify(msg.payload);
}
// Record the agent's response
customerDb.addMessage(
msg.conversation.id,
responseContent,
'agent'
);
// Update conversation in the message
msg.conversation = customerDb.getConversation(msg.conversation.id);
node.send(msg);
} catch (error) {
node.error(`Record response error: ${error.message}`, msg);
msg.error = error.message;
node.send(msg);
}
});
}
RED.nodes.registerType("record-response", RecordResponseNode);
};