gufi-cli 0.1.49 → 0.1.51

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/dist/commands/docs.js +1 -5
  2. package/dist/lib/docs-resolver.d.ts +8 -0
  3. package/dist/lib/docs-resolver.js +27 -0
  4. package/dist/lib/security.js +5 -0
  5. package/dist/mcp.js +56 -43
  6. package/docs/dev-guide/1-01-architecture.md +358 -0
  7. package/docs/dev-guide/1-02-multi-tenant.md +415 -0
  8. package/docs/dev-guide/1-03-column-types.md +594 -0
  9. package/docs/dev-guide/1-04-json-config.md +442 -0
  10. package/docs/dev-guide/1-05-authentication.md +427 -0
  11. package/docs/dev-guide/2-01-api-reference.md +564 -0
  12. package/docs/dev-guide/2-02-automations.md +508 -0
  13. package/docs/dev-guide/2-03-gufi-cli.md +568 -0
  14. package/docs/dev-guide/2-04-realtime.md +401 -0
  15. package/docs/dev-guide/2-05-permissions.md +497 -0
  16. package/docs/dev-guide/2-06-integrations-overview.md +104 -0
  17. package/docs/dev-guide/2-07-stripe.md +173 -0
  18. package/docs/dev-guide/2-08-nayax.md +297 -0
  19. package/docs/dev-guide/2-09-ourvend.md +226 -0
  20. package/docs/dev-guide/2-10-tns.md +177 -0
  21. package/docs/dev-guide/2-11-custom-http.md +268 -0
  22. package/docs/dev-guide/3-01-custom-views.md +555 -0
  23. package/docs/dev-guide/3-02-webhooks-api.md +446 -0
  24. package/docs/mcp/00-overview.md +329 -0
  25. package/docs/mcp/01-architecture.md +226 -0
  26. package/docs/mcp/02-modules.md +285 -0
  27. package/docs/mcp/03-fields.md +357 -0
  28. package/docs/mcp/04-views.md +613 -0
  29. package/docs/mcp/05-automations.md +461 -0
  30. package/docs/mcp/06-api.md +531 -0
  31. package/docs/mcp/07-packages.md +246 -0
  32. package/docs/mcp/08-common-errors.md +284 -0
  33. package/docs/mcp/09-examples.md +453 -0
  34. package/docs/mcp/README.md +71 -0
  35. package/docs/mcp/tool-descriptions.json +64 -0
  36. package/package.json +3 -2
@@ -0,0 +1,329 @@
1
+ # Gufi MCP - Overview
2
+
3
+ > **15 tools** para construir ERPs con Gufi. Simple, eficiente, directo.
4
+
5
+ ## Que es Gufi
6
+
7
+ **Gufi** es una plataforma para crear ERPs personalizados sin codigo backend:
8
+ - Defines estructura de datos (modules) → Gufi crea tablas PostgreSQL
9
+ - Creas vistas React → Gufi las conecta con los datos
10
+ - Escribes automations JavaScript → Gufi las ejecuta en triggers/cron
11
+
12
+ **Filosofia**: "Simple · Professional · Elegance"
13
+
14
+ ---
15
+
16
+ ## Los 15 Tools MCP
17
+
18
+ ### Contexto y Info (3)
19
+
20
+ | Tool | Uso |
21
+ |------|-----|
22
+ | `gufi_context` | **SIEMPRE PRIMERO** - Obtener schema completo |
23
+ | `gufi_whoami` | Ver usuario, entorno, empresas |
24
+ | `gufi_docs` | Leer documentacion (topics: fields, automations, errors...) |
25
+
26
+ ### Schema (1)
27
+
28
+ | Tool | Uso |
29
+ |------|-----|
30
+ | `gufi_schema_modify` | Crear/editar entities y fields (operaciones atomicas) |
31
+
32
+ ### Automations (5)
33
+
34
+ | Tool | Uso |
35
+ |------|-----|
36
+ | `gufi_automation_scripts` | Scripts: list, get, create, update, delete |
37
+ | `gufi_automation_script_test` | Testear script manualmente |
38
+ | `gufi_automation_meta` | Triggers: ver/configurar en entidades |
39
+ | `gufi_automation_integrations` | Ver integraciones built-in (Stripe, Nayax, etc.) |
40
+ | `gufi_automation_executions` | Debugging: historial de ejecuciones |
41
+
42
+ ### Datos (1)
43
+
44
+ | Tool | Uso |
45
+ |------|-----|
46
+ | `gufi_data` | CRUD: list, get, create, update, delete, aggregate |
47
+
48
+ ### Environment (1)
49
+
50
+ | Tool | Uso |
51
+ |------|-----|
52
+ | `gufi_env` | Variables: list, set, delete |
53
+
54
+ ### Views (3)
55
+
56
+ | Tool | Uso |
57
+ |------|-----|
58
+ | `gufi_view_pull` | Descargar vista a local para editar |
59
+ | `gufi_view_push` | Subir cambios a draft |
60
+ | `gufi_view_test` | Test en headless browser (errores, screenshot) |
61
+
62
+ ### Packages (1)
63
+
64
+ | Tool | Uso |
65
+ |------|-----|
66
+ | `gufi_package` | Gestion: list, get, create, delete, add_module, remove_module, publish |
67
+
68
+ ---
69
+
70
+ ## Workflow Tipico
71
+
72
+ ### 1. Obtener contexto (SIEMPRE PRIMERO)
73
+
74
+ ```
75
+ gufi_context({ company_id: '146' })
76
+ ```
77
+
78
+ Devuelve schema completo: modulos, entidades, campos, relaciones, automations.
79
+
80
+ ### 2. Modificar estructura (Schema)
81
+
82
+ ```javascript
83
+ // Crear entidad
84
+ gufi_schema_modify({
85
+ company_id: '146',
86
+ operations: [{
87
+ op: 'add_entity',
88
+ module: 'ventas',
89
+ entity: { name: 'facturas', label: 'Facturas', kind: 'table' }
90
+ }]
91
+ })
92
+
93
+ // Agregar campo
94
+ gufi_schema_modify({
95
+ company_id: '146',
96
+ operations: [{
97
+ op: 'add_field',
98
+ entity: 'ventas.facturas',
99
+ field: { name: 'total', type: 'currency', label: 'Total' }
100
+ }]
101
+ })
102
+
103
+ // Preview (dry run)
104
+ gufi_schema_modify({
105
+ company_id: '146',
106
+ preview: true,
107
+ operations: [...]
108
+ })
109
+ ```
110
+
111
+ ### 3. Operar datos (CRUD)
112
+
113
+ ```javascript
114
+ // Listar
115
+ gufi_data({ action: 'list', table: 'ventas.facturas', company_id: '146' })
116
+
117
+ // Crear
118
+ gufi_data({
119
+ action: 'create',
120
+ table: 'ventas.facturas',
121
+ company_id: '146',
122
+ data: { numero: 'F-001', total: 150.50 }
123
+ })
124
+
125
+ // Actualizar (IMPORTANTE: incluir __display para select/relation)
126
+ gufi_data({
127
+ action: 'update',
128
+ table: 'ventas.facturas',
129
+ company_id: '146',
130
+ id: 123,
131
+ data: {
132
+ estado: 'pagada',
133
+ estado__display: 'Pagada'
134
+ }
135
+ })
136
+
137
+ // Eliminar
138
+ gufi_data({ action: 'delete', table: 'ventas.facturas', company_id: '146', id: 123 })
139
+ ```
140
+
141
+ ### 4. Crear logica (Automations)
142
+
143
+ ```javascript
144
+ // Crear script
145
+ gufi_automation_scripts({
146
+ action: 'create',
147
+ company_id: '146',
148
+ name: 'enviar_factura',
149
+ code: `
150
+ async function enviar_factura(gufi) {
151
+ const { row, env } = gufi.context;
152
+
153
+ await gufi.integrations.notifications.email({
154
+ to: row.cliente_email,
155
+ subject: 'Nueva factura',
156
+ html: '<p>Adjuntamos su factura.</p>',
157
+ user: env.EMAIL_USER,
158
+ pass: env.EMAIL_PASS,
159
+ from: env.EMAIL_FROM,
160
+ });
161
+
162
+ return { success: true };
163
+ }
164
+ `
165
+ })
166
+
167
+ // Asignar trigger a entidad
168
+ gufi_automation_meta({
169
+ entity_id: '123',
170
+ company_id: '146',
171
+ automations: [
172
+ { trigger: 'insert', function_name: 'enviar_factura' }
173
+ ]
174
+ })
175
+
176
+ // Debugging
177
+ gufi_automation_executions({ company_id: '146', script_name: 'enviar_factura' })
178
+ ```
179
+
180
+ ### 5. Editar vistas (Pull/Push/Test)
181
+
182
+ ```javascript
183
+ // 1. Descargar a ~/gufi-dev/view_13/
184
+ gufi_view_pull({ view_id: 13 })
185
+
186
+ // 2. Editar archivos localmente con Read/Edit tools
187
+ // ...
188
+
189
+ // 3. Subir cambios a draft
190
+ gufi_view_push({ view_id: 13, message: 'Fixed chart colors' })
191
+
192
+ // 4. Testear en headless browser (OBLIGATORIO antes de publicar)
193
+ gufi_view_test({ view_id: 13, company_id: '116' })
194
+
195
+ // 5. Si todo OK, publicar package
196
+ gufi_package({ action: 'publish', id: '19' })
197
+ ```
198
+
199
+ ---
200
+
201
+ ## Entorno: Produccion vs Dev
202
+
203
+ ### Cambiar entorno (forma principal)
204
+
205
+ El entorno se configura **globalmente** con el CLI:
206
+
207
+ ```bash
208
+ # Ver entorno actual
209
+ gufi whoami
210
+
211
+ # Cambiar a desarrollo (localhost:3000)
212
+ gufi config:local
213
+ gufi login
214
+
215
+ # Cambiar a produccion (gogufi.com)
216
+ gufi config:prod
217
+ gufi login
218
+ ```
219
+
220
+ Una vez configurado, **TODAS las herramientas MCP usan ese entorno automaticamente**.
221
+
222
+ ### Override por llamada (requiere login previo)
223
+
224
+ Si ya tienes login en ambos entornos, puedes hacer override con `env`:
225
+
226
+ ```javascript
227
+ // Usa el entorno configurado (default)
228
+ gufi_context({ company_id: '146' })
229
+
230
+ // Override a dev (SOLO si ya hiciste gufi config:local && gufi login antes)
231
+ gufi_context({ company_id: '146', env: 'dev' })
232
+ ```
233
+
234
+ **IMPORTANTE**: El parametro `env: 'dev'` **fallará** si no tienes credenciales guardadas para ese entorno. Primero ejecuta:
235
+ ```bash
236
+ gufi config:local && gufi login
237
+ ```
238
+
239
+ | Entorno | URL | Base de datos | Cuando usar |
240
+ |---------|-----|---------------|-------------|
241
+ | `prod` (default) | gogufi.com | Cloud SQL Prod | Produccion, datos reales |
242
+ | `dev` / `local` | localhost:3000 | Cloud SQL Dev | Desarrollo, pruebas |
243
+
244
+ ---
245
+
246
+ ## Conceptos Clave
247
+
248
+ ### Nombres de tabla: Logicos vs Fisicos
249
+
250
+ ```javascript
251
+ // CORRECTO - Nombre logico (dataProvider lo resuelve)
252
+ gufi_data({ table: 'ventas.facturas', ... })
253
+
254
+ // CORRECTO - ID fisico (cuando lo necesites)
255
+ gufi_data({ table: 'm360_t16192', ... })
256
+ ```
257
+
258
+ ### Campos __display
259
+
260
+ Para `select` y `relation`, actualizar AMBOS campos:
261
+
262
+ ```javascript
263
+ gufi_data({
264
+ action: 'update',
265
+ data: {
266
+ estado: 'completado', // Valor
267
+ estado__display: 'Completado' // Label visible
268
+ }
269
+ })
270
+ ```
271
+
272
+ ### gufi.query() en automations
273
+
274
+ **Devuelve rows directamente** (NO destructuring):
275
+
276
+ ```javascript
277
+ // CORRECTO
278
+ const rows = await gufi.query('SELECT * FROM tabla WHERE id = $1', [5]);
279
+
280
+ // INCORRECTO
281
+ const { rows } = await gufi.query(...); // ERROR!
282
+ ```
283
+
284
+ ---
285
+
286
+ ## Referencias Rapidas
287
+
288
+ ### Topics de documentacion (gufi_docs)
289
+
290
+ | Topic | Contenido |
291
+ |-------|-----------|
292
+ | `overview` | Este archivo |
293
+ | `architecture` | Componentes del sistema |
294
+ | `modules` | Sistema de modulos |
295
+ | `fields` | Tipos de campos y CB builders |
296
+ | `views` | Vistas marketplace |
297
+ | `automations` | Scripts y triggers |
298
+ | `api` | API REST |
299
+ | `packages` | Sistema de packages |
300
+ | `errors` | Errores comunes |
301
+ | `examples` | Ejemplos practicos |
302
+
303
+ ### Operaciones de gufi_schema_modify
304
+
305
+ | Operacion | Descripcion |
306
+ |-----------|-------------|
307
+ | `add_entity` | Crear entidad |
308
+ | `update_entity` | Modificar entidad |
309
+ | `remove_entity` | Eliminar entidad |
310
+ | `add_field` | Agregar campo |
311
+ | `update_field` | Modificar campo |
312
+ | `remove_field` | Eliminar campo |
313
+ | `add_submodule` | Agregar seccion |
314
+
315
+ ### Acciones de gufi_package
316
+
317
+ | Accion | Descripcion |
318
+ |--------|-------------|
319
+ | `list` | Listar mis packages |
320
+ | `get` | Ver detalles de package |
321
+ | `create` | Crear package |
322
+ | `delete` | Eliminar package |
323
+ | `add_module` | Agregar modulo |
324
+ | `remove_module` | Quitar modulo |
325
+ | `publish` | Publicar a produccion |
326
+
327
+ ---
328
+
329
+ **Ultima actualizacion**: 2025-02-04
@@ -0,0 +1,226 @@
1
+ # Arquitectura de Gufi
2
+
3
+ ## Componentes principales
4
+
5
+ ### Backend (Express.js) - Puerto 3000
6
+
7
+ Archivo principal: `backend/server.js`
8
+
9
+ **Features organizadas en:**
10
+ ```
11
+ backend/src/features/
12
+ ├── auth/ # Login, refresh, JWT
13
+ ├── companies/ # CRUD companies, schema
14
+ ├── modules/ # Estructura de datos (JSON -> DDL)
15
+ ├── tables/ # CRUD generico de registros
16
+ ├── automations/ # Scripts y triggers
17
+ ├── views/ # Marketplace views API
18
+ ├── marketplace/ # Developer API (packages)
19
+ ├── files/ # Upload/download GCS
20
+ ├── imports/ # Import wizard (Excel)
21
+ ├── exports/ # Export (Excel, PDF)
22
+ ├── cli/ # Endpoints para CLI
23
+ ├── push/ # Push notifications (FCM)
24
+ ├── webhooks/ # Webhooks externos
25
+ └── ...
26
+ ```
27
+
28
+ **Rutas importantes:**
29
+ - `/api/auth/*` - Autenticacion
30
+ - `/api/company/schema` - Schema completo
31
+ - `/api/company/modules` - CRUD modulos
32
+ - `/api/tables/:table/*` - CRUD registros
33
+ - `/api/automation-scripts/*` - Scripts
34
+ - `/api/marketplace/*` - Developer API
35
+ - `/api/cli/*` - CLI endpoints
36
+
37
+ ### Frontend (React + Vite) - Puerto 5173
38
+
39
+ ```
40
+ frontend/src/
41
+ ├── sdk/ # SDK centralizado (@/sdk)
42
+ │ ├── hooks/ # useViewData, useFeatureData
43
+ │ ├── components/ # FeatureContainer, KPICard
44
+ │ ├── utils/ # formatNumber, groupBy
45
+ │ └── marketplace/ # processSeedData, etc.
46
+ ├── features/
47
+ │ ├── core_views/ # table, dashboard
48
+ │ ├── custom_views/ # Apps custom (delivery, machines)
49
+ │ ├── view_engine/ # ViewGateway, plugins
50
+ │ └── view_templates/ # Templates para crear vistas
51
+ ├── pages/ # Paginas principales
52
+ ├── shared/ # Componentes compartidos
53
+ └── stores/ # Zustand stores
54
+ ```
55
+
56
+ ### WebSocket Server - Puerto 4000
57
+
58
+ Archivo: `websocket/server.js`
59
+
60
+ **Funcionalidades:**
61
+ - Realtime updates (PostgreSQL LISTEN/NOTIFY)
62
+ - Code refresh para desarrollo (CLI push)
63
+ - Developer logs (console.log de vistas)
64
+ - Subscriptions por tabla/company
65
+
66
+ **Formato mensaje:**
67
+ ```json
68
+ {
69
+ "type": "subscribe",
70
+ "table": "m360_t16192",
71
+ "company_id": 116
72
+ }
73
+ ```
74
+
75
+ ### Worker (pg-boss)
76
+
77
+ Archivo: `backend/src/core/services/queue/pgBossWorkerV9.js`
78
+
79
+ **Colas:**
80
+ - `automation` - Ejecuta automations
81
+ - `duplicate-company` - Duplica companies
82
+ - `marketplace-install-package` - Instala packages
83
+ - `geocode-batch` - Geocoding de imports
84
+
85
+ **Flujo automation:**
86
+ ```
87
+ 1. Trigger (insert/update/delete) en tabla
88
+ 2. PostgreSQL NOTIFY → pg-boss job
89
+ 3. Worker ejecuta runAutomation()
90
+ 4. Resultado en automation_executions
91
+ ```
92
+
93
+ ### Marketplace Server
94
+
95
+ Archivo: `marketplace/src/features/marketplace/views.controller.js`
96
+
97
+ **Funcionalidades:**
98
+ - Compilar vistas (esbuild)
99
+ - Validar featureConfig
100
+ - Gestionar versiones
101
+ - Hot reload para desarrollo
102
+
103
+ ## Base de datos
104
+
105
+ ### Schema `core` (compartido)
106
+
107
+ ```sql
108
+ -- Usuarios y auth
109
+ core.users
110
+ core.user_companies
111
+ core.refresh_tokens
112
+
113
+ -- Estructura
114
+ core.modules
115
+ core.entities
116
+
117
+ -- Automations
118
+ core.automation_scripts
119
+ core.automation_meta
120
+ core.automation_executions
121
+
122
+ -- Marketplace
123
+ core.marketplace_packages
124
+ core.marketplace_views
125
+ core.marketplace_view_files
126
+
127
+ -- Config
128
+ core.company_env_variables
129
+ ```
130
+
131
+ ### Schema `company_{id}` (por empresa)
132
+
133
+ ```sql
134
+ -- Tablas de datos (generadas de modules)
135
+ m{moduleId}_t{entityId}
136
+
137
+ -- Cada tabla tiene:
138
+ -- id SERIAL PRIMARY KEY
139
+ -- created_at TIMESTAMP
140
+ -- ... campos definidos en module JSON
141
+ ```
142
+
143
+ ### Schema `pgboss` (job queue)
144
+
145
+ ```sql
146
+ pgboss.job -- Jobs pendientes
147
+ pgboss.archive -- Jobs completados
148
+ pgboss.schedule -- Scheduled jobs
149
+ ```
150
+
151
+ ## Multi-tenancy
152
+
153
+ ### Aislamiento
154
+
155
+ 1. JWT contiene `company_id`
156
+ 2. Backend hace `SET search_path TO company_{id}, core, public`
157
+ 3. Queries se ejecutan en schema correcto automaticamente
158
+
159
+ ### Nombres de tabla
160
+
161
+ ```
162
+ m{moduleId}_t{entityId}
163
+
164
+ Ejemplos:
165
+ - m360_t16192 (modulo 360, entidad 16192)
166
+ - m308_t4136 (modulo 308, entidad 4136)
167
+ ```
168
+
169
+ Para saber que modulo/entidad:
170
+ ```sql
171
+ SELECT m.id as module_id, e.id as entity_id, e.name
172
+ FROM core.modules m, jsonb_array_elements(m.json_definition->'submodules') sub,
173
+ jsonb_array_elements(sub->'entities') e
174
+ WHERE m.company_id = 116;
175
+ ```
176
+
177
+ ## Autenticacion
178
+
179
+ ### JWT Flow
180
+
181
+ ```
182
+ 1. POST /api/auth/login { email, password }
183
+ -> { accessToken, refreshToken }
184
+
185
+ 2. Requests con: Authorization: Bearer {accessToken}
186
+ X-Company-ID: {companyId}
187
+
188
+ 3. Token expira -> POST /api/auth/refresh
189
+ -> { accessToken, refreshToken }
190
+ ```
191
+
192
+ ### Permisos (RBAC)
193
+
194
+ ```javascript
195
+ // En entity.permissions:
196
+ {
197
+ "admin": "*", // Todo permitido
198
+ "manager": ["entity:view", "entity:create", "entity:update"],
199
+ "viewer": ["entity:view"]
200
+ }
201
+
202
+ // Permisos posibles:
203
+ // entity:view, entity:create, entity:update, entity:delete
204
+ // entity:import, entity:export
205
+ ```
206
+
207
+ ## Comunicacion entre servicios
208
+
209
+ ```
210
+ Frontend <--HTTP--> Backend <--SQL--> PostgreSQL
211
+ | | |
212
+ |<---WebSocket-----|<--NOTIFY---------|
213
+ | |
214
+ | Worker <--pg-boss queue
215
+ ```
216
+
217
+ ## Puertos por defecto
218
+
219
+ | Servicio | Puerto | Descripcion |
220
+ |----------|--------|-------------|
221
+ | Backend | 3000 | API principal |
222
+ | Frontend | 5173 | React dev server |
223
+ | WebSocket | 4000 | Realtime |
224
+ | PostgreSQL | 5432 | Base de datos |
225
+ | Redis | 6379 | Cache (opcional) |
226
+ | Marketplace | 3001 | Compilacion vistas |