-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
295 lines (248 loc) · 9.21 KB
/
server.js
File metadata and controls
295 lines (248 loc) · 9.21 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
// Load environment variables
if (process.env.NODE_ENV !== 'production') {
require('dotenv').config();
}
const express = require('express');
const cors = require('cors');
const path = require('path');
const { GoogleGenAI } = require('@google/genai');
const { v4: uuidv4 } = require('uuid');
const dental = require('./dental-training');
const db = require('./database');
const app = express();
// Initialize Gemini AI
const apiKey = process.env.GEMINI_API_KEY;
if (!apiKey) {
console.error('❌ GEMINI_API_KEY not found in environment variables!');
}
const ai = new GoogleGenAI({ apiKey });
// Connect to MongoDB
db.connectDB();
// Middleware
app.use(cors());
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true }));
// Session middleware to generate/retrieve session ID
app.use((req, res, next) => {
if (!req.headers['x-session-id']) {
req.sessionId = uuidv4();
res.setHeader('x-session-id', req.sessionId);
} else {
req.sessionId = req.headers['x-session-id'];
}
next();
});
// Health check endpoint
app.get('/api/health', (req, res) => {
res.status(200).json({
status: 'healthy',
timestamp: new Date().toISOString(),
service: 'Saia Dental Assistant',
database: db.Conversation ? 'connected' : 'disconnected'
});
});
// Main chat endpoint with database integration
app.post('/api/chat', async (req, res) => {
const startTime = Date.now();
try {
const { message } = req.body;
const sessionId = req.sessionId;
// Validate input
if (!message || typeof message !== 'string') {
return res.status(400).json({
error: 'Invalid message format. Message must be a non-empty string.'
});
}
if (message.length > 2000) {
return res.status(400).json({
error: 'Message too long. Maximum 2000 characters allowed.'
});
}
// Get conversation history for context
const history = await db.getConversationHistory(sessionId, 5);
// Enhance with dental training
const enhanced = dental.enhanceWithDentalTraining(message);
// Use quick response if available
if (enhanced.quickResponse) {
// Save to database
await db.saveConversation(
sessionId,
message,
enhanced.quickResponse,
{
ip: req.ip,
userAgent: req.headers['user-agent']
},
enhanced.isDental
);
return res.json({
response: enhanced.quickResponse,
sessionId
});
}
// Build context-aware prompt with conversation history
let contextPrompt = enhanced.isDental ? enhanced.enhancedPrompt : message;
if (history.length > 0) {
const historyContext = history.map(msg =>
`${msg.role === 'user' ? 'User' : 'Assistant'}: ${msg.content}`
).join('\n');
contextPrompt = `Previous conversation:\n${historyContext}\n\nCurrent message: ${contextPrompt}`;
}
// Call Gemini API
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 30000);
try {
const response = await ai.models.generateContent({
model: "gemini-2.5-flash",
contents: contextPrompt
});
clearTimeout(timeout);
const responseText = response.text;
const responseTime = Date.now() - startTime;
// Save conversation to database
await db.saveConversation(
sessionId,
message,
responseText,
{
ip: req.ip,
userAgent: req.headers['user-agent']
},
enhanced.isDental
);
// Check for appointment request and save
if (enhanced.appointmentInfo?.phone || enhanced.appointmentInfo?.email) {
await db.saveAppointment({
sessionId,
patientInfo: {
phone: enhanced.appointmentInfo.phone,
email: enhanced.appointmentInfo.email
},
appointmentDetails: {
reason: message,
urgency: enhanced.appointmentInfo.isUrgent ? 'urgent' : 'routine'
},
notes: `Auto-detected from conversation`
});
console.log('[APPOINTMENT] Saved to database:', {
sessionId,
phone: enhanced.appointmentInfo.phone,
email: enhanced.appointmentInfo.email
});
}
// Update analytics asynchronously
db.updateAnalytics().catch(err =>
console.error('Analytics update failed:', err)
);
res.json({
response: responseText,
isDental: enhanced.isDental,
sessionId,
responseTime
});
} catch (apiError) {
clearTimeout(timeout);
throw apiError;
}
} catch (error) {
console.error('[ERROR]', {
timestamp: new Date().toISOString(),
error: error.message,
stack: error.stack
});
if (error.name === 'AbortError') {
return res.status(504).json({
error: 'Request timeout. Please try again.'
});
}
if (error.message?.includes('API key')) {
return res.status(500).json({
error: 'Service configuration error. Please contact support.'
});
}
res.status(500).json({
error: 'An error occurred while processing your request. Please try again.'
});
}
});
// Get conversation history endpoint
app.get('/api/conversation/:sessionId', async (req, res) => {
try {
const { sessionId } = req.params;
const history = await db.getConversationHistory(sessionId, 50);
res.json({ history });
} catch (error) {
console.error('Error fetching conversation:', error);
res.status(500).json({ error: 'Failed to fetch conversation history' });
}
});
// Submit feedback endpoint
app.post('/api/feedback', async (req, res) => {
try {
const { sessionId, rating, feedback, category } = req.body;
const savedFeedback = await db.saveFeedback({
sessionId: sessionId || req.sessionId,
rating,
feedback,
category
});
res.json({
success: true,
feedbackId: savedFeedback._id
});
} catch (error) {
console.error('Error saving feedback:', error);
res.status(500).json({ error: 'Failed to save feedback' });
}
});
// Get analytics endpoint (admin only - add authentication in production)
app.get('/api/analytics', async (req, res) => {
try {
const days = parseInt(req.query.days) || 7;
const startDate = new Date();
startDate.setDate(startDate.getDate() - days);
const analytics = await db.Analytics.find({
date: { $gte: startDate }
}).sort({ date: -1 });
const totalAppointments = await db.Appointment.countDocuments({
createdAt: { $gte: startDate }
});
const appointmentsByStatus = await db.Appointment.aggregate([
{ $match: { createdAt: { $gte: startDate } } },
{ $group: { _id: '$status', count: { $sum: 1 } } }
]);
res.json({
analytics,
totalAppointments,
appointmentsByStatus
});
} catch (error) {
console.error('Error fetching analytics:', error);
res.status(500).json({ error: 'Failed to fetch analytics' });
}
});
// Import and register appointments routes
const appointmentsRouter = require('./routes/appointments');app.use('/api/appointments', appointmentsRouter);
// Serve static files
app.use(express.static(path.join(__dirname, 'public')));
// Catch-all route for SPA
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
// Start server
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`
╔═══════════════════════════════════════╗
║ 🦷 Saia Dental Assistant Server ║
╠═══════════════════════════════════════╣
║ Port: ${port.toString().padEnd(28)}║
║ Environment: ${(process.env.NODE_ENV || 'development').padEnd(20)}║
║ AI Model: gemini-2.5-flash ║
║ Database: MongoDB ║
║ Status: ✅ Running ║
╚═══════════════════════════════════════╝
🌐 Server running on port ${port}
`);
});
module.exports = app;