@winning-sales/nexo 0.3.0 → 0.5.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 +88 -4
- package/assets/docs/pages.json +1 -1
- package/assets/skills/nexo-automations/SKILL.md +12 -0
- package/dist/commands/artifacts.js +118 -0
- package/dist/commands/brain.js +217 -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 +14 -3
- package/dist/commands/skills.js +130 -10
- package/dist/commands/templates.js +279 -0
- 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 +32 -2
- package/dist/input/confirm.js +21 -0
- package/dist/program-artifacts.js +37 -0
- package/dist/program-brain.js +111 -0
- package/dist/program-documents.js +150 -0
- package/dist/program-templates.js +97 -0
- package/dist/program.js +25 -9
- package/dist/skills/bundled-freshness.js +39 -0
- package/dist/skills/remote-skills.js +45 -0
- package/dist/skills/sync-skills.js +50 -0
- package/dist/skills/targets.js +1 -4
- package/dist/skills/user-skills.js +145 -0
- package/dist/tools/tool-manifest.js +211 -0
- package/package.json +2 -2
- package/reference.json +1318 -5
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
import { createReadStream, writeFileSync } from 'node:fs';
|
|
2
|
+
import { clientOf, printJson, printLine, printNotice, sessionOf } from '../context.js';
|
|
3
|
+
import { CliError, usageError } from '../errors.js';
|
|
4
|
+
import { EXIT_CODES } from '../exit-codes.types.js';
|
|
5
|
+
import { confirmed } from '../input/confirm.js';
|
|
6
|
+
import { readAll } from '../input/read-input.js';
|
|
7
|
+
async function call(context, options, method, path, body) {
|
|
8
|
+
const response = await clientOf(context, sessionOf(context, options)).request({
|
|
9
|
+
method,
|
|
10
|
+
path,
|
|
11
|
+
...(body === undefined ? {} : { body })
|
|
12
|
+
});
|
|
13
|
+
return response.body;
|
|
14
|
+
}
|
|
15
|
+
function templatePath(templateId) {
|
|
16
|
+
return `/v1/message-templates/${encodeURIComponent(templateId)}`;
|
|
17
|
+
}
|
|
18
|
+
async function jsonInput(context, input) {
|
|
19
|
+
const label = input === '-' ? 'stdin' : input;
|
|
20
|
+
let text;
|
|
21
|
+
try {
|
|
22
|
+
text = await readAll(input === '-' ? context.stdin : createReadStream(input));
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
throw usageError(`Não consegui ler ${label}.`);
|
|
26
|
+
}
|
|
27
|
+
try {
|
|
28
|
+
return JSON.parse(text);
|
|
29
|
+
}
|
|
30
|
+
catch {
|
|
31
|
+
throw usageError(`O conteúdo de ${label} não é JSON válido.`);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
function isRecord(value) {
|
|
35
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
36
|
+
}
|
|
37
|
+
function saveFile(context, path, text, label) {
|
|
38
|
+
try {
|
|
39
|
+
writeFileSync(path, text);
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
throw new CliError(`Não consegui gravar ${path}.`, EXIT_CODES.failure);
|
|
43
|
+
}
|
|
44
|
+
printNotice(context, `${label} gravado em ${path}.`);
|
|
45
|
+
}
|
|
46
|
+
function formatOf(content) {
|
|
47
|
+
const nodes = content.document?.json.content;
|
|
48
|
+
if (content.document === null) {
|
|
49
|
+
return 'texto simples';
|
|
50
|
+
}
|
|
51
|
+
return nodes !== undefined && nodes.length > 0 && nodes.every((node) => node.type === 'section')
|
|
52
|
+
? 'estruturado, com a marca'
|
|
53
|
+
: 'blocos, formato antigo';
|
|
54
|
+
}
|
|
55
|
+
function printBrand(context, brand) {
|
|
56
|
+
if (brand === null || brand === undefined) {
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
printLine(context, `Marca: identidade ${brand.identidade}${brand.falta.length === 0 ? '' : `, falta ${brand.falta.join(' e ')}`}`);
|
|
60
|
+
if (brand.aviso !== null && brand.aviso !== undefined) {
|
|
61
|
+
printLine(context, brand.aviso);
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
if (brand.onde !== null) {
|
|
65
|
+
printLine(context, `Cadastre em ${brand.onde}${brand.caminho === null ? '' : ` (${brand.caminho})`}.`);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
const IDENTITY_LABELS = {
|
|
69
|
+
complete: 'completa',
|
|
70
|
+
partial: 'parcial',
|
|
71
|
+
absent: 'ausente'
|
|
72
|
+
};
|
|
73
|
+
function printStructureBrand(context, brand) {
|
|
74
|
+
if (brand === null || brand === undefined) {
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
printLine(context, `Marca: identidade ${IDENTITY_LABELS[brand.identity]}${brand.missing.length === 0 ? '' : `, falta ${brand.missing.join(' e ')}`}`);
|
|
78
|
+
if (brand.text !== null) {
|
|
79
|
+
printLine(context, brand.text);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
function row(template) {
|
|
83
|
+
const kit = template.fromKit ? ' (kit)' : '';
|
|
84
|
+
return `${template.id} ${template.channel.padEnd(8)} ${template.state.padEnd(8)} v${String(template.currentSeq)} ${template.name}${kit}`;
|
|
85
|
+
}
|
|
86
|
+
export async function templatesList(context, options) {
|
|
87
|
+
const query = new URLSearchParams();
|
|
88
|
+
for (const [key, value] of [
|
|
89
|
+
['channel', options.channel],
|
|
90
|
+
['state', options.state],
|
|
91
|
+
['subjectType', options.subjectType]
|
|
92
|
+
]) {
|
|
93
|
+
if (value !== undefined) {
|
|
94
|
+
query.set(key, value);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
const suffix = query.size === 0 ? '' : `?${query.toString()}`;
|
|
98
|
+
const list = (await call(context, options, 'GET', `/v1/message-templates${suffix}`));
|
|
99
|
+
if (options.json === true) {
|
|
100
|
+
printJson(context, list);
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
if (list.items.length === 0) {
|
|
104
|
+
printLine(context, 'Nenhum modelo de mensagem.');
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
list.items.forEach((template) => {
|
|
108
|
+
printLine(context, row(template));
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
export async function templatesGet(context, templateId, options) {
|
|
112
|
+
const template = (await call(context, options, 'GET', templatePath(templateId)));
|
|
113
|
+
if (options.json === true) {
|
|
114
|
+
printJson(context, template);
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
printLine(context, row(template));
|
|
118
|
+
if (template.channel === 'email') {
|
|
119
|
+
printLine(context, `Formato: ${formatOf(template.content)}`);
|
|
120
|
+
printLine(context, `Assunto: ${template.content.subject ?? '—'}`);
|
|
121
|
+
}
|
|
122
|
+
if (template.content.body !== '') {
|
|
123
|
+
printLine(context, template.content.body);
|
|
124
|
+
}
|
|
125
|
+
if (template.rules.length > 0) {
|
|
126
|
+
printLine(context, 'Regras que usam o modelo:');
|
|
127
|
+
template.rules.forEach((rule) => {
|
|
128
|
+
printLine(context, ` ${rule.name} (${rule.status})${rule.sendsAutomatically ? ', envia sozinha' : ''}`);
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
printNotice(context, 'Para ler os blocos, use `nexo templates get <id> --json`.');
|
|
132
|
+
}
|
|
133
|
+
export async function templatesPreview(context, templateId, options) {
|
|
134
|
+
const preview = (await call(context, options, 'POST', `${templatePath(templateId)}/preview`, {}));
|
|
135
|
+
if (options.json === true) {
|
|
136
|
+
printJson(context, preview);
|
|
137
|
+
saveHtml(context, options, preview.previews[0]?.email?.html ?? null);
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
preview.previews.forEach((each) => {
|
|
141
|
+
printLine(context, `Assunto: ${each.subject ?? '—'}`);
|
|
142
|
+
printLine(context, each.email === null ? each.body : each.email.text);
|
|
143
|
+
});
|
|
144
|
+
printNotice(context, 'A prévia usa só amostras fixas, nunca registros reais da empresa.');
|
|
145
|
+
saveHtml(context, options, preview.previews[0]?.email?.html ?? null);
|
|
146
|
+
}
|
|
147
|
+
function saveHtml(context, options, html) {
|
|
148
|
+
if (options.html !== undefined && html !== null) {
|
|
149
|
+
saveFile(context, options.html, html, 'O HTML do e-mail');
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
export async function templatesStructure(context, options) {
|
|
153
|
+
if ((options.template === undefined) === (options.input === undefined)) {
|
|
154
|
+
throw usageError('Diga o conteúdo a estruturar com --template <id> ou com --input <arquivo>, só um dos dois.');
|
|
155
|
+
}
|
|
156
|
+
const content = options.template === undefined
|
|
157
|
+
? await jsonInput(context, options.input ?? '-')
|
|
158
|
+
: (await call(context, options, 'GET', templatePath(options.template))).content;
|
|
159
|
+
const structured = (await call(context, options, 'POST', '/v1/message-templates/professional-structure', {
|
|
160
|
+
content
|
|
161
|
+
}));
|
|
162
|
+
if (options.out !== undefined) {
|
|
163
|
+
saveFile(context, options.out, `${JSON.stringify(structured.content, null, 2)}\n`, 'O conteúdo estruturado');
|
|
164
|
+
}
|
|
165
|
+
if (options.json === true) {
|
|
166
|
+
printJson(context, structured);
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
printLine(context, structured.converted ? 'O modelo foi colocado na estrutura nova da marca.' : 'O modelo já estava estruturado, ou vazio: nada mudou.');
|
|
170
|
+
printStructureBrand(context, structured.brand);
|
|
171
|
+
printNotice(context, 'Nada foi gravado. Para gravar, use `nexo templates change`.');
|
|
172
|
+
}
|
|
173
|
+
function listOf(value, label) {
|
|
174
|
+
const list = isRecord(value) ? value['blocos'] : value;
|
|
175
|
+
if (!Array.isArray(list)) {
|
|
176
|
+
throw usageError(`${label} pede a lista de blocos, ou um objeto com "blocos".`);
|
|
177
|
+
}
|
|
178
|
+
return list;
|
|
179
|
+
}
|
|
180
|
+
async function requestOf(context, action, templateId, options) {
|
|
181
|
+
const base = options.input === undefined ? {} : await jsonInput(context, options.input);
|
|
182
|
+
if (!isRecord(base)) {
|
|
183
|
+
throw usageError('O arquivo de --input pede um objeto JSON com os campos do pedido.');
|
|
184
|
+
}
|
|
185
|
+
const request = { ...base, acao: action };
|
|
186
|
+
delete request['confirmationToken'];
|
|
187
|
+
const fields = [
|
|
188
|
+
['modeloId', templateId],
|
|
189
|
+
['canal', options.channel],
|
|
190
|
+
['nome', options.name],
|
|
191
|
+
['assunto', options.subject],
|
|
192
|
+
['texto', options.text],
|
|
193
|
+
['rodape', options.footer],
|
|
194
|
+
['categoria', options.category],
|
|
195
|
+
['cabecalho', options.header],
|
|
196
|
+
['registro', options.record]
|
|
197
|
+
];
|
|
198
|
+
for (const [key, value] of fields) {
|
|
199
|
+
if (value !== undefined) {
|
|
200
|
+
request[key] = value;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
if (options.blocks !== undefined) {
|
|
204
|
+
request['blocos'] = listOf(await jsonInput(context, options.blocks), '--blocks');
|
|
205
|
+
}
|
|
206
|
+
if (options.structure === false) {
|
|
207
|
+
request['semEstrutura'] = true;
|
|
208
|
+
}
|
|
209
|
+
return request;
|
|
210
|
+
}
|
|
211
|
+
function printProblems(context, problems) {
|
|
212
|
+
problems.forEach((problem) => {
|
|
213
|
+
printLine(context, ` - ${problem.nodeKey === null ? '' : `${problem.nodeKey}: `}${problem.reason}`);
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
function printCard(context, card) {
|
|
217
|
+
printLine(context, card.title);
|
|
218
|
+
card.details.forEach((line) => {
|
|
219
|
+
printLine(context, ` ${line}`);
|
|
220
|
+
});
|
|
221
|
+
if (card.change.changes.length > 0) {
|
|
222
|
+
printLine(context, 'O que sai e o que entra:');
|
|
223
|
+
card.change.changes.forEach((line) => {
|
|
224
|
+
printLine(context, ` ${line}`);
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
const subject = card.change.previews[0]?.subject;
|
|
228
|
+
if (subject !== undefined && subject !== null) {
|
|
229
|
+
printLine(context, `Assunto da prévia: ${subject}`);
|
|
230
|
+
}
|
|
231
|
+
printBrand(context, card.change.brand);
|
|
232
|
+
}
|
|
233
|
+
function printApplied(context, applied) {
|
|
234
|
+
printLine(context, `${applied.mensagem} (${applied.modelo}: ${applied.situacao}, versão ${String(applied.versao)})`);
|
|
235
|
+
if (applied.avisoFormato !== undefined) {
|
|
236
|
+
printLine(context, applied.avisoFormato);
|
|
237
|
+
}
|
|
238
|
+
printBrand(context, applied.marca);
|
|
239
|
+
applied.meta?.forEach((line) => {
|
|
240
|
+
printLine(context, `Meta: ${line}`);
|
|
241
|
+
});
|
|
242
|
+
}
|
|
243
|
+
async function change(context, action, templateId, options) {
|
|
244
|
+
const request = await requestOf(context, action, templateId, options);
|
|
245
|
+
const card = (await call(context, options, 'POST', '/v1/message-template-changes/preview', request));
|
|
246
|
+
saveHtml(context, options, card.change.previews[0]?.html ?? null);
|
|
247
|
+
if (options.json !== true) {
|
|
248
|
+
printCard(context, card);
|
|
249
|
+
}
|
|
250
|
+
if (card.change.problems.length > 0) {
|
|
251
|
+
printLine(context, 'O Nexo não aceitou o pedido, corrija e rode de novo:');
|
|
252
|
+
printProblems(context, card.change.problems);
|
|
253
|
+
throw new CliError('Nada foi gravado: o pedido tem problemas.', EXIT_CODES.failure);
|
|
254
|
+
}
|
|
255
|
+
if (!(await confirmed(context, options.yes, 'Gravar assim?'))) {
|
|
256
|
+
if (options.json === true) {
|
|
257
|
+
printJson(context, card);
|
|
258
|
+
}
|
|
259
|
+
return;
|
|
260
|
+
}
|
|
261
|
+
const applied = (await call(context, options, 'POST', '/v1/message-template-changes/apply', {
|
|
262
|
+
...request,
|
|
263
|
+
confirmationToken: card.confirmation.token
|
|
264
|
+
}));
|
|
265
|
+
if (options.json === true) {
|
|
266
|
+
printJson(context, applied);
|
|
267
|
+
return;
|
|
268
|
+
}
|
|
269
|
+
printApplied(context, applied);
|
|
270
|
+
}
|
|
271
|
+
export async function templatesCreate(context, options) {
|
|
272
|
+
await change(context, 'criar_modelo', undefined, options);
|
|
273
|
+
}
|
|
274
|
+
export async function templatesChange(context, templateId, options) {
|
|
275
|
+
await change(context, 'mudar_modelo', templateId, options);
|
|
276
|
+
}
|
|
277
|
+
export async function templatesPublish(context, templateId, options) {
|
|
278
|
+
await change(context, 'publicar_modelo', templateId, options);
|
|
279
|
+
}
|
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
|
+
}
|
|
@@ -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
|
+
}
|