{
  "name": "Otomatzia | ליד מהאתר נכנס לרשימה מסודרת",
  "nodes": [
    {
      "id": "manual-test",
      "name": "Manual test",
      "type": "n8n-nodes-base.manualTrigger",
      "typeVersion": 1,
      "position": [
        0,
        0
      ],
      "parameters": {}
    },
    {
      "id": "sample-lead",
      "name": "Sample lead",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        250,
        0
      ],
      "parameters": {
        "jsCode": "return [{json:{lead_id:'demo-lead-001',name:'עסק לדוגמה',email:'sample@example.com',service:'sales'}}];"
      }
    },
    {
      "id": "website-webhook",
      "name": "Website webhook",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [
        500,
        0
      ],
      "parameters": {
        "httpMethod": "POST",
        "path": "otomatzia-capture-website-lead",
        "authentication": "headerAuth",
        "responseMode": "lastNode",
        "options": {}
      },
      "webhookId": "otomatzia-capture-website-lead"
    },
    {
      "id": "read-leads",
      "name": "Read leads",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        750,
        0
      ],
      "parameters": {
        "documentId": {
          "__rl": true,
          "value": "REPLACE_WITH_SPREADSHEET_ID",
          "mode": "id"
        },
        "sheetName": {
          "__rl": true,
          "value": "Leads",
          "mode": "name"
        },
        "options": {}
      },
      "alwaysOutputData": true
    },
    {
      "id": "process",
      "name": "Process",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1000,
        0
      ],
      "parameters": {
        "jsCode": "const processLeads = function processLeads(kind, rows, incoming, nowIso) {\n  const now = new Date(nowIso);\n  if (!Number.isFinite(now.getTime())) throw new Error('Invalid run timestamp');\n  const columns = ['lead_id','name','email','service','created_at','status','owner','last_contact_at','quote_due_at'];\n  const leads = rows.filter(row => row.lead_id).map(row => Object.fromEntries(columns.map(key => [key, row[key] ?? ''])));\n  const iso = value => value && Number.isFinite(Date.parse(value)) ? Date.parse(value) : null;\n  const active = row => !['accepted', 'rejected', 'closed'].includes(row.status);\n  if (kind === 'capture-website-lead') {\n    const lead = incoming?.body ?? incoming;\n    if (!lead || !/^[a-zA-Z0-9_-]{1,100}$/.test(lead.lead_id ?? '') || typeof lead.name !== 'string' || !lead.name.trim() || !/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(lead.email ?? '')) throw new Error('Required: stable lead_id, name and valid email');\n    if (leads.some(row => row.lead_id === lead.lead_id)) return [];\n    return [{ lead_id: lead.lead_id, name: lead.name.trim().slice(0,150), email: lead.email.trim().toLowerCase(), service: String(lead.service ?? 'other').slice(0,100), created_at: now.toISOString(), status: 'new', owner: '', last_contact_at: '', quote_due_at: '' }];\n  }\n  if (kind === 'assign-lead-owner') return leads.filter(row => active(row) && !row.owner).map(row => ({ ...row, owner: ({ sales: 'sales-team', support: 'support-team' })[row.service] ?? 'unassigned' }));\n  if (kind === 'remind-untouched-leads') return leads.filter(row => row.status === 'new' && !row.last_contact_at && iso(row.created_at) !== null && now.getTime() - iso(row.created_at) >= 86400000).map(row => ({ task_id: `untouched-${row.lead_id}`, lead_id: row.lead_id, owner: row.owner || 'unassigned', task: 'בדקו פנייה שלא טופלה מעל 24 שעות', source: 'untouched' }));\n  if (kind === 'follow-up-quotes') return leads.filter(row => row.status === 'quote_sent' && iso(row.quote_due_at) !== null && iso(row.quote_due_at) < now.getTime()).map(row => ({ task_id: `quote-${row.lead_id}-${row.quote_due_at}`, lead_id: row.lead_id, owner: row.owner || 'unassigned', task: 'בדקו אם נדרש מעקב אחר הצעת המחיר', source: 'quote' }));\n  if (kind === 'daily-lead-summary') return [{ summary_id: now.toLocaleDateString('en-CA', { timeZone: 'Asia/Jerusalem' }), new_leads: leads.filter(row => row.status === 'new').length, overdue: leads.filter(row => active(row) && ((row.status === 'quote_sent' && iso(row.quote_due_at) !== null && iso(row.quote_due_at) < now.getTime()) || (row.status === 'new' && !row.last_contact_at && iso(row.created_at) !== null && now.getTime() - iso(row.created_at) >= 86400000))).length, unassigned: leads.filter(row => active(row) && (!row.owner || row.owner === 'unassigned')).length, generated_at: now.toISOString() }];\n  throw new Error('Unknown recipe');\n};\nconst incoming = $('Website webhook').isExecuted ? $('Website webhook').first().json : $('Sample lead').first().json;\nreturn processLeads('capture-website-lead', $input.all().map(item => item.json), incoming, new Date().toISOString()).map(json => ({json}));"
      }
    },
    {
      "id": "save-result",
      "name": "Save result",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        1250,
        0
      ],
      "parameters": {
        "operation": "appendOrUpdate",
        "documentId": {
          "__rl": true,
          "value": "REPLACE_WITH_SPREADSHEET_ID",
          "mode": "id"
        },
        "sheetName": {
          "__rl": true,
          "value": "Leads",
          "mode": "name"
        },
        "columns": {
          "mappingMode": "autoMapInputData",
          "value": {},
          "matchingColumns": [
            "lead_id"
          ],
          "schema": []
        },
        "options": {
          "cellFormat": "RAW",
          "handlingExtraData": "error"
        }
      }
    }
  ],
  "connections": {
    "Manual test": {
      "main": [
        [
          {
            "node": "Sample lead",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Sample lead": {
      "main": [
        [
          {
            "node": "Read leads",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Website webhook": {
      "main": [
        [
          {
            "node": "Read leads",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read leads": {
      "main": [
        [
          {
            "node": "Process",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Process": {
      "main": [
        [
          {
            "node": "Save result",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1",
    "timezone": "Asia/Jerusalem"
  },
  "pinData": {}
}
