npm package: @iota-big3/sdk-enterprise
Description: Enterprise integration capabilities for SchoolOS SDK
Author: IOTA Big3 Team
Latest version: 2.0.2

# @iota-big3/sdk-enterprise

Enterprise integration capabilities for IOTA SDK, including Legacy System Adapters, Enterprise Service Bus (ESB), Workflow Orchestration, Data Federation, and Enterprise SSO.

## Features

### 🔌 Legacy System Adapters
- **SAP Integration** (S/4HANA, ECC)
- **Oracle Integration** (ERP, Database)  
- **Salesforce Integration** (Sales/Service Cloud)
- **Microsoft Dynamics** support
- **Database Connectors** (DB2, PostgreSQL, MySQL)

### 🚌 Enterprise Service Bus (ESB)
- **Message Routing** with content-based routing
- **Protocol Transformation** (SOAP, REST, GraphQL)
- **Message Transformation** with JSONata
- **Reliable Messaging** with retry and DLQ
- **Service Orchestration** and choreography

### 🔄 Workflow Orchestration
- **BPMN 2.0** support
- **Visual workflow designer**
- **Human task management**
- **Parallel execution** and synchronization
- **Timer and event handling**

### 🌐 Data Federation
- **Virtual data layer** across systems
- **GraphQL federation** for unified API
- **Query optimization** across sources
- **Caching strategies** for performance
- **Real-time data synchronization**

### 🔐 Enterprise SSO
- **SAML 2.0** integration
- **OAuth 2.0/OpenID Connect**
- **Active Directory/LDAP**
- **Multi-factor authentication**
- **Session management**

## Installation

```bash
npm install @iota-big3/sdk-enterprise
```

## Quick Start

```typescript
import { EnterpriseIntegration, EnterpriseConfig } from '@iota-big3/sdk-enterprise';

const config: EnterpriseConfig = {
  adapters: [
    {
      id: 'sap-prod',
      name: 'SAP Production',
      type: 'sap',
      connectionString: 'sap://host:port',
      credentials: {
        username: process.env.SAP_USER,
        password: process.env.SAP_PASS
      }
    }
  ],
  esb: {
    brokers: [{
      type: 'rabbitmq',
      connectionString: 'amqp://localhost'
    }],
    routes: [{
      id: 'sap-to-crm',
      name: 'SAP to CRM Route',
      source: { 
        id: 'sap-events',
        type: 'queue',
        uri: 'sap.events'
      },
      destination: [{
        id: 'crm-api',
        type: 'http',
        uri: 'https://crm.api/webhook'
      }],
      enabled: true
    }]
  },
  workflow: {
    engine: 'camunda',
    apiUrl: 'http://localhost:8080/engine-rest'
  },
  federation: {
    dataSources: [{
      id: 'main-db',
      name: 'Main Database',
      type: 'postgresql',
      connectionConfig: {
        host: 'localhost',
        database: 'school'
      },
      capabilities: {
        filtering: true,
        sorting: true,
        pagination: true,
        aggregation: true,
        transactions: true,
        joins: true
      }
    }]
  },
  sso: [{
    id: 'okta',
    name: 'Okta SSO',
    type: 'saml',
    enabled: true,
    config: {
      entryPoint: 'https://company.okta.com/sso/saml',
      issuer: 'schoolos',
      cert: 'MIID...'
    }
  }]
};

const enterprise = new EnterpriseIntegration(config);
```

## Usage Examples

### SAP Integration

```typescript
// Connect to SAP
await enterprise.connectAdapter('sap-prod');

// Call RFC function
const result = await enterprise.executeAdapterOperation('sap-prod', 'rfc', {
  functionName: 'BAPI_USER_GET_DETAIL',
  parameters: { USERNAME: 'TESTUSER' }
});

// Execute BAPI
const order = await enterprise.executeAdapterOperation('sap-prod', 'bapi', {
  bapiName: 'BAPI_SALESORDER_CREATEFROMDAT2',
  parameters: {
    ORDER_HEADER_IN: { /* header data */ },
    ORDER_ITEMS_IN: [/* line items */]
  }
});
```

### Salesforce Integration

```typescript
// Query Salesforce
const accounts = await enterprise.executeAdapterOperation('salesforce', 'query', {
  soql: 'SELECT Id, Name FROM Account LIMIT 10'
});

// Create Lead
const lead = await enterprise.executeAdapterOperation('salesforce', 'create', {
  sobject: 'Lead',
  records: {
    FirstName: 'John',
    LastName: 'Doe',
    Company: 'Acme Inc',
    Email: 'john@acme.com'
  }
});

// Subscribe to Platform Events
await enterprise.executeAdapterOperation('salesforce', 'streaming', {
  channel: '/event/Order_Event__e'
});
```

### Message Routing

```typescript
// Send message through ESB
await enterprise.routeMessage({
  id: crypto.randomUUID(),
  correlationId: 'order-123',
  timestamp: new Date(),
  source: 'sap.orders',
  destination: 'crm.orders',
  headers: {
    contentType: 'application/json',
    priority: 'high'
  },
  body: {
    orderId: 'ORD-123',
    customer: 'CUST-456',
    items: [/* ... */]
  }
});

// Register custom route
enterprise.router.registerRoute({
  id: 'custom-route',
  name: 'Custom Integration',
  source: { 
    id: 'api',
    type: 'http',
    uri: '/api/webhook'
  },
  destination: [{
    id: 'processor',
    type: 'direct',
    uri: 'processor.input'
  }],
  transformations: [{
    id: 'transform',
    type: 'jsonata',
    template: '{ "processed": $.data }'
  }],
  filters: [{
    id: 'type-filter',
    type: 'header',
    expression: 'eventType',
    operator: 'equals',
    value: 'order.created'
  }],
  enabled: true
});
```

### Workflow Orchestration

```typescript
// Deploy BPMN workflow
const definitionId = await enterprise.deployWorkflow({
  id: 'approval-workflow',
  name: 'Approval Workflow',
  version: '1.0',
  bpmnXml: `<?xml version="1.0" encoding="UTF-8"?>
    <bpmn:definitions>
      <!-- BPMN XML -->
    </bpmn:definitions>`,
  status: 'draft'
});

// Start workflow instance
const instanceId = await enterprise.startWorkflow(
  definitionId,
  'ORDER-123', // business key
  {
    amount: 10000,
    requester: 'john.doe',
    department: 'sales'
  }
);

// Get tasks for user
const tasks = await enterprise.workflow.getTasksForUser('manager1');

// Complete task
await enterprise.completeTask(instanceId, tasks[0].id, {
  approved: true,
  comments: 'Approved with conditions'
});
```

### Data Federation

```typescript
// Execute federated query across multiple sources
const result = await enterprise.executeQuery(
  `
  query GetCustomerOrders {
    customer(id: "123") {
      name
      email
      orders {
        id
        total
        items {
          product
          quantity
        }
      }
      invoices {
        number
        amount
        status
      }
    }
  }
  `,
  { customerId: '123' },
  { cache: true, timeout: 5000 }
);

// Register data source
await enterprise.federation.registerDataSource({
  id: 'analytics-db',
  name: 'Analytics Database',
  type: 'postgresql',
  connectionConfig: {
    host: 'analytics.db.local',
    database: 'analytics'
  },
  capabilities: {
    filtering: true,
    sorting: true,
    pagination: true,
    aggregation: true,
    transactions: false,
    joins: true
  }
});
```

### Enterprise SSO

```typescript
// Authenticate with SAML
const session = await enterprise.authenticateUser('okta', {
  // SAML assertion will be handled by passport
});

// Validate session
const validSession = enterprise.sso.validateSession(session.sessionId);

// Logout
enterprise.sso.logout(session.sessionId);

// Configure OAuth provider
await enterprise.sso.registerProvider({
  id: 'google',
  name: 'Google OAuth',
  type: 'oauth2',
  enabled: true,
  config: {
    authorizationURL: 'https://accounts.google.com/o/oauth2/v2/auth',
    tokenURL: 'https://oauth2.googleapis.com/token',
    clientID: process.env.GOOGLE_CLIENT_ID,
    clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    scope: ['profile', 'email']
  },
  mappings: [
    { source: 'emails[0].value', target: 'email' },
    { source: 'displayName', target: 'name' }
  ]
});
```

## Architecture

```
┌─────────────────────────────────────────────────────────┐
│                Enterprise Integration Layer              │
├─────────────────────────────────────────────────────────┤
│  ┌─────────────┐  ┌──────────────┐  ┌───────────────┐ │
│  │   Adapter   │  │     ESB      │  │   Workflow    │ │
│  │  Framework  │  │   Router     │  │    Engine     │ │
│  └─────────────┘  └──────────────┘  └───────────────┘ │
│  ┌─────────────┐  ┌──────────────┐                     │
│  │    Data     │  │     SSO      │                     │
│  │ Federation  │  │   Manager    │                     │
│  └─────────────┘  └──────────────┘                     │
└─────────────────────────────────────────────────────────┘
```

## Performance

- **Message Throughput**: 10,000+ msg/second
- **Workflow Execution**: <100ms overhead
- **Federated Queries**: <500ms for cross-system queries
- **SSO Authentication**: <2 seconds
- **Adapter Operations**: <50ms overhead

## Monitoring

```typescript
// Get health status
const health = await enterprise.healthCheck();

// Get adapter metrics
const adapterStats = enterprise.adapters.getConnections();

// Get routing metrics  
const routerMetrics = enterprise.router.getMetrics();

// Get workflow instances
const workflows = enterprise.workflow.getInstances({
  state: 'active'
});

// Get active SSO sessions
const sessions = enterprise.sso.getActiveSessions();
```

## Security

- End-to-end encryption for sensitive data
- Certificate-based authentication for adapters
- Role-based access control for workflows
- Secure token handling for SSO
- Audit logging for all operations

## License

MIT