feat: Implement Phase 3 & 4 - AI Reports & ERP Integrations
## Phase 3: DeepSeek AI Integration ### AI Services (apps/api/src/services/ai/) - DeepSeek API client with streaming, rate limiting, retries - AI service for financial analysis, executive summaries, recommendations - Optimized prompts for Mexican CFO digital assistant - Redis caching for AI responses ### Report Generation (apps/api/src/services/reports/) - ReportGenerator: monthly, quarterly, annual, custom reports - PDF generator with corporate branding (PDFKit) - Report templates for PYME, Startup, Enterprise - Spanish prompts for financial narratives - MinIO storage for generated PDFs ### AI & Reports API Routes - POST /api/ai/analyze - Financial metrics analysis - POST /api/ai/chat - CFO digital chat with streaming - POST /api/reports/generate - Async report generation - GET /api/reports/:id/download - PDF download - BullMQ jobs for background processing ### Frontend Pages - /reportes - Report listing with filters - /reportes/nuevo - 3-step wizard for report generation - /reportes/[id] - Full report viewer with charts - /asistente - CFO Digital chat interface - Components: ChatInterface, ReportCard, AIInsightCard ## Phase 4: ERP Integrations ### CONTPAQi Connector (SQL Server) - Contabilidad: catalog, polizas, balanza, estado de resultados - Comercial: clientes, proveedores, facturas, inventario - Nominas: empleados, nominas, percepciones/deducciones ### Aspel Connector (Firebird/SQL Server) - COI: accounting, polizas, balanza, auxiliares - SAE: sales, purchases, inventory, A/R, A/P - NOI: payroll, employees, receipts - BANCO: bank accounts, movements, reconciliation - Latin1 to UTF-8 encoding handling ### Odoo Connector (XML-RPC) - Accounting: chart of accounts, journal entries, reports - Invoicing: customer/vendor invoices, payments - Partners: customers, vendors, statements - Inventory: products, stock levels, valuations - Multi-company and version 14-17 support ### Alegra Connector (REST API) - Invoices, credit/debit notes with CFDI support - Contacts with Mexican fiscal fields (RFC, regimen) - Payments and bank reconciliation - Financial reports: trial balance, P&L, balance sheet - Webhook support for real-time sync ### SAP Business One Connector (OData/Service Layer) - Session management with auto-refresh - Financials: chart of accounts, journal entries, reports - Sales: invoices, credit notes, delivery notes, orders - Purchasing: bills, POs, goods receipts - Inventory: items, stock, transfers, valuation - Banking: accounts, payments, cash flow ### Integration Manager - Unified interface for all connectors - BullMQ scheduler for automated sync - Webhook handling for real-time updates - Migration 003_integrations.sql with sync tables - Frontend page /integraciones for configuration Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
338
apps/api/src/services/integrations/alegra/index.ts
Normal file
338
apps/api/src/services/integrations/alegra/index.ts
Normal file
@@ -0,0 +1,338 @@
|
||||
/**
|
||||
* Alegra Integration Module
|
||||
* Modulo completo de integracion con Alegra - Software contable cloud
|
||||
*
|
||||
* Exporta todos los componentes necesarios para integrar Horux Strategy con Alegra:
|
||||
* - Cliente REST API con rate limiting y reintentos
|
||||
* - Conectores para facturas, contactos, pagos y reportes
|
||||
* - Servicio de sincronizacion bidireccional
|
||||
* - Tipos y schemas de validacion
|
||||
*
|
||||
* Uso basico:
|
||||
* ```typescript
|
||||
* import { createAlegraClient, createAlegraSyncService } from './services/integrations/alegra';
|
||||
*
|
||||
* const client = createAlegraClient({
|
||||
* email: 'usuario@ejemplo.com',
|
||||
* token: 'tu-api-token',
|
||||
* country: 'MX',
|
||||
* });
|
||||
*
|
||||
* // Usar conectores directamente
|
||||
* const invoices = await client.get('/invoices');
|
||||
*
|
||||
* // O usar el servicio de sincronizacion
|
||||
* const syncService = createAlegraSyncService(config);
|
||||
* await syncService.syncToHorux(tenantId, syncConfig);
|
||||
* ```
|
||||
*/
|
||||
|
||||
// ============================================================================
|
||||
// Client
|
||||
// ============================================================================
|
||||
|
||||
export { AlegraClient, createAlegraClient } from './alegra.client.js';
|
||||
|
||||
// ============================================================================
|
||||
// Connectors
|
||||
// ============================================================================
|
||||
|
||||
export {
|
||||
AlegraInvoicesConnector,
|
||||
createInvoicesConnector,
|
||||
} from './invoices.connector.js';
|
||||
|
||||
export {
|
||||
AlegraContactsConnector,
|
||||
createContactsConnector,
|
||||
} from './contacts.connector.js';
|
||||
|
||||
export {
|
||||
AlegraPaymentsConnector,
|
||||
createPaymentsConnector,
|
||||
} from './payments.connector.js';
|
||||
|
||||
export {
|
||||
AlegraReportsConnector,
|
||||
createReportsConnector,
|
||||
} from './reports.connector.js';
|
||||
|
||||
// ============================================================================
|
||||
// Sync Service
|
||||
// ============================================================================
|
||||
|
||||
export {
|
||||
AlegraSyncService,
|
||||
createAlegraSyncService,
|
||||
} from './alegra.sync.js';
|
||||
|
||||
// ============================================================================
|
||||
// Types
|
||||
// ============================================================================
|
||||
|
||||
export type {
|
||||
// Config & Auth
|
||||
AlegraConfig,
|
||||
AlegraAuth,
|
||||
AlegraCountry,
|
||||
|
||||
// Pagination
|
||||
AlegraPaginationParams,
|
||||
AlegraDateFilter,
|
||||
AlegraPaginatedResponse,
|
||||
|
||||
// Contacts
|
||||
AlegraContact,
|
||||
AlegraContactType,
|
||||
AlegraIdentificationType,
|
||||
AlegraAddress,
|
||||
AlegraPhone,
|
||||
AlegraInternalContact,
|
||||
AlegraContactBalance,
|
||||
AlegraContactStatement,
|
||||
AlegraStatementTransaction,
|
||||
|
||||
// Invoices
|
||||
AlegraInvoice,
|
||||
AlegraInvoiceStatus,
|
||||
AlegraInvoiceType,
|
||||
AlegraInvoiceItem,
|
||||
AlegraItemTax,
|
||||
AlegraRetention,
|
||||
AlegraInvoiceTax,
|
||||
AlegraStamp,
|
||||
AlegraPaymentReference,
|
||||
AlegraNumberTemplate,
|
||||
|
||||
// Credit & Debit Notes
|
||||
AlegraCreditNote,
|
||||
AlegraDebitNote,
|
||||
|
||||
// Payments
|
||||
AlegraPaymentReceived,
|
||||
AlegraPaymentMade,
|
||||
AlegraPaymentType,
|
||||
AlegraPaymentMethod,
|
||||
|
||||
// Bank
|
||||
AlegraBankAccount,
|
||||
AlegraBankAccountType,
|
||||
AlegraBankTransaction,
|
||||
AlegraBankTransactionType,
|
||||
AlegraBankReconciliation,
|
||||
|
||||
// Items
|
||||
AlegraItem,
|
||||
AlegraItemType,
|
||||
AlegraItemPrice,
|
||||
AlegraItemInventory,
|
||||
AlegraItemVariant,
|
||||
|
||||
// Categories & Cost Centers
|
||||
AlegraCategory,
|
||||
AlegraCategoryType,
|
||||
AlegraCostCenter,
|
||||
|
||||
// Tax & Payment Terms
|
||||
AlegraTax,
|
||||
AlegraTaxType,
|
||||
AlegraPaymentTerm,
|
||||
|
||||
// Currency & Seller
|
||||
AlegraCurrency,
|
||||
AlegraSeller,
|
||||
AlegraPriceList,
|
||||
|
||||
// Reports
|
||||
AlegraTrialBalance,
|
||||
AlegraTrialBalanceAccount,
|
||||
AlegraProfitAndLoss,
|
||||
AlegraPLSection,
|
||||
AlegraBalanceSheet,
|
||||
AlegraBalanceSection,
|
||||
AlegraCashFlow,
|
||||
AlegraCashFlowSection,
|
||||
AlegraTaxReport,
|
||||
|
||||
// Webhooks
|
||||
AlegraWebhookEvent,
|
||||
AlegraWebhookSubscription,
|
||||
AlegraWebhookPayload,
|
||||
|
||||
// Sync
|
||||
AlegraSyncState,
|
||||
AlegraSyncResult,
|
||||
|
||||
// Errors
|
||||
AlegraErrorCode,
|
||||
} from './alegra.types.js';
|
||||
|
||||
export {
|
||||
AlegraError,
|
||||
AlegraRateLimitError,
|
||||
AlegraAuthError,
|
||||
} from './alegra.types.js';
|
||||
|
||||
// ============================================================================
|
||||
// Schemas
|
||||
// ============================================================================
|
||||
|
||||
export {
|
||||
// Config
|
||||
AlegraConfigSchema,
|
||||
type AlegraConfigInput,
|
||||
|
||||
// Pagination & Filters
|
||||
PaginationSchema,
|
||||
DateFilterSchema,
|
||||
PeriodSchema,
|
||||
type PaginationInput,
|
||||
type DateFilterInput,
|
||||
type PeriodInput,
|
||||
|
||||
// Contacts
|
||||
ContactInputSchema,
|
||||
ContactFilterSchema,
|
||||
IdentificationTypeSchema,
|
||||
ContactTypeSchema,
|
||||
AddressSchema,
|
||||
type ContactInput,
|
||||
type ContactFilter,
|
||||
|
||||
// Invoices
|
||||
InvoiceInputSchema,
|
||||
InvoiceFilterSchema,
|
||||
InvoiceItemSchema,
|
||||
InvoiceStatusSchema,
|
||||
type InvoiceInput,
|
||||
type InvoiceFilter,
|
||||
|
||||
// Credit Notes
|
||||
CreditNoteInputSchema,
|
||||
CreditNoteFilterSchema,
|
||||
type CreditNoteInput,
|
||||
type CreditNoteFilter,
|
||||
|
||||
// Debit Notes
|
||||
DebitNoteInputSchema,
|
||||
DebitNoteFilterSchema,
|
||||
type DebitNoteInput,
|
||||
type DebitNoteFilter,
|
||||
|
||||
// Payments
|
||||
PaymentReceivedInputSchema,
|
||||
PaymentMadeInputSchema,
|
||||
PaymentFilterSchema,
|
||||
PaymentMethodSchema,
|
||||
type PaymentReceivedInput,
|
||||
type PaymentMadeInput,
|
||||
type PaymentFilter,
|
||||
|
||||
// Bank Accounts
|
||||
BankAccountInputSchema,
|
||||
BankAccountFilterSchema,
|
||||
BankTransactionFilterSchema,
|
||||
BankAccountTypeSchema,
|
||||
type BankAccountInput,
|
||||
type BankAccountFilter,
|
||||
type BankTransactionFilter,
|
||||
|
||||
// Items
|
||||
ItemInputSchema,
|
||||
ItemFilterSchema,
|
||||
ItemTypeSchema,
|
||||
type ItemInput,
|
||||
type ItemFilter,
|
||||
|
||||
// Categories & Cost Centers
|
||||
CategoryInputSchema,
|
||||
CostCenterInputSchema,
|
||||
type CategoryInput,
|
||||
type CostCenterInput,
|
||||
|
||||
// Tax
|
||||
TaxInputSchema,
|
||||
type TaxInput,
|
||||
|
||||
// Reports
|
||||
TrialBalanceRequestSchema,
|
||||
ProfitAndLossRequestSchema,
|
||||
BalanceSheetRequestSchema,
|
||||
CashFlowRequestSchema,
|
||||
TaxReportRequestSchema,
|
||||
type TrialBalanceRequest,
|
||||
type ProfitAndLossRequest,
|
||||
type BalanceSheetRequest,
|
||||
type CashFlowRequest,
|
||||
type TaxReportRequest,
|
||||
|
||||
// Webhooks
|
||||
WebhookEventSchema,
|
||||
WebhookSubscriptionInputSchema,
|
||||
type WebhookSubscriptionInput,
|
||||
|
||||
// Sync
|
||||
SyncConfigSchema,
|
||||
type SyncConfig,
|
||||
|
||||
// Utilities
|
||||
validateAlegraConfig,
|
||||
validatePeriod,
|
||||
validatePagination,
|
||||
} from './alegra.schema.js';
|
||||
|
||||
// ============================================================================
|
||||
// Facade Class for Easy Usage
|
||||
// ============================================================================
|
||||
|
||||
import { AlegraClient, createAlegraClient } from './alegra.client.js';
|
||||
import { AlegraInvoicesConnector, createInvoicesConnector } from './invoices.connector.js';
|
||||
import { AlegraContactsConnector, createContactsConnector } from './contacts.connector.js';
|
||||
import { AlegraPaymentsConnector, createPaymentsConnector } from './payments.connector.js';
|
||||
import { AlegraReportsConnector, createReportsConnector } from './reports.connector.js';
|
||||
import { AlegraSyncService, createAlegraSyncService } from './alegra.sync.js';
|
||||
import type { AlegraConfig } from './alegra.types.js';
|
||||
|
||||
/**
|
||||
* Clase de fachada que proporciona acceso unificado a toda la funcionalidad de Alegra
|
||||
*/
|
||||
export class Alegra {
|
||||
public readonly client: AlegraClient;
|
||||
public readonly invoices: AlegraInvoicesConnector;
|
||||
public readonly contacts: AlegraContactsConnector;
|
||||
public readonly payments: AlegraPaymentsConnector;
|
||||
public readonly reports: AlegraReportsConnector;
|
||||
public readonly sync: AlegraSyncService;
|
||||
|
||||
constructor(config: AlegraConfig) {
|
||||
this.client = createAlegraClient(config);
|
||||
this.invoices = createInvoicesConnector(this.client);
|
||||
this.contacts = createContactsConnector(this.client);
|
||||
this.payments = createPaymentsConnector(this.client);
|
||||
this.reports = createReportsConnector(this.client);
|
||||
this.sync = createAlegraSyncService(config);
|
||||
}
|
||||
|
||||
/**
|
||||
* Verifica si las credenciales son validas
|
||||
*/
|
||||
async testConnection(): Promise<boolean> {
|
||||
return this.client.testConnection();
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtiene informacion de la compania
|
||||
*/
|
||||
async getCompanyInfo(): Promise<Record<string, unknown>> {
|
||||
return this.client.getCompanyInfo();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Crea una instancia de Alegra con todos los conectores
|
||||
*/
|
||||
export function createAlegra(config: AlegraConfig): Alegra {
|
||||
return new Alegra(config);
|
||||
}
|
||||
|
||||
export default Alegra;
|
||||
Reference in New Issue
Block a user