# n8n-nodes-surna-elearning

[![npm version](https://badge.fury.io/js/n8n-nodes-surna-elearning.svg)](https://www.npmjs.com/package/n8n-nodes-surna-elearning)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

Official n8n community node for the [Surna eLearning Platform](https://surna.io). Create and manage eLearning courses through visual workflows and AI-powered automation.

## Features

✨ **Two Integration Approaches:**
- **Surna Node**: Full-featured node for manual workflow building with visual configuration
- **Surna AI Tools**: Tools for AI Agent nodes to enable autonomous course creation

🚀 **Key Capabilities:**
- Create, update, and manage courses, lessons, and content blocks
- Support for 18 block types (text, images, videos, quizzes, interactive elements)
- Batch operations for efficient multi-item creation (3+ items recommended)
- Multi-language course version management
- AI image generation and asset management
- Import/export courses as portable JSON
- AI Agent integration via Surna Tools node with comprehensive operation support

⚡ **Performance Optimized:**
- Batch operations reduce API calls by 60-90%
- Atomic transactions ensure data consistency
- Efficient tool discovery without loading all definitions

## Installation

### Method 1: Via n8n Community Nodes (Recommended)

1. Open your n8n instance
2. Go to **Settings** → **Community Nodes**
3. Click **Install a community node**
4. Enter: `n8n-nodes-surna-elearning`
5. Click **Install**

### Method 2: Via npm (Manual)

```bash
# In your n8n installation directory
npm install n8n-nodes-surna-elearning

# Restart n8n
```

### Method 3: From Source (Development)

```bash
# Clone the repository
git clone https://github.com/discoverelearning/n8n-nodes-surna-elearning.git
cd n8n-nodes-surna-elearning

# Install dependencies and build
npm install
npm run build

# Link to your n8n installation
cd /path/to/n8n/installation
npm link /path/to/n8n-nodes-surna-elearning

# Restart n8n
```

## Setup

### 1. Get Your Surna API Key

1. Log in to your [Surna account](https://app.surna.io)
2. Go to **Settings** → **API Keys**
3. Click **Generate New API Key**
4. Copy the API key (you won't be able to see it again!)

### 2. Configure Credentials in n8n

1. In your n8n workflow, add a **Surna** or **Surna AI Tools** node
2. Click **Create New Credentials**
3. Enter:
   - **API Key**: Your Surna API key
   - **API URL**: `https://app.surna.io/api` (default for production)
4. Click **Save**

## Usage

### Using the Surna Node (Visual Workflows)

The Surna node provides a visual interface for all operations:

#### Example 1: Create a Simple Course

```
[Manual Trigger]
    ↓
[Surna Node]
  Resource: Course
  Operation: Create
  Title: "Employee Onboarding"
  Description: "Welcome to the team!"
    ↓
[Surna Node]
  Resource: Lesson
  Operation: Create
  Course ID: {{$node["Surna"].json.id}}
  Title: "Day 1: Introduction"
    ↓
[Surna Node]
  Resource: Block
  Operation: Create
  Lesson ID: {{$node["Surna1"].json.id}}
  Type: paragraph
  Content: {"text": "Welcome to your first day!"}
```

#### Example 2: Batch Create Multiple Lessons

```
[HTTP Request]
  Fetch course outline from external API
    ↓
[Code Node]
  Transform outline into lessons array:
  [
    {"title": "Introduction"},
    {"title": "Getting Started"},
    {"title": "Best Practices"}
  ]
    ↓
[Surna Node]
  Resource: Lesson
  Operation: Batch Create
  Course ID: {{$parameter.courseId}}
  Lessons: {{$json.lessons}}
```

#### Example 3: Generate AI Image and Use in Course

```
[Manual Trigger]
    ↓
[Surna Node]
  Resource: Asset
  Operation: Generate AI Image
  Prompt: "A friendly robot teaching in a modern classroom"
    ↓
[Surna Node]
  Resource: Block
  Operation: Create
  Lesson ID: {{$parameter.lessonId}}
  Type: imageCentered
  Content: {"assetId": "{{$node["Surna"].json.id}}"}
```

### Using Surna AI Tools (AI Agent Workflows)

Surna AI Tools enable autonomous course creation with AI agents. The **Surna Tools** node provides a comprehensive set of operations that AI agents can discover and use dynamically via the `search_tools` operation.

**Key Features:**
- AI agents can discover available tools and their parameters using `search_tools`
- Automatic parameter validation with helpful error messages
- Support for all course, lesson, block, asset, and language operations
- Batch operations for efficient multi-item creation

#### Example 1: AI-Powered Course Generator

```
[Webhook Trigger]
  Receives: {"topic": "Fire Safety", "targetAudience": "office workers"}
    ↓
[AI Agent Node]
  Tools:
    - Surna AI Tools (select: create_course, batch_create_lessons, batch_create_blocks)
  Model: Claude 3.5 Sonnet
  Prompt: "Create a comprehensive fire safety training course
          with 5 lessons covering prevention, detection, response,
          equipment, and compliance. Include text content, headings,
          and dividers."
    ↓
[Code Node]
  Extract and format course ID from agent response
    ↓
[Surna Node]
  Resource: Course
  Operation: Export
  Course ID: {{$json.courseId}}
    ↓
[Send Email]
  Attachment: Course export JSON
```

#### Example 2: Content Repurposing Pipeline

```
[Google Drive Trigger]
  Watches: /Training Materials folder
    ↓
[Extract Text Node]
  Extract text from PDF/DOCX
    ↓
[OpenAI Node]
  Model: GPT-4
  Prompt: "Analyze this document and create a structured
          course outline with lesson titles and key topics"
    ↓
[AI Agent Node]
  Tools: Surna AI Tools
  Context: {{$node["OpenAI"].json.outline}}
  Task: "Create a Surna course based on this outline.
         Use batch operations for efficiency. Add appropriate
         headings, paragraphs, and dividers."
    ↓
[Slack Notification]
  Message: "✅ New course created: {{$json.courseTitle}}"
```

#### Example 3: Multi-Language Course Creation

```
[HTTP Request]
  Get master course content
    ↓
[Surna Node]
  Resource: Course
  Operation: Create
  (Creates English version)
    ↓
[Loop Node]
  Items: ['fr', 'es', 'de', 'ja']
    ↓
[Surna Node]
  Resource: Language
  Operation: Create Version
  Language: {{$item}}
    ↓
[OpenAI Node]
  Translate course content to {{$item}}
    ↓
[AI Agent Node]
  Tools: Surna AI Tools (batch_update_blocks)
  Task: "Update all blocks in this language version
         with the translated content"
```

## Available Operations

### Course Operations
- **Create**: Create a new course
- **Get**: Retrieve course details
- **Get All**: List all courses
- **Update**: Update course properties
- **Delete**: Delete a course
- **Duplicate**: Duplicate course with all content
- **Export**: Export course to JSON
- **Import**: Import course from JSON

### Lesson Operations
- **Create**: Create a new lesson
- **Batch Create**: Create multiple lessons efficiently (3+)
- **Get**: Retrieve lesson details
- **Get All**: List all lessons in a course
- **Update**: Update lesson properties
- **Delete**: Delete a lesson
- **Duplicate**: Duplicate lesson
- **Reorder All Lessons**: Change lesson order in a course

### Block Operations
- **Create**: Create a new content block
- **Batch Create**: Create multiple blocks efficiently (3+)
- **Batch Update**: Update multiple blocks efficiently (3+)
- **Get**: Retrieve block details
- **Get All**: List all blocks in a lesson
- **Update**: Update block content
- **Delete**: Delete a block
- **Duplicate**: Duplicate block
- **Reorder All Blocks**: Change order of all blocks in a lesson

### Asset Operations
- **Get**: Retrieve asset details
- **Get All**: List all assets
- **Create From URL**: Import image from URL
- **Generate AI Image**: Generate image from text prompt
- **Generate AI Narration**: Generate narration audio asset from text/SSML
- **Get Saved Voices**: List saved ElevenLabs voices configured in Surna
- **Replace Asset File**: Replace an existing asset while keeping the same ID
- **Update Metadata**: Update caption and alt text
- **Delete**: Delete an asset

### Language Operations
- **Create Version**: Create new language version
- **Get All Versions**: List all language versions
- **Update Metadata**: Update translated metadata
- **Delete Version**: Delete a language version

## Block Types

Surna supports 18 content block types:

**Text Blocks:**
- `paragraph` - Plain text paragraph
- `heading` - Large heading text (`text` field holds the heading)
- `headingParagraph` - Heading with paragraph combo
- `list` - Bulleted or numbered list

**Image Blocks:**
- `imageCentered` - Centered image with max-width
- `imageFullWidth` - Edge-to-edge image
- `imageSideBySide` - Image with text beside it (`assetId`, `alt`, `text`; optional caption/layout/imageWidthPercent)
- `imageTextOverlay` - Image with text overlay (`overlayText` plus `overlayPosition`)

**Interactive Blocks:**
- `videoEmbed` - Embedded video player
- `tabs` - Tabbed content sections (items = `{ id, title, content }` with `content` for the tab body)
- `accordion` - Collapsible content (items = `{ id, title, content }` with `content` for the expanded text)
- `flipCards` - Interactive flip cards (`cards[{ id, frontText, backText }]`)
- `cardSort` - Drag-and-drop card sorting (requires `categories[{ id, label }]` for headers — max 3 — and `cards[{ id, text, correctCategoryId }]`)

**Assessment Blocks:**
- `singleChoice` - Single-answer quiz
- `multipleChoice` - Multiple-answer quiz
- `fillInBlank` - Text input question (question must include `<BLANK>`; `acceptedAnswers` uses string[] for one blank or string[][] for multiple; include `caseSensitive`, feedback, `allowRetries`)

**Other Blocks:**
- `dividerLine` - Visual divider
- `customButton` - Call-to-action button (`buttonText` is the label)

## Batch Operations

For creating or updating 3+ items, use batch operations for better performance:

### Batch Create Lessons
```json
{
  "courseId": "course_123",
  "lessons": [
    {"title": "Introduction"},
    {"title": "Getting Started"},
    {"title": "Best Practices"}
  ]
}
```

### Batch Create Blocks
```json
{
  "lessonId": "lesson_456",
  "blocks": [
    {"type": "heading", "text": "Welcome"},
    {"type": "paragraph", "text": "This is lesson 1."},
    {"type": "dividerLine", "height": 2, "color": "#e5e7eb"}
  ]
}
```

### Batch Update Blocks
```json
{
  "updates": [
    {"blockId": "block_1", "updates": {"text": "Updated content"}},
    {"blockId": "block_2", "updates": {"paddingTop": 32}}
  ]
}
```

## AI Tool Discovery

## Best Practices

### 1. Use Batch Operations for Multiple Items
```
❌ DON'T: Loop over 5 lessons and create individually (5 API calls)
✅ DO: Use batch_create_lessons once (1 API call)
```

### 2. Select Only Needed Tools
Choose the specific tools your workflow requires (courses, lessons, blocks, assets, voices) to keep agent calls focused.

### 3. Set Proper Alt Text for Images
```
Always provide descriptive alt text for accessibility
```

### 4. Validate Block Types
```
Ensure block type matches available types (18 total)
```

### 5. Use Export/Import for Backups
```
Export courses before major changes
Store exports for version control
```

## Troubleshooting

### Error: "Invalid API Key"
- Verify API key is correct in n8n credentials
- Check API URL is `https://app.surna.io/api`
- Ensure API key hasn't been revoked

### Error: "Block type not supported"
- Check block type spelling (case-sensitive)
- Verify type is one of the 18 supported types
- See [Block Types](#block-types) section

### Batch Operation Fails
- Ensure array is properly formatted JSON
- Validate all required fields are present
- Check for typos in field names

### AI Agent Not Creating Content
- Verify Surna AI Tools node is connected
- Check correct tools are selected
- Review agent prompt clarity

## Development

### Building from Source

```bash
# Install dependencies
npm install

# Build TypeScript
npm run build

# Run linter
npm run lint

# Fix lint issues
npm run lintfix

# Format code
npm run format
```

### Project Structure

```
n8n-nodes-surna-elearning/
├── credentials/
│   └── SurnaApi.credentials.ts      # API credentials
├── nodes/
│   ├── Surna/
│   │   ├── Surna.node.ts            # Main node
│   │   ├── descriptions/            # UI field definitions
│   │   └── operations/              # Operation implementations
│   └── SurnaAiTool/
│       ├── SurnaAiTool.tool.ts      # AI Agent tool
│       └── tool-definitions.ts      # Tool schemas
├── utils/
│   └── SurnaApiClient.ts            # API client
└── package.json
```

## Contributing

Contributions are welcome! Please:

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests if applicable
5. Submit a pull request

## Support

- **Documentation**: [https://surna.io/docs](https://surna.io/docs)
- **Issues**: [GitHub Issues](https://github.com/discoverelearning/n8n-nodes-surna-elearning/issues)
- **Email**: support@surna.io
- **n8n Community**: [n8n Forum](https://community.n8n.io/)

## License

MIT License - see [LICENSE](LICENSE) file for details

## Credits

Built with ❤️ by the Surna team for the n8n community.

- **Surna Platform**: [surna.io](https://surna.io)
- **n8n Workflow Automation**: [n8n.io](https://n8n.io)

---

**Ready to automate your eLearning content creation?** 🚀

Install the node, connect your API key, and start building intelligent course generation workflows today!
