@winning-sales/nexo 0.3.0 → 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 +38 -2
- package/assets/docs/pages.json +1 -1
- package/dist/commands/artifacts.js +118 -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-documents.js +150 -0
- package/dist/program.js +6 -1
- package/package.json +2 -2
- package/reference.json +617 -2
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { clientOf, printNotice } from '../context.js';
|
|
2
|
+
import { CliError, usageError } from '../errors.js';
|
|
3
|
+
import { EXIT_CODES } from '../exit-codes.types.js';
|
|
4
|
+
const BASE = '/v1/agents';
|
|
5
|
+
const POLL_MS = 4000;
|
|
6
|
+
export const DEFAULT_TIMEOUT_SECONDS = '900';
|
|
7
|
+
const STATUS_LABELS = {
|
|
8
|
+
draft: 'rascunho',
|
|
9
|
+
queued: 'na fila',
|
|
10
|
+
running: 'o Nexo está escrevendo',
|
|
11
|
+
ready: 'pronta',
|
|
12
|
+
failed: 'não saiu'
|
|
13
|
+
};
|
|
14
|
+
const FAILURE_LABELS = {
|
|
15
|
+
ai_unavailable: 'a IA não respondeu; peça de novo',
|
|
16
|
+
ai_rejected: 'a IA recusou o pedido ou a resposta foi cortada',
|
|
17
|
+
budget: 'o limite de IA do ciclo da empresa acabou e nada foi escrito',
|
|
18
|
+
values_mismatch: 'a conferência achou valor, data ou prazo que não bate com as respostas',
|
|
19
|
+
check_failed: 'o documento não passou na conferência',
|
|
20
|
+
too_long: 'o contrato passa do tamanho que o Nexo escreve de uma vez'
|
|
21
|
+
};
|
|
22
|
+
export async function call(context, session, method, path, body) {
|
|
23
|
+
const response = await clientOf(context, session).request({
|
|
24
|
+
method,
|
|
25
|
+
path: `${BASE}${path}`,
|
|
26
|
+
...(body === undefined ? {} : { body })
|
|
27
|
+
});
|
|
28
|
+
return response.body;
|
|
29
|
+
}
|
|
30
|
+
export function agentOf(value) {
|
|
31
|
+
if (value !== 'proposal' && value !== 'contract') {
|
|
32
|
+
throw usageError('Diga o agente com --agent proposal ou --agent contract.');
|
|
33
|
+
}
|
|
34
|
+
return value;
|
|
35
|
+
}
|
|
36
|
+
export async function documentOf(context, session, documentId) {
|
|
37
|
+
return (await call(context, session, 'GET', `/documents/${encodeURIComponent(documentId)}`));
|
|
38
|
+
}
|
|
39
|
+
export function versionOf(document, raw) {
|
|
40
|
+
if (raw !== undefined && !/^\d+$/.test(raw)) {
|
|
41
|
+
throw usageError('A versão é o número, como em `nexo documents get`.');
|
|
42
|
+
}
|
|
43
|
+
const version = raw === undefined ? document.current : document.versions.find((each) => each.version === Number(raw));
|
|
44
|
+
if (version === null || version === undefined) {
|
|
45
|
+
throw new CliError(raw === undefined ? 'Este documento ainda não tem versão.' : `Este documento não tem a versão ${raw}.`, EXIT_CODES.notFound);
|
|
46
|
+
}
|
|
47
|
+
return version;
|
|
48
|
+
}
|
|
49
|
+
export function statusLabel(status) {
|
|
50
|
+
return STATUS_LABELS[status];
|
|
51
|
+
}
|
|
52
|
+
export function failureOf(version) {
|
|
53
|
+
const reason = FAILURE_LABELS[version.failureReason ?? ''] ?? 'erro inesperado; peça de novo';
|
|
54
|
+
return [
|
|
55
|
+
`A versão ${String(version.version)} não saiu: ${reason}.`,
|
|
56
|
+
...[...version.valueFindings, ...version.checkFindings].map(bullet)
|
|
57
|
+
];
|
|
58
|
+
}
|
|
59
|
+
function bullet(text) {
|
|
60
|
+
return ` - ${text}`;
|
|
61
|
+
}
|
|
62
|
+
export function timeoutOf(raw) {
|
|
63
|
+
const text = raw ?? DEFAULT_TIMEOUT_SECONDS;
|
|
64
|
+
if (!/^\d+$/.test(text)) {
|
|
65
|
+
throw usageError('--timeout é em segundos, um número inteiro.');
|
|
66
|
+
}
|
|
67
|
+
return Number(text) * 1000;
|
|
68
|
+
}
|
|
69
|
+
export async function pause(context, ms) {
|
|
70
|
+
if (context.sleep !== undefined) {
|
|
71
|
+
await context.sleep(ms);
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
await new Promise((resolve) => {
|
|
75
|
+
setTimeout(resolve, ms);
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
async function versionNow(context, session, documentId, versionId) {
|
|
79
|
+
const document = await documentOf(context, session, documentId);
|
|
80
|
+
const version = document.versions.find((each) => each.id === versionId);
|
|
81
|
+
if (version === undefined) {
|
|
82
|
+
throw new CliError('A versão pedida não está mais no documento.', EXIT_CODES.notFound);
|
|
83
|
+
}
|
|
84
|
+
return version;
|
|
85
|
+
}
|
|
86
|
+
export async function poll(context, polling) {
|
|
87
|
+
let seen = '';
|
|
88
|
+
for (let waited = 0; waited <= polling.timeoutMs; waited += POLL_MS) {
|
|
89
|
+
const value = await polling.read();
|
|
90
|
+
if (polling.stateOf(value) !== seen) {
|
|
91
|
+
seen = polling.stateOf(value);
|
|
92
|
+
printNotice(context, polling.describe(value));
|
|
93
|
+
}
|
|
94
|
+
if (polling.settled(value)) {
|
|
95
|
+
return value;
|
|
96
|
+
}
|
|
97
|
+
await pause(context, POLL_MS);
|
|
98
|
+
}
|
|
99
|
+
throw polling.late;
|
|
100
|
+
}
|
|
101
|
+
export async function waitForVersion(context, session, ids, timeoutMs) {
|
|
102
|
+
return poll(context, {
|
|
103
|
+
read: () => versionNow(context, session, ids.documentId, ids.versionId),
|
|
104
|
+
stateOf: (version) => version.status,
|
|
105
|
+
describe: (version) => `Versão ${String(version.version)}: ${statusLabel(version.status)}.`,
|
|
106
|
+
settled: (version) => version.status === 'ready' || version.status === 'failed',
|
|
107
|
+
timeoutMs,
|
|
108
|
+
late: new CliError('A versão ainda não ficou pronta.', EXIT_CODES.failure, `Ela continua sendo escrita. Acompanhe com \`nexo documents get ${ids.documentId}\`.`)
|
|
109
|
+
});
|
|
110
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const DOCUMENT_AGENTS = ['proposal', 'contract'];
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
const AGENT_LABELS = { proposal: 'proposta', contract: 'contrato' };
|
|
2
|
+
const STATUS_LABELS = {
|
|
3
|
+
draft: 'rascunho',
|
|
4
|
+
queued: 'na fila',
|
|
5
|
+
running: 'escrevendo',
|
|
6
|
+
ready: 'pronta',
|
|
7
|
+
failed: 'não saiu'
|
|
8
|
+
};
|
|
9
|
+
function valueOf(field) {
|
|
10
|
+
if (field.status === 'invalid') {
|
|
11
|
+
return `"${field.refused ?? ''}" não entrou: ${field.error ?? 'formato inválido'}`;
|
|
12
|
+
}
|
|
13
|
+
if (field.status === 'missing') {
|
|
14
|
+
return 'falta responder';
|
|
15
|
+
}
|
|
16
|
+
return field.text ?? '—';
|
|
17
|
+
}
|
|
18
|
+
function fieldLines(field, indent) {
|
|
19
|
+
const source = field.source === null || field.status !== 'filled' ? '' : ` (${field.source.label})`;
|
|
20
|
+
const line = `${indent}${field.label} [${field.path}]: ${valueOf(field)}${source}`;
|
|
21
|
+
if (field.question === null) {
|
|
22
|
+
return [line];
|
|
23
|
+
}
|
|
24
|
+
const options = field.question.options.length === 0 ? '' : ` Opções: ${field.question.options.join(' | ')}`;
|
|
25
|
+
return [line, `${indent} Pergunta: ${field.question.text} (${field.question.reason})${options}`];
|
|
26
|
+
}
|
|
27
|
+
function groupLines(group) {
|
|
28
|
+
const limit = group.max === null ? `mínimo ${String(group.min)}` : `de ${String(group.min)} a ${String(group.max)}`;
|
|
29
|
+
const items = group.items.flatMap((item, index) => [
|
|
30
|
+
` ${group.itemLabel} ${String(index + 1)}`,
|
|
31
|
+
...item.fields.flatMap((field) => fieldLines(field, ' '))
|
|
32
|
+
]);
|
|
33
|
+
return [` ${group.label} [${group.key}]: ${String(group.items.length)} (${limit})`, ...items];
|
|
34
|
+
}
|
|
35
|
+
function linesByBox(response) {
|
|
36
|
+
const boxes = new Map();
|
|
37
|
+
const add = (box, lines) => {
|
|
38
|
+
boxes.set(box, [...(boxes.get(box) ?? []), ...lines]);
|
|
39
|
+
};
|
|
40
|
+
response.questionnaire.fields.forEach((field) => {
|
|
41
|
+
add(field.box, fieldLines(field, ' '));
|
|
42
|
+
});
|
|
43
|
+
response.questionnaire.groups.forEach((group) => {
|
|
44
|
+
add(group.box, groupLines(group));
|
|
45
|
+
});
|
|
46
|
+
return boxes;
|
|
47
|
+
}
|
|
48
|
+
function closingLines(response) {
|
|
49
|
+
const refused = response.refused.map((each) => ` - ${each.label}: ${each.reason}`);
|
|
50
|
+
const pending = response.pending.map((each) => ` - ${each.sentence}`);
|
|
51
|
+
return [
|
|
52
|
+
...(refused.length === 0 ? [] : ['Não entrou:', ...refused]),
|
|
53
|
+
...(pending.length === 0 ? ['Nada falta: o questionário fecha.'] : ['Falta:', ...pending])
|
|
54
|
+
];
|
|
55
|
+
}
|
|
56
|
+
export function describeQuestionnaire(response) {
|
|
57
|
+
const { questionnaire } = response;
|
|
58
|
+
const byBox = linesByBox(response);
|
|
59
|
+
const titled = new Set(questionnaire.boxes.map((box) => box.id));
|
|
60
|
+
const loose = [...byBox.entries()].flatMap(([box, lines]) => titled.has(box) ? [] : lines);
|
|
61
|
+
return [
|
|
62
|
+
`Questionário do ${AGENT_LABELS[questionnaire.agent] ?? questionnaire.agent} com o modelo "${questionnaire.templateName}"`,
|
|
63
|
+
...(response.readingFailure === null ? [] : [`As conversas do negócio não foram lidas: ${response.readingFailure}`]),
|
|
64
|
+
...questionnaire.boxes.flatMap((box) => [
|
|
65
|
+
`${box.title} — ${box.description}`,
|
|
66
|
+
...(byBox.get(box.id) ?? [])
|
|
67
|
+
]),
|
|
68
|
+
...(loose.length === 0 ? [] : ['Outros campos', ...loose]),
|
|
69
|
+
...(questionnaire.notes === null ? [] : [`Observações: ${questionnaire.notes}`]),
|
|
70
|
+
...closingLines(response)
|
|
71
|
+
];
|
|
72
|
+
}
|
|
73
|
+
export function templateRow(template) {
|
|
74
|
+
const support = template.contractType ?? (template.sectionCount === null ? '' : `${String(template.sectionCount)} seções`);
|
|
75
|
+
const marks = [
|
|
76
|
+
template.isDefault ? 'padrão' : '',
|
|
77
|
+
template.ownUpload ? 'só seu' : '',
|
|
78
|
+
support,
|
|
79
|
+
`usado ${String(template.timesUsed)} vez(es)`
|
|
80
|
+
]
|
|
81
|
+
.filter((mark) => mark !== '')
|
|
82
|
+
.join(', ');
|
|
83
|
+
return `${template.id} ${template.format.toUpperCase().padEnd(5)} ${template.name} (${marks})`;
|
|
84
|
+
}
|
|
85
|
+
function standing(document) {
|
|
86
|
+
if (document.acceptance === null) {
|
|
87
|
+
return '';
|
|
88
|
+
}
|
|
89
|
+
return document.acceptance.state === 'accepted' ? ` v${String(document.acceptance.version ?? '')} aceita` : ' rascunho';
|
|
90
|
+
}
|
|
91
|
+
export function documentRow(document) {
|
|
92
|
+
const current = document.current === null ? 'sem versão' : `v${String(document.current.version)} ${STATUS_LABELS[document.current.status] ?? ''}`;
|
|
93
|
+
return `${document.id} ${(AGENT_LABELS[document.agent] ?? document.agent).padEnd(8)} ${(document.number ?? '—').padEnd(14)} ${current}${standing(document)} ${document.title}`;
|
|
94
|
+
}
|
|
95
|
+
function versionRow(version) {
|
|
96
|
+
const note = version.changeSummary ?? version.changeRequest ?? '';
|
|
97
|
+
const failure = version.failureReason === null ? '' : ` (${version.failureReason})`;
|
|
98
|
+
return ` v${String(version.version)} ${(STATUS_LABELS[version.status] ?? version.status).padEnd(10)}${failure} ${version.createdAt} ${note}`.trimEnd();
|
|
99
|
+
}
|
|
100
|
+
export function describeDocument(document) {
|
|
101
|
+
return [documentRow(document), ...document.versions.map(versionRow)];
|
|
102
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { readFileSync, statSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { basename, resolve } from 'node:path';
|
|
3
|
+
import { CliError, usageError } from '../errors.js';
|
|
4
|
+
import { EXIT_CODES } from '../exit-codes.types.js';
|
|
5
|
+
export function localFile(path) {
|
|
6
|
+
try {
|
|
7
|
+
if (!statSync(path).isFile()) {
|
|
8
|
+
throw new Error('not a file');
|
|
9
|
+
}
|
|
10
|
+
return { fileName: basename(path), bytes: readFileSync(path) };
|
|
11
|
+
}
|
|
12
|
+
catch {
|
|
13
|
+
throw usageError(`Não consegui ler o arquivo ${path}.`);
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
export function readText(path) {
|
|
17
|
+
return localFile(path).bytes.toString('utf8');
|
|
18
|
+
}
|
|
19
|
+
export function targetOf(output, fileName, fallback) {
|
|
20
|
+
const name = basename(fileName ?? '');
|
|
21
|
+
return resolve(output ?? (name === '' ? fallback : name));
|
|
22
|
+
}
|
|
23
|
+
async function transfer(context, url, init, what) {
|
|
24
|
+
let response;
|
|
25
|
+
try {
|
|
26
|
+
response = await context.fetchFn(url, init);
|
|
27
|
+
}
|
|
28
|
+
catch (error) {
|
|
29
|
+
throw new CliError(`${what}: ${error instanceof Error ? error.message : String(error)}.`, EXIT_CODES.failure);
|
|
30
|
+
}
|
|
31
|
+
if (!response.ok) {
|
|
32
|
+
throw new CliError(`${what}: o link respondeu ${String(response.status)}.`, EXIT_CODES.failure, 'O link vale 15 minutos; peça de novo.');
|
|
33
|
+
}
|
|
34
|
+
return response;
|
|
35
|
+
}
|
|
36
|
+
export async function download(context, url, target) {
|
|
37
|
+
const response = await transfer(context, url, { method: 'GET' }, 'Não consegui baixar o arquivo');
|
|
38
|
+
writeFileSync(target, Buffer.from(await response.arrayBuffer()));
|
|
39
|
+
}
|
|
40
|
+
export async function upload(context, ticket, file) {
|
|
41
|
+
await transfer(context, ticket.upload.url, { method: 'PUT', headers: { 'content-type': ticket.upload.contentType }, body: new Uint8Array(file.bytes) }, 'Não consegui enviar o arquivo');
|
|
42
|
+
}
|
package/dist/http/problem.js
CHANGED
|
@@ -10,9 +10,26 @@ export function problemOf(status, body) {
|
|
|
10
10
|
title: textOf(fields.title) ?? `A API respondeu ${String(status)}`,
|
|
11
11
|
status,
|
|
12
12
|
detail: textOf(fields.detail),
|
|
13
|
-
requestId: textOf(fields.requestId)
|
|
13
|
+
requestId: textOf(fields.requestId),
|
|
14
|
+
...(isRecord(fields.meta) ? { meta: fields.meta } : {})
|
|
14
15
|
};
|
|
15
16
|
}
|
|
17
|
+
function isRecord(value) {
|
|
18
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
19
|
+
}
|
|
20
|
+
function sentenceOf(item) {
|
|
21
|
+
if (!isRecord(item)) {
|
|
22
|
+
return textOf(item);
|
|
23
|
+
}
|
|
24
|
+
const label = textOf(item.label);
|
|
25
|
+
const reason = textOf(item.reason);
|
|
26
|
+
return textOf(item.sentence) ?? (label === null || reason === null ? null : `${label}: ${reason}`);
|
|
27
|
+
}
|
|
28
|
+
function listedIn(meta) {
|
|
29
|
+
const items = [meta?.pending, meta?.problems, meta?.findings].flatMap((list) => Array.isArray(list) ? list : []);
|
|
30
|
+
const lines = items.map(sentenceOf).flatMap((line) => (line === null ? [] : [` - ${line}`]));
|
|
31
|
+
return lines.length === 0 ? null : lines.join('\n');
|
|
32
|
+
}
|
|
16
33
|
const EXIT_BY_STATUS = {
|
|
17
34
|
401: EXIT_CODES.unauthenticated,
|
|
18
35
|
403: EXIT_CODES.forbidden,
|
|
@@ -24,10 +41,19 @@ const HINT_BY_STATUS = {
|
|
|
24
41
|
403: 'O token não tem o escopo, ou o seu perfil no Nexo não libera esta operação.',
|
|
25
42
|
429: 'Espere um pouco: o limite é da empresa, somando todos os tokens.'
|
|
26
43
|
};
|
|
44
|
+
const HINT_BY_TYPE = {
|
|
45
|
+
'agents.writing_budget': null,
|
|
46
|
+
'core.too_many_attempts': 'Espere alguns minutos: o limite é por pessoa e por empresa, somado ao do app.',
|
|
47
|
+
'agents.template_required': 'Diga o modelo da versão nova com --template <id>.'
|
|
48
|
+
};
|
|
49
|
+
function hintOf(problem) {
|
|
50
|
+
const typed = HINT_BY_TYPE[problem.type];
|
|
51
|
+
return typed === undefined ? (HINT_BY_STATUS[problem.status] ?? listedIn(problem.meta)) : typed;
|
|
52
|
+
}
|
|
27
53
|
export class NexoApiError extends CliError {
|
|
28
54
|
problem;
|
|
29
55
|
constructor(problem) {
|
|
30
|
-
super(NexoApiError.messageOf(problem), EXIT_BY_STATUS[problem.status] ?? EXIT_CODES.failure,
|
|
56
|
+
super(NexoApiError.messageOf(problem), EXIT_BY_STATUS[problem.status] ?? EXIT_CODES.failure, hintOf(problem));
|
|
31
57
|
this.name = 'NexoApiError';
|
|
32
58
|
this.problem = problem;
|
|
33
59
|
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { createInterface } from 'node:readline';
|
|
2
|
+
import { printNotice } from '../context.js';
|
|
3
|
+
export async function confirmed(context, yes, question) {
|
|
4
|
+
if (yes === true) {
|
|
5
|
+
return true;
|
|
6
|
+
}
|
|
7
|
+
if (context.stdin.isTTY !== true) {
|
|
8
|
+
printNotice(context, 'Mostre isto à pessoa. Depois do sim dela, rode de novo com --yes.');
|
|
9
|
+
return false;
|
|
10
|
+
}
|
|
11
|
+
const reader = createInterface({ input: context.stdin, output: context.stderr, terminal: true });
|
|
12
|
+
try {
|
|
13
|
+
const answer = await new Promise((resolve) => {
|
|
14
|
+
reader.question(`${question} (s/N) `, resolve);
|
|
15
|
+
});
|
|
16
|
+
return /^(s|sim|y|yes)$/i.test(answer.trim());
|
|
17
|
+
}
|
|
18
|
+
finally {
|
|
19
|
+
reader.close();
|
|
20
|
+
}
|
|
21
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { artifactsGet, artifactsList, dealsAnalysis } from './commands/artifacts.js';
|
|
2
|
+
export function addDealCommands(program, context) {
|
|
3
|
+
const deals = program.command('deals').alias('negocios').description('Os negócios do Nexo: a análise do negócio');
|
|
4
|
+
deals
|
|
5
|
+
.command('analysis')
|
|
6
|
+
.alias('analise')
|
|
7
|
+
.description('Gera (ou atualiza) a análise de um negócio e mostra o link para abrir e como a IA terminou (aiState)')
|
|
8
|
+
.argument('<negócio>', 'id do negócio')
|
|
9
|
+
.option('--brief <texto>', 'o foco que você quer na análise, nas suas palavras (até 1.500 caracteres)')
|
|
10
|
+
.action(async (dealId, _options, command) => {
|
|
11
|
+
await dealsAnalysis(context, dealId, command.optsWithGlobals());
|
|
12
|
+
});
|
|
13
|
+
}
|
|
14
|
+
export function addArtifactCommands(program, context) {
|
|
15
|
+
const artifacts = program
|
|
16
|
+
.command('artifacts')
|
|
17
|
+
.alias('artefatos')
|
|
18
|
+
.description('Os artefatos de um negócio, como a análise escrita (só leitura)');
|
|
19
|
+
artifacts
|
|
20
|
+
.command('list')
|
|
21
|
+
.description('Os artefatos de um negócio que você lê, do mais recente para o mais antigo')
|
|
22
|
+
.requiredOption('--deal <id>', 'o negócio')
|
|
23
|
+
.option('--kind <tipo>', 'só os deste tipo, como analysis')
|
|
24
|
+
.option('--page <n>', 'página da lista')
|
|
25
|
+
.option('--page-size <n>', 'artefatos por página')
|
|
26
|
+
.action(async (_options, command) => {
|
|
27
|
+
await artifactsList(context, command.optsWithGlobals());
|
|
28
|
+
});
|
|
29
|
+
artifacts
|
|
30
|
+
.command('get')
|
|
31
|
+
.description('Um artefato com as versões; com --version, o conteúdo de uma versão (a análise vem como link para abrir)')
|
|
32
|
+
.argument('<artefato>', 'id do artefato')
|
|
33
|
+
.option('--version-number <n>', 'o número da versão a abrir')
|
|
34
|
+
.action(async (artifactId, _options, command) => {
|
|
35
|
+
await artifactsGet(context, artifactId, command.optsWithGlobals());
|
|
36
|
+
});
|
|
37
|
+
}
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import { Option } from 'commander';
|
|
2
|
+
import { documentsNegotiate } from './commands/document-negotiation.js';
|
|
3
|
+
import { templatesAdd, templatesDownload, templatesList } from './commands/document-templates.js';
|
|
4
|
+
import { documentsAccept, documentsCreate, documentsFile, documentsGet, documentsList, documentsQuestionnaire, documentsRevise } from './commands/documents.js';
|
|
5
|
+
import { DEFAULT_TIMEOUT_SECONDS } from './documents/journey-api.js';
|
|
6
|
+
import { DOCUMENT_AGENTS } from './documents/journey.types.js';
|
|
7
|
+
function collect(value, previous) {
|
|
8
|
+
return [...previous, value];
|
|
9
|
+
}
|
|
10
|
+
function agentOption(description = 'proposal (Proposta) ou contract (Contrato)') {
|
|
11
|
+
return new Option('--agent <agente>', description).choices([...DOCUMENT_AGENTS]);
|
|
12
|
+
}
|
|
13
|
+
function timeoutOption() {
|
|
14
|
+
return new Option('--timeout <segundos>', 'quanto esperar até desistir').default(DEFAULT_TIMEOUT_SECONDS);
|
|
15
|
+
}
|
|
16
|
+
function addTemplateCommands(documents, context) {
|
|
17
|
+
const templates = documents
|
|
18
|
+
.command('templates')
|
|
19
|
+
.description('Os modelos de proposta ou de contrato que você pode usar')
|
|
20
|
+
.addOption(agentOption())
|
|
21
|
+
.action(async (_options, command) => {
|
|
22
|
+
await templatesList(context, command.optsWithGlobals());
|
|
23
|
+
});
|
|
24
|
+
templates
|
|
25
|
+
.command('add')
|
|
26
|
+
.description('Envia outro modelo (proposta: PDF, PPTX, DOCX ou HTML; contrato: DOCX, PDF ou HTML) e espera o Nexo ler')
|
|
27
|
+
.argument('<arquivo>', 'o arquivo do modelo, até 15 MB (PDF: até 4 MB e 30 páginas)')
|
|
28
|
+
.addOption(agentOption())
|
|
29
|
+
.option('--no-wait', 'não espera a leitura do modelo')
|
|
30
|
+
.addOption(timeoutOption())
|
|
31
|
+
.action(async (path, _options, command) => {
|
|
32
|
+
await templatesAdd(context, path, command.optsWithGlobals());
|
|
33
|
+
});
|
|
34
|
+
templates
|
|
35
|
+
.command('download')
|
|
36
|
+
.description('Baixa o arquivo de origem de um modelo')
|
|
37
|
+
.argument('<modelo>', 'id do modelo (veja `nexo documents templates`)')
|
|
38
|
+
.addOption(agentOption())
|
|
39
|
+
.option('-o, --output <arquivo>', 'onde gravar (padrão: o nome do arquivo, na pasta atual)')
|
|
40
|
+
.action(async (templateId, _options, command) => {
|
|
41
|
+
await templatesDownload(context, templateId, command.optsWithGlobals());
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
function addReadCommands(documents, context) {
|
|
45
|
+
documents
|
|
46
|
+
.command('list')
|
|
47
|
+
.description('As propostas e os contratos que você vê, do mais recente para o mais antigo')
|
|
48
|
+
.addOption(agentOption('só os documentos deste agente'))
|
|
49
|
+
.option('--deal <id>', 'só os documentos deste negócio')
|
|
50
|
+
.action(async (_options, command) => {
|
|
51
|
+
await documentsList(context, command.optsWithGlobals());
|
|
52
|
+
});
|
|
53
|
+
documents
|
|
54
|
+
.command('get')
|
|
55
|
+
.description('Um documento com as versões e a situação de cada uma')
|
|
56
|
+
.argument('<documento>', 'id do documento')
|
|
57
|
+
.action(async (documentId, _options, command) => {
|
|
58
|
+
await documentsGet(context, documentId, command.optsWithGlobals());
|
|
59
|
+
});
|
|
60
|
+
documents
|
|
61
|
+
.command('questionnaire')
|
|
62
|
+
.description('O questionário de um negócio com um modelo: blocos, campos, valor, fonte e o que falta')
|
|
63
|
+
.addOption(agentOption())
|
|
64
|
+
.option('--deal <id>', 'o negócio do documento')
|
|
65
|
+
.option('--template <id>', 'o modelo (veja `nexo documents templates`)')
|
|
66
|
+
.option('--proposal <id>', 'contrato: a proposta pronta que entra como fonte dos valores')
|
|
67
|
+
.option('--revising <documento>', 'o documento que vai ganhar uma versão nova: vem com as respostas da versão atual')
|
|
68
|
+
.option('--no-reading', 'não lê as calls e o WhatsApp do negócio (a leitura usa a IA e conta no limite da empresa)')
|
|
69
|
+
.option('-o, --output <arquivo>', 'grava o arquivo de respostas para editar e mandar com --answers')
|
|
70
|
+
.action(async (_options, command) => {
|
|
71
|
+
await documentsQuestionnaire(context, command.optsWithGlobals());
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
function addWritingCommands(documents, context) {
|
|
75
|
+
documents
|
|
76
|
+
.command('create')
|
|
77
|
+
.description('Manda as respostas e pede a escrita do documento; espera a versão ficar pronta')
|
|
78
|
+
.addOption(agentOption())
|
|
79
|
+
.option('--deal <id>', 'o negócio do documento (padrão: o do arquivo de respostas)')
|
|
80
|
+
.option('--template <id>', 'o modelo (padrão: o do arquivo de respostas)')
|
|
81
|
+
.option('--proposal <id>', 'contrato: a proposta pronta que entra como fonte dos valores')
|
|
82
|
+
.option('--answers <arquivo>', 'o arquivo de respostas (de `nexo documents questionnaire -o`)')
|
|
83
|
+
.option('--document <arquivo.html>', 'manda o documento já escrito em HTML; o Nexo limpa e confere, sem rodar a IA')
|
|
84
|
+
.option('--adaptations <arquivo.json>', 'contrato, com --document: a lista do que foi tirado ou adaptado em relação ao modelo')
|
|
85
|
+
.option('--no-wait', 'não espera a escrita: só devolve os ids')
|
|
86
|
+
.addOption(timeoutOption())
|
|
87
|
+
.action(async (_options, command) => {
|
|
88
|
+
await documentsCreate(context, command.optsWithGlobals());
|
|
89
|
+
});
|
|
90
|
+
documents
|
|
91
|
+
.command('revise')
|
|
92
|
+
.description('Pede uma versão nova com um pedido de mudança; a anterior fica no histórico')
|
|
93
|
+
.argument('<documento>', 'id do documento')
|
|
94
|
+
.option('--request <pedido>', 'o pedido de mudança, como você diria: "deixa mais direto"')
|
|
95
|
+
.option('--answers <arquivo>', 'as respostas que mudaram (de `nexo documents questionnaire --revising`)')
|
|
96
|
+
.option('--template <id>', 'outro modelo para a versão nova')
|
|
97
|
+
.option('--document <arquivo.html>', 'manda a versão nova já escrita em HTML; o Nexo limpa e confere')
|
|
98
|
+
.option('--adaptations <arquivo.json>', 'contrato, com --document: a lista do que foi tirado ou adaptado')
|
|
99
|
+
.option('--no-wait', 'não espera a escrita: só devolve os ids')
|
|
100
|
+
.addOption(timeoutOption())
|
|
101
|
+
.action(async (documentId, _options, command) => {
|
|
102
|
+
await documentsRevise(context, documentId, command.optsWithGlobals());
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
function addOutputCommands(documents, context) {
|
|
106
|
+
documents
|
|
107
|
+
.command('accept')
|
|
108
|
+
.description('Aceita uma versão da proposta: ela deixa de ser rascunho (o contrato não tem este passo)')
|
|
109
|
+
.argument('<documento>', 'id do documento')
|
|
110
|
+
.option('--version-number <n>', 'o número da versão (padrão: a atual)')
|
|
111
|
+
.action(async (documentId, _options, command) => {
|
|
112
|
+
await documentsAccept(context, documentId, command.optsWithGlobals());
|
|
113
|
+
});
|
|
114
|
+
for (const kind of ['pdf', 'docx']) {
|
|
115
|
+
documents
|
|
116
|
+
.command(kind)
|
|
117
|
+
.description(kind === 'pdf' ? 'Baixa o PDF de uma versão pronta' : 'Baixa o DOCX de uma versão pronta de um contrato')
|
|
118
|
+
.argument('<documento>', 'id do documento')
|
|
119
|
+
.option('--version-number <n>', 'o número da versão (padrão: a atual)')
|
|
120
|
+
.option('-o, --output <arquivo>', 'onde gravar (padrão: o nome que o Nexo dá, na pasta atual)')
|
|
121
|
+
.action(async (documentId, _options, command) => {
|
|
122
|
+
await documentsFile(context, kind, documentId, command.optsWithGlobals());
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
function addNegotiationCommand(documents, context) {
|
|
127
|
+
documents
|
|
128
|
+
.command('negotiate')
|
|
129
|
+
.description('Começa a negociação: mostra quem recebe o e-mail com o link e pede o sim')
|
|
130
|
+
.argument('<documento>', 'id do documento')
|
|
131
|
+
.option('--person <pessoa>', 'quem recebe o link: "Nome <email>" ou só o e-mail (repita, até 10 pessoas)', collect, [])
|
|
132
|
+
.option('--approver <email>', 'quem dá o de acordo que encerra a negociação (exatamente uma pessoa)')
|
|
133
|
+
.option('--message <texto>', 'mensagem que vai no e-mail')
|
|
134
|
+
.option('--version-number <n>', 'o número da versão a enviar (padrão: a atual)')
|
|
135
|
+
.option('-y, --yes', 'envia depois de mostrar, sem perguntar (só depois do sim da pessoa)')
|
|
136
|
+
.action(async (documentId, _options, command) => {
|
|
137
|
+
await documentsNegotiate(context, documentId, command.optsWithGlobals());
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
export function addDocumentCommands(program, context) {
|
|
141
|
+
const documents = program
|
|
142
|
+
.command('documents')
|
|
143
|
+
.alias('documentos')
|
|
144
|
+
.description('Propostas e contratos: modelos, questionário, escrita, versões, PDF, DOCX e negociação');
|
|
145
|
+
addTemplateCommands(documents, context);
|
|
146
|
+
addReadCommands(documents, context);
|
|
147
|
+
addWritingCommands(documents, context);
|
|
148
|
+
addOutputCommands(documents, context);
|
|
149
|
+
addNegotiationCommand(documents, context);
|
|
150
|
+
}
|
package/dist/program.js
CHANGED
|
@@ -5,6 +5,8 @@ import { docsList, docsSearch, docsShow } from './commands/docs.js';
|
|
|
5
5
|
import { mcpSetup } from './commands/mcp.js';
|
|
6
6
|
import { addConnectCommands } from './program-connect.js';
|
|
7
7
|
import { addAutomationCommands } from './program-automations.js';
|
|
8
|
+
import { addDocumentCommands } from './program-documents.js';
|
|
9
|
+
import { addArtifactCommands, addDealCommands } from './program-artifacts.js';
|
|
8
10
|
import { addDashboardCommands } from './program-dashboards.js';
|
|
9
11
|
import { skillsInstall, skillsList } from './commands/skills.js';
|
|
10
12
|
import { login } from './commands/login.js';
|
|
@@ -136,7 +138,7 @@ function addBillingCommands(program, context) {
|
|
|
136
138
|
}
|
|
137
139
|
export function buildProgram(context) {
|
|
138
140
|
const program = new Command('nexo')
|
|
139
|
-
.description('CLI do Nexo: a API, o Connect, os dashboards
|
|
141
|
+
.description('CLI do Nexo: a API, o Connect, os dashboards, os fluxos, os documentos e as análises no terminal')
|
|
140
142
|
.version(CLI_VERSION, '-v, --version', 'mostra a versão')
|
|
141
143
|
.helpOption('-h, --help', 'mostra a ajuda')
|
|
142
144
|
.helpCommand('help [comando]', 'mostra a ajuda de um comando')
|
|
@@ -156,5 +158,8 @@ export function buildProgram(context) {
|
|
|
156
158
|
addAutomationCommands(program, context);
|
|
157
159
|
addDashboardCommands(program, context);
|
|
158
160
|
addBillingCommands(program, context);
|
|
161
|
+
addDocumentCommands(program, context);
|
|
162
|
+
addDealCommands(program, context);
|
|
163
|
+
addArtifactCommands(program, context);
|
|
159
164
|
return program;
|
|
160
165
|
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@winning-sales/nexo",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "CLI do Nexo: a API, o Connect, os dashboards
|
|
3
|
+
"version": "0.4.0",
|
|
4
|
+
"description": "CLI do Nexo: a API, o Connect, os dashboards, os fluxos, os documentos e as análises no terminal, com a documentação e as skills do produto para a sua IA",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"bin": {
|