迁移订单更新应用服务

This commit is contained in:
Christ committed 2026-08-15 17:04:48 +08:00
1 parent 67a12ff53a
commit b1e62b7bef
6 files changed
+436 -84

No files matched your search

@@ -750,3 +750,4 @@ npm --prefix frontend run build
| 2026-08-15 | P1 调度器与通知 worker 关闭上下文切片 | 已完成 | 自动化调度器、续期调度器和通知 outbox worker 新增 `WaitContext`;`cmd/server` 在同一个 10 秒关闭 Context 内等待 HTTP、后台 worker、调度器、账号和通知,并将 `stopCancel` 延后到全部等待结束,避免使用已取消 Context;补充三个 worker 超时/完成回归测试,相关包测试和中文注释门禁通过。Engine 内部任务等待、平台浏览器关闭和生命周期统一清单仍待继续治理,阶段 5 保持“进行中” |
| 2026-08-15 | P1 订单列表应用服务迁移切片 | 已完成 | 新增 `internal/application/orders.ListService`、纯业务 `ListQuery/ListResult` 和窄 `ListRepository`;分页规范化、账号所有权校验和列表查询从 `internal/server/order_service.go` 迁入应用层,Server 仅负责 DTO 转换和兼容错误映射;新增应用层分页/跨用户/存储错误测试,Server 列表与订单服务回归、架构门禁和中文注释门禁通过。订单详情、更新、导入、手动发货、刷新等用例仍在 Server,阶段 4/8/9 保持“进行中” |
| 2026-08-15 | P1 订单详情应用服务迁移切片 | 已完成 | 新增 `internal/application/orders.DetailService`、`DetailResult` 和窄 `DetailRepository`;订单详情读取、账号所有权校验和商品补全从 `internal/server/order_service.go` 迁入应用层,Server 仅负责兼容错误映射与 DTO 转换;新增跨用户、不存在订单、商品读取失败保留订单主体测试,订单/Server 回归、架构门禁和中文注释门禁通过。订单更新、导入、手动发货、刷新等用例仍在 Server,阶段 4/8/9 保持“进行中” |
| 2026-08-15 | P1 订单更新应用服务迁移切片 | 已完成 | 新增 `internal/application/orders.UpdateService`、`UpdateRequest`、`UpdateRepository` 和 `ValidationError`;订单所有权、状态/金额归一化、商品标题约束及订单+商品事务写入从 `internal/server/order_service.go` 迁入纯应用层,Server 仅负责 HTTP DTO 转换和旧错误分类映射;新增更新成功、非法字段、无权/不存在/存储错误测试,订单/应用定向测试、架构门禁和中文注释门禁通过。订单删除、导入、手动发货、刷新以及其他领域应用服务仍未迁移,阶段 4/8/9 保持“进行中” |
@@ -0,0 +1,241 @@
package orders
import (
"context"
"errors"
"fmt"
"math"
"regexp"
"strconv"
"strings"
)
// UpdateRequest 描述订单更新用例允许修改的字段。
type UpdateRequest struct {
// OrderStatus 是订单状态补丁。
OrderStatus *string
// ItemID 是商品标识补丁。
ItemID *string
// BuyerID 是买家标识补丁。
BuyerID *string
// SpecName 是规格名称补丁。
SpecName *string
// SpecValue 是规格值补丁。
SpecValue *string
// Quantity 是购买数量补丁。
Quantity *string
// Amount 是订单金额补丁。
Amount *string
// ReceiverName 是收货人补丁。
ReceiverName *string
// ReceiverPhone 是收货电话补丁。
ReceiverPhone *string
// ReceiverAddress 是收货地址补丁。
ReceiverAddress *string
// ReceiverCity 是收货城市补丁。
ReceiverCity *string
// ChatID 是聊天会话补丁。
ChatID *string
// SystemShipped 表示是否由系统完成发货。
SystemShipped *bool
// ItemTitle 是关联商品标题补丁。
ItemTitle *string
}
// UpdateRepository 定义订单更新用例所需的最小持久化能力。
type UpdateRepository interface {
// ExistsOwned 判断订单绑定的账号是否归属于当前用户。
ExistsOwned(ctx context.Context, userID int64, cookieID string) (bool, error)
// GetOrder 读取待更新的订单实体。
GetOrder(ctx context.Context, orderID string) (*Order, error)
// WithTransaction 在单个事务中提交订单及商品更新。
WithTransaction(ctx context.Context, work func(Writer) error) error
}
// ValidationError 表示请求字段不满足订单业务约束。
type ValidationError struct {
// Message 是返回给上层适配器的稳定错误信息。
Message string
}
// Error 返回字段校验错误文本。
func (e *ValidationError) Error() string {
if e == nil {
return "订单字段校验失败"
}
return e.Message
}
// NewValidationError 创建订单字段校验错误。
func NewValidationError(message string) error {
return &ValidationError{Message: message}
}
// UpdateService 承载订单更新的所有权、字段校验和事务规则。
type UpdateService struct {
// repository 保存订单更新用例所需的窄数据访问 Port。
repository UpdateRepository
}
// NewUpdateService 创建订单更新应用服务。
func NewUpdateService(repository UpdateRepository) *UpdateService {
return &UpdateService{repository: repository}
}
// Update 校验订单归属并在单事务内更新订单及可选商品标题。
func (s *UpdateService) Update(ctx context.Context, userID int64, orderID string, request UpdateRequest) error {
if s == nil || s.repository == nil {
return errors.New("订单更新 repository 未初始化")
}
// order 保存待更新订单主体。
order, err := s.repository.GetOrder(ctx, orderID)
if err != nil {
return err
}
if order == nil {
return ErrNotFound
}
if strings.TrimSpace(order.CookieID) == "" {
return ErrForbidden
}
// owned 保存订单账号归属校验结果。
owned, err := s.repository.ExistsOwned(ctx, userID, order.CookieID)
if err != nil {
return err
}
if !owned {
return ErrForbidden
}
// err 保存更新请求字段校验错误。
if err := normalizeUpdateRequest(&request); err != nil {
return err
}
// finalItemID 保存更新后订单关联的商品标识。
finalItemID := strings.TrimSpace(order.ItemID)
if request.ItemID != nil {
finalItemID = strings.TrimSpace(*request.ItemID)
request.ItemID = &finalItemID
}
// itemTitle 保存规范化后的商品标题。
itemTitle := ""
if request.ItemTitle != nil {
itemTitle = strings.TrimSpace(*request.ItemTitle)
if itemTitle == "" || finalItemID == "" {
return NewValidationError("商品标题不能为空且订单必须关联商品")
}
request.ItemTitle = &itemTitle
}
return s.repository.WithTransaction(ctx, func(writer Writer) error {
// patch 保存订单字段更新集合。
patch := OrderPatch{
OrderStatus: request.OrderStatus, ItemID: request.ItemID, BuyerID: request.BuyerID,
SpecName: request.SpecName, SpecValue: request.SpecValue, Quantity: request.Quantity,
Amount: request.Amount, ReceiverName: request.ReceiverName, ReceiverPhone: request.ReceiverPhone,
ReceiverAddress: request.ReceiverAddress, ReceiverCity: request.ReceiverCity, ChatID: request.ChatID,
SystemShipped: request.SystemShipped,
}
// err 保存订单补丁写入错误。
if err := writer.PatchOrder(ctx, orderID, patch); err != nil {
return err
}
if request.ItemTitle == nil {
return nil
}
// err 保存商品标题写入错误。
if err := writer.UpsertItemBasic(ctx, ItemWrite{CookieID: order.CookieID, ItemID: finalItemID, ItemTitle: itemTitle}); err != nil {
return fmt.Errorf("更新商品标题失败: %w", err)
}
return nil
})
}
// normalizeUpdateRequest 规范化状态和金额,并拒绝不合法的更新字段。
func normalizeUpdateRequest(request *UpdateRequest) error {
if request == nil {
return NewValidationError("订单更新请求不能为空")
}
if request.OrderStatus != nil {
// normalized 保存规范化后的订单状态。
normalized := NormalizeOrderStatus(strings.TrimSpace(*request.OrderStatus))
if !ValidEditableOrderStatus(normalized) {
return NewValidationError("不支持的订单状态")
}
request.OrderStatus = &normalized
}
if request.Amount != nil {
// normalized 保存规范化后的订单金额。
normalized, ok := NormalizeOrderAmount(*request.Amount)
if !ok {
return NewValidationError("订单金额必须是普通格式的非负有限数字")
}
request.Amount = &normalized
}
return nil
}
// orderAmountPattern 匹配不带千位分隔符的非负金额。
var orderAmountPattern = regexp.MustCompile(`^[0-9]+(?:\.[0-9]+)?$`)
// groupedOrderAmountPattern 匹配带千位分隔符的非负金额。
var groupedOrderAmountPattern = regexp.MustCompile(`^[0-9]{1,3}(?:,[0-9]{3})+(?:\.[0-9]+)?$`)
// NormalizeOrderAmount 把货币符号和千位分隔符规范为十进制金额文本。
func NormalizeOrderAmount(raw string) (string, bool) {
raw = strings.TrimSpace(raw)
if strings.HasPrefix(raw, "¥") {
raw = strings.TrimSpace(strings.TrimPrefix(raw, "¥"))
} else if strings.HasPrefix(raw, "¥") {
raw = strings.TrimSpace(strings.TrimPrefix(raw, "¥"))
}
if raw == "" {
return "", true
}
if strings.Contains(raw, ",") {
if !groupedOrderAmountPattern.MatchString(raw) {
return "", false
}
raw = strings.ReplaceAll(raw, ",", "")
} else if !orderAmountPattern.MatchString(raw) {
return "", false
}
// value 保存解析后的金额数值,用于拒绝 NaN 和无穷大。
value, err := strconv.ParseFloat(raw, 64)
if err != nil || math.IsInf(value, 0) || math.IsNaN(value) {
return "", false
}
return raw, true
}
// NormalizeOrderStatus 将平台数字状态码归一为订单文本状态。
func NormalizeOrderStatus(status string) string {
switch status {
case "paid":
return "pending_ship"
case "1":
return "processing"
case "2":
return "pending_ship"
case "3":
return "shipped"
case "4", "11":
return "completed"
case "5", "7", "9":
return "refunding"
case "6", "8", "10", "12":
return "cancelled"
case "":
return "unknown"
default:
return status
}
}
// ValidEditableOrderStatus 判断订单状态是否允许通过更新接口修改。
func ValidEditableOrderStatus(status string) bool {
switch status {
case "processing", "pending_ship", "shipped", "completed", "cancelled", "refunding":
return true
default:
return false
}
}
@@ -0,0 +1,164 @@
package orders
import (
"context"
"errors"
"testing"
)
// updateRepositoryFake 是订单更新应用服务测试使用的内存 repository。
type updateRepositoryFake struct {
// order 保存待更新订单。
order *Order
// owned 表示订单账号是否属于当前用户。
owned bool
// getErr 保存订单读取错误。
getErr error
// ownedErr 保存账号归属查询错误。
ownedErr error
// txErr 保存事务执行错误。
txErr error
// writer 保存事务回调收到的内存写入器。
writer *updateWriterFake
}
// GetOrder 返回测试订单。
func (f *updateRepositoryFake) GetOrder(context.Context, string) (*Order, error) {
return f.order, f.getErr
}
// ExistsOwned 返回测试账号归属结果。
func (f *updateRepositoryFake) ExistsOwned(context.Context, int64, string) (bool, error) {
return f.owned, f.ownedErr
}
// WithTransaction 执行测试事务回调并记录写入内容。
func (f *updateRepositoryFake) WithTransaction(ctx context.Context, work func(Writer) error) error {
if f.txErr != nil {
return f.txErr
}
// writer 保存当前测试事务的写入器。
f.writer = &updateWriterFake{}
return work(f.writer)
}
// updateWriterFake 是订单更新应用服务测试使用的事务写入器。
type updateWriterFake struct {
// orderID 保存被更新的订单标识。
orderID string
// patch 保存收到的订单补丁。
patch OrderPatch
// item 保存收到的商品写入。
item ItemWrite
// patchErr 保存订单补丁错误。
patchErr error
// itemErr 保存商品写入错误。
itemErr error
}
// PatchOrder 记录测试订单补丁。
func (f *updateWriterFake) PatchOrder(_ context.Context, orderID string, patch OrderPatch) error {
f.orderID = orderID
f.patch = patch
return f.patchErr
}
// UpsertItemBasic 记录测试商品写入。
func (f *updateWriterFake) UpsertItemBasic(_ context.Context, item ItemWrite) error {
f.item = item
return f.itemErr
}
// UpsertOrder 满足订单事务写入器接口的测试兼容方法。
func (f *updateWriterFake) UpsertOrder(context.Context, string, UpsertOptions) error {
return nil
}
// TestUpdateServiceNormalizesAndWrites 验证订单更新会规范字段并写入同一事务。
func TestUpdateServiceNormalizesAndWrites(t *testing.T) {
// repository 保存本用例使用的内存依赖。
repository := &updateRepositoryFake{order: &Order{OrderID: "order-1", CookieID: "cookie-1", ItemID: "item-1"}, owned: true}
// service 保存待测试的订单更新服务。
service := NewUpdateService(repository)
// status 保存待更新的订单状态。
status := " 2 "
// amount 保存待更新的订单金额。
amount := "¥1,234.50"
// itemID 保存待更新的商品标识。
itemID := " item-2 "
// itemTitle 保存待更新的商品标题。
itemTitle := " 新标题 "
// err 保存订单更新结果。
if err := service.Update(context.Background(), 7, "order-1", UpdateRequest{
OrderStatus: &status, Amount: &amount, ItemID: &itemID, ItemTitle: &itemTitle,
}); err != nil {
t.Fatalf("更新订单失败: %v", err)
}
if repository.writer == nil || repository.writer.patch.OrderStatus == nil || *repository.writer.patch.OrderStatus != "pending_ship" {
t.Fatalf("订单状态未规范化: %+v", repository.writer)
}
if repository.writer.patch.Amount == nil || *repository.writer.patch.Amount != "1234.50" {
t.Fatalf("订单金额未规范化: %+v", repository.writer.patch)
}
if repository.writer.patch.ItemID == nil || *repository.writer.patch.ItemID != "item-2" {
t.Fatalf("商品标识未规范化: %+v", repository.writer.patch)
}
if repository.writer.item.ItemID != "item-2" || repository.writer.item.ItemTitle != "新标题" {
t.Fatalf("商品标题写入异常: %+v", repository.writer.item)
}
}
// TestUpdateServiceRejectsInvalidFields 验证订单状态、金额和商品标题校验。
func TestUpdateServiceRejectsInvalidFields(t *testing.T) {
// cases 保存非法字段测试表。
cases := []struct {
// name 是测试场景名称。
name string
// request 是待校验的更新请求。
request UpdateRequest
}{
{name: "invalid status", request: UpdateRequest{OrderStatus: stringPointer("unknown-status")}},
{name: "invalid amount", request: UpdateRequest{Amount: stringPointer("12x")}},
{name: "empty item title", request: UpdateRequest{ItemTitle: stringPointer(" ")}},
}
// testCase 表示当前字段校验场景。
for _, testCase := range cases {
t.Run(testCase.name, func(t *testing.T) {
// service 保存当前场景的订单更新服务。
service := NewUpdateService(&updateRepositoryFake{order: &Order{CookieID: "cookie-1", ItemID: "item-1"}, owned: true})
// err 保存字段校验结果。
err := service.Update(context.Background(), 7, "order-1", testCase.request)
// validationErr 保存可识别的字段校验错误。
var validationErr *ValidationError
if !errors.As(err, &validationErr) {
t.Fatalf("错误类型不正确: %v", err)
}
})
}
}
// TestUpdateServiceOwnershipAndReadErrors 验证订单不存在、无权和存储错误边界。
func TestUpdateServiceOwnershipAndReadErrors(t *testing.T) {
// notFoundService 保存订单不存在场景的应用服务。
notFoundService := NewUpdateService(&updateRepositoryFake{})
if !errors.Is(notFoundService.Update(context.Background(), 1, "missing", UpdateRequest{}), ErrNotFound) {
t.Fatal("订单不存在时未返回 ErrNotFound")
}
// forbiddenService 保存账号无权场景的应用服务。
forbiddenService := NewUpdateService(&updateRepositoryFake{order: &Order{CookieID: "cookie-1"}})
if !errors.Is(forbiddenService.Update(context.Background(), 1, "order-1", UpdateRequest{}), ErrForbidden) {
t.Fatal("账号无权时未返回 ErrForbidden")
}
// expectedErr 保存底层存储错误。
expectedErr := errors.New("读取失败")
// failedService 保存存储错误场景的应用服务。
failedService := NewUpdateService(&updateRepositoryFake{getErr: expectedErr})
if !errors.Is(failedService.Update(context.Background(), 1, "order-1", UpdateRequest{}), expectedErr) {
t.Fatal("存储错误未透传")
}
}
// stringPointer 返回测试使用的字符串指针。
func stringPointer(value string) *string {
return &value
}
+1 -1
View File
@@ -21,7 +21,7 @@ func newApplicationServices(server *Server) *applicationServices {
// orderRepository 保存订单应用服务共享的基础设施适配器。
orderRepository := newStoreOrderRepository(server.Store)
return &applicationServices{
orders: &orderApplicationService{server: newServerOrderRuntime(server), repository: orderRepository, list: orderapp.NewListService(orderRepository), detail: orderapp.NewDetailService(orderRepository), refreshJobs: newStoreOrderRefreshJobRepository(server.Store)},
orders: &orderApplicationService{server: newServerOrderRuntime(server), repository: orderRepository, list: orderapp.NewListService(orderRepository), detail: orderapp.NewDetailService(orderRepository), update: orderapp.NewUpdateService(orderRepository), refreshJobs: newStoreOrderRefreshJobRepository(server.Store)},
itemPublish: &itemPublishService{server: server, repository: newStoreItemPublishRepository(server.Store)},
accountLogin: &accountLoginService{server: server, repository: newStoreAccountLoginRepository(server.Store)},
communication: &communicationService{server: server, repository: newStoreCommunicationRepository(server.Store)},
+5 -28
View File
@@ -6,10 +6,10 @@ import (
"fmt"
"net/http"
"strconv"
"strings"
"github.com/go-chi/chi/v5"
orderapp "xianyu-go/internal/application/orders"
"xianyu-go/internal/auth"
"xianyu-go/internal/db"
"xianyu-go/internal/xianyu/mtop"
@@ -290,20 +290,11 @@ func (s *Server) updateOrder(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
// status 保存状态,供当前处理流程使用
// status 保存兼容字段 order_status/status 合并后的状态值。
status := req.OrderStatus
if status == nil {
status = req.Status
}
if status != nil {
// normalized 保存normalized,供当前处理流程使用
normalized := db.NormalizeOrderStatus(strings.TrimSpace(*status))
if !validEditableOrderStatus(normalized) {
writeErr(w, http.StatusBadRequest, "不支持的订单状态")
return
}
status = &normalized
}
// stringPtrFromAny 保存stringPtrFromAny,供当前处理流程使用
stringPtrFromAny := func(value *any) *string {
if value == nil {
@@ -313,17 +304,8 @@ func (s *Server) updateOrder(w http.ResponseWriter, r *http.Request) {
v := stringFromAny(*value)
return &v
}
// amount 保存amount,供当前处理流程使用
// amount 保存兼容 JSON 数值转换后的订单金额。
amount := stringPtrFromAny(req.Amount)
if amount != nil {
// normalized、ok 保存normalized、ok,供当前处理流程使用
normalized, ok := normalizeOrderAmount(*amount)
if !ok {
writeErr(w, http.StatusBadRequest, "订单金额必须是普通格式的非负有限数字")
return
}
amount = &normalized
}
// sess 保存sess,供当前处理流程使用
sess := auth.SessionFromContext(r.Context())
if // err 保存err,供当前处理流程使用
@@ -357,17 +339,12 @@ func validOrderAmount(raw string) bool {
// normalizeOrderAmount 负责normalize订单Amount相关处理。
func normalizeOrderAmount(raw string) (string, bool) {
return db.NormalizeOrderAmount(raw)
return orderapp.NormalizeOrderAmount(raw)
}
// validEditableOrderStatus 负责有效Editable订单状态相关处理。
func validEditableOrderStatus(status string) bool {
switch status {
case "processing", "pending_ship", "shipped", "completed", "cancelled", "refunding":
return true
default:
return false
}
return orderapp.ValidEditableOrderStatus(status)
}
// manualShipOrders 负责manualShip订单列表相关处理。
+24 -55
View File
@@ -150,6 +150,8 @@ type orderApplicationService struct {
list *orderapp.ListService
// detail 负责订单详情读取、商品补全和账号所有权规则。
detail *orderapp.DetailService
// update 负责订单更新字段校验和事务写入。
update *orderapp.UpdateService
// refreshJobs 提供订单刷新后台任务的持久化 Port。
refreshJobs orderapp.RefreshJobRepository
}
@@ -423,62 +425,29 @@ type orderUpdateRequest struct {
// Update 在单事务内更新订单及可选的商品标题。
func (a *orderApplicationService) Update(ctx context.Context, userID int64, orderID string, request orderUpdateRequest) error {
// order、err 保存order、err,供当前处理流程使用
order, err := a.Get(ctx, userID, orderID)
if err != nil {
return err
}
if request.OrderStatus != nil {
// normalized 保存normalized,供当前处理流程使用
normalized := db.NormalizeOrderStatus(strings.TrimSpace(*request.OrderStatus))
if !validEditableOrderStatus(normalized) {
return newOrderBadRequest("不支持的订单状态")
}
request.OrderStatus = &normalized
}
if request.Amount != nil {
// normalized、ok 保存normalized、ok,供当前处理流程使用
normalized, ok := normalizeOrderAmount(*request.Amount)
if !ok {
return newOrderBadRequest("订单金额必须是普通格式的非负有限数字")
}
request.Amount = &normalized
}
// finalItemID 保存final商品ID,供当前处理流程使用
finalItemID := strings.TrimSpace(order.ItemID)
if request.ItemID != nil {
finalItemID = strings.TrimSpace(*request.ItemID)
request.ItemID = &finalItemID
}
// itemTitle 保存商品标题,供当前处理流程使用
itemTitle := ""
if request.ItemTitle != nil {
itemTitle = strings.TrimSpace(*request.ItemTitle)
if itemTitle == "" || finalItemID == "" {
return newOrderBadRequest("商品标题不能为空且订单必须关联商品")
}
}
return a.repository.WithTransaction(ctx, func(writer orderapp.Writer) error {
if // err 保存err,供当前处理流程使用
err := writer.PatchOrder(ctx, orderID, orderapp.OrderPatch{
OrderStatus: request.OrderStatus, ItemID: request.ItemID, BuyerID: request.BuyerID,
SpecName: request.SpecName, SpecValue: request.SpecValue, Quantity: request.Quantity,
Amount: request.Amount, ReceiverName: request.ReceiverName, ReceiverPhone: request.ReceiverPhone,
ReceiverAddress: request.ReceiverAddress, ReceiverCity: request.ReceiverCity, ChatID: request.ChatID,
SystemShipped: request.SystemShipped,
}); err != nil {
return err
}
if request.ItemTitle != nil {
if // err 保存err,供当前处理流程使用
err := writer.UpsertItemBasic(ctx, orderapp.ItemWrite{
CookieID: order.CookieID, ItemID: finalItemID, ItemTitle: itemTitle,
}); err != nil {
return fmt.Errorf("更新商品标题失败: %w", err)
}
}
return nil
// err 保存应用层订单更新错误。
err := a.update.Update(ctx, userID, orderID, orderapp.UpdateRequest{
OrderStatus: request.OrderStatus, ItemID: request.ItemID, BuyerID: request.BuyerID,
SpecName: request.SpecName, SpecValue: request.SpecValue, Quantity: request.Quantity,
Amount: request.Amount, ReceiverName: request.ReceiverName, ReceiverPhone: request.ReceiverPhone,
ReceiverAddress: request.ReceiverAddress, ReceiverCity: request.ReceiverCity, ChatID: request.ChatID,
SystemShipped: request.SystemShipped, ItemTitle: request.ItemTitle,
})
if err == nil {
return nil
}
// validationErr 保存应用层字段校验错误。
var validationErr *orderapp.ValidationError
if errors.As(err, &validationErr) {
return newOrderBadRequest(validationErr.Error())
}
if errors.Is(err, orderapp.ErrForbidden) {
return db.ErrForbidden
}
if errors.Is(err, orderapp.ErrNotFound) {
return db.ErrNotFound
}
return err
}
// orderImportResult 描述批量导入的逐单结果和统计。