@velaro/cli 1.4.120 → 1.4.122
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 +0 -19
- package/bin/velaro.js +21 -92
- package/lib/avatar-motion.test.js +1 -1
- package/lib/avatar-switch.test.js +1 -1
- package/lib/commands/agent.js +7 -58
- package/lib/commands/ai-config.js +8 -34
- package/lib/commands/index.js +18 -14
- package/lib/commands/kb.js +4 -94
- package/lib/commands/knowledge.js +2 -2
- package/lib/commands/ops-groups.js +0 -13
- package/lib/commands/safety.js +1 -1
- package/lib/commands/salesforce.js +1 -1
- package/lib/commands/sap.js +1 -1
- package/lib/commands/schedule-adherence.js +1 -1
- package/lib/commands/signature.js +39 -3
- package/lib/commands/teams.js +1 -1
- package/lib/commands/woocommerce.js +1 -1
- package/lib/commands/workflow.js +4 -31
- package/lib/signature-policy.js +42 -0
- package/lib/signature-policy.test.js +28 -2
- package/lib/staff-optional.js +10 -0
- package/package.json +2 -2
- package/lib/cobrowse-settings.js +0 -90
- package/lib/cobrowse-settings.test.js +0 -45
- package/lib/commands/activity.js +0 -147
- package/lib/commands/acuity.js +0 -66
- package/lib/commands/ai-federation.js +0 -55
- package/lib/commands/ai-models.js +0 -203
- package/lib/commands/ai-spend.js +0 -71
- package/lib/commands/avatar.js +0 -253
- package/lib/commands/bigcommerce.js +0 -50
- package/lib/commands/calendly.js +0 -62
- package/lib/commands/cobrowse.js +0 -99
- package/lib/commands/coupon-grant.js +0 -192
- package/lib/commands/diag-groups.js +0 -108
- package/lib/commands/diagnostics.js +0 -298
- package/lib/commands/email-inbox.js +0 -110
- package/lib/commands/entitlement.js +0 -375
- package/lib/commands/image-analysis.js +0 -27
- package/lib/commands/logs-insights.js +0 -342
- package/lib/commands/logs.js +0 -1248
- package/lib/commands/migrate.js +0 -379
- package/lib/commands/migration-status.js +0 -66
- package/lib/commands/ops.js +0 -266
- package/lib/commands/parity-staff-tools.js +0 -205
- package/lib/commands/pricing.js +0 -132
- package/lib/commands/report-speed.js +0 -112
- package/lib/commands/scraper.js +0 -38
- package/lib/commands/site-provision.js +0 -68
- package/lib/commands/sitesync.js +0 -158
- package/lib/commands/skill-usage.js +0 -39
- package/lib/commands/staff.js +0 -31
- package/lib/commands/status-page.js +0 -95
- package/lib/commands/status-sla.js +0 -47
- package/lib/commands/subscription.js +0 -102
- package/lib/commands/support.js +0 -309
- package/lib/commands/tour-policy.js +0 -61
- package/lib/commands/triage.js +0 -66
- package/lib/entitlement-report-packages.test.js +0 -47
- package/lib/log-search.js +0 -252
- package/lib/log-search.test.js +0 -374
- package/lib/logs-insights.test.js +0 -146
- package/lib/messaging-routes.test.js +0 -37
- package/lib/report-speed.test.js +0 -26
- package/lib/siteUser.js +0 -35
- package/lib/siteUser.test.js +0 -45
- package/lib/skill-usage.test.js +0 -36
- package/lib/status-sla.test.js +0 -23
package/lib/commands/ops.js
DELETED
|
@@ -1,266 +0,0 @@
|
|
|
1
|
-
import { describeRawMeta, fetchRetry429 } from '../log-search.js';
|
|
2
|
-
import { get, del, post, getCredentials } from '../api.js';
|
|
3
|
-
import { readConfig, ENVS } from '../config.js';
|
|
4
|
-
import { parseBuild, formatBuild } from '../build-info.js';
|
|
5
|
-
import { collectAll, render as renderDeployState } from '../deploy-state.js';
|
|
6
|
-
|
|
7
|
-
// ── helpers ──────────────────────────────────────────────────────────────────
|
|
8
|
-
|
|
9
|
-
function ago(dateStr) {
|
|
10
|
-
if (!dateStr) return 'unknown';
|
|
11
|
-
const diffMs = Date.now() - new Date(dateStr).getTime();
|
|
12
|
-
const mins = Math.round(diffMs / 60000);
|
|
13
|
-
if (mins < 2) return 'just now';
|
|
14
|
-
if (mins < 60) return `${mins}m ago`;
|
|
15
|
-
const hrs = Math.round(mins / 60);
|
|
16
|
-
if (hrs < 24) return `${hrs}h ago`;
|
|
17
|
-
return `${Math.round(hrs / 24)}d ago`;
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
// FIXED 2026-09-24: velaro-messaging's /superadmin/logs/search used to return a bare JSON array
|
|
21
|
-
// for some queries and {entries, nextCursor} for others, depending on which internal code path
|
|
22
|
-
// served the request. It now always returns {entries, nextCursor} -- this helper also accepts a
|
|
23
|
-
// bare array so this command degrades gracefully rather than crashing if pointed at an older
|
|
24
|
-
// deploy.
|
|
25
|
-
function extractLogEntries(response) {
|
|
26
|
-
if (Array.isArray(response)) return response;
|
|
27
|
-
if (response && Array.isArray(response.entries)) return response.entries;
|
|
28
|
-
return [];
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
const OK = '\x1b[32m✓\x1b[0m';
|
|
32
|
-
const WARN = '\x1b[33m⚠\x1b[0m';
|
|
33
|
-
const ERR = '\x1b[31m✗\x1b[0m';
|
|
34
|
-
const HIGH = '\x1b[31m[high]\x1b[0m ';
|
|
35
|
-
const MED = '\x1b[33m[med]\x1b[0m ';
|
|
36
|
-
const LOW = '\x1b[36m[low]\x1b[0m ';
|
|
37
|
-
|
|
38
|
-
function severityPrefix(s) {
|
|
39
|
-
if (s === 'high') return HIGH;
|
|
40
|
-
if (s === 'medium') return MED;
|
|
41
|
-
return LOW;
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
// Reads the real running build from /api/health (build.commitId|sha, builtAt). The old /Version
|
|
45
|
-
// endpoint returned a stale CI-stamped version/deployedAt, so workers polling for a new staging
|
|
46
|
-
// build never saw it land (2026-10-12).
|
|
47
|
-
async function pingHealth(label, url) {
|
|
48
|
-
try {
|
|
49
|
-
const res = await fetch(url, { signal: AbortSignal.timeout(6000) });
|
|
50
|
-
let build = null;
|
|
51
|
-
try { build = parseBuild(await res.json()); } catch { /* non-JSON health body */ }
|
|
52
|
-
return { label, ok: res.ok, status: res.status, build };
|
|
53
|
-
} catch (e) {
|
|
54
|
-
return { label, ok: false, err: e.message };
|
|
55
|
-
}
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
// ── hangfire subcommands ──────────────────────────────────────────────────────
|
|
59
|
-
|
|
60
|
-
async function requireAdmin() {
|
|
61
|
-
const creds = await getCredentials();
|
|
62
|
-
if (creds.siteId !== 1032) {
|
|
63
|
-
console.error('velaro ops is only available to Velaro staff.');
|
|
64
|
-
process.exit(1);
|
|
65
|
-
}
|
|
66
|
-
return creds;
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
const hangfireCommand = {
|
|
70
|
-
command: 'hangfire <action>',
|
|
71
|
-
describe: 'Manage Hangfire failed jobs (Velaro staff only)',
|
|
72
|
-
builder: (yargs) => yargs
|
|
73
|
-
.positional('action', { choices: ['list', 'delete', 'retry'], describe: 'Action to perform' })
|
|
74
|
-
.option('id', { type: 'string', describe: 'Job ID (for delete/retry of a single job)' })
|
|
75
|
-
.option('all', { type: 'boolean', describe: 'Apply to all failed jobs (delete only)' }),
|
|
76
|
-
handler: async (argv) => {
|
|
77
|
-
await requireAdmin();
|
|
78
|
-
const { action, id, all } = argv;
|
|
79
|
-
|
|
80
|
-
if (action === 'list') {
|
|
81
|
-
const jobs = await get('/DatabaseTool/FailedJobs');
|
|
82
|
-
if (!jobs?.length) { console.log('No failed jobs.'); return; }
|
|
83
|
-
console.log(`\n${jobs.length} failed job(s):\n`);
|
|
84
|
-
for (const j of jobs) {
|
|
85
|
-
const name = [j.typeName, j.methodName].filter(Boolean).join('.') || '(unknown)';
|
|
86
|
-
console.log(` #${j.id.padEnd(5)} ${name.padEnd(50)} ${j.exceptionMessage?.split('\n')[0]?.slice(0, 80) ?? ''}`);
|
|
87
|
-
}
|
|
88
|
-
console.log('');
|
|
89
|
-
} else if (action === 'delete') {
|
|
90
|
-
if (all) {
|
|
91
|
-
const res = await del('/DatabaseTool/FailedJobs');
|
|
92
|
-
console.log(`Deleted ${res.deleted} failed job(s).`);
|
|
93
|
-
} else if (id) {
|
|
94
|
-
const res = await del(`/DatabaseTool/FailedJobs/${id}`);
|
|
95
|
-
console.log(`Deleted ${res.deleted} job(s).`);
|
|
96
|
-
} else {
|
|
97
|
-
console.error('Specify --id <jobId> or --all');
|
|
98
|
-
process.exit(1);
|
|
99
|
-
}
|
|
100
|
-
} else if (action === 'retry') {
|
|
101
|
-
if (!id) { console.error('Specify --id <jobId>'); process.exit(1); }
|
|
102
|
-
const res = await post(`/DatabaseTool/FailedJobs/${id}/retry`);
|
|
103
|
-
console.log(`Requeued ${res.requeued} job(s).`);
|
|
104
|
-
}
|
|
105
|
-
},
|
|
106
|
-
};
|
|
107
|
-
|
|
108
|
-
// ── ops command ───────────────────────────────────────────────────────────────
|
|
109
|
-
|
|
110
|
-
export const opsCommand = {
|
|
111
|
-
command: 'ops',
|
|
112
|
-
describe: 'System health: deploy times, Hangfire, API status, and active alerts (Velaro staff only)',
|
|
113
|
-
builder: (yargs) => yargs.command(hangfireCommand),
|
|
114
|
-
handler: async () => {
|
|
115
|
-
const creds = await getCredentials();
|
|
116
|
-
const isAdmin = creds.siteId === 1032;
|
|
117
|
-
|
|
118
|
-
if (!isAdmin) {
|
|
119
|
-
console.error('velaro ops is only available to Velaro staff.');
|
|
120
|
-
process.exit(1);
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
const cfg = readConfig();
|
|
124
|
-
|
|
125
|
-
// ── 1+2. Deploy (real running build) + API health, all four services ────
|
|
126
|
-
const prodBase = cfg.envs?.prod?.adminApiBase ?? ENVS.prod.adminApiBase;
|
|
127
|
-
const stagingBase = cfg.envs?.staging?.adminApiBase ?? ENVS.staging.adminApiBase;
|
|
128
|
-
const prodMsgBase = cfg.envs?.prod?.messagingApiBase ?? ENVS.prod.messagingApiBase;
|
|
129
|
-
const stagingMsgBase = cfg.envs?.staging?.messagingApiBase ?? ENVS.staging.messagingApiBase;
|
|
130
|
-
|
|
131
|
-
const services = await Promise.all([
|
|
132
|
-
pingHealth('admin/prod', `${prodBase}/api/health`),
|
|
133
|
-
pingHealth('admin/staging', `${stagingBase}/api/health`),
|
|
134
|
-
pingHealth('msg/prod', `${prodMsgBase}/api/health`),
|
|
135
|
-
pingHealth('msg/staging', `${stagingMsgBase}/api/health`),
|
|
136
|
-
]);
|
|
137
|
-
|
|
138
|
-
console.log('\n\x1b[1m── Deploy / API Health ─────────────────────────────────────\x1b[0m');
|
|
139
|
-
for (const h of services) {
|
|
140
|
-
if (h.ok) {
|
|
141
|
-
console.log(` ${OK} ${h.label.padEnd(14)} ${formatBuild(h.build)}`);
|
|
142
|
-
} else {
|
|
143
|
-
const detail = h.err ?? `HTTP ${h.status}`;
|
|
144
|
-
console.log(` ${ERR} ${h.label.padEnd(14)} ${h.build ? formatBuild(h.build) + ' ' : ''}UNHEALTHY — ${detail}`);
|
|
145
|
-
}
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
// ── 1b. Where each push landed: staging environment, staging slot 1 of production, production ──
|
|
149
|
-
// Same data as `velaro deploy-state` (needs gh). Never blocks the rest of ops if gh is missing.
|
|
150
|
-
console.log('\n[1m── Where each push landed ──────────────────────────────────[0m');
|
|
151
|
-
try {
|
|
152
|
-
const state = await collectAll();
|
|
153
|
-
console.log(renderDeployState(state, { compact: true }).split('\n').map(l => ' ' + l).join('\n'));
|
|
154
|
-
console.log(' Full detail: velaro deploy-state');
|
|
155
|
-
} catch (e) {
|
|
156
|
-
console.log(` ${WARN} Deploy state unavailable (${e.message}). Needs gh logged in; run velaro deploy-state.`);
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
// ── 3. Hangfire failed jobs ───────────────────────────────────────────────
|
|
160
|
-
console.log('\n\x1b[1m── Hangfire ────────────────────────────────────────────────\x1b[0m');
|
|
161
|
-
try {
|
|
162
|
-
const jobs = await get('/DatabaseTool/FailedJobs');
|
|
163
|
-
if (!jobs?.length) {
|
|
164
|
-
console.log(` ${OK} 0 failed jobs`);
|
|
165
|
-
} else {
|
|
166
|
-
const sym = jobs.length >= 20 ? ERR : jobs.length >= 5 ? WARN : WARN;
|
|
167
|
-
console.log(` ${sym} ${jobs.length} failed job(s)`);
|
|
168
|
-
for (const j of jobs.slice(0, 5)) {
|
|
169
|
-
const when = j.failedAt ? ago(j.failedAt) : '?';
|
|
170
|
-
const name = [j.typeName, j.methodName].filter(Boolean).join('.');
|
|
171
|
-
const msg = j.exceptionMessage?.split('\n')[0]?.slice(0, 80) ?? j.reason?.slice(0, 80) ?? '';
|
|
172
|
-
console.log(` ${WARN} ${name.padEnd(35)} ${when.padEnd(10)} ${msg}`);
|
|
173
|
-
}
|
|
174
|
-
if (jobs.length > 5) console.log(` ... and ${jobs.length - 5} more`);
|
|
175
|
-
console.log(' Open /hangfire to inspect and retry.');
|
|
176
|
-
}
|
|
177
|
-
} catch (e) {
|
|
178
|
-
console.log(` ${WARN} Could not load Hangfire jobs: ${e.message}`);
|
|
179
|
-
}
|
|
180
|
-
|
|
181
|
-
// ── 4. Active alerts (needs-attention via messaging API) ──────────────────
|
|
182
|
-
console.log('\n\x1b[1m── Alerts ──────────────────────────────────────────────────\x1b[0m');
|
|
183
|
-
try {
|
|
184
|
-
const res = await fetch(`${prodMsgBase}/SuperAdmin/needs-attention`, {
|
|
185
|
-
headers: {
|
|
186
|
-
Authorization: `Bearer ${creds.velaroToken}`,
|
|
187
|
-
'X-Internal-SiteId': String(creds.siteId),
|
|
188
|
-
'Content-Type': 'application/json',
|
|
189
|
-
},
|
|
190
|
-
signal: AbortSignal.timeout(15000),
|
|
191
|
-
});
|
|
192
|
-
|
|
193
|
-
if (!res.ok) {
|
|
194
|
-
console.log(` ${WARN} Could not reach alerts endpoint (HTTP ${res.status})`);
|
|
195
|
-
} else {
|
|
196
|
-
const items = await res.json();
|
|
197
|
-
const alertItems = Array.isArray(items)
|
|
198
|
-
? items.filter(i => i.type !== 'hangfire_failed') // shown above
|
|
199
|
-
: [];
|
|
200
|
-
if (!alertItems.length) {
|
|
201
|
-
console.log(` ${OK} Nothing needs attention`);
|
|
202
|
-
} else {
|
|
203
|
-
for (const item of alertItems) {
|
|
204
|
-
console.log(` ${severityPrefix(item.severity)}${item.title}`);
|
|
205
|
-
if (item.recommendedFix) {
|
|
206
|
-
console.log(` \x1b[2m${item.recommendedFix.slice(0, 100)}\x1b[0m`);
|
|
207
|
-
}
|
|
208
|
-
}
|
|
209
|
-
}
|
|
210
|
-
}
|
|
211
|
-
} catch (e) {
|
|
212
|
-
console.log(` ${WARN} Alerts unavailable: ${e.message}`);
|
|
213
|
-
}
|
|
214
|
-
|
|
215
|
-
// ── 5. Recent errors + perf + AI routing (last 1h) ───────────────────────
|
|
216
|
-
console.log('\n\x1b[1m── Recent Issues (last 1h) ─────────────────────────────────\x1b[0m');
|
|
217
|
-
try {
|
|
218
|
-
const stagingMsgBaseLocal = stagingMsgBase;
|
|
219
|
-
const from1h = new Date(Date.now() - 3600000).toISOString();
|
|
220
|
-
|
|
221
|
-
// One search at a time: the server runs at most 2 exact scans per instance. 429 (gate full) is retried honouring Retry-After.
|
|
222
|
-
const errRes = await fetchRetry429(`${stagingMsgBaseLocal}/superadmin/logs/search?level=ERROR&from=${from1h}&take=5`, () => ({
|
|
223
|
-
headers: { Authorization: `Bearer ${creds.velaroToken}`, 'X-Internal-SiteId': String(creds.siteId) },
|
|
224
|
-
signal: AbortSignal.timeout(40000),
|
|
225
|
-
}));
|
|
226
|
-
const perfRes = await fetchRetry429(`${stagingMsgBaseLocal}/superadmin/logs/search?q=${encodeURIComponent('WF-AI-ROUTE|PERF-SLOW')}®ex=true&from=${from1h}&take=20`, () => ({
|
|
227
|
-
headers: { Authorization: `Bearer ${creds.velaroToken}`, 'X-Internal-SiteId': String(creds.siteId) },
|
|
228
|
-
signal: AbortSignal.timeout(40000),
|
|
229
|
-
}));
|
|
230
|
-
|
|
231
|
-
// FIXED 2026-10-14: both searches used to look for the literal TEXT "level:ERROR" / "WF-AI-ROUTE OR PERF-SLOW" (never in any log
|
|
232
|
-
// line), so this check always said "0 errors". Errors are now the server-side level filter, perf/routing a regex, and an
|
|
233
|
-
// unverified or failed scan is reported instead of being counted as a clean result.
|
|
234
|
-
const errBody = errRes.ok ? await errRes.json().catch(() => null) : null;
|
|
235
|
-
const perfBody = perfRes.ok ? await perfRes.json().catch(() => null) : null;
|
|
236
|
-
const errors = errBody ? extractLogEntries(errBody) : [];
|
|
237
|
-
const perfLogs = perfBody ? extractLogEntries(perfBody) : [];
|
|
238
|
-
const scanNote = (label, body, ok) => (!ok || !body) ? `${label}: search failed or timed out (HTTP ${ok ? 'ok' : 'error'}), NOT verified` : (body.truncated === false ? null : `${label}: ${describeRawMeta(body)}`);
|
|
239
|
-
for (const n of [scanNote('errors', errBody, errRes.ok), scanNote('perf/routing', perfBody, perfRes.ok)].filter(Boolean)) console.log(` ${WARN} ${n}`);
|
|
240
|
-
|
|
241
|
-
const perfCount = perfLogs.filter(e => (e.Message ?? e.message ?? '').includes('PERF-SLOW')).length;
|
|
242
|
-
const routeCount = perfLogs.filter(e => (e.Message ?? e.message ?? '').includes('WF-AI-ROUTE')).length;
|
|
243
|
-
|
|
244
|
-
const errSym = errors.length ? ERR : OK;
|
|
245
|
-
const perfSym = perfCount ? WARN : OK;
|
|
246
|
-
const routeSym = routeCount ? '\x1b[36m🤖\x1b[0m' : OK;
|
|
247
|
-
|
|
248
|
-
console.log(` ${errSym} Errors last 1h: ${errors.length}`);
|
|
249
|
-
if (errors.length) {
|
|
250
|
-
for (const e of errors.slice(0, 3)) {
|
|
251
|
-
const msg = (e.Message ?? e.message ?? '').slice(0, 90);
|
|
252
|
-
console.log(` \x1b[31m${msg}\x1b[0m`);
|
|
253
|
-
}
|
|
254
|
-
}
|
|
255
|
-
console.log(` ${perfSym} Slow responses (PERF): ${perfCount}`);
|
|
256
|
-
console.log(` ${routeSym} AI routing events: ${routeCount}`);
|
|
257
|
-
if (errors.length || perfCount || routeCount) {
|
|
258
|
-
console.log(`\n Run \x1b[36mvelaro logs diagnose\x1b[0m for full detail.`);
|
|
259
|
-
}
|
|
260
|
-
} catch (e) {
|
|
261
|
-
console.log(` ${WARN} Could not load recent issues: ${e.message}`);
|
|
262
|
-
}
|
|
263
|
-
|
|
264
|
-
console.log('\n──────────────────────────────────────────────────────────────\n');
|
|
265
|
-
},
|
|
266
|
-
};
|
|
@@ -1,205 +0,0 @@
|
|
|
1
|
-
// CLI parity for MCP tool groups that previously had no CLI command group (parity-close 2026-10-23).
|
|
2
|
-
// Every subcommand calls the SAME REST route the matching MCP tool handler calls (mcp/server.js,
|
|
3
|
-
// mcp/staff-server.js). Admin-API routes go through request(); messaging-API routes through
|
|
4
|
-
// messagingRequest(). Staff-only tools are enforced server-side (the CLI only passes your token).
|
|
5
|
-
// Impactful subcommands need --yes. Naming: `velaro <group> <tool-name-without-group-prefix>`.
|
|
6
|
-
import { request, messagingRequest } from '../api.js';
|
|
7
|
-
import { supportCommand } from './support.js';
|
|
8
|
-
import { pricingCommand } from './pricing.js';
|
|
9
|
-
import { scraperCommand } from './scraper.js';
|
|
10
|
-
import { tourPolicyCommand } from './tour-policy.js';
|
|
11
|
-
import fs from 'node:fs';
|
|
12
|
-
import crypto from 'node:crypto';
|
|
13
|
-
|
|
14
|
-
const out = (r) => console.log(typeof r === 'string' ? r : JSON.stringify(r, null, 2));
|
|
15
|
-
const S = (describe, req) => ({ type: 'string', describe, ...(req ? { demandOption: true } : {}) });
|
|
16
|
-
const N = (describe, req) => ({ type: 'number', describe, ...(req ? { demandOption: true } : {}) });
|
|
17
|
-
const B = (describe) => ({ type: 'boolean', describe });
|
|
18
|
-
const csv = (v) => (v === undefined ? undefined : String(v).split(',').map((x) => x.trim()).filter(Boolean));
|
|
19
|
-
const csvN = (v) => csv(v)?.map(Number);
|
|
20
|
-
const enc = encodeURIComponent;
|
|
21
|
-
// '@file.json' reads a file; otherwise the string is parsed as JSON.
|
|
22
|
-
const json = (v) => (v === undefined ? undefined : JSON.parse(String(v).startsWith('@') ? fs.readFileSync(String(v).slice(1), 'utf8') : v));
|
|
23
|
-
const qs = (o) => {
|
|
24
|
-
const sp = new URLSearchParams();
|
|
25
|
-
for (const [k, v] of Object.entries(o)) if (v !== undefined && v !== null && v !== '') sp.set(k, String(v));
|
|
26
|
-
const s = sp.toString();
|
|
27
|
-
return s ? `?${s}` : '';
|
|
28
|
-
};
|
|
29
|
-
const pick = (a, map) => Object.fromEntries(Object.entries(map).filter(([f]) => a[f] !== undefined).map(([f, k]) => [k, a[f]]));
|
|
30
|
-
const exclusiveEnd = (d) => (/^\d{4}-\d{2}-\d{2}$/.test(d || '') ? new Date(Date.parse(d) + 86400000).toISOString().slice(0, 10) : d);
|
|
31
|
-
|
|
32
|
-
// Messaging admin-tools gateway (same endpoint the MCP uses for ms_bookings_*/outlook_calendar_* range/cancel tools).
|
|
33
|
-
async function gatewayTool(name, args) {
|
|
34
|
-
const r = await messagingRequest('POST', '/mcp/v1/admin-tools/call', { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name, arguments: args } });
|
|
35
|
-
if (r?.error) throw new Error(`${name}: ${r.error.message || JSON.stringify(r.error)}`);
|
|
36
|
-
return r?.result?.content?.[0]?.text ?? r;
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
async function call(s, a) {
|
|
40
|
-
const fn = s.api === 'msg' ? messagingRequest : request;
|
|
41
|
-
return fn(s.method || 'GET', s.path(a), s.body ? s.body(a) : undefined);
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
// Safety guard for subscription/expiry writes. Default is DENY: these commands refuse to run
|
|
45
|
-
// unless VELARO_ALLOW_SUBSCRIPTION_WRITE=1 is set, and a protected site can never be written from
|
|
46
|
-
// the CLI. Site 20678 (Northern New England Poison Control) is protected: it stays on its own
|
|
47
|
-
// account and expiry controls, and must not be extended, flagged, or changed from this CLI.
|
|
48
|
-
const PROTECTED_SITE_IDS = new Set([20678]);
|
|
49
|
-
function subscriptionWriteGuard(a) {
|
|
50
|
-
if (process.env.VELARO_ALLOW_SUBSCRIPTION_WRITE !== '1') return 'Subscription writes are disabled in the CLI. Set VELARO_ALLOW_SUBSCRIPTION_WRITE=1 for one deliberate run.';
|
|
51
|
-
const id = Number(a.site);
|
|
52
|
-
if (PROTECTED_SITE_IDS.has(id)) return `Site ${id} is protected. Subscription and expiry changes for it are not allowed from the CLI.`;
|
|
53
|
-
return null;
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
export function addRoutes(y, specs) {
|
|
57
|
-
for (const s of specs) {
|
|
58
|
-
y.command(s.name, s.desc, (yy) => {
|
|
59
|
-
for (const [k, v] of Object.entries(s.opts || {})) yy.option(k, v);
|
|
60
|
-
if (s.yes || s.needsYes) yy.option('yes', B('Confirm this impactful action'));
|
|
61
|
-
return yy;
|
|
62
|
-
}, async (a) => {
|
|
63
|
-
try {
|
|
64
|
-
if ((s.yes || (s.needsYes && s.needsYes(a))) && !a.yes) { console.error(`Refusing without --yes: ${s.desc}`); process.exit(1); }
|
|
65
|
-
if (s.guard) { const why = s.guard(a); if (why) { console.error(`Refused: ${why}`); process.exit(1); } }
|
|
66
|
-
out(s.run ? await s.run(a) : await call(s, a));
|
|
67
|
-
} catch (e) { console.error(e.message); process.exit(1); }
|
|
68
|
-
});
|
|
69
|
-
}
|
|
70
|
-
return y;
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
const site = { site: N('Site id', true) };
|
|
74
|
-
const SP = (a) => `SupportTools/sites/${a.site}`;
|
|
75
|
-
const rpcOpts = { args: S('Extra tool arguments as JSON or @file.json') };
|
|
76
|
-
const rpcArgs = (a, map) => ({ ...pick(a, map), ...(json(a.args) || {}) });
|
|
77
|
-
|
|
78
|
-
export const SUPPORT_EXTRA = [
|
|
79
|
-
{ name: 'user-lookup', desc: 'Search users by email/name across sites (staff)', opts: { query: S('Search text', true) }, path: (a) => `SupportTools/users/search?q=${enc(a.query)}` },
|
|
80
|
-
{ name: 'site-lookup', desc: 'Search sites by name/URL/admin (staff)', opts: { query: S('Search text', true) }, path: (a) => `SupportTools/sites/search?q=${enc(a.query)}` },
|
|
81
|
-
{ name: 'change-username', desc: 'Change a user login email (staff)', yes: true, method: 'POST', opts: { 'user-id': N('User id', true), 'new-email': S('New email', true) }, path: (a) => `SupportTools/users/${a.userId}/change-username`, body: (a) => ({ newEmail: a.newEmail }) },
|
|
82
|
-
{ name: 'list-admin-users', desc: 'List Velaro staff/admin users', path: () => 'SupportTools/admin-users' },
|
|
83
|
-
{ name: 'list-staff', desc: 'List Velaro staff with roles', path: () => 'SupportTools/admin-users' },
|
|
84
|
-
{ name: 'add-admin-user', desc: 'Grant staff admin access to an email', yes: true, method: 'POST', opts: { email: S('Email', true) }, path: () => 'SupportTools/admin-users', body: (a) => ({ email: a.email }) },
|
|
85
|
-
{ name: 'remove-admin-user', desc: 'Remove staff admin access for a user id', yes: true, method: 'DELETE', opts: { 'user-id': N('User id', true) }, path: (a) => `SupportTools/admin-users/${a.userId}` },
|
|
86
|
-
{ name: 'set-staff-role', desc: 'Set a staff user role', yes: true, method: 'PATCH', opts: { 'user-id': N('User id', true), role: S('Role', true) }, path: (a) => `SupportTools/admin-users/${a.userId}/role`, body: (a) => ({ role: a.role }) },
|
|
87
|
-
{ name: 'integration-logs', desc: 'Integration log entries for a site', opts: { ...site, page: N('Page'), 'page-size': N('Page size (max 100)'), integration: S('Integration'), severity: S('Severity') }, path: (a) => `${SP(a)}/integration-logs${qs({ page: a.page ?? 1, pageSize: Math.min(100, a.pageSize ?? 50), integration: a.integration, severity: a.severity && a.severity !== 'All' ? a.severity : undefined })}` },
|
|
88
|
-
{ name: 'site-health', desc: 'Site health: subscription, agents, last login, 7-day errors', opts: site, path: (a) => `${SP(a)}/health` },
|
|
89
|
-
{ name: 'site-agents', desc: 'Agents on a site', opts: site, path: (a) => `${SP(a)}/agents` },
|
|
90
|
-
{ name: 'site-activity', desc: 'Activity log for a site', opts: { ...site, page: N('Page'), 'page-size': N('Page size (max 200)'), category: S('Category') }, path: (a) => `${SP(a)}/activity${qs({ page: a.page ?? 1, pageSize: Math.min(200, a.pageSize ?? 50), category: a.category })}` },
|
|
91
|
-
{ name: 'extend-subscription', desc: 'Extend a site subscription by N days', guard: subscriptionWriteGuard, yes: true, method: 'POST', opts: { ...site, days: N('Days', true) }, path: (a) => `${SP(a)}/extend-subscription`, body: (a) => ({ days: a.days }) },
|
|
92
|
-
{ name: 'set-user-active', desc: 'Activate/deactivate a user on a site', yes: true, method: 'POST', opts: { ...site, 'user-id': N('User id', true), active: { type: 'boolean', demandOption: true, describe: 'true or false' } }, path: (a) => `SupportTools/users/${a.userId}/sites/${a.site}/set-active`, body: (a) => ({ isActive: a.active }) },
|
|
93
|
-
{ name: 'bulk-set-flags', desc: 'Set several subscription flags at once (JSON object)', guard: subscriptionWriteGuard, yes: true, method: 'POST', opts: { ...site, flags: S('JSON object or @file.json', true) }, path: (a) => `${SP(a)}/subscription/bulk-flags`, body: (a) => ({ flags: json(a.flags) }) },
|
|
94
|
-
{ name: 'create-agent', desc: 'Create an agent on any site (staff)', api: 'msg', method: 'POST', opts: { ...site, email: S('Email', true), 'first-name': S('First name'), 'last-name': S('Last name'), roles: S('Comma list of roles'), 'team-ids': S('Comma list of team ids'), 'max-chats': N('Max chats (0 = default)') }, path: (a) => `/SupportTools/sites/${a.site}/agents`, body: (a) => ({ email: a.email, firstName: a.firstName, lastName: a.lastName, roles: csv(a.roles), teamIds: csvN(a.teamIds), maxChats: a.maxChats ?? 0 }) },
|
|
95
|
-
{ name: 'schedule-adherence', desc: 'Schedule adherence diagnostics for a site', api: 'msg', opts: { ...site, role: S('role'), 'agent-id': N('Agent id (required when role=agent)'), start: S('Start'), end: S('End'), tz: S('Timezone') }, path: (a) => `/Reports/sites/${a.site}/schedule-adherence-diagnostics${qs({ detail: 'true', role: a.role, agentId: a.agentId, start: a.start, end: a.end, tz: a.tz })}` },
|
|
96
|
-
{ name: 'appointments-list-sites', desc: 'Sites with Velaro Appointments enabled', api: 'msg', path: () => '/Appointments/admin/sites-with-appointments' },
|
|
97
|
-
{ name: 'diagnose-after-hours', desc: 'After-hours routing diagnostic data for a site', opts: site, path: (a) => `${SP(a)}/after-hours-routing` },
|
|
98
|
-
{ name: 'diagnose', desc: 'One-shot site diagnosis: health, recent errors, activity, failed Hangfire jobs', opts: site, run: async (a) => {
|
|
99
|
-
const g = (p) => request('GET', p).catch((e) => ({ error: e.message }));
|
|
100
|
-
const [health, integrationErrors, aiToolErrors, activity, failedJobs] = await Promise.all([
|
|
101
|
-
g(`${SP(a)}/health`), g(`${SP(a)}/integration-logs?severity=Error&pageSize=10`), g(`${SP(a)}/integration-logs?severity=Error&category=AiTool&pageSize=10`), g(`${SP(a)}/activity?pageSize=5`), g('DatabaseTool/FailedJobs')]);
|
|
102
|
-
return { health, integrationErrors, aiToolErrors, activity, failedJobs };
|
|
103
|
-
} },
|
|
104
|
-
];
|
|
105
|
-
|
|
106
|
-
const SCRAPER_EXTRA = [
|
|
107
|
-
{ name: 'staff-crawl', desc: 'Trigger a crawl for any site (staff)', method: 'POST', opts: { ...site, urls: S('Comma list of URLs', true), name: S('Job name'), 'crawl-depth': N('Crawl depth (default 1)'), 'max-pages': N('Max pages (default 25)') }, path: (a) => `ScraperJobs/StaffCreate/${a.site}`, body: (a) => ({ name: a.name || `staff-triggered-${a.site}`, urls: csv(a.urls), crawlDepth: a.crawlDepth ?? 1, maxPages: a.maxPages ?? 25 }) },
|
|
108
|
-
];
|
|
109
|
-
|
|
110
|
-
const LIVEFLUENCE = [
|
|
111
|
-
{ name: 'export', desc: 'Export V10 routing rules for a V10 site', opts: { 'v10-site-id': N('V10 site id', true), 'v20-site-id': N('V20 site id'), 'include-non-routing': B('Include non-routing rules'), 'path-only-urls': B('Strip URL terms to path (demo testing only)') }, path: (a) => `DatabaseTool/V10Export/${a.v10SiteId}${qs({ v20SiteId: a.v20SiteId, includeNonRouting: a.includeNonRouting ? 'true' : undefined, pathOnlyUrls: a.pathOnlyUrls ? 'true' : undefined })}` },
|
|
112
|
-
{ name: 'create-teams', desc: 'Create V20 teams from V10 groups (use --dry-run first)', method: 'POST', needsYes: (a) => !a.dryRun, opts: { 'v10-site-id': N('V10 site id', true), 'v20-site-id': N('V20 site id', true), 'dry-run': B('Preview only'), 'group-names': S('Comma list of V10 group names') }, path: () => 'DatabaseTool/V10CreateTeams', body: (a) => ({ v10SiteId: a.v10SiteId, v20SiteId: a.v20SiteId, dryRun: !!a.dryRun, groupNames: csv(a.groupNames) ?? [] }) },
|
|
113
|
-
{ name: 'site-workflows-list', desc: 'List a site workflows', opts: { 'site-id': N('Site id', true) }, path: (a) => `DatabaseTool/SiteWorkflows/${a.siteId}` },
|
|
114
|
-
{ name: 'site-workflows-set-enabled', desc: 'Enable/disable workflows by id or name (use --dry-run first)', method: 'POST', needsYes: (a) => !a.dryRun, opts: { 'site-id': N('Site id', true), 'workflow-ids': S('Comma list of ids'), names: S('Comma list of names'), enabled: B('Enable (omit to disable)'), 'dry-run': B('Preview only'), 'force-partial': B('Allow partial match'), 'v10-site-id': N('V10 site id') }, path: () => 'DatabaseTool/SiteWorkflows/SetEnabled', body: (a) => ({ siteId: a.siteId, workflowIds: csvN(a.workflowIds) ?? [], names: csv(a.names) ?? [], enabled: !!a.enabled, dryRun: !!a.dryRun, forcePartial: !!a.forcePartial, v10SiteId: a.v10SiteId ?? null }) },
|
|
115
|
-
{ name: 'site-workflow-create', desc: 'Create a workflow from a nodes blob', method: 'POST', needsYes: (a) => !a.dryRun, opts: { 'site-id': N('Site id', true), name: S('Name', true), 'trigger-type': S('Trigger (default conversation_opened)'), 'nodes-blob': S('Nodes JSON or @file.json', true), enabled: B('Enable on create'), 'dry-run': B('Preview only') }, path: () => 'DatabaseTool/SiteWorkflows/Create', body: (a) => ({ siteId: a.siteId, name: a.name, triggerType: a.triggerType ?? 'conversation_opened', nodesBlob: String(a.nodesBlob).startsWith('@') ? fs.readFileSync(String(a.nodesBlob).slice(1), 'utf8') : a.nodesBlob, enabled: !!a.enabled, dryRun: !!a.dryRun }) },
|
|
116
|
-
{ name: 'site-workflow-set-action', desc: 'Point a workflow action at a target', method: 'POST', needsYes: (a) => !a.dryRun, opts: { 'site-id': N('Site id', true), 'workflow-id': N('Workflow id', true), 'action-type': S('Action type', true), 'target-id': N('Target id', true), 'dry-run': B('Preview only') }, path: () => 'DatabaseTool/SiteWorkflows/SetAction', body: (a) => ({ siteId: a.siteId, workflowId: a.workflowId, actionType: a.actionType, targetId: a.targetId, dryRun: !!a.dryRun }) },
|
|
117
|
-
{ name: 'site-rules-list', desc: 'List a site routing rules', opts: { 'site-id': N('Site id', true) }, path: (a) => `DatabaseTool/SiteRules/${a.siteId}` },
|
|
118
|
-
{ name: 'site-rules-set-enabled', desc: 'Enable/disable routing rules', method: 'POST', needsYes: (a) => !a.dryRun, opts: { 'site-id': N('Site id', true), 'rule-ids': S('Comma list of ids'), trigger: S('Trigger filter'), enabled: B('Enable (omit to disable)'), 'dry-run': B('Preview only') }, path: () => 'DatabaseTool/SiteRules/SetEnabled', body: (a) => ({ siteId: a.siteId, ruleIds: csvN(a.ruleIds) ?? [], trigger: a.trigger ?? null, enabled: !!a.enabled, dryRun: !!a.dryRun }) },
|
|
119
|
-
{ name: 'seed-url-rules', desc: 'Seed URL rules for an AI config', method: 'POST', needsYes: (a) => !a.dryRun, opts: { 'site-id': N('Site id', true), 'ai-config-id': N('AI config id', true), rules: S('Rules JSON or @file.json', true), 'dry-run': B('Preview only') }, path: () => 'DatabaseTool/V10SeedUrlRules', body: (a) => ({ siteId: a.siteId, aiConfigId: a.aiConfigId, dryRun: !!a.dryRun, rules: json(a.rules) }) },
|
|
120
|
-
{ name: 'conversion-advisor', desc: 'Advise on V10 to V20 conversion (apply with --apply --yes)', method: 'POST', needsYes: (a) => !!a.apply, opts: { 'v10-site-id': N('V10 site id'), 'v20-site-id': N('V20 site id', true), apply: B('Apply recommendations'), 'include-non-routing': B('Include non-routing'), intents: S('Intents JSON array') }, path: () => 'DatabaseTool/ConversionAdvisor', body: (a) => { const intents = json(a.intents); return { v10SiteId: intents?.length ? null : (a.v10SiteId ?? null), v20SiteId: a.v20SiteId, apply: !!a.apply, includeNonRouting: !!a.includeNonRouting, intents: intents ?? null }; } },
|
|
121
|
-
{ name: 'migrate', desc: 'Migrate V10 routing to V20 workflows (use --dry-run first)', method: 'POST', needsYes: (a) => !a.dryRun, opts: { 'v10-site-id': N('V10 site id', true), 'v20-site-id': N('V20 site id'), 'dry-run': B('Preview only'), enable: B('Enable created workflows'), 'include-non-routing': B('Include non-routing'), 'route-bot-groups-to-team': B('Route bot groups to team'), 'path-only-urls': B('Strip URL terms to path (demo testing only)'), 'page-team-availability': B('Launcher availability follows the page team like v10 (default on; --no-page-team-availability to skip)'), 'team-mappings': S('JSON or @file'), 'ai-config-mappings': S('JSON or @file') }, path: () => 'DatabaseTool/V10Migrate', body: (a) => ({ v10SiteId: a.v10SiteId, v20SiteId: a.v20SiteId ?? null, dryRun: !!a.dryRun, enable: !!a.enable, includeNonRouting: !!a.includeNonRouting, routeBotGroupsToTeam: !!a.routeBotGroupsToTeam, pathOnlyUrls: !!a.pathOnlyUrls, pageTeamAvailability: a.pageTeamAvailability !== false, teamMappings: json(a.teamMappings) ?? [], aiConfigMappings: json(a.aiConfigMappings) ?? [] }) },
|
|
122
|
-
];
|
|
123
|
-
|
|
124
|
-
const TABLES = {
|
|
125
|
-
missed: [{ name: 'chat-diagnostics', desc: 'Missed chat diagnostics with routing snapshots', opts: { start: S('Start date'), end: S('End date'), reason: S('Reason filter'), 'team-id': N('Team id'), site: N('Site id (staff)') }, path: (a) => `CallCenterAnalytics/MissedChatDiagnostics${qs({ start: a.start, end: a.end, reason: a.reason, teamId: a.teamId, siteId: a.site })}` }],
|
|
126
|
-
service: [{ name: 'level-report', desc: 'Service level (SLA) report', opts: { 'start-date': S('Start'), 'end-date': S('End (inclusive date)'), granularity: S('day|week|month') }, path: (a) => `ServiceLevel${qs({ startDate: a.startDate, endDate: exclusiveEnd(a.endDate), granularity: a.granularity })}` }],
|
|
127
|
-
page: [
|
|
128
|
-
{ name: 'widget-list', desc: 'List page widgets', path: () => 'PageWidgets' },
|
|
129
|
-
{ name: 'widget-get', desc: 'Get a page widget', opts: { id: N('Widget id', true) }, path: (a) => `PageWidgets/${a.id}` },
|
|
130
|
-
{ name: 'widget-toggle', desc: 'Enable or disable a page widget', opts: { id: N('Widget id', true), enabled: { type: 'boolean', demandOption: true, describe: 'true or false' } }, run: async (a) => { const w = await request('GET', `PageWidgets/${a.id}`); w.isEnabled = !!a.enabled; await request('PUT', `PageWidgets/${a.id}`, w); return `Widget ${a.id} ${a.enabled ? 'enabled' : 'disabled'}.`; } },
|
|
131
|
-
],
|
|
132
|
-
uploaded: [
|
|
133
|
-
{ name: 'files-list', desc: 'List uploaded AI training files', api: 'msg', path: () => '/uploadedFiles/list/AI' },
|
|
134
|
-
{ name: 'file-reindex', desc: 'Re-index an uploaded file', api: 'msg', method: 'POST', opts: { 'file-id': N('File id'), 'file-name': S('File name'), 'index-name': S('Index name') }, path: () => '/uploadedFiles/reindex', body: (a) => { if (!a.fileId && !a.fileName) throw new Error('--file-id or --file-name is required'); return pick(a, { fileId: 'id', fileName: 'fileName', indexName: 'indexName' }); } },
|
|
135
|
-
],
|
|
136
|
-
ms: [
|
|
137
|
-
{ name: 'bookings-status', desc: 'Microsoft Bookings status for a site (staff)', opts: site, path: (a) => `MicrosoftBookings/superadmin/status?siteId=${a.site}` },
|
|
138
|
-
{ name: 'bookings-configure', desc: 'Configure Microsoft Bookings for a site (staff)', method: 'PUT', opts: { ...site, 'business-id': S('Business id', true), 'business-display-name': S('Display name'), disabled: B('Disable the integration') }, path: (a) => `MicrosoftBookings/superadmin/config?siteId=${a.site}`, body: (a) => ({ businessId: a.businessId, businessDisplayName: a.businessDisplayName ?? '', isEnabled: !a.disabled }) },
|
|
139
|
-
{ name: 'bookings-check-availability-range', desc: 'Bookings availability range for a service', opts: { 'service-id': S('Service id', true), ...rpcOpts }, run: (a) => gatewayTool('ms_bookings_check_availability_range', rpcArgs(a, { serviceId: 'service_id' })) },
|
|
140
|
-
{ name: 'bookings-cancel-appointment', desc: 'Cancel a Bookings appointment', yes: true, opts: { 'appointment-id': S('Appointment id', true), ...rpcOpts }, run: (a) => gatewayTool('ms_bookings_cancel_appointment', rpcArgs(a, { appointmentId: 'appointment_id' })) },
|
|
141
|
-
{ name: 'bookings-reschedule-appointment', desc: 'Reschedule a Bookings appointment', yes: true, opts: { 'appointment-id': S('Appointment id', true), 'new-date': S('YYYY-MM-DD', true), 'new-start-time': S('HH:mm', true), ...rpcOpts }, run: (a) => gatewayTool('ms_bookings_reschedule_appointment', rpcArgs(a, { appointmentId: 'appointment_id', newDate: 'new_date', newStartTime: 'new_start_time' })) },
|
|
142
|
-
],
|
|
143
|
-
outlook: [
|
|
144
|
-
{ name: 'calendar-status', desc: 'Outlook calendar status for a site (staff)', opts: site, path: (a) => `OutlookCalendar/superadmin/status?siteId=${a.site}` },
|
|
145
|
-
{ name: 'calendar-test-connection', desc: 'Test the Outlook calendar connection (staff)', opts: { ...site, 'organizer-email': S('Organizer email') }, path: (a) => `OutlookCalendar/superadmin/test-connection?siteId=${a.site}${a.organizerEmail ? `&organizerEmail=${enc(a.organizerEmail)}` : ''}` },
|
|
146
|
-
{ name: 'calendar-get-available-range', desc: 'Available calendar time range', opts: rpcOpts, run: (a) => gatewayTool('outlook_calendar_get_available_range', rpcArgs(a, {})) },
|
|
147
|
-
{ name: 'calendar-cancel', desc: 'Cancel an Outlook calendar event', yes: true, opts: { 'event-id': S('Event id', true), ...rpcOpts }, run: (a) => gatewayTool('outlook_calendar_cancel', rpcArgs(a, { eventId: 'event_id' })) },
|
|
148
|
-
],
|
|
149
|
-
oauth: [
|
|
150
|
-
{ name: 'list', desc: 'List stored OAuth app configs (staff)', path: () => 'SupportTools/oauth-configs' },
|
|
151
|
-
{ name: 'update', desc: 'Update an integration OAuth client id/secret (staff)', yes: true, method: 'PUT', opts: { integration: S('Integration key', true), 'client-id': S('Client id'), 'client-secret': S('Client secret') }, path: (a) => `SupportTools/oauth-configs/${enc(a.integration)}`, body: (a) => { if (!a.clientId && !a.clientSecret) throw new Error('Pass --client-id and/or --client-secret'); return { clientId: a.clientId, clientSecret: a.clientSecret }; } },
|
|
152
|
-
],
|
|
153
|
-
provision: [{ name: 'health', desc: 'Provisioning health checks (run after every staging deploy)', api: 'msg', path: () => '/SuperAdmin/provision-health' }],
|
|
154
|
-
sse: [{ name: 'visitor-diagnostic', desc: 'SSE visitor transport diagnostic', api: 'msg', path: () => '/Diagnostics/sse' }],
|
|
155
|
-
skill: [{ name: 'logs-for-site', desc: 'AI skill call logs for a site (staff)', opts: { ...site, take: N('Entries (max 200)'), 'errors-only': B('Errors only') }, path: (a) => `SuperAdmin/Diagnostics/skill-logs?siteId=${a.site}&take=${Math.min(a.take ?? 50, 200)}&errorsOnly=${!!a.errorsOnly}` }],
|
|
156
|
-
v10: [{ name: 'bot-turn-limits', desc: 'v10 sites with a MaximumBotTurnsPerMonth limit (staff)', path: () => 'BotAnalytics/V10BotTurnLimits' }],
|
|
157
|
-
whatsapp: [{ name: 'campaign-diagnostic', desc: 'WhatsApp campaign diagnostic for a site (staff)', api: 'msg', opts: site, path: (a) => `/Diagnostics/whatsapp-campaign/${a.site}` }],
|
|
158
|
-
mobile: [{ name: 'ota-trigger', desc: 'Trigger the mobile OTA build (GitHub Actions mobile-build.yml; needs GITHUB_TOKEN)', yes: true, run: async () => {
|
|
159
|
-
const token = process.env.GITHUB_TOKEN;
|
|
160
|
-
if (!token) throw new Error('GITHUB_TOKEN env var is not set.');
|
|
161
|
-
const r = await fetch('https://api.github.com/repos/velaro/velaro-messaging/actions/workflows/mobile-build.yml/dispatches', { method: 'POST', headers: { Authorization: `Bearer ${token}`, Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28', 'Content-Type': 'application/json' }, body: JSON.stringify({ ref: 'master', inputs: { profile: 'preview' } }) });
|
|
162
|
-
if (r.status !== 204) throw new Error(`GitHub API returned ${r.status}: ${await r.text()}`);
|
|
163
|
-
return 'Mobile OTA triggered on GitHub Actions (mobile-build.yml -> master).';
|
|
164
|
-
} }],
|
|
165
|
-
signalr: [{ name: 'diagnostics', desc: 'Azure SignalR health (needs SIGNALR_INFRA_CONN / SIGNALR_PROD_CONN env)', opts: { instance: { type: 'string', choices: ['infra', 'legacy', 'both'], default: 'both' }, hub: S('Hub name, e.g. MessengerHub') }, run: async (a) => {
|
|
166
|
-
const targets = [['infra', 'velaro-eastus-prd-signalr (infra)', process.env.SIGNALR_INFRA_CONN], ['legacy', 'velaro-prod-us (legacy)', process.env.SIGNALR_PROD_CONN]].filter(([k]) => a.instance === 'both' || a.instance === k);
|
|
167
|
-
const res = {};
|
|
168
|
-
for (const [, label, conn] of targets) {
|
|
169
|
-
const ep = (/Endpoint=([^;]+)/i.exec(conn || '') || [])[1]; const key = (/AccessKey=([^;]+)/i.exec(conn || '') || [])[1];
|
|
170
|
-
if (!ep || !key) { res[label] = 'connection string not set in env'; continue; }
|
|
171
|
-
const endpoint = ep.replace(/\/+$/, '');
|
|
172
|
-
const jwt = (url) => { const h = Buffer.from(JSON.stringify({ alg: 'HS256', typ: 'JWT' })).toString('base64url'); const n = Math.floor(Date.now() / 1000); const p = Buffer.from(JSON.stringify({ aud: url, iat: n, exp: n + 300 })).toString('base64url'); return `${h}.${p}.${crypto.createHmac('sha256', Buffer.from(key, 'base64')).update(`${h}.${p}`).digest('base64url')}`; };
|
|
173
|
-
const get = async (url) => { const r = await fetch(url, { headers: { Authorization: `Bearer ${jwt(url)}` } }); return { status: r.status, body: (await r.text()).slice(0, 2000) }; };
|
|
174
|
-
res[label] = { health: await get(`${endpoint}/api/v1/health`), ...(a.hub ? { hub: await get(`${endpoint}/api/v1/hubs/${a.hub}`) } : {}) };
|
|
175
|
-
}
|
|
176
|
-
return res;
|
|
177
|
-
} }],
|
|
178
|
-
};
|
|
179
|
-
|
|
180
|
-
const demand = (y, msg) => y.demandCommand(1, msg);
|
|
181
|
-
|
|
182
|
-
export const livefluenceCommand = {
|
|
183
|
-
command: 'livefluence', describe: 'Velaro staff: V10 (LiveFluence) to V20 migration and per-site workflow/rule tools',
|
|
184
|
-
builder: (y) => demand(addRoutes(y, LIVEFLUENCE), 'Specify a subcommand'), handler: () => {},
|
|
185
|
-
};
|
|
186
|
-
export const missedCommand = { command: 'missed', describe: 'Missed chat diagnostics', builder: (y) => demand(addRoutes(y, TABLES.missed), 'Specify a subcommand'), handler: () => {} };
|
|
187
|
-
export const serviceCommand = { command: 'service', describe: 'Service level (SLA) report', builder: (y) => demand(addRoutes(y, TABLES.service), 'Specify a subcommand'), handler: () => {} };
|
|
188
|
-
export const pageCommand = { command: 'page', describe: 'Page widgets (list, get, toggle)', builder: (y) => demand(addRoutes(y, TABLES.page), 'Specify a subcommand'), handler: () => {} };
|
|
189
|
-
export const uploadedCommand = { command: 'uploaded', describe: 'Uploaded AI training files (list, reindex)', builder: (y) => demand(addRoutes(y, TABLES.uploaded), 'Specify a subcommand'), handler: () => {} };
|
|
190
|
-
export const msCommand = { command: 'ms', describe: 'Microsoft Bookings (status, configure, availability, cancel, reschedule)', builder: (y) => demand(addRoutes(y, TABLES.ms), 'Specify a subcommand'), handler: () => {} };
|
|
191
|
-
export const outlookCommand = { command: 'outlook', describe: 'Outlook calendar (status, test connection, availability, cancel)', builder: (y) => demand(addRoutes(y, TABLES.outlook), 'Specify a subcommand'), handler: () => {} };
|
|
192
|
-
export const oauthCommand = { command: 'oauth', describe: 'Velaro staff: stored OAuth app configs', builder: (y) => demand(addRoutes(y, TABLES.oauth), 'Specify a subcommand'), handler: () => {} };
|
|
193
|
-
export const provisionCommand = { command: 'provision', describe: 'Velaro staff: provisioning health', builder: (y) => demand(addRoutes(y, TABLES.provision), 'Specify a subcommand'), handler: () => {} };
|
|
194
|
-
export const sseCommand = { command: 'sse', describe: 'Velaro staff: SSE visitor transport diagnostic', builder: (y) => demand(addRoutes(y, TABLES.sse), 'Specify a subcommand'), handler: () => {} };
|
|
195
|
-
export const skillCommand = { command: 'skill', describe: 'Velaro staff: AI skill logs for a site', builder: (y) => demand(addRoutes(y, TABLES.skill), 'Specify a subcommand'), handler: () => {} };
|
|
196
|
-
export const v10Command = { command: 'v10', describe: 'Velaro staff: v10 bot turn limits', builder: (y) => demand(addRoutes(y, TABLES.v10), 'Specify a subcommand'), handler: () => {} };
|
|
197
|
-
export const whatsappCommand = { command: 'whatsapp', describe: 'Velaro staff: WhatsApp campaign diagnostic', builder: (y) => demand(addRoutes(y, TABLES.whatsapp), 'Specify a subcommand'), handler: () => {} };
|
|
198
|
-
export const mobileCommand = { command: 'mobile', describe: 'Velaro staff: mobile OTA build trigger', builder: (y) => demand(addRoutes(y, TABLES.mobile), 'Specify a subcommand'), handler: () => {} };
|
|
199
|
-
export const signalrCommand = { command: 'signalr', describe: 'Velaro staff: Azure SignalR diagnostics', builder: (y) => demand(addRoutes(y, TABLES.signalr), 'Specify a subcommand'), handler: () => {} };
|
|
200
|
-
|
|
201
|
-
// Existing inline-registered groups, re-exposed as detectable command objects with the missing subcommands added.
|
|
202
|
-
export const supportGroupCommand = { command: 'support', describe: 'Staff SupportTools actions on a site (superadmin only)', builder: (y) => addRoutes(supportCommand(y), SUPPORT_EXTRA), handler: () => {} };
|
|
203
|
-
export const pricingGroupCommand = { command: 'pricing', describe: 'View and manage the pricing catalog', builder: pricingCommand, handler: () => {} };
|
|
204
|
-
export const scraperGroupCommand = { command: 'scraper', describe: 'Velaro staff: scraper / upload / chunk usage and crawl for any site', builder: (y) => addRoutes(scraperCommand(y), SCRAPER_EXTRA), handler: () => {} };
|
|
205
|
-
export const tourPolicyGroupCommand = { command: 'tour-policy', describe: 'Velaro staff: guided-tour auto-open policy (versioned, rollback-able)', builder: tourPolicyCommand, handler: () => {} };
|
package/lib/commands/pricing.js
DELETED
|
@@ -1,132 +0,0 @@
|
|
|
1
|
-
// velaro pricing — view and manage the pricing catalog (superadmin only)
|
|
2
|
-
import { request } from '../api.js';
|
|
3
|
-
|
|
4
|
-
const TYPE_ORDER = ['plan', 'addon', 'block', 'seat', 'compliance', 'skill'];
|
|
5
|
-
|
|
6
|
-
function fmt(pkg) {
|
|
7
|
-
const price = pkg.contactSales
|
|
8
|
-
? 'Contact sales'
|
|
9
|
-
: pkg.monthlyPriceCents
|
|
10
|
-
? `$${(pkg.monthlyPriceCents / 100).toFixed(0)}${pkg.unitLabel || '/mo'}`
|
|
11
|
-
: 'Free';
|
|
12
|
-
return ` ${pkg.packageKey.padEnd(42)} ${price.padEnd(18)} v${pkg.version} ${pkg.displayName}`;
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
async function listPackages(args) {
|
|
16
|
-
const pkgs = await request('GET', '/Pricing/catalog');
|
|
17
|
-
if (!Array.isArray(pkgs) || !pkgs.length) { console.log('No packages found.'); return; }
|
|
18
|
-
|
|
19
|
-
const typeFilter = args.type?.toLowerCase();
|
|
20
|
-
const filtered = typeFilter ? pkgs.filter(p => p.packageType === typeFilter) : pkgs;
|
|
21
|
-
if (!filtered.length) { console.log(`No packages with type '${typeFilter}'.`); return; }
|
|
22
|
-
|
|
23
|
-
const byType = {};
|
|
24
|
-
for (const p of filtered) {
|
|
25
|
-
if (!byType[p.packageType]) byType[p.packageType] = [];
|
|
26
|
-
byType[p.packageType].push(p);
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
console.log(`\nPricing Catalog (${filtered.length} packages)\n`);
|
|
30
|
-
const types = TYPE_ORDER.filter(t => byType[t]);
|
|
31
|
-
for (const t of types) {
|
|
32
|
-
console.log(`── ${t.toUpperCase()} (${byType[t].length}) ──`);
|
|
33
|
-
byType[t].forEach(p => console.log(fmt(p)));
|
|
34
|
-
console.log('');
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
async function getPackage(args) {
|
|
39
|
-
if (!args.key) { console.error('Usage: velaro pricing get --key addon.appointments'); process.exit(1); }
|
|
40
|
-
const p = await request('GET', `/Pricing/catalog/${args.key}`);
|
|
41
|
-
console.log(JSON.stringify(p, null, 2));
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
async function updatePackage(args) {
|
|
45
|
-
if (!args.key) { console.error('Usage: velaro pricing update --key addon.appointments [--price 59] [--name "..."] [--contact-sales]'); process.exit(1); }
|
|
46
|
-
const payload = {};
|
|
47
|
-
if (args.price != null) payload.monthlyPriceCents = Math.round(parseFloat(args.price) * 100);
|
|
48
|
-
if (args.discount != null) payload.annualDiscountBps = Math.round(parseFloat(args.discount) * 100);
|
|
49
|
-
if (args.name) payload.displayName = args.name;
|
|
50
|
-
if (args.description) payload.description = args.description;
|
|
51
|
-
if (args['contact-sales'] != null) payload.contactSales = args['contact-sales'];
|
|
52
|
-
if (args.active != null) payload.isActive = args.active;
|
|
53
|
-
|
|
54
|
-
if (!Object.keys(payload).length) { console.error('No fields to update. Use --price, --name, --description, --contact-sales, --active.'); process.exit(1); }
|
|
55
|
-
|
|
56
|
-
const result = await request('PUT', `/Pricing/catalog/${args.key}`, payload);
|
|
57
|
-
console.log(`✅ Package '${result.packageKey}' updated to v${result.version}.`);
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
async function createPackage(args) {
|
|
61
|
-
if (!args.key || !args.type || !args.name) {
|
|
62
|
-
console.error('Usage: velaro pricing create --key addon.my-feature --type addon --name "My Feature" [--price 49] [--description "..."] [--contact-sales]');
|
|
63
|
-
process.exit(1);
|
|
64
|
-
}
|
|
65
|
-
const body = {
|
|
66
|
-
packageKey: args.key,
|
|
67
|
-
packageType: args.type,
|
|
68
|
-
displayName: args.name,
|
|
69
|
-
description: args.description,
|
|
70
|
-
monthlyPriceCents: args.price ? Math.round(parseFloat(args.price) * 100) : 0,
|
|
71
|
-
contactSales: args['contact-sales'] ?? false,
|
|
72
|
-
unitLabel: args.unit || '/mo',
|
|
73
|
-
};
|
|
74
|
-
const result = await request('POST', '/Pricing/catalog', body);
|
|
75
|
-
console.log(`✅ Created package '${result.packageKey}' (v${result.version}).`);
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
async function seedCatalog() {
|
|
79
|
-
const result = await request('POST', '/Pricing/catalog/seed', {});
|
|
80
|
-
console.log(`✅ Seeded ${result.seeded} packages from PricingCatalogSeeder.cs defaults.`);
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
async function bulkAdjust(args) {
|
|
84
|
-
if (args.percent == null) { console.error('Usage: velaro pricing bulk-adjust --percent 10 [--type addon] [--force-contact-sales]'); process.exit(1); }
|
|
85
|
-
const pct = parseFloat(args.percent);
|
|
86
|
-
if (isNaN(pct) || pct === 0) { console.error('--percent must be a non-zero number (e.g. 10 for +10%, -5 for -5%)'); process.exit(1); }
|
|
87
|
-
|
|
88
|
-
const body = { percentChange: pct };
|
|
89
|
-
if (args.type) body.packageType = args.type;
|
|
90
|
-
if (args['force-contact-sales']) body.forceContactSales = true;
|
|
91
|
-
|
|
92
|
-
const result = await request('POST', '/Pricing/catalog/bulk-adjust', body);
|
|
93
|
-
const sign = pct > 0 ? '+' : '';
|
|
94
|
-
console.log(`\n✅ Applied ${sign}${pct}% to ${result.updated} packages:\n`);
|
|
95
|
-
for (const c of result.changes) {
|
|
96
|
-
const oldFmt = `$${(c.oldPrice / 100).toFixed(0)}`;
|
|
97
|
-
const newFmt = `$${(c.newPrice / 100).toFixed(0)}`;
|
|
98
|
-
const chgFmt = c.change >= 0 ? `+$${(c.change / 100).toFixed(0)}` : `-$${(Math.abs(c.change) / 100).toFixed(0)}`;
|
|
99
|
-
console.log(` ${c.packageKey.padEnd(42)} ${oldFmt.padStart(8)} → ${newFmt.padStart(8)} (${chgFmt}) ${c.displayName}`);
|
|
100
|
-
}
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
export function pricingCommand(yargs) {
|
|
104
|
-
return yargs
|
|
105
|
-
.command('list', 'List all pricing packages', y => y.option('type', { type: 'string', desc: 'Filter: plan | addon | block | seat | compliance | skill' }), a => listPackages(a))
|
|
106
|
-
.command('get', 'Get a single package by key', y => y.option('key', { type: 'string', demandOption: true }), a => getPackage(a))
|
|
107
|
-
.command('update', 'Update a package price or metadata', y => y
|
|
108
|
-
.option('key', { type: 'string', demandOption: true, desc: 'Package key' })
|
|
109
|
-
.option('price', { type: 'number', desc: 'New monthly price in dollars (e.g. 59)' })
|
|
110
|
-
.option('discount', { type: 'number', desc: 'Annual discount percentage (e.g. 20)' })
|
|
111
|
-
.option('name', { type: 'string', desc: 'New display name' })
|
|
112
|
-
.option('description', { type: 'string', desc: 'New description' })
|
|
113
|
-
.option('contact-sales', { type: 'boolean', desc: 'Set to hide price and show "Contact sales"' })
|
|
114
|
-
.option('active', { type: 'boolean', desc: 'Set to false to deactivate' })
|
|
115
|
-
, a => updatePackage(a))
|
|
116
|
-
.command('create', 'Create a new pricing package', y => y
|
|
117
|
-
.option('key', { type: 'string', demandOption: true, desc: 'Unique key (e.g. addon.my-feature)' })
|
|
118
|
-
.option('type', { type: 'string', demandOption: true, desc: 'plan | addon | block | seat | compliance | skill' })
|
|
119
|
-
.option('name', { type: 'string', demandOption: true, desc: 'Display name' })
|
|
120
|
-
.option('price', { type: 'number', desc: 'Monthly price in dollars' })
|
|
121
|
-
.option('description', { type: 'string', desc: 'Short description' })
|
|
122
|
-
.option('unit', { type: 'string', desc: 'Unit label (default: /mo)' })
|
|
123
|
-
.option('contact-sales', { type: 'boolean', desc: 'Show "Contact sales" instead of price' })
|
|
124
|
-
, a => createPackage(a))
|
|
125
|
-
.command('bulk-adjust', 'Apply a blanket % price change across all or filtered packages', y => y
|
|
126
|
-
.option('percent', { type: 'number', demandOption: true, desc: 'Percentage change: 10 = +10%, -5 = -5%' })
|
|
127
|
-
.option('type', { type: 'string', desc: 'Limit to one type: plan | addon | block | seat | compliance' })
|
|
128
|
-
.option('force-contact-sales', { type: 'boolean', desc: 'Also adjust "Contact sales" packages (default: skip them)' })
|
|
129
|
-
, a => bulkAdjust(a))
|
|
130
|
-
.command('seed', 'Re-seed catalog from PricingCatalogSeeder.cs defaults', () => {}, () => seedCatalog())
|
|
131
|
-
.demandCommand(1, 'Specify a subcommand: list | get | update | create | bulk-adjust | seed');
|
|
132
|
-
}
|