@velaro/cli 1.4.110 → 1.4.112
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/bin/velaro.js +2 -0
- package/lib/commands/agent.js +108 -2
- package/lib/commands/migrate.js +7 -1
- package/lib/commands/outbound-activity.js +28 -0
- package/lib/commands/parity-staff-tools.js +2 -2
- package/lib/commands/site-sale.js +118 -0
- package/lib/site-sale.test.js +25 -0
- package/package.json +1 -1
package/bin/velaro.js
CHANGED
|
@@ -123,6 +123,7 @@ import { emailInboxCommand } from '../lib/commands/email-inbox.js';
|
|
|
123
123
|
import { callbackCommand } from '../lib/commands/callback.js';
|
|
124
124
|
import { caseCommand } from '../lib/commands/case.js';
|
|
125
125
|
import { pickupCommand } from '../lib/commands/pickup.js';
|
|
126
|
+
import { siteSaleCommand } from '../lib/commands/site-sale.js';
|
|
126
127
|
import { visitorMonitorCommand } from '../lib/commands/visitor-monitor.js';
|
|
127
128
|
import { visitorLinkCommand } from '../lib/commands/visitor-link.js';
|
|
128
129
|
import { applePayCommand } from '../lib/commands/apple-pay.js';
|
|
@@ -286,6 +287,7 @@ await yargs(hideBin(process.argv))
|
|
|
286
287
|
.command(callbackCommand)
|
|
287
288
|
.command(caseCommand)
|
|
288
289
|
.command(pickupCommand)
|
|
290
|
+
.command(siteSaleCommand)
|
|
289
291
|
.command(visitorMonitorCommand)
|
|
290
292
|
.command(visitorLinkCommand)
|
|
291
293
|
.command(applePayCommand)
|
package/lib/commands/agent.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { get, post, messagingGet, messagingPost, messagingPut, getCredentials } from '../api.js';
|
|
1
|
+
import { get, post, messagingGet, messagingPost, messagingPut, messagingDel, getCredentials } from '../api.js';
|
|
2
2
|
import { runCommand } from '../run.js';
|
|
3
3
|
|
|
4
4
|
const VALID_STATUSES = ['Available', 'Busy', 'Away', 'Offline'];
|
|
@@ -264,5 +264,111 @@ export const agentCommand = {
|
|
|
264
264
|
console.log(r.summary);
|
|
265
265
|
}),
|
|
266
266
|
})
|
|
267
|
-
|
|
267
|
+
// Agent CRM logins (velaro-messaging api/v1/AgentCrmIdentities): which NetSuite / Dynamics / HubSpot user is
|
|
268
|
+
// which Velaro agent. Drives the CRM call pop and the owner of calls logged to the CRM. Site from the key.
|
|
269
|
+
.command({
|
|
270
|
+
command: 'crm-identity <action>',
|
|
271
|
+
describe: 'Link CRM logins (NetSuite, Dynamics, HubSpot) to agents for the CRM call pop and call owner',
|
|
272
|
+
builder: (y) => y
|
|
273
|
+
.command({
|
|
274
|
+
command: 'list',
|
|
275
|
+
describe: 'List linked CRM logins (all agents, or one with --agent / --agent-email)',
|
|
276
|
+
builder: (z) => z
|
|
277
|
+
.option('agent', { type: 'number', describe: 'Agent WorkspaceUser id' })
|
|
278
|
+
.option('agent-email', { type: 'string', describe: 'Agent Velaro email (alternative to --agent)' })
|
|
279
|
+
.option('json', { type: 'boolean', default: false }),
|
|
280
|
+
handler: runCommand(async (argv) => {
|
|
281
|
+
let agentId = argv.agent;
|
|
282
|
+
if (!agentId && argv['agent-email']) agentId = await agentIdByEmail(argv['agent-email']);
|
|
283
|
+
const r = await messagingGet(`/api/v1/AgentCrmIdentities${agentId ? `?workspaceUserId=${agentId}` : ''}`);
|
|
284
|
+
const rows = r?.data?.identities ?? [];
|
|
285
|
+
if (argv.json) { console.log(JSON.stringify(rows, null, 2)); return; }
|
|
286
|
+
if (!rows.length) { console.log('No CRM logins linked.'); return; }
|
|
287
|
+
for (const x of rows) {
|
|
288
|
+
console.log(`#${x.id} ${x.provider.padEnd(10)} ${String(x.loginEmail ?? '-').padEnd(32)} id=${x.crmUserId ?? '-'} -> agent ${x.workspaceUserId} ${x.agentEmail ?? ''} (${x.source})`);
|
|
289
|
+
}
|
|
290
|
+
}),
|
|
291
|
+
})
|
|
292
|
+
.command({
|
|
293
|
+
command: 'add',
|
|
294
|
+
describe: 'Link a CRM login to an agent',
|
|
295
|
+
builder: (z) => z
|
|
296
|
+
.option('agent', { type: 'number', describe: 'Agent WorkspaceUser id' })
|
|
297
|
+
.option('agent-email', { type: 'string', describe: 'Agent Velaro email (alternative to --agent)' })
|
|
298
|
+
.option('provider', { type: 'string', demandOption: true, describe: 'netsuite | dynamics | hubspot | salesforce | zoho | other' })
|
|
299
|
+
.option('login', { type: 'string', describe: 'CRM login email' })
|
|
300
|
+
.option('crm-user-id', { type: 'string', describe: 'CRM user id (NetSuite employee id, Dynamics systemuserid, HubSpot owner id)' })
|
|
301
|
+
.check((a) => {
|
|
302
|
+
if (!a.agent && !a['agent-email']) throw new Error('Pass --agent <id> or --agent-email <email>.');
|
|
303
|
+
if (!a.login && !a['crm-user-id']) throw new Error('Pass --login, --crm-user-id, or both.');
|
|
304
|
+
return true;
|
|
305
|
+
}),
|
|
306
|
+
handler: runCommand(async (argv) => {
|
|
307
|
+
const body = {
|
|
308
|
+
workspaceUserId: argv.agent ?? null,
|
|
309
|
+
agentEmail: argv['agent-email'] ?? null,
|
|
310
|
+
provider: argv.provider,
|
|
311
|
+
loginEmail: argv.login ?? null,
|
|
312
|
+
crmUserId: argv['crm-user-id'] ?? null,
|
|
313
|
+
};
|
|
314
|
+
const r = await messagingPost('/api/v1/AgentCrmIdentities', body);
|
|
315
|
+
const x = r?.data;
|
|
316
|
+
console.log(`Linked ${x?.provider} login ${x?.loginEmail ?? x?.crmUserId} to agent ${x?.workspaceUserId} (${x?.agentEmail ?? ''}), id #${x?.id}.`);
|
|
317
|
+
}),
|
|
318
|
+
})
|
|
319
|
+
.command({
|
|
320
|
+
command: 'remove <id>',
|
|
321
|
+
describe: 'Unlink a CRM login by its id (from list)',
|
|
322
|
+
builder: (z) => z.positional('id', { type: 'number' }),
|
|
323
|
+
handler: runCommand(async (argv) => {
|
|
324
|
+
await messagingDel(`/api/v1/AgentCrmIdentities/${encodeURIComponent(argv.id)}`);
|
|
325
|
+
console.log(`Removed CRM login #${argv.id}.`);
|
|
326
|
+
}),
|
|
327
|
+
})
|
|
328
|
+
.command({
|
|
329
|
+
command: 'unlinked',
|
|
330
|
+
describe: 'CRM logins that polled the call pop but are linked to no agent',
|
|
331
|
+
builder: (z) => z.option('json', { type: 'boolean', default: false }),
|
|
332
|
+
handler: runCommand(async (argv) => {
|
|
333
|
+
const r = await messagingGet('/api/v1/AgentCrmIdentities/unlinked-logins');
|
|
334
|
+
const rows = r?.data?.logins ?? [];
|
|
335
|
+
if (argv.json) { console.log(JSON.stringify(rows, null, 2)); return; }
|
|
336
|
+
if (!rows.length) { console.log('No unlinked CRM logins.'); return; }
|
|
337
|
+
for (const x of rows) {
|
|
338
|
+
console.log(`#${x.id} ${x.provider.padEnd(10)} ${String(x.loginEmail ?? '-').padEnd(32)} id=${x.crmUserId ?? '-'} last seen ${x.lastSeenAt}`);
|
|
339
|
+
}
|
|
340
|
+
}),
|
|
341
|
+
})
|
|
342
|
+
.command({
|
|
343
|
+
command: 'link <id>',
|
|
344
|
+
describe: 'Link an unlinked CRM login (id from "unlinked") to an agent',
|
|
345
|
+
builder: (z) => z
|
|
346
|
+
.positional('id', { type: 'number' })
|
|
347
|
+
.option('agent', { type: 'number', describe: 'Agent WorkspaceUser id' })
|
|
348
|
+
.option('agent-email', { type: 'string', describe: 'Agent Velaro email (alternative to --agent)' })
|
|
349
|
+
.check((a) => {
|
|
350
|
+
if (!a.agent && !a['agent-email']) throw new Error('Pass --agent <id> or --agent-email <email>.');
|
|
351
|
+
return true;
|
|
352
|
+
}),
|
|
353
|
+
handler: runCommand(async (argv) => {
|
|
354
|
+
const r = await messagingPost(`/api/v1/AgentCrmIdentities/unlinked-logins/${encodeURIComponent(argv.id)}/link`, {
|
|
355
|
+
workspaceUserId: argv.agent ?? null,
|
|
356
|
+
agentEmail: argv['agent-email'] ?? null,
|
|
357
|
+
});
|
|
358
|
+
const x = r?.data;
|
|
359
|
+
console.log(`Linked ${x?.provider} login ${x?.loginEmail ?? x?.crmUserId} to agent ${x?.workspaceUserId}, id #${x?.id}.`);
|
|
360
|
+
}),
|
|
361
|
+
})
|
|
362
|
+
.demandCommand(1, 'Specify an action: list | add | remove | unlinked | link'),
|
|
363
|
+
})
|
|
364
|
+
.demandCommand(1, 'Specify a subcommand: list | set-status | missed-chats | availability | ai-summary | crm-identity'),
|
|
268
365
|
};
|
|
366
|
+
|
|
367
|
+
/** WorkspaceUser id of the agent with this email on the caller's site (messaging Users/List). */
|
|
368
|
+
async function agentIdByEmail(email) {
|
|
369
|
+
const users = await messagingGet('/Users/List');
|
|
370
|
+
const list = Array.isArray(users) ? users : (users?.data ?? users?.users ?? []);
|
|
371
|
+
const hit = list.find((u) => String(u.email ?? '').toLowerCase() === String(email).toLowerCase());
|
|
372
|
+
if (!hit) throw new Error(`No agent with email ${email} on this site.`);
|
|
373
|
+
return hit.id;
|
|
374
|
+
}
|
package/lib/commands/migrate.js
CHANGED
|
@@ -26,11 +26,13 @@ const migrateExportCommand = {
|
|
|
26
26
|
y
|
|
27
27
|
.positional('v10SiteId', { type: 'number', describe: 'V10 site ID to export from' })
|
|
28
28
|
.option('v20-site-id', { type: 'number', alias: 's', describe: 'V20 site ID for auto-matching teams/AI configs' })
|
|
29
|
-
.option('include-non-routing', { type: 'boolean', default: false, describe: 'Also include v10 rules with IsRouting=false (group-assignment rules)' })
|
|
29
|
+
.option('include-non-routing', { type: 'boolean', default: false, describe: 'Also include v10 rules with IsRouting=false (group-assignment rules)' })
|
|
30
|
+
.option('path-only-urls', { type: 'boolean', default: false, describe: 'Strip v10 URL terms to their path (demo-page testing only). Default keeps the host, like v10.' }),
|
|
30
31
|
handler: runCommand(async (argv) => {
|
|
31
32
|
const params = [];
|
|
32
33
|
if (argv['v20-site-id']) params.push(`v20SiteId=${argv['v20-site-id']}`);
|
|
33
34
|
if (argv['include-non-routing']) params.push('includeNonRouting=true');
|
|
35
|
+
if (argv['path-only-urls']) params.push('pathOnlyUrls=true');
|
|
34
36
|
const qs = params.length ? `?${params.join('&')}` : '';
|
|
35
37
|
const data = await get(`/DatabaseTool/V10Export/${argv.v10SiteId}${qs}`);
|
|
36
38
|
|
|
@@ -89,6 +91,8 @@ const migrateLivefluenceCommand = {
|
|
|
89
91
|
.option('enable', { type: 'boolean', default: false, describe: 'Enable created workflows immediately (default: disabled; workflows with unconverted v10 terms always stay disabled)' })
|
|
90
92
|
.option('include-non-routing', { type: 'boolean', default: false, describe: 'Also migrate v10 rules with IsRouting=false (group-assignment rules)' })
|
|
91
93
|
.option('route-bot-groups-to-team', { type: 'boolean', default: false, describe: 'Route to the v20 team named after the v10 group even if the group had a v10 bot' })
|
|
94
|
+
.option('path-only-urls', { type: 'boolean', default: false, describe: 'Strip v10 URL terms to their path (demo-page testing only). Default keeps the host, like v10.' })
|
|
95
|
+
.option('page-team-availability', { type: 'boolean', default: true, describe: "Launcher availability follows the page's team like v10 (page-load Route to Team workflows + chat window flag). --no-page-team-availability to skip." })
|
|
92
96
|
.option('team-map', { type: 'string', describe: 'JSON: [{"v10GroupId":1,"v20TeamId":5},...] override auto-resolution for teams' })
|
|
93
97
|
.option('ai-config-map',{ type: 'string', describe: 'JSON: [{"v10GroupId":2,"v20AiConfigId":3},...] override auto-resolution for AI configs' }),
|
|
94
98
|
handler: runCommand(async (argv) => {
|
|
@@ -102,6 +106,8 @@ const migrateLivefluenceCommand = {
|
|
|
102
106
|
enable: argv.enable,
|
|
103
107
|
includeNonRouting: argv['include-non-routing'],
|
|
104
108
|
routeBotGroupsToTeam: argv['route-bot-groups-to-team'],
|
|
109
|
+
pathOnlyUrls: argv['path-only-urls'],
|
|
110
|
+
pageTeamAvailability: argv['page-team-availability'] !== false,
|
|
105
111
|
teamMappings: argv['team-map'] ? JSON.parse(argv['team-map']) : [],
|
|
106
112
|
aiConfigMappings: argv['ai-config-map'] ? JSON.parse(argv['ai-config-map']) : [],
|
|
107
113
|
};
|
|
@@ -82,6 +82,27 @@ async function listHandler(argv) {
|
|
|
82
82
|
render(data, 'Outbound activity');
|
|
83
83
|
}
|
|
84
84
|
|
|
85
|
+
async function volumeHandler(argv) {
|
|
86
|
+
const days = Math.min(90, Math.max(1, Number(argv.days ?? 30)));
|
|
87
|
+
const data = await request('GET', `/Marketing/OutboundActivity/Volume?days=${days}`);
|
|
88
|
+
const byDay = new Map();
|
|
89
|
+
for (const b of data?.buckets ?? []) {
|
|
90
|
+
const d = byDay.get(b.date) ?? { sent: 0, failed: 0 };
|
|
91
|
+
if (b.status === 'Failed') d.failed += b.count;
|
|
92
|
+
else if (b.status === 'Sent') d.sent += b.count;
|
|
93
|
+
byDay.set(b.date, d);
|
|
94
|
+
}
|
|
95
|
+
console.log(`\n${BOLD}Outbound volume, last ${days} days (campaign + broadcast)${RST}\n`);
|
|
96
|
+
if (data?.degradedSources?.length) {
|
|
97
|
+
console.log(`${YEL} ! Not counted: ${data.degradedSources.join(', ')}${RST}\n`);
|
|
98
|
+
}
|
|
99
|
+
for (const [date, d] of [...byDay.entries()].sort(([a], [b]) => a.localeCompare(b))) {
|
|
100
|
+
console.log(` ${date} ${GRN}sent ${d.sent}${RST} ${RED}failed ${d.failed}${RST}`);
|
|
101
|
+
}
|
|
102
|
+
if (!byDay.size) console.log(` ${DIM}No campaign or broadcast sends in this window.${RST}`);
|
|
103
|
+
console.log('');
|
|
104
|
+
}
|
|
105
|
+
|
|
85
106
|
async function contactHandler(argv) {
|
|
86
107
|
const email = String(argv.email || '').trim();
|
|
87
108
|
// The scoping identifier is required, never optional — an omitted email must never silently
|
|
@@ -112,6 +133,13 @@ export const outboundActivityCommand = {
|
|
|
112
133
|
.option('search', { describe: 'Match recipient or subject', type: 'string' }),
|
|
113
134
|
handler: listHandler,
|
|
114
135
|
})
|
|
136
|
+
.command({
|
|
137
|
+
command: 'volume',
|
|
138
|
+
describe: 'Daily sent vs failed counts for campaign and broadcast sends',
|
|
139
|
+
builder: yy => yy
|
|
140
|
+
.option('days', { describe: 'Window in days (1-90)', type: 'number', default: 30 }),
|
|
141
|
+
handler: volumeHandler,
|
|
142
|
+
})
|
|
115
143
|
.command({
|
|
116
144
|
command: 'contact <email>',
|
|
117
145
|
describe: 'Every email sent to ONE address, across all three send systems',
|
|
@@ -95,7 +95,7 @@ const SCRAPER_EXTRA = [
|
|
|
95
95
|
];
|
|
96
96
|
|
|
97
97
|
const LIVEFLUENCE = [
|
|
98
|
-
{ 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: (a) => `DatabaseTool/V10Export/${a.v10SiteId}${qs({ v20SiteId: a.v20SiteId, includeNonRouting: a.includeNonRouting ? 'true' : undefined })}` },
|
|
98
|
+
{ 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 })}` },
|
|
99
99
|
{ 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) ?? [] }) },
|
|
100
100
|
{ name: 'site-workflows-list', desc: 'List a site workflows', opts: { 'site-id': N('Site id', true) }, path: (a) => `DatabaseTool/SiteWorkflows/${a.siteId}` },
|
|
101
101
|
{ 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 }) },
|
|
@@ -105,7 +105,7 @@ const LIVEFLUENCE = [
|
|
|
105
105
|
{ 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 }) },
|
|
106
106
|
{ 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) }) },
|
|
107
107
|
{ 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 }; } },
|
|
108
|
-
{ 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'), '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, teamMappings: json(a.teamMappings) ?? [], aiConfigMappings: json(a.aiConfigMappings) ?? [] }) },
|
|
108
|
+
{ 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) ?? [] }) },
|
|
109
109
|
];
|
|
110
110
|
|
|
111
111
|
const TABLES = {
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { messagingGet, messagingPost, messagingPut, messagingDel } from '../api.js';
|
|
2
|
+
import { runCommand } from '../run.js';
|
|
3
|
+
|
|
4
|
+
// ── velaro site-sale ───────────────────────────────────────────────────────────
|
|
5
|
+
// CLI surface for "Current Sales": a time-boxed override Q&A. While a sale is active
|
|
6
|
+
// the bot answers sales/discount/coupon questions deterministically and can issue
|
|
7
|
+
// per-customer coupons; it stops at the end time. siteId is applied server-side from
|
|
8
|
+
// the vmsg-siteId header (see cli/lib/api.js messagingRequest) -- never a CLI arg.
|
|
9
|
+
//
|
|
10
|
+
// Backend contract: velaro-messaging SiteSalesController
|
|
11
|
+
// GET SiteSales
|
|
12
|
+
// POST SiteSales
|
|
13
|
+
// PUT SiteSales/{id}
|
|
14
|
+
// POST SiteSales/{id}/end
|
|
15
|
+
// DELETE SiteSales/{id}
|
|
16
|
+
|
|
17
|
+
const BOLD = '\x1b[1m';
|
|
18
|
+
const DIM = '\x1b[2m';
|
|
19
|
+
const GRN = '\x1b[32m';
|
|
20
|
+
const RST = '\x1b[0m';
|
|
21
|
+
|
|
22
|
+
export function buildSaleBody(argv) {
|
|
23
|
+
return {
|
|
24
|
+
name: argv.name,
|
|
25
|
+
description: argv.description,
|
|
26
|
+
appliesTo: argv.appliesTo,
|
|
27
|
+
appliesToValue: argv.appliesToValue,
|
|
28
|
+
discountType: argv.discountType,
|
|
29
|
+
discountValue: argv.discountValue,
|
|
30
|
+
startsAtUtc: argv.startsAtUtc,
|
|
31
|
+
endsAtUtc: argv.endsAtUtc,
|
|
32
|
+
couponCode: argv.couponCode,
|
|
33
|
+
autoGenerateCoupons: argv.autoGenerateCoupons,
|
|
34
|
+
maxCouponsPerCustomer: argv.maxCouponsPerCustomer,
|
|
35
|
+
couponUsageLimit: argv.couponUsageLimit,
|
|
36
|
+
couponExpiresHours: argv.couponExpiresHours,
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function addSaleOptions(y, { creating }) {
|
|
41
|
+
return y
|
|
42
|
+
.option('name', { describe: 'Sale name', type: 'string', demandOption: creating })
|
|
43
|
+
.option('description', { describe: 'Short description the bot can quote', type: 'string' })
|
|
44
|
+
.option('applies-to', { describe: 'Scope: all | category | products', type: 'string', choices: ['all', 'category', 'products'] })
|
|
45
|
+
.option('applies-to-value', { describe: 'Category name or comma-separated products', type: 'string' })
|
|
46
|
+
.option('discount-type', { describe: 'percentage | fixed_amount | free_shipping', type: 'string', choices: ['percentage', 'fixed_amount', 'free_shipping'], demandOption: creating })
|
|
47
|
+
.option('discount-value', { describe: 'Percent or fixed amount', type: 'number' })
|
|
48
|
+
.option('starts-at-utc', { describe: 'ISO 8601 start (UTC)', type: 'string', demandOption: creating })
|
|
49
|
+
.option('ends-at-utc', { describe: 'ISO 8601 end (UTC); the bot stops answering at this time', type: 'string', demandOption: creating })
|
|
50
|
+
.option('coupon-code', { describe: 'Optional shared coupon code', type: 'string' })
|
|
51
|
+
.option('auto-generate-coupons', { describe: 'Issue a unique coupon per customer', type: 'boolean' })
|
|
52
|
+
.option('max-coupons-per-customer',{ describe: 'Max coupons issued to one customer', type: 'number' })
|
|
53
|
+
.option('coupon-usage-limit', { describe: 'Uses allowed per coupon', type: 'number' })
|
|
54
|
+
.option('coupon-expires-hours', { describe: 'Hours before an issued coupon expires', type: 'number' });
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
async function listHandler() {
|
|
58
|
+
const sales = await messagingGet('/SiteSales');
|
|
59
|
+
if (!Array.isArray(sales) || !sales.length) {
|
|
60
|
+
console.log('\n No current sales for this site.\n');
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
console.log(`\n${BOLD}Current Sales${RST}\n`);
|
|
64
|
+
for (const s of sales) {
|
|
65
|
+
console.log(` #${s.id} ${s.name} ${DIM}${s.discountType ?? ''} ${s.discountValue ?? ''} ${s.startsAtUtc ?? '-'} -> ${s.endsAtUtc ?? '-'}${RST}`);
|
|
66
|
+
}
|
|
67
|
+
console.log('');
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
async function createHandler(argv) {
|
|
71
|
+
const sale = await messagingPost('/SiteSales', buildSaleBody(argv));
|
|
72
|
+
console.log(`\n${GRN}✓${RST} Sale created${sale && sale.id != null ? ` (#${sale.id})` : ''}.\n`);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
async function updateHandler(argv) {
|
|
76
|
+
await messagingPut(`/SiteSales/${encodeURIComponent(argv.id)}`, buildSaleBody(argv));
|
|
77
|
+
console.log(`\n${GRN}✓${RST} Sale ${argv.id} updated.\n`);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
async function endHandler(argv) {
|
|
81
|
+
await messagingPost(`/SiteSales/${encodeURIComponent(argv.id)}/end`, {});
|
|
82
|
+
console.log(`\n${GRN}✓${RST} Sale ${argv.id} ended.\n`);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
async function deleteHandler(argv) {
|
|
86
|
+
await messagingDel(`/SiteSales/${encodeURIComponent(argv.id)}`);
|
|
87
|
+
console.log(`\n${GRN}✓${RST} Sale ${argv.id} deleted.\n`);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export const siteSaleCommand = {
|
|
91
|
+
command: 'site-sale <subcommand>',
|
|
92
|
+
describe: 'Current Sales -- temporary sales or discounts the bot answers about and can issue coupons for',
|
|
93
|
+
builder: (y) => y
|
|
94
|
+
.command({ command: 'list', describe: 'List current sales', handler: runCommand(listHandler) })
|
|
95
|
+
.command({
|
|
96
|
+
command: 'create', describe: 'Create a sale',
|
|
97
|
+
builder: (y2) => addSaleOptions(y2, { creating: true }),
|
|
98
|
+
handler: runCommand(createHandler),
|
|
99
|
+
})
|
|
100
|
+
.command({
|
|
101
|
+
command: 'update <id>', describe: 'Update a sale (omit a flag to leave it unchanged)',
|
|
102
|
+
builder: (y2) => addSaleOptions(y2.positional('id', { describe: 'Sale ID', type: 'number' }), { creating: false }),
|
|
103
|
+
handler: runCommand(updateHandler),
|
|
104
|
+
})
|
|
105
|
+
.command({
|
|
106
|
+
command: 'end <id>', describe: 'End a sale now',
|
|
107
|
+
builder: (y2) => y2.positional('id', { describe: 'Sale ID', type: 'number' }),
|
|
108
|
+
handler: runCommand(endHandler),
|
|
109
|
+
})
|
|
110
|
+
.command({
|
|
111
|
+
command: 'delete <id>', describe: 'Delete a sale',
|
|
112
|
+
builder: (y2) => y2.positional('id', { describe: 'Sale ID', type: 'number' }),
|
|
113
|
+
handler: runCommand(deleteHandler),
|
|
114
|
+
})
|
|
115
|
+
.demandCommand(1, 'Specify a site-sale subcommand: list | create | update | end | delete')
|
|
116
|
+
.strict(),
|
|
117
|
+
handler: () => {},
|
|
118
|
+
};
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { test } from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { readFileSync } from 'node:fs';
|
|
4
|
+
import { dirname, join } from 'node:path';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
import { buildSaleBody, siteSaleCommand } from './commands/site-sale.js';
|
|
7
|
+
|
|
8
|
+
const here = dirname(fileURLToPath(import.meta.url));
|
|
9
|
+
|
|
10
|
+
test('sale body carries only the SiteSales contract fields and never a site id', () => {
|
|
11
|
+
const body = buildSaleBody({ name: 'n', discountType: 'percentage', discountValue: 20, siteId: 5, startsAtUtc: 'a', endsAtUtc: 'b' });
|
|
12
|
+
assert.deepEqual(Object.keys(body).sort(), [
|
|
13
|
+
'appliesTo', 'appliesToValue', 'autoGenerateCoupons', 'couponCode', 'couponExpiresHours', 'couponUsageLimit',
|
|
14
|
+
'description', 'discountType', 'discountValue', 'endsAtUtc', 'maxCouponsPerCustomer', 'name', 'startsAtUtc',
|
|
15
|
+
]);
|
|
16
|
+
assert.equal(body.discountValue, 20);
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
test('site-sale command registered in velaro.js with all five subcommands', () => {
|
|
20
|
+
assert.equal(siteSaleCommand.command, 'site-sale <subcommand>');
|
|
21
|
+
const src = readFileSync(join(here, '..', 'bin', 'velaro.js'), 'utf8');
|
|
22
|
+
assert.match(src, /\.command\(siteSaleCommand\)/);
|
|
23
|
+
const cmdSrc = readFileSync(join(here, 'commands', 'site-sale.js'), 'utf8');
|
|
24
|
+
for (const c of ["'list'", "'create'", "'update <id>'", "'end <id>'", "'delete <id>'"]) assert.ok(cmdSrc.includes(c), c);
|
|
25
|
+
});
|
package/package.json
CHANGED