重构:统一应用服务与基础设施适配边界
将账号、认证、管理员、分析、自动化、卡券、聊天、商品、关键词、设置和订单能力迁移到 application 与 adapter,删除 Server 内对应的旧仓储和业务服务实现,并收紧架构检查。 完善批量发布与订单刷新生命周期、凭证写回、账号任务补偿、订单 reconciliation、通知和敏感数据边界;补充正常、失败、取消、并发、越权及多方言回归测试,并修正 MySQL 延迟任务表的 InnoDB 配置。 修复空卡密响应为 null 时前端加载失败的问题,重建嵌入式前端资产;重写重构总计划,清除历史流水并明确阶段 1 至 10 各对应一次完整迭代和一个 PR。 验证:make check;make test-server-race;npm test/typecheck/comments:check/build;Docker SQLite/MySQL 8.4/PostgreSQL 17 TestMultiDB_*。
This commit is contained in:
1 parent
19a7d5f924
commit
375e84d663
239 files changed
+23870
-7871
No files matched your search
@@ -0,0 +1,246 @@
|
||||
// Package analytics 定义订单分析用例、纯查询模型和消费者侧持久化 Port。
|
||||
// 本包不依赖数据库、HTTP、平台协议或 Server 实现。
|
||||
package analytics
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Query 是订单分析用例使用的用户范围、日期和时区条件。
|
||||
type Query struct {
|
||||
// UserID 是当前登录用户的本地身份标识。
|
||||
UserID int64
|
||||
// StartDate 是用户本地日期范围的起始日期,格式为 YYYY-MM-DD。
|
||||
StartDate string
|
||||
// EndDate 是用户本地日期范围的结束日期,格式为 YYYY-MM-DD。
|
||||
EndDate string
|
||||
// Location 是用于日期边界和按日聚合的用户本地时区。
|
||||
Location *time.Location
|
||||
}
|
||||
|
||||
// Filter 是持久化查询已经转换后的用户、UTC 日期和有效状态条件。
|
||||
type Filter struct {
|
||||
// UserID 是订单所属账号对应的用户身份标识。
|
||||
UserID int64
|
||||
// StartAt 是包含边界的 UTC 起始时间文本;为空表示不限制起始时间。
|
||||
StartAt string
|
||||
// EndBefore 是排除边界的 UTC 结束时间文本;为空表示不限制结束时间。
|
||||
EndBefore string
|
||||
// Statuses 是允许参与统计的订单状态候选集合。
|
||||
Statuses []string
|
||||
}
|
||||
|
||||
// DashboardStats 是用户仪表盘所需的非敏感统计摘要。
|
||||
type DashboardStats struct {
|
||||
// TotalCookies 是用户账号总数。
|
||||
TotalCookies int64
|
||||
// ActiveCookies 是没有明确禁用记录的账号数。
|
||||
ActiveCookies int64
|
||||
// TotalCards 是用户卡密组总数。
|
||||
TotalCards int64
|
||||
// AvailableCardStock 是启用数据卡密组中的非空卡密行数。
|
||||
AvailableCardStock int64
|
||||
// TotalKeywords 是用户关键词规则总数。
|
||||
TotalKeywords int64
|
||||
// TotalOrders 是用户未删除订单总数。
|
||||
TotalOrders int64
|
||||
}
|
||||
|
||||
// RevenueStats 是订单收益聚合结果。
|
||||
type RevenueStats struct {
|
||||
// TotalOrders 是统计范围内的去重订单数。
|
||||
TotalOrders int
|
||||
// TotalAmount 是统计范围内的订单总金额。
|
||||
TotalAmount float64
|
||||
// AvgAmount 是统计范围内的订单平均金额。
|
||||
AvgAmount float64
|
||||
// UniqueBuyers 是统计范围内的去重买家数。
|
||||
UniqueBuyers int
|
||||
// UniqueItems 是统计范围内的去重商品数。
|
||||
UniqueItems int
|
||||
}
|
||||
|
||||
// DailyRecord 是按订单返回的日期聚合原始记录。
|
||||
type DailyRecord struct {
|
||||
// OrderID 是用于保留原有订单计数口径的订单标识。
|
||||
OrderID string
|
||||
// Amount 是数据库中的订单金额文本。
|
||||
Amount string
|
||||
// CreatedAt 是数据库中的订单创建时间文本。
|
||||
CreatedAt string
|
||||
}
|
||||
|
||||
// StatusRecord 是数据库按原始状态聚合的结果。
|
||||
type StatusRecord struct {
|
||||
// Status 是持久化的订单状态文本或数字码。
|
||||
Status string
|
||||
// Count 是该原始状态对应的去重订单数。
|
||||
Count int
|
||||
// Amount 是该原始状态对应的金额合计。
|
||||
Amount float64
|
||||
}
|
||||
|
||||
// CityRecord 是数据库按收货城市聚合的结果。
|
||||
type CityRecord struct {
|
||||
// City 是收货城市名称。
|
||||
City string
|
||||
// Count 是该城市的去重订单数。
|
||||
Count int
|
||||
// Amount 是该城市的金额合计。
|
||||
Amount float64
|
||||
}
|
||||
|
||||
// ItemRecord 是数据库按商品标识聚合的结果。
|
||||
type ItemRecord struct {
|
||||
// ItemID 是平台商品标识。
|
||||
ItemID string
|
||||
// Count 是该商品的去重订单数。
|
||||
Count int
|
||||
// TotalAmount 是该商品的金额合计。
|
||||
TotalAmount float64
|
||||
// AvgAmount 是该商品的平均金额。
|
||||
AvgAmount float64
|
||||
}
|
||||
|
||||
// ValidOrderRecord 是有效订单明细所需的非敏感字段。
|
||||
type ValidOrderRecord struct {
|
||||
// OrderID 是平台订单标识。
|
||||
OrderID string
|
||||
// ItemID 是平台商品标识。
|
||||
ItemID string
|
||||
// ItemTitle 是本地商品标题。
|
||||
ItemTitle string
|
||||
// ItemDetail 是本地商品详情 JSON,用于提取主图地址。
|
||||
ItemDetail string
|
||||
// BuyerID 是买家平台标识。
|
||||
BuyerID string
|
||||
// Quantity 是订单数量文本。
|
||||
Quantity string
|
||||
// Amount 是订单金额文本。
|
||||
Amount string
|
||||
// Status 是持久化的订单状态文本或数字码。
|
||||
Status string
|
||||
// CookieID 是订单所属账号标识。
|
||||
CookieID string
|
||||
// CreatedAt 是订单创建时间文本。
|
||||
CreatedAt string
|
||||
}
|
||||
|
||||
// OrderAnalytics 是订单分析用例的完整结果模型。
|
||||
type OrderAnalytics struct {
|
||||
// RevenueStats 是收益汇总。
|
||||
RevenueStats RevenueStats
|
||||
// DailyStats 是按用户本地日期聚合的结果。
|
||||
DailyStats []DailyStats
|
||||
// StatusStats 是按归一化订单状态聚合的结果。
|
||||
StatusStats []StatusStats
|
||||
// CityStats 是按收货城市聚合的结果。
|
||||
CityStats []CityStats
|
||||
// ItemStats 是按商品标识聚合的结果。
|
||||
ItemStats []ItemStats
|
||||
}
|
||||
|
||||
// DailyStats 是单个本地日期的订单聚合结果。
|
||||
type DailyStats struct {
|
||||
// Date 是用户本地日期。
|
||||
Date string
|
||||
// OrderCount 是该日期的订单数。
|
||||
OrderCount int
|
||||
// Amount 是该日期的金额合计。
|
||||
Amount float64
|
||||
}
|
||||
|
||||
// StatusStats 是单个归一化状态的订单聚合结果。
|
||||
type StatusStats struct {
|
||||
// Status 是归一化后的状态名称。
|
||||
Status string
|
||||
// Count 是该状态的订单数。
|
||||
Count int
|
||||
// Amount 是该状态的金额合计。
|
||||
Amount float64
|
||||
}
|
||||
|
||||
// CityStats 是单个收货城市的订单聚合结果。
|
||||
type CityStats struct {
|
||||
// City 是收货城市名称。
|
||||
City string
|
||||
// OrderCount 是该城市的订单数。
|
||||
OrderCount int
|
||||
// TotalAmount 是该城市的金额合计。
|
||||
TotalAmount float64
|
||||
}
|
||||
|
||||
// ItemStats 是单个商品的订单聚合结果。
|
||||
type ItemStats struct {
|
||||
// ItemID 是平台商品标识。
|
||||
ItemID string
|
||||
// OrderCount 是该商品的订单数。
|
||||
OrderCount int
|
||||
// TotalAmount 是该商品的金额合计。
|
||||
TotalAmount float64
|
||||
// AvgAmount 是该商品的平均金额。
|
||||
AvgAmount float64
|
||||
}
|
||||
|
||||
// ValidOrders 是有效订单分页结果。
|
||||
type ValidOrders struct {
|
||||
// Orders 是当前页的有效订单明细。
|
||||
Orders []ValidOrder
|
||||
// Total 是筛选条件下的有效订单总数。
|
||||
Total int
|
||||
// Page 是当前页码。
|
||||
Page int
|
||||
// PageSize 是当前页大小。
|
||||
PageSize int
|
||||
// Truncated 表示结果是否还有未返回的订单。
|
||||
Truncated bool
|
||||
}
|
||||
|
||||
// ValidOrder 是面向 HTTP 映射的有效订单明细模型。
|
||||
type ValidOrder struct {
|
||||
// OrderID 是平台订单标识。
|
||||
OrderID string
|
||||
// ItemID 是平台商品标识。
|
||||
ItemID string
|
||||
// BuyerID 是买家平台标识。
|
||||
BuyerID string
|
||||
// ItemTitle 是本地商品标题。
|
||||
ItemTitle string
|
||||
// ItemImage 是从商品详情提取的主图地址。
|
||||
ItemImage string
|
||||
// Quantity 是订单数量文本。
|
||||
Quantity string
|
||||
// Amount 是订单金额文本。
|
||||
Amount string
|
||||
// OrderStatus 是兼容字段,值为归一化状态名称。
|
||||
OrderStatus string
|
||||
// Status 是归一化状态名称。
|
||||
Status string
|
||||
// CookieID 是订单所属账号标识。
|
||||
CookieID string
|
||||
// CreatedAt 是订单创建时间文本。
|
||||
CreatedAt string
|
||||
}
|
||||
|
||||
// Repository 定义订单分析用例需要的最小查询能力。
|
||||
type Repository interface {
|
||||
// DashboardStats 返回用户范围内的仪表盘计数。
|
||||
DashboardStats(ctx context.Context, userID int64) (DashboardStats, error)
|
||||
// AvailableCardStock 返回用户启用数据卡密组中的可用卡密行数。
|
||||
AvailableCardStock(ctx context.Context, userID int64) (int64, error)
|
||||
// QueryRevenue 返回收益汇总。
|
||||
QueryRevenue(ctx context.Context, filter Filter) (RevenueStats, error)
|
||||
// QueryDaily 返回订单日期聚合所需的原始记录。
|
||||
QueryDaily(ctx context.Context, filter Filter) ([]DailyRecord, error)
|
||||
// QueryStatus 返回订单状态聚合结果。
|
||||
QueryStatus(ctx context.Context, filter Filter) ([]StatusRecord, error)
|
||||
// QueryCity 返回收货城市聚合结果。
|
||||
QueryCity(ctx context.Context, filter Filter) ([]CityRecord, error)
|
||||
// QueryItem 返回商品聚合结果。
|
||||
QueryItem(ctx context.Context, filter Filter) ([]ItemRecord, error)
|
||||
// CountValidOrders 返回有效订单总数。
|
||||
CountValidOrders(ctx context.Context, filter Filter) (int, error)
|
||||
// ListValidOrders 返回有效订单分页明细。
|
||||
ListValidOrders(ctx context.Context, filter Filter, limit, offset int) ([]ValidOrderRecord, error)
|
||||
}
|
||||
@@ -0,0 +1,375 @@
|
||||
package analytics
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ValidOrderStatuses 是参与订单分析的有效状态候选集合。
|
||||
var ValidOrderStatuses = []string{"pending_ship", "paid", "2", "shipped", "3", "completed", "4", "11"}
|
||||
|
||||
// Stage 标识订单分析失败的查询阶段。
|
||||
type Stage string
|
||||
|
||||
const (
|
||||
// StageRevenue 表示收益汇总查询失败。
|
||||
StageRevenue Stage = "revenue"
|
||||
// StageDaily 表示每日统计查询失败。
|
||||
StageDaily Stage = "daily"
|
||||
// StageStatus 表示状态统计查询失败。
|
||||
StageStatus Stage = "status"
|
||||
// StageCity 表示城市统计查询失败。
|
||||
StageCity Stage = "city"
|
||||
// StageItem 表示商品统计查询失败。
|
||||
StageItem Stage = "item"
|
||||
// StageValidCount 表示有效订单总数查询失败。
|
||||
StageValidCount Stage = "valid_count"
|
||||
// StageValidRows 表示有效订单明细查询失败。
|
||||
StageValidRows Stage = "valid_rows"
|
||||
)
|
||||
|
||||
// StageError 保留查询阶段并包装底层错误,供传输层映射兼容消息。
|
||||
type StageError struct {
|
||||
// Stage 是失败的查询阶段。
|
||||
Stage Stage
|
||||
// Err 是底层查询错误。
|
||||
Err error
|
||||
}
|
||||
|
||||
// Error 返回底层错误文本。
|
||||
func (e *StageError) Error() string {
|
||||
if e == nil || e.Err == nil {
|
||||
return "订单分析查询失败"
|
||||
}
|
||||
return e.Err.Error()
|
||||
}
|
||||
|
||||
// Unwrap 暴露底层查询错误以支持 errors.Is 和 errors.As。
|
||||
func (e *StageError) Unwrap() error {
|
||||
if e == nil {
|
||||
return nil
|
||||
}
|
||||
return e.Err
|
||||
}
|
||||
|
||||
// NewService 构造订单分析应用服务。
|
||||
func NewService(repository Repository) *Service {
|
||||
return &Service{repository: repository}
|
||||
}
|
||||
|
||||
// Service 编排订单分析用例,不感知 HTTP、数据库连接或 Server。
|
||||
type Service struct {
|
||||
// repository 提供订单分析所需的窄查询能力。
|
||||
repository Repository
|
||||
}
|
||||
|
||||
// LocationFromOffset 将浏览器提交的分钟偏移转换为用户时区。
|
||||
func LocationFromOffset(rawOffset string) *time.Location {
|
||||
// offset 是浏览器相对 UTC 的分钟偏移。
|
||||
offset, err := strconv.Atoi(strings.TrimSpace(rawOffset))
|
||||
if err != nil || offset < -14*60 || offset > 14*60 {
|
||||
return time.Local
|
||||
}
|
||||
return time.FixedZone("browser", offset*60)
|
||||
}
|
||||
|
||||
// DateBoundary 将用户本地日期转换为数据库使用的 UTC 边界文本。
|
||||
func DateBoundary(raw string, endExclusive bool, location *time.Location) string {
|
||||
if location == nil {
|
||||
location = time.Local
|
||||
}
|
||||
// parsed 是按用户时区解释后的日期起点。
|
||||
parsed, err := time.ParseInLocation("2006-01-02", strings.TrimSpace(raw), location)
|
||||
if err != nil {
|
||||
return raw
|
||||
}
|
||||
if endExclusive {
|
||||
parsed = parsed.AddDate(0, 0, 1)
|
||||
}
|
||||
return parsed.UTC().Format("2006-01-02 15:04:05")
|
||||
}
|
||||
|
||||
// DashboardStats 查询用户数据概览和可用卡密库存。
|
||||
func (svc *Service) DashboardStats(ctx context.Context, userID int64) (DashboardStats, error) {
|
||||
// stats 是数据库返回的用户范围计数。
|
||||
stats, err := svc.repository.DashboardStats(ctx, userID)
|
||||
if err != nil {
|
||||
return DashboardStats{}, err
|
||||
}
|
||||
// stock 是基础设施按数据卡密组内容计算出的可用库存数量。
|
||||
stock, err := svc.repository.AvailableCardStock(ctx, userID)
|
||||
if err != nil {
|
||||
return DashboardStats{}, err
|
||||
}
|
||||
stats.AvailableCardStock = stock
|
||||
return stats, nil
|
||||
}
|
||||
|
||||
// OrderAnalytics 查询收益及按日、状态、城市和商品维度聚合的订单分析结果。
|
||||
func (svc *Service) OrderAnalytics(ctx context.Context, query Query) (OrderAnalytics, error) {
|
||||
// filter 是按用户本地日期转换后的持久化查询条件。
|
||||
filter := query.filter()
|
||||
// revenue 是收益汇总查询结果。
|
||||
revenue, err := svc.repository.QueryRevenue(ctx, filter)
|
||||
if err != nil {
|
||||
return OrderAnalytics{}, &StageError{Stage: StageRevenue, Err: err}
|
||||
}
|
||||
// dailyRecords 是按订单返回的日期聚合原始记录。
|
||||
dailyRecords, err := svc.repository.QueryDaily(ctx, filter)
|
||||
if err != nil {
|
||||
return OrderAnalytics{}, &StageError{Stage: StageDaily, Err: err}
|
||||
}
|
||||
// dailyMap 按用户本地日期累计订单数量和金额。
|
||||
dailyMap := make(map[string]dailyValue)
|
||||
// record 是当前订单日期聚合原始记录。
|
||||
for _, record := range dailyRecords {
|
||||
// created 是解析后的订单创建时间。
|
||||
created := parseDBTime(record.CreatedAt)
|
||||
if created.IsZero() {
|
||||
continue
|
||||
}
|
||||
if query.Location != nil {
|
||||
created = created.In(query.Location)
|
||||
}
|
||||
// date 是订单在用户时区中的日期。
|
||||
date := created.Format("2006-01-02")
|
||||
// value 是当前日期的累计统计值。
|
||||
value := dailyMap[date]
|
||||
value.count++
|
||||
value.amount += parseAmount(record.Amount)
|
||||
dailyMap[date] = value
|
||||
}
|
||||
// daily 是排序后的按日统计结果。
|
||||
daily := make([]DailyStats, 0, len(dailyMap))
|
||||
// dates 是待输出的日期列表。
|
||||
dates := make([]string, 0, len(dailyMap))
|
||||
// date 是当前待输出的日期键。
|
||||
for date := range dailyMap {
|
||||
dates = append(dates, date)
|
||||
}
|
||||
sort.Strings(dates)
|
||||
// date 是当前输出的日期键。
|
||||
for _, date := range dates {
|
||||
// value 是当前日期的累计统计值。
|
||||
value := dailyMap[date]
|
||||
daily = append(daily, DailyStats{Date: date, OrderCount: value.count, Amount: round2(value.amount)})
|
||||
}
|
||||
|
||||
// statusRecords 是数据库按原始状态返回的聚合结果。
|
||||
statusRecords, err := svc.repository.QueryStatus(ctx, filter)
|
||||
if err != nil {
|
||||
return OrderAnalytics{}, &StageError{Stage: StageStatus, Err: err}
|
||||
}
|
||||
// statusMap 按归一化状态累计数据库聚合结果。
|
||||
statusMap := make(map[string]statusValue)
|
||||
// record 是当前原始状态聚合记录。
|
||||
for _, record := range statusRecords {
|
||||
// status 是兼容数字码转换后的状态名称。
|
||||
status := normalizeStatus(record.Status)
|
||||
// value 是当前状态的累计统计值。
|
||||
value := statusMap[status]
|
||||
value.count += record.Count
|
||||
value.amount += record.Amount
|
||||
statusMap[status] = value
|
||||
}
|
||||
// statusStats 是按订单数量降序排列的状态统计结果。
|
||||
statusStats := make([]StatusStats, 0, len(statusMap))
|
||||
// statusNames 是待排序的状态名称。
|
||||
statusNames := make([]string, 0, len(statusMap))
|
||||
// status 是当前待排序的归一化状态名称。
|
||||
for status := range statusMap {
|
||||
statusNames = append(statusNames, status)
|
||||
}
|
||||
sort.Slice(statusNames, func(i, j int) bool { return statusMap[statusNames[i]].count > statusMap[statusNames[j]].count })
|
||||
// status 是当前输出的归一化状态名称。
|
||||
for _, status := range statusNames {
|
||||
// value 是当前状态的累计统计值。
|
||||
value := statusMap[status]
|
||||
statusStats = append(statusStats, StatusStats{Status: status, Count: value.count, Amount: round2(value.amount)})
|
||||
}
|
||||
|
||||
// cityRecords 是数据库按收货城市返回的聚合结果。
|
||||
cityRecords, err := svc.repository.QueryCity(ctx, filter)
|
||||
if err != nil {
|
||||
return OrderAnalytics{}, &StageError{Stage: StageCity, Err: err}
|
||||
}
|
||||
// cityStats 是收货城市统计结果。
|
||||
cityStats := make([]CityStats, 0, len(cityRecords))
|
||||
// record 是当前收货城市聚合记录。
|
||||
for _, record := range cityRecords {
|
||||
cityStats = append(cityStats, CityStats{City: record.City, OrderCount: record.Count, TotalAmount: round2(record.Amount)})
|
||||
}
|
||||
|
||||
// itemRecords 是数据库按商品返回的聚合结果。
|
||||
itemRecords, err := svc.repository.QueryItem(ctx, filter)
|
||||
if err != nil {
|
||||
return OrderAnalytics{}, &StageError{Stage: StageItem, Err: err}
|
||||
}
|
||||
// itemStats 是商品排行统计结果。
|
||||
itemStats := make([]ItemStats, 0, len(itemRecords))
|
||||
// record 是当前商品聚合记录。
|
||||
for _, record := range itemRecords {
|
||||
itemStats = append(itemStats, ItemStats{ItemID: record.ItemID, OrderCount: record.Count, TotalAmount: round2(record.TotalAmount), AvgAmount: round2(record.AvgAmount)})
|
||||
}
|
||||
return OrderAnalytics{RevenueStats: RevenueStats{
|
||||
TotalOrders: revenue.TotalOrders, TotalAmount: round2(revenue.TotalAmount), AvgAmount: round2(revenue.AvgAmount),
|
||||
UniqueBuyers: revenue.UniqueBuyers, UniqueItems: revenue.UniqueItems,
|
||||
}, DailyStats: daily, StatusStats: statusStats, CityStats: cityStats, ItemStats: itemStats}, nil
|
||||
}
|
||||
|
||||
// ValidOrders 查询有效订单分页明细。
|
||||
func (svc *Service) ValidOrders(ctx context.Context, query Query, page, pageSize int) (ValidOrders, error) {
|
||||
// filter 是按用户本地日期转换后的持久化查询条件。
|
||||
filter := query.filter()
|
||||
// total 是符合筛选条件的有效订单总数。
|
||||
total, err := svc.repository.CountValidOrders(ctx, filter)
|
||||
if err != nil {
|
||||
return ValidOrders{}, &StageError{Stage: StageValidCount, Err: err}
|
||||
}
|
||||
// offset 是当前分页需要跳过的记录数。
|
||||
offset := (page - 1) * pageSize
|
||||
// records 是当前分页的订单明细原始记录。
|
||||
records, err := svc.repository.ListValidOrders(ctx, filter, pageSize, offset)
|
||||
if err != nil {
|
||||
return ValidOrders{}, &StageError{Stage: StageValidRows, Err: err}
|
||||
}
|
||||
// orders 是面向传输层的有效订单明细。
|
||||
orders := make([]ValidOrder, 0, len(records))
|
||||
// record 是当前有效订单原始记录。
|
||||
for _, record := range records {
|
||||
// status 是兼容数字码转换后的状态名称。
|
||||
status := normalizeStatus(record.Status)
|
||||
orders = append(orders, ValidOrder{
|
||||
OrderID: record.OrderID, ItemID: record.ItemID, BuyerID: record.BuyerID, ItemTitle: record.ItemTitle,
|
||||
ItemImage: itemImageFromDetail(record.ItemDetail), Quantity: record.Quantity, Amount: record.Amount,
|
||||
OrderStatus: status, Status: status, CookieID: record.CookieID, CreatedAt: record.CreatedAt,
|
||||
})
|
||||
}
|
||||
return ValidOrders{Orders: orders, Total: total, Page: page, PageSize: pageSize, Truncated: offset+len(orders) < total}, nil
|
||||
}
|
||||
|
||||
// ErrorMessage 将分析失败阶段映射为原有 HTTP 错误消息。
|
||||
func ErrorMessage(err error) string {
|
||||
// stageErr 是带查询阶段的应用服务错误。
|
||||
var stageErr *StageError
|
||||
if !errors.As(err, &stageErr) {
|
||||
return "查询失败"
|
||||
}
|
||||
switch stageErr.Stage {
|
||||
case StageRevenue:
|
||||
return "查询收益统计失败"
|
||||
case StageDaily:
|
||||
return "查询每日统计失败"
|
||||
case StageStatus:
|
||||
return "查询状态统计失败"
|
||||
case StageCity:
|
||||
return "查询城市统计失败"
|
||||
case StageItem:
|
||||
return "查询商品统计失败"
|
||||
default:
|
||||
return "查询失败"
|
||||
}
|
||||
}
|
||||
|
||||
// filter 将用户本地日期查询转换为数据库 UTC 范围并复制状态集合。
|
||||
func (query Query) filter() Filter {
|
||||
// statuses 是固定有效状态的独立副本,避免调用方修改全局集合。
|
||||
statuses := append([]string(nil), ValidOrderStatuses...)
|
||||
return Filter{UserID: query.UserID, StartAt: dateBoundary(query.StartDate, false, query.Location), EndBefore: dateBoundary(query.EndDate, true, query.Location), Statuses: statuses}
|
||||
}
|
||||
|
||||
// dailyValue 保存单个日期的订单数和金额累计值。
|
||||
type dailyValue struct {
|
||||
// count 是当前日期的订单数量。
|
||||
count int
|
||||
// amount 是当前日期的金额累计值。
|
||||
amount float64
|
||||
}
|
||||
|
||||
// statusValue 保存单个归一化状态的订单数和金额累计值。
|
||||
type statusValue struct {
|
||||
// count 是当前状态的订单数量。
|
||||
count int
|
||||
// amount 是当前状态的金额累计值。
|
||||
amount float64
|
||||
}
|
||||
|
||||
// dateBoundary 是内部日期边界转换实现。
|
||||
func dateBoundary(raw string, endExclusive bool, location *time.Location) string {
|
||||
return DateBoundary(raw, endExclusive, location)
|
||||
}
|
||||
|
||||
// parseDBTime 将数据库常见时间文本解析为 UTC 时间。
|
||||
func parseDBTime(raw string) time.Time {
|
||||
// layouts 是支持的数据库时间格式集合。
|
||||
layouts := []string{"2006-01-02 15:04:05", time.RFC3339, "2006-01-02T15:04:05Z07:00"}
|
||||
// layout 是当前尝试的数据库时间格式。
|
||||
for _, layout := range layouts {
|
||||
// parsed 是当前格式尝试得到的时间值。
|
||||
parsed, err := time.ParseInLocation(layout, strings.TrimSpace(raw), time.UTC)
|
||||
if err == nil {
|
||||
return parsed
|
||||
}
|
||||
}
|
||||
return time.Time{}
|
||||
}
|
||||
|
||||
// parseAmount 将订单金额文本转换为数值。
|
||||
func parseAmount(raw string) float64 {
|
||||
// cleaned 是移除货币符号和千分位后的金额文本。
|
||||
cleaned := strings.TrimSpace(strings.NewReplacer("¥", "", ",", "").Replace(raw))
|
||||
// value 是解析后的金额;非法金额按零处理以保持历史统计口径。
|
||||
value, _ := strconv.ParseFloat(cleaned, 64)
|
||||
return value
|
||||
}
|
||||
|
||||
// round2 将金额按两位小数进行四舍五入。
|
||||
func round2(value float64) float64 {
|
||||
return float64(int(value*100+0.5)) / 100
|
||||
}
|
||||
|
||||
// normalizeStatus 将历史数字状态码归一为业务状态名称。
|
||||
func normalizeStatus(status string) string {
|
||||
// normalized 是历史平台数字状态到业务名称的兼容映射。
|
||||
normalized, ok := map[string]string{
|
||||
"paid": "pending_ship", "1": "processing", "2": "pending_ship", "3": "shipped", "4": "completed",
|
||||
"5": "refunding", "6": "cancelled", "7": "refunding", "8": "cancelled", "9": "refunding", "10": "cancelled", "11": "completed", "12": "cancelled",
|
||||
}[status]
|
||||
if ok {
|
||||
return normalized
|
||||
}
|
||||
if status == "" {
|
||||
return "unknown"
|
||||
}
|
||||
return status
|
||||
}
|
||||
|
||||
// itemImageFromDetail 从商品详情 JSON 中提取主图地址。
|
||||
func itemImageFromDetail(detail string) string {
|
||||
if detail == "" {
|
||||
return ""
|
||||
}
|
||||
// payload 是商品详情的动态 JSON 对象。
|
||||
var payload map[string]any
|
||||
if // err 是商品详情 JSON 解析错误。
|
||||
err := json.Unmarshal([]byte(detail), &payload); err != nil {
|
||||
return ""
|
||||
}
|
||||
// picture 是商品详情中的图片信息对象。
|
||||
if picture, ok := payload["pic_info"].(map[string]any); ok {
|
||||
if // url、ok 是图片地址及其类型判断结果。
|
||||
url, ok := picture["picUrl"].(string); ok {
|
||||
return url
|
||||
}
|
||||
}
|
||||
if // url、ok 是兼容图片地址及其类型判断结果。
|
||||
url, ok := payload["item_image"].(string); ok {
|
||||
return url
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -0,0 +1,335 @@
|
||||
package analytics
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// analyticsRepositoryFake 是订单分析应用服务测试使用的可控 Port 实现。
|
||||
type analyticsRepositoryFake struct {
|
||||
// dashboard 保存仪表盘统计结果。
|
||||
dashboard DashboardStats
|
||||
// stock 保存可用卡密库存数量。
|
||||
stock int64
|
||||
// revenue 保存收益聚合结果。
|
||||
revenue RevenueStats
|
||||
// daily 保存日期聚合原始记录。
|
||||
daily []DailyRecord
|
||||
// statuses 保存状态聚合原始记录。
|
||||
statuses []StatusRecord
|
||||
// cities 保存城市聚合原始记录。
|
||||
cities []CityRecord
|
||||
// items 保存商品聚合原始记录。
|
||||
items []ItemRecord
|
||||
// validOrders 保存有效订单原始记录。
|
||||
validOrders []ValidOrderRecord
|
||||
// total 保存有效订单总数。
|
||||
total int
|
||||
// err 保存所有测试 Port 调用返回的错误。
|
||||
err error
|
||||
// dashboardErr 保存仪表盘计数查询错误。
|
||||
dashboardErr error
|
||||
// stockErr 保存卡密库存查询错误。
|
||||
stockErr error
|
||||
// revenueErr 保存收益查询错误。
|
||||
revenueErr error
|
||||
// dailyErr 保存按日查询错误。
|
||||
dailyErr error
|
||||
// statusErr 保存按状态查询错误。
|
||||
statusErr error
|
||||
// cityErr 保存按城市查询错误。
|
||||
cityErr error
|
||||
// itemErr 保存按商品查询错误。
|
||||
itemErr error
|
||||
// countErr 保存有效订单总数查询错误。
|
||||
countErr error
|
||||
// rowsErr 保存有效订单明细查询错误。
|
||||
rowsErr error
|
||||
// receivedFilter 保存最近一次收到的查询条件。
|
||||
receivedFilter Filter
|
||||
// receivedLimit 保存最近一次分页大小。
|
||||
receivedLimit int
|
||||
// receivedOffset 保存最近一次分页偏移。
|
||||
receivedOffset int
|
||||
}
|
||||
|
||||
// DashboardStats 返回预置的仪表盘统计。
|
||||
func (f *analyticsRepositoryFake) DashboardStats(context.Context, int64) (DashboardStats, error) {
|
||||
if f.dashboardErr != nil {
|
||||
return DashboardStats{}, f.dashboardErr
|
||||
}
|
||||
return f.dashboard, f.err
|
||||
}
|
||||
|
||||
// AvailableCardStock 返回预置的可用卡密库存。
|
||||
func (f *analyticsRepositoryFake) AvailableCardStock(context.Context, int64) (int64, error) {
|
||||
if f.stockErr != nil {
|
||||
return 0, f.stockErr
|
||||
}
|
||||
return f.stock, f.err
|
||||
}
|
||||
|
||||
// QueryRevenue 返回预置的收益统计并记录筛选条件。
|
||||
func (f *analyticsRepositoryFake) QueryRevenue(_ context.Context, filter Filter) (RevenueStats, error) {
|
||||
f.receivedFilter = filter
|
||||
if f.revenueErr != nil {
|
||||
return RevenueStats{}, f.revenueErr
|
||||
}
|
||||
return f.revenue, f.err
|
||||
}
|
||||
|
||||
// QueryDaily 返回预置的日期记录。
|
||||
func (f *analyticsRepositoryFake) QueryDaily(context.Context, Filter) ([]DailyRecord, error) {
|
||||
if f.dailyErr != nil {
|
||||
return nil, f.dailyErr
|
||||
}
|
||||
return f.daily, f.err
|
||||
}
|
||||
|
||||
// QueryStatus 返回预置的状态记录。
|
||||
func (f *analyticsRepositoryFake) QueryStatus(context.Context, Filter) ([]StatusRecord, error) {
|
||||
if f.statusErr != nil {
|
||||
return nil, f.statusErr
|
||||
}
|
||||
return f.statuses, f.err
|
||||
}
|
||||
|
||||
// QueryCity 返回预置的城市记录。
|
||||
func (f *analyticsRepositoryFake) QueryCity(context.Context, Filter) ([]CityRecord, error) {
|
||||
if f.cityErr != nil {
|
||||
return nil, f.cityErr
|
||||
}
|
||||
return f.cities, f.err
|
||||
}
|
||||
|
||||
// QueryItem 返回预置的商品记录。
|
||||
func (f *analyticsRepositoryFake) QueryItem(context.Context, Filter) ([]ItemRecord, error) {
|
||||
if f.itemErr != nil {
|
||||
return nil, f.itemErr
|
||||
}
|
||||
return f.items, f.err
|
||||
}
|
||||
|
||||
// CountValidOrders 返回预置的有效订单总数。
|
||||
func (f *analyticsRepositoryFake) CountValidOrders(context.Context, Filter) (int, error) {
|
||||
if f.countErr != nil {
|
||||
return 0, f.countErr
|
||||
}
|
||||
return f.total, f.err
|
||||
}
|
||||
|
||||
// ListValidOrders 返回预置的有效订单记录并记录分页参数。
|
||||
func (f *analyticsRepositoryFake) ListValidOrders(_ context.Context, _ Filter, limit, offset int) ([]ValidOrderRecord, error) {
|
||||
f.receivedLimit = limit
|
||||
f.receivedOffset = offset
|
||||
if f.rowsErr != nil {
|
||||
return nil, f.rowsErr
|
||||
}
|
||||
return f.validOrders, f.err
|
||||
}
|
||||
|
||||
// TestDashboardStatsUsesNarrowStockPort 验证仪表盘只依赖非敏感库存数量 Port。
|
||||
func TestDashboardStatsUsesNarrowStockPort(t *testing.T) {
|
||||
// repository 是带有预置摘要和库存的测试 Port。
|
||||
repository := &analyticsRepositoryFake{dashboard: DashboardStats{TotalCookies: 2, TotalOrders: 5}, stock: 7}
|
||||
// service 是待验证的订单分析应用服务。
|
||||
service := NewService(repository)
|
||||
// result、err 是应用服务返回的仪表盘结果和错误。
|
||||
result, err := service.DashboardStats(context.Background(), 9)
|
||||
if err != nil {
|
||||
t.Fatalf("仪表盘查询失败: %v", err)
|
||||
}
|
||||
if result.TotalCookies != 2 || result.TotalOrders != 5 || result.AvailableCardStock != 7 {
|
||||
t.Fatalf("仪表盘结果异常: %+v", result)
|
||||
}
|
||||
}
|
||||
|
||||
// TestOrderAnalyticsAggregatesAndConvertsLocalDate 验证订单分析聚合和本地日期转换。
|
||||
func TestOrderAnalyticsAggregatesAndConvertsLocalDate(t *testing.T) {
|
||||
// repository 是带有各维度订单记录的测试 Port。
|
||||
repository := &analyticsRepositoryFake{
|
||||
revenue: RevenueStats{TotalOrders: 2, TotalAmount: 12.345, AvgAmount: 6.789, UniqueBuyers: 2, UniqueItems: 1},
|
||||
daily: []DailyRecord{
|
||||
{OrderID: "one", Amount: "¥10.50", CreatedAt: "2026-06-27 16:30:00"},
|
||||
{OrderID: "two", Amount: "abc", CreatedAt: "2026-06-27 17:00:00"},
|
||||
},
|
||||
statuses: []StatusRecord{{Status: "3", Count: 1, Amount: 8.5}, {Status: "shipped", Count: 1, Amount: 2}},
|
||||
cities: []CityRecord{{City: "杭州", Count: 2, Amount: 10.5}},
|
||||
items: []ItemRecord{{ItemID: "item-1", Count: 2, TotalAmount: 10.5, AvgAmount: 5.25}},
|
||||
}
|
||||
// service 是待验证的订单分析应用服务。
|
||||
service := NewService(repository)
|
||||
// location 是 UTC+8 的用户本地时区。
|
||||
location := time.FixedZone("UTC+8", 8*60*60)
|
||||
// result、err 是应用服务返回的完整分析结果和错误。
|
||||
result, err := service.OrderAnalytics(context.Background(), Query{UserID: 7, StartDate: "2026-06-28", EndDate: "2026-06-28", Location: location})
|
||||
if err != nil {
|
||||
t.Fatalf("订单分析失败: %v", err)
|
||||
}
|
||||
if len(result.DailyStats) != 1 || result.DailyStats[0].Date != "2026-06-28" || result.DailyStats[0].Amount != 10.5 {
|
||||
t.Fatalf("日期统计异常: %+v", result.DailyStats)
|
||||
}
|
||||
if len(result.StatusStats) != 1 || result.StatusStats[0].Status != "shipped" || result.StatusStats[0].Count != 2 {
|
||||
t.Fatalf("状态统计异常: %+v", result.StatusStats)
|
||||
}
|
||||
if result.RevenueStats.TotalAmount != 12.35 || result.RevenueStats.AvgAmount != 6.79 {
|
||||
t.Fatalf("收益四舍五入异常: %+v", result.RevenueStats)
|
||||
}
|
||||
if repository.receivedFilter.UserID != 7 || repository.receivedFilter.StartAt != "2026-06-27 16:00:00" || repository.receivedFilter.EndBefore != "2026-06-28 16:00:00" {
|
||||
t.Fatalf("筛选条件异常: %+v", repository.receivedFilter)
|
||||
}
|
||||
}
|
||||
|
||||
// TestValidOrdersMapsLegacyStatusAndPagination 验证有效订单分页保留兼容字段和主图。
|
||||
func TestValidOrdersMapsLegacyStatusAndPagination(t *testing.T) {
|
||||
// repository 是带有数字状态和商品详情的测试 Port。
|
||||
repository := &analyticsRepositoryFake{total: 4, validOrders: []ValidOrderRecord{{
|
||||
OrderID: "order-1", ItemID: "item-1", ItemTitle: "商品", ItemDetail: `{"pic_info":{"picUrl":"https://img.example/1.png"}}`,
|
||||
Status: "3", Amount: "9.90", Quantity: "1", CookieID: "cookie-1",
|
||||
}}}
|
||||
// service 是待验证的订单分析应用服务。
|
||||
service := NewService(repository)
|
||||
// result、err 是应用服务返回的分页结果和错误。
|
||||
result, err := service.ValidOrders(context.Background(), Query{UserID: 1}, 2, 2)
|
||||
if err != nil {
|
||||
t.Fatalf("有效订单查询失败: %v", err)
|
||||
}
|
||||
if result.Page != 2 || result.PageSize != 2 || !result.Truncated || repository.receivedLimit != 2 || repository.receivedOffset != 2 {
|
||||
t.Fatalf("分页结果异常: %+v limit=%d offset=%d", result, repository.receivedLimit, repository.receivedOffset)
|
||||
}
|
||||
if len(result.Orders) != 1 || result.Orders[0].Status != "shipped" || result.Orders[0].OrderStatus != "shipped" || result.Orders[0].ItemImage == "" {
|
||||
t.Fatalf("有效订单映射异常: %+v", result.Orders)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAnalyticsErrorsKeepQueryStage 验证查询失败仍保留阶段错误语义。
|
||||
func TestAnalyticsErrorsKeepQueryStage(t *testing.T) {
|
||||
// expected 是底层测试查询错误。
|
||||
expected := errors.New("query failed")
|
||||
// service 是返回底层错误的订单分析应用服务。
|
||||
service := NewService(&analyticsRepositoryFake{err: expected})
|
||||
// _, err 是收益阶段查询返回的错误。
|
||||
_, err := service.OrderAnalytics(context.Background(), Query{})
|
||||
if !errors.Is(err, expected) || ErrorMessage(err) != "查询收益统计失败" {
|
||||
t.Fatalf("阶段错误异常: err=%v message=%s", err, ErrorMessage(err))
|
||||
}
|
||||
}
|
||||
|
||||
// TestAnalyticsErrorStagesCoverAllQueries 验证每个查询阶段错误都映射为稳定的兼容消息。
|
||||
func TestAnalyticsErrorStagesCoverAllQueries(t *testing.T) {
|
||||
// expected 是每个测试场景共用的底层查询错误。
|
||||
expected := errors.New("stage query failed")
|
||||
// cases 是查询阶段、构造测试 Port 和兼容错误消息的映射表。
|
||||
cases := []struct {
|
||||
// name 是测试场景名称。
|
||||
name string
|
||||
// repository 是注入对应阶段错误的测试 Port。
|
||||
repository *analyticsRepositoryFake
|
||||
// run 是触发当前阶段查询的应用用例调用。
|
||||
run func(*Service) error
|
||||
// message 是原有 HTTP 层需要保持的错误消息。
|
||||
message string
|
||||
}{
|
||||
{name: "daily", repository: &analyticsRepositoryFake{dailyErr: expected}, run: func(service *Service) error {
|
||||
// err 是每日查询阶段返回的错误。
|
||||
_, err := service.OrderAnalytics(context.Background(), Query{})
|
||||
return err
|
||||
}, message: "查询每日统计失败"},
|
||||
{name: "status", repository: &analyticsRepositoryFake{statusErr: expected}, run: func(service *Service) error {
|
||||
// err 是状态查询阶段返回的错误。
|
||||
_, err := service.OrderAnalytics(context.Background(), Query{})
|
||||
return err
|
||||
}, message: "查询状态统计失败"},
|
||||
{name: "city", repository: &analyticsRepositoryFake{cityErr: expected}, run: func(service *Service) error {
|
||||
// err 是城市查询阶段返回的错误。
|
||||
_, err := service.OrderAnalytics(context.Background(), Query{})
|
||||
return err
|
||||
}, message: "查询城市统计失败"},
|
||||
{name: "item", repository: &analyticsRepositoryFake{itemErr: expected}, run: func(service *Service) error {
|
||||
// err 是商品查询阶段返回的错误。
|
||||
_, err := service.OrderAnalytics(context.Background(), Query{})
|
||||
return err
|
||||
}, message: "查询商品统计失败"},
|
||||
{name: "valid-count", repository: &analyticsRepositoryFake{countErr: expected}, run: func(service *Service) error {
|
||||
// err 是有效订单总数查询阶段返回的错误。
|
||||
_, err := service.ValidOrders(context.Background(), Query{}, 1, 10)
|
||||
return err
|
||||
}, message: "查询失败"},
|
||||
{name: "valid-rows", repository: &analyticsRepositoryFake{rowsErr: expected}, run: func(service *Service) error {
|
||||
// err 是有效订单明细查询阶段返回的错误。
|
||||
_, err := service.ValidOrders(context.Background(), Query{}, 1, 10)
|
||||
return err
|
||||
}, message: "查询失败"},
|
||||
}
|
||||
// item 是当前遍历的阶段错误场景。
|
||||
for _, item := range cases {
|
||||
t.Run(item.name, func(t *testing.T) {
|
||||
// err 是当前阶段用例返回的错误。
|
||||
err := item.run(NewService(item.repository))
|
||||
if !errors.Is(err, expected) || ErrorMessage(err) != item.message {
|
||||
t.Fatalf("阶段错误异常: err=%v message=%s", err, ErrorMessage(err))
|
||||
}
|
||||
})
|
||||
}
|
||||
// dashboardCases 是仪表盘两个查询阶段的错误场景。
|
||||
dashboardCases := []struct {
|
||||
// name 是测试场景名称。
|
||||
name string
|
||||
// repository 是注入错误的测试 Port。
|
||||
repository *analyticsRepositoryFake
|
||||
}{
|
||||
{name: "dashboard-count", repository: &analyticsRepositoryFake{dashboardErr: expected}},
|
||||
{name: "dashboard-stock", repository: &analyticsRepositoryFake{stockErr: expected}},
|
||||
}
|
||||
// item 是当前遍历的仪表盘错误场景。
|
||||
for _, item := range dashboardCases {
|
||||
t.Run(item.name, func(t *testing.T) {
|
||||
// err 是当前仪表盘用例返回的错误。
|
||||
_, err := NewService(item.repository).DashboardStats(context.Background(), 1)
|
||||
if !errors.Is(err, expected) {
|
||||
t.Fatalf("仪表盘错误未保留: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestAnalyticsCompatibilityHelpersCoverFallbacks 验证日期、状态和商品图片兼容回退。
|
||||
func TestAnalyticsCompatibilityHelpersCoverFallbacks(t *testing.T) {
|
||||
// location 是边界转换使用的测试时区。
|
||||
location := time.FixedZone("UTC+8", 8*60*60)
|
||||
if // got 是非法起始日期回退后的原始文本。
|
||||
got := DateBoundary("invalid", false, location); got != "invalid" {
|
||||
t.Fatalf("非法日期应保留原文本: %q", got)
|
||||
}
|
||||
if // got 是非法偏移回退后的本地时区。
|
||||
got := LocationFromOffset("invalid"); got != time.Local {
|
||||
t.Fatalf("非法时区偏移应回退本地时区: %v", got)
|
||||
}
|
||||
if // got 是空状态归一后的未知状态名称。
|
||||
got := normalizeStatus(""); got != "unknown" || normalizeStatus("custom") != "custom" {
|
||||
t.Fatalf("状态回退异常: empty=%q custom=%q", got, normalizeStatus("custom"))
|
||||
}
|
||||
// repository 是带有兼容图片字段的测试 Port。
|
||||
repository := &analyticsRepositoryFake{total: 1, validOrders: []ValidOrderRecord{{OrderID: "fallback", ItemDetail: `{"item_image":"https://img.example/fallback.png"}`}}}
|
||||
// result、err 是兼容图片字段映射结果和错误。
|
||||
result, err := NewService(repository).ValidOrders(context.Background(), Query{}, 1, 1)
|
||||
if err != nil || len(result.Orders) != 1 || result.Orders[0].ItemImage == "" {
|
||||
t.Fatalf("兼容图片回退异常: result=%+v err=%v", result, err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDateBoundaryConvertsLocalDayToUTC 验证用户本地日期边界转换为 UTC 文本。
|
||||
func TestDateBoundaryConvertsLocalDayToUTC(t *testing.T) {
|
||||
// location 是 UTC+8 的测试时区。
|
||||
location := time.FixedZone("UTC+8", 8*60*60)
|
||||
if // got 是起始日期转换后的 UTC 边界。
|
||||
got := DateBoundary("2026-06-28", false, location); got != "2026-06-27 16:00:00" {
|
||||
t.Fatalf("起始边界=%q", got)
|
||||
}
|
||||
if // got 是结束日期转换后的 UTC 边界。
|
||||
got := DateBoundary("2026-06-28", true, location); got != "2026-06-28 16:00:00" {
|
||||
t.Fatalf("结束边界=%q", got)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user