refactor backend packages and global db service

This commit is contained in:
2026-07-18 21:58:15 +08:00
parent 62bd3d0455
commit 7800b07d42
51 changed files with 719 additions and 647 deletions

View File

@@ -0,0 +1,78 @@
package projects
import (
"net/http"
"strconv"
"github.com/gin-gonic/gin"
"senlinai-agent/backend/internal/logic/auth"
)
type Handler struct {
service *Service
}
func NewHandler(service *Service) *Handler {
return &Handler{service: service}
}
func (h *Handler) Register(router gin.IRouter) {
router.POST("/projects", h.createProject)
router.GET("/projects", h.listProjects)
router.GET("/projects/:id/dashboard", h.dashboard)
}
func (h *Handler) createProject(c *gin.Context) {
userID, ok := auth.CurrentUserID(c)
if !ok {
c.JSON(http.StatusUnauthorized, gin.H{"error": "missing current user"})
return
}
var input struct {
Name string `json:"name"`
Description string `json:"description"`
}
if err := c.ShouldBindJSON(&input); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request"})
return
}
project, err := h.service.CreateProject(userID, input.Name, input.Description)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusCreated, project)
}
func (h *Handler) listProjects(c *gin.Context) {
userID, ok := auth.CurrentUserID(c)
if !ok {
c.JSON(http.StatusUnauthorized, gin.H{"error": "missing current user"})
return
}
projects, err := h.service.ListProjects(userID)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to list projects"})
return
}
c.JSON(http.StatusOK, projects)
}
func (h *Handler) dashboard(c *gin.Context) {
userID, ok := auth.CurrentUserID(c)
if !ok {
c.JSON(http.StatusUnauthorized, gin.H{"error": "missing current user"})
return
}
projectID, err := strconv.ParseUint(c.Param("id"), 10, 64)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid project id"})
return
}
dashboard, err := h.service.Dashboard(userID, uint(projectID))
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to load dashboard"})
return
}
c.JSON(http.StatusOK, dashboard)
}

View File

@@ -0,0 +1,74 @@
package projects
import (
"errors"
"strings"
"senlinai-agent/backend/internal/models"
)
type Service struct {
}
type Dashboard struct {
ProjectID uint `json:"project_id"`
PendingInboxCount int64 `json:"pending_inbox_count"`
OpenTaskCount int64 `json:"open_task_count"`
RecentNoteCount int64 `json:"recent_note_count"`
RecentSessionCount int64 `json:"recent_session_count"`
}
func NewService() *Service {
return &Service{}
}
func (s *Service) CreateProject(ownerID uint, name string, description string) (*models.SenlinAgentProject, error) {
name = strings.TrimSpace(name)
if name == "" {
return nil, errors.New("project name is required")
}
project := &models.SenlinAgentProject{OwnerID: ownerID, Name: name, Description: description}
return project, models.DBService.Create(project).Error
}
func (s *Service) ListProjects(ownerID uint) ([]models.SenlinAgentProject, error) {
var projects []models.SenlinAgentProject
err := models.DBService.Where("owner_id = ?", ownerID).Order("updated_at desc").Find(&projects).Error
return projects, err
}
func (s *Service) CreateTag(projectID uint, name string) (*models.SenlinAgentTag, error) {
name = strings.TrimSpace(name)
if name == "" {
return nil, errors.New("tag name is required")
}
tag := &models.SenlinAgentTag{ProjectID: projectID, Name: name}
return tag, models.DBService.Create(tag).Error
}
func (s *Service) ListTags(projectID uint) ([]models.SenlinAgentTag, error) {
var tags []models.SenlinAgentTag
err := models.DBService.Where("project_id = ?", projectID).Order("name asc").Find(&tags).Error
return tags, err
}
func (s *Service) Dashboard(ownerID uint, projectID uint) (Dashboard, error) {
var project models.SenlinAgentProject
if err := models.DBService.Where("id = ? AND owner_id = ?", projectID, ownerID).First(&project).Error; err != nil {
return Dashboard{}, err
}
dashboard := Dashboard{ProjectID: projectID}
if err := models.DBService.Model(&models.SenlinAgentInboxItem{}).Where("project_id = ? AND status = ?", projectID, "open").Count(&dashboard.PendingInboxCount).Error; err != nil {
return dashboard, err
}
if err := models.DBService.Model(&models.SenlinAgentTask{}).Where("project_id = ? AND status <> ?", projectID, "done").Count(&dashboard.OpenTaskCount).Error; err != nil {
return dashboard, err
}
if err := models.DBService.Model(&models.SenlinAgentNote{}).Where("project_id = ?", projectID).Count(&dashboard.RecentNoteCount).Error; err != nil {
return dashboard, err
}
if err := models.DBService.Model(&models.SenlinAgentAISession{}).Where("project_id = ?", projectID).Count(&dashboard.RecentSessionCount).Error; err != nil {
return dashboard, err
}
return dashboard, nil
}

View File

@@ -0,0 +1,69 @@
package projects
import (
"fmt"
"testing"
"github.com/glebarez/sqlite"
"github.com/stretchr/testify/require"
"gorm.io/gorm"
"senlinai-agent/backend/internal/models"
)
func TestProjectTagsAreScopedToProject(t *testing.T) {
newTestDB(t)
service := NewService()
first, err := service.CreateProject(1, "Alpha", "")
require.NoError(t, err)
second, err := service.CreateProject(1, "Beta", "")
require.NoError(t, err)
_, err = service.CreateTag(first.ID, "重要")
require.NoError(t, err)
_, err = service.CreateTag(second.ID, "重要")
require.NoError(t, err)
firstTags, err := service.ListTags(first.ID)
require.NoError(t, err)
require.Len(t, firstTags, 1)
require.Equal(t, first.ID, firstTags[0].ProjectID)
}
func TestDashboardCountsOnlyRequestedProject(t *testing.T) {
database := newTestDB(t)
service := NewService()
first, err := service.CreateProject(1, "Alpha", "")
require.NoError(t, err)
second, err := service.CreateProject(1, "Beta", "")
require.NoError(t, err)
require.NoError(t, database.Create(&models.SenlinAgentInboxItem{ProjectID: first.ID, CreatedBy: 1, SourceType: "text", Status: "open"}).Error)
require.NoError(t, database.Create(&models.SenlinAgentInboxItem{ProjectID: second.ID, CreatedBy: 1, SourceType: "text", Status: "open"}).Error)
require.NoError(t, database.Create(&models.SenlinAgentTask{ProjectID: first.ID, CreatedBy: 1, Title: "A", Status: "open"}).Error)
require.NoError(t, database.Create(&models.SenlinAgentTask{ProjectID: second.ID, CreatedBy: 1, Title: "B", Status: "open"}).Error)
dashboard, err := service.Dashboard(1, first.ID)
require.NoError(t, err)
require.Equal(t, int64(1), dashboard.PendingInboxCount)
require.Equal(t, int64(1), dashboard.OpenTaskCount)
}
func TestDashboardRejectsProjectOwnedByAnotherUser(t *testing.T) {
newTestDB(t)
service := NewService()
project, err := service.CreateProject(2, "Beta", "")
require.NoError(t, err)
_, err = service.Dashboard(1, project.ID)
require.Error(t, err)
}
func newTestDB(t *testing.T) *gorm.DB {
t.Helper()
database, err := gorm.Open(sqlite.Open(fmt.Sprintf("file:%s?mode=memory&cache=shared", t.Name())), &gorm.Config{})
require.NoError(t, err)
require.NoError(t, models.AutoMigrate(database))
models.DBService = database
return database
}