chore(init): 初始化解忧商行项目并完成 Phase 0 基座

This commit is contained in:
yml2213
2026-10-30 11:46:10 +08:00
commit 8d9481c251
689 changed files with 138703 additions and 0 deletions
@@ -0,0 +1,3 @@
# Notification Module
站内信列表、已读状态和订单流程消息。
@@ -0,0 +1,27 @@
package notification
import "time"
type NotificationDTO struct {
ID uint64 `json:"id"`
UserID uint64 `json:"user_id"`
Type string `json:"type"`
Title string `json:"title"`
Content string `json:"content"`
BizType string `json:"biz_type"`
BizID *uint64 `json:"biz_id"`
DistributionSiteID *uint64 `json:"distribution_site_id,omitempty"`
ReadAt *time.Time `json:"read_at"`
CreatedAt time.Time `json:"created_at"`
}
type PaginatedResult struct {
Items interface{} `json:"items"`
Total int64 `json:"total"`
Page int `json:"page"`
PageSize int `json:"page_size"`
}
type UnreadCountDTO struct {
UnreadCount int64 `json:"unread_count"`
}
@@ -0,0 +1,125 @@
package notification
import (
"errors"
"strconv"
"hfb_sys/backend/internal/middleware"
"hfb_sys/backend/internal/sitecode"
"hfb_sys/backend/pkg/response"
"github.com/gin-gonic/gin"
)
type Handler struct {
service *Service
}
func NewHandler(service *Service) *Handler {
return &Handler{service: service}
}
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 (h *Handler) List(c *gin.Context) {
userID, ok := currentUserID(c)
if !ok {
response.Unauthorized(c, "缺少用户上下文")
return
}
page, pageSize := parsePagination(c)
siteCode := parseSiteCode(c)
result, err := h.service.List(c.Request.Context(), userID, page, pageSize, siteCode)
if err != nil {
writeNotificationError(c, err)
return
}
response.OK(c, result)
}
func (h *Handler) UnreadCount(c *gin.Context) {
userID, ok := currentUserID(c)
if !ok {
response.Unauthorized(c, "缺少用户上下文")
return
}
siteCode := parseSiteCode(c)
result, err := h.service.UnreadCount(c.Request.Context(), userID, siteCode)
if err != nil {
writeNotificationError(c, err)
return
}
response.OK(c, result)
}
func (h *Handler) MarkAllRead(c *gin.Context) {
userID, ok := currentUserID(c)
if !ok {
response.Unauthorized(c, "缺少用户上下文")
return
}
siteCode := parseSiteCode(c)
count, err := h.service.MarkAllRead(c.Request.Context(), userID, siteCode)
if err != nil {
writeNotificationError(c, err)
return
}
response.OK(c, gin.H{"read_count": count})
}
func (h *Handler) MarkRead(c *gin.Context) {
userID, ok := currentUserID(c)
if !ok {
response.Unauthorized(c, "缺少用户上下文")
return
}
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
if err != nil || id == 0 {
response.BadRequest(c, "ID 不正确")
return
}
siteCode := parseSiteCode(c)
if err := h.service.MarkRead(c.Request.Context(), userID, id, siteCode); err != nil {
writeNotificationError(c, err)
return
}
response.OK(c, gin.H{"read": true})
}
func parseSiteCode(c *gin.Context) string {
return sitecode.FromRequest(c)
}
func currentUserID(c *gin.Context) (uint64, bool) {
value, ok := c.Get(middleware.ContextUserID)
if !ok {
return 0, false
}
userID, ok := value.(uint64)
return userID, ok
}
func writeNotificationError(c *gin.Context, err error) {
response.RecordError(c, err)
switch {
case errors.Is(err, ErrDependencyUnavailable):
response.ServiceUnavailable(c, "数据库未连接")
case errors.Is(err, ErrNotificationNotFound):
response.NotFound(c, "通知不存在")
default:
response.ServiceUnavailable(c, "通知服务暂时不可用")
}
}
@@ -0,0 +1,208 @@
package notification
import (
"context"
"errors"
"strings"
"time"
"hfb_sys/backend/internal/model"
"gorm.io/gorm"
)
type Repository struct {
db *gorm.DB
}
type Entry struct {
UserID uint64
Type string
Title string
Content string
BizType string
BizID *uint64
DistributionSiteID *uint64
}
func NewRepository(db *gorm.DB) *Repository {
return &Repository{db: db}
}
func (r *Repository) resolveSite(ctx context.Context, siteCode string) (uint64, bool, error) {
siteCode = strings.TrimSpace(siteCode)
if siteCode == "" {
return 0, false, nil
}
var site model.DistributionSite
if err := r.db.WithContext(ctx).Where("site_code = ? AND status = 'active'", siteCode).First(&site).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return 0, false, nil
}
return 0, false, err
}
return site.ID, true, nil
}
func (r *Repository) applySiteFilter(db *gorm.DB, siteID uint64, isSite bool) *gorm.DB {
if isSite && siteID > 0 {
return db.Where("distribution_site_id = ?", siteID)
}
return db.Where("distribution_site_id IS NULL OR distribution_site_id = 0")
}
func (r *Repository) List(ctx context.Context, userID uint64, page, pageSize int, siteCode ...string) (*PaginatedResult, error) {
var code string
if len(siteCode) > 0 {
code = siteCode[0]
}
siteID, isSite, err := r.resolveSite(ctx, code)
if err != nil {
return nil, err
}
query := r.db.WithContext(ctx).Model(&model.Notification{}).Where("user_id = ?", userID)
query = r.applySiteFilter(query, siteID, isSite)
var total int64
if err := query.Count(&total).Error; err != nil {
return nil, err
}
offset := (page - 1) * pageSize
var rows []model.Notification
dataQuery := r.db.WithContext(ctx).Where("user_id = ?", userID)
dataQuery = r.applySiteFilter(dataQuery, siteID, isSite)
if err := dataQuery.Order("id DESC").Offset(offset).Limit(pageSize).Find(&rows).Error; err != nil {
return nil, err
}
items := make([]NotificationDTO, 0, len(rows))
for _, row := range rows {
items = append(items, toDTO(row))
}
return &PaginatedResult{Items: items, Total: total, Page: page, PageSize: pageSize}, nil
}
func (r *Repository) MarkRead(ctx context.Context, userID uint64, id uint64, siteCode ...string) error {
var code string
if len(siteCode) > 0 {
code = siteCode[0]
}
siteID, isSite, err := r.resolveSite(ctx, code)
if err != nil {
return err
}
now := time.Now()
query := r.db.WithContext(ctx).Model(&model.Notification{}).Where("id = ? AND user_id = ?", id, userID)
query = r.applySiteFilter(query, siteID, isSite)
result := query.Update("read_at", now)
if result.Error != nil {
return result.Error
}
if result.RowsAffected == 0 {
checkQuery := r.db.WithContext(ctx).Model(&model.Notification{}).Where("id = ? AND user_id = ?", id, userID)
checkQuery = r.applySiteFilter(checkQuery, siteID, isSite)
var total int64
if err := checkQuery.Count(&total).Error; err != nil {
return err
}
if total == 0 {
return ErrNotificationNotFound
}
}
return nil
}
func (r *Repository) UnreadCount(ctx context.Context, userID uint64, siteCode ...string) (int64, error) {
var code string
if len(siteCode) > 0 {
code = siteCode[0]
}
siteID, isSite, err := r.resolveSite(ctx, code)
if err != nil {
return 0, err
}
query := r.db.WithContext(ctx).Model(&model.Notification{}).Where("user_id = ? AND read_at IS NULL", userID)
query = r.applySiteFilter(query, siteID, isSite)
var total int64
err = query.Count(&total).Error
return total, err
}
func (r *Repository) MarkAllRead(ctx context.Context, userID uint64, siteCode ...string) (int64, error) {
var code string
if len(siteCode) > 0 {
code = siteCode[0]
}
siteID, isSite, err := r.resolveSite(ctx, code)
if err != nil {
return 0, err
}
now := time.Now()
query := r.db.WithContext(ctx).Model(&model.Notification{}).Where("user_id = ? AND read_at IS NULL", userID)
query = r.applySiteFilter(query, siteID, isSite)
result := query.Update("read_at", now)
return result.RowsAffected, result.Error
}
func Append(tx *gorm.DB, entries ...Entry) error {
for _, entry := range entries {
if entry.UserID == 0 || entry.Title == "" {
continue
}
siteID := entry.DistributionSiteID
if siteID == nil {
if (entry.BizType == "order" || entry.BizType == "order_handoff") && entry.BizID != nil && *entry.BizID > 0 {
var orderSiteID *uint64
var mode string
row := tx.Table("rental_orders").Where("id = ?", *entry.BizID).Select("distribution_site_id, distribution_mode").Row()
if err := row.Scan(&orderSiteID, &mode); err == nil && orderSiteID != nil && mode != "two_party_distributor_receive" {
siteID = orderSiteID
}
} else if entry.BizType == "dispute" && entry.BizID != nil && *entry.BizID > 0 {
var orderSiteID *uint64
var mode string
row := tx.Table("order_disputes d").Joins("JOIN rental_orders o ON o.id = d.order_id").Where("d.id = ?", *entry.BizID).Select("o.distribution_site_id, o.distribution_mode").Row()
if err := row.Scan(&orderSiteID, &mode); err == nil && orderSiteID != nil && mode != "two_party_distributor_receive" {
siteID = orderSiteID
}
}
}
row := model.Notification{
UserID: entry.UserID,
Type: entry.Type,
Title: entry.Title,
Content: entry.Content,
BizType: entry.BizType,
BizID: entry.BizID,
DistributionSiteID: siteID,
}
if row.Type == "" {
row.Type = "system"
}
if err := tx.Create(&row).Error; err != nil {
return err
}
}
return nil
}
func toDTO(row model.Notification) NotificationDTO {
return NotificationDTO{
ID: row.ID,
UserID: row.UserID,
Type: row.Type,
Title: row.Title,
Content: row.Content,
BizType: row.BizType,
BizID: row.BizID,
DistributionSiteID: row.DistributionSiteID,
ReadAt: row.ReadAt,
CreatedAt: row.CreatedAt,
}
}
@@ -0,0 +1,193 @@
package notification
import (
"context"
"errors"
"testing"
"hfb_sys/backend/internal/database"
"hfb_sys/backend/internal/model"
)
func TestRepositoryUnreadCountAndMarkRead(t *testing.T) {
db := database.NewTestDB()
if err := database.AutoMigrateIfMissing(db, &model.Notification{}); err != nil {
t.Fatalf("AutoMigrate() error = %v", err)
}
repo := NewRepository(db)
ctx := context.Background()
if err := db.Create(&model.Notification{
UserID: 10,
Type: "order",
Title: "订单通知",
Content: "请处理订单",
}).Error; err != nil {
t.Fatalf("Create() error = %v", err)
}
count, err := repo.UnreadCount(ctx, 10)
if err != nil {
t.Fatalf("UnreadCount() error = %v", err)
}
if count != 1 {
t.Fatalf("UnreadCount() = %d, want 1", count)
}
if err := repo.MarkRead(ctx, 10, 1); err != nil {
t.Fatalf("MarkRead() error = %v", err)
}
// 重复标记应保持幂等,不应误报不存在。
if err := repo.MarkRead(ctx, 10, 1); err != nil {
t.Fatalf("MarkRead() repeat error = %v", err)
}
count, err = repo.UnreadCount(ctx, 10)
if err != nil {
t.Fatalf("UnreadCount() after read error = %v", err)
}
if count != 0 {
t.Fatalf("UnreadCount() after read = %d, want 0", count)
}
}
func TestRepositoryMarkReadNotFound(t *testing.T) {
db := database.NewTestDB()
if err := database.AutoMigrateIfMissing(db, &model.Notification{}); err != nil {
t.Fatalf("AutoMigrate() error = %v", err)
}
repo := NewRepository(db)
err := repo.MarkRead(context.Background(), 10, 99)
if !errors.Is(err, ErrNotificationNotFound) {
t.Fatalf("MarkRead() error = %v, want ErrNotificationNotFound", err)
}
}
func TestNotificationTenantIsolation(t *testing.T) {
db := database.NewTestDB()
if err := database.AutoMigrateIfMissing(db, &model.Notification{}, &model.DistributionSite{}, &model.RentalOrder{}); err != nil {
t.Fatalf("AutoMigrate() error = %v", err)
}
repo := NewRepository(db)
ctx := context.Background()
site := model.DistributionSite{
ID: 101,
SiteCode: "branch_a",
SiteName: "分站A",
Status: "active",
}
if err := db.Create(&site).Error; err != nil {
t.Fatalf("create distribution site error: %v", err)
}
siteID := site.ID
// 1. 创建主站通知
mainNotif := model.Notification{
UserID: 20,
Type: "order",
Title: "主站订单通知",
Content: "这是主站的订单通知",
BizType: "order",
DistributionSiteID: nil,
}
if err := db.Create(&mainNotif).Error; err != nil {
t.Fatalf("create main notif error: %v", err)
}
// 2. 创建分站通知
branchNotif := model.Notification{
UserID: 20,
Type: "order",
Title: "分站A订单通知",
Content: "这是分站A的订单通知",
BizType: "order",
DistributionSiteID: &siteID,
}
if err := db.Create(&branchNotif).Error; err != nil {
t.Fatalf("create branch notif error: %v", err)
}
// 3. 验证未读数隔离
mainUnread, err := repo.UnreadCount(ctx, 20)
if err != nil || mainUnread != 1 {
t.Fatalf("mainUnread = %d, err = %v, want 1", mainUnread, err)
}
branchUnread, err := repo.UnreadCount(ctx, 20, "branch_a")
if err != nil || branchUnread != 1 {
t.Fatalf("branchUnread = %d, err = %v, want 1", branchUnread, err)
}
// 4. 验证列表查询隔离
mainList, err := repo.List(ctx, 20, 1, 10)
if err != nil || mainList.Total != 1 {
t.Fatalf("mainList total = %d, err = %v, want 1", mainList.Total, err)
}
items := mainList.Items.([]NotificationDTO)
if items[0].Title != "主站订单通知" {
t.Fatalf("mainList item title = %s, want 主站订单通知", items[0].Title)
}
branchList, err := repo.List(ctx, 20, 1, 10, "branch_a")
if err != nil || branchList.Total != 1 {
t.Fatalf("branchList total = %d, err = %v, want 1", branchList.Total, err)
}
branchItems := branchList.Items.([]NotificationDTO)
if branchItems[0].Title != "分站A订单通知" {
t.Fatalf("branchList item title = %s, want 分站A订单通知", branchItems[0].Title)
}
// 5. 跨站点标记单条已读阻断
err = repo.MarkRead(ctx, 20, mainNotif.ID, "branch_a")
if !errors.Is(err, ErrNotificationNotFound) {
t.Fatalf("cross-site MarkRead error = %v, want ErrNotificationNotFound", err)
}
// 6. 分站全部已读不影响主站
affected, err := repo.MarkAllRead(ctx, 20, "branch_a")
if err != nil || affected != 1 {
t.Fatalf("MarkAllRead affected = %d, err = %v, want 1", affected, err)
}
branchUnreadAfter, err := repo.UnreadCount(ctx, 20, "branch_a")
if err != nil || branchUnreadAfter != 0 {
t.Fatalf("branchUnreadAfter = %d, want 0", branchUnreadAfter)
}
mainUnreadAfter, err := repo.UnreadCount(ctx, 20)
if err != nil || mainUnreadAfter != 1 {
t.Fatalf("mainUnreadAfter = %d, want 1 (should remain unread)", mainUnreadAfter)
}
// 7. 测试 Append 自动关联订单 distribution_site_id
order := model.RentalOrder{
ID: 3001,
DistributionSiteID: &siteID,
OrderNo: "ORD3001",
}
if err := db.Create(&order).Error; err != nil {
t.Fatalf("create order error: %v", err)
}
orderID := order.ID
err = Append(db, Entry{
UserID: 20,
Type: "order",
Title: "订单自动关联分站",
Content: "自动读取订单 site ID",
BizType: "order",
BizID: &orderID,
})
if err != nil {
t.Fatalf("Append with auto lookup error: %v", err)
}
var autoNotif model.Notification
if err := db.Where("biz_id = ? AND biz_type = 'order'", orderID).First(&autoNotif).Error; err != nil {
t.Fatalf("find autoNotif error: %v", err)
}
if autoNotif.DistributionSiteID == nil || *autoNotif.DistributionSiteID != siteID {
t.Fatalf("autoNotif.DistributionSiteID = %v, want %d", autoNotif.DistributionSiteID, siteID)
}
}
@@ -0,0 +1,49 @@
package notification
import (
"context"
"errors"
)
var ErrDependencyUnavailable = errors.New("dependency unavailable")
var ErrNotificationNotFound = errors.New("notification not found")
type Service struct {
repo *Repository
}
func NewService(repo *Repository) *Service {
return &Service{repo: repo}
}
func (s *Service) List(ctx context.Context, userID uint64, page, pageSize int, siteCode ...string) (*PaginatedResult, error) {
if s.repo == nil {
return nil, ErrDependencyUnavailable
}
return s.repo.List(ctx, userID, page, pageSize, siteCode...)
}
func (s *Service) MarkRead(ctx context.Context, userID uint64, id uint64, siteCode ...string) error {
if s.repo == nil {
return ErrDependencyUnavailable
}
return s.repo.MarkRead(ctx, userID, id, siteCode...)
}
func (s *Service) UnreadCount(ctx context.Context, userID uint64, siteCode ...string) (*UnreadCountDTO, error) {
if s.repo == nil {
return nil, ErrDependencyUnavailable
}
count, err := s.repo.UnreadCount(ctx, userID, siteCode...)
if err != nil {
return nil, err
}
return &UnreadCountDTO{UnreadCount: count}, nil
}
func (s *Service) MarkAllRead(ctx context.Context, userID uint64, siteCode ...string) (int64, error) {
if s.repo == nil {
return 0, ErrDependencyUnavailable
}
return s.repo.MarkAllRead(ctx, userID, siteCode...)
}