@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.
@@ -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,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
+ }
@@ -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 › Integrações › Tokens de API e MCP.');
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 › Integrações › Tokens de API e MCP.');
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.');
@@ -1,9 +1,8 @@
1
1
  import { clientOf, printJson, printLine, sessionOf } from '../context.js';
2
- const ROLE_LABELS = {
3
- admin: 'administrador',
4
- sales_lead: 'líder de vendas',
5
- rep: 'vendedor'
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}>, ${ROLE_LABELS[me.user.role]}`,
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
+ }