@flowapt/flowiq-cli 0.10.0 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +75 -2
- package/TEAM-GUIDE.md +13 -1
- package/package.json +1 -1
- package/src/batch-f.test.mjs +63 -0
- package/src/commands/agent-test.js +15 -3
- package/src/commands/agents.js +31 -0
- package/src/commands/broadcast.js +9 -0
- package/src/commands/links.js +63 -20
- package/src/commands/members.js +95 -0
- package/src/commands/messages.js +39 -0
- package/src/commands/notes.js +63 -0
- package/src/commands/org.js +55 -6
- package/src/commands/products.js +58 -0
- package/src/commands/prompts.js +46 -1
- package/src/commands/segments.js +47 -14
- package/src/commands/tag.js +77 -7
- package/src/commands/templates.js +66 -5
- package/src/index.js +147 -6
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
// `flowiq steer list|add|clear <contact_id>` + `flowiq notes list|add
|
|
2
|
+
// <contact_id>` — the internal rows in a contact's chat (server: api/cli/notes.js).
|
|
3
|
+
|
|
4
|
+
import { http } from "../http.js";
|
|
5
|
+
import { fmtSast } from "./audit.js";
|
|
6
|
+
|
|
7
|
+
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
8
|
+
function fail(prefix, e) { console.error(`${prefix}: ${e.message}`); if (e.body?.error && !e.message.includes(e.body.error)) console.error(` ${e.body.error}`); process.exit(1); }
|
|
9
|
+
const requireContact = (v) => { if (!UUID_RE.test(v || "")) { console.error(`Error: "${v}" is not a valid contact UUID.`); process.exit(1); } };
|
|
10
|
+
|
|
11
|
+
async function listKind(contactId, kind, opts) {
|
|
12
|
+
requireContact(contactId);
|
|
13
|
+
let resp;
|
|
14
|
+
try { resp = await http.get("notes", { contact_id: contactId, kind, limit: opts.limit }); } catch (e) { fail("List failed", e); }
|
|
15
|
+
if (opts.json) { console.log(JSON.stringify(resp, null, 2)); return; }
|
|
16
|
+
const label = kind === "notes" ? "internal note" : "steer";
|
|
17
|
+
console.log(`${resp.contact_name || "(no name)"} ${resp.contact_whatsapp_id || ""} on ${resp.organization_name}: ${resp.count} ${label}(s)${kind === "steers" ? ` · AI ${resp.bot_status === false ? "OFF" : "on"}${resp.steer_messages_flag ? "" : " · steer_messages flag off (inbox hides the control; vert still applies rows)"}` : ""}`);
|
|
18
|
+
for (const r of resp.rows) {
|
|
19
|
+
const head = kind === "notes" ? `${r.author ?? "?"}` : `${r.mode}${r.mode === "once" ? (r.consumed ? ", consumed" : ", pending") : ""}`;
|
|
20
|
+
console.log(`\n ${fmtSast(r.created_at)} SAST · ${head}${kind === "steers" && !r.active ? " · inactive" : ""}\n ${r.id}\n ${String(r.text).split("\n").join("\n ")}`);
|
|
21
|
+
}
|
|
22
|
+
if (kind === "steers" && resp.rows.some((r) => r.active)) console.log(`\n Remove: flowiq steer clear ${contactId} [--id <id>] --confirm`);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export const steerList = (contactId, opts = {}) => listKind(contactId, "steers", opts);
|
|
26
|
+
export const notesList = (contactId, opts = {}) => listKind(contactId, "notes", opts);
|
|
27
|
+
|
|
28
|
+
export async function steerAdd(contactId, textParts, opts = {}) {
|
|
29
|
+
requireContact(contactId);
|
|
30
|
+
const text = (Array.isArray(textParts) ? textParts.join(" ") : String(textParts ?? "")).trim();
|
|
31
|
+
if (!text) { console.error("Error: flowiq steer add <contact_id> \"instruction for the agent\" [--once]"); process.exit(1); }
|
|
32
|
+
let resp;
|
|
33
|
+
try { resp = await http.post("notes", { action: "add_steer", contact_id: contactId, text, mode: opts.once ? "once" : "persistent" }); } catch (e) { fail("Steer failed", e); }
|
|
34
|
+
if (opts.json) { console.log(JSON.stringify(resp, null, 2)); return; }
|
|
35
|
+
console.log(`✓ ${resp.mode === "once" ? "one-shot" : "ongoing"} steer added (${resp.id}) as ${resp.author}. ${resp.mode === "once" ? "The agent applies it on the next reply, then it is spent." : "The agent applies it on EVERY reply until: flowiq steer clear " + contactId + " --id " + resp.id + " --confirm"}`);
|
|
36
|
+
for (const w of resp.warnings || []) console.error(` ⚠ ${w}`);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export async function steerClear(contactId, opts = {}) {
|
|
40
|
+
requireContact(contactId);
|
|
41
|
+
const ids = opts.id ? [].concat(opts.id) : undefined;
|
|
42
|
+
let resp;
|
|
43
|
+
try { resp = await http.post("notes", { action: "clear_steers", contact_id: contactId, steer_ids: ids, confirm: !!opts.confirm }); } catch (e) { fail("Clear failed", e); }
|
|
44
|
+
if (opts.json) { console.log(JSON.stringify(resp, null, 2)); return; }
|
|
45
|
+
if (resp.dry_run) {
|
|
46
|
+
if (!resp.count) { console.log("No steers to remove."); return; }
|
|
47
|
+
console.log(`Would delete ${resp.count} steer(s):`);
|
|
48
|
+
for (const s of resp.steers) console.log(` ${s.id} ${s.mode}${s.consumed ? " (consumed)" : ""} ${String(s.text).slice(0, 80)}`);
|
|
49
|
+
console.log("Add --confirm to delete (the texts are kept in the audit row).");
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
console.log(`✓ deleted ${resp.deleted} steer(s).`);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export async function notesAdd(contactId, textParts, opts = {}) {
|
|
56
|
+
requireContact(contactId);
|
|
57
|
+
const text = (Array.isArray(textParts) ? textParts.join(" ") : String(textParts ?? "")).trim();
|
|
58
|
+
if (!text) { console.error("Error: flowiq notes add <contact_id> \"note for the team\""); process.exit(1); }
|
|
59
|
+
let resp;
|
|
60
|
+
try { resp = await http.post("notes", { action: "add_note", contact_id: contactId, text }); } catch (e) { fail("Note failed", e); }
|
|
61
|
+
if (opts.json) { console.log(JSON.stringify(resp, null, 2)); return; }
|
|
62
|
+
console.log(`✓ internal note added (${resp.id}) as ${resp.author}; it shows on the Customer panel, never to the customer.`);
|
|
63
|
+
}
|
package/src/commands/org.js
CHANGED
|
@@ -13,31 +13,78 @@ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
|
|
|
13
13
|
export async function list(search, opts = {}) {
|
|
14
14
|
let resp;
|
|
15
15
|
try {
|
|
16
|
-
resp = await http.get("org", { list: "1", search: search || undefined });
|
|
16
|
+
resp = await http.get("org", { list: "1", search: search || undefined, number: opts.number || undefined });
|
|
17
17
|
} catch (e) {
|
|
18
18
|
console.error(`Lookup failed: ${e.message}`);
|
|
19
|
+
if (e.body?.error && !e.message.includes(e.body.error)) console.error(` ${e.body.error}`);
|
|
19
20
|
process.exit(1);
|
|
20
21
|
}
|
|
21
22
|
if (opts.json) { console.log(JSON.stringify(resp, null, 2)); return; }
|
|
22
23
|
|
|
23
|
-
|
|
24
|
+
// A number lookup shows parked orgs too: the number is the question.
|
|
25
|
+
const orgs = (resp.orgs || []).filter((o) => (opts.all || opts.number ? true : !o.inactive));
|
|
24
26
|
if (!orgs.length) {
|
|
25
|
-
console.log(search ? `No organizations match "${search}".` : "No organizations found.");
|
|
27
|
+
console.log(opts.number ? `No organization has WhatsApp number / phone id / WABA ${opts.number}.` : search ? `No organizations match "${search}".` : "No organizations found.");
|
|
26
28
|
return;
|
|
27
29
|
}
|
|
28
30
|
const pad = (s, n) => String(s ?? "").padEnd(n);
|
|
29
31
|
const nameW = Math.min(34, Math.max(4, ...orgs.map((o) => (o.name || "").length)));
|
|
30
|
-
|
|
32
|
+
const byNumber = !!opts.number;
|
|
33
|
+
console.log(`${pad("NAME", nameW)} ${pad("ID", 36)} ${byNumber ? `${pad("NUMBER", 16)}${pad("PHONE ID", 18)}${pad("WABA", 18)}` : `${pad("PLATFORM", 9)}STORE`}`);
|
|
31
34
|
for (const o of orgs) {
|
|
32
35
|
console.log(
|
|
33
36
|
`${pad((o.name || "").slice(0, nameW), nameW)} ${pad(o.id, 36)} ` +
|
|
34
|
-
|
|
37
|
+
(byNumber
|
|
38
|
+
? `${pad(o.phone_number || "—", 16)}${pad(o.phone_id || "—", 18)}${pad(o.waba_id || "—", 18)}`
|
|
39
|
+
: `${pad(o.platform || "—", 9)}${o.store || ""}`) +
|
|
40
|
+
`${o.inactive ? " (inactive)" : ""}`
|
|
35
41
|
);
|
|
36
42
|
}
|
|
37
43
|
const hidden = (resp.orgs || []).length - orgs.length;
|
|
38
44
|
console.log(`\n${orgs.length} organization(s)${hidden ? ` · ${hidden} inactive hidden (--all to show)` : ""}`);
|
|
39
45
|
}
|
|
40
46
|
|
|
47
|
+
// `flowiq org agent <org> on|off [--commit] [--yes]` — the agent master switch
|
|
48
|
+
// (organizations.wati_webhook_status). Off = no customer gets the AI. On with
|
|
49
|
+
// vert.active:false + an allowlist = test mode. On with vert.active true =
|
|
50
|
+
// live for everyone, which is the shape that needs --yes.
|
|
51
|
+
export async function agentSwitch(orgId, state, opts = {}) {
|
|
52
|
+
requireOrg(orgId);
|
|
53
|
+
const s = String(state || "").toLowerCase();
|
|
54
|
+
if (!["on", "off"].includes(s)) { console.error('Error: pass "on" or "off", e.g. flowiq org agent <org> off --commit'); process.exit(1); }
|
|
55
|
+
let resp;
|
|
56
|
+
try { resp = await http.post("org", { action: "agent_switch", organization_id: orgId, enabled: s === "on", dry_run: !opts.commit, confirm: !!opts.yes }); }
|
|
57
|
+
catch (e) { fail("Switch failed", e); }
|
|
58
|
+
if (opts.json) { console.log(JSON.stringify(resp, null, 2)); return; }
|
|
59
|
+
console.log(`${resp.organization_name} — agent master switch`);
|
|
60
|
+
console.log(` now: ${resp.from ? "ON" : "OFF"} · vert.active ${resp.vert_active ?? "unset"}${resp.allowed_whatsapp_ids?.length ? ` · allowlist ${resp.allowed_whatsapp_ids.join(", ")}` : ""} · active agent ${resp.active_whatsapp_agent ?? "NONE"}`);
|
|
61
|
+
if (resp.unchanged) { console.log(` already ${resp.to ? "ON" : "OFF"} — nothing to do.`); return; }
|
|
62
|
+
console.log(` ${resp.dry_run ? "would set" : "✓ set"}: ${resp.to ? "ON" : "OFF"} → ${resp.mode}`);
|
|
63
|
+
if (resp.dry_run) {
|
|
64
|
+
console.log(`\nDRY RUN — add --commit to switch${resp.needs_confirm ? ", and --yes because this makes the agent LIVE for every customer (set vert.allowed_whatsapp_ids + vert.active false first for a test mode)" : ""}.`);
|
|
65
|
+
} else {
|
|
66
|
+
console.log(`\nUndo: flowiq org agent ${orgId} ${resp.from ? "on" : "off"} --commit${resp.from ? " --yes" : ""}`);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// `flowiq org park <org> [--unpark] --confirm` — organizations.inactive.
|
|
71
|
+
export async function park(orgId, opts = {}) {
|
|
72
|
+
requireOrg(orgId);
|
|
73
|
+
let resp;
|
|
74
|
+
try { resp = await http.post("org", { action: "park", organization_id: orgId, inactive: !opts.unpark, confirm: !!opts.confirm }); }
|
|
75
|
+
catch (e) { fail("Park failed", e); }
|
|
76
|
+
if (opts.json) { console.log(JSON.stringify(resp, null, 2)); return; }
|
|
77
|
+
if (resp.unchanged) { console.log(`${resp.organization_name} is already ${resp.inactive ? "parked (inactive)" : "active"}.`); return; }
|
|
78
|
+
const verb = opts.unpark ? "unpark" : "park";
|
|
79
|
+
if (resp.dry_run) {
|
|
80
|
+
console.log(`Would ${verb} ${resp.organization_name} (inactive ${resp.from} → ${resp.to}).${resp.master_switch && !opts.unpark ? " Its agent master switch is still ON — parking hides the org from censuses and crons, it does not switch the agent off (flowiq org agent <org> off --commit)." : ""}`);
|
|
81
|
+
console.log("Add --confirm to write.");
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
console.log(`✓ ${verb}ed ${resp.organization_name} (inactive ${resp.from} → ${resp.to}).${resp.master_switch && !opts.unpark ? " ⚠ agent master switch still ON." : ""}`);
|
|
85
|
+
console.log(`Undo: flowiq org park ${orgId}${opts.unpark ? "" : " --unpark"} --confirm`);
|
|
86
|
+
}
|
|
87
|
+
|
|
41
88
|
export async function info(orgId, opts = {}) {
|
|
42
89
|
if (!UUID_RE.test(orgId)) {
|
|
43
90
|
console.error(`Error: "${orgId}" is not a valid organization UUID.`);
|
|
@@ -175,8 +222,10 @@ export async function health(orgId, opts = {}) {
|
|
|
175
222
|
const h = resp.health;
|
|
176
223
|
console.log(`${resp.organization_name} — is the agent ready? ${h.ready ? "✓ yes" : `✗ ${h.problems.length} problem(s)`}`);
|
|
177
224
|
for (const p of h.problems) console.log(` ✗ ${p}`);
|
|
225
|
+
for (const w of h.warnings || []) console.log(` ⚠ ${w}`);
|
|
178
226
|
console.log(` switch: master ${h.master_switch ? "ON" : "OFF"} · vert.active ${yn(h.vert_active)}${h.allowed_whatsapp_ids ? ` (only ${h.allowed_whatsapp_ids})` : ""} · provider ${h.provider}${h.coexistence ? ` · ${h.coexistence}` : ""}${h.phone_number ? ` · ${h.phone_number}` : ""}`);
|
|
179
|
-
|
|
227
|
+
const spare = h.keys.openai_spare;
|
|
228
|
+
console.log(` keys: OpenAI ${h.keys.openai.state}${h.keys.openai.detail ? ` (${h.keys.openai.detail})` : ""}${spare ? ` · spare ${spare.state}${spare.detail ? ` (${spare.detail})` : ""}` : ""} · Claude ${h.keys.anthropic_present ? "present" : "none"}`);
|
|
180
229
|
console.log(` agent: ${h.agent ? `${h.agent.name} · ${h.agent.prompt_chars.toLocaleString()} prompt chars · prompt ${h.agent.use_settings_prompt === false ? "OFF" : "on"} · ${h.agent.model ?? "house model"} · product_lookup ${yn(h.agent.product_lookup)} · tickets ${yn(h.agent.ticket_tool_status)}` : "NONE"}`);
|
|
181
230
|
console.log(` catalogue: ${h.catalogue.products} product rows · ${h.catalogue.embedded} with embeddings${h.catalogue.last_sync ? ` · last sync ${when(h.catalogue.last_sync.created_at)} ${h.catalogue.last_sync.success === false ? "FAILED" : "ok"} (+${h.catalogue.last_sync.added ?? 0} ~${h.catalogue.last_sync.updated ?? 0} -${h.catalogue.last_sync.deleted ?? 0})` : " · no sync recorded"}`);
|
|
182
231
|
const s = h.store;
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
// `flowiq products status|search|reconcile <org>` — the synced catalogue as
|
|
2
|
+
// the agent sees it (server: api/cli/products.js).
|
|
3
|
+
|
|
4
|
+
import { http } from "../http.js";
|
|
5
|
+
import { fmtSast } from "./audit.js";
|
|
6
|
+
|
|
7
|
+
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
8
|
+
const pad = (s, n) => String(s ?? "").padEnd(n);
|
|
9
|
+
function fail(prefix, e) { console.error(`${prefix}: ${e.message}`); if (e.body?.error && !e.message.includes(e.body.error)) console.error(` ${e.body.error}`); process.exit(1); }
|
|
10
|
+
const requireOrg = (v) => { if (!UUID_RE.test(v || "")) { console.error(`Error: "${v}" is not a valid organization UUID.`); process.exit(1); } };
|
|
11
|
+
|
|
12
|
+
export async function status(orgId, opts = {}) {
|
|
13
|
+
requireOrg(orgId);
|
|
14
|
+
let resp;
|
|
15
|
+
try { resp = await http.get("products", { organization_id: orgId, status: "1" }); } catch (e) { fail("Status failed", e); }
|
|
16
|
+
if (opts.json) { console.log(JSON.stringify(resp, null, 2)); return; }
|
|
17
|
+
const c = resp.counts;
|
|
18
|
+
console.log(`${resp.organization_name} — catalogue (${resp.platform ?? "no store"})${resp.sync_inactive_products ? " · sync_inactive_products on" : ""}`);
|
|
19
|
+
console.log(` rows: ${c.total} total · ${c.active} active · ${c.archived} archived · ${c.draft} draft${c.other ? ` · ${c.other} other` : ""}`);
|
|
20
|
+
console.log(` embeddings: ${c.embedded} with · ${c.missing_embedding} MISSING${c.missing_embedding ? " ⚠ the agent cannot find these by meaning (products reconcile re-embeds)" : ""}`);
|
|
21
|
+
console.log(` images: ${c.with_image} with an image · prices: ${c.with_price} with a price · ${c.zero_stock} at zero stock`);
|
|
22
|
+
console.log(` newest row: ${resp.newest_row_updated_at ? `${fmtSast(resp.newest_row_updated_at)} SAST` : "—"}`);
|
|
23
|
+
if (resp.last_syncs.length) {
|
|
24
|
+
console.log(` last syncs:`);
|
|
25
|
+
for (const s of resp.last_syncs) console.log(` ${fmtSast(s.created_at)} SAST ${(s.success ?? s.successful) === false ? "FAILED" : "ok "} +${s.added ?? 0} ~${s.updated ?? 0} -${s.deleted ?? 0}${s.source ? ` ${s.source}` : ""}${s.summary ? ` ${String(s.summary).slice(0, 70)}` : ""}`);
|
|
26
|
+
} else console.log(` last syncs: none recorded`);
|
|
27
|
+
if (resp.missing_embedding_sample.length) {
|
|
28
|
+
console.log(` missing embedding (sample):`);
|
|
29
|
+
for (const p of resp.missing_embedding_sample) console.log(` ${pad(p.variant_id, 16)} ${pad(p.status ?? "", 9)} ${String(p.product_title || "").slice(0, 60)}`);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export async function search(orgId, textParts, opts = {}) {
|
|
34
|
+
requireOrg(orgId);
|
|
35
|
+
const text = (Array.isArray(textParts) ? textParts.join(" ") : String(textParts ?? "")).trim();
|
|
36
|
+
if (text.length < 2) { console.error("Error: give at least 2 characters, e.g. flowiq products search <org> whey protein"); process.exit(1); }
|
|
37
|
+
let resp;
|
|
38
|
+
try { resp = await http.get("products", { organization_id: orgId, search: text, limit: opts.limit, min_similarity: opts.minSimilarity }); } catch (e) { fail("Search failed", e); }
|
|
39
|
+
if (opts.json) { console.log(JSON.stringify(resp, null, 2)); return; }
|
|
40
|
+
console.log(`${resp.organization_name}: ${resp.count} match(es) for "${text}" via ${resp.rpc} (min similarity ${resp.min_similarity}) — what the agent's product_lookup tool sees`);
|
|
41
|
+
for (const p of resp.results) {
|
|
42
|
+
const sim = p.similarity ?? p.score ?? p.sim;
|
|
43
|
+
const stock = p.stockcount && typeof p.stockcount === "object" ? Object.values(p.stockcount).reduce((a, b) => a + (Number(b) || 0), 0) : p.stockcount;
|
|
44
|
+
console.log(` ${pad(sim != null ? Number(sim).toFixed(2) : "", 5)} ${pad(p.variant_id ?? "", 16)} ${pad(p.price != null ? String(p.price) : "", 9)} ${pad(stock != null ? `stock ${stock}` : "", 11)} ${pad(p.status ?? "", 8)} ${String(p.product_title ?? p.title ?? "").slice(0, 70)}`);
|
|
45
|
+
}
|
|
46
|
+
if (!resp.count) console.log(` (nothing within similarity ${resp.min_similarity}; try --min-similarity 0.05, or check embeddings with: flowiq products status ${orgId})`);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export async function reconcile(orgId, opts = {}) {
|
|
50
|
+
requireOrg(orgId);
|
|
51
|
+
let resp;
|
|
52
|
+
try { resp = await http.post("products", { action: "reconcile", organization_id: orgId, platform: opts.platform, confirm: !!opts.confirm }); } catch (e) { fail("Reconcile failed", e); }
|
|
53
|
+
if (opts.json) { console.log(JSON.stringify(resp, null, 2)); return; }
|
|
54
|
+
if (resp.dry_run) { console.log(`Would trigger a ${resp.platform} reconcile for ${resp.organization_name} (${resp.note}). Add --confirm.`); return; }
|
|
55
|
+
console.log(`${resp.ok ? "✓" : "✗"} products-reconcile-scheduler answered ${resp.http_status} for ${resp.organization_name} (${resp.platform})`);
|
|
56
|
+
console.log(` ${JSON.stringify(resp.response).slice(0, 600)}`);
|
|
57
|
+
console.log(`\n Watch it land: flowiq products status ${orgId}`);
|
|
58
|
+
}
|
package/src/commands/prompts.js
CHANGED
|
@@ -96,7 +96,34 @@ export function mintSectionIds(sections) {
|
|
|
96
96
|
return touched;
|
|
97
97
|
}
|
|
98
98
|
|
|
99
|
-
|
|
99
|
+
// --dry-run: what a push WOULD change, section by section, against the live
|
|
100
|
+
// agent, without writing. Compares by section id (title for sections that
|
|
101
|
+
// have no id yet) and reports added / removed / changed sections with the
|
|
102
|
+
// character delta, plus title / hidden / channels / window changes.
|
|
103
|
+
export function diffSections(live, local) {
|
|
104
|
+
const keyOf = (s) => s.id || `title:${s.title}`;
|
|
105
|
+
const liveBy = new Map((live || []).map((s) => [keyOf(s), s]));
|
|
106
|
+
const localBy = new Map((local || []).map((s) => [keyOf(s), s]));
|
|
107
|
+
const added = [], removed = [], changed = [];
|
|
108
|
+
for (const [k, s] of localBy) if (!liveBy.has(k)) added.push({ title: s.title, chars: (s.content || "").length });
|
|
109
|
+
for (const [k, s] of liveBy) if (!localBy.has(k)) removed.push({ title: s.title, chars: (s.content || "").length });
|
|
110
|
+
for (const [k, s] of localBy) {
|
|
111
|
+
const l = liveBy.get(k);
|
|
112
|
+
if (!l) continue;
|
|
113
|
+
const what = [];
|
|
114
|
+
if ((l.content || "") !== (s.content || "")) what.push(`content ${(l.content || "").length} → ${(s.content || "").length} chars`);
|
|
115
|
+
if ((l.title || "") !== (s.title || "")) what.push(`title "${l.title}" → "${s.title}"`);
|
|
116
|
+
if (!!l.hidden !== !!s.hidden) what.push(`hidden ${!!l.hidden} → ${!!s.hidden}`);
|
|
117
|
+
if (JSON.stringify(l.channels ?? null) !== JSON.stringify(s.channels ?? null)) what.push(`channels ${JSON.stringify(l.channels ?? "all")} → ${JSON.stringify(s.channels ?? "all")}`);
|
|
118
|
+
for (const f of ["active_from", "active_until", "active_tz"]) if ((l[f] ?? null) !== (s[f] ?? null)) what.push(`${f} ${l[f] ?? "unset"} → ${s[f] ?? "unset"}`);
|
|
119
|
+
if (what.length) changed.push({ title: s.title, what });
|
|
120
|
+
}
|
|
121
|
+
const order = (list) => list.map(keyOf).join("|");
|
|
122
|
+
const reordered = !added.length && !removed.length && order(live || []) !== order(local || []);
|
|
123
|
+
return { added, removed, changed, reordered, unchanged: !added.length && !removed.length && !changed.length && !reordered };
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export async function push(identifier, opts = {}) {
|
|
100
127
|
let filePath;
|
|
101
128
|
try {
|
|
102
129
|
filePath = await resolvePushPath(identifier);
|
|
@@ -121,6 +148,24 @@ export async function push(identifier) {
|
|
|
121
148
|
process.exit(1);
|
|
122
149
|
}
|
|
123
150
|
|
|
151
|
+
if (opts.dryRun) {
|
|
152
|
+
let live;
|
|
153
|
+
try { live = await http.get("prompts", { organization_id: data.organization_id, agent_id: data.agent_id }); }
|
|
154
|
+
catch (e) { console.error(`Dry run failed (could not read the live prompt): ${e.message}`); process.exit(1); }
|
|
155
|
+
const d = diffSections(live.prompt_sections, data.prompt_sections);
|
|
156
|
+
const liveChars = (live.prompt_sections || []).reduce((a, s) => a + (s.content || "").length, 0);
|
|
157
|
+
const localChars = data.prompt_sections.reduce((a, s) => a + (s.content || "").length, 0);
|
|
158
|
+
console.log(`DRY RUN — ${filePath} against ${live.agent_name} (${live.agent_id}) on ${live.organization_name}`);
|
|
159
|
+
console.log(` live: ${(live.prompt_sections || []).length} sections, ${liveChars.toLocaleString()} chars · file: ${data.prompt_sections.length} sections, ${localChars.toLocaleString()} chars`);
|
|
160
|
+
if (d.unchanged) { console.log(" no differences — a push would change nothing."); return; }
|
|
161
|
+
for (const a of d.added) console.log(` + add "${a.title}" (${a.chars} chars)`);
|
|
162
|
+
for (const r of d.removed) console.log(` - REMOVE "${r.title}" (${r.chars} chars)`);
|
|
163
|
+
for (const c of d.changed) console.log(` ~ change "${c.title}": ${c.what.join("; ")}`);
|
|
164
|
+
if (d.reordered) console.log(" ~ sections reordered");
|
|
165
|
+
console.log(`\nNothing written. Push for real: flowiq prompts push ${identifier}`);
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
|
|
124
169
|
// A section added by hand has no id yet. Mint one and write it back to the
|
|
125
170
|
// file BEFORE pushing, so a later pull or push keeps the same id.
|
|
126
171
|
const minted = mintSectionIds(data.prompt_sections);
|
package/src/commands/segments.js
CHANGED
|
@@ -288,7 +288,20 @@ export async function plan(orgId, opts = {}) {
|
|
|
288
288
|
console.log(`⚠ could not check existing batch tags (${e.message}) — verify with \`seg list --prefix ${prefix}\` before apply.`);
|
|
289
289
|
}
|
|
290
290
|
|
|
291
|
-
|
|
291
|
+
// A continuation (--start-index N) is a NEW plan, not a rewrite of the first
|
|
292
|
+
// one: the earlier file is the record of who got the earlier batches, so it
|
|
293
|
+
// is never overwritten. The continuation lands in <slug>-from-NN.json
|
|
294
|
+
// unless --segment names it.
|
|
295
|
+
const baseSlug = slugify(opts.segment || prefix, prefix);
|
|
296
|
+
const slug = !opts.segment && startIndex > 1 ? `${baseSlug}-from-${String(startIndex).padStart(2, "0")}` : baseSlug;
|
|
297
|
+
if (await fs.access(planPath(slug)).then(() => true).catch(() => false)) {
|
|
298
|
+
const prev = JSON.parse(await fs.readFile(planPath(slug), "utf8").catch(() => "{}"));
|
|
299
|
+
if (prev.applied) {
|
|
300
|
+
console.error(`Error: ${planPath(slug)} already exists AND was applied on ${prev.applied.at} — it is the record of who got those batches. Pass --segment <new-name> to write a different file.`);
|
|
301
|
+
process.exit(1);
|
|
302
|
+
}
|
|
303
|
+
console.log(`⚠ overwriting ${planPath(slug)} (never applied)`);
|
|
304
|
+
}
|
|
292
305
|
const planDoc = {
|
|
293
306
|
schema_version: 1,
|
|
294
307
|
segment: slug,
|
|
@@ -373,24 +386,44 @@ export async function apply(orgId, identifier, opts = {}) {
|
|
|
373
386
|
if (a !== planDoc.segment) { console.log("Mismatch — aborted, nothing tagged."); process.exit(0); }
|
|
374
387
|
}
|
|
375
388
|
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
389
|
+
// One HTTP request per chunk of ≤ APPLY_CHUNK ids. The server already splits
|
|
390
|
+
// its DB calls at 8,000 rows, but a big cohort in ONE request still ran past
|
|
391
|
+
// the function timeout (Zero BS 18,614 on 30 Sep 2026: two timeouts, one
|
|
392
|
+
// batch half-tagged). Smaller requests finish, and a failure names the chunk
|
|
393
|
+
// so a re-run (idempotent) picks up where it stopped.
|
|
394
|
+
const APPLY_CHUNK = 4000;
|
|
395
|
+
const chunks = [];
|
|
396
|
+
for (const b of planDoc.batches) {
|
|
397
|
+
for (let i = 0; i < b.contact_ids.length; i += APPLY_CHUNK) chunks.push({ tag: b.tag, contact_ids: b.contact_ids.slice(i, i + APPLY_CHUNK) });
|
|
398
|
+
}
|
|
399
|
+
const byTag = new Map();
|
|
400
|
+
for (const [ci, chunk] of chunks.entries()) {
|
|
401
|
+
let resp;
|
|
402
|
+
try {
|
|
403
|
+
resp = await http.post("segments", { mode: "apply", organization_id: orgId, batches: [chunk] });
|
|
404
|
+
} catch (e) {
|
|
405
|
+
const done = [...byTag.values()].reduce((a, r) => a + r.tagged, 0);
|
|
406
|
+
console.error(`Apply failed on request ${ci + 1}/${chunks.length} (${chunk.tag}, ${chunk.contact_ids.length} ids): ${e.message}`);
|
|
407
|
+
if (e.body?.error) console.error(` ${e.body.error}`);
|
|
408
|
+
console.error(` ${done} contact(s) tagged by the earlier requests. Re-run the same apply: it is idempotent and only the missing ones get tagged.`);
|
|
409
|
+
process.exit(1);
|
|
410
|
+
}
|
|
411
|
+
for (const r of resp.results || []) {
|
|
412
|
+
const prev = byTag.get(r.tag) ?? { tag: r.tag, tagged: 0, already_had: 0, not_found: 0 };
|
|
413
|
+
prev.tagged += r.tagged ?? 0; prev.already_had += r.already_had ?? 0; prev.not_found += r.not_found ?? 0;
|
|
414
|
+
byTag.set(r.tag, prev);
|
|
415
|
+
}
|
|
416
|
+
if (chunks.length > 1) console.log(` request ${ci + 1}/${chunks.length}: ${chunk.tag} ${chunk.contact_ids.length} ids → tagged ${(resp.results || []).reduce((a, r) => a + (r.tagged ?? 0), 0)}`);
|
|
386
417
|
}
|
|
418
|
+
const results = [...byTag.values()];
|
|
419
|
+
const totals = results.reduce((a, r) => ({ tagged: a.tagged + r.tagged, already_had: a.already_had + r.already_had, not_found: a.not_found + r.not_found }), { tagged: 0, already_had: 0, not_found: 0 });
|
|
387
420
|
|
|
388
|
-
for (const r of
|
|
421
|
+
for (const r of results) {
|
|
389
422
|
console.log(` ${r.tag.padEnd(40)} tagged ${r.tagged}${r.already_had ? ` · already_had ${r.already_had}` : ""}${r.not_found ? ` · not_found ${r.not_found}` : ""}`);
|
|
390
423
|
}
|
|
391
|
-
console.log(`Totals: tagged ${
|
|
424
|
+
console.log(`Totals: tagged ${totals.tagged} · already_had ${totals.already_had} · not_found ${totals.not_found}`);
|
|
392
425
|
|
|
393
|
-
planDoc.applied = { at: new Date().toISOString(), tag_counts: Object.fromEntries(
|
|
426
|
+
planDoc.applied = { at: new Date().toISOString(), tag_counts: Object.fromEntries(results.map((r) => [r.tag, r.tagged + r.already_had])) };
|
|
394
427
|
await fs.writeFile(filePath, JSON.stringify(planDoc, null, 2) + "\n", "utf8");
|
|
395
428
|
console.log("");
|
|
396
429
|
console.log(`Send per tag, one batch at a time: flowiq broadcast send ${orgId} --tag ${planDoc.batches[0].tag} --template <name> …`);
|
package/src/commands/tag.js
CHANGED
|
@@ -8,8 +8,12 @@
|
|
|
8
8
|
// flowiq tag segment <org> --min-orders 2 --min-spent 1000 --region ZA-GP --tag gp-repeat
|
|
9
9
|
// flowiq tag attributes <org> --filter allow_broadcast_true --tag broadcastable
|
|
10
10
|
// flowiq tag messages <org> --min-count 3 --sender user-whatsapp --tag engaged
|
|
11
|
+
// flowiq tag ids <org> --ids a,b,c | --ids-file ids.txt --tag <name> [--commit]
|
|
12
|
+
// flowiq tag holders <org> <tag> [--limit 200] [--all] [--csv]
|
|
13
|
+
// flowiq tag field <org> --field whatsapp_id --any 27794975464 --exact --tag x --commit
|
|
11
14
|
// flowiq tag list <org>
|
|
12
|
-
// flowiq tag remove <org> <tag>[,<tag>...] --confirm
|
|
15
|
+
// flowiq tag remove <org> <tag>[,<tag>...] --confirm (every contact)
|
|
16
|
+
// flowiq tag remove <org> <tag> --contacts a,b | --contacts-file f --confirm (those only)
|
|
13
17
|
//
|
|
14
18
|
// Every match mode prints the dry-run count + a sample; nothing writes until
|
|
15
19
|
// --commit AND (for large writes) a typed confirmation. Appends only — it
|
|
@@ -91,12 +95,76 @@ export async function field(orgId, opts = {}) {
|
|
|
91
95
|
requireOrg(orgId);
|
|
92
96
|
const keywords = splitList(opts.any || opts.all);
|
|
93
97
|
if (!keywords) { console.error("Error: pass --any \"a,b\" (OR) or --all \"a,b\" (AND)."); process.exit(1); }
|
|
98
|
+
if (opts.exact && opts.all) { console.error("Error: --exact matches whole values, so it is an OR over --any (drop --all)."); process.exit(1); }
|
|
94
99
|
const payload = {
|
|
95
100
|
mode: "field", organization_id: orgId, field_name: opts.field || "order_history",
|
|
96
|
-
keywords, logic: opts.all ? "AND" : "OR", case_sensitive: !!opts.caseSensitive,
|
|
101
|
+
keywords, logic: opts.all ? "AND" : "OR", case_sensitive: !!opts.caseSensitive, exact: !!opts.exact,
|
|
97
102
|
};
|
|
98
103
|
await confirmLargeWrite(orgId, payload, opts, "Field search");
|
|
99
|
-
await runMatch("Field search", payload, opts);
|
|
104
|
+
await runMatch(opts.exact ? "Exact field match" : "Field search", payload, opts);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
async function readIds(csv, file) {
|
|
108
|
+
const fs = await import("node:fs/promises");
|
|
109
|
+
let ids = splitList(csv) || [];
|
|
110
|
+
if (file) {
|
|
111
|
+
const text = await fs.readFile(file, "utf8").catch((e) => { console.error(`Error: cannot read ${file}: ${e.message}`); process.exit(1); });
|
|
112
|
+
ids.push(...text.split(/[\s,]+/).map((s) => s.trim()).filter(Boolean));
|
|
113
|
+
}
|
|
114
|
+
ids = [...new Set(ids)];
|
|
115
|
+
const bad = ids.filter((id) => !UUID_RE.test(id));
|
|
116
|
+
if (bad.length) console.error(`⚠ ${bad.length} value(s) are not contact UUIDs and will be ignored (e.g. ${bad[0]})`);
|
|
117
|
+
return ids.filter((id) => UUID_RE.test(id));
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// `flowiq tag ids <org> --ids a,b | --ids-file f --tag <name> [--commit]`
|
|
121
|
+
export async function ids(orgId, opts = {}) {
|
|
122
|
+
requireOrg(orgId);
|
|
123
|
+
const list = await readIds(opts.ids, opts.idsFile);
|
|
124
|
+
if (!list.length) { console.error("Error: pass --ids a,b,c or --ids-file <path> (contact UUIDs, one per line or comma-separated)."); process.exit(1); }
|
|
125
|
+
const payload = { mode: "ids", organization_id: orgId, contact_ids: list };
|
|
126
|
+
await confirmLargeWrite(orgId, payload, opts, "Id list");
|
|
127
|
+
const commit = !!opts.commit;
|
|
128
|
+
if (commit && !opts.tag) { console.error("Error: --tag <name> is required with --commit."); process.exit(1); }
|
|
129
|
+
let resp;
|
|
130
|
+
try { resp = await http.post("tag", { ...payload, dry_run: !commit, tag: commit ? opts.tag.trim() : undefined }); }
|
|
131
|
+
catch (e) { console.error(`Tag ids failed: ${e.message}`); if (e.body?.error && !e.message.includes(e.body.error)) console.error(` ${e.body.error}`); process.exit(1); }
|
|
132
|
+
if (opts.json) { console.log(JSON.stringify(resp, null, 2)); return; }
|
|
133
|
+
if (!commit) {
|
|
134
|
+
console.log(`Id list: ${resp.matched} of ${list.length} id(s) belong to ${resp.organization_name}${resp.not_found ? ` · ${resp.not_found} not in this org (ignored)` : ""}.`);
|
|
135
|
+
renderSample(resp.sample);
|
|
136
|
+
console.log(`\nAdd --tag <name> --commit to apply. (dry run — nothing written)`);
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
console.log(`Id list: matched ${resp.matched} · newly tagged ${resp.tagged} · already had "${resp.tag}" ${resp.already_had}${resp.not_found ? ` · not in org ${resp.not_found}` : ""}.`);
|
|
140
|
+
console.log(`\nVerify: flowiq tag holders ${orgId} ${resp.tag} · Undo: flowiq tag remove ${orgId} ${resp.tag} --contacts-file <the same file> --confirm`);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// `flowiq tag holders <org> <tag> [--limit] [--all] [--csv]` — who carries a tag.
|
|
144
|
+
export async function holders(orgId, tagName, opts = {}) {
|
|
145
|
+
requireOrg(orgId);
|
|
146
|
+
if (!tagName) { console.error("Error: pass the tag name, e.g. flowiq tag holders <org> vip"); process.exit(1); }
|
|
147
|
+
const pageSize = opts.all ? 1000 : Math.min(Number(opts.limit) || 200, 1000);
|
|
148
|
+
const contacts = [];
|
|
149
|
+
let offset = 0, resp;
|
|
150
|
+
for (;;) {
|
|
151
|
+
try { resp = await http.post("tag", { mode: "holders", organization_id: orgId, tag: tagName, limit: pageSize, offset }); }
|
|
152
|
+
catch (e) { console.error(`Holders failed: ${e.message}`); if (e.body?.error && !e.message.includes(e.body.error)) console.error(` ${e.body.error}`); process.exit(1); }
|
|
153
|
+
contacts.push(...(resp.contacts || []));
|
|
154
|
+
if (!opts.all || !resp.has_more || !(resp.contacts || []).length) break;
|
|
155
|
+
offset += resp.contacts.length;
|
|
156
|
+
}
|
|
157
|
+
if (opts.json) { console.log(JSON.stringify({ ...resp, contacts }, null, 2)); return; }
|
|
158
|
+
if (opts.csv) {
|
|
159
|
+
console.log("id,full_name,whatsapp_id,email,allow_broadcast,archived,blocked");
|
|
160
|
+
for (const c of contacts) console.log([c.id, c.full_name, c.whatsapp_id, c.email, c.allow_broadcast, c.archived, c.blocked].map((v) => { const s = v == null ? "" : String(v); return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s; }).join(","));
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
console.log(`"${tagName}" on ${resp.organization_name}: ${resp.total} contact(s)${contacts.length < resp.total ? ` (showing ${contacts.length}; --all for every page, --csv to export)` : ""}`);
|
|
164
|
+
for (const c of contacts) {
|
|
165
|
+
const flags = [c.allow_broadcast === false && "no-broadcast", c.archived && "archived", c.blocked && "blocked", c.bot_status === false && "AI off"].filter(Boolean).join(", ");
|
|
166
|
+
console.log(` ${(c.full_name || "—").slice(0, 28).padEnd(28)} ${String(c.whatsapp_id || c.email || "").padEnd(16)} ${c.id}${flags ? ` (${flags})` : ""}`);
|
|
167
|
+
}
|
|
100
168
|
}
|
|
101
169
|
|
|
102
170
|
export async function cohort(orgId, opts = {}) {
|
|
@@ -170,12 +238,14 @@ export async function remove(orgId, tagArg, opts = {}) {
|
|
|
170
238
|
requireOrg(orgId);
|
|
171
239
|
const tags = splitList(tagArg);
|
|
172
240
|
if (!tags || !tags.length) { console.error("Error: pass one or more tag names (comma-separated)."); process.exit(1); }
|
|
241
|
+
const contactIds = opts.contacts || opts.contactsFile ? await readIds(opts.contacts, opts.contactsFile) : null;
|
|
242
|
+
if ((opts.contacts || opts.contactsFile) && !contactIds.length) { console.error("Error: --contacts / --contacts-file gave no contact UUIDs."); process.exit(1); }
|
|
173
243
|
if (!opts.confirm) {
|
|
174
|
-
console.log(`DRY RUN — would remove ${tags.length} tag(s) from
|
|
244
|
+
console.log(`DRY RUN — would remove ${tags.length} tag(s) from ${contactIds ? `${contactIds.length} listed contact(s)` : "ALL contacts"}: ${tags.join(", ")}. Add --confirm to remove.`);
|
|
175
245
|
return;
|
|
176
246
|
}
|
|
177
247
|
let resp;
|
|
178
|
-
try { resp = await http.post("tag", { mode: "remove", organization_id: orgId, tags }); }
|
|
179
|
-
catch (e) { console.error(`Remove failed: ${e.message}`); process.exit(1); }
|
|
180
|
-
console.log(`Removed ${tags.join(", ")} from ${resp.contacts_touched} contact(s) on ${resp.organization_name}.`);
|
|
248
|
+
try { resp = await http.post("tag", { mode: "remove", organization_id: orgId, tags, ...(contactIds ? { contact_ids: contactIds } : {}) }); }
|
|
249
|
+
catch (e) { console.error(`Remove failed: ${e.message}`); if (e.body?.error && !e.message.includes(e.body.error)) console.error(` ${e.body.error}`); process.exit(1); }
|
|
250
|
+
console.log(`Removed ${tags.join(", ")} from ${resp.contacts_touched} contact(s) on ${resp.organization_name}${contactIds ? ` (of ${contactIds.length} listed${resp.not_found ? `, ${resp.not_found} not in this org` : ""})` : ""}.`);
|
|
181
251
|
}
|
|
@@ -343,8 +343,37 @@ export async function show(orgId, name, opts = {}) {
|
|
|
343
343
|
|
|
344
344
|
const rows = resp.templates || [];
|
|
345
345
|
if (!rows.length) {
|
|
346
|
-
|
|
347
|
-
|
|
346
|
+
// Not in FlowIQ's table is not "does not exist": a template made in Meta's
|
|
347
|
+
// own tools or on a swapped WABA lives only at Meta (Health Matrix, 22 Sep
|
|
348
|
+
// 2026). Read it from Meta before giving up.
|
|
349
|
+
let live;
|
|
350
|
+
try { live = await http.get("templates", { organization_id: orgId, name }); } catch { live = null; }
|
|
351
|
+
const liveRows = (live?.templates || []).filter((t) => t.name === name) .concat((live?.templates || []).filter((t) => t.name !== name));
|
|
352
|
+
if (!liveRows.length) {
|
|
353
|
+
console.error(`No template on this org matching "${name}", in FlowIQ or at Meta. List them with: flowiq templates status ${orgId} --live`);
|
|
354
|
+
process.exit(1);
|
|
355
|
+
}
|
|
356
|
+
const t = liveRows[0];
|
|
357
|
+
if (liveRows.length > 1 && t.name !== name) {
|
|
358
|
+
console.error(`"${name}" matches ${liveRows.length} templates at Meta — name one exactly:`);
|
|
359
|
+
for (const r of liveRows) console.error(` ${r.name} [${r.status}] ${r.category}`);
|
|
360
|
+
process.exit(1);
|
|
361
|
+
}
|
|
362
|
+
if (opts.json) { console.log(JSON.stringify({ source: "meta", template: t }, null, 2)); return; }
|
|
363
|
+
console.log(`${t.name} [${t.status}] ${t.category}${t.previous_category && t.previous_category !== t.category ? ` (was ${t.previous_category})` : ""} · ${t.language}${t.parameter_format ? ` · ${t.parameter_format}` : ""}`);
|
|
364
|
+
console.log(` org: ${orgId}`);
|
|
365
|
+
console.log(` source: META ONLY — not recorded in FlowIQ's templates table (made in Meta's tools or on another WABA), so it cannot be picked in the send dialog until it is pulled in`);
|
|
366
|
+
if (t.id) console.log(` meta id: ${t.id}`);
|
|
367
|
+
if (t.rejected_reason && t.rejected_reason !== "NONE") console.log(` rejected: ${t.rejected_reason}`);
|
|
368
|
+
for (const c of t.components || []) {
|
|
369
|
+
const label = String(c.type || "").toLowerCase().padEnd(9);
|
|
370
|
+
if (c.type === "BODY" || c.type === "FOOTER") console.log(` ${label} ${String(c.text || "").replace(/\n/g, "\n ")}`);
|
|
371
|
+
else if (c.type === "HEADER") console.log(` ${label} ${c.format}${c.text ? `: ${c.text}` : ""}`);
|
|
372
|
+
else if (c.type === "BUTTONS") for (const b of c.buttons || []) console.log(` button ${b.type}: ${b.text}${b.url ? ` → ${b.url}` : ""}${b.phone_number ? ` → ${b.phone_number}` : ""}`);
|
|
373
|
+
else if (c.type === "CAROUSEL") console.log(` carousel ${(c.cards || []).length} card(s)`);
|
|
374
|
+
}
|
|
375
|
+
console.log(`\n The full Meta record: flowiq templates pull ${orgId}`);
|
|
376
|
+
return;
|
|
348
377
|
}
|
|
349
378
|
// Prefer an exact name match; otherwise if the substring is ambiguous, say so.
|
|
350
379
|
let row = rows.find((r) => r.template_name === name);
|
|
@@ -444,22 +473,54 @@ export async function attempts(orgId, opts = {}) {
|
|
|
444
473
|
if (opts.json) { console.log(JSON.stringify(resp, null, 2)); return; }
|
|
445
474
|
|
|
446
475
|
const rows = resp.attempts || [];
|
|
447
|
-
|
|
476
|
+
const logs = resp.status_logs || [];
|
|
477
|
+
if (!rows.length && !logs.length) {
|
|
448
478
|
console.log(opts.failed ? "(no failed submissions on record for this org)" : "(no template submissions on record for this org — the ledger started 21 Sep 2026)");
|
|
449
479
|
return;
|
|
450
480
|
}
|
|
451
|
-
|
|
481
|
+
// Meta's history per template, newest first: what happened AFTER submit.
|
|
482
|
+
// A category flip shows as the same status with a new category.
|
|
483
|
+
const historyOf = (name) => logs.filter((l) => l.template_name === name);
|
|
484
|
+
const describeHistory = (name, submittedCategory) => {
|
|
485
|
+
const h = historyOf(name).slice().reverse(); // oldest first
|
|
486
|
+
if (!h.length) return [];
|
|
487
|
+
const lines = [];
|
|
488
|
+
let lastCat = submittedCategory || null;
|
|
489
|
+
for (const l of h) {
|
|
490
|
+
const flipped = l.category && lastCat && l.category !== lastCat;
|
|
491
|
+
lines.push(`${sast(l.created_at)} ${l.status}${l.category ? ` / ${l.category}` : ""}${flipped ? ` ⚠ CATEGORY MOVED ${lastCat} → ${l.category}` : ""}${l.reason ? ` (${l.reason})` : ""}`);
|
|
492
|
+
if (l.category) lastCat = l.category;
|
|
493
|
+
}
|
|
494
|
+
return lines;
|
|
495
|
+
};
|
|
496
|
+
if (rows.length) console.log(`${rows.length} submission${rows.length === 1 ? "" : "s"}${opts.failed ? " (failed only)" : ""}, newest first (SAST):`);
|
|
497
|
+
const named = new Set();
|
|
452
498
|
for (const a of rows) {
|
|
453
499
|
const mark = a.outcome === "submitted" ? "✓" : "✗";
|
|
454
500
|
const who = a.source ? ` via ${a.source}` : "";
|
|
455
501
|
console.log(`\n ${mark} ${sast(a.created_at)} ${a.template_name || "(unnamed)"}${a.category ? ` [${a.category}]` : ""}${who}`);
|
|
456
502
|
if (a.outcome === "submitted") {
|
|
457
503
|
console.log(` submitted to Meta — id ${a.meta_template_id || "?"}, status at submit ${a.meta_status || "?"}`);
|
|
504
|
+
const hist = describeHistory(a.template_name, a.category);
|
|
505
|
+
named.add(a.template_name);
|
|
506
|
+
if (hist.length) for (const line of hist) console.log(` then: ${line}`);
|
|
507
|
+
else console.log(` no status webhook from Meta recorded yet (still ${a.meta_status || "PENDING"} as far as FlowIQ knows: flowiq templates status ${orgId} --live --name ${a.template_name})`);
|
|
458
508
|
} else {
|
|
459
509
|
console.log(` FAILED (HTTP ${a.http_status ?? "?"}) ${a.error || ""}`);
|
|
460
510
|
if (a.message && a.message !== a.error) console.log(` ${a.message}`);
|
|
461
511
|
if (a.meta_error?.error_user_msg && a.meta_error.error_user_msg !== a.message) console.log(` Meta: ${a.meta_error.error_user_msg}`);
|
|
462
512
|
}
|
|
463
513
|
}
|
|
464
|
-
|
|
514
|
+
// Templates with Meta history but no submission row (submitted before the
|
|
515
|
+
// ledger existed, or from Meta's own tools): still worth showing when asked
|
|
516
|
+
// for by name, or when nothing else matched.
|
|
517
|
+
const orphan = [...new Set(logs.map((l) => l.template_name))].filter((n) => !named.has(n));
|
|
518
|
+
if (orphan.length && (opts.name || !rows.length)) {
|
|
519
|
+
console.log(`\nMeta status history with no submission row (older than the ledger, or submitted outside FlowIQ):`);
|
|
520
|
+
for (const n of orphan.slice(0, 20)) {
|
|
521
|
+
console.log(`\n ${n}`);
|
|
522
|
+
for (const line of describeHistory(n, null)) console.log(` ${line}`);
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
if (rows.length) console.log(`\nA failed row is the reason the template is not in \`templates status\` — fix what the message names and submit again.`);
|
|
465
526
|
}
|