@winning-sales/nexo 0.5.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.
Files changed (36) hide show
  1. package/README.md +119 -1
  2. package/assets/skills/nexo-api/SKILL.md +2 -1
  3. package/assets/skills/nexo-connect/SKILL.md +20 -5
  4. package/dist/commands/connect-access.js +279 -0
  5. package/dist/commands/connect-agents.js +132 -0
  6. package/dist/commands/connect-build.js +172 -0
  7. package/dist/commands/connect-execute.js +85 -0
  8. package/dist/commands/connect-files.js +23 -7
  9. package/dist/commands/connect-hosts.js +177 -0
  10. package/dist/commands/connect-retained.js +134 -0
  11. package/dist/commands/connect-runs.js +70 -14
  12. package/dist/commands/connect-versions.js +143 -0
  13. package/dist/commands/erp.js +225 -0
  14. package/dist/commands/login.js +1 -5
  15. package/dist/commands/mcp.js +2 -1
  16. package/dist/commands/platform.js +98 -0
  17. package/dist/commands/whoami.js +9 -1
  18. package/dist/config/environments.js +10 -0
  19. package/dist/connect/access.js +117 -0
  20. package/dist/connect/agents.js +71 -0
  21. package/dist/connect/changes.js +68 -7
  22. package/dist/connect/operation-args.js +30 -0
  23. package/dist/connect/retained.js +106 -0
  24. package/dist/connect/runs.js +65 -10
  25. package/dist/connect/schedule.js +38 -0
  26. package/dist/connect/template.js +23 -0
  27. package/dist/connect/versions.js +60 -0
  28. package/dist/erp/operations.js +87 -0
  29. package/dist/http/problem.js +22 -1
  30. package/dist/program-connect-access.js +134 -0
  31. package/dist/program-connect.js +256 -4
  32. package/dist/program-erp.js +44 -0
  33. package/dist/program.js +22 -1
  34. package/dist/tools/tool-manifest.js +65 -0
  35. package/package.json +1 -1
  36. package/reference.json +1394 -54
@@ -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);
@@ -11,7 +11,8 @@ function isObject(value) {
11
11
  function serversOf(apiUrl) {
12
12
  return [
13
13
  { name: 'nexo', url: `${apiUrl}/mcp` },
14
- { name: 'nexo-connect', url: `${apiUrl}/connect/mcp` }
14
+ { name: 'nexo-connect', url: `${apiUrl}/connect/mcp` },
15
+ { name: 'nexo-admin', url: `${apiUrl}/admin/mcp` }
15
16
  ];
16
17
  }
17
18
  function apiUrlOf(context, options) {
@@ -0,0 +1,98 @@
1
+ import { clientOf, printJson, printLine, printNotice, sessionOf } from '../context.js';
2
+ import { usageError } from '../errors.js';
3
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
4
+ function isCompany(value) {
5
+ if (typeof value !== 'object' || value === null) {
6
+ return false;
7
+ }
8
+ const fields = value;
9
+ return typeof fields.id === 'string' && typeof fields.name === 'string';
10
+ }
11
+ async function fetchCompanies(context, options, search) {
12
+ const response = await clientOf(context, sessionOf(context, options)).request({
13
+ method: 'GET',
14
+ path: '/v1/platform/companies',
15
+ ...(search === undefined || search.trim() === '' ? {} : { query: { search: search.trim() } })
16
+ });
17
+ const list = response.body?.companies;
18
+ if (!Array.isArray(list) || !list.every(isCompany)) {
19
+ throw new Error('Resposta inesperada de /v1/platform/companies.');
20
+ }
21
+ return list;
22
+ }
23
+ function lineOf(company) {
24
+ return `${company.id} ${company.name}${company.suspended ? ' (suspensa por cobrança: só leitura)' : ''}`;
25
+ }
26
+ export async function companies(context, search, options) {
27
+ const list = await fetchCompanies(context, options, search);
28
+ if (options.json === true) {
29
+ printJson(context, { companies: list });
30
+ return;
31
+ }
32
+ if (list.length === 0) {
33
+ printNotice(context, search === undefined ? 'Nenhuma empresa.' : `Nenhuma empresa com "${search}" no nome.`);
34
+ return;
35
+ }
36
+ list.forEach((company) => {
37
+ printLine(context, lineOf(company));
38
+ });
39
+ printNotice(context, 'Escolha uma com `nexo use <id ou nome>`.');
40
+ }
41
+ async function resolveCompany(context, target, options) {
42
+ const trimmed = target.trim();
43
+ const list = await fetchCompanies(context, options, UUID.test(trimmed) ? undefined : trimmed);
44
+ const byId = list.find((company) => company.id.toLowerCase() === trimmed.toLowerCase());
45
+ if (byId !== undefined) {
46
+ return byId;
47
+ }
48
+ if (UUID.test(trimmed)) {
49
+ throw usageError(`Nenhuma empresa com o id ${trimmed}.`, 'Veja as opções com `nexo companies`.');
50
+ }
51
+ const exact = list.filter((company) => company.name.toLowerCase() === trimmed.toLowerCase());
52
+ const matches = exact.length === 1 ? exact : list;
53
+ if (matches.length === 1 && matches[0] !== undefined) {
54
+ return matches[0];
55
+ }
56
+ if (matches.length === 0) {
57
+ throw usageError(`Nenhuma empresa casa com "${trimmed}".`, 'Veja as opções com `nexo companies`.');
58
+ }
59
+ throw usageError(`"${trimmed}" casa com ${String(matches.length)} empresas; não escolhi nenhuma:\n${matches.map((company) => ` ${lineOf(company)}`).join('\n')}`, 'Rode `nexo use <id>` com o id da que você quer.');
60
+ }
61
+ async function leaveCompany(context, options) {
62
+ await clientOf(context, sessionOf(context, options)).request({ method: 'DELETE', path: '/v1/platform/active-company' });
63
+ if (options.json === true) {
64
+ printJson(context, { activeCompany: null });
65
+ return;
66
+ }
67
+ printLine(context, 'Nenhuma empresa escolhida.');
68
+ }
69
+ async function chooseCompany(context, target, options) {
70
+ const company = await resolveCompany(context, target, options);
71
+ const response = await clientOf(context, sessionOf(context, options)).request({
72
+ method: 'PUT',
73
+ path: '/v1/platform/active-company',
74
+ body: { companyId: company.id }
75
+ });
76
+ if (options.json === true) {
77
+ printJson(context, response.body);
78
+ return;
79
+ }
80
+ printLine(context, `Empresa ativa: ${company.name} (${company.id})`);
81
+ if (company.suspended) {
82
+ printNotice(context, 'A empresa está suspensa por cobrança: dentro dela, a conexão só lê.');
83
+ }
84
+ }
85
+ export async function useCompany(context, target, options) {
86
+ const named = target !== undefined && target.trim() !== '';
87
+ if (options.none === true && named) {
88
+ throw usageError('Use `nexo use --none` sem empresa, ou `nexo use <empresa>`, não os dois.');
89
+ }
90
+ if (options.none === true) {
91
+ await leaveCompany(context, options);
92
+ return;
93
+ }
94
+ if (target === undefined || !named) {
95
+ throw usageError('Diga a empresa: `nexo use <id ou nome>`, ou `nexo use --none` para sair dela.', 'Veja as opções com `nexo companies`.');
96
+ }
97
+ await chooseCompany(context, target, options);
98
+ }
@@ -17,12 +17,20 @@ export async function fetchMe(context, session) {
17
17
  }
18
18
  return response.body;
19
19
  }
20
+ function companyLines(me) {
21
+ if (me.platform?.global !== true) {
22
+ return [`Empresa: ${me.company.name}`];
23
+ }
24
+ return me.platform.activeCompanyId === null
25
+ ? ['Conexão de plataforma: nenhuma empresa escolhida; rode `nexo companies` e `nexo use <empresa>`']
26
+ : [`Conexão de plataforma, empresa ativa: ${me.company.name} (${me.platform.activeCompanyId})`];
27
+ }
20
28
  export function describeMe(me, session) {
21
29
  const expires = new Date(me.credential.expiresAt).toLocaleDateString('pt-BR', { timeZone: me.company.timezone });
22
30
  const source = session.source === 'env' ? 'NEXO_TOKEN' : `perfil ${session.profile}`;
23
31
  return [
24
32
  `${me.user.name} <${me.user.email}>, ${profilesOf(me)}`,
25
- `Empresa: ${me.company.name}`,
33
+ ...companyLines(me),
26
34
  `Credencial: ${me.credential.name} (${source}), vale até ${expires}`,
27
35
  `Escopos: ${me.credential.scopes.join(', ')}`,
28
36
  `API: ${session.apiUrl}`