@winning-sales/nexo 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,144 @@
1
+ import { clientOf, printJson, printLine, printNotice, sessionOf } from '../context.js';
2
+ const MODE_LABELS = {
3
+ self_service: 'autoatendimento (paga pelos assentos usados, depois do ciclo)',
4
+ seats: 'assentos pré-pagos'
5
+ };
6
+ const STANDING_LABELS = {
7
+ active: 'em dia',
8
+ past_due: 'em atraso (a conta vira só leitura se nada for pago)',
9
+ suspended: 'suspensa (só leitura, a IA parada)'
10
+ };
11
+ const INVOICE_LABELS = { issued: 'emitida', overdue: 'vencida', paid: 'paga' };
12
+ const METHOD_LABELS = { card: 'cartão', pix: 'Pix', boleto: 'boleto' };
13
+ export function brl(cents) {
14
+ if (cents === null) {
15
+ return '—';
16
+ }
17
+ return (cents / 100).toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' });
18
+ }
19
+ export function day(value) {
20
+ if (value === null) {
21
+ return '—';
22
+ }
23
+ const [year, month, date] = value.slice(0, 10).split('-');
24
+ return `${date ?? ''}/${month ?? ''}/${year ?? ''}`;
25
+ }
26
+ async function get(context, options, path) {
27
+ const response = await clientOf(context, sessionOf(context, options)).request({ method: 'GET', path });
28
+ return response.body;
29
+ }
30
+ function seatsLine(seats) {
31
+ const contracted = seats.contracted === null
32
+ ? ''
33
+ : `, ${String(seats.contracted)} contratados (assento extra: ${seats.extraPolicy === 'charge' ? 'cobra' : 'bloqueia'})`;
34
+ return `Assentos: ${String(seats.paid)} em uso${contracted}; pico no ciclo ${String(seats.peakInCycle)}; ${String(seats.viewers)} só leitura`;
35
+ }
36
+ function standingLines(status) {
37
+ const lines = [`Situação: ${STANDING_LABELS[status.status]}`];
38
+ if (status.graceEndsAt !== null) {
39
+ lines.push(` Prazo até ${day(status.graceEndsAt)}`);
40
+ }
41
+ if (status.openInvoice !== null) {
42
+ lines.push(` Fatura em aberto ${status.openInvoice.invoiceId}: ${brl(status.openInvoice.totalCents)}, vence em ${day(status.openInvoice.dueDate)}`);
43
+ }
44
+ if (status.lastChargeFailure !== null) {
45
+ lines.push(` Cartão recusado em ${day(status.lastChargeFailure.failedAt)} (fatura ${status.lastChargeFailure.invoiceId})`);
46
+ }
47
+ return lines;
48
+ }
49
+ function cardLine(card) {
50
+ if (!card.verified) {
51
+ return 'Cartão: nenhum cadastrado';
52
+ }
53
+ const expiry = card.expiryMonth === null || card.expiryYear === null
54
+ ? ''
55
+ : `, vale ${String(card.expiryMonth).padStart(2, '0')}/${String(card.expiryYear)}`;
56
+ return `Cartão: ${card.brand ?? 'cartão'} final ${card.lastFourDigits ?? '—'}${expiry}`;
57
+ }
58
+ export function describeOverview(overview) {
59
+ const lines = [
60
+ `Modo: ${MODE_LABELS[overview.billingMode]}`,
61
+ seatsLine(overview.seats),
62
+ `Assento: ${brl(overview.pricePerSeatInCents)} por ciclo; mensalidade ${brl(overview.monthlyFeeInCents)}`
63
+ ];
64
+ if (overview.modules.length > 0) {
65
+ lines.push(`Módulos: ${overview.modules.map((item) => `${item.displayName} (${brl(item.priceInCents)})`).join(', ')}`);
66
+ }
67
+ lines.push(`IA: ${String(overview.ai.usedPercent)}% do ciclo usado; excedente ${overview.ai.overageAllowed ? 'liberado' : 'desligado'}, ${brl(overview.ai.overageInCents)} até agora`, `Gravação de reuniões: ${brl(overview.meetingRecording.totalInCents)} no ciclo`, ...standingLines(overview.status), cardLine(overview.paymentMethod));
68
+ if (overview.next === null) {
69
+ lines.push('Próximo pagamento: sem assinatura ativa');
70
+ return lines;
71
+ }
72
+ lines.push(`Próximo pagamento: ${brl(overview.next.estimatedTotalInCents)} estimados, ciclo fecha em ${day(overview.next.date)}`);
73
+ overview.next.lines.forEach((line) => lines.push(` ${line.label} ${brl(line.totalInCents)}`));
74
+ return lines;
75
+ }
76
+ export async function billingOverview(context, options) {
77
+ const overview = (await get(context, options, '/v1/billing'));
78
+ if (options.json === true) {
79
+ printJson(context, overview);
80
+ return;
81
+ }
82
+ describeOverview(overview).forEach((line) => {
83
+ printLine(context, line);
84
+ });
85
+ }
86
+ function invoiceRow(invoice) {
87
+ const cycle = invoice.cycleStart === null ? '—' : `${day(invoice.cycleStart)} a ${day(invoice.cycleEnd)}`;
88
+ return `${invoice.invoiceId} ${INVOICE_LABELS[invoice.status].padEnd(7)} ${brl(invoice.totalCents).padStart(14)} vence ${day(invoice.dueDate)} ciclo ${cycle}`;
89
+ }
90
+ async function invoiceList(context, options) {
91
+ const query = new URLSearchParams();
92
+ for (const [key, value] of [
93
+ ['page', options.page],
94
+ ['pageSize', options.pageSize]
95
+ ]) {
96
+ if (value !== undefined) {
97
+ query.set(key, value);
98
+ }
99
+ }
100
+ const page = (await get(context, options, `/v1/billing/invoices${query.size === 0 ? '' : `?${query.toString()}`}`));
101
+ if (options.json === true) {
102
+ printJson(context, page);
103
+ return;
104
+ }
105
+ if (page.data.length === 0) {
106
+ printLine(context, 'Nenhuma fatura.');
107
+ return;
108
+ }
109
+ page.data.forEach((invoice) => {
110
+ printLine(context, invoiceRow(invoice));
111
+ });
112
+ if (page.pagination.page < page.pagination.totalPages) {
113
+ printNotice(context, `Página ${String(page.pagination.page)} de ${String(page.pagination.totalPages)}: veja a próxima com --page.`);
114
+ }
115
+ }
116
+ async function invoiceDetail(context, options, invoiceId) {
117
+ const invoice = (await get(context, options, `/v1/billing/invoices/${encodeURIComponent(invoiceId)}`));
118
+ if (options.json === true) {
119
+ printJson(context, invoice);
120
+ return;
121
+ }
122
+ printLine(context, `Fatura ${invoice.invoiceId}: ${INVOICE_LABELS[invoice.status]}, ${brl(invoice.totalCents)}`);
123
+ printLine(context, `Ciclo ${day(invoice.cycleStart)} a ${day(invoice.cycleEnd)}; vence em ${day(invoice.dueDate)}; emitida em ${day(invoice.issuedAt)}`);
124
+ if (invoice.paidAt !== null) {
125
+ const method = invoice.paymentMethod === null ? '' : ` por ${METHOD_LABELS[invoice.paymentMethod.method]}`;
126
+ printLine(context, `Paga em ${day(invoice.paidAt)}${method}`);
127
+ }
128
+ printLine(context, `Modo: ${MODE_LABELS[invoice.mode]}`);
129
+ let group = null;
130
+ for (const line of invoice.lines) {
131
+ if (line.group !== group) {
132
+ group = line.group;
133
+ printLine(context, group);
134
+ }
135
+ printLine(context, ` ${line.label} ${String(line.quantity)} × ${brl(line.unitInCents)} = ${brl(line.totalInCents)}`);
136
+ }
137
+ }
138
+ export async function billingInvoices(context, invoiceId, options) {
139
+ if (invoiceId === undefined) {
140
+ await invoiceList(context, options);
141
+ return;
142
+ }
143
+ await invoiceDetail(context, options, invoiceId);
144
+ }
@@ -0,0 +1,138 @@
1
+ import { automationsCatalog, automationsEntities, automationsEvents, automationsGet, automationsInit, automationsList, automationsPublish, automationsPull, automationsPush, automationsRun, automationsRestore, automationsRuns, automationsToggle, automationsVersions } from './commands/automations.js';
2
+ function addFileCommands(automations, context) {
3
+ automations
4
+ .command('init')
5
+ .description('Cria uma pasta com automation.json (o documento da regra)')
6
+ .argument('<pasta>', 'pasta nova da automação')
7
+ .option('--name <nome>', 'nome da automação')
8
+ .action((dir, _options, command) => {
9
+ automationsInit(context, dir, command.optsWithGlobals());
10
+ });
11
+ automations
12
+ .command('pull')
13
+ .description('Baixa uma automação do Nexo (o rascunho, ou a última versão salva)')
14
+ .argument('<automação>', 'id da automação (veja `nexo automations list`)')
15
+ .argument('[pasta]', 'pasta nova (padrão: o id)')
16
+ .action(async (id, dir, _options, command) => {
17
+ await automationsPull(context, id, dir, command.optsWithGlobals());
18
+ });
19
+ automations
20
+ .command('push')
21
+ .description('Cria a automação ou salva o rascunho, e mostra os problemas que impedem publicar')
22
+ .argument('[pasta]', 'pasta da automação', '.')
23
+ .option('-m, --summary <texto>', 'o que mudou')
24
+ .action(async (dir, _options, command) => {
25
+ await automationsPush(context, dir, command.optsWithGlobals());
26
+ });
27
+ }
28
+ function addLiveCommands(automations, context) {
29
+ automations
30
+ .command('publish')
31
+ .description('Publica o rascunho: mostra o que vai ao ar e pede o sim')
32
+ .argument('[pasta]', 'pasta da automação', '.')
33
+ .option('-y, --yes', 'publica depois de mostrar, sem perguntar (só depois do sim da pessoa)')
34
+ .option('--cancel-live-runs', 'cancela as execuções em andamento da versão anterior')
35
+ .action(async (dir, _options, command) => {
36
+ await automationsPublish(context, dir, command.optsWithGlobals());
37
+ });
38
+ automations
39
+ .command('restore')
40
+ .description('Volta a uma versão antiga: cria uma versão nova com o documento dela e pede o sim')
41
+ .argument('<versão>', 'o número da versão (veja `nexo automations versions`)')
42
+ .argument('[pasta]', 'pasta da automação', '.')
43
+ .option('-y, --yes', 'restaura depois de mostrar, sem perguntar (só depois do sim da pessoa)')
44
+ .option('--cancel-live-runs', 'cancela as execuções em andamento')
45
+ .action(async (seq, dir, _options, command) => {
46
+ await automationsRestore(context, seq, dir, command.optsWithGlobals());
47
+ });
48
+ for (const action of ['pause', 'resume']) {
49
+ automations
50
+ .command(action)
51
+ .description(action === 'pause' ? 'Pausa a automação' : 'Liga de novo uma automação pausada')
52
+ .argument('[pasta]', 'pasta da automação', '.')
53
+ .action(async (dir, _options, command) => {
54
+ await automationsToggle(context, action, dir, command.optsWithGlobals());
55
+ });
56
+ }
57
+ }
58
+ function addReadCommands(automations, context) {
59
+ addGetCommands(automations, context);
60
+ addEventCommands(automations, context);
61
+ }
62
+ function addGetCommands(automations, context) {
63
+ automations
64
+ .command('get')
65
+ .description('Uma automação: o estado, o rascunho e os problemas')
66
+ .argument('[automação]', 'id da automação (padrão: a da pasta atual)')
67
+ .action(async (id, _options, command) => {
68
+ await automationsGet(context, id, undefined, command.optsWithGlobals());
69
+ });
70
+ automations
71
+ .command('entities')
72
+ .description('As entidades que os gatilhos genéricos escutam, com os campos')
73
+ .argument('[entidade]', 'a chave da entidade (por exemplo deal ou lead)')
74
+ .option('--domain <domínio>', 'a família da regra (padrão: crm)')
75
+ .action(async (entity, _options, command) => {
76
+ await automationsEntities(context, entity, command.optsWithGlobals());
77
+ });
78
+ automations
79
+ .command('versions')
80
+ .description('As versões salvas da automação')
81
+ .argument('[pasta]', 'pasta da automação', '.')
82
+ .action(async (dir, _options, command) => {
83
+ await automationsVersions(context, dir, command.optsWithGlobals());
84
+ });
85
+ }
86
+ function addEventCommands(automations, context) {
87
+ automations
88
+ .command('events')
89
+ .description('O que aconteceu com um registro (os eventos que as automações escutam, dos últimos 14 dias)')
90
+ .argument('<entidade>', 'a chave da entidade (por exemplo deal ou lead)')
91
+ .argument('<registro>', 'o id do registro')
92
+ .option('--domain <domínio>', 'a família da regra (padrão: crm)')
93
+ .option('--limit <n>', 'quantos eventos por página')
94
+ .option('--cursor <id>', 'o cursor da página anterior')
95
+ .action(async (entity, subjectId, _options, command) => {
96
+ await automationsEvents(context, entity, subjectId, command.optsWithGlobals());
97
+ });
98
+ }
99
+ function addHistoryCommands(automations, context) {
100
+ automations
101
+ .command('runs')
102
+ .description('As execuções, da mais nova para a mais antiga')
103
+ .argument('[pasta]', 'pasta da automação', '.')
104
+ .option('--state <estado>', 'queued, running, waiting, completed, failed ou canceled')
105
+ .action(async (dir, _options, command) => {
106
+ await automationsRuns(context, dir, command.optsWithGlobals());
107
+ });
108
+ automations
109
+ .command('run')
110
+ .description('Uma execução, passo a passo')
111
+ .argument('<execução>', 'id da execução')
112
+ .action(async (runId, _options, command) => {
113
+ await automationsRun(context, runId, command.optsWithGlobals());
114
+ });
115
+ }
116
+ export function addAutomationCommands(program, context) {
117
+ const automations = program
118
+ .command('automations')
119
+ .alias('flows')
120
+ .description('Automações como código: a regra num arquivo do seu repositório')
121
+ .option('--automation <id>', 'usa esta automação no lugar da da pasta');
122
+ automations
123
+ .command('catalog')
124
+ .description('Os gatilhos, as ações e os campos que uma regra pode usar')
125
+ .action(async (_options, command) => {
126
+ await automationsCatalog(context, command.optsWithGlobals());
127
+ });
128
+ automations
129
+ .command('list')
130
+ .description('As automações da empresa')
131
+ .action(async (_options, command) => {
132
+ await automationsList(context, command.optsWithGlobals());
133
+ });
134
+ addReadCommands(automations, context);
135
+ addFileCommands(automations, context);
136
+ addLiveCommands(automations, context);
137
+ addHistoryCommands(automations, context);
138
+ }
package/dist/program.js CHANGED
@@ -1,8 +1,10 @@
1
1
  import { Command, Option } from 'commander';
2
2
  import { api } from './commands/api.js';
3
+ import { billingInvoices, billingOverview } from './commands/billing.js';
3
4
  import { docsList, docsSearch, docsShow } from './commands/docs.js';
4
5
  import { mcpSetup } from './commands/mcp.js';
5
6
  import { addConnectCommands } from './program-connect.js';
7
+ import { addAutomationCommands } from './program-automations.js';
6
8
  import { addDashboardCommands } from './program-dashboards.js';
7
9
  import { skillsInstall, skillsList } from './commands/skills.js';
8
10
  import { login } from './commands/login.js';
@@ -114,6 +116,24 @@ function addMcpCommand(program, context) {
114
116
  mcpSetup(context, command.optsWithGlobals());
115
117
  });
116
118
  }
119
+ function addBillingCommands(program, context) {
120
+ const billing = program
121
+ .command('billing')
122
+ .alias('cobranca')
123
+ .description('Plano e cobrança da empresa, só leitura: assentos, próximo pagamento, situação e cartão (exige o escopo billing:read e um administrador)')
124
+ .action(async (_options, command) => {
125
+ await billingOverview(context, command.optsWithGlobals());
126
+ });
127
+ billing
128
+ .command('invoices')
129
+ .description('Lista as faturas, da mais nova para a mais antiga; com o id, mostra a fatura com as linhas')
130
+ .argument('[id]', 'id da fatura (UUID), para ver as linhas')
131
+ .option('--page <n>', 'página da lista')
132
+ .option('--page-size <n>', 'faturas por página')
133
+ .action(async (id, _options, command) => {
134
+ await billingInvoices(context, id, command.optsWithGlobals());
135
+ });
136
+ }
117
137
  export function buildProgram(context) {
118
138
  const program = new Command('nexo')
119
139
  .description('CLI do Nexo: a API, o Connect, os dashboards e os fluxos no terminal')
@@ -133,6 +153,8 @@ export function buildProgram(context) {
133
153
  addSkillsCommands(program, context);
134
154
  addMcpCommand(program, context);
135
155
  addConnectCommands(program, context);
156
+ addAutomationCommands(program, context);
136
157
  addDashboardCommands(program, context);
158
+ addBillingCommands(program, context);
137
159
  return program;
138
160
  }
@@ -16,7 +16,7 @@ function agentsBlock(skills) {
16
16
  BLOCK_START,
17
17
  '## Nexo',
18
18
  '',
19
- 'Antes de mexer com o Nexo (API, Connect, painéis), leia a skill do assunto e use a CLI `nexo` (`nexo --help`, `nexo docs search`):',
19
+ 'Antes de mexer com o Nexo (API, Connect, painéis, automações), leia a skill do assunto e use a CLI `nexo` (`nexo --help`, `nexo docs search`):',
20
20
  '',
21
21
  ...lines,
22
22
  BLOCK_END
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@winning-sales/nexo",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "CLI do Nexo: a API, o Connect, os dashboards e os fluxos no terminal, com a documentação e as skills do produto para a sua IA",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -11,7 +11,8 @@
11
11
  "dist",
12
12
  "assets",
13
13
  "README.md",
14
- "LICENSE"
14
+ "LICENSE",
15
+ "reference.json"
15
16
  ],
16
17
  "engines": {
17
18
  "node": ">=20.11"
@@ -30,7 +31,7 @@
30
31
  "format:check": "prettier --check .",
31
32
  "test": "vitest run",
32
33
  "openapi:sync": "openapi-typescript https://mcp-nexo.winningsales.com.br/v1/openapi.json -o src/generated/openapi.ts && prettier --write src/generated/openapi.ts",
33
- "prepublishOnly": "npm run build",
34
+ "prepublishOnly": "npm run build && npm run reference -- --out reference.json",
34
35
  "check": "npm run format:check && npm run lint && npm run typecheck && npm test",
35
36
  "docs:sync": "tsx scripts/sync-docs.ts",
36
37
  "reference": "tsx scripts/reference.ts"