npm package: @headoffice/qc-dashboard-sdk
Description: Node.js SDK for QC Dashboard API
Author: QC Dashboard Team
Latest version: 1.0.0

# QC Dashboard SDK

Node.js SDK for accessing the QC Dashboard API. This SDK provides a simple and intuitive interface for evaluating AI agent responses and managing quality control operations.

## Installation

### Public Installation (when published)

```bash
npm install @qc-dashboard/sdk
# or
yarn add @qc-dashboard/sdk
```

### Local Installation (Development)

Para usar o SDK localmente em outros projetos na sua máquina, você tem algumas opções:

#### Opção 1: npm link (Recomendado)

```bash
# No diretório do SDK
cd sdk
npm install
npm link

# No seu outro projeto
cd /caminho/para/seu/outro/projeto
npm link @qc-dashboard/sdk
```

#### Opção 2: file: Protocol

Adicione no `package.json` do outro projeto:

```json
{
  "dependencies": {
    "@qc-dashboard/sdk": "file:/caminho/absoluto/para/qc-dashboard/sdk"
  }
}
```

Depois execute `npm install`.

**Veja `PUBLISHING.md` para mais detalhes sobre todas as opções.**

## Quick Start

```javascript
const { QCDashboardClient } = require('@qc-dashboard/sdk');

// Initialize the client
const client = new QCDashboardClient({
  baseURL: 'http://localhost:3001/api/v1'
});

// Evaluate a draft response
const result = await client.evaluate({
  messageId: 'msg_123',
  conversationId: 'conv_456',
  agentId: 1,
  draft: 'Hello! How can I help you today?',
  prePrompts: 'You are a helpful customer service agent.',
  knowledge: 'Our return policy allows returns within 30 days.',
  channel: 'WhatsApp',
  userLanguage: 'pt-BR',
  lastUserMessage: 'I need help with my order'
});

console.log(`Status: ${result.status}`);
console.log(`Score: ${result.overallScore}`);
console.log(`Final Answer: ${result.final}`);
```

## Configuration

```javascript
const client = new QCDashboardClient({
  baseURL: 'https://your-qc-dashboard.manus.space/api/v1', // Default: 'http://localhost:3001/api/v1'
  timeout: 30000,                                           // Default: 30000ms
  headers: {                                                // Optional additional headers
    'X-Custom-Header': 'value'
  },
  apiKey: 'your-api-key'                                    // Optional API key for authentication
});
```

## API Methods

### `evaluate(data)`

Evaluate a draft AI response for quality control.

**Parameters:**
- `data.messageId` (string, required) - Unique identifier for this message
- `data.conversationId` (string, required) - Conversation/thread identifier
- `data.agentId` (number, required) - Agent ID from QC Dashboard
- `data.draft` (string, required) - The draft answer to evaluate
- `data.prePrompts` (string, required) - System instructions/prompts
- `data.knowledge` (string, required) - Relevant knowledge base context
- `data.channel` (string, required) - Communication channel ('WhatsApp' | 'Web' | 'Email' | 'SMS')
- `data.userLanguage` (string, required) - User's preferred language (e.g., 'pt-BR', 'en')
- `data.lastUserMessage` (string, required) - The user's original question/message
- `data.toolLogs` (array, optional) - Tool executions for this message

**Returns:** Promise<QualityReport>

**Example:**
```javascript
const result = await client.evaluate({
  messageId: `msg_${Date.now()}`,
  conversationId: `conv_${Date.now()}`,
  agentId: 9,
  draft: "Claro! Vou verificar o status do seu pedido. Por favor, aguarde um momento.",
  prePrompts: "Você é um agente de atendimento ao cliente. Por favor, ajude-me com meu pedido.",
  knowledge: "Nosso sistema fornece rastreamento de pedido em tempo real.",
  channel: "WhatsApp",
  userLanguage: "pt-BR",
  lastUserMessage: "Olá, eu preciso de ajuda com meu pedido. Por favor, verifique o status do meu pedido.",
  toolLogs: []
});
```

### `getLogs(options)`

Get quality evaluation logs with optional filtering.

**Parameters:**
- `options.agentId` (number, optional) - Filter by agent ID
- `options.limit` (number, optional) - Maximum number of logs (default: 50)
- `options.offset` (number, optional) - Offset for pagination (default: 0)
- `options.status` (string, optional) - Filter by status ('PASSED' | 'REVISED' | 'ESCALATED')
- `options.channel` (string, optional) - Filter by channel
- `options.startDate` (string, optional) - Start date (ISO 8601 format)
- `options.endDate` (string, optional) - End date (ISO 8601 format)

**Returns:** Promise<QualityReport[]>

**Example:**
```javascript
const logs = await client.getLogs({
  agentId: 1,
  limit: 10,
  status: 'PASSED'
});
```

### `getLog(id)`

Get a specific quality log by ID.

**Parameters:**
- `id` (number, required) - Log ID

**Returns:** Promise<QualityReport>

**Example:**
```javascript
const log = await client.getLog(123);
```

### `batchAnalyze(data)`

Start a batch quality analysis job.

**Parameters:**
- `data.items` (array, required) - Array of items to analyze
- `data.jobName` (string, optional) - Job name for tracking
- `data.priority` (string, optional) - Priority level ('low' | 'normal' | 'high')
- `data.callbackUrl` (string, optional) - Callback URL for completion notification

**Returns:** Promise<{ batchId: number, status: string }>

**Example:**
```javascript
const batch = await client.batchAnalyze({
  items: [
    {
      id: 'item_1',
      agentId: 1,
      draft: 'Response text',
      lastUserMessage: 'User question',
      channel: 'WhatsApp',
      userLanguage: 'pt-BR'
    }
  ],
  jobName: 'Daily Analysis'
});
```

### `getBatchStatus(batchId)`

Get batch job status.

**Parameters:**
- `batchId` (number, required) - Batch job ID

**Returns:** Promise<BatchJobStatusResponse>

**Example:**
```javascript
const status = await client.getBatchStatus(123);
console.log(`Progress: ${status.progress}%`);
```

### `getAnalyticsOverview(options)`

Get quality analytics overview.

**Parameters:**
- `options.startDate` (string, optional) - Start date (ISO 8601 format)
- `options.endDate` (string, optional) - End date (ISO 8601 format)

**Returns:** Promise<Object>

**Example:**
```javascript
const analytics = await client.getAnalyticsOverview({
  startDate: '2025-01-01',
  endDate: '2025-01-31'
});
```

### `getAgentAnalytics(agentId, options)`

Get agent-specific analytics.

**Parameters:**
- `agentId` (number, required) - Agent ID
- `options.startDate` (string, optional) - Start date (ISO 8601 format)
- `options.endDate` (string, optional) - End date (ISO 8601 format)

**Returns:** Promise<Object>

**Example:**
```javascript
const analytics = await client.getAgentAnalytics(1, {
  startDate: '2025-01-01',
  endDate: '2025-01-31'
});
```

### `submitFeedback(id, feedback)`

Submit feedback for a quality log.

**Parameters:**
- `id` (number, required) - Log ID
- `feedback.type` (string, required) - Feedback type ('like' | 'dislike')
- `feedback.comment` (string, optional) - Optional comment

**Returns:** Promise<Object>

**Example:**
```javascript
await client.submitFeedback(123, {
  type: 'like',
  comment: 'Great response!'
});
```

### `getAgentRules(agentId)`

Get all quality rules associated with an agent.

**Parameters:**
- `agentId` (number | string, required) - Agent ID (numeric or external string ID)

**Returns:** Promise<QualityRule[]>

**Example:**
```javascript
const rules = await client.getAgentRules(1);
console.log(`Agent has ${rules.length} quality rules`);
rules.forEach(rule => {
  console.log(`- ${rule.label} (${rule.severity})`);
});
```

## Response Types

### QualityReport

```typescript
{
  id?: number;
  version: string;
  messageId: string;
  conversationId: string;
  agentId: number;
  channel: string;
  draft: string;
  final: string;
  status: 'PASSED' | 'REVISED' | 'ESCALATED';
  overallScore: number;
  attempts: number;
  findings: QualityFinding[];
  toolAssertions: ToolAssertion[];
  kbCoverage: KbCoverage;
  suggestionsForManager?: string[];
  createdAt: Date | string;
}
```

### QualityRule

```typescript
{
  id?: string;
  ruleId: string;
  label: string;
  description?: string;
  type: 'grounding' | 'format' | 'policy' | 'tool' | 'regex' | 'length' | 'llm';
  severity: 'BLOCKING' | 'WARN';
  weight: number;
  params?: string;
  whenCondition?: string;
  remediationHint?: string;
  createdAt?: Date | string;
  updatedAt?: Date | string;
}
```

## Error Handling

The SDK throws enhanced errors with useful information:

```javascript
try {
  const result = await client.evaluate(data);
} catch (error) {
  if (error.status === 400) {
    console.error('Invalid request:', error.response);
  } else if (error.isNetworkError) {
    console.error('Network error:', error.message);
  } else {
    console.error('Error:', error.message);
  }
}
```

## TypeScript Support

TypeScript definitions are included:

```typescript
import { QCDashboardClient, EvaluateQualityRequest, QualityReport } from '@qc-dashboard/sdk';

const client = new QCDashboardClient({
  baseURL: 'http://localhost:3001/api/v1'
});

const data: EvaluateQualityRequest = {
  // ... your data
};

const result: QualityReport = await client.evaluate(data);
```

## License

MIT