From 6de8b93aced1cde4853e8e6d32357d4d6b22a5e1 Mon Sep 17 00:00:00 2001 From: romanskijdev Date: Thu, 13 Aug 2026 15:48:59 +0300 Subject: [PATCH] Added SMS pushing to Bitrix --- .../handlers/telephony/bitrix.go | 80 +++++++++++++++++++ .../handlers/telephony/handlers.go | 3 + 2 files changed, 83 insertions(+) create mode 100644 service/rest_telephony_service/handlers/telephony/bitrix.go diff --git a/service/rest_telephony_service/handlers/telephony/bitrix.go b/service/rest_telephony_service/handlers/telephony/bitrix.go new file mode 100644 index 0000000..d6cc90d --- /dev/null +++ b/service/rest_telephony_service/handlers/telephony/bitrix.go @@ -0,0 +1,80 @@ +package telephony + +import ( + "bytes" + "encoding/json" + "fmt" + "net/http" + + "github.com/sirupsen/logrus" +) + +// URL вебхука, который ты создал в Битрикс24 +const bitrixWebhookURL = "https://thebest.bitrix24.ru/rest/292/paz20o3316e6cfe7/" + +// BxContactListResp описывает структуру ответа Битрикс24 при поиске +type BxContactListResp struct { + Result []struct { + ID string `json:"ID"` + CompanyID string `json:"COMPANY_ID"` + } `json:"result"` +} + +// PushSmsToBitrix ищет контакт по номеру и пушит SMS в его таймлайн +func PushSmsToBitrix(clientNumber, text string, direction int) { + // 🚀 Выполняем в отдельной горутине, чтобы мгновенно ответить АТС (200 OK) + // и не блокировать работу сервера, пока ждем ответа от Битрикса + go func() { + // 1. Ищем контакт по номеру телефона + searchReqBody, _ := json.Marshal(map[string]interface{}{ + "filter": map[string]string{"PHONE": clientNumber}, + "select": []string{"ID", "COMPANY_ID"}, + }) + + resp, err := http.Post(bitrixWebhookURL+"crm.contact.list.json", "application/json", bytes.NewBuffer(searchReqBody)) + if err != nil { + logrus.Errorf("Bitrix24 search contact error: %v", err) + return + } + defer resp.Body.Close() + + var listResp BxContactListResp + if err := json.NewDecoder(resp.Body).Decode(&listResp); err != nil { + logrus.Errorf("Bitrix24 decode error: %v", err) + return + } + + if len(listResp.Result) == 0 { + logrus.Infof("Bitrix24: Contact with phone %s not found. Skipping timeline comment.", clientNumber) + return + } + + // Берем ID первого найденного контакта + contactID := listResp.Result[0].ID + + // 2. Формируем красивый текст комментария с использованием BBCode (Битрикс его поддерживает) + dirStr := "[b]📥 Входящее SMS[/b]" + if direction == 1 { + dirStr = "[b]📤 Исходящее SMS[/b]" + } + + comment := fmt.Sprintf("%s\nНомер: %s\n\n%s", dirStr, clientNumber, text) + + addReqBody, _ := json.Marshal(map[string]interface{}{ + "fields": map[string]interface{}{ + "ENTITY_ID": contactID, + "ENTITY_TYPE": "contact", // События контакта автоматически видны и в привязанной Компании/Сделке + "COMMENT": comment, + }, + }) + + addResp, err := http.Post(bitrixWebhookURL+"crm.timeline.comment.add.json", "application/json", bytes.NewBuffer(addReqBody)) + if err != nil { + logrus.Errorf("Bitrix24 add comment error: %v", err) + return + } + defer addResp.Body.Close() + + logrus.Infof("Successfully pushed SMS to Bitrix24 timeline for contact ID %s", contactID) + }() +} diff --git a/service/rest_telephony_service/handlers/telephony/handlers.go b/service/rest_telephony_service/handlers/telephony/handlers.go index 3fd48bc..b5e7939 100644 --- a/service/rest_telephony_service/handlers/telephony/handlers.go +++ b/service/rest_telephony_service/handlers/telephony/handlers.go @@ -45,6 +45,9 @@ func (s *TelephonyReg) WebhookTelephonyHandler(w http.ResponseWriter, r *http.Re return nil, errors.New("database error") } + // 🆕 Отправляем SMS в карточку Битрикс24 (выполнится асинхронно) + PushSmsToBitrix(*smsLog.ClientNumber, *smsLog.Text, *smsLog.Direction) + logrus.Infof("Successfully logged SMS from client %s", req.Event.ClientNumber) return map[string]string{"status": "success"}, nil } -- 2.43.0