@velaro/cli 1.4.240 → 1.4.242

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.
@@ -1,30 +1,205 @@
1
- import { messagingGet, messagingPost } from '../api.js';
2
- import { runCommand } from '../run.js';
3
-
4
- // velaro scheduler get | set <slug>
5
- // Mirrors the scheduler_selection_get / scheduler_selection_update MCP tools.
6
- // Same endpoints as `velaro appointments get-scheduler|set-scheduler` (kept as aliases).
7
- export const schedulerCommand = {
8
- command: 'scheduler <subcommand>',
9
- describe: 'Choose which calendar/scheduler receives new bookings',
10
- builder: yargs => yargs
11
- .command({
12
- command: 'get',
13
- describe: 'Show which scheduler receives new bookings',
14
- handler: runCommand(async () => {
15
- const r = await messagingGet('/Appointments/Settings');
16
- console.log(`\nNew bookings go to: ${r?.writeTargetSlug || 'Velaro (first connected calendar)'}\n`);
17
- }),
18
- })
19
- .command({
20
- command: 'set <slug>',
21
- describe: 'Choose the scheduler (GoogleCalendar | OutlookCalendar | MicrosoftBookings | Calendly | Acuity | CalCom | none for Velaro)',
22
- builder: y => y.positional('slug', { describe: 'Provider slug, or "none"', type: 'string' }),
23
- handler: runCommand(async (argv) => {
24
- const slug = argv.slug.toLowerCase() === 'none' ? null : argv.slug;
25
- await messagingPost('/Appointments/Settings', { writeTargetSlug: slug });
26
- console.log(`\n✓ New bookings now go to ${slug ?? 'Velaro (first connected calendar)'}.\n`);
27
- }),
28
- })
29
- .demandCommand(1, 'Specify a subcommand: get | set'),
30
- };
1
+ import { messagingGet, messagingPost, messagingPut, messagingDel } from '../api.js';
2
+ import { runCommand } from '../run.js';
3
+
4
+ // -- velaro scheduler ------------------------------------------------------------
5
+ // Intake questions per bookable service and time off / special hours (date
6
+ // overrides) for the Velaro scheduler. Backend (velaro-messaging):
7
+ // /BookableServiceIntakeQuestions and /BookingDateOverrides. SiteId always derives
8
+ // from the caller's JWT server-side, never a CLI argument. Mirrors the
9
+ // scheduler_intake_question_* and scheduler_date_override_* MCP tools and the
10
+ // Moshky tools in CopilotBookingTools.cs.
11
+
12
+ const QUESTION_TYPES = ['text', 'textarea', 'select', 'checkbox'];
13
+
14
+ // Only send options the caller actually passed, so a PUT stays partial.
15
+ function pick(obj) {
16
+ const out = {};
17
+ for (const [k, v] of Object.entries(obj)) if (v !== undefined) out[k] = v;
18
+ return out;
19
+ }
20
+ function csv(v) { return v === undefined ? undefined : String(v).split(',').map(s => s.trim()).filter(Boolean); }
21
+
22
+ export const schedulerCommand = {
23
+ command: 'scheduler <subcommand>',
24
+ describe: 'Velaro scheduler -- booking calendar choice, intake questions and time off',
25
+ builder: yargs => yargs
26
+ .command({
27
+ command: 'intake <action>',
28
+ describe: 'Manage the intake questions customers answer when booking a service',
29
+ builder: y => y
30
+ .command({
31
+ command: 'list',
32
+ describe: 'List intake questions, optionally for one service',
33
+ builder: y2 => y2.option('service', { type: 'number', describe: 'Service id' }),
34
+ handler: runCommand(async argv => {
35
+ const qs = argv.service != null ? `?serviceId=${argv.service}` : '';
36
+ const rows = await messagingGet(`/BookableServiceIntakeQuestions${qs}`);
37
+ if (!Array.isArray(rows) || !rows.length) { console.log('\n No intake questions found.\n'); return; }
38
+ console.log('\nIntake Questions\n');
39
+ for (const q of rows) console.log(` id:${q.id} service:${q.bookableServiceId} [${q.questionType}]${q.isRequired ? ' required' : ''}${q.isActive === false ? ' (inactive)' : ''} ${q.label}`);
40
+ console.log('');
41
+ }),
42
+ })
43
+ .command({
44
+ command: 'get <id>',
45
+ describe: 'Get one intake question',
46
+ builder: y2 => y2.positional('id', { type: 'number' }),
47
+ handler: runCommand(async argv => {
48
+ console.log(JSON.stringify(await messagingGet(`/BookableServiceIntakeQuestions/${argv.id}`), null, 2));
49
+ }),
50
+ })
51
+ .command({
52
+ command: 'create',
53
+ describe: 'Add an intake question to a service',
54
+ builder: y2 => y2
55
+ .option('service', { type: 'number', demandOption: true, describe: 'Service id' })
56
+ .option('label', { type: 'string', demandOption: true, describe: 'Question text' })
57
+ .option('type', { type: 'string', choices: QUESTION_TYPES, demandOption: true })
58
+ .option('options', { type: 'string', describe: 'Comma-separated choices (select only)' })
59
+ .option('required', { type: 'boolean', describe: 'Customer must answer' })
60
+ .option('sort-order', { type: 'number' })
61
+ .option('active', { type: 'boolean' }),
62
+ handler: runCommand(async argv => {
63
+ const q = await messagingPost('/BookableServiceIntakeQuestions', pick({
64
+ bookableServiceId: argv.service, label: argv.label, questionType: argv.type,
65
+ options: csv(argv.options), isRequired: argv.required, sortOrder: argv.sortOrder, isActive: argv.active,
66
+ }));
67
+ console.log(`\n✓ Created intake question id:${q.id}\n`);
68
+ }),
69
+ })
70
+ .command({
71
+ command: 'update <id>',
72
+ describe: 'Update an intake question -- only supplied fields change',
73
+ builder: y2 => y2
74
+ .positional('id', { type: 'number' })
75
+ .option('label', { type: 'string' })
76
+ .option('type', { type: 'string', choices: QUESTION_TYPES })
77
+ .option('options', { type: 'string', describe: 'Comma-separated choices (select only)' })
78
+ .option('required', { type: 'boolean' })
79
+ .option('sort-order', { type: 'number' })
80
+ .option('active', { type: 'boolean' }),
81
+ handler: runCommand(async argv => {
82
+ await messagingPut(`/BookableServiceIntakeQuestions/${argv.id}`, pick({
83
+ label: argv.label, questionType: argv.type, options: csv(argv.options),
84
+ isRequired: argv.required, sortOrder: argv.sortOrder, isActive: argv.active,
85
+ }));
86
+ console.log(`\n✓ Updated intake question id:${argv.id}\n`);
87
+ }),
88
+ })
89
+ .command({
90
+ command: 'delete <id>',
91
+ describe: 'Delete an intake question',
92
+ builder: y2 => y2.positional('id', { type: 'number' }),
93
+ handler: runCommand(async argv => {
94
+ await messagingDel(`/BookableServiceIntakeQuestions/${argv.id}`);
95
+ console.log(`\n✓ Deleted intake question id:${argv.id}\n`);
96
+ }),
97
+ })
98
+ .demandCommand(1, 'Specify an intake action: list | get | create | update | delete'),
99
+ })
100
+ .command({
101
+ command: 'time-off <action>',
102
+ describe: 'Manage time off and special hours (date overrides)',
103
+ builder: y => y
104
+ .command({
105
+ command: 'list',
106
+ describe: 'List time off / special hours, optionally for one resource or from a date',
107
+ builder: y2 => y2
108
+ .option('resource', { type: 'number', describe: 'Resource id' })
109
+ .option('from', { type: 'string', describe: 'From date, yyyy-MM-dd' }),
110
+ handler: runCommand(async argv => {
111
+ const q = new URLSearchParams();
112
+ if (argv.resource != null) q.set('resourceId', String(argv.resource));
113
+ if (argv.from) q.set('fromDate', argv.from);
114
+ const rows = await messagingGet(`/BookingDateOverrides${q.toString() ? '?' + q : ''}`);
115
+ if (!Array.isArray(rows) || !rows.length) { console.log('\n No time off or special hours found.\n'); return; }
116
+ console.log('\nTime Off and Special Hours\n');
117
+ for (const o of rows) {
118
+ const what = o.isClosed ? 'closed' : `${o.startLocal || '-'}-${o.endLocal || '-'}`;
119
+ console.log(` id:${o.id} ${o.startDate}..${o.endDate} ${what} ${o.resourceId == null ? 'whole business' : 'resource:' + o.resourceId}${o.reason ? ' ' + o.reason : ''}`);
120
+ }
121
+ console.log('');
122
+ }),
123
+ })
124
+ .command({
125
+ command: 'get <id>',
126
+ describe: 'Get one time off entry',
127
+ builder: y2 => y2.positional('id', { type: 'number' }),
128
+ handler: runCommand(async argv => {
129
+ console.log(JSON.stringify(await messagingGet(`/BookingDateOverrides/${argv.id}`), null, 2));
130
+ }),
131
+ })
132
+ .command({
133
+ command: 'create',
134
+ describe: 'Add time off (default) or custom hours for a date range',
135
+ builder: y2 => y2
136
+ .option('start', { type: 'string', demandOption: true, describe: 'Start date, yyyy-MM-dd' })
137
+ .option('end', { type: 'string', demandOption: true, describe: 'End date, yyyy-MM-dd (inclusive)' })
138
+ .option('resource', { type: 'number', describe: 'Resource id (omit for the whole business)' })
139
+ .option('open-from', { type: 'string', describe: 'Custom hours start HH:mm (makes it special hours, not time off)' })
140
+ .option('open-to', { type: 'string', describe: 'Custom hours end HH:mm' })
141
+ .option('reason', { type: 'string' })
142
+ .option('timezone', { type: 'string', describe: 'IANA timezone id' })
143
+ .option('active', { type: 'boolean' }),
144
+ handler: runCommand(async argv => {
145
+ const custom = argv.openFrom != null || argv.openTo != null;
146
+ const o = await messagingPost('/BookingDateOverrides', pick({
147
+ resourceId: argv.resource, startDate: argv.start, endDate: argv.end, isClosed: !custom,
148
+ startLocal: argv.openFrom, endLocal: argv.openTo, reason: argv.reason, ianaTimeZone: argv.timezone, isActive: argv.active,
149
+ }));
150
+ console.log(`\n✓ Created ${custom ? 'special hours' : 'time off'} id:${o.id}\n`);
151
+ }),
152
+ })
153
+ .command({
154
+ command: 'update <id>',
155
+ describe: 'Update a time off entry -- only supplied fields change',
156
+ builder: y2 => y2
157
+ .positional('id', { type: 'number' })
158
+ .option('start', { type: 'string' })
159
+ .option('end', { type: 'string' })
160
+ .option('resource', { type: 'number' })
161
+ .option('closed', { type: 'boolean', describe: 'true = time off, false = custom hours' })
162
+ .option('open-from', { type: 'string' })
163
+ .option('open-to', { type: 'string' })
164
+ .option('reason', { type: 'string' })
165
+ .option('timezone', { type: 'string' })
166
+ .option('active', { type: 'boolean' }),
167
+ handler: runCommand(async argv => {
168
+ await messagingPut(`/BookingDateOverrides/${argv.id}`, pick({
169
+ resourceId: argv.resource, startDate: argv.start, endDate: argv.end, isClosed: argv.closed,
170
+ startLocal: argv.openFrom, endLocal: argv.openTo, reason: argv.reason, ianaTimeZone: argv.timezone, isActive: argv.active,
171
+ }));
172
+ console.log(`\n✓ Updated time off id:${argv.id}\n`);
173
+ }),
174
+ })
175
+ .command({
176
+ command: 'delete <id>',
177
+ describe: 'Delete a time off entry',
178
+ builder: y2 => y2.positional('id', { type: 'number' }),
179
+ handler: runCommand(async argv => {
180
+ await messagingDel(`/BookingDateOverrides/${argv.id}`);
181
+ console.log(`\n✓ Deleted time off id:${argv.id}\n`);
182
+ }),
183
+ })
184
+ .demandCommand(1, 'Specify a time-off action: list | get | create | update | delete'),
185
+ })
186
+ .command({
187
+ command: 'get',
188
+ describe: 'Show which scheduler receives new bookings',
189
+ handler: runCommand(async () => {
190
+ const r = await messagingGet('/Appointments/Settings');
191
+ console.log(`\nNew bookings go to: ${r?.writeTargetSlug || 'Velaro (first connected calendar)'}\n`);
192
+ }),
193
+ })
194
+ .command({
195
+ command: 'set <slug>',
196
+ describe: 'Choose the scheduler (GoogleCalendar | OutlookCalendar | MicrosoftBookings | Calendly | Acuity | CalCom | none for Velaro)',
197
+ builder: y => y.positional('slug', { describe: 'Provider slug, or "none"', type: 'string' }),
198
+ handler: runCommand(async (argv) => {
199
+ const slug = argv.slug.toLowerCase() === 'none' ? null : argv.slug;
200
+ await messagingPost('/Appointments/Settings', { writeTargetSlug: slug });
201
+ console.log(`\n✓ New bookings now go to ${slug ?? 'Velaro (first connected calendar)'}.\n`);
202
+ }),
203
+ })
204
+ .demandCommand(1, 'Specify a subcommand: get | set | intake | time-off'),
205
+ };
package/lib/confirm.js ADDED
@@ -0,0 +1,14 @@
1
+ import readline from 'node:readline';
2
+
3
+ /**
4
+ * Destructive-action confirmation. --yes skips the prompt. Without a TTY and without --yes the command refuses,
5
+ * so a script can never delete or revoke by accident.
6
+ */
7
+ export async function confirmDestructive(message, { yes = false } = {}) {
8
+ if (yes) return;
9
+ if (!process.stdin.isTTY) throw new Error(`${message} Refusing to continue without a terminal: pass --yes to confirm.`);
10
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
11
+ const answer = await new Promise((resolve) => rl.question(`${message} Type "yes" to continue: `, resolve));
12
+ rl.close();
13
+ if (String(answer).trim().toLowerCase() !== 'yes') throw new Error('Cancelled. Nothing was changed.');
14
+ }
package/package.json CHANGED
@@ -1,45 +1,40 @@
1
- {
2
- "name": "@velaro/cli",
3
- "version": "1.4.240",
4
- "description": "Velaro Workspace v20 — command-line interface for managing bots, knowledge base ingestion, MCP API keys, search indexes, and ops health.",
5
- "type": "module",
6
- "bin": {
7
- "velaro": "bin/velaro.js"
8
- },
9
- "scripts": {
10
- "postinstall": "node scripts/postinstall.js",
11
- "test": "node --test lib/*.test.js staff/tests/*.test.js"
12
- },
13
- "engines": {
14
- "node": ">=18.0.0"
15
- },
16
- "dependencies": {
17
- "@azure/identity": "^4.4.1",
18
- "@azure/keyvault-secrets": "^4.9.0",
19
- "mssql": "^12.7.0",
20
- "pdfkit": "^0.20.2",
21
- "yargs": "^17.7.2"
22
- },
23
- "optionalDependencies": {
24
- "playwright": "^1.43.1",
25
- "xlsx": "https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz"
26
- },
27
- "repository": {
28
- "type": "git",
29
- "url": "https://github.com/velaro/velaro-admin"
30
- },
31
- "files": [
32
- "bin/",
33
- "lib/",
34
- "scripts/",
35
- "assets/"
36
- ],
37
- "devDependencies": {
38
- "license-checker-rseidelsohn": "^4.4.2"
39
- },
40
- "overrides": {
41
- "@azure/msal-node": "^7.1.0",
42
- "minimatch": "^11.0.1",
43
- "glob": "^14.0.2"
44
- }
45
- }
1
+ {
2
+ "name": "@velaro/cli",
3
+ "version": "1.4.242",
4
+ "description": "Velaro Workspace v20 — command-line interface for managing bots, knowledge base ingestion, MCP API keys, search indexes, and ops health.",
5
+ "type": "module",
6
+ "bin": {
7
+ "velaro": "bin/velaro.js"
8
+ },
9
+ "scripts": {
10
+ "postinstall": "node scripts/postinstall.js",
11
+ "test": "node --test lib/*.test.js lib/commands/*.test.js staff/tests/*.test.js"
12
+ },
13
+ "engines": {
14
+ "node": ">=18.0.0"
15
+ },
16
+ "dependencies": {
17
+ "yargs": "^17.7.2"
18
+ },
19
+ "optionalDependencies": {
20
+ "playwright": "^1.43.1",
21
+ "xlsx": "https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz"
22
+ },
23
+ "repository": {
24
+ "type": "git",
25
+ "url": "https://github.com/velaro/velaro-admin"
26
+ },
27
+ "files": [
28
+ "bin/",
29
+ "lib/",
30
+ "scripts/"
31
+ ],
32
+ "devDependencies": {
33
+ "license-checker-rseidelsohn": "^4.4.2"
34
+ },
35
+ "overrides": {
36
+ "@azure/msal-node": "^7.1.0",
37
+ "minimatch": "^11.0.1",
38
+ "glob": "^14.0.2"
39
+ }
40
+ }
@@ -1,105 +0,0 @@
1
- import { runCommand } from '../run.js';
2
-
3
- // ────────────────────────────────────────────────────────────────────────────
4
- // Direct database query tool — read-only by default.
5
- //
6
- // Built 2026-08-17 after a session burned significant time trying to answer
7
- // one question ("did migration X actually apply to staging?") through the
8
- // Azure Portal's browser-based Query Editor, which stopped responding to
9
- // clicks under host memory pressure. This is the durable replacement: a
10
- // scriptable, non-interactive way to run a SQL query against any of the
11
- // named databases below, with connection strings sourced from Key Vault
12
- // (never hardcoded) per this repo's KV-first secrets rule.
13
- //
14
- // SAFE BY DEFAULT: only SELECT statements are allowed unless --allow-write
15
- // is passed explicitly. This tool is for diagnostics, not migrations —
16
- // schema changes still go through `dotnet ef migrations add` per this
17
- // repo's EF-migrations-are-the-source-of-truth rule.
18
- // ────────────────────────────────────────────────────────────────────────────
19
-
20
- // Maps a short --db name to the Key Vault secret holding its connection string.
21
- // Add a new entry here (and set the secret in the vault) whenever a new
22
- // database needs to be queryable this way — never hardcode a connection
23
- // string in this file.
24
- const DB_SECRETS = {
25
- kb: {
26
- staging: { vault: 'velaro-eastus-stg-kv', secret: 'KnowledgeBaseConnectionString-Staging' },
27
- },
28
- messaging: {
29
- staging: { vault: 'velaro-eastus-stg-kv', secret: 'MessagingConnectionString-Staging' },
30
- prod: { vault: 'velaro-eastus-prd-kv', secret: 'MessagingReadOnlyConnectionString' },
31
- },
32
- };
33
-
34
- async function getConnectionString(dbName, env, connectionStringFile) {
35
- if (connectionStringFile) {
36
- const { readFileSync } = await import('fs');
37
- return readFileSync(connectionStringFile, 'utf8').trim();
38
- }
39
- const entry = DB_SECRETS[dbName]?.[env];
40
- if (!entry) {
41
- const known = Object.entries(DB_SECRETS)
42
- .flatMap(([db, envs]) => Object.keys(envs).map((e) => `${db}/${e}`))
43
- .join(', ');
44
- throw new Error(`No connection string registered for --db ${dbName} --env ${env}. Known: ${known}. Or pass --connection-string-file for a one-off ad-hoc connection (never commit that file).`);
45
- }
46
- const { SecretClient } = await import('@azure/keyvault-secrets');
47
- const { DefaultAzureCredential } = await import('@azure/identity');
48
- const client = new SecretClient(`https://${entry.vault}.vault.azure.net`, new DefaultAzureCredential());
49
- const secret = await client.getSecret(entry.secret);
50
- return secret.value;
51
- }
52
-
53
- // Conservative guard: block anything that isn't a plain read. This is a
54
- // string check, not a real SQL parser — it exists to stop accidental writes
55
- // from a mistyped query, not to be airtight against a determined bypass.
56
- // Real write protection is the underlying SQL user's own grants.
57
- function assertReadOnly(query) {
58
- const normalized = query.trim().replace(/^\s*;+/, '').toUpperCase();
59
- const writeVerbs = ['INSERT', 'UPDATE', 'DELETE', 'DROP', 'ALTER', 'TRUNCATE', 'EXEC', 'MERGE', 'CREATE'];
60
- const firstWord = normalized.split(/\s+/)[0];
61
- if (writeVerbs.includes(firstWord)) {
62
- throw new Error(`Query looks like a write (${firstWord}) — pass --allow-write to run it, or use a proper EF migration for schema changes.`);
63
- }
64
- }
65
-
66
- export const dbCommand = {
67
- command: 'db <subcommand>',
68
- describe: 'Run direct SQL queries against a named database (diagnostics only — read-only unless --allow-write)',
69
- builder: (yargs) =>
70
- yargs
71
- .command({
72
- command: 'query <sql>',
73
- describe: 'Run a SQL query. Wrap the query in quotes.',
74
- builder: (y) =>
75
- y
76
- .positional('sql', { type: 'string', describe: 'SQL query to run' })
77
- .option('db', { type: 'string', describe: `Database name (${Object.keys(DB_SECRETS).join(', ')})` })
78
- .option('env', { type: 'string', default: 'staging', choices: ['staging', 'prod'], describe: 'Environment' })
79
- .option('connection-string-file', { type: 'string', describe: 'Path to a local file containing a raw connection string, for one-off ad-hoc queries not yet registered in Key Vault' })
80
- .option('allow-write', { type: 'boolean', default: false, describe: 'Allow INSERT/UPDATE/DELETE/DDL statements' }),
81
- handler: runCommand(async (argv) => {
82
- if (!argv['allow-write']) assertReadOnly(argv.sql);
83
-
84
- const sql = await import('mssql');
85
- const connectionString = await getConnectionString(argv.db, argv.env, argv['connection-string-file']);
86
- const pool = await sql.default.connect(connectionString);
87
- try {
88
- const result = await pool.request().query(argv.sql);
89
- const rows = Array.isArray(result.recordset) ? result.recordset : [];
90
- if (rows.length === 0) {
91
- console.log(argv['allow-write']
92
- ? `Done. Rows affected: ${result.rowsAffected?.join(', ') ?? 0}`
93
- : 'No rows returned.');
94
- return;
95
- }
96
- console.table(rows);
97
- console.log(`\n${rows.length} row(s).`);
98
- } finally {
99
- await pool.close();
100
- }
101
- }),
102
- })
103
- .demandCommand(1, 'Specify: query'),
104
- handler: () => {},
105
- };
@@ -1,26 +0,0 @@
1
- import { collectAll, render, PRODUCTS } from '../deploy-state.js';
2
-
3
- // velaro deploy-state: what is on the staging environment, on staging slot 1 of production and in
4
- // production for Admin and Messaging, what is merged to dev but not in production, which gate is
5
- // waiting and the merge-freeze file. Uses only `gh` (logged in) and public /Version endpoints.
6
- export const deployStateCommand = {
7
- command: 'deploy-state',
8
- describe: 'Where each push landed: staging environment, staging slot 1 of production, production (Velaro staff, needs gh)',
9
- builder: (yargs) => yargs
10
- .option('product', { type: 'string', choices: ['admin', 'messaging'], describe: 'Only one product (default both)' })
11
- .option('json', { type: 'boolean', describe: 'Print the raw state as JSON' })
12
- .option('compact', { type: 'boolean', describe: 'One line per place' }),
13
- handler: async (argv) => {
14
- try {
15
- const products = argv.product
16
- ? [Object.keys(PRODUCTS).find((n) => n.toLowerCase() === argv.product)]
17
- : undefined;
18
- const state = await collectAll({ products });
19
- console.log(argv.json ? JSON.stringify(state, null, 2) : render(state, { compact: !!argv.compact }));
20
- } catch (e) {
21
- console.error(`deploy-state failed: ${e.message}`);
22
- console.error('This command needs the GitHub CLI (gh) installed and logged in with access to velaro/velaro-admin and velaro/velaro-messaging. Run: gh auth login');
23
- process.exit(1);
24
- }
25
- },
26
- };
@@ -1,107 +0,0 @@
1
- import { messagingGet as get, messagingPost as post } from '../api.js';
2
- import { runCommand } from '../run.js';
3
-
4
- export const deploymentCommand = {
5
- command: 'deployment <subcommand>',
6
- describe: 'Manage chat widget deployments',
7
- builder: (yargs) =>
8
- yargs
9
- .command(deploymentListCommand)
10
- .command(deploymentRenameCommand)
11
- .command(deploymentAssignCommand)
12
- .demandCommand(1, 'Specify a subcommand: list, rename, assign-team'),
13
- handler: () => {},
14
- };
15
-
16
- // ── list ───────────────────────────────────────────────────────────────────────
17
-
18
- const deploymentListCommand = {
19
- command: 'list',
20
- describe: 'List chat widget deployments',
21
- handler: runCommand(async () => {
22
- const [deployments, teams] = await Promise.all([
23
- get('/Deployment'),
24
- get('/Teams/List'),
25
- ]);
26
-
27
- if (!deployments?.length) {
28
- console.log('No deployments found.');
29
- console.log('\nA deployment is a chat widget embed — one per page or team you want to serve.');
30
- return;
31
- }
32
-
33
- const teamMap = Object.fromEntries((teams ?? []).map(t => [t.id, t.name]));
34
-
35
- const rows = deployments.map(d => ({
36
- id: `[${d.id}]`,
37
- key: d.deploymentId ?? '—',
38
- team: teamMap[d.teamId] ?? `team ${d.teamId}`,
39
- name: d.displayName ?? '(unnamed)',
40
- }));
41
-
42
- const idW = Math.max(...rows.map(r => r.id.length));
43
- const keyW = Math.max('embed-key'.length, ...rows.map(r => r.key.length));
44
- const teamW = Math.max('team'.length, ...rows.map(r => r.team.length));
45
-
46
- console.log(`\n${'id'.padStart(idW)} ${'embed-key'.padEnd(keyW)} ${'team'.padEnd(teamW)} name`);
47
- console.log(`${'-'.repeat(idW)} ${'-'.repeat(keyW)} ${'-'.repeat(teamW)} ----`);
48
- for (const r of rows) {
49
- console.log(`${r.id.padStart(idW)} ${r.key.padEnd(keyW)} ${r.team.padEnd(teamW)} ${r.name}`);
50
- }
51
- console.log(`\n${rows.length} deployment(s)`);
52
- console.log('\nThe embed-key goes in your widget JavaScript snippet.');
53
- }),
54
- };
55
-
56
- // ── rename ─────────────────────────────────────────────────────────────────────
57
-
58
- const deploymentRenameCommand = {
59
- command: 'rename <id> <name>',
60
- describe: 'Rename a deployment',
61
- builder: (y) =>
62
- y
63
- .positional('id', { type: 'number', describe: 'Deployment numeric ID' })
64
- .positional('name', { type: 'string', describe: 'New display name' }),
65
- handler: runCommand(async (argv) => {
66
- const dep = await get(`/Deployment/${argv.id}`);
67
- if (!dep) {
68
- console.error(`Deployment ${argv.id} not found.`);
69
- process.exit(1);
70
- }
71
-
72
- await post('/Deployment', { ...dep, id: argv.id, displayName: argv.name });
73
- console.log(`Deployment ${argv.id} renamed to "${argv.name}".`);
74
- }),
75
- };
76
-
77
- // ── assign-team ────────────────────────────────────────────────────────────────
78
-
79
- const deploymentAssignCommand = {
80
- command: 'assign-team <id> <team-id>',
81
- describe: 'Assign a team to a deployment',
82
- builder: (y) =>
83
- y
84
- .positional('id', { type: 'number', describe: 'Deployment numeric ID' })
85
- .positional('team-id', { type: 'number', describe: 'Team ID to assign' }),
86
- handler: runCommand(async (argv) => {
87
- const [dep, teams] = await Promise.all([
88
- get(`/Deployment/${argv.id}`),
89
- get('/Teams/List'),
90
- ]);
91
-
92
- if (!dep) {
93
- console.error(`Deployment ${argv.id} not found.`);
94
- process.exit(1);
95
- }
96
-
97
- const team = (teams ?? []).find(t => t.id === argv['team-id']);
98
- if (!team) {
99
- console.error(`Team ${argv['team-id']} not found.`);
100
- console.error('Run: velaro team list');
101
- process.exit(1);
102
- }
103
-
104
- await post('/Deployment', { ...dep, id: argv.id, teamId: argv['team-id'] });
105
- console.log(`Deployment ${argv.id} ("${dep.displayName}") assigned to team "${team.name}".`);
106
- }),
107
- };
@@ -1,33 +0,0 @@
1
- import { messagingGet } from '../api.js';
2
- import { runCommand } from '../run.js';
3
-
4
- // -- velaro schedule-adherence --------------------------------------------------
5
- // Staff-only. siteId is an EXPLICIT argument (SupportTools-style), never derived from the caller.
6
- // Backend: velaro-messaging GET /Reports/sites/{siteId}/schedule-adherence-diagnostics
7
- // (server-side staff gate; role=agent requires agentId, fails closed).
8
-
9
- export const scheduleAdherenceCommand = {
10
- command: 'schedule-adherence <siteId>',
11
- describe: 'Staff: schedule adherence overview/breakdown/intraday/timeline for a site as manager or agent',
12
- builder: (y) => y
13
- .positional('siteId', { type: 'number', describe: 'Target customer site ID' })
14
- .option('role', { type: 'string', choices: ['manager', 'agent'], default: 'manager', describe: 'Scope to apply' })
15
- .option('agent-id', { type: 'number', describe: 'WorkspaceUser id (required for --role agent)' })
16
- .option('start', { type: 'string', describe: 'yyyy-MM-dd' })
17
- .option('end', { type: 'string', describe: 'yyyy-MM-dd' })
18
- .option('tz', { type: 'string', describe: 'IANA time zone override' })
19
- .option('json', { type: 'boolean', default: false, describe: 'Raw JSON output' }),
20
- handler: runCommand(async (argv) => {
21
- if (argv.role === 'agent' && !argv.agentId) throw new Error('--agent-id is required with --role agent');
22
- const qs = new URLSearchParams({ detail: 'true', role: argv.role });
23
- if (argv.agentId) qs.set('agentId', String(argv.agentId));
24
- for (const k of ['start', 'end', 'tz']) if (argv[k]) qs.set(k, argv[k]);
25
- const d = await messagingGet(`/Reports/sites/${argv.siteId}/schedule-adherence-diagnostics?${qs}`);
26
- if (argv.json) { console.log(JSON.stringify(d, null, 2)); return; }
27
- console.log(`\nSite ${d.siteId} scope=${d.scope} ${d.range?.start}..${d.range?.end} tz=${d.timeZone} invariantsPass=${d.invariantsPass}`);
28
- console.log(` Totals: sched ${d.totals?.scheduledMinutes}m adherent ${d.totals?.adherentMinutes}m avg ${d.totals?.avgAdherencePercent}%`);
29
- for (const a of d.agents ?? []) {
30
- console.log(` [${a.agentId}] ${a.agentName}: ${a.adherencePercent}% status=${a.currentStatus ?? '-'} days=${a.days?.length ?? 0} shiftsToday=${a.timeline?.shifts?.length ?? 0}`);
31
- }
32
- }),
33
- };