# n8n Store Data Integration Guide

## Overview

This document describes how to integrate the Chat Store Data endpoint (`/chat/store-data`) into the n8n coupon generator workflow to enable AI-powered coupon generation with store-specific product IDs, category IDs, and coupon codes.

## Endpoint Details

**URL**: `POST {restUrl}/storeagent-ai/v1/chat/store-data`

**Authentication**: Token-based (aiToolToken from chat session)

**Premium Requirement**: Advanced Coupons Premium plugin must be active

## Request Parameters

```json
{
  "token": "string (required)",
  "types": ["products", "categories", "coupons"] (optional),
  "limit": 50 (optional, 1-100),
  "search": "string (optional)"
}
```

### Parameter Details

| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `token` | string | Yes | - | AI tool authentication token (format: `session_id:::token`) |
| `types` | array | No | `["products", "categories", "coupons"]` | Array of data types to retrieve |
| `limit` | integer | No | 50 | Maximum number of items per type (1-100) |
| `search` | string | No | - | Filter by name, code, or SKU |

## Response Format

### Success Response (200)

```json
{
  "success": true,
  "data": {
    "products": [
      {
        "id": 123,
        "name": "Blue T-Shirt",
        "sku": "BLUE-TS-001",
        "price": "19.99",
        "sale_price": "14.99"
      }
    ],
    "categories": [
      {
        "id": 5,
        "name": "Clothing",
        "slug": "clothing",
        "count": 42
      }
    ],
    "coupons": [
      {
        "id": 789,
        "code": "SUMMER20",
        "type": "percent",
        "amount": "20"
      }
    ]
  },
  "cached": false,
  "timestamp": 1738820400
}
```

### Error Responses

**403 Forbidden - Premium Required**
```json
{
  "code": "premium_required",
  "message": "Advanced Coupons Premium is required to access store data for AI coupon generation.",
  "data": {
    "status": 403
  }
}
```

**401 Unauthorized - Invalid Token**
```json
{
  "code": "invalid_token",
  "message": "Invalid or expired temporary token.",
  "data": {
    "status": 401
  }
}
```

## n8n Workflow Integration

### Current Workflow

**Webhook**: `https://hal.rymera.com.au/webhook/coupon-generator-ai`

**Current Flow**:
1. Receive request from client plugin
2. Generate coupons with AI based on prompt
3. Return coupon templates

### Updated Workflow

**New Flow**:
1. Receive request from client plugin
2. **[NEW]** Fetch store data from `/chat/store-data` endpoint
3. Provide store data context to AI
4. Generate coupons with specific product/category IDs
5. Return coupon templates

### Implementation Steps

#### Step 1: Add HTTP Request Node

**Node Configuration**:

- **Node Name**: `Fetch Store Data`
- **Method**: `POST`
- **URL**: `{{ $json.restUrl }}/storeagent-ai/v1/chat/store-data`
- **Authentication**: None (uses token in body)
- **Headers**:
  ```json
  {
    "Content-Type": "application/json"
  }
  ```
- **Body** (JSON):
  ```json
  {
    "token": "{{ $json.aiToolToken }}",
    "types": ["products", "categories", "coupons"],
    "limit": 50
  }
  ```

**Error Handling**:
- **Continue On Fail**: Yes
- **Fallback**: If request fails, continue without store data (graceful degradation)

#### Step 2: Update AI Prompt Node

**Current Prompt** (example):
```
Generate {{ $json.amount }} WooCommerce coupons based on this description:
{{ $json.description }}

Return as JSON array with coupon objects containing:
- code (string)
- discount_type (percent|fixed_cart|fixed_product)
- amount (number)
- usage_limit (number, optional)
- expiry_date (YYYY-MM-DD, optional)
```

**New Prompt with Store Context**:
```
Generate {{ $json.amount }} WooCommerce coupons based on this description:
{{ $json.description }}

AVAILABLE STORE DATA:
{{ $json.storeData }}

INSTRUCTIONS:
- Use specific product IDs from the store data when the description mentions products
- Use category IDs for category-wide discounts
- Reference existing coupon codes to avoid duplicates
- Format arrays as valid JSON arrays of integers

COUPON SCHEMA:
{
  "code": "string",
  "discount_type": "percent|fixed_cart|fixed_product",
  "amount": "number",
  "product_ids": [123, 456],
  "excluded_product_ids": [789],
  "product_categories": [5, 6],
  "excluded_product_categories": [7],
  "usage_limit": "number",
  "expiry_date": "YYYY-MM-DD"
}

Return as JSON array of coupon objects.
```

**Store Data Reference**:
```javascript
// In n8n, reference the store data response:
{{ $('Fetch Store Data').item.json.data }}

// Or format it nicely:
{{
  JSON.stringify(
    $('Fetch Store Data').item.json.data,
    null,
    2
  )
}}
```

#### Step 3: Data Transformation (Optional)

Add a **Function Node** to format store data for better AI comprehension:

```javascript
// Node: Format Store Data for AI
const storeData = $('Fetch Store Data').item.json.data;

// Format as readable text
let formattedData = "AVAILABLE PRODUCTS:\n";
if (storeData.products) {
  storeData.products.forEach(p => {
    formattedData += `- ID ${p.id}: "${p.name}" (SKU: ${p.sku}, Price: $${p.price})\n`;
  });
}

formattedData += "\nAVAILABLE CATEGORIES:\n";
if (storeData.categories) {
  storeData.categories.forEach(c => {
    formattedData += `- ID ${c.id}: "${c.name}" (${c.count} products)\n`;
  });
}

formattedData += "\nEXISTING COUPONS:\n";
if (storeData.coupons) {
  storeData.coupons.forEach(c => {
    formattedData += `- Code "${c.code}" (Type: ${c.type}, Amount: ${c.amount})\n`;
  });
}

return {
  json: {
    ...items[0].json,
    formattedStoreData: formattedData
  }
};
```

Then use `{{ $json.formattedStoreData }}` in the AI prompt.

## Example Use Cases

### Use Case 1: Product-Specific Discount

**User Prompt**: `"Create a 20% discount for Blue T-Shirt"`

**AI Action**:
1. Parse prompt: identifies "Blue T-Shirt"
2. Search store data: finds product ID 123
3. Generate coupon:
   ```json
   {
     "code": "BLUE20",
     "discount_type": "percent",
     "amount": "20",
     "product_ids": [123]
   }
   ```

### Use Case 2: Category Discount

**User Prompt**: `"Create 10% off all Clothing items"`

**AI Action**:
1. Parse prompt: identifies "Clothing" category
2. Search store data: finds category ID 5
3. Generate coupon:
   ```json
   {
     "code": "CLOTHING10",
     "discount_type": "percent",
     "amount": "10",
     "product_categories": [5]
   }
   ```

### Use Case 3: Avoid Duplicate Codes

**User Prompt**: `"Create a summer sale coupon"`

**AI Action**:
1. Check existing coupons: sees "SUMMER20" exists
2. Generate unique code:
   ```json
   {
     "code": "SUMMER25",
     "discount_type": "percent",
     "amount": "25"
   }
   ```

## Testing Checklist

### Prerequisites
- [ ] Advanced Coupons Premium plugin active on test site
- [ ] StoreAgent AI plugin updated with new endpoint
- [ ] n8n workflow updated with HTTP request node
- [ ] Test products, categories, and coupons exist

### Test Scenarios

#### 1. Basic Functionality
- [ ] Endpoint returns product data
- [ ] Endpoint returns category data
- [ ] Endpoint returns coupon data
- [ ] Response is cached (second request shows `cached: true`)

#### 2. Premium Gating
- [ ] Returns 403 when ACFW Premium is not active
- [ ] Works correctly when ACFW Premium is active

#### 3. Authentication
- [ ] Returns 401 with invalid token
- [ ] Works with valid aiToolToken from chat session

#### 4. Filtering
- [ ] `types` parameter filters correctly
- [ ] `limit` parameter limits results
- [ ] `search` parameter filters by name/code/SKU

#### 5. AI Integration
- [ ] AI generates coupons with specific product_ids
- [ ] AI generates coupons with specific product_categories
- [ ] AI avoids duplicate coupon codes
- [ ] Generated coupons apply correctly at checkout

## Troubleshooting

### Issue: 403 Premium Required

**Cause**: ACFW Premium plugin is not active

**Solution**:
1. Check plugin status: `wp plugin list --name=advanced-coupons`
2. Activate if needed: `wp plugin activate advanced-coupons-for-woocommerce`

### Issue: 401 Invalid Token

**Cause**: aiToolToken is missing or expired

**Solution**:
1. Ensure `aiToolToken` is passed from client to n8n
2. Check token format: `session_id:::token`
3. Token expiry: 30 minutes (refresh by generating new chat session)

### Issue: Empty Response Data

**Cause**: No products/categories/coupons in store, or wrong status filter

**Solution**:
1. Check data exists: `wp post list --post_type=product --post_status=publish`
2. Verify categories: `wp term list product_cat`
3. Check coupons: `wp post list --post_type=shop_coupon --post_status=publish`

### Issue: Store Data Not Used by AI

**Cause**: Prompt doesn't reference store data, or AI doesn't understand format

**Solution**:
1. Ensure store data is included in AI prompt
2. Format data as readable text (see Step 3 above)
3. Add explicit instructions to use IDs from provided data

## Performance Considerations

### Caching
- **Cache Duration**: 5 minutes
- **Cache Key**: Based on parameters (types, limit, search)
- **Invalidation**: Automatic expiry, no manual clearing needed

### Rate Limiting
- **Token Expiry**: 30 minutes per session
- **Request Limits**: No explicit limit, but consider plan limits

### Optimization Tips
1. **Limit Results**: Use `limit` parameter to reduce response size
2. **Filter Types**: Only request needed data types (e.g., just "products")
3. **Search**: Use `search` parameter to narrow results
4. **Cache Awareness**: Design workflows to benefit from 5-minute cache

## Security Considerations

### Token Security
- Tokens are session-based and expire after 30 minutes
- Tokens are validated against WordPress transients
- Each token is unique per user session

### Premium Validation
- Endpoint checks ACFW Premium activation status
- Uses WordPress `is_plugin_active()` for reliable detection

### Data Exposure
- Only returns published products/categories/coupons
- No sensitive customer data exposed
- Respects WooCommerce visibility settings

## Implementation Checklist

- [x] Create `/chat/store-data` endpoint
- [x] Implement premium gating
- [x] Add token validation
- [x] Implement caching (5 minutes)
- [x] Register endpoint in bootstrap
- [ ] Update n8n workflow with HTTP request node
- [ ] Update AI prompt with store data context
- [ ] Test product-specific coupons
- [ ] Test category-specific coupons
- [ ] Test duplicate code avoidance
- [ ] Monitor performance and errors

## Related Documentation

- **Endpoint Code**: `/includes/REST/Chat/Chat_Store_Data.php`
- **Bootstrap Registration**: `/bootstrap/rest-objects.php`
- **Token Trait**: `/includes/Traits/AI_Tool_Token_Trait.php`
- **Chat Tools**: `/includes/REST/Chat/Chat_Tools.php`

## Support

For issues or questions:
1. Check error logs: `wp eval "error_log(print_r(get_transient('saai_store_data_HASH'), true));"`
2. Test endpoint directly: `curl -k -X POST {site}/wp-json/storeagent-ai/v1/chat/store-data`
3. Contact development team with n8n workflow details

---

**Last Updated**: February 2025  
**Version**: 1.0.0  
**Feature**: AI Store Data for Coupon Generation
