contlity 0.3.0__tar.gz

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,362 @@
1
+ Metadata-Version: 2.4
2
+ Name: contlity
3
+ Version: 0.3.0
4
+ Summary: SDK oficial para la API de Contlity — automatización fiscal e integraciones ERP
5
+ Author: Contlity
6
+ License-Expression: LicenseRef-Proprietary
7
+ Project-URL: Homepage, https://contlity.tech-mx.cloud
8
+ Project-URL: Documentation, https://contlity.tech-mx.cloud/docs/sdk
9
+ Project-URL: Repository, https://github.com/manuelalvarado-gthb/contlity
10
+ Project-URL: Issues, https://github.com/manuelalvarado-gthb/contlity/issues
11
+ Keywords: contlity,sat,cfdi,fiscal,mexico,erp,dbapi,sqlalchemy
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Requires-Python: >=3.10
19
+ Description-Content-Type: text/markdown
20
+ Requires-Dist: requests>=2.28
21
+ Provides-Extra: dev
22
+ Requires-Dist: pytest; extra == "dev"
23
+ Requires-Dist: pytest-mock; extra == "dev"
24
+ Requires-Dist: responses; extra == "dev"
25
+ Provides-Extra: sqlalchemy
26
+ Requires-Dist: sqlalchemy>=2.0; extra == "sqlalchemy"
27
+
28
+ # Contlity Python SDK
29
+
30
+ SDK oficial para la [API de Contlity](https://contlity.tech-mx.cloud/docs/api) — automatización fiscal, SAT Descarga Masiva, timbrado e integraciones ERP.
31
+
32
+ > **Requiere plan Enterprise.** Las API keys se generan en la sección **Desarrollador** de tu cuenta (`/desarrollador`).
33
+
34
+ ## Instalación
35
+
36
+ ```bash
37
+ pip install contlity
38
+ pip install "contlity[sqlalchemy]" # con el driver para SQLAlchemy y pandas
39
+ ```
40
+
41
+ ## Inicialización
42
+
43
+ ```bash
44
+ # Define la API key como variable de entorno (recomendado):
45
+ export CONTLITY_API_KEY="ctly_live_..."
46
+ ```
47
+
48
+ ```python
49
+ from contlity import ContlityClient
50
+
51
+ # Recomendado — lee CONTLITY_API_KEY del entorno
52
+ client = ContlityClient.from_env()
53
+
54
+ # Explícito (no usar en código fuente/repositorios)
55
+ client = ContlityClient("ctly_live_...")
56
+
57
+ # Verificar conexión
58
+ info = client.ping()
59
+ print(f"Conectado como: {info['name']} (plan: {info['plan']})")
60
+ ```
61
+
62
+ ## Inicio rápido
63
+
64
+ ```python
65
+ from contlity import ContlityClient
66
+
67
+ client = ContlityClient.from_env()
68
+
69
+ # Listar clientes
70
+ clients = client.clients.list()
71
+ print(clients) # [{"rfc": "ABC123...", "name": "Mi Empresa", ...}, ...]
72
+
73
+ # CFDIs de un RFC
74
+ result = client.cfdis.list("RFC123456789", limit=50)
75
+ print(result["total"]) # 1234
76
+
77
+ # CFDI por UUID
78
+ cfdi = client.cfdis.get("9A1B2C3D-...")
79
+ print(cfdi["uuid"])
80
+
81
+ # SQL fiscal
82
+ rows = client.sql.execute("SELECT COUNT(*) AS total, SUM(total) AS monto FROM cfdi")
83
+ print(rows["rows"])
84
+
85
+ # Balance de créditos
86
+ bal = client.credits.balance()
87
+ print(f"Créditos: {bal['balance']} / {bal['bundle']}") # enterprise: bundle=null
88
+ ```
89
+
90
+ ## SAT Descarga Masiva
91
+
92
+ ```python
93
+ # Listar jobs existentes
94
+ jobs = client.sat.jobs(rfc="RFC123456789", limit=10)
95
+
96
+ # Iniciar sync
97
+ job = client.sat.sync(
98
+ rfc="RFC123456789",
99
+ tipo="recibidos",
100
+ fecha_inicial="2026-01-01",
101
+ fecha_final="2026-01-31",
102
+ )
103
+ print(job["job_id"])
104
+
105
+ # Revisar estado
106
+ import time
107
+ while True:
108
+ status = client.sat.job_status(job["job_id"])
109
+ if status["status"] in ("done", "error", "timeout"):
110
+ break
111
+ time.sleep(10)
112
+
113
+ print(f"CFDIs descargados: {status['cfdis_ingested']}")
114
+ ```
115
+
116
+ ## Workflows
117
+
118
+ ```python
119
+ # Ejecutar workflow
120
+ run = client.workflows.run("workflow-uuid-aqui")
121
+ run_id = run["run_id"]
122
+
123
+ # Revisar estado
124
+ status = client.workflows.run_status(run_id)
125
+ print(status["status"]) # "running" | "success" | "error"
126
+ ```
127
+
128
+ ## Webhooks
129
+
130
+ ### Suscribir tu URL
131
+
132
+ ```python
133
+ sub = client.webhooks.create(
134
+ url="https://mi-erp.com/hooks/contlity",
135
+ events=["sat.sync.completed", "invoice.created", "credits.low"],
136
+ description="Integración ERP principal",
137
+ )
138
+ # ⚠️ Guarda el secret ahora — no se puede recuperar después
139
+ secret = sub["secret"] # "whsec_abc123..."
140
+ print(f"Subscription ID: {sub['subscription_id']}")
141
+
142
+ # Listar suscripciones
143
+ subs = client.webhooks.list()
144
+
145
+ # Enviar ping de prueba
146
+ client.webhooks.test(sub["subscription_id"])
147
+
148
+ # Ver historial de entregas
149
+ deliveries = client.webhooks.deliveries(sub["subscription_id"], limit=20)
150
+
151
+ # Actualizar eventos
152
+ client.webhooks.update(sub["subscription_id"], events=["*"]) # todos los eventos
153
+
154
+ # Eliminar
155
+ client.webhooks.delete(sub["subscription_id"])
156
+ ```
157
+
158
+ ### Verificar webhooks entrantes
159
+
160
+ ```python
161
+ from contlity import WebhookHandler, WebhookError
162
+
163
+ handler = WebhookHandler(secret="whsec_abc123...")
164
+
165
+ # En tu endpoint Flask/FastAPI/Django:
166
+ @app.post("/hooks/contlity")
167
+ async def handle_webhook(request: Request):
168
+ body = await request.body()
169
+ headers = dict(request.headers)
170
+
171
+ try:
172
+ payload = handler.verify(body, headers)
173
+ except WebhookError:
174
+ return Response(status_code=401)
175
+
176
+ event = payload["event"]
177
+ data = payload["data"]
178
+
179
+ if event == "sat.sync.completed":
180
+ print(f"SAT sync ✓ — {data['cfdis_ingested']} CFDIs")
181
+ elif event == "invoice.created":
182
+ print(f"Factura emitida: {data['uuid']}")
183
+ elif event == "credits.low":
184
+ print(f"⚠️ Créditos bajos: {data['balance']} ({data['pct']}%)")
185
+ elif event == "credits.depleted":
186
+ print("🚨 Créditos agotados")
187
+
188
+ return {"ok": True}
189
+ ```
190
+
191
+ ### Listar tipos de evento disponibles
192
+
193
+ ```python
194
+ events = client.webhooks.list_event_types()
195
+ # [{"event": "sat.sync.completed", "description": "..."}, ...]
196
+ ```
197
+
198
+ ### Todos los eventos disponibles
199
+
200
+ | Evento | Descripción |
201
+ |--------|-------------|
202
+ | `cfdi.ingested` | Lote de CFDIs cargado al catálogo |
203
+ | `sat.sync.completed` | Sincronización SAT completada |
204
+ | `sat.sync.failed` | Sincronización SAT falló |
205
+ | `invoice.created` | Factura electrónica emitida |
206
+ | `invoice.cancelled` | Factura electrónica cancelada |
207
+ | `portal.completed` | Job de portal autofactura completado |
208
+ | `portal.failed` | Job de portal autofactura falló |
209
+ | `workflow.completed` | Workflow completado exitosamente |
210
+ | `workflow.failed` | Workflow falló |
211
+ | `credits.low` | Balance < 20% del bundle mensual |
212
+ | `credits.depleted` | Créditos agotados |
213
+
214
+ ## Manejo de errores
215
+
216
+ ```python
217
+ from contlity import (
218
+ ContlityClient,
219
+ AuthError,
220
+ CreditError,
221
+ RateLimitError,
222
+ NotFoundError,
223
+ PlanError,
224
+ WebhookError,
225
+ )
226
+ import time
227
+
228
+ client = ContlityClient("ctly_live_...")
229
+
230
+ try:
231
+ result = client.sql.execute("SELECT * FROM cfdi LIMIT 1000")
232
+ except AuthError:
233
+ print("API key inválida o revocada")
234
+ except CreditError as e:
235
+ print(f"Sin créditos: tienes {e.balance}, la operación cuesta {e.cost}")
236
+ except RateLimitError as e:
237
+ print(f"Rate limit — espera {e.retry_after}s")
238
+ time.sleep(e.retry_after)
239
+ # reintentar...
240
+ except NotFoundError:
241
+ print("Recurso no encontrado")
242
+ except PlanError:
243
+ print("Operación no disponible en tu plan actual")
244
+ ```
245
+
246
+ ## Cargas: stages y COPY INTO
247
+
248
+ Requiere una API key con el alcance **Cargas**; actúa con los permisos del usuario de la key.
249
+
250
+ ```python
251
+ client = ContlityClient.from_env()
252
+
253
+ print(client.cargas.stages()) # stages visibles
254
+ client.cargas.subir("@despacho.integraciones.entrada/ventas/", "ventas_enero.csv")
255
+ print(client.cargas.archivos("@despacho.integraciones.entrada/ventas/"))
256
+
257
+ r = client.cargas.copiar("despacho.integraciones.ventas", # la crea si no existe
258
+ "@despacho.integraciones.entrada/ventas/",
259
+ formato={"type": "csv"}, on_error="skip_file")
260
+ print(r["filas"], "filas cargadas")
261
+
262
+ client.cargas.actualizar_tabla_externa("despacho.integraciones.clientes_erp")
263
+ ```
264
+
265
+ Para traer datos de un servidor de la oficina sin programar, usa el conector local (ver /docs/integraciones).
266
+
267
+ ## Driver SQL: DB-API 2.0, SQLAlchemy y pandas
268
+
269
+ `contlity.dbapi` es un driver estándar de Python (PEP 249). Como los de Snowflake o Athena, habla con
270
+ Contlity por HTTPS: no hay puertos que abrir y cada consulta corre con los permisos, la cartera y los
271
+ créditos del usuario de la API key (alcance **SQL**). Solo lectura.
272
+
273
+ ```python
274
+ import datetime
275
+ import contlity.dbapi as ctly
276
+
277
+ con = ctly.connect(database="despacho") # API key en CONTLITY_API_KEY
278
+ cur = con.cursor()
279
+ cur.execute("SELECT rfc_emisor, sum(total) FROM comprobantes WHERE fecha >= %(desde)s GROUP BY 1",
280
+ {"desde": datetime.date(2026, 1, 1)})
281
+ for rfc, total in cur: # total llega como Decimal, fechas como date/datetime
282
+ print(rfc, total)
283
+ ```
284
+
285
+ Con SQLAlchemy (`pip install "contlity[sqlalchemy]"`) funcionan pandas, Jupyter, Superset, Streamlit y
286
+ cualquier herramienta que acepte una URL de SQLAlchemy:
287
+
288
+ ```python
289
+ from sqlalchemy import create_engine, inspect
290
+ import pandas as pd
291
+
292
+ eng = create_engine("contlity:///despacho") # o contlity://:ctly_live_...@/despacho?schema=ventas
293
+ df = pd.read_sql("SELECT * FROM ventas.facturas", eng)
294
+ inspect(eng).get_table_names(schema="ventas")
295
+ ```
296
+
297
+ La conexión queda en una base (por omisión, la principal). Los esquemas son los de esa base; las vistas
298
+ del núcleo están en el esquema `contlity` y se consultan sin calificar (`FROM comprobantes`).
299
+ `client.sql.catalog(database)` devuelve el mismo catálogo (esquemas, tablas, columnas y tipos).
300
+
301
+ ## Configuración avanzada
302
+
303
+ ```python
304
+ # URL personalizada (instancia self-hosted o staging)
305
+ client = ContlityClient(
306
+ api_key="ctly_live_...",
307
+ base_url="https://mi-instancia.ejemplo.com/api",
308
+ timeout=60, # segundos
309
+ )
310
+ ```
311
+
312
+ ## Referencia de endpoints `/v1`
313
+
314
+ | Método | Endpoint | Descripción | Créditos |
315
+ |--------|----------|-------------|---------|
316
+ | GET | `/v1/account` | Info de la cuenta | 0 |
317
+ | GET | `/v1/clients` | Lista de clientes | 0 |
318
+ | GET | `/v1/clients/{rfc}/cfdis` | CFDIs de un RFC | 0 |
319
+ | GET | `/v1/cfdis/{uuid}` | CFDI por UUID | 0 |
320
+ | POST | `/v1/sql` | Ejecutar SQL | 1–2 |
321
+ | GET | `/v1/catalog` | Esquemas, tablas y columnas visibles | 0 |
322
+ | GET | `/v1/stages` | Stages visibles | 0 |
323
+ | GET/POST | `/v1/stages/{base}/{esquema}/{stage}/files` | Listar / subir archivos | 0 |
324
+ | POST | `/v1/copy` | COPY INTO tabla desde un stage | 1–2 |
325
+ | POST | `/v1/external-tables/{base}/{esquema}/{tabla}/refresh` | Actualizar tabla externa | 1–2 |
326
+ | GET | `/v1/sat/jobs` | Lista jobs SAT | 0 |
327
+ | GET | `/v1/sat/jobs/{id}` | Estado de un job | 0 |
328
+ | POST | `/v1/sat/sync/{rfc}` | Disparar sync SAT | 5 |
329
+ | POST | `/v1/workflows/{id}/run` | Ejecutar workflow | 1 |
330
+ | GET | `/v1/workflows/runs/{id}` | Estado de ejecución | 0 |
331
+ | GET | `/v1/credits` | Balance de créditos | 0 |
332
+ | GET | `/v1/worksheets` | Lista worksheets | 0 |
333
+ | GET | `/v1/worksheets/{id}` | Obtener worksheet | 0 |
334
+ | POST | `/v1/upload/{rfc}` | Subir XMLs de CFDIs | 0 |
335
+ | GET | `/v1/webhooks` | Lista suscripciones | 0 |
336
+ | POST | `/v1/webhooks` | Crear suscripción | 0 |
337
+ | GET | `/v1/webhooks/{id}` | Detalle suscripción | 0 |
338
+ | PUT | `/v1/webhooks/{id}` | Actualizar suscripción | 0 |
339
+ | DELETE | `/v1/webhooks/{id}` | Eliminar suscripción | 0 |
340
+ | POST | `/v1/webhooks/{id}/test` | Enviar ping de prueba | 0 |
341
+ | GET | `/v1/webhooks/{id}/deliveries` | Historial entregas | 0 |
342
+ | GET | `/v1/events` | Tipos de evento | 0 |
343
+
344
+ **Rate limit:** 120 peticiones/minuto por API key. Respuesta 429 con `retry_after: 60`.
345
+
346
+ ## Verificación de firma — detalles
347
+
348
+ El SDK incluye `WebhookHandler` que verifica firmas HMAC-SHA256:
349
+
350
+ ```python
351
+ from contlity import WebhookHandler, WebhookError
352
+
353
+ handler = WebhookHandler(secret="whsec_...")
354
+
355
+ # Verificar + parsear payload
356
+ payload = handler.verify(body_bytes, headers_dict)
357
+
358
+ # Solo verificar firma (sin parsear)
359
+ is_valid = handler.verify_signature_only(body_bytes, "sha256=abc...")
360
+ ```
361
+
362
+ La firma se calcula sobre el body JSON crudo con HMAC-SHA256 usando el `secret` como clave. El header verificado es `X-Contlity-Signature`.
@@ -0,0 +1,335 @@
1
+ # Contlity Python SDK
2
+
3
+ SDK oficial para la [API de Contlity](https://contlity.tech-mx.cloud/docs/api) — automatización fiscal, SAT Descarga Masiva, timbrado e integraciones ERP.
4
+
5
+ > **Requiere plan Enterprise.** Las API keys se generan en la sección **Desarrollador** de tu cuenta (`/desarrollador`).
6
+
7
+ ## Instalación
8
+
9
+ ```bash
10
+ pip install contlity
11
+ pip install "contlity[sqlalchemy]" # con el driver para SQLAlchemy y pandas
12
+ ```
13
+
14
+ ## Inicialización
15
+
16
+ ```bash
17
+ # Define la API key como variable de entorno (recomendado):
18
+ export CONTLITY_API_KEY="ctly_live_..."
19
+ ```
20
+
21
+ ```python
22
+ from contlity import ContlityClient
23
+
24
+ # Recomendado — lee CONTLITY_API_KEY del entorno
25
+ client = ContlityClient.from_env()
26
+
27
+ # Explícito (no usar en código fuente/repositorios)
28
+ client = ContlityClient("ctly_live_...")
29
+
30
+ # Verificar conexión
31
+ info = client.ping()
32
+ print(f"Conectado como: {info['name']} (plan: {info['plan']})")
33
+ ```
34
+
35
+ ## Inicio rápido
36
+
37
+ ```python
38
+ from contlity import ContlityClient
39
+
40
+ client = ContlityClient.from_env()
41
+
42
+ # Listar clientes
43
+ clients = client.clients.list()
44
+ print(clients) # [{"rfc": "ABC123...", "name": "Mi Empresa", ...}, ...]
45
+
46
+ # CFDIs de un RFC
47
+ result = client.cfdis.list("RFC123456789", limit=50)
48
+ print(result["total"]) # 1234
49
+
50
+ # CFDI por UUID
51
+ cfdi = client.cfdis.get("9A1B2C3D-...")
52
+ print(cfdi["uuid"])
53
+
54
+ # SQL fiscal
55
+ rows = client.sql.execute("SELECT COUNT(*) AS total, SUM(total) AS monto FROM cfdi")
56
+ print(rows["rows"])
57
+
58
+ # Balance de créditos
59
+ bal = client.credits.balance()
60
+ print(f"Créditos: {bal['balance']} / {bal['bundle']}") # enterprise: bundle=null
61
+ ```
62
+
63
+ ## SAT Descarga Masiva
64
+
65
+ ```python
66
+ # Listar jobs existentes
67
+ jobs = client.sat.jobs(rfc="RFC123456789", limit=10)
68
+
69
+ # Iniciar sync
70
+ job = client.sat.sync(
71
+ rfc="RFC123456789",
72
+ tipo="recibidos",
73
+ fecha_inicial="2026-01-01",
74
+ fecha_final="2026-01-31",
75
+ )
76
+ print(job["job_id"])
77
+
78
+ # Revisar estado
79
+ import time
80
+ while True:
81
+ status = client.sat.job_status(job["job_id"])
82
+ if status["status"] in ("done", "error", "timeout"):
83
+ break
84
+ time.sleep(10)
85
+
86
+ print(f"CFDIs descargados: {status['cfdis_ingested']}")
87
+ ```
88
+
89
+ ## Workflows
90
+
91
+ ```python
92
+ # Ejecutar workflow
93
+ run = client.workflows.run("workflow-uuid-aqui")
94
+ run_id = run["run_id"]
95
+
96
+ # Revisar estado
97
+ status = client.workflows.run_status(run_id)
98
+ print(status["status"]) # "running" | "success" | "error"
99
+ ```
100
+
101
+ ## Webhooks
102
+
103
+ ### Suscribir tu URL
104
+
105
+ ```python
106
+ sub = client.webhooks.create(
107
+ url="https://mi-erp.com/hooks/contlity",
108
+ events=["sat.sync.completed", "invoice.created", "credits.low"],
109
+ description="Integración ERP principal",
110
+ )
111
+ # ⚠️ Guarda el secret ahora — no se puede recuperar después
112
+ secret = sub["secret"] # "whsec_abc123..."
113
+ print(f"Subscription ID: {sub['subscription_id']}")
114
+
115
+ # Listar suscripciones
116
+ subs = client.webhooks.list()
117
+
118
+ # Enviar ping de prueba
119
+ client.webhooks.test(sub["subscription_id"])
120
+
121
+ # Ver historial de entregas
122
+ deliveries = client.webhooks.deliveries(sub["subscription_id"], limit=20)
123
+
124
+ # Actualizar eventos
125
+ client.webhooks.update(sub["subscription_id"], events=["*"]) # todos los eventos
126
+
127
+ # Eliminar
128
+ client.webhooks.delete(sub["subscription_id"])
129
+ ```
130
+
131
+ ### Verificar webhooks entrantes
132
+
133
+ ```python
134
+ from contlity import WebhookHandler, WebhookError
135
+
136
+ handler = WebhookHandler(secret="whsec_abc123...")
137
+
138
+ # En tu endpoint Flask/FastAPI/Django:
139
+ @app.post("/hooks/contlity")
140
+ async def handle_webhook(request: Request):
141
+ body = await request.body()
142
+ headers = dict(request.headers)
143
+
144
+ try:
145
+ payload = handler.verify(body, headers)
146
+ except WebhookError:
147
+ return Response(status_code=401)
148
+
149
+ event = payload["event"]
150
+ data = payload["data"]
151
+
152
+ if event == "sat.sync.completed":
153
+ print(f"SAT sync ✓ — {data['cfdis_ingested']} CFDIs")
154
+ elif event == "invoice.created":
155
+ print(f"Factura emitida: {data['uuid']}")
156
+ elif event == "credits.low":
157
+ print(f"⚠️ Créditos bajos: {data['balance']} ({data['pct']}%)")
158
+ elif event == "credits.depleted":
159
+ print("🚨 Créditos agotados")
160
+
161
+ return {"ok": True}
162
+ ```
163
+
164
+ ### Listar tipos de evento disponibles
165
+
166
+ ```python
167
+ events = client.webhooks.list_event_types()
168
+ # [{"event": "sat.sync.completed", "description": "..."}, ...]
169
+ ```
170
+
171
+ ### Todos los eventos disponibles
172
+
173
+ | Evento | Descripción |
174
+ |--------|-------------|
175
+ | `cfdi.ingested` | Lote de CFDIs cargado al catálogo |
176
+ | `sat.sync.completed` | Sincronización SAT completada |
177
+ | `sat.sync.failed` | Sincronización SAT falló |
178
+ | `invoice.created` | Factura electrónica emitida |
179
+ | `invoice.cancelled` | Factura electrónica cancelada |
180
+ | `portal.completed` | Job de portal autofactura completado |
181
+ | `portal.failed` | Job de portal autofactura falló |
182
+ | `workflow.completed` | Workflow completado exitosamente |
183
+ | `workflow.failed` | Workflow falló |
184
+ | `credits.low` | Balance < 20% del bundle mensual |
185
+ | `credits.depleted` | Créditos agotados |
186
+
187
+ ## Manejo de errores
188
+
189
+ ```python
190
+ from contlity import (
191
+ ContlityClient,
192
+ AuthError,
193
+ CreditError,
194
+ RateLimitError,
195
+ NotFoundError,
196
+ PlanError,
197
+ WebhookError,
198
+ )
199
+ import time
200
+
201
+ client = ContlityClient("ctly_live_...")
202
+
203
+ try:
204
+ result = client.sql.execute("SELECT * FROM cfdi LIMIT 1000")
205
+ except AuthError:
206
+ print("API key inválida o revocada")
207
+ except CreditError as e:
208
+ print(f"Sin créditos: tienes {e.balance}, la operación cuesta {e.cost}")
209
+ except RateLimitError as e:
210
+ print(f"Rate limit — espera {e.retry_after}s")
211
+ time.sleep(e.retry_after)
212
+ # reintentar...
213
+ except NotFoundError:
214
+ print("Recurso no encontrado")
215
+ except PlanError:
216
+ print("Operación no disponible en tu plan actual")
217
+ ```
218
+
219
+ ## Cargas: stages y COPY INTO
220
+
221
+ Requiere una API key con el alcance **Cargas**; actúa con los permisos del usuario de la key.
222
+
223
+ ```python
224
+ client = ContlityClient.from_env()
225
+
226
+ print(client.cargas.stages()) # stages visibles
227
+ client.cargas.subir("@despacho.integraciones.entrada/ventas/", "ventas_enero.csv")
228
+ print(client.cargas.archivos("@despacho.integraciones.entrada/ventas/"))
229
+
230
+ r = client.cargas.copiar("despacho.integraciones.ventas", # la crea si no existe
231
+ "@despacho.integraciones.entrada/ventas/",
232
+ formato={"type": "csv"}, on_error="skip_file")
233
+ print(r["filas"], "filas cargadas")
234
+
235
+ client.cargas.actualizar_tabla_externa("despacho.integraciones.clientes_erp")
236
+ ```
237
+
238
+ Para traer datos de un servidor de la oficina sin programar, usa el conector local (ver /docs/integraciones).
239
+
240
+ ## Driver SQL: DB-API 2.0, SQLAlchemy y pandas
241
+
242
+ `contlity.dbapi` es un driver estándar de Python (PEP 249). Como los de Snowflake o Athena, habla con
243
+ Contlity por HTTPS: no hay puertos que abrir y cada consulta corre con los permisos, la cartera y los
244
+ créditos del usuario de la API key (alcance **SQL**). Solo lectura.
245
+
246
+ ```python
247
+ import datetime
248
+ import contlity.dbapi as ctly
249
+
250
+ con = ctly.connect(database="despacho") # API key en CONTLITY_API_KEY
251
+ cur = con.cursor()
252
+ cur.execute("SELECT rfc_emisor, sum(total) FROM comprobantes WHERE fecha >= %(desde)s GROUP BY 1",
253
+ {"desde": datetime.date(2026, 1, 1)})
254
+ for rfc, total in cur: # total llega como Decimal, fechas como date/datetime
255
+ print(rfc, total)
256
+ ```
257
+
258
+ Con SQLAlchemy (`pip install "contlity[sqlalchemy]"`) funcionan pandas, Jupyter, Superset, Streamlit y
259
+ cualquier herramienta que acepte una URL de SQLAlchemy:
260
+
261
+ ```python
262
+ from sqlalchemy import create_engine, inspect
263
+ import pandas as pd
264
+
265
+ eng = create_engine("contlity:///despacho") # o contlity://:ctly_live_...@/despacho?schema=ventas
266
+ df = pd.read_sql("SELECT * FROM ventas.facturas", eng)
267
+ inspect(eng).get_table_names(schema="ventas")
268
+ ```
269
+
270
+ La conexión queda en una base (por omisión, la principal). Los esquemas son los de esa base; las vistas
271
+ del núcleo están en el esquema `contlity` y se consultan sin calificar (`FROM comprobantes`).
272
+ `client.sql.catalog(database)` devuelve el mismo catálogo (esquemas, tablas, columnas y tipos).
273
+
274
+ ## Configuración avanzada
275
+
276
+ ```python
277
+ # URL personalizada (instancia self-hosted o staging)
278
+ client = ContlityClient(
279
+ api_key="ctly_live_...",
280
+ base_url="https://mi-instancia.ejemplo.com/api",
281
+ timeout=60, # segundos
282
+ )
283
+ ```
284
+
285
+ ## Referencia de endpoints `/v1`
286
+
287
+ | Método | Endpoint | Descripción | Créditos |
288
+ |--------|----------|-------------|---------|
289
+ | GET | `/v1/account` | Info de la cuenta | 0 |
290
+ | GET | `/v1/clients` | Lista de clientes | 0 |
291
+ | GET | `/v1/clients/{rfc}/cfdis` | CFDIs de un RFC | 0 |
292
+ | GET | `/v1/cfdis/{uuid}` | CFDI por UUID | 0 |
293
+ | POST | `/v1/sql` | Ejecutar SQL | 1–2 |
294
+ | GET | `/v1/catalog` | Esquemas, tablas y columnas visibles | 0 |
295
+ | GET | `/v1/stages` | Stages visibles | 0 |
296
+ | GET/POST | `/v1/stages/{base}/{esquema}/{stage}/files` | Listar / subir archivos | 0 |
297
+ | POST | `/v1/copy` | COPY INTO tabla desde un stage | 1–2 |
298
+ | POST | `/v1/external-tables/{base}/{esquema}/{tabla}/refresh` | Actualizar tabla externa | 1–2 |
299
+ | GET | `/v1/sat/jobs` | Lista jobs SAT | 0 |
300
+ | GET | `/v1/sat/jobs/{id}` | Estado de un job | 0 |
301
+ | POST | `/v1/sat/sync/{rfc}` | Disparar sync SAT | 5 |
302
+ | POST | `/v1/workflows/{id}/run` | Ejecutar workflow | 1 |
303
+ | GET | `/v1/workflows/runs/{id}` | Estado de ejecución | 0 |
304
+ | GET | `/v1/credits` | Balance de créditos | 0 |
305
+ | GET | `/v1/worksheets` | Lista worksheets | 0 |
306
+ | GET | `/v1/worksheets/{id}` | Obtener worksheet | 0 |
307
+ | POST | `/v1/upload/{rfc}` | Subir XMLs de CFDIs | 0 |
308
+ | GET | `/v1/webhooks` | Lista suscripciones | 0 |
309
+ | POST | `/v1/webhooks` | Crear suscripción | 0 |
310
+ | GET | `/v1/webhooks/{id}` | Detalle suscripción | 0 |
311
+ | PUT | `/v1/webhooks/{id}` | Actualizar suscripción | 0 |
312
+ | DELETE | `/v1/webhooks/{id}` | Eliminar suscripción | 0 |
313
+ | POST | `/v1/webhooks/{id}/test` | Enviar ping de prueba | 0 |
314
+ | GET | `/v1/webhooks/{id}/deliveries` | Historial entregas | 0 |
315
+ | GET | `/v1/events` | Tipos de evento | 0 |
316
+
317
+ **Rate limit:** 120 peticiones/minuto por API key. Respuesta 429 con `retry_after: 60`.
318
+
319
+ ## Verificación de firma — detalles
320
+
321
+ El SDK incluye `WebhookHandler` que verifica firmas HMAC-SHA256:
322
+
323
+ ```python
324
+ from contlity import WebhookHandler, WebhookError
325
+
326
+ handler = WebhookHandler(secret="whsec_...")
327
+
328
+ # Verificar + parsear payload
329
+ payload = handler.verify(body_bytes, headers_dict)
330
+
331
+ # Solo verificar firma (sin parsear)
332
+ is_valid = handler.verify_signature_only(body_bytes, "sha256=abc...")
333
+ ```
334
+
335
+ La firma se calcula sobre el body JSON crudo con HMAC-SHA256 usando el `secret` como clave. El header verificado es `X-Contlity-Signature`.