chore(init): 初始化解忧商行项目并完成 Phase 0 基座
This commit is contained in:
@@ -0,0 +1,62 @@
|
||||
package announcement
|
||||
|
||||
import "time"
|
||||
|
||||
type AnnouncementDTO struct {
|
||||
ID uint64 `json:"id"`
|
||||
DistributionSiteID uint64 `json:"distribution_site_id"`
|
||||
DistributionSiteName string `json:"distribution_site_name,omitempty"`
|
||||
Title string `json:"title"`
|
||||
Content string `json:"content"`
|
||||
Category string `json:"category"`
|
||||
Priority int `json:"priority"`
|
||||
IsPinned bool `json:"is_pinned"`
|
||||
IsImportant bool `json:"is_important"`
|
||||
IsPopup bool `json:"is_popup"`
|
||||
ViewCount int `json:"view_count"`
|
||||
Status string `json:"status"`
|
||||
PublishedAt *time.Time `json:"published_at"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
type AnnouncementListQuery struct {
|
||||
Category string
|
||||
Status string
|
||||
Page int
|
||||
PageSize int
|
||||
// AllowedSiteIDs 前台可见范围:主站=[0];分站 inherit=[0, siteID];分站 own_only=[siteID]。
|
||||
AllowedSiteIDs []uint64
|
||||
// AdminSiteID 管理端按站点筛选:nil=全部,0=仅主站,>0=指定分站。
|
||||
AdminSiteID *uint64
|
||||
}
|
||||
|
||||
type PaginatedResult struct {
|
||||
Items interface{} `json:"items"`
|
||||
Total int64 `json:"total"`
|
||||
Page int `json:"page"`
|
||||
PageSize int `json:"page_size"`
|
||||
}
|
||||
|
||||
type CreateAnnouncementRequest struct {
|
||||
// DistributionSiteID 归属站点,0=主站(平台后台可指定分站代发)。
|
||||
DistributionSiteID uint64 `json:"distribution_site_id"`
|
||||
Title string `json:"title" binding:"required,max=255"`
|
||||
Content string `json:"content" binding:"required"`
|
||||
Category string `json:"category" binding:"required,oneof=notice tutorial rule faq"`
|
||||
Priority int `json:"priority"`
|
||||
IsPinned bool `json:"is_pinned"`
|
||||
IsImportant bool `json:"is_important"`
|
||||
// IsPopup 弹窗公告:前台首页弹出且需用户手动关闭,同一天只弹一次。
|
||||
IsPopup bool `json:"is_popup"`
|
||||
}
|
||||
|
||||
type UpdateAnnouncementRequest struct {
|
||||
Title string `json:"title" binding:"max=255"`
|
||||
Content string `json:"content"`
|
||||
Category string `json:"category" binding:"omitempty,oneof=notice tutorial rule faq"`
|
||||
Priority int `json:"priority"`
|
||||
IsPinned bool `json:"is_pinned"`
|
||||
IsImportant bool `json:"is_important"`
|
||||
IsPopup bool `json:"is_popup"`
|
||||
}
|
||||
@@ -0,0 +1,292 @@
|
||||
package announcement
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"hfb_sys/backend/internal/middleware"
|
||||
"hfb_sys/backend/internal/sitecode"
|
||||
"hfb_sys/backend/pkg/response"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
service *Service
|
||||
}
|
||||
|
||||
func NewHandler(service *Service) *Handler {
|
||||
return &Handler{service: service}
|
||||
}
|
||||
|
||||
// List 获取公告列表(前台用户,按当前站点隔离)
|
||||
func (h *Handler) List(c *gin.Context) {
|
||||
query := AnnouncementListQuery{
|
||||
Category: c.Query("category"),
|
||||
Status: "published",
|
||||
}
|
||||
query.Page, query.PageSize = parsePagination(c)
|
||||
|
||||
siteIDs, err := h.service.ResolvePublicSiteScope(c.Request.Context(), sitecode.FromRequest(c))
|
||||
if err != nil {
|
||||
response.RecordError(c, err)
|
||||
response.InternalServerError(c, "获取公告列表失败")
|
||||
return
|
||||
}
|
||||
query.AllowedSiteIDs = siteIDs
|
||||
|
||||
result, err := h.service.List(c.Request.Context(), query)
|
||||
if err != nil {
|
||||
response.RecordError(c, err)
|
||||
response.InternalServerError(c, "获取公告列表失败")
|
||||
return
|
||||
}
|
||||
|
||||
response.OK(c, result)
|
||||
}
|
||||
|
||||
// Popup 获取前台首页要弹出的弹窗公告(按当前站点隔离;无可弹公告时 data 为 null)
|
||||
func (h *Handler) Popup(c *gin.Context) {
|
||||
siteIDs, err := h.service.ResolvePublicSiteScope(c.Request.Context(), sitecode.FromRequest(c))
|
||||
if err != nil {
|
||||
response.RecordError(c, err)
|
||||
response.InternalServerError(c, "获取弹窗公告失败")
|
||||
return
|
||||
}
|
||||
|
||||
announcement, err := h.service.PublicPopup(c.Request.Context(), siteIDs)
|
||||
if err != nil {
|
||||
response.RecordError(c, err)
|
||||
response.InternalServerError(c, "获取弹窗公告失败")
|
||||
return
|
||||
}
|
||||
|
||||
response.OK(c, announcement)
|
||||
}
|
||||
|
||||
// GetByID 获取公告详情(限当前站点可见范围)
|
||||
func (h *Handler) GetByID(c *gin.Context) {
|
||||
id, err := parseID(c)
|
||||
if err != nil {
|
||||
response.BadRequest(c, "公告ID不正确")
|
||||
return
|
||||
}
|
||||
|
||||
siteIDs, err := h.service.ResolvePublicSiteScope(c.Request.Context(), sitecode.FromRequest(c))
|
||||
if err != nil {
|
||||
response.InternalServerError(c, "获取公告失败")
|
||||
return
|
||||
}
|
||||
|
||||
announcement, err := h.service.GetByID(c.Request.Context(), id, siteIDs)
|
||||
if err != nil {
|
||||
if errors.Is(err, ErrNotFound) {
|
||||
response.NotFound(c, "公告不存在")
|
||||
return
|
||||
}
|
||||
response.InternalServerError(c, "获取公告失败")
|
||||
return
|
||||
}
|
||||
|
||||
response.OK(c, announcement)
|
||||
}
|
||||
|
||||
// AdminList 管理员获取公告列表(site_id 可选:不传=全部,0=主站,>0=指定分站)
|
||||
func (h *Handler) AdminList(c *gin.Context) {
|
||||
query := AnnouncementListQuery{
|
||||
Category: c.Query("category"),
|
||||
Status: c.Query("status"),
|
||||
}
|
||||
query.Page, query.PageSize = parsePagination(c)
|
||||
if raw, ok := c.GetQuery("site_id"); ok {
|
||||
siteID, err := strconv.ParseUint(strings.TrimSpace(raw), 10, 64)
|
||||
if err != nil {
|
||||
response.BadRequest(c, "站点ID不正确")
|
||||
return
|
||||
}
|
||||
query.AdminSiteID = &siteID
|
||||
}
|
||||
|
||||
result, err := h.service.AdminList(c.Request.Context(), query)
|
||||
if err != nil {
|
||||
response.RecordError(c, err)
|
||||
response.InternalServerError(c, "获取公告列表失败")
|
||||
return
|
||||
}
|
||||
|
||||
response.OK(c, result)
|
||||
}
|
||||
|
||||
// AdminGetByID 管理员获取公告详情
|
||||
func (h *Handler) AdminGetByID(c *gin.Context) {
|
||||
id, err := parseID(c)
|
||||
if err != nil {
|
||||
response.BadRequest(c, "公告ID不正确")
|
||||
return
|
||||
}
|
||||
|
||||
announcement, err := h.service.AdminGetByID(c.Request.Context(), id)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
response.NotFound(c, "公告不存在")
|
||||
return
|
||||
}
|
||||
response.InternalServerError(c, "获取公告失败")
|
||||
return
|
||||
}
|
||||
|
||||
response.OK(c, announcement)
|
||||
}
|
||||
|
||||
// Create 创建公告
|
||||
func (h *Handler) Create(c *gin.Context) {
|
||||
adminID, ok := currentAdminID(c)
|
||||
if !ok {
|
||||
response.Unauthorized(c, "未授权")
|
||||
return
|
||||
}
|
||||
|
||||
var req CreateAnnouncementRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
response.BadRequest(c, "请求参数不正确")
|
||||
return
|
||||
}
|
||||
|
||||
announcement, err := h.service.Create(c.Request.Context(), req, adminID)
|
||||
if err != nil {
|
||||
response.RecordError(c, err)
|
||||
response.InternalServerError(c, "创建公告失败")
|
||||
return
|
||||
}
|
||||
|
||||
response.OK(c, announcement)
|
||||
}
|
||||
|
||||
// Update 更新公告
|
||||
func (h *Handler) Update(c *gin.Context) {
|
||||
id, err := parseID(c)
|
||||
if err != nil {
|
||||
response.BadRequest(c, "公告ID不正确")
|
||||
return
|
||||
}
|
||||
|
||||
var req UpdateAnnouncementRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
response.BadRequest(c, "请求参数不正确")
|
||||
return
|
||||
}
|
||||
|
||||
announcement, err := h.service.Update(c.Request.Context(), id, req)
|
||||
if err != nil {
|
||||
response.RecordError(c, err)
|
||||
response.InternalServerError(c, "更新公告失败")
|
||||
return
|
||||
}
|
||||
|
||||
response.OK(c, announcement)
|
||||
}
|
||||
|
||||
// Publish 发布公告
|
||||
func (h *Handler) Publish(c *gin.Context) {
|
||||
id, err := parseID(c)
|
||||
if err != nil {
|
||||
response.BadRequest(c, "公告ID不正确")
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.service.Publish(c.Request.Context(), id); err != nil {
|
||||
response.RecordError(c, err)
|
||||
response.InternalServerError(c, "发布公告失败")
|
||||
return
|
||||
}
|
||||
|
||||
response.OK(c, gin.H{"message": "发布成功"})
|
||||
}
|
||||
|
||||
// Archive 归档公告
|
||||
func (h *Handler) Archive(c *gin.Context) {
|
||||
id, err := parseID(c)
|
||||
if err != nil {
|
||||
response.BadRequest(c, "公告ID不正确")
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.service.Archive(c.Request.Context(), id); err != nil {
|
||||
response.RecordError(c, err)
|
||||
response.InternalServerError(c, "归档公告失败")
|
||||
return
|
||||
}
|
||||
|
||||
response.OK(c, gin.H{"message": "归档成功"})
|
||||
}
|
||||
|
||||
// Unarchive 取消归档公告
|
||||
func (h *Handler) Unarchive(c *gin.Context) {
|
||||
id, err := parseID(c)
|
||||
if err != nil {
|
||||
response.BadRequest(c, "公告ID不正确")
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.service.Unarchive(c.Request.Context(), id); err != nil {
|
||||
response.RecordError(c, err)
|
||||
response.InternalServerError(c, "取消归档公告失败")
|
||||
return
|
||||
}
|
||||
|
||||
response.OK(c, gin.H{"message": "取消归档成功"})
|
||||
}
|
||||
|
||||
// Delete 删除公告
|
||||
func (h *Handler) Delete(c *gin.Context) {
|
||||
id, err := parseID(c)
|
||||
if err != nil {
|
||||
response.BadRequest(c, "公告ID不正确")
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.service.Delete(c.Request.Context(), id); err != nil {
|
||||
response.RecordError(c, err)
|
||||
response.InternalServerError(c, "删除公告失败")
|
||||
return
|
||||
}
|
||||
|
||||
response.OK(c, gin.H{"message": "删除成功"})
|
||||
}
|
||||
|
||||
// 工具函数
|
||||
|
||||
func parseID(c *gin.Context) (uint64, error) {
|
||||
idStr := c.Param("id")
|
||||
id, err := strconv.ParseUint(idStr, 10, 64)
|
||||
if err != nil || id == 0 {
|
||||
return 0, errors.New("无效的ID")
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
func parsePagination(c *gin.Context) (int, int) {
|
||||
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||
pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
if pageSize < 1 {
|
||||
pageSize = 20
|
||||
}
|
||||
if pageSize > 100 {
|
||||
pageSize = 100
|
||||
}
|
||||
return page, pageSize
|
||||
}
|
||||
|
||||
func currentAdminID(c *gin.Context) (uint64, bool) {
|
||||
value, ok := c.Get(middleware.ContextAdminID)
|
||||
if !ok {
|
||||
return 0, false
|
||||
}
|
||||
adminID, ok := value.(uint64)
|
||||
return adminID, ok
|
||||
}
|
||||
@@ -0,0 +1,292 @@
|
||||
package announcement
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"hfb_sys/backend/internal/model"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type Repository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewRepository(db *gorm.DB) *Repository {
|
||||
return &Repository{db: db}
|
||||
}
|
||||
|
||||
// ResolvePublicSiteScope 解析前台请求应看到的公告归属站点集合。
|
||||
//
|
||||
// - 主站(无站点编码):只看主站公告 [0]
|
||||
// - 分站 inherit:主站公告 + 本站公告 [0, siteID]
|
||||
// - 分站 own_only:仅本站公告 [siteID]
|
||||
// - 站点编码无效/已停用:回落主站,与前台站点探测失败的兜底一致
|
||||
func (r *Repository) ResolvePublicSiteScope(ctx context.Context, siteCode string) ([]uint64, error) {
|
||||
code := strings.TrimSpace(siteCode)
|
||||
if code == "" {
|
||||
return []uint64{0}, nil
|
||||
}
|
||||
var site model.DistributionSite
|
||||
err := r.db.WithContext(ctx).Select("id", "announcement_mode").
|
||||
Where("site_code = ? AND status = ?", code, "active").First(&site).Error
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return []uint64{0}, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if strings.TrimSpace(site.AnnouncementMode) == model.AnnouncementModeOwnOnly {
|
||||
return []uint64{site.ID}, nil
|
||||
}
|
||||
return []uint64{0, site.ID}, nil
|
||||
}
|
||||
|
||||
// List 获取公告列表(前台用户)
|
||||
func (r *Repository) List(ctx context.Context, query AnnouncementListQuery) (*PaginatedResult, error) {
|
||||
var total int64
|
||||
tx := r.db.WithContext(ctx).Model(&model.Announcement{}).Where("status = ?", "published")
|
||||
|
||||
if len(query.AllowedSiteIDs) > 0 {
|
||||
tx = tx.Where("distribution_site_id IN ?", query.AllowedSiteIDs)
|
||||
}
|
||||
|
||||
if query.Category != "" {
|
||||
tx = tx.Where("category = ?", query.Category)
|
||||
}
|
||||
|
||||
if err := tx.Count(&total).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
offset := (query.Page - 1) * query.PageSize
|
||||
var rows []model.Announcement
|
||||
if err := tx.Order("is_pinned DESC, priority DESC, published_at DESC").
|
||||
Offset(offset).
|
||||
Limit(query.PageSize).
|
||||
Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
items := make([]AnnouncementDTO, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
items = append(items, toAnnouncementDTO(row))
|
||||
}
|
||||
|
||||
return &PaginatedResult{
|
||||
Items: items,
|
||||
Total: total,
|
||||
Page: query.Page,
|
||||
PageSize: query.PageSize,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// PublicPopup 取当前站点范围内优先级最高的弹窗公告;没有可弹公告时返回 nil, nil。
|
||||
//
|
||||
// 只取 published 且 is_popup = 1 的公告,按 priority DESC(其次发布时间/ID)排序取第一条,
|
||||
// 因此「多条同时生效只弹优先级最高的一条」由这里保证,前台无需再筛选。
|
||||
func (r *Repository) PublicPopup(ctx context.Context, allowedSiteIDs []uint64) (*AnnouncementDTO, error) {
|
||||
query := r.db.WithContext(ctx).
|
||||
Where("status = ? AND is_popup = ?", "published", true)
|
||||
if len(allowedSiteIDs) > 0 {
|
||||
query = query.Where("distribution_site_id IN ?", allowedSiteIDs)
|
||||
}
|
||||
|
||||
var announcement model.Announcement
|
||||
if err := query.
|
||||
Order("priority DESC, published_at DESC, id DESC").
|
||||
First(&announcement).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
dto := toAnnouncementDTO(announcement)
|
||||
return &dto, nil
|
||||
}
|
||||
|
||||
// GetByID 获取公告详情(限前台可见的站点范围,避免跨站按 ID 读取)
|
||||
func (r *Repository) GetByID(ctx context.Context, id uint64, allowedSiteIDs []uint64) (*AnnouncementDTO, error) {
|
||||
var announcement model.Announcement
|
||||
db := r.db.WithContext(ctx)
|
||||
query := db.Where("id = ? AND status = ?", id, "published")
|
||||
if len(allowedSiteIDs) > 0 {
|
||||
query = query.Where("distribution_site_id IN ?", allowedSiteIDs)
|
||||
}
|
||||
if err := query.First(&announcement).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 增加查看次数
|
||||
db.Model(&model.Announcement{}).Where("id = ?", id).UpdateColumn("view_count", gorm.Expr("view_count + ?", 1))
|
||||
|
||||
dto := toAnnouncementDTO(announcement)
|
||||
return &dto, nil
|
||||
}
|
||||
|
||||
// AdminList 管理员获取公告列表(可按站点筛选,含草稿/归档)
|
||||
func (r *Repository) AdminList(ctx context.Context, query AnnouncementListQuery) (*PaginatedResult, error) {
|
||||
base := r.adminListBase(ctx, query)
|
||||
|
||||
var total int64
|
||||
if err := base.Session(&gorm.Session{}).Count(&total).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
offset := (query.Page - 1) * query.PageSize
|
||||
var items []AnnouncementDTO
|
||||
if err := base.Session(&gorm.Session{}).
|
||||
Order("a.is_pinned DESC, a.priority DESC, a.id DESC").
|
||||
Offset(offset).
|
||||
Limit(query.PageSize).
|
||||
Scan(&items).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if items == nil {
|
||||
items = []AnnouncementDTO{}
|
||||
}
|
||||
|
||||
return &PaginatedResult{
|
||||
Items: items,
|
||||
Total: total,
|
||||
Page: query.Page,
|
||||
PageSize: query.PageSize,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// adminListBase 管理端公告列表基础查询:带站点名,支持状态/分类/站点筛选。
|
||||
func (r *Repository) adminListBase(ctx context.Context, query AnnouncementListQuery) *gorm.DB {
|
||||
base := r.db.WithContext(ctx).Table("announcements AS a").
|
||||
Select("a.id, a.distribution_site_id, COALESCE(s.site_name, '') AS distribution_site_name, a.title, a.content, a.category, a.priority, a.is_pinned, a.is_important, a.is_popup, a.view_count, a.status, a.published_at, a.created_at, a.updated_at").
|
||||
Joins("LEFT JOIN distribution_sites AS s ON s.id = a.distribution_site_id")
|
||||
|
||||
if query.Status != "" {
|
||||
base = base.Where("a.status = ?", query.Status)
|
||||
}
|
||||
if query.Category != "" {
|
||||
base = base.Where("a.category = ?", query.Category)
|
||||
}
|
||||
if query.AdminSiteID != nil {
|
||||
base = base.Where("a.distribution_site_id = ?", *query.AdminSiteID)
|
||||
}
|
||||
return base
|
||||
}
|
||||
|
||||
// AdminGetByID 管理员获取公告详情(带站点名)
|
||||
func (r *Repository) AdminGetByID(ctx context.Context, id uint64) (*AnnouncementDTO, error) {
|
||||
var dto AnnouncementDTO
|
||||
if err := r.adminListBase(ctx, AnnouncementListQuery{}).
|
||||
Where("a.id = ?", id).
|
||||
Scan(&dto).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if dto.ID == 0 {
|
||||
return nil, gorm.ErrRecordNotFound
|
||||
}
|
||||
return &dto, nil
|
||||
}
|
||||
|
||||
// Create 创建公告
|
||||
func (r *Repository) Create(ctx context.Context, req CreateAnnouncementRequest, createdBy uint64) (*AnnouncementDTO, error) {
|
||||
announcement := model.Announcement{
|
||||
DistributionSiteID: req.DistributionSiteID,
|
||||
Title: req.Title,
|
||||
Content: req.Content,
|
||||
Category: req.Category,
|
||||
Priority: req.Priority,
|
||||
IsPinned: req.IsPinned,
|
||||
IsImportant: req.IsImportant,
|
||||
IsPopup: req.IsPopup,
|
||||
Status: "draft",
|
||||
CreatedBy: &createdBy,
|
||||
}
|
||||
|
||||
if err := r.db.WithContext(ctx).Create(&announcement).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
dto := toAnnouncementDTO(announcement)
|
||||
return &dto, nil
|
||||
}
|
||||
|
||||
// Update 更新公告
|
||||
func (r *Repository) Update(ctx context.Context, id uint64, req UpdateAnnouncementRequest) (*AnnouncementDTO, error) {
|
||||
updates := make(map[string]interface{})
|
||||
|
||||
if req.Title != "" {
|
||||
updates["title"] = req.Title
|
||||
}
|
||||
if req.Content != "" {
|
||||
updates["content"] = req.Content
|
||||
}
|
||||
if req.Category != "" {
|
||||
updates["category"] = req.Category
|
||||
}
|
||||
updates["priority"] = req.Priority
|
||||
updates["is_pinned"] = req.IsPinned
|
||||
updates["is_important"] = req.IsImportant
|
||||
updates["is_popup"] = req.IsPopup
|
||||
|
||||
if err := r.db.WithContext(ctx).Model(&model.Announcement{}).Where("id = ?", id).Updates(updates).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return r.AdminGetByID(ctx, id)
|
||||
}
|
||||
|
||||
// Publish 发布公告
|
||||
func (r *Repository) Publish(ctx context.Context, id uint64) error {
|
||||
now := time.Now()
|
||||
return r.db.WithContext(ctx).Model(&model.Announcement{}).
|
||||
Where("id = ?", id).
|
||||
Updates(map[string]interface{}{
|
||||
"status": "published",
|
||||
"published_at": now,
|
||||
}).Error
|
||||
}
|
||||
|
||||
// Archive 归档公告
|
||||
func (r *Repository) Archive(ctx context.Context, id uint64) error {
|
||||
return r.db.WithContext(ctx).Model(&model.Announcement{}).
|
||||
Where("id = ?", id).
|
||||
Update("status", "archived").Error
|
||||
}
|
||||
|
||||
// Unarchive 取消归档公告,恢复为已发布状态
|
||||
func (r *Repository) Unarchive(ctx context.Context, id uint64) error {
|
||||
now := time.Now()
|
||||
return r.db.WithContext(ctx).Model(&model.Announcement{}).
|
||||
Where("id = ?", id).
|
||||
Updates(map[string]interface{}{
|
||||
"status": "published",
|
||||
"published_at": gorm.Expr("COALESCE(published_at, ?)", now),
|
||||
}).Error
|
||||
}
|
||||
|
||||
// Delete 删除公告
|
||||
func (r *Repository) Delete(ctx context.Context, id uint64) error {
|
||||
return r.db.WithContext(ctx).Where("id = ?", id).Delete(&model.Announcement{}).Error
|
||||
}
|
||||
|
||||
func toAnnouncementDTO(a model.Announcement) AnnouncementDTO {
|
||||
return AnnouncementDTO{
|
||||
ID: a.ID,
|
||||
DistributionSiteID: a.DistributionSiteID,
|
||||
Title: a.Title,
|
||||
Content: a.Content,
|
||||
Category: a.Category,
|
||||
Priority: a.Priority,
|
||||
IsPinned: a.IsPinned,
|
||||
IsImportant: a.IsImportant,
|
||||
IsPopup: a.IsPopup,
|
||||
ViewCount: a.ViewCount,
|
||||
Status: a.Status,
|
||||
PublishedAt: a.PublishedAt,
|
||||
CreatedAt: a.CreatedAt,
|
||||
UpdatedAt: a.UpdatedAt,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
package announcement
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"hfb_sys/backend/internal/database"
|
||||
"hfb_sys/backend/internal/model"
|
||||
)
|
||||
|
||||
// TestPublicScopeAndSiteIsolation 覆盖公告中心的分站可见范围:
|
||||
// 主站只看主站、分站继承=主站+本站、分站仅本站=只有本站,详情也不能跨站读取。
|
||||
func TestPublicScopeAndSiteIsolation(t *testing.T) {
|
||||
db := database.NewTestDB()
|
||||
repo := NewRepository(db)
|
||||
ctx := context.Background()
|
||||
|
||||
mainAnnouncement := model.Announcement{Title: "主站公告", Content: "主站内容", Category: "notice", Status: "published"}
|
||||
if err := db.Create(&mainAnnouncement).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
inheritSite := model.DistributionSite{
|
||||
SiteCode: "ann_inherit", SiteName: "继承站", Domain: "ann-inherit.example.com",
|
||||
Status: "active", AnnouncementMode: model.AnnouncementModeInherit,
|
||||
}
|
||||
ownOnlySite := model.DistributionSite{
|
||||
SiteCode: "ann_own_only", SiteName: "独立站", Domain: "ann-own.example.com",
|
||||
Status: "active", AnnouncementMode: model.AnnouncementModeOwnOnly,
|
||||
}
|
||||
if err := db.Create(&inheritSite).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Create(&ownOnlySite).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
inheritOwn := model.Announcement{
|
||||
DistributionSiteID: inheritSite.ID, Title: "继承站公告", Content: "本站内容",
|
||||
Category: "notice", Status: "published",
|
||||
}
|
||||
ownOnlyOwn := model.Announcement{
|
||||
DistributionSiteID: ownOnlySite.ID, Title: "独立站公告", Content: "本站内容",
|
||||
Category: "notice", Status: "published",
|
||||
}
|
||||
if err := db.Create(&inheritOwn).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Create(&ownOnlyOwn).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// 主站:仅 [0]
|
||||
mainScope, err := repo.ResolvePublicSiteScope(ctx, "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(mainScope) != 1 || mainScope[0] != 0 {
|
||||
t.Fatalf("main scope = %v, want [0]", mainScope)
|
||||
}
|
||||
mainList, err := repo.List(ctx, AnnouncementListQuery{AllowedSiteIDs: mainScope, Page: 1, PageSize: 20})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if mainList.Total != 1 {
|
||||
t.Fatalf("主站应只看到 1 条主站公告, got %d", mainList.Total)
|
||||
}
|
||||
|
||||
// 分站 inherit:[0, siteID] → 主站公告 + 本站公告
|
||||
inheritScope, err := repo.ResolvePublicSiteScope(ctx, inheritSite.SiteCode)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(inheritScope) != 2 {
|
||||
t.Fatalf("inherit scope = %v, want [0, siteID]", inheritScope)
|
||||
}
|
||||
inheritList, err := repo.List(ctx, AnnouncementListQuery{AllowedSiteIDs: inheritScope, Page: 1, PageSize: 20})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if inheritList.Total != 2 {
|
||||
t.Fatalf("继承站应看到主站+本站共 2 条, got %d", inheritList.Total)
|
||||
}
|
||||
|
||||
// 分站 own_only:只有本站公告(不含主站公告)
|
||||
ownScope, err := repo.ResolvePublicSiteScope(ctx, ownOnlySite.SiteCode)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(ownScope) != 1 || ownScope[0] != ownOnlySite.ID {
|
||||
t.Fatalf("own_only scope = %v, want [siteID]", ownScope)
|
||||
}
|
||||
ownList, err := repo.List(ctx, AnnouncementListQuery{AllowedSiteIDs: ownScope, Page: 1, PageSize: 20})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if ownList.Total != 1 {
|
||||
t.Fatalf("仅本站站点应只看到本站 1 条, got %d", ownList.Total)
|
||||
}
|
||||
|
||||
// 无效站点编码回落主站,避免把主站公告错误地当成某站的
|
||||
fallbackScope, err := repo.ResolvePublicSiteScope(ctx, "not_exists_site")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(fallbackScope) != 1 || fallbackScope[0] != 0 {
|
||||
t.Fatalf("未知站点应回落主站, got %v", fallbackScope)
|
||||
}
|
||||
|
||||
// 详情跨站隔离:主站访客不能按 ID 读分站公告
|
||||
if _, err := repo.GetByID(ctx, inheritOwn.ID, []uint64{0}); err == nil {
|
||||
t.Fatalf("主站不应能读取分站公告详情")
|
||||
}
|
||||
if _, err := repo.GetByID(ctx, inheritOwn.ID, inheritScope); err != nil {
|
||||
t.Fatalf("继承站应能读取本站公告详情: %v", err)
|
||||
}
|
||||
if _, err := repo.GetByID(ctx, ownOnlyOwn.ID, inheritScope); err == nil {
|
||||
t.Fatalf("继承站不应能读取其它分站公告详情")
|
||||
}
|
||||
}
|
||||
|
||||
// TestAdminListFiltersBySite 管理端可按站点筛选,并带出站点名。
|
||||
func TestAdminListFiltersBySite(t *testing.T) {
|
||||
db := database.NewTestDB()
|
||||
repo := NewRepository(db)
|
||||
ctx := context.Background()
|
||||
|
||||
site := model.DistributionSite{
|
||||
SiteCode: "ann_admin", SiteName: "筛选站", Domain: "ann-admin.example.com",
|
||||
Status: "active", AnnouncementMode: model.AnnouncementModeInherit,
|
||||
}
|
||||
if err := db.Create(&site).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Create(&model.Announcement{Title: "主站公告", Content: "x", Category: "notice", Status: "draft"}).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Create(&model.Announcement{
|
||||
DistributionSiteID: site.ID, Title: "分站公告", Content: "y", Category: "notice", Status: "draft",
|
||||
}).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
all, err := repo.AdminList(ctx, AnnouncementListQuery{Page: 1, PageSize: 20})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if all.Total != 2 {
|
||||
t.Fatalf("不传站点应返回全部 2 条, got %d", all.Total)
|
||||
}
|
||||
|
||||
mainOnly := uint64(0)
|
||||
mainList, err := repo.AdminList(ctx, AnnouncementListQuery{AdminSiteID: &mainOnly, Page: 1, PageSize: 20})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if mainList.Total != 1 {
|
||||
t.Fatalf("site_id=0 应只返回主站公告, got %d", mainList.Total)
|
||||
}
|
||||
|
||||
siteID := site.ID
|
||||
siteList, err := repo.AdminList(ctx, AnnouncementListQuery{AdminSiteID: &siteID, Page: 1, PageSize: 20})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if siteList.Total != 1 {
|
||||
t.Fatalf("按站点筛选应只返回该站公告, got %d", siteList.Total)
|
||||
}
|
||||
items, ok := siteList.Items.([]AnnouncementDTO)
|
||||
if !ok || len(items) != 1 {
|
||||
t.Fatalf("unexpected items: %#v", siteList.Items)
|
||||
}
|
||||
if items[0].DistributionSiteID != site.ID || items[0].DistributionSiteName != "筛选站" {
|
||||
t.Fatalf("站点信息未透出: %+v", items[0])
|
||||
}
|
||||
}
|
||||
|
||||
// TestPublicPopupSelection 覆盖弹窗公告的选取口径:
|
||||
// 只有 published + is_popup 才参与,站点范围内按优先级取最高的一条,无候选时返回 nil。
|
||||
func TestPublicPopupSelection(t *testing.T) {
|
||||
db := database.NewTestDB()
|
||||
repo := NewRepository(db)
|
||||
ctx := context.Background()
|
||||
|
||||
// 主站:非弹窗公告(不应参与) + 两条弹窗公告(优先级不同)
|
||||
plain := model.Announcement{
|
||||
Title: "普通公告", Content: "内容", Category: "notice", Status: "published",
|
||||
}
|
||||
lowPriority := model.Announcement{
|
||||
Title: "低优先级弹窗", Content: "内容", Category: "notice",
|
||||
Status: "published", IsPopup: true, Priority: 1,
|
||||
}
|
||||
highPriority := model.Announcement{
|
||||
Title: "高优先级弹窗", Content: "内容", Category: "notice",
|
||||
Status: "published", IsPopup: true, Priority: 9,
|
||||
}
|
||||
// 弹窗但未发布:不应参与
|
||||
draftPopup := model.Announcement{
|
||||
Title: "草稿弹窗", Content: "内容", Category: "notice",
|
||||
Status: "draft", IsPopup: true, Priority: 99,
|
||||
}
|
||||
for _, row := range []*model.Announcement{&plain, &lowPriority, &highPriority, &draftPopup} {
|
||||
if err := db.Create(row).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
popup, err := repo.PublicPopup(ctx, []uint64{0})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if popup == nil {
|
||||
t.Fatal("主站应弹出一条弹窗公告, got nil")
|
||||
}
|
||||
if popup.ID != highPriority.ID || popup.Title != "高优先级弹窗" {
|
||||
t.Fatalf("应取优先级最高的弹窗公告, got %+v", popup)
|
||||
}
|
||||
if !popup.IsPopup {
|
||||
t.Fatalf("返回的公告应带 is_popup 标记: %+v", popup)
|
||||
}
|
||||
|
||||
// 站点隔离:独立站只看到本站公告,主站弹窗不可见
|
||||
site := model.DistributionSite{
|
||||
SiteCode: "ann_popup_site", SiteName: "弹窗站", Domain: "ann-popup.example.com",
|
||||
Status: "active", AnnouncementMode: model.AnnouncementModeOwnOnly,
|
||||
}
|
||||
if err := db.Create(&site).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
none, err := repo.PublicPopup(ctx, []uint64{site.ID})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if none != nil {
|
||||
t.Fatalf("本站没有弹窗公告时应返回 nil, got %+v", none)
|
||||
}
|
||||
|
||||
// 本站有自己的弹窗公告时应生效
|
||||
sitePopup := model.Announcement{
|
||||
DistributionSiteID: site.ID, Title: "本站弹窗", Content: "内容",
|
||||
Category: "notice", Status: "published", IsPopup: true, Priority: 5,
|
||||
}
|
||||
if err := db.Create(&sitePopup).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := repo.PublicPopup(ctx, []uint64{site.ID})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got == nil || got.ID != sitePopup.ID {
|
||||
t.Fatalf("应取本站弹窗公告, got %+v", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package announcement
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
repo *Repository
|
||||
}
|
||||
|
||||
func NewService(repo *Repository) *Service {
|
||||
return &Service{repo: repo}
|
||||
}
|
||||
|
||||
var (
|
||||
ErrNotFound = errors.New("公告不存在")
|
||||
ErrInvalidRequest = errors.New("请求参数不正确")
|
||||
ErrUnauthorized = errors.New("未授权")
|
||||
)
|
||||
|
||||
// ResolvePublicSiteScope 解析前台请求应看到的公告归属站点集合(站点编码由请求头解析)。
|
||||
func (s *Service) ResolvePublicSiteScope(ctx context.Context, siteCode string) ([]uint64, error) {
|
||||
return s.repo.ResolvePublicSiteScope(ctx, siteCode)
|
||||
}
|
||||
|
||||
// List 获取公告列表(前台用户)
|
||||
func (s *Service) List(ctx context.Context, query AnnouncementListQuery) (*PaginatedResult, error) {
|
||||
if query.Page < 1 {
|
||||
query.Page = 1
|
||||
}
|
||||
if query.PageSize < 1 {
|
||||
query.PageSize = 20
|
||||
}
|
||||
if query.PageSize > 100 {
|
||||
query.PageSize = 100
|
||||
}
|
||||
|
||||
return s.repo.List(ctx, query)
|
||||
}
|
||||
|
||||
// PublicPopup 获取前台首页要弹出的弹窗公告(无则返回 nil)
|
||||
func (s *Service) PublicPopup(ctx context.Context, allowedSiteIDs []uint64) (*AnnouncementDTO, error) {
|
||||
return s.repo.PublicPopup(ctx, allowedSiteIDs)
|
||||
}
|
||||
|
||||
// GetByID 获取公告详情(限前台可见的站点范围)
|
||||
func (s *Service) GetByID(ctx context.Context, id uint64, allowedSiteIDs []uint64) (*AnnouncementDTO, error) {
|
||||
dto, err := s.repo.GetByID(ctx, id, allowedSiteIDs)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return dto, nil
|
||||
}
|
||||
|
||||
// AdminList 管理员获取公告列表
|
||||
func (s *Service) AdminList(ctx context.Context, query AnnouncementListQuery) (*PaginatedResult, error) {
|
||||
if query.Page < 1 {
|
||||
query.Page = 1
|
||||
}
|
||||
if query.PageSize < 1 {
|
||||
query.PageSize = 20
|
||||
}
|
||||
if query.PageSize > 100 {
|
||||
query.PageSize = 100
|
||||
}
|
||||
|
||||
return s.repo.AdminList(ctx, query)
|
||||
}
|
||||
|
||||
// AdminGetByID 管理员获取公告详情
|
||||
func (s *Service) AdminGetByID(ctx context.Context, id uint64) (*AnnouncementDTO, error) {
|
||||
dto, err := s.repo.AdminGetByID(ctx, id)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return dto, nil
|
||||
}
|
||||
|
||||
// Create 创建公告
|
||||
func (s *Service) Create(ctx context.Context, req CreateAnnouncementRequest, createdBy uint64) (*AnnouncementDTO, error) {
|
||||
return s.repo.Create(ctx, req, createdBy)
|
||||
}
|
||||
|
||||
// Update 更新公告
|
||||
func (s *Service) Update(ctx context.Context, id uint64, req UpdateAnnouncementRequest) (*AnnouncementDTO, error) {
|
||||
return s.repo.Update(ctx, id, req)
|
||||
}
|
||||
|
||||
// Publish 发布公告
|
||||
func (s *Service) Publish(ctx context.Context, id uint64) error {
|
||||
return s.repo.Publish(ctx, id)
|
||||
}
|
||||
|
||||
// Archive 归档公告
|
||||
func (s *Service) Archive(ctx context.Context, id uint64) error {
|
||||
return s.repo.Archive(ctx, id)
|
||||
}
|
||||
|
||||
// Unarchive 取消归档公告
|
||||
func (s *Service) Unarchive(ctx context.Context, id uint64) error {
|
||||
return s.repo.Unarchive(ctx, id)
|
||||
}
|
||||
|
||||
// Delete 删除公告
|
||||
func (s *Service) Delete(ctx context.Context, id uint64) error {
|
||||
return s.repo.Delete(ctx, id)
|
||||
}
|
||||
Reference in New Issue
Block a user