@winning-sales/nexo 0.6.0 → 0.7.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.
@@ -3,7 +3,10 @@ import { CliError, usageError } from '../errors.js';
3
3
  import { EXIT_CODES } from '../exit-codes.types.js';
4
4
  import { readAll, readSecret } from '../input/read-input.js';
5
5
  import { requestChange } from '../connect/changes.js';
6
- import { projectDirectory, readState } from '../connect/project.js';
6
+ import { readArgs } from '../connect/operation-args.js';
7
+ import { projectDirectory, readState, writeState } from '../connect/project.js';
8
+ import { companyTimeZone, formatNextRun, hasNextRun } from '../connect/schedule.js';
9
+ import { fetchConnector } from './connect-files.js';
7
10
  import { DEFAULT_WAIT, fetchRun, printRun, runIsClean, waitForRun } from '../connect/runs.js';
8
11
  export function connectorIdOf(options, dir) {
9
12
  if (options.connector !== undefined) {
@@ -15,21 +18,29 @@ export function connectorIdOf(options, dir) {
15
18
  }
16
19
  return state.connectorId;
17
20
  }
18
- function reportRehearsal(context, run, rehearsal, json) {
19
- if (json) {
21
+ export function reportRehearsal(context, run, rehearsal, options) {
22
+ if (options.json === true) {
20
23
  printJson(context, run);
21
24
  return;
22
25
  }
23
- printRun(context, run);
26
+ printRun(context, run, { quiet: options.quiet === true });
24
27
  printLine(context, `Tela: ${rehearsal.link}`);
25
28
  }
26
29
  export async function connectRehearse(context, dir, options, wait = DEFAULT_WAIT) {
30
+ if (options.args !== undefined && options.operation === undefined) {
31
+ throw usageError('--args vai com --operation.', 'Diga qual operação do manifesto ensaiar: --operation <chave>.');
32
+ }
33
+ const args = options.args === undefined ? undefined : readArgs(options.args);
27
34
  const connectorId = connectorIdOf(options, dir);
28
35
  const session = sessionOf(context, options);
29
36
  const response = await clientOf(context, session).request({
30
37
  method: 'POST',
31
38
  path: `/v1/connect/connectors/${connectorId}/rehearsals`,
32
- body: { scope: options.full === true ? 'full' : 'sample' }
39
+ body: {
40
+ scope: options.full === true ? 'full' : 'sample',
41
+ ...(options.operation === undefined ? {} : { operation: options.operation }),
42
+ ...(args === undefined ? {} : { args })
43
+ }
33
44
  });
34
45
  const rehearsal = response.body;
35
46
  if (options.wait === false) {
@@ -37,7 +48,7 @@ export async function connectRehearse(context, dir, options, wait = DEFAULT_WAIT
37
48
  return;
38
49
  }
39
50
  const run = await waitForRun(context, session, { connectorId, runId: rehearsal.runId }, wait);
40
- reportRehearsal(context, run, rehearsal, options.json === true);
51
+ reportRehearsal(context, run, rehearsal, options);
41
52
  if (!runIsClean(run)) {
42
53
  throw new CliError('O ensaio não passou limpo.', EXIT_CODES.failure, 'Leia o erro acima, corrija, suba outra versão e ensaie de novo.');
43
54
  }
@@ -48,7 +59,7 @@ export async function connectRun(context, runId, dir, options) {
48
59
  printJson(context, run);
49
60
  return;
50
61
  }
51
- printRun(context, run);
62
+ printRun(context, run, { quiet: options.quiet === true });
52
63
  }
53
64
  export async function connectRuns(context, dir, options) {
54
65
  const connectorId = connectorIdOf(options, dir);
@@ -69,13 +80,14 @@ export async function connectRuns(context, dir, options) {
69
80
  export async function connectChange(context, kind, dir, options) {
70
81
  await requestChange(context, sessionOf(context, options), {
71
82
  connectorId: connectorIdOf(options, dir),
72
- kind,
83
+ path: kind,
84
+ command: `nexo connect ${kind}`,
73
85
  confirm: options.confirm,
74
86
  yes: options.yes === true,
75
87
  json: options.json === true
76
88
  });
77
89
  }
78
- async function secretValue(context, name, options) {
90
+ export async function secretValue(context, name, options) {
79
91
  if (options.stdin === true) {
80
92
  return (await readAll(context.stdin)).replace(/\r?\n$/, '');
81
93
  }
@@ -115,18 +127,62 @@ export async function connectSystems(context, options) {
115
127
  }
116
128
  }
117
129
  export async function connectList(context, options) {
118
- const response = await clientOf(context, sessionOf(context, options)).request({
130
+ const session = sessionOf(context, options);
131
+ const response = await clientOf(context, session).request({
119
132
  method: 'GET',
120
133
  path: '/v1/connect/connectors'
121
134
  });
122
- const rows = Array.isArray(response.body)
123
- ? response.body
124
- : [];
135
+ const rows = Array.isArray(response.body) ? response.body : [];
125
136
  if (options.json === true) {
126
137
  printJson(context, rows);
127
138
  return;
128
139
  }
140
+ const zone = hasNextRun(rows) ? await companyTimeZone(context, session) : 'UTC';
129
141
  for (const row of rows) {
130
- printLine(context, `${row.id} ${row.status.padEnd(8)} v${String(row.headSeq)} (publicada ${row.publishedSeq === null ? '-' : String(row.publishedSeq)}) ${row.name}`);
142
+ const next = typeof row.nextRunAt === 'string' ? formatNextRun(row.nextRunAt, zone) : '-';
143
+ printLine(context, `${row.id} ${row.status.padEnd(8)} v${String(row.headSeq)} (publicada ${row.publishedSeq === null ? '-' : String(row.publishedSeq)}) próxima ${next.padEnd(11)} ${row.name}`);
144
+ }
145
+ }
146
+ export async function connectRename(context, name, dir, options) {
147
+ const newName = name.trim();
148
+ if (newName === '') {
149
+ throw usageError('Diga o nome novo do conector.', 'Use `nexo connect rename "<nome>"`.');
150
+ }
151
+ const connectorId = connectorIdOf(options, dir);
152
+ const session = sessionOf(context, options);
153
+ const before = (await fetchConnector(context, session, connectorId)).connector.name;
154
+ const response = await clientOf(context, session).request({
155
+ method: 'PATCH',
156
+ path: `/v1/connect/connectors/${connectorId}`,
157
+ body: { name: newName, ...(options.description === undefined ? {} : { description: options.description }) }
158
+ });
159
+ if (options.connector === undefined) {
160
+ const directory = projectDirectory(dir);
161
+ writeState(directory, { ...readState(directory), name: newName });
162
+ }
163
+ if (options.json === true) {
164
+ printJson(context, response.body);
165
+ return;
166
+ }
167
+ printLine(context, `Nome: "${before}" -> "${response.body.name ?? newName}".`);
168
+ if (options.description !== undefined) {
169
+ printLine(context, options.description === '' ? 'Descrição apagada.' : 'Descrição mudada.');
131
170
  }
132
171
  }
172
+ export async function connectDelete(context, dir, options) {
173
+ const connectorId = connectorIdOf(options, dir);
174
+ const session = sessionOf(context, options);
175
+ await requestChange(context, session, {
176
+ connectorId,
177
+ path: 'delete',
178
+ applyAs: { method: 'DELETE', path: '' },
179
+ command: 'nexo connect delete',
180
+ ...(options.confirm === undefined && options.json !== true
181
+ ? { typeToConfirm: (await fetchConnector(context, session, connectorId)).connector.name }
182
+ : {}),
183
+ summarize: () => ['Conector apagado, sem volta. A pasta local continua no disco: apague você, se quiser.'],
184
+ confirm: options.confirm,
185
+ yes: false,
186
+ json: options.json === true
187
+ });
188
+ }
@@ -0,0 +1,143 @@
1
+ import { clientOf, printJson, printLine, sessionOf } from '../context.js';
2
+ import { CliError, usageError } from '../errors.js';
3
+ import { EXIT_CODES } from '../exit-codes.types.js';
4
+ import { requestLocalChange } from '../connect/changes.js';
5
+ import { projectDirectory, readFiles, readState, writeFiles, writeState } from '../connect/project.js';
6
+ import { describeVersion, isVersionDiff, isVersionFiles, isVersionList, sameFiles, filesDigest } from '../connect/versions.js';
7
+ import { fetchConnector } from './connect-files.js';
8
+ import { connectorIdOf } from './connect-runs.js';
9
+ function base(connectorId) {
10
+ return `/v1/connect/connectors/${connectorId}`;
11
+ }
12
+ function seqOf(raw) {
13
+ const seq = Number(raw);
14
+ if (!Number.isInteger(seq) || seq < 1) {
15
+ throw usageError(`"${raw}" não é um número de versão.`, 'Veja as versões com `nexo connect versions`.');
16
+ }
17
+ return seq;
18
+ }
19
+ async function fetchVersion(context, session, connectorId, seq) {
20
+ const response = await clientOf(context, session).request({
21
+ method: 'GET',
22
+ path: `${base(connectorId)}/versions/${String(seq)}`
23
+ });
24
+ if (!isVersionFiles(response.body)) {
25
+ throw new Error('Versão em formato inesperado.');
26
+ }
27
+ return response.body;
28
+ }
29
+ export async function connectVersions(context, dir, options) {
30
+ const connectorId = connectorIdOf(options, dir);
31
+ const session = sessionOf(context, options);
32
+ const response = await clientOf(context, session).request({ method: 'GET', path: `${base(connectorId)}/versions` });
33
+ if (!isVersionList(response.body)) {
34
+ throw new Error('Lista de versões em formato inesperado.');
35
+ }
36
+ if (options.json === true) {
37
+ printJson(context, response.body);
38
+ return;
39
+ }
40
+ const view = (await fetchConnector(context, session, connectorId)).connector;
41
+ for (const version of response.body) {
42
+ printLine(context, describeVersion(version, { head: view.headSeq, published: view.publishedSeq }));
43
+ }
44
+ }
45
+ /** `diff <de> [para] [pasta]`: o segundo argumento que não é número é a pasta. */
46
+ function diffArguments(from, second, third) {
47
+ if (second !== undefined && !/^\d+$/.test(second) && third === undefined) {
48
+ return { from: seqOf(from), to: null, dir: second };
49
+ }
50
+ return { from: seqOf(from), to: second === undefined ? null : seqOf(second), dir: third };
51
+ }
52
+ export async function connectDiff(context, from, second, third, options) {
53
+ const wanted = diffArguments(from, second, third);
54
+ const connectorId = connectorIdOf(options, wanted.dir);
55
+ const session = sessionOf(context, options);
56
+ const to = wanted.to ?? (await fetchConnector(context, session, connectorId)).connector.headSeq;
57
+ const response = await clientOf(context, session).request({
58
+ method: 'GET',
59
+ path: `${base(connectorId)}/versions/${String(to)}/diff?against=${String(wanted.from)}`
60
+ });
61
+ if (options.json === true) {
62
+ printJson(context, response.body);
63
+ return;
64
+ }
65
+ if (!isVersionDiff(response.body)) {
66
+ throw new Error('Comparação em formato inesperado.');
67
+ }
68
+ if (response.body.same) {
69
+ printLine(context, `A versão ${String(wanted.from)} e a ${String(to)} têm o mesmo código e o mesmo manifesto.`);
70
+ return;
71
+ }
72
+ printLine(context, `Da versão ${String(wanted.from)} para a ${String(to)}:`);
73
+ if (response.body.code !== '') {
74
+ printLine(context, `--- código\n${response.body.code.trimEnd()}`);
75
+ }
76
+ if (response.body.manifest !== '') {
77
+ printLine(context, `--- manifesto\n${response.body.manifest.trimEnd()}`);
78
+ }
79
+ }
80
+ async function assertFolderUnchanged(context, session, connectorId, directory, state) {
81
+ const local = readFiles(directory);
82
+ if (state.baseDigest !== undefined) {
83
+ if (filesDigest(local) !== state.baseDigest) {
84
+ throw changedFolder();
85
+ }
86
+ return;
87
+ }
88
+ const origin = state.baseSeq === null ? null : await fetchVersion(context, session, connectorId, state.baseSeq);
89
+ if (origin === null || !sameFiles(local, origin)) {
90
+ throw changedFolder();
91
+ }
92
+ }
93
+ function changedFolder() {
94
+ return new CliError('A pasta tem mudanças que não foram para o Nexo; restaurar as apagaria.', EXIT_CODES.failure, 'Suba com `nexo connect push -m "..."`, ou use --force para descartá-las.');
95
+ }
96
+ function restorePreview(target, seq) {
97
+ return {
98
+ title: `Voltar à versão ${String(seq)}${target.summary === null ? '' : `: ${target.summary}`}`,
99
+ changes: [
100
+ `Escrita em ${target.createdAt.slice(0, 16).replace('T', ' ')} (${target.origin}).`,
101
+ 'O Nexo guarda isto como uma versão nova, em edição; o que está publicado não muda.',
102
+ 'connector.ts e manifest.json desta pasta são reescritos com ela.'
103
+ ]
104
+ };
105
+ }
106
+ async function applyRestore(context, session, where, target) {
107
+ const response = await clientOf(context, session).request({
108
+ method: 'POST',
109
+ path: `${base(where.connectorId)}/versions/${String(target.seq)}/restore`
110
+ });
111
+ const created = response.body.seq ?? target.seq;
112
+ writeFiles(where.directory, { code: target.code, manifest: target.manifest });
113
+ writeState(where.directory, {
114
+ ...where.state,
115
+ connectorId: where.connectorId,
116
+ baseSeq: created,
117
+ baseDigest: filesDigest({ code: target.code, manifest: target.manifest })
118
+ });
119
+ return response;
120
+ }
121
+ export async function connectRestore(context, seqText, dir, options) {
122
+ const seq = seqOf(seqText);
123
+ const directory = projectDirectory(dir);
124
+ const state = readState(directory);
125
+ const connectorId = connectorIdOf(options, dir);
126
+ const session = sessionOf(context, options);
127
+ if (options.force !== true) {
128
+ await assertFolderUnchanged(context, session, connectorId, directory, state);
129
+ }
130
+ const target = await fetchVersion(context, session, connectorId, seq);
131
+ await requestLocalChange(context, {
132
+ preview: restorePreview(target, seq),
133
+ command: `nexo connect restore ${String(seq)}`,
134
+ confirmed: options.confirm === true,
135
+ yes: options.yes === true,
136
+ json: options.json === true,
137
+ apply: () => applyRestore(context, session, { connectorId, directory, state }, target),
138
+ report: (body) => {
139
+ const created = body.seq;
140
+ printLine(context, `A versão ${String(seq)} voltou como a versão ${String(created ?? '?')}, em edição. Ensaie com \`nexo connect rehearse\` e publique.`);
141
+ }
142
+ });
143
+ }
@@ -0,0 +1,225 @@
1
+ import { clientOf, printJson, printLine, printNotice, sessionOf } from '../context.js';
2
+ import { usageError } from '../errors.js';
3
+ import { ask, requestLocalChange } from '../connect/changes.js';
4
+ import { readArgs } from '../connect/operation-args.js';
5
+ import { appliedOf, catalogLines, catalogOf, outputLines, previewOf, queryOf, writeLines } from '../erp/operations.js';
6
+ const REPEATED_MESSAGE = 'Esta confirmação já tinha sido aplicada: nada foi gravado de novo. Esta é a resposta da primeira vez.';
7
+ const NOT_FOUND_HINT = 'Veja as operações que você alcança com `nexo erp list`.';
8
+ async function catalog(context, session, search) {
9
+ const response = await clientOf(context, session).request({
10
+ method: 'GET',
11
+ path: '/v1/erp/operations',
12
+ ...(search === undefined ? {} : { query: { search } })
13
+ });
14
+ return catalogOf(response);
15
+ }
16
+ /** O id (`<conector>:<chave>`) vai direto; uma chave solta é resolvida pela lista. Não usa a busca da API (ela casa por palavras, não pela chave): pega a lista e compara a chave. */
17
+ export async function resolveOperation(context, session, target) {
18
+ if (target.includes(':')) {
19
+ return target;
20
+ }
21
+ const all = await catalog(context, session, undefined);
22
+ const found = all.operacoes.filter((operation) => operation.key === target);
23
+ if (found.length === 0) {
24
+ throw usageError(`Não achei a operação ${target} entre as que você pode usar.`, all.total > all.mostrando
25
+ ? `A lista traz só ${String(all.mostrando)} de ${String(all.total)}: use o id completo (<conector>:<chave>) ou veja com \`nexo erp list ${target}\`.`
26
+ : NOT_FOUND_HINT);
27
+ }
28
+ if (found.length > 1) {
29
+ throw usageError(`A chave ${target} existe em mais de um conector: ${found.map((operation) => operation.id).join(', ')}.`, 'Use o id completo (<conector>:<chave>).');
30
+ }
31
+ return found[0]?.id ?? target;
32
+ }
33
+ export async function erpList(context, search, options) {
34
+ const result = await catalog(context, sessionOf(context, options), search);
35
+ if (options.json === true) {
36
+ printJson(context, result);
37
+ return;
38
+ }
39
+ if (result.operacoes.length === 0) {
40
+ printLine(context, result.aviso ?? 'Nenhuma operação de ERP para você.');
41
+ return;
42
+ }
43
+ for (const line of catalogLines(result)) {
44
+ printLine(context, line);
45
+ }
46
+ if (result.total > result.mostrando) {
47
+ printLine(context, `Mostrando ${String(result.mostrando)} de ${String(result.total)}${result.aviso === undefined ? '' : `. ${result.aviso}`}`);
48
+ }
49
+ }
50
+ function argsOf(options) {
51
+ return options.args === undefined ? {} : readArgs(options.args);
52
+ }
53
+ export async function erpQuery(context, target, options) {
54
+ const args = argsOf(options);
55
+ const session = sessionOf(context, options);
56
+ const id = await resolveOperation(context, session, target);
57
+ const response = await clientOf(context, session).request({
58
+ method: 'POST',
59
+ path: `/v1/erp/operations/${encodeURIComponent(id)}/query`,
60
+ body: { args }
61
+ });
62
+ if (options.json === true) {
63
+ printJson(context, response.body);
64
+ return;
65
+ }
66
+ const answer = queryOf(response);
67
+ printLine(context, `Resultado de ${answer.id}${answer.emCache ? ' (da memória do conector, sem ir ao outro sistema)' : ''}:`);
68
+ for (const line of outputLines(answer.saida)) {
69
+ printLine(context, line);
70
+ }
71
+ }
72
+ function shellQuote(text) {
73
+ return `'${text.replaceAll("'", `'\\''`)}'`;
74
+ }
75
+ function showPreview(context, preview) {
76
+ printLine(context, `${preview.acao} (${preview.conector}) escreveria no outro sistema:`);
77
+ const writes = writeLines(preview.escritas);
78
+ if (writes.length === 0) {
79
+ printLine(context, ' (nada)');
80
+ }
81
+ for (const line of writes) {
82
+ printLine(context, line);
83
+ }
84
+ const output = outputLines(preview.saidaDoEnsaio);
85
+ if (output.length > 0) {
86
+ printLine(context, 'Resultado do ensaio:');
87
+ for (const line of output) {
88
+ printLine(context, line);
89
+ }
90
+ }
91
+ if (preview.aviso !== undefined) {
92
+ printLine(context, preview.aviso);
93
+ }
94
+ }
95
+ async function applyAction(context, session, request) {
96
+ const response = await clientOf(context, session).request({
97
+ method: 'POST',
98
+ path: `/v1/erp/operations/${encodeURIComponent(request.id)}/apply`,
99
+ body: { args: request.args, confirmationToken: request.token }
100
+ });
101
+ const applied = appliedOf(response);
102
+ if (request.json) {
103
+ if (applied.repetida) {
104
+ printNotice(context, REPEATED_MESSAGE);
105
+ }
106
+ printJson(context, response.body);
107
+ return;
108
+ }
109
+ printLine(context, applied.repetida ? REPEATED_MESSAGE : 'Feito.');
110
+ printLine(context, `Situação: ${applied.situacao}`);
111
+ for (const line of outputLines(applied.saida)) {
112
+ printLine(context, line);
113
+ }
114
+ }
115
+ async function decideAction(context, session, request) {
116
+ showPreview(context, request.preview);
117
+ const token = request.preview.confirmation?.token;
118
+ if (token === undefined) {
119
+ printNotice(context, 'Esta ação não pode gravar agora: nada foi aplicado.');
120
+ return;
121
+ }
122
+ if (context.stdin.isTTY !== true) {
123
+ printNotice(context, 'Mostre isto à pessoa. Depois do sim dela, aplique uma vez:');
124
+ printNotice(context, ` nexo erp action ${request.id} --args ${shellQuote(JSON.stringify(request.args))} --confirm ${token}`);
125
+ return;
126
+ }
127
+ if (await ask(context, 'Confirma? (s/N) ')) {
128
+ await applyAction(context, session, { id: request.id, args: request.args, token, json: false });
129
+ return;
130
+ }
131
+ printNotice(context, 'Nada mudou.');
132
+ }
133
+ /** `-y` não existe aqui de propósito: gravar no sistema do cliente pede o sim da pessoa, ou o token da prévia que ela viu. */
134
+ export async function erpAction(context, target, options) {
135
+ const args = argsOf(options);
136
+ const session = sessionOf(context, options);
137
+ const id = await resolveOperation(context, session, target);
138
+ if (typeof options.confirm === 'string') {
139
+ await applyAction(context, session, { id, args, token: options.confirm, json: options.json === true });
140
+ return;
141
+ }
142
+ const response = await clientOf(context, session).request({
143
+ method: 'POST',
144
+ path: `/v1/erp/operations/${encodeURIComponent(id)}/preview`,
145
+ body: { args }
146
+ });
147
+ const preview = previewOf(response);
148
+ if (options.json === true) {
149
+ printJson(context, response.body);
150
+ return;
151
+ }
152
+ await decideAction(context, session, { id, args, preview });
153
+ }
154
+ const NOTE_MAX_CHARS = 500;
155
+ function noteBase(id) {
156
+ const split = id.indexOf(':');
157
+ return {
158
+ path: `/v1/connect/connectors/${id.slice(0, split)}/operations/${encodeURIComponent(id.slice(split + 1))}/notes`,
159
+ key: id.slice(split + 1)
160
+ };
161
+ }
162
+ async function currentNote(context, session, path, field) {
163
+ const response = await clientOf(context, session).request({ method: 'GET', path });
164
+ const notes = response.body.notes;
165
+ const found = (Array.isArray(notes) ? notes : []).find((note) => note.field === field);
166
+ return found?.text ?? null;
167
+ }
168
+ function noteCommand(id, options, text) {
169
+ const field = options.field === undefined ? '' : ` --field ${shellQuote(options.field.trim())}`;
170
+ return `nexo erp note ${id}${field} ${text === undefined ? '--remove' : shellQuote(text)}`;
171
+ }
172
+ function checkNoteInput(text, options) {
173
+ if (options.remove === true && text !== undefined) {
174
+ throw usageError('Use o texto ou --remove, não os dois.');
175
+ }
176
+ if (options.remove !== true && (text === undefined || text.trim() === '')) {
177
+ throw usageError('Falta o texto da nota.', 'Escreva `nexo erp note <operação> "<texto>"`, ou apague com --remove.');
178
+ }
179
+ if (text !== undefined && text.trim().length > NOTE_MAX_CHARS) {
180
+ throw usageError(`A nota passa de ${String(NOTE_MAX_CHARS)} caracteres.`, 'Encurte o texto.');
181
+ }
182
+ }
183
+ function noteRequest(path, field, text) {
184
+ return text === null
185
+ ? { method: 'DELETE', path, ...(field === null ? {} : { query: { field } }) }
186
+ : { method: 'PUT', path, body: { ...(field === null ? {} : { field }), text } };
187
+ }
188
+ function fieldOf(options) {
189
+ return options.field?.trim() ?? null;
190
+ }
191
+ function afterOf(text, options) {
192
+ return options.remove === true ? null : (text?.trim() ?? null);
193
+ }
194
+ function unchangedMessage(where, after) {
195
+ return after === null ? `Não há nota em ${where} para apagar.` : `A nota de ${where} já tem este texto.`;
196
+ }
197
+ /** Sem `-y`: o assistente lê a nota como verdade da empresa, então só a pessoa (terminal) ou o `--confirm` do script grava. */
198
+ export async function erpNote(context, target, text, options) {
199
+ checkNoteInput(text, options);
200
+ const session = sessionOf(context, options);
201
+ const id = await resolveOperation(context, session, target);
202
+ const { path, key } = noteBase(id);
203
+ const field = fieldOf(options);
204
+ const before = await currentNote(context, session, path, field);
205
+ const after = afterOf(text, options);
206
+ const where = `${key}${field === null ? '' : ` / ${field}`}`;
207
+ if (before === after) {
208
+ printLine(context, unchangedMessage(where, after));
209
+ return;
210
+ }
211
+ await requestLocalChange(context, {
212
+ preview: {
213
+ title: `Nota da empresa em ${where}`,
214
+ changes: [`Antes: ${before ?? '(sem nota)'}`, `Depois: ${after ?? '(sem nota)'}`]
215
+ },
216
+ command: noteCommand(id, options, after === null ? undefined : after),
217
+ confirmed: options.confirm === true,
218
+ yes: false,
219
+ json: options.json === true,
220
+ apply: () => clientOf(context, session).request(noteRequest(path, field, after)),
221
+ report: () => {
222
+ printLine(context, after === null ? 'Nota apagada.' : 'Nota gravada.');
223
+ }
224
+ });
225
+ }
@@ -1,4 +1,4 @@
1
- import { DEFAULT_ENVIRONMENT, ENVIRONMENTS, TOKENS_PAGE, environmentNamed, normalizedApiUrl } from '../config/environments.js';
1
+ import { TOKENS_PAGE, appUrlOf, environmentNamed, normalizedApiUrl } from '../config/environments.js';
2
2
  import { profileName } from '../config/session.js';
3
3
  import { printJson, printLine, printNotice } from '../context.js';
4
4
  import { usageError } from '../errors.js';
@@ -6,10 +6,6 @@ import { readAll, readSecret } from '../input/read-input.js';
6
6
  import { LOGIN_TIMEOUT_MS, browserLogin } from './login-browser.js';
7
7
  import { describeMe, fetchMe } from './whoami.js';
8
8
  const PERSONAL_TOKEN = /^nexo_pat_[A-Za-z0-9]{38}$/;
9
- function appUrlOf(apiUrl) {
10
- const known = Object.values(ENVIRONMENTS).find((environment) => environment.apiUrl === apiUrl);
11
- return (known ?? DEFAULT_ENVIRONMENT).appUrl;
12
- }
13
9
  function targetApiUrl(options) {
14
10
  if (options.apiUrl !== undefined) {
15
11
  return normalizedApiUrl(options.apiUrl);
@@ -8,6 +8,7 @@ export const DEFAULT_ENVIRONMENT = {
8
8
  appUrl: 'https://app.nexo.winningsales.com.br'
9
9
  };
10
10
  export const TOKENS_PAGE = '/settings/api-tokens';
11
+ export const AGENT_PAIRING_PAGE = '/settings/connections/connectors?tab=agent&foco=parear';
11
12
  export function environmentNamed(name) {
12
13
  const environment = ENVIRONMENTS[name];
13
14
  if (environment === undefined) {
@@ -31,3 +32,12 @@ export function normalizedApiUrl(raw) {
31
32
  function isLoopback(hostname) {
32
33
  return hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '[::1]';
33
34
  }
35
+ /** O app do ambiente da API, ou `null` quando a API não é de nenhum ambiente conhecido (localhost, staging). */
36
+ export function knownAppUrl(apiUrl) {
37
+ const known = Object.values(ENVIRONMENTS).find((environment) => environment.apiUrl === apiUrl);
38
+ return known?.appUrl ?? null;
39
+ }
40
+ /** O endereço do app para o `nexo login`; um ambiente desconhecido cai no de produção. */
41
+ export function appUrlOf(apiUrl) {
42
+ return knownAppUrl(apiUrl) ?? DEFAULT_ENVIRONMENT.appUrl;
43
+ }
@@ -0,0 +1,117 @@
1
+ import { CliError } from '../errors.js';
2
+ import { EXIT_CODES } from '../exit-codes.types.js';
3
+ export const DEFAULT_PATIENCE = { intervalMs: 3000, timeoutMs: 10 * 60_000 };
4
+ /**
5
+ * Confere `check` de tempos em tempos até ele devolver algo, ou o limite passar.
6
+ * O relógio só mede a espera: o que vale é o estado lido, nunca a hora da máquina contra a do servidor.
7
+ */
8
+ export async function pollUntil(check, pause, patience, onTimeout) {
9
+ const now = patience.now ?? Date.now;
10
+ const deadline = now() + patience.timeoutMs;
11
+ for (;;) {
12
+ const found = await check();
13
+ if (found !== null) {
14
+ return found;
15
+ }
16
+ if (now() >= deadline) {
17
+ throw onTimeout();
18
+ }
19
+ await pause(patience.intervalMs);
20
+ }
21
+ }
22
+ export function timedOut(message, hint) {
23
+ return () => new CliError(message, EXIT_CODES.failure, hint);
24
+ }
25
+ function fieldsOf(value) {
26
+ return typeof value === 'object' && value !== null && !Array.isArray(value) ? value : null;
27
+ }
28
+ function strings(value) {
29
+ return Array.isArray(value) && value.every((item) => typeof item === 'string');
30
+ }
31
+ export function isSecretList(value) {
32
+ return (Array.isArray(value) &&
33
+ value.every((item) => {
34
+ const fields = fieldsOf(item);
35
+ return fields !== null && typeof fields.name === 'string' && typeof fields.filled === 'boolean';
36
+ }));
37
+ }
38
+ export function isWebhook(value) {
39
+ const fields = fieldsOf(value);
40
+ return fields !== null && typeof fields.url === 'string' && typeof fields.secretSet === 'boolean';
41
+ }
42
+ export function isOAuthStatus(value) {
43
+ const fields = fieldsOf(value);
44
+ return fields !== null && typeof fields.required === 'boolean' && typeof fields.status === 'string' && typeof fields.app === 'string';
45
+ }
46
+ export function isOAuthAuthorization(value) {
47
+ const fields = fieldsOf(value);
48
+ return fields !== null && typeof fields.authorizeUrl === 'string';
49
+ }
50
+ function isSftpKey(value) {
51
+ const fields = fieldsOf(value);
52
+ return fields !== null && typeof fields.host === 'string' && typeof fields.port === 'number' && typeof fields.fingerprint === 'string';
53
+ }
54
+ export function isSftpKeyList(value) {
55
+ return Array.isArray(value) && value.every(isSftpKey);
56
+ }
57
+ export function isMailAddress(value) {
58
+ const fields = fieldsOf(value);
59
+ return fields !== null && (fields.address === null || typeof fields.address === 'string') && strings(fields.senders);
60
+ }
61
+ export function isMailFileList(value) {
62
+ return (Array.isArray(value) &&
63
+ value.every((item) => {
64
+ const fields = fieldsOf(item);
65
+ return fields !== null && typeof fields.name === 'string' && typeof fields.status === 'string';
66
+ }));
67
+ }
68
+ export function describeSecret(slot) {
69
+ return `${slot.name.padEnd(28)} ${slot.filled ? `preenchido${slot.setAt === null ? '' : ` desde ${slot.setAt}`}` : 'faltando'}`;
70
+ }
71
+ export function describeWebhook(webhook) {
72
+ return [
73
+ `URL: ${webhook.url} (POST com corpo JSON)`,
74
+ `Assinatura: o cabeçalho ${webhook.signatureHeader} leva sha256= e o HMAC-SHA256 de "<timestamp>.<corpo>" com o segredo; o cabeçalho ${webhook.timestampHeader} leva a hora da chamada, em segundos (5 minutos de tolerância).`,
75
+ webhook.secretSet ? 'Segredo: definido.' : 'Segredo: ainda não definido. Defina com `nexo connect webhook secret set --generate`.'
76
+ ];
77
+ }
78
+ const APP_NAMES = {
79
+ nexo: 'o app do Nexo',
80
+ own: 'o app da própria empresa',
81
+ none: 'nenhum (a empresa precisa trazer o app dela)'
82
+ };
83
+ const STATUS_NAMES = {
84
+ unauthorized: 'não autorizado',
85
+ authorized: 'autorizado',
86
+ revoked: 'revogado pelo outro sistema'
87
+ };
88
+ export function describeOAuth(oauth) {
89
+ return [
90
+ oauth.required ? 'A versão em edição pede OAuth.' : 'A versão em edição não pede OAuth.',
91
+ `Sistema: ${oauth.systemName ?? 'fora do catálogo'}. App: ${APP_NAMES[oauth.app]}${oauth.clientId === null ? '' : ` (client id ${oauth.clientId})`}.`,
92
+ `Estado: ${STATUS_NAMES[oauth.status]}${oauth.authorizedAt === null ? '' : `, autorizado em ${oauth.authorizedAt}`}${oauth.expiresAt === null ? '' : `, o token vale até ${oauth.expiresAt} e o Nexo o renova`}.`,
93
+ ...(oauth.revokedReason === null
94
+ ? []
95
+ : [`Motivo da revogação: ${oauth.revokedReason}. Autorize de novo com \`nexo connect oauth authorize\`.`])
96
+ ];
97
+ }
98
+ export function describeSftpKey(key) {
99
+ return `${key.host}:${String(key.port)} ${key.fingerprint} guardada em ${key.pinnedAt}`;
100
+ }
101
+ export function describeMail(mail) {
102
+ return [
103
+ mail.address === null ? 'Endereço: ainda não gerado. Gere com `nexo connect email renew`.' : `Endereço: ${mail.address}`,
104
+ mail.senders.length === 0 ? 'Quem pode mandar: ninguém declarado no manifesto.' : `Quem pode mandar: ${mail.senders.join(', ')}`
105
+ ];
106
+ }
107
+ const IGNORED_REASONS = {
108
+ not_spreadsheet: 'não é planilha (.csv, .tsv, .txt ou .xlsx)',
109
+ too_large: 'passou do limite de tamanho',
110
+ empty: 'sem conteúdo'
111
+ };
112
+ export function describeMailFile(file) {
113
+ const left = file.status === 'received'
114
+ ? 'recebido'
115
+ : `deixado de fora: ${IGNORED_REASONS[file.ignoredReason ?? ''] ?? file.ignoredReason ?? '?'}`;
116
+ return `${file.receivedAt} ${file.name} ${String(file.sizeBytes)} bytes ${left}`;
117
+ }