{
  "name": "OLO • Заявка с сайта и приёмка в CRM",
  "nodes": [
    {
      "id": "9fea6700-d8d0-4f50-a2d1-000000000002",
      "name": "Заявка с сайта",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2.1,
      "position": [
        0,
        0
      ],
      "parameters": {
        "httpMethod": "POST",
        "path": "olo-site-request",
        "responseMode": "responseNode",
        "options": {},
        "authentication": "headerAuth"
      },
      "webhookId": "9fea6700-d8d0-4f50-a2d1-000000000001",
      "credentials": {
        "httpHeaderAuth": {
          "id": "OLO Site Header Auth",
          "name": "OLO Site Header Auth"
        }
      }
    },
    {
      "id": "9fea6700-d8d0-4f50-a2d1-000000000003",
      "name": "Создать задачу в OLO",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        260,
        0
      ],
      "parameters": {
        "method": "POST",
        "url": "https://company.olo.kz/api/integrations/v1/tasks",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendHeaders": true,
        "sendBody": true,
        "contentType": "raw",
        "rawContentType": "application/json",
        "body": "={{ JSON.stringify($json.body ?? {}) }}",
        "options": {
          "redirect": {
            "redirect": {
              "followRedirects": false
            }
          },
          "response": {
            "response": {
              "fullResponse": true,
              "neverError": true,
              "responseFormat": "text",
              "outputPropertyName": "body"
            }
          },
          "timeout": 8000
        },
        "headerParameters": {
          "parameters": [
            {
              "name": "Accept",
              "value": "application/json"
            }
          ]
        }
      },
      "credentials": {
        "httpHeaderAuth": {
          "id": "OLO API Header Auth",
          "name": "OLO API Header Auth"
        }
      },
      "onError": "continueRegularOutput"
    },
    {
      "id": "9fea6700-d8d0-4f50-a2d1-000000000004",
      "name": "Ответить сайту",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.4,
      "position": [
        520,
        0
      ],
      "parameters": {
        "respondWith": "text",
        "responseBody": "={{ $json.statusCode ? ($json.body || '{}') : JSON.stringify({ error: 'olo_unavailable' }) }}",
        "options": {
          "responseCode": "={{ $json.statusCode || 502 }}",
          "responseHeaders": {
            "entries": [
              {
                "name": "Content-Type",
                "value": "application/json; charset=utf-8"
              }
            ]
          }
        }
      }
    },
    {
      "id": "9fea6700-d8d0-4f50-a2d1-000000000006",
      "name": "Приёмка OLO",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2.1,
      "position": [
        0,
        360
      ],
      "parameters": {
        "httpMethod": "POST",
        "path": "olo-task-accepted",
        "responseMode": "responseNode",
        "options": {
          "rawBody": true
        }
      },
      "webhookId": "9fea6700-d8d0-4f50-a2d1-000000000005"
    },
    {
      "id": "9fea6700-d8d0-4f50-a2d1-000000000007",
      "name": "Проверить подпись OLO",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        260,
        360
      ],
      "parameters": {
        "jsCode": "const secret = 'SET_OLO_WEBHOOK_SECRET';\nconst reject = (httpStatus, error) => [{ json: { valid: false, httpStatus, error } }];\n\nif (!secret || secret === 'SET_OLO_WEBHOOK_SECRET') {\n  return reject(503, 'olo_secret_not_configured');\n}\n\nconst { createHmac, timingSafeEqual } = require('crypto');\nconst headers = $input.first().json.headers ?? {};\nconst timestamp = headers['x-olo-timestamp'];\nconst signature = headers['x-olo-signature'];\nconst deliveryId = headers['x-olo-delivery'];\n\nif (typeof timestamp !== 'string' || !/^\\d{10}$/.test(timestamp) ||\n    Math.abs(Math.floor(Date.now() / 1000) - Number(timestamp)) > 300 ||\n    typeof signature !== 'string' || !/^sha256=[a-f0-9]{64}$/.test(signature)) {\n  return reject(401, 'invalid_olo_signature');\n}\n\nif (!$input.first().binary?.data) {\n  return reject(400, 'raw_body_required');\n}\n\nconst raw = await this.helpers.getBinaryDataBuffer(0, 'data');\nconst digest = createHmac('sha256', secret).update(timestamp + '.').update(raw).digest();\n\nif (!timingSafeEqual(digest, Buffer.from(signature.slice(7), 'hex'))) {\n  return reject(401, 'invalid_olo_signature');\n}\n\nconst rawEvent = raw.toString('utf8');\nlet event;\ntry {\n  event = JSON.parse(rawEvent);\n} catch {\n  return reject(400, 'invalid_olo_event');\n}\n\nif (headers['x-olo-event'] !== 'task.accepted' || event?.event !== 'task.accepted' ||\n    event.version !== 1 || typeof event.id !== 'string' ||\n    !/^[a-f0-9-]{36}$/i.test(event.id) || event.id !== deliveryId ||\n    typeof event.data?.external_id !== 'string' || !event.data.external_id ||\n    event.data.review_status !== 'accepted') {\n  return reject(422, 'invalid_olo_event');\n}\n\nreturn [{ json: { valid: true, deliveryId: event.id, rawEvent } }];"
      }
    },
    {
      "id": "9fea6700-d8d0-4f50-a2d1-000000000009",
      "name": "Подпись и событие верны?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        520,
        360
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "9fea6700-d8d0-4f50-a2d1-000000000008",
              "leftValue": "={{ $json.valid }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "9fea6700-d8d0-4f50-a2d1-00000000000a",
      "name": "Отправить результат в CRM",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        780,
        260
      ],
      "parameters": {
        "method": "POST",
        "url": "https://crm.example.invalid/hooks/olo",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Idempotency-Key",
              "value": "={{ $json.deliveryId }}"
            }
          ]
        },
        "sendBody": true,
        "contentType": "raw",
        "rawContentType": "application/json",
        "body": "={{ $json.rawEvent }}",
        "options": {
          "redirect": {
            "redirect": {
              "followRedirects": false
            }
          },
          "response": {
            "response": {
              "fullResponse": true,
              "neverError": true,
              "responseFormat": "text"
            }
          },
          "timeout": 3000
        }
      },
      "credentials": {
        "httpHeaderAuth": {
          "id": "CRM API Header Auth",
          "name": "CRM API Header Auth"
        }
      },
      "onError": "continueRegularOutput"
    },
    {
      "id": "9fea6700-d8d0-4f50-a2d1-00000000000b",
      "name": "Подтвердить OLO после CRM",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.4,
      "position": [
        1040,
        260
      ],
      "parameters": {
        "respondWith": "text",
        "responseBody": "={{ $json.statusCode >= 200 && $json.statusCode < 300 ? '' : JSON.stringify({ error: 'crm_unavailable' }) }}",
        "options": {
          "responseCode": "={{ $json.statusCode >= 200 && $json.statusCode < 300 ? 204 : 502 }}",
          "responseHeaders": {
            "entries": [
              {
                "name": "Content-Type",
                "value": "application/json; charset=utf-8"
              }
            ]
          }
        }
      }
    },
    {
      "id": "9fea6700-d8d0-4f50-a2d1-00000000000c",
      "name": "Отклонить вебхук",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.4,
      "position": [
        780,
        460
      ],
      "parameters": {
        "respondWith": "text",
        "responseBody": "={{ JSON.stringify({ error: $json.error }) }}",
        "options": {
          "responseCode": "={{ $json.httpStatus }}",
          "responseHeaders": {
            "entries": [
              {
                "name": "Content-Type",
                "value": "application/json; charset=utf-8"
              }
            ]
          }
        }
      }
    }
  ],
  "connections": {
    "Заявка с сайта": {
      "main": [
        [
          {
            "node": "Создать задачу в OLO",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Создать задачу в OLO": {
      "main": [
        [
          {
            "node": "Ответить сайту",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Приёмка OLO": {
      "main": [
        [
          {
            "node": "Проверить подпись OLO",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Проверить подпись OLO": {
      "main": [
        [
          {
            "node": "Подпись и событие верны?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Подпись и событие верны?": {
      "main": [
        [
          {
            "node": "Отправить результат в CRM",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Отклонить вебхук",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Отправить результат в CRM": {
      "main": [
        [
          {
            "node": "Подтвердить OLO после CRM",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1",
    "saveDataErrorExecution": "none",
    "saveDataSuccessExecution": "none",
    "saveManualExecutions": false
  },
  "pinData": {},
  "tags": []
}
