@velaro/cli 1.4.208 → 1.4.210
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 +3 -0
- package/lib/commands/crm-approvals-scoring.js +179 -0
- package/lib/commands/sign.js +57 -1
- package/lib/sign-fields.js +49 -0
- package/lib/sign-fields.test.js +27 -0
- package/package.json +1 -1
package/bin/velaro.js
CHANGED
|
@@ -139,6 +139,7 @@ import { aiFollowupsCommand, businessActionCommand, callCommand, conversationCom
|
|
|
139
139
|
import { crmViewCommand, crmBulkCommand, crmWebformCommand } from '../lib/commands/crm-views-bulk-webforms.js';
|
|
140
140
|
import { crmImportCommand, crmTagCommand, crmDedupeCommand, crmAuditCommand } from '../lib/commands/crm-import-dedupe-audit.js';
|
|
141
141
|
import { crmObjectCommand, crmRelCommand } from '../lib/commands/crm-objects-relationships.js';
|
|
142
|
+
import { crmApprovalCommand, crmScoreCommand } from '../lib/commands/crm-approvals-scoring.js';
|
|
142
143
|
import { featureDiscoveryGroup } from '../lib/commands/feature-discovery.js';
|
|
143
144
|
import { billingInsightsGroup } from '../lib/commands/billing-insights.js';
|
|
144
145
|
import { supportTicketsCommand } from '../lib/commands/support-tickets.js';
|
|
@@ -329,6 +330,8 @@ await (registerStaffCommands ? registerStaffCommands(baseYargs) : baseYargs)
|
|
|
329
330
|
.command(crmAuditCommand)
|
|
330
331
|
.command(crmObjectCommand)
|
|
331
332
|
.command(crmRelCommand)
|
|
333
|
+
.command(crmApprovalCommand)
|
|
334
|
+
.command(crmScoreCommand)
|
|
332
335
|
.demandCommand(1, 'Specify a command. Run "velaro --help" for options.')
|
|
333
336
|
.strict()
|
|
334
337
|
.fail((msg, err, y) => {
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
import { messagingGet, messagingPost, messagingPut, messagingDel } from '../api.js';
|
|
2
|
+
import { runCommand } from '../run.js';
|
|
3
|
+
|
|
4
|
+
// -- velaro crm-approval / crm-score -------------------------------------------
|
|
5
|
+
// CLI for CRM Studio features 15 and 16 (docs/architecture/crm-studio-program.md):
|
|
6
|
+
// crm-approval CrmApprovalsController /CrmApprovals (rules that hold a deal change for a Manager or Administrator)
|
|
7
|
+
// crm-score CrmLeadScoringController /CrmLeadScoring (lead scoring rules, preview and recompute)
|
|
8
|
+
// The site always comes from the signed-in credential; no command takes a site id.
|
|
9
|
+
// MCP parity: mcp/parity/crm-approvals-scoring.customer.js (crm_approval_*, crm_score_* tools).
|
|
10
|
+
|
|
11
|
+
const BOLD = '\x1b[1m';
|
|
12
|
+
const DIM = '\x1b[2m';
|
|
13
|
+
const RST = '\x1b[0m';
|
|
14
|
+
|
|
15
|
+
const data = (r) => (r && typeof r === 'object' && 'data' in r ? r.data : r);
|
|
16
|
+
const printJson = (v) => console.log(JSON.stringify(v, null, 2));
|
|
17
|
+
const q = (o) => {
|
|
18
|
+
const p = Object.entries(o).filter(([, v]) => v !== undefined && v !== null && v !== '').map(([k, v]) => `${k}=${encodeURIComponent(v)}`);
|
|
19
|
+
return p.length ? `?${p.join('&')}` : '';
|
|
20
|
+
};
|
|
21
|
+
const json = (y) => y.option('json', { type: 'boolean', default: false, describe: 'Print raw JSON' });
|
|
22
|
+
const parseJson = (text, what) => {
|
|
23
|
+
try { return JSON.parse(text); } catch { throw new Error(`[CRM] ${what} must be valid JSON.`); }
|
|
24
|
+
};
|
|
25
|
+
const done = (msg) => console.log(`\n ${msg}\n`);
|
|
26
|
+
|
|
27
|
+
// ---------------------------------------------------------------- approvals
|
|
28
|
+
|
|
29
|
+
async function approvalRuleListHandler(argv) {
|
|
30
|
+
const r = data(await messagingGet('/CrmApprovals/rules'));
|
|
31
|
+
if (argv.json) return printJson(r);
|
|
32
|
+
const list = Array.isArray(r) ? r : r?.rules ?? [];
|
|
33
|
+
console.log(`\n${BOLD}Approval rules${RST} (${list.length})`);
|
|
34
|
+
for (const x of list) console.log(` #${x.id} ${x.name} ${DIM}${x.kind}${x.threshold != null ? `, over ${x.threshold}` : ''}${x.stageId ? `, stage ${x.stageId}` : ''}${x.isActive === false ? ', off' : ''}${RST}`);
|
|
35
|
+
console.log('');
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// --body is the rule as JSON: kind (stage | amount | discount), name, stageId, pipelineId, threshold, isActive, includeManagers.
|
|
39
|
+
async function approvalRuleSaveHandler(argv) {
|
|
40
|
+
const body = parseJson(argv.body, '--body');
|
|
41
|
+
const r = data(argv.id ? await messagingPut(`/CrmApprovals/rules/${argv.id}`, body) : await messagingPost('/CrmApprovals/rules', body));
|
|
42
|
+
if (argv.json) return printJson(r);
|
|
43
|
+
done(`Approval rule saved${r?.id ? ` (#${r.id})` : ''}.`);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async function approvalRuleDeleteHandler(argv) {
|
|
47
|
+
await messagingDel(`/CrmApprovals/rules/${argv.id}`);
|
|
48
|
+
done(`Approval rule ${argv.id} deleted. Changes already waiting stay in the queue.`);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
async function approvalListHandler(argv) {
|
|
52
|
+
const r = data(await messagingGet(`/CrmApprovals${q({ status: argv.status, page: argv.page, pageSize: argv.pageSize })}`));
|
|
53
|
+
if (argv.json) return printJson(r);
|
|
54
|
+
const rows = r?.items ?? [];
|
|
55
|
+
console.log(`\n${BOLD}Approvals (${argv.status})${RST} (${r?.total ?? rows.length})`);
|
|
56
|
+
for (const a of rows) console.log(` #${a.id} deal #${a.dealId} ${a.dealName ?? ''} ${a.summary} ${DIM}requested by ${a.requestedBy ?? 'unknown'}${a.reviewer ? `, ${a.status} by ${a.reviewer}` : ''}${RST}`);
|
|
57
|
+
console.log('');
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
async function approvalApproveHandler(argv) {
|
|
61
|
+
const r = data(await messagingPost(`/CrmApprovals/${argv.id}/approve`, { comment: argv.comment }));
|
|
62
|
+
if (argv.json) return printJson(r);
|
|
63
|
+
done(`Approval ${argv.id} approved and the change applied.`);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
async function approvalRejectHandler(argv) {
|
|
67
|
+
const r = data(await messagingPost(`/CrmApprovals/${argv.id}/reject`, { comment: argv.comment }));
|
|
68
|
+
if (argv.json) return printJson(r);
|
|
69
|
+
done(`Approval ${argv.id} rejected. The deal was not changed.`);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export const crmApprovalCommand = {
|
|
73
|
+
command: 'crm-approval <subcommand>',
|
|
74
|
+
describe: 'CRM approvals: hold a deal stage move, amount or discount for a Manager or Administrator to decide',
|
|
75
|
+
builder: (y) => y
|
|
76
|
+
.command({ command: 'rule-list', describe: 'List approval rules', builder: json, handler: runCommand(approvalRuleListHandler) })
|
|
77
|
+
.command({
|
|
78
|
+
command: 'rule-save',
|
|
79
|
+
describe: 'Create an approval rule, or update one with --id',
|
|
80
|
+
builder: (yy) => json(yy
|
|
81
|
+
.option('id', { type: 'number' })
|
|
82
|
+
.option('body', { type: 'string', demandOption: true, describe: 'Rule as JSON: kind (stage, amount or discount), name, stageId, pipelineId, threshold, isActive, includeManagers' })),
|
|
83
|
+
handler: runCommand(approvalRuleSaveHandler),
|
|
84
|
+
})
|
|
85
|
+
.command({ command: 'rule-delete <id>', describe: 'Delete an approval rule', handler: runCommand(approvalRuleDeleteHandler) })
|
|
86
|
+
.command({
|
|
87
|
+
command: 'list',
|
|
88
|
+
describe: 'List approval requests',
|
|
89
|
+
builder: (yy) => json(yy
|
|
90
|
+
.option('status', { choices: ['pending', 'approved', 'rejected', 'all'], default: 'pending' })
|
|
91
|
+
.option('page', { type: 'number', default: 1 })
|
|
92
|
+
.option('page-size', { type: 'number', alias: 'pageSize' })),
|
|
93
|
+
handler: runCommand(approvalListHandler),
|
|
94
|
+
})
|
|
95
|
+
.command({
|
|
96
|
+
command: 'approve <id>',
|
|
97
|
+
describe: 'Approve a held change; it is applied and attributed to you',
|
|
98
|
+
builder: (yy) => json(yy.option('comment', { type: 'string' })),
|
|
99
|
+
handler: runCommand(approvalApproveHandler),
|
|
100
|
+
})
|
|
101
|
+
.command({
|
|
102
|
+
command: 'reject <id>',
|
|
103
|
+
describe: 'Reject a held change (a comment is required)',
|
|
104
|
+
builder: (yy) => json(yy.option('comment', { type: 'string', demandOption: true })),
|
|
105
|
+
handler: runCommand(approvalRejectHandler),
|
|
106
|
+
})
|
|
107
|
+
.demandCommand(1),
|
|
108
|
+
handler: () => {},
|
|
109
|
+
};
|
|
110
|
+
|
|
111
|
+
// ---------------------------------------------------------------- lead scoring
|
|
112
|
+
|
|
113
|
+
async function scoreRuleListHandler(argv) {
|
|
114
|
+
const r = data(await messagingGet('/CrmLeadScoring/rules'));
|
|
115
|
+
if (argv.json) return printJson(r);
|
|
116
|
+
const list = Array.isArray(r) ? r : r?.rules ?? [];
|
|
117
|
+
console.log(`\n${BOLD}Lead scoring rules${RST} (${list.length})`);
|
|
118
|
+
for (const x of list) console.log(` #${x.id} ${x.name ?? ''} ${DIM}${x.kind}, ${x.points} point(s)${x.isActive === false ? ', off' : ''}${RST}`);
|
|
119
|
+
console.log('');
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// --body is the rule as JSON: kind (field | activity | decay), name, field, operator, value, activityType, windowDays, decayDays, points, maxPoints, isActive.
|
|
123
|
+
async function scoreRuleSaveHandler(argv) {
|
|
124
|
+
const body = parseJson(argv.body, '--body');
|
|
125
|
+
const r = data(argv.id ? await messagingPut(`/CrmLeadScoring/rules/${argv.id}`, body) : await messagingPost('/CrmLeadScoring/rules', body));
|
|
126
|
+
if (argv.json) return printJson(r);
|
|
127
|
+
done(`Scoring rule saved${r?.id ? ` (#${r.id})` : ''}.`);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
async function scoreRuleDeleteHandler(argv) {
|
|
131
|
+
await messagingDel(`/CrmLeadScoring/rules/${argv.id}`);
|
|
132
|
+
done(`Scoring rule ${argv.id} deleted. Scores update the next time they are recomputed.`);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
async function scorePreviewHandler(argv) {
|
|
136
|
+
const r = data(await messagingGet(`/CrmLeadScoring/preview${q({ contactId: argv.contactId })}`));
|
|
137
|
+
if (argv.json) return printJson(r);
|
|
138
|
+
console.log(`\n${BOLD}Score for contact #${argv.contactId}${RST}: ${r.score} (stored ${r.storedScore}). Nothing was saved.`);
|
|
139
|
+
for (const l of r.breakdown ?? []) console.log(` ${l.points >= 0 ? '+' : ''}${l.points} ${l.label} ${DIM}${l.detail ?? ''}${RST}`);
|
|
140
|
+
console.log('');
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
async function scoreRecomputeHandler(argv) {
|
|
144
|
+
const body = {};
|
|
145
|
+
if (argv.contactId !== undefined) body.contactId = argv.contactId;
|
|
146
|
+
if (argv.afterId !== undefined) body.afterId = argv.afterId;
|
|
147
|
+
if (argv.batchSize !== undefined) body.batchSize = argv.batchSize;
|
|
148
|
+
const r = data(await messagingPost('/CrmLeadScoring/recompute', body));
|
|
149
|
+
if (argv.json) return printJson(r);
|
|
150
|
+
printJson(r);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export const crmScoreCommand = {
|
|
154
|
+
command: 'crm-score <subcommand>',
|
|
155
|
+
describe: 'CRM lead scoring: rules, a score preview for a contact, and recompute',
|
|
156
|
+
builder: (y) => y
|
|
157
|
+
.command({ command: 'rule-list', describe: 'List scoring rules', builder: json, handler: runCommand(scoreRuleListHandler) })
|
|
158
|
+
.command({
|
|
159
|
+
command: 'rule-save',
|
|
160
|
+
describe: 'Create a scoring rule, or update one with --id',
|
|
161
|
+
builder: (yy) => json(yy
|
|
162
|
+
.option('id', { type: 'number' })
|
|
163
|
+
.option('body', { type: 'string', demandOption: true, describe: 'Rule as JSON: kind (field, activity or decay), name, field, operator, value, activityType, windowDays, decayDays, points, maxPoints, isActive' })),
|
|
164
|
+
handler: runCommand(scoreRuleSaveHandler),
|
|
165
|
+
})
|
|
166
|
+
.command({ command: 'rule-delete <id>', describe: 'Delete a scoring rule', handler: runCommand(scoreRuleDeleteHandler) })
|
|
167
|
+
.command({ command: 'preview', describe: 'Show the score and breakdown for one contact without saving it', builder: (yy) => json(yy.option('contact-id', { type: 'number', alias: 'contactId', demandOption: true })), handler: runCommand(scorePreviewHandler) })
|
|
168
|
+
.command({
|
|
169
|
+
command: 'recompute',
|
|
170
|
+
describe: 'Recompute and store scores: one contact, or batches walked with --after-id',
|
|
171
|
+
builder: (yy) => json(yy
|
|
172
|
+
.option('contact-id', { type: 'number', alias: 'contactId' })
|
|
173
|
+
.option('after-id', { type: 'number', alias: 'afterId' })
|
|
174
|
+
.option('batch-size', { type: 'number', alias: 'batchSize' })),
|
|
175
|
+
handler: runCommand(scoreRecomputeHandler),
|
|
176
|
+
})
|
|
177
|
+
.demandCommand(1),
|
|
178
|
+
handler: () => {},
|
|
179
|
+
};
|
package/lib/commands/sign.js
CHANGED
|
@@ -2,6 +2,7 @@ import { readFileSync, writeFileSync } from 'node:fs';
|
|
|
2
2
|
import { basename } from 'node:path';
|
|
3
3
|
import { get, post, put, postForm, getBinary, getCredentials } from '../api.js';
|
|
4
4
|
import { runCommand } from '../run.js';
|
|
5
|
+
import { fieldsPath, FROM_SIGNUP_PATH, buildFieldsBody, describeFields, buildFromSignupBody } from '../sign-fields.js';
|
|
5
6
|
import { versionsPath, diffPath, uploadPath, describeVersions, describeDiff, buildUploadForm, OWNER_ONLY_RULE } from '../sign-versions.js';
|
|
6
7
|
|
|
7
8
|
// velaro sign -- Velaro Sign routing, reminders, final PDF download, file verification.
|
|
@@ -118,6 +119,35 @@ async function uploadVersion(id, file, note) {
|
|
|
118
119
|
console.log(describeVersions(await get(versionsPath(id))));
|
|
119
120
|
}
|
|
120
121
|
|
|
122
|
+
async function fieldsGet(id, json) {
|
|
123
|
+
const res = await get(fieldsPath(id));
|
|
124
|
+
console.log(json ? JSON.stringify(res, null, 2) : describeFields(res));
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
async function fieldsPut(id, file, initialsEveryPage) {
|
|
128
|
+
const parsed = JSON.parse(readFileSync(file, 'utf8'));
|
|
129
|
+
const list = Array.isArray(parsed) ? parsed : parsed.fields;
|
|
130
|
+
const res = await put(fieldsPath(id), buildFieldsBody(list, initialsEveryPage ?? parsed.initialsEveryPage));
|
|
131
|
+
console.log(`Saved fields for contract ${id}.`);
|
|
132
|
+
console.log(JSON.stringify(res, null, 2));
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// Service-to-service endpoint: needs the internal secret (env VELARO_INTERNAL_SECRET) and Features:SignupContracts on the server.
|
|
136
|
+
async function fromSignup(a) {
|
|
137
|
+
const secret = process.env.VELARO_INTERNAL_SECRET;
|
|
138
|
+
if (!secret) throw new Error('Set VELARO_INTERNAL_SECRET (Key Vault: VelaroInternalSecret) to call from-signup.');
|
|
139
|
+
const creds = await getCredentials();
|
|
140
|
+
const base = String(creds.adminApiBase).replace(/\/+$/, '');
|
|
141
|
+
const res = await fetch(`${base}${FROM_SIGNUP_PATH}`, {
|
|
142
|
+
method: 'POST',
|
|
143
|
+
headers: { 'Content-Type': 'application/json', 'X-Velaro-Internal-Secret': secret },
|
|
144
|
+
body: JSON.stringify(buildFromSignupBody(a)),
|
|
145
|
+
});
|
|
146
|
+
const text = await res.text();
|
|
147
|
+
if (!res.ok) throw new Error(`POST ${FROM_SIGNUP_PATH} -> ${res.status}: ${text.slice(0, 300)}`);
|
|
148
|
+
console.log(text);
|
|
149
|
+
}
|
|
150
|
+
|
|
121
151
|
export const signCommand = {
|
|
122
152
|
command: 'sign <subcommand>',
|
|
123
153
|
describe: 'Velaro Sign -- signer routing, reminders, final PDF, file verification',
|
|
@@ -191,7 +221,33 @@ export const signCommand = {
|
|
|
191
221
|
.option('note', { type: 'string', describe: 'Change note stored with the version' }),
|
|
192
222
|
handler: runCommand((a) => uploadVersion(a.contractId, a.file, a.note)),
|
|
193
223
|
})
|
|
194
|
-
.
|
|
224
|
+
.command({
|
|
225
|
+
command: 'fields <action> <contractId> [file]',
|
|
226
|
+
describe: 'Signing fields: get | put <file.json> (full set; types incl. fullname, email, company, title, dropdown; prefillKey)',
|
|
227
|
+
builder: (y2) => y2
|
|
228
|
+
.positional('action', { type: 'string', choices: ['get', 'put'] })
|
|
229
|
+
.positional('contractId', { type: 'number' })
|
|
230
|
+
.positional('file', { type: 'string' })
|
|
231
|
+
.option('json', { type: 'boolean', default: false })
|
|
232
|
+
.option('initials-every-page', { type: 'boolean', describe: 'Add an initials box to every page' }),
|
|
233
|
+
handler: runCommand((a) => {
|
|
234
|
+
if (a.action === 'get') return fieldsGet(a.contractId, a.json);
|
|
235
|
+
if (!a.file) throw new Error('put needs a JSON file: velaro sign fields put <contractId> <file.json>');
|
|
236
|
+
return fieldsPut(a.contractId, a.file, a.initialsEveryPage);
|
|
237
|
+
}),
|
|
238
|
+
})
|
|
239
|
+
.command({
|
|
240
|
+
command: 'from-signup',
|
|
241
|
+
describe: 'Create and send a contract from a signup flow, returns the signing link (needs VELARO_INTERNAL_SECRET)',
|
|
242
|
+
builder: (y2) => y2
|
|
243
|
+
.option('siteId', { type: 'number', demandOption: true }).option('title', { type: 'string', demandOption: true })
|
|
244
|
+
.option('customerEmail', { type: 'string', demandOption: true }).option('customerName', { type: 'string' })
|
|
245
|
+
.option('customerCompany', { type: 'string' }).option('packageName', { type: 'string' })
|
|
246
|
+
.option('totalMonthlyValue', { type: 'number' }).option('setupFee', { type: 'number' })
|
|
247
|
+
.option('contractTemplateId', { type: 'number' }).option('sendEmail', { type: 'boolean', default: false }),
|
|
248
|
+
handler: runCommand((a) => fromSignup(a)),
|
|
249
|
+
})
|
|
250
|
+
.demandCommand(1, 'Specify: fields | from-signup | signers | reassign | reminders | download | verify | versions | diff | upload-version')
|
|
195
251
|
.strict(),
|
|
196
252
|
handler: () => {},
|
|
197
253
|
};
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
// Pure helpers for Velaro Sign field surfaces (`velaro sign fields get|put`, `velaro sign from-signup`, MCP sign_fields_get/put).
|
|
2
|
+
// REST: GET/PUT /api/Contract/{id}/fields, POST /api/Contract/from-signup (internal secret, Features:SignupContracts).
|
|
3
|
+
export const FIELD_TYPES = ['signature', 'initials', 'date', 'text', 'checkbox', 'fullname', 'email', 'company', 'title', 'dropdown'];
|
|
4
|
+
export const SIGNER_ROLES = ['customer', 'velaro'];
|
|
5
|
+
|
|
6
|
+
export const fieldsPath = (id) => `/api/Contract/${Number(id)}/fields`;
|
|
7
|
+
export const FROM_SIGNUP_PATH = '/api/Contract/from-signup';
|
|
8
|
+
|
|
9
|
+
export function validateFields(fields) {
|
|
10
|
+
if (!Array.isArray(fields)) throw new Error('fields must be an array');
|
|
11
|
+
fields.forEach((f, i) => {
|
|
12
|
+
const at = `field ${i + 1}`;
|
|
13
|
+
if (!FIELD_TYPES.includes(f.fieldType)) throw new Error(`${at}: fieldType must be one of ${FIELD_TYPES.join(', ')}`);
|
|
14
|
+
if (f.signerRole && !SIGNER_ROLES.includes(f.signerRole)) throw new Error(`${at}: signerRole must be customer or velaro`);
|
|
15
|
+
if (!Number.isInteger(f.page) || f.page < 1) throw new Error(`${at}: page must be 1 or more`);
|
|
16
|
+
for (const k of ['xPct', 'yPct', 'widthPct', 'heightPct']) {
|
|
17
|
+
if (typeof f[k] !== 'number') throw new Error(`${at}: ${k} must be a number (percent of the page)`);
|
|
18
|
+
}
|
|
19
|
+
if (f.fieldType === 'dropdown' && !String(f.options || '').trim()) throw new Error(`${at}: a dropdown needs options (one per line)`);
|
|
20
|
+
});
|
|
21
|
+
return fields;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// Body for PUT /fields. The server replaces the whole field set, so callers pass the full list.
|
|
25
|
+
export function buildFieldsBody(fields, initialsEveryPage = false) {
|
|
26
|
+
return { initialsEveryPage: !!initialsEveryPage, fields: validateFields(fields) };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function describeFields(res) {
|
|
30
|
+
if (!res?.hasDocument) return 'No document uploaded yet; upload a PDF before placing fields.';
|
|
31
|
+
const rows = res.fields ?? [];
|
|
32
|
+
const out = [`${res.fileName || 'document'}: ${res.pageCount ?? '?'} page(s), ${rows.length} field(s)${res.initialsEveryPage ? ', initials on every page' : ''}`];
|
|
33
|
+
for (const f of rows) {
|
|
34
|
+
out.push(` #${f.id} p${f.page} ${f.fieldType} (${f.signerRole})${f.required ? ' required' : ''}${f.label ? ` "${f.label}"` : ''}${f.prefillKey ? ` prefill=${f.prefillKey}` : ''}${f.options ? ` options=${String(f.options).split('\n').length}` : ''}`);
|
|
35
|
+
}
|
|
36
|
+
return out.join('\n');
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function buildFromSignupBody(a) {
|
|
40
|
+
const siteId = Number(a.siteId);
|
|
41
|
+
if (!Number.isInteger(siteId) || siteId <= 0) throw new Error('siteId is required');
|
|
42
|
+
if (!a.title || !String(a.title).trim()) throw new Error('title is required');
|
|
43
|
+
if (!a.customerEmail || !String(a.customerEmail).includes('@')) throw new Error('a valid customerEmail is required');
|
|
44
|
+
const body = { siteId, title: String(a.title).trim(), customerEmail: String(a.customerEmail).trim(), sendEmail: !!a.sendEmail };
|
|
45
|
+
for (const k of ['customerName', 'customerCompany', 'packageName', 'totalMonthlyValue', 'setupFee', 'contractTemplateId']) {
|
|
46
|
+
if (a[k] !== undefined && a[k] !== null && a[k] !== '') body[k] = a[k];
|
|
47
|
+
}
|
|
48
|
+
return body;
|
|
49
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { test } from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { fieldsPath, buildFieldsBody, describeFields, buildFromSignupBody } from './sign-fields.js';
|
|
4
|
+
|
|
5
|
+
const ok = { fieldType: 'fullname', page: 1, xPct: 10, yPct: 10, widthPct: 20, heightPct: 5, prefillKey: 'name' };
|
|
6
|
+
|
|
7
|
+
test('fieldsPath', () => assert.equal(fieldsPath('7'), '/api/Contract/7/fields'));
|
|
8
|
+
|
|
9
|
+
test('buildFieldsBody accepts new types and rejects bad ones', () => {
|
|
10
|
+
assert.equal(buildFieldsBody([ok]).fields.length, 1);
|
|
11
|
+
assert.throws(() => buildFieldsBody([{ ...ok, fieldType: 'nope' }]), /fieldType/);
|
|
12
|
+
assert.throws(() => buildFieldsBody([{ ...ok, fieldType: 'dropdown' }]), /options/);
|
|
13
|
+
assert.throws(() => buildFieldsBody([{ ...ok, page: 0 }]), /page/);
|
|
14
|
+
assert.throws(() => buildFieldsBody([{ ...ok, signerRole: 'x' }]), /signerRole/);
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
test('describeFields shows prefill key', () => {
|
|
18
|
+
const out = describeFields({ hasDocument: true, fileName: 'a.pdf', pageCount: 2, fields: [{ id: 3, page: 1, fieldType: 'email', signerRole: 'customer', required: true, prefillKey: 'email' }] });
|
|
19
|
+
assert.match(out, /prefill=email/);
|
|
20
|
+
assert.match(describeFields({ hasDocument: false }), /No document/);
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
test('buildFromSignupBody validates', () => {
|
|
24
|
+
assert.throws(() => buildFromSignupBody({ title: 't', customerEmail: 'a@b.c' }), /siteId/);
|
|
25
|
+
assert.throws(() => buildFromSignupBody({ siteId: 1, title: 't', customerEmail: 'x' }), /customerEmail/);
|
|
26
|
+
assert.deepEqual(buildFromSignupBody({ siteId: 1, title: ' t ', customerEmail: 'a@b.c', sendEmail: true }), { siteId: 1, title: 't', customerEmail: 'a@b.c', sendEmail: true });
|
|
27
|
+
});
|
package/package.json
CHANGED