supersam/no8-logic.js

87 lines
3.5 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// n8n workflow: No8 — «Смена статуса на Доставлено (запрос из 1С)»
// Payload от 1С: { Value: "<секрет>", dost: "<номер заказа>" }
// Цель: найти order_group по номеру, delivery_status → delivered, лог-событие.
const NO8_SECRET = "energy7066-stood-Sight-nation569";
// helper вызова Supabase REST
async function supa(method, path, body) {
return this.helpers.request({
method,
url: `${"https://supa.supersamsev.ru"}/rest/v1${path}`,
headers: {
apikey: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoiYW5vbiIsImlzcyI6InN1cGFiYXNlIiwiaWF0IjoxNzc0ODc4Nzk4LCJleHAiOjE5MzI1NTg3OTh9.GAhB_V3js6KzpcBxoY0971-x6oR0WjYnj6wakvPPtIg",
Authorization: "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoiYW5vbiIsImlzcyI6InN1cGFiYXNlIiwiaWF0IjoxNzc0ODc4Nzk4LCJleHAiOjE5MzI1NTg3OTh9.GAhB_V3js6KzpcBxoY0971-x6oR0WjYnj6wakvPPtIg",
"Content-Type": "application/json",
Prefer: "return=minimal",
},
body: ["POST", "PATCH", "PUT"].includes(method) ? JSON.stringify(body) : undefined,
});
}
// === вход: $json.body из вебхука (уже пришёл из 1С) ===
const body = $json.body || {};
// === check secret ===
if (body.Value !== NO8_SECRET) {
return [{ json: { ok: false, error: "unauthorized" } },];
}
// === номер заказа ===
const dostRaw = String(body.dost || "").replace(/\D/g, "");
if (!dostRaw) {
return [{ json: { ok: false, error: "dost (номер заказа) не передан или не содержит цифр" } }];
}
const candidates = [`ТП-${dostRaw}`, dostRaw];
console.log("No8: ищем заказ:", candidates.join(", "));
// === 1) найти order_group ===
let orderGroup = null;
for (const num of candidates) {
const found = await supa.call(this, "GET",
`/order_groups?select=id,user_id,order_number,customer_phone,customer_phone_normalized,notification_status,delivery_type,delivery_status&order_number=eq.${encodeURIComponent(num)}&limit=1`);
if (Array.isArray(found) && found.length) {
orderGroup = found[0];
orderGroup.order_number = num;
break;
}
}
if (!orderGroup) {
return [{ json: { ok: false, error: `Заказ ${body.dost} не найден (пробовали ${candidates.join(" / ")})` } }];
}
console.log("No8: найден заказ:", orderGroup.order_number, "group.id:", orderGroup.id);
// === 2) обновить статус delivery_status='delivered' + called_at ===
const now = new Date().toISOString();
await supa.call(this, "PATCH", `/order_groups?id=eq.${orderGroup.id}`, {
delivery_status: "delivered",
called_at: now,
updated_at: now,
});
console.log("No8: выставлен delivered для group:", orderGroup.id);
// === 3) событие логистики (action_log) ===
try {
await supa.call(this, "POST", "/action_log", {
user_id: orderGroup.user_id || null,
order_group_id: orderGroup.id,
action_type: "delivered_by_robot",
comment: `Доставлено по сигналу No8 из 1С. Заказ ${orderGroup.order_number}`,
created_at: now,
});
console.log("No8: событие записано в action_log");
} catch (e) {
console.warn("No8: action_log не принял (может отсутствовать колонка):", e.message || e);
}
// === выход ===
return [{
json: {
ok: true,
order_group_id: orderGroup.id,
order_number: orderGroup.order_number,
delivery_status: "delivered",
},
}];