@velaro/cli 1.4.243 → 1.4.245
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 +343 -360
- package/lib/commands/billing.js +3 -71
- package/lib/commands/endpoint-parity.js +53 -58
- package/lib/commands/index.js +1 -43
- package/lib/commands/ingest.js +63 -36
- package/lib/commands/ingest.test.js +22 -0
- package/lib/commands/package-builder-my.js +13 -0
- package/lib/public-help.test.js +35 -0
- package/package.json +40 -40
- package/lib/commands/billing-agents.js +0 -51
- package/lib/commands/billing-automation.js +0 -184
- package/lib/commands/billing-email-preference.js +0 -64
- package/lib/commands/billing-subscription.js +0 -909
- package/lib/commands/order-form.js +0 -112
- package/lib/commands/package-builder.js +0 -35
- package/lib/commands/price-increase.js +0 -93
- package/lib/commands/sign.js +0 -253
- package/lib/commands/status-notify.js +0 -98
- package/lib/sign-fields.js +0 -49
- package/lib/sign-fields.test.js +0 -27
- package/lib/sign-versions.js +0 -58
- package/lib/sign-versions.test.js +0 -50
- package/lib/sign.test.js +0 -19
|
@@ -1,112 +0,0 @@
|
|
|
1
|
-
// velaro order-form -- staff-only order form onboarding flow (OrderFormController).
|
|
2
|
-
// See docs/architecture/order-form-onboarding-flow.md. Nothing here provisions, charges, or
|
|
3
|
-
// touches QuickBooks: it drafts a deal, generates the contract, and sends it through Velaro Sign.
|
|
4
|
-
import { request } from '../api.js';
|
|
5
|
-
|
|
6
|
-
function money(cents) {
|
|
7
|
-
return `$${(cents / 100).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
|
|
8
|
-
}
|
|
9
|
-
|
|
10
|
-
// --line "slug:qty[:unitPriceCents[:setupFeeCents[:termMonths[:cadence]]]]" (repeatable)
|
|
11
|
-
function parseLine(spec) {
|
|
12
|
-
const [slug, qty, unit, setup, term, cadence] = String(spec).split(':');
|
|
13
|
-
if (!slug) throw new Error(`Bad --line "${spec}". Format: slug:qty[:unitPriceCents[:setupFeeCents[:termMonths[:cadence]]]]`);
|
|
14
|
-
const line = { catalogSlug: slug, quantity: qty ? Number(qty) : 1 };
|
|
15
|
-
if (unit) line.unitPriceCents = Number(unit);
|
|
16
|
-
if (setup) line.setupFeeCents = Number(setup);
|
|
17
|
-
if (term) line.termMonths = Number(term);
|
|
18
|
-
if (cadence) line.cadence = cadence;
|
|
19
|
-
return line;
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
function printForm(f) {
|
|
23
|
-
console.log(`Order form ${f.id}: ${f.customerName} [${f.status}]`);
|
|
24
|
-
if (f.annualIncreasePercent != null) console.log(` annual increase ${f.annualIncreasePercent}% on ${f.increaseBasis ?? 'site default'} price`);
|
|
25
|
-
console.log(` payment=${f.paymentMode} invoiceDetail=${f.invoiceDetailMode} applyOnSign=${f.applyOnSign} contractId=${f.contractId ?? '-'}`);
|
|
26
|
-
for (const l of f.lines ?? []) {
|
|
27
|
-
console.log(` - ${l.catalogSlug} x${l.quantity} @ ${money(l.unitPriceCents)} (list ${money(l.listPriceCents)}) setup ${money(l.setupFeeCents)} ${l.termMonths}mo ${l.cadence}`);
|
|
28
|
-
}
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
async function createForm(args) {
|
|
32
|
-
const lines = [].concat(args.line ?? []).map(parseLine);
|
|
33
|
-
if (!args.customer || lines.length === 0) {
|
|
34
|
-
console.error('Usage: velaro order-form create --customer "Acme" --line slug:qty[:unitCents[:setupCents[:termMonths[:cadence]]]] [--line ...] [--site-id N] [--target v20] [--target-account-id X] [--payment-mode manual|card_checkout|invoice_net_terms] [--invoice-detail LineItemized|TermsReference] [--apply-on-sign] [--increase-percent 8] [--increase-basis list|net]');
|
|
35
|
-
process.exit(1);
|
|
36
|
-
}
|
|
37
|
-
const body = {
|
|
38
|
-
customerName: args.customer,
|
|
39
|
-
siteId: args.siteId,
|
|
40
|
-
targetSystem: args.target,
|
|
41
|
-
targetAccountId: args.targetAccountId,
|
|
42
|
-
paymentMode: args.paymentMode,
|
|
43
|
-
invoiceDetailMode: args.invoiceDetail,
|
|
44
|
-
applyOnSign: !!args.applyOnSign,
|
|
45
|
-
annualIncreasePercent: args.increasePercent,
|
|
46
|
-
increaseBasis: args.increaseBasis,
|
|
47
|
-
lines,
|
|
48
|
-
};
|
|
49
|
-
const f = await request('POST', '/api/OrderForm', body);
|
|
50
|
-
printForm(f);
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
async function getForm(id) {
|
|
54
|
-
printForm(await request('GET', `/api/OrderForm/${id}`));
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
async function listForms(args) {
|
|
58
|
-
const q = args.status ? `?status=${encodeURIComponent(args.status)}` : '';
|
|
59
|
-
const forms = await request('GET', `/api/OrderForm${q}`);
|
|
60
|
-
if (!forms.length) { console.log('No order forms.'); return; }
|
|
61
|
-
for (const f of forms) console.log(`${f.id}\t${f.status}\t${f.customerName}\tcontract=${f.contractId ?? '-'}`);
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
async function generateContract(id, args) {
|
|
65
|
-
if (!args.email) {
|
|
66
|
-
console.error('Usage: velaro order-form generate-contract <id> --email buyer@example.com [--name "Buyer Name"]');
|
|
67
|
-
process.exit(1);
|
|
68
|
-
}
|
|
69
|
-
const r = await request('POST', `/api/OrderForm/${id}/generate-contract`, { customerEmail: args.email, customerName: args.name });
|
|
70
|
-
console.log(`Contract ${r.contractId} generated (draft). Run: velaro order-form send ${id}`);
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
async function sendForm(id, args) {
|
|
74
|
-
const r = await request('POST', `/api/OrderForm/${id}/send`, { expirationDays: args.expirationDays });
|
|
75
|
-
console.log(`Sent. emailSent=${r.emailSent}${r.emailError ? ` (${r.emailError})` : ''}\nSigning URL: ${r.signingUrl}`);
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
async function voidForm(id) {
|
|
79
|
-
const f = await request('POST', `/api/OrderForm/${id}/void`);
|
|
80
|
-
console.log(`Order form ${f.id} is now ${f.status}.`);
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
export const orderFormCommand = {
|
|
84
|
-
command: 'order-form <subcommand>',
|
|
85
|
-
describe: 'Draft, contract, send, and void order forms (staff only)',
|
|
86
|
-
builder: (yargs) =>
|
|
87
|
-
yargs
|
|
88
|
-
.command('create', 'Create a draft order form (lines validated against the catalog)', {
|
|
89
|
-
customer: { type: 'string' },
|
|
90
|
-
line: { type: 'string', array: true, describe: 'slug:qty[:unitPriceCents[:setupFeeCents[:termMonths[:cadence]]]]' },
|
|
91
|
-
'site-id': { type: 'number' },
|
|
92
|
-
target: { type: 'string' },
|
|
93
|
-
'target-account-id': { type: 'string' },
|
|
94
|
-
'payment-mode': { type: 'string', choices: ['manual', 'card_checkout', 'invoice_net_terms'] },
|
|
95
|
-
'invoice-detail': { type: 'string', choices: ['LineItemized', 'TermsReference'] },
|
|
96
|
-
'apply-on-sign': { type: 'boolean', default: false },
|
|
97
|
-
'increase-percent': { type: 'number', describe: 'annual price increase percent stated in the contract' },
|
|
98
|
-
'increase-basis': { type: 'string', choices: ['list', 'net'], describe: 'calculate the increase on the undiscounted (list) or discounted (net) price; omit for the site default' },
|
|
99
|
-
}, (args) => createForm(args))
|
|
100
|
-
.command('get <id>', 'Show an order form', {}, (args) => getForm(args.id))
|
|
101
|
-
.command('list', 'List order forms', { status: { type: 'string' } }, (args) => listForms(args))
|
|
102
|
-
.command('generate-contract <id>', 'Generate the draft contract from the order form', {
|
|
103
|
-
email: { type: 'string' },
|
|
104
|
-
name: { type: 'string' },
|
|
105
|
-
}, (args) => generateContract(args.id, args))
|
|
106
|
-
.command('send <id>', 'Send the generated contract for signature via Velaro Sign', {
|
|
107
|
-
'expiration-days': { type: 'number' },
|
|
108
|
-
}, (args) => sendForm(args.id, args))
|
|
109
|
-
.command('void <id>', 'Void an order form (and its unsigned contract)', {}, (args) => voidForm(args.id))
|
|
110
|
-
.demandCommand(1),
|
|
111
|
-
handler: () => {},
|
|
112
|
-
};
|
|
@@ -1,35 +0,0 @@
|
|
|
1
|
-
// velaro package-builder: package graph, drafts, simulation, audit (staff only; `my` is customer-safe).
|
|
2
|
-
import { request } from '../api.js';
|
|
3
|
-
|
|
4
|
-
const show = (o) => console.log(JSON.stringify(o, null, 2));
|
|
5
|
-
const get = (path) => async () => show(await request('GET', path));
|
|
6
|
-
const enc = encodeURIComponent;
|
|
7
|
-
|
|
8
|
-
export function packageBuilderCommand(yargs) {
|
|
9
|
-
return yargs
|
|
10
|
-
.command('graph', 'Features, packages, add-ons and standalone flags', () => {}, get('/PackageBuilder/graph'))
|
|
11
|
-
.command('site <siteId>', 'Per-flag provenance for a site', y => y.positional('siteId', { type: 'number' }), async a => show(await request('GET', `/PackageBuilder/site/${a.siteId}`)))
|
|
12
|
-
.command('versions <planKey>', 'Version history of a plan', y => y.positional('planKey', { type: 'string' }), async a => show(await request('GET', `/PackageBuilder/versions/${enc(a.planKey)}`)))
|
|
13
|
-
.command('diff', 'Diff two plan versions', y => y.option('plan', { type: 'string', demandOption: true }).option('from', { type: 'number', demandOption: true }).option('to', { type: 'number', demandOption: true }),
|
|
14
|
-
async a => show(await request('GET', `/PackageBuilder/diff?planKey=${enc(a.plan)}&from=${a.from}&to=${a.to}`)))
|
|
15
|
-
.command('drafts', 'List drafts', y => y.option('status', { type: 'string' }), async a => show(await request('GET', `/PackageBuilder/drafts${a.status ? `?status=${enc(a.status)}` : ''}`)))
|
|
16
|
-
.command('draft-create', 'Create a draft (from scratch or --clone-of plan.key)', y => y
|
|
17
|
-
.option('name', { type: 'string' }).option('clone-of', { type: 'string' }).option('features', { type: 'string', desc: 'comma-separated feature keys' }),
|
|
18
|
-
async a => show(await request('POST', '/PackageBuilder/drafts', { name: a.name, cloneOf: a['clone-of'], definition: a.features ? { features: a.features.split(',') } : undefined })))
|
|
19
|
-
.command('draft-update <id>', 'Replace a draft definition', y => y.positional('id', { type: 'number' }).option('features', { type: 'string', demandOption: true }).option('price-cents', { type: 'number' }).option('name', { type: 'string' }),
|
|
20
|
-
async a => show(await request('PUT', `/PackageBuilder/drafts/${a.id}`, { name: a.name, definition: { features: a.features.split(','), priceCents: a['price-cents'] } })))
|
|
21
|
-
.command('submit <id>', 'Submit draft for approval', y => y.positional('id', { type: 'number' }), async a => show(await request('POST', `/PackageBuilder/drafts/${a.id}/submit`, {})))
|
|
22
|
-
.command('approve <id>', 'Approve draft (approver must differ from creator)', y => y.positional('id', { type: 'number' }), async a => show(await request('POST', `/PackageBuilder/drafts/${a.id}/approve`, {})))
|
|
23
|
-
.command('publish <id>', 'Publish approved draft as new PlanEntitlement version rows', y => y.positional('id', { type: 'number' }), async a => show(await request('POST', `/PackageBuilder/drafts/${a.id}/publish`, {})))
|
|
24
|
-
.command('simulate', 'What-if across a cohort (pure read)', y => y.option('draft', { type: 'number' }).option('plan', { type: 'string' }).option('cohort', { type: 'string' }),
|
|
25
|
-
async a => show(await request('POST', '/PackageBuilder/simulate', { draftId: a.draft, basePlanKey: a.plan, cohort: a.cohort })))
|
|
26
|
-
.command('audit', 'Entitlement/package change timeline', y => y.option('site', { type: 'number' }).option('plan', { type: 'string' }),
|
|
27
|
-
async a => show(await request('GET', `/PackageBuilder/audit?${new URLSearchParams({ ...(a.site ? { siteId: a.site } : {}), ...(a.plan ? { planKey: a.plan } : {}) })}`)))
|
|
28
|
-
.command('health', 'Orphan flags, overlap, drift, cart parity', () => {}, get('/PackageBuilder/health'))
|
|
29
|
-
.command('fit', 'Cheapest package covering the given features', y => y.option('features', { type: 'string', demandOption: true }),
|
|
30
|
-
async a => show(await request('POST', '/PackageBuilder/fit', { featureKeys: a.features.split(',') })))
|
|
31
|
-
.command('proration', 'Upgrade/downgrade proration preview', y => y.option('from', { type: 'string', demandOption: true }).option('to', { type: 'string', demandOption: true }).option('days-remaining', { type: 'number', demandOption: true }).option('days-in-period', { type: 'number', default: 30 }),
|
|
32
|
-
async a => show(await request('GET', `/PackageBuilder/proration?fromPlan=${enc(a.from)}&toPlan=${enc(a.to)}&daysRemaining=${a['days-remaining']}&daysInPeriod=${a['days-in-period']}`)))
|
|
33
|
-
.command('my', 'Your own package and what it includes (customer-safe)', () => {}, get('/PackageBuilder/my'))
|
|
34
|
-
.demandCommand(1, 'Specify a subcommand');
|
|
35
|
-
}
|
|
@@ -1,93 +0,0 @@
|
|
|
1
|
-
// velaro price-increase -- staff-only annual price increase basis (PriceIncreaseController).
|
|
2
|
-
// See docs/architecture/price-increase-basis.md.
|
|
3
|
-
// basis "list": increase = % of the undiscounted price, added to what the customer pays (discount stays the same dollars)
|
|
4
|
-
// basis "net": increase = % of what the customer pays (discount stays the same percent)
|
|
5
|
-
// Nothing here appears on an invoice; every applied increase is written to an internal audit log.
|
|
6
|
-
import { request } from '../api.js';
|
|
7
|
-
|
|
8
|
-
const BASE = '/api/PriceIncrease';
|
|
9
|
-
|
|
10
|
-
function money(cents) {
|
|
11
|
-
if (cents === null || cents === undefined) return '-';
|
|
12
|
-
return `$${(Number(cents) / 100).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
async function getSettings() {
|
|
16
|
-
const s = await request('GET', `${BASE}/settings`);
|
|
17
|
-
console.log(`Default increase basis: ${s.defaultBasis}${s.isExplicitlySet ? '' : ' (never set, using the built-in default)'}`);
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
async function setDefault(args) {
|
|
21
|
-
if (!['list', 'net', 'clear'].includes(args.basis)) {
|
|
22
|
-
console.error('Usage: velaro price-increase set-default <list|net|clear>');
|
|
23
|
-
process.exit(1);
|
|
24
|
-
}
|
|
25
|
-
const r = await request('PUT', `${BASE}/settings`, { defaultBasis: args.basis === 'clear' ? null : args.basis });
|
|
26
|
-
console.log(`Default increase basis is now: ${r.defaultBasis}`);
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
async function showSubscription(id) {
|
|
30
|
-
const t = await request('GET', `${BASE}/subscriptions/${id}`);
|
|
31
|
-
console.log(`Subscription ${t.subscriptionId}`);
|
|
32
|
-
console.log(` net per period: ${money(t.recurringAmountCents)} list per period: ${money(t.recurringListAmountCents)}`);
|
|
33
|
-
console.log(` basis: ${t.effectiveBasis} (from ${t.effectiveBasisSource}${t.basis ? '' : ', inherited'}) annual increase: ${t.annualIncreasePercent ?? '-'}%`);
|
|
34
|
-
console.log(` next increase: ${t.nextPriceIncreaseDate?.slice(0, 10) ?? '-'} applied so far: ${t.priceIncreasesApplied}${t.needsReview ? ' NEEDS REVIEW (list price missing)' : ''}`);
|
|
35
|
-
for (const l of t.log ?? []) {
|
|
36
|
-
console.log(` year ${l.contractYearIndex} ${l.anniversaryDate?.slice(0, 10)} ${l.applied ? 'APPLIED' : 'SKIPPED'}: ${l.formula}${l.invoiceId ? ` (invoice ${l.invoiceId})` : ''}`);
|
|
37
|
-
}
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
async function setSubscription(id, args) {
|
|
41
|
-
const body = {};
|
|
42
|
-
if (args.basis !== undefined) body.basis = args.basis === 'inherit' ? null : args.basis;
|
|
43
|
-
if (args.percent !== undefined) body.annualIncreasePercent = args.percent === 'none' ? null : Number(args.percent);
|
|
44
|
-
if (args.listCents !== undefined) body.recurringListAmountCents = Number(args.listCents);
|
|
45
|
-
if (args.next !== undefined) body.nextPriceIncreaseDate = args.next === 'none' ? null : args.next;
|
|
46
|
-
if (Object.keys(body).length === 0) {
|
|
47
|
-
console.error('Usage: velaro price-increase set <subscriptionId> [--basis list|net|inherit] [--percent 8|none] [--list-cents 1000000] [--next 2027-01-01|none]');
|
|
48
|
-
process.exit(1);
|
|
49
|
-
}
|
|
50
|
-
const r = await request('PUT', `${BASE}/subscriptions/${id}`, body);
|
|
51
|
-
console.log(r.changes?.length ? `Updated: ${r.changes.join('; ')}` : 'No change.');
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
async function linkOrderForm(id, formId) {
|
|
55
|
-
const r = await request('POST', `${BASE}/subscriptions/${id}/link-order-form/${formId}`, {});
|
|
56
|
-
console.log(r.summary ?? 'Linked.');
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
async function preview(args) {
|
|
60
|
-
const r = await request('POST', `${BASE}/preview`, {
|
|
61
|
-
listCents: Number(args.listCents), netCents: Number(args.netCents), percent: Number(args.percent), years: args.years,
|
|
62
|
-
});
|
|
63
|
-
console.log('Year LIST basis (net / discount) NET basis (net / discount)');
|
|
64
|
-
r.list.forEach((row, i) => {
|
|
65
|
-
const n = r.net[i];
|
|
66
|
-
console.log(`${String(row.year).padEnd(5)} ${(money(row.netCents) + ' / ' + money(row.discountCents)).padEnd(34)} ${money(n.netCents)} / ${money(n.discountCents)}`);
|
|
67
|
-
});
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
export const priceIncreaseCommand = {
|
|
71
|
-
command: 'price-increase <subcommand>',
|
|
72
|
-
describe: 'Annual price increase basis: list vs discounted price (staff only)',
|
|
73
|
-
builder: (yargs) =>
|
|
74
|
-
yargs
|
|
75
|
-
.command('settings', 'Show the site-wide default basis', {}, () => getSettings())
|
|
76
|
-
.command('set-default <basis>', 'Set the site-wide default basis: list | net | clear', {}, (args) => setDefault(args))
|
|
77
|
-
.command('show <id>', 'Show a subscription\'s increase terms and its audit log', {}, (args) => showSubscription(args.id))
|
|
78
|
-
.command('set <id>', 'Update a subscription\'s increase terms (only the flags you pass change)', {
|
|
79
|
-
basis: { type: 'string', choices: ['list', 'net', 'inherit'] },
|
|
80
|
-
percent: { type: 'string', describe: 'annual percent, or "none" to clear' },
|
|
81
|
-
'list-cents': { type: 'number', describe: 'undiscounted price per billing period, in cents' },
|
|
82
|
-
next: { type: 'string', describe: 'next anniversary date (YYYY-MM-DD) or "none"' },
|
|
83
|
-
}, (args) => setSubscription(args.id, args))
|
|
84
|
-
.command('link-order-form <id> <formId>', 'Copy the increase terms of a SIGNED order form (basis, percent, per-line exceptions) onto a subscription so billing follows the contract', {}, (args) => linkOrderForm(args.id, args.formId))
|
|
85
|
-
.command('preview', 'Compare both bases side by side (no changes made)', {
|
|
86
|
-
'list-cents': { type: 'number', demandOption: true },
|
|
87
|
-
'net-cents': { type: 'number', demandOption: true },
|
|
88
|
-
percent: { type: 'number', demandOption: true },
|
|
89
|
-
years: { type: 'number' },
|
|
90
|
-
}, (args) => preview(args))
|
|
91
|
-
.demandCommand(1),
|
|
92
|
-
handler: () => {},
|
|
93
|
-
};
|
package/lib/commands/sign.js
DELETED
|
@@ -1,253 +0,0 @@
|
|
|
1
|
-
import { readFileSync, writeFileSync } from 'node:fs';
|
|
2
|
-
import { basename } from 'node:path';
|
|
3
|
-
import { get, post, put, postForm, getBinary, getCredentials } from '../api.js';
|
|
4
|
-
import { runCommand } from '../run.js';
|
|
5
|
-
import { fieldsPath, FROM_SIGNUP_PATH, buildFieldsBody, describeFields, buildFromSignupBody } from '../sign-fields.js';
|
|
6
|
-
import { versionsPath, diffPath, uploadPath, describeVersions, describeDiff, buildUploadForm, OWNER_ONLY_RULE } from '../sign-versions.js';
|
|
7
|
-
|
|
8
|
-
// velaro sign -- Velaro Sign routing, reminders, final PDF download, file verification.
|
|
9
|
-
// Backend: server/Velaro.Admin/Controllers/ContractSignersController.cs (route api/Contract)
|
|
10
|
-
// GET api/Contract/{id}/signers
|
|
11
|
-
// PUT api/Contract/{id}/signers
|
|
12
|
-
// POST api/Contract/{id}/signers/reassignments/{requestId}/approve|deny
|
|
13
|
-
// PUT api/Contract/{id}/reminders
|
|
14
|
-
// GET api/Contract/{id}/signed-document
|
|
15
|
-
// POST api/Contract/verify (multipart 'file')
|
|
16
|
-
|
|
17
|
-
const csv = (v) => (v == null ? [] : String(v).split(',').map(s => s.trim()).filter(Boolean));
|
|
18
|
-
|
|
19
|
-
export function buildSignersBody(existing, argv) {
|
|
20
|
-
const emails = csv(argv.order);
|
|
21
|
-
const names = csv(argv.names);
|
|
22
|
-
const roles = csv(argv.roles);
|
|
23
|
-
const body = {
|
|
24
|
-
mode: argv.mode || existing?.mode || 'sequential',
|
|
25
|
-
allowReassignment: argv.allowReassign != null ? !!argv.allowReassign : existing?.allowReassignment,
|
|
26
|
-
reminderEveryDays: existing?.reminderEveryDays,
|
|
27
|
-
reminderMaxCount: existing?.reminderMaxCount,
|
|
28
|
-
};
|
|
29
|
-
if (emails.length) {
|
|
30
|
-
const prior = new Map((existing?.signers || []).map(s => [String(s.email).toLowerCase(), s]));
|
|
31
|
-
body.signers = emails.map((email, i) => {
|
|
32
|
-
const p = prior.get(email.toLowerCase());
|
|
33
|
-
return {
|
|
34
|
-
order: i + 1,
|
|
35
|
-
role: roles[i] || p?.role || 'customer',
|
|
36
|
-
name: names[i] || p?.name || email.split('@')[0],
|
|
37
|
-
email,
|
|
38
|
-
};
|
|
39
|
-
});
|
|
40
|
-
} else {
|
|
41
|
-
body.signers = (existing?.signers || []).map((s, i) => ({ order: s.order ?? i + 1, role: s.role, name: s.name, email: s.email }));
|
|
42
|
-
}
|
|
43
|
-
return body;
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
function showSigners(r) {
|
|
47
|
-
console.log(`\nContract status: ${r.contractStatus} routing: ${r.routingStatus} mode: ${r.mode} reassignment: ${r.allowReassignment ? 'allowed' : 'off'}`);
|
|
48
|
-
console.log(`Reminders: every ${r.reminderEveryDays ?? '-'}d, max ${r.reminderMaxCount ?? '-'}`);
|
|
49
|
-
console.log(`Original SHA-256: ${r.originalSha256 || '-'}`);
|
|
50
|
-
console.log(`Signed SHA-256: ${r.signedSha256 || '-'} (final PDF ${r.finalPdfAvailable ? 'available' : 'not available'})`);
|
|
51
|
-
for (const s of r.signers || []) {
|
|
52
|
-
console.log(` ${s.order}. [${s.role}] ${s.name} <${s.email}> ${s.status}${s.signedAt ? ' ' + s.signedAt : ''}`);
|
|
53
|
-
}
|
|
54
|
-
for (const q of r.reassignmentRequests || []) {
|
|
55
|
-
console.log(` reassignment request: ${JSON.stringify(q)}`);
|
|
56
|
-
}
|
|
57
|
-
console.log('');
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
async function signersHandler(argv) {
|
|
61
|
-
const base = `/api/Contract/${argv.id}/signers`;
|
|
62
|
-
const existing = await get(base);
|
|
63
|
-
if (argv.action !== 'set') return showSigners(existing);
|
|
64
|
-
await put(base, buildSignersBody(existing, argv));
|
|
65
|
-
showSigners(await get(base));
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
async function reassignHandler(argv) {
|
|
69
|
-
await post(`/api/Contract/${argv.id}/signers/reassignments/${argv.requestId}/${argv.decision}`, argv.note ? { note: argv.note } : {});
|
|
70
|
-
console.log(`\nReassignment ${argv.requestId} ${argv.decision === 'approve' ? 'approved' : 'denied'}.\n`);
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
async function remindersHandler(argv) {
|
|
74
|
-
await put(`/api/Contract/${argv.id}/reminders`, { everyDays: argv.every, maxCount: argv.max });
|
|
75
|
-
console.log(`\nReminders set: every ${argv.every} day(s), max ${argv.max}.\n`);
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
async function downloadHandler(argv) {
|
|
79
|
-
const buf = await getBinary(`/api/Contract/${argv.id}/signed-document`);
|
|
80
|
-
const out = argv.out || `contract-${argv.id}-signed.pdf`;
|
|
81
|
-
writeFileSync(out, buf);
|
|
82
|
-
console.log(`\nSaved ${buf.length} bytes to ${out}\n`);
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
async function verifyHandler(argv) {
|
|
86
|
-
const form = new FormData();
|
|
87
|
-
form.append('file', new Blob([readFileSync(argv.file)]), basename(argv.file));
|
|
88
|
-
const r = await postForm('/api/Contract/verify', form);
|
|
89
|
-
if (r?.match) {
|
|
90
|
-
console.log(`\nMATCH contract ${r.contractId} "${r.title ?? ''}" (${r.status}) matched ${r.matched}\n sha256 ${r.sha256}\n`);
|
|
91
|
-
} else {
|
|
92
|
-
console.log(`\nNO MATCH sha256 ${r?.sha256 ?? '-'}\n`);
|
|
93
|
-
process.exitCode = 1;
|
|
94
|
-
}
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
async function versions(id, json) {
|
|
98
|
-
const res = await get(versionsPath(id));
|
|
99
|
-
console.log(json ? JSON.stringify(res, null, 2) : describeVersions(res));
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
async function diff(id, from, to, json) {
|
|
103
|
-
const res = await get(diffPath(id, from, to));
|
|
104
|
-
console.log(json ? JSON.stringify(res, null, 2) : describeDiff(res));
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
async function uploadVersion(id, file, note) {
|
|
108
|
-
const creds = await getCredentials();
|
|
109
|
-
const form = buildUploadForm(file, note);
|
|
110
|
-
const base = String(creds.adminApiBase).replace(/\/+$/, '');
|
|
111
|
-
const res = await fetch(`${base}${uploadPath(id)}`, {
|
|
112
|
-
method: 'POST',
|
|
113
|
-
headers: { Authorization: `Bearer ${creds.velaroToken}` },
|
|
114
|
-
body: form,
|
|
115
|
-
});
|
|
116
|
-
const text = await res.text();
|
|
117
|
-
if (!res.ok) throw new Error(`POST ${uploadPath(id)} -> ${res.status}: ${text.slice(0, 300)}\n${OWNER_ONLY_RULE}`);
|
|
118
|
-
console.log(`Uploaded new version for contract ${id}.`);
|
|
119
|
-
console.log(describeVersions(await get(versionsPath(id))));
|
|
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
|
-
|
|
151
|
-
export const signCommand = {
|
|
152
|
-
command: 'sign <subcommand>',
|
|
153
|
-
describe: 'Velaro Sign -- signer routing, reminders, final PDF, file verification',
|
|
154
|
-
builder: (y) => y
|
|
155
|
-
.command({
|
|
156
|
-
command: 'signers <id> [action]',
|
|
157
|
-
describe: 'Show signers (default) or "set" the routing',
|
|
158
|
-
builder: (y2) => y2
|
|
159
|
-
.positional('id', { type: 'number' })
|
|
160
|
-
.positional('action', { type: 'string', choices: ['set'] })
|
|
161
|
-
.option('order', { describe: 'Comma-separated signer emails in signing order', type: 'string' })
|
|
162
|
-
.option('names', { describe: 'Comma-separated names matching --order', type: 'string' })
|
|
163
|
-
.option('roles', { describe: 'Comma-separated roles (customer|velaro) matching --order', type: 'string' })
|
|
164
|
-
.option('mode', { describe: 'sequential | parallel', type: 'string', choices: ['sequential', 'parallel'] })
|
|
165
|
-
.option('allow-reassign', { describe: 'Allow signers to request reassignment', type: 'boolean' }),
|
|
166
|
-
handler: runCommand(signersHandler),
|
|
167
|
-
})
|
|
168
|
-
.command({
|
|
169
|
-
command: 'reassign <decision> <id> <requestId>',
|
|
170
|
-
describe: 'Approve or deny a signer reassignment request',
|
|
171
|
-
builder: (y2) => y2
|
|
172
|
-
.positional('decision', { type: 'string', choices: ['approve', 'deny'] })
|
|
173
|
-
.positional('id', { type: 'number' })
|
|
174
|
-
.positional('requestId', { type: 'number' })
|
|
175
|
-
.option('note', { type: 'string' }),
|
|
176
|
-
handler: runCommand(reassignHandler),
|
|
177
|
-
})
|
|
178
|
-
.command({
|
|
179
|
-
command: 'reminders set <id>',
|
|
180
|
-
describe: 'Set reminder cadence',
|
|
181
|
-
builder: (y2) => y2
|
|
182
|
-
.positional('id', { type: 'number' })
|
|
183
|
-
.option('every', { describe: 'Days between reminders', type: 'number', demandOption: true })
|
|
184
|
-
.option('max', { describe: 'Max reminders', type: 'number', demandOption: true }),
|
|
185
|
-
handler: runCommand(remindersHandler),
|
|
186
|
-
})
|
|
187
|
-
.command({
|
|
188
|
-
command: 'download <id>',
|
|
189
|
-
describe: 'Download the final signed PDF',
|
|
190
|
-
builder: (y2) => y2.positional('id', { type: 'number' }).option('out', { type: 'string', describe: 'Output file' }),
|
|
191
|
-
handler: runCommand(downloadHandler),
|
|
192
|
-
})
|
|
193
|
-
.command({
|
|
194
|
-
command: 'verify <file>',
|
|
195
|
-
describe: 'Verify a file against original/final contract hashes (exit 1 on no match)',
|
|
196
|
-
builder: (y2) => y2.positional('file', { type: 'string' }),
|
|
197
|
-
handler: runCommand(verifyHandler),
|
|
198
|
-
})
|
|
199
|
-
.command({
|
|
200
|
-
command: 'versions <contractId>',
|
|
201
|
-
describe: 'List every uploaded document version of a contract (owner-only)',
|
|
202
|
-
builder: (y2) => y2.positional('contractId', { type: 'number' }).option('json', { type: 'boolean', default: false }),
|
|
203
|
-
handler: runCommand((a) => versions(a.contractId, a.json)),
|
|
204
|
-
})
|
|
205
|
-
.command({
|
|
206
|
-
command: 'diff <contractId> <from> <to>',
|
|
207
|
-
describe: 'Text diff between two document versions (owner-only)',
|
|
208
|
-
builder: (y2) => y2
|
|
209
|
-
.positional('contractId', { type: 'number' })
|
|
210
|
-
.positional('from', { type: 'number' })
|
|
211
|
-
.positional('to', { type: 'number' })
|
|
212
|
-
.option('json', { type: 'boolean', default: false }),
|
|
213
|
-
handler: runCommand((a) => diff(a.contractId, a.from, a.to, a.json)),
|
|
214
|
-
})
|
|
215
|
-
.command({
|
|
216
|
-
command: 'upload-version <contractId> <file>',
|
|
217
|
-
describe: 'Upload a new PDF version (draft contracts only; after send/sign void and re-send)',
|
|
218
|
-
builder: (y2) => y2
|
|
219
|
-
.positional('contractId', { type: 'number' })
|
|
220
|
-
.positional('file', { type: 'string' })
|
|
221
|
-
.option('note', { type: 'string', describe: 'Change note stored with the version' }),
|
|
222
|
-
handler: runCommand((a) => uploadVersion(a.contractId, a.file, a.note)),
|
|
223
|
-
})
|
|
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')
|
|
251
|
-
.strict(),
|
|
252
|
-
handler: () => {},
|
|
253
|
-
};
|
|
@@ -1,98 +0,0 @@
|
|
|
1
|
-
import { messagingRequest } from '../api.js';
|
|
2
|
-
|
|
3
|
-
// Staff "Notify subscribers" for the public status page (velaro-messaging StatusNotificationsController).
|
|
4
|
-
// Only major incidents and scheduled maintenance are ever emailed. `send` is guarded: it re-runs the preview,
|
|
5
|
-
// refuses unless --confirm-count equals the live recipient count, and needs an --idempotency-key.
|
|
6
|
-
|
|
7
|
-
function buildRequest(argv) {
|
|
8
|
-
const body = {};
|
|
9
|
-
if (argv.incident !== undefined) body.incidentId = argv.incident;
|
|
10
|
-
if (argv.title) {
|
|
11
|
-
body.announcement = {
|
|
12
|
-
title: argv.title,
|
|
13
|
-
impact: argv.impact ?? null,
|
|
14
|
-
components: argv.components ? String(argv.components).split(',').map((s) => s.trim()).filter(Boolean) : null,
|
|
15
|
-
windowStart: argv.windowStart ?? null,
|
|
16
|
-
windowEnd: argv.windowEnd ?? null,
|
|
17
|
-
};
|
|
18
|
-
}
|
|
19
|
-
if (argv.subject) body.subject = argv.subject;
|
|
20
|
-
if (argv.body) body.body = argv.body;
|
|
21
|
-
return body;
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
const draftOptions = (y) => y
|
|
25
|
-
.option('incident', { type: 'number', describe: 'Status incident id (use this OR --title)' })
|
|
26
|
-
.option('title', { type: 'string', describe: 'Announcement title (no incident)' })
|
|
27
|
-
.option('impact', { type: 'string' })
|
|
28
|
-
.option('components', { type: 'string', describe: 'CSV of component names' })
|
|
29
|
-
.option('window-start', { type: 'string', describe: 'ISO timestamp' })
|
|
30
|
-
.option('window-end', { type: 'string', describe: 'ISO timestamp' })
|
|
31
|
-
.option('subject', { type: 'string', describe: 'Edited subject (default: generated)' })
|
|
32
|
-
.option('body', { type: 'string', describe: 'Edited plain-text body (default: generated)' });
|
|
33
|
-
|
|
34
|
-
const out = (data) => console.log(JSON.stringify(data, null, 2));
|
|
35
|
-
|
|
36
|
-
const settingsCommand = {
|
|
37
|
-
command: 'settings',
|
|
38
|
-
describe: 'Show send switch, recipient cap and subscriber counts',
|
|
39
|
-
builder: (y) => y,
|
|
40
|
-
handler: async () => out(await messagingRequest('GET', '/StatusNotifications/settings')),
|
|
41
|
-
};
|
|
42
|
-
|
|
43
|
-
const subscribersCommand = {
|
|
44
|
-
command: 'subscribers',
|
|
45
|
-
describe: 'Confirmed / pending / unsubscribed subscriber counts',
|
|
46
|
-
builder: (y) => y,
|
|
47
|
-
handler: async () => {
|
|
48
|
-
const s = await messagingRequest('GET', '/StatusNotifications/settings');
|
|
49
|
-
console.log(`confirmed=${s.confirmedSubscribers} pending=${s.pendingSubscribers} unsubscribed=${s.unsubscribed}`);
|
|
50
|
-
},
|
|
51
|
-
};
|
|
52
|
-
|
|
53
|
-
const previewCommand = {
|
|
54
|
-
command: 'preview',
|
|
55
|
-
describe: 'Draft the notice and show the live recipient count. Sends nothing.',
|
|
56
|
-
builder: draftOptions,
|
|
57
|
-
handler: async (argv) => out(await messagingRequest('POST', '/StatusNotifications/preview', buildRequest(argv))),
|
|
58
|
-
};
|
|
59
|
-
|
|
60
|
-
const testSendCommand = {
|
|
61
|
-
command: 'test-send',
|
|
62
|
-
describe: 'Send the draft to the signed-in staff member only',
|
|
63
|
-
builder: draftOptions,
|
|
64
|
-
handler: async (argv) => out(await messagingRequest('POST', '/StatusNotifications/test-send', buildRequest(argv))),
|
|
65
|
-
};
|
|
66
|
-
|
|
67
|
-
const sendCommand = {
|
|
68
|
-
command: 'send',
|
|
69
|
-
describe: 'Send the notice to ALL confirmed subscribers. Requires --confirm-count (must equal the preview recipient count) and --idempotency-key.',
|
|
70
|
-
builder: (y) => draftOptions(y)
|
|
71
|
-
.option('confirm-count', { type: 'number', demandOption: true, describe: 'Recipient count from `status-notify preview`' })
|
|
72
|
-
.option('idempotency-key', { type: 'string', demandOption: true, describe: 'One key per announcement; retries never double-send' }),
|
|
73
|
-
handler: async (argv) => {
|
|
74
|
-
const req = buildRequest(argv);
|
|
75
|
-
const preview = await messagingRequest('POST', '/StatusNotifications/preview', req);
|
|
76
|
-
if (preview.recipientCount !== argv.confirmCount) {
|
|
77
|
-
console.error(`Refusing to send: --confirm-count ${argv.confirmCount} does not match live recipient count ${preview.recipientCount}. Re-run preview.`);
|
|
78
|
-
process.exitCode = 1;
|
|
79
|
-
return;
|
|
80
|
-
}
|
|
81
|
-
out(await messagingRequest('POST', '/StatusNotifications/send', { ...req, expectedRecipientCount: argv.confirmCount, idempotencyKey: argv.idempotencyKey }));
|
|
82
|
-
},
|
|
83
|
-
};
|
|
84
|
-
|
|
85
|
-
const auditCommand = {
|
|
86
|
-
command: 'audit',
|
|
87
|
-
describe: 'Recent send audit rows',
|
|
88
|
-
builder: (y) => y.option('take', { type: 'number', default: 50 }),
|
|
89
|
-
handler: async (argv) => out(await messagingRequest('GET', `/StatusNotifications/audit?take=${argv.take}`)),
|
|
90
|
-
};
|
|
91
|
-
|
|
92
|
-
export const statusNotifyCommand = {
|
|
93
|
-
command: 'status-notify <subcommand>',
|
|
94
|
-
describe: 'Status page email alerts: settings, preview, test-send, send, audit, subscribers (staff only)',
|
|
95
|
-
builder: (y) => y.command(settingsCommand).command(subscribersCommand).command(previewCommand).command(testSendCommand).command(sendCommand).command(auditCommand)
|
|
96
|
-
.demandCommand(1, 'Specify a subcommand: settings, subscribers, preview, test-send, send, audit').strict(),
|
|
97
|
-
handler: () => {},
|
|
98
|
-
};
|
package/lib/sign-fields.js
DELETED
|
@@ -1,49 +0,0 @@
|
|
|
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
|
-
}
|