72 lines
2.0 KiB
Go
72 lines
2.0 KiB
Go
package telegram
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
type Handler struct {
|
|
service *Service
|
|
}
|
|
|
|
func NewHandler(service *Service) *Handler {
|
|
return &Handler{service: service}
|
|
}
|
|
|
|
// settingsResponse never includes the raw bot token (spec section 32: secrets
|
|
// must never be exposed to the frontend) -- only whether one is configured.
|
|
type settingsResponse struct {
|
|
Enabled bool `json:"enabled"`
|
|
BotTokenConfigured bool `json:"bot_token_configured"`
|
|
ChatID string `json:"chat_id"`
|
|
NotifyNewOrder bool `json:"notify_new_order"`
|
|
}
|
|
|
|
func toResponse(s *Settings) settingsResponse {
|
|
return settingsResponse{
|
|
Enabled: s.Enabled,
|
|
BotTokenConfigured: s.BotToken != "",
|
|
ChatID: s.ChatID,
|
|
NotifyNewOrder: s.NotifyNewOrder,
|
|
}
|
|
}
|
|
|
|
func (h *Handler) Get(c *gin.Context) {
|
|
settings, err := h.service.Get(c.Request.Context())
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to load telegram settings"})
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, toResponse(settings))
|
|
}
|
|
|
|
type updateRequest struct {
|
|
Enabled bool `json:"enabled"`
|
|
BotToken string `json:"bot_token"`
|
|
ChatID string `json:"chat_id" binding:"required_if=Enabled true"`
|
|
NotifyNewOrder bool `json:"notify_new_order"`
|
|
}
|
|
|
|
func (h *Handler) Update(c *gin.Context) {
|
|
var req updateRequest
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "validation error", "details": err.Error()})
|
|
return
|
|
}
|
|
settings, err := h.service.Update(c.Request.Context(), req.Enabled, req.BotToken, req.ChatID, req.NotifyNewOrder)
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to update telegram settings"})
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, toResponse(settings))
|
|
}
|
|
|
|
func (h *Handler) Test(c *gin.Context) {
|
|
if err := h.service.SendTestMessage(c.Request.Context()); err != nil {
|
|
c.JSON(http.StatusBadGateway, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, gin.H{"message": "test notification sent"})
|
|
}
|