@velaro/cli 1.4.220 → 1.4.221

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.
@@ -0,0 +1,141 @@
1
+ import { messagingGet, messagingPost } from '../api.js';
2
+ import { runCommand } from '../run.js';
3
+
4
+ // -- velaro crm calc-values / calc-deps -----------------------------------------
5
+ // CLI for calculated fields beyond the field editor (docs/architecture/crm-studio-program.md, feature 6):
6
+ // calc-values POST /CrmCustomFields/calculated/values (computed values for up to 100 records, the caller's view)
7
+ // calc-filter POST /CrmCustomFields/calculated/filter (records matching filters on calculated values)
8
+ // calc-sources GET /CrmCustomFields/calculated/sources (related custom object sources a rollup may read)
9
+ // calc-deps GET /CrmCustomFields/calculated/deps (which calculated fields read which, evaluation order, cycles)
10
+ // calc-test is an alias of `crm formula-test` (POST /CrmCustomFields/formula/test) registered in crm-studio.js.
11
+ // The site always comes from the signed-in credential; no command takes a site id.
12
+ // MCP parity: mcp/parity/crm-calculated-fields.customer.js (crm_calculated_values, crm_calculated_deps).
13
+
14
+ const BOLD = '\x1b[1m';
15
+ const DIM = '\x1b[2m';
16
+ const RST = '\x1b[0m';
17
+
18
+ const data = (r) => (r && typeof r === 'object' && 'data' in r ? r.data : r);
19
+ const printJson = (v) => console.log(JSON.stringify(v, null, 2));
20
+
21
+ export const ENTITY_PATTERN = /^(deal|contact|company|ticket|obj:\d+)$/;
22
+ export const entityCheck = (a) => (ENTITY_PATTERN.test(a.entity) ? true : '[CrmFormula] --entity must be deal, contact, company, ticket or obj:<typeId>.');
23
+
24
+ // "1,2, 3" -> [1,2,3]; rejects anything that is not a whole number and enforces the 1 to 100 batch size.
25
+ export function parseIds(text) {
26
+ const ids = String(text ?? '').split(',').map((s) => s.trim()).filter(Boolean).map(Number);
27
+ if (!ids.length || ids.some((n) => !Number.isInteger(n) || n <= 0)) throw new Error('[CrmFormula] --ids must be a comma-separated list of record ids, for example 1,2,3.');
28
+ if (ids.length > 100) throw new Error('[CrmFormula] --ids takes at most 100 record ids per call.');
29
+ return ids;
30
+ }
31
+
32
+ async function calcValuesHandler(argv) {
33
+ const r = data(await messagingPost('/CrmCustomFields/calculated/values', { entity: argv.entity, recordIds: parseIds(argv.ids) }));
34
+ if (argv.json) return printJson(r);
35
+ const fields = r?.fields ?? [];
36
+ console.log(`\n${BOLD}Calculated values${RST} (${argv.entity}, ${(r?.items ?? []).length} records)${r?.truncated ? ` ${DIM}(truncated)${RST}` : ''}`);
37
+ for (const item of r?.items ?? []) {
38
+ console.log(` #${item.recordId}`);
39
+ for (const f of fields) {
40
+ const v = item.values?.[String(f.id)];
41
+ console.log(` ${f.label} ${DIM}(${f.resultType})${RST}: ${v === null || v === undefined ? 'no value' : v}`);
42
+ }
43
+ }
44
+ console.log('');
45
+ }
46
+
47
+ async function calcDepsHandler(argv) {
48
+ const r = data(await messagingGet(`/CrmCustomFields/calculated/deps?entity=${encodeURIComponent(argv.entity)}`));
49
+ if (argv.json) return printJson(r);
50
+ const fields = r?.fields ?? [];
51
+ const byId = new Map(fields.map((f) => [f.id, f]));
52
+ console.log(`\n${BOLD}Calculated fields on ${argv.entity}${RST} (${fields.length})`);
53
+ for (const id of r?.order?.length ? r.order : fields.map((f) => f.id)) {
54
+ const f = byId.get(id);
55
+ if (!f) continue;
56
+ console.log(` #${f.id} ${f.label} ${DIM}${f.kind}: ${f.expr}${RST}`);
57
+ if (f.readsLabels?.length) console.log(` reads: ${f.readsLabels.join(', ')}`);
58
+ }
59
+ if (r?.cycles?.length) {
60
+ console.log(`\n ${BOLD}Cycles${RST}`);
61
+ for (const c of r.cycles) console.log(` ${c.join(' -> ')}`);
62
+ }
63
+ console.log('');
64
+ }
65
+
66
+ export const FILTER_OPS = ['eq', 'neq', 'contains', 'gt', 'gte', 'lt', 'lte', 'in', 'empty', 'notEmpty'];
67
+
68
+ // --filter is repeatable: "cf:12 gt 100", "cf:12 empty", "cf:12 in a|b|c". Returns [{ field, op, value? }].
69
+ export function parseFilters(list) {
70
+ const items = Array.isArray(list) ? list : list === undefined ? [] : [list];
71
+ if (!items.length) throw new Error('[CrmFormula] Pass at least one --filter, for example --filter "cf:12 gt 100".');
72
+ return items.map((text) => {
73
+ const m = /^\s*(\S+)\s+(\S+)(?:\s+(.*))?$/.exec(String(text));
74
+ if (!m || !FILTER_OPS.includes(m[2])) throw new Error(`[CrmFormula] --filter must look like "cf:12 gt 100" with an operator from: ${FILTER_OPS.join(', ')}.`);
75
+ const f = { field: m[1], op: m[2] };
76
+ if (m[2] === 'empty' || m[2] === 'notEmpty') return f;
77
+ if (m[3] === undefined || m[3] === '') throw new Error(`[CrmFormula] The "${m[2]}" filter needs a value.`);
78
+ f.value = m[2] === 'in' ? m[3].split('|').map((v) => v.trim()) : m[3];
79
+ return f;
80
+ });
81
+ }
82
+
83
+ async function calcFilterHandler(argv) {
84
+ const body = { entity: argv.entity, filters: parseFilters(argv.filter) };
85
+ if (argv.limit !== undefined) body.limit = argv.limit;
86
+ const r = data(await messagingPost('/CrmCustomFields/calculated/filter', body));
87
+ if (argv.json) return printJson(r);
88
+ const ids = r?.recordIds ?? [];
89
+ console.log(`\n${BOLD}Matching records${RST} (${ids.length}, scanned ${r?.scanned ?? 0})${r?.capped ? ` ${DIM}(capped)${RST}` : ''}`);
90
+ if (ids.length) console.log(` ${ids.join(', ')}`);
91
+ if (r?.message) console.log(` ${r.message}`);
92
+ console.log('');
93
+ }
94
+
95
+ async function calcSourcesHandler(argv) {
96
+ const r = data(await messagingGet(`/CrmCustomFields/calculated/sources?entity=${encodeURIComponent(argv.entity)}`));
97
+ if (argv.json) return printJson(r);
98
+ const list = r?.sources ?? [];
99
+ console.log(`\n${BOLD}Rollup sources on ${argv.entity}${RST} (${list.length})`);
100
+ for (const s of list) {
101
+ console.log(` ${s.source} ${DIM}${s.label}${RST}`);
102
+ for (const f of s.fields ?? []) console.log(` ${s.source}.${f.name} ${DIM}${f.label}${f.numeric ? ', number' : ''}${RST}`);
103
+ }
104
+ console.log('');
105
+ }
106
+
107
+ // Added to the `crm` group's subcommand chain in crm-studio.js.
108
+ export function addCalculatedFieldCommands(y) {
109
+ const entity = (yy) => yy.option('entity', { type: 'string', demandOption: true, describe: 'deal, contact, company, ticket or obj:<typeId> for a custom object' });
110
+ const json = (yy) => yy.option('json', { type: 'boolean', default: false, describe: 'Print raw JSON' });
111
+ return y
112
+ .command({
113
+ command: 'calc-values',
114
+ describe: 'Show the calculated field values of up to 100 records, as the signed-in user sees them (nothing is stored)',
115
+ builder: (yy) => json(entity(yy)
116
+ .option('ids', { type: 'string', demandOption: true, describe: 'Comma-separated record ids, for example 1,2,3' })
117
+ .check(entityCheck)),
118
+ handler: runCommand(calcValuesHandler),
119
+ })
120
+ .command({
121
+ command: 'calc-filter',
122
+ describe: 'Find records by their calculated values, the same filters saved views use: eq, neq, contains, gt, gte, lt, lte, in, empty, notEmpty',
123
+ builder: (yy) => json(entity(yy)
124
+ .option('filter', { type: 'string', array: true, describe: 'Repeatable: "cf:12 gt 100", "cf:12 empty", "cf:12 in a|b|c"' })
125
+ .option('limit', { type: 'number', describe: 'Most record ids to return' })
126
+ .check(entityCheck)),
127
+ handler: runCommand(calcFilterHandler),
128
+ })
129
+ .command({
130
+ command: 'calc-sources',
131
+ describe: 'List the custom object record types a rollup on this record type can read, with their fields (Administrator)',
132
+ builder: (yy) => json(entity(yy).check(entityCheck)),
133
+ handler: runCommand(calcSourcesHandler),
134
+ })
135
+ .command({
136
+ command: 'calc-deps',
137
+ describe: 'Show which calculated fields read which others, the order they are worked out in, and any cycles (Administrator)',
138
+ builder: (yy) => json(entity(yy).check(entityCheck)),
139
+ handler: runCommand(calcDepsHandler),
140
+ });
141
+ }
@@ -1,11 +1,13 @@
1
1
  import { messagingGet, messagingPost, messagingPut, messagingDel } from '../api.js';
2
2
  import { runCommand } from '../run.js';
3
+ import { addCalculatedFieldCommands, entityCheck } from './crm-calculated-fields.js';
3
4
 
4
5
  // -- velaro crm ---------------------------------------------------------------
5
6
  // CLI for CRM Studio (docs/architecture/crm-studio-program.md):
6
7
  // field-* CrmCustomFieldsController /CrmCustomFields
7
8
  // layout-* CrmFormLayoutsController /CrmFormLayouts
8
- // formula-test POST /CrmCustomFields/formula/test (dry run of a calculated field or rollup; writes nothing)
9
+ // calc-values, calc-deps crm-calculated-fields.js (computed values for records, dependency order and cycles)
10
+ // formula-test (alias calc-test) POST /CrmCustomFields/formula/test (dry run of a calculated field or rollup; writes nothing)
9
11
  // The site always comes from the signed-in credential; no command takes a site id.
10
12
  // MCP parity: mcp/parity/crm-studio.customer.js (crm_* tools).
11
13
 
@@ -51,7 +53,7 @@ function formulaArg(argv) {
51
53
  }
52
54
 
53
55
  const json = (y) => y.option('json', { type: 'boolean', default: false, describe: 'Print raw JSON' });
54
- const entity = (y) => y.option('entity', { choices: ENTITIES, demandOption: true, describe: 'Record type' });
56
+ const entity = (y) => y.option('entity', { type: 'string', demandOption: true, describe: `Record type: ${ENTITIES.join(', ')} or obj:<typeId> for a custom object` }).check(entityCheck);
55
57
 
56
58
  async function fieldListHandler(argv) {
57
59
  const v = data(await messagingGet(`/CrmCustomFields${q({ entity: argv.entity, pipelineId: argv.pipelineId })}`));
@@ -160,7 +162,7 @@ async function layoutRestoreHandler(argv) {
160
162
  export const crmCommand = {
161
163
  command: 'crm <subcommand>',
162
164
  describe: 'CRM Studio: custom fields and form layouts (Form Designer)',
163
- builder: (y) => y
165
+ builder: (y) => addCalculatedFieldCommands(y)
164
166
  .command({
165
167
  command: 'field-list',
166
168
  describe: 'List CRM custom fields for a record type',
@@ -184,7 +186,7 @@ export const crmCommand = {
184
186
  .option('read-roles', { type: 'string', alias: 'readRoles', describe: 'Comma-separated role names; empty means everyone' })
185
187
  .option('write-roles', { type: 'string', alias: 'writeRoles', describe: 'Comma-separated role names; empty means everyone' })
186
188
  .option('visible-when', { type: 'string', alias: 'visibleWhen', describe: 'JSON rule' })
187
- .option('formula', { type: 'string', describe: 'Calculated field spec as JSON, for example {"kind":"formula","expr":"amount * 2","resultType":"number"}; empty clears it' })
189
+ .option('formula', { type: 'string', alias: ['formula-json', 'formulaJson'], describe: 'Calculated field spec as JSON, for example {"kind":"formula","expr":"amount * 2","resultType":"number"}; empty clears it' })
188
190
  .option('expr', { type: 'string', describe: 'Calculated field expression, for example "ROUND(amount * probability / 100, 2)" or "SUM(lineItems.total)" (builds --formula)' })
189
191
  .option('kind', { choices: ['formula', 'rollup'], describe: 'With --expr: a formula (default) or a rollup over related records' })
190
192
  .option('result-type', { choices: RESULT_TYPES, alias: 'resultType', describe: 'With --expr: defaults from --type (Number, Currency, Percent = number); rollups are numbers' })
@@ -193,11 +195,11 @@ export const crmCommand = {
193
195
  handler: runCommand(fieldDefineHandler),
194
196
  })
195
197
  .command({
196
- command: 'formula-test',
198
+ command: ['formula-test', 'calc-test'],
197
199
  describe: 'Dry-run a calculated field expression or rollup against sample values or a real record (Administrator; writes nothing)',
198
200
  builder: (yy) => json(entity(yy)
199
201
  .option('expr', { type: 'string', describe: 'Expression, for example "amount * 2"' })
200
- .option('formula', { type: 'string', describe: 'Whole spec as JSON instead of --expr (use for rollups)' })
202
+ .option('formula', { type: 'string', alias: ['formula-json', 'formulaJson'], describe: 'Whole spec as JSON instead of --expr (use for rollups)' })
201
203
  .option('result-type', { choices: RESULT_TYPES, alias: 'resultType', describe: 'Defaults to number' })
202
204
  .option('sample', { type: 'string', describe: 'JSON object of sample values, for example {"amount":100,"cf:12":"Gold"}' })
203
205
  .option('record-id', { type: 'number', alias: 'recordId', describe: "Use this record's real values underneath the samples (required to test a rollup)" })
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@velaro/cli",
3
- "version": "1.4.220",
3
+ "version": "1.4.221",
4
4
  "description": "Velaro Workspace v20 — command-line interface for managing bots, knowledge base ingestion, MCP API keys, search indexes, and ops health.",
5
5
  "type": "module",
6
6
  "bin": {