npm package: @proofchain/partner-sdk
Description: ProofChain Partner SDK for integrating with campaign data
Author: ProofChain
Latest version: 1.4.0

# ProofChain Partner SDK

SDK for partners to integrate with ProofChain campaigns. Provides methods for:
- Fetching campaign configuration with dynamic feedback schemas
- Checking user consent status
- Querying user data views
- Submitting feedback events with schema validation

## Installation

```bash
npm install @proofchain/partner-sdk
```

## Quick Start

```typescript
import { ProofChainPartner } from '@proofchain/partner-sdk';

// Initialize with your integrator API key and campaign ID
const partner = new ProofChainPartner({
  apiKey: 'ik_live_xxx',
  campaignId: 'your-campaign-uuid',
});

// Get campaign configuration (includes feedback schemas)
const config = await partner.getConfig();
console.log('Available views:', config.data_views);
console.log('Feedback types:', config.feedback.types);

// Check if user has consented
const consent = await partner.checkConsent('user_123');
if (!consent.has_consent) {
  // Redirect to consent page
  const consentUrl = partner.getConsentUrl('user_123', {
    redirectUrl: 'https://your-site.com/callback'
  });
  window.location.href = consentUrl;
}

// Query user data
const profile = await partner.getUserProfile('user_123');
console.log('User profile:', profile.data);

// Submit feedback event
const result = await partner.submitFeedback('user_123', 'purchase', {
  amount: 99.99,
  currency: 'USD',
  product_id: 'ticket-123'
});
console.log('Feedback submitted:', result.feedback_id);
```

## Dynamic Feedback Schemas

Each campaign can define custom feedback types with their own schemas. The SDK provides methods to discover and validate against these schemas:

```typescript
// Get all available feedback types
const feedbackTypes = await partner.getFeedbackTypes();
// Returns: [
//   {
//     type: 'purchase',
//     name: 'Purchase',
//     description: 'Track when a user makes a purchase',
//     schema: {
//       type: 'object',
//       properties: {
//         amount: { type: 'number', minimum: 0 },
//         currency: { type: 'string', enum: ['USD', 'EUR', 'GBP', 'ZAR'] },
//         product_id: { type: 'string' }
//       },
//       required: ['amount', 'currency']
//     }
//   },
//   ...
// ]

// Get schema for a specific feedback type
const purchaseSchema = await partner.getFeedbackSchema('purchase');

// Validate data before submitting
const validation = await partner.validateFeedback('purchase', {
  amount: 99.99,
  currency: 'INVALID'
});
if (!validation.valid) {
  console.error('Validation errors:', validation.errors);
}
```

## React Integration

The SDK includes React components and hooks:

```tsx
import { 
  PartnerProvider, 
  usePartner, 
  ConsentWidget, 
  FeedbackForm 
} from '@proofchain/partner-sdk/react';

function App() {
  return (
    <PartnerProvider config={{
      apiKey: 'ik_live_xxx',
      campaignId: 'your-campaign-uuid',
    }}>
      <MyComponent />
    </PartnerProvider>
  );
}

function MyComponent() {
  const { partner, config, loading } = usePartner();
  
  if (loading) return <div>Loading...</div>;
  
  return (
    <div>
      <h1>{config?.campaign_name}</h1>
      
      {/* Consent widget */}
      <ConsentWidget
        partner={partner}
        userId="user_123"
        onSuccess={(consent) => console.log('Consented!', consent)}
        onCancel={() => console.log('Cancelled')}
      />
      
      {/* Dynamic feedback form */}
      <FeedbackForm
        partner={partner}
        userId="user_123"
        feedbackType="purchase"
        onSuccess={(result) => console.log('Submitted!', result)}
      />
    </div>
  );
}
```

## API Reference

### ProofChainPartner

#### Constructor

```typescript
new ProofChainPartner({
  apiKey: string,      // Required: Integrator API key
  campaignId: string,  // Required: Campaign UUID
  baseUrl?: string,    // Optional: API base URL (default: https://api.proofchain.io)
  timeout?: number,    // Optional: Request timeout in ms (default: 30000)
  debug?: boolean,     // Optional: Enable debug logging
})
```

#### Methods

| Method | Description |
|--------|-------------|
| `getConfig()` | Get campaign configuration including feedback schemas |
| `getAvailableViews()` | Get list of available data views |
| `getFeedbackTypes()` | Get available feedback types with schemas |
| `getFeedbackSchema(type)` | Get schema for a specific feedback type |
| `checkConsent(userId)` | Check if user has consented |
| `getConsentUrl(userId, options?)` | Get URL for consent widget |
| `queryView(userId, viewName)` | Query a data view |
| `getUserProfile(userId)` | Get user's fan profile |
| `getActivitySummary(userId)` | Get user's activity summary |
| `getEvents(userId)` | Get user's recent events |
| `submitFeedback(userId, type, data)` | Submit a feedback event |
| `validateFeedback(type, data)` | Validate feedback data against schema |

## Error Handling

All methods throw `PartnerError` on failure:

```typescript
interface PartnerError {
  status: number;    // HTTP status code
  code: string;      // Error code
  message: string;   // Human-readable message
  details?: object;  // Additional details
}
```

Common error codes:
- `INVALID_FEEDBACK_TYPE` - Feedback type not allowed for this campaign
- `MISSING_REQUIRED_FIELDS` - Required fields missing from feedback data
- `CONSENT_REQUIRED` - User has not consented to data sharing
- `RATE_LIMITED` - Too many requests

## License

MIT