# Nago — n8n Workflow Setup

> Step-by-step guide untuk setup n8n + OpenAI integration

---

## 📊 Visual Workflow

```
┌─────────────────────────────────────────────────────────────────┐
│                         USER FLOW                               │
└─────────────────────────────────────────────────────────────────┘
                                │
                                ▼
┌─────────────────────────────────────────────────────────────────┐
│                      FRONTEND WEBSITE                           │
│                    (10 Questions Form)                           │
│                                                                 │
│  ┌─────┐ ┌─────┐ ┌─────┐      ┌─────┐ ┌─────┐               │
│  │ Q1  │→│ Q2  │→│ Q3  │ →...→│ Q9  │→│ Q10 │               │
│  └─────┘ └─────┘ └─────┘      └─────┘ └─────┘               │
│                         │                                      │
│                         ▼                                      │
│              [Submit → POST to Webhook]                        │
└─────────────────────────────────────────────────────────────────┘
                                │
                                ▼
┌─────────────────────────────────────────────────────────────────┐
│                         n8n WORKFLOW                            │
│                                                                 │
│  ┌──────────────┐                                             │
│  │   WEBHOOK    │ ← Trigger dari website                     │
│  │  (POST /v1/) │                                             │
│  └──────┬───────┘                                             │
│         │                                                     │
│         ▼                                                     │
│  ┌──────────────┐                                             │
│  │     SET      │ ← Format data + compile prompt              │
│  │ (Build JSON) │   Jawaban 1-10 + System Prompt              │
│  └──────┬───────┘                                             │
│         │                                                     │
│         ▼                                                     │
│  ┌──────────────┐                                             │
│  │   OPENAI     │ ← Generate AI insight                       │
│  │  (GPT-4)     │   Temperature: 0.8                           │
│  │               │   Max tokens: 2000                          │
│  └──────┬───────┘                                             │
│         │                                                     │
│         ▼                                                     │
│  ┌──────────────┐                                             │
│  │    CODE      │ ← Format output JSON                        │
│  │ (Transform)  │   Parse hasil AI ke struktur               │
│  └──────┬───────┘                                             │
│         │                                                     │
│         ▼                                                     │
│  ┌──────────────┐                                             │
│  │    SEND      │ ← Return hasil ke frontend                  │
│  │  RESPONSE    │   (JSON dengan insight)                    │
│  └──────────────┘                                             │
│                                                                 │
│  ┌──────────────┐                                             │
│  │  NOTIFY      │ ← Optional: Email/Discord notification      │
│  │  (EMAIL)     │   Notifikasi ke Nago                        │
│  └──────────────┘                                             │
└─────────────────────────────────────────────────────────────────┘
                                │
                                ▼
┌─────────────────────────────────────────────────────────────────┐
│                      FRONTEND WEBSITE                           │
│                   (Display AI Result)                           │
│                                                                 │
│           🎭 Your Authentic Self Portrait                      │
│           💎 Core Strengths                                    │
│           🪞 Hidden Patterns                                   │
│           ⚠️ Grow Areas                                       │
│           🧭 Your Life Compass                                 │
│           ✉️ Message from Future Self                          │
│                                                                 │
│           [Upsell: Book Session with Nago]                      │
└─────────────────────────────────────────────────────────────────┘
```

---

## 🚀 Step-by-Step Setup

### Prerequisites

1. **Node.js** installed (v18+)
2. **n8n** account atau self-hosted instance
3. **OpenAI API key**

---

### STEP 1: Setup n8n

**Option A: Cloud (n8n.io)**
```
1. Daftar di https://n8n.io
2. Create new workflow
3. Start from scratch
```

**Option B: Self-hosted**
```bash
npm install -g n8n
n8n start
```

---

### STEP 2: Create Webhook Node

```
1. Add node → "Webhook"
2. Settings:
   - Path: /v1/nago-discovery
   - Method: POST
   - Response Mode: Response to incoming request
   - Response Data: JSON
```

**Webhook URL nanti akan jadi:**
```
https://your-n8n-instance.com/webhook/v1/nago-discovery
```

---

### STEP 3: Setup OpenAI Node

```
1. Add node → "OpenAI"
2. Operation: Complete
3. Model: gpt-4
4. Messages:

Message 1 (System):
---
{{ $json.system_prompt }}
---

(Taruh system prompt lengkap dari file `nago-prompt-design.md`)

Message 2 (User):
---
{{ $json.user_prompt }}
---

(Taruh user prompt template + jawaban dari webhook)

5. Settings:
   - Temperature: 0.8
   - Max Tokens: 2000
```

---

### STEP 4: Setup Code Node (Format Output)

```javascript
// Input: {{ $json.choices[0].message.content }}
// Output: JSON structure yang rapih

const aiResponse = $input.first().json.choices[0].message.content;

// Parse the sections
const sections = {
  authenticPortrait: extractSection(aiResponse, 'YOUR AUTHENTIC SELF PORTRAIT'),
  coreStrengths: extractSection(aiResponse, 'CORE STRENGTHS'),
  hiddenPatterns: extractSection(aiResponse, 'HIDDEN PATTERNS'),
  growAreas: extractSection(aiResponse, 'GROW AREAS'),
  lifeCompass: extractSection(aiResponse, 'YOUR LIFE COMPASS'),
  futureMessage: extractSection(aiResponse, 'MESSAGE FROM YOUR FUTURE SELF')
};

return [
  {
    json: {
      success: true,
      result: aiResponse,
      structured: sections
    }
  }
];

// Helper function
function extractSection(text, header) {
  const regex = new RegExp(`${header}[\\s\\S]*?(?=\\n## |$)`, 'i');
  const match = text.match(regex);
  return match ? match[0].trim() : '';
}
```

---

### STEP 5: Setup Notify Node (Optional)

**Email to Nago:**
```
1. Add node → "Email"
2. To: nago@email.com
3. Subject: New Discovery Submission! 🎭
4. Body:
   New person just completed the Authentic Discovery!
   
   Timestamp: {{ $now }}
   Name: {{ $json.name || 'Anonymous' }}
   
   ---
   
   Preview of their answers:
   {{ $json.answers.q1.substring(0, 100) }}...
   
   ---
   
   View full result: [Dashboard Link]
```

---

## 🔌 Frontend Integration

### HTML Form (Simple Version)

```html
<form id="discovery-form">
  <div class="question" data-q="1">
    <label>1. Dalam 2 minggu terakhir, apa satu momen yang membuatmu merasa benar-benar hidup?</label>
    <textarea name="q1" required></textarea>
  </div>
  
  <div class="question" data-q="2">
    <label>2. Apa mimpi terbesarmu dalam hidup ini?</label>
    <textarea name="q2" required></textarea>
  </div>
  
  <!-- Q3-Q10... -->
  
  <button type="submit">Dapatkan Insightmu</button>
</form>

<script>
document.getElementById('discovery-form').addEventListener('submit', async (e) => {
  e.preventDefault();
  
  const formData = new FormData(e.target);
  const answers = {
    q1: formData.get('q1'),
    q2: formData.get('q2'),
    q3: formData.get('q3'),
    q4: formData.get('q4'),
    q5: formData.get('q5'),
    q6: formData.get('q6'),
    q7: formData.get('q7'),
    q8: formData.get('q8'),
    q9: formData.get('q9'),
    q10: formData.get('q10')
  };
  
  // Show loading
  document.getElementById('loading').style.display = 'block';
  
  try {
    const response = await fetch('YOUR_N8N_WEBHOOK_URL', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(answers)
    });
    
    const result = await response.json();
    
    // Display result
    document.getElementById('result').innerHTML = result.result;
    document.getElementById('result').style.display = 'block';
  } catch (error) {
    alert('Terjadi kesalahan. Coba lagi ya.');
  }
  
  document.getElementById('loading').style.display = 'none';
});
</script>
```

---

## 📁 n8n Workflow JSON (Importable)

```json
{
  "name": "Nago Authentic Discovery",
  "nodes": [
    {
      "parameters": {
        "path": "nago-discovery",
        "method": "post",
        "responseMode": "responseNode"
      },
      "name": "Webhook",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 1,
      "position": [250, 300]
    },
    {
      "parameters": {
        "values": {
          "string": [
            {
              "name": "system_prompt",
              "value": "Kamu adalah Nago Tejena — seorang psikolog..."
            }
          ]
        },
        "options": {}
      },
      "name": "Set - Compile Prompt",
      "type": "n8n-nodes-base.set",
      "typeVersion": 1,
      "position": [450, 300]
    },
    {
      "parameters": {
        "operation": "complete",
        "model": "gpt-4",
        "messages": {
          "values": [
            {
              "role": "system",
              "content": "={{ $json.system_prompt }}"
            },
            {
              "role": "user",
              "content": "={{ $json.user_prompt }}"
            }
          ]
        },
        "options": {
          "temperature": 0.8,
          "maxTokens": 2000
        }
      },
      "name": "OpenAI - Generate Insight",
      "type": "n8n-nodes-base.openAi",
      "typeVersion": 1,
      "position": [650, 300]
    },
    {
      "parameters": {
        "jsCode": "// Format output\nconst aiResponse = $input.first().json.choices[0].message.content;\n\nreturn [\n  {\n    json: {\n      success: true,\n      result: aiResponse\n    }\n  }\n];"
      },
      "name": "Code - Format Output",
      "type": "n8n-nodes-base.code",
      "typeVersion": 1,
      "position": [850, 300]
    }
  ],
  "connections": {
    "Webhook": {
      "main": [[
        { "node": "Set - Compile Prompt", "type": "main", "index": 0 }
      ]]
    },
    "Set - Compile Prompt": {
      "main": [[
        { "node": "OpenAI - Generate Insight", "type": "main", "index": 0 }
      ]]
    },
    "OpenAI - Generate Insight": {
      "main": [[
        { "node": "Code - Format Output", "type": "main", "index": 0 }
      ]]
    }
  }
}
```

---

## ⚙️ Environment Variables

```bash
# .env file
OPENAI_API_KEY=sk-xxxxx
N8N_BASIC_AUTH_ACTIVE=true
N8N_BASIC_AUTH_USER=admin
N8N_BASIC_AUTH_PASSWORD=xxxxx
```

---

## 📝 Todo List

- [x] n8n workflow design
- [ ] Setup n8n account
- [ ] Create webhook
- [ ] Configure OpenAI node
- [ ] Test workflow
- [ ] Frontend development
- [ ] Integration testing
- [ ] Deploy

---

## 💰 Estimated Cost

| Item | Cost |
|------|------|
| n8n Cloud (Starter) | ~$16/bulan |
| OpenAI GPT-4 | ~$0.03-0.06/submission |
| Domain + Hosting | ~$5-10/bulan |

**Per submission:** ~Rp 500-1000 (AI cost aja)

---

## Status

- [x] Prompt design
- [x] n8n workflow design
- [ ] n8n setup
- [ ] Frontend wireframe
- [ ] Testing
- [ ] Deployment

