Commit Graph

55 Commits

Author SHA1 Message Date
Consultoria AS
bcabbd4959 feat: add CLI script for emergency FIEL decryption from filesystem
Decrypts .cer and .key from FIEL_STORAGE_PATH/<RFC>/ to /tmp with
30-minute auto-cleanup for security.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-15 23:33:18 +00:00
Consultoria AS
12dda005af feat: add dual filesystem storage for FIEL credentials
Save encrypted .cer, .key, and metadata to FIEL_STORAGE_PATH alongside
the existing DB storage. Each file has separate .iv and .tag sidecar files.
Filesystem failure is non-blocking (logs warning, DB remains primary).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-15 23:32:42 +00:00
Consultoria AS
d8f9f92389 refactor: remove schema-manager and tenantSchema backward compat
Delete schema-manager.ts (replaced by TenantConnectionManager).
Remove deprecated tenantSchema from Express Request interface.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-15 23:31:06 +00:00
Consultoria AS
96e1ea554c feat: add graceful shutdown and PM2 cross-worker messaging
Close all tenant DB pools on SIGTERM/SIGINT for clean restarts.
Support PM2 cluster invalidate-tenant-cache messages.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-15 23:30:08 +00:00
Consultoria AS
b064f15404 refactor: migrate all tenant services and controllers to pool-based queries
Replace Prisma raw queries with pg.Pool for all tenant-scoped services:
cfdi, dashboard, impuestos, alertas, calendario, reportes, export, and SAT.
Controllers now pass req.tenantPool instead of req.tenantSchema.
Fixes SQL injection in calendario.service.ts (parameterized interval).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-15 23:29:20 +00:00
Consultoria AS
7eaeefa09d feat: rewrite tenants service to use TenantConnectionManager
- Replace inline schema SQL with tenantDb.provisionDatabase
- Delete now soft-deletes DB (rename) and invalidates pool
- Use PLANS config for default limits per plan

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-15 23:20:37 +00:00
Consultoria AS
2b5a856845 feat: update auth service to provision databases via TenantConnectionManager
- Replace createTenantSchema with tenantDb.provisionDatabase
- JWT payload now includes databaseName (already renamed from schemaName)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-15 23:19:58 +00:00
Consultoria AS
8bfb8912c1 feat: rewrite tenant middleware for pool-based tenant resolution
- Resolve tenant DB via TenantConnectionManager instead of SET search_path
- Add tenantPool to Express Request for direct pool queries
- Keep tenantSchema as backward compat until all services are migrated
- Support admin impersonation via X-View-Tenant header

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-15 23:19:12 +00:00
Consultoria AS
d6b86dbbd3 feat: add TenantConnectionManager with dynamic pool management
- Adds pg dependency for direct PostgreSQL connections to tenant DBs
- TenantConnectionManager: singleton managing Map<tenantId, Pool>
- provisionDatabase: creates new DB with tables and indexes
- deprovisionDatabase: soft-deletes by renaming DB
- Automatic idle pool cleanup every 60s (5min threshold)
- Max 3 connections per pool (6/tenant with 2 PM2 workers)
- Graceful shutdown support for all pools

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-15 23:17:54 +00:00
Consultoria AS
f96a9c55c5 feat(saas): update schema for db-per-tenant and per-component FIEL encryption
- Rename Tenant.schemaName to databaseName across all services
- Add Subscription and Payment models to Prisma schema
- Update FielCredential to per-component IV/tag encryption columns
- Switch FIEL encryption key from JWT_SECRET to FIEL_ENCRYPTION_KEY
- Add Subscription and Payment shared types
- Update JWTPayload to use databaseName

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-15 23:15:55 +00:00
Consultoria AS
0d17fe3494 feat: add env vars for FIEL encryption, MercadoPago, SMTP, and admin email
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-15 23:08:46 +00:00
Consultoria AS
08a7312761 perf(cfdi): optimize page performance
Database optimizations:
- Add indexes on fecha_emision, tipo, estado, rfc_emisor, rfc_receptor
- Add trigram indexes for fast ILIKE searches on nombre fields
- Combine COUNT with main query using window function (1 query instead of 2)

Frontend optimizations:
- Add 300ms debounce to autocomplete searches
- Add staleTime (30s) and gcTime (5min) to useCfdis hook
- Reduce unnecessary API calls on every keystroke

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-17 07:15:33 +00:00
Consultoria AS
0e49c0922d feat(cfdi): add autocomplete for emisor and receptor filters
- Add /cfdi/emisores and /cfdi/receptores API endpoints
- Search by RFC or nombre with ILIKE
- Show suggestions dropdown while typing (min 2 chars)
- Click suggestion to select and populate filter input
- Show loading state while searching

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-17 07:07:01 +00:00
Consultoria AS
5c6367839f fix(cfdi): cast date filters to proper PostgreSQL date type
- Add ::date cast to fechaInicio filter
- Add ::date cast and +1 day interval to fechaFin to include full day
- Fixes "operator does not exist: timestamp >= text" error

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-17 07:03:49 +00:00
Consultoria AS
29ac067a82 feat(cfdi): add inline column filters for date, emisor, receptor
- Add emisor and receptor filters to CfdiFilters type
- Update backend service to filter by emisor/receptor (RFC or nombre)
- Update controller and API client to pass new filters
- Add toggle button to show/hide column filters in table
- Add date range inputs for fecha filter
- Add text inputs for emisor and receptor filters
- Apply filters on Enter key or search button click
- Add clear filters button when filters are active

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-17 06:21:13 +00:00
Consultoria AS
5ff5629cd8 fix(api): add UUID type cast in getCfdiById and getXmlById
PostgreSQL requires explicit type cast when comparing UUID columns
with text parameters in raw queries.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-17 02:51:45 +00:00
Consultoria AS
427c94fb9d feat(api): add GET /cfdi/:id/xml endpoint
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-17 02:34:16 +00:00
Consultoria AS
266e547eb5 feat(api): add xmlOriginal to getCfdiById and add getXmlById
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-17 02:33:21 +00:00
Consultoria AS
3466ec740e fix: resolve TypeScript compilation errors in API
- Add explicit IRouter type to all route files
- Add explicit Express type to app.ts
- Fix env.ts by moving getCorsOrigins after parsing
- Fix token.ts SignOptions type for expiresIn
- Cast req.params.id to String() in controllers

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-31 06:48:26 +00:00
Consultoria AS
1fe462764f fix: use transaction in refreshTokens to prevent race conditions
- Wrap token refresh logic in Prisma transaction
- Use deleteMany instead of delete to handle race conditions gracefully

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-31 03:09:32 +00:00
Consultoria AS
dcc33af523 feat: SAT sync improvements and documentation
- Add custom date range support for SAT synchronization
- Fix UUID cast in SQL queries for sat_sync_job_id
- Fix processInitialSync to respect custom dateFrom/dateTo parameters
- Add date picker UI for custom period sync
- Add comprehensive documentation for SAT sync implementation

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-25 03:01:27 +00:00
Consultoria AS
492cd62772 debug: add logging to verify SAT status 2026-01-25 02:20:29 +00:00
Consultoria AS
008f586b54 fix: reduce sync years to 6 (SAT maximum allowed)
SAT only allows downloading CFDIs from the last 6 years.
Reduced from 10 to avoid wasted requests.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-25 02:17:33 +00:00
Consultoria AS
38466a2b23 fix: use isTypeOf for SAT status request checking
The StatusRequest class has an isTypeOf method that properly checks
the status. Using getValue() and comparing numbers was unreliable.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-25 02:17:17 +00:00
Consultoria AS
98d704a549 feat: use @nodecfdi/sat-ws-descarga-masiva for SAT sync
Replace manual SOAP authentication with the official nodecfdi library
which properly handles WS-Security signatures for SAT web services.

- Add sat-client.service.ts using Fiel.create() for authentication
- Update sat.service.ts to use new client
- Update fiel.service.ts to return raw certificate data

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-25 02:07:55 +00:00
Consultoria AS
c52548a2bb fix: remove double base64 encoding of certificate in SAT auth
The PEM certificate content is already base64 encoded after removing
headers and newlines. We should not re-encode it.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-25 01:51:57 +00:00
Consultoria AS
121fe731d0 fix: use combined encryption for FIEL credentials
Each piece of data was being encrypted with a different IV, but only
the first IV was saved. Now using encryptFielCredentials/decryptFielCredentials
helper functions that encrypt all data together with a single IV/tag.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-25 01:50:15 +00:00
Consultoria AS
02ccfb41a0 fix: convert certificate dates to Date objects in fiel.service
The @nodecfdi/credentials library returns date values that aren't
JavaScript Date objects, causing getTime() to fail.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-25 01:46:54 +00:00
Consultoria AS
75a9819c1e fix: use JWT tenantId instead of header in FIEL and SAT controllers
The controllers were looking for x-tenant-id header which the frontend
doesn't send. Now using req.user!.tenantId from the JWT token instead.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-25 01:45:42 +00:00
Consultoria AS
2dd22ec152 fix: correct global admin tenant RFC 2026-01-25 01:38:38 +00:00
Consultoria AS
69efb585d3 feat: add global user administration for admin users
Backend:
- Add getAllUsuarios() to get users from all tenants
- Add updateUsuarioGlobal() to edit users and change their tenant
- Add deleteUsuarioGlobal() for global user deletion
- Add global admin check based on tenant RFC
- Add new API routes: /usuarios/global/*

Frontend:
- Add UserListItem.tenantId and tenantName fields
- Add /admin/usuarios page with full user management
- Support filtering by tenant and search
- Inline editing for name, role, and tenant assignment
- Group users by company for better organization
- Add "Admin Usuarios" menu item for admin navigation

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-25 01:22:34 +00:00
Consultoria AS
e50e7100f1 feat(sat): add API endpoints for FIEL and SAT sync (Phase 7)
- Add FIEL controller with upload, status, and delete endpoints
- Add SAT controller with sync start, status, history, and retry
- Add admin endpoints for cron job info and manual execution
- Register new routes in app.ts
- All endpoints protected with authentication middleware

Endpoints added:
- POST /api/fiel/upload
- GET /api/fiel/status
- DELETE /api/fiel
- POST /api/sat/sync
- GET /api/sat/sync/status
- GET /api/sat/sync/history
- GET /api/sat/sync/:id
- POST /api/sat/sync/:id/retry
- GET /api/sat/cron
- POST /api/sat/cron/run

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-25 00:56:47 +00:00
Consultoria AS
0a65c60570 feat(sat): add scheduled cron job for daily sync (Phase 6)
- Add sat-sync.job.ts with scheduled daily sync at 3:00 AM
- Automatic detection of tenants with active FIEL
- Initial sync (10 years) for new tenants, daily for existing
- Concurrent processing with configurable batch size
- Integration with app startup for production environment
- Install node-cron dependency

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-25 00:53:54 +00:00
Consultoria AS
473912bfd7 feat(sat): add main sync orchestrator service (Phase 5)
- Add sat.service.ts as the main orchestrator that coordinates:
  - FIEL credential retrieval and token management
  - SAT download request workflow
  - Package processing and CFDI storage
  - Progress tracking and job management
- Support for initial sync (10 years history) and daily sync
- Automatic token refresh during long-running syncs
- Month-by-month processing to avoid SAT limits
- Raw SQL queries for multi-tenant schema isolation

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-25 00:52:18 +00:00
Consultoria AS
09684f77b9 feat(sat): add CFDI XML parser service (Phase 4)
- Add sat-parser.service.ts for processing SAT packages:
  - Extract XML files from ZIP packages
  - Parse CFDI 4.0 XML structure with proper namespace handling
  - Extract fiscal data: UUID, amounts, taxes, dates, RFC info
  - Map SAT types (I/E/T/P/N) to application types
  - Handle IVA and ISR retention calculations
- Install @nodecfdi/cfdi-core dependency

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-25 00:50:11 +00:00
Consultoria AS
56e6e27ab3 feat(sat): add SAT authentication and download services (Phase 3)
- Add sat-auth.service.ts for SAML token authentication with SAT
  using FIEL credentials and SOAP protocol
- Add sat-download.service.ts with full download workflow:
  - Request CFDI download (emitted/received)
  - Verify request status with polling support
  - Download ZIP packages when ready
  - Helper functions for status checking
- Install fast-xml-parser and adm-zip dependencies

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-25 00:49:02 +00:00
Consultoria AS
a64aa11548 feat(sat): add FIEL management and encryption services (Phase 2)
- Add sat-crypto.service.ts with AES-256-GCM encryption for secure
  credential storage using JWT_SECRET as key derivation source
- Add fiel.service.ts with complete FIEL lifecycle management:
  - Upload and validate FIEL credentials (.cer/.key files)
  - Verify certificate is FIEL (not CSD) and not expired
  - Store encrypted credentials in database
  - Retrieve and decrypt credentials for SAT sync operations
- Install @nodecfdi/credentials for FIEL/CSD handling

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-25 00:44:04 +00:00
Consultoria AS
787aac9a4c feat(sat): add database models for SAT sync
Phase 1 - Database models:
- Add FielCredential model for encrypted FIEL storage
- Add SatSyncJob model for sync job tracking
- Add SAT-related enums (SatSyncType, SatSyncStatus, CfdiSyncType)
- Add TypeScript types in shared package
- Relations: Tenant -> FielCredential (1:1), Tenant -> SatSyncJobs (1:N)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-25 00:38:51 +00:00
Consultoria AS
7454cf67e6 chore: increase max upload size to 1GB
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-22 07:09:03 +00:00
Consultoria AS
db1f2eaecd perf: optimize bulk XML upload for 100k+ files
Backend:
- Add batch insert using multi-row INSERT with ON CONFLICT
- Process in batches of 500 records for optimal DB performance
- Return detailed batch results (inserted, duplicates, errors)

Frontend:
- Parse files in chunks of 500 to prevent memory issues
- Upload in batches of 200 CFDIs per request
- Add detailed progress bar with real-time stats
- Show upload statistics (loaded, duplicates, errors)
- Add cancel functionality during upload
- Refresh data after upload completes

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-22 07:01:04 +00:00
Consultoria AS
c3ce7199af feat: bulk XML upload, period selector, and session persistence
- Add bulk XML CFDI upload support (up to 300MB)
- Add period selector component for month/year navigation
- Fix session persistence on page refresh (Zustand hydration)
- Fix income/expense classification based on tenant RFC
- Fix IVA calculation from XML (correct Impuestos element)
- Add error handling to reportes page
- Support multiple CORS origins
- Update reportes service with proper Decimal/BigInt handling
- Add RFC to tenant view store for proper CFDI classification
- Update README with changelog and new features

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-22 06:51:53 +00:00
Consultoria AS
0c10c887d2 feat: add multi-tenant client management for admins
- Add tenants API endpoints (list, get, create)
- Add tenant middleware override via X-View-Tenant header
- Add TenantSelector dropdown component in header
- Add tenant view store with persistence
- Add Clientes management page
- Update all navigation layouts with Clientes link for admins

Admins can now:
- View list of all clients
- Create new clients with automatic schema setup
- Switch between viewing different clients' data
- See which client they are currently viewing

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-22 03:55:44 +00:00
Consultoria AS
74b1bb8c02 fix: add missing UI components and utilities
- Add tabs.tsx component
- Add select.tsx component
- Add formatCurrency utility function
- Export new components from index

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-22 03:40:03 +00:00
Consultoria AS
f4b42aa8c2 fix: add missing errors utility and fix seed timestamp casting
- Add apps/api/src/utils/errors.ts with AppError class
- Fix seed.ts timestamp casting for calendario_fiscal

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-22 03:30:49 +00:00
Consultoria AS
0c4b1a43a9 feat(fase3): update sidebar navigation and seed with calendario_fiscal
- Add navigation items for Reportes, Calendario, Alertas, Usuarios
- Add calendario_fiscal table creation in seed
- Insert demo fiscal events for all 12 months

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-22 03:04:25 +00:00
Consultoria AS
9b8aaea7eb feat(alertas): add alerts CRUD with stats and management UI
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-22 03:02:20 +00:00
Consultoria AS
6d59c8d842 feat(export): add Excel export for CFDIs and reports
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-22 02:58:19 +00:00
Consultoria AS
9d49f8a833 feat(api): add impuestos API endpoints (IVA/ISR mensual y resumen)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-22 02:23:54 +00:00
Consultoria AS
a81d8437ce feat(api): add CFDI API endpoints (list, detail, resumen)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-22 02:21:25 +00:00
Consultoria AS
4d0d23c642 feat(api): add dashboard API endpoints (kpis, ingresos-egresos, resumen-fiscal, alertas) 2026-01-22 02:19:22 +00:00