conduyt 1.61.0 → 1.62.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 +13 -3
- package/dist/board-settings.js +6 -1
- package/dist/client.js +39 -14
- package/dist/index.js +318 -5
- package/dist/pipeline-settings.js +155 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -37,10 +37,20 @@ conduyt deals list --pipeline <id> # list deals
|
|
|
37
37
|
conduyt deals list --health-summary --pipeline <id> # Pipeline health strip for the filtered set (totalOpenDeals, atRiskValue, checks[]); add --health-check stale --health-limit 20 for one check's deals, --health-cursor <nextCursor> to page, --health-rows-only for just the page
|
|
38
38
|
conduyt deals health --pipeline <id> --check needs_action # GET /deals/inspection: the six checks over open deals; --check adds its deals, --cursor/--offset pages
|
|
39
39
|
conduyt deals card-fields set value,contact,custom:next_contact_at # the kanban card fields (1-8, built-ins or custom:<fieldKey>); `card-fields get` reads them
|
|
40
|
-
conduyt pipelines stage-rules set <pipelineId> <stageId> --required-fields contactId,custom:loan_amount --required-documents 2 # what a deal needs to enter the stage; other stages untouched; `stage-rules get [pipelineId] [stageId]` reads
|
|
40
|
+
conduyt pipelines stage-rules set <pipelineId> <stageId> --required-fields contactId,custom:loan_amount --required-documents 2 [--lost-reason-allow-other true] # what a deal needs to enter the stage; other stages untouched; `stage-rules get [pipelineId] [stageId]` reads
|
|
41
41
|
conduyt deals bulk-update --file updates.json # update up to 100 deals at once ([{id, stageId, value, ...}]); per-item results, exit 1 if any failed
|
|
42
|
-
conduyt pipelines # list pipelines and stages
|
|
43
|
-
conduyt pipelines
|
|
42
|
+
conduyt pipelines # list pipelines and stages (each carries color, automationOnly, sortOrder)
|
|
43
|
+
conduyt pipelines list --archived # the archived pipelines (owner / admin key): name, archivedName, openDeals, stageCount
|
|
44
|
+
conduyt pipelines archive <id> --move-open-deals-to <pipelineId|none> [--expected-settings-revision N] # archive + move the open deals in one transaction; refusals print their code (stale_settings_revision, target_not_open, dpp_post_close, archive_too_large, target_archived, intake_target, pipeline_archived) and exit 1
|
|
45
|
+
conduyt pipelines settings-revision # the account settingsRevision to pass as --expected-settings-revision to archive / delete-stage (409 stale_settings_revision when settings changed since)
|
|
46
|
+
conduyt pipelines restore <id> # bring an archived pipeline back (last in the menu, never the default; 409 name_taken)
|
|
47
|
+
conduyt pipelines reorder --order id1,id2 --expected-revision id1,id2 # board-menu order in one transaction (409 order_changed prints the current revision); `reorder-stages <pipelineId>` does the same for a pipeline's columns
|
|
48
|
+
conduyt pipelines delete-stage <pipelineId> <stageId> [--move-to <stageId>] [--expected-settings-revision N] # move the live deals to another stage and delete this one; a stale revision is 409 stale_settings_revision
|
|
49
|
+
conduyt pipelines rot-days set <pipelineId> 21 # days without activity (1-90) before a deal reads "Stale in stage"; `rot-days get [pipelineId]` reads
|
|
50
|
+
conduyt status-metadata list --stage-id <id> # the status codes + buckets attached to stages; `get | create | update | delete | import` (update / delete take --expected-updated-at; 409 metadata_changed)
|
|
51
|
+
conduyt status-metadata import --file rows.json --mode replace # set-based import (max 1000; an item key outside stageId, code, bucket, lifecycleStage, dripEligible, dripTrackName, isTerminal, notes is refused before any request); per-item errors print and exit 1; `--mode replace` with no items is refused unless `--confirm-empty-replace` (it deletes every row). Timeouts: archive 75 s, import and the Mailchimp write / action commands 60 s; on a timeout the server may have applied it, so read the state first
|
|
52
|
+
conduyt integrations mailchimp settings # the Mailchimp audience sync (API key scope integrations); `set | audiences | push | retry-unsubscribes | reconcile-statuses [--restart] | confirm-reconciliation`. Connecting is browser-only (OAuth): do it in the app
|
|
53
|
+
conduyt pipelines update <id> --automation-only true # only automations, API keys and owners / admins move or edit its cards (owner / admin key); also --color <palette hex> and --sort-order
|
|
44
54
|
conduyt search "acme corp" # search across the CRM
|
|
45
55
|
conduyt insights summary # run an AI insight query
|
|
46
56
|
conduyt insights saved_report --report "Lead Activity" --period last_7_days # run any saved report as a tool
|
package/dist/board-settings.js
CHANGED
|
@@ -11,7 +11,7 @@ export const MAX_STAGE_REQUIRED_FIELDS = 25;
|
|
|
11
11
|
export const MAX_STAGE_REQUIRED_DOCUMENTS = 20;
|
|
12
12
|
export const MAX_LOST_REASON_OPTIONS = 50;
|
|
13
13
|
const CUSTOM_FIELD_RE = /^custom:[a-zA-Z_][a-zA-Z0-9_]*$/;
|
|
14
|
-
export const RULE_KEYS = ["requiredFields", "requiredDocuments", "lostReasonLabel", "lostReasonOptions"];
|
|
14
|
+
export const RULE_KEYS = ["requiredFields", "requiredDocuments", "lostReasonLabel", "lostReasonOptions", "lostReasonAllowOther"];
|
|
15
15
|
const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
16
16
|
/** "a,b,custom:x" → ["a","b","custom:x"]; blank items are dropped, an all-blank value is an empty list */
|
|
17
17
|
export function splitList(raw) {
|
|
@@ -64,6 +64,11 @@ export function validateRuleChange(raw) {
|
|
|
64
64
|
throw new Error("lostReasonLabel must be 1-60 characters.");
|
|
65
65
|
out[k] = t;
|
|
66
66
|
}
|
|
67
|
+
else if (k === "lostReasonAllowOther") {
|
|
68
|
+
if (typeof v !== "boolean")
|
|
69
|
+
throw new Error("lostReasonAllowOther must be true or false.");
|
|
70
|
+
out[k] = v;
|
|
71
|
+
}
|
|
67
72
|
else {
|
|
68
73
|
if (!Array.isArray(v) || v.some((o) => typeof o !== "string"))
|
|
69
74
|
throw new Error("lostReasonOptions must be a list of strings.");
|
package/dist/client.js
CHANGED
|
@@ -1,4 +1,12 @@
|
|
|
1
1
|
import { requireAuth } from "./config.js";
|
|
2
|
+
/** A deadline hit (only when the call set one) is "the server may have applied it", for every method: read the state first. */
|
|
3
|
+
function ambiguousTimeout(err, method, path, timeoutMs, what) {
|
|
4
|
+
const name = err?.name;
|
|
5
|
+
if (timeoutMs !== undefined && (name === "TimeoutError" || name === "AbortError")) {
|
|
6
|
+
return new Error(`Conduyt API timeout: ${what} within ${timeoutMs / 1000}s for ${method} ${path}. The server may have applied it: read the current state before repeating it.`);
|
|
7
|
+
}
|
|
8
|
+
return err;
|
|
9
|
+
}
|
|
2
10
|
export class ConduytClient {
|
|
3
11
|
baseUrl;
|
|
4
12
|
apiKey;
|
|
@@ -7,17 +15,34 @@ export class ConduytClient {
|
|
|
7
15
|
this.baseUrl = cfg.apiUrl.replace(/\/+$/, "");
|
|
8
16
|
this.apiKey = cfg.apiKey;
|
|
9
17
|
}
|
|
10
|
-
|
|
18
|
+
/** timeoutMs: a per-call deadline for the routes whose server budget is long (archive 75 s, Mailchimp admin and
|
|
19
|
+
* status-metadata import 60 s). Without it the request has no client-side deadline. A call that hits it may still have
|
|
20
|
+
* been applied by the server, and the error says so. */
|
|
21
|
+
async request(method, path, body, opts) {
|
|
11
22
|
const url = `${this.baseUrl}${path.startsWith("/") ? path : `/${path}`}`;
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
23
|
+
let res;
|
|
24
|
+
try {
|
|
25
|
+
res = await fetch(url, {
|
|
26
|
+
method,
|
|
27
|
+
headers: {
|
|
28
|
+
Authorization: `Bearer ${this.apiKey}`,
|
|
29
|
+
"Content-Type": "application/json",
|
|
30
|
+
},
|
|
31
|
+
body: body !== undefined ? JSON.stringify(body) : undefined,
|
|
32
|
+
...(opts?.timeoutMs !== undefined ? { signal: AbortSignal.timeout(opts.timeoutMs) } : {}),
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
catch (err) {
|
|
36
|
+
throw ambiguousTimeout(err, method, path, opts?.timeoutMs, "no answer");
|
|
37
|
+
}
|
|
38
|
+
// the headers can arrive and the body then stall until the deadline: the same ambiguity, not a raw TimeoutError
|
|
39
|
+
let text;
|
|
40
|
+
try {
|
|
41
|
+
text = await res.text();
|
|
42
|
+
}
|
|
43
|
+
catch (err) {
|
|
44
|
+
throw ambiguousTimeout(err, method, path, opts?.timeoutMs, "the response body did not finish");
|
|
45
|
+
}
|
|
21
46
|
const json = text ? safeParse(text) : null;
|
|
22
47
|
if (!res.ok) {
|
|
23
48
|
// Preserve structured non-2xx bodies: several endpoints return the data
|
|
@@ -44,14 +69,14 @@ export class ConduytClient {
|
|
|
44
69
|
get(path) {
|
|
45
70
|
return this.request("GET", path);
|
|
46
71
|
}
|
|
47
|
-
post(path, body) {
|
|
48
|
-
return this.request("POST", path, body);
|
|
72
|
+
post(path, body, opts) {
|
|
73
|
+
return this.request("POST", path, body, opts);
|
|
49
74
|
}
|
|
50
75
|
patch(path, body) {
|
|
51
76
|
return this.request("PATCH", path, body);
|
|
52
77
|
}
|
|
53
|
-
put(path, body) {
|
|
54
|
-
return this.request("PUT", path, body);
|
|
78
|
+
put(path, body, opts) {
|
|
79
|
+
return this.request("PUT", path, body, opts);
|
|
55
80
|
}
|
|
56
81
|
del(path) {
|
|
57
82
|
return this.request("DELETE", path);
|
package/dist/index.js
CHANGED
|
@@ -6,6 +6,7 @@ import { dirname, join } from "node:path";
|
|
|
6
6
|
import { Command } from "commander";
|
|
7
7
|
import { ConduytClient, buildQuery } from "./client.js";
|
|
8
8
|
import { splitList, stageRulePatch, validateCardFields, validateRuleChange } from "./board-settings.js";
|
|
9
|
+
import { ARCHIVE_PIPELINE_TIMEOUT_MS, MAILCHIMP_ADMIN_TIMEOUT_MS, STATUS_METADATA_IMPORT_TIMEOUT_MS, PIPELINE_COLORS, boolFlag, intFlag, isoDate, lifecycleStage as lifecycleStageArg, MAX_PIPELINE_ROT_DAYS, MIN_PIPELINE_ROT_DAYS, pipelineColor, settingsRevision, slug as slugArg, uuid as uuidOf, uuidList, validateImportItems, validateStatusMetadataBody } from "./pipeline-settings.js";
|
|
9
10
|
import { saveConfig, resolveConfig, configPath } from "./config.js";
|
|
10
11
|
import { print, fail, unwrap } from "./output.js";
|
|
11
12
|
// Exit cleanly when a downstream pipe closes early (e.g. `conduyt deals list |
|
|
@@ -758,18 +759,22 @@ const pipelines = program
|
|
|
758
759
|
.action(run(async (client) => client.get("/api/v1/pipelines")));
|
|
759
760
|
pipelines
|
|
760
761
|
.command("list")
|
|
761
|
-
.description("List pipelines and their stages")
|
|
762
|
-
.
|
|
762
|
+
.description("List pipelines and their stages (each pipeline carries color, automationOnly, sortOrder). --archived lists the ARCHIVED pipelines instead (owner / admin key): id, name (the pre-archive name), archivedName, color, archivedAt, openDeals, stageCount")
|
|
763
|
+
.option("--archived", "list the archived pipelines (GET /pipelines?archived=true) instead of the active ones")
|
|
764
|
+
.action(run(async (client, opts) => client.get(opts.archived ? "/api/v1/pipelines?archived=true" : "/api/v1/pipelines")));
|
|
763
765
|
pipelines
|
|
764
766
|
.command("create")
|
|
765
767
|
.description("Create a pipeline with stages")
|
|
766
768
|
.option("--name <name>", "pipeline name")
|
|
767
769
|
.option("--stages <json>", "JSON array of stages, e.g. '[{\"name\":\"Lead\"},{\"name\":\"Won\",\"isWon\":true}]'")
|
|
770
|
+
.option("--color <hex>", `pipeline colour, one of the palette: ${PIPELINE_COLORS.join(" ")}`)
|
|
768
771
|
.option("--json <json>", "full JSON body, merged over the flags")
|
|
769
772
|
.action(run(async (client, opts) => {
|
|
770
773
|
const body = {};
|
|
771
774
|
if (opts.name !== undefined)
|
|
772
775
|
body.name = opts.name;
|
|
776
|
+
if (opts.color !== undefined)
|
|
777
|
+
body.color = pipelineColor(opts.color);
|
|
773
778
|
if (opts.stages !== undefined) {
|
|
774
779
|
if (opts.stages.trim() === "")
|
|
775
780
|
throw new Error("--stages must be valid JSON (got an empty string).");
|
|
@@ -803,6 +808,7 @@ pipelines
|
|
|
803
808
|
.option("--is-default <bool>", "true|false: the account's default pipeline")
|
|
804
809
|
.option("--automation-only <bool>", "true|false: only automations, API keys and owners / admins move or edit its cards")
|
|
805
810
|
.option("--sort-order <n>", "position among the pipelines (integer)")
|
|
811
|
+
.option("--color <hex>", `pipeline colour, one of the palette: ${PIPELINE_COLORS.join(" ")}`)
|
|
806
812
|
.option("--json <json>", "full JSON body, merged over the flags")
|
|
807
813
|
.action(run(async (client, id, opts) => {
|
|
808
814
|
assertUuid(id, "pipeline id");
|
|
@@ -841,6 +847,8 @@ pipelines
|
|
|
841
847
|
throw new Error("--sort-order must be an integer.");
|
|
842
848
|
body.sortOrder = n;
|
|
843
849
|
}
|
|
850
|
+
if (opts.color !== undefined && unlessJson("color"))
|
|
851
|
+
body.color = pipelineColor(opts.color);
|
|
844
852
|
Object.assign(body, fromJson);
|
|
845
853
|
if (Object.keys(body).length === 0)
|
|
846
854
|
throw new Error("Nothing to update. Pass at least one field flag or --json.");
|
|
@@ -853,7 +861,7 @@ const stageRules = pipelines
|
|
|
853
861
|
.description("Per-stage rules (settings.pipelineStageRules): the fields and documents a deal needs before it may enter a stage");
|
|
854
862
|
stageRules
|
|
855
863
|
.command("get [pipelineId] [stageId]")
|
|
856
|
-
.description("Read the stage rules as { pipelineId: { stageId: { requiredFields, requiredDocuments, lostReasonLabel, lostReasonOptions } } }, for everything, one pipeline, or one stage")
|
|
864
|
+
.description("Read the stage rules as { pipelineId: { stageId: { requiredFields, requiredDocuments, lostReasonLabel, lostReasonOptions, lostReasonAllowOther } } }, for everything, one pipeline, or one stage")
|
|
857
865
|
.action(run(async (client, pipelineId, stageId) => {
|
|
858
866
|
if (pipelineId !== undefined)
|
|
859
867
|
assertUuid(pipelineId, "pipeline id");
|
|
@@ -876,7 +884,8 @@ stageRules
|
|
|
876
884
|
.option("--required-documents <n>", "integer 0-20")
|
|
877
885
|
.option("--lost-reason-label <text>", "label of the stage's lost-reason prompt (1-60 chars)")
|
|
878
886
|
.option("--lost-reason-options <list>", "comma-separated dropdown options of the lost-reason prompt (max 50; empty clears)")
|
|
879
|
-
.option("--
|
|
887
|
+
.option("--lost-reason-allow-other <bool>", "true|false: the rep may also pick \"Other\" and type the reason (stored as the reason text; takes effect while the stage has lost-reason options)")
|
|
888
|
+
.option("--json <json>", "the rule fields as a JSON object ({requiredFields, requiredDocuments, lostReasonLabel, lostReasonOptions, lostReasonAllowOther}), merged over the flags")
|
|
880
889
|
.action(run(async (client, pipelineId, stageId, opts) => {
|
|
881
890
|
assertUuid(pipelineId, "pipeline id");
|
|
882
891
|
assertUuid(stageId, "stage id");
|
|
@@ -891,11 +900,13 @@ stageRules
|
|
|
891
900
|
raw.lostReasonLabel = opts.lostReasonLabel;
|
|
892
901
|
if (opts.lostReasonOptions !== undefined)
|
|
893
902
|
raw.lostReasonOptions = splitList(opts.lostReasonOptions);
|
|
903
|
+
if (opts.lostReasonAllowOther !== undefined)
|
|
904
|
+
raw.lostReasonAllowOther = boolFlag(opts.lostReasonAllowOther, "--lost-reason-allow-other");
|
|
894
905
|
if (opts.json !== undefined)
|
|
895
906
|
Object.assign(raw, jsonArg(opts.json, "--json"));
|
|
896
907
|
const change = validateRuleChange(raw);
|
|
897
908
|
if (Object.keys(change).length === 0)
|
|
898
|
-
throw new Error("Nothing to set. Pass --required-fields, --required-documents, --lost-reason-label, --lost-reason-options or --json.");
|
|
909
|
+
throw new Error("Nothing to set. Pass --required-fields, --required-documents, --lost-reason-label, --lost-reason-options, --lost-reason-allow-other or --json.");
|
|
899
910
|
return patchGeneralSettingsMerged(client, (settings) => stageRulePatch(settings, pipelineId, stageId, change));
|
|
900
911
|
}));
|
|
901
912
|
// (system stages 2026-09-24) tri-surface parity: the stage flags the API takes on PATCH /pipelines/:id/stages/:stageId,
|
|
@@ -951,6 +962,245 @@ pipelines
|
|
|
951
962
|
throw new Error("Nothing to update. Pass at least one field flag or --json.");
|
|
952
963
|
return client.patch(`/api/v1/pipelines/${encodeURIComponent(pipelineId)}/stages/${encodeURIComponent(stageId)}`, body);
|
|
953
964
|
}));
|
|
965
|
+
// (pipeline settings 10-08) archive / restore / reorder, stage delete with a move, the stale-in-stage days.
|
|
966
|
+
pipelines
|
|
967
|
+
.command("archive <id>")
|
|
968
|
+
.description("Archive a pipeline (owner / admin key): renamed with the archived prefix, never deleted; its closed deals stay as history and `pipelines restore` brings it back. Every OPEN deal moves in the same transaction to --move-open-deals-to's first stage through the normal stage-entry rules; any refusal aborts all of it. Pass --move-open-deals-to none only when there are no open deals. Waits up to 75 s; if it times out the archive may have committed, so run `pipelines list` / `pipelines list --archived` before retrying. The default pipeline cannot be archived. Refusal codes are printed with the error and the command exits 1: stale_settings_revision, target_not_open, dpp_post_close, archive_too_large, target_archived, intake_target, pipeline_archived, open_deals, default_pipeline, stage_requirements, archive_raced, pipeline_automation_only. An already-archived pipeline answers { archived: true, alreadyArchived: true }")
|
|
969
|
+
.requiredOption("--move-open-deals-to <pipelineId|none>", "the active pipeline the open deals move to (its first stage must be open), or none when the pipeline has no open deals")
|
|
970
|
+
.option("--expected-settings-revision <n>", "the settingsRevision from `pipelines settings-revision`; refused 409 stale_settings_revision when settings changed since")
|
|
971
|
+
.action(run(async (client, id, opts) => {
|
|
972
|
+
const pid = uuidOf(id, "pipeline id");
|
|
973
|
+
const target = opts.moveOpenDealsTo.trim().toLowerCase();
|
|
974
|
+
const moveOpenDealsTo = target === "none" ? null : uuidOf(opts.moveOpenDealsTo, "--move-open-deals-to");
|
|
975
|
+
const body = { moveOpenDealsTo };
|
|
976
|
+
if (opts.expectedSettingsRevision !== undefined)
|
|
977
|
+
body.expectedSettingsRevision = settingsRevision(opts.expectedSettingsRevision);
|
|
978
|
+
return client.post(`/api/v1/pipelines/${pid}/archive`, body, { timeoutMs: ARCHIVE_PIPELINE_TIMEOUT_MS });
|
|
979
|
+
}));
|
|
980
|
+
pipelines
|
|
981
|
+
.command("restore <id>")
|
|
982
|
+
.description("Restore an ARCHIVED pipeline (owner / admin key): it loses the archived prefix, goes last in the board menu and is never the default; its stages and closed deals come back with it. 404 when it is not an archived pipeline of this account; 409 name_taken when an active pipeline has its name (rename that one first); 403 PLAN_LIMIT_REACHED when the plan's pipeline limit is full")
|
|
983
|
+
.action(run(async (client, id) => client.post(`/api/v1/pipelines/${uuidOf(id, "pipeline id")}/restore`, {})));
|
|
984
|
+
pipelines
|
|
985
|
+
.command("reorder")
|
|
986
|
+
.description("Set the board-menu order of the active pipelines in one transaction (owner / admin key). --order must list EVERY active pipeline exactly once; --expected-revision is the order you last read (the pipeline ids by position, comma-joined). 409 order_changed (with the current revision) when the order moved since; nothing is written. Prints { order, revision }")
|
|
987
|
+
.requiredOption("--order <ids>", "comma-separated pipeline ids in the new order")
|
|
988
|
+
.requiredOption("--expected-revision <revision>", "the current order: the pipeline ids by position, comma-joined")
|
|
989
|
+
.action(run(async (client, opts) => {
|
|
990
|
+
const order = uuidList(opts.order, "--order");
|
|
991
|
+
if (opts.expectedRevision.trim() === "")
|
|
992
|
+
throw new Error("--expected-revision must be the current order (the pipeline ids by position, comma-joined).");
|
|
993
|
+
return client.post("/api/v1/pipelines/reorder", { order, expectedRevision: opts.expectedRevision.trim().toLowerCase() });
|
|
994
|
+
}));
|
|
995
|
+
pipelines
|
|
996
|
+
.command("reorder-stages <pipelineId>")
|
|
997
|
+
.description("Set a pipeline's column order in one transaction (owner / admin key). --order must list EVERY stage of the pipeline exactly once and may not put a system holding stage first that was not first; --expected-revision is the stage ids by position, comma-joined. 409 order_changed (with the current revision) when it moved since, 409 pipeline_archived when the pipeline was archived meanwhile. Prints { order, revision }")
|
|
998
|
+
.requiredOption("--order <ids>", "comma-separated stage ids in the new order")
|
|
999
|
+
.requiredOption("--expected-revision <revision>", "the current order: the stage ids by position, comma-joined")
|
|
1000
|
+
.action(run(async (client, pipelineId, opts) => {
|
|
1001
|
+
const pid = uuidOf(pipelineId, "pipeline id");
|
|
1002
|
+
const order = uuidList(opts.order, "--order");
|
|
1003
|
+
if (opts.expectedRevision.trim() === "")
|
|
1004
|
+
throw new Error("--expected-revision must be the current order (the stage ids by position, comma-joined).");
|
|
1005
|
+
return client.post(`/api/v1/pipelines/${pid}/stages/reorder`, { order, expectedRevision: opts.expectedRevision.trim().toLowerCase() });
|
|
1006
|
+
}));
|
|
1007
|
+
pipelines
|
|
1008
|
+
.command("delete-stage <pipelineId> <stageId>")
|
|
1009
|
+
.description("Delete a stage (owner / admin key). Without --move-to the stage must have no deals; with it the live deals move to another stage of the SAME pipeline (same won / lost setting, not a system stage) and the stage is deleted in one transaction. A stage a soft-deleted deal still points at is refused. With --expected-settings-revision the answer is { id, deleted: true, settingsRevision }. Refusals exit 1 with the code printed: stale_settings_revision, pipeline_archived, intake_target (other 409s name the cause)")
|
|
1010
|
+
.option("--move-to <stageId>", "another stage of the same pipeline the live deals move to")
|
|
1011
|
+
.option("--expected-settings-revision <n>", "the settingsRevision from `pipelines settings-revision`; refused 409 stale_settings_revision when settings changed since")
|
|
1012
|
+
.action(run(async (client, pipelineId, stageId, opts) => {
|
|
1013
|
+
const qs = new URLSearchParams();
|
|
1014
|
+
if (opts.moveTo !== undefined)
|
|
1015
|
+
qs.set("move_to", uuidOf(opts.moveTo, "--move-to"));
|
|
1016
|
+
if (opts.expectedSettingsRevision !== undefined)
|
|
1017
|
+
qs.set("expected_settings_revision", settingsRevision(opts.expectedSettingsRevision));
|
|
1018
|
+
const q = qs.toString();
|
|
1019
|
+
const res = await client.del(`/api/v1/pipelines/${uuidOf(pipelineId, "pipeline id")}/stages/${uuidOf(stageId, "stage id")}${q ? `?${q}` : ""}`);
|
|
1020
|
+
return res ?? { data: { deleted: true, id: stageId } };
|
|
1021
|
+
}));
|
|
1022
|
+
pipelines
|
|
1023
|
+
.command("settings-revision")
|
|
1024
|
+
.description("The account settingsRevision (plus the stored stage rules and rot days): pass it as --expected-settings-revision to `pipelines archive` / `pipelines delete-stage` so they are refused (409 stale_settings_revision) when settings changed after you read it. Read it right before the mutation")
|
|
1025
|
+
.action(run(async (client) => {
|
|
1026
|
+
const res = (await client.get("/api/v1/settings"));
|
|
1027
|
+
const d = res?.data ?? {};
|
|
1028
|
+
return { data: { settingsRevision: typeof d.settingsRevision === "string" ? d.settingsRevision : null, pipelineStageRules: d.pipelineStageRules ?? null, pipelineRotDays: d.pipelineRotDays ?? null } };
|
|
1029
|
+
}));
|
|
1030
|
+
// settings.pipelineRotDays: days without activity before a deal reads "Stale in stage" (per pipeline, 1-90)
|
|
1031
|
+
const rotDays = pipelines
|
|
1032
|
+
.command("rot-days")
|
|
1033
|
+
.description("Stale-in-stage threshold per pipeline (settings.pipelineRotDays): days without activity (1-90) before a deal reads \"Stale in stage\"");
|
|
1034
|
+
rotDays
|
|
1035
|
+
.command("get [pipelineId]")
|
|
1036
|
+
.description("Read the thresholds as { pipelineId: days }, for every pipeline that has one or just the one given")
|
|
1037
|
+
.action(run(async (client, pipelineId) => {
|
|
1038
|
+
const pid = pipelineId === undefined ? undefined : uuidOf(pipelineId, "pipeline id");
|
|
1039
|
+
const res = (await client.get("/api/v1/settings"));
|
|
1040
|
+
const all = res?.data?.pipelineRotDays && typeof res.data.pipelineRotDays === "object" ? res.data.pipelineRotDays : {};
|
|
1041
|
+
return { data: { pipelineRotDays: pid === undefined ? all : all[pid] !== undefined ? { [pid]: all[pid] } : {} } };
|
|
1042
|
+
}));
|
|
1043
|
+
rotDays
|
|
1044
|
+
.command("set <pipelineId> <days>")
|
|
1045
|
+
.description(`Set one pipeline's threshold (admin key, settings:edit): an integer ${MIN_PIPELINE_ROT_DAYS}-${MAX_PIPELINE_ROT_DAYS}. Only that pipeline changes. The pipeline must be an ACTIVE pipeline of the account (422 for an unknown or archived one). Saved with the settings revision; a 409 is re-read and retried once`)
|
|
1046
|
+
.action(run(async (client, pipelineId, days) => {
|
|
1047
|
+
const pid = uuidOf(pipelineId, "pipeline id");
|
|
1048
|
+
const n = intFlag(days, "days", MIN_PIPELINE_ROT_DAYS, MAX_PIPELINE_ROT_DAYS);
|
|
1049
|
+
return patchGeneralSettingsMerged(client, () => ({ pipelineRotDays: { [pid]: n } }));
|
|
1050
|
+
}));
|
|
1051
|
+
// ---- status metadata (app 10-08): the status taxonomy rows attached to a pipeline stage ----
|
|
1052
|
+
const statusMetadata = program
|
|
1053
|
+
.command("status-metadata")
|
|
1054
|
+
.description("Status metadata: the status codes and buckets attached to pipeline stages (one row per stage and code). update / delete take --expected-updated-at (the row's updatedAt as read): 409 metadata_changed (with the current row) when it changed or moved since, 404 status_metadata_not_found");
|
|
1055
|
+
statusMetadata
|
|
1056
|
+
.command("list")
|
|
1057
|
+
.description("List the rows (settings:view); updatedAt is the version for --expected-updated-at")
|
|
1058
|
+
.option("--stage-id <id>", "only this stage's rows")
|
|
1059
|
+
.option("--bucket <bucket>", "only this bucket")
|
|
1060
|
+
.option("--code <code>", "only this code")
|
|
1061
|
+
.action(run(async (client, opts) => client.get(`/api/v1/status-metadata${buildQuery({ stageId: opts.stageId === undefined ? undefined : uuidOf(opts.stageId, "--stage-id"), bucket: opts.bucket, code: opts.code })}`)));
|
|
1062
|
+
statusMetadata
|
|
1063
|
+
.command("get <id>")
|
|
1064
|
+
.description("One row with its stage and drip track")
|
|
1065
|
+
.action(run(async (client, id) => client.get(`/api/v1/status-metadata/${uuidOf(id, "id")}`)));
|
|
1066
|
+
/** the row fields shared by create and update; "null" clears a nullable one */
|
|
1067
|
+
function statusMetadataFields(opts) {
|
|
1068
|
+
const body = {};
|
|
1069
|
+
if (opts.stageId !== undefined)
|
|
1070
|
+
body.stageId = uuidOf(opts.stageId, "--stage-id");
|
|
1071
|
+
if (opts.code !== undefined)
|
|
1072
|
+
body.code = slugArg(opts.code, "--code");
|
|
1073
|
+
if (opts.bucket !== undefined)
|
|
1074
|
+
body.bucket = slugArg(opts.bucket, "--bucket");
|
|
1075
|
+
if (opts.lifecycleStage !== undefined)
|
|
1076
|
+
body.lifecycleStage = opts.lifecycleStage === "null" ? null : lifecycleStageArg(opts.lifecycleStage);
|
|
1077
|
+
if (opts.dripEligible !== undefined)
|
|
1078
|
+
body.dripEligible = boolFlag(opts.dripEligible, "--drip-eligible");
|
|
1079
|
+
if (opts.dripTrackId !== undefined)
|
|
1080
|
+
body.dripTrackId = opts.dripTrackId === "null" ? null : uuidOf(opts.dripTrackId, "--drip-track-id");
|
|
1081
|
+
if (opts.isTerminal !== undefined)
|
|
1082
|
+
body.isTerminal = boolFlag(opts.isTerminal, "--is-terminal");
|
|
1083
|
+
if (opts.notes !== undefined) {
|
|
1084
|
+
if (opts.notes !== "null" && opts.notes.length > 5000)
|
|
1085
|
+
throw new Error("--notes must be at most 5000 characters.");
|
|
1086
|
+
body.notes = opts.notes === "null" ? null : opts.notes;
|
|
1087
|
+
}
|
|
1088
|
+
return body;
|
|
1089
|
+
}
|
|
1090
|
+
statusMetadata
|
|
1091
|
+
.command("create")
|
|
1092
|
+
.description("Create a row (settings:edit, active billing). --code and --bucket are lowercase slugs (letters, numbers, underscores, max 80); one row per stage and code (a duplicate is a 409)")
|
|
1093
|
+
.requiredOption("--stage-id <id>", "pipeline stage the row attaches to")
|
|
1094
|
+
.requiredOption("--code <slug>", "status code, e.g. appt_set")
|
|
1095
|
+
.requiredOption("--bucket <slug>", "bucket, e.g. working")
|
|
1096
|
+
.option("--lifecycle-stage <stage>", `one of ${["pre_sale", "sale", "underwriting", "active", "resolution", "terminal"].join(", ")}, or null`)
|
|
1097
|
+
.option("--drip-eligible <bool>", "true|false")
|
|
1098
|
+
.option("--drip-track-id <id>", "drip track id, or null")
|
|
1099
|
+
.option("--is-terminal <bool>", "true|false")
|
|
1100
|
+
.option("--notes <text>", "free text (max 5000), or null")
|
|
1101
|
+
.option("--json <json>", "full JSON body, merged over the flags")
|
|
1102
|
+
.action(run(async (client, opts) => {
|
|
1103
|
+
const body = statusMetadataFields(opts);
|
|
1104
|
+
if (opts.json !== undefined)
|
|
1105
|
+
Object.assign(body, jsonArg(opts.json, "--json"));
|
|
1106
|
+
// flags + --json together, against the exact field list and types: the API ignores a misspelled key and applies the rest
|
|
1107
|
+
return client.post("/api/v1/status-metadata", validateStatusMetadataBody(body, "create"));
|
|
1108
|
+
}));
|
|
1109
|
+
statusMetadata
|
|
1110
|
+
.command("update <id>")
|
|
1111
|
+
.description("Update a row (settings:edit, active billing): only the fields you pass change. --expected-updated-at refuses the update when the row was changed or moved since you read it (409 metadata_changed, the current row is in the error)")
|
|
1112
|
+
.option("--expected-updated-at <iso>", "the row's updatedAt as you read it")
|
|
1113
|
+
.option("--stage-id <id>", "move the row to another stage")
|
|
1114
|
+
.option("--code <slug>", "status code")
|
|
1115
|
+
.option("--bucket <slug>", "bucket")
|
|
1116
|
+
.option("--lifecycle-stage <stage>", "lifecycle stage, or null")
|
|
1117
|
+
.option("--drip-eligible <bool>", "true|false")
|
|
1118
|
+
.option("--drip-track-id <id>", "drip track id, or null")
|
|
1119
|
+
.option("--is-terminal <bool>", "true|false")
|
|
1120
|
+
.option("--notes <text>", "free text (max 5000), or null")
|
|
1121
|
+
.option("--json <json>", "full JSON body, merged over the flags")
|
|
1122
|
+
.action(run(async (client, id, opts) => {
|
|
1123
|
+
const rowId = uuidOf(id, "id");
|
|
1124
|
+
const body = statusMetadataFields(opts);
|
|
1125
|
+
if (opts.expectedUpdatedAt !== undefined)
|
|
1126
|
+
body.expectedUpdatedAt = isoDate(opts.expectedUpdatedAt, "--expected-updated-at");
|
|
1127
|
+
if (opts.json !== undefined)
|
|
1128
|
+
Object.assign(body, jsonArg(opts.json, "--json"));
|
|
1129
|
+
validateStatusMetadataBody(body, "update");
|
|
1130
|
+
if (Object.keys(body).filter((k) => k !== "expectedUpdatedAt").length === 0)
|
|
1131
|
+
throw new Error("Nothing to update. Pass at least one field flag or --json.");
|
|
1132
|
+
return client.patch(`/api/v1/status-metadata/${rowId}`, body);
|
|
1133
|
+
}));
|
|
1134
|
+
statusMetadata
|
|
1135
|
+
.command("delete <id>")
|
|
1136
|
+
.description("Delete a row (settings:edit, active billing). --expected-updated-at refuses the delete when the row changed or moved since you read it (409 metadata_changed)")
|
|
1137
|
+
.option("--expected-updated-at <iso>", "the row's updatedAt as you read it")
|
|
1138
|
+
.action(run(async (client, id, opts) => {
|
|
1139
|
+
const rowId = uuidOf(id, "id");
|
|
1140
|
+
const q = opts.expectedUpdatedAt === undefined ? "" : `?expected_updated_at=${encodeURIComponent(isoDate(opts.expectedUpdatedAt, "--expected-updated-at"))}`;
|
|
1141
|
+
const res = await client.del(`/api/v1/status-metadata/${rowId}${q}`);
|
|
1142
|
+
return res ?? { data: { deleted: true, id: rowId } };
|
|
1143
|
+
}));
|
|
1144
|
+
statusMetadata
|
|
1145
|
+
.command("import")
|
|
1146
|
+
.description(`Set-based import (owner / admin key, active billing; max 1000 items) from a JSON array of { stageId, code, bucket, lifecycleStage?, dripEligible?, dripTrackName?, isTerminal?, notes? } via --items or --file. merge (default) upserts the valid items and reports the rest in errors[]; replace replaces the rows of the ACTIVE pipelines and imports nothing if any item is invalid (rows of archived pipelines are kept). With --mode replace and NO items nothing is sent unless --confirm-empty-replace is given (it would delete every row). Prints { imported, skipped, errors } and exits 1 when errors is not empty (the full result is still printed). 409 pipeline_archived when an item names a stage of an archived pipeline`)
|
|
1147
|
+
.option("--mode <mode>", "merge (default) | replace")
|
|
1148
|
+
.option("--items <json>", "the items as a JSON array (or @file)")
|
|
1149
|
+
.option("--file <path>", "read the items JSON array from a file")
|
|
1150
|
+
.option("--confirm-empty-replace", "allow --mode replace with NO items, which deletes every status metadata row of the active pipelines")
|
|
1151
|
+
.action(async (opts) => {
|
|
1152
|
+
try {
|
|
1153
|
+
if (opts.items !== undefined && opts.file !== undefined)
|
|
1154
|
+
throw new Error("Pass either --items or --file, not both.");
|
|
1155
|
+
if (opts.mode !== undefined && opts.mode !== "merge" && opts.mode !== "replace")
|
|
1156
|
+
throw new Error("--mode must be merge or replace.");
|
|
1157
|
+
let raw;
|
|
1158
|
+
if (opts.file !== undefined) {
|
|
1159
|
+
try {
|
|
1160
|
+
raw = readFileSync(opts.file, "utf8");
|
|
1161
|
+
}
|
|
1162
|
+
catch {
|
|
1163
|
+
throw new Error(`--file could not be read: ${opts.file}`);
|
|
1164
|
+
}
|
|
1165
|
+
}
|
|
1166
|
+
else if (opts.items !== undefined) {
|
|
1167
|
+
raw = opts.items.startsWith("@") ? readFileSync(opts.items.slice(1), "utf8") : opts.items;
|
|
1168
|
+
}
|
|
1169
|
+
else {
|
|
1170
|
+
throw new Error("The items are required. Pass --items '<json array>' or --file <path>.");
|
|
1171
|
+
}
|
|
1172
|
+
let parsed;
|
|
1173
|
+
try {
|
|
1174
|
+
parsed = JSON.parse(raw);
|
|
1175
|
+
}
|
|
1176
|
+
catch {
|
|
1177
|
+
throw new Error("The items must be valid JSON.");
|
|
1178
|
+
}
|
|
1179
|
+
const items = validateImportItems(parsed);
|
|
1180
|
+
// checked before any request; the flag is only a local confirmation and is never sent
|
|
1181
|
+
if (opts.mode === "replace" && items.length === 0 && !opts.confirmEmptyReplace) {
|
|
1182
|
+
throw new Error("replace with no items would delete every status metadata row; pass --confirm-empty-replace to do that on purpose");
|
|
1183
|
+
}
|
|
1184
|
+
const client = new ConduytClient();
|
|
1185
|
+
const res = await client.post("/api/v1/status-metadata/import", { ...(opts.mode !== undefined ? { mode: opts.mode } : {}), items }, { timeoutMs: STATUS_METADATA_IMPORT_TIMEOUT_MS });
|
|
1186
|
+
print(res);
|
|
1187
|
+
// a 200 can still carry per-item errors (merge) or a refused replace (imported 0): that is a refusal, exit 1
|
|
1188
|
+
const data = unwrap(res);
|
|
1189
|
+
if (!data || typeof data !== "object" || typeof data.imported !== "number" || !Array.isArray(data.errors)) {
|
|
1190
|
+
process.stderr.write("Error: Unexpected response shape from the API: expected { imported, skipped, errors }.\n");
|
|
1191
|
+
process.exitCode = 1;
|
|
1192
|
+
}
|
|
1193
|
+
else if (data.errors.length > 0) {
|
|
1194
|
+
for (const e of data.errors)
|
|
1195
|
+
process.stderr.write(`Skipped ${String(e?.stageId ?? "?")}: ${String(e?.reason ?? "unknown reason")}\n`);
|
|
1196
|
+
process.stderr.write(`Error: ${data.errors.length} item(s) were not imported (${data.imported} imported).\n`);
|
|
1197
|
+
process.exitCode = 1;
|
|
1198
|
+
}
|
|
1199
|
+
}
|
|
1200
|
+
catch (err) {
|
|
1201
|
+
fail(err);
|
|
1202
|
+
}
|
|
1203
|
+
});
|
|
954
1204
|
// ---- search ----
|
|
955
1205
|
program
|
|
956
1206
|
.command("search <query>")
|
|
@@ -2473,6 +2723,69 @@ wordpressForms
|
|
|
2473
2723
|
.command("revoke <id>")
|
|
2474
2724
|
.description("Revoke an intake address: submissions to it answer 404 from now on. The row is kept (status revoked) for history")
|
|
2475
2725
|
.action(run(async (client, id) => client.del(`/api/v1/integrations/wordpress-forms/intakes/${uuidArg(id, "id")}`)));
|
|
2726
|
+
// Integrations -> Mailchimp (app 10-07/10-08, API key scope `integrations`): the audience sync. The OAuth connect and
|
|
2727
|
+
// callback are browser-only (connect Mailchimp in the app: Settings > Integrations), so there is no `connect` here.
|
|
2728
|
+
const mailchimp = integrations
|
|
2729
|
+
.command("mailchimp")
|
|
2730
|
+
.description("Mailchimp audience sync (API key scope integrations). Connecting is browser-only (OAuth): do it in the app, then configure it here. Errors exit 1 with the server's message and code (404 not connected, 409 revoked: reconnect in the app)");
|
|
2731
|
+
mailchimp
|
|
2732
|
+
.command("settings")
|
|
2733
|
+
.description("The Mailchimp connection: the audience, the source (one smart list or one tag), statusIfNew, unsubscribeSetsOptOut and the sync status (backfill progress, pending pushes, last pushed, last webhook, the last Mailchimp error, statusSweepBlocked). connected: false when there is none")
|
|
2734
|
+
.action(run(async (client) => client.get("/api/v1/integrations/mailchimp/settings")));
|
|
2735
|
+
mailchimp
|
|
2736
|
+
.command("set")
|
|
2737
|
+
.description("Configure the sync (PUT; settings:edit, active billing): only the flags you pass change. A new audience gets Conduyt's webhook and starts the backfill; a new source starts the backfill. --source-type and --source-id go together")
|
|
2738
|
+
.option("--list-id <id>", "Mailchimp audience id (see `audiences`)")
|
|
2739
|
+
.option("--source-type <type>", "smart_list | tag")
|
|
2740
|
+
.option("--source-id <id>", "the smart list or tag UUID")
|
|
2741
|
+
.option("--status-if-new <status>", "subscribed (default) | pending (Mailchimp sends a confirmation email)")
|
|
2742
|
+
.option("--unsubscribe-sets-opt-out <bool>", "true|false (default true): a Mailchimp unsubscribe also opts the contact out of Conduyt email")
|
|
2743
|
+
.action(run(async (client, opts) => {
|
|
2744
|
+
const body = {};
|
|
2745
|
+
if (opts.listId !== undefined) {
|
|
2746
|
+
if (opts.listId.trim() === "")
|
|
2747
|
+
throw new Error("--list-id was provided but is blank.");
|
|
2748
|
+
body.listId = opts.listId.trim();
|
|
2749
|
+
}
|
|
2750
|
+
if ((opts.sourceType === undefined) !== (opts.sourceId === undefined))
|
|
2751
|
+
throw new Error("--source-type and --source-id go together.");
|
|
2752
|
+
if (opts.sourceType !== undefined) {
|
|
2753
|
+
if (opts.sourceType !== "smart_list" && opts.sourceType !== "tag")
|
|
2754
|
+
throw new Error('--source-type must be "smart_list" or "tag".');
|
|
2755
|
+
body.source = { type: opts.sourceType, id: uuidOf(opts.sourceId, "--source-id") };
|
|
2756
|
+
}
|
|
2757
|
+
if (opts.statusIfNew !== undefined) {
|
|
2758
|
+
if (opts.statusIfNew !== "subscribed" && opts.statusIfNew !== "pending")
|
|
2759
|
+
throw new Error('--status-if-new must be "subscribed" or "pending".');
|
|
2760
|
+
body.statusIfNew = opts.statusIfNew;
|
|
2761
|
+
}
|
|
2762
|
+
if (opts.unsubscribeSetsOptOut !== undefined)
|
|
2763
|
+
body.unsubscribeSetsOptOut = boolFlag(opts.unsubscribeSetsOptOut, "--unsubscribe-sets-opt-out");
|
|
2764
|
+
if (Object.keys(body).length === 0)
|
|
2765
|
+
throw new Error("Nothing to set. Pass --list-id, --source-type with --source-id, --status-if-new or --unsubscribe-sets-opt-out.");
|
|
2766
|
+
return client.put("/api/v1/integrations/mailchimp/settings", body, { timeoutMs: MAILCHIMP_ADMIN_TIMEOUT_MS });
|
|
2767
|
+
}));
|
|
2768
|
+
mailchimp
|
|
2769
|
+
.command("audiences")
|
|
2770
|
+
.description("The connected account's audiences: id, name, memberCount (use an id as --list-id)")
|
|
2771
|
+
.action(run(async (client) => client.get("/api/v1/integrations/mailchimp/audiences")));
|
|
2772
|
+
mailchimp
|
|
2773
|
+
.command("push")
|
|
2774
|
+
.description("Run one sync pass now instead of waiting for the next minute (settings:edit, active billing): queue the contacts newly in the source, take a backfill step, send due pushes. Waits up to 60 s (if it times out the server may have applied it: read `settings`). Prints { ran, result, settings }; ran false means another pass holds the connection or Mailchimp asked to slow down")
|
|
2775
|
+
.action(run(async (client) => client.post("/api/v1/integrations/mailchimp/push", {}, { timeoutMs: MAILCHIMP_ADMIN_TIMEOUT_MS })));
|
|
2776
|
+
mailchimp
|
|
2777
|
+
.command("retry-unsubscribes")
|
|
2778
|
+
.description("Try again, in one pass now, the unsubscribes Conduyt could not deliver to Mailchimp (also retried daily). Prints { ran, pending, delivered, undelivered, result, settings }; pending true = nothing was tried. One retry per account per 10 minutes: otherwise exit 1 with 429 retry_cooldown")
|
|
2779
|
+
.action(run(async (client) => client.post("/api/v1/integrations/mailchimp/unsubscribes/retry", {}, { timeoutMs: MAILCHIMP_ADMIN_TIMEOUT_MS })));
|
|
2780
|
+
mailchimp
|
|
2781
|
+
.command("reconcile-statuses")
|
|
2782
|
+
.description("Full reconciliation when Conduyt's check of Mailchimp's unsubscribes is blocked (statusSweepBlocked in `settings`; owner / admin key): reads every member Mailchimp shows as unsubscribed or cleaned up to the blocked second and applies them (it only ever OPTS OUT), then records a report; it never resumes the check on its own, review the report and run `confirm-reconciliation`. Starts or resumes the run and runs one pass: repeat until done is true. --restart replaces a completed run's report with a new run; without it a completed run exits 1 with 409 reconciliation_completed")
|
|
2783
|
+
.option("--restart", "replace a completed run's report with a new run")
|
|
2784
|
+
.action(run(async (client, opts) => client.post("/api/v1/integrations/mailchimp/reconcile-statuses", opts.restart ? { restart: true } : {}, { timeoutMs: MAILCHIMP_ADMIN_TIMEOUT_MS })));
|
|
2785
|
+
mailchimp
|
|
2786
|
+
.command("confirm-reconciliation")
|
|
2787
|
+
.description("Confirm the completed reconciliation's report and resume the unsubscribe check after the blocked second (owner / admin key; audited with the report's counts). 409 when nothing is blocked, a reconciliation is still running, or none completed since the block began")
|
|
2788
|
+
.action(run(async (client) => client.post("/api/v1/integrations/mailchimp/confirm-reconciliation", {}, { timeoutMs: MAILCHIMP_ADMIN_TIMEOUT_MS })));
|
|
2476
2789
|
// ---------------------------------------------------------------------------
|
|
2477
2790
|
// Sequences (one model for Email and SMS since 2026-09-30): steps send saved templates of the sequence's channel a
|
|
2478
2791
|
// number of days apart inside a send window; a run stops on a reply, a booked meeting, an opt-out, a closed deal or a
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pipeline settings release (app 10-08), status metadata and Mailchimp: the validators the commands run before any
|
|
3
|
+
* request. They mirror the API (the source of truth) so a bad value fails locally with the same words; the API still
|
|
4
|
+
* re-checks everything and its refusal codes are printed with the error.
|
|
5
|
+
*/
|
|
6
|
+
export const PIPELINE_COLORS = ["#3845C9", "#43DFF6", "#2DD6B5", "#22C58B", "#9BD13B", "#F2B544", "#F07A2F", "#E6465A", "#FD88C0", "#956EFA"];
|
|
7
|
+
export const LIFECYCLE_STAGES = ["pre_sale", "sale", "underwriting", "active", "resolution", "terminal"];
|
|
8
|
+
export const MAX_STATUS_METADATA_IMPORT = 1000;
|
|
9
|
+
/** per-call deadlines above the server budgets (archive tx 60 s; Mailchimp admin 60 s; import tx 20 s plus locks) */
|
|
10
|
+
export const ARCHIVE_PIPELINE_TIMEOUT_MS = 75_000;
|
|
11
|
+
export const MAILCHIMP_ADMIN_TIMEOUT_MS = 60_000;
|
|
12
|
+
export const STATUS_METADATA_IMPORT_TIMEOUT_MS = 60_000;
|
|
13
|
+
/** the exact fields an import item takes; anything else (a misspelled isTerminal, say) would be dropped by the API and stored as defaults */
|
|
14
|
+
export const IMPORT_ITEM_KEYS = ["stageId", "code", "bucket", "lifecycleStage", "dripEligible", "dripTrackName", "isTerminal", "notes"];
|
|
15
|
+
export const MIN_PIPELINE_ROT_DAYS = 1;
|
|
16
|
+
export const MAX_PIPELINE_ROT_DAYS = 90;
|
|
17
|
+
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
18
|
+
const SLUG_RE = /^[a-z0-9][a-z0-9_]{0,79}$/;
|
|
19
|
+
const SETTINGS_REVISION_RE = /^\d+$/;
|
|
20
|
+
export const isUuid = (v) => typeof v === "string" && UUID_RE.test(v.trim());
|
|
21
|
+
export function uuid(raw, name) {
|
|
22
|
+
if (!isUuid(raw))
|
|
23
|
+
throw new Error(`${name} must be a UUID.`);
|
|
24
|
+
return raw.trim().toLowerCase();
|
|
25
|
+
}
|
|
26
|
+
/** true | false (any case) */
|
|
27
|
+
export function boolFlag(raw, name) {
|
|
28
|
+
const v = raw.trim().toLowerCase();
|
|
29
|
+
if (v === "true")
|
|
30
|
+
return true;
|
|
31
|
+
if (v === "false")
|
|
32
|
+
return false;
|
|
33
|
+
throw new Error(`${name} must be true or false.`);
|
|
34
|
+
}
|
|
35
|
+
export function intFlag(raw, name, min, max) {
|
|
36
|
+
const t = raw.trim();
|
|
37
|
+
const n = Number(t);
|
|
38
|
+
if (t === "" || !Number.isInteger(n) || n < min || n > max)
|
|
39
|
+
throw new Error(`${name} must be an integer ${min}-${max}.`);
|
|
40
|
+
return n;
|
|
41
|
+
}
|
|
42
|
+
/** A pipeline colour is one of the 10 palette colours (case-insensitive); the API answers 400 for anything else. */
|
|
43
|
+
export function pipelineColor(raw, name = "--color") {
|
|
44
|
+
const upper = raw.trim().toUpperCase();
|
|
45
|
+
const hit = PIPELINE_COLORS.find((c) => c === upper);
|
|
46
|
+
if (!hit)
|
|
47
|
+
throw new Error(`${name} must be one of the pipeline palette colours: ${PIPELINE_COLORS.join(", ")}.`);
|
|
48
|
+
return hit;
|
|
49
|
+
}
|
|
50
|
+
/** The settingsRevision a settings-backed write was read at: digits only (the API's pattern). */
|
|
51
|
+
export function settingsRevision(raw, name = "--expected-settings-revision") {
|
|
52
|
+
const t = raw.trim();
|
|
53
|
+
if (!SETTINGS_REVISION_RE.test(t))
|
|
54
|
+
throw new Error(`${name} must be the settingsRevision you read (digits only).`);
|
|
55
|
+
return t;
|
|
56
|
+
}
|
|
57
|
+
/** An ISO date (the row's updatedAt as read); the API answers 400 for anything else. */
|
|
58
|
+
export function isoDate(raw, name) {
|
|
59
|
+
const t = raw.trim();
|
|
60
|
+
if (t === "" || Number.isNaN(new Date(t).getTime()))
|
|
61
|
+
throw new Error(`${name} must be the updatedAt you read (an ISO date).`);
|
|
62
|
+
return t;
|
|
63
|
+
}
|
|
64
|
+
export function slug(raw, name) {
|
|
65
|
+
if (!SLUG_RE.test(raw))
|
|
66
|
+
throw new Error(`${name} must be a lowercase machine slug using letters, numbers and underscores (max 80).`);
|
|
67
|
+
return raw;
|
|
68
|
+
}
|
|
69
|
+
export function lifecycleStage(raw, name = "--lifecycle-stage") {
|
|
70
|
+
if (!LIFECYCLE_STAGES.includes(raw))
|
|
71
|
+
throw new Error(`${name} must be one of: ${LIFECYCLE_STAGES.join(", ")}.`);
|
|
72
|
+
return raw;
|
|
73
|
+
}
|
|
74
|
+
/** A comma-separated order list of UUIDs, no duplicates. */
|
|
75
|
+
export function uuidList(raw, name) {
|
|
76
|
+
const ids = raw.split(",").map((s) => s.trim()).filter((s) => s !== "").map((s) => uuid(s, `${name} entry`));
|
|
77
|
+
if (ids.length === 0)
|
|
78
|
+
throw new Error(`${name} needs at least one id.`);
|
|
79
|
+
if (new Set(ids).size !== ids.length)
|
|
80
|
+
throw new Error(`${name} lists an id more than once.`);
|
|
81
|
+
return ids;
|
|
82
|
+
}
|
|
83
|
+
/** The fields of a status metadata row for create / update / get (a drip track is named by id); import names it by dripTrackName instead. */
|
|
84
|
+
export const ROW_FIELD_KEYS = IMPORT_ITEM_KEYS.map((k) => (k === "dripTrackName" ? "dripTrackId" : k));
|
|
85
|
+
/**
|
|
86
|
+
* THE one definition of a status metadata row's fields and types, shared by import items and the create / update bodies:
|
|
87
|
+
* unknown keys are refused naming the key (the API drops them and applies the rest of the call), and each present value is
|
|
88
|
+
* type-checked like the API does. `required`: stageId, code and bucket must be present. `trackKey` is the drip track field.
|
|
89
|
+
*/
|
|
90
|
+
function checkRowFields(o, at, allowed, required, trackKey, what) {
|
|
91
|
+
for (const k of Object.keys(o)) {
|
|
92
|
+
if (!allowed.includes(k))
|
|
93
|
+
throw new Error(`${at}: unknown field "${k}". ${what} takes ${allowed.join(", ")}; nothing was sent.`);
|
|
94
|
+
}
|
|
95
|
+
const has = (k) => o[k] !== undefined;
|
|
96
|
+
if (required || has("stageId")) {
|
|
97
|
+
if (typeof o.stageId !== "string" || !isUuid(o.stageId))
|
|
98
|
+
throw new Error(`${at}.stageId must be a UUID.`);
|
|
99
|
+
}
|
|
100
|
+
for (const k of ["code", "bucket"]) {
|
|
101
|
+
if (required || has(k)) {
|
|
102
|
+
if (typeof o[k] !== "string")
|
|
103
|
+
throw new Error(`${at}.${k} must be a slug.`);
|
|
104
|
+
slug(o[k], `${at}.${k}`);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
if (has("lifecycleStage") && o.lifecycleStage !== null) {
|
|
108
|
+
if (typeof o.lifecycleStage !== "string")
|
|
109
|
+
throw new Error(`${at}.lifecycleStage must be one of: ${LIFECYCLE_STAGES.join(", ")}, or null.`);
|
|
110
|
+
lifecycleStage(o.lifecycleStage, `${at}.lifecycleStage`);
|
|
111
|
+
}
|
|
112
|
+
if (has("dripEligible") && typeof o.dripEligible !== "boolean")
|
|
113
|
+
throw new Error(`${at}.dripEligible must be a boolean.`);
|
|
114
|
+
if (has("isTerminal") && typeof o.isTerminal !== "boolean")
|
|
115
|
+
throw new Error(`${at}.isTerminal must be a boolean.`);
|
|
116
|
+
if (has(trackKey) && o[trackKey] !== null) {
|
|
117
|
+
const v = o[trackKey];
|
|
118
|
+
if (typeof v !== "string")
|
|
119
|
+
throw new Error(`${at}.${trackKey} must be ${trackKey === "dripTrackId" ? "a UUID" : "a slug"} or null.`);
|
|
120
|
+
if (trackKey === "dripTrackId") {
|
|
121
|
+
if (!isUuid(v))
|
|
122
|
+
throw new Error(`${at}.dripTrackId must be a UUID or null.`);
|
|
123
|
+
}
|
|
124
|
+
else
|
|
125
|
+
slug(v, `${at}.dripTrackName`);
|
|
126
|
+
}
|
|
127
|
+
if (has("notes") && o.notes !== null && (typeof o.notes !== "string" || o.notes.trim().length > 5000))
|
|
128
|
+
throw new Error(`${at}.notes must be text of at most 5000 characters.`);
|
|
129
|
+
}
|
|
130
|
+
/** One status metadata item, as the import route takes it. */
|
|
131
|
+
export function validateImportItem(raw, index) {
|
|
132
|
+
const at = `items[${index}]`;
|
|
133
|
+
if (raw === null || typeof raw !== "object" || Array.isArray(raw))
|
|
134
|
+
throw new Error(`${at} must be an object.`);
|
|
135
|
+
checkRowFields(raw, at, IMPORT_ITEM_KEYS, true, "dripTrackName", "An import item");
|
|
136
|
+
return raw;
|
|
137
|
+
}
|
|
138
|
+
/** The COMPLETE body of `status-metadata create` / `update` (flags + --json merged), checked before any request. */
|
|
139
|
+
export function validateStatusMetadataBody(body, mode) {
|
|
140
|
+
const allowed = mode === "update" ? [...ROW_FIELD_KEYS, "expectedUpdatedAt"] : ROW_FIELD_KEYS;
|
|
141
|
+
checkRowFields(body, "body", allowed, mode === "create", "dripTrackId", mode === "create" ? "A status metadata row" : "A status metadata update");
|
|
142
|
+
if (body.expectedUpdatedAt !== undefined) {
|
|
143
|
+
if (typeof body.expectedUpdatedAt !== "string")
|
|
144
|
+
throw new Error("body.expectedUpdatedAt must be the updatedAt you read (an ISO date).");
|
|
145
|
+
isoDate(body.expectedUpdatedAt, "body.expectedUpdatedAt");
|
|
146
|
+
}
|
|
147
|
+
return body;
|
|
148
|
+
}
|
|
149
|
+
export function validateImportItems(raw) {
|
|
150
|
+
if (!Array.isArray(raw))
|
|
151
|
+
throw new Error("items must be a JSON array.");
|
|
152
|
+
if (raw.length > MAX_STATUS_METADATA_IMPORT)
|
|
153
|
+
throw new Error(`items takes at most ${MAX_STATUS_METADATA_IMPORT} entries (got ${raw.length}).`);
|
|
154
|
+
return raw.map((item, i) => validateImportItem(item, i));
|
|
155
|
+
}
|
package/package.json
CHANGED