Skip to content

Commit 1f071ea

Browse files
Add debug logging to trace chat history auto-save and userType flow
1 parent d789b6c commit 1f071ea

3 files changed

Lines changed: 47 additions & 6 deletions

File tree

backend/routes/chat.js

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,12 @@ router.post('/message', optionalAuth, async (req, res) => {
100100
const userId = authUser?.user_id || null;
101101
const effectiveUserType = authUser?.user_type || user_type || null;
102102

103+
// DEBUG: Log userType flow
104+
console.log('[CHAT DEBUG] /message - authUser.user_type:', authUser?.user_type);
105+
console.log('[CHAT DEBUG] /message - req.body.user_type:', user_type);
106+
console.log('[CHAT DEBUG] /message - effectiveUserType:', effectiveUserType);
107+
console.log('[CHAT DEBUG] /message - userId:', userId);
108+
103109
const convId = conversation_id || `conv_${Date.now()}_${Math.floor(Math.random() * 1000)}`;
104110

105111
if (userId) {
@@ -251,9 +257,13 @@ router.post('/message', optionalAuth, async (req, res) => {
251257

252258
router.get('/history/:userId', requireAuth, async (req, res) => {
253259
const { userId } = req.params;
260+
console.log('[CHAT DEBUG] /history/:userId - userId:', userId, 'req.user.user_id:', req.user.user_id);
261+
254262
if (req.user.user_type !== 'admin' && String(req.user.user_id) !== String(userId)) {
263+
console.log('[CHAT DEBUG] /history - Forbidden: user_id mismatch');
255264
return res.status(403).json({ success: false, error: 'Forbidden' });
256265
}
266+
257267
const query = `
258268
SELECT m.conversation_id,
259269
COALESCE(c.title, m.conversation_id) as title,
@@ -266,8 +276,13 @@ router.get('/history/:userId', requireAuth, async (req, res) => {
266276
GROUP BY m.conversation_id
267277
ORDER BY updated_at DESC
268278
`;
279+
269280
global.db.all(query, [userId], (err, rows) => {
270-
if (err) return res.status(500).json({ success: false, error: err.message });
281+
if (err) {
282+
console.log('[CHAT DEBUG] /history ERROR:', err);
283+
return res.status(500).json({ success: false, error: err.message });
284+
}
285+
console.log('[CHAT DEBUG] /history SUCCESS - rows:', rows?.length || 0, 'data:', rows);
271286
res.json({ success: true, data: rows });
272287
});
273288
});
@@ -415,7 +430,10 @@ router.delete('/conversation/:conversationId', requireAuth, (req, res) => {
415430
});
416431

417432
async function saveMessage(convId, userId, sender, message, nodeId) {
433+
console.log('[CHAT DEBUG] saveMessage called - convId:', convId, 'userId:', userId, 'sender:', sender, 'nodeId:', nodeId);
434+
418435
if (!global.db) {
436+
console.log('[CHAT DEBUG] saveMessage - No database, using memory');
419437
MEMORY_MESSAGES.push({
420438
conversation_id: convId,
421439
user_id: userId,
@@ -431,8 +449,13 @@ async function saveMessage(convId, userId, sender, message, nodeId) {
431449
const query = `INSERT INTO chat_messages (conversation_id, user_id, sender, message, node_id)
432450
VALUES (?, ?, ?, ?, ?)`;
433451
global.db.run(query, [convId, userId, sender, message, nodeId], function (err) {
434-
if (err) reject(err);
435-
else resolve(this.lastID);
452+
if (err) {
453+
console.log('[CHAT DEBUG] saveMessage ERROR:', err);
454+
reject(err);
455+
} else {
456+
console.log('[CHAT DEBUG] saveMessage SUCCESS - messageId:', this.lastID);
457+
resolve(this.lastID);
458+
}
436459
});
437460
});
438461
}

backend/services/llmScorer.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,10 @@ async function generateCareerQuestion({ userType, profile, memoryAnswers, intent
3434
? memoryAnswers.slice(-8).map((a) => ({ q: a?.question || a?.q, a: a?.answer || a?.a })).filter((x) => x.q || x.a)
3535
: [];
3636

37+
console.log('[LLM DEBUG] generateCareerQuestion - userType:', safeUserType);
38+
console.log('[LLM DEBUG] generateCareerQuestion - profile:', profileText);
39+
console.log('[LLM DEBUG] generateCareerQuestion - memory:', JSON.stringify(memoryText));
40+
3741
const systemPrompt = `Bạn là chuyên gia tư vấn hướng nghiệp.
3842
Nhiệm vụ: tạo 1 câu hỏi TIẾP THEO phù hợp với nhóm người dùng và bối cảnh hiện tại.
3943
@@ -71,6 +75,11 @@ profile: ${profileText}
7175
memory: ${JSON.stringify(memoryText)}
7276
intent: ${JSON.stringify(intent || {})}
7377
78+
TRỌNG: Hãy kiểm tra kỹ userType và chỉ tạo câu hỏi phù hợp với nhóm đó.
79+
Nếu userType là "professional", tuyệt đối KHÔNG hỏi về môn học hay hoạt động học đường.
80+
Nếu userType là "high_school", tuyệt đối KHÔNG hỏi về kinh nghiệm làm việc hay công ty.
81+
Nếu userType là "university", tuyệt đối KHÔNG hỏi về kinh nghiệm làm việc dài hạn hay quản lý nhân sự.
82+
7483
Hãy tạo câu hỏi tiếp theo bằng tiếng Việt, xưng hô lịch sự, ngắn gọn.`;
7584

7685
const payload = {

frontend/src/pages/Chat.jsx

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -126,8 +126,13 @@ export default function Chat() {
126126
}, [userId, token]);
127127

128128
async function refreshHistory() {
129-
if (!IS_OFFLINE && (!userId || !token)) return;
129+
console.log('[FRONTEND DEBUG] refreshHistory called - userId:', userId, 'token:', !!token);
130+
if (!IS_OFFLINE && (!userId || !token)) {
131+
console.log('[FRONTEND DEBUG] refreshHistory skipped - no userId or token');
132+
return;
133+
}
130134
const jsonHistory = await api.getHistory(userId, token);
135+
console.log('[FRONTEND DEBUG] refreshHistory response:', jsonHistory);
131136
setHistory(jsonHistory?.data || []);
132137
}
133138

@@ -176,8 +181,10 @@ export default function Chat() {
176181
request_more: options.requestMore || false,
177182
user_id: userId || null
178183
};
184+
console.log('[FRONTEND DEBUG] sendMessage - userType:', userType, 'userId:', userId, 'conversationId:', conversationId);
179185
const json = await api.sendMessage(body, token);
180186
const data = json?.data || {};
187+
console.log('[FRONTEND DEBUG] sendMessage - response data:', data);
181188

182189
const botMessage = { id: `${Date.now()}-b`, sender: 'bot', text: data.bot_reply };
183190
const applyBotMessage = () => {
@@ -188,9 +195,11 @@ export default function Chat() {
188195
if (data.conversation_id) {
189196
const prevId = conversationId;
190197
setConversationId(data.conversation_id);
191-
// Refresh history when conversation changes OR when recommendations are saved
192-
if (token && userId && (data.conversation_id !== prevId || data.completed)) {
198+
// Always refresh history after every message for logged-in users
199+
if (token && userId) {
200+
console.log('[FRONTEND DEBUG] About to refreshHistory after message');
193201
await refreshHistory();
202+
console.log('[FRONTEND DEBUG] refreshHistory completed');
194203
}
195204
}
196205
setCurrentNode(data.next_node || null);

0 commit comments

Comments
 (0)