feat(manual-entry): 支持筛选及全量导出 CSV
This commit is contained in:
@@ -13,4 +13,5 @@ var (
|
||||
ErrOptionNameInvalid = errors.New("manual entry option name is invalid")
|
||||
ErrOptionExists = errors.New("manual entry option already exists")
|
||||
ErrOptionNotFound = errors.New("manual entry option not found")
|
||||
ErrExportTooLarge = errors.New("manual entry export too large")
|
||||
)
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
package csmanualentry
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/csv"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"hfb_sys/backend/internal/timeutil"
|
||||
)
|
||||
|
||||
var manualEntryExportHeader = []string{
|
||||
"ID",
|
||||
"编号",
|
||||
"组别",
|
||||
"平台",
|
||||
"操作人",
|
||||
"客服",
|
||||
"登录账号",
|
||||
"备注",
|
||||
"登记时间",
|
||||
}
|
||||
|
||||
func buildManualEntryCSV(items []EntryDTO) ([]byte, error) {
|
||||
var buf bytes.Buffer
|
||||
buf.WriteString("\xEF\xBB\xBF")
|
||||
|
||||
writer := csv.NewWriter(&buf)
|
||||
writer.UseCRLF = true
|
||||
if err := writer.Write(manualEntryExportHeader); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, item := range items {
|
||||
record := []string{
|
||||
strconv.FormatUint(item.ID, 10),
|
||||
manualEntryCSVText(item.EntryNo),
|
||||
manualEntryGroupLabel(item.EntryGroup),
|
||||
manualEntryCSVText(item.Platform),
|
||||
manualEntryCSVText(item.Operator),
|
||||
manualEntryCSVText(item.AdminName),
|
||||
manualEntryCSVText(item.AdminUsername),
|
||||
manualEntryCSVText(item.Remark),
|
||||
formatManualEntryCSVTime(item.CreatedAt),
|
||||
}
|
||||
if err := writer.Write(record); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
writer.Flush()
|
||||
if err := writer.Error(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
|
||||
func manualEntryGroupLabel(group string) string {
|
||||
switch group {
|
||||
case EntryGroupCollect:
|
||||
return "收号"
|
||||
case EntryGroupSell:
|
||||
return "出号"
|
||||
default:
|
||||
return group
|
||||
}
|
||||
}
|
||||
|
||||
func manualEntryCSVText(value string) string {
|
||||
if value == "" {
|
||||
return ""
|
||||
}
|
||||
trimmed := strings.TrimLeft(value, " \t\r")
|
||||
if trimmed == "" {
|
||||
return value
|
||||
}
|
||||
switch trimmed[0] {
|
||||
case '=', '+', '-', '@', '\t', '\r':
|
||||
return "'" + value
|
||||
default:
|
||||
return value
|
||||
}
|
||||
}
|
||||
|
||||
func formatManualEntryCSVTime(value time.Time) string {
|
||||
if value.IsZero() {
|
||||
return ""
|
||||
}
|
||||
return value.In(timeutil.ShanghaiLocation()).Format("2006-01-02 15:04:05")
|
||||
}
|
||||
|
||||
func encodeManualEntryExportFilename(filename string) string {
|
||||
var builder strings.Builder
|
||||
for _, value := range []byte(filename) {
|
||||
if (value >= 'a' && value <= 'z') ||
|
||||
(value >= 'A' && value <= 'Z') ||
|
||||
(value >= '0' && value <= '9') ||
|
||||
value == '-' || value == '_' || value == '.' || value == '~' {
|
||||
builder.WriteByte(value)
|
||||
continue
|
||||
}
|
||||
builder.WriteByte('%')
|
||||
builder.WriteString(strings.ToUpper(fmt.Sprintf("%02X", value)))
|
||||
}
|
||||
return builder.String()
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
package csmanualentry
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/csv"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"hfb_sys/backend/internal/database"
|
||||
"hfb_sys/backend/internal/middleware"
|
||||
"hfb_sys/backend/internal/model"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func TestBuildManualEntryCSVUsesExcelFriendlyEncodingAndEscaping(t *testing.T) {
|
||||
createdAt := time.Date(2026, 11, 28, 22, 44, 6, 0, time.FixedZone("CST", 8*60*60))
|
||||
items := []EntryDTO{
|
||||
{
|
||||
ID: 18788,
|
||||
EntryNo: "=202611280470",
|
||||
EntryGroup: EntryGroupSell,
|
||||
Platform: "平台,带逗号",
|
||||
Operator: `操作"人`,
|
||||
AdminName: "潘晓艳",
|
||||
AdminUsername: "panxiaoyan",
|
||||
Remark: "第一行\n第二行",
|
||||
CreatedAt: createdAt,
|
||||
},
|
||||
}
|
||||
|
||||
data, err := buildManualEntryCSV(items)
|
||||
if err != nil {
|
||||
t.Fatalf("buildManualEntryCSV() error = %v", err)
|
||||
}
|
||||
if !bytes.HasPrefix(data, []byte{0xEF, 0xBB, 0xBF}) {
|
||||
t.Fatal("CSV 缺少 UTF-8 BOM")
|
||||
}
|
||||
|
||||
records, err := csv.NewReader(bytes.NewReader(data[3:])).ReadAll()
|
||||
if err != nil {
|
||||
t.Fatalf("解析 CSV 失败: %v", err)
|
||||
}
|
||||
if len(records) != 2 {
|
||||
t.Fatalf("CSV 行数 = %d, want 2", len(records))
|
||||
}
|
||||
if len(records[0]) != len(manualEntryExportHeader) {
|
||||
t.Fatalf("表头列数 = %d, want %d", len(records[0]), len(manualEntryExportHeader))
|
||||
}
|
||||
|
||||
row := records[1]
|
||||
if row[1] != "'=202611280470" {
|
||||
t.Fatalf("编号未转义公式注入: %q", row[1])
|
||||
}
|
||||
if row[2] != "出号" || row[3] != "平台,带逗号" || row[4] != `操作"人` {
|
||||
t.Fatalf("组别/平台/操作人 = %q/%q/%q", row[2], row[3], row[4])
|
||||
}
|
||||
if row[7] != "第一行\n第二行" {
|
||||
t.Fatalf("备注 = %q", row[7])
|
||||
}
|
||||
if row[8] != "2026-11-28 22:44:06" {
|
||||
t.Fatalf("登记时间 = %q", row[8])
|
||||
}
|
||||
}
|
||||
|
||||
func TestServiceExportManualEntriesReusesFilters(t *testing.T) {
|
||||
repo, db := newManualEntryTestRepo(t)
|
||||
ctx := t.Context()
|
||||
|
||||
admin := model.AdminUser{Username: "cs-export", Nickname: "导出客服", PasswordHash: "x"}
|
||||
if err := db.Create(&admin).Error; err != nil {
|
||||
t.Fatalf("创建管理员失败: %v", err)
|
||||
}
|
||||
if _, err := repo.Create(ctx, admin.ID, admin.Nickname, admin.Username, "EXPORT-001", EntryGroupCollect, "网易大神", "客服甲", ""); err != nil {
|
||||
t.Fatalf("创建第一条录单失败: %v", err)
|
||||
}
|
||||
if _, err := repo.Create(ctx, admin.ID, admin.Nickname, admin.Username, "EXPORT-002", EntryGroupSell, "交易猫", "客服乙", ""); err != nil {
|
||||
t.Fatalf("创建第二条录单失败: %v", err)
|
||||
}
|
||||
|
||||
data, rowCount, err := NewService(repo).Export(ctx, ListQuery{Keyword: "网易大神"})
|
||||
if err != nil {
|
||||
t.Fatalf("Export() error = %v", err)
|
||||
}
|
||||
if rowCount != 1 {
|
||||
t.Fatalf("导出行数 = %d, want 1", rowCount)
|
||||
}
|
||||
records, err := csv.NewReader(bytes.NewReader(data[3:])).ReadAll()
|
||||
if err != nil {
|
||||
t.Fatalf("解析导出 CSV 失败: %v", err)
|
||||
}
|
||||
if len(records) != 2 || records[1][1] != "EXPORT-001" {
|
||||
t.Fatalf("筛选导出行 = %#v", records)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyManualEntryFiltersBuildsTenantScopedQuery(t *testing.T) {
|
||||
db := database.NewDryRunDB()
|
||||
queryDB := applyManualEntryFilters(
|
||||
manualEntryTenantScope(
|
||||
manualEntryTenantContext(77),
|
||||
db.Model(&model.CSManualEntry{}),
|
||||
"tenant_id",
|
||||
),
|
||||
ListQuery{
|
||||
EntryNo: "202611280470",
|
||||
EntryGroup: EntryGroupSell,
|
||||
Keyword: "客服",
|
||||
AdminID: 9,
|
||||
StartDate: "2026-11-01",
|
||||
EndDate: "2026-11-29",
|
||||
},
|
||||
)
|
||||
sql := queryDB.ToSQL(func(tx *gorm.DB) *gorm.DB {
|
||||
return tx.Find(&[]model.CSManualEntry{})
|
||||
})
|
||||
|
||||
for _, expected := range []string{
|
||||
"tenant_id = 77",
|
||||
"(entry_no = '202611280470' OR entry_no LIKE '202611280470-%' OR entry_no LIKE '202611280470/%')",
|
||||
"entry_group = 'sell'",
|
||||
"admin_id = 9",
|
||||
"admin_name LIKE '%客服%'",
|
||||
"created_at >= '2026-11-01 00:00:00'",
|
||||
"created_at < '2026-11-30 00:00:00'",
|
||||
} {
|
||||
if !strings.Contains(sql, expected) {
|
||||
t.Fatalf("SQL 缺少条件 %q:\n%s", expected, sql)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandlerExportWritesCSVDownloadResponse(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
repo, db := newManualEntryTestRepo(t)
|
||||
admin := model.AdminUser{Username: "cs-header", Nickname: "导出客服", PasswordHash: "x"}
|
||||
if err := db.Create(&admin).Error; err != nil {
|
||||
t.Fatalf("创建管理员失败: %v", err)
|
||||
}
|
||||
if _, err := repo.Create(t.Context(), admin.ID, admin.Nickname, admin.Username, "HEADER-001", EntryGroupCollect, "", "", ""); err != nil {
|
||||
t.Fatalf("创建录单失败: %v", err)
|
||||
}
|
||||
|
||||
handler := NewHandler(NewService(repo))
|
||||
router := gin.New()
|
||||
router.GET("/export", func(c *gin.Context) {
|
||||
c.Set(middleware.ContextAdminID, admin.ID)
|
||||
handler.Export(c)
|
||||
})
|
||||
|
||||
recorder := httptest.NewRecorder()
|
||||
request := httptest.NewRequest(http.MethodGet, "/export", nil)
|
||||
router.ServeHTTP(recorder, request)
|
||||
|
||||
if recorder.Code != http.StatusOK {
|
||||
t.Fatalf("状态码 = %d, body = %s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
if contentType := recorder.Header().Get("Content-Type"); !strings.HasPrefix(contentType, "text/csv") {
|
||||
t.Fatalf("Content-Type = %q", contentType)
|
||||
}
|
||||
if disposition := recorder.Header().Get("Content-Disposition"); !strings.Contains(disposition, ".csv") {
|
||||
t.Fatalf("Content-Disposition = %q", disposition)
|
||||
}
|
||||
if rowCount := recorder.Header().Get("X-Export-Row-Count"); rowCount != "1" {
|
||||
t.Fatalf("X-Export-Row-Count = %q, want 1", rowCount)
|
||||
}
|
||||
}
|
||||
@@ -2,11 +2,13 @@ package csmanualentry
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"hfb_sys/backend/internal/middleware"
|
||||
"hfb_sys/backend/internal/timeutil"
|
||||
"hfb_sys/backend/pkg/response"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -44,24 +46,13 @@ func (h *Handler) List(c *gin.Context) {
|
||||
response.Unauthorized(c, "缺少管理员上下文")
|
||||
return
|
||||
}
|
||||
query, ok := parseListFilters(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
page, pageSize := parsePagination(c)
|
||||
query := ListQuery{
|
||||
EntryNo: strings.TrimSpace(c.Query("entry_no")),
|
||||
EntryGroup: strings.TrimSpace(c.Query("entry_group")),
|
||||
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
|
||||
}
|
||||
query.Page = page
|
||||
query.PageSize = pageSize
|
||||
result, err := h.service.List(c.Request.Context(), query)
|
||||
if err != nil {
|
||||
writeManualEntryError(c, err)
|
||||
@@ -70,6 +61,33 @@ func (h *Handler) List(c *gin.Context) {
|
||||
response.OK(c, result)
|
||||
}
|
||||
|
||||
// Export 导出客服手动录单 CSV;筛选参数与列表一致,不传筛选条件时导出全部。
|
||||
func (h *Handler) Export(c *gin.Context) {
|
||||
if _, ok := currentAdminID(c); !ok {
|
||||
response.Unauthorized(c, "缺少管理员上下文")
|
||||
return
|
||||
}
|
||||
query, ok := parseListFilters(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
data, rowCount, err := h.service.Export(c.Request.Context(), query)
|
||||
if err != nil {
|
||||
writeManualEntryError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
timestamp := timeutil.ShanghaiNow().Format("20060102-150405")
|
||||
filename := fmt.Sprintf("客服手动录单_%s.csv", timestamp)
|
||||
asciiFilename := fmt.Sprintf("manual-entry-export-%s.csv", timestamp)
|
||||
c.Header(
|
||||
"Content-Disposition",
|
||||
fmt.Sprintf(`attachment; filename="%s"; filename*=UTF-8''%s`, asciiFilename, encodeManualEntryExportFilename(filename)),
|
||||
)
|
||||
c.Header("X-Export-Row-Count", strconv.Itoa(rowCount))
|
||||
c.Data(http.StatusOK, "text/csv; charset=utf-8", data)
|
||||
}
|
||||
|
||||
func (h *Handler) TodayAgentStats(c *gin.Context) {
|
||||
if _, ok := currentAdminID(c); !ok {
|
||||
response.Unauthorized(c, "缺少管理员上下文")
|
||||
@@ -236,6 +254,25 @@ func parsePagination(c *gin.Context) (int, int) {
|
||||
return page, pageSize
|
||||
}
|
||||
|
||||
func parseListFilters(c *gin.Context) (ListQuery, bool) {
|
||||
query := ListQuery{
|
||||
EntryNo: strings.TrimSpace(c.Query("entry_no")),
|
||||
EntryGroup: strings.TrimSpace(c.Query("entry_group")),
|
||||
Keyword: strings.TrimSpace(c.Query("keyword")),
|
||||
StartDate: strings.TrimSpace(c.Query("start_date")),
|
||||
EndDate: strings.TrimSpace(c.Query("end_date")),
|
||||
}
|
||||
if raw := c.Query("admin_id"); raw != "" {
|
||||
adminID, err := strconv.ParseUint(raw, 10, 64)
|
||||
if err != nil {
|
||||
response.BadRequest(c, "客服 ID 不正确")
|
||||
return ListQuery{}, false
|
||||
}
|
||||
query.AdminID = adminID
|
||||
}
|
||||
return query, true
|
||||
}
|
||||
|
||||
func writeManualEntryError(c *gin.Context, err error) {
|
||||
response.RecordError(c, err)
|
||||
switch {
|
||||
@@ -259,6 +296,13 @@ func writeManualEntryError(c *gin.Context, err error) {
|
||||
response.NotFound(c, "选项不存在")
|
||||
case errors.Is(err, ErrOptionExists):
|
||||
response.Error(c, http.StatusConflict, "option_exists", "该选项已存在")
|
||||
case errors.Is(err, ErrExportTooLarge):
|
||||
response.Error(
|
||||
c,
|
||||
http.StatusBadRequest,
|
||||
"manual_entry_export_too_large",
|
||||
fmt.Sprintf("导出数据超过 %d 条,请缩小筛选范围", maxManualEntryExportRows),
|
||||
)
|
||||
default:
|
||||
response.Error(c, http.StatusInternalServerError, "internal_error", "录单服务暂时不可用")
|
||||
}
|
||||
|
||||
@@ -18,6 +18,8 @@ type Repository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
const maxManualEntryExportRows = 50000
|
||||
|
||||
func NewRepository(db *gorm.DB) *Repository {
|
||||
return &Repository{db: db}
|
||||
}
|
||||
@@ -119,52 +121,14 @@ func (r *Repository) Delete(ctx context.Context, id uint64) error {
|
||||
|
||||
// List 按条件分页查询录单记录。
|
||||
func (r *Repository) List(ctx context.Context, query ListQuery) (*PaginatedResult, error) {
|
||||
db := manualEntryTenantScope(ctx, r.db.WithContext(ctx).Model(&model.CSManualEntry{}), "tenant_id")
|
||||
countDB := manualEntryTenantScope(ctx, r.db.WithContext(ctx).Model(&model.CSManualEntry{}), "tenant_id")
|
||||
|
||||
// 编号查询:精确匹配该编号,并同时展示其带后缀的变体(如 202611060124-0、202611060124/1)。
|
||||
if query.EntryNo != "" {
|
||||
base := query.EntryNo
|
||||
dashVariant := base + "-%"
|
||||
slashVariant := base + "/%"
|
||||
cond := r.db.Where(
|
||||
"entry_no = ? OR entry_no LIKE ? OR entry_no LIKE ?",
|
||||
base, dashVariant, slashVariant,
|
||||
)
|
||||
db = db.Where(cond)
|
||||
countDB = countDB.Where(cond)
|
||||
}
|
||||
if query.EntryGroup != "" {
|
||||
db = db.Where("entry_group = ?", query.EntryGroup)
|
||||
countDB = countDB.Where("entry_group = ?", query.EntryGroup)
|
||||
}
|
||||
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 ? OR platform LIKE ? OR operator LIKE ?",
|
||||
like, 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)
|
||||
}
|
||||
}
|
||||
db := applyManualEntryFilters(
|
||||
manualEntryTenantScope(ctx, r.db.WithContext(ctx).Model(&model.CSManualEntry{}), "tenant_id"),
|
||||
query,
|
||||
)
|
||||
countDB := applyManualEntryFilters(
|
||||
manualEntryTenantScope(ctx, r.db.WithContext(ctx).Model(&model.CSManualEntry{}), "tenant_id"),
|
||||
query,
|
||||
)
|
||||
|
||||
var total int64
|
||||
if err := countDB.Count(&total).Error; err != nil {
|
||||
@@ -183,6 +147,65 @@ func (r *Repository) List(ctx context.Context, query ListQuery) (*PaginatedResul
|
||||
return &PaginatedResult{Items: items, Total: total, Page: query.Page, PageSize: query.PageSize}, nil
|
||||
}
|
||||
|
||||
// ListForExport 按列表相同的条件查询全部匹配录单,限制最大导出行数。
|
||||
func (r *Repository) ListForExport(ctx context.Context, query ListQuery) ([]EntryDTO, error) {
|
||||
db := applyManualEntryFilters(
|
||||
manualEntryTenantScope(ctx, r.db.WithContext(ctx).Model(&model.CSManualEntry{}), "tenant_id"),
|
||||
query,
|
||||
)
|
||||
rows := make([]model.CSManualEntry, 0)
|
||||
if err := db.Order("id DESC").Limit(maxManualEntryExportRows + 1).Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(rows) > maxManualEntryExportRows {
|
||||
return nil, ErrExportTooLarge
|
||||
}
|
||||
items := make([]EntryDTO, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
items = append(items, toDTO(row))
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
func applyManualEntryFilters(db *gorm.DB, query ListQuery) *gorm.DB {
|
||||
// 编号查询:精确匹配该编号,并同时展示其带后缀的变体(如 202611060124-0、202611060124/1)。
|
||||
if query.EntryNo != "" {
|
||||
base := query.EntryNo
|
||||
dashVariant := base + "-%"
|
||||
slashVariant := base + "/%"
|
||||
db = db.Where(
|
||||
"entry_no = ? OR entry_no LIKE ? OR entry_no LIKE ?",
|
||||
base, dashVariant, slashVariant,
|
||||
)
|
||||
}
|
||||
if query.EntryGroup != "" {
|
||||
db = db.Where("entry_group = ?", query.EntryGroup)
|
||||
}
|
||||
if query.AdminID > 0 {
|
||||
db = db.Where("admin_id = ?", query.AdminID)
|
||||
}
|
||||
if kw := strings.TrimSpace(query.Keyword); kw != "" {
|
||||
like := "%" + kw + "%"
|
||||
db = db.Where(
|
||||
"entry_no LIKE ? OR admin_name LIKE ? OR admin_username LIKE ? OR platform LIKE ? OR operator LIKE ?",
|
||||
like, like, like, like, like,
|
||||
)
|
||||
}
|
||||
loc := timeutil.ShanghaiLocation()
|
||||
if query.StartDate != "" {
|
||||
if start, err := parseDay(query.StartDate, loc); err == nil {
|
||||
db = db.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)
|
||||
}
|
||||
}
|
||||
return db
|
||||
}
|
||||
|
||||
// TodayAgentStats 统计指定日期(北京时间自然日)各客服的录单量。
|
||||
func (r *Repository) TodayAgentStats(ctx context.Context, day time.Time) ([]AgentDayStatsDTO, error) {
|
||||
loc := timeutil.ShanghaiLocation()
|
||||
|
||||
@@ -96,6 +96,22 @@ func (s *Service) List(ctx context.Context, query ListQuery) (*PaginatedResult,
|
||||
return s.repo.List(ctx, query)
|
||||
}
|
||||
|
||||
// Export 按列表筛选条件生成 CSV;空筛选表示导出全部。
|
||||
func (s *Service) Export(ctx context.Context, query ListQuery) ([]byte, int, error) {
|
||||
if s.repo == nil {
|
||||
return nil, 0, ErrDependencyUnavailable
|
||||
}
|
||||
items, err := s.repo.ListForExport(ctx, query)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
data, err := buildManualEntryCSV(items)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
return data, len(items), nil
|
||||
}
|
||||
|
||||
// TodayAgentStats 返回今日(北京时间)各客服录单统计。
|
||||
func (s *Service) TodayAgentStats(ctx context.Context) ([]AgentDayStatsDTO, error) {
|
||||
if s.repo == nil {
|
||||
|
||||
@@ -847,6 +847,7 @@ func New(cfg config.Config, deps Dependencies, logger *zap.Logger) *gin.Engine {
|
||||
adminRoutes.POST("/manual-entries/options", requirePerm("cs_manual_entry:option_manage"), manualEntryHandler.CreateOption)
|
||||
adminRoutes.PUT("/manual-entries/options/:id", requirePerm("cs_manual_entry:option_manage"), manualEntryHandler.UpdateOption)
|
||||
adminRoutes.DELETE("/manual-entries/options/:id", requirePerm("cs_manual_entry:option_manage"), manualEntryHandler.DeleteOption)
|
||||
adminRoutes.GET("/manual-entries/export", requirePerm("cs_manual_entry:view"), manualEntryHandler.Export)
|
||||
adminRoutes.GET("/manual-entries", requirePerm("cs_manual_entry:view"), manualEntryHandler.List)
|
||||
adminRoutes.POST("/manual-entries", requirePerm("cs_manual_entry:create"), manualEntryHandler.Create)
|
||||
adminRoutes.PUT("/manual-entries/:id", requirePerm("cs_manual_entry:update"), manualEntryHandler.Update)
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const apiClient = vi.hoisted(() => ({
|
||||
get: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/shared/api/client', () => ({ apiClient }))
|
||||
|
||||
import { exportManualEntries } from './adminManualEntry'
|
||||
|
||||
describe('manual entry export API', () => {
|
||||
it('exports filtered rows and reads download metadata', async () => {
|
||||
const blob = new Blob(['csv'])
|
||||
const filename = '客服手动录单_20261129-103000.csv'
|
||||
apiClient.get.mockResolvedValueOnce({
|
||||
data: blob,
|
||||
headers: {
|
||||
'content-disposition': `attachment; filename="manual-entry-export.csv"; filename*=UTF-8''${encodeURIComponent(filename)}`,
|
||||
'x-export-row-count': '3',
|
||||
},
|
||||
})
|
||||
|
||||
await expect(
|
||||
exportManualEntries({
|
||||
entry_no: '202611280470',
|
||||
entry_group: 'sell',
|
||||
keyword: '',
|
||||
start_date: '2026-11-01',
|
||||
end_date: undefined,
|
||||
})
|
||||
).resolves.toEqual({ blob, filename, rowCount: 3 })
|
||||
expect(apiClient.get).toHaveBeenCalledWith('/admin/manual-entries/export', {
|
||||
params: {
|
||||
entry_no: '202611280470',
|
||||
entry_group: 'sell',
|
||||
start_date: '2026-11-01',
|
||||
},
|
||||
responseType: 'blob',
|
||||
timeout: 60000,
|
||||
skipErrorHandler: true,
|
||||
})
|
||||
})
|
||||
|
||||
it('exports all rows when no filters are provided', async () => {
|
||||
apiClient.get.mockResolvedValueOnce({
|
||||
data: new Blob(['csv']),
|
||||
headers: {},
|
||||
})
|
||||
|
||||
await exportManualEntries()
|
||||
|
||||
expect(apiClient.get).toHaveBeenCalledWith('/admin/manual-entries/export', {
|
||||
params: {},
|
||||
responseType: 'blob',
|
||||
timeout: 60000,
|
||||
skipErrorHandler: true,
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,3 +1,5 @@
|
||||
import axios from 'axios'
|
||||
|
||||
import { apiClient } from '@/shared/api/client'
|
||||
|
||||
import type { ApiResponse, PaginatedResult } from '@/shared/types/types'
|
||||
@@ -70,6 +72,12 @@ export interface ManualEntryListQuery {
|
||||
end_date?: string
|
||||
}
|
||||
|
||||
function cleanParams(query: object) {
|
||||
return Object.fromEntries(
|
||||
Object.entries(query).filter(([, value]) => value !== '' && value !== undefined)
|
||||
)
|
||||
}
|
||||
|
||||
export async function fetchManualEntries(
|
||||
page = 1,
|
||||
pageSize = 20,
|
||||
@@ -84,6 +92,48 @@ export async function fetchManualEntries(
|
||||
return data.data
|
||||
}
|
||||
|
||||
export async function exportManualEntries(query: ManualEntryListQuery = {}) {
|
||||
try {
|
||||
const response = await apiClient.get<Blob>('/admin/manual-entries/export', {
|
||||
params: cleanParams(query),
|
||||
responseType: 'blob',
|
||||
timeout: 60000,
|
||||
skipErrorHandler: true,
|
||||
})
|
||||
return {
|
||||
blob: response.data,
|
||||
filename: readExportFilename(response.headers['content-disposition']),
|
||||
rowCount: Number(response.headers['x-export-row-count'] || 0),
|
||||
}
|
||||
} catch (error) {
|
||||
if (axios.isAxiosError(error) && error.response?.data instanceof Blob) {
|
||||
const text = await error.response.data.text()
|
||||
try {
|
||||
const payload = JSON.parse(text) as { message?: unknown }
|
||||
if (typeof payload.message === 'string') {
|
||||
error.message = payload.message
|
||||
}
|
||||
} catch {
|
||||
// 非 JSON 错误响应保留原始 Axios 错误。
|
||||
}
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
function readExportFilename(contentDisposition: unknown) {
|
||||
if (typeof contentDisposition !== 'string') return 'manual-entry-export.csv'
|
||||
const encoded = contentDisposition.match(/filename\*=UTF-8''([^;]+)/i)?.[1]
|
||||
if (encoded) {
|
||||
try {
|
||||
return decodeURIComponent(encoded)
|
||||
} catch {
|
||||
return encoded
|
||||
}
|
||||
}
|
||||
return contentDisposition.match(/filename="?([^";]+)"?/i)?.[1] || 'manual-entry-export.csv'
|
||||
}
|
||||
|
||||
export async function createManualEntry(payload: CreateManualEntryRequest) {
|
||||
const { data } = await apiClient.post<ApiResponse<{ entry: ManualEntryItem }>>(
|
||||
'/admin/manual-entries',
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, reactive, ref } from 'vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { Download } from '@element-plus/icons-vue'
|
||||
|
||||
import {
|
||||
createManualEntry,
|
||||
createManualEntryOption,
|
||||
deleteManualEntry,
|
||||
deleteManualEntryOption,
|
||||
exportManualEntries,
|
||||
fetchManualEntries,
|
||||
fetchManualEntryOptions,
|
||||
updateManualEntry,
|
||||
@@ -88,6 +90,18 @@ function handleEntryOperatorChange(name: string) {
|
||||
}
|
||||
|
||||
const submitting = ref(false)
|
||||
const exporting = ref(false)
|
||||
|
||||
function currentListQuery() {
|
||||
const [startDate, endDate] = filters.dateRange || []
|
||||
return {
|
||||
keyword: filters.keyword || undefined,
|
||||
entry_no: filters.entry_no || undefined,
|
||||
entry_group: filters.entry_group || undefined,
|
||||
start_date: startDate,
|
||||
end_date: endDate,
|
||||
}
|
||||
}
|
||||
|
||||
const {
|
||||
loading,
|
||||
@@ -98,14 +112,7 @@ const {
|
||||
load: loadEntries,
|
||||
} = useAdminPaginatedTable<ManualEntryItem>({
|
||||
fetchFn: (page, pageSize) => {
|
||||
const [startDate, endDate] = filters.dateRange || []
|
||||
return fetchManualEntries(page, pageSize, {
|
||||
keyword: filters.keyword || undefined,
|
||||
entry_no: filters.entry_no || undefined,
|
||||
entry_group: filters.entry_group || undefined,
|
||||
start_date: startDate,
|
||||
end_date: endDate,
|
||||
})
|
||||
return fetchManualEntries(page, pageSize, currentListQuery())
|
||||
},
|
||||
})
|
||||
|
||||
@@ -138,6 +145,32 @@ function applySearch() {
|
||||
void loadEntries()
|
||||
}
|
||||
|
||||
async function handleExportCommand(command: string) {
|
||||
exporting.value = true
|
||||
try {
|
||||
const result = await exportManualEntries(command === 'all' ? {} : currentListQuery())
|
||||
downloadBlob(result.blob, result.filename)
|
||||
ElMessage.success(
|
||||
result.rowCount > 0 ? `已导出 ${result.rowCount} 条录单记录` : '当前条件下暂无录单记录'
|
||||
)
|
||||
} catch (error) {
|
||||
ElMessage.error(readError(error, '导出失败'))
|
||||
} finally {
|
||||
exporting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function downloadBlob(blob: Blob, filename: string) {
|
||||
const url = URL.createObjectURL(blob)
|
||||
const link = document.createElement('a')
|
||||
link.href = url
|
||||
link.download = filename
|
||||
document.body.appendChild(link)
|
||||
link.click()
|
||||
document.body.removeChild(link)
|
||||
URL.revokeObjectURL(url)
|
||||
}
|
||||
|
||||
async function handleCreate() {
|
||||
const entryNo = entryForm.entry_no.trim()
|
||||
if (!entryNo) {
|
||||
@@ -412,6 +445,19 @@ async function handleRemoveOption(item: ManualEntryOption) {
|
||||
</p>
|
||||
</div>
|
||||
<div class="page-header-actions">
|
||||
<el-dropdown
|
||||
trigger="click"
|
||||
:disabled="exporting || loading"
|
||||
@command="handleExportCommand"
|
||||
>
|
||||
<el-button :icon="Download" :loading="exporting">导出 CSV</el-button>
|
||||
<template #dropdown>
|
||||
<el-dropdown-menu>
|
||||
<el-dropdown-item command="filtered">导出筛选结果</el-dropdown-item>
|
||||
<el-dropdown-item command="all">导出全部</el-dropdown-item>
|
||||
</el-dropdown-menu>
|
||||
</template>
|
||||
</el-dropdown>
|
||||
<el-button v-if="canManageOptions" :loading="optionsLoading" @click="openConfig">
|
||||
配置平台/操作人/出款人
|
||||
</el-button>
|
||||
|
||||
Reference in New Issue
Block a user