/** * select_candidate — resuelve un pending NEEDS_TYPE eligiendo woo_id. * * Si el pending tenía `requested_qty` ya, lo promueve directo a READY → cart. * Sino lo deja en NEEDS_QUANTITY esperando set_quantity. */ import { updatePendingItem, moveReadyToCart, PendingStatus, } from "../../orderModel.js"; import { getSnapshotItemsByIds } from "../../../shared/wooSnapshot.js"; export async function selectCandidateTool(args, ctx) { const { pending_id, woo_id } = args; const pending = (ctx.order.pending || []).find((p) => p.id === pending_id); if (!pending) { return { ok: false, error: "pending_not_found" }; } // Buscar el producto seleccionado en el snapshot para nombre/unit/precio const lookup = await getSnapshotItemsByIds({ tenantId: ctx.tenantId, wooProductIds: [woo_id], }); const found = (lookup?.items || [])[0]; if (!found) { return { ok: false, error: "woo_id_unknown", hint: "El woo_id no existe en el catálogo. Probá con search_catalog.", }; } const sellsByWeight = !found.sell_unit || !["unit", "unidad"].includes(found.sell_unit); const displayUnit = found.sell_unit === "unit" ? "unit" : sellsByWeight ? "kg" : "unit"; const hasRequestedQty = pending.requested_qty != null && Number.isFinite(pending.requested_qty) && pending.requested_qty > 0; const finalQty = hasRequestedQty ? pending.requested_qty : null; const finalUnit = pending.requested_unit || displayUnit; const needsQty = sellsByWeight && !hasRequestedQty; const updated = updatePendingItem(ctx.order, pending_id, { selected_woo_id: woo_id, selected_name: found.name, selected_price: found.price ?? null, selected_unit: displayUnit, candidates: [], qty: needsQty ? null : finalQty, unit: finalUnit, status: needsQty ? PendingStatus.NEEDS_QUANTITY : PendingStatus.READY, }); ctx.order = moveReadyToCart(updated); if (!needsQty) { ctx.pending_actions.push({ type: "add_to_cart", payload: { woo_id, qty: finalQty, unit: finalUnit }, }); ctx.last_shown_options = []; } return { ok: true, selected: { woo_id, name: found.name, unit: displayUnit, sells_by_weight: sellsByWeight }, needs_quantity: needsQty, cart_size: (ctx.order.cart || []).length, }; }