{
  "name": "OLO • Битрикс24: новая сделка и результат приёмки",
  "nodes": [
    {
      "id": "a9cfe100-c6a7-4c6b-917d-000000000002",
      "name": "Новая сделка Битрикс24",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2.1,
      "position": [
        0,
        0
      ],
      "parameters": {
        "httpMethod": "POST",
        "path": "olo-bitrix24-deal-created",
        "responseMode": "responseNode",
        "options": {}
      },
      "webhookId": "a9cfe100-c6a7-4c6b-917d-000000000001"
    },
    {
      "id": "a9cfe100-c6a7-4c6b-917d-000000000004",
      "name": "Приёмка задачи OLO",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2.1,
      "position": [
        0,
        200
      ],
      "parameters": {
        "httpMethod": "POST",
        "path": "olo-bitrix24-task-accepted",
        "responseMode": "responseNode",
        "options": {
          "rawBody": true
        }
      },
      "webhookId": "a9cfe100-c6a7-4c6b-917d-000000000003"
    },
    {
      "id": "a9cfe100-c6a7-4c6b-917d-000000000005",
      "name": "Ответить источнику",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.4,
      "position": [
        1840,
        340
      ],
      "parameters": {
        "respondWith": "text",
        "responseBody": "={{ $json.body ? JSON.stringify($json.body) : '' }}",
        "options": {
          "responseCode": "={{ $json.httpStatus }}",
          "responseHeaders": {
            "entries": [
              {
                "name": "Content-Type",
                "value": "application/json; charset=utf-8"
              }
            ]
          }
        }
      }
    },
    {
      "id": "a9cfe100-c6a7-4c6b-917d-000000000006",
      "name": "Проверить событие и настроить подключение",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        260,
        100
      ],
      "parameters": {
        "jsCode": "const config = {\n  portal: 'company.bitrix24.kz',\n  restWebhook: 'https://company.bitrix24.kz/rest/USER_ID/WEBHOOK_KEY/',\n  bitrixEventToken: 'SET_BITRIX24_EVENT_TOKEN',\n  categoryId: 'SET_BITRIX24_CATEGORY_ID',\n  resultField: 'SET_BITRIX24_RESULT_FIELD',\n  oloSigningSecret: 'SET_OLO_WEBHOOK_SECRET',\n};\n\nconst { createHash, createHmac, timingSafeEqual } = require('crypto');\nconst item = $input.first();\nconst headers = item.json.headers ?? {};\nconst stop = (httpStatus, error) => [{ json: { proceed: false, httpStatus, body: { error } } }];\nconst sameSecret = (a, b) => {\n  if (typeof a !== 'string' || !a || a.length > 512) return false;\n  const digest = value => createHash('sha256').update(value).digest();\n  return timingSafeEqual(digest(a), digest(b));\n};\nconst isDealId = value => /^[1-9][0-9]*$/.test(String(value)) && Number.isSafeInteger(Number(value));\n\nif (!/^(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9][a-z0-9-]*$/.test(config.portal) ||\n    !config.restWebhook.startsWith('https://' + config.portal + '/rest/') ||\n    !/^\\/rest\\/[1-9][0-9]*\\/[a-z0-9_-]+\\/$/i.test(config.restWebhook.slice(('https://' + config.portal).length)) ||\n    !/^(?:0|[1-9][0-9]*)$/.test(String(config.categoryId)) ||\n    !/^UF_CRM_[A-Z0-9_]+$/.test(config.resultField) ||\n    !config.bitrixEventToken || config.bitrixEventToken.startsWith('SET_') ||\n    !config.oloSigningSecret || config.oloSigningSecret.startsWith('SET_')) {\n  return stop(503, 'connection_not_configured');\n}\n\nconst context = {\n  proceed: true,\n  portal: config.portal,\n  restWebhook: config.restWebhook,\n  categoryId: Number(config.categoryId),\n  resultField: config.resultField,\n};\n\nif (!item.binary?.data) {\n  const event = item.json.body ?? {};\n  const domain = event.auth?.domain ?? event['auth[domain]'];\n  const token = event.auth?.application_token ?? event['auth[application_token]'];\n  if (domain !== config.portal || !sameSecret(token, config.bitrixEventToken)) {\n    return stop(401, 'invalid_bitrix24_token');\n  }\n  if (String(event.event).toUpperCase() !== 'ONCRMDEALADD') {\n    return [{ json: { proceed: false, httpStatus: 204 } }];\n  }\n  const dealId = event.data?.FIELDS?.ID ?? event['data[FIELDS][ID]'];\n  if (!isDealId(dealId)) return stop(422, 'invalid_deal_id');\n  return [{ json: { ...context, intake: true, dealId: Number(dealId) } }];\n}\n\nconst timestamp = headers['x-olo-timestamp'];\nconst signature = headers['x-olo-signature'];\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 stop(401, 'invalid_olo_signature');\n}\n\nconst raw = await this.helpers.getBinaryDataBuffer(0, 'data');\nconst expected = createHmac('sha256', config.oloSigningSecret).update(timestamp + '.').update(raw).digest();\nif (!timingSafeEqual(expected, Buffer.from(signature.slice(7), 'hex'))) {\n  return stop(401, 'invalid_olo_signature');\n}\n\nlet event;\ntry {\n  event = JSON.parse(raw.toString('utf8'));\n} catch {\n  return stop(400, 'invalid_olo_event');\n}\n\nconst data = event?.data;\nconst dealId = /^bitrix24:deal:([1-9][0-9]*)$/.exec(data?.external_id)?.[1];\nconst reviewedAt = Date.parse(data?.reviewed_at);\nif (event?.event !== 'task.accepted' || headers['x-olo-event'] !== 'task.accepted' ||\n    event.version !== 1 || typeof event.id !== 'string' || event.id !== headers['x-olo-delivery'] ||\n    !isDealId(dealId) || !isDealId(data?.task_id) || data.review_status !== 'accepted' ||\n    !Number.isFinite(reviewedAt)) {\n  return stop(422, 'invalid_olo_event');\n}\n\nreturn [{ json: {\n  ...context,\n  intake: false,\n  dealId: Number(dealId),\n  taskId: Number(data.task_id),\n  reviewedAt: new Date(reviewedAt).toISOString(),\n  reviewComment: typeof data.review_comment === 'string' ? data.review_comment.slice(0, 500) : '',\n} }];"
      }
    },
    {
      "id": "a9cfe100-c6a7-4c6b-917d-000000000008",
      "name": "Запрос подтверждён?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        520,
        100
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "a9cfe100-c6a7-4c6b-917d-000000000007",
              "leftValue": "={{ $json.proceed }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "a9cfe100-c6a7-4c6b-917d-000000000009",
      "name": "Прочитать сделку Битрикс24",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        780,
        0
      ],
      "parameters": {
        "method": "POST",
        "url": "={{ $json.restWebhook + 'crm.item.get.json' }}",
        "authentication": "none",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Accept",
              "value": "application/json"
            }
          ]
        },
        "sendBody": true,
        "contentType": "raw",
        "rawContentType": "application/json",
        "body": "={{ JSON.stringify({ entityTypeId: 2, id: $json.dealId, useOriginalUfNames: 'Y' }) }}",
        "options": {
          "redirect": {
            "redirect": {
              "followRedirects": false
            }
          },
          "response": {
            "response": {
              "fullResponse": true,
              "neverError": true,
              "responseFormat": "json"
            }
          },
          "timeout": 1700
        }
      },
      "onError": "continueRegularOutput"
    },
    {
      "id": "a9cfe100-c6a7-4c6b-917d-00000000000a",
      "name": "Подготовить заявку или результат",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1040,
        0
      ],
      "parameters": {
        "jsCode": "const context = $('Проверить событие и настроить подключение').item.json;\nconst response = $input.first().json;\nconst deal = response.body?.result?.item;\nconst stop = (httpStatus, error) => [{ json: { proceed: false, httpStatus, ...(error ? { body: { error } } : {}) } }];\n\nif (!(response.statusCode >= 200 && response.statusCode < 300) ||\n    response.body?.error || Number(deal?.id) !== context.dealId) {\n  return stop(502, 'bitrix24_read_failed');\n}\n\nif (deal.categoryId == null || String(deal.categoryId) === '' || Number(deal.categoryId) !== context.categoryId) {\n  return context.intake ? stop(204) : stop(422, 'deal_outside_configured_funnel');\n}\n\nif (context.intake) {\n  const title = typeof deal.title === 'string' ? deal.title.trim() : '';\n  const externalId = 'bitrix24:deal:' + context.dealId;\n  return [{ json: { proceed: true, intake: true, request: {\n    external_id: externalId,\n    title: title ? Array.from(title).slice(0, 255).join('') : 'Сделка Битрикс24 №' + context.dealId,\n    source_url: 'https://' + context.portal + '/crm/deal/details/' + context.dealId + '/',\n  } } }];\n}\n\nif (!Object.hasOwn(deal, context.resultField)) {\n  return stop(502, 'bitrix24_result_field_not_found');\n}\n\nconst current = typeof deal[context.resultField] === 'string' ? deal[context.resultField] : '';\nconst currentResult = /^Принято в OLO\\r?\\nЗадача №(\\d+)\\r?\\nПриёмка \\(UTC\\): ([^\\r\\n]+)/.exec(current);\nif (Number(currentResult?.[1]) === context.taskId &&\n    Date.parse(currentResult[2]) >= Date.parse(context.reviewedAt)) {\n  return stop(204);\n}\n\nconst value = [\n  'Принято в OLO',\n  'Задача №' + context.taskId,\n  'Приёмка (UTC): ' + context.reviewedAt,\n  context.reviewComment ? '\\nКомментарий: ' + context.reviewComment : '',\n].filter(Boolean).join('\\n');\n\nreturn [{ json: {\n  proceed: true,\n  intake: false,\n  restWebhook: context.restWebhook,\n  dealId: context.dealId,\n  resultField: context.resultField,\n  value,\n} }];"
      }
    },
    {
      "id": "a9cfe100-c6a7-4c6b-917d-00000000000c",
      "name": "Есть действие?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        1300,
        0
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "a9cfe100-c6a7-4c6b-917d-00000000000b",
              "leftValue": "={{ $json.proceed }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "a9cfe100-c6a7-4c6b-917d-00000000000e",
      "name": "Новая сделка?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        1560,
        0
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "a9cfe100-c6a7-4c6b-917d-00000000000d",
              "leftValue": "={{ $json.intake }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "a9cfe100-c6a7-4c6b-917d-00000000000f",
      "name": "Создать задачу в OLO",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1840,
        -150
      ],
      "parameters": {
        "method": "POST",
        "url": "https://company.olo.kz/api/integrations/v1/tasks",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Accept",
              "value": "application/json"
            }
          ]
        },
        "sendBody": true,
        "contentType": "raw",
        "rawContentType": "application/json",
        "body": "={{ JSON.stringify($json.request) }}",
        "options": {
          "redirect": {
            "redirect": {
              "followRedirects": false
            }
          },
          "response": {
            "response": {
              "fullResponse": true,
              "neverError": true,
              "responseFormat": "text",
              "outputPropertyName": "body"
            }
          },
          "timeout": 8000
        }
      },
      "onError": "continueRegularOutput",
      "credentials": {
        "httpHeaderAuth": {
          "id": "OLO API Header Auth",
          "name": "OLO API Header Auth"
        }
      }
    },
    {
      "id": "a9cfe100-c6a7-4c6b-917d-000000000010",
      "name": "Ответить Битрикс24",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.4,
      "position": [
        2100,
        -150
      ],
      "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": "a9cfe100-c6a7-4c6b-917d-000000000011",
      "name": "Записать приёмку в поле сделки",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1840,
        100
      ],
      "parameters": {
        "method": "POST",
        "url": "={{ $json.restWebhook + 'crm.item.update.json' }}",
        "authentication": "none",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Accept",
              "value": "application/json"
            }
          ]
        },
        "sendBody": true,
        "contentType": "raw",
        "rawContentType": "application/json",
        "body": "={{ JSON.stringify({ entityTypeId: 2, id: $json.dealId, useOriginalUfNames: 'Y', fields: { [$json.resultField]: $json.value } }) }}",
        "options": {
          "redirect": {
            "redirect": {
              "followRedirects": false
            }
          },
          "response": {
            "response": {
              "fullResponse": true,
              "neverError": true,
              "responseFormat": "json"
            }
          },
          "timeout": 1700
        }
      },
      "onError": "continueRegularOutput"
    },
    {
      "id": "a9cfe100-c6a7-4c6b-917d-000000000012",
      "name": "Проверить сохранение результата",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        2100,
        100
      ],
      "parameters": {
        "jsCode": "const expected = $('Подготовить заявку или результат').item.json;\nconst response = $input.first().json;\nconst updated = response.body?.result?.item;\nconst saved = response.statusCode >= 200 && response.statusCode < 300 &&\n  !response.body?.error && Number(updated?.id) === expected.dealId &&\n  updated?.[expected.resultField] === expected.value;\n\nreturn [{ json: {\n  httpStatus: saved ? 204 : 502,\n  ...(saved ? {} : { body: { error: 'bitrix24_update_not_confirmed' } }),\n} }];"
      }
    },
    {
      "id": "a9cfe100-c6a7-4c6b-917d-000000000013",
      "name": "Ответить OLO",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.4,
      "position": [
        2360,
        100
      ],
      "parameters": {
        "respondWith": "text",
        "responseBody": "={{ $json.body ? JSON.stringify($json.body) : '' }}",
        "options": {
          "responseCode": "={{ $json.httpStatus }}",
          "responseHeaders": {
            "entries": [
              {
                "name": "Content-Type",
                "value": "application/json; charset=utf-8"
              }
            ]
          }
        }
      }
    }
  ],
  "connections": {
    "Новая сделка Битрикс24": {
      "main": [
        [
          {
            "node": "Проверить событие и настроить подключение",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Приёмка задачи OLO": {
      "main": [
        [
          {
            "node": "Проверить событие и настроить подключение",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Проверить событие и настроить подключение": {
      "main": [
        [
          {
            "node": "Запрос подтверждён?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Запрос подтверждён?": {
      "main": [
        [
          {
            "node": "Прочитать сделку Битрикс24",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Ответить источнику",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Прочитать сделку Битрикс24": {
      "main": [
        [
          {
            "node": "Подготовить заявку или результат",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Подготовить заявку или результат": {
      "main": [
        [
          {
            "node": "Есть действие?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Есть действие?": {
      "main": [
        [
          {
            "node": "Новая сделка?",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Ответить источнику",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Новая сделка?": {
      "main": [
        [
          {
            "node": "Создать задачу в OLO",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Записать приёмку в поле сделки",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Создать задачу в OLO": {
      "main": [
        [
          {
            "node": "Ответить Битрикс24",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Записать приёмку в поле сделки": {
      "main": [
        [
          {
            "node": "Проверить сохранение результата",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Проверить сохранение результата": {
      "main": [
        [
          {
            "node": "Ответить OLO",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1",
    "saveDataErrorExecution": "none",
    "saveDataSuccessExecution": "none",
    "saveManualExecutions": false
  },
  "pinData": {},
  "tags": []
}
