@winning-sales/nexo 0.2.1 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +66 -2
- package/assets/docs/pages.json +1 -1
- package/assets/skills/nexo-automations/SKILL.md +45 -0
- package/dist/automations/project.js +69 -0
- package/dist/automations/summary.js +79 -0
- package/dist/commands/artifacts.js +118 -0
- package/dist/commands/automations.js +354 -0
- package/dist/commands/billing.js +144 -0
- package/dist/commands/document-negotiation.js +60 -0
- package/dist/commands/document-templates.js +76 -0
- package/dist/commands/documents.js +215 -0
- package/dist/commands/logout.js +2 -2
- package/dist/commands/whoami.js +5 -6
- package/dist/documents/answers-file.js +91 -0
- package/dist/documents/journey-api.js +110 -0
- package/dist/documents/journey.types.js +1 -0
- package/dist/documents/summary.js +102 -0
- package/dist/documents/transfer.js +42 -0
- package/dist/http/problem.js +28 -2
- package/dist/input/confirm.js +21 -0
- package/dist/program-artifacts.js +37 -0
- package/dist/program-automations.js +138 -0
- package/dist/program-documents.js +150 -0
- package/dist/program.js +28 -1
- package/dist/skills/targets.js +1 -1
- package/package.json +2 -2
- package/reference.json +1080 -57
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import { clientOf, printJson, printLine, printNotice, sessionOf } from '../context.js';
|
|
2
|
+
const MODE_LABELS = {
|
|
3
|
+
self_service: 'autoatendimento (paga pelos assentos usados, depois do ciclo)',
|
|
4
|
+
seats: 'assentos pré-pagos'
|
|
5
|
+
};
|
|
6
|
+
const STANDING_LABELS = {
|
|
7
|
+
active: 'em dia',
|
|
8
|
+
past_due: 'em atraso (a conta vira só leitura se nada for pago)',
|
|
9
|
+
suspended: 'suspensa (só leitura, a IA parada)'
|
|
10
|
+
};
|
|
11
|
+
const INVOICE_LABELS = { issued: 'emitida', overdue: 'vencida', paid: 'paga' };
|
|
12
|
+
const METHOD_LABELS = { card: 'cartão', pix: 'Pix', boleto: 'boleto' };
|
|
13
|
+
export function brl(cents) {
|
|
14
|
+
if (cents === null) {
|
|
15
|
+
return '—';
|
|
16
|
+
}
|
|
17
|
+
return (cents / 100).toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' });
|
|
18
|
+
}
|
|
19
|
+
export function day(value) {
|
|
20
|
+
if (value === null) {
|
|
21
|
+
return '—';
|
|
22
|
+
}
|
|
23
|
+
const [year, month, date] = value.slice(0, 10).split('-');
|
|
24
|
+
return `${date ?? ''}/${month ?? ''}/${year ?? ''}`;
|
|
25
|
+
}
|
|
26
|
+
async function get(context, options, path) {
|
|
27
|
+
const response = await clientOf(context, sessionOf(context, options)).request({ method: 'GET', path });
|
|
28
|
+
return response.body;
|
|
29
|
+
}
|
|
30
|
+
function seatsLine(seats) {
|
|
31
|
+
const contracted = seats.contracted === null
|
|
32
|
+
? ''
|
|
33
|
+
: `, ${String(seats.contracted)} contratados (assento extra: ${seats.extraPolicy === 'charge' ? 'cobra' : 'bloqueia'})`;
|
|
34
|
+
return `Assentos: ${String(seats.paid)} em uso${contracted}; pico no ciclo ${String(seats.peakInCycle)}; ${String(seats.viewers)} só leitura`;
|
|
35
|
+
}
|
|
36
|
+
function standingLines(status) {
|
|
37
|
+
const lines = [`Situação: ${STANDING_LABELS[status.status]}`];
|
|
38
|
+
if (status.graceEndsAt !== null) {
|
|
39
|
+
lines.push(` Prazo até ${day(status.graceEndsAt)}`);
|
|
40
|
+
}
|
|
41
|
+
if (status.openInvoice !== null) {
|
|
42
|
+
lines.push(` Fatura em aberto ${status.openInvoice.invoiceId}: ${brl(status.openInvoice.totalCents)}, vence em ${day(status.openInvoice.dueDate)}`);
|
|
43
|
+
}
|
|
44
|
+
if (status.lastChargeFailure !== null) {
|
|
45
|
+
lines.push(` Cartão recusado em ${day(status.lastChargeFailure.failedAt)} (fatura ${status.lastChargeFailure.invoiceId})`);
|
|
46
|
+
}
|
|
47
|
+
return lines;
|
|
48
|
+
}
|
|
49
|
+
function cardLine(card) {
|
|
50
|
+
if (!card.verified) {
|
|
51
|
+
return 'Cartão: nenhum cadastrado';
|
|
52
|
+
}
|
|
53
|
+
const expiry = card.expiryMonth === null || card.expiryYear === null
|
|
54
|
+
? ''
|
|
55
|
+
: `, vale ${String(card.expiryMonth).padStart(2, '0')}/${String(card.expiryYear)}`;
|
|
56
|
+
return `Cartão: ${card.brand ?? 'cartão'} final ${card.lastFourDigits ?? '—'}${expiry}`;
|
|
57
|
+
}
|
|
58
|
+
export function describeOverview(overview) {
|
|
59
|
+
const lines = [
|
|
60
|
+
`Modo: ${MODE_LABELS[overview.billingMode]}`,
|
|
61
|
+
seatsLine(overview.seats),
|
|
62
|
+
`Assento: ${brl(overview.pricePerSeatInCents)} por ciclo; mensalidade ${brl(overview.monthlyFeeInCents)}`
|
|
63
|
+
];
|
|
64
|
+
if (overview.modules.length > 0) {
|
|
65
|
+
lines.push(`Módulos: ${overview.modules.map((item) => `${item.displayName} (${brl(item.priceInCents)})`).join(', ')}`);
|
|
66
|
+
}
|
|
67
|
+
lines.push(`IA: ${String(overview.ai.usedPercent)}% do ciclo usado; excedente ${overview.ai.overageAllowed ? 'liberado' : 'desligado'}, ${brl(overview.ai.overageInCents)} até agora`, `Gravação de reuniões: ${brl(overview.meetingRecording.totalInCents)} no ciclo`, ...standingLines(overview.status), cardLine(overview.paymentMethod));
|
|
68
|
+
if (overview.next === null) {
|
|
69
|
+
lines.push('Próximo pagamento: sem assinatura ativa');
|
|
70
|
+
return lines;
|
|
71
|
+
}
|
|
72
|
+
lines.push(`Próximo pagamento: ${brl(overview.next.estimatedTotalInCents)} estimados, ciclo fecha em ${day(overview.next.date)}`);
|
|
73
|
+
overview.next.lines.forEach((line) => lines.push(` ${line.label} ${brl(line.totalInCents)}`));
|
|
74
|
+
return lines;
|
|
75
|
+
}
|
|
76
|
+
export async function billingOverview(context, options) {
|
|
77
|
+
const overview = (await get(context, options, '/v1/billing'));
|
|
78
|
+
if (options.json === true) {
|
|
79
|
+
printJson(context, overview);
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
describeOverview(overview).forEach((line) => {
|
|
83
|
+
printLine(context, line);
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
function invoiceRow(invoice) {
|
|
87
|
+
const cycle = invoice.cycleStart === null ? '—' : `${day(invoice.cycleStart)} a ${day(invoice.cycleEnd)}`;
|
|
88
|
+
return `${invoice.invoiceId} ${INVOICE_LABELS[invoice.status].padEnd(7)} ${brl(invoice.totalCents).padStart(14)} vence ${day(invoice.dueDate)} ciclo ${cycle}`;
|
|
89
|
+
}
|
|
90
|
+
async function invoiceList(context, options) {
|
|
91
|
+
const query = new URLSearchParams();
|
|
92
|
+
for (const [key, value] of [
|
|
93
|
+
['page', options.page],
|
|
94
|
+
['pageSize', options.pageSize]
|
|
95
|
+
]) {
|
|
96
|
+
if (value !== undefined) {
|
|
97
|
+
query.set(key, value);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
const page = (await get(context, options, `/v1/billing/invoices${query.size === 0 ? '' : `?${query.toString()}`}`));
|
|
101
|
+
if (options.json === true) {
|
|
102
|
+
printJson(context, page);
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
if (page.data.length === 0) {
|
|
106
|
+
printLine(context, 'Nenhuma fatura.');
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
page.data.forEach((invoice) => {
|
|
110
|
+
printLine(context, invoiceRow(invoice));
|
|
111
|
+
});
|
|
112
|
+
if (page.pagination.page < page.pagination.totalPages) {
|
|
113
|
+
printNotice(context, `Página ${String(page.pagination.page)} de ${String(page.pagination.totalPages)}: veja a próxima com --page.`);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
async function invoiceDetail(context, options, invoiceId) {
|
|
117
|
+
const invoice = (await get(context, options, `/v1/billing/invoices/${encodeURIComponent(invoiceId)}`));
|
|
118
|
+
if (options.json === true) {
|
|
119
|
+
printJson(context, invoice);
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
printLine(context, `Fatura ${invoice.invoiceId}: ${INVOICE_LABELS[invoice.status]}, ${brl(invoice.totalCents)}`);
|
|
123
|
+
printLine(context, `Ciclo ${day(invoice.cycleStart)} a ${day(invoice.cycleEnd)}; vence em ${day(invoice.dueDate)}; emitida em ${day(invoice.issuedAt)}`);
|
|
124
|
+
if (invoice.paidAt !== null) {
|
|
125
|
+
const method = invoice.paymentMethod === null ? '' : ` por ${METHOD_LABELS[invoice.paymentMethod.method]}`;
|
|
126
|
+
printLine(context, `Paga em ${day(invoice.paidAt)}${method}`);
|
|
127
|
+
}
|
|
128
|
+
printLine(context, `Modo: ${MODE_LABELS[invoice.mode]}`);
|
|
129
|
+
let group = null;
|
|
130
|
+
for (const line of invoice.lines) {
|
|
131
|
+
if (line.group !== group) {
|
|
132
|
+
group = line.group;
|
|
133
|
+
printLine(context, group);
|
|
134
|
+
}
|
|
135
|
+
printLine(context, ` ${line.label} ${String(line.quantity)} × ${brl(line.unitInCents)} = ${brl(line.totalInCents)}`);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
export async function billingInvoices(context, invoiceId, options) {
|
|
139
|
+
if (invoiceId === undefined) {
|
|
140
|
+
await invoiceList(context, options);
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
await invoiceDetail(context, options, invoiceId);
|
|
144
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { printJson, printLine, sessionOf } from '../context.js';
|
|
2
|
+
import { usageError } from '../errors.js';
|
|
3
|
+
import { call, documentOf, versionOf } from '../documents/journey-api.js';
|
|
4
|
+
import { confirmed } from '../input/confirm.js';
|
|
5
|
+
const NAMED = /^\s*(.*?)\s*<\s*([^<>\s]+)\s*>\s*$/;
|
|
6
|
+
const EMAIL = /^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+$/;
|
|
7
|
+
function personOf(raw, approver) {
|
|
8
|
+
const named = NAMED.exec(raw);
|
|
9
|
+
const email = (named?.[2] ?? raw).trim().toLowerCase();
|
|
10
|
+
const name = (named?.[1] ?? '').trim();
|
|
11
|
+
if (!EMAIL.test(email)) {
|
|
12
|
+
throw usageError(`"${raw}" não é uma pessoa: use "Nome <email>" ou só o e-mail.`);
|
|
13
|
+
}
|
|
14
|
+
return { name: name === '' ? null : name, email, approver };
|
|
15
|
+
}
|
|
16
|
+
export function peopleOf(options) {
|
|
17
|
+
if (options.approver === undefined) {
|
|
18
|
+
throw usageError('Diga quem aprova com --approver <email>: o de acordo dessa pessoa encerra a negociação.');
|
|
19
|
+
}
|
|
20
|
+
const approver = personOf(options.approver, true);
|
|
21
|
+
const people = new Map();
|
|
22
|
+
(options.person ?? []).forEach((raw) => {
|
|
23
|
+
const person = personOf(raw, false);
|
|
24
|
+
people.set(person.email, person);
|
|
25
|
+
});
|
|
26
|
+
const listed = people.get(approver.email);
|
|
27
|
+
people.set(approver.email, { ...approver, name: approver.name ?? listed?.name ?? null });
|
|
28
|
+
return [...people.values()];
|
|
29
|
+
}
|
|
30
|
+
function preview(document, version, people, message) {
|
|
31
|
+
return [
|
|
32
|
+
`Começar a negociação de ${document.number ?? 'documento'} "${document.title}", versão ${String(version.version)}.`,
|
|
33
|
+
`O Nexo manda um e-mail com o link do documento para ${String(people.length)} pessoa(s):`,
|
|
34
|
+
...people.map((person) => ` - ${person.name === null ? '' : `${person.name} `}<${person.email}>${person.approver ? ' (aprova)' : ''}`),
|
|
35
|
+
...(message === null ? [] : [`Mensagem no e-mail: ${message}`])
|
|
36
|
+
];
|
|
37
|
+
}
|
|
38
|
+
export async function documentsNegotiate(context, documentId, options) {
|
|
39
|
+
const people = peopleOf(options);
|
|
40
|
+
const message = (options.message ?? '').trim() === '' ? null : (options.message ?? '').trim();
|
|
41
|
+
const session = sessionOf(context, options);
|
|
42
|
+
const document = await documentOf(context, session, documentId);
|
|
43
|
+
const version = versionOf(document, options.versionNumber);
|
|
44
|
+
preview(document, version, people, message).forEach((line) => {
|
|
45
|
+
printLine(context, line);
|
|
46
|
+
});
|
|
47
|
+
if (!(await confirmed(context, options.yes, 'Enviar os e-mails?'))) {
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
const negotiation = await call(context, session, 'POST', `/documents/${encodeURIComponent(documentId)}/negotiation`, {
|
|
51
|
+
people,
|
|
52
|
+
message,
|
|
53
|
+
versionId: version.id
|
|
54
|
+
});
|
|
55
|
+
if (options.json === true) {
|
|
56
|
+
printJson(context, negotiation);
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
printLine(context, `Negociação aberta: ${String(people.length)} pessoa(s) receberam o link por e-mail.`);
|
|
60
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { printJson, printLine, printNotice, sessionOf } from '../context.js';
|
|
2
|
+
import { CliError } from '../errors.js';
|
|
3
|
+
import { EXIT_CODES } from '../exit-codes.types.js';
|
|
4
|
+
import { agentOf, call, poll, timeoutOf } from '../documents/journey-api.js';
|
|
5
|
+
import { templateRow } from '../documents/summary.js';
|
|
6
|
+
import { download, localFile, targetOf, upload } from '../documents/transfer.js';
|
|
7
|
+
const READING_LABELS = {
|
|
8
|
+
reading: 'o Nexo está lendo o modelo',
|
|
9
|
+
ready: 'modelo lido',
|
|
10
|
+
failed: 'a leitura não saiu'
|
|
11
|
+
};
|
|
12
|
+
export async function templatesList(context, options) {
|
|
13
|
+
const agent = agentOf(options.agent);
|
|
14
|
+
const choices = (await call(context, sessionOf(context, options), 'GET', `/${agent}/templates`));
|
|
15
|
+
if (options.json === true) {
|
|
16
|
+
printJson(context, choices);
|
|
17
|
+
return;
|
|
18
|
+
}
|
|
19
|
+
if (choices.templates.length === 0) {
|
|
20
|
+
printLine(context, 'Nenhum modelo.');
|
|
21
|
+
printNotice(context, `Sem modelo não há documento: envie um com \`nexo documents templates add <arquivo> --agent ${agent}\`.`);
|
|
22
|
+
return;
|
|
23
|
+
}
|
|
24
|
+
choices.templates.forEach((template) => {
|
|
25
|
+
printLine(context, templateRow(template));
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
async function readTemplate(context, session, agent, template, options) {
|
|
29
|
+
if (options.wait === false || template.state !== 'reading') {
|
|
30
|
+
return template;
|
|
31
|
+
}
|
|
32
|
+
return poll(context, {
|
|
33
|
+
read: async () => (await call(context, session, 'GET', `/${agent}/templates/${template.id}`)),
|
|
34
|
+
stateOf: (each) => each.state,
|
|
35
|
+
describe: (each) => `${each.name}: ${READING_LABELS[each.state]}.`,
|
|
36
|
+
settled: (each) => each.state !== 'reading',
|
|
37
|
+
timeoutMs: timeoutOf(options.timeout),
|
|
38
|
+
late: new CliError('O Nexo ainda está lendo o modelo.', EXIT_CODES.failure, `Ele aparece em \`nexo documents templates --agent ${agent}\`; o questionário abre quando a leitura terminar.`)
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
export async function templatesAdd(context, path, options) {
|
|
42
|
+
const agent = agentOf(options.agent);
|
|
43
|
+
const file = localFile(path);
|
|
44
|
+
const session = sessionOf(context, options);
|
|
45
|
+
const ticket = (await call(context, session, 'POST', `/${agent}/templates/uploads`, {
|
|
46
|
+
fileName: file.fileName,
|
|
47
|
+
sizeInBytes: file.bytes.length
|
|
48
|
+
}));
|
|
49
|
+
await upload(context, ticket, file);
|
|
50
|
+
const confirmed = (await call(context, session, 'POST', `/${agent}/templates/uploads/${ticket.uploadId}/confirm`, {
|
|
51
|
+
fileName: file.fileName
|
|
52
|
+
}));
|
|
53
|
+
const template = await readTemplate(context, session, agent, confirmed, options);
|
|
54
|
+
if (options.json === true) {
|
|
55
|
+
printJson(context, template);
|
|
56
|
+
}
|
|
57
|
+
if (template.state === 'failed') {
|
|
58
|
+
throw new CliError(`O Nexo não conseguiu ler o modelo: ${template.failure ?? 'motivo não informado'}.`, EXIT_CODES.failure);
|
|
59
|
+
}
|
|
60
|
+
if (options.json === true) {
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
printLine(context, `${template.id} ${template.name} ${READING_LABELS[template.state]}`);
|
|
64
|
+
printNotice(context, template.shared ? 'O modelo já vale para a empresa.' : 'O modelo vale só para você até um admin ou líder liberar para a empresa.');
|
|
65
|
+
}
|
|
66
|
+
export async function templatesDownload(context, templateId, options) {
|
|
67
|
+
const agent = agentOf(options.agent);
|
|
68
|
+
const link = (await call(context, sessionOf(context, options), 'GET', `/${agent}/templates/${encodeURIComponent(templateId)}/source`));
|
|
69
|
+
const target = targetOf(options.output, link.fileName, `modelo-${templateId}`);
|
|
70
|
+
await download(context, link.url, target);
|
|
71
|
+
if (options.json === true) {
|
|
72
|
+
printJson(context, { templateId, path: target });
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
printLine(context, target);
|
|
76
|
+
}
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
import { printJson, printLine, printNotice, sessionOf } from '../context.js';
|
|
2
|
+
import { CliError, usageError } from '../errors.js';
|
|
3
|
+
import { EXIT_CODES } from '../exit-codes.types.js';
|
|
4
|
+
import { answersFileOf, changedAnswers, readAnswersFile, readJsonFile, writeAnswersFile } from '../documents/answers-file.js';
|
|
5
|
+
import { agentOf, call, documentOf, failureOf, statusLabel, timeoutOf, versionOf, waitForVersion } from '../documents/journey-api.js';
|
|
6
|
+
import { describeDocument, describeQuestionnaire, documentRow } from '../documents/summary.js';
|
|
7
|
+
import { download, readText, targetOf } from '../documents/transfer.js';
|
|
8
|
+
function needsTemplate(templateId) {
|
|
9
|
+
if (templateId === null) {
|
|
10
|
+
throw usageError('Diga o modelo com --template <id>.', 'Veja os modelos com `nexo documents templates --agent proposal|contract`.');
|
|
11
|
+
}
|
|
12
|
+
return templateId;
|
|
13
|
+
}
|
|
14
|
+
function firstOf(...values) {
|
|
15
|
+
return values.find((value) => value !== null && value !== undefined) ?? null;
|
|
16
|
+
}
|
|
17
|
+
function newStart(options, file) {
|
|
18
|
+
return {
|
|
19
|
+
agent: agentOf(firstOf(options.agent, file?.agent)),
|
|
20
|
+
dealId: firstOf(options.deal, file?.dealId),
|
|
21
|
+
templateId: needsTemplate(firstOf(options.template, file?.templateId)),
|
|
22
|
+
proposalDocumentId: firstOf(options.proposal, file?.proposalDocumentId),
|
|
23
|
+
documentId: null
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
async function revisionStart(context, session, documentId, options) {
|
|
27
|
+
const document = await documentOf(context, session, documentId);
|
|
28
|
+
return {
|
|
29
|
+
agent: document.agent,
|
|
30
|
+
dealId: document.dealId,
|
|
31
|
+
templateId: options.template ?? null,
|
|
32
|
+
proposalDocumentId: null,
|
|
33
|
+
documentId: document.id
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
async function questionnaireOf(context, session, start, dealReading) {
|
|
37
|
+
const { agent, ...body } = start;
|
|
38
|
+
return (await call(context, session, 'POST', `/${agent}/questionnaire`, { ...body, dealReading }));
|
|
39
|
+
}
|
|
40
|
+
async function answeredOf(context, session, start, file) {
|
|
41
|
+
if (file === null) {
|
|
42
|
+
return { answers: [], groups: [] };
|
|
43
|
+
}
|
|
44
|
+
const baseline = await questionnaireOf(context, session, start, false);
|
|
45
|
+
return {
|
|
46
|
+
answers: changedAnswers(file, baseline.questionnaire),
|
|
47
|
+
groups: file.groups,
|
|
48
|
+
...(file.notes === null || file.notes.trim() === '' ? {} : { notes: file.notes })
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
function writtenOf(options) {
|
|
52
|
+
if (options.document === undefined) {
|
|
53
|
+
if (options.adaptations !== undefined) {
|
|
54
|
+
throw usageError('--adaptations só vale com --document, o documento já escrito.');
|
|
55
|
+
}
|
|
56
|
+
return {};
|
|
57
|
+
}
|
|
58
|
+
const html = readText(options.document);
|
|
59
|
+
if (html.trim() === '') {
|
|
60
|
+
throw usageError(`${options.document} está vazio.`);
|
|
61
|
+
}
|
|
62
|
+
return { html, ...(options.adaptations === undefined ? {} : { adaptations: readJsonFile(options.adaptations) }) };
|
|
63
|
+
}
|
|
64
|
+
function fileOf(options) {
|
|
65
|
+
return options.answers === undefined ? null : readAnswersFile(options.answers);
|
|
66
|
+
}
|
|
67
|
+
export async function documentsList(context, options) {
|
|
68
|
+
const query = new URLSearchParams();
|
|
69
|
+
if (options.agent !== undefined) {
|
|
70
|
+
query.set('agent', agentOf(options.agent));
|
|
71
|
+
}
|
|
72
|
+
if (options.deal !== undefined) {
|
|
73
|
+
query.set('dealId', options.deal);
|
|
74
|
+
}
|
|
75
|
+
const body = (await call(context, sessionOf(context, options), 'GET', `/documents${query.size === 0 ? '' : `?${query.toString()}`}`));
|
|
76
|
+
if (options.json === true) {
|
|
77
|
+
printJson(context, body);
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
if (body.items.length === 0) {
|
|
81
|
+
printLine(context, 'Nenhum documento.');
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
body.items.forEach((document) => {
|
|
85
|
+
printLine(context, documentRow(document));
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
export async function documentsGet(context, documentId, options) {
|
|
89
|
+
const document = await documentOf(context, sessionOf(context, options), documentId);
|
|
90
|
+
if (options.json === true) {
|
|
91
|
+
printJson(context, document);
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
describeDocument(document).forEach((line) => {
|
|
95
|
+
printLine(context, line);
|
|
96
|
+
});
|
|
97
|
+
if (document.current?.status === 'failed') {
|
|
98
|
+
failureOf(document.current).forEach((line) => {
|
|
99
|
+
printLine(context, line);
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
export async function documentsQuestionnaire(context, options) {
|
|
104
|
+
const session = sessionOf(context, options);
|
|
105
|
+
const start = options.revising === undefined ? newStart(options, null) : await revisionStart(context, session, options.revising, options);
|
|
106
|
+
const response = await questionnaireOf(context, session, start, options.reading !== false);
|
|
107
|
+
if (options.output !== undefined) {
|
|
108
|
+
writeAnswersFile(options.output, answersFileOf(response.questionnaire));
|
|
109
|
+
}
|
|
110
|
+
if (options.json === true) {
|
|
111
|
+
printJson(context, response);
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
describeQuestionnaire(response).forEach((line) => {
|
|
115
|
+
printLine(context, line);
|
|
116
|
+
});
|
|
117
|
+
if (options.output !== undefined) {
|
|
118
|
+
printNotice(context, `Respostas em ${options.output}: edite o "text" de cada resposta e mande com --answers ${options.output}.`);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
function reportReceipt(context, receipt, version, options) {
|
|
122
|
+
if (options.json === true) {
|
|
123
|
+
printJson(context, {
|
|
124
|
+
...receipt,
|
|
125
|
+
...(version === null
|
|
126
|
+
? {}
|
|
127
|
+
: {
|
|
128
|
+
status: version.status,
|
|
129
|
+
failureReason: version.failureReason,
|
|
130
|
+
findings: [...version.valueFindings, ...version.checkFindings],
|
|
131
|
+
changeSummary: version.changeSummary
|
|
132
|
+
})
|
|
133
|
+
});
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
const status = statusLabel(version?.status ?? receipt.status);
|
|
137
|
+
printLine(context, `${receipt.documentId} ${receipt.number ?? '—'} versão ${String(receipt.version)} ${status} ${receipt.title}`);
|
|
138
|
+
if (version?.changeSummary !== null && version?.changeSummary !== undefined) {
|
|
139
|
+
printLine(context, `O que mudou: ${version.changeSummary}`);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
function failed(context, version) {
|
|
143
|
+
const [headline, ...findings] = failureOf(version);
|
|
144
|
+
findings.forEach((line) => {
|
|
145
|
+
printNotice(context, line);
|
|
146
|
+
});
|
|
147
|
+
return new CliError(headline ?? 'A versão não saiu.', EXIT_CODES.failure, 'Corrija a resposta e peça uma versão nova com `nexo documents revise`.');
|
|
148
|
+
}
|
|
149
|
+
async function followReceipt(context, session, receipt, options) {
|
|
150
|
+
if (receipt.status === 'ready') {
|
|
151
|
+
reportReceipt(context, receipt, null, options);
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
if (options.wait === false) {
|
|
155
|
+
reportReceipt(context, receipt, null, options);
|
|
156
|
+
printNotice(context, `Acompanhe com \`nexo documents get ${receipt.documentId}\`.`);
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
const version = await waitForVersion(context, session, receipt, timeoutOf(options.timeout));
|
|
160
|
+
reportReceipt(context, receipt, version, options);
|
|
161
|
+
if (version.status === 'failed') {
|
|
162
|
+
throw failed(context, version);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
export async function documentsCreate(context, options) {
|
|
166
|
+
const session = sessionOf(context, options);
|
|
167
|
+
const file = fileOf(options);
|
|
168
|
+
const written = writtenOf(options);
|
|
169
|
+
const start = newStart(options, file);
|
|
170
|
+
const { agent, documentId: _none, ...body } = start;
|
|
171
|
+
const receipt = (await call(context, session, 'POST', `/${agent}/documents${written.html === undefined ? '' : '/written'}`, {
|
|
172
|
+
...body,
|
|
173
|
+
...(await answeredOf(context, session, start, file)),
|
|
174
|
+
...written
|
|
175
|
+
}));
|
|
176
|
+
await followReceipt(context, session, receipt, options);
|
|
177
|
+
}
|
|
178
|
+
export async function documentsRevise(context, documentId, options) {
|
|
179
|
+
const request = (options.request ?? '').trim();
|
|
180
|
+
const file = fileOf(options);
|
|
181
|
+
const written = writtenOf(options);
|
|
182
|
+
if (request === '' && file === null && written.html === undefined) {
|
|
183
|
+
throw usageError('Diga o que muda: --request "o pedido", --answers com as respostas que mudaram, ou --document com a versão já escrita.');
|
|
184
|
+
}
|
|
185
|
+
const session = sessionOf(context, options);
|
|
186
|
+
const answered = file === null
|
|
187
|
+
? { answers: [], groups: [] }
|
|
188
|
+
: await answeredOf(context, session, await revisionStart(context, session, documentId, options), file);
|
|
189
|
+
const receipt = (await call(context, session, 'POST', `/documents/${encodeURIComponent(documentId)}/versions${written.html === undefined ? '' : '/written'}`, { templateId: options.template ?? null, request: request === '' ? null : request, ...answered, ...written }));
|
|
190
|
+
await followReceipt(context, session, receipt, options);
|
|
191
|
+
}
|
|
192
|
+
export async function documentsAccept(context, documentId, options) {
|
|
193
|
+
const session = sessionOf(context, options);
|
|
194
|
+
const version = versionOf(await documentOf(context, session, documentId), options.versionNumber);
|
|
195
|
+
const accepted = await call(context, session, 'POST', `/documents/${encodeURIComponent(documentId)}/versions/${version.id}/acceptance`);
|
|
196
|
+
if (options.json === true) {
|
|
197
|
+
printJson(context, accepted);
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
printLine(context, `Versão ${String(version.version)} aceita: a proposta deixou de ser rascunho.`);
|
|
201
|
+
printNotice(context, `Baixe com \`nexo documents pdf ${documentId}\` ou comece a negociação com \`nexo documents negotiate ${documentId}\`.`);
|
|
202
|
+
}
|
|
203
|
+
export async function documentsFile(context, kind, documentId, options) {
|
|
204
|
+
const session = sessionOf(context, options);
|
|
205
|
+
const document = await documentOf(context, session, documentId);
|
|
206
|
+
const version = versionOf(document, options.versionNumber);
|
|
207
|
+
const link = (await call(context, session, 'POST', `/documents/${encodeURIComponent(documentId)}/versions/${version.id}/${kind}`));
|
|
208
|
+
const target = targetOf(options.output, link.fileName, `${document.number ?? document.id}-v${String(version.version)}.${kind}`);
|
|
209
|
+
await download(context, link.url, target);
|
|
210
|
+
if (options.json === true) {
|
|
211
|
+
printJson(context, { documentId, versionId: version.id, version: version.version, path: target });
|
|
212
|
+
return;
|
|
213
|
+
}
|
|
214
|
+
printLine(context, target);
|
|
215
|
+
}
|
package/dist/commands/logout.js
CHANGED
|
@@ -21,10 +21,10 @@ function notices(context, stored, revocation) {
|
|
|
21
21
|
printNotice(context, 'O acesso da CLI foi revogado no Nexo.');
|
|
22
22
|
}
|
|
23
23
|
if (revocation === 'failed') {
|
|
24
|
-
printNotice(context, 'Não consegui revogar no Nexo; desconecte a "Nexo CLI" em Configurações ›
|
|
24
|
+
printNotice(context, 'Não consegui revogar no Nexo; desconecte a "Nexo CLI" em Configurações › Conexões › IA e API.');
|
|
25
25
|
}
|
|
26
26
|
if (stored?.kind === 'pat') {
|
|
27
|
-
printNotice(context, 'O token continua valendo até você revogá-lo no Nexo, em Configurações ›
|
|
27
|
+
printNotice(context, 'O token continua valendo até você revogá-lo no Nexo, em Configurações › Conexões › IA e API.');
|
|
28
28
|
}
|
|
29
29
|
if ((context.env.NEXO_TOKEN ?? '') !== '') {
|
|
30
30
|
printNotice(context, 'NEXO_TOKEN ainda está definido no ambiente e continua sendo usado.');
|
package/dist/commands/whoami.js
CHANGED
|
@@ -1,9 +1,8 @@
|
|
|
1
1
|
import { clientOf, printJson, printLine, sessionOf } from '../context.js';
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
};
|
|
2
|
+
function profilesOf(me) {
|
|
3
|
+
const names = me.user.profiles.map((profile) => profile.name);
|
|
4
|
+
return names.length === 0 ? 'sem perfil' : `${names.length === 1 ? 'perfil' : 'perfis'}: ${names.join(', ')}`;
|
|
5
|
+
}
|
|
7
6
|
function isMe(value) {
|
|
8
7
|
if (typeof value !== 'object' || value === null) {
|
|
9
8
|
return false;
|
|
@@ -22,7 +21,7 @@ export function describeMe(me, session) {
|
|
|
22
21
|
const expires = new Date(me.credential.expiresAt).toLocaleDateString('pt-BR', { timeZone: me.company.timezone });
|
|
23
22
|
const source = session.source === 'env' ? 'NEXO_TOKEN' : `perfil ${session.profile}`;
|
|
24
23
|
return [
|
|
25
|
-
`${me.user.name} <${me.user.email}>, ${
|
|
24
|
+
`${me.user.name} <${me.user.email}>, ${profilesOf(me)}`,
|
|
26
25
|
`Empresa: ${me.company.name}`,
|
|
27
26
|
`Credencial: ${me.credential.name} (${source}), vale até ${expires}`,
|
|
28
27
|
`Escopos: ${me.credential.scopes.join(', ')}`,
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { readFileSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { usageError } from '../errors.js';
|
|
3
|
+
export function fieldsOf(questionnaire) {
|
|
4
|
+
const grouped = questionnaire.groups.flatMap((group) => group.items.flatMap((item) => item.fields));
|
|
5
|
+
return [...questionnaire.fields, ...grouped];
|
|
6
|
+
}
|
|
7
|
+
function fileAnswerOf(field) {
|
|
8
|
+
const options = field.question?.options.length ? field.question.options : field.options;
|
|
9
|
+
return {
|
|
10
|
+
path: field.path,
|
|
11
|
+
label: field.label,
|
|
12
|
+
type: field.type,
|
|
13
|
+
required: field.required,
|
|
14
|
+
text: field.text,
|
|
15
|
+
source: field.source?.label ?? null,
|
|
16
|
+
...(field.question === null ? {} : { question: field.question.text }),
|
|
17
|
+
...(options.length === 0 ? {} : { options })
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
export function answersFileOf(questionnaire) {
|
|
21
|
+
return {
|
|
22
|
+
agent: questionnaire.agent,
|
|
23
|
+
dealId: questionnaire.dealId,
|
|
24
|
+
templateId: questionnaire.templateId,
|
|
25
|
+
proposalDocumentId: questionnaire.proposal?.documentId ?? null,
|
|
26
|
+
documentId: questionnaire.documentId,
|
|
27
|
+
notes: questionnaire.notes,
|
|
28
|
+
groups: [],
|
|
29
|
+
answers: fieldsOf(questionnaire).map(fileAnswerOf)
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
export function writeAnswersFile(path, file) {
|
|
33
|
+
writeFileSync(path, `${JSON.stringify(file, null, 2)}\n`);
|
|
34
|
+
}
|
|
35
|
+
function textOrNull(value) {
|
|
36
|
+
return typeof value === 'string' ? value : null;
|
|
37
|
+
}
|
|
38
|
+
function isAnswer(value) {
|
|
39
|
+
if (typeof value !== 'object' || value === null) {
|
|
40
|
+
return false;
|
|
41
|
+
}
|
|
42
|
+
const fields = value;
|
|
43
|
+
return typeof fields.path === 'string' && (fields.text === null || typeof fields.text === 'string');
|
|
44
|
+
}
|
|
45
|
+
function isGroupChange(value) {
|
|
46
|
+
if (typeof value !== 'object' || value === null) {
|
|
47
|
+
return false;
|
|
48
|
+
}
|
|
49
|
+
const fields = value;
|
|
50
|
+
return typeof fields.group === 'string' && (fields.action === 'add' || fields.action === 'remove');
|
|
51
|
+
}
|
|
52
|
+
function listOf(path, key, value, valid, shape) {
|
|
53
|
+
if (value === undefined) {
|
|
54
|
+
return [];
|
|
55
|
+
}
|
|
56
|
+
if (!Array.isArray(value) || !value.every(valid)) {
|
|
57
|
+
throw usageError(`${path}: "${key}" precisa ser uma lista de ${shape}.`);
|
|
58
|
+
}
|
|
59
|
+
return value;
|
|
60
|
+
}
|
|
61
|
+
export function readJsonFile(path) {
|
|
62
|
+
try {
|
|
63
|
+
return JSON.parse(readFileSync(path, 'utf8'));
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
throw usageError(`${path} não existe ou não é JSON válido.`);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
export function readAnswersFile(path) {
|
|
70
|
+
const raw = readJsonFile(path);
|
|
71
|
+
if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {
|
|
72
|
+
throw usageError(`${path} não tem o formato do arquivo de respostas.`, 'Gere um com `nexo documents questionnaire … -o respostas.json`.');
|
|
73
|
+
}
|
|
74
|
+
const fields = raw;
|
|
75
|
+
return {
|
|
76
|
+
agent: fields.agent === 'proposal' || fields.agent === 'contract' ? fields.agent : null,
|
|
77
|
+
dealId: textOrNull(fields.dealId),
|
|
78
|
+
templateId: textOrNull(fields.templateId),
|
|
79
|
+
proposalDocumentId: textOrNull(fields.proposalDocumentId),
|
|
80
|
+
documentId: textOrNull(fields.documentId),
|
|
81
|
+
notes: textOrNull(fields.notes),
|
|
82
|
+
groups: listOf(path, 'groups', fields.groups, isGroupChange, '{ "group", "action": "add" ou "remove" }'),
|
|
83
|
+
answers: listOf(path, 'answers', fields.answers, isAnswer, '{ "path", "text" }')
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
export function changedAnswers(file, baseline) {
|
|
87
|
+
const known = new Map(fieldsOf(baseline).map((field) => [field.path, (field.text ?? '').trim()]));
|
|
88
|
+
return file.answers
|
|
89
|
+
.map((answer) => ({ path: answer.path, text: (answer.text ?? '').trim() }))
|
|
90
|
+
.filter((answer) => answer.text !== (known.get(answer.path) ?? ''));
|
|
91
|
+
}
|