corregidos bugs de: ret, vs delivery, efectivo vs link, charsets, price query
This commit is contained in:
@@ -19,6 +19,7 @@ export async function getSettings({ tenantId }) {
|
||||
pickup_enabled, pickup_days,
|
||||
pickup_hours_start::text as pickup_hours_start,
|
||||
pickup_hours_end::text as pickup_hours_end,
|
||||
schedule,
|
||||
created_at, updated_at
|
||||
FROM tenant_settings
|
||||
WHERE tenant_id = $1
|
||||
@@ -46,15 +47,17 @@ export async function upsertSettings({ tenantId, settings }) {
|
||||
pickup_days,
|
||||
pickup_hours_start,
|
||||
pickup_hours_end,
|
||||
schedule,
|
||||
} = settings;
|
||||
|
||||
const sql = `
|
||||
INSERT INTO tenant_settings (
|
||||
tenant_id, store_name, bot_name, store_address, store_phone,
|
||||
delivery_enabled, delivery_days, delivery_hours_start, delivery_hours_end, delivery_min_order,
|
||||
pickup_enabled, pickup_days, pickup_hours_start, pickup_hours_end
|
||||
pickup_enabled, pickup_days, pickup_hours_start, pickup_hours_end,
|
||||
schedule
|
||||
)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15)
|
||||
ON CONFLICT (tenant_id) DO UPDATE SET
|
||||
store_name = COALESCE(EXCLUDED.store_name, tenant_settings.store_name),
|
||||
bot_name = COALESCE(EXCLUDED.bot_name, tenant_settings.bot_name),
|
||||
@@ -69,6 +72,7 @@ export async function upsertSettings({ tenantId, settings }) {
|
||||
pickup_days = COALESCE(EXCLUDED.pickup_days, tenant_settings.pickup_days),
|
||||
pickup_hours_start = COALESCE(EXCLUDED.pickup_hours_start, tenant_settings.pickup_hours_start),
|
||||
pickup_hours_end = COALESCE(EXCLUDED.pickup_hours_end, tenant_settings.pickup_hours_end),
|
||||
schedule = COALESCE(EXCLUDED.schedule, tenant_settings.schedule),
|
||||
updated_at = NOW()
|
||||
RETURNING
|
||||
id, tenant_id,
|
||||
@@ -80,6 +84,7 @@ export async function upsertSettings({ tenantId, settings }) {
|
||||
pickup_enabled, pickup_days,
|
||||
pickup_hours_start::text as pickup_hours_start,
|
||||
pickup_hours_end::text as pickup_hours_end,
|
||||
schedule,
|
||||
created_at, updated_at
|
||||
`;
|
||||
|
||||
@@ -98,6 +103,7 @@ export async function upsertSettings({ tenantId, settings }) {
|
||||
pickup_days || null,
|
||||
pickup_hours_start || null,
|
||||
pickup_hours_end || null,
|
||||
schedule ? JSON.stringify(schedule) : null,
|
||||
];
|
||||
|
||||
const { rows } = await pool.query(sql, params);
|
||||
@@ -105,6 +111,64 @@ export async function upsertSettings({ tenantId, settings }) {
|
||||
return rows[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* Formatea horarios desde schedule JSONB para mostrar de forma natural
|
||||
* Agrupa días con mismos horarios: "Lun a Vie de 9 a 14hs, Sáb de 9 a 13hs"
|
||||
*/
|
||||
function formatScheduleHours(scheduleType, enabled) {
|
||||
if (!enabled || !scheduleType || typeof scheduleType !== "object") {
|
||||
return enabled === false ? "No disponible" : "";
|
||||
}
|
||||
|
||||
const dayOrder = ["lun", "mar", "mie", "jue", "vie", "sab", "dom"];
|
||||
const dayNames = {
|
||||
lun: "Lunes", mar: "Martes", mie: "Miércoles",
|
||||
jue: "Jueves", vie: "Viernes", sab: "Sábado", dom: "Domingo"
|
||||
};
|
||||
|
||||
// Agrupar días por horario
|
||||
const groups = {};
|
||||
for (const day of dayOrder) {
|
||||
const slot = scheduleType[day];
|
||||
if (!slot || !slot.start || !slot.end) continue;
|
||||
|
||||
const key = `${slot.start}-${slot.end}`;
|
||||
if (!groups[key]) {
|
||||
groups[key] = { start: slot.start, end: slot.end, days: [] };
|
||||
}
|
||||
groups[key].days.push(day);
|
||||
}
|
||||
|
||||
if (Object.keys(groups).length === 0) return "";
|
||||
|
||||
// Formatear cada grupo
|
||||
const parts = Object.values(groups).map(g => {
|
||||
const days = g.days;
|
||||
let dayStr;
|
||||
|
||||
// Detectar rangos consecutivos
|
||||
if (days.length >= 3) {
|
||||
const indices = days.map(d => dayOrder.indexOf(d));
|
||||
const isConsecutive = indices.every((v, i, arr) => i === 0 || v === arr[i-1] + 1);
|
||||
if (isConsecutive) {
|
||||
dayStr = `${dayNames[days[0]]} a ${dayNames[days[days.length-1]]}`;
|
||||
} else {
|
||||
dayStr = days.map(d => dayNames[d]).join(", ");
|
||||
}
|
||||
} else if (days.length === 2) {
|
||||
dayStr = `${dayNames[days[0]]} y ${dayNames[days[1]]}`;
|
||||
} else {
|
||||
dayStr = dayNames[days[0]];
|
||||
}
|
||||
|
||||
const startH = g.start.slice(0, 5);
|
||||
const endH = g.end.slice(0, 5);
|
||||
return `${dayStr} de ${startH} a ${endH}`;
|
||||
});
|
||||
|
||||
return parts.join(", ");
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtiene la configuración formateada para usar en prompts (storeConfig)
|
||||
*/
|
||||
@@ -121,39 +185,43 @@ export async function getStoreConfig({ tenantId }) {
|
||||
phone: "",
|
||||
deliveryHours: "",
|
||||
pickupHours: "",
|
||||
schedule: null,
|
||||
};
|
||||
}
|
||||
|
||||
// Formatear horarios para mostrar
|
||||
const formatHours = (enabled, days, start, end) => {
|
||||
if (!enabled) return "No disponible";
|
||||
if (!days || !start || !end) return "";
|
||||
|
||||
const daysFormatted = days.split(",").map(d => d.trim()).join(", ");
|
||||
const startFormatted = start?.slice(0, 5) || "";
|
||||
const endFormatted = end?.slice(0, 5) || "";
|
||||
|
||||
return `${daysFormatted} de ${startFormatted} a ${endFormatted}`;
|
||||
};
|
||||
const schedule = settings.schedule || {};
|
||||
|
||||
const deliveryHours = formatHours(
|
||||
settings.delivery_enabled,
|
||||
settings.delivery_days,
|
||||
settings.delivery_hours_start,
|
||||
settings.delivery_hours_end
|
||||
);
|
||||
// Usar nuevo formato schedule si existe, sino legacy
|
||||
let deliveryHours, pickupHours;
|
||||
|
||||
if (schedule.delivery && Object.keys(schedule.delivery).length > 0) {
|
||||
deliveryHours = formatScheduleHours(schedule.delivery, settings.delivery_enabled);
|
||||
} else {
|
||||
// Legacy format
|
||||
deliveryHours = formatLegacyHours(
|
||||
settings.delivery_enabled,
|
||||
settings.delivery_days,
|
||||
settings.delivery_hours_start,
|
||||
settings.delivery_hours_end
|
||||
);
|
||||
}
|
||||
|
||||
const pickupHours = formatHours(
|
||||
settings.pickup_enabled,
|
||||
settings.pickup_days,
|
||||
settings.pickup_hours_start,
|
||||
settings.pickup_hours_end
|
||||
);
|
||||
if (schedule.pickup && Object.keys(schedule.pickup).length > 0) {
|
||||
pickupHours = formatScheduleHours(schedule.pickup, settings.pickup_enabled);
|
||||
} else {
|
||||
// Legacy format
|
||||
pickupHours = formatLegacyHours(
|
||||
settings.pickup_enabled,
|
||||
settings.pickup_days,
|
||||
settings.pickup_hours_start,
|
||||
settings.pickup_hours_end
|
||||
);
|
||||
}
|
||||
|
||||
// Combinar horarios para store_hours
|
||||
// Combinar horarios para store_hours (usa pickup como horario de tienda)
|
||||
let storeHours = "";
|
||||
if (settings.pickup_enabled && settings.pickup_days) {
|
||||
storeHours = `${settings.pickup_days.split(",").join(", ")} ${settings.pickup_hours_start?.slice(0,5) || ""}-${settings.pickup_hours_end?.slice(0,5) || ""}`;
|
||||
if (settings.pickup_enabled) {
|
||||
storeHours = pickupHours;
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -166,5 +234,24 @@ export async function getStoreConfig({ tenantId }) {
|
||||
pickupHours,
|
||||
deliveryEnabled: settings.delivery_enabled,
|
||||
pickupEnabled: settings.pickup_enabled,
|
||||
schedule,
|
||||
// Campos legacy para compatibilidad
|
||||
delivery_days: settings.delivery_days,
|
||||
delivery_hours_start: settings.delivery_hours_start,
|
||||
delivery_hours_end: settings.delivery_hours_end,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Formatear horarios en formato legacy (días + rango único)
|
||||
*/
|
||||
function formatLegacyHours(enabled, days, start, end) {
|
||||
if (!enabled) return "No disponible";
|
||||
if (!days || !start || !end) return "";
|
||||
|
||||
const daysFormatted = days.split(",").map(d => d.trim()).join(", ");
|
||||
const startFormatted = start?.slice(0, 5) || "";
|
||||
const endFormatted = end?.slice(0, 5) || "";
|
||||
|
||||
return `${daysFormatted} de ${startFormatted} a ${endFormatted}`;
|
||||
}
|
||||
|
||||
@@ -3,6 +3,22 @@ import { getSettings, upsertSettings, getStoreConfig } from "../db/settingsRepo.
|
||||
// Días de la semana para validación
|
||||
const VALID_DAYS = ["lun", "mar", "mie", "jue", "vie", "sab", "dom"];
|
||||
|
||||
/**
|
||||
* Genera schedule por defecto con horarios uniformes
|
||||
*/
|
||||
function createDefaultSchedule() {
|
||||
const defaultDays = ["lun", "mar", "mie", "jue", "vie", "sab"];
|
||||
const delivery = {};
|
||||
const pickup = {};
|
||||
|
||||
for (const day of defaultDays) {
|
||||
delivery[day] = { start: "09:00", end: "18:00" };
|
||||
pickup[day] = { start: "08:00", end: "20:00" };
|
||||
}
|
||||
|
||||
return { delivery, pickup };
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtiene la configuración actual del tenant
|
||||
*/
|
||||
@@ -25,10 +41,17 @@ export async function handleGetSettings({ tenantId }) {
|
||||
pickup_days: "lun,mar,mie,jue,vie,sab",
|
||||
pickup_hours_start: "08:00",
|
||||
pickup_hours_end: "20:00",
|
||||
schedule: createDefaultSchedule(),
|
||||
is_default: true,
|
||||
};
|
||||
}
|
||||
|
||||
// Si no tiene schedule, generar desde datos legacy
|
||||
let schedule = settings.schedule;
|
||||
if (!schedule || Object.keys(schedule).length === 0) {
|
||||
schedule = buildScheduleFromLegacy(settings);
|
||||
}
|
||||
|
||||
return {
|
||||
...settings,
|
||||
// Formatear horarios TIME a HH:MM
|
||||
@@ -36,10 +59,121 @@ export async function handleGetSettings({ tenantId }) {
|
||||
delivery_hours_end: settings.delivery_hours_end?.slice(0, 5) || "18:00",
|
||||
pickup_hours_start: settings.pickup_hours_start?.slice(0, 5) || "08:00",
|
||||
pickup_hours_end: settings.pickup_hours_end?.slice(0, 5) || "20:00",
|
||||
schedule,
|
||||
is_default: false,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Construye schedule desde datos legacy
|
||||
*/
|
||||
function buildScheduleFromLegacy(settings) {
|
||||
const schedule = { delivery: {}, pickup: {} };
|
||||
|
||||
// Delivery
|
||||
if (settings.delivery_enabled && settings.delivery_days) {
|
||||
const days = settings.delivery_days.split(",").map(d => d.trim());
|
||||
const start = settings.delivery_hours_start?.slice(0, 5) || "09:00";
|
||||
const end = settings.delivery_hours_end?.slice(0, 5) || "18:00";
|
||||
for (const day of days) {
|
||||
if (VALID_DAYS.includes(day)) {
|
||||
schedule.delivery[day] = { start, end };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Pickup
|
||||
if (settings.pickup_enabled && settings.pickup_days) {
|
||||
const days = settings.pickup_days.split(",").map(d => d.trim());
|
||||
const start = settings.pickup_hours_start?.slice(0, 5) || "08:00";
|
||||
const end = settings.pickup_hours_end?.slice(0, 5) || "20:00";
|
||||
for (const day of days) {
|
||||
if (VALID_DAYS.includes(day)) {
|
||||
schedule.pickup[day] = { start, end };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return schedule;
|
||||
}
|
||||
|
||||
/**
|
||||
* Valida la estructura del schedule
|
||||
*/
|
||||
function validateSchedule(schedule) {
|
||||
if (!schedule || typeof schedule !== "object") return;
|
||||
|
||||
const timeRegex = /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/;
|
||||
|
||||
for (const type of ["delivery", "pickup"]) {
|
||||
const typeSchedule = schedule[type];
|
||||
if (!typeSchedule || typeof typeSchedule !== "object") continue;
|
||||
|
||||
for (const [day, slot] of Object.entries(typeSchedule)) {
|
||||
if (!VALID_DAYS.includes(day)) {
|
||||
throw new Error(`Invalid day in schedule.${type}: ${day}`);
|
||||
}
|
||||
|
||||
if (slot === null) continue; // null = no disponible
|
||||
|
||||
if (typeof slot !== "object" || !slot.start || !slot.end) {
|
||||
throw new Error(`Invalid slot format for ${type}.${day}`);
|
||||
}
|
||||
|
||||
if (!timeRegex.test(slot.start)) {
|
||||
throw new Error(`Invalid start time for ${type}.${day}: ${slot.start}`);
|
||||
}
|
||||
if (!timeRegex.test(slot.end)) {
|
||||
throw new Error(`Invalid end time for ${type}.${day}: ${slot.end}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sincroniza campos legacy desde schedule
|
||||
*/
|
||||
function syncLegacyFromSchedule(settings) {
|
||||
const schedule = settings.schedule;
|
||||
if (!schedule) return;
|
||||
|
||||
// Sincronizar delivery
|
||||
if (schedule.delivery) {
|
||||
const deliveryDays = Object.keys(schedule.delivery).filter(d => schedule.delivery[d] !== null);
|
||||
if (deliveryDays.length > 0) {
|
||||
// Ordenar días
|
||||
deliveryDays.sort((a, b) => VALID_DAYS.indexOf(a) - VALID_DAYS.indexOf(b));
|
||||
settings.delivery_days = deliveryDays.join(",");
|
||||
|
||||
// Usar primer horario como legacy
|
||||
const firstSlot = schedule.delivery[deliveryDays[0]];
|
||||
if (firstSlot) {
|
||||
settings.delivery_hours_start = firstSlot.start;
|
||||
settings.delivery_hours_end = firstSlot.end;
|
||||
}
|
||||
} else {
|
||||
settings.delivery_days = "";
|
||||
}
|
||||
}
|
||||
|
||||
// Sincronizar pickup
|
||||
if (schedule.pickup) {
|
||||
const pickupDays = Object.keys(schedule.pickup).filter(d => schedule.pickup[d] !== null);
|
||||
if (pickupDays.length > 0) {
|
||||
pickupDays.sort((a, b) => VALID_DAYS.indexOf(a) - VALID_DAYS.indexOf(b));
|
||||
settings.pickup_days = pickupDays.join(",");
|
||||
|
||||
const firstSlot = schedule.pickup[pickupDays[0]];
|
||||
if (firstSlot) {
|
||||
settings.pickup_hours_start = firstSlot.start;
|
||||
settings.pickup_hours_end = firstSlot.end;
|
||||
}
|
||||
} else {
|
||||
settings.pickup_days = "";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Guarda la configuración del tenant
|
||||
*/
|
||||
@@ -52,41 +186,48 @@ export async function handleSaveSettings({ tenantId, settings }) {
|
||||
throw new Error("bot_name is required");
|
||||
}
|
||||
|
||||
// Validar días
|
||||
if (settings.delivery_days) {
|
||||
const days = settings.delivery_days.split(",").map(d => d.trim().toLowerCase());
|
||||
for (const day of days) {
|
||||
if (!VALID_DAYS.includes(day)) {
|
||||
throw new Error(`Invalid delivery day: ${day}`);
|
||||
// Validar schedule si viene
|
||||
if (settings.schedule) {
|
||||
validateSchedule(settings.schedule);
|
||||
// Sincronizar campos legacy desde schedule
|
||||
syncLegacyFromSchedule(settings);
|
||||
} else {
|
||||
// Legacy: validar días individuales
|
||||
if (settings.delivery_days) {
|
||||
const days = settings.delivery_days.split(",").map(d => d.trim().toLowerCase());
|
||||
for (const day of days) {
|
||||
if (!VALID_DAYS.includes(day)) {
|
||||
throw new Error(`Invalid delivery day: ${day}`);
|
||||
}
|
||||
}
|
||||
settings.delivery_days = days.join(",");
|
||||
}
|
||||
settings.delivery_days = days.join(",");
|
||||
}
|
||||
|
||||
if (settings.pickup_days) {
|
||||
const days = settings.pickup_days.split(",").map(d => d.trim().toLowerCase());
|
||||
for (const day of days) {
|
||||
if (!VALID_DAYS.includes(day)) {
|
||||
throw new Error(`Invalid pickup day: ${day}`);
|
||||
if (settings.pickup_days) {
|
||||
const days = settings.pickup_days.split(",").map(d => d.trim().toLowerCase());
|
||||
for (const day of days) {
|
||||
if (!VALID_DAYS.includes(day)) {
|
||||
throw new Error(`Invalid pickup day: ${day}`);
|
||||
}
|
||||
}
|
||||
settings.pickup_days = days.join(",");
|
||||
}
|
||||
settings.pickup_days = days.join(",");
|
||||
}
|
||||
|
||||
// Validar horarios
|
||||
const timeRegex = /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/;
|
||||
|
||||
if (settings.delivery_hours_start && !timeRegex.test(settings.delivery_hours_start)) {
|
||||
throw new Error("Invalid delivery_hours_start format (use HH:MM)");
|
||||
}
|
||||
if (settings.delivery_hours_end && !timeRegex.test(settings.delivery_hours_end)) {
|
||||
throw new Error("Invalid delivery_hours_end format (use HH:MM)");
|
||||
}
|
||||
if (settings.pickup_hours_start && !timeRegex.test(settings.pickup_hours_start)) {
|
||||
throw new Error("Invalid pickup_hours_start format (use HH:MM)");
|
||||
}
|
||||
if (settings.pickup_hours_end && !timeRegex.test(settings.pickup_hours_end)) {
|
||||
throw new Error("Invalid pickup_hours_end format (use HH:MM)");
|
||||
// Validar horarios legacy
|
||||
const timeRegex = /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/;
|
||||
|
||||
if (settings.delivery_hours_start && !timeRegex.test(settings.delivery_hours_start)) {
|
||||
throw new Error("Invalid delivery_hours_start format (use HH:MM)");
|
||||
}
|
||||
if (settings.delivery_hours_end && !timeRegex.test(settings.delivery_hours_end)) {
|
||||
throw new Error("Invalid delivery_hours_end format (use HH:MM)");
|
||||
}
|
||||
if (settings.pickup_hours_start && !timeRegex.test(settings.pickup_hours_start)) {
|
||||
throw new Error("Invalid pickup_hours_start format (use HH:MM)");
|
||||
}
|
||||
if (settings.pickup_hours_end && !timeRegex.test(settings.pickup_hours_end)) {
|
||||
throw new Error("Invalid pickup_hours_end format (use HH:MM)");
|
||||
}
|
||||
}
|
||||
|
||||
const result = await upsertSettings({ tenantId, settings });
|
||||
|
||||
@@ -258,16 +258,27 @@ const runStatus = llmMeta?.error ? "warn" : "ok";
|
||||
...baseAddress,
|
||||
phone: baseAddress.phone || phoneFromWa,
|
||||
};
|
||||
// Obtener shipping_method y payment_method del contexto (preferir decision que es el resultado del turn)
|
||||
const shippingMethod = decision?.context_patch?.shipping_method || reducedContext?.shipping_method || null;
|
||||
const paymentMethod = decision?.context_patch?.payment_method || reducedContext?.payment_method || null;
|
||||
const order = await createOrder({
|
||||
tenantId,
|
||||
wooCustomerId: externalCustomerId,
|
||||
basket: basketToUse,
|
||||
address: addressWithPhone,
|
||||
shippingMethod,
|
||||
paymentMethod,
|
||||
run_id: null,
|
||||
});
|
||||
actionPatch.woo_order_id = order?.id || null;
|
||||
actionPatch.order_total = calcOrderTotal(order);
|
||||
newTools.push({ type: "create_order", ok: true, order_id: order?.id || null });
|
||||
// Notificar via SSE para actualizar la pantalla de pedidos
|
||||
sseSend("order.created", {
|
||||
order_id: order?.id,
|
||||
chat_id,
|
||||
shipping_method: shippingMethod,
|
||||
});
|
||||
} else if (act.type === "update_order") {
|
||||
const baseAddrUpd = reducedContext?.delivery_address || reducedContext?.address || {};
|
||||
const phoneFromWaUpd = from?.replace(/@.*$/, "")?.replace(/[^0-9]/g, "") || "";
|
||||
|
||||
@@ -333,13 +333,103 @@ async function handleRecommendIntent({ tenantId, text, nlu, currentOrder, audit
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Detecta si el usuario pregunta por el total del carrito actual
|
||||
*/
|
||||
function isCartTotalQuery(nlu) {
|
||||
const query = nlu?.entities?.product_query || "";
|
||||
const q = query.trim().toLowerCase();
|
||||
|
||||
// Patrones que indican consulta sobre el carrito actual
|
||||
const cartKeywords = [
|
||||
"todo", "el total", "total", "mi pedido", "el pedido", "precio total",
|
||||
"lo que tengo", "lo que llevo", "lo que estoy pidiendo", "lo que pedí",
|
||||
"en el carrito", "del carrito", "mi carrito", "el carrito",
|
||||
"lo que voy", "hasta ahora", "hasta el momento",
|
||||
];
|
||||
|
||||
// Si la query contiene alguna de estas frases, es consulta del carrito
|
||||
if (cartKeywords.some(kw => q.includes(kw))) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Patrones regex adicionales
|
||||
const patterns = [
|
||||
/^cu[aá]nto (es|sale|cuesta|est[aá])/i,
|
||||
/^precio/i,
|
||||
];
|
||||
return patterns.some(p => p.test(q));
|
||||
}
|
||||
|
||||
/**
|
||||
* Maneja price_query
|
||||
*/
|
||||
async function handlePriceQuery({ tenantId, nlu, currentOrder, audit }) {
|
||||
// Si pregunta por el total del carrito
|
||||
if (isCartTotalQuery(nlu) || !nlu?.entities?.product_query) {
|
||||
const cartItems = currentOrder?.cart || [];
|
||||
if (cartItems.length === 0) {
|
||||
return {
|
||||
plan: {
|
||||
reply: "Tu carrito está vacío. ¿Qué te gustaría agregar?",
|
||||
next_state: ConversationState.CART,
|
||||
intent: "price_query",
|
||||
missing_fields: [],
|
||||
order_action: "none",
|
||||
},
|
||||
decision: { actions: [], order: currentOrder, audit },
|
||||
};
|
||||
}
|
||||
|
||||
// Calcular y mostrar el total
|
||||
let total = 0;
|
||||
const lines = cartItems.map(item => {
|
||||
const itemTotal = (item.price || 0) * (item.qty || 0);
|
||||
total += itemTotal;
|
||||
const unitStr = item.unit === "unit" ? "" : " kg";
|
||||
return `• ${item.name}: ${item.qty}${unitStr} x $${item.price} = $${itemTotal.toLocaleString("es-AR")}`;
|
||||
});
|
||||
|
||||
const reply = `Tu pedido actual:\n\n${lines.join("\n")}\n\n💰 Total: $${total.toLocaleString("es-AR")}\n\n¿Algo más?`;
|
||||
return {
|
||||
plan: {
|
||||
reply,
|
||||
next_state: ConversationState.CART,
|
||||
intent: "price_query",
|
||||
missing_fields: [],
|
||||
order_action: "none",
|
||||
},
|
||||
decision: { actions: [], order: currentOrder, audit },
|
||||
};
|
||||
}
|
||||
|
||||
const productQueries = extractProductQueries(nlu);
|
||||
|
||||
if (productQueries.length === 0) {
|
||||
// Si no hay query pero hay carrito, mostrar el carrito
|
||||
const cartItems = currentOrder?.cart || [];
|
||||
if (cartItems.length > 0) {
|
||||
let total = 0;
|
||||
const lines = cartItems.map(item => {
|
||||
const itemTotal = (item.price || 0) * (item.qty || 0);
|
||||
total += itemTotal;
|
||||
const unitStr = item.unit === "unit" ? "" : " kg";
|
||||
return `• ${item.name}: ${item.qty}${unitStr} x $${item.price} = $${itemTotal.toLocaleString("es-AR")}`;
|
||||
});
|
||||
|
||||
const reply = `Tu pedido actual:\n\n${lines.join("\n")}\n\n💰 Total: $${total.toLocaleString("es-AR")}\n\n¿Querés saber el precio de algún producto específico?`;
|
||||
return {
|
||||
plan: {
|
||||
reply,
|
||||
next_state: ConversationState.CART,
|
||||
intent: "price_query",
|
||||
missing_fields: [],
|
||||
order_action: "none",
|
||||
},
|
||||
decision: { actions: [], order: currentOrder, audit },
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
plan: {
|
||||
reply: "¿De qué producto querés saber el precio?",
|
||||
|
||||
@@ -354,7 +354,7 @@ function processStrongMatch({ updatedOrder, pendingItem, best, audit }) {
|
||||
const displayUnit = normalizeUnit(best.sell_unit) || inferDefaultUnit({ name: best.name, categories: best.categories });
|
||||
const hasQty = pendingItem.requested_qty != null && pendingItem.requested_qty > 0;
|
||||
const needsQuantity = displayUnit !== "unit" && !hasQty;
|
||||
|
||||
|
||||
const autoSelectedOrder = updatePendingItem(updatedOrder, pendingItem.id, {
|
||||
selected_woo_id: best.woo_product_id,
|
||||
selected_name: best.name,
|
||||
|
||||
@@ -25,25 +25,17 @@ function isDeliveryInfoQuestion(text) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Formatea los días de entrega para mostrar
|
||||
* Detecta si el usuario pregunta por horarios de retiro
|
||||
*/
|
||||
function formatDeliveryDays(daysStr) {
|
||||
if (!daysStr) return null;
|
||||
|
||||
const dayMap = {
|
||||
"lun": "Lunes", "mar": "Martes", "mie": "Miércoles", "mié": "Miércoles",
|
||||
"jue": "Jueves", "vie": "Viernes", "sab": "Sábado", "sáb": "Sábado", "dom": "Domingo",
|
||||
};
|
||||
|
||||
const days = daysStr.split(",").map(d => d.trim().toLowerCase());
|
||||
const formatted = days.map(d => dayMap[d] || d).filter(Boolean);
|
||||
|
||||
if (formatted.length === 0) return null;
|
||||
if (formatted.length === 1) return formatted[0];
|
||||
|
||||
// "Lunes, Martes, Miércoles y Jueves"
|
||||
const last = formatted.pop();
|
||||
return `${formatted.join(", ")} y ${last}`;
|
||||
function isPickupInfoQuestion(text) {
|
||||
const t = String(text || "").toLowerCase();
|
||||
const patterns = [
|
||||
/horario.*(retir|buscar|pasar)/i,
|
||||
/cu[aá]ndo.*(retir|buscar|pasar)/i,
|
||||
/a\s+qu[eé]\s+hora.*(retir|buscar)/i,
|
||||
/d[ií]as?.*(retir|buscar)/i,
|
||||
];
|
||||
return patterns.some(p => p.test(t));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -71,19 +63,17 @@ export async function handleWaitingState({ tenantId, text, nlu, order, audit, st
|
||||
|
||||
// Preguntas sobre horarios/días de entrega
|
||||
if (isDeliveryInfoQuestion(text)) {
|
||||
const deliveryDays = formatDeliveryDays(storeConfig.delivery_days);
|
||||
const startHour = storeConfig.delivery_hours_start?.slice(0, 5);
|
||||
const endHour = storeConfig.delivery_hours_end?.slice(0, 5);
|
||||
// Usar deliveryHours que ya viene formateado desde getStoreConfig
|
||||
// (agrupa días con mismos horarios: "Lunes a Viernes de 9:00 a 14:00, Sábado de 9:00 a 13:00")
|
||||
const deliveryHours = storeConfig.deliveryHours;
|
||||
|
||||
let reply = "";
|
||||
if (deliveryDays) {
|
||||
reply = `Hacemos entregas los días ${deliveryDays}`;
|
||||
if (startHour && endHour) {
|
||||
reply += ` de ${startHour} a ${endHour}`;
|
||||
}
|
||||
reply += ". ";
|
||||
if (deliveryHours && deliveryHours !== "No disponible") {
|
||||
reply = `Hacemos entregas: ${deliveryHours}. `;
|
||||
} else if (storeConfig.deliveryEnabled === false) {
|
||||
reply = "Por el momento no ofrecemos delivery. ";
|
||||
} else {
|
||||
reply = "Todavía no tengo configurado los días de entrega. ";
|
||||
reply = "Todavía no tengo configurados los horarios de entrega. ";
|
||||
}
|
||||
|
||||
reply += "Tu pedido ya está en proceso, avisame cualquier cosa.";
|
||||
@@ -100,6 +90,33 @@ export async function handleWaitingState({ tenantId, text, nlu, order, audit, st
|
||||
};
|
||||
}
|
||||
|
||||
// Preguntas sobre horarios de retiro
|
||||
if (isPickupInfoQuestion(text)) {
|
||||
const pickupHours = storeConfig.pickupHours;
|
||||
|
||||
let reply = "";
|
||||
if (pickupHours && pickupHours !== "No disponible") {
|
||||
reply = `Podés retirar: ${pickupHours}. `;
|
||||
} else if (storeConfig.pickupEnabled === false) {
|
||||
reply = "Por el momento no ofrecemos retiro en tienda. ";
|
||||
} else {
|
||||
reply = "Todavía no tengo configurados los horarios de retiro. ";
|
||||
}
|
||||
|
||||
reply += "Tu pedido ya está en proceso, avisame cualquier cosa.";
|
||||
|
||||
return {
|
||||
plan: {
|
||||
reply,
|
||||
next_state: ConversationState.WAITING_WEBHOOKS,
|
||||
intent: "pickup_info",
|
||||
missing_fields: [],
|
||||
order_action: "none",
|
||||
},
|
||||
decision: { actions: [], order: currentOrder, audit },
|
||||
};
|
||||
}
|
||||
|
||||
// Default
|
||||
const reply = currentOrder.payment_type === "link"
|
||||
? "Tu pedido está en proceso. Avisame si necesitás algo más o esperá la confirmación de pago."
|
||||
|
||||
@@ -188,7 +188,7 @@ function mapAddress(address) {
|
||||
};
|
||||
}
|
||||
|
||||
export async function createOrder({ tenantId, wooCustomerId, basket, address, run_id }) {
|
||||
export async function createOrder({ tenantId, wooCustomerId, basket, address, shippingMethod, paymentMethod, run_id }) {
|
||||
const lockKey = `${tenantId}:${wooCustomerId || "anon"}`;
|
||||
return withLock(lockKey, async () => {
|
||||
const client = await getWooClient({ tenantId });
|
||||
@@ -200,9 +200,15 @@ export async function createOrder({ tenantId, wooCustomerId, basket, address, ru
|
||||
customer_id: wooCustomerId || undefined,
|
||||
line_items: lineItems,
|
||||
...(addr ? { billing: addr, shipping: addr } : {}),
|
||||
// Si es cash, usar payment_method "cod" (Cash On Delivery) de WooCommerce
|
||||
...(paymentMethod === "cash" ? { payment_method: "cod", payment_method_title: "Efectivo" } : {}),
|
||||
meta_data: [
|
||||
{ key: "source", value: "whatsapp" },
|
||||
...(run_id ? [{ key: "run_id", value: run_id }] : []),
|
||||
// Guardar shipping_method como metadata para poder leerlo después
|
||||
...(shippingMethod ? [{ key: "shipping_method", value: shippingMethod }] : []),
|
||||
// Guardar payment_method como metadata también
|
||||
...(paymentMethod ? [{ key: "payment_method_wa", value: paymentMethod }] : []),
|
||||
],
|
||||
};
|
||||
const url = `${client.base}/orders`;
|
||||
@@ -313,17 +319,34 @@ export async function listRecentOrders({ tenantId, limit = 20 }) {
|
||||
const source = sourceMeta?.value || "web";
|
||||
|
||||
// Método de envío (shipping)
|
||||
// 1. Primero intentar leer de metadata (para pedidos de WhatsApp)
|
||||
const metaShippingMethod = order.meta_data?.find(m => m.key === "shipping_method")?.value || null;
|
||||
// 2. Fallback a shipping_lines de WooCommerce (para pedidos web)
|
||||
const shippingLines = order.shipping_lines || [];
|
||||
const shippingMethod = shippingLines[0]?.method_title || shippingLines[0]?.method_id || null;
|
||||
const isDelivery = shippingMethod ?
|
||||
!shippingMethod.toLowerCase().includes("retiro") &&
|
||||
!shippingMethod.toLowerCase().includes("pickup") &&
|
||||
!shippingMethod.toLowerCase().includes("local") : false;
|
||||
const wooShippingMethod = shippingLines[0]?.method_title || shippingLines[0]?.method_id || null;
|
||||
// 3. Usar metadata si existe, sino WooCommerce
|
||||
const shippingMethod = metaShippingMethod || wooShippingMethod;
|
||||
// 4. Determinar isDelivery
|
||||
let isDelivery = false;
|
||||
if (metaShippingMethod) {
|
||||
// Si viene de metadata, "delivery" = true, "pickup" = false
|
||||
isDelivery = metaShippingMethod === "delivery";
|
||||
} else if (wooShippingMethod) {
|
||||
// Si viene de WooCommerce, detectar por nombre
|
||||
isDelivery = !wooShippingMethod.toLowerCase().includes("retiro") &&
|
||||
!wooShippingMethod.toLowerCase().includes("pickup") &&
|
||||
!wooShippingMethod.toLowerCase().includes("local");
|
||||
}
|
||||
|
||||
// Método de pago
|
||||
// 1. Primero intentar leer de metadata (para pedidos de WhatsApp)
|
||||
const metaPaymentMethod = order.meta_data?.find(m => m.key === "payment_method_wa")?.value || null;
|
||||
// 2. Luego de los campos estándar de WooCommerce
|
||||
const paymentMethod = order.payment_method || null;
|
||||
const paymentMethodTitle = order.payment_method_title || null;
|
||||
const isCash = paymentMethod === "cod" ||
|
||||
// 3. Determinar si es cash
|
||||
const isCash = metaPaymentMethod === "cash" ||
|
||||
paymentMethod === "cod" ||
|
||||
paymentMethodTitle?.toLowerCase().includes("efectivo") ||
|
||||
paymentMethodTitle?.toLowerCase().includes("cash");
|
||||
|
||||
|
||||
@@ -72,6 +72,51 @@ function parsePrice(p) {
|
||||
return Number.isFinite(n) ? n : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decodifica HTML entities comunes (WooCommerce las usa en nombres de productos)
|
||||
*/
|
||||
function decodeHtmlEntities(str) {
|
||||
if (!str || typeof str !== "string") return str;
|
||||
// Solo procesar si hay entidades
|
||||
if (!str.includes("&")) return str;
|
||||
|
||||
const entities = {
|
||||
"&": "&", "<": "<", ">": ">", """: '"', "'": "'", "'": "'",
|
||||
" ": " ", "¡": "¡", "¢": "¢", "£": "£", "¤": "¤",
|
||||
"¥": "¥", "¦": "¦", "§": "§", "¨": "¨", "©": "©",
|
||||
"ª": "ª", "«": "«", "¬": "¬", "­": "\u00AD", "®": "®",
|
||||
"¯": "¯", "°": "°", "±": "±", "²": "²", "³": "³",
|
||||
"´": "´", "µ": "µ", "¶": "¶", "·": "·", "¸": "¸",
|
||||
"¹": "¹", "º": "º", "»": "»", "¼": "¼", "½": "½",
|
||||
"¾": "¾", "¿": "¿", "À": "À", "Á": "Á", "Â": "Â",
|
||||
"Ã": "Ã", "Ä": "Ä", "Å": "Å", "Æ": "Æ", "Ç": "Ç",
|
||||
"È": "È", "É": "É", "Ê": "Ê", "Ë": "Ë", "Ì": "Ì",
|
||||
"Í": "Í", "Î": "Î", "Ï": "Ï", "Ð": "Ð", "Ñ": "Ñ",
|
||||
"Ò": "Ò", "Ó": "Ó", "Ô": "Ô", "Õ": "Õ", "Ö": "Ö",
|
||||
"×": "×", "Ø": "Ø", "Ù": "Ù", "Ú": "Ú", "Û": "Û",
|
||||
"Ü": "Ü", "Ý": "Ý", "Þ": "Þ", "ß": "ß", "à": "à",
|
||||
"á": "á", "â": "â", "ã": "ã", "ä": "ä", "å": "å",
|
||||
"æ": "æ", "ç": "ç", "è": "è", "é": "é", "ê": "ê",
|
||||
"ë": "ë", "ì": "ì", "í": "í", "î": "î", "ï": "ï",
|
||||
"ð": "ð", "ñ": "ñ", "ò": "ò", "ó": "ó", "ô": "ô",
|
||||
"õ": "õ", "ö": "ö", "÷": "÷", "ø": "ø", "ù": "ù",
|
||||
"ú": "ú", "û": "û", "ü": "ü", "ý": "ý", "þ": "þ",
|
||||
"ÿ": "ÿ",
|
||||
};
|
||||
|
||||
let result = str;
|
||||
// Reemplazar entities nombradas usando iteración (más robusto que regex)
|
||||
for (const [entity, char] of Object.entries(entities)) {
|
||||
if (result.includes(entity)) {
|
||||
result = result.split(entity).join(char);
|
||||
}
|
||||
}
|
||||
// Reemplazar entities numéricas ({ o {)
|
||||
result = result.replace(/&#(\d+);/g, (_, num) => String.fromCharCode(parseInt(num, 10)));
|
||||
result = result.replace(/&#x([0-9a-fA-F]+);/gi, (_, hex) => String.fromCharCode(parseInt(hex, 16)));
|
||||
return result;
|
||||
}
|
||||
|
||||
function normalizeAttributes(attrs) {
|
||||
const out = {};
|
||||
if (!Array.isArray(attrs)) return out;
|
||||
@@ -90,7 +135,7 @@ function normalizeWooProduct(p) {
|
||||
woo_id: p?.id,
|
||||
type: p?.type || "simple",
|
||||
parent_id: p?.parent_id || null,
|
||||
name: p?.name || "",
|
||||
name: decodeHtmlEntities(p?.name || ""),
|
||||
slug: p?.slug || null,
|
||||
status: p?.status || null,
|
||||
catalog_visibility: p?.catalog_visibility || null,
|
||||
@@ -114,7 +159,7 @@ function snapshotRowToItem(row) {
|
||||
const raw = row?.raw || {};
|
||||
return {
|
||||
woo_product_id: row?.woo_id,
|
||||
name: row?.name || "",
|
||||
name: decodeHtmlEntities(row?.name || ""),
|
||||
sku: raw?.SKU || raw?.sku || row?.slug || null,
|
||||
slug: row?.slug || null,
|
||||
price: row?.price_current != null ? Number(row.price_current) : null,
|
||||
|
||||
Reference in New Issue
Block a user