npm package: @ordersune/crm-web-sdk
Description: A comprehensive TypeScript SDK for integrating the Order Sune CRM solution into your web applications. Enables seamless user tracking, event monitoring, purchase analytics, in-app messaging, and customer data management.
Latest version: 1.1.5

# Order Sune CRM TypeScript SDK

A comprehensive TypeScript SDK for integrating the Order Sune CRM solution into your web applications. Enables seamless user tracking, event monitoring, purchase analytics, in-app messaging, and customer data management.

## Installation

```bash
npm install @ordersune/crm-web-sdk
# or
yarn add @ordersune/crm-web-sdk
```

## Quick Start

### Initialize the SDK

```typescript
import { WebSDK } from '@ordersune/crm-web-sdk';

const crm = new WebSDK({
  apiKey: 'your-api-key',
  endpoint: 'https://api.example.com',
  debug: false,
  batchSize: 10,
  batchInterval: 10000
});
```

## Core Features

### User Management

#### User Identification
Track both registered and guest users:

```typescript
// Identify a registered user
crm.identify('user123');

// Get current user profile
const userProfile = crm.getUserProfile();

// Clear user data and generate new device ID
crm.clearUserData();
```

### Event Tracking

#### Basic Event Tracking
```typescript
// Simple event
crm.trackEvent('page_view');

// Event with properties
crm.trackEvent('purchase_completed', {
  productId: 'prod_123',
  amount: 99.99,
  currency: 'USD'
});

// Event with custom options
crm.trackEvent('custom_event', 
  { key: 'value' },
  { 
    timestamp: '2024-12-28T10:00:00Z',
    requestId: 'req_abc123'
  }
);
```

#### Purchase Tracking
Track detailed purchase events:

```typescript
crm.logProductPurchase(
  'order_123',        // orderId
  'item_456',         // itemId
  'Premium Widget',   // itemName
  29.99,              // unitPrice
  2,                  // quantity
  'web',              // source
  'direct',           // channel
  'electronics'       // itemCategory (optional)
);
```

### Custom Attributes

Track persistent user attributes that are sent with every batch:

```typescript
crm.trackCustomAttribute('preference_theme', 'dark');
crm.trackCustomAttribute('notification_enabled', true);
crm.trackCustomAttribute('user_tier', 'premium');
```

### Push Notifications

#### Token Management
```typescript
// Set push notification token
crm.setToken('your-push-token');

// Log push notification clicks
crm.logClick('campaign_123');
```

### In-App Messaging

Display rich in-app messages with customizable styling:

```typescript
const messageData = JSON.stringify({
  header: "Welcome!",
  message: "Check out our new features",
  modal: {
    button1: {
      type: "Continue",
      backgroundColor: "#007AFF",
      textColor: "#FFFFFF",
      borderColor: "#007AFF",
      webOnClickValue: "redirect_to_web_url",
      webOnClickAction: "https://example.com"
    },
    button2: {
      type: "Skip",
      backgroundColor: "#F2F2F2",
      textColor: "#000000",
      borderColor: "#CCCCCC"
    },
    dismissMessageAutomatically: true,
    dismissMessageInSeconds: "10",
    headerColor: "#000000",
    messageColor: "#666666",
    closeColor: "#999999"
  },
  mediaConfig: {
    inAppImage: "https://example.com/image.png"
  }
});

crm.displayInAppMessage(messageData, 'campaign_456');
```

### Batch Processing

#### Manual Control
```typescript
// Force send all queued events immediately
await crm.forceSend();

// Clean up resources
crm.dispose();
```

## Configuration Options

### SDKConfig

```typescript
interface SDKConfig {
  apiKey: string;           // Your API key (required)
  endpoint: string;         // API endpoint URL (required)
  debug?: boolean;          // Enable debug logging
  batchSize?: number;       // Events per batch (default: 10)
  batchInterval?: number;   // Batch interval in ms (default: 10000)
}
```

## Data Types

### UserProfile

```typescript
interface UserProfile {
  id: string;              // User identifier
  guestUserId?: string;    // Guest user identifier
}
```

### EventOptions

```typescript
interface EventOptions {
  timestamp?: string;      // Custom event timestamp
  requestId?: string;      // Custom request identifier
}
```

### PurchasePayload

```typescript
interface PurchasePayload {
  externalId: string;      // Order ID
  itemId: string;          // Product/item ID
  itemName: string;        // Product name
  unitPrice: number;       // Price per unit
  quantity: number;        // Number of items
  source: string;          // Purchase source
  channel: string;         // Purchase channel
  itemCategory?: string;   // Product category
}
```

## Key Features

### Automatic Functionality
- **Session Management**: Automatic session tracking with device ID generation
- **Guest User Handling**: Seamless guest-to-registered user transition
- **Batch Processing**: Efficient event batching with configurable size and interval
- **Offline Support**: Event queuing when offline with automatic retry
- **Device Detection**: Automatic platform and device information collection
- **Timezone Detection**: Automatic timezone detection and tracking

### Performance Optimizations
- **Event Queuing**: Intelligent batching to reduce network requests
- **Session Storage**: Persistent storage for user data and custom attributes
- **Error Handling**: Robust error handling with automatic retry mechanisms
- **Memory Management**: Efficient cleanup and disposal methods

### Developer Experience
- **TypeScript Support**: Full type definitions included
- **Debug Mode**: Comprehensive logging for development
- **Flexible Configuration**: Customizable batch sizes and intervals
- **Modern API**: Promise-based async operations

## Requirements

- **TypeScript**: 5.0+
- **Browser**: Modern browsers with sessionStorage support
- **Network**: Internet connection for event transmission
- **Dependencies**: UUID library (automatically installed)

## Browser Compatibility

- Chrome 60+
- Firefox 55+
- Safari 12+
- Edge 79+

## License

MIT License

## Support & Documentation

- [API Documentation](https://docs.ordersune.com/crm)
- [Support Portal](mailto:support@ordersune.com)
- [GitHub Issues](https://github.com/ordersune/crm-web-sdk/issues)