@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.
@@ -37,6 +37,18 @@ Além dos gatilhos de cada registro, três gatilhos escutam **qualquer entidade*
37
37
  6. Investigar: `nexo automations runs <pasta> --state failed` e `nexo automations run <id>`, que mostra cada passo, o erro e o que produziu. A regra não disparou? `nexo automations events <entidade> <registro>` mostra o que o Nexo guardou do registro nos últimos 14 dias: a operação, os **nomes** dos campos que mudaram (nunca os valores), a origem e se o despacho já ocorreu (`pendente`, `despachado` ou `desistiu`). Sem evento, a gravação não chegou; evento sem execução, confira o filtro `fields`, a janela de 24 h (`runs` mostra `janela até`) e a origem.
38
38
  7. `nexo automations get`, `versions` e `restore <seq> --yes` (cria uma versão nova com o documento antigo; só depois do sim da pessoa).
39
39
 
40
+ ## E-mail com a marca da empresa
41
+
42
+ Modelo de e-mail pelo `automation_change` e `automation_apply` (`criar_modelo`, `mudar_modelo`) com `blocos`. Antes de criar ou mudar, leia `automations`, parte `modelos`: ela traz `marca` (identidade completa, parcial ou ausente, o que falta e onde cadastrar), os nomes de cor com o papel de cada um e a diretriz do guia confirmado.
43
+
44
+ - **Estilo.** E-mail corporativo automático, sóbrio e escaneável: abre com a marca (bloco `logo`), um objetivo e uma ação principal (um botão), faixas e cards (`secao`) só onde ajudam. A composição é sua e varia com o conteúdo; não copie um gabarito.
45
+ - **Vocabulário.** `logo {variante: claro | escuro | auto}`, `secao {fundo, cantos, blocos}` (uma seção dentro de outra só como card), `cor` no texto e no fundo do botão, `cantos` (`reto`, `suave`, `redondo`). Cor só por nome: `marca`, `marca-escura`, `suave`, `texto`, `apoio`, `branco`.
46
+ - **Nunca** escreva hex, CSS nem a URL do logo: o código troca os nomes pelas cores reais, garante o logo, o cabeçalho e o contraste e grava tudo no modelo.
47
+ - **Recusa.** Quando o compositor recusar (hex, contraste, seção dentro de seção dentro de seção, botões demais, tamanho), a resposta traz o motivo: corrija a lista de blocos e chame de novo, sem mostrar nada à pessoa antes.
48
+ - **Sem a marca.** `semEstrutura: true` só quando a pessoa pede o e-mail sem logo, faixas nem cabeçalho.
49
+ - **Identidade parcial ou ausente.** Diga à pessoa, em uma frase, o que falta e onde cadastrar (`marca.onde`), sem inventar.
50
+ - **Modelo antigo.** O resultado diz `formato_antigo`: mande a lista de blocos recomposta.
51
+
40
52
  ## Cuidados
41
53
 
42
54
  - Ações com `risk` `notifies`, `prepares_message` ou `uses_ai` mandam algo a pessoas ou gastam IA: diga isso à pessoa antes de publicar.
@@ -0,0 +1,118 @@
1
+ import { clientOf, printJson, printLine, printNotice, sessionOf } from '../context.js';
2
+ import { usageError } from '../errors.js';
3
+ const AI_STATE_LABELS = {
4
+ written: 'a IA escreveu a página',
5
+ fallback_budget: 'só os números do Nexo: o limite de IA da empresa acabou',
6
+ fallback_invalid: 'só os números do Nexo: a IA não respeitou as regras de número',
7
+ fallback_unavailable: 'só os números do Nexo: a IA estava indisponível',
8
+ fallback_empty: 'só os números do Nexo: nenhum negócio ao alcance'
9
+ };
10
+ async function call(context, options, method, path, body) {
11
+ const response = await clientOf(context, sessionOf(context, options)).request({
12
+ method,
13
+ path,
14
+ ...(body === undefined ? {} : { body })
15
+ });
16
+ return response.body;
17
+ }
18
+ function versionNumber(value) {
19
+ if (value === undefined) {
20
+ return undefined;
21
+ }
22
+ if (!/^[1-9]\d*$/.test(value)) {
23
+ throw usageError(`--version-number pede o número da versão, a partir de 1 (veio "${value}").`);
24
+ }
25
+ return Number(value);
26
+ }
27
+ function stateLabel(aiState) {
28
+ return aiState === null ? '—' : aiState;
29
+ }
30
+ function contentPath(artifactId, version) {
31
+ return `/v1/artifacts/${encodeURIComponent(artifactId)}/versions/${String(version)}/content`;
32
+ }
33
+ function printLink(context, label, link) {
34
+ if (link !== null) {
35
+ printLine(context, `${label}: ${link.url}`);
36
+ printNotice(context, `O link vale até ${link.expiresAt}.`);
37
+ }
38
+ }
39
+ export async function dealsAnalysis(context, dealId, options) {
40
+ const brief = options.brief?.trim();
41
+ const analysis = (await call(context, options, 'POST', `/v1/deals/${encodeURIComponent(dealId)}/analysis`, brief === undefined || brief === '' ? {} : { brief }));
42
+ const content = (await call(context, options, 'GET', contentPath(analysis.artifact.id, analysis.version.version)));
43
+ if (options.json === true) {
44
+ printJson(context, { ...analysis, view: content.view, download: content.download });
45
+ return;
46
+ }
47
+ printLine(context, `${analysis.artifact.name}: versão ${String(analysis.version.version)} (artefato ${analysis.artifact.id}), gerada em ${analysis.generatedAt}`);
48
+ printLine(context, `aiState: ${analysis.aiState} (${AI_STATE_LABELS[analysis.aiState] ?? 'estado novo'})`);
49
+ if (!analysis.saved) {
50
+ printNotice(context, 'Nada foi gravado: a versão boa anterior continua como a atual. Tente de novo mais tarde.');
51
+ }
52
+ printLink(context, 'view', content.view);
53
+ }
54
+ function listQuery(dealId, options) {
55
+ const query = new URLSearchParams({ dealId });
56
+ for (const [key, value] of [
57
+ ['kind', options.kind],
58
+ ['page', options.page],
59
+ ['pageSize', options.pageSize]
60
+ ]) {
61
+ if (value !== undefined) {
62
+ query.set(key, value);
63
+ }
64
+ }
65
+ return query;
66
+ }
67
+ export async function artifactsList(context, options) {
68
+ if (options.deal === undefined) {
69
+ throw usageError('Diga o negócio com --deal <id>.', 'A lista é sempre de um negócio.');
70
+ }
71
+ const query = listQuery(options.deal, options);
72
+ const page = (await call(context, options, 'GET', `/v1/artifacts?${query.toString()}`));
73
+ if (options.json === true) {
74
+ printJson(context, page);
75
+ return;
76
+ }
77
+ if (page.data.length === 0) {
78
+ printLine(context, 'Nenhum artefato neste negócio.');
79
+ return;
80
+ }
81
+ page.data.forEach((artifact) => {
82
+ printLine(context, `${artifact.id} ${artifact.kind.padEnd(9)} v${String(artifact.currentVersion)} ${stateLabel(artifact.current?.aiState ?? null).padEnd(20)} ${artifact.name}`);
83
+ });
84
+ if (page.pagination.page < page.pagination.totalPages) {
85
+ printNotice(context, `Página ${String(page.pagination.page)} de ${String(page.pagination.totalPages)}: veja a próxima com --page.`);
86
+ }
87
+ }
88
+ async function artifactVersion(context, artifactId, version, options) {
89
+ const content = (await call(context, options, 'GET', contentPath(artifactId, version)));
90
+ if (options.json === true) {
91
+ printJson(context, content);
92
+ return;
93
+ }
94
+ printLine(context, `Versão ${String(content.version)}: ${content.fileName} (${content.mimeType}, ${String(content.sizeInBytes)} bytes, ${content.storage})`);
95
+ printLink(context, 'view', content.view);
96
+ printLink(context, 'download', content.download);
97
+ if (content.content !== null) {
98
+ printLine(context, content.content);
99
+ }
100
+ }
101
+ export async function artifactsGet(context, artifactId, options) {
102
+ const version = versionNumber(options.versionNumber);
103
+ if (version !== undefined) {
104
+ await artifactVersion(context, artifactId, version, options);
105
+ return;
106
+ }
107
+ const artifact = (await call(context, options, 'GET', `/v1/artifacts/${encodeURIComponent(artifactId)}`));
108
+ if (options.json === true) {
109
+ printJson(context, artifact);
110
+ return;
111
+ }
112
+ printLine(context, `${artifact.name} (${artifact.kind}), versão atual ${String(artifact.currentVersion)}`);
113
+ printLine(context, `Negócio: ${artifact.dealId ?? '—'} Dono: ${artifact.ownerName ?? '—'} Atualizado em ${artifact.updatedAt}`);
114
+ artifact.versions.forEach((each) => {
115
+ printLine(context, ` v${String(each.version)} ${each.source.padEnd(10)} ${stateLabel(each.aiState).padEnd(20)} ${each.createdAt}`);
116
+ });
117
+ printNotice(context, 'Para abrir uma versão: `nexo artifacts get <id> --version-number <n>`.');
118
+ }
@@ -0,0 +1,217 @@
1
+ import { clientOf, printJson, printLine, sessionOf } from '../context.js';
2
+ import { usageError } from '../errors.js';
3
+ import { confirmed } from '../input/confirm.js';
4
+ const PATHS = {
5
+ company: '/v1/brain/company-skills',
6
+ area: '/v1/brain/area-skills',
7
+ team: '/v1/brain/team-skills',
8
+ person: '/v1/brain/person-skills'
9
+ };
10
+ const UPDATE_SEPARATOR = '=>';
11
+ async function call(context, options, method, path, extra = {}) {
12
+ const response = await clientOf(context, sessionOf(context, options)).request({ method, path, ...extra });
13
+ return response.body;
14
+ }
15
+ function levelOf(raw) {
16
+ if (raw === 'company' || raw === 'area' || raw === 'team' || raw === 'person') {
17
+ return raw;
18
+ }
19
+ throw usageError(`Nível "${raw}" não existe: use company (empresa), area, team (time) ou person (pessoal).`);
20
+ }
21
+ function skillPath(level, skillId) {
22
+ return `${PATHS[level]}/${encodeURIComponent(skillId)}`;
23
+ }
24
+ function listOf(values) {
25
+ return values ?? [];
26
+ }
27
+ function updatesOf(list, values) {
28
+ return listOf(values).map((value) => {
29
+ const at = value.indexOf(UPDATE_SEPARATOR);
30
+ const item = at < 0 ? '' : value.slice(0, at).trim();
31
+ const to = at < 0 ? '' : value.slice(at + UPDATE_SEPARATOR.length).trim();
32
+ if (item === '' || to === '') {
33
+ throw usageError(`Para atualizar um item, use "item atual ${UPDATE_SEPARATOR} item novo" (recebi "${value}").`);
34
+ }
35
+ return { op: 'update', list, item, to };
36
+ });
37
+ }
38
+ function changesOf(options) {
39
+ const adds = (list, values) => listOf(values).map((item) => ({ op: 'add', list, item }));
40
+ const removes = (list, values) => listOf(values).map((item) => ({ op: 'remove', list, item }));
41
+ return [
42
+ ...adds('sempre', options.addAlways),
43
+ ...adds('nunca', options.addNever),
44
+ ...updatesOf('sempre', options.updateAlways),
45
+ ...updatesOf('nunca', options.updateNever),
46
+ ...removes('sempre', options.removeAlways),
47
+ ...removes('nunca', options.removeNever)
48
+ ];
49
+ }
50
+ function required(value, flag) {
51
+ if (value === undefined || value.trim() === '') {
52
+ throw usageError(`Falta ${flag}.`);
53
+ }
54
+ return value;
55
+ }
56
+ function ideaOf(options) {
57
+ const always = listOf(options.always);
58
+ const never = listOf(options.never);
59
+ if (always.length + never.length === 0) {
60
+ throw usageError('Diga ao menos uma coisa para fazer sempre (--always) ou para nunca fazer (--never).');
61
+ }
62
+ return {
63
+ objective: required(options.objective, '--objective'),
64
+ moment: required(options.moment, '--moment'),
65
+ always,
66
+ never,
67
+ example: required(options.example, '--example')
68
+ };
69
+ }
70
+ function printSkill(context, skill) {
71
+ printLine(context, `${skill.id} ${skill.name} [${skill.status}, versão ${String(skill.version)}]`);
72
+ printLine(context, ` ${skill.description}`);
73
+ }
74
+ export async function brainAreas(context, options) {
75
+ const list = (await call(context, options, 'GET', '/v1/brain/areas'));
76
+ if (options.json === true) {
77
+ printJson(context, list);
78
+ return;
79
+ }
80
+ for (const area of list.areas) {
81
+ printLine(context, `${area.id} ${area.name}`);
82
+ }
83
+ }
84
+ export async function brainMoments(context, options) {
85
+ const list = (await call(context, options, 'GET', '/v1/brain/skills/moments'));
86
+ const moments = list.moments ?? [];
87
+ if (options.json === true) {
88
+ printJson(context, { moments });
89
+ return;
90
+ }
91
+ printLine(context, moments.length === 0 ? 'Nenhum momento aceita skill nova por enquanto.' : moments.join('\n'));
92
+ }
93
+ export async function brainList(context, rawLevel, options) {
94
+ const level = levelOf(rawLevel);
95
+ const query = options.scope === undefined || level === 'company' || level === 'person' ? {} : { scopeId: options.scope };
96
+ const list = (await call(context, options, 'GET', PATHS[level], { query }));
97
+ if (options.json === true) {
98
+ printJson(context, list);
99
+ return;
100
+ }
101
+ if (list.skills.length === 0) {
102
+ printLine(context, 'Nenhuma skill neste nível.');
103
+ }
104
+ for (const skill of list.skills) {
105
+ printSkill(context, skill);
106
+ }
107
+ if (level === 'person' && list.maxSkills !== undefined) {
108
+ printLine(context, `${String(list.skills.length)} de ${String(list.maxSkills)} skills pessoais.`);
109
+ }
110
+ }
111
+ export async function brainCreate(context, rawLevel, options) {
112
+ const level = levelOf(rawLevel);
113
+ const idea = ideaOf(options);
114
+ const where = level === 'area'
115
+ ? { areaId: required(options.area, '--area') }
116
+ : level === 'team'
117
+ ? { teamId: required(options.team, '--team') }
118
+ : {};
119
+ const skill = (await call(context, options, 'POST', PATHS[level], { body: { ...where, ...idea } }));
120
+ if (options.json === true) {
121
+ printJson(context, skill);
122
+ return;
123
+ }
124
+ printLine(context, 'Skill criada. Ela nasce em teste e só liga depois do teste "não piora" e da escolha às cegas.');
125
+ printSkill(context, skill);
126
+ }
127
+ export async function brainEdit(context, rawLevel, skillId, options) {
128
+ const level = levelOf(rawLevel);
129
+ const changes = changesOf(options);
130
+ if (changes.length === 0) {
131
+ throw usageError('Nenhuma mudança: use --add-always, --add-never, --update-always, --update-never, --remove-always ou --remove-never.');
132
+ }
133
+ const body = { changes, confirmShrink: options.confirmShrink === true };
134
+ const skill = (await call(context, options, 'PUT', skillPath(level, skillId), { body }));
135
+ if (options.json === true) {
136
+ printJson(context, skill);
137
+ return;
138
+ }
139
+ printLine(context, `Skill editada: versão ${String(skill.version)}.`);
140
+ printSkill(context, skill);
141
+ }
142
+ export async function brainRemove(context, rawLevel, skillId, options) {
143
+ const level = levelOf(rawLevel);
144
+ if (!(await confirmed(context, options.yes, `Apagar a skill ${skillId}?`))) {
145
+ return;
146
+ }
147
+ await call(context, options, 'DELETE', skillPath(level, skillId));
148
+ printLine(context, level === 'person' ? 'Skill apagada. Dá para restaurar em 30 dias, pelo app.' : 'Skill apagada.');
149
+ }
150
+ export async function brainTemplates(context, options) {
151
+ const list = (await call(context, options, 'GET', `${PATHS.person}/templates`));
152
+ if (options.json === true) {
153
+ printJson(context, list);
154
+ return;
155
+ }
156
+ for (const template of list.templates) {
157
+ const keys = template.fields.map((field) => `${field.key} (${field.label})`).join(', ');
158
+ printLine(context, `${template.id} ${template.title} [${template.moment}${template.available ? '' : ', indisponível'}]`);
159
+ printLine(context, ` campos: ${keys}`);
160
+ }
161
+ }
162
+ function answersOf(values) {
163
+ const answers = {};
164
+ for (const value of listOf(values)) {
165
+ const at = value.indexOf('=');
166
+ const key = at < 0 ? '' : value.slice(0, at).trim();
167
+ const text = at < 0 ? '' : value.slice(at + 1).trim();
168
+ if (key === '' || text === '') {
169
+ throw usageError(`Use --answer "campo=texto" (recebi "${value}").`);
170
+ }
171
+ answers[key] = text;
172
+ }
173
+ if (Object.keys(answers).length === 0) {
174
+ throw usageError('Falta --answer "campo=texto" (um por campo do modelo; veja `nexo brain templates`).');
175
+ }
176
+ return answers;
177
+ }
178
+ export async function brainFromTemplate(context, templateId, options) {
179
+ const body = { templateId, answers: answersOf(options.answer) };
180
+ const skill = (await call(context, options, 'POST', `${PATHS.person}/from-template`, { body }));
181
+ if (options.json === true) {
182
+ printJson(context, skill);
183
+ return;
184
+ }
185
+ printLine(context, 'Skill pessoal criada a partir do modelo. Ela nasce em teste e só liga depois do teste "não piora" e da escolha às cegas.');
186
+ printSkill(context, skill);
187
+ }
188
+ export async function brainBlindTest(context, skillId, options) {
189
+ const pair = (await call(context, options, 'POST', `${skillPath('person', skillId)}/blind-test`));
190
+ if (options.json === true) {
191
+ printJson(context, pair);
192
+ return;
193
+ }
194
+ printLine(context, `Comparação ${pair.id}`);
195
+ printLine(context, `Cenário: ${pair.scenario}`);
196
+ printLine(context, `\n--- Texto A ---\n${pair.a}\n\n--- Texto B ---\n${pair.b}\n`);
197
+ printLine(context, `Escolha o melhor, sem saber qual tem a skill: nexo brain choose ${pair.id} <a|b>`);
198
+ }
199
+ export async function brainChoose(context, choiceId, chosen, options) {
200
+ const pick = chosen.toLowerCase();
201
+ if (pick !== 'a' && pick !== 'b') {
202
+ throw usageError(`Escolha "a" ou "b" (recebi "${chosen}").`);
203
+ }
204
+ const result = (await call(context, options, 'POST', `${PATHS.person}/blind-tests/${encodeURIComponent(choiceId)}/choose`, {
205
+ body: { chosen: pick }
206
+ }));
207
+ if (options.json === true) {
208
+ printJson(context, result);
209
+ return;
210
+ }
211
+ printLine(context, `A skill estava no texto ${result.withSkillAt.toUpperCase()}; você escolheu ${result.chosen.toUpperCase()}.`);
212
+ printLine(context, result.next === 'ask_what_was_missing'
213
+ ? 'A skill continua desligada: faltou algo nela. Diga o que faltava e edite a skill por item.'
214
+ : result.activated
215
+ ? 'Ganho confirmado: a skill está ligada.'
216
+ : 'Ganho confirmado; a skill liga quando o teste "não piora" aprovar esta versão.');
217
+ }
@@ -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
+ }