feat(admin): 新增客服手动录单功能与仪表盘今日录单统计
- 做了什么: - 新增客服手动录单数据库迁移 000084 及对应模型,支持编号唯一校验、客服快照绑定与 CRUD 操作; - 后端提供 csmanualentry 业务模块及相关 API,并在仪表盘摘要中聚合今日各客服录单数量; - 前端增加客服手动录单视图页面、路由与侧边栏导航,支持录单二次确认与细粒度权限控制; - 管理后台仪表盘增加今日客服手动录单卡片展示。 - 为什么: - 满足客服在后台手动登记外部业务编号需求,并便于运营按客服统计今日录单业绩和追溯对账。 - 验证方式: - 执行后端全量测试 go test ./... 与静态检查 go vet ./... 全部通过; - 执行前端代码门禁 npm run check 与 vite build 全部通过; - 执行 goose down/up 迁移回滚与应用测试通过,角色权限分配正确; - 本地 dev 联调 POST /api/admin/manual-entries 录单成功返回 201。
This commit is contained in:
@@ -3,12 +3,13 @@ package admindashboard
|
||||
import "time"
|
||||
|
||||
type DashboardDTO struct {
|
||||
Metrics MetricsDTO `json:"metrics"`
|
||||
Pending PendingDTO `json:"pending"`
|
||||
ListingDaily ListingDailyOverviewDTO `json:"listing_daily"`
|
||||
RecentOrders []RecentOrderDTO `json:"recent_orders"`
|
||||
RecentDisputes []RecentDisputeDTO `json:"recent_disputes"`
|
||||
GeneratedAt time.Time `json:"generated_at"`
|
||||
Metrics MetricsDTO `json:"metrics"`
|
||||
Pending PendingDTO `json:"pending"`
|
||||
ListingDaily ListingDailyOverviewDTO `json:"listing_daily"`
|
||||
ManualEntryToday []ManualEntryAgentStatsDTO `json:"manual_entry_today"`
|
||||
RecentOrders []RecentOrderDTO `json:"recent_orders"`
|
||||
RecentDisputes []RecentDisputeDTO `json:"recent_disputes"`
|
||||
GeneratedAt time.Time `json:"generated_at"`
|
||||
}
|
||||
|
||||
type MetricsDTO struct {
|
||||
@@ -56,6 +57,13 @@ type ListingUploaderDayStatsDTO struct {
|
||||
UploadCount int64 `json:"upload_count"`
|
||||
}
|
||||
|
||||
// ManualEntryAgentStatsDTO 今日客服手动录单统计(按客服聚合)。
|
||||
type ManualEntryAgentStatsDTO struct {
|
||||
AdminID uint64 `json:"admin_id"`
|
||||
AdminName string `json:"admin_name"`
|
||||
Count int64 `json:"count"`
|
||||
}
|
||||
|
||||
type PendingDTO struct {
|
||||
ListingReviews int64 `json:"listing_reviews"`
|
||||
Disputes int64 `json:"disputes"`
|
||||
|
||||
@@ -78,6 +78,10 @@ func (r *Repository) Summary(ctx context.Context) (*DashboardDTO, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
manualEntryToday, err := r.manualEntryToday(ctx, now)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
recentOrders, err := r.recentOrders(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -87,12 +91,13 @@ func (r *Repository) Summary(ctx context.Context) (*DashboardDTO, error) {
|
||||
return nil, err
|
||||
}
|
||||
return &DashboardDTO{
|
||||
Metrics: metrics,
|
||||
Pending: pending,
|
||||
ListingDaily: listingDaily,
|
||||
RecentOrders: recentOrders,
|
||||
RecentDisputes: recentDisputes,
|
||||
GeneratedAt: now,
|
||||
Metrics: metrics,
|
||||
Pending: pending,
|
||||
ListingDaily: listingDaily,
|
||||
ManualEntryToday: manualEntryToday,
|
||||
RecentOrders: recentOrders,
|
||||
RecentDisputes: recentDisputes,
|
||||
GeneratedAt: now,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -348,6 +353,47 @@ func isTradeLeaveEvent(eventType, source string) bool {
|
||||
}
|
||||
}
|
||||
|
||||
// manualEntryToday 统计今日(北京时间自然日)各客服的手动录单数量。
|
||||
// 录单表是后来新增的功能表,若迁移尚未执行(表不存在)则降级为空统计,
|
||||
// 避免连带整个仪表盘不可用。
|
||||
func (r *Repository) manualEntryToday(ctx context.Context, now time.Time) ([]ManualEntryAgentStatsDTO, error) {
|
||||
if r.db == nil || !r.db.Migrator().HasTable("cs_manual_entries") {
|
||||
return []ManualEntryAgentStatsDTO{}, nil
|
||||
}
|
||||
loc := timeutil.ShanghaiLocation()
|
||||
start := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, loc)
|
||||
end := start.AddDate(0, 0, 1)
|
||||
|
||||
type row struct {
|
||||
AdminID uint64
|
||||
AdminName string
|
||||
Count int64
|
||||
}
|
||||
rows := make([]row, 0)
|
||||
if err := r.db.WithContext(ctx).Table("cs_manual_entries").
|
||||
Select("admin_id, MAX(admin_name) AS admin_name, COUNT(*) AS count").
|
||||
Where("created_at >= ? AND created_at < ?", start, end).
|
||||
Group("admin_id").
|
||||
Scan(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sort.Slice(rows, func(i, j int) bool {
|
||||
if rows[i].Count != rows[j].Count {
|
||||
return rows[i].Count > rows[j].Count
|
||||
}
|
||||
return rows[i].AdminName < rows[j].AdminName
|
||||
})
|
||||
items := make([]ManualEntryAgentStatsDTO, 0, len(rows))
|
||||
for _, item := range rows {
|
||||
items = append(items, ManualEntryAgentStatsDTO{
|
||||
AdminID: item.AdminID,
|
||||
AdminName: item.AdminName,
|
||||
Count: item.Count,
|
||||
})
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
func (r *Repository) recentOrders(ctx context.Context) ([]RecentOrderDTO, error) {
|
||||
rows := make([]RecentOrderDTO, 0)
|
||||
err := r.db.WithContext(ctx).Table("rental_orders AS o").
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
package csmanualentry
|
||||
|
||||
import "time"
|
||||
|
||||
// CreateRequest 客服手动录单请求。
|
||||
type CreateRequest struct {
|
||||
EntryNo string `json:"entry_no" binding:"required"`
|
||||
Remark string `json:"remark"`
|
||||
}
|
||||
|
||||
// UpdateRequest 管理员修正录单请求。
|
||||
type UpdateRequest struct {
|
||||
EntryNo string `json:"entry_no" binding:"required"`
|
||||
Remark string `json:"remark"`
|
||||
}
|
||||
|
||||
// EntryDTO 录单记录。
|
||||
type EntryDTO struct {
|
||||
ID uint64 `json:"id"`
|
||||
EntryNo string `json:"entry_no"`
|
||||
AdminID uint64 `json:"admin_id"`
|
||||
AdminName string `json:"admin_name"`
|
||||
AdminUsername string `json:"admin_username"`
|
||||
Remark string `json:"remark"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
// ListQuery 录单查询条件。
|
||||
type ListQuery struct {
|
||||
EntryNo string
|
||||
Keyword string
|
||||
AdminID uint64
|
||||
StartDate string // YYYY-MM-DD(北京时间,闭区间)
|
||||
EndDate string // YYYY-MM-DD(北京时间,闭区间)
|
||||
Page int
|
||||
PageSize int
|
||||
}
|
||||
|
||||
// PaginatedResult 分页结果。
|
||||
type PaginatedResult struct {
|
||||
Items []EntryDTO `json:"items"`
|
||||
Total int64 `json:"total"`
|
||||
Page int `json:"page"`
|
||||
PageSize int `json:"page_size"`
|
||||
}
|
||||
|
||||
// AgentDayStatsDTO 某客服某日录单统计。
|
||||
type AgentDayStatsDTO struct {
|
||||
Date string `json:"date"` // YYYY-MM-DD(北京时间)
|
||||
AdminID uint64 `json:"admin_id"`
|
||||
AdminName string `json:"admin_name"`
|
||||
Count int64 `json:"count"`
|
||||
}
|
||||
|
||||
// CreateResult 录单结果。
|
||||
type CreateResult struct {
|
||||
Entry EntryDTO `json:"entry"`
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package csmanualentry
|
||||
|
||||
import "errors"
|
||||
|
||||
var (
|
||||
ErrDependencyUnavailable = errors.New("dependency unavailable")
|
||||
ErrEntryNoExists = errors.New("manual entry number already exists")
|
||||
ErrEntryNoInvalid = errors.New("entry number is invalid")
|
||||
ErrEntryNotFound = errors.New("manual entry not found")
|
||||
ErrAdminNotFound = errors.New("admin not found")
|
||||
)
|
||||
@@ -0,0 +1,165 @@
|
||||
package csmanualentry
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"hfb_sys/backend/internal/middleware"
|
||||
"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 (h *Handler) Create(c *gin.Context) {
|
||||
adminID, ok := currentAdminID(c)
|
||||
if !ok {
|
||||
response.Unauthorized(c, "缺少管理员上下文")
|
||||
return
|
||||
}
|
||||
var req CreateRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
response.BadRequest(c, "录单参数不正确")
|
||||
return
|
||||
}
|
||||
result, err := h.service.Create(c.Request.Context(), adminID, req)
|
||||
if err != nil {
|
||||
writeManualEntryError(c, err)
|
||||
return
|
||||
}
|
||||
response.Created(c, result)
|
||||
}
|
||||
|
||||
func (h *Handler) List(c *gin.Context) {
|
||||
if _, ok := currentAdminID(c); !ok {
|
||||
response.Unauthorized(c, "缺少管理员上下文")
|
||||
return
|
||||
}
|
||||
page, pageSize := parsePagination(c)
|
||||
query := ListQuery{
|
||||
EntryNo: strings.TrimSpace(c.Query("entry_no")),
|
||||
Keyword: strings.TrimSpace(c.Query("keyword")),
|
||||
StartDate: strings.TrimSpace(c.Query("start_date")),
|
||||
EndDate: strings.TrimSpace(c.Query("end_date")),
|
||||
Page: page,
|
||||
PageSize: pageSize,
|
||||
}
|
||||
if raw := c.Query("admin_id"); raw != "" {
|
||||
adminID, err := strconv.ParseUint(raw, 10, 64)
|
||||
if err != nil {
|
||||
response.BadRequest(c, "客服 ID 不正确")
|
||||
return
|
||||
}
|
||||
query.AdminID = adminID
|
||||
}
|
||||
result, err := h.service.List(c.Request.Context(), query)
|
||||
if err != nil {
|
||||
writeManualEntryError(c, err)
|
||||
return
|
||||
}
|
||||
response.OK(c, result)
|
||||
}
|
||||
|
||||
func (h *Handler) TodayAgentStats(c *gin.Context) {
|
||||
if _, ok := currentAdminID(c); !ok {
|
||||
response.Unauthorized(c, "缺少管理员上下文")
|
||||
return
|
||||
}
|
||||
items, err := h.service.TodayAgentStats(c.Request.Context())
|
||||
if err != nil {
|
||||
writeManualEntryError(c, err)
|
||||
return
|
||||
}
|
||||
response.OK(c, items)
|
||||
}
|
||||
|
||||
func (h *Handler) Update(c *gin.Context) {
|
||||
if _, ok := currentAdminID(c); !ok {
|
||||
response.Unauthorized(c, "缺少管理员上下文")
|
||||
return
|
||||
}
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil || id == 0 {
|
||||
response.BadRequest(c, "ID 不正确")
|
||||
return
|
||||
}
|
||||
var req UpdateRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
response.BadRequest(c, "录单参数不正确")
|
||||
return
|
||||
}
|
||||
entry, err := h.service.Update(c.Request.Context(), id, req)
|
||||
if err != nil {
|
||||
writeManualEntryError(c, err)
|
||||
return
|
||||
}
|
||||
response.OK(c, entry)
|
||||
}
|
||||
|
||||
func (h *Handler) Delete(c *gin.Context) {
|
||||
if _, ok := currentAdminID(c); !ok {
|
||||
response.Unauthorized(c, "缺少管理员上下文")
|
||||
return
|
||||
}
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil || id == 0 {
|
||||
response.BadRequest(c, "ID 不正确")
|
||||
return
|
||||
}
|
||||
if err := h.service.Delete(c.Request.Context(), id); err != nil {
|
||||
writeManualEntryError(c, err)
|
||||
return
|
||||
}
|
||||
response.OK(c, gin.H{"deleted": true})
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
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 writeManualEntryError(c *gin.Context, err error) {
|
||||
response.RecordError(c, err)
|
||||
switch {
|
||||
case errors.Is(err, ErrDependencyUnavailable):
|
||||
response.ServiceUnavailable(c, "数据库未连接")
|
||||
case errors.Is(err, ErrAdminNotFound):
|
||||
response.Unauthorized(c, "客服账号不存在")
|
||||
case errors.Is(err, ErrEntryNoInvalid):
|
||||
response.BadRequest(c, "编号格式不正确")
|
||||
case errors.Is(err, ErrEntryNotFound):
|
||||
response.NotFound(c, "录单记录不存在")
|
||||
case errors.Is(err, ErrEntryNoExists):
|
||||
response.Error(c, http.StatusConflict, "entry_no_exists", "该编号已被登记")
|
||||
default:
|
||||
response.Error(c, http.StatusInternalServerError, "internal_error", "录单服务暂时不可用")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
package csmanualentry
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"hfb_sys/backend/internal/model"
|
||||
"hfb_sys/backend/internal/timeutil"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type Repository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewRepository(db *gorm.DB) *Repository {
|
||||
return &Repository{db: db}
|
||||
}
|
||||
|
||||
// FindAdminSnapshot 读取客服的昵称与登录名,用于录单时绑定快照。
|
||||
func (r *Repository) FindAdminSnapshot(ctx context.Context, adminID uint64) (name, username string, err error) {
|
||||
var admin model.AdminUser
|
||||
if err := r.db.WithContext(ctx).First(&admin, adminID).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return "", "", ErrAdminNotFound
|
||||
}
|
||||
return "", "", err
|
||||
}
|
||||
return admin.Nickname, admin.Username, nil
|
||||
}
|
||||
|
||||
// Create 写入一条录单记录。
|
||||
func (r *Repository) Create(ctx context.Context, adminID uint64, adminName, adminUsername, entryNo, remark string) (*EntryDTO, error) {
|
||||
row := model.CSManualEntry{
|
||||
EntryNo: entryNo,
|
||||
AdminID: adminID,
|
||||
AdminName: adminName,
|
||||
AdminUsername: adminUsername,
|
||||
Remark: remark,
|
||||
}
|
||||
if err := r.db.WithContext(ctx).Create(&row).Error; err != nil {
|
||||
if isDuplicateEntry(err) {
|
||||
return nil, ErrEntryNoExists
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
dto := toDTO(row)
|
||||
return &dto, nil
|
||||
}
|
||||
|
||||
// FindByID 按 ID 查询单条录单记录。
|
||||
func (r *Repository) FindByID(ctx context.Context, id uint64) (*EntryDTO, error) {
|
||||
var row model.CSManualEntry
|
||||
if err := r.db.WithContext(ctx).First(&row, id).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrEntryNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
dto := toDTO(row)
|
||||
return &dto, nil
|
||||
}
|
||||
|
||||
// Update 修正录单的编号与备注。编号唯一冲突返回 ErrEntryNoExists。
|
||||
func (r *Repository) Update(ctx context.Context, id uint64, entryNo, remark string) (*EntryDTO, error) {
|
||||
result := r.db.WithContext(ctx).Model(&model.CSManualEntry{}).
|
||||
Where("id = ?", id).
|
||||
Updates(map[string]any{
|
||||
"entry_no": entryNo,
|
||||
"remark": remark,
|
||||
})
|
||||
if result.Error != nil {
|
||||
if isDuplicateEntry(result.Error) {
|
||||
return nil, ErrEntryNoExists
|
||||
}
|
||||
return nil, result.Error
|
||||
}
|
||||
if result.RowsAffected == 0 {
|
||||
var count int64
|
||||
if err := r.db.WithContext(ctx).Model(&model.CSManualEntry{}).Where("id = ?", id).Count(&count).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if count == 0 {
|
||||
return nil, ErrEntryNotFound
|
||||
}
|
||||
}
|
||||
return r.FindByID(ctx, id)
|
||||
}
|
||||
|
||||
// Delete 删除一条录单记录。
|
||||
func (r *Repository) Delete(ctx context.Context, id uint64) error {
|
||||
result := r.db.WithContext(ctx).Delete(&model.CSManualEntry{}, id)
|
||||
if result.Error != nil {
|
||||
return result.Error
|
||||
}
|
||||
if result.RowsAffected == 0 {
|
||||
return ErrEntryNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// List 按条件分页查询录单记录。
|
||||
func (r *Repository) List(ctx context.Context, query ListQuery) (*PaginatedResult, error) {
|
||||
db := r.db.WithContext(ctx).Model(&model.CSManualEntry{})
|
||||
countDB := r.db.WithContext(ctx).Model(&model.CSManualEntry{})
|
||||
|
||||
if query.EntryNo != "" {
|
||||
db = db.Where("entry_no = ?", query.EntryNo)
|
||||
countDB = countDB.Where("entry_no = ?", query.EntryNo)
|
||||
}
|
||||
if query.AdminID > 0 {
|
||||
db = db.Where("admin_id = ?", query.AdminID)
|
||||
countDB = countDB.Where("admin_id = ?", query.AdminID)
|
||||
}
|
||||
if kw := strings.TrimSpace(query.Keyword); kw != "" {
|
||||
like := "%" + kw + "%"
|
||||
cond := r.db.Where("entry_no LIKE ? OR admin_name LIKE ? OR admin_username LIKE ?", like, like, like)
|
||||
db = db.Where(cond)
|
||||
countDB = countDB.Where(cond)
|
||||
}
|
||||
loc := timeutil.ShanghaiLocation()
|
||||
if query.StartDate != "" {
|
||||
if start, err := parseDay(query.StartDate, loc); err == nil {
|
||||
db = db.Where("created_at >= ?", start)
|
||||
countDB = countDB.Where("created_at >= ?", start)
|
||||
}
|
||||
}
|
||||
if query.EndDate != "" {
|
||||
if end, err := parseDay(query.EndDate, loc); err == nil {
|
||||
next := end.AddDate(0, 0, 1)
|
||||
db = db.Where("created_at < ?", next)
|
||||
countDB = countDB.Where("created_at < ?", next)
|
||||
}
|
||||
}
|
||||
|
||||
var total int64
|
||||
if err := countDB.Count(&total).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
offset := (query.Page - 1) * query.PageSize
|
||||
rows := make([]model.CSManualEntry, 0)
|
||||
if err := db.Order("id DESC").Offset(offset).Limit(query.PageSize).Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items := make([]EntryDTO, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
items = append(items, toDTO(row))
|
||||
}
|
||||
return &PaginatedResult{Items: items, Total: total, Page: query.Page, PageSize: query.PageSize}, nil
|
||||
}
|
||||
|
||||
// TodayAgentStats 统计指定日期(北京时间自然日)各客服的录单量。
|
||||
func (r *Repository) TodayAgentStats(ctx context.Context, day time.Time) ([]AgentDayStatsDTO, error) {
|
||||
loc := timeutil.ShanghaiLocation()
|
||||
start := time.Date(day.Year(), day.Month(), day.Day(), 0, 0, 0, 0, loc)
|
||||
end := start.AddDate(0, 0, 1)
|
||||
|
||||
type row struct {
|
||||
AdminID uint64
|
||||
AdminName string
|
||||
Count int64
|
||||
}
|
||||
rows := make([]row, 0)
|
||||
if err := r.db.WithContext(ctx).Table("cs_manual_entries").
|
||||
Select("admin_id, MAX(admin_name) AS admin_name, COUNT(*) AS count").
|
||||
Where("created_at >= ? AND created_at < ?", start, end).
|
||||
Group("admin_id").
|
||||
Scan(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sort.Slice(rows, func(i, j int) bool {
|
||||
if rows[i].Count != rows[j].Count {
|
||||
return rows[i].Count > rows[j].Count
|
||||
}
|
||||
return rows[i].AdminName < rows[j].AdminName
|
||||
})
|
||||
date := start.Format("2006-01-02")
|
||||
items := make([]AgentDayStatsDTO, 0, len(rows))
|
||||
for _, item := range rows {
|
||||
items = append(items, AgentDayStatsDTO{
|
||||
Date: date,
|
||||
AdminID: item.AdminID,
|
||||
AdminName: item.AdminName,
|
||||
Count: item.Count,
|
||||
})
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
func parseDay(value string, loc *time.Location) (time.Time, error) {
|
||||
return time.ParseInLocation("2006-01-02", value, loc)
|
||||
}
|
||||
|
||||
// isDuplicateEntry 判断错误是否为 entry_no 唯一键冲突。
|
||||
func isDuplicateEntry(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
if errors.Is(err, gorm.ErrDuplicatedKey) {
|
||||
return true
|
||||
}
|
||||
return strings.Contains(err.Error(), "1062")
|
||||
}
|
||||
|
||||
func toDTO(row model.CSManualEntry) EntryDTO {
|
||||
return EntryDTO{
|
||||
ID: row.ID,
|
||||
EntryNo: row.EntryNo,
|
||||
AdminID: row.AdminID,
|
||||
AdminName: row.AdminName,
|
||||
AdminUsername: row.AdminUsername,
|
||||
Remark: row.Remark,
|
||||
CreatedAt: row.CreatedAt,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package csmanualentry
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"hfb_sys/backend/internal/timeutil"
|
||||
)
|
||||
|
||||
const maxEntryNoLength = 64
|
||||
|
||||
type Service struct {
|
||||
repo *Repository
|
||||
}
|
||||
|
||||
func NewService(repo *Repository) *Service {
|
||||
return &Service{repo: repo}
|
||||
}
|
||||
|
||||
// Create 校验编号并落库。客服身份由 handler 从登录上下文注入。
|
||||
func (s *Service) Create(ctx context.Context, adminID uint64, req CreateRequest) (*CreateResult, error) {
|
||||
if s.repo == nil {
|
||||
return nil, ErrDependencyUnavailable
|
||||
}
|
||||
entryNo, err := normalizeEntryNo(req.EntryNo)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
adminName, adminUsername, err := s.repo.FindAdminSnapshot(ctx, adminID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if adminName == "" {
|
||||
adminName = adminUsername
|
||||
}
|
||||
entry, err := s.repo.Create(ctx, adminID, adminName, adminUsername, entryNo, strings.TrimSpace(req.Remark))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &CreateResult{Entry: *entry}, nil
|
||||
}
|
||||
|
||||
// Update 管理员修正录单记录。
|
||||
func (s *Service) Update(ctx context.Context, id uint64, req UpdateRequest) (*EntryDTO, error) {
|
||||
if s.repo == nil {
|
||||
return nil, ErrDependencyUnavailable
|
||||
}
|
||||
entryNo, err := normalizeEntryNo(req.EntryNo)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.repo.Update(ctx, id, entryNo, strings.TrimSpace(req.Remark))
|
||||
}
|
||||
|
||||
// Delete 管理员删除录单记录。
|
||||
func (s *Service) Delete(ctx context.Context, id uint64) error {
|
||||
if s.repo == nil {
|
||||
return ErrDependencyUnavailable
|
||||
}
|
||||
return s.repo.Delete(ctx, id)
|
||||
}
|
||||
|
||||
// List 分页查询录单记录。
|
||||
func (s *Service) List(ctx context.Context, query ListQuery) (*PaginatedResult, error) {
|
||||
if s.repo == nil {
|
||||
return nil, ErrDependencyUnavailable
|
||||
}
|
||||
return s.repo.List(ctx, query)
|
||||
}
|
||||
|
||||
// TodayAgentStats 返回今日(北京时间)各客服录单统计。
|
||||
func (s *Service) TodayAgentStats(ctx context.Context) ([]AgentDayStatsDTO, error) {
|
||||
if s.repo == nil {
|
||||
return nil, ErrDependencyUnavailable
|
||||
}
|
||||
return s.repo.TodayAgentStats(ctx, timeutil.ShanghaiNow())
|
||||
}
|
||||
|
||||
// normalizeEntryNo 去除首尾空白并做基础校验。
|
||||
func normalizeEntryNo(raw string) (string, error) {
|
||||
value := strings.TrimSpace(raw)
|
||||
if value == "" {
|
||||
return "", ErrEntryNoInvalid
|
||||
}
|
||||
if len(value) > maxEntryNoLength {
|
||||
return "", ErrEntryNoInvalid
|
||||
}
|
||||
if strings.ContainsAny(value, " \t\r\n") {
|
||||
return "", ErrEntryNoInvalid
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package csmanualentry
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestNormalizeEntryNo(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
input string
|
||||
want string
|
||||
wantErr error
|
||||
}{
|
||||
{name: "trim", input: " 202610120013 ", want: "202610120013"},
|
||||
{name: "plain", input: "202610120013", want: "202610120013"},
|
||||
{name: "empty", input: " ", wantErr: ErrEntryNoInvalid},
|
||||
{name: "inner space", input: "2026 1001", wantErr: ErrEntryNoInvalid},
|
||||
{name: "too long", input: strings.Repeat("1", 65), wantErr: ErrEntryNoInvalid},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got, err := normalizeEntryNo(tt.input)
|
||||
if !errors.Is(err, tt.wantErr) {
|
||||
t.Fatalf("normalizeEntryNo(%q) error = %v, want %v", tt.input, err, tt.wantErr)
|
||||
}
|
||||
if tt.wantErr == nil && got != tt.want {
|
||||
t.Fatalf("normalizeEntryNo(%q) = %q, want %q", tt.input, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsDuplicateEntry(t *testing.T) {
|
||||
if isDuplicateEntry(nil) {
|
||||
t.Fatal("nil should not be duplicate")
|
||||
}
|
||||
if !isDuplicateEntry(errors.New("Error 1062 (23000): Duplicate entry")) {
|
||||
t.Fatal("1062 error should be duplicate")
|
||||
}
|
||||
if isDuplicateEntry(errors.New("some other error")) {
|
||||
t.Fatal("unrelated error should not be duplicate")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user