From 2fb6df13af4e478bf771a2617053aac52e025d8b Mon Sep 17 00:00:00 2001 From: Christ Date: Sat, 15 Aug 2026 17:31:33 +0800 Subject: [PATCH] =?UTF-8?q?=E8=BF=81=E7=A7=BB=E6=89=8B=E5=8A=A8=E5=8F=91?= =?UTF-8?q?=E8=B4=A7=E5=BA=94=E7=94=A8=E6=9C=8D=E5=8A=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/architecture/refactoring-master-plan.md | 1 + .../application/orders/manual_ship_service.go | 244 +++++++++++++++ .../orders/manual_ship_service_test.go | 284 ++++++++++++++++++ internal/server/application_services.go | 4 +- internal/server/order_handlers.go | 11 - internal/server/order_service.go | 178 ++++------- 6 files changed, 584 insertions(+), 138 deletions(-) create mode 100644 internal/application/orders/manual_ship_service.go create mode 100644 internal/application/orders/manual_ship_service_test.go diff --git a/docs/architecture/refactoring-master-plan.md b/docs/architecture/refactoring-master-plan.md index 5c21e82..a109a83 100644 --- a/docs/architecture/refactoring-master-plan.md +++ b/docs/architecture/refactoring-master-plan.md @@ -753,3 +753,4 @@ npm --prefix frontend run build | 2026-08-15 | P1 订单更新应用服务迁移切片 | 已完成 | 新增 `internal/application/orders.UpdateService`、`UpdateRequest`、`UpdateRepository` 和 `ValidationError`;订单所有权、状态/金额归一化、商品标题约束及订单+商品事务写入从 `internal/server/order_service.go` 迁入纯应用层,Server 仅负责 HTTP DTO 转换和旧错误分类映射;新增更新成功、非法字段、无权/不存在/存储错误测试,订单/应用定向测试、架构门禁和中文注释门禁通过。订单删除、导入、手动发货、刷新以及其他领域应用服务仍未迁移,阶段 4/8/9 保持“进行中” | | 2026-08-15 | P1 订单删除应用服务迁移切片 | 已完成 | 新增 `internal/application/orders.DeleteService` 和窄 `DeleteRepository`;订单存在性、账号所有权和逻辑删除从 `internal/server/order_service.go` 迁入纯应用层,Server 仅负责兼容错误映射;新增成功删除、无权/不存在、读取/删除存储错误测试,订单/应用定向测试、架构门禁和中文注释门禁通过。订单导入、手动发货、刷新以及其他领域应用服务仍未迁移,阶段 4/8/9 保持“进行中” | | 2026-08-15 | P1 订单导入应用服务迁移切片 | 已完成 | 新增 `internal/application/orders.ImportService`、具名 `ImportOrder/ImportResult` 和窄 `ImportRepository`;动态文件/HTTP 行只在 Server 边界转换,账号归属、状态/金额校验、逐条结果和订单+商品事务写入迁入纯应用层;新增成功导入、混合失败、事务/商品写入失败测试,导入 HTTP 回归、全量 Go 测试、race、架构门禁和中文注释门禁通过。手动发货、刷新以及其他领域应用服务仍未迁移,阶段 4/8/9 保持“进行中” | +| 2026-08-15 | P1 手动发货应用服务迁移切片 | 已完成 | 新增 `internal/application/orders.ManualShipService`、具名批量/逐单结果、`ManualShipRepository` 和 `ManualShipRuntime`;状态发货、完整自动化发货、凭证同步、通知及远端成功/本地失败补偿从 `internal/server/order_service.go` 迁入应用层,Server 仅负责 Port 适配和旧响应转换;手动发货应用服务文件覆盖率达到 100%,并覆盖平台异常、业务失败、离线/未装配、补偿写入失败等分支;手动发货 HTTP 回归、全量 Go 测试、race、架构门禁和中文注释门禁通过。订单刷新及其他领域应用服务仍未迁移,阶段 4/5/8/9 保持“进行中” | diff --git a/internal/application/orders/manual_ship_service.go b/internal/application/orders/manual_ship_service.go new file mode 100644 index 0000000..f5102c8 --- /dev/null +++ b/internal/application/orders/manual_ship_service.go @@ -0,0 +1,244 @@ +package orders + +import ( + "context" + "errors" + "fmt" + "strings" + "time" +) + +// ManualShipRequest 描述批量手动发货用例的输入。 +type ManualShipRequest struct { + // UserID 是当前登录用户标识。 + UserID int64 + // OrderIDs 是待处理订单标识列表。 + OrderIDs []string + // ShipMode 是发货模式,支持 status_only 和 full_delivery。 + ShipMode string +} + +// ManualShipItemResult 描述单个订单的手动发货结果。 +type ManualShipItemResult struct { + // OrderID 是结果对应的订单标识。 + OrderID string + // Status 是结果状态,如 succeeded、failed 或 reconciliation_required。 + Status string + // Success 表示远端动作或完整自动化动作是否成功。 + Success bool + // Message 是面向用户的结果说明。 + Message string + // ReconciliationID 是本地补偿记录标识。 + ReconciliationID string + // ReconciliationWarning 是补偿或本地状态写入警告。 + ReconciliationWarning string + // ReconciliationFieldsPresent 表示兼容响应是否应包含补偿字段。 + ReconciliationFieldsPresent bool +} + +// ManualShipResult 描述批量手动发货统计及逐单结果。 +type ManualShipResult struct { + // SuccessCount 是成功处理数量。 + SuccessCount int + // FailedCount 是失败处理数量。 + FailedCount int + // Results 是逐订单结果。 + Results []ManualShipItemResult +} + +// ConsignResult 描述远端确认发货接口的结果和凭证变化。 +type ConsignResult struct { + // Success 表示远端是否确认发货成功。 + Success bool + // Messages 是远端返回的业务提示列表。 + Messages []string + // RuntimeCookie 是需要同步到运行时的最新 Cookie。 + RuntimeCookie string + // RuntimeCookieChanged 表示 RuntimeCookie 是否有变化。 + RuntimeCookieChanged bool + // Err 是远端调用或会话处理错误。 + Err error +} + +// ManualShipRepository 定义手动发货用例所需的最小订单持久化能力。 +type ManualShipRepository interface { + // ListOwnedIDs 返回用户拥有的账号标识。 + ListOwnedIDs(ctx context.Context, userID int64) ([]string, error) + // GetOrder 读取待发货订单。 + GetOrder(ctx context.Context, orderID string) (*Order, error) + // UpsertOrder 写入远端确认后的本地订单状态。 + UpsertOrder(ctx context.Context, orderID string, options UpsertOptions) error +} + +// ManualShipRuntime 定义手动发货访问平台、自动化、运行时和补偿能力的最小 Port。 +type ManualShipRuntime interface { + // MTopAvailable 判断平台客户端是否已装配。 + MTopAvailable() bool + // AutomationReady 判断完整发货自动化依赖是否已装配。 + AutomationReady() bool + // AccountRunning 判断订单所属账号运行时是否在线。 + AccountRunning(cookieID string) bool + // ManualFullDelivery 执行完整自动化发货。 + ManualFullDelivery(ctx context.Context, order *Order) (int, error) + // ConfirmShipment 调用平台确认发货接口。 + ConfirmShipment(ctx context.Context, cookieID, orderID string, userID int64) ConsignResult + // UpdateRunningCookie 同步运行时账号 Cookie。 + UpdateRunningCookie(ctx context.Context, cookieID, value string) + // NotifyDelivery 发送手动发货结果通知。 + NotifyDelivery(cookieID, buyerID, itemID, chatID, message string) + // RecordReconciliation 创建外部成功、本地状态待补偿的记录。 + RecordReconciliation(ctx context.Context, orderID, cookieID, kind, message string) (string, error) + // ReportPersistenceFailure 记录本地订单状态持久化失败。 + ReportPersistenceFailure(orderID string, err error) +} + +// ManualShipService 承载手动发货的所有权、远端动作和本地补偿规则。 +type ManualShipService struct { + // repository 保存手动发货用例所需的订单 Port。 + repository ManualShipRepository + // runtime 保存手动发货用例所需的平台和运行时 Port。 + runtime ManualShipRuntime +} + +// NewManualShipService 创建手动发货应用服务。 +func NewManualShipService(repository ManualShipRepository, runtime ManualShipRuntime) *ManualShipService { + return &ManualShipService{repository: repository, runtime: runtime} +} + +// ManualShip 按订单逐条执行状态确认或完整自动化发货。 +func (s *ManualShipService) ManualShip(ctx context.Context, request ManualShipRequest) (ManualShipResult, error) { + if s == nil || s.repository == nil || s.runtime == nil { + return ManualShipResult{}, errors.New("手动发货依赖未初始化") + } + // ownedCookieIDs 保存当前用户可操作的账号标识。 + ownedCookieIDs, err := s.repository.ListOwnedIDs(ctx, request.UserID) + if err != nil { + return ManualShipResult{}, err + } + // result 保存批量手动发货统计和逐条结果。 + result := ManualShipResult{Results: make([]ManualShipItemResult, 0, len(request.OrderIDs))} + // rawOrderID 表示当前遍历中的原始订单标识。 + for _, rawOrderID := range request.OrderIDs { + // orderID 保存去除空白后的订单标识。 + orderID := strings.TrimSpace(rawOrderID) + if orderID == "" { + continue + } + // order、getErr 保存订单读取结果及错误。 + order, getErr := s.repository.GetOrder(ctx, orderID) + if getErr != nil || order == nil { + s.appendFailure(&result, orderID, "订单不存在") + continue + } + if !containsOwnedCookieID(ownedCookieIDs, order.CookieID) { + s.appendFailure(&result, orderID, "无权操作此订单") + continue + } + if NormalizeOrderStatus(strings.TrimSpace(order.OrderStatus)) != "pending_ship" { + s.appendFailure(&result, orderID, "仅待发货订单可以执行手动发货") + continue + } + if request.ShipMode == "full_delivery" { + s.manualFullDelivery(ctx, order, orderID, &result) + continue + } + s.manualStatusShip(ctx, request.UserID, order, orderID, &result) + } + return result, nil +} + +// appendFailure 追加一条手动发货失败记录并更新失败计数。 +func (s *ManualShipService) appendFailure(result *ManualShipResult, orderID, message string) { + result.FailedCount++ + result.Results = append(result.Results, ManualShipItemResult{OrderID: orderID, Status: "failed", Message: message}) +} + +// manualFullDelivery 执行完整自动化发货分支。 +func (s *ManualShipService) manualFullDelivery(ctx context.Context, order *Order, orderID string, result *ManualShipResult) { + if !s.runtime.AutomationReady() { + s.appendFailure(result, orderID, "自动化中心未初始化") + return + } + if !s.runtime.AccountRunning(order.CookieID) { + s.appendFailure(result, orderID, "该账号未在线运行,无法执行完整发货") + return + } + // sent、err 保存完整自动化发货结果和错误。 + sent, err := s.runtime.ManualFullDelivery(ctx, order) + if err != nil { + s.appendFailure(result, orderID, err.Error()) + s.runtime.NotifyDelivery(order.CookieID, order.BuyerID, order.ItemID, order.ChatID, "手动完整发货失败: "+err.Error()) + return + } + result.SuccessCount++ + result.Results = append(result.Results, ManualShipItemResult{OrderID: orderID, Status: "succeeded", Success: true, Message: fmt.Sprintf("完整发货成功,已发送%d条卡券信息给买家", sent)}) + s.runtime.NotifyDelivery(order.CookieID, order.BuyerID, order.ItemID, order.ChatID, fmt.Sprintf("手动完整发货成功(订单 %s,已发送 %d 条)", orderID, sent)) +} + +// manualStatusShip 调用平台确认发货并把成功状态写入本地订单。 +func (s *ManualShipService) manualStatusShip(ctx context.Context, userID int64, order *Order, orderID string, result *ManualShipResult) { + if !s.runtime.MTopAvailable() { + s.appendFailure(result, orderID, "mtop 客户端未初始化") + return + } + // consign 保存远端确认发货结果。 + consign := s.runtime.ConfirmShipment(ctx, order.CookieID, orderID, userID) + if consign.RuntimeCookieChanged { + s.runtime.UpdateRunningCookie(ctx, order.CookieID, consign.RuntimeCookie) + } + if consign.Err != nil && !consign.Success { + s.appendFailure(result, orderID, "确认发货异常: "+consign.Err.Error()) + s.runtime.NotifyDelivery(order.CookieID, order.BuyerID, order.ItemID, order.ChatID, "手动确认发货异常: "+consign.Err.Error()) + return + } + if !consign.Success { + // message 保存远端确认发货失败说明。 + message := "确认发货失败" + if len(consign.Messages) > 0 { + message += ": " + strings.Join(consign.Messages, "; ") + } + s.appendFailure(result, orderID, message) + s.runtime.NotifyDelivery(order.CookieID, order.BuyerID, order.ItemID, order.ChatID, "手动确认发货失败: "+message) + return + } + // systemShipped 标识本地订单已由系统确认发货。 + systemShipped := true + // upsertErr 保存远端成功后本地订单写入错误。 + upsertErr := s.repository.UpsertOrder(ctx, orderID, UpsertOptions{ + CookieID: order.CookieID, OrderStatus: "shipped", SystemShipped: &systemShipped, ItemID: order.ItemID, + BuyerID: order.BuyerID, ReceiverName: order.ReceiverName, ReceiverPhone: order.ReceiverPhone, + ReceiverAddress: order.ReceiverAddress, ReceiverCity: order.ReceiverCity, ChatID: order.ChatID, + SpecName: order.SpecName, SpecValue: order.SpecValue, Quantity: order.Quantity, Amount: order.Amount, + }) + if upsertErr != nil { + s.runtime.ReportPersistenceFailure(orderID, upsertErr) + } + result.SuccessCount++ + // status 表示远端动作与本地状态同步的三态结果。 + status := "succeeded" + // message 保存手动确认发货结果说明。 + message := "已成功修改闲鱼发货状态" + // reconciliationID 保存待补偿记录标识。 + reconciliationID := "" + // reconciliationWarning 保存本地状态写入或补偿记录写入错误。 + reconciliationWarning := "" + if upsertErr != nil { + status = "reconciliation_required" + message = "闲鱼已确认发货;本地订单状态待补偿,请勿重复确认发货" + reconciliationWarning = upsertErr.Error() + // recordCtx、recordCancel 保存补偿写入使用的短时独立上下文。 + recordCtx, recordCancel := context.WithTimeout(context.Background(), 5*time.Second) + // recordErr 保存补偿记录写入错误。 + var recordErr error + reconciliationID, recordErr = s.runtime.RecordReconciliation(recordCtx, orderID, order.CookieID, "manual_status_ship", upsertErr.Error()) + recordCancel() + if recordErr != nil { + reconciliationWarning = errors.Join(errors.New(reconciliationWarning), fmt.Errorf("写入补偿记录失败: %w", recordErr)).Error() + } + } + result.Results = append(result.Results, ManualShipItemResult{ + OrderID: orderID, Status: status, Success: true, Message: message, + ReconciliationID: reconciliationID, ReconciliationWarning: reconciliationWarning, ReconciliationFieldsPresent: true, + }) + s.runtime.NotifyDelivery(order.CookieID, order.BuyerID, order.ItemID, order.ChatID, fmt.Sprintf("手动确认发货成功(订单 %s)", orderID)) +} diff --git a/internal/application/orders/manual_ship_service_test.go b/internal/application/orders/manual_ship_service_test.go new file mode 100644 index 0000000..7b35ce6 --- /dev/null +++ b/internal/application/orders/manual_ship_service_test.go @@ -0,0 +1,284 @@ +package orders + +import ( + "context" + "errors" + "strings" + "testing" +) + +// manualShipRepositoryFake 是手动发货应用服务测试使用的内存 repository。 +type manualShipRepositoryFake struct { + // ownedIDs 保存测试用户拥有的账号标识。 + ownedIDs []string + // orders 保存测试订单。 + orders map[string]*Order + // listErr 保存账号列表查询错误。 + listErr error + // upsertErr 保存订单状态写入错误。 + upsertErr error + // upsertID 保存最近一次写入订单标识。 + upsertID string + // upsertOptions 保存最近一次订单写入字段。 + upsertOptions UpsertOptions +} + +// ListOwnedIDs 返回测试用户拥有的账号标识。 +func (f *manualShipRepositoryFake) ListOwnedIDs(context.Context, int64) ([]string, error) { + return f.ownedIDs, f.listErr +} + +// GetOrder 返回测试订单。 +func (f *manualShipRepositoryFake) GetOrder(_ context.Context, orderID string) (*Order, error) { + return f.orders[orderID], nil +} + +// UpsertOrder 记录测试订单状态写入。 +func (f *manualShipRepositoryFake) UpsertOrder(_ context.Context, orderID string, options UpsertOptions) error { + f.upsertID = orderID + f.upsertOptions = options + return f.upsertErr +} + +// manualShipRuntimeFake 是手动发货应用服务测试使用的平台运行时 Port。 +type manualShipRuntimeFake struct { + // mtopAvailable 表示平台客户端是否可用。 + mtopAvailable bool + // automationReady 表示完整自动化依赖是否可用。 + automationReady bool + // accountRunning 表示订单账号运行时是否在线。 + accountRunning bool + // sentCount 保存完整自动化发货发送数量。 + sentCount int + // fullDeliveryErr 保存完整自动化发货错误。 + fullDeliveryErr error + // consign 保存平台确认发货结果。 + consign ConsignResult + // updatedCookie 保存同步到运行时的 Cookie。 + updatedCookie string + // notifications 保存发送的通知文本。 + notifications []string + // reconciliationID 保存补偿记录标识。 + reconciliationID string + // reconciliationErr 保存补偿记录写入错误。 + reconciliationErr error + // reportedPersistenceErr 保存报告的本地持久化错误。 + reportedPersistenceErr error +} + +// MTopAvailable 返回测试平台客户端可用状态。 +func (f *manualShipRuntimeFake) MTopAvailable() bool { + return f.mtopAvailable +} + +// AutomationReady 返回测试自动化依赖可用状态。 +func (f *manualShipRuntimeFake) AutomationReady() bool { + return f.automationReady +} + +// AccountRunning 返回测试账号运行状态。 +func (f *manualShipRuntimeFake) AccountRunning(string) bool { + return f.accountRunning +} + +// ManualFullDelivery 返回测试完整自动化发货结果。 +func (f *manualShipRuntimeFake) ManualFullDelivery(context.Context, *Order) (int, error) { + return f.sentCount, f.fullDeliveryErr +} + +// ConfirmShipment 返回测试平台确认发货结果。 +func (f *manualShipRuntimeFake) ConfirmShipment(context.Context, string, string, int64) ConsignResult { + return f.consign +} + +// UpdateRunningCookie 记录测试运行时 Cookie 更新。 +func (f *manualShipRuntimeFake) UpdateRunningCookie(_ context.Context, _, value string) { + f.updatedCookie = value +} + +// NotifyDelivery 记录测试发货通知。 +func (f *manualShipRuntimeFake) NotifyDelivery(_, _, _, _, message string) { + f.notifications = append(f.notifications, message) +} + +// RecordReconciliation 返回测试补偿记录结果。 +func (f *manualShipRuntimeFake) RecordReconciliation(context.Context, string, string, string, string) (string, error) { + return f.reconciliationID, f.reconciliationErr +} + +// ReportPersistenceFailure 记录测试本地持久化错误。 +func (f *manualShipRuntimeFake) ReportPersistenceFailure(_ string, err error) { + f.reportedPersistenceErr = err +} + +// TestManualShipServiceStatusSuccess 验证状态发货成功会同步 Cookie 和本地订单状态。 +func TestManualShipServiceStatusSuccess(t *testing.T) { + // repository 保存本用例使用的内存依赖。 + repository := &manualShipRepositoryFake{ownedIDs: []string{"cookie-1"}, orders: map[string]*Order{ + "order-1": {OrderID: "order-1", CookieID: "cookie-1", ItemID: "item-1", BuyerID: "buyer-1", ChatID: "chat-1", OrderStatus: "2"}, + }} + // runtime 保存本用例使用的平台运行时依赖。 + runtime := &manualShipRuntimeFake{mtopAvailable: true, consign: ConsignResult{Success: true, RuntimeCookie: "new-cookie", RuntimeCookieChanged: true}} + // service 保存待测试的手动发货服务。 + service := NewManualShipService(repository, runtime) + // result、err 保存手动发货结果和错误。 + result, err := service.ManualShip(context.Background(), ManualShipRequest{UserID: 7, OrderIDs: []string{"order-1"}, ShipMode: "status_only"}) + if err != nil || result.SuccessCount != 1 || result.FailedCount != 0 { + t.Fatalf("发货结果异常: result=%+v err=%v", result, err) + } + if runtime.updatedCookie != "new-cookie" || repository.upsertID != "order-1" || repository.upsertOptions.OrderStatus != "shipped" { + t.Fatalf("发货副作用异常: runtime=%+v repository=%+v", runtime, repository) + } + if result.Results[0].Status != "succeeded" || !result.Results[0].Success { + t.Fatalf("成功结果异常: %+v", result.Results[0]) + } +} + +// TestManualShipServiceRejectsInvalidOrders 验证不存在、无权和非待发货订单不会调用远端。 +func TestManualShipServiceRejectsInvalidOrders(t *testing.T) { + // repository 保存本用例使用的订单依赖。 + repository := &manualShipRepositoryFake{ownedIDs: []string{"cookie-1"}, orders: map[string]*Order{ + "forbidden": {CookieID: "other", OrderStatus: "2"}, + "cancelled": {CookieID: "cookie-1", OrderStatus: "cancelled"}, + }} + // runtime 保存本用例使用的平台运行时依赖。 + runtime := &manualShipRuntimeFake{mtopAvailable: true} + // service 保存待测试的手动发货服务。 + service := NewManualShipService(repository, runtime) + // result、err 保存混合订单处理结果和错误。 + result, err := service.ManualShip(context.Background(), ManualShipRequest{UserID: 7, OrderIDs: []string{"", "missing", "forbidden", "cancelled"}, ShipMode: "status_only"}) + if err != nil || result.FailedCount != 3 || len(result.Results) != 3 { + t.Fatalf("失败结果异常: result=%+v err=%v", result, err) + } + if repository.upsertID != "" || runtime.updatedCookie != "" { + t.Fatal("无效订单不应执行远端或本地写入") + } +} + +// TestManualShipServiceRejectsUninitializedDependencies 验证未装配依赖时不会执行发货。 +func TestManualShipServiceRejectsUninitializedDependencies(t *testing.T) { + // service 保存 repository 未装配场景的应用服务。 + service := NewManualShipService(nil, &manualShipRuntimeFake{}) + // result、err 保存未装配依赖结果和错误。 + result, err := service.ManualShip(context.Background(), ManualShipRequest{UserID: 7}) + if err == nil || result.SuccessCount != 0 { + t.Fatalf("repository 未装配时应返回错误: result=%+v err=%v", result, err) + } + // runtimeService 保存 runtime 未装配场景的应用服务。 + runtimeService := NewManualShipService(&manualShipRepositoryFake{}, nil) + // result、err 保存 runtime 未装配结果和错误。 + result, err = runtimeService.ManualShip(context.Background(), ManualShipRequest{UserID: 7}) + if err == nil || result.SuccessCount != 0 { + t.Fatalf("runtime 未装配时应返回错误: result=%+v err=%v", result, err) + } +} + +// TestManualShipServicePropagatesAccountQueryError 验证账号列表读取错误会阻止批次执行。 +func TestManualShipServicePropagatesAccountQueryError(t *testing.T) { + // expectedErr 保存账号列表查询错误。 + expectedErr := errors.New("账号查询失败") + // service 保存账号列表查询失败场景的应用服务。 + service := NewManualShipService(&manualShipRepositoryFake{listErr: expectedErr}, &manualShipRuntimeFake{}) + // result、err 保存账号列表查询结果和错误。 + result, err := service.ManualShip(context.Background(), ManualShipRequest{UserID: 7, OrderIDs: []string{"order-1"}}) + if !errors.Is(err, expectedErr) || result.SuccessCount != 0 || result.FailedCount != 0 { + t.Fatalf("账号列表错误未正确透传: result=%+v err=%v", result, err) + } +} + +// TestManualShipServiceReconciliationRequired 验证远端成功、本地写入失败时生成补偿结果。 +func TestManualShipServiceReconciliationRequired(t *testing.T) { + // repository 保存本地订单写入失败依赖。 + repository := &manualShipRepositoryFake{ownedIDs: []string{"cookie-1"}, upsertErr: errors.New("本地写入失败"), orders: map[string]*Order{ + "order-1": {CookieID: "cookie-1", ItemID: "item-1", OrderStatus: "pending_ship"}, + }} + // runtime 保存远端成功和补偿记录依赖。 + runtime := &manualShipRuntimeFake{mtopAvailable: true, consign: ConsignResult{Success: true}, reconciliationID: "reconcile-1", reconciliationErr: errors.New("补偿写入失败")} + // service 保存待测试的手动发货服务。 + service := NewManualShipService(repository, runtime) + // result、err 保存补偿场景结果和错误。 + result, err := service.ManualShip(context.Background(), ManualShipRequest{UserID: 7, OrderIDs: []string{"order-1"}}) + if err != nil || result.SuccessCount != 1 || result.Results[0].Status != "reconciliation_required" { + t.Fatalf("补偿结果异常: result=%+v err=%v", result, err) + } + if result.Results[0].ReconciliationID != "reconcile-1" || !strings.Contains(result.Results[0].ReconciliationWarning, "补偿写入失败") || runtime.reportedPersistenceErr == nil { + t.Fatalf("补偿副作用异常: result=%+v runtime=%+v", result, runtime) + } +} + +// TestManualShipServiceStatusFailures 验证平台未装配、远端异常和业务失败分支。 +func TestManualShipServiceStatusFailures(t *testing.T) { + // repository 保存状态失败测试订单。 + repository := &manualShipRepositoryFake{ownedIDs: []string{"cookie-1"}, orders: map[string]*Order{ + "order-1": {CookieID: "cookie-1", ItemID: "item-1", OrderStatus: "pending_ship"}, + }} + // unavailableRuntime 保存平台客户端未装配场景依赖。 + unavailableRuntime := &manualShipRuntimeFake{} + // unavailableService 保存平台客户端未装配场景服务。 + unavailableService := NewManualShipService(repository, unavailableRuntime) + // result、err 保存平台未装配结果和错误。 + result, err := unavailableService.ManualShip(context.Background(), ManualShipRequest{UserID: 7, OrderIDs: []string{"order-1"}}) + if err != nil || result.FailedCount != 1 || !strings.Contains(result.Results[0].Message, "mtop") { + t.Fatalf("平台未装配结果异常: result=%+v err=%v", result, err) + } + // remoteErrorRuntime 保存远端调用异常场景依赖。 + remoteErrorRuntime := &manualShipRuntimeFake{mtopAvailable: true, consign: ConsignResult{Err: errors.New("网络异常")}} + // remoteErrorService 保存远端调用异常场景服务。 + remoteErrorService := NewManualShipService(repository, remoteErrorRuntime) + // result、err 保存远端调用异常结果和错误。 + result, err = remoteErrorService.ManualShip(context.Background(), ManualShipRequest{UserID: 7, OrderIDs: []string{"order-1"}}) + if err != nil || result.FailedCount != 1 || !strings.Contains(result.Results[0].Message, "网络异常") { + t.Fatalf("远端异常结果异常: result=%+v err=%v", result, err) + } + // businessFailureRuntime 保存远端业务失败场景依赖。 + businessFailureRuntime := &manualShipRuntimeFake{mtopAvailable: true, consign: ConsignResult{Messages: []string{"订单不存在", "状态不允许"}}} + // businessFailureService 保存远端业务失败场景服务。 + businessFailureService := NewManualShipService(repository, businessFailureRuntime) + // result、err 保存远端业务失败结果和错误。 + result, err = businessFailureService.ManualShip(context.Background(), ManualShipRequest{UserID: 7, OrderIDs: []string{"order-1"}}) + if err != nil || result.FailedCount != 1 || !strings.Contains(result.Results[0].Message, "订单不存在; 状态不允许") { + t.Fatalf("远端业务失败结果异常: result=%+v err=%v", result, err) + } +} + +// TestManualShipServiceFullDeliveryBranches 验证完整自动化发货的依赖、成功和失败分支。 +func TestManualShipServiceFullDeliveryBranches(t *testing.T) { + // repository 保存完整发货测试订单。 + repository := &manualShipRepositoryFake{ownedIDs: []string{"cookie-1"}, orders: map[string]*Order{"order-1": {CookieID: "cookie-1", OrderStatus: "pending_ship"}}} + // unavailableRuntime 保存自动化未装配场景依赖。 + unavailableRuntime := &manualShipRuntimeFake{} + // unavailableService 保存自动化未装配场景服务。 + unavailableService := NewManualShipService(repository, unavailableRuntime) + // result、err 保存自动化未装配结果和错误。 + result, err := unavailableService.ManualShip(context.Background(), ManualShipRequest{UserID: 7, OrderIDs: []string{"order-1"}, ShipMode: "full_delivery"}) + if err != nil || result.FailedCount != 1 || !strings.Contains(result.Results[0].Message, "自动化") { + t.Fatalf("自动化未装配结果异常: result=%+v err=%v", result, err) + } + // offlineRuntime 保存账号运行时离线场景依赖。 + offlineRuntime := &manualShipRuntimeFake{automationReady: true} + // offlineService 保存账号运行时离线场景服务。 + offlineService := NewManualShipService(repository, offlineRuntime) + // result、err 保存账号运行时离线结果和错误。 + result, err = offlineService.ManualShip(context.Background(), ManualShipRequest{UserID: 7, OrderIDs: []string{"order-1"}, ShipMode: "full_delivery"}) + if err != nil || result.FailedCount != 1 || !strings.Contains(result.Results[0].Message, "未在线") { + t.Fatalf("账号离线结果异常: result=%+v err=%v", result, err) + } + // successRuntime 保存完整发货成功场景依赖。 + successRuntime := &manualShipRuntimeFake{automationReady: true, accountRunning: true, sentCount: 2} + // successService 保存完整发货成功场景服务。 + successService := NewManualShipService(repository, successRuntime) + // result、err 保存完整发货成功结果和错误。 + result, err = successService.ManualShip(context.Background(), ManualShipRequest{UserID: 7, OrderIDs: []string{"order-1"}, ShipMode: "full_delivery"}) + if err != nil || result.SuccessCount != 1 || !strings.Contains(result.Results[0].Message, "2条") { + t.Fatalf("完整发货成功结果异常: result=%+v err=%v", result, err) + } + // failureRuntime 保存完整发货失败场景依赖。 + failureRuntime := &manualShipRuntimeFake{automationReady: true, accountRunning: true, fullDeliveryErr: errors.New("自动化失败")} + // failureService 保存完整发货失败场景服务。 + failureService := NewManualShipService(repository, failureRuntime) + // result、err 保存完整发货失败结果和错误。 + result, err = failureService.ManualShip(context.Background(), ManualShipRequest{UserID: 7, OrderIDs: []string{"order-1"}, ShipMode: "full_delivery"}) + if err != nil || result.FailedCount != 1 || !strings.Contains(result.Results[0].Message, "自动化失败") { + t.Fatalf("完整发货失败结果异常: result=%+v err=%v", result, err) + } +} diff --git a/internal/server/application_services.go b/internal/server/application_services.go index 85bc4c7..f8d760c 100644 --- a/internal/server/application_services.go +++ b/internal/server/application_services.go @@ -20,8 +20,10 @@ type applicationServices struct { func newApplicationServices(server *Server) *applicationServices { // orderRepository 保存订单应用服务共享的基础设施适配器。 orderRepository := newStoreOrderRepository(server.Store) + // orderRuntime 保存订单服务共享的运行时能力适配器。 + orderRuntime := newServerOrderRuntime(server) return &applicationServices{ - orders: &orderApplicationService{server: newServerOrderRuntime(server), repository: orderRepository, list: orderapp.NewListService(orderRepository), detail: orderapp.NewDetailService(orderRepository), delete: orderapp.NewDeleteService(orderRepository), update: orderapp.NewUpdateService(orderRepository), importOrders: orderapp.NewImportService(orderRepository), refreshJobs: newStoreOrderRefreshJobRepository(server.Store)}, + orders: &orderApplicationService{server: orderRuntime, repository: orderRepository, list: orderapp.NewListService(orderRepository), detail: orderapp.NewDetailService(orderRepository), delete: orderapp.NewDeleteService(orderRepository), update: orderapp.NewUpdateService(orderRepository), importOrders: orderapp.NewImportService(orderRepository), manualShip: orderapp.NewManualShipService(orderRepository, orderRuntime), 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)}, diff --git a/internal/server/order_handlers.go b/internal/server/order_handlers.go index 57bfb3f..47beef0 100644 --- a/internal/server/order_handlers.go +++ b/internal/server/order_handlers.go @@ -493,14 +493,3 @@ func (s *Server) notifyDelivery(cookieID, buyerID, itemID, chatID, message strin } s.notifier.NotifyDelivery(cookieID, "", buyerID, itemID, message, chatID) } - -// containsCookieID 判断账号 ID 列表中是否包含目标账号,不触碰 Cookie 明文。 -func containsCookieID(cookieIDs []string, target string) bool { - // cookieID 是当前遍历到的账号 ID。 - for _, cookieID := range cookieIDs { - if cookieID == target { - return true - } - } - return false -} diff --git a/internal/server/order_service.go b/internal/server/order_service.go index 2e74a61..458de07 100644 --- a/internal/server/order_service.go +++ b/internal/server/order_service.go @@ -53,7 +53,7 @@ type serverOrderRuntimeAdapter struct { } // newServerOrderRuntime 创建订单运行时 Port 的 Server 适配器。 -func newServerOrderRuntime(server *Server) orderRuntimePort { +func newServerOrderRuntime(server *Server) serverOrderRuntimeAdapter { return serverOrderRuntimeAdapter{server: server} } @@ -98,16 +98,36 @@ func (a serverOrderRuntimeAdapter) consignWithCurrentCookie(ctx context.Context, return a.server.consignWithCurrentCookie(ctx, cookieID, orderID, userID) } +// ConfirmShipment 将 Server 的确认发货能力适配为应用层结果模型。 +func (a serverOrderRuntimeAdapter) ConfirmShipment(ctx context.Context, cookieID, orderID string, userID int64) orderapp.ConsignResult { + // ok、messages、runtimeCookie、runtimeCookieChanged、err 保存确认发货结果及凭证变化。 + ok, messages, runtimeCookie, runtimeCookieChanged, err := a.consignWithCurrentCookie(ctx, cookieID, orderID, userID) + return orderapp.ConsignResult{ + Success: ok, Messages: messages, RuntimeCookie: runtimeCookie, + RuntimeCookieChanged: runtimeCookieChanged, Err: err, + } +} + // updateRunningCookie 同步运行时账号 Cookie。 func (a serverOrderRuntimeAdapter) updateRunningCookie(ctx context.Context, cookieID, value string) { a.server.updateRunningCookie(ctx, cookieID, value) } +// UpdateRunningCookie 将运行时账号 Cookie 能力暴露给手动发货应用 Port。 +func (a serverOrderRuntimeAdapter) UpdateRunningCookie(ctx context.Context, cookieID, value string) { + a.updateRunningCookie(ctx, cookieID, value) +} + // notifyDelivery 发送发货结果通知。 func (a serverOrderRuntimeAdapter) notifyDelivery(cookieID, buyerID, itemID, chatID, message string) { a.server.notifyDelivery(cookieID, buyerID, itemID, chatID, message) } +// NotifyDelivery 将发货通知能力暴露给手动发货应用 Port。 +func (a serverOrderRuntimeAdapter) NotifyDelivery(cookieID, buyerID, itemID, chatID, message string) { + a.notifyDelivery(cookieID, buyerID, itemID, chatID, message) +} + // RecordOrderReconciliation 将外部动作成功后的本地状态异常写入补偿记录。 func (a serverOrderRuntimeAdapter) RecordOrderReconciliation(ctx context.Context, orderID, cookieID, kind, message string) (string, error) { if a.server == nil || a.server.Store == nil || a.server.Store.Reconciliations == nil { @@ -116,6 +136,19 @@ func (a serverOrderRuntimeAdapter) RecordOrderReconciliation(ctx context.Context return a.server.Store.Reconciliations.CreatePending(ctx, orderID, cookieID, kind, message) } +// RecordReconciliation 将补偿记录能力暴露给手动发货应用 Port。 +func (a serverOrderRuntimeAdapter) RecordReconciliation(ctx context.Context, orderID, cookieID, kind, message string) (string, error) { + return a.RecordOrderReconciliation(ctx, orderID, cookieID, kind, message) +} + +// ReportPersistenceFailure 记录手动发货本地订单状态持久化失败。 +func (a serverOrderRuntimeAdapter) ReportPersistenceFailure(orderID string, err error) { + if a.server == nil || a.server.Logger == nil || err == nil { + return + } + a.server.Logger.Error("更新订单为系统已发货失败", "order_id", orderID, "err", err) +} + // persistMTopCookieSessionLocked 持久化平台响应 Cookie Jar。 func (a serverOrderRuntimeAdapter) persistMTopCookieSessionLocked(ctx context.Context, detail *orderapp.PlatformRuntimeData, session *mtop.CookieSession) (string, bool, bool, error) { return a.server.persistMTopCookieSessionLocked(ctx, cookieDetailForOrderPlatform(detail), session) @@ -156,6 +189,8 @@ type orderApplicationService struct { update *orderapp.UpdateService // importOrders 负责订单导入的归属校验和事务写入。 importOrders *orderapp.ImportService + // manualShip 负责手动发货的远端动作、本地状态和补偿规则。 + manualShip *orderapp.ManualShipService // refreshJobs 提供订单刷新后台任务的持久化 Port。 refreshJobs orderapp.RefreshJobRepository } @@ -532,138 +567,29 @@ type manualShipResult struct { // ManualShip 执行状态确认或完整自动化发货,并集中处理逐单失败而不中断批次的规则。 func (a *orderApplicationService) ManualShip(ctx context.Context, request manualShipRequest) (manualShipResult, error) { - // ownedCookieIDs、err 保存owned登录凭证IDs、err,供当前处理流程使用 - ownedCookieIDs, err := a.repository.ListOwnedIDs(ctx, request.UserID) + // result 保存应用层手动发货结果。 + result, err := a.manualShip.ManualShip(ctx, orderapp.ManualShipRequest{UserID: request.UserID, OrderIDs: request.OrderIDs, ShipMode: request.ShipMode}) if err != nil { return manualShipResult{}, err } - // result 保存结果,供当前处理流程使用 - result := manualShipResult{Results: make([]map[string]any, 0, len(request.OrderIDs))} - // rawOrderID 表示当前遍历过程中的原始订单ID - for _, rawOrderID := range request.OrderIDs { - // orderID 保存订单ID,供当前处理流程使用 - orderID := strings.TrimSpace(rawOrderID) - if orderID == "" { - continue - } - // order、getErr 保存order、getErr,供当前处理流程使用 - order, getErr := a.repository.GetOrder(ctx, orderID) - if getErr != nil || order == nil { - a.appendManualFailure(&result, orderID, "订单不存在") - continue - } - if !containsCookieID(ownedCookieIDs, order.CookieID) { - a.appendManualFailure(&result, orderID, "无权操作此订单") - continue - } - if db.NormalizeOrderStatus(strings.TrimSpace(order.OrderStatus)) != "pending_ship" { - a.appendManualFailure(&result, orderID, "仅待发货订单可以执行手动发货") - continue - } - if request.ShipMode == "full_delivery" { - a.manualFullDelivery(ctx, order, orderID, &result) - continue - } - a.manualStatusShip(ctx, request.UserID, order, orderID, &result) - } - return result, nil + return manualShipResultFromApplication(result), nil } -// appendManualFailure 追加一条手动发货失败记录并更新失败计数。 -func (a *orderApplicationService) appendManualFailure(result *manualShipResult, orderID, message string) { - result.FailedCount++ - result.Results = append(result.Results, map[string]any{"order_id": orderID, "status": "failed", "success": false, "message": message}) -} - -// manualFullDelivery 执行完整自动化发货分支。 -func (a *orderApplicationService) manualFullDelivery(ctx context.Context, order *orderapp.Order, orderID string, result *manualShipResult) { - if !a.server.AutomationReady() { - a.appendManualFailure(result, orderID, "自动化中心未初始化") - return - } - if // running 保存running,供当前处理流程使用 - !a.server.AccountRunning(order.CookieID) { - a.appendManualFailure(result, orderID, "该账号未在线运行,无法执行完整发货") - return - } - // sent、err 保存sent、err,供当前处理流程使用 - sent, err := a.server.ManualFullDelivery(ctx, order) - if err != nil { - a.appendManualFailure(result, orderID, err.Error()) - a.server.notifyDelivery(order.CookieID, order.BuyerID, order.ItemID, order.ChatID, "手动完整发货失败: "+err.Error()) - return - } - result.SuccessCount++ - result.Results = append(result.Results, map[string]any{"order_id": orderID, "status": "succeeded", "success": true, "message": fmt.Sprintf("完整发货成功,已发送%d条卡券信息给买家", sent)}) - a.server.notifyDelivery(order.CookieID, order.BuyerID, order.ItemID, order.ChatID, fmt.Sprintf("手动完整发货成功(订单 %s,已发送 %d 条)", orderID, sent)) -} - -// manualStatusShip 调用平台确认发货并把成功状态写入本地订单。 -func (a *orderApplicationService) manualStatusShip(ctx context.Context, userID int64, order *orderapp.Order, orderID string, result *manualShipResult) { - if !a.server.MTopAvailable() { - a.appendManualFailure(result, orderID, "mtop 客户端未初始化") - return - } - // ok、ret、runtimeCookie、runtimeCookieChanged、err 保存ok、ret、runtimeCookie、runtime登录凭证Changed、err,供当前处理流程使用 - ok, ret, runtimeCookie, runtimeCookieChanged, err := a.server.consignWithCurrentCookie(ctx, order.CookieID, orderID, userID) - if runtimeCookieChanged { - a.server.updateRunningCookie(ctx, order.CookieID, runtimeCookie) - } - if err != nil && !ok { - a.appendManualFailure(result, orderID, "确认发货异常: "+err.Error()) - a.server.notifyDelivery(order.CookieID, order.BuyerID, order.ItemID, order.ChatID, "手动确认发货异常: "+err.Error()) - return - } - if !ok { - // message 保存消息,供当前处理流程使用 - message := "确认发货失败" - if len(ret) > 0 { - message += ": " + strings.Join(ret, "; ") +// manualShipResultFromApplication 将应用层手动发货结果转换为旧 HTTP 响应兼容模型。 +func manualShipResultFromApplication(result orderapp.ManualShipResult) manualShipResult { + // results 保存兼容客户端使用的逐条动态结果。 + results := make([]map[string]any, 0, len(result.Results)) + // item 保存当前应用层手动发货结果行。 + for _, item := range result.Results { + // row 保存兼容客户端使用的单条结果。 + row := map[string]any{"order_id": item.OrderID, "status": item.Status, "success": item.Success, "message": item.Message} + if item.ReconciliationFieldsPresent { + row["reconciliation_id"] = item.ReconciliationID + row["reconciliation_warning"] = item.ReconciliationWarning } - a.appendManualFailure(result, orderID, message) - a.server.notifyDelivery(order.CookieID, order.BuyerID, order.ItemID, order.ChatID, "手动确认发货失败: "+message) - return + results = append(results, row) } - // sysShip 保存sysShip,供当前处理流程使用 - sysShip := true - // upsertErr 保存upsertErr,供当前处理流程使用 - upsertErr := a.repository.UpsertOrder(ctx, orderID, orderapp.UpsertOptions{ - CookieID: order.CookieID, OrderStatus: "shipped", SystemShipped: &sysShip, ItemID: order.ItemID, - BuyerID: order.BuyerID, ReceiverName: order.ReceiverName, ReceiverPhone: order.ReceiverPhone, - ReceiverAddress: order.ReceiverAddress, ReceiverCity: order.ReceiverCity, ChatID: order.ChatID, - SpecName: order.SpecName, SpecValue: order.SpecValue, Quantity: order.Quantity, Amount: order.Amount, - }) - if upsertErr != nil && a.server.logger() != nil { - a.server.logger().Error("更新订单为系统已发货失败", "order_id", orderID, "err", upsertErr) - } - result.SuccessCount++ - // status 表示远端动作与本地状态同步的三态结果。 - status := "succeeded" - // message 保存消息,供当前处理流程使用。 - message := "已成功修改闲鱼发货状态" - // reconciliationID 保存待补偿记录标识。 - reconciliationID := "" - // reconciliationWarning 保存本地状态写入或补偿记录写入错误。 - reconciliationWarning := "" - if upsertErr != nil { - status = "reconciliation_required" - message = "闲鱼已确认发货;本地订单状态待补偿,请勿重复确认发货" - reconciliationWarning = upsertErr.Error() - // reconciliationID、recordErr 保存补偿记录标识及其写入错误。 - var recordErr error - // recordCtx、recordCancel 确保请求取消后仍有短暂时间写入补偿记录。 - recordCtx, recordCancel := context.WithTimeout(context.Background(), 5*time.Second) - reconciliationID, recordErr = a.server.RecordOrderReconciliation(recordCtx, orderID, order.CookieID, "manual_status_ship", upsertErr.Error()) - recordCancel() - if recordErr != nil { - reconciliationWarning = errors.Join(errors.New(reconciliationWarning), fmt.Errorf("写入补偿记录失败: %w", recordErr)).Error() - } - } - result.Results = append(result.Results, map[string]any{ - "order_id": orderID, "status": status, "success": true, "message": message, - "reconciliation_id": reconciliationID, "reconciliation_warning": reconciliationWarning, - }) - a.server.notifyDelivery(order.CookieID, order.BuyerID, order.ItemID, order.ChatID, fmt.Sprintf("手动确认发货成功(订单 %s)", orderID)) + return manualShipResult{SuccessCount: result.SuccessCount, FailedCount: result.FailedCount, Results: results} } // RefreshSingle 刷新单个订单详情并写回本地订单。