# Zapier Integration

Vega AI provides a comprehensive API for integrating with Zapier to automate workflows, sync data to CRM systems, and trigger actions based on student activities. This document covers all REST API endpoints designed specifically for Zapier integration.

### Base URL

```
https://backend.myvega/api/zapier
```

### Authentication

All API endpoints require authentication using an API key. The API key can be provided in one of the following ways:

#### Headers

* `x-api-key`: Your organization's API key
* `Authorization`: Bearer token or direct API key

#### Query Parameters (for compatibility)

* `apiKey`: Your organization's API key

#### Example Request with Authentication

```bash
curl -X GET "https://backend.myvega/api/zapier/healthcheck" \
  -H "x-api-key: your-api-key-here"
```

***

### API Endpoints

#### 1. Health Check

Validates API key and returns service status information.

**Endpoint:** `GET /api/zapier/healthcheck`

**Authentication:** Required

**Response:**

```json
{
  "success": true,
  "status": "healthy",
  "message": "API is operational and your credentials are valid",
  "authentication": {
    "valid": true,
    "organizationName": "Your Organization Name"
  },
  "timestamp": "25-12-2024",
  "endpoints": [
    {
      "path": "/api/zapier/healthcheck",
      "method": "GET",
      "description": "Health check with API key validation",
      "authenticated": true
    },
    {
      "path": "/api/zapier/userinfo",
      "method": "POST",
      "description": "Get organization users list with subscription info (supports pagination with page and limit in request body)",
      "authenticated": true
    },
    {
      "path": "/api/zapier/new-student-signups",
      "method": "GET",
      "description": "Get new student signups for CRM integration (supports ?limit=50&since=ISO_DATE for basic signup data)",
      "authenticated": true
    },
    {
      "path": "/api/zapier/student-diagnostic-tests",
      "method": "POST",
      "description": "Get all diagnostic test data for the organization. Supports filtering by date, test type, and pagination",
      "authenticated": true
    },
    {
      "path": "/api/zapier/students-analytics",
      "method": "POST",
      "description": "Get students analytics data (similar to GraphQL getStudentsAnalytics). Supports filtering by test types, dates, names, course, and status",
      "authenticated": true
    },
    {
      "path": "/api/zapier/students-practice-analytics",
      "method": "POST",
      "description": "Get students analytics data for quiz, assignment, homework, and exit ticket tests with pagination support",
      "authenticated": true
    }
  ]
}
```

#### 2. Organization Users Information

Retrieves a paginated list of users in the organization with subscription details.

**Endpoint:** `POST /api/zapier/userinfo`

**Authentication:** Required

**Request Body:**

```json
{
  "page": 1,
  "limit": 10
}
```

**Parameters:**

* `page` (optional): Page number for pagination (default: 1)
* `limit` (optional): Number of users per page (default: 10, max: 100)

**Response:**

```json
{
  "success": true,
  "pagination": {
    "page": 1,
    "limit": 10,
    "total": 150,
    "totalPages": 15,
    "hasNextPage": true,
    "hasPreviousPage": false
  },
  "count": 10,
  "users": [
    {
      "firstName": "John",
      "lastName": "Doe",
      "fullName": "John Doe",
      "email": "john.doe@example.com",
      "parentEmail": "parent@example.com",
      "phoneNumber": "+1234567890",
      "role": "STUDENT",
      "createdAt": "25-12-2024",
      "isOnboardingCompleted": true,
      "intentLevel": "high",
      "reasoning": "Student shows strong interest in SAT preparation",
      "subscription": "PRO",
      "userType": "paid"
    }
  ]
}
```

#### 3. New Student Signups (Trigger)

Retrieves new student signups for CRM integration. Designed for polling triggers in Zapier.

**Endpoint:** `GET /api/zapier/new-student-signups`

**Authentication:** Required

**Query Parameters:**

* `limit` (optional): Number of students to return (default: 10, max: 100)
* `since` (optional): ISO date string to filter students created after this date (e.g., "2024-01-01T00:00:00Z")

**Response:** Returns an array of student objects for easy mapping in Zapier:

```json
[
  {
    "firstName": "Jane",
    "lastName": "Smith",
    "fullName": "Jane Smith",
    "email": "jane.smith@example.com",
    "phoneNumber": "+1987654321",
    "role": "STUDENT",
    "signupDate": "2024-12-25",
    "isOnboardingCompleted": false,
    "lastLogin": null,
    "intentLevel": "medium",
    "intentReasoning": "Interested in college preparation"
  }
]
```

**Zapier Setup:**

1. Create a "Polling" trigger in Zapier
2. Use: `GET /api/zapier/new-student-signups`
3. Add your API key to headers
4. Configure polling interval (recommended: every 15 minutes)
5. Map response fields to your CRM fields

#### 4. Student Diagnostic Tests

Retrieves diagnostic test data for the organization with detailed analytics.

**Endpoint:** `POST /api/zapier/student-diagnostic-tests`

**Authentication:** Required

**Request Body:**

```json
{
  "limit": 100,
  "since": "2024-01-01T00:00:00Z",
  "testType": "DIAGNOSTIC"
}
```

**Parameters:**

* `limit` (optional): Number of test records to return (default: 100, max: 500)
* `since` (optional): ISO date string to filter tests created after this date
* `testType` (optional): Filter by test type ("DIAGNOSTIC" or "STRUCTURED\_TEST", default: "DIAGNOSTIC")

**Response:**

```json
{
  "success": true,
  "message": "Diagnostic test data retrieved successfully",
  "count": 25,
  "data": [
    {
      "testName": "SAT Diagnostic Test - Math",
      "testType": "DIAGNOSTIC",
      "studentName": "John Doe",
      "studentEmail": "john.doe@example.com",
      "courseName": "SAT Math Preparation",
      "masteryScore": 75,
      "overallCompletionStatus": "COMPLETED",
      "createdAt": "2024-12-25T10:30:00.000Z",
      "completedAt": "25-12-2024",
      "computedMetrics": [
        {
          "metricName": "Algebra",
          "value": 80,
          "maxScore": 100
        },
        {
          "metricName": "Geometry",
          "value": 70,
          "maxScore": 100
        }
      ]
    }
  ]
}
```

#### 5. Student Analytics (Structured Tests)

Retrieves student analytics data for structured tests with detailed metrics and pagination.

**Endpoint:** `POST /api/zapier/students-analytics`

**Authentication:** Required

**Request Body:**

```json
{
  "page": 1,
  "limit": 50
}
```

**Parameters:**

* `page` (required): Page number for pagination
* `limit` (required): Number of results per page (1-100)

**Response:**

```json
{
  "success": true,
  "message": "Success",
  "totalPages": 5,
  "totalTests": 250,
  "currentPage": 1,
  "nextPage": 2,
  "previousPage": null,
  "hasNextPage": true,
  "hasPreviousPage": false,
  "tests": [
    {
      "name": "John Doe",
      "courseName": "SAT Math Preparation",
      "testName": "Chapter 5 Practice Test",
      "testType": "STRUCTURED_TEST",
      "masteryScore": 85,
      "maxScoreForAllQuestions": 100,
      "projectedScore": 1450,
      "overallCompletionStatus": "COMPLETED",
      "aiFeedback": "Excellent performance on algebra concepts",
      "date": "2024-12-25T10:30:00.000Z",
      "retaken": false,
      "timeZone": "America/New_York",
      "computedMetrics": {
        "Algebra Mastery": 90,
        "Algebra Mastery_maxScore": 100,
        "Geometry Mastery": 80,
        "Geometry Mastery_maxScore": 100,
        "Data Analysis": 85,
        "Data Analysis_maxScore": 100
      }
    }
  ]
}
```

#### 6. Student Practice Analytics

Retrieves student analytics for practice tests (Quiz, Assignment, Homework, Exit Ticket).

**Endpoint:** `POST /api/zapier/students-practice-analytics`

**Authentication:** Required

**Request Body:**

```json
{
  "page": 1,
  "limit": 50
}
```

**Parameters:**

* `page` (required): Page number for pagination
* `limit` (required): Number of results per page (1-100)

**Response:**

```json
{
  "success": true,
  "message": "Success",
  "totalPages": 10,
  "totalTests": 500,
  "currentPage": 1,
  "nextPage": 2,
  "previousPage": null,
  "hasNextPage": true,
  "hasPreviousPage": false,
  "tests": [
    {
      "name": "Jane Smith",
      "courseName": "SAT Math Preparation",
      "testName": "Weekly Quiz - Linear Equations",
      "testType": "QUIZ",
      "masteryScore": 92,
      "maxScoreForAllQuestions": 100,
      "overallCompletionStatus": "COMPLETED",
      "aiFeedback": "Perfect score! Strong understanding of linear equations",
      "date": "2024-12-25T14:20:00.000Z",
      "retaken": false,
      "timeZone": "America/New_York"
    }
  ]
}
```

#### Subscribe to Webhooks

Subscribe a Zapier webhook URL to receive real-time notifications.

**Endpoint:** `POST /api/zapier/subscribe`

**Authentication:** Required

**Request Body:**

```json
{
  "hookUrl": "https://hooks.zapier.com/hooks/catch/123456/abcdef/"
}
```

**Response:**

```json
{
  "success": true,
  "message": "Webhook subscribed successfully",
  "webhook": {
    "url": "https://hooks.zapier.com/hooks/catch/123456/abcdef/",
    "status": "active",
    "createdAt": "2024-12-25T10:30:00.000Z"
  },
  "hookUrl": "https://hooks.zapier.com/hooks/catch/123456/abcdef/"
}
```

#### Unsubscribe from Webhooks

Remove a webhook URL from notifications.

**Endpoint:** `POST /api/zapier/unsubscribe`

**Authentication:** Required

**Request Body:**

```json
{
  "hookUrl": "https://hooks.zapier.com/hooks/catch/123456/abcdef/"
}
```

**Response:**

```json
{
  "success": true,
  "message": "Webhook unsubscribed successfully"
}
```

#### Webhook Notifications

When students register, the following payload is sent to active webhooks:

```json
{
  "id": "507f1f77bcf86cd799439011",
  "firstName": "John",
  "lastName": "Doe",
  "fullName": "John Doe",
  "email": "john.doe@example.com",
  "phoneNumber": "+1234567890",
  "role": "STUDENT",
  "signupDate": "2024-12-25",
  "isOnboardingCompleted": false,
  "lastLogin": null,
  "intentLevel": "high",
  "intentReasoning": "Strong interest in SAT preparation"
}
```

### Error Handling

All endpoints return standardized error responses:

```json
{
  "success": false,
  "message": "Error description",
  "error": "Detailed error message",
  "timestamp": "25-12-2024"
}
```

Common HTTP status codes:

* `200`: Success
* `400`: Bad Request (invalid parameters)
* `403`: Forbidden (invalid API key)
* `404`: Not Found
* `500`: Internal Server Error

### Rate Limiting

* API requests are rate-limited per organization
* Standard limits apply to prevent abuse
* Contact support for increased limits if needed

#### Date Formats

* API responses use `DD-MM-YYYY` format for display dates
* ISO 8601 format (`YYYY-MM-DD`) for precise timestamps
* Query parameters accept ISO 8601 date strings

#### Test Types

* `DIAGNOSTIC`: Initial assessment tests
* `STRUCTURED_TEST`: Full practice tests
* `QUIZ`: Short quizzes
* `ASSIGNMENT`: Homework assignments
* `HOMEWORK`: Homework tasks
* `EXIT_TICKET`: End-of-lesson assessments

#### Subscription Tiers

* `BASIC`: Free tier
* `PRO`: Professional tier
* `PRO_MAX`: Premium tier

#### Completion Status

* `PENDING`: Test not started
* `IN_PROGRESS`: Test in progress
* `COMPLETED`: Test finished
* `EXPIRED`: Test expired

### Zapier Integration Examples

#### 1. Student Signup to CRM

1. **Trigger**: Polling trigger on `/api/zapier/new-student-signups`
2. **Action**: Create/update contact in CRM (HubSpot, Salesforce, etc.)
3. **Schedule**: Every 15 minutes

#### 2. Test Results to Google Sheets

1. **Trigger**: Polling trigger on `/api/zapier/students-analytics`
2. **Action**: Add/update row in Google Sheet
3. **Schedule**: Every hour

#### 3. Real-time Signup Notifications

1. **Trigger**: Webhook trigger on `/api/zapier/subscribe`
2. **Action**: Send Slack notification or email alert

#### 4. Diagnostic Results to Analytics Platform

1. **Trigger**: Polling trigger on `/api/zapier/student-diagnostic-tests`
2. **Action**: Send data to analytics platform (Mixpanel, Amplitude, etc.)
3. **Schedule**: Daily

### Support

For API key generation, technical support, or additional endpoints:

* Contact: <support@learnq.ai>
* Documentation: <https://docs.learnq.ai>

### Version History

* **v1.0**: Initial Zapier API release
  * Health check endpoint
  * User information endpoint
  * New student signups trigger
  * Student diagnostic tests endpoint
  * Student analytics endpoints
  * Webhook subscription system

***

**Last Updated:** December 25, 2024 **API Version:** v1.0
