66 lines
1.4 KiB
Go
66 lines
1.4 KiB
Go
package senders
|
||
|
||
import (
|
||
"encoding/json"
|
||
"errors"
|
||
"fmt"
|
||
"github.com/gofiber/fiber/v2"
|
||
)
|
||
|
||
type WebhookSender struct {
|
||
client *fiber.Client
|
||
}
|
||
|
||
func NewWebhookSender() *WebhookSender {
|
||
return &WebhookSender{
|
||
client: fiber.AcquireClient(),
|
||
}
|
||
}
|
||
|
||
type WebhookPayload struct {
|
||
QAPairs map[string]string `json:"qa_pairs"` // вопрос -> ответ
|
||
}
|
||
|
||
func (w *WebhookSender) SendLead(data LeadData) error {
|
||
if data.Template == "reject" { // это у нас для неуплоченных, смысл отправлять пост с напомиашкой есть?
|
||
return nil
|
||
}
|
||
|
||
qaPairs := make(map[string]string)
|
||
for _, answer := range data.TemplateData.AllAnswers {
|
||
questionTitle, exists := data.TemplateData.QuestionsMap[answer.QuestionID]
|
||
if exists {
|
||
qaPairs[questionTitle] = answer.Content
|
||
}
|
||
}
|
||
|
||
webhookData := WebhookPayload{
|
||
QAPairs: qaPairs,
|
||
}
|
||
|
||
jsonData, err := json.Marshal(webhookData)
|
||
if err != nil {
|
||
return fmt.Errorf("error marshaling webhook data: %w", err)
|
||
}
|
||
|
||
url := data.To.(string)
|
||
|
||
agent := w.client.Post(url)
|
||
agent.Set("Content-Type", "application/json").Body(jsonData)
|
||
|
||
statusCode, _, errs := agent.Bytes()
|
||
if len(errs) > 0 {
|
||
return fmt.Errorf("error send webhook request: %w", errors.Join(errs...))
|
||
}
|
||
|
||
if statusCode != fiber.StatusOK {
|
||
return fmt.Errorf("received an incorrect status code from webhook: %d", statusCode)
|
||
}
|
||
|
||
return nil
|
||
}
|
||
|
||
func (w *WebhookSender) Name() string {
|
||
return "webhook"
|
||
}
|