modificando el patron del sistema, orientado mas al usuario

This commit is contained in:
Lucas Tettamanti
2026-01-25 22:32:58 -03:00
parent 93e331535f
commit bd63d92c50
15 changed files with 707 additions and 83 deletions

View File

@@ -63,7 +63,7 @@ export const makeRespondToTakeover = (tenantIdOrFn) => async (req, res) => {
try {
const tenantId = typeof tenantIdOrFn === "function" ? tenantIdOrFn() : tenantIdOrFn;
const id = parseInt(req.params.id, 10);
const { response, responded_by, add_alias } = req.body || {};
const { response, responded_by, add_alias, cart_items } = req.body || {};
if (!response) {
return res.status(400).json({ ok: false, error: "response_required" });
@@ -75,6 +75,7 @@ export const makeRespondToTakeover = (tenantIdOrFn) => async (req, res) => {
response,
respondedBy: responded_by || null,
addAlias: add_alias || null,
cartItems: cart_items || null,
});
res.json(result);
} catch (err) {

View File

@@ -10,7 +10,7 @@ import {
getTakeoverStats,
} from "../db/takeoverRepo.js";
import { insertAlias, upsertAliasMapping } from "../db/repo.js";
import { getRecentMessagesForLLM } from "../../2-identity/db/repo.js";
import { getRecentMessagesForLLM, getConversationState, upsertConversationState } from "../../2-identity/db/repo.js";
/**
* Lista takeovers pendientes de respuesta
@@ -99,19 +99,72 @@ export async function handleRespondToTakeover({
response,
respondedBy = null,
addAlias = null, // { query: string, woo_product_id: number }
cartItems = null, // [{ woo_id, name, qty, unit }] - items a agregar al carrito
}) {
// Responder al takeover
// Responder al takeover con los items del carrito
const result = await respondToTakeover({
tenantId,
id,
humanResponse: response,
respondedBy,
cartItems, // Pasar los items para que se guarden
});
if (!result) {
throw new Error("Takeover not found or already responded");
}
// Si hay items para agregar al carrito, actualizar el estado de la conversación
if (cartItems && cartItems.length > 0 && result.chat_id) {
try {
// Obtener estado actual
const currentState = await getConversationState(tenantId, result.chat_id);
const context = currentState?.context || {};
const order = context.order || { cart: [], pending: [] };
// Agregar los items al carrito
const newCartItems = cartItems.map(item => ({
woo_id: item.woo_id,
qty: parseFloat(item.qty) || 1,
unit: item.unit || "kg",
name: item.name || null,
price: item.price || null,
}));
order.cart = [...(order.cart || []), ...newCartItems];
// Actualizar estado: cambiar a CART para que el bot retome
await upsertConversationState({
tenant_id: tenantId,
wa_chat_id: result.chat_id,
state: "CART", // Retomar flujo normal
last_intent: "human_response",
context: { ...context, order },
});
console.log(`[takeovers] Added ${newCartItems.length} items to cart for ${result.chat_id}`);
} catch (e) {
console.error("[takeovers] Error updating cart:", e);
// No fallar si hay error al actualizar carrito
}
} else if (result.chat_id) {
// Si no hay items pero respondió, igual cambiar estado a CART preservando el context
try {
const currentState = await getConversationState(tenantId, result.chat_id);
const context = currentState?.context || {};
await upsertConversationState({
tenant_id: tenantId,
wa_chat_id: result.chat_id,
state: "CART",
last_intent: "human_response",
context,
});
} catch (e) {
console.error("[takeovers] Error updating state:", e);
}
}
// Si se pidió agregar alias, hacerlo
if (addAlias && addAlias.query && addAlias.woo_product_id) {
try {
@@ -138,6 +191,7 @@ export async function handleRespondToTakeover({
return {
ok: true,
takeover: result,
cart_items_added: cartItems?.length || 0,
message: "Response sent successfully",
};
}