npm package: @phoenixforgeos/sdk
Description: Shared SDK for the PhoenixOS platform — Supabase client, VAD service, auth, and automation
Author: PhoenixForge
Latest version: 2.0.1

# 🚀 Valuu Automation SDK (VTMS-Aligned)

**JavaScript/TypeScript SDK for Valuu automation flows, runs, and webhooks with full VTMS integration**

## 🎯 **VTMS Alignment & Platform Integration**

This SDK is specifically designed to align with your **Virtual Table Management System (VTMS)** architecture and leverage existing platform services for maximum reuse and consistency.

### **✅ VTMS Architecture Compliance**
- **Virtual Table Resolution**: Uses VTMS functions for dynamic table management
- **App Registration**: Integrates with your platform app marketplace
- **Company Isolation**: Follows your multi-tenant data isolation patterns
- **Component Registry**: Leverages your existing component architecture

### **🔄 Platform Service Reuse**
- **WorkflowEngineService**: Integrates with existing workflow infrastructure
- **VTMS Notifications**: Uses your notification enhancer patterns
- **Unified Services**: Leverages analytics, notifications, and configuration services
- **Business Logic**: Integrates with existing business logic execution patterns

## 📦 **Installation**

```bash
npm install @valuu/sdk-js
```

## 🚀 **Quick Start**

### **VTMS-Aligned Client (Recommended)**

```typescript
import { VTMSValuuClient, PlatformIntegrationService } from '@valuu/sdk-js';

// Initialize with VTMS configuration
const client = new VTMSValuuClient({
  supabaseUrl: 'https://your-project.supabase.co',
  supabaseKey: 'your-anon-key',
  companyId: 'your-company-id',
  environment: 'dev',
  appName: 'MyAutomationApp' // VTMS app identifier
});

// Register as platform app (VTMS integration)
await client.registerAsPlatformApp();

// Use VTMS-integrated methods
const flows = await client.listFlows();
const runs = await client.listRuns();
```

### **Platform Integration Service**

```typescript
// Leverage existing platform services
const platformService = new PlatformIntegrationService(
  client.getSupabaseClient(),
  'your-company-id'
);

// Create workflow from automation flow (WorkflowEngineService integration)
const workflow = await platformService.createWorkflowFromFlow(flow);

// Send VTMS notifications
await platformService.sendVTMSNotification(
  'automation_completed',
  'Flow execution completed successfully',
  ['user@example.com']
);

// Track metrics using unified analytics
await platformService.trackAutomationMetrics(
  'flow_execution',
  { flow_id: flow.id, duration: 1500 },
  ['automation', 'performance']
);
```

## 🏗️ **Architecture & VTMS Integration**

### **Virtual Table Management**
```typescript
// SDK automatically resolves virtual tables through VTMS
const tableName = await client.resolveVirtualTable('automation_flows');
// Returns: {company_id}_automation_flows_{workspace} or platform.automation_flows

// All operations use VTMS-resolved table names
const flows = await client.listFlows(); // Uses VTMS resolution
```

### **Platform App Integration**
```typescript
// SDK registers itself in your platform app registry
await client.registerAsPlatformApp();

// This enables:
// - Component discovery in your marketplace
// - Integration with existing VTMS services
// - Consistent with your app architecture
```

### **Service Reuse Patterns**
```typescript
// Leverages existing WorkflowEngineService patterns
const workflow = await platformService.createWorkflowFromFlow(flow);

// Uses existing VTMS notification infrastructure
await platformService.sendVTMSNotification(type, message, recipients);

// Integrates with unified services
await platformService.trackAutomationMetrics(event, data, tags);
```

## 📚 **API Reference**

### **VTMSValuuClient Methods**

#### **VTMS Integration**
- `registerAsPlatformApp()` - Register SDK as platform app
- `resolveVirtualTable(tableName)` - Resolve virtual table names
- `getVTMSConfig()` - Get current VTMS configuration

#### **Automation Flows (VTMS-Integrated)**
- `listFlows(filters?)` - List flows using VTMS table resolution
- `getFlow(flowId)` - Get flow by ID using VTMS
- `createFlow(request)` - Create flow using VTMS
- `updateFlow(flowId, request)` - Update flow using VTMS
- `deleteFlow(flowId)` - Delete flow using VTMS

#### **Automation Runs (VTMS-Integrated)**
- `listRuns(filters?)` - List runs using VTMS
- `getRun(runId)` - Get run by ID using VTMS
- `createRun(request)` - Create run using VTMS
- `updateRunStatus(runId, status, error?)` - Update run status using VTMS

#### **Run Steps (VTMS-Integrated)**
- `getRunSteps(runId)` - Get run steps using VTMS
- `updateRunStepStatus(stepId, status, output?, error?)` - Update step status using VTMS

#### **Webhooks (VTMS-Integrated)**
- `listWebhooks(filters?)` - List webhook configurations using VTMS
- `triggerWebhook(request)` - Trigger webhook using VTMS

#### **Approvals (VTMS-Integrated)**
- `listApprovals(filters?)` - List approval requests using VTMS
- `respondToApproval(approvalId, response, comment?)` - Respond to approval using VTMS

### **PlatformIntegrationService Methods**

#### **Workflow Engine Integration**
- `createWorkflowFromFlow(flow)` - Convert automation flow to workflow
- `convertFlowToWorkflowNodes(flowDefinition)` - Extract workflow nodes
- `convertFlowToWorkflowEdges(flowDefinition)` - Extract workflow edges

#### **VTMS Notifications**
- `sendVTMSNotification(type, message, recipients, metadata?)` - Send VTMS notifications

#### **Component Registry**
- `registerAutomationComponents(flow)` - Register reusable components
- `extractComponentsFromFlow(flow)` - Extract component patterns

#### **Business Logic**
- `executeBusinessLogic(logicType, input, context?)` - Execute business logic

#### **Unified Services**
- `trackAutomationMetrics(event, data, tags?)` - Track analytics
- `sendUnifiedNotification(channel, message, recipients, options?)` - Send notifications

#### **Platform Configuration**
- `getPlatformConfiguration(configKey, defaultValue?)` - Get configuration
- `setPlatformConfiguration(configKey, value)` - Set configuration

## 🔧 **Configuration**

### **VTMS Client Configuration**
```typescript
interface VTMSClientConfig {
  supabaseUrl: string;           // Your Supabase project URL
  supabaseKey: string;           // Your Supabase anon key
  companyId?: string;            // Company ID for multi-tenancy
  environment?: 'dev' | 'stage' | 'prod';  // Environment
  appName?: string;              // VTMS app identifier
}
```

### **Environment Variables**
```bash
VITE_SUPABASE_URL=https://your-project.supabase.co
VITE_SUPABASE_ANON_KEY=your-anon-key
VITE_COMPANY_ID=your-company-id
VITE_ENVIRONMENT=dev
VITE_APP_NAME=MyAutomationApp
```

## 🎯 **VTMS Benefits**

### **1. Multi-Tenant Isolation**
- Each company gets isolated virtual tables
- Automatic data separation
- No cross-company data leakage

### **2. Dynamic Scaling**
- Tables created on-demand
- Automatic cleanup of unused tables
- No pre-provisioning required

### **3. App Marketplace Integration**
- SDK appears in your app registry
- Consistent with platform architecture
- Reusable components and patterns

### **4. Service Reuse**
- Leverages existing workflow engine
- Uses VTMS notification patterns
- Integrates with unified services

## 📊 **Usage Examples**

### **Complete VTMS Workflow**
```typescript
import { VTMSValuuClient, PlatformIntegrationService } from '@valuu/sdk-js';

const client = new VTMSValuuClient({
  supabaseUrl: process.env.VITE_SUPABASE_URL!,
  supabaseKey: process.env.VITE_SUPABASE_ANON_KEY!,
  companyId: process.env.VITE_COMPANY_ID!,
  appName: 'ECommerceAutomation'
});

const platformService = new PlatformIntegrationService(
  client.getSupabaseClient(),
  process.env.VITE_COMPANY_ID!
);

// 1. Register as platform app
await client.registerAsPlatformApp();

// 2. Create automation flow
const flow = await client.createFlow({
  name: 'Order Processing',
  description: 'Automated order processing workflow',
  company_id: process.env.VITE_COMPANY_ID!,
  created_by: 'user-id',
  definition: { nodes: [], edges: [] }
});

// 3. Register components in platform registry
await platformService.registerAutomationComponents(flow);

// 4. Create workflow from flow
const workflow = await platformService.createWorkflowFromFlow(flow);

// 5. Track metrics
await platformService.trackAutomationMetrics(
  'flow_created',
  { flow_id: flow.id, workflow_id: workflow.data.workflow_id },
  ['automation', 'workflow']
);

// 6. Send notification
await platformService.sendVTMSNotification(
  'automation_ready',
  'Order processing automation is ready for use',
  ['admin@company.com']
);
```

### **Leveraging Existing Services**
```typescript
// Use existing workflow engine patterns
const workflow = await platformService.createWorkflowFromFlow(flow);

// Use existing VTMS notification infrastructure
await platformService.sendVTMSNotification(
  'flow_execution_started',
  `Flow ${flow.name} execution started`,
  ['ops@company.com']
);

// Use existing unified analytics
await platformService.trackAutomationMetrics(
  'flow_execution_completed',
  { 
    flow_id: flow.id, 
    duration: 2500, 
    steps_completed: 5 
  },
  ['automation', 'performance', 'monitoring']
);

// Use existing platform configuration
const config = await platformService.getPlatformConfiguration(
  'automation.max_concurrent_runs',
  10
);
```

## 🧪 **Testing**

```bash
# Run tests
npm test

# Run tests with coverage
npm run test:coverage

# Run tests in watch mode
npm run test:watch
```

## 🚀 **Build & Development**

```bash
# Build the package
npm run build

# Development mode with watch
npm run dev

# Type checking
npm run type-check

# Linting
npm run lint
```

## 🔒 **Security & VTMS**

### **Row Level Security (RLS)**
- All operations respect VTMS RLS policies
- Company-level data isolation
- Automatic permission enforcement

### **Virtual Table Security**
- Tables created with proper RLS policies
- Company ID validation on all operations
- Secure credential management

## 📈 **Performance & VTMS**

### **Virtual Table Optimization**
- Efficient table resolution
- Automatic indexing on virtual tables
- Query optimization through VTMS

### **Caching Integration**
- Leverages existing platform caching
- VTMS-aware caching strategies
- Performance monitoring integration

## 🔮 **Future Enhancements**

### **VTMS Advanced Features**
- Schema versioning and evolution
- Automatic migration management
- Advanced table resolution strategies

### **Platform Service Integration**
- Enhanced workflow engine integration
- Advanced notification patterns
- Machine learning integration

## 🤝 **Contributing**

This SDK follows your VTMS architecture and platform patterns. When contributing:

1. **Follow VTMS patterns** from existing services
2. **Leverage existing platform services** when possible
3. **Maintain company isolation** in all operations
4. **Use existing component patterns** for consistency
5. **Integrate with unified services** for functionality

## 📄 **License**

MIT License - see LICENSE file for details.

## 🆘 **Support**

For VTMS integration questions or platform service usage:
- Check existing VTMS documentation
- Review platform service patterns
- Consult with your VTMS architecture team

---

**Built with ❤️ for the Valuu VTMS Platform**