fix(chat): safely resolve user_id for public.users FK and persist assistant message id
This commit is contained in:
@@ -180,19 +180,38 @@ Instrucciones:
|
||||
|
||||
// 5. Caso: Cliente específico activo -> Persistir pregunta del usuario en el historial
|
||||
const admin = createAdminClient(supabaseUrl, serviceKey);
|
||||
|
||||
// Validar si user.id existe en public.users para respetar constraint FK chat_messages_user_id_fkey
|
||||
let validDbUserId: string | null = null;
|
||||
try {
|
||||
const { data: pUser } = await admin
|
||||
.from('users')
|
||||
.select('id')
|
||||
.eq('id', user.id)
|
||||
.maybeSingle();
|
||||
if (pUser?.id) validDbUserId = pUser.id;
|
||||
} catch (err) {
|
||||
validDbUserId = null;
|
||||
}
|
||||
|
||||
let userMessageRowId: string | null = null;
|
||||
try {
|
||||
const { data: uRow } = await admin
|
||||
const { data: uRow, error: uErr } = await admin
|
||||
.from('chat_messages')
|
||||
.insert({
|
||||
tenant_id: tenantId,
|
||||
user_id: user.id,
|
||||
user_id: validDbUserId,
|
||||
role: 'user',
|
||||
content: userMessage,
|
||||
tool_calls: {
|
||||
auth_user_id: user.id,
|
||||
user_email: user.email,
|
||||
},
|
||||
})
|
||||
.select('id')
|
||||
.single();
|
||||
if (uRow?.id) userMessageRowId = uRow.id;
|
||||
if (uErr) console.error('Error insert user message in chat_messages:', uErr);
|
||||
} catch (dbErr) {
|
||||
console.error('Error guardando mensaje del usuario en chat_messages:', dbErr);
|
||||
}
|
||||
@@ -315,21 +334,23 @@ REGLAS Y PAUTAS INMUTABLES:
|
||||
|
||||
let assistantMessageRowId: string | null = null;
|
||||
try {
|
||||
const { data: aRow } = await admin
|
||||
const { data: aRow, error: aErr } = await admin
|
||||
.from('chat_messages')
|
||||
.insert({
|
||||
tenant_id: tenantId,
|
||||
user_id: user.id,
|
||||
user_id: validDbUserId,
|
||||
role: 'assistant',
|
||||
content: replyText,
|
||||
tool_calls: {
|
||||
model: 'claude-sonnet-4-5-20250929',
|
||||
user_message_id: userMessageRowId,
|
||||
auth_user_id: user.id,
|
||||
},
|
||||
})
|
||||
.select('id')
|
||||
.single();
|
||||
if (aRow?.id) assistantMessageRowId = aRow.id;
|
||||
if (aErr) console.error('Error insert assistant message in chat_messages:', aErr);
|
||||
} catch (dbErr) {
|
||||
console.error('Error guardando respuesta del asistente en chat_messages:', dbErr);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user