pedidos
This commit is contained in:
@@ -89,7 +89,7 @@ async function getWooClient({ tenantId }) {
|
||||
return {
|
||||
base,
|
||||
authHeader: { Authorization: `Basic ${auth}` },
|
||||
timeout: Math.max(cfg.timeout_ms ?? 20000, 20000),
|
||||
timeout: Math.max(cfg.timeout_ms ?? 60000, 60000),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -134,7 +134,7 @@ async function buildLineItems({ tenantId, basket }) {
|
||||
const total = pricePerKg != null ? toMoney(pricePerKg * qty) : null;
|
||||
lineItems.push({
|
||||
product_id: productId,
|
||||
variation_id: it.variation_id ?? null,
|
||||
...(it.variation_id ? { variation_id: it.variation_id } : {}),
|
||||
quantity: Math.round(qty),
|
||||
...(total ? { subtotal: total, total } : {}),
|
||||
meta_data: [
|
||||
@@ -150,7 +150,7 @@ async function buildLineItems({ tenantId, basket }) {
|
||||
const total = pricePerKg != null ? toMoney(pricePerKg * kilos) : null;
|
||||
lineItems.push({
|
||||
product_id: productId,
|
||||
variation_id: it.variation_id ?? null,
|
||||
...(it.variation_id ? { variation_id: it.variation_id } : {}),
|
||||
quantity: 1,
|
||||
...(total ? { subtotal: total, total } : {}),
|
||||
meta_data: [
|
||||
@@ -224,6 +224,33 @@ export async function updateOrder({ tenantId, wooOrderId, basket, address, run_i
|
||||
});
|
||||
}
|
||||
|
||||
function isRetryableNetworkError(err) {
|
||||
const e0 = err;
|
||||
const e1 = err?.cause;
|
||||
const e2 = err?.cause?.cause;
|
||||
const candidates = [e0, e1, e2].filter(Boolean);
|
||||
const codes = new Set(candidates.map((e) => e.code).filter(Boolean));
|
||||
const names = new Set(candidates.map((e) => e.name).filter(Boolean));
|
||||
const messages = candidates.map((e) => String(e.message || "")).join(" | ").toLowerCase();
|
||||
|
||||
const aborted =
|
||||
names.has("AbortError") ||
|
||||
messages.includes("aborted") ||
|
||||
messages.includes("timeout") ||
|
||||
messages.includes("timed out");
|
||||
|
||||
const retryCodes = new Set(["ECONNRESET", "ETIMEDOUT", "UND_ERR_CONNECT_TIMEOUT", "UND_ERR_SOCKET"]);
|
||||
const byCode = [...codes].some((c) => retryCodes.has(c));
|
||||
|
||||
return aborted || byCode;
|
||||
}
|
||||
|
||||
async function getOrderStatus({ client, wooOrderId }) {
|
||||
const url = `${client.base}/orders/${encodeURIComponent(wooOrderId)}`;
|
||||
const data = await fetchWoo({ url, method: "GET", timeout: client.timeout, headers: client.authHeader });
|
||||
return { id: data?.id, status: data?.status, raw: data };
|
||||
}
|
||||
|
||||
export async function updateOrderStatus({ tenantId, wooOrderId, status }) {
|
||||
if (!wooOrderId) throw new Error("missing_woo_order_id");
|
||||
const lockKey = `${tenantId}:order:${wooOrderId}:status`;
|
||||
@@ -231,8 +258,115 @@ export async function updateOrderStatus({ tenantId, wooOrderId, status }) {
|
||||
const client = await getWooClient({ tenantId });
|
||||
const payload = { status };
|
||||
const url = `${client.base}/orders/${encodeURIComponent(wooOrderId)}`;
|
||||
const data = await fetchWoo({ url, method: "PUT", body: payload, timeout: client.timeout, headers: client.authHeader });
|
||||
return { id: data?.id || wooOrderId, raw: data };
|
||||
|
||||
// Timeout corto para el PUT (Woo procesa pero tarda en responder)
|
||||
const putTimeout = 3000;
|
||||
|
||||
try {
|
||||
const data = await fetchWoo({ url, method: "PUT", body: payload, timeout: putTimeout, headers: client.authHeader });
|
||||
return { id: data?.id || wooOrderId, raw: data };
|
||||
} catch (err) {
|
||||
// Si es timeout, verificar si el status cambió con un GET
|
||||
if (isRetryableNetworkError(err)) {
|
||||
if (dbg.wooHttp) console.log("[wooOrders] updateOrderStatus timeout, checking with GET...");
|
||||
|
||||
try {
|
||||
const current = await getOrderStatus({ client, wooOrderId });
|
||||
// Si el status ya es el deseado, la operación fue exitosa
|
||||
if (current.status === status) {
|
||||
if (dbg.wooHttp) console.log("[wooOrders] updateOrderStatus confirmed via GET", { wooOrderId, status });
|
||||
return { id: current.id || wooOrderId, raw: current.raw, recovered: true };
|
||||
}
|
||||
} catch (getErr) {
|
||||
// Si falla el GET también, propagar el error original
|
||||
if (dbg.wooHttp) console.log("[wooOrders] updateOrderStatus GET also failed:", getErr.message);
|
||||
}
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export async function listRecentOrders({ tenantId, limit = 20 }) {
|
||||
const client = await getWooClient({ tenantId });
|
||||
const url = `${client.base}/orders?per_page=${limit}&orderby=date&order=desc`;
|
||||
const data = await fetchWoo({ url, method: "GET", timeout: client.timeout, headers: client.authHeader });
|
||||
|
||||
if (!Array.isArray(data)) return [];
|
||||
|
||||
// Mapear a formato simplificado
|
||||
return data.map(order => {
|
||||
// Detectar si es orden de test (run_id empieza con "test-")
|
||||
const runIdMeta = order.meta_data?.find(m => m.key === "run_id");
|
||||
const runId = runIdMeta?.value || null;
|
||||
const isTest = runId?.startsWith("test-") || false;
|
||||
const sourceMeta = order.meta_data?.find(m => m.key === "source");
|
||||
const source = sourceMeta?.value || "web";
|
||||
|
||||
// Método de envío (shipping)
|
||||
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;
|
||||
|
||||
// Método de pago
|
||||
const paymentMethod = order.payment_method || null;
|
||||
const paymentMethodTitle = order.payment_method_title || null;
|
||||
const isCash = paymentMethod === "cod" ||
|
||||
paymentMethodTitle?.toLowerCase().includes("efectivo") ||
|
||||
paymentMethodTitle?.toLowerCase().includes("cash");
|
||||
|
||||
// Estado de pago (basado en status de la orden)
|
||||
// pending = no pago, processing/completed = pago
|
||||
const isPaid = ["processing", "completed", "on-hold"].includes(order.status);
|
||||
const datePaid = order.date_paid || null;
|
||||
|
||||
return {
|
||||
id: order.id,
|
||||
status: order.status,
|
||||
total: order.total,
|
||||
currency: order.currency,
|
||||
date_created: order.date_created,
|
||||
date_paid: datePaid,
|
||||
billing: {
|
||||
first_name: order.billing?.first_name || "",
|
||||
last_name: order.billing?.last_name || "",
|
||||
phone: order.billing?.phone || "",
|
||||
email: order.billing?.email || "",
|
||||
address_1: order.billing?.address_1 || "",
|
||||
address_2: order.billing?.address_2 || "",
|
||||
city: order.billing?.city || "",
|
||||
state: order.billing?.state || "",
|
||||
postcode: order.billing?.postcode || "",
|
||||
},
|
||||
shipping: {
|
||||
first_name: order.shipping?.first_name || "",
|
||||
last_name: order.shipping?.last_name || "",
|
||||
address_1: order.shipping?.address_1 || "",
|
||||
address_2: order.shipping?.address_2 || "",
|
||||
city: order.shipping?.city || "",
|
||||
state: order.shipping?.state || "",
|
||||
postcode: order.shipping?.postcode || "",
|
||||
},
|
||||
line_items: (order.line_items || []).map(li => ({
|
||||
id: li.id,
|
||||
name: li.name,
|
||||
quantity: li.quantity,
|
||||
total: li.total,
|
||||
})),
|
||||
source,
|
||||
run_id: runId,
|
||||
is_test: isTest,
|
||||
// Shipping info
|
||||
shipping_method: shippingMethod,
|
||||
is_delivery: isDelivery,
|
||||
// Payment info
|
||||
payment_method: paymentMethod,
|
||||
payment_method_title: paymentMethodTitle,
|
||||
is_cash: isCash,
|
||||
is_paid: isPaid,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user