npm package: @kodeme-io/next-core-n8n
Description: N8N workflow integration for Next.js + Odoo applications
Author: ABC Food
Latest version: 0.8.4

# @next-core/n8n

N8N workflow integration for Next.js applications with pre-configured workflows, status tracking, and React hooks.

## Features

### Core Features
- ✅ **Pre-configured Workflows** - 10+ ready-to-use workflow templates
- ✅ **Type-Safe Triggers** - Pre-built methods for all workflows
- ✅ **Status Tracking** - Real-time execution monitoring
- ✅ **React Hooks** - Easy integration with React components
- ✅ **UI Components** - Ready-made trigger and status components
- ✅ **Progress Tracking** - Monitor workflow execution progress
- ✅ **Error Handling** - Comprehensive error management

### 🚀 Enhanced Monitoring Features (NEW)
- ✅ **Structured Logging** - Comprehensive metrics collection and analysis
- ✅ **Real-time Dashboard** - Live monitoring dashboard with health checks
- ✅ **Circuit Breaker** - Prevent cascade failures with automatic circuit breaking
- ✅ **Exponential Backoff** - Intelligent retry logic with configurable backoff
- ✅ **Dead Letter Queue** - Handle failed executions with manual retry capability
- ✅ **WebSocket Updates** - Real-time workflow updates without polling
- ✅ **Performance Analytics** - Track success rates, duration, and error patterns
- ✅ **Health Monitoring** - System-wide health checks and service status
- ✅ **Alert System** - Configurable alerts for high error rates and system issues

### Supported Integrations
- 🤖 **AI** - OpenAI GPT-4 & Vision for summaries and analysis
- 💬 **WhatsApp** - Business API notifications
- 📊 **Redis** - Background job queues
- 🔄 **Odoo** - ERP integration

## Installation

```bash
pnpm add @next-core/n8n
```

## Quick Start

### 1. Setup Clients

```typescript
import {
  createN8NWorkflowTrigger,
  createN8NWorkflowStatus
} from '@next-core/n8n'

// Trigger client (required)
const n8nTrigger = createN8NWorkflowTrigger({
  webhookBaseUrl: process.env.NEXT_PUBLIC_N8N_WEBHOOK_URL!
})

// Status tracker (optional, for execution tracking)
const n8nStatus = createN8NWorkflowStatus({
  apiUrl: process.env.NEXT_PUBLIC_N8N_API_URL!,
  apiKey: process.env.NEXT_PUBLIC_N8N_API_KEY
})
```

### 2. Trigger Workflows

#### Simple Trigger (Fire-and-Forget)

```typescript
const result = await n8nTrigger.visitAISummary({
  visit_id: 123,
  notes: 'Customer interested in Product X...',
  photos: ['https://example.com/photo.jpg'],
  customer_name: 'John Doe'
})

if (result.success) {
  console.log('Workflow triggered:', result.executionId)
}
```

#### With React Hook

```typescript
import { useN8NWorkflow } from '@next-core/n8n'

function MyComponent() {
  const { trigger, isProcessing, result } = useN8NWorkflow(
    'visit-ai-summary',
    {
      client: n8nTrigger,
      statusTracker: n8nStatus,
      waitForCompletion: true,
      onSuccess: (result) => {
        console.log('Summary:', result.data.summary)
      }
    }
  )

  const handleGenerate = async () => {
    await trigger({
      visit_id: 123,
      notes: 'Customer visit notes...'
    })
  }

  return (
    <button onClick={handleGenerate} disabled={isProcessing}>
      {isProcessing ? 'Generating...' : 'Generate Summary'}
    </button>
  )
}
```

#### With UI Component

```typescript
import { WorkflowTriggerWithResult } from '@next-core/n8n'

function MyComponent() {
  return (
    <WorkflowTriggerWithResult
      workflowName="photo-quality-check"
      client={n8nTrigger}
      statusTracker={n8nStatus}
      payload={{
        photo_url: 'https://example.com/photo.jpg',
        quality_threshold: 75
      }}
      waitForCompletion
      buttonText="Check Photo Quality"
      onSuccess={(result) => {
        console.log('Quality Score:', result.data.quality_score)
      }}
    />
  )
}
```

## Available Workflows

### AI Workflows

#### 1. Visit AI Summary
Generates AI summaries from visit notes and photos using OpenAI GPT-4 + Vision.

```typescript
const result = await n8nTrigger.visitAISummary({
  visit_id: 123,
  notes: 'Customer interested in...',
  photos: ['url1.jpg', 'url2.jpg'],
  customer_name: 'John Doe',
  visit_date: '2024-10-07'
})

console.log(result.data.summary)
console.log(result.data.photo_analysis)
```

**Returns:**
```typescript
{
  summary: string
  photo_analysis?: string
}
```

#### 2. Photo Quality Check
Analyzes photo quality and compliance using OpenAI Vision.

```typescript
const result = await n8nTrigger.photoQualityCheck({
  photo_url: 'https://example.com/photo.jpg',
  quality_threshold: 75,
  check_compliance: true
})

console.log(result.data.quality_score) // 0-100
console.log(result.data.compliant) // true/false
console.log(result.data.issues) // string[]
```

**Returns:**
```typescript
{
  quality_score: number
  issues: string[]
  compliant: boolean
}
```

#### 3. Lead Scoring
Scores lead quality (1-100) using AI and Odoo history.

```typescript
const result = await n8nTrigger.leadScoring({
  customer_id: 456,
  company_name: 'Acme Corp',
  industry: 'Manufacturing',
  company_size: '100-500',
  revenue: 5000000
})

console.log(result.data.score) // 1-100
console.log(result.data.priority) // 'low' | 'medium' | 'high'
console.log(result.data.insights)
```

**Returns:**
```typescript
{
  score: number
  insights: string
  priority: 'low' | 'medium' | 'high'
}
```

### WhatsApp Workflows

#### 4. Visit Reminder
Sends visit reminders via WhatsApp Business API.

```typescript
const result = await n8nTrigger.whatsAppVisitReminder({
  customer_phone: '+628123456789',
  customer_name: 'Jane Smith',
  visit_date: '2024-10-15',
  visit_time: '10:00 AM',
  sales_rep_name: 'John Agent',
  language: 'id' // 'en' or 'id'
})

console.log(result.data.message_id)
console.log(result.data.sent) // true/false
```

#### 5. Delivery Notification
```typescript
await n8nTrigger.whatsAppDeliveryNotification({
  customer_phone: '+628123456789',
  customer_name: 'Jane',
  order_number: 'SO001',
  delivery_status: 'dispatched',
  tracking_url: 'https://...'
})
```

#### 6. Order Confirmation
```typescript
await n8nTrigger.whatsAppOrderConfirmation({
  customer_phone: '+628123456789',
  customer_name: 'Jane',
  order_number: 'SO001',
  order_total: 5000000,
  items_count: 3
})
```

### Redis Queue Workflows

#### 7. Report Generation
```typescript
const result = await n8nTrigger.redisReportGeneration({
  report_type: 'sales',
  date_from: '2024-01-01',
  date_to: '2024-12-31',
  user_id: 1,
  format: 'pdf'
})

console.log(result.data.job_id)
console.log(result.data.report_url) // When complete
```

#### 8. Data Export
```typescript
await n8nTrigger.redisDataExport({
  export_type: 'customers',
  format: 'excel',
  user_id: 1,
  filters: { region: 'Jakarta' }
})
```

#### 9. Batch Processing
```typescript
await n8nTrigger.redisBatchProcessing({
  operation: 'update',
  model: 'res.partner',
  records: [
    { id: 1, data: { active: false } },
    { id: 2, data: { active: false } }
  ]
})
```

### Advanced Workflows

#### 10. Multi-Step Visit Workflow
Complete workflow: AI summary + photo analysis + WhatsApp + Odoo update.

```typescript
const result = await n8nTrigger.multiStepVisitWorkflow({
  visit_id: 789,
  notes: 'Customer visit notes...',
  photos: ['url1.jpg', 'url2.jpg'],
  customer_id: 123,
  customer_phone: '+628123456789',
  product_ids: [1, 2, 3],
  notify_manager_if_issues: true
})

console.log(result.data.summary)
console.log(result.data.photo_analysis)
console.log(result.data.whatsapp_sent)
console.log(result.data.odoo_updated)
console.log(result.data.manager_notified)
```

## React Hooks

### useN8NWorkflow

For triggering workflows with state management:

```typescript
import { useN8NWorkflow } from '@next-core/n8n'

const {
  trigger,
  isTriggering,
  isProcessing,
  result,
  error,
  progress,
  reset
} = useN8NWorkflow('visit-ai-summary', {
  client: n8nTrigger,
  statusTracker: n8nStatus,
  waitForCompletion: true,
  onProgress: (progress) => {
    console.log(`${progress.progress}%`)
  },
  onSuccess: (result) => {
    console.log('Success:', result.data)
  },
  onError: (error) => {
    console.error('Error:', error)
  }
})

// Trigger workflow
await trigger({ visit_id: 123, notes: '...' })

// Reset state
reset()
```

### useWorkflowStatus

For tracking existing executions:

```typescript
import { useWorkflowStatus } from '@next-core/n8n'

const {
  execution,
  progress,
  result,
  error,
  isLoading,
  isPolling,
  startPolling,
  stopPolling,
  cancel
} = useWorkflowStatus(executionId, {
  statusTracker: n8nStatus,
  autoStart: true,
  onComplete: (result) => {
    console.log('Completed:', result.data)
  }
})

// Cancel running execution
await cancel()
```

## UI Components

### WorkflowTrigger

Button component for triggering workflows:

```typescript
import { WorkflowTrigger } from '@next-core/n8n'

<WorkflowTrigger
  workflowName="lead-scoring"
  client={n8nTrigger}
  statusTracker={n8nStatus}
  payload={{ customer_id: 456, company_name: 'Acme' }}
  waitForCompletion
  showProgress
  showResult
  buttonText="Score Lead"
  onSuccess={(result) => console.log(result.data)}
/>
```

**Variants:**
- `WorkflowTriggerButton` - Simple button only
- `WorkflowTriggerWithProgress` - With progress bar
- `WorkflowTriggerWithResult` - Full-featured (progress + result)

### WorkflowStatus

Status display component:

```typescript
import { WorkflowStatus } from '@next-core/n8n'

<WorkflowStatus
  executionId="exec-123"
  statusTracker={n8nStatus}
  showProgress
  showDetails
  autoRefresh
  refreshInterval={3000}
  onComplete={(result) => alert('Done!')}
/>
```

## N8N Setup

### 1. Import Workflow Templates

Navigate to `packages/n8n/workflows/` and import JSON templates:

- `visit-ai-summary.json`
- `photo-quality-check.json`
- `lead-scoring.json`
- `whatsapp-visit-reminder.json`
- More in `/workflows/README.md`

### 2. Configure Environment Variables

In your n8n instance:

```bash
OPENAI_API_KEY=sk-...
ODOO_URL=https://your-odoo.com
WHATSAPP_API_TOKEN=...
WHATSAPP_PHONE_NUMBER_ID=...
REDIS_HOST=localhost
REDIS_PORT=6379
```

### 3. Set Up Credentials

In n8n, create these credentials:

1. **OpenAI API** (id: 1, name: "OpenAI Account")
2. **Odoo API Key** (id: 2, name: "Odoo API Key")
3. **WhatsApp Business API Token** (id: 3, name: "WhatsApp Business API Token")

### 4. Activate Workflows

Activate imported workflows in n8n UI.

## Webhook Authentication

### Security Patterns

The package supports 4 authentication patterns for securing webhook endpoints:

#### 1. Bearer Token (Recommended) ✅

```typescript
import { createN8NWorkflowTrigger } from '@next-core/n8n'

const n8nTrigger = createN8NWorkflowTrigger({
  webhookBaseUrl: process.env.NEXT_PUBLIC_N8N_WEBHOOK_URL!,
  webhookAuth: {
    type: 'bearer',
    token: process.env.NEXT_PUBLIC_N8N_WEBHOOK_TOKEN!
  }
})
```

**In n8n Webhook Node:**
- Authentication: Header Auth
- Header Name: `Authorization`
- Header Value: `Bearer your-token-here`

#### 2. Basic Authentication

```typescript
const n8nTrigger = createN8NWorkflowTrigger({
  webhookBaseUrl: process.env.NEXT_PUBLIC_N8N_WEBHOOK_URL!,
  webhookAuth: {
    type: 'basic',
    username: process.env.NEXT_PUBLIC_N8N_USERNAME!,
    password: process.env.NEXT_PUBLIC_N8N_PASSWORD!
  }
})
```

**In n8n Webhook Node:**
- Authentication: Basic Auth
- Username: `your-username`
- Password: `your-password`

#### 3. Custom Header

```typescript
const n8nTrigger = createN8NWorkflowTrigger({
  webhookBaseUrl: process.env.NEXT_PUBLIC_N8N_WEBHOOK_URL!,
  webhookAuth: {
    type: 'header',
    headerName: 'X-Webhook-Secret',
    headerValue: process.env.NEXT_PUBLIC_N8N_WEBHOOK_SECRET!
  }
})
```

**In n8n Webhook Node:**
- Authentication: Header Auth
- Header Name: `X-Webhook-Secret`
- Header Value: `your-secret-value`

#### 4. No Authentication (Development Only) ⚠️

```typescript
const n8nTrigger = createN8NWorkflowTrigger({
  webhookBaseUrl: process.env.NEXT_PUBLIC_N8N_WEBHOOK_URL!,
  webhookAuth: { type: 'none' }
})
```

**Warning:** Only use in development. Production webhooks should always be authenticated.

### Complete Auth Examples

See [/src/examples/auth-patterns.tsx](./src/examples/auth-patterns.tsx) for comprehensive authentication examples including:
- Multi-environment setup
- Security best practices
- Token generation
- Common patterns

## Environment Variables

### Recommended Setup

```bash
# ==============================================
# N8N WEBHOOK CONFIGURATION
# ==============================================

# Required: Webhook base URL
NEXT_PUBLIC_N8N_WEBHOOK_URL=https://n8n.yourdomain.com/webhook

# Webhook Authentication (choose one pattern)

# Option 1: Bearer Token (Recommended)
NEXT_PUBLIC_N8N_WEBHOOK_TOKEN=sk_live_abc123xyz789

# Option 2: Basic Auth
# NEXT_PUBLIC_N8N_USERNAME=username
# NEXT_PUBLIC_N8N_PASSWORD=password

# Option 3: Custom Header
# NEXT_PUBLIC_N8N_WEBHOOK_SECRET=your-secret-key

# ==============================================
# N8N API CONFIGURATION (Optional - for status tracking)
# ==============================================

NEXT_PUBLIC_N8N_API_URL=https://n8n.yourdomain.com/api/v1
NEXT_PUBLIC_N8N_API_KEY=your-n8n-api-key
```

### Backward Compatibility

```bash
# Old way (deprecated but still works)
NEXT_PUBLIC_N8N_WEBHOOK_URL=https://n8n.yourdomain.com/webhook
NEXT_PUBLIC_N8N_API_KEY=your-token  # Used as Bearer token

# New way (recommended)
NEXT_PUBLIC_N8N_WEBHOOK_URL=https://n8n.yourdomain.com/webhook
NEXT_PUBLIC_N8N_WEBHOOK_TOKEN=your-webhook-token
NEXT_PUBLIC_N8N_API_KEY=your-api-key  # For REST API
```

## TypeScript Support

Full TypeScript support with typed payloads:

```typescript
import type {
  VisitAISummaryPayload,
  PhotoQualityCheckPayload,
  LeadScoringPayload,
  WorkflowResult
} from '@next-core/n8n'

const payload: VisitAISummaryPayload = {
  visit_id: 123,
  notes: 'Customer visit notes',
  photos: ['url1.jpg']
}

const result: WorkflowResult<{ summary: string }> =
  await n8nTrigger.visitAISummary(payload)
```

## Error Handling

```typescript
const result = await n8nTrigger.visitAISummary({
  visit_id: 123,
  notes: 'Notes...'
})

if (!result.success) {
  if (result.error?.includes('Missing required environment')) {
    // Configuration error
    console.error('Setup error:', result.error)
  } else {
    // Execution error
    console.error('Workflow failed:', result.error)
  }
}
```

## Advanced Examples

See `/src/examples/basic-usage.tsx` for 10+ complete examples including:

- Fire-and-forget triggers
- Wait for completion
- React hooks usage
- UI components
- Error handling
- Multi-step workflows
- Progress tracking
- Execution cancellation

## Best Practices

1. **Use Pre-configured Methods** - Type-safe and validated
2. **Enable Status Tracking** - For long-running workflows
3. **Handle Errors Gracefully** - Show user feedback
4. **Monitor Progress** - For better UX
5. **Validate Environment** - Check required env vars on startup
6. **Use UI Components** - Consistent UX across app
7. **Batch Similar Operations** - Reduce API calls

## 🚀 Enhanced Monitoring & Observability

### Real-time Monitoring Dashboard

The enhanced monitoring system provides a comprehensive dashboard for tracking workflow health and performance:

```typescript
import { MonitoringDashboard } from '@next-core/n8n'

function AdminDashboard() {
  return (
    <MonitoringDashboard
      config={{
        environment: 'production',
        enableRemoteLogging: true,
        remoteEndpoint: 'https://monitoring.example.com/api/metrics',
        apiKey: process.env.MONITORING_API_KEY
      }}
      refreshInterval={5000}
      showCharts={true}
      showHealthCheck={true}
      onHealthChange={(health) => {
        if (health.status === 'unhealthy') {
          // Trigger alert
          alertSystem.notify(health)
        }
      }}
    />
  )
}
```

### Enhanced Client with Retry & Circuit Breaker

Use the enhanced client for production-grade reliability:

```typescript
import { createN8NEnhancedClient } from '@next-core/n8n'

const enhancedClient = createN8NEnhancedClient(
  {
    webhookBaseUrl: process.env.NEXT_PUBLIC_N8N_WEBHOOK_URL!,
    webhookAuth: {
      type: 'bearer',
      token: process.env.NEXT_PUBLIC_N8N_WEBHOOK_TOKEN!
    }
  },
  // Retry configuration
  {
    maxRetries: 3,
    baseDelay: 1000,
    maxDelay: 30000,
    backoffMultiplier: 2,
    jitter: true,
    retryableErrors: [
      'ECONNRESET',
      'ETIMEDOUT',
      'HTTP 429',
      'HTTP 500',
      'HTTP 503'
    ]
  },
  // Circuit breaker configuration
  {
    failureThreshold: 5,
    resetTimeout: 60000,
    monitoringPeriod: 300000
  }
)

// Use with retry logic
const result = await enhancedClient.triggerWithRetry('visit-ai-summary', payload)

// Batch operations with retry
const batchResults = await enhancedClient.triggerBatchWithRetry([
  { webhookPath: 'workflow-1', payload: payload1 },
  { webhookPath: 'workflow-2', payload: payload2 }
])
```

### Real-time Updates with WebSocket

Get instant workflow updates without polling:

```typescript
import { createN8NWebSocketClient } from '@next-core/n8n'

const wsClient = createN8NWebSocketClient(statusTracker, {
  reconnectInterval: 3000,
  maxReconnectAttempts: 10,
  heartbeatInterval: 30000
})

// Subscribe to specific execution
const unsubscribe = wsClient.subscribe('exec-123', (update) => {
  switch (update.type) {
    case 'progress':
      console.log(`Progress: ${update.progress?.progress}%`)
      break
    case 'completed':
      console.log('Workflow completed:', update.data)
      break
    case 'error':
      console.error('Workflow error:', update.error)
      break
  }
})

// Subscribe to all workflow updates
const unsubscribeAll = wsClient.subscribeToAll({
  onStatus: (execution) => console.log('Status update:', execution),
  onProgress: (progress) => console.log('Progress update:', progress),
  onComplete: (result) => console.log('Completed:', result),
  onError: (executionId, error) => console.error('Error:', executionId, error)
})
```

### Structured Logging & Metrics

Set up comprehensive monitoring and metrics collection:

```typescript
import { getWorkflowMonitor } from '@next-core/n8n'

const monitor = getWorkflowMonitor({
  environment: 'production',
  enableConsoleLogging: false,
  enableRemoteLogging: true,
  remoteEndpoint: 'https://monitoring.example.com/api/metrics',
  apiKey: process.env.MONITORING_API_KEY,
  maxStoredMetrics: 50000,
  enableHealthChecks: true,
  healthCheckInterval: 30000
})

// Subscribe to metrics for custom alerting
monitor.subscribe((metrics) => {
  if (metrics.status === 'error') {
    // Check error rate for this workflow
    const recentMetrics = monitor.getAllMetrics().filter(m => {
      const metricTime = new Date(m.timestamp).getTime()
      const fiveMinutesAgo = Date.now() - 5 * 60 * 1000
      return metricTime > fiveMinutesAgo && m.workflowName === metrics.workflowName
    })

    const errorRate = (recentMetrics.filter(m => m.status === 'error').length / recentMetrics.length) * 100

    if (errorRate > 50) {
      // Trigger alert to Slack, PagerDuty, etc.
      alertSystem.triggerHighErrorRate(metrics.workflowName, errorRate)
    }
  }
})
```

### Performance Analytics

Get detailed performance insights:

```typescript
// Get performance metrics for a specific workflow
const performance = monitor.getPerformanceMetrics('visit-ai-summary', {
  start: '2024-10-01T00:00:00Z',
  end: '2024-10-31T23:59:59Z'
})

if (performance) {
  console.log(`Success Rate: ${performance.successRate.toFixed(1)}%`)
  console.log(`Average Duration: ${performance.averageDuration}ms`)
  console.log(`Total Executions: ${performance.totalExecutions}`)

  // Top errors
  performance.topErrors.forEach(error => {
    console.log(`${error.error}: ${error.count} times (${error.percentage.toFixed(1)}%)`)
  })
}

// Get system health
const health = monitor.getSystemHealth()
if (health) {
  console.log(`System Status: ${health.status}`)
  console.log(`Error Rate: ${health.errorRate.toFixed(1)}%`)
  console.log(`Services:`, health.services)
}
```

### Dead Letter Queue Management

Handle failed executions with retry capability:

```typescript
// View dead letter queue
const dlqItems = enhancedClient.getDeadLetterQueue()
console.log(`DLQ has ${dlqItems.length} items`)

// Retry failed items
const retryResults = await enhancedClient.retryFromDLQ(['dlq-item-1', 'dlq-item-2'])
retryResults.forEach(result => {
  if (result.success) {
    console.log(`Successfully retried: ${result.id}`)
  } else {
    console.error(`Retry failed: ${result.id} - ${result.error}`)
  }
})

// Clear DLQ
enhancedClient.clearDeadLetterQueue()
```

### Circuit Breaker Status

Monitor and manage circuit breaker state:

```typescript
// Get circuit breaker status
const status = enhancedClient.getCircuitBreakerStatus()
console.log(`Circuit State: ${status.state}`)
console.log(`Failure Count: ${status.failureCount}`)

// Reset circuit breaker manually
if (status.state === 'open') {
  enhancedClient.resetCircuitBreaker()
  console.log('Circuit breaker reset manually')
}
```

### Export Metrics for Analysis

Export metrics for external analysis:

```typescript
// Export as JSON
const jsonMetrics = monitor.exportMetrics('json')
fs.writeFileSync('metrics.json', jsonMetrics)

// Export as CSV for Excel analysis
const csvMetrics = monitor.exportMetrics('csv')
fs.writeFileSync('metrics.csv', csvMetrics)
```

### Production Monitoring Setup

Complete production monitoring configuration:

```typescript
// monitoring-setup.ts
import { getWorkflowMonitor, createN8NEnhancedClient, createN8NWebSocketClient } from '@next-core/n8n'

export function setupProductionMonitoring() {
  // 1. Configure monitoring
  const monitor = getWorkflowMonitor({
    environment: 'production',
    enableConsoleLogging: false,
    enableRemoteLogging: true,
    remoteEndpoint: process.env.MONITORING_ENDPOINT,
    apiKey: process.env.MONITORING_API_KEY,
    maxStoredMetrics: 100000,
    metricsRetentionDays: 90,
    enableHealthChecks: true,
    healthCheckInterval: 30000
  })

  // 2. Set up alerts
  monitor.subscribe((metrics) => {
    // High error rate alert
    if (metrics.status === 'error') {
      const errorRate = monitor.getSuccessRate(metrics.workflowName)
      if (errorRate < 90) { // Less than 90% success rate
        alertSystem.sendSlackAlert({
          channel: '#alerts',
          message: `High error rate for ${metrics.workflowName}: ${(100 - errorRate).toFixed(1)}%`,
          severity: 'high'
        })
      }
    }
  })

  // 3. Enhanced client with production config
  const enhancedClient = createN8NEnhancedClient(
    {
      webhookBaseUrl: process.env.NEXT_PUBLIC_N8N_WEBHOOK_URL!,
      webhookAuth: {
        type: 'bearer',
        token: process.env.NEXT_PUBLIC_N8N_WEBHOOK_TOKEN!
      }
    },
    {
      maxRetries: 5,
      baseDelay: 2000,
      maxDelay: 60000,
      backoffMultiplier: 2,
      jitter: true
    },
    {
      failureThreshold: 10,
      resetTimeout: 120000,
      monitoringPeriod: 600000
    }
  )

  // 4. WebSocket client for real-time updates
  const wsClient = createN8NWebSocketClient(
    createN8NWorkflowStatus({
      apiUrl: process.env.NEXT_PUBLIC_N8N_API_URL!,
      apiKey: process.env.NEXT_PUBLIC_N8N_API_KEY
    }),
    {
      reconnectInterval: 5000,
      maxReconnectAttempts: 20,
      heartbeatInterval: 30000
    }
  )

  return { monitor, enhancedClient, wsClient }
}
```

## Monitoring & Debugging (Legacy)

### View Executions

```typescript
const execution = await n8nStatus.getStatus('exec-123')

console.log(execution.status)     // 'running' | 'success' | 'error'
console.log(execution.startedAt)  // ISO timestamp
console.log(execution.finishedAt) // ISO timestamp
console.log(execution.data)       // Result data
console.log(execution.error)      // Error message
```

### Track Progress

```typescript
const progress = await n8nStatus.getProgress('exec-123')

console.log(progress.status)   // Current status
console.log(progress.progress) // 0-100
```

### Cancel Execution

```typescript
const success = await n8nStatus.cancel('exec-123')

if (success) {
  console.log('Workflow canceled')
}
```

## Migration from Old Package

If migrating from `@next-odoo/n8n`:

```typescript
// Old
import { createN8NClient } from '@next-odoo/n8n'
const client = createN8NClient({ webhookBaseUrl: '...' })
await client.trigger('partner-created', { ... })

// New
import { createN8NWorkflowTrigger } from '@next-core/n8n'
const trigger = createN8NWorkflowTrigger({ webhookBaseUrl: '...' })
await trigger.visitAISummary({ ... })
```

The old `N8NClient` is still available for backward compatibility.

## API Reference

### Core Classes
- `N8NWorkflowTrigger` - Trigger workflows
- `N8NWorkflowStatus` - Track execution status
- `N8NClient` - Base client for webhook communication

### Enhanced Monitoring Classes 🆕
- `N8NEnhancedClient` - Enhanced client with retry, circuit breaker, and DLQ
- `N8NWorkflowMonitor` - Comprehensive monitoring and metrics collection
- `N8NWebSocketClient` - Real-time WebSocket updates

### Monitoring Components 🆕
- `MonitoringDashboard` - Real-time monitoring dashboard with health checks

### Hooks
- `useN8NWorkflow` - Trigger with state management
- `useWorkflowStatus` - Track existing execution

### Components
- `WorkflowTrigger` - Trigger button
- `WorkflowStatus` - Status display

### Types
- `WorkflowName` - All workflow names
- `WorkflowResult<T>` - Execution result
- `WorkflowExecution` - Execution metadata
- `WorkflowProgress` - Progress tracking

### Monitoring Types 🆕
- `WorkflowMetrics` - Structured workflow execution metrics
- `WorkflowPerformanceMetrics` - Performance analytics data
- `SystemHealthMetrics` - System-wide health status
- `MonitoringConfig` - Configuration for monitoring system
- `RetryConfig` - Configuration for retry logic
- `CircuitBreakerConfig` - Configuration for circuit breaker
- `DeadLetterQueueItem` - Failed execution item in DLQ
- `WebSocketConfig` - Configuration for WebSocket client
- `WorkflowUpdate` - Real-time workflow update message

### Factory Functions
- `createN8NWorkflowTrigger` - Create workflow trigger client
- `createN8NWorkflowStatus` - Create status tracking client
- `createN8NEnhancedClient` - Create enhanced client with monitoring
- `createN8NWebSocketClient` - Create WebSocket client for real-time updates
- `getWorkflowMonitor` - Get or create global workflow monitor
- `resetWorkflowMonitor` - Reset global monitor instance

### Key Methods 🆕

#### N8NEnhancedClient
```typescript
triggerWithRetry(webhookPath, payload, retryConfig?)  // Trigger with retry logic
triggerBatchWithRetry(payloads)                        // Batch trigger with retry
getDeadLetterQueue()                                   // Get failed executions
retryFromDLQ(itemIds?)                                // Retry failed executions
clearDeadLetterQueue()                                 // Clear DLQ
getCircuitBreakerStatus()                             // Get circuit breaker state
resetCircuitBreaker()                                 // Reset circuit breaker
```

#### N8NWorkflowMonitor
```typescript
trackExecution(metrics)                               // Track workflow execution
getPerformanceMetrics(workflowName, timeRange?)       // Get performance analytics
getSystemHealth()                                     // Get system health status
getSuccessRate(workflowName?, timeRange?)             // Calculate success rate
getAverageDuration(workflowName, timeRange?)          // Calculate average duration
subscribe(callback)                                   // Subscribe to metrics updates
exportMetrics(format)                                 // Export metrics (JSON/CSV)
clearMetrics()                                        // Clear stored metrics
```

#### N8NWebSocketClient
```typescript
connect()                                             // Connect to WebSocket
disconnect()                                          // Disconnect from WebSocket
subscribe(executionId, callback)                     // Subscribe to execution updates
subscribeToAll(callbacks)                             // Subscribe to all updates
getConnectionState()                                 // Get connection status
```

See `/src/index.ts` for complete exports.

## Support

- **Documentation:** [/workflows/README.md](./workflows/README.md)
- **Examples:** [/src/examples/](./src/examples/)
- **🚀 Monitoring Example:** [/src/examples/monitoring-example.tsx](./src/examples/monitoring-example.tsx) - Complete monitoring setup
- **N8N Docs:** https://docs.n8n.io

### New Monitoring Examples 🆕

- **[monitoring-example.tsx](./src/examples/monitoring-example.tsx)** - Complete monitoring dashboard with all features
- **[basic-usage.tsx](./src/examples/basic-usage.tsx)** - 10+ basic workflow examples
- **[auth-patterns.tsx](./src/examples/auth-patterns.tsx)** - Authentication pattern examples

## License

MIT