@winning-sales/nexo 0.6.0 → 0.7.1

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,134 @@
1
+ import { clientOf, printJson, printLine, sessionOf } from '../context.js';
2
+ import { requestChange, requestLocalChange } from '../connect/changes.js';
3
+ import { usageError } from '../errors.js';
4
+ import { readFixFile, describeItem, describeWrites, fixFrom, fixPreview, isExternalWrites, isQuarantineList } from '../connect/retained.js';
5
+ import { connectorIdOf } from './connect-runs.js';
6
+ function base(connectorId) {
7
+ return `/v1/connect/connectors/${connectorId}`;
8
+ }
9
+ function tokenOf(options) {
10
+ return typeof options.confirm === 'string' ? options.confirm : undefined;
11
+ }
12
+ async function openItems(context, options, dir) {
13
+ const response = await clientOf(context, sessionOf(context, options)).request({
14
+ method: 'GET',
15
+ path: `${base(connectorIdOf(options, dir))}/quarantine`
16
+ });
17
+ if (!isQuarantineList(response.body)) {
18
+ throw new Error('Quarentena em formato inesperado.');
19
+ }
20
+ return response.body;
21
+ }
22
+ export async function quarantineList(context, dir, options) {
23
+ const items = await openItems(context, options, dir);
24
+ if (options.json === true) {
25
+ printJson(context, items);
26
+ return;
27
+ }
28
+ if (items.length === 0) {
29
+ printLine(context, 'Nenhum registro aberto na quarentena.');
30
+ return;
31
+ }
32
+ for (const line of items.flatMap(describeItem)) {
33
+ printLine(context, line);
34
+ }
35
+ }
36
+ async function itemOf(context, itemId, dir, options) {
37
+ const item = (await openItems(context, options, dir)).find((found) => found.id === itemId);
38
+ if (item === undefined) {
39
+ throw usageError(`O registro ${itemId} não está aberto na quarentena.`, 'Veja os abertos com `nexo connect quarantine`.');
40
+ }
41
+ return item;
42
+ }
43
+ export async function quarantineFix(context, itemId, dir, options) {
44
+ const fix = fixFrom(options.set ?? [], options.file === undefined ? null : readFixFile(options.file));
45
+ const item = await itemOf(context, itemId, dir, options);
46
+ const connectorId = connectorIdOf(options, dir);
47
+ await requestLocalChange(context, {
48
+ preview: fixPreview(item, fix),
49
+ command: `nexo connect quarantine fix ${itemId}`,
50
+ confirmed: options.confirm === true,
51
+ yes: options.yes === true,
52
+ json: options.json === true,
53
+ apply: () => clientOf(context, sessionOf(context, options)).request({
54
+ method: 'PATCH',
55
+ path: `${base(connectorId)}/quarantine/${encodeURIComponent(itemId)}`,
56
+ body: fix
57
+ })
58
+ });
59
+ }
60
+ export async function quarantineDiscard(context, itemId, dir, options) {
61
+ const item = await itemOf(context, itemId, dir, options);
62
+ const connectorId = connectorIdOf(options, dir);
63
+ await requestLocalChange(context, {
64
+ preview: {
65
+ title: `Descartar o registro ${item.id} (${item.objectType}) da quarentena`,
66
+ changes: [...describeItem(item).slice(1), 'Ele sai da quarentena sem ir para o Nexo.']
67
+ },
68
+ command: `nexo connect quarantine discard ${itemId}`,
69
+ confirmed: options.confirm === true,
70
+ yes: options.yes === true,
71
+ json: options.json === true,
72
+ apply: () => clientOf(context, sessionOf(context, options)).request({
73
+ method: 'POST',
74
+ path: `${base(connectorId)}/quarantine/${encodeURIComponent(itemId)}/discard`
75
+ })
76
+ });
77
+ }
78
+ function reprocessSummary(body) {
79
+ const result = body;
80
+ return [
81
+ `Resolvidos: ${String(result.resolved ?? 0)}, recusados de novo: ${String(result.refused ?? 0)}, para o próximo: ${String(result.left ?? 0)}.`,
82
+ ...(result.status === 'running' ? ['A execução continua; veja `nexo connect runs`.'] : [])
83
+ ];
84
+ }
85
+ export async function quarantineReprocess(context, dir, options) {
86
+ await requestChange(context, sessionOf(context, options), {
87
+ connectorId: connectorIdOf(options, dir),
88
+ path: 'quarantine/reprocess',
89
+ body: {},
90
+ command: 'nexo connect quarantine reprocess',
91
+ summarize: reprocessSummary,
92
+ confirm: tokenOf(options),
93
+ yes: options.yes === true,
94
+ json: options.json === true
95
+ });
96
+ }
97
+ export async function writesList(context, dir, options) {
98
+ const response = await clientOf(context, sessionOf(context, options)).request({
99
+ method: 'GET',
100
+ path: `${base(connectorIdOf(options, dir))}/external-writes`
101
+ });
102
+ if (!isExternalWrites(response.body)) {
103
+ throw new Error('Escritas retidas em formato inesperado.');
104
+ }
105
+ if (options.json === true) {
106
+ printJson(context, response.body);
107
+ return;
108
+ }
109
+ const writes = response.body;
110
+ for (const line of describeWrites(writes)) {
111
+ printLine(context, line);
112
+ }
113
+ }
114
+ export async function writesConfirm(context, id, dir, options) {
115
+ await requestChange(context, sessionOf(context, options), {
116
+ connectorId: connectorIdOf(options, dir),
117
+ path: `external-writes/${encodeURIComponent(id)}/confirm`,
118
+ command: `nexo connect writes confirm ${id}`,
119
+ confirm: tokenOf(options),
120
+ yes: options.yes === true,
121
+ json: options.json === true
122
+ });
123
+ }
124
+ export async function writeHost(context, action, host, dir, options) {
125
+ await requestChange(context, sessionOf(context, options), {
126
+ connectorId: connectorIdOf(options, dir),
127
+ path: `write-hosts/${action}`,
128
+ body: { host },
129
+ command: `nexo connect write-hosts ${action} ${host}`,
130
+ confirm: tokenOf(options),
131
+ yes: options.yes === true,
132
+ json: options.json === true
133
+ });
134
+ }
@@ -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);