feat(dashboard-apps): align chatwoot payloads

This commit is contained in:
2026-06-06 13:03:16 +08:00
parent 11e5537f9b
commit 75f0e809a5
9 changed files with 312 additions and 71 deletions
+123 -28
View File
@@ -1,13 +1,18 @@
package v1
import (
"encoding/json"
"errors"
"net/http"
"time"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
"github.com/gochat/gochat/internal/model"
"github.com/gochat/gochat/internal/service"
applogger "github.com/gochat/gochat/pkg/logger"
"github.com/gochat/gochat/pkg/response"
pkgvalidator "github.com/gochat/gochat/pkg/validator"
)
// DashboardAppHandler handles DashboardApp CRUD endpoints.
@@ -21,6 +26,13 @@ type DashboardAppHandler struct {
svc *service.DashboardAppService
}
type dashboardAppPayload struct {
ID uint `json:"id"`
Title string `json:"title"`
Content json.RawMessage `json:"content"`
CreatedAt time.Time `json:"created_at"`
}
func NewDashboardAppHandler(svc *service.DashboardAppService) *DashboardAppHandler {
return &DashboardAppHandler{svc: svc}
}
@@ -37,26 +49,24 @@ func (h *DashboardAppHandler) Create(c *gin.Context) {
userID := getUserID(c)
userIDPtr := &userID
var wrapper service.DashboardAppCreateWrapper
if err := c.ShouldBindJSON(&wrapper); err != nil {
req, err := bindDashboardAppCreate(c)
if err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrValidation, err.Error())
return
}
req := wrapper.DashboardApp
if err := pkgvalidator.ValidateStruct(&req); err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrValidation, err.Error())
if req.Title == "" {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrValidation, "title is required")
return
}
app, err := h.svc.Create(c.Request.Context(), accountID, userIDPtr, &req)
app, err := h.svc.Create(c.Request.Context(), accountID, userIDPtr, req)
if err != nil {
applogger.L().Errorf("Create dashboard app: %v", err)
response.AbortWithStatusError(c, http.StatusInternalServerError, response.ErrInternal, "failed to create dashboard app")
response.AbortWithStatusError(c, http.StatusUnprocessableEntity, response.ErrValidation, err.Error())
return
}
response.Created(c, app)
c.JSON(http.StatusOK, serializeDashboardApp(app))
}
// Get retrieves a dashboard app by ID.
@@ -68,14 +78,20 @@ func (h *DashboardAppHandler) Get(c *gin.Context) {
return
}
app, err := h.svc.GetByID(c.Request.Context(), id)
accountID := getAccountID(c)
if accountID == 0 {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid account_id")
return
}
app, err := h.svc.GetByAccountAndID(c.Request.Context(), accountID, id)
if err != nil {
applogger.L().Errorf("Get dashboard app: %v", err)
response.AbortWithStatusError(c, http.StatusNotFound, response.ErrNotFound, "dashboard app not found")
return
}
response.OK(c, app)
c.JSON(http.StatusOK, serializeDashboardApp(app))
}
// Update modifies an existing dashboard app.
@@ -88,21 +104,26 @@ func (h *DashboardAppHandler) Update(c *gin.Context) {
return
}
var wrapper service.DashboardAppUpdateWrapper
if err := c.ShouldBindJSON(&wrapper); err != nil {
accountID := getAccountID(c)
if accountID == 0 {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid account_id")
return
}
req, err := bindDashboardAppUpdate(c)
if err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrValidation, err.Error())
return
}
req := wrapper.DashboardApp
app, err := h.svc.Update(c.Request.Context(), id, &req)
app, err := h.svc.UpdateByAccountAndID(c.Request.Context(), accountID, id, req)
if err != nil {
applogger.L().Errorf("Update dashboard app: %v", err)
response.AbortWithStatusError(c, http.StatusInternalServerError, response.ErrInternal, "failed to update dashboard app")
handleDashboardAppMutationError(c, err)
return
}
response.OK(c, app)
c.JSON(http.StatusOK, serializeDashboardApp(app))
}
// Delete removes a dashboard app.
@@ -115,8 +136,18 @@ func (h *DashboardAppHandler) Delete(c *gin.Context) {
return
}
if err := h.svc.Delete(c.Request.Context(), id); err != nil {
accountID := getAccountID(c)
if accountID == 0 {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid account_id")
return
}
if err := h.svc.DeleteByAccountAndID(c.Request.Context(), accountID, id); err != nil {
applogger.L().Errorf("Delete dashboard app: %v", err)
if errors.Is(err, gorm.ErrRecordNotFound) {
response.AbortWithStatusError(c, http.StatusNotFound, response.ErrNotFound, "dashboard app not found")
return
}
response.AbortWithStatusError(c, http.StatusInternalServerError, response.ErrInternal, "failed to delete dashboard app")
return
}
@@ -133,21 +164,26 @@ func (h *DashboardAppHandler) Patch(c *gin.Context) {
return
}
var wrapper service.DashboardAppUpdateWrapper
if err := c.ShouldBindJSON(&wrapper); err != nil {
accountID := getAccountID(c)
if accountID == 0 {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid account_id")
return
}
req, err := bindDashboardAppUpdate(c)
if err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrValidation, err.Error())
return
}
req := wrapper.DashboardApp
app, err := h.svc.Update(c.Request.Context(), id, &req)
app, err := h.svc.UpdateByAccountAndID(c.Request.Context(), accountID, id, req)
if err != nil {
applogger.L().Errorf("Patch dashboard app: %v", err)
response.AbortWithStatusError(c, http.StatusInternalServerError, response.ErrInternal, "failed to update dashboard app")
handleDashboardAppMutationError(c, err)
return
}
response.OK(c, app)
c.JSON(http.StatusOK, serializeDashboardApp(app))
}
// List returns all dashboard apps for an account.
@@ -167,8 +203,67 @@ func (h *DashboardAppHandler) List(c *gin.Context) {
return
}
// Chatwoot returns a pure JSON array (no meta/pagination wrapper)
c.JSON(http.StatusOK, apps)
payload := make([]dashboardAppPayload, 0, len(apps))
for i := range apps {
payload = append(payload, serializeDashboardApp(&apps[i]))
}
c.JSON(http.StatusOK, payload)
}
func bindDashboardAppCreate(c *gin.Context) (*service.CreateDashboardAppRequest, error) {
var raw map[string]json.RawMessage
if err := c.ShouldBindJSON(&raw); err != nil {
return nil, err
}
if nested, ok := raw["dashboard_app"]; ok {
var req service.CreateDashboardAppRequest
if err := json.Unmarshal(nested, &req); err != nil {
return nil, err
}
return &req, nil
}
body, _ := json.Marshal(raw)
var req service.CreateDashboardAppRequest
if err := json.Unmarshal(body, &req); err != nil {
return nil, err
}
return &req, nil
}
func bindDashboardAppUpdate(c *gin.Context) (*service.UpdateDashboardAppRequest, error) {
var raw map[string]json.RawMessage
if err := c.ShouldBindJSON(&raw); err != nil {
return nil, err
}
if nested, ok := raw["dashboard_app"]; ok {
var req service.UpdateDashboardAppRequest
if err := json.Unmarshal(nested, &req); err != nil {
return nil, err
}
return &req, nil
}
body, _ := json.Marshal(raw)
var req service.UpdateDashboardAppRequest
if err := json.Unmarshal(body, &req); err != nil {
return nil, err
}
return &req, nil
}
func serializeDashboardApp(app *model.DashboardApp) dashboardAppPayload {
content := app.Content
if len(content) == 0 {
content = json.RawMessage(`[]`)
}
return dashboardAppPayload{ID: app.ID, Title: app.Title, Content: content, CreatedAt: app.CreatedAt}
}
func handleDashboardAppMutationError(c *gin.Context, err error) {
if errors.Is(err, gorm.ErrRecordNotFound) {
response.AbortWithStatusError(c, http.StatusNotFound, response.ErrNotFound, "dashboard app not found")
return
}
response.AbortWithStatusError(c, http.StatusUnprocessableEntity, response.ErrValidation, err.Error())
}
// ========== GoChat Extension Endpoints (not in Chatwoot) ==========
@@ -297,4 +392,4 @@ func (h *DashboardAppHandler) UpdateWidget(c *gin.Context) {
}
response.OK(c, widgets)
}
}
@@ -117,14 +117,22 @@ func (s *DashboardAppHandlerTestSuite) TestCreate_Success() {
c.Next()
}, s.handler.Create)
// Chatwoot requires nested {dashboard_app: {title: "...", content: [...]}}
body := `{"dashboard_app": {"title": "Test Dashboard App", "content": [{"type": "frame", "url": "https://example.com/widget"}]}}`
// The reused Chatwoot frontend sends a raw payload; Rails wraps it into
// dashboard_app server-side, so GoChat accepts both shapes.
body := `{"title": "Test Dashboard App", "content": [{"type": "frame", "url": "https://example.com/widget"}]}`
w := httptest.NewRecorder()
req, _ := http.NewRequest("POST", fmt.Sprintf("/api/v1/accounts/%d/dashboard_apps", s.account.ID), bytes.NewBufferString(body))
req.Header.Set("Content-Type", "application/json")
r.ServeHTTP(w, req)
assert.Equal(s.T(), http.StatusCreated, w.Code)
assert.Equal(s.T(), http.StatusOK, w.Code)
var payload map[string]any
s.Require().NoError(json.Unmarshal(w.Body.Bytes(), &payload))
assert.NotContains(s.T(), payload, "success")
assert.NotContains(s.T(), payload, "data")
assert.Equal(s.T(), "Test Dashboard App", payload["title"])
assert.NotContains(s.T(), payload, "account_id")
assert.NotContains(s.T(), payload, "updated_at")
}
func (s *DashboardAppHandlerTestSuite) TestGet_Success() {
@@ -144,6 +152,42 @@ func (s *DashboardAppHandlerTestSuite) TestGet_Success() {
s.T().Logf("Get response: status=%d, body=%s", w.Code, w.Body.String())
assert.Equal(s.T(), http.StatusOK, w.Code)
var payload map[string]any
s.Require().NoError(json.Unmarshal(w.Body.Bytes(), &payload))
assert.NotContains(s.T(), payload, "success")
assert.NotContains(s.T(), payload, "data")
assert.Equal(s.T(), "Seed App", payload["title"])
assert.Contains(s.T(), payload, "created_at")
assert.NotContains(s.T(), payload, "account_id")
}
func (s *DashboardAppHandlerTestSuite) TestPatch_RawPayloadAndAccountScope() {
r := gin.New()
r.PATCH("/api/v1/accounts/:account_id/dashboard_apps/:dashboard_app_id", s.handler.Patch)
seedApp, err := s.handler.svc.Create(context.Background(), s.account.ID, &s.user.ID, &service.CreateDashboardAppRequest{
Title: "Before",
Content: json.RawMessage(`[{"type":"frame","url":"https://example.com/before"}]`),
})
s.Require().NoError(err)
body := `{"title":"After","content":[{"type":"frame","url":"https://example.com/after"}]}`
w := httptest.NewRecorder()
req, _ := http.NewRequest("PATCH", fmt.Sprintf("/api/v1/accounts/%d/dashboard_apps/%d", s.account.ID, seedApp.ID), bytes.NewBufferString(body))
req.Header.Set("Content-Type", "application/json")
r.ServeHTTP(w, req)
assert.Equal(s.T(), http.StatusOK, w.Code)
var payload map[string]any
s.Require().NoError(json.Unmarshal(w.Body.Bytes(), &payload))
assert.Equal(s.T(), "After", payload["title"])
assert.NotContains(s.T(), payload, "success")
w = httptest.NewRecorder()
req, _ = http.NewRequest("PATCH", fmt.Sprintf("/api/v1/accounts/%d/dashboard_apps/%d", s.account.ID+100, seedApp.ID), bytes.NewBufferString(body))
req.Header.Set("Content-Type", "application/json")
r.ServeHTTP(w, req)
assert.Equal(s.T(), http.StatusNotFound, w.Code)
}
func (s *DashboardAppHandlerTestSuite) TestDelete_Success() {
@@ -162,4 +206,4 @@ func (s *DashboardAppHandlerTestSuite) TestDelete_Success() {
// Chatwoot: head :no_content → 204
assert.Equal(s.T(), http.StatusNoContent, w.Code)
}
}
+26 -21
View File
@@ -3,6 +3,7 @@ package model
import (
"encoding/json"
"fmt"
"strings"
"time"
"gorm.io/gorm"
@@ -16,25 +17,26 @@ import (
// account and optionally to a specific user (personal dashboards).
//
// Content format: JSON array of iframe configurations, e.g.:
// [{"type": "frame", "url": "https://example.com/widget"}]
//
// [{"type": "frame", "url": "https://example.com/widget"}]
//
// Validation rules (per Chatwoot):
// - content must be a JSON array (empty array allowed)
// - content must be a JSON array with at least one widget
// - each element must have type="frame" and url (http/https URI)
type DashboardApp struct {
ID uint `gorm:"primaryKey;autoIncrement" json:"id"`
AccountID uint `gorm:"not null;index" json:"account_id"`
UserID *uint `gorm:"index" json:"user_id,omitempty"` // optional: per-user dashboard
Title string `gorm:"size:255;not null" json:"title"`
Description string `gorm:"type:text" json:"description,omitempty"`
Icon string `gorm:"size:255" json:"icon,omitempty"` // icon URL or icon name
URL string `gorm:"size:512" json:"url,omitempty"` // primary iframe URL
Kind string `gorm:"size:100;default:'frame'" json:"kind"` // frame, link
ID uint `gorm:"primaryKey;autoIncrement" json:"id"`
AccountID uint `gorm:"not null;index" json:"account_id"`
UserID *uint `gorm:"index" json:"user_id,omitempty"` // optional: per-user dashboard
Title string `gorm:"size:255;not null" json:"title"`
Description string `gorm:"type:text" json:"description,omitempty"`
Icon string `gorm:"size:255" json:"icon,omitempty"` // icon URL or icon name
URL string `gorm:"size:512" json:"url,omitempty"` // primary iframe URL
Kind string `gorm:"size:100;default:'frame'" json:"kind"` // frame, link
Content json.RawMessage `gorm:"type:json;serializer:json;default:'[]'" json:"content"` // iframe config array
Active *bool `gorm:"default:true;not null" json:"active"`
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updated_at"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"deleted_at,omitempty"`
Active *bool `gorm:"default:true;not null" json:"active"`
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updated_at"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"deleted_at,omitempty"`
// Relations
Account *Account `gorm:"foreignKey:AccountID" json:"account,omitempty"`
@@ -52,9 +54,9 @@ func BoolPtr(b bool) *bool { return &b }
// This is an in-memory structure used for widget CRUD — not a separate DB table.
// Widgets are stored as elements in the DashboardApp.Content jsonb array.
type DashboardWidget struct {
Type string `json:"type"` // must be "frame"
URL string `json:"url"` // must be http/https URI
ID string `json:"id,omitempty"` // optional client-assigned widget ID
Type string `json:"type"` // must be "frame"
URL string `json:"url"` // must be http/https URI
ID string `json:"id,omitempty"` // optional client-assigned widget ID
Name string `json:"name,omitempty"` // optional widget display name
}
@@ -65,19 +67,22 @@ type DashboardWidget struct {
// - each element must have type="frame" and url (http/https URI)
func ValidateContent(content json.RawMessage) error {
if len(content) == 0 || string(content) == "" {
return nil // empty content is OK (will be stored as [])
return fmt.Errorf("content must be a JSON array")
}
var widgets []DashboardWidget
if err := json.Unmarshal(content, &widgets); err != nil {
return fmt.Errorf("content must be a JSON array: %w", err)
}
if len(widgets) == 0 {
return fmt.Errorf("content must contain at least one widget")
}
for i, w := range widgets {
if w.Type != "" && w.Type != "frame" {
if w.Type != "frame" {
return fmt.Errorf("widget[%d].type must be 'frame', got '%s'", i, w.Type)
}
if w.URL != "" && !IsValidHTTPURL(w.URL) {
if strings.TrimSpace(w.URL) == "" || !IsValidHTTPURL(w.URL) {
return fmt.Errorf("widget[%d].url must be http/https URI, got '%s'", i, w.URL)
}
}
@@ -87,4 +92,4 @@ func ValidateContent(content json.RawMessage) error {
// IsValidHTTPURL checks if a URL uses http or https scheme.
func IsValidHTTPURL(u string) bool {
return (len(u) >= 7 && u[:7] == "http://") || (len(u) >= 8 && u[:8] == "https://")
}
}
+13 -1
View File
@@ -28,6 +28,14 @@ func (r *DashboardAppRepo) GetByID(ctx context.Context, id uint) (*model.Dashboa
return &app, nil
}
func (r *DashboardAppRepo) GetByAccountAndID(ctx context.Context, accountID, id uint) (*model.DashboardApp, error) {
var app model.DashboardApp
if err := r.db.WithContext(ctx).Where("account_id = ? AND id = ?", accountID, id).First(&app).Error; err != nil {
return nil, err
}
return &app, nil
}
func (r *DashboardAppRepo) Update(ctx context.Context, app *model.DashboardApp) error {
return r.db.WithContext(ctx).Save(app).Error
}
@@ -36,6 +44,10 @@ func (r *DashboardAppRepo) Delete(ctx context.Context, id uint) error {
return r.db.WithContext(ctx).Delete(&model.DashboardApp{}, id).Error
}
func (r *DashboardAppRepo) DeleteByAccountAndID(ctx context.Context, accountID, id uint) error {
return r.db.WithContext(ctx).Where("account_id = ? AND id = ?", accountID, id).Delete(&model.DashboardApp{}).Error
}
// FindAllByAccountID returns all dashboard apps for an account (no pagination).
// Chatwoot: Current.account.dashboard_apps — returns all without limit/offset
func (r *DashboardAppRepo) FindAllByAccountID(ctx context.Context, accountID uint) ([]model.DashboardApp, error) {
@@ -105,4 +117,4 @@ func (r *DashboardAppRepo) FindAllActiveByAccountID(ctx context.Context, account
return nil, err
}
return apps, nil
}
}
+70 -2
View File
@@ -5,6 +5,7 @@ import (
"encoding/json"
"errors"
"fmt"
"strings"
"github.com/gochat/gochat/internal/model"
"github.com/gochat/gochat/internal/repository"
@@ -89,7 +90,7 @@ func (s *DashboardAppService) Create(ctx context.Context, accountID uint, userID
URL: req.URL,
Kind: kind,
Content: content,
Active: active,
Active: active,
}
if err := s.repo.Create(ctx, app); err != nil {
applogger.L().Errorf("Create dashboard app: %v", err)
@@ -107,6 +108,15 @@ func (s *DashboardAppService) GetByID(ctx context.Context, id uint) (*model.Dash
return app, nil
}
func (s *DashboardAppService) GetByAccountAndID(ctx context.Context, accountID, id uint) (*model.DashboardApp, error) {
app, err := s.repo.GetByAccountAndID(ctx, accountID, id)
if err != nil {
applogger.L().Errorf("Get dashboard app: %v", err)
return nil, err
}
return app, nil
}
func (s *DashboardAppService) Update(ctx context.Context, id uint, req *UpdateDashboardAppRequest) (*model.DashboardApp, error) {
app, err := s.repo.GetByID(ctx, id)
if err != nil {
@@ -150,6 +160,48 @@ func (s *DashboardAppService) Update(ctx context.Context, id uint, req *UpdateDa
return app, nil
}
func (s *DashboardAppService) UpdateByAccountAndID(ctx context.Context, accountID, id uint, req *UpdateDashboardAppRequest) (*model.DashboardApp, error) {
app, err := s.repo.GetByAccountAndID(ctx, accountID, id)
if err != nil {
applogger.L().Errorf("Get dashboard app for update: %v", err)
return nil, err
}
if len(req.Content) > 0 && string(req.Content) != "" {
if err := model.ValidateContent(req.Content); err != nil {
return nil, err
}
}
if strings.TrimSpace(req.Title) != "" {
app.Title = req.Title
}
if req.Description != "" {
app.Description = req.Description
}
if req.Icon != "" {
app.Icon = req.Icon
}
if req.URL != "" {
app.URL = req.URL
}
if req.Kind != "" {
app.Kind = req.Kind
}
if len(req.Content) > 0 && string(req.Content) != "" {
app.Content = req.Content
}
if req.Active != nil {
app.Active = req.Active
}
if err := s.repo.Update(ctx, app); err != nil {
applogger.L().Errorf("Update dashboard app: %v", err)
return nil, err
}
return app, nil
}
func (s *DashboardAppService) Delete(ctx context.Context, id uint) error {
app, err := s.repo.GetByID(ctx, id)
if err != nil {
@@ -166,6 +218,22 @@ func (s *DashboardAppService) Delete(ctx context.Context, id uint) error {
return nil
}
func (s *DashboardAppService) DeleteByAccountAndID(ctx context.Context, accountID, id uint) error {
app, err := s.repo.GetByAccountAndID(ctx, accountID, id)
if err != nil {
applogger.L().Errorf("Delete dashboard app: find failed: %v", err)
return err
}
if app == nil {
return fmt.Errorf("dashboard app not found")
}
if err := s.repo.DeleteByAccountAndID(ctx, accountID, id); err != nil {
applogger.L().Errorf("Delete dashboard app: %v", err)
return err
}
return nil
}
// ListByAccount returns all dashboard apps for an account.
// Chatwoot: Current.account.dashboard_apps — no pagination
func (s *DashboardAppService) ListByAccount(ctx context.Context, accountID uint) ([]model.DashboardApp, error) {
@@ -381,4 +449,4 @@ func (s *DashboardAppService) GetWidgets(ctx context.Context, dashboardAppID uin
}
}
return widgets, nil
}
}
@@ -64,9 +64,9 @@ func TestDashboardAppService_Create_空Content(t *testing.T) {
}
app, err := svc.Create(context.Background(), account.ID, nil, req)
require.NoError(t, err)
assert.NotZero(t, app.ID)
assert.Equal(t, json.RawMessage("[]"), app.Content)
assert.Error(t, err)
assert.Nil(t, app)
assert.Contains(t, err.Error(), "at least one widget")
}
func TestDashboardAppService_Create_无效Content非数组(t *testing.T) {
@@ -482,4 +482,4 @@ func TestDashboardAppService_UpdateWidget_不存在App(t *testing.T) {
app, err := svc.UpdateWidget(context.Background(), 99999, 0, req)
assert.Error(t, err)
assert.Nil(t, app)
}
}